cargo-rail 0.28.1

Cargo-native Rust workspace engine for affected CI, Rust source-surface analysis, compiler reuse, dependency coherence, exact-SHA releases, and split/sync
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
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
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
//! Front-door coverage for transparent local compiler-cache installation.

use anyhow::{Context as _, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::io::{Read as _, Write as _};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::Duration;

use crate::helpers::TestWorkspace;
#[cfg(windows)]
use crate::helpers::assert_native_driver_unavailable_bypass;

#[cfg(unix)]
struct UnchangedFileEvidence {
    device: u64,
    inode: u64,
}

#[cfg(windows)]
struct UnchangedFileEvidence {
    _deny_write_and_delete: fs::File,
}

#[cfg(unix)]
fn capture_unchanged_file(path: &Path) -> Result<UnchangedFileEvidence> {
    use std::os::unix::fs::MetadataExt as _;

    let metadata = fs::metadata(path).with_context(|| format!("read identity for {}", path.display()))?;
    Ok(UnchangedFileEvidence {
        device: metadata.dev(),
        inode: metadata.ino(),
    })
}

#[cfg(windows)]
fn capture_unchanged_file(path: &Path) -> Result<UnchangedFileEvidence> {
    use std::os::windows::fs::OpenOptionsExt as _;
    use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;

    // The retained handle permits the reads required by setup while denying
    // writes and deletes. An in-place rewrite or atomic replacement therefore
    // fails with a sharing violation instead of passing through a weak timestamp
    // comparison.
    let file = fs::OpenOptions::new()
        .read(true)
        .share_mode(FILE_SHARE_READ)
        .open(path)
        .with_context(|| format!("protect unchanged file {}", path.display()))?;
    Ok(UnchangedFileEvidence {
        _deny_write_and_delete: file,
    })
}

#[cfg(unix)]
fn assert_unchanged_file(path: &Path, expected: &UnchangedFileEvidence, description: &str) -> Result<()> {
    use std::os::unix::fs::MetadataExt as _;

    let metadata = fs::metadata(path).with_context(|| format!("read identity for {}", path.display()))?;
    anyhow::ensure!(
        (metadata.dev(), metadata.ino()) == (expected.device, expected.inode),
        "{description} was replaced"
    );
    Ok(())
}

#[cfg(windows)]
fn assert_unchanged_file(path: &Path, _expected: &UnchangedFileEvidence, description: &str) -> Result<()> {
    let metadata = fs::metadata(path).with_context(|| format!("read protected file {}", path.display()))?;
    anyhow::ensure!(metadata.is_file(), "{description} is no longer a regular file");
    Ok(())
}

fn rail(workspace: &Path, cargo_home: &Path, arguments: &[&str]) -> Result<Output> {
    Command::new(crate::helpers::cargo_binary("cargo-rail"))
        .current_dir(workspace)
        .args(arguments)
        .env("CARGO_HOME", cargo_home)
        .env_remove("CARGO_BUILD_RUSTC_WRAPPER")
        .env_remove("RUSTC_WRAPPER")
        .env_remove("RUSTC_WORKSPACE_WRAPPER")
        .output()
        .context("run cargo-rail cache command")
}

fn selected_profile_status(workspace: &Path, cargo_home: &Path) -> Result<serde_json::Value> {
    let output = rail(
        workspace,
        cargo_home,
        &["rail", "cache", "status", "--scope", "local", "-f", "json"],
    )?;
    anyhow::ensure!(output.status.success(), "cache status failed: {output:?}");
    json(&output)
}

fn selected_profile_cache_root(workspace: &Path, cargo_home: &Path) -> Result<PathBuf> {
    let status = selected_profile_status(workspace, cargo_home)?;
    status["status"]["local"]["cache"]["root"]
        .as_str()
        .map(PathBuf::from)
        .context("selected profile cache root")
}

#[cfg(unix)]
#[test]
fn authenticated_compiler_components_follow_installation_ownership() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let manufactured = PathBuf::from(std::env::var_os("CARGO_RAIL_TEST_COMPONENT_BINARY").context(
            "set CARGO_RAIL_TEST_COMPONENT_BINARY to the cargo-rail binary from the authenticated component preparation route",
        )?);
        let source = manufactured.parent().context("manufactured component directory")?;
        let bundle = tempfile::tempdir()?;
        for name in [
            "cargo-rail",
            "cargo-rail-native-rustc-wrapper",
            "cargo-rail-native-rustc-worker",
            "cargo-rail-fact-driver",
            "cargo-rail-fact-driver-source-v1.json",
        ] {
            fs::copy(source.join(name), bundle.path().join(name))?;
        }
        let workspace = TestWorkspace::new_single_crate("installed-components", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let run = |arguments: &[&str]| -> Result<Output> {
            let mut command = Command::new(bundle.path().join("cargo-rail"));
            for (name, _) in std::env::vars_os() {
                if name.to_str().is_some_and(|name| name.starts_with("CARGO_RAIL_")) {
                    command.env_remove(name);
                }
            }
            command
                .args(arguments)
                .current_dir(&workspace.path)
                .env("CARGO_HOME", cargo_home.path())
                .env_remove("CARGO_BUILD_RUSTC_WRAPPER")
                .env_remove("RUSTC_WRAPPER")
                .env_remove("RUSTC_WORKSPACE_WRAPPER")
                .output()
                .context("run authenticated component installation")
        };
        let source_bundle = bundle.path().join("cargo-rail-fact-driver-source-v1.json");
        let source_bytes = fs::read(&source_bundle)?;
        fs::remove_file(&source_bundle)?;
        let missing = run(&["rail", "cache", "setup"])?;
        anyhow::ensure!(
            !missing.status.success(),
            "missing authenticated source was accepted: {missing:?}"
        );
        anyhow::ensure!(
            fs::read_dir(cargo_home.path())?.next().is_none(),
            "rejected setup wrote Cargo state"
        );
        fs::write(&source_bundle, &source_bytes)?;

        let setup = run(&["rail", "cache", "setup"])?;
        anyhow::ensure!(setup.status.success(), "component setup failed: {setup:?}");
        let installation = fs::canonicalize(cargo_home.path())?.join("cargo-rail/compiler-cache-v1");
        let receipt_path = installation.join("setup.json");
        let receipt_bytes = fs::read(&receipt_path)?;
        let receipt: serde_json::Value = serde_json::from_slice(&receipt_bytes)?;
        assert_eq!(receipt["version"], 5);
        let components = receipt["compiler_components"]
            .as_array()
            .context("required component inventory")?;
        assert_eq!(components.len(), 2);
        let names = components
            .iter()
            .map(|component| {
                let path = PathBuf::from(component["path"].as_str().context("component path")?);
                anyhow::ensure!(
                    path.parent() == Some(installation.as_path()),
                    "component escaped installation"
                );
                let name = path.file_name().context("component name")?.to_owned();
                anyhow::ensure!(
                    fs::read(&path)? == fs::read(bundle.path().join(&name))?,
                    "installed component bytes changed"
                );
                let mode = if name == "cargo-rail-fact-driver" { 0o700 } else { 0o600 };
                anyhow::ensure!(
                    fs::metadata(&path)?.permissions().mode() & 0o777 == mode,
                    "component permissions changed"
                );
                Ok(name)
            })
            .collect::<Result<BTreeSet<_>>>()?;
        assert_eq!(
            names,
            BTreeSet::from([
                "cargo-rail-fact-driver".into(),
                "cargo-rail-fact-driver-source-v1.json".into()
            ])
        );
        let before = components
            .iter()
            .map(|component| {
                let path = PathBuf::from(component["path"].as_str().context("component path")?);
                Ok((path.clone(), capture_unchanged_file(&path)?))
            })
            .collect::<Result<Vec<_>>>()?;
        let repeated = run(&["rail", "cache", "setup"])?;
        anyhow::ensure!(
            repeated.status.success(),
            "repeated component setup failed: {repeated:?}"
        );
        assert_eq!(fs::read(&receipt_path)?, receipt_bytes);
        for (path, identity) in before {
            assert_unchanged_file(&path, &identity, "unchanged compiler component")?;
        }

        let installed_source = installation.join("cargo-rail-fact-driver-source-v1.json");
        fs::write(&installed_source, b"changed component bytes")?;
        let status = run(&["rail", "cache", "status", "--scope", "local", "-f", "json"])?;
        assert_eq!(json(&status)?["status"]["installation"]["healthy"], false);
        let config_before = fs::read(cargo_home.path().join("config.toml"))?;
        let retained_files = [
            "cargo-rail-native-rustc-wrapper",
            "cargo-rail-native-rustc-worker",
            "cargo-rail-fact-driver",
        ]
        .into_iter()
        .map(|name| {
            let path = installation.join(name);
            Ok((path.clone(), capture_unchanged_file(&path)?))
        })
        .collect::<Result<Vec<_>>>()?;
        let refused = run(&["rail", "cache", "uninstall"])?;
        anyhow::ensure!(
            !refused.status.success(),
            "changed component removal was accepted: {refused:?}"
        );
        assert_eq!(fs::read(cargo_home.path().join("config.toml"))?, config_before);
        assert_eq!(fs::read(&receipt_path)?, receipt_bytes);
        for (path, identity) in retained_files {
            assert_unchanged_file(&path, &identity, "compiler file after refused component removal")?;
        }
        assert_eq!(fs::read(&installed_source)?, b"changed component bytes");
        let repair = run(&["rail", "cache", "setup"])?;
        anyhow::ensure!(repair.status.success(), "component repair failed: {repair:?}");
        assert_eq!(fs::read(&installed_source)?, source_bytes);
        let status = run(&["rail", "cache", "status", "--scope", "local", "-f", "json"])?;
        assert_eq!(json(&status)?["status"]["installation"]["healthy"], true);
        let sentinel = installation.join("unowned-user-file");
        fs::write(&sentinel, b"retain this file")?;
        let removed = run(&["rail", "cache", "uninstall"])?;
        anyhow::ensure!(removed.status.success(), "component removal failed: {removed:?}");
        assert!(!installed_source.exists());
        assert!(!installation.join("cargo-rail-fact-driver").exists());
        assert!(!receipt_path.exists());
        assert_eq!(fs::read(sentinel)?, b"retain this file");
        Ok(())
    })();
    super::helpers::finish_test(result);
}

fn selected_profile_state_root(workspace: &Path, cargo_home: &Path) -> Result<PathBuf> {
    let status = selected_profile_status(workspace, cargo_home)?;
    let profile_id = status["status"]["installation"]["profile_id"]
        .as_str()
        .context("selected profile ID")?;
    Ok(cargo_home.join("cargo-rail/cache-profiles-v1/state").join(profile_id))
}

#[cfg(unix)]
fn profile_authority_projection(status: &serde_json::Value) -> serde_json::Value {
    serde_json::json!({
        "profile_id": status["status"]["installation"]["profile_id"],
        "bound_workspace_root": status["status"]["installation"]["bound_workspace_root"],
        "trust_domain": status["status"]["installation"]["trust_domain"],
        "cache_root": status["status"]["local"]["cache"]["root"],
        "max_bytes": status["status"]["installation"]["max_bytes"],
        "root_portability": status["status"]["installation"]["root_portability"],
        "remote_authority": status["status"]["remote"]["authority"],
        "remote_mode": status["status"]["remote"]["mode"],
        "selection_source": status["status"]["remote"]["selection_source"],
    })
}

fn remote_probe(workspace: &Path, cargo_home: &Path, remote: &str, mode: &str) -> Result<Output> {
    Command::new(crate::helpers::cargo_binary("cargo-rail"))
        .current_dir(workspace)
        .args(["rail", "cache", "probe", "-f", "json"])
        .env("CARGO_HOME", cargo_home)
        .env("CARGO_RAIL_CACHE_REMOTE", remote)
        .env("CARGO_RAIL_CACHE_MODE", mode)
        .env("AWS_ACCESS_KEY_ID", "fixture-access-key")
        .env("AWS_SECRET_ACCESS_KEY", "fixture-secret-key")
        .env("AWS_SESSION_TOKEN", "fixture-session-token")
        .env("AWS_EC2_METADATA_DISABLED", "true")
        .env("AWS_CONFIG_FILE", workspace.join("missing-aws-config"))
        .env("AWS_SHARED_CREDENTIALS_FILE", workspace.join("missing-aws-credentials"))
        .env_remove("AWS_ENDPOINT_URL")
        .env_remove("AWS_ENDPOINT_URL_S3")
        .env_remove("AWS_PROFILE")
        .env_remove("AWS_DEFAULT_PROFILE")
        .output()
        .context("probe loopback remote cache")
}

fn cargo_check(workspace: &Path, cargo_home: &Path, rustc: Option<&Path>, cache: Option<&str>) -> Result<Output> {
    let mut command = Command::new("cargo");
    command
        .current_dir(workspace)
        .args(["check", "--quiet"])
        .env("CARGO_HOME", cargo_home)
        .env("CARGO_INCREMENTAL", "0")
        .env_remove("RUSTC_WRAPPER")
        .env_remove("RUSTC_WORKSPACE_WRAPPER");
    if let Some(rustc) = rustc {
        command.env("RUSTC", rustc);
    }
    if let Some(cache) = cache {
        command.env("CARGO_RAIL_CACHE", cache);
    }
    command.output().context("run isolated cargo check")
}

#[cfg(unix)]
fn cargo_check_remote(
    workspace: &Path,
    cargo_home: &Path,
    remote: &str,
    mode: &str,
    rustc: Option<&Path>,
    coverage: Option<&Path>,
) -> Result<Output> {
    let mut command = Command::new("cargo");
    command
        .current_dir(workspace)
        .args(["check", "--quiet"])
        .env("CARGO_HOME", cargo_home)
        .env("CARGO_INCREMENTAL", "0")
        .env("CARGO_RAIL_CACHE_REMOTE", remote)
        .env("CARGO_RAIL_CACHE_MODE", mode)
        .env("AWS_ACCESS_KEY_ID", "fixture-access-key")
        .env("AWS_SECRET_ACCESS_KEY", "fixture-secret-key")
        .env("AWS_SESSION_TOKEN", "fixture-session-token")
        .env("AWS_EC2_METADATA_DISABLED", "true")
        .env("AWS_CONFIG_FILE", workspace.join("missing-aws-config"))
        .env("AWS_SHARED_CREDENTIALS_FILE", workspace.join("missing-aws-credentials"))
        .env_remove("AWS_ENDPOINT_URL")
        .env_remove("AWS_ENDPOINT_URL_S3")
        .env_remove("AWS_PROFILE")
        .env_remove("AWS_DEFAULT_PROFILE")
        .env_remove("OUT_DIR")
        .env_remove("RUSTC_WRAPPER")
        .env_remove("RUSTC_WORKSPACE_WRAPPER");
    if let Some(rustc) = rustc {
        command
            .env("RUSTC", rustc)
            .env("REAL_RUSTC", "rustc")
            .env("REMOTE_ENV_LOG", workspace.join("remote-compiler-environment.log"));
    }
    if let Some(coverage) = coverage {
        let coverage = cargo_rail::utils::canonicalize_existing(coverage)
            .context("canonicalize native-cache coverage directory")?;
        command
            .env("CARGO_RAIL_CACHE", "__cargo_rail_benchmark_coverage_v1")
            .env("CARGO_RAIL_BENCH_NATIVE_COVERAGE_DIRECTORY", coverage);
    }
    command.output().context("run cargo check with loopback remote cache")
}

fn cargo_check_installed_remote(workspace: &Path, cargo_home: &Path, coverage: &Path) -> Result<Output> {
    cargo_check_installed_remote_with_options(workspace, cargo_home, coverage, None, None, None)
}

fn cargo_check_installed_remote_in_target(
    workspace: &Path,
    cargo_home: &Path,
    coverage: &Path,
    target: &Path,
) -> Result<Output> {
    cargo_check_installed_remote_with_options(workspace, cargo_home, coverage, None, Some(target), None)
}

fn cargo_check_installed_remote_with_rustflags(
    workspace: &Path,
    cargo_home: &Path,
    coverage: &Path,
    rustflags: Option<&str>,
) -> Result<Output> {
    cargo_check_installed_remote_with_options(workspace, cargo_home, coverage, rustflags, None, None)
}

fn cargo_check_installed_remote_with_options(
    workspace: &Path,
    cargo_home: &Path,
    coverage: &Path,
    rustflags: Option<&str>,
    target: Option<&Path>,
    artifact_target: Option<&str>,
) -> Result<Output> {
    let coverage =
        cargo_rail::utils::canonicalize_existing(coverage).context("canonicalize native-cache coverage directory")?;
    let mut command = Command::new("cargo");
    command
        .current_dir(workspace)
        .args(["check", "--quiet"])
        .env("CARGO_HOME", cargo_home)
        .env("CARGO_INCREMENTAL", "0")
        .env("CARGO_RAIL_CACHE", "__cargo_rail_benchmark_coverage_v1")
        .env("CARGO_RAIL_BENCH_NATIVE_COVERAGE_DIRECTORY", coverage)
        .env("AWS_ACCESS_KEY_ID", "fixture-access-key")
        .env("AWS_SECRET_ACCESS_KEY", "fixture-secret-key")
        .env("AWS_SESSION_TOKEN", "fixture-session-token")
        .env("AWS_EC2_METADATA_DISABLED", "true")
        .env("AWS_CONFIG_FILE", workspace.join("missing-aws-config"))
        .env("AWS_SHARED_CREDENTIALS_FILE", workspace.join("missing-aws-credentials"))
        .env_remove("AWS_ENDPOINT_URL")
        .env_remove("AWS_ENDPOINT_URL_S3")
        .env_remove("CARGO_RAIL_CACHE_REMOTE")
        .env_remove("CARGO_RAIL_CACHE_MODE")
        .env_remove("CARGO_RAIL_CACHE_REMOTE_ENVIRONMENT")
        .env_remove("AWS_SECURITY_TOKEN")
        .env_remove("AWS_PROFILE")
        .env_remove("AWS_DEFAULT_PROFILE")
        .env_remove("OUT_DIR")
        .env_remove("RUSTC_WRAPPER")
        .env_remove("RUSTC_WORKSPACE_WRAPPER");
    if let Some(artifact_target) = artifact_target {
        command.arg("--target").arg(artifact_target);
    }
    if let Some(rustflags) = rustflags {
        command.env("RUSTFLAGS", rustflags);
    } else {
        command.env_remove("RUSTFLAGS");
    }
    if let Some(target) = target {
        command.env("CARGO_TARGET_DIR", target);
    } else {
        command.env_remove("CARGO_TARGET_DIR");
    }
    command.output().context("run cargo check with installed remote policy")
}

#[derive(Clone)]
struct FixtureObject {
    body: Vec<u8>,
    etag: String,
}

#[derive(Default)]
struct LoopbackS3State {
    objects: BTreeMap<String, FixtureObject>,
    requests: Vec<(String, String)>,
    generation: u64,
}

struct LoopbackS3 {
    address: SocketAddr,
    state: Arc<Mutex<LoopbackS3State>>,
    #[cfg(unix)]
    available: Arc<AtomicBool>,
    stopping: Arc<AtomicBool>,
    worker: Option<JoinHandle<()>>,
}

impl LoopbackS3 {
    fn start() -> Result<Self> {
        let listener = TcpListener::bind(("127.0.0.1", 0))?;
        let address = listener.local_addr()?;
        listener.set_nonblocking(true)?;
        let state = Arc::new(Mutex::new(LoopbackS3State::default()));
        let available = Arc::new(AtomicBool::new(true));
        let stopping = Arc::new(AtomicBool::new(false));
        let worker_state = Arc::clone(&state);
        let worker_available = Arc::clone(&available);
        let worker_stopping = Arc::clone(&stopping);
        let worker = thread::spawn(move || {
            let mut requests = Vec::new();
            while !worker_stopping.load(Ordering::Acquire) {
                match listener.accept() {
                    Ok((stream, _)) => {
                        let request_state = Arc::clone(&worker_state);
                        let request_available = Arc::clone(&worker_available);
                        requests.push(thread::spawn(move || {
                            drop(serve_s3_request(
                                stream,
                                &request_state,
                                request_available.load(Ordering::Acquire),
                            ));
                        }));
                    }
                    Err(error)
                        if matches!(
                            error.kind(),
                            std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
                        ) =>
                    {
                        thread::sleep(Duration::from_millis(2));
                    }
                    Err(_) => break,
                }
                let mut index = 0usize;
                while index < requests.len() {
                    if requests[index].is_finished() {
                        let request = requests.swap_remove(index);
                        drop(request.join());
                    } else {
                        index = index.saturating_add(1);
                    }
                }
            }
            for request in requests {
                drop(request.join());
            }
        });
        Ok(Self {
            address,
            state,
            #[cfg(unix)]
            available,
            stopping,
            worker: Some(worker),
        })
    }

    fn remote_url(&self) -> String {
        format!("s3+http://{}/fixture-bucket/team?region=test-1", self.address)
    }

    #[cfg(unix)]
    fn request_count(&self) -> usize {
        self.state.lock().map_or(0, |state| state.requests.len())
    }

    fn requests(&self) -> Vec<(String, String)> {
        self.state
            .lock()
            .map_or_else(|_| Vec::new(), |state| state.requests.clone())
    }

    #[cfg(unix)]
    fn set_available(&self, available: bool) {
        self.available.store(available, Ordering::Release);
    }

    #[cfg(unix)]
    fn corrupt_result(&self) -> bool {
        let Ok(mut state) = self.state.lock() else {
            return false;
        };
        let Some(object) = state
            .objects
            .iter_mut()
            .find_map(|(key, object)| key.contains("/entries/").then_some(object))
        else {
            return false;
        };
        let Some(last) = object.body.last_mut() else {
            return false;
        };
        *last ^= 0xff;
        object.etag = "\"corrupt-result\"".to_string();
        true
    }

    fn corrupt_protocol_marker(&self) -> bool {
        let Ok(mut state) = self.state.lock() else {
            return false;
        };
        let Some(object) = state
            .objects
            .iter_mut()
            .find_map(|(key, object)| key.ends_with("/protocol").then_some(object))
        else {
            return false;
        };
        object.body = b"incompatible protocol".to_vec();
        object.etag = "\"corrupt-protocol\"".to_string();
        true
    }
}

impl Drop for LoopbackS3 {
    fn drop(&mut self) {
        self.stopping.store(true, Ordering::Release);
        drop(TcpStream::connect(self.address));
        if let Some(worker) = self.worker.take() {
            drop(worker.join());
        }
    }
}

fn serve_s3_request(
    mut stream: TcpStream,
    state: &Arc<Mutex<LoopbackS3State>>,
    available: bool,
) -> std::io::Result<()> {
    // Windows accepted sockets can inherit the listener's nonblocking mode.
    stream.set_nonblocking(false)?;
    stream.set_read_timeout(Some(Duration::from_secs(5)))?;
    stream.set_write_timeout(Some(Duration::from_secs(5)))?;
    let mut request = Vec::new();
    let header_end = loop {
        if request.len() > 1024 * 1024 {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "fixture request headers exceeded their bound",
            ));
        }
        let mut buffer = [0_u8; 16 * 1024];
        let read = stream.read(&mut buffer)?;
        if read == 0 {
            return Ok(());
        }
        request.extend_from_slice(&buffer[..read]);
        if let Some(offset) = request.windows(4).position(|window| window == b"\r\n\r\n") {
            break offset + 4;
        }
    };
    let header = std::str::from_utf8(&request[..header_end])
        .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "fixture request header was not UTF-8"))?;
    let mut lines = header.split("\r\n");
    let request_line = lines
        .next()
        .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData, "fixture request line was absent"))?;
    let mut request_parts = request_line.split_whitespace();
    let method = request_parts.next().unwrap_or_default().to_string();
    let target = request_parts.next().unwrap_or_default();
    let path = target.split('?').next().unwrap_or(target).to_string();
    let headers = lines
        .filter_map(|line| line.split_once(':'))
        .map(|(name, value)| (name.trim().to_ascii_lowercase(), value.trim().to_string()))
        .collect::<BTreeMap<_, _>>();
    let content_length = headers
        .get("content-length")
        .and_then(|value| value.parse::<usize>().ok())
        .unwrap_or(0);
    if content_length > 64 * 1024 * 1024 {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "fixture request body exceeded its bound",
        ));
    }
    while request.len() < header_end.saturating_add(content_length) {
        let mut buffer = [0_u8; 64 * 1024];
        let read = stream.read(&mut buffer)?;
        if read == 0 {
            break;
        }
        request.extend_from_slice(&buffer[..read]);
    }
    if request.len() != header_end.saturating_add(content_length) {
        return Err(std::io::Error::new(
            std::io::ErrorKind::UnexpectedEof,
            "fixture request body was truncated",
        ));
    }
    let encoded_body = &request[header_end..];
    let body = if headers
        .get("content-encoding")
        .is_some_and(|value| value.split(',').any(|encoding| encoding.trim() == "aws-chunked"))
    {
        decode_chunked_fixture_body(encoded_body)?
    } else {
        encoded_body.to_vec()
    };

    let mut state = state
        .lock()
        .map_err(|_| std::io::Error::other("fixture state lock was poisoned"))?;
    state.requests.push((method.clone(), path.clone()));
    if !available {
        return write_s3_error(&mut stream, 503, "ServiceUnavailable");
    }
    match method.as_str() {
        "GET" => match state.objects.get(&path) {
            Some(object) => write_s3_response(&mut stream, 200, &object.etag, &object.body),
            None => write_s3_error(&mut stream, 404, "NoSuchKey"),
        },
        "PUT" => {
            let allowed = match (
                headers.get("if-none-match"),
                headers.get("if-match"),
                state.objects.get(&path),
            ) {
                (Some(value), _, None) if value == "*" => true,
                (Some(value), _, Some(_)) if value == "*" => false,
                (_, Some(expected), Some(object)) => expected == &object.etag,
                (_, Some(_), None) => false,
                (None, None, _) => true,
                _ => false,
            };
            if !allowed {
                return write_s3_error(&mut stream, 412, "PreconditionFailed");
            }
            state.generation = state.generation.saturating_add(1);
            let etag = format!("\"fixture-{}\"", state.generation);
            state.objects.insert(
                path,
                FixtureObject {
                    body,
                    etag: etag.clone(),
                },
            );
            write_s3_response(&mut stream, 200, &etag, b"")
        }
        _ => write_s3_error(&mut stream, 405, "MethodNotAllowed"),
    }
}

fn decode_chunked_fixture_body(encoded: &[u8]) -> std::io::Result<Vec<u8>> {
    let mut decoded = Vec::new();
    let mut offset = 0usize;
    loop {
        let line_end = encoded[offset..]
            .windows(2)
            .position(|window| window == b"\r\n")
            .map(|position| offset + position)
            .ok_or_else(|| {
                std::io::Error::new(std::io::ErrorKind::InvalidData, "fixture chunk header was truncated")
            })?;
        let header = std::str::from_utf8(&encoded[offset..line_end])
            .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "fixture chunk header was not UTF-8"))?;
        let length = usize::from_str_radix(header.split(';').next().unwrap_or_default(), 16)
            .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "fixture chunk length was invalid"))?;
        offset = line_end.saturating_add(2);
        if length == 0 {
            break;
        }
        let end = offset
            .checked_add(length)
            .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData, "fixture chunk length overflowed"))?;
        if end.saturating_add(2) > encoded.len() || &encoded[end..end + 2] != b"\r\n" {
            return Err(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "fixture chunk payload was truncated",
            ));
        }
        decoded.extend_from_slice(&encoded[offset..end]);
        offset = end + 2;
    }
    Ok(decoded)
}

fn write_s3_response(stream: &mut TcpStream, status: u16, etag: &str, body: &[u8]) -> std::io::Result<()> {
    let reason = if status == 200 { "OK" } else { "Error" };
    write!(
        stream,
        "HTTP/1.1 {status} {reason}\r\nContent-Length: {}\r\nETag: {etag}\r\nx-amz-request-id: fixture\r\nConnection: close\r\n\r\n",
        body.len()
    )?;
    stream.write_all(body)
}

fn write_s3_error(stream: &mut TcpStream, status: u16, code: &str) -> std::io::Result<()> {
    let body = format!(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Error><Code>{code}</Code><Message>{code}</Message><RequestId>fixture</RequestId><HostId>fixture</HostId></Error>"
    );
    write!(
        stream,
        "HTTP/1.1 {status} Error\r\nContent-Type: application/xml\r\nContent-Length: {}\r\nx-amz-request-id: fixture\r\nConnection: close\r\n\r\n{body}",
        body.len()
    )
}

fn coverage_events(directory: &Path) -> Result<Vec<serde_json::Value>> {
    fs::read_dir(directory)?
        .map(|entry| {
            let path = entry?.path();
            serde_json::from_slice(&fs::read(path)?).context("decode native-cache coverage event")
        })
        .collect()
}

fn json(output: &Output) -> Result<serde_json::Value> {
    serde_json::from_slice(&output.stdout).context("decode command JSON")
}

fn explicit_target_cargo(
    workspace: &Path,
    cargo_home: &Path,
    workload: &str,
    target: &str,
    report: Option<&Path>,
) -> Result<()> {
    let mut command = Command::new("cargo");
    command
        .current_dir(workspace)
        .args([workload, "--offline", "--quiet", "--target", target])
        .env("CARGO_HOME", cargo_home)
        .env("CARGO_INCREMENTAL", "0")
        .env("CARGO_TARGET_DIR", workspace.join("target"))
        .env_remove("CARGO_BUILD_TARGET")
        .env_remove("CARGO_BUILD_RUSTC_WRAPPER")
        .env_remove("CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER")
        .env_remove("RUSTC_WRAPPER")
        .env_remove("RUSTC_WORKSPACE_WRAPPER")
        .env_remove("RUSTFLAGS")
        .env_remove("CARGO_ENCODED_RUSTFLAGS")
        .env_remove("CARGO_RAIL_CACHE")
        .env_remove("CARGO_RAIL_CACHE_REMOTE")
        .env_remove("CARGO_RAIL_CACHE_MODE")
        .env_remove("CARGO_RAIL_CACHE_REMOTE_ENVIRONMENT")
        .env_remove("CARGO_RAIL_CACHE_REPORT")
        .env_remove("OUT_DIR");
    if let Some(report) = report {
        command.env("CARGO_RAIL_CACHE_REPORT", report);
    }
    let output = command
        .output()
        .with_context(|| format!("run explicit-target cargo {workload} for {target}"))?;
    anyhow::ensure!(
        output.status.success(),
        "cargo {workload} --target {target} failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    Ok(())
}

fn compiler_only_outputs(directory: &Path) -> Result<BTreeMap<PathBuf, Vec<u8>>> {
    let mut outputs = BTreeMap::new();
    for entry in fs::read_dir(directory)? {
        let path = entry?.path();
        if matches!(
            path.extension().and_then(|extension| extension.to_str()),
            Some("rmeta" | "rlib")
        ) {
            outputs.insert(path.strip_prefix(directory)?.to_path_buf(), fs::read(path)?);
        }
    }
    Ok(outputs)
}

fn explicit_target_reuse(target: &str, mixed_host_target: bool) -> Result<()> {
    for workload in ["check", "build"] {
        let workspace = TestWorkspace::new_single_crate("explicit-target", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let source = if mixed_host_target {
            fs::write(
                workspace.path.join("Cargo.toml"),
                "[package]\nname = \"explicit-target\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\
                 [dependencies]\nhost-target-support = { path = \"support\" }\n\
                 [build-dependencies]\nhost-target-support = { path = \"support\" }\n",
            )?;
            fs::create_dir_all(workspace.path.join("support/src"))?;
            fs::write(
                workspace.path.join("support/Cargo.toml"),
                "[package]\nname = \"host-target-support\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
            )?;
            fs::write(workspace.path.join("support/src/lib.rs"), "pub const VALUE: u64 = 7;\n")?;
            fs::write(
                workspace.path.join("build.rs"),
                "fn main() { assert_eq!(host_target_support::VALUE, 7); \
                 println!(\"cargo::rerun-if-changed=build.rs\"); }\n",
            )?;
            "pub const VALUE: u64 = 41 + host_target_support::VALUE;\n"
        } else {
            "pub const VALUE: u64 = 41;\n"
        };
        fs::write(workspace.path.join("src/lib.rs"), source)?;
        explicit_target_cargo(&workspace.path, cargo_home.path(), workload, target, None)
            .context("uncached upstream fixture must build before cache qualification")?;
        let target_directory = workspace.path.join("target").join(target);
        let outputs_directory = target_directory.join("debug/deps");
        let baseline = compiler_only_outputs(&outputs_directory)?;
        let expected_libraries = if mixed_host_target { 2 } else { 1 };
        let metadata_count = baseline
            .keys()
            .filter(|path| path.extension().is_some_and(|extension| extension == "rmeta"))
            .count();
        anyhow::ensure!(
            metadata_count == expected_libraries,
            "upstream {workload} produced {metadata_count} metadata files; expected {expected_libraries}"
        );
        let archive_count = baseline
            .keys()
            .filter(|path| path.extension().is_some_and(|extension| extension == "rlib"))
            .count();
        let expected_archives = if workload == "build" { expected_libraries } else { 0 };
        anyhow::ensure!(
            archive_count == expected_archives,
            "upstream {workload} produced {archive_count} archives; expected {expected_archives}"
        );
        let host_outputs = if mixed_host_target {
            let outputs = compiler_only_outputs(&workspace.path.join("target/debug/deps"))?;
            anyhow::ensure!(
                outputs
                    .keys()
                    .any(|path| path.extension().is_some_and(|extension| extension == "rlib")),
                "the shared build dependency was not compiled for the host"
            );
            Some(outputs)
        } else {
            None
        };
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        anyhow::ensure!(setup.status.success(), "explicit-target cache setup failed: {setup:?}");

        fs::remove_dir_all(&target_directory)?;
        explicit_target_cargo(&workspace.path, cargo_home.path(), workload, target, None)?;
        let cold = selected_profile_status(&workspace.path, cargo_home.path())?;
        let cold_usage = &cold["status"]["installation"]["usage"];
        #[cfg(not(windows))]
        anyhow::ensure!(
            cold_usage["misses"] == expected_libraries,
            "cold {workload} did not cache every target library: {cold_usage}"
        );
        #[cfg(windows)]
        anyhow::ensure!(
            cold_usage["misses"] == 0 && cold_usage["failures"] == 0 && cold_usage["bypasses"] == expected_libraries,
            "unexpected Windows cold outcome: {cold_usage}"
        );
        anyhow::ensure!(
            cold_usage["hits"] == 0,
            "cold {workload} reused an unseeded result: {cold_usage}"
        );
        anyhow::ensure!(
            compiler_only_outputs(&outputs_directory)? == baseline,
            "cached cold {workload} changed upstream output bytes"
        );

        fs::remove_dir_all(&target_directory)?;
        explicit_target_cargo(&workspace.path, cargo_home.path(), workload, target, None)?;
        let warm = selected_profile_status(&workspace.path, cargo_home.path())?;
        let warm_usage = &warm["status"]["installation"]["usage"];
        #[cfg(not(windows))]
        anyhow::ensure!(
            warm_usage["hits"] == expected_libraries,
            "warm {workload} did not restore every target library: {warm_usage}"
        );
        #[cfg(windows)]
        anyhow::ensure!(
            warm_usage["hits"] == 0 && warm_usage["failures"] == 0 && warm_usage["bypasses"] == expected_libraries * 2,
            "unexpected Windows warm outcome: {warm_usage}"
        );
        anyhow::ensure!(
            warm_usage["misses"] == cold_usage["misses"],
            "warm {workload} compiled a target library: cold {cold_usage}; warm {warm_usage}"
        );
        anyhow::ensure!(
            compiler_only_outputs(&outputs_directory)? == baseline,
            "warm {workload} restored different output bytes"
        );

        let changed_source = source.replace("41", "42");
        anyhow::ensure!(
            source.len() == changed_source.len(),
            "source replacement changed length from {} to {}",
            source.len(),
            changed_source.len()
        );
        fs::write(workspace.path.join("src/lib.rs"), changed_source)?;
        explicit_target_cargo(&workspace.path, cargo_home.path(), workload, target, None)?;
        let changed = selected_profile_status(&workspace.path, cargo_home.path())?;
        let changed_usage = &changed["status"]["installation"]["usage"];
        #[cfg(not(windows))]
        anyhow::ensure!(
            changed_usage["misses"] == expected_libraries + 1,
            "same-size source replacement did not cause a miss: {changed_usage}"
        );
        #[cfg(windows)]
        anyhow::ensure!(
            changed_usage["misses"] == 0
                && changed_usage["failures"] == 0
                && changed_usage["bypasses"] == expected_libraries * 2 + 1,
            "unexpected Windows changed outcome: {changed_usage}"
        );
        anyhow::ensure!(
            changed_usage["hits"] == warm_usage["hits"],
            "same-size source replacement reused stale output: warm {warm_usage}; changed {changed_usage}"
        );
        anyhow::ensure!(
            compiler_only_outputs(&outputs_directory)? != baseline,
            "same-size source replacement restored the old library"
        );
        if let Some(host_outputs) = host_outputs {
            anyhow::ensure!(
                compiler_only_outputs(&workspace.path.join("target/debug/deps"))? == host_outputs,
                "target cache activity changed the host build dependency"
            );
        }
    }
    Ok(())
}

#[test]
fn explicit_host_target_check_and_build_restore_exact_compiler_outputs() {
    let result: Result<()> = (|| {
        let version = Command::new("rustc").arg("-vV").output()?;
        anyhow::ensure!(version.status.success(), "rustc -vV failed: {version:?}");
        let verbose = String::from_utf8(version.stdout)?;
        let host = verbose
            .lines()
            .find_map(|line| line.strip_prefix("host: "))
            .context("rustc host target")?;
        explicit_target_reuse(host, false)
    })();
    super::helpers::finish_test(result);
}

#[cfg(target_os = "macos")]
#[test]
fn cross_target_check_and_build_restore_libraries_without_changing_host_dependencies() {
    let result: Result<()> = (|| {
        let target = "x86_64-unknown-linux-gnu";
        let installed = Command::new("rustup")
            .args(["target", "list", "--installed"])
            .output()?;
        anyhow::ensure!(
            installed.status.success(),
            "cannot inspect installed targets: {installed:?}"
        );
        anyhow::ensure!(
            String::from_utf8(installed.stdout)?
                .lines()
                .any(|installed| installed == target),
            "cross-target cache qualification requires the {target} standard library declared in rust-toolchain.toml; run rustup target add {target}"
        );
        explicit_target_reuse(target, true)
    })();
    super::helpers::finish_test(result);
}

#[cfg(target_os = "macos")]
#[test]
fn explicit_default_linker_restores_the_exact_executable_and_mode() {
    super::helpers::finish_test(explicit_linker_reuse(false));
}

#[cfg(target_os = "macos")]
#[test]
fn direct_rust_lld_restores_the_exact_executable_and_mode() {
    super::helpers::finish_test(explicit_linker_reuse(true));
}

#[cfg(target_os = "macos")]
#[test]
fn dynamic_libraries_restore_after_rustc_removes_its_export_lists() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let workspace = TestWorkspace::new_single_crate("export-lists", "0.1.0")?;
        fs::write(
            workspace.path.join("Cargo.toml"),
            "[workspace]\nmembers = [\"dylib\", \"cdylib\", \"macros\"]\nresolver = \"3\"\n\
             [profile.dev]\ndebug = 1\nsplit-debuginfo = \"unpacked\"\n",
        )?;
        for (name, crate_type, source) in [
            ("dylib", "dylib", "pub fn answer() -> u64 { 41 }\n"),
            (
                "cdylib",
                "cdylib",
                "#[unsafe(no_mangle)] pub extern \"C\" fn answer() -> u64 { 42 }\n",
            ),
            (
                "macros",
                "proc-macro",
                "use proc_macro::TokenStream;\n\
                 #[proc_macro] pub fn answer(_: TokenStream) -> TokenStream { \"43\".parse().unwrap() }\n",
            ),
        ] {
            let directory = workspace.path.join(name);
            fs::create_dir_all(directory.join("src"))?;
            fs::write(
                directory.join("Cargo.toml"),
                format!(
                    "[package]\nname = \"export-{name}\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\
                     [lib]\ncrate-type = [\"{crate_type}\"]\n"
                ),
            )?;
            fs::write(directory.join("src/lib.rs"), source)?;
        }
        let version = Command::new("rustc").arg("-vV").output()?;
        anyhow::ensure!(version.status.success(), "rustc prerequisite failed: {version:?}");
        let verbose = String::from_utf8(version.stdout)?;
        let host = verbose
            .lines()
            .find_map(|line| line.strip_prefix("host: "))
            .context("rustc host")?;
        let cargo_home = tempfile::tempdir()?;
        let target = workspace.path.join("target");
        explicit_target_cargo(&workspace.path, cargo_home.path(), "build", host, None)?;
        let mut baseline = BTreeMap::new();
        for directory in [target.join("debug/deps"), target.join(host).join("debug/deps")] {
            if !directory.is_dir() {
                continue;
            }
            for entry in fs::read_dir(directory)? {
                let path = entry?.path();
                if path.extension().is_some_and(|extension| extension == "dylib")
                    || path
                        .file_name()
                        .is_some_and(|name| name.to_string_lossy().ends_with(".rcgu.o"))
                {
                    baseline.insert(
                        path.strip_prefix(&target)?.to_path_buf(),
                        (fs::read(&path)?, fs::metadata(&path)?.permissions().mode() & 0o777),
                    );
                }
            }
        }
        assert_eq!(
            baseline
                .keys()
                .filter(|path| path.extension().is_some_and(|extension| extension == "dylib"))
                .count(),
            3,
            "upstream dynamic-library inventory"
        );
        assert!(
            baseline
                .keys()
                .any(|path| path.extension().is_some_and(|extension| extension == "o")),
            "upstream separate debug objects are absent"
        );
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "export-list cache setup failed: {setup:?}");
        let reports = tempfile::tempdir()?;
        for (phase, hits) in [("cold", 0), ("warm", 3)] {
            fs::remove_dir_all(&target)?;
            let recording = reports.path().join(format!("{phase}.json"));
            let report_path = recording.to_str().context("export-list report path")?;
            let start = rail(
                &workspace.path,
                cargo_home.path(),
                &["rail", "cache", "report", "--start", report_path],
            )?;
            assert!(start.status.success(), "{phase} report start failed: {start:?}");
            explicit_target_cargo(&workspace.path, cargo_home.path(), "build", host, Some(&recording))?;
            let finish = rail(
                &workspace.path,
                cargo_home.path(),
                &["rail", "cache", "report", "--finish", report_path, "-f", "json"],
            )?;
            assert!(finish.status.success(), "{phase} report finish failed: {finish:?}");
            let report = json(&finish)?;
            assert_eq!(report["measurements"]["hits"], hits, "{phase}: {report}");
            assert_eq!(report["measurements"]["misses"], 3 - hits, "{phase}: {report}");
            assert_eq!(report["measurements"]["failures"], 0, "{phase}: {report}");
            for (path, (bytes, mode)) in &baseline {
                let output = target.join(path);
                assert!(fs::read(&output)? == *bytes, "{phase} changed {}", path.display());
                assert_eq!(
                    fs::metadata(&output)?.permissions().mode() & 0o777,
                    *mode,
                    "{phase} mode of {}",
                    path.display()
                );
            }
        }
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(target_os = "macos")]
fn explicit_linker_reuse(direct_lld: bool) -> Result<()> {
    (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let version = Command::new("rustc").arg("-vV").output()?;
        anyhow::ensure!(version.status.success(), "rustc -vV failed: {version:?}");
        let verbose = String::from_utf8(version.stdout)?;
        let host = verbose
            .lines()
            .find_map(|line| line.strip_prefix("host: "))
            .context("rustc host target")?;
        let (linker, flags, source, expected_status, expected_stdout) = if direct_lld {
            let sysroot = Command::new("rustc").arg("--print=sysroot").output()?;
            anyhow::ensure!(sysroot.status.success(), "rustc sysroot query failed: {sysroot:?}");
            let sysroot = String::from_utf8(sysroot.stdout)?;
            (
                Path::new(sysroot.trim())
                    .join("lib/rustlib")
                    .join(host)
                    .join("bin/rust-lld"),
                "rustflags = [\"-Clinker-flavor=ld64.lld\"]\n",
                "#![no_std]\n#![no_main]\n\
                 #[panic_handler]\nfn panic(_: &core::panic::PanicInfo) -> ! { loop {} }\n\
                 #[unsafe(no_mangle)]\npub extern \"C\" fn main() -> i32 { 42 }\n",
                Some(42),
                &b""[..],
            )
        } else {
            (
                PathBuf::from("/usr/bin/cc"),
                "",
                "fn main() { println!(\"explicit linker result\"); }\n",
                Some(0),
                &b"explicit linker result\n"[..],
            )
        };
        let workspace = TestWorkspace::new_single_crate("explicit-linker", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        fs::remove_file(workspace.path.join("src/lib.rs"))?;
        fs::write(workspace.path.join("src/main.rs"), source)?;
        fs::create_dir(workspace.path.join(".cargo"))?;
        fs::write(
            workspace.path.join(".cargo/config.toml"),
            format!(
                "[target.{host}]\nlinker = {}\n{flags}\n[profile.dev]\nsplit-debuginfo = \"off\"\npanic = \"abort\"\n",
                serde_json::to_string(linker.to_str().context("linker path")?)?
            ),
        )?;
        explicit_target_cargo(&workspace.path, cargo_home.path(), "build", host, None)
            .context("uncached upstream explicit-linker fixture must build before cache qualification")?;
        let target_directory = workspace.path.join("target").join(host);
        let executable = target_directory.join("debug/explicit-linker");
        let baseline_bytes = fs::read(&executable)?;
        let baseline_mode = fs::metadata(&executable)?.permissions().mode() & 0o777;
        anyhow::ensure!(baseline_mode & 0o111 != 0, "upstream output has no executable mode");
        let baseline_output = Command::new(&executable).output()?;
        anyhow::ensure!(
            baseline_output.status.code() == expected_status,
            "upstream executable failed: {baseline_output:?}"
        );
        anyhow::ensure!(
            baseline_output.stdout == expected_stdout,
            "upstream executable stdout changed: {baseline_output:?}"
        );
        anyhow::ensure!(baseline_output.stderr.is_empty(), "upstream executable emitted stderr");
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        anyhow::ensure!(setup.status.success(), "explicit-linker cache setup failed: {setup:?}");

        let reports = tempfile::tempdir()?;
        for (phase, expected_hits) in [("cold", 0), ("warm", 1)] {
            fs::remove_dir_all(&target_directory)?;
            let recording = reports.path().join(format!("{phase}.json"));
            let path = recording.to_str().context("explicit-linker report path")?;
            let started = rail(
                &workspace.path,
                cargo_home.path(),
                &["rail", "cache", "report", "--start", path],
            )?;
            anyhow::ensure!(started.status.success(), "{phase} report start failed: {started:?}");
            explicit_target_cargo(&workspace.path, cargo_home.path(), "build", host, Some(&recording))?;
            let finished = rail(
                &workspace.path,
                cargo_home.path(),
                &["rail", "cache", "report", "--finish", path, "-f", "json"],
            )?;
            anyhow::ensure!(finished.status.success(), "{phase} report finish failed: {finished:?}");
            let report = json(&finished)?;
            let status = selected_profile_status(&workspace.path, cargo_home.path())?;
            let usage = &status["status"]["installation"]["usage"];
            anyhow::ensure!(
                usage["misses"] == 1,
                "{phase} explicit-linker build did not retain one verified miss: {usage}; report: {report}"
            );
            anyhow::ensure!(
                usage["hits"] == expected_hits,
                "{phase} explicit-linker build had the wrong reuse outcome: {usage}; report: {report}"
            );
            anyhow::ensure!(
                fs::read(&executable)? == baseline_bytes,
                "{phase} explicit-linker output differs from uncached bytes"
            );
            anyhow::ensure!(
                fs::metadata(&executable)?.permissions().mode() & 0o777 == baseline_mode,
                "{phase} explicit-linker executable mode changed"
            );
            let output = Command::new(&executable).output()?;
            anyhow::ensure!(
                output.status == baseline_output.status,
                "{phase} explicit-linker executable failed: {output:?}"
            );
            anyhow::ensure!(
                output.stdout == baseline_output.stdout,
                "{phase} executable stdout changed"
            );
            anyhow::ensure!(
                output.stderr == baseline_output.stderr,
                "{phase} executable stderr changed"
            );
        }
        Ok(())
    })()
}

#[cfg(target_os = "macos")]
#[test]
fn cranelift_emitted_library_reuse_binds_backend_bytes_and_preserves_assembly_bypass() {
    let result: Result<()> = (|| {
        let toolchain = std::env::var("CARGO_RAIL_TEST_CRANELIFT_TOOLCHAIN")
            .context("select the matched Cranelift test toolchain")?;
        let workspace = TestWorkspace::new_single_crate("clif-fixture", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let copied = tempfile::tempdir()?;
        let original = Command::new("rustc")
            .env("RUSTUP_TOOLCHAIN", &toolchain)
            .args(["--print", "sysroot"])
            .output()?;
        anyhow::ensure!(original.status.success(), "Cranelift toolchain: {original:?}");
        let sysroot = copied.path().join("sysroot");
        let copied_output = Command::new("cp")
            .arg("-cR")
            .arg(String::from_utf8(original.stdout)?.trim())
            .arg(&sysroot)
            .output()?;
        anyhow::ensure!(
            copied_output.status.success(),
            "private sysroot clone: {copied_output:?}"
        );
        let rustc = sysroot.join("bin/rustc");
        let version = Command::new(&rustc).arg("-vV").output()?;
        anyhow::ensure!(version.status.success(), "copied compiler: {version:?}");
        let version = String::from_utf8(version.stdout)?;
        let host = version
            .lines()
            .find_map(|line| line.strip_prefix("host: "))
            .context("compiler host")?;
        let backends = fs::read_dir(sysroot.join("lib/rustlib").join(host).join("codegen-backends"))?
            .map(|entry| entry.map(|entry| entry.path()))
            .collect::<std::io::Result<Vec<_>>>()?;
        let backend = backends
            .iter()
            .filter(|path| {
                path.file_name()
                    .is_some_and(|name| name.to_string_lossy().contains("rustc_codegen_cranelift"))
            })
            .collect::<Vec<_>>();
        let [backend] = backend.as_slice() else {
            anyhow::bail!("expected one Cranelift backend");
        };
        let mut backend_bytes = fs::read(backend)?;
        backend_bytes.push(0);
        fs::write(backend, &backend_bytes)?;
        fs::create_dir_all(workspace.path.join(".cargo"))?;
        fs::write(
            workspace.path.join(".cargo/config.toml"),
            "[build]\nrustflags = [\"-Zcodegen-backend=cranelift\"]\n",
        )?;
        let source = workspace.path.join("src/lib.rs");
        fs::write(&source, "pub fn value() -> u32 { 7 }\n")?;
        let target = workspace.path.join("target");
        let reports = tempfile::tempdir()?;
        let recording = reports.path().join("cranelift.json");
        let recording_path = recording.to_str().context("Cranelift recording path")?;
        let run = |program: &Path, args: &[&str], cached: bool| -> Result<Output> {
            let mut command = Command::new(program);
            command
                .current_dir(&workspace.path)
                .args(args)
                .env("RUSTUP_TOOLCHAIN", &toolchain)
                .env("RUSTC", &rustc)
                .env("CARGO_HOME", cargo_home.path())
                .env("CARGO_TARGET_DIR", &target)
                .env("CARGO_INCREMENTAL", "0")
                .env_remove("CARGO_BUILD_TARGET")
                .env_remove("RUSTFLAGS")
                .env_remove("CARGO_ENCODED_RUSTFLAGS")
                .env_remove("RUSTC_WORKSPACE_WRAPPER")
                .env_remove("CARGO_BUILD_RUSTC_WRAPPER")
                .env_remove("CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER")
                .env_remove("CARGO_RAIL_CACHE")
                .env_remove("CARGO_RAIL_CACHE_REMOTE")
                .env_remove("CARGO_RAIL_CACHE_MODE")
                .env_remove("CARGO_RAIL_CACHE_REMOTE_ENVIRONMENT")
                .env_remove("CARGO_RAIL_CACHE_REPORT");
            if cached && program == Path::new("cargo") {
                command.env("CARGO_RAIL_CACHE_REPORT", &recording);
            }
            if cached {
                command.env_remove("RUSTC_WRAPPER");
            } else {
                command.env("RUSTC_WRAPPER", "");
            }
            Ok(command.output()?)
        };
        let compile = |cached| run(Path::new("cargo"), &["build", "--offline", "--quiet"], cached);
        let cli = &crate::helpers::cargo_binary("cargo-rail");
        let baseline = compile(false)?;
        anyhow::ensure!(baseline.status.success(), "ordinary Cranelift: {baseline:?}");
        let mut expected = directory_snapshot(&target.join("debug/deps"))?;
        let modes = expected
            .keys()
            .map(|path| {
                Ok((
                    path.clone(),
                    fs::metadata(target.join("debug/deps").join(path))?.permissions(),
                ))
            })
            .collect::<Result<Vec<_>>>()?;
        let setup = run(cli, &["rail", "cache", "setup"], true)?;
        anyhow::ensure!(setup.status.success(), "Cranelift cache setup: {setup:?}");
        let started = run(cli, &["rail", "cache", "report", "--start", recording_path], true)?;
        anyhow::ensure!(started.status.success(), "Cranelift report: {started:?}");
        for (phase, misses, hits, value) in [
            ("cold", 1, 0, 7),
            ("warm", 1, 1, 7),
            ("source changed", 2, 1, 8),
            ("source warm", 2, 2, 8),
            ("backend changed", 3, 2, 8),
            ("backend warm", 3, 3, 8),
        ] {
            if phase == "source changed" {
                fs::write(&source, "pub fn value() -> u32 { 8 }\n")?;
            }
            if phase == "backend changed" {
                *backend_bytes.last_mut().context("backend trailer")? = 1;
                fs::write(backend, &backend_bytes)?;
            }
            fs::remove_dir_all(&target)?;
            let output = compile(true)?;
            assert_eq!(output.status.code(), baseline.status.code(), "{phase}: {output:?}");
            assert_eq!(output.stdout, baseline.stdout, "{phase}");
            assert_eq!(output.stderr, baseline.stderr, "{phase}: {output:?}");
            let status = run(
                cli,
                &["rail", "cache", "status", "--scope", "local", "-f", "json"],
                true,
            )?;
            anyhow::ensure!(status.status.success(), "cache status: {status:?}");
            let status = json(&status)?;
            let usage = &status["status"]["installation"]["usage"];
            if usage["misses"] != misses || usage["hits"] != hits {
                let report = run(
                    cli,
                    &["rail", "cache", "report", "--finish", recording_path, "-f", "json"],
                    true,
                )?;
                anyhow::bail!("{phase}: {status}; report: {}", String::from_utf8_lossy(&report.stdout));
            }
            assert_eq!(usage["misses"], misses, "{phase}: {status}");
            assert_eq!(usage["hits"], hits, "{phase}: {status}");
            let observed = directory_snapshot(&target.join("debug/deps"))?;
            if phase == "source changed" {
                assert_ne!(observed, expected, "source change must change emitted bytes");
                expected = observed;
            } else {
                assert_eq!(observed, expected, "{phase} exact outputs");
            }
            for (path, mode) in &modes {
                assert_eq!(
                    &fs::metadata(target.join("debug/deps").join(path))?.permissions(),
                    mode,
                    "{phase}"
                );
            }
            let consumer = copied.path().join("consumer.rs");
            fs::write(&consumer, "fn main() { println!(\"{}\", clif_fixture::value()); }\n")?;
            let executable = copied.path().join("consumer");
            let linked = Command::new(&rustc)
                .arg(&consumer)
                .arg("--extern")
                .arg(format!(
                    "clif_fixture={}",
                    target.join("debug/libclif_fixture.rlib").display()
                ))
                .arg("-o")
                .arg(&executable)
                .output()?;
            anyhow::ensure!(linked.status.success(), "consume emitted rlib: {linked:?}");
            let executed = Command::new(&executable).output()?;
            anyhow::ensure!(executed.status.success(), "execute rlib consumer: {executed:?}");
            assert_eq!(executed.stdout, format!("{value}\n").as_bytes());
            assert!(executed.stderr.is_empty());
        }
        fs::write(
            &source,
            "pub fn value() -> u32 { 8 }\ncore::arch::global_asm!(\".byte 0\");\n",
        )?;
        fs::remove_dir_all(&target)?;
        let assembly_baseline = compile(false)?;
        anyhow::ensure!(
            assembly_baseline.status.success(),
            "ordinary assembly: {assembly_baseline:?}"
        );
        let assembly_outputs = directory_snapshot(&target.join("debug/deps"))?;
        fs::remove_dir_all(&target)?;
        let assembly = compile(true)?;
        assert_eq!(assembly.status.code(), assembly_baseline.status.code(), "{assembly:?}");
        assert_eq!(assembly.stdout, assembly_baseline.stdout);
        assert_eq!(assembly.stderr, assembly_baseline.stderr);
        assert_eq!(directory_snapshot(&target.join("debug/deps"))?, assembly_outputs);
        let status = run(
            cli,
            &["rail", "cache", "status", "--scope", "local", "-f", "json"],
            true,
        )?;
        anyhow::ensure!(status.status.success(), "assembly cache status: {status:?}");
        let status = json(&status)?;
        let usage = &status["status"]["installation"]["usage"];
        assert_eq!(usage["misses"], 3, "{status}");
        assert_eq!(usage["hits"], 3, "{status}");
        assert_eq!(usage["bypasses"], 1, "{status}");
        let finished = run(
            cli,
            &["rail", "cache", "report", "--finish", recording_path, "-f", "json"],
            true,
        )?;
        anyhow::ensure!(finished.status.success(), "Cranelift report finish: {finished:?}");
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(all(target_os = "linux", target_env = "gnu"))]
#[test]
#[ignore = "requires GNU BFD and a C compiler; run actual linker-runtime qualification explicitly"]
fn elf_link_adapter_rejects_a_runtime_loaded_only_during_linking() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let root = tempfile::tempdir()?;
        fs::set_permissions(root.path(), fs::Permissions::from_mode(0o700))?;
        let source = root.path().join("native.c");
        let object = root.path().join("native.o");
        let observer_source = root.path().join("observer.c");
        let observer = root.path().join("observer.so");
        let plugin = root.path().join("extra.so");
        fs::write(&source, "unsigned native_value(void) { return 7; }\n")?;
        fs::write(
            &observer_source,
            r#"#define _GNU_SOURCE
#include <dlfcn.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
__attribute__((constructor)) static void observe_link(void) {
    char argv[16384];
    int fd = open("/proc/self/cmdline", O_RDONLY);
    if (fd < 0) return;
    ssize_t len = read(fd, argv, sizeof(argv));
    close(fd);
    if (len <= 0 || !memmem(argv, (size_t)len, "--dependency-file=", 18)) return;
    const char *marker = getenv("RAIL_LINK_EXECUTIONS");
    if (marker) {
        FILE *file = fopen(marker, "a");
        if (file) { fputs("link execution\n", file); fclose(file); }
    }
    const char *plugin = getenv("RAIL_LINK_RUNTIME_PLUGIN");
    if (plugin) dlopen(plugin, RTLD_NOW | RTLD_LOCAL);
}
"#,
        )?;
        for arguments in [
            vec![
                "-fPIC".into(),
                "-c".into(),
                source.as_os_str().to_owned(),
                "-o".into(),
                object.as_os_str().to_owned(),
            ],
            vec![
                "-fPIC".into(),
                "-shared".into(),
                source.as_os_str().to_owned(),
                "-o".into(),
                plugin.as_os_str().to_owned(),
            ],
            vec![
                "-fPIC".into(),
                "-shared".into(),
                observer_source.as_os_str().to_owned(),
                "-ldl".into(),
                "-o".into(),
                observer.as_os_str().to_owned(),
            ],
        ] {
            let compiled = Command::new("cc").args(arguments).output()?;
            anyhow::ensure!(compiled.status.success(), "C fixture compilation: {compiled:?}");
        }
        let selected = Command::new("sh").args(["-c", "command -v ld.bfd"]).output()?;
        anyhow::ensure!(selected.status.success(), "BFD prerequisite: {selected:?}");
        let linker = PathBuf::from(String::from_utf8(selected.stdout)?.trim());
        for late_runtime in [false, true] {
            let attempt = tempfile::tempdir_in(root.path())?;
            fs::set_permissions(attempt.path(), fs::Permissions::from_mode(0o700))?;
            let output = attempt.path().join("libnative.so");
            let marker = attempt.path().join("executions");
            let certificate = attempt.path().join("elf-linker-dependencies.d");
            let evidence = attempt.path().join("elf-linker-driver-inputs.json");
            let configure = |command: &mut Command| {
                command
                    .arg("-shared")
                    .arg(&object)
                    .arg("-o")
                    .arg(&output)
                    .env("LD_PRELOAD", &observer)
                    .env("RAIL_LINK_EXECUTIONS", &marker)
                    .env_remove("LD_DEBUG")
                    .env_remove("LD_DEBUG_OUTPUT")
                    .env_remove("LD_TRACE_LOADED_OBJECTS")
                    .env_remove("RAIL_LINK_RUNTIME_PLUGIN");
                if late_runtime {
                    command.env("RAIL_LINK_RUNTIME_PLUGIN", &plugin);
                }
            };
            let mut ordinary = Command::new(&linker);
            configure(&mut ordinary);
            let ordinary = ordinary.output()?;
            anyhow::ensure!(ordinary.status.success(), "ordinary link: {ordinary:?}");
            let bytes = fs::read(&output)?;
            let mode = fs::metadata(&output)?.permissions();
            fs::remove_file(&output)?;
            let mut adapter = Command::new(crate::helpers::cargo_binary("cargo-rail"));
            configure(&mut adapter);
            adapter
                .env("CARGO_RAIL_ELF_LINK_ADAPTER", "1")
                .env("CARGO_RAIL_ELF_LINK_DRIVER", &linker)
                .env("CARGO_RAIL_ELF_LINK_DEPENDENCIES", &certificate)
                .env("CARGO_RAIL_ELF_LINK_DRIVER_INPUTS", &evidence);
            let observed = adapter.output()?;
            assert_eq!(observed.status.code(), ordinary.status.code(), "{observed:?}");
            assert_eq!(observed.stdout, ordinary.stdout);
            assert_eq!(observed.stderr, ordinary.stderr);
            assert_eq!(fs::read(&output)?, bytes);
            assert_eq!(fs::metadata(&output)?.permissions(), mode);
            assert_eq!(fs::read(&marker)?, b"link execution\n", "linker must execute once");
            let record: serde_json::Value = serde_json::from_slice(&fs::read(&evidence)?)?;
            assert_eq!(record["completed"], !late_runtime, "{record}");
        }
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(target_os = "linux")]
#[test]
#[ignore = "requires mold, a C compiler, ar and Python; run the direct ELF linker contract explicitly"]
fn direct_mold_reuse_tracks_selected_libraries_and_tool_bytes() {
    elf_linker_reuse("mold", false);
}

#[cfg(target_os = "linux")]
#[test]
#[ignore = "requires GNU BFD, a C compiler, ar and Python; run the direct ELF linker contract explicitly"]
fn direct_bfd_reuse_tracks_selected_libraries_and_tool_bytes() {
    elf_linker_reuse("ld.bfd", false);
}

#[cfg(target_os = "linux")]
#[test]
#[ignore = "requires GNU gold, a C compiler, ar and Python; run the direct ELF linker contract explicitly"]
fn direct_gold_reuse_tracks_selected_libraries_and_tool_bytes() {
    elf_linker_reuse("ld.gold", false);
}

#[cfg(target_os = "linux")]
#[test]
#[ignore = "requires GCC, collect2, GNU ld, liblto_plugin, ar and Python; run the GCC linker contract explicitly"]
fn gcc_driver_reuse_tracks_selected_tools_and_plugin_bytes() {
    elf_linker_reuse("gcc", false);
}

#[cfg(target_os = "linux")]
#[test]
#[ignore = "requires GCC, collect2, GNU ld, liblto_plugin, ar and Python; run the default GCC contract explicitly"]
fn default_gcc_driver_reuse_tracks_selected_tools_and_plugin_bytes() {
    elf_linker_reuse("gcc", true);
}

#[cfg(target_os = "linux")]
fn elf_linker_reuse(linker_name: &str, default_gcc: bool) {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let workspace = TestWorkspace::new_single_crate("direct-elf", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let coverage = tempfile::tempdir()?;
        fs::set_permissions(coverage.path(), fs::Permissions::from_mode(0o700))?;
        let selected_linker = Command::new("sh")
            .args(["-c", "command -v \"$1\"", "select-linker", linker_name])
            .output()?;
        anyhow::ensure!(
            selected_linker.status.success(),
            "{linker_name} prerequisite: {selected_linker:?}"
        );
        let selected_linker = fs::canonicalize(String::from_utf8(selected_linker.stdout)?.trim())?;
        let mut tool_bytes = fs::read(&selected_linker)?;
        tool_bytes.push(0);
        let linker = if linker_name == "gcc" {
            let bin = workspace.path.join("gcc-installation/bin");
            fs::create_dir_all(&bin)?;
            bin.join(if default_gcc { "cc" } else { "gcc" })
        } else {
            workspace.path.join(linker_name)
        };
        fs::write(&linker, &tool_bytes)?;
        fs::set_permissions(&linker, fs::Permissions::from_mode(0o700))?;
        let mut tools = vec![(linker.clone(), tool_bytes)];
        if linker_name == "gcc" {
            let compiler_prefix = selected_linker
                .parent()
                .and_then(Path::parent)
                .context("GCC installation prefix")?;
            let query = |argument: &str| -> Result<String> {
                let output = Command::new("gcc").arg(argument).output()?;
                anyhow::ensure!(output.status.success(), "GCC {argument} prerequisite: {output:?}");
                Ok(String::from_utf8(output.stdout)?.trim().to_string())
            };
            let triple = query("-dumpmachine")?;
            let installation = workspace.path.join("gcc-installation");
            let linker_directory = installation.join(&triple).join("bin");
            fs::create_dir_all(&linker_directory)?;
            let mut selections = Vec::new();
            for (name, query_argument, mutate) in [
                ("collect2", "-print-prog-name=collect2", true),
                ("ld.bfd", "-print-prog-name=ld.bfd", true),
                ("liblto_plugin.so", "-print-file-name=liblto_plugin.so", true),
                ("lto-wrapper", "-print-prog-name=lto-wrapper", false),
                ("crtbeginS.o", "-print-file-name=crtbeginS.o", false),
                ("crtendS.o", "-print-file-name=crtendS.o", false),
            ] {
                let selection = query(query_argument)?;
                let source = if Path::new(&selection).is_absolute() {
                    PathBuf::from(selection)
                } else {
                    let resolved = Command::new("sh")
                        .args(["-c", "command -v \"$1\"", "select-gcc-tool", &selection])
                        .output()?;
                    anyhow::ensure!(resolved.status.success(), "resolve GCC {name}: {resolved:?}");
                    PathBuf::from(String::from_utf8(resolved.stdout)?.trim())
                };
                let canonical = fs::canonicalize(&source).with_context(|| format!("resolve GCC {name}: {source:?}"))?;
                let mut bytes = fs::read(&canonical)?;
                if mutate {
                    bytes.push(0);
                }
                // Preserve GCC's lib/libexec layout and aliases so information
                // probes and actual links select the same private runtime files.
                let path = if name == "ld.bfd" {
                    linker_directory.join(name)
                } else {
                    installation.join(canonical.strip_prefix(compiler_prefix)?)
                };
                fs::create_dir_all(path.parent().context("private GCC input parent")?)?;
                fs::write(&path, &bytes)?;
                fs::set_permissions(&path, fs::Permissions::from_mode(0o700))?;
                if name != "ld.bfd" && source != canonical {
                    let alias = installation.join(source.strip_prefix(compiler_prefix)?);
                    fs::create_dir_all(alias.parent().context("private GCC alias parent")?)?;
                    std::os::unix::fs::symlink(&path, alias)?;
                }
                selections.push((name, query_argument, path.clone()));
                if mutate {
                    tools.push((path, bytes));
                }
            }
            // GCC's relative searches can traverse another tool's directory.
            // Complete the installation before validating any selection.
            for (name, query_argument, path) in selections {
                let selected = Command::new(&linker).arg(query_argument).output()?;
                anyhow::ensure!(selected.status.success(), "private GCC selection: {selected:?}");
                let selection = String::from_utf8(selected.stdout)?;
                assert_eq!(
                    fs::canonicalize(selection.trim())
                        .with_context(|| format!("private GCC {name} selection: {selection:?}"))?,
                    fs::canonicalize(&path)?,
                    "GCC must select the private {name} before its mutation is exercised"
                );
            }
        }
        let early = workspace.path.join("early");
        let selected = workspace.path.join("selected");
        fs::create_dir(&selected)?;
        let build_library = |directory: &Path, value: u32| -> Result<()> {
            fs::create_dir_all(directory)?;
            let source = directory.join("native.c");
            let object = directory.join("native.o");
            fs::write(
                &source,
                format!("unsigned cache_native_value(void) {{ return {value}; }}\n"),
            )?;
            let compiled = Command::new("cc")
                .args(["-fPIC", "-c"])
                .arg(&source)
                .arg("-o")
                .arg(&object)
                .output()?;
            anyhow::ensure!(compiled.status.success(), "C prerequisite: {compiled:?}");
            let archived = Command::new("ar")
                .arg("crs")
                .arg(directory.join("libcache_native.a"))
                .arg(&object)
                .output()?;
            anyhow::ensure!(archived.status.success(), "archive prerequisite: {archived:?}");
            Ok(())
        };
        build_library(&selected, 7)?;
        fs::write(
            workspace.path.join("Cargo.toml"),
            "[package]\nname = \"direct-elf\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\
             [lib]\ncrate-type = [\"cdylib\"]\n[profile.dev]\npanic = \"abort\"\ndebug = 0\n",
        )?;
        fs::write(
            workspace.path.join("src/lib.rs"),
            "#![no_std]\n#[link(name = \"cache_native\", kind = \"static\")]\n\
             unsafe extern \"C\" { fn cache_native_value() -> u32; }\n\
             #[unsafe(no_mangle)] pub extern \"C\" fn cache_linker_value() -> u32 { unsafe { cache_native_value() } }\n\
             #[panic_handler] fn panic(_: &core::panic::PanicInfo<'_>) -> ! { loop {} }\n",
        )?;
        fs::create_dir(workspace.path.join(".cargo"))?;
        let mut flags = vec![
            format!("-Clinker-flavor={}", if linker_name == "gcc" { "gcc" } else { "ld" }),
            format!("-Lnative={}", early.display()),
            format!("-Lnative={}", selected.display()),
        ];
        if linker_name == "gcc" {
            // Select the BFD contract explicitly; target defaults can select LLD.
            flags.push("-Clink-arg=-fuse-ld=bfd".to_string());
        }
        if !default_gcc {
            flags.push(format!("-Clinker={}", linker.display()));
        }
        let inherited_path = std::env::var_os("PATH").context("toolchain PATH")?;
        let path = if default_gcc {
            std::env::join_paths(
                std::iter::once(linker.parent().context("private GCC bin directory")?.to_path_buf())
                    .chain(std::env::split_paths(&inherited_path)),
            )?
        } else {
            inherited_path
        };
        fs::write(
            workspace.path.join(".cargo/config.toml"),
            format!("[build]\nrustflags = {}\n", serde_json::to_string(&flags)?),
        )?;
        let target = workspace.path.join("target");
        let compile = || -> Result<Output> {
            Ok(Command::new("cargo")
                .current_dir(&workspace.path)
                .args(["build", "--offline", "--quiet"])
                .env("PATH", &path)
                .env("CARGO_HOME", cargo_home.path())
                .env("CARGO_TARGET_DIR", &target)
                .env("CARGO_INCREMENTAL", "0")
                .env("CARGO_RAIL_CACHE", "__cargo_rail_benchmark_coverage_v1")
                .env("CARGO_RAIL_BENCH_NATIVE_COVERAGE_DIRECTORY", coverage.path())
                .env_remove("CARGO_BUILD_TARGET")
                .env_remove("RUSTC_WRAPPER")
                .env_remove("RUSTC_WORKSPACE_WRAPPER")
                .env_remove("CARGO_BUILD_RUSTC_WRAPPER")
                .env_remove("CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER")
                .env_remove("RUSTFLAGS")
                .env_remove("CARGO_ENCODED_RUSTFLAGS")
                .env_remove("CARGO_RAIL_CACHE_REMOTE")
                .env_remove("CARGO_RAIL_CACHE_MODE")
                .env_remove("CARGO_RAIL_CACHE_REMOTE_ENVIRONMENT")
                .env_remove("CARGO_RAIL_CACHE_REPORT")
                .output()?)
        };
        let baseline = compile()?;
        anyhow::ensure!(baseline.status.success(), "ordinary {linker_name} build: {baseline:?}");
        let mut expected_outputs = directory_snapshot(&target.join("debug/deps"))?;
        let expected_modes = expected_outputs
            .keys()
            .map(|path| {
                Ok((
                    path.clone(),
                    fs::metadata(target.join("debug/deps").join(path))?.permissions().mode(),
                ))
            })
            .collect::<Result<BTreeMap<_, _>>>()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        anyhow::ensure!(setup.status.success(), "{linker_name} cache setup: {setup:?}");
        let mut phases = vec![
            ("cold".to_string(), 1, 0, 7, None),
            ("warm".to_string(), 1, 1, 7, None),
            ("library changed".to_string(), 2, 1, 8, None),
            ("library warm".to_string(), 2, 2, 8, None),
        ];
        let (mut misses, mut hits) = (2, 2);
        for (index, (path, _)) in tools.iter().enumerate() {
            misses += 1;
            phases.push((
                format!("tool changed: {}", path.display()),
                misses,
                hits,
                8,
                Some(index),
            ));
            hits += 1;
            phases.push((format!("tool warm: {}", path.display()), misses, hits, 8, None));
        }
        phases.push(("earlier candidate".to_string(), misses + 1, hits, 9, None));
        phases.push(("earlier warm".to_string(), misses + 1, hits + 1, 9, None));
        for (phase, misses, hits, value, changed_tool) in phases {
            if phase == "library changed" {
                let length = fs::metadata(selected.join("libcache_native.a"))?.len();
                build_library(&selected, value)?;
                assert_eq!(fs::metadata(selected.join("libcache_native.a"))?.len(), length);
            } else if let Some(index) = changed_tool {
                let (path, bytes) = &mut tools[index];
                *bytes.last_mut().context("tool trailer")? = 1;
                fs::write(path, bytes)?;
            } else if phase == "earlier candidate" {
                build_library(&early, value)?;
            }
            fs::remove_dir_all(&target)?;
            let output = compile()?;
            assert_eq!(output.status.code(), baseline.status.code(), "{phase}: {output:?}");
            assert_eq!(output.stdout, baseline.stdout, "{phase} compiler stdout");
            assert_eq!(
                output.stderr,
                baseline.stderr,
                "{phase} compiler stderr: {}",
                String::from_utf8_lossy(&output.stderr)
            );
            let status = selected_profile_status(&workspace.path, cargo_home.path())?;
            let usage = &status["status"]["installation"]["usage"];
            let events = directory_snapshot(coverage.path())?
                .values()
                .map(|bytes| serde_json::from_slice::<serde_json::Value>(bytes))
                .collect::<Result<Vec<_>, _>>()?;
            assert_eq!(usage["misses"], misses, "{phase}: {status}; events: {events:?}");
            assert_eq!(usage["hits"], hits, "{phase}: {status}");
            let outputs = directory_snapshot(&target.join("debug/deps"))?;
            if matches!(phase.as_str(), "library changed" | "earlier candidate") {
                assert_ne!(outputs, expected_outputs, "{phase} must affect linked bytes");
                expected_outputs = outputs;
            } else {
                assert_eq!(outputs, expected_outputs, "{phase} exact compiler output inventory");
            }
            for (path, mode) in &expected_modes {
                assert_eq!(
                    fs::metadata(target.join("debug/deps").join(path))?.permissions().mode(),
                    *mode,
                    "{phase}"
                );
            }
            let executed = Command::new("python3")
                .args([
                    "-c",
                    "import ctypes, sys; print(ctypes.CDLL(sys.argv[1]).cache_linker_value())",
                ])
                .arg(target.join("debug/libdirect_elf.so"))
                .output()?;
            assert!(executed.status.success(), "{phase}: {executed:?}");
            assert_eq!(executed.stdout, format!("{value}\n").as_bytes(), "{phase}");
            assert!(executed.stderr.is_empty(), "{phase}: {executed:?}");
        }
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(target_os = "macos")]
#[test]
fn cache_setup_preserves_the_implicit_linker_selected_from_path() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let workspace = TestWorkspace::new_single_crate("path-linker", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let tools = tempfile::tempdir()?;
        let driver = tools.path().join("cc");
        let selected_log = tools.path().join("selected.log");
        let recording = tools.path().join("report.json");
        let report_path = recording.to_str().context("PATH linker report path")?;
        fs::write(
            &driver,
            "#!/bin/sh\nprintf 'selected cc\\n' >> \"$SELECTED_CC_LOG\"\nexec /usr/bin/cc \"$@\"\n",
        )?;
        fs::set_permissions(&driver, fs::Permissions::from_mode(0o755))?;
        let inherited_path = std::env::var_os("PATH").context("toolchain PATH")?;
        let path = std::env::join_paths(
            std::iter::once(tools.path().to_path_buf()).chain(std::env::split_paths(&inherited_path)),
        )?;
        fs::remove_file(workspace.path.join("src/lib.rs"))?;
        fs::write(
            workspace.path.join("src/main.rs"),
            "fn main() { println!(\"selected linker result\"); }\n",
        )?;

        for phase in ["upstream", "installed"] {
            if phase == "installed" {
                let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
                assert!(setup.status.success(), "PATH linker cache setup failed: {setup:?}");
                fs::remove_dir_all(workspace.path.join("target"))?;
                let started = rail(
                    &workspace.path,
                    cargo_home.path(),
                    &["rail", "cache", "report", "--start", report_path],
                )?;
                assert!(started.status.success(), "PATH linker report start failed: {started:?}");
            }
            fs::write(&selected_log, b"")?;
            let mut command = Command::new("cargo");
            for (name, _) in std::env::vars_os() {
                if name.to_str().is_some_and(|name| {
                    name.starts_with("CARGO_RAIL_") || name.starts_with("CARGO_TARGET_") && name.ends_with("_LINKER")
                }) {
                    command.env_remove(name);
                }
            }
            command
                .current_dir(&workspace.path)
                .args(["build", "--offline", "--quiet"])
                .env("CARGO_HOME", cargo_home.path())
                .env("CARGO_INCREMENTAL", "0")
                .env("CARGO_TARGET_DIR", workspace.path.join("target"))
                .env("PATH", &path)
                .env("SELECTED_CC_LOG", &selected_log)
                .env_remove("CARGO_BUILD_TARGET")
                .env_remove("CARGO_BUILD_RUSTC_WRAPPER")
                .env_remove("CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER")
                .env_remove("RUSTC_WRAPPER")
                .env_remove("RUSTC_WORKSPACE_WRAPPER")
                .env_remove("RUSTFLAGS")
                .env_remove("CARGO_ENCODED_RUSTFLAGS")
                .env_remove("OUT_DIR");
            if phase == "installed" {
                command.env("CARGO_RAIL_CACHE_REPORT", &recording);
            }
            let built = command.output()?;
            assert!(built.status.success(), "{phase} PATH linker build failed: {built:?}");
            assert_eq!(
                fs::read(&selected_log)?,
                b"selected cc\n",
                "{phase} build did not execute the selected PATH linker exactly once"
            );
            let output = Command::new(workspace.path.join("target/debug/path-linker")).output()?;
            assert!(output.status.success(), "{phase} executable failed: {output:?}");
            assert_eq!(output.stdout, b"selected linker result\n");
            assert!(output.stderr.is_empty());
        }
        let finished = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "report", "--finish", report_path, "-f", "json"],
        )?;
        assert!(
            finished.status.success(),
            "PATH linker report finish failed: {finished:?}"
        );
        let report = json(&finished)?;
        assert_eq!(
            report["measurements"]["bypass_reasons"]["default_linker_execution_evidence_unavailable"], 1,
            "custom PATH linker must execute normally without cache admission: {report}"
        );
        assert_eq!(report["measurements"]["misses"], 0, "{report}");
        assert_eq!(report["measurements"]["hits"], 0, "{report}");
        assert_eq!(report["measurements"]["failures"], 0, "{report}");
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(target_os = "macos")]
#[test]
fn apple_link_adapter_retry_certifies_only_the_successful_attempt() {
    let result: Result<()> = (|| {
        let fixture = tempfile::tempdir()?;
        let directory = fs::canonicalize(fixture.path())?;
        let source = directory.join("main.c");
        let object = directory.join("main.o");
        let missing = directory.join("missing.o");
        let executable = directory.join("linked");
        let certificate = directory.join("apple-linker-dependencies.bin");
        let driver_inputs = directory.join("apple-linker-driver-inputs.json");
        fs::write(
            &source,
            "#include <stdio.h>\nint main(void) { puts(\"adapter retry result\"); return 0; }\n",
        )?;
        let compiled = Command::new("/usr/bin/cc")
            .arg("-c")
            .arg(&source)
            .arg("-o")
            .arg(&object)
            .output()?;
        assert!(
            compiled.status.success(),
            "adapter object prerequisite failed: {compiled:?}"
        );

        let adapter = |inputs: &[&Path]| -> Result<Output> {
            let mut command = Command::new(crate::helpers::cargo_binary("cargo-rail"));
            for (name, _) in std::env::vars_os() {
                if name.to_str().is_some_and(|name| name.starts_with("CARGO_RAIL_")) {
                    command.env_remove(name);
                }
            }
            command
                .current_dir(&directory)
                .args(inputs)
                .arg("-o")
                .arg(&executable)
                .env("CARGO_RAIL_APPLE_LINK_ADAPTER", "1")
                .env("CARGO_RAIL_APPLE_LINK_DRIVER", "/usr/bin/cc")
                .env("CARGO_RAIL_APPLE_LINK_CERTIFICATE", &certificate)
                .env("CARGO_RAIL_APPLE_LINK_DRIVER_INPUTS", &driver_inputs)
                .output()
                .context("run the real Apple linker adapter")
        };
        let ordinary_failure = Command::new("/usr/bin/cc")
            .arg(&missing)
            .arg(&object)
            .arg("-o")
            .arg(&executable)
            .output()?;
        assert!(!ordinary_failure.status.success());
        let failed = adapter(&[&missing, &object])?;
        assert_eq!(failed.status.code(), ordinary_failure.status.code(), "{failed:?}");
        assert_eq!(failed.stdout, ordinary_failure.stdout);
        assert_eq!(failed.stderr, ordinary_failure.stderr);
        assert!(!executable.exists());
        assert!(
            fs::read(&driver_inputs)?.is_empty(),
            "failed driver probing must not certify an invocation"
        );

        let completed = adapter(&[&object])?;
        assert!(completed.status.success(), "adapter retry failed: {completed:?}");
        assert!(completed.stdout.is_empty(), "{completed:?}");
        assert!(completed.stderr.is_empty(), "{completed:?}");
        let evidence: serde_json::Value = serde_json::from_slice(&fs::read(&driver_inputs)?)?;
        assert_eq!(evidence["completed"], true, "{evidence}");
        assert_eq!(evidence["direct_inputs"], serde_json::json!([object]));
        assert!(fs::metadata(&certificate)?.len() > 0);
        let output = Command::new(&executable).output()?;
        assert!(output.status.success(), "retried link output failed: {output:?}");
        assert_eq!(output.stdout, b"adapter retry result\n");
        assert!(output.stderr.is_empty());
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[test]
fn setup_check_in_a_source_checkout_reports_the_missing_component_recovery() {
    let result: Result<()> = (|| {
        let source_checkout = tempfile::tempdir()?;
        let source_root = source_checkout.path();
        let source_target = source_root.join("target");
        fs::create_dir_all(&source_target)?;
        let isolated_bin = tempfile::Builder::new()
            .prefix("cargo-rail-missing-worker-")
            .tempdir_in(&source_target)?;
        let executable_name = crate::helpers::cargo_binary("cargo-rail")
            .file_name()
            .context("cargo-rail test binary has no file name")?
            .to_owned();
        let executable = isolated_bin.path().join(executable_name);
        fs::copy(crate::helpers::cargo_binary("cargo-rail"), &executable)?;
        let cargo_home = tempfile::tempdir()?;

        let output = Command::new(&executable)
            .current_dir(source_root)
            .args(["rail", "cache", "setup", "--check"])
            .env("CARGO_HOME", cargo_home.path())
            .env_remove("CARGO_BUILD_RUSTC_WRAPPER")
            .env_remove("RUSTC_WRAPPER")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .output()?;

        assert_eq!(output.status.code(), Some(2), "{output:?}");
        assert!(output.stdout.is_empty());
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("native compiler cache worker executable is unavailable"),
            "{stderr}"
        );
        assert!(stderr.contains("just build"), "{stderr}");
        assert!(stderr.contains("cargo rail cache setup --check"), "{stderr}");
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[test]
fn setup_preview_apply_repeat_status_and_exact_remove_are_lossless() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("transparent-setup", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            fs::set_permissions(cargo_home.path(), fs::Permissions::from_mode(0o755))?;
        }
        let config = cargo_home.path().join("config.toml");
        let original = "# retained\n[net]\noffline = true\n";
        fs::write(&config, original)?;

        let check = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "setup", "--check", "-f", "json"],
        )?;
        assert_eq!(
            check.status.code(),
            Some(1),
            "setup preview must report changes: {check:?}"
        );
        assert_eq!(
            fs::read_to_string(&config)?,
            original,
            "setup preview mutated Cargo config"
        );
        assert!(!cargo_home.path().join("cargo-rail/compiler-cache-v1").exists());

        let apply = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "setup", "--max-size", "32MiB", "-f", "json"],
        )?;
        assert!(apply.status.success(), "setup failed: {apply:?}");
        let applied = json(&apply)?;
        assert_eq!(applied["changed"], true);
        assert_eq!(applied["pending"], false);
        assert_eq!(applied["max_bytes"], 32 * 1024 * 1024);
        let configured = fs::read_to_string(&config)?;
        assert!(configured.starts_with(original));
        assert!(configured.contains("rustc-wrapper"));
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            assert_eq!(fs::metadata(cargo_home.path())?.permissions().mode() & 0o777, 0o755);
        }

        let repeated = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "setup", "--check", "-f", "json"],
        )?;
        assert!(
            repeated.status.success(),
            "repeat setup was not idempotent: {repeated:?}"
        );
        assert_eq!(json(&repeated)?["pending"], false);

        let status = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local", "-f", "json"],
        )?;
        assert!(status.status.success(), "installation status failed: {status:?}");
        let status = json(&status)?;
        assert_eq!(status["status"]["schema_version"], 18);
        assert_eq!(status["status"]["installation"]["state"], "installed");
        assert_eq!(status["status"]["installation"]["healthy"], true);
        assert_eq!(status["status"]["installation"]["root_portability"], "physical");
        let wrapper = PathBuf::from(
            status["status"]["installation"]["wrapper_path"]
                .as_str()
                .context("installed wrapper path")?,
        );
        let profile_cache_root = PathBuf::from(
            status["status"]["local"]["cache"]["root"]
                .as_str()
                .context("profile cache root")?,
        );

        fs::remove_file(&wrapper)?;
        let drifted = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local", "-f", "json"],
        )?;
        assert_eq!(json(&drifted)?["status"]["installation"]["state"], "drifted");
        let repair_check = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "setup", "--check"],
        )?;
        assert_eq!(repair_check.status.code(), Some(1));
        let repair = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(repair.status.success(), "setup repair failed: {repair:?}");
        assert!(wrapper.is_file(), "setup repair did not restore the owned wrapper");
        #[cfg(not(windows))]
        let worker = wrapper.with_file_name("cargo-rail-native-rustc-worker");
        #[cfg(windows)]
        let worker = wrapper.with_file_name("cargo-rail-native-rustc-worker.exe");
        assert!(worker.is_file(), "setup did not install the owned worker");
        fs::remove_file(&worker)?;
        let drifted = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local", "-f", "json"],
        )?;
        assert_eq!(json(&drifted)?["status"]["installation"]["state"], "drifted");
        let repair = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(repair.status.success(), "worker repair failed: {repair:?}");
        assert!(worker.is_file(), "setup repair did not restore the owned worker");

        let remove_check = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "uninstall", "--check", "-f", "json"],
        )?;
        assert_eq!(remove_check.status.code(), Some(1));
        assert!(config.exists(), "removal preview mutated Cargo config");
        let remove = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "uninstall", "-f", "json"],
        )?;
        assert!(remove.status.success(), "removal failed: {remove:?}");
        assert_eq!(fs::read_to_string(&config)?, original);
        assert!(!cargo_home.path().join("cargo-rail/compiler-cache-v1").exists());
        assert!(profile_cache_root.exists(), "uninstall deleted the profile CAS");
        assert!(
            cargo_home.path().join("cargo-rail/cache-profiles-v1").is_dir(),
            "uninstall deleted the profile registry"
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[test]
fn markerless_local_cas_recovery_quarantines_every_byte_before_reinitializing() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("transparent-recovery", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "setup failed: {setup:?}");
        let seeded = cargo_check(&workspace.path, cargo_home.path(), None, None)?;
        assert!(seeded.status.success(), "cache seed failed: {seeded:?}");

        let root = fs::canonicalize(selected_profile_cache_root(&workspace.path, cargo_home.path())?)?;
        fs::remove_file(root.join("OWNER"))?;
        fs::remove_file(root.join("CAPACITY.json"))?;
        fs::remove_file(root.join("NATIVE_LEDGER.json"))?;
        let retained = directory_snapshot(&root)?;
        assert!(!retained.is_empty(), "partial CAS fixture retained no cache bytes");

        let preview = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "recover", "--check", "-f", "json"],
        )?;
        assert_eq!(
            preview.status.code(),
            Some(1),
            "recovery preview did not report pending work"
        );
        let preview = json(&preview)?;
        assert_eq!(preview["pending"], true);
        assert_eq!(preview["recovery"]["selected_root"], root.to_string_lossy().as_ref());
        let quarantine = PathBuf::from(
            preview["recovery"]["quarantine_root"]
                .as_str()
                .context("quarantine path")?,
        );
        let receipt = PathBuf::from(
            preview["recovery"]["receipt_path"]
                .as_str()
                .context("recovery receipt path")?,
        );
        assert!(root.is_dir());
        assert!(!quarantine.exists());
        assert!(!receipt.exists());

        let applied = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "recover", "-f", "json"],
        )?;
        assert!(applied.status.success(), "recovery failed: {applied:?}");
        let applied = json(&applied)?;
        assert_eq!(
            applied["recovery"]["quarantine_root"],
            quarantine.to_string_lossy().as_ref()
        );
        assert_eq!(directory_snapshot(&quarantine)?, retained);
        assert!(root.join("OWNER").is_file());
        assert_eq!(
            serde_json::from_slice::<serde_json::Value>(&fs::read(&receipt)?)?["state"],
            "completed"
        );

        let repeated = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "recover", "--check", "-f", "json"],
        )?;
        assert!(
            repeated.status.success(),
            "repeated recovery was not clean: {repeated:?}"
        );
        assert_eq!(json(&repeated)?["pending"], false);

        fs::remove_dir_all(workspace.path.join("target"))?;
        let cold = cargo_check(&workspace.path, cargo_home.path(), None, None)?;
        assert!(cold.status.success(), "fresh CAS did not populate: {cold:?}");
        fs::remove_dir_all(workspace.path.join("target"))?;
        let reused = cargo_check(&workspace.path, cargo_home.path(), None, None)?;
        assert!(reused.status.success(), "fresh CAS did not restore: {reused:?}");
        let status = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local", "-f", "json"],
        )?;
        #[cfg(not(windows))]
        assert!(
            json(&status)?["status"]["installation"]["usage"]["hits"]
                .as_u64()
                .unwrap_or_default()
                >= 1
        );
        #[cfg(windows)]
        {
            let status = json(&status)?;
            let usage = &status["status"]["installation"]["usage"];
            assert_eq!(usage["hits"], 0);
            assert_eq!(usage["misses"], 0);
            assert_eq!(usage["failures"], 0);
            assert!(usage["bypasses"].as_u64().is_some_and(|count| count >= 2));
        }
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(target_os = "macos")]
#[test]
fn distributed_worker_revalidates_a_cross_target_library_before_local_admission() {
    let result: Result<()> = (|| {
        let target = "x86_64-unknown-linux-gnu";
        let workspace = TestWorkspace::new_single_crate("distributed_cross_target", "0.1.0")?;
        fs::write(workspace.path.join("src/lib.rs"), "pub const VALUE: u64 = 41;\n")?;
        let cargo_home = tempfile::tempdir()?;
        let coverage = tempfile::tempdir()?;
        use std::os::unix::fs::PermissionsExt as _;
        fs::set_permissions(coverage.path(), fs::Permissions::from_mode(0o700))?;
        let coverage = cargo_rail::utils::canonicalize_existing(coverage.path())?;
        let build = || {
            Command::new("cargo")
                .current_dir(&workspace.path)
                .args(["build", "--offline", "--release", "--lib", "--target", target])
                .env("CARGO_HOME", cargo_home.path())
                .env("CARGO_INCREMENTAL", "0")
                .env("CARGO_RAIL_CACHE", "__cargo_rail_benchmark_coverage_v1")
                .env("CARGO_RAIL_BENCH_NATIVE_COVERAGE_DIRECTORY", &coverage)
                .env_remove("OUT_DIR")
                .env_remove("RUSTFLAGS")
                .env_remove("CARGO_ENCODED_RUSTFLAGS")
                .env_remove("RUSTC_WRAPPER")
                .env_remove("RUSTC_WORKSPACE_WRAPPER")
                .output()
        };
        let upstream = build()?;
        anyhow::ensure!(
            upstream.status.success(),
            "uncached cross-target compilation failed: {upstream:?}"
        );
        let outputs = workspace.path.join("target").join(target).join("release/deps");
        let baseline = compiler_only_outputs(&outputs)?;
        anyhow::ensure!(baseline.len() == 2, "uncached metadata/rlib contract is incomplete");
        let setup = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "setup", "--distributed-local"],
        )?;
        anyhow::ensure!(setup.status.success(), "worker fixture setup failed: {setup:?}");
        fs::remove_dir_all(workspace.path.join("target"))?;
        let seeded = build()?;
        anyhow::ensure!(seeded.status.success(), "target environment seed failed: {seeded:?}");
        anyhow::ensure!(
            compiler_only_outputs(&outputs)? == baseline,
            "local capture changed uncached output bytes"
        );
        let cache_root = selected_profile_cache_root(&workspace.path, cargo_home.path())?;
        fs::remove_dir_all(workspace.path.join("target"))?;
        for entry in fs::read_dir(cache_root.join("native-actions-v2"))? {
            fs::remove_file(entry?.path())?;
        }
        for entry in fs::read_dir(&coverage)? {
            fs::remove_file(entry?.path())?;
        }
        let distributed = build()?;
        let events = coverage_events(&coverage)?;
        anyhow::ensure!(
            distributed.status.success(),
            "cross-target worker compilation failed: {distributed:?}"
        );
        anyhow::ensure!(
            events
                .iter()
                .any(|event| event["reason"] == "verified_distributed_execution"),
            "cross-target operation never crossed worker admission: {:?}; {}",
            events
                .iter()
                .map(|event| (&event["crate_name"], &event["status"], &event["reason"]))
                .collect::<Vec<_>>(),
            String::from_utf8_lossy(&distributed.stderr)
        );
        anyhow::ensure!(
            compiler_only_outputs(&outputs)? == baseline,
            "worker changed uncached target bytes"
        );
        fs::write(workspace.path.join("src/lib.rs"), "pub const VALUE: u64 = 42;\n")?;
        let changed = build()?;
        anyhow::ensure!(
            changed.status.success(),
            "changed target compilation failed: {changed:?}"
        );
        anyhow::ensure!(
            compiler_only_outputs(&outputs)? != baseline,
            "same-size input change reused stale worker output"
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[test]
fn receipt_qualified_local_distribution_executes_an_ordinary_cargo_library() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("distributed_front_door", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let coverage = tempfile::tempdir()?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            fs::set_permissions(coverage.path(), fs::Permissions::from_mode(0o700))?;
        }
        let coverage = cargo_rail::utils::canonicalize_existing(coverage.path())?;

        let preview = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "setup", "--distributed-local", "--check", "-f", "json"],
        )?;
        assert_eq!(
            preview.status.code(),
            Some(1),
            "qualification preview failed: {preview:?}"
        );
        assert_eq!(json(&preview)?["distributed"], "local_process_qualification_v1");
        assert!(!cargo_home.path().join("cargo-rail/compiler-cache-v1").exists());

        let setup = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "setup", "--distributed-local", "-f", "json"],
        )?;
        assert!(setup.status.success(), "qualification setup failed: {setup:?}");
        assert_eq!(json(&setup)?["distributed"], "local_process_qualification_v1");
        let installation = cargo_home.path().join("cargo-rail/compiler-cache-v1");
        #[cfg(not(windows))]
        let distributed_worker = installation.join("cargo-rail-distributed-worker");
        #[cfg(windows)]
        let distributed_worker = installation.join("cargo-rail-distributed-worker.exe");
        assert!(
            distributed_worker.is_file(),
            "setup omitted the receipt-owned distributed worker"
        );

        let build = || {
            Command::new("cargo")
                .current_dir(&workspace.path)
                .args(["build", "--release", "--lib", "--message-format=json"])
                .env("CARGO_HOME", cargo_home.path())
                .env("CARGO_INCREMENTAL", "0")
                .env("CARGO_RAIL_CACHE", "__cargo_rail_benchmark_coverage_v1")
                .env("CARGO_RAIL_BENCH_NATIVE_COVERAGE_DIRECTORY", &coverage)
                .env_remove("OUT_DIR")
                .env_remove("RUSTC_WRAPPER")
                .env_remove("RUSTC_WORKSPACE_WRAPPER")
                .output()
        };
        let built = build()?;
        assert!(
            built.status.success(),
            "ordinary Cargo did not seed its first-seen compiler environment\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&built.stdout),
            String::from_utf8_lossy(&built.stderr)
        );
        let seeded_events = coverage_events(&coverage)?;
        #[cfg(not(windows))]
        assert!(
            seeded_events.iter().any(|event| {
                event["status"] == "miss"
                    && event["reason"].as_str().is_some_and(|reason| {
                        reason.starts_with("environment_selector_not_found;stored_verified_result")
                    })
            }),
            "ordinary Cargo did not establish local compiler-environment authority: {seeded_events:?}"
        );
        #[cfg(windows)]
        assert_native_driver_unavailable_bypass(&seeded_events, "distributed seed");
        fs::remove_dir_all(workspace.path.join("target"))?;
        let cache_roots = fs::read_dir(cargo_home.path().join("cargo-rail"))?
            .filter_map(|entry| entry.ok())
            .filter(|entry| entry.file_name().to_string_lossy().starts_with("local-cas-v2"))
            .filter(|entry| entry.path().is_dir())
            .collect::<Vec<_>>();
        let [cache_root] = cache_roots.as_slice() else {
            anyhow::bail!("local distribution test did not contain one local CAS root: {cache_roots:?}");
        };
        for entry in fs::read_dir(cache_root.path().join("native-actions-v2"))? {
            fs::remove_file(entry?.path())?;
        }
        for entry in fs::read_dir(&coverage)? {
            fs::remove_file(entry?.path())?;
        }

        let built = build()?;
        assert!(
            built.status.success(),
            "ordinary Cargo did not complete through local distribution\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&built.stdout),
            String::from_utf8_lossy(&built.stderr)
        );
        let events = coverage_events(&coverage)?;
        #[cfg(not(windows))]
        assert!(
            events
                .iter()
                .any(|event| event["status"] == "hit" && event["reason"] == "verified_distributed_execution"),
            "ordinary Cargo never crossed the distributed admission boundary\nstderr:\n{}\nevents: {events:?}",
            String::from_utf8_lossy(&built.stderr)
        );
        #[cfg(windows)]
        assert_native_driver_unavailable_bypass(&events, "distributed rebuild");

        fs::write(
            workspace.path.join("src/lib.rs"),
            "compile_error!(\"distributed failure proof\");\n",
        )?;
        fs::remove_dir_all(workspace.path.join("target"))?;
        let failed = Command::new("cargo")
            .current_dir(&workspace.path)
            .args(["build", "--release", "--lib", "--message-format=json"])
            .env("CARGO_HOME", cargo_home.path())
            .env("CARGO_INCREMENTAL", "0")
            .env_remove("OUT_DIR")
            .env_remove("RUSTC_WRAPPER")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .output()?;
        assert!(
            !failed.status.success(),
            "worker compiler failure unexpectedly succeeded"
        );
        let diagnostics = [failed.stdout.as_slice(), failed.stderr.as_slice()].concat();
        assert!(
            diagnostics
                .windows(b"distributed failure proof".len())
                .any(|window| window == b"distributed failure proof"),
            "first-seen compiler diagnostics were not preserved: {failed:?}"
        );
        assert!(
            !diagnostics
                .windows(b"/cargo-rail/exec/v5".len())
                .any(|window| window == b"/cargo-rail/exec/v5"),
            "distributed virtual paths escaped into Cargo diagnostics: {failed:?}"
        );

        let status = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local", "-f", "json"],
        )?;
        let status = json(&status)?;
        assert_eq!(status["status"]["installation"]["state"], "installed");
        assert_eq!(
            status["status"]["installation"]["distributed"],
            "local_process_qualification_v1"
        );

        fs::write(&distributed_worker, b"drifted")?;
        let drifted = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local", "-f", "json"],
        )?;
        assert_eq!(json(&drifted)?["status"]["installation"]["state"], "drifted");
        let repair = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(repair.status.success(), "qualification repair failed: {repair:?}");
        assert_ne!(fs::read(&distributed_worker)?, b"drifted");

        let remove = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "uninstall"])?;
        assert!(remove.status.success(), "qualification removal failed: {remove:?}");
        assert!(
            !distributed_worker.exists(),
            "removal retained the receipt-owned worker"
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[test]
fn failure_reason_status_reads_durable_counters_when_the_usage_ledger_is_full() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("transparent-failure-telemetry", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "cache setup failed: {setup:?}");

        let profile_state = selected_profile_state_root(&workspace.path, cargo_home.path())?;
        fs::write(profile_state.join("usage-v1.log"), vec![b'B'; 64 * 1024])?;
        let expected = BTreeMap::from([
            ("complete_action_capture_unavailable", 1_u64),
            ("complete_action_identity_unavailable", 2_u64),
            ("post_execution_witness_validation_unavailable", 3_u64),
        ]);
        fs::write(
            profile_state.join("failure-counters-v1.json"),
            b"{\n  \"schema_version\": 1,\n  \"complete_action_capture_unavailable\": 1,\n  \"complete_action_identity_unavailable\": 2,\n  \"post_execution_witness_validation_unavailable\": 3\n}\n",
        )?;
        let counter_file = fs::OpenOptions::new()
            .write(true)
            .open(profile_state.join("failure-counters-v1.json"))?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            counter_file.set_permissions(fs::Permissions::from_mode(0o600))?;
        }
        drop(counter_file);
        let status = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local", "-f", "json"],
        )?;
        assert!(status.status.success(), "{status:?}");
        let status = json(&status)?;
        let usage = &status["status"]["installation"]["usage"];
        assert_eq!(usage["recorded_events"], 64 * 1024);
        assert_eq!(usage["ledger_full"], true);
        assert_eq!(usage["failure_reason_counts_available"], true);
        for (reason, count) in &expected {
            assert_eq!(usage["failure_reasons"][reason], *count);
        }

        let human = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local"],
        )?;
        assert!(human.status.success(), "human cache status failed: {human:?}");
        let human = String::from_utf8_lossy(&human.stdout);
        for (reason, count) in &expected {
            if *count == 0 {
                continue;
            }
            assert!(
                human.contains(&format!("Cache failure {reason}: {count}")),
                "human status omitted {reason}:\n{human}"
            );
        }

        let counters = profile_state.join("failure-counters-v1.json");
        assert!(fs::metadata(&counters)?.len() <= 4 * 1024);

        fs::write(&counters, b"{}\n")?;
        let unavailable = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local", "-f", "json"],
        )?;
        let unavailable = json(&unavailable)?;
        assert_eq!(unavailable["status"]["installation"]["healthy"], true);
        assert_eq!(
            unavailable["status"]["installation"]["usage"]["failure_reason_counts_available"],
            false
        );

        let status = selected_profile_status(&workspace.path, cargo_home.path())?;
        let profile_id = status["status"]["installation"]["profile_id"]
            .as_str()
            .context("profile ID")?
            .to_string();
        let detach = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "detach"])?;
        assert!(detach.status.success(), "profile detach failed: {detach:?}");
        let remove = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "drop-profile", "--profile", &profile_id],
        )?;
        assert!(remove.status.success(), "profile removal failed: {remove:?}");
        assert!(!counters.exists());
        assert!(!profile_state.join("failure-counters-v1.lock").exists());
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn readiness_probe_proves_uncached_cold_and_warm_execution() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("transparent-readiness", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "setup failed: {setup:?}");

        let ready = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "ready", "-f", "json"],
        )?;
        assert!(ready.status.success(), "readiness probe failed: {ready:?}");
        let ready = json(&ready)?;
        assert_eq!(ready["ready"], true);
        assert_eq!(ready["selected_toolchain_readiness"], "ready");
        assert!(ready["cold"]["misses"].as_u64().is_some_and(|count| count > 0));
        assert!(ready["warm"]["hits"].as_u64().is_some_and(|count| count > 0));

        let status = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "all", "-f", "json"],
        )?;
        let status = json(&status)?;
        assert_eq!(status["status"]["selected_toolchain_readiness"], "ready");
        assert_eq!(status["status"]["installation"]["workspace_enrollment"], "enrolled");
        assert_eq!(status["status"]["remote_authority"], "not_configured");
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[test]
fn setup_refuses_global_conflicts_and_workspace_shadowing() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("transparent-conflict", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let config = cargo_home.path().join("config.toml");
        fs::write(&config, "[build]\nrustc-wrapper = 'sccache'\n")?;
        let conflict = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "setup", "--check"],
        )?;
        assert_eq!(conflict.status.code(), Some(2));
        assert!(String::from_utf8_lossy(&conflict.stderr).contains("already selects rustc wrapper"));

        fs::write(&config, "[net]\noffline = true\n")?;
        for name in ["RUSTC_WRAPPER", "CARGO_BUILD_RUSTC_WRAPPER"] {
            let shadowed = Command::new(crate::helpers::cargo_binary("cargo-rail"))
                .current_dir(&workspace.path)
                .args(["rail", "cache", "setup", "--check"])
                .env("CARGO_HOME", cargo_home.path())
                .env(name, "environment-wrapper")
                .env_remove(if name == "RUSTC_WRAPPER" {
                    "CARGO_BUILD_RUSTC_WRAPPER"
                } else {
                    "RUSTC_WRAPPER"
                })
                .output()?;
            assert_eq!(shadowed.status.code(), Some(2));
            assert!(String::from_utf8_lossy(&shadowed.stderr).contains("shadows Cargo's user rustc-wrapper setting"));
        }
        fs::create_dir_all(workspace.path.join(".cargo"))?;
        fs::write(
            workspace.path.join(".cargo/config.toml"),
            "[build]\nrustc-wrapper = 'workspace-wrapper'\n",
        )?;
        let shadowed = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "setup", "--check"],
        )?;
        assert_eq!(shadowed.status.code(), Some(2));
        assert!(String::from_utf8_lossy(&shadowed.stderr).contains("shadows the user rustc-wrapper setting"));
        assert_eq!(fs::read_to_string(config)?, "[net]\noffline = true\n");
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[test]
fn cache_status_reports_only_redacted_machine_selected_remote_authority() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("transparent-remote-status", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let output = Command::new(crate::helpers::cargo_binary("cargo-rail"))
            .current_dir(&workspace.path)
            .args(["rail", "cache", "status", "--scope", "local", "-f", "json"])
            .env("CARGO_HOME", cargo_home.path())
            .env(
                "CARGO_RAIL_CACHE_REMOTE",
                "s3://cargo-rail-cache-fixture/cache?region=us-east-1&owner=123456789012",
            )
            .env("CARGO_RAIL_CACHE_MODE", "read")
            .env_remove("RUSTC_WRAPPER")
            .env_remove("CARGO_BUILD_RUSTC_WRAPPER")
            .output()?;
        assert!(output.status.success(), "remote status failed: {output:?}");
        let value = json(&output)?;
        assert_eq!(value["status"]["schema_version"], 18);
        assert_eq!(value["status"]["remote_authority"], "read");
        assert_eq!(value["status"]["remote"]["activation"], "direct_transport_selected");
        assert_eq!(value["status"]["remote"]["provider"], "aws-s3");
        assert_eq!(value["status"]["remote"]["mode"], "read");
        assert!(value["status"]["remote"].get("normalized_url").is_none());
        assert!(
            value["status"]["remote"]["authority"]
                .as_str()
                .is_some_and(|identity| identity.starts_with("remote-authority-v1-sha256-"))
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[test]
fn setup_owned_remote_is_automatic_coordinated_and_removable() {
    let result: Result<()> = (|| {
        #[cfg(unix)]
        use std::os::unix::fs::PermissionsExt as _;

        let workspace = TestWorkspace::new_single_crate("transparent-remote-setup", "0.1.0")?;
        let remote = LoopbackS3::start()?;
        let remote_url = remote.remote_url();

        let seed_home = tempfile::tempdir()?;
        let seed_setup = rail(
            &workspace.path,
            seed_home.path(),
            &[
                "rail",
                "cache",
                "setup",
                "--remote",
                &remote_url,
                "--remote-mode",
                "read-write",
                "-f",
                "json",
            ],
        )?;
        assert!(seed_setup.status.success(), "remote setup failed: {seed_setup:?}");
        let setup_value = json(&seed_setup)?;
        assert_eq!(setup_value["remote"]["activation"], "direct_transport_selected");
        assert_eq!(setup_value["remote"]["mode"], "read-write");
        assert!(setup_value["remote"].get("normalized_url").is_none());

        let seed_coverage = tempfile::tempdir()?;
        #[cfg(unix)]
        fs::set_permissions(seed_coverage.path(), fs::Permissions::from_mode(0o700))?;
        let seed = cargo_check_installed_remote(&workspace.path, seed_home.path(), seed_coverage.path())?;
        assert!(seed.status.success(), "automatic remote seed failed: {seed:?}");
        let seed_events = coverage_events(seed_coverage.path())?;
        assert_setup_owned_remote_transport(&seed_events, "seed");
        let seed_requests = remote.requests();
        #[cfg(not(windows))]
        assert!(
            seed_requests
                .iter()
                .any(|(method, path)| method == "PUT" && path.contains("/entries/")),
            "automatic remote seed did not publish an entry: requests={seed_requests:?}, events={seed_events:?}"
        );
        #[cfg(windows)]
        {
            assert_native_driver_unavailable_bypass(&seed_events, "remote seed");
            assert!(
                !seed_requests
                    .iter()
                    .any(|(method, path)| method == "PUT" && path.contains("/entries/")),
                "unobserved Windows compilation published a remote entry: {seed_requests:?}"
            );
        }

        fs::remove_dir_all(workspace.path.join("target"))?;
        let import_home = tempfile::tempdir()?;
        let import_setup = rail(
            &workspace.path,
            import_home.path(),
            &[
                "rail",
                "cache",
                "setup",
                "--remote",
                &remote_url,
                "--remote-mode",
                "read",
            ],
        )?;
        assert!(
            import_setup.status.success(),
            "remote import setup failed: {import_setup:?}"
        );
        let import_coverage = tempfile::tempdir()?;
        #[cfg(unix)]
        fs::set_permissions(import_coverage.path(), fs::Permissions::from_mode(0o700))?;
        let imported = cargo_check_installed_remote(&workspace.path, import_home.path(), import_coverage.path())?;
        assert!(
            imported.status.success(),
            "automatic remote import failed: {imported:?}"
        );
        let imported_events = coverage_events(import_coverage.path())?;
        #[cfg(not(windows))]
        assert!(
            imported_events
                .iter()
                .any(|event| event["status"] == "hit" && event["reason"] == "verified_remote_result"),
            "ordinary Cargo did not restore the setup-owned remote result: {imported_events:?}"
        );
        #[cfg(windows)]
        assert_native_driver_unavailable_bypass(&imported_events, "remote import");
        assert_setup_owned_remote_transport(&imported_events, "import");

        let local_only = rail(
            &workspace.path,
            import_home.path(),
            &["rail", "cache", "setup", "--local-only", "-f", "json"],
        )?;
        assert!(local_only.status.success(), "local-only setup failed: {local_only:?}");
        assert!(json(&local_only)?["remote"].is_null());
        let status = rail(
            &workspace.path,
            import_home.path(),
            &["rail", "cache", "status", "--scope", "local", "-f", "json"],
        )?;
        assert!(status.status.success(), "local-only status failed: {status:?}");
        assert!(json(&status)?["status"]["remote"].is_null());
        let remove = rail(&workspace.path, import_home.path(), &["rail", "cache", "uninstall"])?;
        assert!(
            remove.status.success(),
            "coordinator installation removal failed: {remove:?}"
        );
        let installation = import_home.path().join("cargo-rail/compiler-cache-v1");
        let residue = fs::read_dir(&installation)
            .map(|entries| {
                entries
                    .filter_map(Result::ok)
                    .map(|entry| entry.file_name())
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();
        assert!(
            !installation.exists(),
            "coordinator state survived exact installation removal: {residue:?}"
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(unix)]
#[test]
fn one_global_wrapper_isolates_three_concurrent_workspace_profiles_and_an_unenrolled_workspace() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let workspaces = [
            TestWorkspace::new_single_crate("profile-alpha", "0.1.0")?,
            TestWorkspace::new_single_crate("profile-beta", "0.1.0")?,
            TestWorkspace::new_single_crate("profile-gamma", "0.1.0")?,
        ];
        let cargo_home = tempfile::tempdir()?;
        let remotes = [LoopbackS3::start()?, LoopbackS3::start()?, LoopbackS3::start()?];
        let remote_urls = remotes.each_ref().map(|remote| remote.remote_url());

        let first = rail(
            &workspaces[0].path,
            cargo_home.path(),
            &[
                "rail",
                "cache",
                "setup",
                "--remote",
                &remote_urls[0],
                "--remote-mode",
                "read-write",
                "--root-portability",
                "remap",
            ],
        )?;
        assert!(first.status.success(), "first profile setup failed: {first:?}");

        let mut setup_jobs = Vec::new();
        for index in 1..3 {
            let workspace = workspaces[index].path.clone();
            let cargo_home = cargo_home.path().to_path_buf();
            let remote = remote_urls[index].clone();
            setup_jobs.push(thread::spawn(move || {
                rail(
                    &workspace,
                    &cargo_home,
                    &[
                        "rail",
                        "cache",
                        "setup",
                        "--remote",
                        &remote,
                        "--remote-mode",
                        "read-write",
                        "--root-portability",
                        "remap",
                    ],
                )
            }));
        }
        for job in setup_jobs {
            let output = job
                .join()
                .map_err(|_| anyhow::anyhow!("concurrent profile setup panicked"))??;
            assert!(output.status.success(), "concurrent profile setup failed: {output:?}");
        }

        let mut profile_ids = BTreeSet::new();
        let mut trust_domains = BTreeSet::new();
        let mut cache_roots = BTreeSet::new();
        let mut remote_authorities = BTreeSet::new();
        let mut initial_statuses = Vec::new();
        for workspace in &workspaces {
            let status = selected_profile_status(&workspace.path, cargo_home.path())?;
            assert_eq!(
                status["status"]["installation"]["selection_source"],
                "installed_profile"
            );
            assert_eq!(status["status"]["remote"]["selection_source"], "installed_profile");
            assert_eq!(status["status"]["local"]["profile_scoped"], true);
            profile_ids.insert(
                status["status"]["installation"]["profile_id"]
                    .as_str()
                    .context("profile ID")?
                    .to_string(),
            );
            trust_domains.insert(
                status["status"]["installation"]["trust_domain"]
                    .as_str()
                    .context("profile trust domain")?
                    .to_string(),
            );
            cache_roots.insert(
                status["status"]["local"]["cache"]["root"]
                    .as_str()
                    .context("profile cache root")?
                    .to_string(),
            );
            remote_authorities.insert(
                status["status"]["remote"]["authority"]
                    .as_str()
                    .context("profile remote authority")?
                    .to_string(),
            );
            initial_statuses.push(profile_authority_projection(&status));
        }
        assert_eq!(profile_ids.len(), 3);
        assert_eq!(trust_domains.len(), 3);
        assert_eq!(cache_roots.len(), 3);
        assert_eq!(remote_authorities.len(), 3);

        let profiles = rail(
            &workspaces[0].path,
            cargo_home.path(),
            &["rail", "cache", "profiles", "-f", "json"],
        )?;
        assert!(profiles.status.success(), "profile inspection failed: {profiles:?}");
        assert_eq!(json(&profiles)?["profiles"].as_array().map(Vec::len), Some(3));

        let coverage = [tempfile::tempdir()?, tempfile::tempdir()?, tempfile::tempdir()?];
        for directory in &coverage {
            fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o700))?;
        }
        let request_counts = remotes.each_ref().map(|remote| remote.request_count());
        let mut cargo_jobs = Vec::new();
        for index in 0..3 {
            let workspace = workspaces[index].path.clone();
            let cargo_home = cargo_home.path().to_path_buf();
            let coverage = coverage[index].path().to_path_buf();
            cargo_jobs.push(thread::spawn(move || {
                cargo_check_installed_remote(&workspace, &cargo_home, &coverage)
            }));
        }
        for job in cargo_jobs {
            let output = job
                .join()
                .map_err(|_| anyhow::anyhow!("concurrent Cargo profile use panicked"))??;
            assert!(output.status.success(), "profile-selected Cargo failed: {output:?}");
        }
        for index in 0..3 {
            assert!(
                remotes[index].request_count() > request_counts[index],
                "workspace profile {} did not contact only its installed remote: {:?}",
                index,
                remotes[index].requests()
            );
            assert_setup_owned_remote_transport(&coverage_events(coverage[index].path())?, "isolated profile");
            assert_eq!(
                profile_authority_projection(&selected_profile_status(&workspaces[index].path, cargo_home.path(),)?),
                initial_statuses[index],
                "ordinary Cargo replaced profile {index}"
            );
        }

        let unenrolled = TestWorkspace::new_single_crate("profile-unenrolled", "0.1.0")?;
        let before_unenrolled = remotes.each_ref().map(|remote| remote.request_count());
        let cold = cargo_check(&unenrolled.path, cargo_home.path(), None, None)?;
        assert!(
            cold.status.success(),
            "unenrolled workspace did not compile normally: {cold:?}"
        );
        assert_eq!(
            remotes.each_ref().map(|remote| remote.request_count()),
            before_unenrolled,
            "unenrolled workspace contacted an installed profile remote"
        );
        let unenrolled_status = selected_profile_status(&unenrolled.path, cargo_home.path())?;
        assert!(unenrolled_status["status"]["installation"]["profile_id"].is_null());
        assert!(unenrolled_status["status"]["remote"].is_null());

        fs::remove_dir_all(workspaces[0].path.join("target"))?;
        let clean = rail(
            &workspaces[0].path,
            cargo_home.path(),
            &["rail", "cache", "clean", "--scope", "local"],
        )?;
        assert!(clean.status.success(), "transient fixture cleanup failed: {clean:?}");
        let repair = rail(&workspaces[0].path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(repair.status.success(), "transient fixture repair failed: {repair:?}");
        let transient = LoopbackS3::start()?;
        let transient_coverage = tempfile::tempdir()?;
        fs::set_permissions(transient_coverage.path(), fs::Permissions::from_mode(0o700))?;
        let installed_before = remotes[0].request_count();
        let transient_output = cargo_check_remote(
            &workspaces[0].path,
            cargo_home.path(),
            &transient.remote_url(),
            "read-write",
            None,
            Some(transient_coverage.path()),
        )?;
        assert!(
            transient_output.status.success(),
            "transient profile override failed: {transient_output:?}"
        );
        assert!(transient.request_count() > 0);
        assert_eq!(remotes[0].request_count(), installed_before);
        assert_eq!(
            profile_authority_projection(&selected_profile_status(&workspaces[0].path, cargo_home.path(),)?),
            initial_statuses[0],
            "transient policy rewrote the installed profile"
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[test]
fn profile_detach_rebind_cleanup_and_global_uninstall_have_disjoint_scopes() {
    let result: Result<()> = (|| {
        let first = TestWorkspace::new_single_crate("profile-lifecycle-first", "0.1.0")?;
        let second = TestWorkspace::new_single_crate("profile-lifecycle-second", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        for workspace in [&first, &second] {
            let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
            assert!(setup.status.success(), "profile setup failed: {setup:?}");
            let seed = cargo_check(&workspace.path, cargo_home.path(), None, None)?;
            assert!(seed.status.success(), "profile seed failed: {seed:?}");
        }
        let first_status = selected_profile_status(&first.path, cargo_home.path())?;
        let first_id = first_status["status"]["installation"]["profile_id"]
            .as_str()
            .context("first profile ID")?
            .to_string();
        let first_cache = selected_profile_cache_root(&first.path, cargo_home.path())?;
        let second_cache = selected_profile_cache_root(&second.path, cargo_home.path())?;
        let additional_root = TestWorkspace::new_single_crate("profile-lifecycle-additional-root", "0.1.0")?;
        let bind_additional = rail(
            &additional_root.path,
            cargo_home.path(),
            &["rail", "cache", "setup", "--profile", &first_id],
        )?;
        assert!(
            bind_additional.status.success(),
            "explicit additional-root binding failed: {bind_additional:?}"
        );
        let profiles = rail(
            &first.path,
            cargo_home.path(),
            &["rail", "cache", "profiles", "-f", "json"],
        )?;
        let profiles = json(&profiles)?;
        let first_profile = profiles["profiles"]
            .as_array()
            .context("profile list")?
            .iter()
            .find(|profile| profile["profile_id"] == first_id)
            .context("first profile")?;
        assert_eq!(first_profile["roots"].as_array().map(Vec::len), Some(2));

        let clean = rail(
            &first.path,
            cargo_home.path(),
            &["rail", "cache", "clean", "--scope", "local"],
        )?;
        assert!(clean.status.success(), "first profile cleanup failed: {clean:?}");
        assert!(!first_cache.exists());
        assert!(
            second_cache.exists(),
            "first profile cleanup removed the second profile CAS"
        );
        let repair = rail(&first.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(repair.status.success(), "first profile repair failed: {repair:?}");

        let detached_check = rail(
            &first.path,
            cargo_home.path(),
            &["rail", "cache", "detach", "--check", "-f", "json"],
        )?;
        assert_eq!(detached_check.status.code(), Some(1));
        assert!(first_cache.exists(), "detach preview removed profile data");
        let detached = rail(&first.path, cargo_home.path(), &["rail", "cache", "detach"])?;
        assert!(detached.status.success(), "profile detach failed: {detached:?}");
        assert!(first_cache.exists(), "detach removed profile data");

        let rebound = rail(
            &first.path,
            cargo_home.path(),
            &["rail", "cache", "setup", "--profile", &first_id],
        )?;
        assert!(rebound.status.success(), "explicit profile rebind failed: {rebound:?}");
        assert_eq!(
            selected_profile_status(&first.path, cargo_home.path())?["status"]["installation"]["profile_id"],
            first_id
        );

        let detached = rail(&first.path, cargo_home.path(), &["rail", "cache", "detach"])?;
        assert!(detached.status.success(), "second profile detach failed: {detached:?}");
        let detached_additional = rail(&additional_root.path, cargo_home.path(), &["rail", "cache", "detach"])?;
        assert!(
            detached_additional.status.success(),
            "additional root detach failed: {detached_additional:?}"
        );
        let drop_check = rail(
            &first.path,
            cargo_home.path(),
            &["rail", "cache", "drop-profile", "--profile", &first_id, "--check"],
        )?;
        assert_eq!(drop_check.status.code(), Some(1));
        assert!(first_cache.exists(), "profile removal preview removed the CAS");
        let dropped = rail(
            &first.path,
            cargo_home.path(),
            &["rail", "cache", "drop-profile", "--profile", &first_id],
        )?;
        assert!(dropped.status.success(), "profile removal failed: {dropped:?}");
        assert!(!first_cache.exists());
        assert!(second_cache.exists());

        let uninstall = rail(&second.path, cargo_home.path(), &["rail", "cache", "uninstall"])?;
        assert!(uninstall.status.success(), "global uninstall failed: {uninstall:?}");
        assert!(second_cache.exists(), "global uninstall removed a profile CAS");
        assert!(
            cargo_home.path().join("cargo-rail/cache-profiles-v1").exists(),
            "global uninstall removed the profile registry"
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[test]
fn pre_profile_receipt_is_quarantined_and_migrated_without_losing_cache_authority() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("pre-profile-refusal", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        anyhow::ensure!(setup.status.success(), "fixture setup failed: {setup:?}");
        let cache_root = selected_profile_cache_root(&workspace.path, cargo_home.path())?;
        let cache_before = directory_snapshot(&cache_root)?;
        let store = cargo_home.path().join("cargo-rail/cache-profiles-v1");
        let profile_path = fs::read_dir(store.join("profiles"))?
            .next()
            .transpose()?
            .context("fixture profile")?
            .path();
        let profile: serde_json::Value = serde_json::from_slice(&fs::read(profile_path)?)?;
        let receipt_path = cargo_home.path().join("cargo-rail/compiler-cache-v1/setup.json");
        let mut receipt: serde_json::Value = serde_json::from_slice(&fs::read(&receipt_path)?)?;
        receipt["version"] = serde_json::json!(3);
        receipt["cache"] = profile["cache"].clone();
        receipt["root_portability"] = profile["root_portability"].clone();
        let receipt_bytes = serde_json::to_vec_pretty(&receipt)?;
        fs::write(&receipt_path, &receipt_bytes)?;
        let config_path = cargo_home.path().join("config.toml");
        let config_before = fs::read(&config_path)?;
        fs::remove_dir_all(&store)?;
        let stale = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local", "-f", "json"],
        )?;
        anyhow::ensure!(stale.status.success(), "stale installation status failed: {stale:?}");
        let stale = json(&stale)?;
        assert_eq!(stale["status"]["installation"]["state"], "stale");
        assert_eq!(stale["status"]["installation"]["receipt_version"], 3);
        assert_eq!(
            stale["status"]["installation"]["recovery_action"],
            "cargo rail cache setup"
        );

        let check = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "setup", "--check", "-f", "json"],
        )?;
        assert_eq!(check.status.code(), Some(1), "migration preview: {check:?}");
        let check = json(&check)?;
        assert_eq!(check["private_state_action"], "quarantine_and_reinstall");
        let quarantine = PathBuf::from(
            check["quarantine_receipt_path"]
                .as_str()
                .context("quarantine receipt path")?,
        );
        anyhow::ensure!(
            fs::read(&receipt_path)? == receipt_bytes
                && fs::read(&config_path)? == config_before
                && !quarantine.exists(),
            "migration preview changed installation authority"
        );

        let migrated = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "setup", "-f", "json"],
        )?;
        anyhow::ensure!(migrated.status.success(), "migration failed: {migrated:?}");
        assert_eq!(json(&migrated)?["private_state_action"], "quarantine_and_reinstall");
        anyhow::ensure!(
            fs::read(&quarantine)? == receipt_bytes,
            "stale receipt evidence changed"
        );
        anyhow::ensure!(fs::read(&config_path)? == config_before, "owned Cargo config changed");
        anyhow::ensure!(directory_snapshot(&cache_root)? == cache_before, "cache bytes changed");

        let receipt: serde_json::Value = serde_json::from_slice(&fs::read(&receipt_path)?)?;
        assert_eq!(receipt["version"], 5);
        let repeated = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "setup", "--check", "-f", "json"],
        )?;
        anyhow::ensure!(repeated.status.success(), "migrated setup is not stable: {repeated:?}");
        let status = selected_profile_status(&workspace.path, cargo_home.path())?;
        assert_eq!(status["status"]["installation"]["state"], "installed");
        assert_eq!(status["status"]["installation"]["quarantined_receipts"], 1);
        assert!(
            status["status"]["installation"]["reclaimable_bytes"]
                .as_u64()
                .unwrap_or_default()
                > 0
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(unix)]
#[test]
fn hostile_or_corrupt_profile_state_fails_closed_without_touching_an_external_target() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::{PermissionsExt as _, symlink};

        let workspace = TestWorkspace::new_single_crate("profile-hostile-state", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let remote = LoopbackS3::start()?;
        let remote_url = remote.remote_url();
        let setup = rail(
            &workspace.path,
            cargo_home.path(),
            &[
                "rail",
                "cache",
                "setup",
                "--remote",
                &remote_url,
                "--remote-mode",
                "read-write",
            ],
        )?;
        assert!(setup.status.success(), "hostile-state fixture setup failed: {setup:?}");
        let store = cargo_home.path().join("cargo-rail/cache-profiles-v1");
        let binding = fs::read_dir(store.join("bindings"))?
            .next()
            .transpose()?
            .context("profile binding")?
            .path();
        let profile = fs::read_dir(store.join("profiles"))?
            .next()
            .transpose()?
            .context("profile record")?
            .path();
        let binding_bytes = fs::read(&binding)?;
        let profile_bytes = fs::read(&profile)?;
        let external = tempfile::tempdir()?;
        let external_target = external.path().join("outside.json");
        fs::write(&external_target, &binding_bytes)?;
        fs::set_permissions(&external_target, fs::Permissions::from_mode(0o600))?;
        let expected_external = fs::read(&external_target)?;

        let assert_cold_without_remote = |label: &str| -> Result<()> {
            let target = workspace.path.join("target");
            if target.exists() {
                fs::remove_dir_all(&target)?;
            }
            let before = remote.request_count();
            let output = cargo_check(&workspace.path, cargo_home.path(), None, None)?;
            anyhow::ensure!(
                output.status.success(),
                "{label} blocked normal compilation: {output:?}"
            );
            anyhow::ensure!(
                remote.request_count() == before,
                "{label} selected the installed remote through invalid profile state"
            );
            anyhow::ensure!(
                fs::read(&external_target)? == expected_external,
                "{label} modified the external target"
            );
            Ok(())
        };

        fs::remove_file(&binding)?;
        symlink(&external_target, &binding)?;
        let status = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local"],
        )?;
        assert!(!status.status.success());
        assert_cold_without_remote("symlinked binding")?;

        fs::remove_file(&binding)?;
        fs::hard_link(&external_target, &binding)?;
        let status = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local"],
        )?;
        assert!(!status.status.success());
        assert_cold_without_remote("hard-linked binding")?;

        fs::remove_file(&binding)?;
        fs::write(&binding, &binding_bytes)?;
        fs::set_permissions(&binding, fs::Permissions::from_mode(0o600))?;
        fs::write(&profile, b"{malformed}\n")?;
        let status = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local"],
        )?;
        assert!(!status.status.success());
        assert_cold_without_remote("corrupt profile")?;

        fs::write(&profile, &profile_bytes)?;
        fs::set_permissions(&profile, fs::Permissions::from_mode(0o600))?;
        fs::remove_file(&profile)?;
        let status = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local"],
        )?;
        assert!(!status.status.success());
        assert_cold_without_remote("missing profile")?;

        fs::write(&profile, &profile_bytes)?;
        fs::set_permissions(&profile, fs::Permissions::from_mode(0o600))?;
        let alias_parent = tempfile::tempdir()?;
        let unicode_alias = alias_parent.path().join("cafe\u{301}-workspace");
        symlink(&workspace.path, &unicode_alias)?;
        let alias_setup = rail(&unicode_alias, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(
            alias_setup.status.success(),
            "canonical alias setup failed: {alias_setup:?}"
        );
        let profiles = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "profiles", "-f", "json"],
        )?;
        assert_eq!(json(&profiles)?["profiles"].as_array().map(Vec::len), Some(1));

        let bindings = store.join("bindings");
        let quarantined_bindings = store.join("bindings-real");
        fs::rename(&bindings, &quarantined_bindings)?;
        symlink(external.path(), &bindings)?;
        let status = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local"],
        )?;
        assert!(!status.status.success());
        assert_cold_without_remote("replaced binding directory")?;
        assert_eq!(fs::read(&external_target)?, expected_external);
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(target_os = "macos")]
#[test]
fn cross_target_l2_reuse_preserves_physical_and_remapped_root_authority() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;
        let target = "x86_64-unknown-linux-gnu";
        for portability in ["physical", "remap"] {
            let first = TestWorkspace::new_single_crate("target-remote", "0.1.0")?;
            let second = TestWorkspace::new_single_crate("target-remote", "0.1.0")?;
            for workspace in [&first.path, &second.path] {
                fs::write(workspace.join("src/lib.rs"), "pub const VALUE: u64 = 41;\n")?;
            }
            let consumer = if portability == "physical" {
                &first.path
            } else {
                &second.path
            };
            let remote = LoopbackS3::start()?;
            let remote_url = remote.remote_url();
            let seed_home = tempfile::tempdir()?;
            let import_home = tempfile::tempdir()?;
            let seed_coverage = tempfile::tempdir()?;
            let import_coverage = tempfile::tempdir()?;
            for directory in [seed_coverage.path(), import_coverage.path()] {
                fs::set_permissions(directory, fs::Permissions::from_mode(0o700))?;
            }
            for (workspace, home, mode) in [
                (&first.path, seed_home.path(), "read-write"),
                (consumer, import_home.path(), "read"),
            ] {
                let setup = rail(
                    workspace,
                    home,
                    &[
                        "rail",
                        "cache",
                        "setup",
                        "--remote",
                        &remote_url,
                        "--remote-mode",
                        mode,
                        "--root-portability",
                        portability,
                    ],
                )?;
                anyhow::ensure!(setup.status.success(), "target L2 setup failed: {setup:?}");
            }
            let seeded = cargo_check_installed_remote_with_options(
                &first.path,
                seed_home.path(),
                seed_coverage.path(),
                None,
                None,
                Some(target),
            )?;
            anyhow::ensure!(seeded.status.success(), "target L2 seed failed: {seeded:?}");
            let baseline = compiler_only_outputs(&first.path.join("target").join(target).join("debug/deps"))?;
            anyhow::ensure!(baseline.len() == 1, "target metadata seed contract incomplete");
            if consumer == &first.path {
                fs::remove_dir_all(first.path.join("target"))?;
            }
            let writes = remote.requests().iter().filter(|(method, _)| method == "PUT").count();
            let imported = cargo_check_installed_remote_with_options(
                consumer,
                import_home.path(),
                import_coverage.path(),
                None,
                None,
                Some(target),
            )?;
            let events = coverage_events(import_coverage.path())?;
            anyhow::ensure!(imported.status.success(), "target L2 import failed: {imported:?}");
            anyhow::ensure!(
                events.iter().any(|event| event["status"] == "hit"
                    && event["reason"]
                        .as_str()
                        .is_some_and(|reason| reason.starts_with("verified_remote_result"))),
                "{portability} target result did not cross L2 verification: {:?}; {}",
                events
                    .iter()
                    .map(|event| (&event["crate_name"], &event["status"], &event["reason"]))
                    .collect::<Vec<_>>(),
                String::from_utf8_lossy(&imported.stderr)
            );
            anyhow::ensure!(
                compiler_only_outputs(&consumer.join("target").join(target).join("debug/deps"))? == baseline,
                "{portability} L2 restore changed target metadata bytes"
            );
            anyhow::ensure!(
                remote.requests().iter().filter(|(method, _)| method == "PUT").count() == writes,
                "read-only target import wrote remote objects"
            );
            fs::write(consumer.join("src/lib.rs"), "pub const VALUE: u64 = 42;\n")?;
            let mutated = cargo_check_installed_remote_with_options(
                consumer,
                import_home.path(),
                import_coverage.path(),
                None,
                None,
                Some(target),
            )?;
            anyhow::ensure!(mutated.status.success(), "target L2 input mutation failed: {mutated:?}");
            anyhow::ensure!(
                compiler_only_outputs(&consumer.join("target").join(target).join("debug/deps"))? != baseline,
                "same-size input mutation restored stale target metadata"
            );
        }
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[test]
fn local_only_reports_its_root_portability_conflict_semantically() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("local-only-conflict", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let output = rail(
            &workspace.path,
            cargo_home.path(),
            &[
                "rail",
                "cache",
                "setup",
                "--local-only",
                "--root-portability",
                "physical",
            ],
        )?;
        assert_eq!(output.status.code(), Some(2));
        let diagnostic = String::from_utf8_lossy(&output.stderr);
        assert!(
            diagnostic.contains("--local-only cannot select --root-portability"),
            "{diagnostic}"
        );
        assert!(diagnostic.contains("fresh local profile"), "{diagnostic}");
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[test]
fn remap_authority_restores_a_verified_l2_result_across_checkout_roots() {
    let result: Result<()> = (|| {
        #[cfg(unix)]
        use std::os::unix::fs::PermissionsExt as _;

        let first = TestWorkspace::new_single_crate("portable-root-fixture", "0.1.0")?;
        let second = TestWorkspace::new_single_crate("portable-root-fixture", "0.1.0")?;
        for workspace in [&first.path, &second.path] {
            fs::create_dir_all(workspace.join(".config"))?;
            fs::write(workspace.join(".config/target-matrix.json"), "{\"target\":1}\n")?;
            fs::write(
                workspace.join("src/lib.rs"),
                "const MATRIX: &str = include_str!(\"../.config/target-matrix.json\");\nfn unused() { let _ = MATRIX; }\n",
            )?;
        }
        let remote = LoopbackS3::start()?;
        let remote_url = remote.remote_url();
        let first_home = tempfile::tempdir()?;
        let second_home = tempfile::tempdir()?;

        let unbacked = rail(
            &first.path,
            first_home.path(),
            &["rail", "cache", "setup", "--root-portability", "remap"],
        )?;
        assert_eq!(unbacked.status.code(), Some(2));
        assert!(
            String::from_utf8_lossy(&unbacked.stderr)
                .contains("root portability remapping requires an installed remote cache authority")
        );

        for (workspace, cargo_home, mode) in [
            (&first.path, first_home.path(), "read-write"),
            (&second.path, second_home.path(), "read"),
        ] {
            let setup = rail(
                workspace,
                cargo_home,
                &[
                    "rail",
                    "cache",
                    "setup",
                    "--remote",
                    &remote_url,
                    "--remote-mode",
                    mode,
                    "--root-portability",
                    "remap",
                    "-f",
                    "json",
                ],
            )?;
            assert!(setup.status.success(), "portable setup failed: {setup:?}");
            assert_eq!(json(&setup)?["root_portability"], "remap");
            let status = rail(
                workspace,
                cargo_home,
                &["rail", "cache", "status", "--scope", "local", "-f", "json"],
            )?;
            assert_eq!(json(&status)?["status"]["installation"]["root_portability"], "remap");
        }

        let first_coverage = tempfile::tempdir()?;
        let second_coverage = tempfile::tempdir()?;
        let external_targets = tempfile::tempdir()?;
        let producer_target = external_targets.path().join("producer-target");
        let consumer_target = external_targets.path().join("consumer-target");
        let mutation_target = external_targets.path().join("mutation-target");
        assert!(!producer_target.exists() && !consumer_target.exists() && !mutation_target.exists());
        #[cfg(unix)]
        {
            fs::set_permissions(first_coverage.path(), fs::Permissions::from_mode(0o700))?;
            fs::set_permissions(second_coverage.path(), fs::Permissions::from_mode(0o700))?;
        }
        let seeded = cargo_check_installed_remote_in_target(
            &first.path,
            first_home.path(),
            first_coverage.path(),
            &producer_target,
        )?;
        assert!(seeded.status.success(), "portable seed failed: {seeded:?}");
        let seed_events = coverage_events(first_coverage.path())?;
        #[cfg(windows)]
        {
            assert_native_driver_unavailable_bypass(&seed_events, "remapped seed");
            assert!(
                !remote
                    .requests()
                    .iter()
                    .any(|(method, path)| method == "PUT" && path.contains("/entries/")),
                "unobserved remapped compilation published a remote entry"
            );
        }
        let writes_before_consumer = remote.requests().iter().filter(|(method, _)| method == "PUT").count();
        let restored = cargo_check_installed_remote_in_target(
            &second.path,
            second_home.path(),
            second_coverage.path(),
            &consumer_target,
        )?;
        assert!(restored.status.success(), "portable restore failed: {restored:?}");
        let events = coverage_events(second_coverage.path())?;
        #[cfg(not(windows))]
        assert!(
            events.iter().any(|event| {
                event["status"] == "hit"
                    && event["reason"].as_str().is_some_and(|reason| {
                        reason.starts_with("verified_remote_result")
                            && reason.contains("root_portability_remap_eligible")
                    })
            }),
            "second checkout did not report a verified L2 hit: producer_stderr={}, consumer_stderr={}, seed={seed_events:?}, restored={events:?}, requests={:?}",
            String::from_utf8_lossy(&seeded.stderr),
            String::from_utf8_lossy(&restored.stderr),
            remote.requests()
        );
        #[cfg(windows)]
        assert_native_driver_unavailable_bypass(&events, "remapped consumer");
        assert_eq!(
            remote.requests().iter().filter(|(method, _)| method == "PUT").count(),
            writes_before_consumer,
            "read-only second-checkout restore wrote a remote object"
        );
        let seeded_diagnostics = String::from_utf8_lossy(&seeded.stderr);
        let restored_diagnostics = String::from_utf8_lossy(&restored.stderr);
        assert!(seeded_diagnostics.contains("function `unused` is never used"));
        assert!(restored_diagnostics.contains("function `unused` is never used"));
        assert!(!restored_diagnostics.contains(first.path.to_string_lossy().as_ref()));

        let first_root = first.path.to_string_lossy().into_owned().into_bytes();
        let mut pending = vec![consumer_target];
        while let Some(directory) = pending.pop() {
            for entry in fs::read_dir(directory)? {
                let entry = entry?;
                let file_type = entry.file_type()?;
                if file_type.is_dir() {
                    pending.push(entry.path());
                } else if file_type.is_file() {
                    let bytes = fs::read(entry.path())?;
                    assert!(
                        !bytes.windows(first_root.len()).any(|window| window == first_root),
                        "restored output leaked the producer checkout root: {}",
                        entry.path().display()
                    );
                }
            }
        }

        fs::write(second.path.join(".config/target-matrix.json"), "{\"target\":2}\n")?;
        let mutated_coverage = tempfile::tempdir()?;
        #[cfg(unix)]
        fs::set_permissions(mutated_coverage.path(), fs::Permissions::from_mode(0o700))?;
        let mutated = cargo_check_installed_remote_in_target(
            &second.path,
            second_home.path(),
            mutated_coverage.path(),
            &mutation_target,
        )?;
        assert!(
            mutated.status.success(),
            "same-size dynamic-input rebuild failed: {mutated:?}"
        );
        let mutated_events = coverage_events(mutated_coverage.path())?;
        #[cfg(not(windows))]
        assert!(
            mutated_events.iter().any(|event| event["status"] == "miss")
                && mutated_events.iter().all(|event| event["status"] != "hit"),
            "same-size selected-input mutation did not produce a clean miss: stderr={}, events={mutated_events:?}",
            String::from_utf8_lossy(&mutated.stderr)
        );
        #[cfg(windows)]
        assert_native_driver_unavailable_bypass(&mutated_events, "remapped mutation");
        assert_eq!(
            remote.requests().iter().filter(|(method, _)| method == "PUT").count(),
            writes_before_consumer,
            "read-only same-size miss wrote a remote object"
        );
        assert_eq!(
            fs::read_dir(external_targets.path())?
                .collect::<Result<Vec<_>, _>>()?
                .into_iter()
                .map(|entry| entry.file_name())
                .collect::<BTreeSet<_>>(),
            BTreeSet::from([
                std::ffi::OsString::from("consumer-target"),
                std::ffi::OsString::from("mutation-target"),
                std::ffi::OsString::from("producer-target"),
            ]),
            "remote qualification wrote outside its exact external target roots"
        );

        let ambiguous_coverage = tempfile::tempdir()?;
        #[cfg(unix)]
        fs::set_permissions(ambiguous_coverage.path(), fs::Permissions::from_mode(0o700))?;
        let ambiguous = cargo_check_installed_remote_with_rustflags(
            &first.path,
            first_home.path(),
            ambiguous_coverage.path(),
            Some("--remap-path-prefix=/tmp=/ambiguous"),
        )?;
        assert!(
            ambiguous.status.success(),
            "ambiguous remap fallback failed: {ambiguous:?}"
        );
        let ambiguous_events = coverage_events(ambiguous_coverage.path())?;
        assert!(
            ambiguous_events.iter().any(|event| {
                event["status"] == "bypassed" && event["reason"] == "remapped_path_observation_unavailable"
            }),
            "an existing path remap did not fail closed with its named reason: {ambiguous_events:?}"
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

fn assert_setup_owned_remote_transport(events: &[serde_json::Value], phase: &str) {
    let coordinated = events
        .iter()
        .filter_map(|event| event["remote_coordinator_requests"].as_u64())
        .sum::<u64>()
        > 0;
    #[cfg(not(windows))]
    assert!(
        coordinated,
        "setup-owned remote {phase} bypassed coordination: {events:?}"
    );
    #[cfg(windows)]
    {
        let explicit_direct_fallback = events.iter().any(|event| {
            event["remote_request_attempts"]
                .as_u64()
                .is_some_and(|attempts| attempts > 0)
                && event["remote_error"].as_str().is_some_and(|error| !error.is_empty())
        });
        assert!(
            coordinated || explicit_direct_fallback,
            "setup-owned remote {phase} used neither coordination nor an evidenced direct fallback: {events:?}"
        );
    }
}

#[test]
fn cache_normalize_is_network_free_canonical_and_rejects_credentials() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("remote-normalize", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let normalized = rail(
            &workspace.path,
            cargo_home.path(),
            &[
                "rail",
                "cache",
                "normalize",
                "s3://Rail-Cache//team/%61?region=us-east-1&owner=123456789012",
                "--mode",
                "read",
                "-f",
                "json",
            ],
        )?;
        assert!(normalized.status.success(), "normalization failed: {normalized:?}");
        let normalized = json(&normalized)?;
        assert_eq!(
            normalized["normalized_url"],
            "s3://rail-cache/team/a?owner=123456789012&region=us-east-1"
        );
        assert_eq!(normalized["remote"]["mode"], "read");

        let rejected = rail(
            &workspace.path,
            cargo_home.path(),
            &[
                "rail",
                "cache",
                "normalize",
                "s3://user:top-secret@rail-cache/team?owner=123456789012&region=us-east-1",
            ],
        )?;
        assert_eq!(rejected.status.code(), Some(2));
        assert!(!String::from_utf8_lossy(&rejected.stderr).contains("top-secret"));
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[test]
fn cache_probe_authenticates_and_reports_protocol_marker_state() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("remote-probe", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let remote = LoopbackS3::start()?;
        let remote_url = remote.remote_url();

        let initialized = remote_probe(&workspace.path, cargo_home.path(), &remote_url, "read-write")?;
        assert!(
            initialized.status.success(),
            "marker initialization failed: {initialized:?}"
        );
        let initialized_json = json(&initialized)?;
        assert_eq!(initialized_json["result"], "ready");
        assert_eq!(initialized_json["ready"], true);
        assert_eq!(initialized_json["protocol_marker"], "initialized");
        assert_eq!(initialized_json["remote"]["provider"], "s3-compatible");
        assert_eq!(initialized_json["remote"]["mode"], "read-write");
        assert!(
            remote
                .requests()
                .iter()
                .any(|(method, path)| method == "PUT" && path.ends_with("/protocol")),
            "probe did not initialize the protocol marker"
        );

        let puts_before_existing = remote.requests().iter().filter(|(method, _)| method == "PUT").count();
        let existing = remote_probe(&workspace.path, cargo_home.path(), &remote_url, "read")?;
        assert!(existing.status.success(), "existing marker probe failed: {existing:?}");
        assert_eq!(json(&existing)?["protocol_marker"], "existing");
        assert_eq!(
            remote.requests().iter().filter(|(method, _)| method == "PUT").count(),
            puts_before_existing,
            "read-only probe wrote to the object store"
        );

        let missing_url = remote_url.replace("/team?", "/missing?");
        let missing = remote_probe(&workspace.path, cargo_home.path(), &missing_url, "read")?;
        assert_eq!(missing.status.code(), Some(2));
        let missing_json = json(&missing)?;
        assert_eq!(missing_json["result"], "probe_failed");
        assert_eq!(missing_json["ready"], false);
        assert_eq!(missing_json["failure"]["kind"], "configuration_failure");

        #[cfg(unix)]
        {
            remote.set_available(false);
            let unavailable = remote_probe(&workspace.path, cargo_home.path(), &remote_url, "read")?;
            remote.set_available(true);
            assert_eq!(unavailable.status.code(), Some(2));
            let unavailable_json = json(&unavailable)?;
            assert_eq!(unavailable_json["failure"]["kind"], "transport_failure");
            assert_eq!(unavailable_json["failure"]["cause"], "http");
            assert_eq!(
                unavailable_json["failure"]["retry"],
                "retry the probe after the remote service recovers"
            );
        }

        assert!(remote.corrupt_protocol_marker());
        let incompatible = remote_probe(&workspace.path, cargo_home.path(), &remote_url, "read")?;
        assert_eq!(incompatible.status.code(), Some(2));
        assert_eq!(json(&incompatible)?["failure"]["kind"], "integrity_failure");
        let output = String::from_utf8_lossy(&incompatible.stdout);
        assert!(!output.contains(&remote_url));
        assert!(!output.contains("fixture-access-key"));
        assert!(!output.contains("fixture-secret-key"));
        assert!(!output.contains("fixture-session-token"));
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(unix)]
#[test]
fn direct_s3_remote_is_l2_only_and_falls_back_cold_on_corruption_or_outage() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let started = std::time::Instant::now();
        let phase = |name: &str| {
            eprintln!(
                "S3 cache qualification [{:.3}s]: {name}",
                started.elapsed().as_secs_f64()
            );
        };
        let workspace = TestWorkspace::new_single_crate("transparent-remote", "0.1.0")?;
        let remote = LoopbackS3::start()?;
        let remote_url = remote.remote_url();
        let rustc = workspace.path.join("rustc-remote-proof");
        fs::write(
            &rustc,
            "#!/bin/sh\nprintf 'url=%s access=%s secret=%s token=%s config=%s args=%s\\n' \"${CARGO_RAIL_CACHE_REMOTE-unset}\" \"${AWS_ACCESS_KEY_ID-unset}\" \"${AWS_SECRET_ACCESS_KEY-unset}\" \"${AWS_SESSION_TOKEN-unset}\" \"${AWS_CONFIG_FILE-unset}\" \"$*\" >> \"$REMOTE_ENV_LOG\"\nexec \"$REAL_RUSTC\" \"$@\"\n",
        )?;
        fs::set_permissions(&rustc, fs::Permissions::from_mode(0o700))?;

        let credential_home = tempfile::tempdir()?;
        let source_path = workspace.path.join("src/lib.rs");
        let original_source = fs::read_to_string(&source_path)?;
        let mut credential_source = original_source.clone();
        for name in [
            "CARGO_RAIL_CACHE_REMOTE",
            "AWS_ACCESS_KEY_ID",
            "AWS_SECRET_ACCESS_KEY",
            "AWS_SESSION_TOKEN",
            "AWS_CONFIG_FILE",
            "AWS_SHARED_CREDENTIALS_FILE",
        ] {
            credential_source.push_str(&format!(
                "\nconst _: () = assert!(option_env!(\"{name}\").is_none(), \"compiler inherited {name}\");\n"
            ));
        }
        fs::write(&source_path, credential_source)?;
        phase("credential setup");
        let setup = rail(&workspace.path, credential_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "credential cache setup failed: {setup:?}");
        phase("credential compilation");
        let credential_probe = cargo_check_remote(
            &workspace.path,
            credential_home.path(),
            &remote_url,
            "read-write",
            Some(&rustc),
            None,
        )?;
        assert!(
            credential_probe.status.success(),
            "credential scrub probe failed: {credential_probe:?}"
        );
        let compiler_environments = fs::read_to_string(workspace.path.join("remote-compiler-environment.log"))?;
        let controlled_compilers = compiler_environments
            .lines()
            .filter(|line| line.contains("--crate-name transparent_remote") || line.ends_with("args=--print=sysroot"))
            .collect::<Vec<_>>();
        assert!(
            !controlled_compilers.is_empty()
                && controlled_compilers.iter().all(|line| {
                    line.starts_with("url=unset access=unset secret=unset token=unset config=unset args=")
                }),
            "remote authority entered a Cargo-Rail-controlled compiler subprocess: {compiler_environments:?}"
        );
        fs::write(source_path, original_source)?;
        fs::remove_dir_all(workspace.path.join("target"))?;

        let seed_home = tempfile::tempdir()?;
        phase("seed setup");
        let setup = rail(&workspace.path, seed_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "seed cache setup failed: {setup:?}");
        let seed_coverage = tempfile::tempdir()?;
        fs::set_permissions(seed_coverage.path(), fs::Permissions::from_mode(0o700))?;
        phase("remote seed compilation");
        let seed = cargo_check_remote(
            &workspace.path,
            seed_home.path(),
            &remote_url,
            "read-write",
            None,
            Some(seed_coverage.path()),
        )?;
        assert!(seed.status.success(), "remote seed compilation failed: {seed:?}");
        let requests = remote.requests();
        assert!(
            requests
                .iter()
                .any(|(method, path)| method == "PUT" && path.contains("/entries/")),
            "remote seed did not publish a compressed entry: {requests:?}"
        );

        remote.set_available(false);
        fs::remove_dir_all(workspace.path.join("target"))?;
        let before_l1_hit = remote.request_count();
        let l1_coverage = tempfile::tempdir()?;
        fs::set_permissions(l1_coverage.path(), fs::Permissions::from_mode(0o700))?;
        phase("offline L1 reuse");
        let l1_hit = cargo_check_remote(
            &workspace.path,
            seed_home.path(),
            &remote_url,
            "read-write",
            None,
            Some(l1_coverage.path()),
        )?;
        assert!(
            l1_hit.status.success(),
            "L1 reuse failed during remote outage: {l1_hit:?}"
        );
        assert_eq!(
            remote.request_count(),
            before_l1_hit,
            "a verified L1 hit performed an L2 request"
        );
        let l1_events = coverage_events(l1_coverage.path())?;
        assert!(
            !l1_events.is_empty()
                && l1_events
                    .iter()
                    .all(|event| event["remote_request_attempts"] == 0 && event["remote_coordinator_requests"] == 0),
            "a verified L1 hit reported an L2 request: {l1_events:?}"
        );

        remote.set_available(true);
        let import_home = tempfile::tempdir()?;
        phase("import setup");
        let setup = rail(&workspace.path, import_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "import cache setup failed: {setup:?}");
        fs::remove_dir_all(workspace.path.join("target"))?;
        let import_coverage = tempfile::tempdir()?;
        fs::set_permissions(import_coverage.path(), fs::Permissions::from_mode(0o700))?;
        let writes_before_import = remote.requests().iter().filter(|(method, _)| method == "PUT").count();
        let requests_before_import = remote.request_count();
        phase("remote import");
        let imported = cargo_check_remote(
            &workspace.path,
            import_home.path(),
            &remote_url,
            "read",
            None,
            Some(import_coverage.path()),
        )?;
        assert!(imported.status.success(), "remote import failed: {imported:?}");
        let imported_events = coverage_events(import_coverage.path())?;
        assert!(
            imported_events
                .iter()
                .any(|event| event["status"] == "hit" && event["reason"] == "verified_remote_result"),
            "empty L1 did not import and verify the remote result: {imported_events:?}"
        );
        assert_eq!(
            remote.requests().iter().filter(|(method, _)| method == "PUT").count(),
            writes_before_import,
            "read-only remote import performed a write"
        );
        let import_request_attempts = imported_events
            .iter()
            .filter_map(|event| event["remote_request_attempts"].as_u64())
            .sum::<u64>();
        let coordinator_requests = imported_events
            .iter()
            .filter_map(|event| event["remote_coordinator_requests"].as_u64())
            .sum::<u64>();
        let coordinated_events = imported_events
            .iter()
            .filter(|event| {
                event["remote_coordinator_requests"]
                    .as_u64()
                    .is_some_and(|requests| requests > 0)
            })
            .count();
        let observed_remote_requests = u64::try_from(remote.request_count().saturating_sub(requests_before_import))?;
        assert!(
            observed_remote_requests > 0 && import_request_attempts >= observed_remote_requests,
            "coordinated import under-reported fixture-observed S3 requests: attempts={import_request_attempts}, \
     observed={observed_remote_requests}, events={imported_events:?}"
        );
        assert!(
            coordinator_requests > 0 && import_request_attempts > 0,
            "coordinated import performed no remote work: {imported_events:?}"
        );
        assert_eq!(
            coordinator_requests,
            u64::try_from(coordinated_events)?,
            "coordinated import performed control-plane requests beyond its cache lookup: {imported_events:?}"
        );
        assert!(
            imported_events
                .iter()
                .filter_map(|event| event["remote_payload_bytes_read"].as_u64())
                .sum::<u64>()
                > 0,
            "remote import reported no downloaded payload bytes: {imported_events:?}"
        );
        assert!(
            imported_events
                .iter()
                .filter_map(|event| event["remote_service_elapsed_ns"].as_u64())
                .sum::<u64>()
                > 0,
            "remote import reported no provider/coordinator service time: {imported_events:?}"
        );
        let remote_hits = imported_events
            .iter()
            .filter(|event| event["status"] == "hit" && event["reason"] == "verified_remote_result")
            .collect::<Vec<_>>();
        assert!(
            remote_hits.iter().all(|event| {
                event["timing"]["total"]["count"].as_u64() == Some(1)
                    && event["timing"]["lookup"]["count"].as_u64() == Some(1)
                    && event["timing"]["decode"]["count"].as_u64() == Some(1)
                    && event["timing"]["validation"]["count"].as_u64() == Some(1)
                    && event["timing"]["l1_admission"]["count"].as_u64() == Some(1)
                    && event["timing"]["output_restore"]["count"].as_u64() == Some(1)
            }),
            "remote-hit phase accounting is incomplete: {remote_hits:?}"
        );
        assert!(
            remote_hits
                .iter()
                .filter_map(|event| event["durability"]["l1_file_sync"]["count"].as_u64())
                .sum::<u64>()
                > 0,
            "remote-hit L1 durability accounting is empty: {remote_hits:?}"
        );
        assert!(
            imported_events
                .iter()
                .all(|event| event["remote_payload_bytes_written"] == 0),
            "read-only remote import reported uploaded payload bytes: {imported_events:?}"
        );

        remote.set_available(false);
        fs::remove_dir_all(workspace.path.join("target"))?;
        let requests_before_packed_hit = remote.request_count();
        let packed_coverage = tempfile::tempdir()?;
        fs::set_permissions(packed_coverage.path(), fs::Permissions::from_mode(0o700))?;
        phase("offline imported L1 reuse");
        let packed_hit = cargo_check_remote(
            &workspace.path,
            import_home.path(),
            &remote_url,
            "read",
            None,
            Some(packed_coverage.path()),
        )?;
        assert!(
            packed_hit.status.success(),
            "packed L1 reuse failed during remote outage: {packed_hit:?}"
        );
        assert_eq!(
            remote.request_count(),
            requests_before_packed_hit,
            "a packed L1 hit performed an L2 request"
        );
        let packed_events = coverage_events(packed_coverage.path())?;
        assert!(
            packed_events
                .iter()
                .any(|event| event["status"] == "hit" && event["reason"] == "verified_local_result")
                && packed_events
                    .iter()
                    .all(|event| event["remote_request_attempts"] == 0 && event["remote_coordinator_requests"] == 0),
            "the imported packed authority did not serve an offline L1 hit: {packed_events:?}"
        );

        // Reclaim result authority through the CLI while retaining the authenticated
        // compiler component. Recovery needs an empty L1, not another driver build.
        let clear_seed_l1 = || -> Result<()> {
            let root = selected_profile_cache_root(&workspace.path, seed_home.path())?;
            let clean = rail(
                &workspace.path,
                seed_home.path(),
                &["rail", "cache", "clean", "--scope", "local"],
            )?;
            assert!(clean.status.success(), "recovery L1 cleanup failed: {clean:?}");
            assert!(!root.try_exists()?, "recovery retained the seeded L1 authority");
            let setup = rail(&workspace.path, seed_home.path(), &["rail", "cache", "setup"])?;
            assert!(setup.status.success(), "recovery cache setup failed: {setup:?}");
            Ok(())
        };

        remote.set_available(true);
        assert!(remote.corrupt_result(), "fixture had no remote result to corrupt");
        phase("corruption L1 reset");
        clear_seed_l1()?;
        fs::remove_dir_all(workspace.path.join("target"))?;
        let corrupt_coverage = tempfile::tempdir()?;
        fs::set_permissions(corrupt_coverage.path(), fs::Permissions::from_mode(0o700))?;
        phase("corruption cold fallback");
        let corrupt = cargo_check_remote(
            &workspace.path,
            seed_home.path(),
            &remote_url,
            "read-write",
            None,
            Some(corrupt_coverage.path()),
        )?;
        assert!(
            corrupt.status.success(),
            "remote corruption blocked the cold compilation: {corrupt:?}"
        );
        let corrupt_events = coverage_events(corrupt_coverage.path())?;
        assert!(
            corrupt_events.iter().any(|event| event["status"] == "miss"
                && event["reason"].as_str().is_some_and(|reason| {
                    reason.starts_with("remote_entry_rejected;") && reason.ends_with("remote_publication_failed")
                })),
            "corrupt remote data was not rejected before cold fallback: {corrupt_events:?}"
        );

        remote.set_available(false);
        phase("outage L1 reset");
        clear_seed_l1()?;
        fs::remove_dir_all(workspace.path.join("target"))?;
        let outage_coverage = tempfile::tempdir()?;
        fs::set_permissions(outage_coverage.path(), fs::Permissions::from_mode(0o700))?;
        phase("outage cold fallback");
        let outage = cargo_check_remote(
            &workspace.path,
            seed_home.path(),
            &remote_url,
            "read-write",
            None,
            Some(outage_coverage.path()),
        )?;
        assert!(
            outage.status.success(),
            "remote outage blocked the cold compilation: {outage:?}"
        );
        let outage_events = coverage_events(outage_coverage.path())?;
        assert!(
            outage_events.iter().any(|event| event["status"] == "miss")
                && outage_events.iter().all(|event| event["status"] != "hit"),
            "remote outage did not execute cold with an empty L1: {outage_events:?}"
        );
        phase("complete");
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(unix)]
#[test]
fn direct_cargo_reuses_verified_outputs_and_off_never_touches_l1() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let workspace = TestWorkspace::new_single_crate("transparent-hit", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "setup failed: {setup:?}");
        let cold = cargo_check(&workspace.path, cargo_home.path(), None, None)?;
        assert!(cold.status.success(), "cold compilation failed: {cold:?}");
        fs::remove_dir_all(workspace.path.join("target"))?;

        let real_rustc = Path::new("rustc");
        let shim = workspace.path.join("rustc-hit-proof");
        fs::write(
            &shim,
            "#!/bin/sh\nif [ -n \"$CACHE_ENV_LOG\" ]; then printf '%s\\n' \"${CARGO_RAIL_CACHE-unset}\" >> \"$CACHE_ENV_LOG\"; fi\nfor arg in \"$@\"; do\n  if [ \"$arg\" = \"transparent_hit\" ]; then exit 91; fi\ndone\nexec \"$REAL_RUSTC\" \"$@\"\n",
        )?;
        fs::set_permissions(&shim, fs::Permissions::from_mode(0o700))?;
        let hit = cargo_check(&workspace.path, cargo_home.path(), None, None)?;
        assert!(hit.status.success(), "verified hit failed: {hit:?}");

        fs::remove_dir_all(workspace.path.join("target"))?;
        let replaced = Command::new("cargo")
            .current_dir(&workspace.path)
            .args(["check", "--quiet"])
            .env("CARGO_HOME", cargo_home.path())
            .env("CARGO_INCREMENTAL", "0")
            .env("RUSTC", &shim)
            .env("REAL_RUSTC", real_rustc)
            .env_remove("RUSTC_WRAPPER")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .output()?;
        assert!(
            !replaced.status.success(),
            "cache skipped the selected compiler: {replaced:?}"
        );
        assert!(String::from_utf8_lossy(&replaced.stderr).contains("exit status: 91"));

        let observed = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local", "-f", "json"],
        )?;
        let observed = json(&observed)?;
        let installed_wrapper = PathBuf::from(
            observed["status"]["installation"]["wrapper_path"]
                .as_str()
                .context("installed wrapper path")?,
        );
        assert!(
            observed["status"]["installation"]["usage"]["misses"]
                .as_u64()
                .unwrap_or_default()
                >= 1
        );
        assert!(
            observed["status"]["installation"]["usage"]["hits"]
                .as_u64()
                .unwrap_or_default()
                >= 1
        );

        fs::remove_dir_all(workspace.path.join("target"))?;
        let cache_root = selected_profile_cache_root(&workspace.path, cargo_home.path())?;
        let before = directory_snapshot(&cache_root)?;
        #[cfg(not(windows))]
        let installed_worker = installed_wrapper.with_file_name("cargo-rail-native-rustc-worker");
        #[cfg(windows)]
        let installed_worker = installed_wrapper.with_file_name("cargo-rail-native-rustc-worker.exe");
        fs::remove_file(installed_worker)?;
        let off = Command::new("cargo")
            .current_dir(&workspace.path)
            .args(["check", "--quiet"])
            .env("CARGO_HOME", cargo_home.path())
            .env("CARGO_INCREMENTAL", "0")
            .env("CARGO_RAIL_CACHE", "off")
            .env("CACHE_ENV_LOG", workspace.path.join("cache-env.log"))
            .env("RUSTC", &shim)
            .env("REAL_RUSTC", real_rustc)
            .env_remove("RUSTC_WRAPPER")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .output()?;
        assert!(
            !off.status.success(),
            "cache opt-out did not execute the original compiler"
        );
        assert_eq!(
            directory_snapshot(&cache_root)?,
            before,
            "cache opt-out touched L1 state"
        );
        let observed_environment = fs::read_to_string(workspace.path.join("cache-env.log"))?;
        assert!(
            observed_environment.lines().all(|value| value == "off"),
            "cache opt-out changed the compiler environment: {observed_environment:?}"
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(unix)]
#[test]
fn selected_compiler_wrapper_preserves_its_flags_after_cache_setup() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let workspace = TestWorkspace::new_single_crate("selected-compiler-wrapper", "0.1.0")?;
        fs::write(
            workspace.path.join("src/lib.rs"),
            "#[cfg(not(wrapper_authorized))]\ncompile_error!(\"selected compiler flag was lost\");\npub fn value() -> u8 { 7 }\n",
        )?;
        let probe = tempfile::tempdir()?;
        let compiler = probe.path().join("selected-rustc");
        fs::write(&compiler, "#!/bin/sh\nexec rustc \"$@\" --cfg wrapper_authorized\n")?;
        fs::set_permissions(&compiler, fs::Permissions::from_mode(0o700))?;
        let cargo_home = tempfile::tempdir()?;
        let run = || {
            Command::new("cargo")
                .current_dir(&workspace.path)
                .args(["check", "--quiet"])
                .env("CARGO_HOME", cargo_home.path())
                .env("RUSTC", &compiler)
                .env("CARGO_INCREMENTAL", "0")
                .env_remove("RUSTC_WRAPPER")
                .env_remove("RUSTC_WORKSPACE_WRAPPER")
                .env_remove("CARGO_BUILD_RUSTC_WRAPPER")
                .env_remove("CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER")
                .output()
        };
        let uncached = run()?;
        assert!(uncached.status.success(), "uncached compiler failed: {uncached:?}");
        let outputs = compiler_only_outputs(&workspace.path.join("target/debug/deps"))?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "cache setup failed: {setup:?}");
        fs::remove_dir_all(workspace.path.join("target"))?;
        let installed = run()?;
        assert!(
            installed.status.success(),
            "cache changed selected compiler behavior: {installed:?}"
        );
        assert_eq!(installed.stdout, uncached.stdout);
        assert_eq!(installed.stderr, uncached.stderr);
        assert_eq!(
            compiler_only_outputs(&workspace.path.join("target/debug/deps"))?,
            outputs
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(unix)]
#[test]
fn analysis_missing_binding_executes_despite_an_ordinary_native_result() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let workspace = TestWorkspace::new_single_crate("fact-cache-guard", "0.1.0")?;
        fs::create_dir_all(workspace.path.join("helper/src"))?;
        fs::write(
            workspace.path.join("helper/Cargo.toml"),
            "[package]\nname = \"helper\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )?;
        fs::write(workspace.path.join("helper/src/lib.rs"), "pub fn helper() {}\n")?;
        let manifest = workspace.path.join("Cargo.toml");
        fs::write(
            &manifest,
            fs::read_to_string(&manifest)?
                .replace("[dependencies]\n", "[dependencies]\nhelper = { path = \"helper\" }\n"),
        )?;
        let lock = Command::new("cargo")
            .current_dir(&workspace.path)
            .args(["generate-lockfile"])
            .output()?;
        assert!(lock.status.success(), "lockfile generation failed: {lock:?}");
        workspace.commit("Add unused path dependency")?;

        let cargo_home = tempfile::tempdir()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "cache setup failed: {setup:?}");
        let cold = Command::new("cargo")
            .current_dir(&workspace.path)
            .args([
                "check",
                "--locked",
                "--all-targets",
                "--message-format=json",
                "--package",
                "fact-cache-guard",
            ])
            .env("CARGO_HOME", cargo_home.path())
            .env("CARGO_INCREMENTAL", "0")
            .env_remove("RUSTC_WRAPPER")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .output()?;
        assert!(cold.status.success(), "ordinary cache seed failed: {cold:?}");
        let native_actions = selected_profile_cache_root(&workspace.path, cargo_home.path())?.join("native-actions-v2");
        assert!(
            fs::read_dir(&native_actions)?.next().transpose()?.is_some(),
            "ordinary cargo check did not publish a native result"
        );
        let metadata = Command::new("cargo")
            .current_dir(&workspace.path)
            .args(["metadata", "--format-version=1", "--no-deps"])
            .env("CARGO_HOME", cargo_home.path())
            .output()?;
        assert!(metadata.status.success(), "target discovery failed: {metadata:?}");
        let metadata: serde_json::Value = serde_json::from_slice(&metadata.stdout)?;
        let target_directory = PathBuf::from(
            metadata["target_directory"]
                .as_str()
                .context("Cargo metadata target directory")?,
        );
        fs::remove_dir_all(&target_directory)?;
        assert!(!target_directory.exists(), "Cargo target directory survived removal");

        let rustc_probe = tempfile::tempdir()?;
        let rustc_log = rustc_probe.path().join("fact-rustc.log");
        let rustc_shim = rustc_probe.path().join("fact-rustc-shim");
        fs::write(
            &rustc_shim,
            "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$CARGO_RAIL_TEST_RUSTC_LOG\"\nexec \"$REAL_RUSTC\" \"$@\"\n",
        )?;
        fs::set_permissions(&rustc_shim, fs::Permissions::from_mode(0o700))?;
        let analysis = Command::new(crate::helpers::cargo_binary("cargo-rail"))
            .current_dir(&workspace.path)
            .args(["rail", "unify", "--check"])
            .env("CARGO_HOME", cargo_home.path())
            .env("CARGO_INCREMENTAL", "0")
            .env("RUSTC", &rustc_shim)
            .env("REAL_RUSTC", "rustc")
            .env("CARGO_RAIL_TEST_RUSTC_LOG", &rustc_log)
            .env_remove("RUSTC_WRAPPER")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .output()?;
        let rustc_invocations =
            fs::read_to_string(&rustc_log).unwrap_or_else(|error| format!("<unavailable: {error}>"));
        assert_eq!(
            analysis.status.code(),
            Some(1),
            "unused dependency analysis lost required compiler facts\nstdout:\n{}\nstderr:\n{}\nrustc:\n{}",
            String::from_utf8_lossy(&analysis.stdout),
            String::from_utf8_lossy(&analysis.stderr),
            rustc_invocations
        );
        assert!(
            String::from_utf8_lossy(&analysis.stdout).contains("Dependencies: helper"),
            "unused path dependency was not planned\nstdout:\n{}",
            String::from_utf8_lossy(&analysis.stdout)
        );
        assert!(
            rustc_invocations.lines().any(|invocation| {
                invocation.contains("--crate-name fact_cache_guard") && invocation.contains("unused-crate-dependencies")
            }),
            "fact-required workspace compilation was restored from the ordinary native result:\n{rustc_invocations}"
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(unix)]
#[test]
fn compiler_analysis_reuses_native_result_only_after_an_exact_binding() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("bound-analysis-cache", "0.1.0")?;
        fs::create_dir_all(workspace.path.join("helper/src"))?;
        fs::write(
            workspace.path.join("helper/Cargo.toml"),
            "[package]\nname = \"helper\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )?;
        fs::write(workspace.path.join("helper/src/lib.rs"), "pub fn helper() {}\n")?;
        let manifest = workspace.path.join("Cargo.toml");
        fs::write(
            &manifest,
            fs::read_to_string(&manifest)?
                .replace("[dependencies]\n", "[dependencies]\nhelper = { path = \"helper\" }\n"),
        )?;
        fs::write(workspace.path.join("build.rs"), "fn main() {}\n")?;
        let lock = Command::new("cargo")
            .current_dir(&workspace.path)
            .args(["generate-lockfile"])
            .output()?;
        assert!(lock.status.success(), "lockfile generation failed: {lock:?}");
        workspace.commit("Add bound analysis fixture")?;

        let cargo_home = tempfile::tempdir()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "cache setup failed: {setup:?}");

        let wrapper_probe = tempfile::tempdir()?;
        let wrapper_log = wrapper_probe.path().join("wrapper.log");
        let run = |wrapper: Option<&Path>| -> Result<std::process::Output> {
            let mut command = Command::new(crate::helpers::cargo_binary("cargo-rail"));
            command
                .current_dir(&workspace.path)
                .args(["rail", "unify", "--check"])
                .env("CARGO_HOME", cargo_home.path())
                .env("CARGO_INCREMENTAL", "0")
                .env_remove("CARGO_BUILD_RUSTC_WRAPPER")
                .env_remove("CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER")
                .env_remove("RUSTC_WRAPPER")
                .env_remove("RUSTC_WORKSPACE_WRAPPER");
            if let Some(wrapper) = wrapper {
                command
                    .env("RUSTC_WORKSPACE_WRAPPER", wrapper)
                    .env("CARGO_RAIL_TEST_WORKSPACE_WRAPPER_LOG", &wrapper_log);
            }
            Ok(command.output()?)
        };

        let cold = run(None)?;
        assert_eq!(cold.status.code(), Some(1), "cold analysis failed: {cold:?}");
        let usage = || -> Result<serde_json::Value> {
            let status = rail(
                &workspace.path,
                cargo_home.path(),
                &["rail", "cache", "status", "--scope", "local", "-f", "json"],
            )?;
            assert!(status.status.success(), "cache status failed: {status:?}");
            Ok(json(&status)?["status"]["installation"]["usage"].clone())
        };
        let cold_usage = usage()?;
        assert!(cold_usage["misses"].as_u64().unwrap() >= 1, "{cold_usage}");
        assert_eq!(cold_usage["hits"], 0, "{cold_usage}");
        assert!(String::from_utf8_lossy(&cold.stdout).contains("Dependencies: helper"));

        let warm = run(None)?;
        assert_eq!(warm.status.code(), Some(1), "warm analysis failed: {warm:?}");
        assert!(
            String::from_utf8_lossy(&warm.stdout).contains("Dependencies: helper"),
            "warm analysis lost exact diagnostic evidence: {warm:?}"
        );
        let warm_usage = usage()?;
        assert!(warm_usage["hits"].as_u64().unwrap() >= 1, "{warm_usage}");
        assert_eq!(warm_usage["misses"], cold_usage["misses"], "{warm_usage}");
        fs::write(workspace.path.join("src/lib.rs"), "pub fn changed() {}\n")?;
        let changed = run(None)?;
        assert_eq!(changed.status.code(), Some(1), "changed analysis failed: {changed:?}");
        assert!(String::from_utf8_lossy(&changed.stdout).contains("Dependencies: helper"));
        let changed_usage = usage()?;
        assert!(
            changed_usage["misses"].as_u64().unwrap() > warm_usage["misses"].as_u64().unwrap(),
            "{changed_usage}"
        );
        fs::write(
            workspace.path.join("src/lib.rs"),
            "pub fn used() { helper::helper(); }\n",
        )?;
        let used = run(None)?;
        assert!(used.status.success(), "used dependency analysis failed: {used:?}");
        assert!(!String::from_utf8_lossy(&used.stdout).contains("Dependencies: helper"));
        use std::os::unix::fs::PermissionsExt as _;
        let wrapper = wrapper_probe.path().join("workspace-wrapper");
        fs::write(
            &wrapper,
            "#!/bin/sh\nprintf '%s\n' \"$*\" >> \"$CARGO_RAIL_TEST_WORKSPACE_WRAPPER_LOG\"\nexec \"$@\"\n",
        )?;
        fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o700))?;
        fs::write(workspace.path.join("src/lib.rs"), "pub fn changed() {}\n")?;
        let wrapped = run(Some(&wrapper))?;
        assert_eq!(wrapped.status.code(), Some(1), "wrapped analysis failed: {wrapped:?}");
        assert!(String::from_utf8_lossy(&wrapped.stdout).contains("Dependencies: helper"));
        assert!(fs::read_to_string(&wrapper_log)?.contains("--crate-name bound_analysis_cache"));
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(unix)]
#[test]
fn remote_diagnostics_reuse_revalidates_source_inputs() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("remote-bound-analysis", "0.1.0")?;
        fs::create_dir_all(workspace.path.join("helper/src"))?;
        fs::write(
            workspace.path.join("helper/Cargo.toml"),
            "[package]\nname = \"helper\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )?;
        fs::write(workspace.path.join("helper/src/lib.rs"), "pub fn helper() {}\n")?;
        let manifest = workspace.path.join("Cargo.toml");
        fs::write(
            &manifest,
            fs::read_to_string(&manifest)?
                .replace("[dependencies]\n", "[dependencies]\nhelper = { path = \"helper\" }\n"),
        )?;
        let lock = Command::new("cargo")
            .current_dir(&workspace.path)
            .args(["generate-lockfile"])
            .output()?;
        assert!(lock.status.success(), "lockfile generation failed: {lock:?}");
        workspace.commit("Add remote analysis fixture")?;

        let remote = LoopbackS3::start()?;
        let remote_url = remote.remote_url();
        let cargo_home = tempfile::tempdir()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "remote fixture setup: {setup:?}");

        let run = |cache_root: &Path, mode: &str| -> Result<Output> {
            Ok(Command::new(crate::helpers::cargo_binary("cargo-rail"))
                .current_dir(&workspace.path)
                .args(["rail", "--diagnostics-file"])
                .arg(cache_root.join("diagnostics.json"))
                .args(["unify", "--check"])
                .env("CARGO_HOME", cargo_home.path())
                .env("CARGO_RAIL_CACHE_DIR", cache_root)
                .env("CARGO_INCREMENTAL", "0")
                .env("AWS_ACCESS_KEY_ID", "fixture-access-key")
                .env("AWS_SECRET_ACCESS_KEY", "fixture-secret-key")
                .env("AWS_SESSION_TOKEN", "fixture-session-token")
                .env("AWS_EC2_METADATA_DISABLED", "true")
                .env("AWS_CONFIG_FILE", workspace.path.join("missing-aws-config"))
                .env(
                    "AWS_SHARED_CREDENTIALS_FILE",
                    workspace.path.join("missing-aws-credentials"),
                )
                .env("CARGO_RAIL_CACHE_REMOTE", &remote_url)
                .env("CARGO_RAIL_CACHE_MODE", mode)
                .env_remove("CARGO_BUILD_RUSTC_WRAPPER")
                .env_remove("CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER")
                .env_remove("RUSTC_WRAPPER")
                .env_remove("RUSTC_WORKSPACE_WRAPPER")
                .env_remove("AWS_ENDPOINT_URL")
                .env_remove("AWS_ENDPOINT_URL_S3")
                .env_remove("AWS_PROFILE")
                .env_remove("AWS_DEFAULT_PROFILE")
                .output()?)
        };

        let seed_cache = tempfile::tempdir()?;
        let seed = run(seed_cache.path(), "read-write")?;
        assert_eq!(seed.status.code(), Some(1), "remote analysis seed failed: {seed:?}");
        let seed_requests = remote.requests();
        assert!(
            seed_requests
                .iter()
                .any(|(method, path)| method == "PUT" && path.contains("/evidence-v1/objects/")),
            "analysis seed did not publish evidence objects: {seed_requests:?}"
        );
        assert!(
            seed_requests
                .iter()
                .any(|(method, path)| method == "PUT" && path.contains("/evidence-v1/candidates/")),
            "analysis seed did not publish evidence candidate indexes: {seed_requests:?}"
        );

        let import_cache = tempfile::tempdir()?;
        let requests_before_import = remote.request_count();
        let imported = run(import_cache.path(), "read")?;
        assert_eq!(
            imported.status.code(),
            Some(1),
            "remote analysis import failed: {imported:?}"
        );
        assert!(
            String::from_utf8_lossy(&imported.stdout).contains("Dependencies: helper"),
            "remote analysis import lost exact fact evidence: {imported:?}"
        );
        let imported_counters: serde_json::Value =
            serde_json::from_slice(&fs::read(import_cache.path().join("diagnostics.json"))?)?;
        assert_eq!(
            imported_counters["compiler_acquisition"]["cargo_views"], 0,
            "unchanged remote diagnostics must avoid Cargo acquisition: {imported_counters}; {imported:?}"
        );
        assert_eq!(imported_counters["compiler_acquisition"]["compiler_actions"], 0);
        let import_requests = remote.requests();
        assert!(
            import_requests[requests_before_import..]
                .iter()
                .any(|(method, path)| method == "GET" && path.contains("/evidence-v1/candidates/")),
            "analysis reuse did not query remote evidence candidates: {import_requests:?}"
        );
        assert!(
            import_requests[requests_before_import..]
                .iter()
                .any(|(method, path)| method == "GET" && path.contains("/evidence-v1/objects/")),
            "analysis reuse did not import remote evidence objects: {import_requests:?}"
        );
        assert!(
            import_requests[requests_before_import..]
                .iter()
                .all(|(method, _)| method != "PUT"),
            "read-only diagnostics import published remote data"
        );

        fs::remove_dir_all(workspace.path.join("target"))?;
        let cold_cache = tempfile::tempdir()?;
        fs::write(workspace.path.join("src/lib.rs"), "pub fn changed() -> u8 { 7 }\n")?;
        let cold = run(cold_cache.path(), "read")?;
        assert_eq!(cold.status.code(), Some(1), "changed-input acquisition: {cold:?}");
        assert!(String::from_utf8_lossy(&cold.stdout).contains("Dependencies: helper"));
        let cold_counters: serde_json::Value =
            serde_json::from_slice(&fs::read(cold_cache.path().join("diagnostics.json"))?)?;
        assert_eq!(
            cold_counters["compiler_acquisition"]["cargo_views"], 1,
            "{cold_counters}"
        );
        assert!(
            cold_counters["compiler_acquisition"]["compiler_actions"]
                .as_u64()
                .is_some_and(|count| count > 0),
            "source change must execute the compiler: {cold_counters}"
        );
        let removed = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "uninstall"])?;
        assert!(removed.status.success(), "stop fixture coordinator: {removed:?}");
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[test]
fn unsupported_shapes_bypass_before_acquisition_while_proc_macro_producers_remain_cacheable() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("transparent-early-bypass", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "setup failed: {setup:?}");
        let installation = selected_profile_state_root(&workspace.path, cargo_home.path())?;
        let cache_root = selected_profile_cache_root(&workspace.path, cargo_home.path())?;
        let before = directory_snapshot(&cache_root)?;

        let incremental = Command::new("cargo")
            .current_dir(&workspace.path)
            .args(["check", "--quiet"])
            .env("CARGO_HOME", cargo_home.path())
            .env_remove("CARGO_INCREMENTAL")
            .env_remove("RUSTC_FORCE_INCREMENTAL")
            .env_remove("RUSTC_WRAPPER")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .output()?;
        assert!(
            incremental.status.success(),
            "incremental bypass failed: {incremental:?}"
        );
        assert!(!installation.join("session.json").exists());
        assert!(!installation.join("usage-v1.log").exists());
        assert!(installation.join("early-bypass-v1.log").is_file());
        assert_eq!(
            directory_snapshot(&cache_root)?,
            before,
            "incremental bypass touched L1"
        );
        let early_status = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local", "-f", "json"],
        )?;
        let early_usage = &json(&early_status)?["status"]["installation"]["usage"];
        assert!(early_usage["early_bypasses"].as_u64().unwrap_or_default() >= 1);
        assert!(
            early_usage["early_bypass_reasons"]["incremental_work_product_observation_unavailable"]
                .as_u64()
                .unwrap_or_default()
                >= 1,
            "incremental bypass class was not observable: {early_usage}"
        );

        let clippy = Command::new("cargo")
            .current_dir(&workspace.path)
            .args(["clippy", "--quiet"])
            .env("CARGO_HOME", cargo_home.path())
            .env_remove("CARGO_INCREMENTAL")
            .env_remove("RUSTC_FORCE_INCREMENTAL")
            .env_remove("RUSTC_WRAPPER")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .output()?;
        assert!(clippy.status.success(), "clippy bypass failed: {clippy:?}");
        assert!(!installation.join("session.json").exists());
        assert!(!installation.join("usage-v1.log").exists());
        assert!(installation.join("early-bypass-v1.log").is_file());
        assert_eq!(directory_snapshot(&cache_root)?, before, "clippy bypass touched L1");

        fs::create_dir_all(workspace.path.join("fixture-macros/src"))?;
        fs::write(
            workspace.path.join("fixture-macros/Cargo.toml"),
            r#"[package]
name = "fixture-macros"
version = "0.1.0"
edition = "2024"

[lib]
proc-macro = true
"#,
        )?;
        fs::write(
            workspace.path.join("fixture-macros/src/lib.rs"),
            r#"extern crate proc_macro;

use proc_macro::TokenStream;

#[proc_macro_derive(Fixture)]
pub fn derive_fixture(_: TokenStream) -> TokenStream {
  TokenStream::new()
}
"#,
        )?;
        fs::write(
            workspace.path.join("Cargo.toml"),
            r#"[package]
name = "transparent-early-bypass"
version = "0.1.0"
edition = "2024"

[dependencies]
fixture-macros = { path = "fixture-macros" }

[workspace]
members = ["fixture-macros"]
resolver = "3"
"#,
        )?;
        fs::write(
            workspace.path.join("src/lib.rs"),
            "#[derive(fixture_macros::Fixture)]\npub struct Fixture;\n",
        )?;
        let coverage = tempfile::tempdir()?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            fs::set_permissions(coverage.path(), fs::Permissions::from_mode(0o700))?;
        }
        let coverage_path = cargo_rail::utils::canonicalize_existing(coverage.path())?;
        let proc_macro = Command::new("cargo")
            .current_dir(&workspace.path)
            .args(["check", "--workspace", "--quiet"])
            .env("CARGO_HOME", cargo_home.path())
            .env("CARGO_INCREMENTAL", "0")
            .env("CARGO_RAIL_CACHE", "__cargo_rail_benchmark_coverage_v1")
            .env("CARGO_RAIL_BENCH_NATIVE_COVERAGE_DIRECTORY", &coverage_path)
            .env_remove("RUSTC_WRAPPER")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .output()?;
        assert!(proc_macro.status.success(), "proc-macro bypass failed: {proc_macro:?}");
        assert!(installation.join("session.json").is_file());
        assert!(installation.join("usage-v1.log").is_file());
        assert_ne!(
            directory_snapshot(&cache_root)?,
            before,
            "graduated proc-macro producer did not touch L1"
        );

        let mut producer_cached = false;
        #[cfg(windows)]
        let mut producer_bypassed = false;
        let mut consumer_bypassed_before_acquisition = false;
        let mut event_summary = Vec::new();
        for entry in fs::read_dir(&coverage_path)? {
            let event: serde_json::Value = serde_json::from_slice(&fs::read(entry?.path())?)?;
            let arguments = event["arguments"].as_array().context("coverage arguments")?;
            let crate_name = arguments.windows(2).find_map(|pair| {
                (pair[0].as_str() == Some("--crate-name"))
                    .then(|| pair[1].as_str())
                    .flatten()
            });
            event_summary.push((
                crate_name.map(str::to_string),
                event["status"].as_str().map(str::to_string),
                event["reason"].as_str().map(str::to_string),
                event["action_key"].as_str().map(str::to_string),
            ));
            if crate_name == Some("fixture_macros") && matches!(event["status"].as_str(), Some("hit" | "miss")) {
                producer_cached |= event["action_key"].as_str().is_some();
            }
            #[cfg(windows)]
            if crate_name == Some("fixture_macros") {
                assert_eq!(event["status"], "bypassed");
                assert_eq!(event["reason"], "compiler_native_input_driver_unavailable");
                producer_bypassed = true;
            }
            let consumes_fixture_macro = crate_name == Some("transparent_early_bypass")
                && arguments.iter().any(|argument| {
                    argument
                        .as_str()
                        .is_some_and(|argument| argument.starts_with("fixture_macros="))
                });
            if consumes_fixture_macro {
                assert_eq!(event["status"], "bypassed");
                assert_eq!(event["reason"], "dynamic_dependency_execution_observation_unavailable");
                assert!(event.get("action_key").is_none());
                assert_eq!(event["bytes_hashed"], 0);
                assert_eq!(event["cache_bytes_read"], 0);
                consumer_bypassed_before_acquisition = true;
            }
        }
        #[cfg(not(windows))]
        assert!(
            producer_cached,
            "proc-macro producer did not enter verified L1: {event_summary:?}"
        );
        #[cfg(windows)]
        assert!(
            producer_bypassed && !producer_cached,
            "proc-macro producer did not bypass unavailable native capture: {event_summary:?}"
        );
        assert!(
            consumer_bypassed_before_acquisition,
            "native proc-macro consumer did not retain its acquisition-free bypass: {event_summary:?}"
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(unix)]
#[test]
fn custom_target_and_deterministic_flags_reuse_without_runtime_residue() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let workspace = TestWorkspace::new_single_crate("transparent-custom-target", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "setup failed: {setup:?}");

        let coverage = tempfile::tempdir()?;
        fs::set_permissions(coverage.path(), fs::Permissions::from_mode(0o700))?;
        let coverage_path = cargo_rail::utils::canonicalize_existing(coverage.path())?;
        let first_target_parent = tempfile::tempdir()?;
        let first_target = first_target_parent.path().join("producer-target");
        assert!(!first_target.exists(), "producer target existed before Cargo started");
        let first_runtime = tempfile::tempdir()?;
        let seed = Command::new("cargo")
            .current_dir(&workspace.path)
            .args(["check", "--quiet"])
            .env("CARGO_HOME", cargo_home.path())
            .env("CARGO_INCREMENTAL", "0")
            .env("CARGO_TARGET_DIR", &first_target)
            .env("TMPDIR", first_runtime.path())
            .env("CARGO_RAIL_CACHE", "__cargo_rail_benchmark_coverage_v1")
            .env("CARGO_RAIL_BENCH_NATIVE_COVERAGE_DIRECTORY", &coverage_path)
            .env(
                "RUSTFLAGS",
                "-Zcrate-attr=allow(unexpected_cfgs) -Ctarget-feature=+crt-static",
            )
            .env("RUSTC_BOOTSTRAP", "1")
            .env_remove("RUSTC_WRAPPER")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .output()?;
        assert!(seed.status.success(), "custom-target cache seed failed: {seed:?}");
        assert!(first_target.is_dir(), "Cargo did not create the producer target");
        assert_eq!(
            fs::read_dir(first_target_parent.path())?
                .collect::<Result<Vec<_>, _>>()?
                .into_iter()
                .map(|entry| entry.file_name())
                .collect::<Vec<_>>(),
            [std::ffi::OsString::from("producer-target")],
            "producer wrote outside its exact external target root"
        );
        assert_no_native_runtime_residue(first_runtime.path())?;

        let second_target_parent = tempfile::tempdir()?;
        let second_target = second_target_parent.path().join("consumer-target");
        assert!(!second_target.exists(), "consumer target existed before Cargo started");
        let reused = Command::new("cargo")
            .current_dir(&workspace.path)
            .args(["check", "--quiet"])
            .env("CARGO_HOME", cargo_home.path())
            .env("CARGO_INCREMENTAL", "0")
            .env("CARGO_TARGET_DIR", &second_target)
            .env("TMPDIR", first_runtime.path())
            .env("CARGO_RAIL_CACHE", "__cargo_rail_benchmark_coverage_v1")
            .env("CARGO_RAIL_BENCH_NATIVE_COVERAGE_DIRECTORY", &coverage_path)
            .env(
                "RUSTFLAGS",
                "-Zcrate-attr=allow(unexpected_cfgs) -Ctarget-feature=+crt-static",
            )
            .env("RUSTC_BOOTSTRAP", "1")
            .env_remove("RUSTC_WRAPPER")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .output()?;
        assert!(
            reused.status.success(),
            "the second physical target root did not reuse the verified action: {reused:?}; coverage: {:?}",
            native_coverage_summary(coverage.path())?
        );
        assert!(second_target.is_dir(), "Cargo did not create the consumer target");
        assert_eq!(
            fs::read_dir(second_target_parent.path())?
                .collect::<Result<Vec<_>, _>>()?
                .into_iter()
                .map(|entry| entry.file_name())
                .collect::<Vec<_>>(),
            [std::ffi::OsString::from("consumer-target")],
            "consumer restore wrote outside its exact external target root"
        );
        assert_no_native_runtime_residue(first_runtime.path())?;

        let status = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local", "-f", "json"],
        )?;
        assert!(
            json(&status)?["status"]["installation"]["usage"]["hits"]
                .as_u64()
                .unwrap_or_default()
                >= 1,
            "custom-target compilation did not record a native cache hit: {:?}",
            (
                native_coverage_summary(coverage.path())?,
                String::from_utf8_lossy(&seed.stderr),
                String::from_utf8_lossy(&reused.stderr),
            )
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(unix)]
fn assert_no_native_runtime_residue(directory: &Path) -> Result<()> {
    let residue = fs::read_dir(directory)?
        .collect::<Result<Vec<_>, _>>()?
        .into_iter()
        .map(|entry| entry.file_name())
        .filter(|name| name.to_string_lossy().starts_with("cargo-rail-native-cargo-"))
        .collect::<Vec<_>>();
    anyhow::ensure!(residue.is_empty(), "native wrapper runtime residue: {residue:?}");
    Ok(())
}

#[cfg(unix)]
type NativeCoverageSummary = (Option<String>, String, Option<String>, Option<String>);

#[cfg(unix)]
fn native_coverage_summary(directory: &Path) -> Result<Vec<NativeCoverageSummary>> {
    let mut summary = fs::read_dir(directory)?
        .collect::<Result<Vec<_>, _>>()?
        .into_iter()
        .map(|entry| -> Result<_> {
            let event: serde_json::Value = serde_json::from_slice(&fs::read(entry.path())?)?;
            Ok((
                event["action"]["crate_name"].as_str().map(str::to_string),
                event["status"].as_str().unwrap_or("missing").to_string(),
                event["reason"].as_str().map(str::to_string),
                event["action_key"].as_str().map(str::to_string),
            ))
        })
        .collect::<Result<Vec<_>>>()?;
    summary.sort();
    Ok(summary)
}

#[cfg(unix)]
#[test]
fn local_cache_outage_executes_cold_and_setup_repairs_the_same_authority() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let workspace = TestWorkspace::new_single_crate("transparent-outage", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "setup failed: {setup:?}");
        let cold = cargo_check(&workspace.path, cargo_home.path(), None, None)?;
        assert!(cold.status.success(), "cold seed failed: {cold:?}");
        fs::remove_dir_all(workspace.path.join("target"))?;
        let cache_root = selected_profile_cache_root(&workspace.path, cargo_home.path())?;
        fs::remove_dir_all(&cache_root)?;

        let log = workspace.path.join("outage-rustc.log");
        let shim = workspace.path.join("rustc-outage-proof");
        fs::write(
            &shim,
            "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$RUSTC_LOG\"\nexec \"$REAL_RUSTC\" \"$@\"\n",
        )?;
        fs::set_permissions(&shim, fs::Permissions::from_mode(0o700))?;
        let outage = Command::new("cargo")
            .current_dir(&workspace.path)
            .args(["check", "--quiet"])
            .env("CARGO_HOME", cargo_home.path())
            .env("CARGO_INCREMENTAL", "0")
            .env("RUSTC", &shim)
            .env("REAL_RUSTC", "rustc")
            .env("RUSTC_LOG", &log)
            .env_remove("RUSTC_WRAPPER")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .output()?;
        assert!(outage.status.success(), "cache outage did not compile cold: {outage:?}");
        assert!(fs::read_to_string(&log)?.contains("transparent_outage"));

        let status = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local", "-f", "json"],
        )?;
        assert_eq!(json(&status)?["status"]["installation"]["state"], "drifted");
        let check = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "setup", "--check"],
        )?;
        assert_eq!(check.status.code(), Some(1));
        let repair = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(repair.status.success(), "cache authority repair failed: {repair:?}");
        assert!(cache_root.is_dir());
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(unix)]
#[test]
fn workspace_wrapper_composes_by_bypassing_and_recursive_composition_is_rejected() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let workspace = TestWorkspace::new_single_crate("transparent-wrapper-chain", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "setup failed: {setup:?}");
        let status = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "status", "--scope", "local", "-f", "json"],
        )?;
        let wrapper = json(&status)?["status"]["installation"]["wrapper_path"]
            .as_str()
            .context("wrapper path")?
            .to_string();

        let chain = workspace.path.join("workspace-rustc-wrapper");
        let log = workspace.path.join("workspace-wrapper.log");
        fs::write(
            &chain,
            "#!/bin/sh\nprintf 'called\\n' >> \"$WRAPPER_LOG\"\nexec \"$@\"\n",
        )?;
        fs::set_permissions(&chain, fs::Permissions::from_mode(0o700))?;
        fs::create_dir_all(workspace.path.join(".cargo"))?;
        fs::write(
            workspace.path.join(".cargo/config.toml"),
            format!("[build]\nrustc-workspace-wrapper = '{}'\n", chain.display()),
        )?;
        let composed = Command::new("cargo")
            .current_dir(&workspace.path)
            .args(["check", "--quiet"])
            .env("CARGO_HOME", cargo_home.path())
            .env("WRAPPER_LOG", &log)
            .env_remove("RUSTC_WRAPPER")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .output()?;
        assert!(
            composed.status.success(),
            "safe wrapper composition failed: {composed:?}"
        );
        assert!(fs::read_to_string(&log)?.contains("called"));

        fs::remove_dir_all(workspace.path.join("target"))?;
        fs::write(
            workspace.path.join(".cargo/config.toml"),
            format!("[build]\nrustc-workspace-wrapper = '{wrapper}'\n"),
        )?;
        let recursive = Command::new("cargo")
            .current_dir(&workspace.path)
            .args(["check", "--quiet"])
            .env("CARGO_HOME", cargo_home.path())
            .env_remove("RUSTC_WRAPPER")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .output()?;
        assert!(!recursive.status.success(), "recursive wrapper unexpectedly ran");
        assert!(
            String::from_utf8_lossy(&recursive.stderr).contains("recursive transparent wrapper configuration"),
            "recursive wrapper failure was ambiguous: {recursive:?}"
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[test]
fn removal_refuses_a_changed_wrapper_field_and_preserves_unowned_configuration() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("transparent-remove-drift", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "setup failed: {setup:?}");
        let config = cargo_home.path().join("config.toml");
        fs::write(
            &config,
            "[build]\nrustc-wrapper = 'replacement-wrapper'\n[net]\noffline = true\n",
        )?;
        let remove = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "uninstall", "--check"],
        )?;
        assert_eq!(remove.status.code(), Some(2));
        assert!(String::from_utf8_lossy(&remove.stderr).contains("removal refused"));
        assert!(fs::read_to_string(&config)?.contains("replacement-wrapper"));
        assert!(
            cargo_home
                .path()
                .join("cargo-rail/compiler-cache-v1/setup.json")
                .is_file()
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[test]
fn local_cleanup_uses_the_receipt_selected_custom_cache_and_is_repairable() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("transparent-custom-clean", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let cache_base = tempfile::tempdir()?;
        let cache_base_root = fs::canonicalize(cache_base.path())?;
        let cache_base_arg = cache_base.path().to_str().context("cache base path")?;
        let setup = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "setup", "--local-dir", cache_base_arg],
        )?;
        assert!(setup.status.success(), "custom setup failed: {setup:?}");
        let cold = cargo_check(&workspace.path, cargo_home.path(), None, None)?;
        assert!(cold.status.success(), "custom cache seed failed: {cold:?}");
        let custom_root = selected_profile_cache_root(&workspace.path, cargo_home.path())?;
        let installation = cargo_home.path().join("cargo-rail/compiler-cache-v1");
        #[cfg(not(windows))]
        let wrapper = installation.join("cargo-rail-native-rustc-wrapper");
        #[cfg(windows)]
        let wrapper = installation.join("cargo-rail-native-rustc-wrapper.exe");
        #[cfg(not(windows))]
        let worker = installation.join("cargo-rail-native-rustc-worker");
        #[cfg(windows)]
        let worker = installation.join("cargo-rail-native-rustc-worker.exe");
        let receipt = installation.join("setup.json");
        let config = cargo_home.path().join("config.toml");
        let wrapper_evidence = capture_unchanged_file(&wrapper)?;
        let worker_evidence = capture_unchanged_file(&worker)?;
        let receipt_evidence = capture_unchanged_file(&receipt)?;
        let config_evidence = capture_unchanged_file(&config)?;
        assert!(custom_root.is_dir());
        assert!(custom_root.starts_with(&cache_base_root));

        let check = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "clean", "--scope", "local", "--check"],
        )?;
        assert_eq!(check.status.code(), Some(1));
        assert!(custom_root.is_dir(), "cleanup preview mutated the selected cache");
        let clean = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "clean", "--scope", "local"],
        )?;
        assert!(clean.status.success(), "custom cache cleanup failed: {clean:?}");
        assert!(!custom_root.exists());
        assert!(custom_root.starts_with(&cache_base_root));

        let repair = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(repair.status.success(), "custom cache repair failed: {repair:?}");
        assert!(
            custom_root.is_dir(),
            "repair changed or ignored the receipt-selected cache"
        );
        assert_unchanged_file(&wrapper, &wrapper_evidence, "installed compiler wrapper")?;
        assert_unchanged_file(&worker, &worker_evidence, "installed compiler worker")?;
        assert_unchanged_file(&receipt, &receipt_evidence, "installation receipt")?;
        assert_unchanged_file(&config, &config_evidence, "Cargo configuration")?;
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(unix)]
#[test]
fn ordinary_cargo_and_nextest_commands_receive_eligible_library_reuse() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let workspace = TestWorkspace::new_single_crate("transparent_shapes", "0.1.0")?;
        fs::write(
            workspace.path.join("src/main.rs"),
            "fn main() { println!(\"{}\", transparent_shapes::hello()); }\n",
        )?;
        let cargo_home = tempfile::tempdir()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "setup failed: {setup:?}");

        let lanes: &[(&str, &[&str])] = &[
            ("check", &["check", "--quiet"]),
            ("build", &["build", "--quiet"]),
            ("test", &["test", "--quiet"]),
            ("run", &["run", "--quiet"]),
            ("bench", &["bench", "--quiet", "--no-run"]),
            ("nextest", &["nextest", "run", "--profile", "default"]),
        ];
        for (name, arguments) in lanes {
            let seed = Command::new("cargo")
                .current_dir(&workspace.path)
                .args(*arguments)
                .env("CARGO_HOME", cargo_home.path())
                .env("CARGO_INCREMENTAL", "0")
                .env_remove("RUSTC_WRAPPER")
                .env_remove("RUSTC_WORKSPACE_WRAPPER")
                .output()?;
            assert!(seed.status.success(), "{name} seed failed: {seed:?}");
            fs::remove_dir_all(workspace.path.join("target"))?;
            let coverage = tempfile::tempdir()?;
            fs::set_permissions(coverage.path(), fs::Permissions::from_mode(0o700))?;
            let coverage_path = cargo_rail::utils::canonicalize_existing(coverage.path())?;
            let reused = Command::new("cargo")
                .current_dir(&workspace.path)
                .args(*arguments)
                .env("CARGO_HOME", cargo_home.path())
                .env("CARGO_INCREMENTAL", "0")
                .env("CARGO_RAIL_CACHE", "__cargo_rail_benchmark_coverage_v1")
                .env("CARGO_RAIL_BENCH_NATIVE_COVERAGE_DIRECTORY", &coverage_path)
                .env_remove("RUSTC_WRAPPER")
                .env_remove("RUSTC_WORKSPACE_WRAPPER")
                .output()?;
            assert!(
                reused.status.success(),
                "{name} executed an eligible library compiler instead of restoring it: {reused:?}"
            );
            let events = coverage_events(&coverage_path)?;
            let libraries = events
                .iter()
                .filter(|event| {
                    event["action"]["crate_name"] == "transparent_shapes"
                        && event["action"]["action_class"] == "rust_library"
                })
                .collect::<Vec<_>>();
            assert!(
                !libraries.is_empty(),
                "{name} did not observe library reuse: {events:?}"
            );
            assert!(
                libraries.iter().all(|event| event["status"] == "hit"),
                "{name}: {libraries:?}"
            );
            fs::remove_dir_all(workspace.path.join("target"))?;
        }
        Ok(())
    })();
    super::helpers::finish_test(result);
}

fn directory_snapshot(root: &Path) -> Result<BTreeMap<PathBuf, Vec<u8>>> {
    fn visit(root: &Path, current: &Path, snapshot: &mut BTreeMap<PathBuf, Vec<u8>>) -> Result<()> {
        let mut entries = fs::read_dir(current)?.collect::<Result<Vec<_>, _>>()?;
        entries.sort_unstable_by_key(fs::DirEntry::file_name);
        for entry in entries {
            let path = entry.path();
            let metadata = fs::symlink_metadata(&path)?;
            if metadata.is_dir() {
                visit(root, &path, snapshot)?;
            } else if metadata.is_file() {
                snapshot.insert(path.strip_prefix(root)?.to_path_buf(), fs::read(path)?);
            }
        }
        Ok(())
    }

    let mut snapshot = BTreeMap::new();
    visit(root, root, &mut snapshot)?;
    Ok(snapshot)
}

#[test]
fn cache_reporting_intervals_capture_cold_and_warm_production_outcomes() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("cache-reporting", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let reports = tempfile::tempdir()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "{setup:?}");
        let mut measurements = Vec::new();
        for name in ["cold", "warm"] {
            let recording = reports.path().join(format!("{name}.json"));
            let path = recording.to_str().context("report path")?;
            let started = rail(
                &workspace.path,
                cargo_home.path(),
                &["rail", "cache", "report", "--start", path, "-f", "json"],
            )?;
            assert!(started.status.success(), "{started:?}");
            if name == "warm" {
                fs::remove_dir_all(workspace.path.join("target"))?;
            }
            let compiled = Command::new("cargo")
                .current_dir(&workspace.path)
                .args(["check", "--quiet"])
                .env("CARGO_HOME", cargo_home.path())
                .env("CARGO_INCREMENTAL", "0")
                .env("CARGO_RAIL_CACHE_REPORT", &recording)
                .env_remove("RUSTC_WRAPPER")
                .env_remove("RUSTC_WORKSPACE_WRAPPER")
                .output()?;
            assert!(compiled.status.success(), "{compiled:?}");
            let finished = rail(
                &workspace.path,
                cargo_home.path(),
                &["rail", "cache", "report", "--finish", path, "-f", "json"],
            )?;
            assert!(finished.status.success(), "{finished:?}");
            let output = json(&finished)?;
            let schema: serde_json::Value =
                serde_json::from_str(include_str!("../../schemas/cache-report-v1.schema.json"))?;
            assert!(
                jsonschema::validator_for(&schema)
                    .map_err(|error| anyhow::anyhow!("invalid report schema: {error}"))?
                    .is_valid(&output)
            );
            assert_eq!(output["measurements"]["incomplete"], false, "{output}");
            assert!(fs::metadata(&recording)?.len() < 4096);
            measurements.push(output["measurements"].clone());
        }
        #[cfg(not(windows))]
        {
            assert!(
                measurements[0]["misses"].as_u64().unwrap_or_default() >= 1,
                "cold: {}",
                measurements[0]
            );
            assert!(
                measurements[1]["hits"].as_u64().unwrap_or_default() >= 1,
                "warm: {}",
                measurements[1]
            );
        }
        #[cfg(windows)]
        for measurement in &measurements {
            assert_eq!(measurement["hits"], 0);
            assert_eq!(measurement["misses"], 0);
            assert_eq!(measurement["failures"], 0);
            assert_eq!(
                measurement["bypass_reasons"]["compiler_native_input_driver_unavailable"],
                1
            );
        }
        assert_eq!(measurements[1]["misses"], 0, "report path changed cache identity");
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(target_os = "macos")]
#[test]
fn cross_windows_link_restores_the_exact_dll_pdb_and_import_library() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let workspace = TestWorkspace::new_single_crate("coff-outputs", "0.1.0")?;
        let cargo_home = tempfile::tempdir()?;
        let reports = tempfile::tempdir()?;
        let target = "x86_64-pc-windows-msvc";
        let mut rustflags = Vec::new();
        for (directory, name) in [("link", "first"), ("link-inputs", "second")] {
            let directory = workspace.path.join(directory);
            fs::create_dir(&directory)?;
            let source = directory.join("lib.rs");
            fs::write(
                &source,
                format!("#![no_std]\n#[unsafe(no_mangle)] pub extern \"C\" fn {name}() -> u32 {{ 1 }}\n"),
            )?;
            let compiled = Command::new("rustc")
                .args([
                    "--edition=2024",
                    "--crate-type=rlib",
                    "--target",
                    target,
                    "--crate-name",
                    name,
                ])
                .arg(&source)
                .arg("-o")
                .arg(directory.join(format!("{name}.lib")))
                .output()?;
            anyhow::ensure!(compiled.status.success(), "COFF input archive failed: {compiled:?}");
            rustflags.push(format!("-Lnative={}", directory.display()));
        }
        fs::write(
            workspace.path.join("Cargo.toml"),
            "[package]\nname = \"coff-outputs\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[lib]\ncrate-type = [\"cdylib\"]\n",
        )?;
        let source = workspace.path.join("src/lib.rs");
        let original_source = "#[link(name = \"first\", kind = \"static\")] unsafe extern \"C\" { fn first() -> u32; }\n\
            #[link(name = \"second\", kind = \"static\")] unsafe extern \"C\" { fn second() -> u32; }\n\
            #[unsafe(no_mangle)] pub extern \"C\" fn answer() -> u32 { unsafe { first() + second() + 42 } }\n";
        fs::write(&source, original_source)?;
        let target_directory = workspace.path.join("target").join(target);
        let build = |recording: Option<&Path>| -> Result<()> {
            let mut command = Command::new("cargo");
            command
                .current_dir(&workspace.path)
                .args(["xwin", "build", "--offline", "--quiet", "--target", target])
                .env("CARGO_HOME", cargo_home.path())
                .env("CARGO_INCREMENTAL", "0")
                .env("SOURCE_DATE_EPOCH", "0")
                .env("CARGO_TARGET_DIR", workspace.path.join("target"))
                .env_remove("RUSTC_WRAPPER")
                .env_remove("RUSTC_WORKSPACE_WRAPPER")
                .env_remove("RUSTFLAGS")
                .env("CARGO_ENCODED_RUSTFLAGS", rustflags.join("\x1f"))
                .env_remove("CARGO_RAIL_CACHE")
                .env_remove("CARGO_RAIL_CACHE_REPORT")
                .env_remove("LLD_REPRODUCE");
            if let Some(recording) = recording {
                command.env("CARGO_RAIL_CACHE_REPORT", recording);
            }
            let output = command
                .output()
                .context("run cargo-xwin using the already provisioned MSVC SDK")?;
            anyhow::ensure!(
                output.status.success(),
                "cross-Windows Cargo build failed; provision cargo-xwin, lld-link and its cached MSVC SDK before this lane: {}",
                String::from_utf8_lossy(&output.stderr)
            );
            Ok(())
        };
        let outputs = || -> Result<BTreeMap<PathBuf, (Vec<u8>, u32)>> {
            let mut result = BTreeMap::new();
            for entry in fs::read_dir(target_directory.join("debug/deps"))? {
                let entry = entry?;
                let path = entry.path();
                if matches!(
                    path.extension().and_then(std::ffi::OsStr::to_str),
                    Some("dll" | "pdb" | "lib")
                ) {
                    result.insert(
                        PathBuf::from(entry.file_name()),
                        (fs::read(&path)?, fs::metadata(&path)?.permissions().mode() & 0o777),
                    );
                }
            }
            anyhow::ensure!(
                result.len() == 3,
                "expected exactly the DLL, PDB and import library, observed {:?}",
                result.keys().collect::<Vec<_>>()
            );
            Ok(result)
        };
        build(None).context("uncached upstream Windows link must succeed before cache qualification")?;
        let baseline = outputs()?;
        assert!(
            baseline
                .keys()
                .any(|path| path.extension().is_some_and(|extension| extension == "pdb"))
        );
        assert!(baseline.keys().any(|path| path.to_string_lossy().ends_with(".dll.lib")));
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "COFF cache setup failed: {setup:?}");
        let mut cold_outputs = None;
        for (phase, hits, misses) in [("cold", 0, 1), ("warm", 1, 0), ("source-change", 0, 1)] {
            if phase == "source-change" {
                fs::write(&source, original_source.replace("42", "43"))?;
            }
            fs::remove_dir_all(&target_directory)?;
            let recording = reports.path().join(format!("{phase}.json"));
            let path = recording.to_str().context("COFF report path")?;
            let start = rail(
                &workspace.path,
                cargo_home.path(),
                &["rail", "cache", "report", "--start", path],
            )?;
            assert!(start.status.success(), "{phase} recording failed: {start:?}");
            build(Some(&recording))?;
            let finish = rail(
                &workspace.path,
                cargo_home.path(),
                &["rail", "cache", "report", "--finish", path, "-f", "json"],
            )?;
            assert!(finish.status.success(), "{phase} reporting failed: {finish:?}");
            let report = json(&finish)?;
            assert_eq!(report["measurements"]["hits"], hits, "{phase}: {report}");
            assert_eq!(report["measurements"]["misses"], misses, "{phase}: {report}");
            assert!(
                report["measurements"]["bypass_reasons"]
                    .as_object()
                    .context("COFF bypass reasons")?
                    .keys()
                    .all(|reason| matches!(
                        reason.as_str(),
                        "compiler_information_request" | "compiler_stdin_observation_unavailable"
                    )),
                "{phase} bypassed a compiler action: {report}"
            );
            assert_eq!(report["measurements"]["failures"], 0, "{phase}: {report}");
            let current = outputs()?;
            if phase == "cold" {
                assert_eq!(
                    current.keys().collect::<Vec<_>>(),
                    baseline.keys().collect::<Vec<_>>(),
                    "instrumentation changed the ordinary output set"
                );
                for (name, (_, mode)) in &baseline {
                    assert_eq!(
                        current.get(name).map(|(_, current_mode)| current_mode),
                        Some(mode),
                        "instrumentation changed mode for {}",
                        name.display()
                    );
                    if name.to_string_lossy().ends_with(".dll.lib") {
                        assert_eq!(
                            current.get(name),
                            baseline.get(name),
                            "instrumentation changed the deterministic import library"
                        );
                    }
                }
                cold_outputs = Some(current);
            } else if phase == "warm" {
                assert_eq!(
                    Some(current),
                    cold_outputs,
                    "warm restore changed COFF output bytes or modes"
                );
            } else {
                assert_ne!(
                    Some(current),
                    cold_outputs,
                    "same-size source mutation did not change linked outputs"
                );
            }
        }
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(target_os = "macos")]
#[test]
fn packed_apple_debug_outputs_run_the_compiler_until_the_complete_tree_is_owned() {
    let result: Result<()> = (|| {
        let workspace = TestWorkspace::new_single_crate("apple-debug-outputs", "0.1.0")?;
        let manifest = workspace.path.join("Cargo.toml");
        fs::write(
            &manifest,
            format!(
                "{}\n[profile.dev]\nsplit-debuginfo = \"packed\"\n",
                fs::read_to_string(&manifest)?
            ),
        )?;
        fs::remove_file(workspace.path.join("src/lib.rs"))?;
        fs::write(
            workspace.path.join("src/main.rs"),
            "fn main() { println!(\"debug outputs\"); }\n",
        )?;
        let version = Command::new("rustc").arg("-vV").output()?;
        assert!(version.status.success(), "rustc prerequisite failed: {version:?}");
        let verbose = String::from_utf8(version.stdout)?;
        let host = verbose
            .lines()
            .find_map(|line| line.strip_prefix("host: "))
            .context("rustc host")?;
        let cargo_home = tempfile::tempdir()?;
        let reports = tempfile::tempdir()?;
        explicit_target_cargo(&workspace.path, cargo_home.path(), "build", host, None)?;
        let target = workspace.path.join("target").join(host);
        let baseline = directory_snapshot(&target.join("debug/deps"))?;
        let auxiliary_names = baseline
            .keys()
            .filter(|path| {
                path.extension().is_some_and(|extension| extension == "o")
                    || path
                        .components()
                        .any(|part| part.as_os_str().to_string_lossy().ends_with(".dSYM"))
            })
            .cloned()
            .collect::<BTreeSet<_>>();
        assert!(
            !auxiliary_names.is_empty(),
            "upstream packed debug build emitted no separate debug artifacts: {:?}",
            baseline.keys().collect::<Vec<_>>()
        );
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "debug cache setup failed: {setup:?}");
        fs::remove_dir_all(&target)?;
        let recording = reports.path().join("debug.json");
        let path = recording.to_str().context("debug report path")?;
        let start = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "report", "--start", path],
        )?;
        assert!(start.status.success(), "debug report start failed: {start:?}");
        explicit_target_cargo(&workspace.path, cargo_home.path(), "build", host, Some(&recording))?;
        let finish = rail(
            &workspace.path,
            cargo_home.path(),
            &["rail", "cache", "report", "--finish", path, "-f", "json"],
        )?;
        assert!(finish.status.success(), "debug report finish failed: {finish:?}");
        let report = json(&finish)?;
        assert_eq!(report["measurements"]["hits"], 0, "{report}");
        assert_eq!(report["measurements"]["misses"], 0, "{report}");
        assert!(
            report["measurements"]["bypass_reasons"]
                .as_object()
                .context("debug bypass reasons")?
                .keys()
                .all(|reason| matches!(
                    reason.as_str(),
                    "compiler_information_request"
                        | "compiler_stdin_observation_unavailable"
                        | "compiler_debug_output_evidence_unavailable"
                )),
            "unexpected debug bypass: {report}"
        );
        assert_eq!(
            report["measurements"]["bypass_reasons"]["compiler_debug_output_evidence_unavailable"], 1,
            "{report}"
        );
        let current = directory_snapshot(&target.join("debug/deps"))?;
        for name in auxiliary_names {
            assert!(
                current.get(&name).is_some_and(|bytes| !bytes.is_empty()),
                "ordinary compiler lost debug output {}",
                name.display()
            );
        }
        let output = Command::new(target.join("debug/apple-debug-outputs")).output()?;
        assert!(output.status.success(), "debug executable failed: {output:?}");
        assert_eq!(output.stdout, b"debug outputs\n");
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(target_os = "macos")]
#[test]
fn coff_adapter_preserves_exact_outputs_with_windows_response_arguments() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let fixture = tempfile::tempdir()?;
        let directory = fs::canonicalize(fixture.path())?.join("COFF response fixture");
        fs::create_dir(&directory)?;
        let driver = std::env::split_paths(&std::env::var_os("PATH").context("linker PATH")?)
            .map(|directory| directory.join("lld-link"))
            .find(|path| path.is_file())
            .context("lld-link must be provisioned before this explicit local contract")?;
        let source = directory.join("source.c");
        let object = directory.join("source object.obj");
        fs::write(&source, "__declspec(dllexport) int answer(void) { return 42; }\n")?;
        let compiled = Command::new("clang")
            .args(["--target=x86_64-pc-windows-msvc", "-gcodeview", "-c"])
            .arg(&source)
            .arg("-o")
            .arg(&object)
            .output()?;
        assert!(
            compiled.status.success(),
            "COFF object prerequisite failed: {compiled:?}"
        );
        let dll = directory.join("fixture.dll");
        let pdb = directory.join("fixture.pdb");
        let library = directory.join("fixture.dll.lib");
        let response = directory.join("original arguments.rsp");
        fs::write(
            &response,
            format!(
                "/dll\n/noentry\n/debug\n/out:\"{}\"\n/pdb:\"{}\"\n/implib:\"{}\"\n\"{}\"\n",
                dll.display(),
                pdb.display(),
                library.display(),
                object.display()
            ),
        )?;
        let argument = format!("@{}", response.display());
        let baseline = Command::new(&driver)
            .arg(&argument)
            .current_dir(&directory)
            .env("SOURCE_DATE_EPOCH", "0")
            .env_remove("LLD_REPRODUCE")
            .env_remove("LINK")
            .env_remove("_LINK_")
            .output()?;
        assert!(baseline.status.success(), "ordinary COFF linker failed: {baseline:?}");
        let mut expected = BTreeMap::new();
        for path in [&dll, &pdb, &library] {
            expected.insert(
                path.clone(),
                (fs::read(path)?, fs::metadata(path)?.permissions().mode() & 0o777),
            );
            fs::remove_file(path)?;
        }
        let evidence = directory.join("coff-linker-driver-inputs.json");
        let archive = directory.join("coff-linker-inputs.tar");
        let mut command = Command::new(crate::helpers::cargo_binary("cargo-rail"));
        for (name, _) in std::env::vars_os() {
            if name.to_str().is_some_and(|name| name.starts_with("CARGO_RAIL_")) {
                command.env_remove(name);
            }
        }
        let observed = command
            .arg(argument)
            .current_dir(&directory)
            .env("SOURCE_DATE_EPOCH", "0")
            .env("CARGO_RAIL_COFF_LINK_ADAPTER", "1")
            .env("CARGO_RAIL_COFF_LINK_DRIVER", &driver)
            .env("CARGO_RAIL_COFF_LINK_ARCHIVE", &archive)
            .env("CARGO_RAIL_COFF_LINK_EVIDENCE", &evidence)
            .env_remove("LLD_REPRODUCE")
            .env_remove("LINK")
            .env_remove("_LINK_")
            .output()?;
        assert_eq!(observed.status.code(), baseline.status.code(), "{observed:?}");
        assert_eq!(observed.stdout, baseline.stdout);
        assert_eq!(observed.stderr, baseline.stderr);
        for (path, (bytes, mode)) in expected {
            assert!(fs::read(&path)? == bytes, "adapter changed {}", path.display());
            assert_eq!(fs::metadata(&path)?.permissions().mode() & 0o777, mode);
        }
        let evidence: serde_json::Value = serde_json::from_slice(&fs::read(evidence)?)?;
        assert_eq!(evidence["completed"], true, "{evidence}");
        assert_eq!(
            evidence["response_files"].as_array().map(Vec::len),
            Some(1),
            "{evidence}"
        );
        assert!(fs::metadata(archive)?.len() > fs::metadata(object)?.len());
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(target_os = "macos")]
#[test]
fn unpacked_debug_objects_restore_exactly_and_remain_bound_to_the_output_directory() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let workspace = TestWorkspace::new_single_crate("unpacked-debug", "0.1.0")?;
        let manifest = workspace.path.join("Cargo.toml");
        fs::write(
            &manifest,
            format!(
                "{}\n[profile.dev]\nsplit-debuginfo = \"unpacked\"\n",
                fs::read_to_string(&manifest)?
            ),
        )?;
        fs::write(workspace.path.join("src/lib.rs"), "pub fn answer() -> u64 { 41 }\n")?;
        let version = Command::new("rustc").arg("-vV").output()?;
        assert!(version.status.success(), "rustc prerequisite failed: {version:?}");
        let verbose = String::from_utf8(version.stdout)?;
        let host = verbose
            .lines()
            .find_map(|line| line.strip_prefix("host: "))
            .context("rustc host")?;
        let cargo_home = tempfile::tempdir()?;
        explicit_target_cargo(&workspace.path, cargo_home.path(), "build", host, None)?;
        let target = workspace.path.join("target").join(host);
        let outputs = target.join("debug/deps");
        let baseline = directory_snapshot(&outputs)?;
        let objects = baseline
            .keys()
            .filter(|name| name.to_string_lossy().ends_with(".rcgu.o"))
            .collect::<Vec<_>>();
        assert_eq!(
            objects.len(),
            1,
            "upstream separate object inventory: {:?}",
            baseline.keys()
        );
        let modes = baseline
            .keys()
            .map(|name| {
                Ok((
                    name.clone(),
                    fs::metadata(outputs.join(name))?.permissions().mode() & 0o777,
                ))
            })
            .collect::<Result<BTreeMap<_, _>>>()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "unpacked cache setup failed: {setup:?}");
        let reports = tempfile::tempdir()?;
        for (phase, hits) in [("cold", 0), ("warm", 1)] {
            fs::remove_dir_all(&target)?;
            let recording = reports.path().join(format!("{phase}.json"));
            let path = recording.to_str().context("report path")?;
            let start = rail(
                &workspace.path,
                cargo_home.path(),
                &["rail", "cache", "report", "--start", path],
            )?;
            assert!(start.status.success(), "report start failed: {start:?}");
            explicit_target_cargo(&workspace.path, cargo_home.path(), "build", host, Some(&recording))?;
            let finish = rail(
                &workspace.path,
                cargo_home.path(),
                &["rail", "cache", "report", "--finish", path, "-f", "json"],
            )?;
            assert!(finish.status.success(), "report finish failed: {finish:?}");
            let report = json(&finish)?;
            assert_eq!(report["measurements"]["hits"], hits, "{phase}: {report}");
            assert_eq!(report["measurements"]["misses"], 1 - hits, "{phase}: {report}");
            assert_eq!(report["measurements"]["failures"], 0, "{phase}: {report}");
            assert_eq!(
                directory_snapshot(&outputs)?,
                baseline,
                "{phase} changed or omitted an upstream compiler output"
            );
            for (name, mode) in &modes {
                assert_eq!(
                    fs::metadata(outputs.join(name))?.permissions().mode() & 0o777,
                    *mode,
                    "{phase} mode of {}",
                    name.display()
                );
            }
        }
        let moved_target = workspace.path.join("target/moved");
        let moved = Command::new("cargo")
            .current_dir(&workspace.path)
            .args(["build", "--offline", "--quiet", "--target", host])
            .env("CARGO_HOME", cargo_home.path())
            .env("CARGO_TARGET_DIR", &moved_target)
            .env("CARGO_INCREMENTAL", "0")
            .env_remove("RUSTC_WRAPPER")
            .env_remove("RUSTC_WORKSPACE_WRAPPER")
            .env_remove("CARGO_BUILD_RUSTC_WRAPPER")
            .env_remove("CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER")
            .env_remove("RUSTFLAGS")
            .env_remove("CARGO_ENCODED_RUSTFLAGS")
            .output()?;
        assert!(moved.status.success(), "moved unpacked build failed: {moved:?}");
        let moved_status = selected_profile_status(&workspace.path, cargo_home.path())?;
        let usage = &moved_status["status"]["installation"]["usage"];
        assert_eq!(
            usage["hits"], 1,
            "separate debug objects crossed output directories: {usage}"
        );
        assert_eq!(
            usage["misses"], 2,
            "moved debug build did not compile its own objects: {usage}"
        );
        assert_eq!(
            directory_snapshot(&outputs)?,
            baseline,
            "moved build changed the original debug objects"
        );
        fs::remove_dir_all(&target)?;
        fs::write(workspace.path.join("src/lib.rs"), "pub fn answer() -> u64 { 42 }\n")?;
        explicit_target_cargo(&workspace.path, cargo_home.path(), "build", host, None)?;
        let changed = selected_profile_status(&workspace.path, cargo_home.path())?;
        let usage = &changed["status"]["installation"]["usage"];
        assert_eq!(usage["hits"], 1, "changed source restored stale debug objects: {usage}");
        assert_eq!(usage["misses"], 3, "changed source did not cause a miss: {usage}");
        assert_ne!(
            fs::read(outputs.join(objects[0]))?,
            baseline[objects[0]],
            "changed code retained stale separate debug bytes"
        );
        Ok(())
    })();
    super::helpers::finish_test(result);
}

#[cfg(target_os = "macos")]
#[test]
fn external_macho_order_file_invalidates_reuse_without_changing_source() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;

        let linker = std::env::split_paths(&std::env::var_os("PATH").context("linker PATH")?)
            .map(|directory| directory.join("ld64.lld"))
            .find(|path| path.is_file())
            .context("install ld64.lld and put it on PATH before running the Mach-O linker contract")?;
        let workspace = TestWorkspace::new_single_crate("order-control", "0.1.0")?;
        let external = tempfile::tempdir()?;
        let external_root = fs::canonicalize(external.path())?;
        let order_file = external_root.join("symbols.order");
        let clang_config = external_root.join("clang.cfg");
        fs::write(
            &clang_config,
            format!(
                "-fuse-ld={}\n-Wl,-platform_version,macos,11.0,11.0\n-Wl,-order_file,{}\n",
                linker.display(),
                order_file.display()
            ),
        )?;
        fs::remove_file(workspace.path.join("src/lib.rs"))?;
        fs::write(
            workspace.path.join("src/main.rs"),
            "#![no_std]\n#![no_main]\n\
             #[panic_handler]\nfn panic(_: &core::panic::PanicInfo) -> ! { loop {} }\n\
             #[unsafe(no_mangle)]\n#[inline(never)]\npub extern \"C\" fn first() -> u64 { 41 }\n\
             #[unsafe(no_mangle)]\n#[inline(never)]\npub extern \"C\" fn second() -> u64 { 42 }\n\
             #[unsafe(no_mangle)]\npub extern \"C\" fn main() -> i32 { (first() + second() - 83) as i32 }\n",
        )?;
        let version = Command::new("rustc").arg("-vV").output()?;
        assert!(version.status.success(), "rustc prerequisite failed: {version:?}");
        let verbose = String::from_utf8(version.stdout)?;
        let host = verbose
            .lines()
            .find_map(|line| line.strip_prefix("host: "))
            .context("rustc host")?;
        fs::create_dir(workspace.path.join(".cargo"))?;
        fs::write(
            workspace.path.join(".cargo/config.toml"),
            format!(
                "[target.{host}]\nlinker = \"/usr/bin/clang\"\nrustflags = [{}]\n\
                 [profile.dev]\nsplit-debuginfo = \"off\"\npanic = \"abort\"\n",
                serde_json::to_string(&format!("-Clink-arg=--config={}", clang_config.display()))?
            ),
        )?;
        let cargo_home = tempfile::tempdir()?;
        let target = workspace.path.join("target").join(host);
        let executable = target.join("debug/order-control");
        let orders = ["_first\n_second\n", "_second\n_first\n"];
        assert_eq!(orders[0].len(), orders[1].len(), "order mutation must retain file size");
        let mut baselines = Vec::new();
        for order in orders {
            fs::write(&order_file, order)?;
            if target.exists() {
                fs::remove_dir_all(&target)?;
            }
            explicit_target_cargo(&workspace.path, cargo_home.path(), "build", host, None)?;
            let run = Command::new(&executable).output()?;
            assert!(run.status.success(), "uncached executable failed: {run:?}");
            assert!(run.stdout.is_empty());
            assert!(run.stderr.is_empty());
            baselines.push((
                fs::read(&executable)?,
                fs::metadata(&executable)?.permissions().mode() & 0o777,
            ));
        }
        assert_ne!(
            baselines[0].0, baselines[1].0,
            "order-file fixture did not change the independently linked executable"
        );
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "order-file cache setup failed: {setup:?}");
        let reports = tempfile::tempdir()?;
        for (phase, order_index, hits, misses) in [("cold", 0, 0, 1), ("warm", 0, 1, 0), ("changed-order", 1, 0, 1)] {
            if phase != "warm" {
                fs::write(&order_file, orders[order_index])?;
            }
            fs::remove_dir_all(&target)?;
            let recording = reports.path().join(format!("{phase}.json"));
            let path = recording.to_str().context("report path")?;
            let start = rail(
                &workspace.path,
                cargo_home.path(),
                &["rail", "cache", "report", "--start", path],
            )?;
            assert!(start.status.success(), "report start failed: {start:?}");
            explicit_target_cargo(&workspace.path, cargo_home.path(), "build", host, Some(&recording))?;
            let finish = rail(
                &workspace.path,
                cargo_home.path(),
                &["rail", "cache", "report", "--finish", path, "-f", "json"],
            )?;
            assert!(finish.status.success(), "report finish failed: {finish:?}");
            let report = json(&finish)?;
            assert_eq!(report["measurements"]["hits"], hits, "{phase}: {report}");
            assert_eq!(report["measurements"]["misses"], misses, "{phase}: {report}");
            assert_eq!(report["measurements"]["failures"], 0, "{phase}: {report}");
            assert_eq!(
                fs::read(&executable)?,
                baselines[order_index].0,
                "{phase} did not preserve uncached linker output"
            );
            assert_eq!(
                fs::metadata(&executable)?.permissions().mode() & 0o777,
                baselines[order_index].1,
                "{phase} changed executable permissions"
            );
        }
        Ok(())
    })();
    super::helpers::finish_test(result);
}

/// Qualify native reuse with tiny, dependency-free Cargo workloads on each host.
#[cfg(unix)]
#[test]
fn native_host_restores_and_executes_small_cargo_outputs() {
    let result: Result<()> = (|| {
        use std::os::unix::fs::PermissionsExt as _;
        let workspace = TestWorkspace::new_single_crate("cache_host", "0.1.0")?;
        fs::write(
            workspace.path.join("Cargo.toml"),
            r#"[package]
name = "cache_host"
version = "0.1.0"
edition = "2024"
[workspace]
members = ["macros", "consumer"]
resolver = "3"
"#,
        )?;
        fs::write(
            workspace.path.join("build.rs"),
            r#"fn main() {
    std::fs::write(std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap()).join("value.rs"),
                   "pub fn value() -> u32 { 42 }").unwrap();
}"#,
        )?;
        fs::write(
            workspace.path.join("src/lib.rs"),
            r#"include!(concat!(env!("OUT_DIR"), "/value.rs"));"#,
        )?;
        fs::write(
            workspace.path.join("src/main.rs"),
            r#"fn main() { println!("{}", cache_host::value()); }"#,
        )?;
        for directory in ["macros/src", "consumer/src"] {
            fs::create_dir_all(workspace.path.join(directory))?;
        }
        fs::write(
            workspace.path.join("macros/Cargo.toml"),
            r#"[package]
name = "host_macros"
version = "0.1.0"
edition = "2024"
[lib]
proc-macro = true
"#,
        )?;
        fs::write(
            workspace.path.join("macros/src/lib.rs"),
            r#"extern crate proc_macro;
#[proc_macro]
pub fn answer(_: proc_macro::TokenStream) -> proc_macro::TokenStream { "42".parse().unwrap() }
"#,
        )?;
        fs::write(
            workspace.path.join("consumer/Cargo.toml"),
            r#"[package]
name = "host_consumer"
version = "0.1.0"
edition = "2024"
[dependencies]
host_macros = { path = "../macros" }
"#,
        )?;
        fs::write(
            workspace.path.join("consumer/src/lib.rs"),
            "pub fn value() -> u32 { host_macros::answer!() }\n",
        )?;
        let cargo_home = tempfile::tempdir()?;
        let target = workspace.path.join("target");
        let compile = |coverage: Option<&Path>| -> Result<Output> {
            let mut command = Command::new("cargo");
            command
                .current_dir(&workspace.path)
                .args(["build", "--workspace", "--quiet"])
                .env("CARGO_HOME", cargo_home.path())
                .env("CARGO_INCREMENTAL", "0")
                .env_remove("RUSTC_WRAPPER")
                .env_remove("RUSTC_WORKSPACE_WRAPPER")
                .env_remove("CARGO_BUILD_RUSTC_WRAPPER");
            if let Some(coverage) = coverage {
                command
                    .env("CARGO_RAIL_CACHE", "__cargo_rail_benchmark_coverage_v1")
                    .env("CARGO_RAIL_BENCH_NATIVE_COVERAGE_DIRECTORY", coverage);
            } else {
                command.env("CARGO_RAIL_CACHE", "off");
            }
            Ok(command.output()?)
        };
        let baseline = compile(None)?;
        assert!(baseline.status.success(), "uncached build failed: {baseline:?}");
        let executable = target.join("debug/cache_host");
        let artifacts = || -> Result<BTreeMap<PathBuf, (Vec<u8>, u32)>> {
            directory_snapshot(&target)?
                .into_iter()
                .filter(|(path, _)| {
                    matches!(
                        path.extension().and_then(|value| value.to_str()),
                        Some("rlib" | "rmeta" | "so" | "dylib")
                    ) || path == Path::new("debug/cache_host")
                        || path.file_name().is_some_and(|name| name == "build-script-build")
                })
                .map(|(path, bytes)| {
                    let mode = fs::metadata(target.join(&path))?.permissions().mode();
                    Ok((path, (bytes, mode)))
                })
                .collect()
        };
        let expected = artifacts()?;
        let setup = rail(&workspace.path, cargo_home.path(), &["rail", "cache", "setup"])?;
        assert!(setup.status.success(), "cache setup failed: {setup:?}");
        for (phase, expected_status) in [("cold", "miss"), ("warm", "hit")] {
            fs::remove_dir_all(&target)?;
            let coverage = tempfile::tempdir()?;
            fs::set_permissions(coverage.path(), fs::Permissions::from_mode(0o700))?;
            let coverage_path = cargo_rail::utils::canonicalize_existing(coverage.path())?;
            let output = compile(Some(&coverage_path))?;
            assert!(output.status.success(), "{phase} build failed: {output:?}");
            eprintln!(
                "{phase} compiler diagnostics:\n{}",
                String::from_utf8_lossy(&output.stderr)
            );
            let events = coverage_events(&coverage_path)?;
            for (crate_name, action_class) in [
                ("cache_host", "rust_library"),
                ("cache_host", "binary"),
                ("host_macros", "proc_macro_producer"),
                ("build_script_build", "build_script"),
            ] {
                let actions = events
                    .iter()
                    .filter(|event| {
                        event["action"]["crate_name"] == crate_name && event["action"]["action_class"] == action_class
                    })
                    .collect::<Vec<_>>();
                assert!(
                    !actions.is_empty(),
                    "{phase}: missing {crate_name}/{action_class}: {events:?}"
                );
                assert!(
                    actions.iter().all(|event| event["status"] == expected_status),
                    "{phase}: incorrect {crate_name}/{action_class} reuse: {actions:?}"
                );
            }
            assert!(
                events.iter().any(|event| event["status"] == "bypassed"
                    && event["reason"] == "dynamic_dependency_execution_observation_unavailable"),
                "{phase}: proc-macro consumer must retain safe bypass: {events:?}"
            );
            assert!(
                artifacts()? == expected,
                "{phase}: output inventory, bytes or modes changed"
            );
            let executed = Command::new(&executable).output()?;
            assert!(
                executed.status.success(),
                "{phase}: restored executable failed: {executed:?}"
            );
            assert_eq!(executed.stdout, b"42\n");
            assert!(executed.stderr.is_empty());
        }
        Ok(())
    })();
    super::helpers::finish_test(result);
}