rch 2.1.25

Remote Compilation Helper - PreToolUse hook CLI
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
//! Remote cargo target-dir resolution / naming / command-rewrite for the hook.
//!
//! This submodule owns the logic that decides *where* a remote cargo build writes
//! its artifacts and *how* the delegated command is reshaped so the worker uses
//! that location, extracted from `hook.rs` per bead
//! `remote_compilation_helper-zcecy.14`:
//!
//! - **`CARGO_TARGET_DIR` forwarding** — [`resolve_forwarded_cargo_target_dir`]
//!   (and its lookup-injected core [`resolve_forwarded_cargo_target_dir_with_lookup`])
//!   decide whether the agent asked for a specific local target dir (via the
//!   environment or the delegated command tokens) so the artifacts can be synced
//!   back there, plus [`cargo_target_env_allowlist`] / [`cargo_target_env_overrides`]
//!   that thread `CARGO_TARGET_DIR` through the worker env.
//! - **Remote target-dir naming** — [`remote_cargo_target_dir_name`] (unique
//!   per-job) and [`remote_cargo_pooled_target_dir_name`] (the stable, cache-warm
//!   pooled name keyed on toolchain/triple/profile/feature-set), with
//!   [`sanitize_cargo_home_token`] producing the path-safe segment they share.
//!   [`target_reuse_disabled`] selects between the two; [`stale_target_reap_idle_hours`]
//!   tunes the abandoned-per-job-dir reaper.
//! - **Command rewriting** — [`rewrite_cargo_target_dir_command_for_remote`] strips
//!   any local `CARGO_TARGET_DIR` / `--target-dir` from the command before remote
//!   execution (so the worker-scoped dir is injected instead), built on the
//!   token-level [`strip_cargo_target_dir_assignments_from_command_tokens`],
//!   [`strip_cargo_target_dir_flags_from_command_tokens`], and
//!   [`extract_cargo_target_dir_from_command_tokens`] helpers.
//!
//! It reaches its support layer from the parent via `use super::*`: `HookReporter`,
//! the `rch_common` types (`CompilationKind`, `WorkerId`, `ToolchainInfo`,
//! `pooled_target_key::*`), the `RCH_DISABLE_TARGET_REUSE_ENV` const, and the
//! parent helpers `parse_command_tokens` / `join_exec_command`. `detect_target_label`
//! is imported directly from the sibling `super::formatting` module.
//!
//! Items consumed by the parent (`run_hook` / `run_exec` call
//! `resolve_forwarded_cargo_target_dir` + `rewrite_cargo_target_dir_command_for_remote`,
//! and `add_cargo_isolation` shares `sanitize_cargo_home_token`) are re-exported
//! into `hook`; the sibling `transfer_orchestration` imports the six dir-naming /
//! env helpers it needs directly from `super::cargo_target_dir`. The remaining
//! `pub(super)` items are reached only by the hook test suite (which imports them
//! into `hook::tests`). Four helpers used solely within this cluster
//! (`env_allowlist_contains`, `cargo_kind_uses_target_dir`,
//! `default_host_target_triple`, `skip_env_option_prefix`) stay private.

use super::formatting::detect_target_label;
use super::*;
use std::collections::HashMap;

fn env_allowlist_contains(env_allowlist: &[String], key: &str) -> bool {
    env_allowlist
        .iter()
        .map(|item| item.trim())
        .any(|item| item == key)
}

fn cargo_kind_uses_target_dir(kind: Option<CompilationKind>) -> bool {
    matches!(
        kind,
        Some(
            CompilationKind::CargoBuild
                | CompilationKind::CargoCheck
                | CompilationKind::CargoClippy
                | CompilationKind::CargoDoc
                | CompilationKind::CargoTest
                | CompilationKind::CargoNextest
                | CompilationKind::CargoBench
                // Zigbuild writes into CARGO_TARGET_DIR exactly like a plain
                // build; omitting it here left the forwarded target dir (and
                // its sync-back) disengaged, so cross-built binaries stayed in
                // the worker's default .rch-target and never came home (hfdt
                // aarch64 release leg, 2026-08-06 — same class as the
                // command_uses_cargo_dependency_graph omission).
                | CompilationKind::CargoZigbuild,
        )
    )
}

pub(super) fn resolve_forwarded_cargo_target_dir_with_lookup<F>(
    kind: Option<CompilationKind>,
    invocation_cwd: &Path,
    reporter: &HookReporter,
    mut lookup_env: F,
    command_tokens: Option<&[String]>,
) -> Option<PathBuf>
where
    F: FnMut(&str) -> Option<String>,
{
    if !cargo_kind_uses_target_dir(kind) {
        return None;
    }

    let raw = command_tokens
        .and_then(|tokens| {
            extract_cargo_target_dir_from_command_tokens(tokens).inspect(|_| {
                reporter.verbose(
                    "[RCH] CARGO_TARGET_DIR forwarding detected from delegated command tokens",
                );
            })
        })
        .or_else(|| {
            lookup_env("CARGO_TARGET_DIR").inspect(|_| {
                reporter.verbose("[RCH] CARGO_TARGET_DIR forwarding detected from environment");
            })
        });

    let resolved = raw.and_then(|value| {
        let trimmed = value.trim();
        if trimmed.is_empty() {
            reporter.verbose("[RCH] CARGO_TARGET_DIR is empty; using default Cargo target dir");
            return None;
        }

        let requested = PathBuf::from(trimmed);
        Some(if requested.is_absolute() {
            requested
        } else {
            invocation_cwd.join(requested)
        })
    });

    let resolved = resolved.unwrap_or_else(|| invocation_cwd.join("target"));

    reporter.verbose(&format!(
        "[RCH] Cargo target sync active; forcing worker CARGO_TARGET_DIR to an isolated remote target and syncing back to {}",
        resolved.display()
    ));
    Some(resolved)
}

pub(super) fn resolve_forwarded_cargo_target_dir(
    kind: Option<CompilationKind>,
    invocation_cwd: &Path,
    reporter: &HookReporter,
    command_tokens: Option<&[String]>,
) -> Option<PathBuf> {
    resolve_forwarded_cargo_target_dir_with_lookup(
        kind,
        invocation_cwd,
        reporter,
        |key| std::env::var(key).ok(),
        command_tokens,
    )
}

pub(super) fn cargo_target_env_allowlist(
    env_allowlist: &[String],
    cargo_target_sync: bool,
) -> Vec<String> {
    let mut effective = env_allowlist.to_vec();
    if cargo_target_sync && !env_allowlist_contains(&effective, "CARGO_TARGET_DIR") {
        effective.push("CARGO_TARGET_DIR".to_string());
    }
    effective
}

pub(super) fn cargo_target_env_overrides(
    local_target_dir: Option<&Path>,
) -> Option<HashMap<String, String>> {
    let local_target_dir = local_target_dir?;
    let mut overrides = HashMap::new();
    overrides.insert(
        "CARGO_TARGET_DIR".to_string(),
        local_target_dir.to_string_lossy().to_string(),
    );
    Some(overrides)
}

/// Reduce an arbitrary token to a path-safe basename component: ASCII
/// alphanumerics, `-` and `_` are kept; everything else collapses to `-`,
/// leading/trailing `-` are trimmed, and an empty result falls back to
/// `"worker"`. Shared by the per-job target dir and isolated CARGO_HOME naming.
pub(super) fn sanitize_cargo_home_token(token: &str) -> String {
    let safe = token
        .chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
                ch
            } else {
                '-'
            }
        })
        .collect::<String>();
    let safe = safe.trim_matches('-');
    if safe.is_empty() {
        "worker".to_string()
    } else {
        safe.to_string()
    }
}

pub(super) fn remote_cargo_target_dir_name(build_id: Option<u64>, worker_id: &WorkerId) -> String {
    static REMOTE_CARGO_TARGET_DIR_SEQUENCE: std::sync::atomic::AtomicU64 =
        std::sync::atomic::AtomicU64::new(0);

    let safe_worker_id = sanitize_cargo_home_token(worker_id.as_str());
    let job_id = build_id
        .map(|id| format!("job-{id}"))
        .unwrap_or_else(|| format!("pid-{}", std::process::id()));
    let timestamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let sequence =
        REMOTE_CARGO_TARGET_DIR_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);

    format!(".rch-target-{safe_worker_id}-{job_id}-{timestamp}-{sequence}")
}

/// Whether remote target-dir REUSE is disabled via [`RCH_DISABLE_TARGET_REUSE_ENV`].
/// Any non-empty value other than `0`/`false`/`no`/`off` (case-insensitive) opts out.
pub(super) fn target_reuse_disabled() -> bool {
    target_reuse_disabled_from_value(std::env::var(RCH_DISABLE_TARGET_REUSE_ENV).ok())
}

/// Pure predicate behind [`target_reuse_disabled`] (env value injected so it is
/// unit-testable under `#![forbid(unsafe_code)]`, where `set_var` is unusable).
pub(super) fn target_reuse_disabled_from_value(value: Option<String>) -> bool {
    value
        .map(|v| {
            let v = v.trim().to_ascii_lowercase();
            !v.is_empty() && v != "0" && v != "false" && v != "no" && v != "off"
        })
        .unwrap_or(false)
}

/// The Rust target triple this build will compile for: an explicit `--target`
/// or inline `--config build.target=...` wins, otherwise the host default the
/// binary was built for (`std::env::consts`-derived). This is a pooled-dir cache
/// DIMENSION — a cross-compile must not share a host build's pool.
pub(super) fn target_triple_for_command(command: &str) -> String {
    explicit_target_triple_for_command(command).unwrap_or_else(default_host_target_triple)
}

/// The target pinned by Cargo's own arguments, not arguments after `--`.
/// An explicit `--target` outranks inline `--config build.target=...`; repeated
/// string config overrides are applied left-to-right, as in Cargo. This does
/// not resolve config files, environment defaults, or multi-target arrays.
///
/// GitHub #68: ignoring inline build.target misclassified worker-host proc
/// macros as foreign target output, and also selected the wrong pooled cache.
pub(super) fn explicit_target_triple_for_command(command: &str) -> Option<String> {
    let (tokens, cargo_index) = cargo_command_tokens(command).ok()?;
    let mut iter = tokens[cargo_index + 1..].iter();
    let mut configured_target = None;
    while let Some(token) = iter.next() {
        if token == "--" {
            break;
        }
        if let Some(value) = token.strip_prefix("--target=") {
            if !value.is_empty() {
                return Some(value.to_string());
            }
        } else if token == "--target" {
            if let Some(value) = iter.next().filter(|value| !value.is_empty()) {
                return Some(value.to_string());
            }
        } else {
            let config = if token == "--config" {
                iter.next().map(String::as_str)
            } else {
                token.strip_prefix("--config=")
            };
            if let Some(config) = config
                && let Ok(config) = toml::from_str::<toml::Value>(config)
                && let Some(target) = config.get("build").and_then(|build| build.get("target"))
            {
                configured_target = target
                    .as_str()
                    .filter(|value| !value.is_empty())
                    .map(str::to_string);
            }
        }
    }
    configured_target
}

/// Best-effort host target triple, assembled from compile-time `std::env::consts`.
/// Cargo's own triples are `<arch>-<vendor>-<os>[-<env>]`; we reconstruct the
/// common Linux/macOS/Windows shapes. Only used as a *cache-key dimension* (and to
/// disambiguate pools), so an approximate-but-stable value is acceptable — it just
/// needs to be the SAME across invocations on the same host and DIFFERENT across
/// architectures/OSes.
pub(super) fn default_host_target_triple() -> String {
    let arch = std::env::consts::ARCH; // e.g. "x86_64", "aarch64"
    match std::env::consts::OS {
        "linux" => format!("{arch}-unknown-linux-gnu"),
        "macos" => format!("{arch}-apple-darwin"),
        "windows" => format!("{arch}-pc-windows-msvc"),
        other => format!("{arch}-unknown-{other}"),
    }
}

/// Parse the cargo feature set that affects compiled artifacts from `command`.
/// Captures `--features <list>` / `--features=<list>` (space- or comma-separated),
/// `-F <list>`, `--all-features`, and `--no-default-features`. The result feeds
/// `PooledTargetDimensions` whose key derivation is order- and duplicate-insensitive,
/// so two commands that enable the same feature SET share a pool regardless of
/// flag order. `--all-features`/`--no-default-features` are recorded as sentinel
/// pseudo-features so they partition pools (they change the compiled output).
pub(super) fn feature_set_for_command(command: &str) -> Vec<String> {
    let mut features: Vec<String> = Vec::new();
    let push_list = |list: &str, features: &mut Vec<String>| {
        for f in list
            .split([',', ' '])
            .map(str::trim)
            .filter(|s| !s.is_empty())
        {
            features.push(f.to_string());
        }
    };

    let tokens: Vec<&str> = command.split_whitespace().collect();
    let mut iter = tokens.iter().peekable();
    while let Some(token) = iter.next() {
        if let Some(value) = token.strip_prefix("--features=") {
            push_list(value, &mut features);
        } else if let Some(value) = token.strip_prefix("-F=") {
            push_list(value, &mut features);
        } else if *token == "--features" || *token == "-F" {
            if let Some(value) = iter.next() {
                push_list(value, &mut features);
            }
        } else if *token == "--all-features" {
            features.push("__rch_all_features".to_string());
        } else if *token == "--no-default-features" {
            features.push("__rch_no_default_features".to_string());
        }
    }
    features
}

/// Derive the STABLE pooled remote target-dir name for a build's cache dimensions,
/// so independent jobs sharing (project, toolchain, triple, profile, feature-set)
/// REUSE the same warm remote incremental cache instead of cold-recompiling into a
/// unique-per-job dir.
///
/// The key (`rch_common::PooledTargetKey`) is a domain-separated 32-char hex over
/// those dimensions; its native layout is `.rch-pool/<key>` but that contains a
/// `/` which `TransferPipeline::with_remote_cargo_target_dir_name` rejects (the
/// name must be a single path segment). So we flatten to one segment that keeps
/// the `.rch-target-` prefix the stale-dir reaper recognizes and adds a `-pool-`
/// marker the reaper's `REAP_GLOBS` matches: `.rch-target-<worker>-pool-<key>`.
///
/// CONCURRENCY: two concurrent jobs with identical dimensions now share one remote
/// target dir. cargo's own `target/.cargo-lock` (an flock) serializes them
/// correctly — this is expected/fine. The 12h-idle reaper won't evict an
/// actively-building dir (fresh mtime), so the immediate eviction race is
/// low-risk. (Fuller active-build pinning — marking a pool dir in-use for the
/// duration of a job — is a follow-up; the idle-based reaper + cargo flock are the
/// safety mechanism today.)
pub(super) fn remote_cargo_pooled_target_dir_name(
    worker_id: &WorkerId,
    normalized_project_root: &Path,
    toolchain: Option<&ToolchainInfo>,
    command: &str,
) -> String {
    let toolchain_id = toolchain
        .map(ToolchainInfo::rustup_toolchain)
        .unwrap_or_else(|| "unknown".to_string());
    let profile = detect_target_label(command, "").unwrap_or_else(|| "dev".to_string());
    let triple = target_triple_for_command(command);

    let dims = rch_common::pooled_target_key::PooledTargetDimensions::new(
        normalized_project_root.to_string_lossy().to_string(),
        toolchain_id,
        triple,
        profile,
    )
    .with_features(feature_set_for_command(command));

    let key = rch_common::pooled_target_key::PooledTargetKey::derive(&dims);
    let safe_worker_id = sanitize_cargo_home_token(worker_id.as_str());
    // Flatten `.rch-pool/<key>` to a single, slash-free segment while keeping the
    // reaper-recognized `.rch-target-…-pool-…` shape. The key is lowercase hex and
    // the worker id is sanitized, so the result is filesystem- and reaper-safe.
    format!(".rch-target-{safe_worker_id}-pool-{}", key.as_str())
}

/// Idle threshold (hours) after which an abandoned per-job remote target dir is
/// eligible for reaping. Defaults to 12h: empirically (ts2 disk-fill incident,
/// 2026-05) active per-job dirs are touched within ~2h while abandoned ones sit
/// idle 18h+, so 12h cleanly separates the two with margin. Overridable via
/// `RCH_STALE_TARGET_REAP_HOURS`; floored at 1h so a misconfiguration can never
/// reap a live incremental cache.
pub(super) fn stale_target_reap_idle_hours() -> u32 {
    parse_stale_target_reap_idle_hours(std::env::var("RCH_STALE_TARGET_REAP_HOURS").ok())
}

pub(super) fn parse_stale_target_reap_idle_hours(raw: Option<String>) -> u32 {
    const DEFAULT_IDLE_HOURS: u32 = 12;
    raw.and_then(|v| v.trim().parse::<u32>().ok())
        .map(|hours| hours.max(1))
        .unwrap_or(DEFAULT_IDLE_HOURS)
}

pub(super) fn rewrite_cargo_target_dir_command_for_remote(
    command: &str,
    command_tokens: Option<&[String]>,
    forwarded_cargo_target_dir: Option<&PathBuf>,
    reporter: &HookReporter,
) -> String {
    if forwarded_cargo_target_dir.is_none() {
        return command.to_string();
    }

    let parsed_tokens;
    let tokens = if let Some(tokens) = command_tokens {
        tokens
    } else {
        parsed_tokens = parse_command_tokens(command, reporter);
        let Some(tokens) = parsed_tokens.as_deref() else {
            return command.to_string();
        };
        tokens
    };

    let mut stripped = tokens.to_vec();
    let mut removed_target_dir = false;
    if let Some(without_assignments) =
        strip_cargo_target_dir_assignments_from_command_tokens(&stripped)
    {
        stripped = without_assignments;
        removed_target_dir = true;
    }
    if let Some(without_flags) = strip_cargo_target_dir_flags_from_command_tokens(&stripped) {
        stripped = without_flags;
        removed_target_dir = true;
    }
    if removed_target_dir {
        reporter.verbose(
            "[RCH] removed local Cargo target-dir setting before remote execution; worker-scoped target dir will be injected",
        );
        return join_exec_command(&stripped);
    }

    command.to_string()
}

/// Parse the supported literal command grammar and locate the Cargo executable.
/// Leading assignments are normalized with an explicit `env` token; the returned
/// index refers to this normalized argv, after any supported wrapper prefixes.
pub(super) fn managed_clean_overlay_cargo_tokens(
    command: &str,
) -> anyhow::Result<(Vec<String>, usize)> {
    literal_cargo_tokens(command, false)
}

fn literal_cargo_tokens(
    command: &str,
    allow_classified_wrappers: bool,
) -> anyhow::Result<(Vec<String>, usize)> {
    // shell_words preserves literal argv, not shell evaluation. Refuse syntax
    // whose expansion or execution would change when those words are re-quoted.
    let mut quote = None;
    let mut escaped = false;
    for ch in command.chars() {
        if escaped {
            escaped = false;
        } else if ch == '\\' && quote != Some('\'') {
            escaped = true;
        } else if quote == Some(ch) {
            quote = None;
        } else if quote.is_none() && matches!(ch, '\'' | '"') {
            quote = Some(ch);
        } else if quote != Some('\'') && matches!(ch, '$' | '`')
            || quote.is_none()
                && matches!(
                    ch,
                    ';' | '|' | '&' | '<' | '>' | '\n' | '*' | '?' | '[' | '~' | '(' | ')'
                )
        {
            anyhow::bail!("cannot safely bind Cargo build directory across shell evaluation");
        }
    }
    // A shell reads a trailing backslash as a line continuation, so the command
    // it runs is not the argv the tokenizer below would return.
    if escaped || quote.is_some() {
        anyhow::bail!("cannot safely bind Cargo build directory across shell evaluation");
    }
    cargo_command_tokens_with_wrappers(command, allow_classified_wrappers)
}

/// Tokenize without evaluating shell syntax and skip supported executable
/// prefixes. Shared with target detection so `env --` and wrapper option values
/// are not mistaken for Cargo's argument separator or executable.
fn cargo_command_tokens(command: &str) -> anyhow::Result<(Vec<String>, usize)> {
    cargo_command_tokens_with_wrappers(command, false)
}

fn cargo_command_tokens_with_wrappers(
    command: &str,
    allow_classified_wrappers: bool,
) -> anyhow::Result<(Vec<String>, usize)> {
    let mut tokens = shell_words::split(command)?;
    let assignment = super::is_shell_assignment;
    // Quoting an assignment as an entire shell word makes it an executable.
    // An explicit env prefix keeps the same assignment bytes as real argv.
    if tokens.first().is_some_and(|token| assignment(token)) {
        tokens.insert(0, "env".to_string());
    }
    let mut index = 0;
    loop {
        let token = tokens
            .get(index)
            .ok_or_else(|| anyhow::anyhow!("missing Cargo command"))?;
        let executable = Path::new(token).file_name().and_then(|name| name.to_str());
        let wrapper_start = index;
        match executable {
            Some(
                "cargo" | "cargo.exe" | "cargo-zigbuild" | "cargo-zigbuild.exe" | "cargo-xwin"
                | "cargo-xwin.exe",
            ) => break,
            Some("env") => {
                index += 1;
                while let Some(token) = tokens.get(index) {
                    match token.as_str() {
                        "--" => {
                            index += 1;
                            break;
                        }
                        "-i" | "--ignore-environment" => index += 1,
                        "--debug" if allow_classified_wrappers => index += 1,
                        "-u" | "--unset" | "-C" | "--chdir" => {
                            anyhow::ensure!(
                                tokens.get(index + 1).is_some(),
                                "missing env option value"
                            );
                            index += 2;
                        }
                        value
                            if value.starts_with("--unset=")
                                || value.starts_with("--chdir=")
                                || assignment(value) =>
                        {
                            index += 1
                        }
                        value if value.starts_with('-') && allow_classified_wrappers => {
                            let cargo_index = classified_cargo_suffix(&tokens, wrapper_start)?;
                            return Ok((tokens, cargo_index));
                        }
                        value if value.starts_with('-') => anyhow::bail!(
                            "unsupported env option in managed Cargo command: {value}"
                        ),
                        _ => break,
                    }
                }
                while tokens.get(index).is_some_and(|token| assignment(token)) {
                    index += 1;
                }
            }
            Some("time") => {
                index += 1;
                while let Some(token) = tokens.get(index) {
                    match token.as_str() {
                        "--" => {
                            index += 1;
                            break;
                        }
                        "-p" | "--portability" | "-v" | "--verbose" | "-a" | "--append" | "-q"
                        | "--quiet" => index += 1,
                        "-f" | "--format" | "-o" | "--output" => {
                            anyhow::ensure!(
                                tokens.get(index + 1).is_some(),
                                "missing time option value"
                            );
                            index += 2;
                        }
                        value
                            if value.starts_with("--format=") || value.starts_with("--output=") =>
                        {
                            index += 1
                        }
                        value if value.starts_with('-') && allow_classified_wrappers => {
                            let cargo_index = classified_cargo_suffix(&tokens, wrapper_start)?;
                            return Ok((tokens, cargo_index));
                        }
                        value if value.starts_with('-') => anyhow::bail!(
                            "unsupported time option in managed Cargo command: {value}"
                        ),
                        _ => break,
                    }
                }
            }
            Some("rustup") => {
                anyhow::ensure!(
                    tokens.get(index + 1).is_some_and(|token| token == "run"),
                    "expected rustup run before Cargo"
                );
                index += 2;
                if tokens.get(index).is_some_and(|token| token == "--install") {
                    index += 1;
                }
                anyhow::ensure!(
                    tokens
                        .get(index)
                        .is_some_and(|token| !token.is_empty() && !token.starts_with('-')),
                    "missing rustup toolchain"
                );
                index += 1;
            }
            _ if allow_classified_wrappers => {
                let cargo_index = classified_cargo_suffix(&tokens, wrapper_start)?;
                return Ok((tokens, cargo_index));
            }
            _ => anyhow::bail!("unsupported executable prefix in managed Cargo command: {token}"),
        }
    }
    Ok((tokens, index))
}

/// Reuse the classifier's wrapper vocabulary only for an unchanged argv
/// suffix. Execution retains wrapper arguments and the actual executable path.
fn classified_cargo_suffix(tokens: &[String], wrapper_start: usize) -> anyhow::Result<usize> {
    let remaining = join_exec_command(&tokens[wrapper_start..]);
    let normalized = rch_common::patterns::normalize_command(&remaining);
    let suffix = shell_words::split(&normalized)?;
    let start = tokens.len().checked_sub(suffix.len());
    if let Some(start) = start.filter(|&start| start >= wrapper_start)
        && !suffix.is_empty()
        && matches!(
            Path::new(&tokens[start])
                .file_name()
                .and_then(|name| name.to_str()),
            Some(
                "cargo"
                    | "cargo.exe"
                    | "cargo-zigbuild"
                    | "cargo-zigbuild.exe"
                    | "cargo-xwin"
                    | "cargo-xwin.exe"
            )
        )
        && tokens[start + 1..] == suffix[1..]
    {
        return Ok(start);
    }
    anyhow::bail!("cannot locate an unchanged Cargo argv suffix: {remaining}");
}

/// Bind Cargo's intermediate cache to the same managed directory as its
/// artifacts. A final CLI config wins over inherited files, environment and
/// earlier CLI config without intercepting either compiler wrapper.
pub(super) fn managed_clean_overlay_cargo_build_dir(
    command: &str,
    managed_target: &str,
) -> anyhow::Result<String> {
    anyhow::ensure!(
        !managed_target.is_empty() && !managed_target.chars().any(char::is_control),
        "managed Cargo build directory must be a nonempty path without control characters"
    );
    let (mut tokens, cargo_index) = managed_clean_overlay_cargo_tokens(command)?;
    let executable = Path::new(&tokens[cargo_index])
        .file_name()
        .and_then(|name| name.to_str());
    let standalone_xwin = matches!(executable, Some("cargo-xwin" | "cargo-xwin.exe"));
    anyhow::ensure!(
        standalone_xwin || matches!(executable, Some("cargo" | "cargo.exe")),
        "managed clean-overlay build directory requires Cargo or an exact xwin build"
    );
    let mut index = cargo_index + 1;
    if !standalone_xwin
        && tokens
            .get(index)
            .is_some_and(|token| token.starts_with('+'))
    {
        index += 1;
    }
    // Locate the subcommand without confusing option values for its name.
    while let Some(token) = tokens.get(index) {
        match token.as_str() {
            "--config" | "--color" | "-Z" | "-C" => {
                anyhow::ensure!(
                    tokens.get(index + 1).is_some_and(|value| value != "--"),
                    "missing Cargo global option value"
                );
                index += 2;
            }
            "-v" | "-vv" | "-q" | "--verbose" | "--quiet" | "--locked" | "--offline"
            | "--frozen" => index += 1,
            value
                if value.starts_with("--config=")
                    || value.starts_with("--color=")
                    || value.starts_with("-Z") && value.len() > 2 =>
            {
                index += 1
            }
            value if value.starts_with('-') => {
                anyhow::bail!("unsupported Cargo global option: {value}")
            }
            _ => break,
        }
    }
    let subcommand = tokens
        .get(index)
        .ok_or_else(|| anyhow::anyhow!("missing Cargo subcommand"))?;
    let xwin = standalone_xwin || subcommand == "xwin";
    if xwin {
        anyhow::ensure!(
            rch_common::patterns::is_cargo_xwin_build(command),
            "managed xwin requires an exact classified xwin build"
        );
        if subcommand == "xwin" {
            index += 1;
        }
    }
    let subcommand = tokens
        .get(index)
        .ok_or_else(|| anyhow::anyhow!("missing Cargo build subcommand"))?;
    if !xwin && subcommand == "fmt" {
        return Ok(command.to_string());
    }
    let packaging = !xwin && matches!(subcommand.as_str(), "package" | "publish");
    if packaging {
        // Apply the SAME authority check as classification, before inserting
        // any worker configuration. A dry-run token inside an option value,
        // --no-verify, or an unknown flag must never enable real publication.
        anyhow::ensure!(
            rch_common::patterns::is_cargo_package_verification(command),
            "managed packaging requires verified cargo package or explicit cargo publish --dry-run"
        );
    }
    anyhow::ensure!(
        packaging
            || matches!(
                subcommand.as_str(),
                "build"
                    | "b"
                    | "check"
                    | "c"
                    | "test"
                    | "t"
                    | "clippy"
                    | "doc"
                    | "d"
                    | "bench"
                    | "run"
                    | "r"
                    | "rustc"
                    | "rustdoc"
                    | "fix"
            ),
        "unsupported Cargo subcommand for managed build directory: {subcommand}"
    );
    let end = tokens[index + 1..]
        .iter()
        .position(|token| token == "--")
        .map_or(tokens.len(), |offset| index + 1 + offset);
    anyhow::ensure!(
        !tokens[index + 1..end]
            .iter()
            .any(|token| token == "--build-dir" || token.starts_with("--build-dir=")),
        "explicit --build-dir is unsupported for clean-overlay execution"
    );
    let value = format!(
        "build.build-dir={}",
        toml::Value::String(managed_target.to_string())
    );
    tokens.splice(end..end, ["--config".to_string(), value]);
    Ok(join_exec_command(&tokens))
}

/// Bind the owned closure's final artifacts to its granted pool using Cargo's
/// actual CLI option, which takes precedence over environment and configuration.
/// This is applied only to execution after the caller's output policy is saved.
pub(super) fn bind_owned_cargo_target_dir(
    command: &str,
    managed_target: &str,
) -> anyhow::Result<String> {
    anyhow::ensure!(
        Path::new(managed_target).is_absolute()
            && Path::new(managed_target).file_name().is_some()
            && !managed_target.chars().any(char::is_control)
            && !managed_target.contains('\\')
            && !managed_target
                .split('/')
                .any(|part| part == "." || part == ".."),
        "owned Cargo target must be an absolute literal pool path"
    );
    let (mut tokens, cargo_index) = managed_clean_overlay_cargo_tokens(command)?;
    anyhow::ensure!(
        Path::new(&tokens[cargo_index])
            .file_name()
            .is_some_and(|name| name == "cargo" || name == "cargo.exe"),
        "owned target binding requires the Cargo executable"
    );
    let mut index = cargo_index + 1;
    if tokens
        .get(index)
        .is_some_and(|token| token.starts_with('+'))
    {
        index += 1;
    }
    while let Some(token) = tokens.get(index) {
        match token.as_str() {
            "--config" | "--color" | "-Z" => {
                anyhow::ensure!(
                    tokens.get(index + 1).is_some_and(|value| value != "--"),
                    "missing Cargo global option value"
                );
                index += 2;
            }
            "-v" | "-vv" | "-q" | "--verbose" | "--quiet" | "--locked" | "--offline"
            | "--frozen" => index += 1,
            value
                if value.starts_with("--config=")
                    || value.starts_with("--color=")
                    || value.starts_with("-Z") && value.len() > 2 =>
            {
                index += 1
            }
            value if value.starts_with('-') => {
                anyhow::bail!("unsupported owned Cargo global option: {value}")
            }
            _ => break,
        }
    }
    let subcommand = tokens
        .get(index)
        .ok_or_else(|| anyhow::anyhow!("missing Cargo subcommand"))?;
    anyhow::ensure!(
        matches!(
            subcommand.as_str(),
            "build"
                | "b"
                | "check"
                | "c"
                | "test"
                | "t"
                | "clippy"
                | "doc"
                | "d"
                | "bench"
                | "run"
                | "r"
                | "rustc"
                | "rustdoc"
                | "fix"
                | "package"
                | "publish"
        ),
        "unsupported Cargo subcommand for owned target binding: {subcommand}"
    );
    let end = tokens[index + 1..]
        .iter()
        .position(|token| token == "--")
        .map_or(tokens.len(), |offset| index + 1 + offset);
    anyhow::ensure!(
        !tokens[index + 1..end]
            .iter()
            .any(|token| token == "--target-dir" || token.starts_with("--target-dir=")),
        "owned Cargo target binding requires the caller's target selector to be absent"
    );
    tokens.splice(
        end..end,
        ["--target-dir".to_owned(), managed_target.to_owned()],
    );
    Ok(join_exec_command(&tokens))
}

/// Keep the caller's output contract separate from execution-only rewrites.
/// In particular, injected TOML configuration contains shell quotes which the
/// conservative package classifier must not interpret as publication authority.
/// Both live retrieval and the durable recovery recipe use `policy_command`.
pub(super) struct ManagedCargoCommand<'a> {
    original: &'a str,
    rewritten: Option<String>,
}

impl<'a> ManagedCargoCommand<'a> {
    pub(super) fn new(command: &'a str, managed_target: Option<&str>) -> anyhow::Result<Self> {
        let rewritten = managed_target
            .map(|target| managed_clean_overlay_cargo_build_dir(command, target))
            .transpose()?;
        Ok(Self {
            original: command,
            rewritten,
        })
    }

    pub(super) fn policy_command(&self) -> &str {
        self.original
    }

    pub(super) fn execution_command(&self) -> &str {
        self.rewritten.as_deref().unwrap_or(self.original)
    }
}

pub(super) fn bind_build_source_stamp(command: &str, stamp: &str) -> anyhow::Result<String> {
    anyhow::ensure!(
        !stamp.is_empty() && !stamp.chars().any(char::is_control),
        "invalid build-source stamp"
    );
    let (mut tokens, cargo_index) = literal_cargo_tokens(command, true)?;
    let end = tokens
        .iter()
        .enumerate()
        .skip(cargo_index + 1)
        .find_map(|(index, token)| (token == "--").then_some(index))
        .unwrap_or(tokens.len());
    let value = format!(
        "env.RCH_BUILD_SOURCE.value={}",
        toml::Value::String(stamp.to_owned())
    );
    if cargo_subcommand_is_nextest(&tokens, cargo_index) {
        // cargo-nextest deserializes each `--config` as a whole `[env]` entry,
        // so a lone `force=true` has no `value` and nextest exits 96, and Cargo
        // refuses the inline-table form. Bind the value alone and give Cargo's
        // process environment the same stamp, which is all `force` overrides.
        tokens.splice(end..end, ["--config".to_owned(), value]);
        tokens.splice(
            cargo_index..cargo_index,
            ["env".to_owned(), format!("RCH_BUILD_SOURCE={stamp}")],
        );
        return Ok(join_exec_command(&tokens));
    }
    tokens.splice(
        end..end,
        [
            "--config".to_owned(),
            value,
            "--config".to_owned(),
            "env.RCH_BUILD_SOURCE.force=true".to_owned(),
        ],
    );
    Ok(join_exec_command(&tokens))
}

/// Same subcommand rule as the classifier: skip `+toolchain` and global flags,
/// including the separate value of `--color`, `-Z`, `-C` and `--config`.
fn cargo_subcommand_is_nextest(tokens: &[String], cargo_index: usize) -> bool {
    const CARGO_VALUE_FLAGS: &[&str] = &["--color", "-Z", "-C", "--config"];
    let mut rest = tokens.iter().skip(cargo_index + 1);
    while let Some(token) = rest.next() {
        if token.starts_with('+') {
            continue;
        }
        if token.starts_with('-') {
            if !token.contains('=') && CARGO_VALUE_FLAGS.contains(&token.as_str()) {
                rest.next();
            }
            continue;
        }
        return token == "nextest";
    }
    false
}

/// Refuse unselected worker Cargo configuration immediately before Unix Cargo.
/// The outer command prefixes run first, so the guard sees Cargo's effective
/// environment. This checks ordinary filesystem state, not atomic protection
/// against an adversary changing paths between inspection and execution.
pub(super) fn guard_clean_overlay_cargo_config(command: &str) -> anyhow::Result<String> {
    let (mut tokens, cargo_index) = managed_clean_overlay_cargo_tokens(command)?;
    let guard = r#"rch_config_refuse() {
    printf '%s\n' 'RCH-E413 clean-overlay unselected Cargo configuration' >&2
    exit 113
}
rch_config_directory() {
    [ -d "$1" ] && [ -r "$1" ] && [ -x "$1" ] || rch_config_refuse
    /bin/ls -a "$1" >/dev/null 2>&1 || rch_config_refuse
}
rch_config_absent() {
    for rch_config_name in config config.toml; do
        if [ -e "$1/$rch_config_name" ] || [ -L "$1/$rch_config_name" ]; then
            rch_config_refuse
        fi
    done
}
case "${CARGO_HOME-}" in
    /*) ;;
    *) rch_config_refuse ;;
esac
rch_config_directory "$CARGO_HOME"
rch_config_absent "$CARGO_HOME"
rch_config_parent=$(pwd -P) || rch_config_refuse
case "$rch_config_parent" in
    /*) ;;
    *) rch_config_refuse ;;
esac
while [ "$rch_config_parent" != / ]; do # ubs:ignore — compares a directory path with filesystem root, not a secret.
    rch_config_parent=${rch_config_parent%/*}
    [ -n "$rch_config_parent" ] || rch_config_parent=/
    rch_config_directory "$rch_config_parent"
    if [ -e "$rch_config_parent/.cargo" ] || [ -L "$rch_config_parent/.cargo" ]; then
        rch_config_directory "$rch_config_parent/.cargo"
        rch_config_absent "$rch_config_parent/.cargo"
    fi
done
exec "$@""#;
    tokens.splice(
        cargo_index..cargo_index,
        [
            "/bin/sh".to_string(),
            "-c".to_string(),
            guard.to_string(),
            "rch-clean-overlay-config".to_string(),
        ],
    );
    Ok(join_exec_command(&tokens))
}

pub(super) fn strip_cargo_target_dir_assignments_from_command_tokens(
    tokens: &[String],
) -> Option<Vec<String>> {
    fn strip_assignment_prefix(tokens: &mut Vec<String>, mut index: usize) -> bool {
        let mut changed = false;
        while let Some(token) = tokens.get(index) {
            let Some((key, _)) = token.split_once('=') else {
                break;
            };
            if key == "CARGO_TARGET_DIR" {
                tokens.remove(index);
                changed = true;
            } else {
                index += 1;
            }
        }
        changed
    }

    let mut stripped = tokens.to_vec();
    let mut index = 0usize;
    while let Some(token) = stripped.get(index) {
        match token.as_str() {
            "sudo" | "time" => {
                index += 1;
                while let Some(flag) = stripped.get(index) {
                    if flag.starts_with('-') {
                        index += 1;
                    } else {
                        break;
                    }
                }
            }
            "env" => {
                index = skip_env_option_prefix(&stripped, index + 1);
                return strip_assignment_prefix(&mut stripped, index).then_some(stripped);
            }
            _ => {
                return strip_assignment_prefix(&mut stripped, index).then_some(stripped);
            }
        }
    }

    None
}

fn skip_env_option_prefix(tokens: &[String], mut index: usize) -> usize {
    while let Some(flag) = tokens.get(index).map(String::as_str) {
        if flag == "--" {
            return index + 1;
        }

        match flag {
            "-u" | "--unset" => {
                index += 1;
                if tokens.get(index).is_some() {
                    index += 1;
                }
            }
            _ if flag.starts_with("--unset=") => {
                index += 1;
            }
            _ if flag.starts_with('-') && !flag.contains('=') => {
                index += 1;
            }
            _ => break,
        }
    }

    index
}

/// Find the single literal --target-dir option belonging to Cargo. Both
/// extraction and removal use this span, so a wrapper separator or opaque
/// option value cannot make those two operations disagree about the target.
fn cargo_target_dir_flag_span(tokens: &[String]) -> Option<(std::ops::Range<usize>, String)> {
    let command = shell_words::join(tokens);
    let (normalized, cargo_index) = cargo_command_tokens_with_wrappers(&command, true).ok()?;
    // The shared parser may add `env` for leading assignments. Map its index
    // back to the original argv; never reconstruct or change wrapper arguments.
    let added = normalized.len().checked_sub(tokens.len())?;
    if added > 1 || normalized.get(added..)? != tokens {
        return None;
    }
    let mut index = cargo_index.checked_sub(added)? + 1;
    let mut selected = None;
    while let Some(token) = tokens.get(index) {
        if token == "--" {
            break;
        }
        let (end, value) = if token == "--target-dir" {
            let value = tokens.get(index + 1)?;
            if value.starts_with('-') {
                return None;
            }
            (index + 2, Some(value.as_str()))
        } else if let Some(value) = token.strip_prefix("--target-dir=") {
            (index + 1, Some(value))
        } else {
            // A value can itself spell --target-dir or --. It remains an
            // opaque value, not an option to extract/remove or a separator.
            let takes_value = matches!(
                token.as_str(),
                "--config"
                    | "--target"
                    | "--manifest-path"
                    | "--lockfile-path"
                    | "--profile"
                    | "--package"
                    | "-p"
                    | "--exclude"
                    | "--features"
                    | "-F"
                    | "--bin"
                    | "--example"
                    | "--test"
                    | "--bench"
                    | "--color"
                    | "--message-format"
                    | "--jobs"
                    | "-j"
                    | "-Z"
                    | "-C"
                    | "--artifact-dir"
                    | "--out-dir"
                    | "--build-dir"
            );
            if takes_value {
                tokens.get(index + 1)?;
            }
            (index + if takes_value { 2 } else { 1 }, None)
        };
        if let Some(value) = value {
            if selected.is_some() || value.is_empty() || value.chars().any(char::is_control) {
                // Do not turn an invalid or ambiguous invocation into a valid
                // build by deleting its diagnostics-producing arguments.
                return None;
            }
            selected = Some((index..end, value.to_string()));
        }
        index = end;
    }
    selected
}

pub(super) fn strip_cargo_target_dir_flags_from_command_tokens(
    tokens: &[String],
) -> Option<Vec<String>> {
    let (span, _) = cargo_target_dir_flag_span(tokens)?;
    let mut stripped = tokens.to_vec();
    stripped.drain(span);
    Some(stripped)
}

pub(super) fn extract_cargo_target_dir_from_command_tokens(tokens: &[String]) -> Option<String> {
    // Cargo's explicit option wins over inline and inherited environment.
    // Resolve it before scanning assignment prefixes, not afterward.
    if let Some((_, value)) = cargo_target_dir_flag_span(tokens) {
        return Some(value);
    }

    fn scan_assignment_prefix(tokens: &[String], start: usize) -> Option<String> {
        let mut index = start;
        while let Some(token) = tokens.get(index) {
            if let Some((key, value)) = token.split_once('=') {
                if key == "CARGO_TARGET_DIR" {
                    return Some(value.to_string());
                }
                index += 1;
                continue;
            }
            break;
        }
        None
    }

    let mut index = 0usize;
    while let Some(token) = tokens.get(index) {
        match token.as_str() {
            "sudo" | "time" => {
                index += 1;
                while let Some(flag) = tokens.get(index) {
                    if flag.starts_with('-') {
                        index += 1;
                    } else {
                        break;
                    }
                }
            }
            "env" => {
                index = skip_env_option_prefix(tokens, index + 1);
                return scan_assignment_prefix(tokens, index);
            }
            _ => return scan_assignment_prefix(tokens, index),
        }
    }
    None
}

#[cfg(test)]
mod managed_build_dir_tests {
    use super::{
        bind_owned_cargo_target_dir, managed_clean_overlay_cargo_build_dir,
        managed_clean_overlay_cargo_tokens,
    };

    #[test]
    fn owned_target_binding_preserves_wrappers_and_passthrough() {
        let target = "/worker/pools/target with ' quotes";
        for argv in [
            vec![
                "cargo",
                "build",
                "--config",
                "build.target-dir=\"/unselected\"",
            ],
            vec![
                "env",
                "--",
                "CARGO_TARGET_DIR=/unselected",
                "cargo",
                "+nightly",
                "test",
                "--",
                "--target-dir=/test-payload",
            ],
            vec![
                "time",
                "-f",
                "literal --target-dir",
                "cargo",
                "--color",
                "never",
                "clippy",
                "--",
                "-D",
                "warnings",
            ],
            vec![
                "rustup",
                "run",
                "nightly",
                "cargo",
                "check",
                "--all-targets",
            ],
        ] {
            let command = shell_words::join(&argv);
            let managed = managed_clean_overlay_cargo_build_dir(&command, target).unwrap();
            let mut expected = shell_words::split(&managed).unwrap();
            let (_, cargo_index) = managed_clean_overlay_cargo_tokens(&managed).unwrap();
            let separator = expected[cargo_index + 1..]
                .iter()
                .position(|token| token == "--")
                .map_or(expected.len(), |offset| cargo_index + 1 + offset);
            expected.splice(
                separator..separator,
                ["--target-dir".to_owned(), target.to_owned()],
            );
            let bound = bind_owned_cargo_target_dir(&managed, target).unwrap();
            assert_eq!(shell_words::split(&bound).unwrap(), expected, "{command}");
        }
    }

    #[test]
    fn owned_target_binding_refuses_unsupported_or_duplicate_output_authority() {
        for command in [
            "cargo fmt",
            "cargo clean",
            "cargo build --target-dir /unselected",
            "cargo build --target-dir=/unselected",
            "cargo -C /elsewhere build",
            "cargo-xwin build",
            "cargo build; echo changed",
        ] {
            assert!(
                bind_owned_cargo_target_dir(command, "/worker/pool").is_err(),
                "{command}"
            );
        }
        for target in ["relative", "/", "/worker/../pool", "/worker/pool\nother"] {
            assert!(
                bind_owned_cargo_target_dir("cargo build", target).is_err(),
                "{target:?}"
            );
        }
    }

    /// Real Cargo verifies the extracted archive, not merely the working tree.
    /// The transfer below is local rsync fed by the production artifact policy;
    /// it does not stand in for daemon admission, SSH or source-lease qualification.
    #[cfg(target_os = "linux")]
    #[test]
    fn managed_packaging_real_cargo_verifies_archive_and_returns_identical_bytes() {
        use super::super::artifact_patterns::get_custom_target_artifact_patterns;
        use std::fs;
        use std::io::{Read as _, Write as _};
        use std::path::{Path, PathBuf};
        use std::process::{Command, Stdio};

        fn files(root: &Path, directory: &Path, paths: &mut Vec<PathBuf>) {
            for entry in fs::read_dir(directory).unwrap() {
                let entry = entry.unwrap();
                let kind = entry.file_type().unwrap();
                assert!(
                    !kind.is_symlink(),
                    "unexpected fixture symlink: {:?}",
                    entry.path()
                );
                if kind.is_dir() {
                    files(root, &entry.path(), paths);
                } else if kind.is_file() {
                    paths.push(entry.path().strip_prefix(root).unwrap().to_path_buf());
                }
            }
        }

        let root = tempfile::Builder::new()
            .prefix("rch-managed-package-")
            .tempdir()
            .unwrap()
            .keep();
        eprintln!(
            "managed packaging fixture and logs retained at {}",
            root.display()
        );
        for directory in ["src", ".cargo", "bin", "cargo-home", "logs", "returned"] {
            fs::create_dir(root.join(directory)).unwrap();
        }
        // Explicit inclusion keeps the toolchain symlink, logs and managed
        // caches out of the package, and makes the negative source meaningful.
        fs::write(
            root.join("Cargo.toml"),
            "[package]\nname='managed_package_fixture'\nversion='0.1.0'\nedition='2021'\n\
             include=['Cargo.toml', 'build.rs', 'src/**', 'packaged.txt']\n[workspace]\n",
        )
        .unwrap();
        fs::write(root.join("packaged.txt"), "archive-owned input\n").unwrap();
        fs::write(root.join("worktree-only.txt"), "excluded input\n").unwrap();
        let source = b"pub const MESSAGE: &str = include_str!(\"../packaged.txt\");\n";
        fs::write(root.join("src/lib.rs"), source).unwrap();
        fs::write(
            root.join("build.rs"),
            r#"fn main() {
    let origin = std::env::var("CARGO_MANIFEST_DIR").unwrap();
    let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap());
    std::fs::write(out.join("rch-package-origin"), origin).unwrap();
}
"#,
        )
        .unwrap();
        let outside_file = root.join("outside-file-config");
        let outside_env = root.join("outside-environment");
        fs::write(
            root.join(".cargo/config.toml"),
            format!(
                "[build]\nbuild-dir={}\n",
                toml::Value::String(outside_file.to_str().unwrap().to_owned())
            ),
        )
        .unwrap();

        // Follow the same test-only real-Cargo resolution as the other native
        // managed-build-dir fixtures. Never intercept or replace a real compiler.
        let mut cargo = PathBuf::from(env!("CARGO"));
        if fs::metadata(&cargo).unwrap().len() <= 8 * 1024
            && fs::read_to_string(&cargo)
                .unwrap()
                .lines()
                .any(|line| line.starts_with("# rch-toolchain-wrap-version:"))
        {
            cargo.set_file_name("cargo-rch-real");
        }
        let mut magic = [0; 4];
        fs::File::open(&cargo)
            .unwrap()
            .read_exact(&mut magic)
            .unwrap();
        assert_eq!(&magic, b"\x7fELF", "fixture requires real Cargo");
        let cargo_bin = cargo.parent().unwrap();
        std::os::unix::fs::symlink(&cargo, root.join("bin/cargo")).unwrap();
        let path = std::env::join_paths([
            root.join("bin"),
            cargo_bin.to_path_buf(),
            PathBuf::from("/usr/bin"),
            PathBuf::from("/bin"),
        ])
        .unwrap();
        let run = |name: &str, command: &str, pool: &Path| {
            let plan =
                super::ManagedCargoCommand::new(command, Some(pool.to_str().unwrap())).unwrap();
            let stamped =
                super::bind_build_source_stamp(plan.execution_command(), &"a".repeat(40)).unwrap();
            let guarded = super::guard_clean_overlay_cargo_config(&stamped).unwrap();
            // Fixed, fixture-owned commands only. timeout also bounds compiler
            // descendants; no test relies on an indefinitely running child.
            let output = Command::new("/usr/bin/timeout") // ubs:ignore — native Cargo regression in an owned temporary project.
                .args(["--kill-after=5", "120", "sh", "-c", &guarded])
                .current_dir(&root)
                .env_clear()
                .env("PATH", &path)
                .env("HOME", &root)
                .env("CARGO_HOME", root.join("cargo-home"))
                .env("CARGO_TARGET_DIR", pool)
                .env("CARGO_BUILD_BUILD_DIR", &outside_env)
                .env("RUSTC", cargo_bin.join("rustc"))
                .env("RUSTUP_AUTO_INSTALL", "0")
                .env("RCH_CARGO_WRAPPER_BYPASS", "1")
                .env("LC_ALL", "C")
                .output()
                .expect("GNU timeout and the fixture's native Cargo must be available");
            fs::write(root.join(format!("logs/{name}.stdout")), &output.stdout).unwrap();
            fs::write(root.join(format!("logs/{name}.stderr")), &output.stderr).unwrap();
            output
        };

        let command = "cargo package --offline --allow-dirty --no-metadata -j1";
        let pool = root.join("managed pool");
        let packaged = run("package", command, &pool);
        assert!(packaged.status.success(), "{packaged:?}");
        let mut inventory = Vec::new();
        files(&pool, &pool, &mut inventory);
        let extracted = pool.join("package/managed_package_fixture-0.1.0");
        assert!(
            inventory.iter().any(|relative| {
                relative
                    .file_name()
                    .is_some_and(|name| name == "rch-package-origin")
                    && fs::read_to_string(pool.join(relative)).unwrap()
                        == extracted.to_str().unwrap()
            }),
            "verification must execute the build script from the extracted archive"
        );

        let plan = super::ManagedCargoCommand::new(command, Some(pool.to_str().unwrap())).unwrap();
        let patterns = get_custom_target_artifact_patterns(
            Some(rch_common::CompilationKind::CargoBuild),
            Some(plan.policy_command()),
        );
        let pipeline = crate::transfer::TransferPipeline::new(
            root.join("returned"),
            "native-package".into(),
            "fixture".into(),
            rch_common::TransferConfig::default(),
        );
        let (selected, _) = pipeline
            .partition_staged_artifact_paths(&inventory, &patterns)
            .unwrap();
        let archive = PathBuf::from("package/managed_package_fixture-0.1.0.crate");
        // Cargo can retain its identical archive staging copy. The production
        // policy deliberately retrieves tmp-crate archives for dry-run publish;
        // keep that contract while rejecting every unrelated selected file.
        let temporary_archive =
            PathBuf::from("package/tmp-crate/managed_package_fixture-0.1.0.crate");
        let mut expected = vec![archive.clone()];
        if pool.join(&temporary_archive).is_file() {
            assert_eq!(
                fs::read(pool.join(&temporary_archive)).unwrap(),
                fs::read(pool.join(&archive)).unwrap(),
                "Cargo's staging archive must be byte-identical to its final archive"
            );
            expected.push(temporary_archive.clone());
        }
        expected.sort();
        let mut selected_set = selected.clone();
        selected_set.sort();
        assert_eq!(selected_set, expected);
        let mut rsync = Command::new("/usr/bin/timeout") // ubs:ignore — copies only production-selected fixture archives, locally.
            .args([
                "--kill-after=5",
                "60",
                "rsync",
                "-a",
                "--from0",
                "--files-from=-",
                "--",
            ])
            .arg(format!("{}/", pool.display()))
            .arg(format!("{}/", root.join("returned").display()))
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .expect("rsync must be available for the native retrieval fixture");
        {
            let mut input = rsync.stdin.take().unwrap();
            for relative in &selected {
                input
                    .write_all(relative.as_os_str().as_encoded_bytes())
                    .unwrap();
                input.write_all(&[0]).unwrap();
            }
        }
        let transferred = rsync.wait_with_output().unwrap();
        assert!(transferred.status.success(), "{transferred:?}");
        for relative in &selected {
            let original = fs::read(pool.join(relative)).unwrap();
            let returned = fs::read(root.join("returned").join(relative)).unwrap();
            assert_eq!(
                blake3::hash(&returned),
                blake3::hash(&original),
                "returned archive bytes differ for {relative:?}"
            );
        }
        let original = fs::read(pool.join(&archive)).unwrap();
        let returned = fs::read(root.join("returned").join(&archive)).unwrap();
        assert_eq!(blake3::hash(&returned), blake3::hash(&original));
        let mut members = tar::Archive::new(flate2::read::GzDecoder::new(returned.as_slice()));
        let mut saw_source = false;
        for entry in members.entries().unwrap() {
            let mut entry = entry.unwrap();
            let path = entry.path().unwrap().into_owned();
            assert!(!path.ends_with("worktree-only.txt"));
            if path.ends_with("src/lib.rs") {
                let mut bytes = Vec::new();
                entry.read_to_end(&mut bytes).unwrap();
                assert_eq!(bytes.as_slice(), &source[..]);
                saw_source = true;
            }
        }
        assert!(saw_source);
        assert!(!outside_file.exists() && !outside_env.exists());

        // The worktree remains buildable, but the archive deliberately omits
        // the required input. Verification must fail, not silently build the
        // working tree or reuse artifacts from the earlier verified package.
        let failing_source = b"pub const MESSAGE: &str = include_str!(\"../worktree-only.txt\");\n";
        fs::write(root.join("src/lib.rs"), failing_source).unwrap();
        let check = run(
            "worktree",
            "cargo check --offline -j1",
            &root.join("check pool"),
        );
        assert!(check.status.success(), "{check:?}");
        let failed_pool = root.join("failed package pool");
        let failed = run("package-missing-input", command, &failed_pool);
        assert_eq!(failed.status.code(), Some(101), "{failed:?}");
        assert!(String::from_utf8_lossy(&failed.stderr).contains("worktree-only.txt"));
        // Cargo promotes the staged archive only after verification succeeds.
        // The failed package must retain the new source in staging without
        // presenting it as a successfully verified final archive.
        assert!(
            failed_pool.join(&temporary_archive).is_file(),
            "verification failure must occur after staging the archive"
        );
        assert!(
            !failed_pool.join(&archive).exists(),
            "failed verification must not promote a final archive"
        );
        let failed_archive = fs::read(failed_pool.join(&temporary_archive)).unwrap();
        assert_ne!(
            failed_archive, original,
            "failed package must use the new source"
        );
        let mut members =
            tar::Archive::new(flate2::read::GzDecoder::new(failed_archive.as_slice()));
        let mut saw_failing_source = false;
        let mut saw_packaged_input = false;
        for entry in members.entries().unwrap() {
            let mut entry = entry.unwrap();
            let path = entry.path().unwrap().into_owned();
            assert!(!path.ends_with("worktree-only.txt"));
            if path == Path::new("managed_package_fixture-0.1.0/src/lib.rs") {
                let mut bytes = Vec::new();
                entry.read_to_end(&mut bytes).unwrap();
                assert_eq!(bytes.as_slice(), &failing_source[..]);
                saw_failing_source = true;
            } else if path == Path::new("managed_package_fixture-0.1.0/packaged.txt") {
                let mut bytes = Vec::new();
                entry.read_to_end(&mut bytes).unwrap();
                assert_eq!(bytes, b"archive-owned input\n");
                saw_packaged_input = true;
            }
        }
        assert!(saw_failing_source && saw_packaged_input);
        let mut failed_inventory = Vec::new();
        files(&failed_pool, &failed_pool, &mut failed_inventory);
        let failed_extracted = failed_pool.join("package/managed_package_fixture-0.1.0");
        assert!(
            failed_inventory.iter().any(|relative| {
                relative
                    .file_name()
                    .is_some_and(|name| name == "rch-package-origin")
                    && fs::read_to_string(failed_pool.join(relative)).unwrap()
                        == failed_extracted.to_str().unwrap()
            }),
            "failed verification must execute the build script from the extracted archive"
        );
        assert_eq!(
            fs::read(root.join("worktree-only.txt")).unwrap(),
            b"excluded input\n"
        );
        assert!(!outside_file.exists() && !outside_env.exists());
    }

    #[test]
    fn managed_packaging_preserves_the_classified_command_and_binds_the_cache() {
        use rch_common::patterns::{classify_command, is_cargo_package_verification};

        let target = "/worker/cache with 'single' and \"double\" quotes";
        for command in [
            "cargo package --offline -j1",
            "cargo publish --dry-run --locked -j1",
            "cargo publish -n --workspace -p demo",
            "cargo +nightly package --locked",
            "cargo --offline publish --dry-run",
            "env CARGO_HOME=/tmp/cargo cargo publish --dry-run",
        ] {
            assert!(is_cargo_package_verification(command), "{command}");
            assert_eq!(
                classify_command(command).kind,
                Some(rch_common::CompilationKind::CargoBuild),
                "{command}"
            );
            let plan = super::ManagedCargoCommand::new(command, Some(target)).unwrap();
            assert_eq!(plan.policy_command(), command);
            let original = shell_words::split(command).unwrap();
            let rewritten = shell_words::split(plan.execution_command()).unwrap();
            assert_eq!(&rewritten[..original.len()], original.as_slice());
            assert_eq!(rewritten.len(), original.len() + 2);
            assert_eq!(rewritten[original.len()], "--config");
            let config: toml::Value = toml::from_str(&rewritten[original.len() + 1]).unwrap();
            assert_eq!(config["build"]["build-dir"].as_str(), Some(target));
        }
    }

    #[test]
    fn managed_packaging_never_promotes_publication_or_a_dry_run_option_value() {
        for command in [
            "cargo publish",
            "cargo publish --no-verify --dry-run",
            "cargo package --no-verify",
            "cargo package --list",
            "cargo publish --help --dry-run",
            "cargo publish --token --dry-run",
            "cargo publish --token=--dry-run",
            "cargo publish --registry=-n",
            "cargo publish --config=--dry-run",
            "cargo publish --manifest-path --dry-run",
            "cargo publish --unknown --dry-run",
            "cargo publish -- --dry-run",
            "cargo publish --dry-run=false",
            "cargo publish --dry-run --build-dir /unmanaged",
            "cargo publish --dry-run; cargo publish",
            "cargo publish '$MODE'",
            "cargo package --config 'build.jobs=1'",
        ] {
            assert!(
                super::ManagedCargoCommand::new(command, Some("/worker/target")).is_err(),
                "{command}"
            );
        }
    }

    #[test]
    fn managed_packaging_keeps_archive_only_delivery_through_all_execution_rewrites() {
        use super::super::artifact_patterns::{
            expected_output_glob_list, get_custom_target_artifact_patterns,
            get_project_artifact_patterns, sync_back_verified_zero_package_archives,
        };
        use std::collections::BTreeSet;
        use std::path::PathBuf;

        let kind = Some(rch_common::CompilationKind::CargoBuild);
        let archives: Vec<PathBuf> = [
            "package/demo-0.1.0.crate",
            "package/tmp-registry/dependency-0.1.0.crate",
            "package/tmp-crate/demo-0.1.0.crate",
        ]
        .into_iter()
        .map(PathBuf::from)
        .collect();
        let mut inventory = archives.clone();
        inventory.extend(
            [
                "package/demo-0.1.0/src/lib.rs",
                "package/tmp-registry/index/config.json",
                ".rustc_info.json",
                "debug/stale-executable",
                "debug/incremental/stale.o",
            ]
            .into_iter()
            .map(PathBuf::from),
        );
        for command in [
            "cargo package --offline",
            "cargo publish --dry-run --locked",
        ] {
            for target in [None, Some("/worker/managed pool")] {
                let plan = super::ManagedCargoCommand::new(command, target).unwrap();
                let stamped =
                    super::bind_build_source_stamp(plan.execution_command(), &"a".repeat(40))
                        .unwrap();
                assert!(stamped.contains("RCH_BUILD_SOURCE"));
                assert_eq!(plan.policy_command(), command);
                let patterns =
                    get_custom_target_artifact_patterns(kind, Some(plan.policy_command()));
                assert_eq!(
                    expected_output_glob_list(&patterns),
                    [
                        "package/*.crate",
                        "package/tmp-registry/*.crate",
                        "package/tmp-crate/*.crate",
                    ]
                );
                assert!(
                    get_project_artifact_patterns(kind, Some(plan.policy_command()), true)
                        .is_empty()
                );
                assert_eq!(
                    get_project_artifact_patterns(kind, Some(plan.policy_command()), false),
                    [
                        "target/package/*.crate",
                        "target/package/tmp-registry/*.crate",
                        "target/package/tmp-crate/*.crate",
                    ]
                );
                let pipeline = crate::transfer::TransferPipeline::new(
                    PathBuf::from("/unused/local"),
                    "package-policy".into(),
                    "fixture".into(),
                    rch_common::TransferConfig::default(),
                );
                let (selected, excluded) = pipeline
                    .partition_staged_artifact_paths(&inventory, &patterns)
                    .unwrap();
                assert_eq!(
                    selected.into_iter().collect::<BTreeSet<_>>(),
                    archives.iter().cloned().collect::<BTreeSet<_>>()
                );
                assert_eq!(excluded.len(), 5);
                assert!(sync_back_verified_zero_package_archives(
                    Some(0),
                    plan.policy_command()
                ));
                assert!(!sync_back_verified_zero_package_archives(
                    Some(1),
                    plan.policy_command()
                ));
                assert!(!sync_back_verified_zero_package_archives(
                    None,
                    plan.policy_command()
                ));
            }
        }
    }

    #[test]
    fn unmanaged_command_plan_does_not_reclassify_or_rewrite_non_cargo_jobs() {
        let command = "python3 -I collect.py --config 'literal $value'";
        let plan = super::ManagedCargoCommand::new(command, None).unwrap();
        assert_eq!(plan.policy_command(), command);
        assert_eq!(plan.execution_command(), command);
    }

    #[test]
    fn explicit_target_honors_inline_config_and_shell_quoting() {
        let target = "aarch64-apple-darwin";
        for command in [
            r#"cargo build --config 'build.target="aarch64-apple-darwin"'"#,
            r#"cargo build --config='build.target="aarch64-apple-darwin"'"#,
            r#"cargo --config "build.target = 'aarch64-apple-darwin'" build"#,
            r#"cargo build --target 'aarch64-apple-darwin'"#,
            r#"cargo build '--target=aarch64-apple-darwin'"#,
            r#"env -- CARGO_TARGET_DIR='/custom target' /opt/bin/cargo +nightly build --config 'build.target="aarch64-apple-darwin"'"#,
            r#"/usr/bin/time -f cargo env -u cargo -- rustup run nightly cargo build --config 'build.target="aarch64-apple-darwin"'"#,
        ] {
            assert_eq!(
                super::explicit_target_triple_for_command(command).as_deref(),
                Some(target),
                "{command}"
            );
            assert_eq!(super::target_triple_for_command(command), target);
        }
    }

    #[test]
    fn explicit_target_obeys_precedence_and_ignores_passthrough() {
        for command in [
            r#"cargo build --config 'build.target="x86_64-unknown-linux-gnu"' --target aarch64-apple-darwin"#,
            r#"cargo build --target=aarch64-apple-darwin --config 'build.target="x86_64-unknown-linux-gnu"'"#,
            r#"cargo build --config 'build.target="x86_64-unknown-linux-gnu"' --config 'build.target="aarch64-apple-darwin"' --config 'build.jobs=2'"#,
            r#"cargo rustc --config 'build.target="aarch64-apple-darwin"' -- --target x86_64-unknown-linux-gnu"#,
        ] {
            assert_eq!(
                super::explicit_target_triple_for_command(command).as_deref(),
                Some("aarch64-apple-darwin"),
                "{command}"
            );
        }
        for command in [
            "cargo build --release",
            "cargo build --target-dir /tmp/target",
            "cargo test -- --target aarch64-apple-darwin",
            r#"cargo test -- --config 'build.target="aarch64-apple-darwin"'"#,
            "cargo build --config .cargo/extra.toml",
            r#"cargo build --config 'build.target-dir="aarch64-apple-darwin"'"#,
            r#"cargo build --config 'build.target=["aarch64-apple-darwin", "x86_64-unknown-linux-gnu"]'"#,
            "cargo build --config 'unterminated",
        ] {
            assert_eq!(
                super::explicit_target_triple_for_command(command),
                None,
                "{command}"
            );
        }
    }

    #[test]
    fn configured_cross_target_artifacts_exclude_host_tools_but_keep_target_guard() {
        use super::super::artifact_triple::foreign_target_artifacts;

        let command = r#"cargo build --release --config 'build.target="aarch64-apple-darwin"' --config 'target.aarch64-apple-darwin.linker="/usr/local/bin/zigcc-aarch64-darwin"'"#;
        let pinned = super::explicit_target_triple_for_command(command).unwrap();
        for custom in [false, true] {
            let dir = tempfile::tempdir().unwrap();
            let prefix = if custom { "" } else { "target/" };
            let host = format!("{prefix}release/deps/libclap_derive-fixture.so");
            let target = format!("{prefix}{pinned}/release/app");
            for path in [&host, &target] {
                std::fs::create_dir_all(dir.path().join(path).parent().unwrap()).unwrap();
            }
            std::fs::write(dir.path().join(&host), b"\x7fELF\0\0\0\0").unwrap();
            std::fs::write(dir.path().join(&target), b"\xcf\xfa\xed\xfe\0\0\0\0").unwrap();
            let manifest = vec![host.clone(), target.clone()];
            assert!(
                foreign_target_artifacts(dir.path(), &manifest, custom, &pinned, Some(&pinned))
                    .is_empty()
            );
            // The exclusion is only for host tools. A foreign binary under the
            // requested triple still fails, and native builds keep their guard.
            std::fs::write(dir.path().join(&target), b"\x7fELF\0\0\0\0").unwrap();
            let foreign =
                foreign_target_artifacts(dir.path(), &manifest, custom, &pinned, Some(&pinned));
            assert_eq!(foreign.len(), 1);
            assert_eq!(foreign[0].path, target);
            let native = foreign_target_artifacts(dir.path(), &manifest, custom, &pinned, None);
            assert_eq!(native.len(), 1);
            assert_eq!(native[0].path, host);
        }
    }

    #[cfg(unix)]
    struct ConfigGuardFixture {
        root: std::path::PathBuf,
        project: std::path::PathBuf,
        home: std::path::PathBuf,
        cargo: std::path::PathBuf,
        sentinel: std::path::PathBuf,
    }

    #[cfg(unix)]
    impl ConfigGuardFixture {
        fn new() -> Self {
            use std::os::unix::fs::PermissionsExt as _;

            let root = tempfile::Builder::new()
                .prefix("rch-cfg-")
                .tempdir_in("/tmp")
                .unwrap()
                .keep();
            let project = root.join("project");
            let home = root.join("cargo home");
            let cargo = root.join("cargo");
            let sentinel = root.join("child-started");
            std::fs::create_dir(&project).unwrap();
            std::fs::create_dir(&home).unwrap();
            std::fs::write(
                &cargo,
                "#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$RCH_CONFIG_GUARD_SENTINEL\"\n",
            )
            .unwrap();
            std::fs::set_permissions(&cargo, std::fs::Permissions::from_mode(0o700)).unwrap();
            Self {
                root,
                project,
                home,
                cargo,
                sentinel,
            }
        }

        fn run(&self, prefix: &str) -> std::process::Output {
            let command = format!(
                "{prefix} {} test -- 'literal $value; with spaces'",
                shell_words::quote(self.cargo.to_str().unwrap())
            );
            let guarded = super::guard_clean_overlay_cargo_config(&command).unwrap();
            std::process::Command::new("/bin/sh") // ubs:ignore — executes the quoted guard under test with owned fixture argv.
                .args(["-c", &guarded])
                .current_dir(&self.project)
                .env_clear()
                .env("PATH", "/usr/bin:/bin")
                .env("CARGO_HOME", &self.home)
                .env("RCH_CONFIG_GUARD_SENTINEL", &self.sentinel)
                .output()
                .unwrap()
        }

        fn assert_refused(&self, output: &std::process::Output) {
            assert_eq!(output.status.code(), Some(113), "{output:?}");
            assert_eq!(
                output.stderr,
                b"RCH-E413 clean-overlay unselected Cargo configuration\n"
            );
            assert!(output.stdout.is_empty());
            assert!(!self.sentinel.exists(), "Cargo child must not start");
        }
    }

    #[cfg(unix)]
    #[test]
    fn source_pair_config_guard_allows_clean_home_and_selected_project_config() {
        let fixture = ConfigGuardFixture::new();
        std::fs::create_dir(fixture.project.join(".cargo")).unwrap();
        std::fs::write(
            fixture.project.join(".cargo/config.toml"),
            "[build]\njobs=1\n",
        )
        .unwrap();
        let output = fixture.run("");
        assert!(output.status.success(), "{output:?}");
        assert!(output.stderr.is_empty());
        assert_eq!(
            std::fs::read_to_string(&fixture.sentinel).unwrap(),
            "test\n--\nliteral $value; with spaces\n"
        );
    }

    #[cfg(unix)]
    #[test]
    fn source_pair_config_guard_refuses_home_config_and_broken_symlink() {
        for name in ["config", "config.toml"] {
            for symlink in [false, true] {
                let fixture = ConfigGuardFixture::new();
                let path = fixture.home.join(name);
                if symlink {
                    std::os::unix::fs::symlink(fixture.root.join("absent"), &path).unwrap();
                } else {
                    std::fs::write(&path, "secret-looking-config-value").unwrap();
                }
                fixture.assert_refused(&fixture.run(""));
            }
        }
    }

    #[cfg(unix)]
    #[test]
    fn source_pair_config_guard_checks_inline_home_after_env_prefix() {
        let fixture = ConfigGuardFixture::new();
        let inline_home = fixture.root.join("inline 'cargo' home");
        std::fs::create_dir(&inline_home).unwrap();
        std::fs::write(inline_home.join("config.toml"), "must-not-be-printed").unwrap();
        let prefix = format!(
            "env -- CARGO_HOME={}",
            shell_words::quote(inline_home.to_str().unwrap())
        );
        fixture.assert_refused(&fixture.run(&prefix));
    }

    #[cfg(unix)]
    #[test]
    fn source_pair_config_guard_refuses_ancestor_config() {
        for name in ["config", "config.toml"] {
            let fixture = ConfigGuardFixture::new();
            std::fs::create_dir(fixture.root.join(".cargo")).unwrap();
            std::fs::write(fixture.root.join(".cargo").join(name), "unselected").unwrap();
            fixture.assert_refused(&fixture.run(""));
        }
    }

    #[cfg(unix)]
    #[test]
    fn source_pair_config_guard_refuses_unknown_home_and_non_directory() {
        for prefix in ["CARGO_HOME=relative", "CARGO_HOME=", "env -u CARGO_HOME"] {
            let fixture = ConfigGuardFixture::new();
            fixture.assert_refused(&fixture.run(prefix));
        }
        for exists in [false, true] {
            let fixture = ConfigGuardFixture::new();
            let unusable = fixture.root.join("unusable");
            if exists {
                std::fs::write(&unusable, "not a directory").unwrap();
            }
            let prefix = format!(
                "CARGO_HOME={}",
                shell_words::quote(unusable.to_str().unwrap())
            );
            fixture.assert_refused(&fixture.run(&prefix));
        }
    }

    #[test]
    fn source_pair_cargo_tokens_distinguishes_prefix_values_from_executable() {
        for (command, cargo_index) in [
            ("cargo test", 0),
            ("/opt/bin/cargo.exe +nightly test", 0),
            ("/usr/bin/time -f cargo cargo test", 3),
            ("rustup run cargo /opt/bin/cargo test", 3),
            (
                "CARGO_MARK='cargo' /usr/bin/time -f cargo env -u cargo -- X=cargo /opt/bin/cargo test",
                10,
            ),
        ] {
            let (tokens, actual_index) = managed_clean_overlay_cargo_tokens(command).unwrap();
            assert_eq!(actual_index, cargo_index, "{command}");
            let mut expected = shell_words::split(command).unwrap();
            if command.starts_with("CARGO_MARK=") {
                expected.insert(0, "env".to_string());
            }
            assert_eq!(tokens, expected, "{command}");
            assert!(matches!(
                std::path::Path::new(&tokens[actual_index])
                    .file_name()
                    .unwrap()
                    .to_str(),
                Some("cargo" | "cargo.exe")
            ));
        }
    }

    #[test]
    fn source_pair_cargo_tokens_rejects_unfinished_syntax_but_keeps_literal_backslash() {
        for command in [
            "cargo test --manifest-path unfinished\\",
            "cargo test --manifest-path \"unfinished",
            "cargo test --manifest-path 'unfinished",
        ] {
            assert!(
                managed_clean_overlay_cargo_tokens(command).is_err(),
                "{command:?}"
            );
        }
        for command in [
            r#"cargo test --manifest-path 'trailing\'"#,
            r#"cargo test --manifest-path "trailing\\""#,
        ] {
            let (tokens, index) = managed_clean_overlay_cargo_tokens(command).unwrap();
            assert_eq!(index, 0);
            assert_eq!(
                tokens,
                ["cargo", "test", "--manifest-path", "trailing\\"]
                    .into_iter()
                    .map(str::to_owned)
                    .collect::<Vec<_>>()
            );
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn source_pair_build_dir_real_cargo_overrides_file_env_and_cli() {
        use std::io::Read as _;
        use std::path::{Path, PathBuf};

        let root = tempfile::tempdir().unwrap().keep();
        for directory in ["src", ".cargo", "bin", "cargo-home"] {
            std::fs::create_dir(root.join(directory)).unwrap();
        }
        std::fs::write(root.join("Cargo.toml"), "[package]\nname='managed_build_dir_fixture'\nversion='0.1.0'\nedition='2024'\n[workspace]\n").unwrap();
        std::fs::write(root.join("fixture.txt"), "sealed fixture").unwrap();
        std::fs::write(root.join("src/lib.rs"), "#[test] fn reads_fixture() { let root = std::path::Path::new(env!(\"CARGO_MANIFEST_DIR\")); assert_eq!(std::fs::read_to_string(root.join(\"fixture.txt\")).unwrap(), \"sealed fixture\"); }\n").unwrap();
        let outside: Vec<_> = ["outside-A", "outside-B", "outside-C"]
            .into_iter()
            .map(|name| root.join(name))
            .collect();
        let config_value = |path: &Path| toml::Value::String(path.to_str().unwrap().to_string());
        std::fs::write(
            root.join(".cargo/config.toml"),
            format!("[build]\nbuild-dir={}\n", config_value(&outside[0])),
        )
        .unwrap();
        // The harness's Cargo identifies the compiler used to build this test.
        // A managed toolchain shim retains its real executable beside it.
        let mut cargo = PathBuf::from(env!("CARGO"));
        if std::fs::metadata(&cargo).unwrap().len() <= 8 * 1024
            && std::fs::read_to_string(&cargo)
                .unwrap()
                .lines()
                .any(|line| line.starts_with("# rch-toolchain-wrap-version:"))
        {
            cargo.set_file_name("cargo-rch-real");
        }
        let mut magic = [0; 4];
        std::fs::File::open(&cargo)
            .unwrap()
            .read_exact(&mut magic)
            .unwrap();
        assert_eq!(
            &magic, b"\x7fELF",
            "fixture must execute a real Cargo binary"
        );
        let cargo_bin = cargo.parent().unwrap();
        let executable = root.join("bin/cargo");
        std::os::unix::fs::symlink(&cargo, &executable).unwrap();
        let path = std::env::join_paths(
            std::iter::once(cargo_bin.to_path_buf())
                .chain(std::env::split_paths(&std::env::var_os("PATH").unwrap())),
        )
        .unwrap();
        let pool = root.join("managed pool");
        for (subcommand, passthrough) in [("test", "--nocapture"), ("clippy", "-D warnings")] {
            let command = format!(
                "{} {subcommand} --offline --jobs 1 --message-format=json --config {} -- {passthrough}",
                shell_words::quote(executable.to_str().unwrap()),
                shell_words::quote(&format!("build.build-dir={}", config_value(&outside[2])))
            );
            let managed =
                managed_clean_overlay_cargo_build_dir(&command, pool.to_str().unwrap()).unwrap();
            let output = std::process::Command::new("sh") // ubs:ignore — executes the managed argv rewriter against an owned fixture.
                .args(["-c", &managed])
                .current_dir(&root)
                .env("PATH", &path)
                .env("CARGO_HOME", root.join("cargo-home"))
                .env("CARGO_BUILD_BUILD_DIR", &outside[1])
                .env("CARGO_TARGET_DIR", &pool)
                .env("RUSTC", cargo_bin.join("rustc"))
                .env("RUSTFLAGS", "")
                .env("RUSTUP_AUTO_INSTALL", "0")
                .env("RCH_CARGO_WRAPPER_BYPASS", "1")
                .env_remove("RUSTUP_TOOLCHAIN")
                .env_remove("CARGO_ENCODED_RUSTFLAGS")
                .env_remove("CARGO_BUILD_RUSTC")
                .env_remove("CARGO_BUILD_TARGET")
                .env_remove("CARGO_BUILD_TARGET_DIR")
                .env_remove("CARGO_BUILD_RUSTFLAGS")
                .env_remove("RUSTC_WRAPPER")
                .env_remove("RUSTC_WORKSPACE_WRAPPER")
                .env_remove("CARGO_BUILD_RUSTC_WRAPPER")
                .env_remove("CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER")
                .output()
                .unwrap();
            let stdout = String::from_utf8(output.stdout).unwrap();
            assert!(
                output.status.success(),
                "{subcommand}: {stdout}\n{}",
                String::from_utf8_lossy(&output.stderr)
            );
            let artifacts: Vec<_> = stdout
                .lines()
                .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
                .filter(|message| {
                    message["reason"] == "compiler-artifact"
                        && message["target"]["name"] == "managed_build_dir_fixture"
                })
                .collect();
            assert!(
                !artifacts.is_empty(),
                "real compiler artifact receipt required: {stdout}"
            );
            for artifact in artifacts {
                assert_eq!(
                    artifact["manifest_path"].as_str(),
                    root.join("Cargo.toml").to_str()
                );
                assert!(!artifact["filenames"].as_array().unwrap().is_empty());
                for filename in artifact["filenames"].as_array().unwrap() {
                    let filename = Path::new(filename.as_str().unwrap());
                    assert!(
                        filename.starts_with(&pool) && filename.is_file(),
                        "{}",
                        filename.display()
                    );
                }
            }
            if subcommand == "test" {
                assert!(stdout.contains("test reads_fixture ... ok"), "{stdout}");
            }
            assert!(
                outside.iter().all(|path| !path.exists()),
                "unmanaged cache directory was created"
            );
        }
        eprintln!(
            "managed build-dir real Cargo evidence retained at {}",
            root.display()
        );
    }

    #[test]
    fn source_pair_build_dir_keeps_wrappers_and_literal_arguments() {
        let command = "env -- CARGO_BUILD_BUILD_DIR='/outside cache' /usr/bin/time -f '%e seconds' rustup run nightly-2026-08-31 /opt/rust/bin/cargo +nightly test --config 'build.build-dir=\"/also outside\"' -p 'space name' -- 'literal $value; with quotes'";
        let target = "/managed/cache with 'single' and \"double\" quotes";
        let rewritten = managed_clean_overlay_cargo_build_dir(command, target).unwrap();
        let original = shell_words::split(command).unwrap();
        let actual = shell_words::split(&rewritten).unwrap();
        let separator = original.iter().rposition(|token| token == "--").unwrap();
        assert_eq!(&actual[..separator], &original[..separator]);
        assert_eq!(actual[separator], "--config");
        let config: toml::Value = toml::from_str(&actual[separator + 1]).unwrap();
        assert_eq!(config["build"]["build-dir"].as_str(), Some(target));
        assert_eq!(&actual[separator + 2..], &original[separator..]);
    }

    #[test]
    fn source_pair_build_dir_final_config_wins_before_clippy_passthrough() {
        let rewritten = managed_clean_overlay_cargo_build_dir(
            "RUSTC_WRAPPER='/wrapper with spaces' cargo --config 'build.build-dir=\"/global\"' clippy --all-targets --config=build.build-dir='\"/later\"' -- -D warnings",
            "/managed",
        ).unwrap();
        let tokens = shell_words::split(&rewritten).unwrap();
        assert_eq!(tokens[0], "env");
        assert_eq!(tokens[1], "RUSTC_WRAPPER=/wrapper with spaces");
        let separator = tokens.iter().position(|token| token == "--").unwrap();
        assert_eq!(&tokens[separator..], ["--", "-D", "warnings"]);
        assert_eq!(tokens[separator - 2], "--config");
        let config: toml::Value = toml::from_str(&tokens[separator - 1]).unwrap();
        assert_eq!(config["build"]["build-dir"].as_str(), Some("/managed"));
        assert!(
            tokens
                .iter()
                .any(|token| token == "--config=build.build-dir=\"/later\"")
        );
    }

    #[test]
    fn build_source_stamp_bind_places_config_before_cargo_separator() {
        let stamp = "a".repeat(40);
        let vergen_command = format!("env -- VERGEN_GIT_SHA={} cargo build", "b".repeat(40));
        let alias_command = format!(
            "RCH_GIT_COMMIT={} cargo test -- --config fixture",
            "c".repeat(40)
        );
        for command in [
            "cargo build",
            "cargo +nightly test -- --nocapture",
            "env -i cargo check",
            "env --debug cargo build",
            "env -uCARGO_HOME cargo build",
            "time -f%U cargo build",
            "time -l cargo build",
            "cargo-zigbuild zigbuild --target x86_64-unknown-linux-gnu",
            "env -i /opt/bin/cargo-zigbuild build --release",
            "rustup run nightly cargo-zigbuild zigbuild --locked",
            "cargo-xwin xwin build --release",
            "nice -n 10 cargo build",
            "nice --adjustment=+5 cargo build",
            "timeout -s KILL 90 cargo test -- --nocapture",
            "ionice -c 2 -n 4 cargo build",
            "sudo nice -n 5 cargo build",
            "/usr/bin/time -f cargo nice -n 5 cargo build",
            vergen_command.as_str(),
            alias_command.as_str(),
            "/usr/bin/time -f cargo rustup run nightly cargo build",
        ] {
            let bound = super::bind_build_source_stamp(command, &stamp)
                .unwrap_or_else(|error| panic!("{command}: {error}"));
            let original = shell_words::split(command).unwrap();
            let mut expected = original.clone();
            if original.first().is_some_and(|token| {
                token.split_once('=').is_some_and(|(key, _)| {
                    !key.is_empty()
                        && key
                            .chars()
                            .all(|ch| ch == '_' || ch.is_ascii_alphanumeric())
                })
            }) {
                expected.insert(0, "env".to_string());
            }
            let actual = shell_words::split(&bound).unwrap();
            let configs: Vec<_> = actual
                .iter()
                .enumerate()
                .filter(|(index, token)| {
                    *token == "--config" && actual[index + 1].starts_with("env.RCH_BUILD_SOURCE.")
                })
                .collect();
            assert_eq!(configs.len(), 2, "{command}: {bound}");
            let (config_index, _) = configs[0];
            let value_config: toml::Value = toml::from_str(&actual[config_index + 1]).unwrap();
            assert_eq!(
                value_config["env"]["RCH_BUILD_SOURCE"]["value"].as_str(),
                Some(stamp.as_str()),
                "{command}"
            );
            assert_eq!(actual[config_index + 2], "--config", "{command}: {bound}");
            let force_config: toml::Value = toml::from_str(&actual[config_index + 3]).unwrap();
            assert_eq!(
                force_config["env"]["RCH_BUILD_SOURCE"]["force"].as_bool(),
                Some(true),
                "{command}"
            );
            assert_eq!(
                &actual[..config_index],
                &expected[..config_index],
                "{command}"
            );
            assert_eq!(
                &actual[config_index + 4..],
                &expected[config_index..],
                "{command}"
            );
            if let Some(token) = expected.get(config_index) {
                assert_eq!(token, "--", "{command}: {bound}");
            } else {
                assert_eq!(config_index, expected.len(), "{command}: {bound}");
            }
        }
    }

    #[test]
    fn build_source_stamp_binds_nextest_with_value_config_and_process_env() {
        let stamp = format!("{}-dirty", "a".repeat(40));
        for (command, expected) in [
            (
                "cargo nextest run --workspace",
                "env RCH_BUILD_SOURCE={stamp} cargo nextest run --workspace --config {value}",
            ),
            (
                "cargo +nightly nextest run -- --nocapture",
                "env RCH_BUILD_SOURCE={stamp} cargo +nightly nextest run --config {value} -- --nocapture",
            ),
            (
                "cargo --color never --locked nextest run",
                "env RCH_BUILD_SOURCE={stamp} cargo --color never --locked nextest run --config {value}",
            ),
            (
                "CARGO_TERM_COLOR=never cargo nextest run",
                "env CARGO_TERM_COLOR=never env RCH_BUILD_SOURCE={stamp} cargo nextest run --config {value}",
            ),
            (
                "rustup run nightly cargo nextest run",
                "rustup run nightly env RCH_BUILD_SOURCE={stamp} cargo nextest run --config {value}",
            ),
        ] {
            let value = format!(
                "env.RCH_BUILD_SOURCE.value={}",
                toml::Value::String(stamp.clone())
            );
            let expected: Vec<String> = expected
                .split(' ')
                .map(|token| token.replace("{stamp}", &stamp).replace("{value}", &value))
                .collect();
            let bound = super::bind_build_source_stamp(command, &stamp)
                .unwrap_or_else(|error| panic!("{command}: {error}"));
            assert_eq!(shell_words::split(&bound).unwrap(), expected, "{command}");
            assert!(!bound.contains("force"), "{command}: {bound}");
        }
        // Not nextest: a `nextest` package name or test filter keeps the cargo form.
        for command in ["cargo test nextest", "cargo -C nextest build"] {
            let bound = super::bind_build_source_stamp(command, &stamp).unwrap();
            assert!(
                bound.contains("env.RCH_BUILD_SOURCE.force=true") && !bound.starts_with("env "),
                "{command}: {bound}"
            );
        }
    }

    /// The bound command must run under real cargo-nextest, which rejected the
    /// former `--config env.RCH_BUILD_SOURCE.force=true` with exit 96 (bd-k90ud).
    #[test]
    fn build_source_stamp_real_nextest_accepts_bound_command() {
        let cargo = std::path::PathBuf::from(env!("CARGO"));
        let cargo_bin = cargo.parent().unwrap().to_path_buf();
        let path = std::env::join_paths(std::iter::once(cargo_bin.clone()).chain(
            std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()),
        ))
        .unwrap();
        let cargo_home_bin = std::env::var_os("CARGO_HOME")
            .map(std::path::PathBuf::from)
            .or_else(|| {
                std::env::var_os("HOME").map(|home| std::path::Path::new(&home).join(".cargo"))
            })
            .map(|home| home.join("bin"));
        let has_nextest = std::env::split_paths(&path)
            .chain(cargo_home_bin)
            .any(|directory| directory.join("cargo-nextest").is_file());
        if !has_nextest {
            eprintln!("skipping: cargo-nextest is not installed");
            return;
        }
        let root = tempfile::tempdir().unwrap();
        std::fs::create_dir(root.path().join("src")).unwrap();
        std::fs::write(
            root.path().join("Cargo.toml"),
            "[package]\nname='nextest_stamp_fixture'\nversion='0.1.0'\nedition='2021'\n[workspace]\n",
        )
        .unwrap();
        std::fs::write(
            root.path().join("src/lib.rs"),
            "#[test]\nfn stamp() {\n    assert_eq!(env!(\"RCH_BUILD_SOURCE\"), \"bound\");\n    \
             assert_eq!(std::env::var(\"RCH_BUILD_SOURCE\").unwrap(), \"bound\");\n}\n",
        )
        .unwrap();
        let bound = super::bind_build_source_stamp("cargo nextest run", "bound").unwrap();
        let output = std::process::Command::new("/bin/sh")
            .args(["-c", &bound])
            .current_dir(root.path())
            .env("PATH", &path)
            .env("CARGO_TARGET_DIR", root.path().join("target"))
            .env("RCH_BUILD_SOURCE", "ambient")
            .env("RCH_CARGO_WRAPPER_BYPASS", "1")
            .env_remove("CARGO_BUILD_TARGET_DIR")
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "{bound}: {:?}\n{}",
            output.status,
            String::from_utf8_lossy(&output.stderr)
        );
    }

    #[test]
    fn build_source_stamp_bind_rejects_shell_evaluation_and_bad_stamps() {
        let stamp = "a".repeat(40);
        assert!(super::bind_build_source_stamp("cargo build $FLAGS", &stamp).is_err());
        assert!(super::bind_build_source_stamp("cargo build; echo x", &stamp).is_err());
        assert!(super::bind_build_source_stamp("env --debug cargo build; echo x", &stamp).is_err());
        assert!(super::bind_build_source_stamp("env -u cargo build", &stamp).is_err());
        assert!(super::bind_build_source_stamp("cargo test `id`", &stamp).is_err());
        assert!(super::bind_build_source_stamp("sh -c 'cargo test'", &stamp).is_err());
        assert!(super::bind_build_source_stamp("cargo build", "").is_err());
        assert!(super::bind_build_source_stamp("cargo build", "bad\nstamp").is_err());
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn build_source_stamp_real_cargo_binds_stamp_through_build_script() {
        use std::io::Read as _;
        use std::path::PathBuf;

        let root = tempfile::tempdir().unwrap().keep();
        for directory in ["src", "bin", "cargo-home", "target", ".cargo"] {
            std::fs::create_dir(root.join(directory)).unwrap();
        }
        std::fs::write(
            root.join("Cargo.toml"),
            "[package]\nname='build_source_stamp_fixture'\nversion='0.1.0'\nedition='2021'\n[workspace]\n",
        )
        .unwrap();
        std::fs::write(
            root.join("build.rs"),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../rch-common/build.rs"
            )),
        )
        .unwrap();
        std::fs::write(
            root.join("src/main.rs"),
            "fn main() { println!(\"{}\", option_env!(\"RCH_GIT_COMMIT\").unwrap_or(\"\")); }\n",
        )
        .unwrap();
        let fixture_git = |args: &[&str]| {
            let output = std::process::Command::new("git")
                .current_dir(&root)
                .args(args)
                .output()
                .expect("git fixture command runs");
            assert!(
                output.status.success(),
                "git {args:?}: {}",
                String::from_utf8_lossy(&output.stderr)
            );
            String::from_utf8(output.stdout).unwrap().trim().to_owned()
        };
        fixture_git(&["init", "-q", "-b", "main"]);
        fixture_git(&["add", "Cargo.toml", "build.rs", "src/main.rs"]);
        fixture_git(&[
            "-c",
            "user.name=RCH-Test",
            "-c",
            "user.email=rch-test@example.invalid",
            "commit",
            "-q",
            "--no-gpg-sign",
            "-m",
            "fixture",
        ]);
        let fixture_head = fixture_git(&["rev-parse", "HEAD"]);
        assert_ne!(fixture_head, "a".repeat(40));

        let mut cargo = PathBuf::from(env!("CARGO"));
        if std::fs::metadata(&cargo).unwrap().len() <= 8 * 1024
            && std::fs::read_to_string(&cargo)
                .unwrap()
                .lines()
                .any(|line| line.starts_with("# rch-toolchain-wrap-version:"))
        {
            cargo.set_file_name("cargo-rch-real");
        }
        let mut magic = [0; 4];
        std::fs::File::open(&cargo)
            .unwrap()
            .read_exact(&mut magic)
            .unwrap();
        assert_eq!(
            &magic, b"\x7fELF",
            "fixture must execute a real Cargo binary"
        );
        let cargo_bin = cargo.parent().unwrap();
        let executable = root.join("bin/cargo");
        std::os::unix::fs::symlink(&cargo, &executable).unwrap();
        let path = std::env::join_paths(
            std::iter::once(cargo_bin.to_path_buf())
                .chain(std::env::split_paths(&std::env::var_os("PATH").unwrap())),
        )
        .unwrap();
        let rustc = cargo_bin.join("rustc");

        let source_a = "a".repeat(40);
        let dirty_a = format!("{source_a}-dirty");
        let overlay = format!("{source_a}-overlay-{}", "b".repeat(64));
        let alias_c = "c".repeat(40);
        let alias_d = "d".repeat(40);
        let alias = |key: &str, value: &str| {
            [(key.to_owned(), value.to_owned())]
                .into_iter()
                .collect::<std::collections::HashMap<_, _>>()
        };
        let cases: Vec<(&str, &str, std::collections::HashMap<String, String>, &str)> = vec![
            ("plain", &source_a, Default::default(), &source_a),
            ("dirty", &dirty_a, Default::default(), &dirty_a),
            ("overlay", &overlay, Default::default(), &overlay),
            ("unknown-stamp", "unknown", Default::default(), ""),
            ("malformed-stamp", "not a stamp!", Default::default(), ""),
            ("cargo-cli-config", &source_a, Default::default(), &alias_d),
            (
                "cargo-project-config",
                &source_a,
                Default::default(),
                &alias_d,
            ),
            (
                "cargo-cli-config-caller-wins",
                &source_a,
                alias("VERGEN_GIT_SHA", &alias_c),
                &alias_c,
            ),
            (
                "cargo-cli-config-empty-caller",
                &source_a,
                alias("VERGEN_GIT_SHA", ""),
                &source_a,
            ),
            (
                "cargo-cli-config-invalid-caller",
                &source_a,
                alias("VERGEN_GIT_SHA", "not-a-revision"),
                &source_a,
            ),
            (
                "explicit-rch-git-commit",
                &source_a,
                alias("RCH_GIT_COMMIT", &alias_c),
                &alias_c,
            ),
            (
                "explicit-vergen",
                &source_a,
                alias("VERGEN_GIT_SHA", &alias_d),
                &alias_d,
            ),
            (
                "caller-alias-precedence",
                &source_a,
                [
                    ("RCH_GIT_COMMIT".to_owned(), alias_c.clone()),
                    ("VERGEN_GIT_SHA".to_owned(), alias_d.clone()),
                ]
                .into_iter()
                .collect(),
                &alias_c,
            ),
        ];
        for (name, stamp, aliases, expected_stdout) in &cases {
            std::fs::write(
                root.join(".cargo/config.toml"),
                if *name == "cargo-project-config" {
                    format!("[env]\nVERGEN_GIT_SHA = '{alias_d}'\n")
                } else {
                    String::new()
                },
            )
            .unwrap();
            let extra_config = if name.starts_with("cargo-cli-config") {
                format!(
                    " --config {}",
                    shell_words::quote(&format!("env.VERGEN_GIT_SHA='{alias_d}'"))
                )
            } else {
                String::new()
            };
            let command = format!(
                "{} run --quiet --offline --jobs 1{extra_config}",
                shell_words::quote(executable.to_str().unwrap())
            );
            let bound = super::bind_build_source_stamp(&command, stamp).unwrap();
            let env = super::super::source_fidelity::build_source_commit_env(|key| {
                aliases.get(key).cloned()
            });
            let bound = super::super::source_fidelity::bind_build_source_aliases(&bound, &env);
            let mut process = std::process::Command::new("sh");
            process
                .args(["-c", &bound])
                .current_dir(&root)
                .env("PATH", &path)
                .env("HOME", &root)
                .env("CARGO_HOME", root.join("cargo-home"))
                .env("CARGO_TARGET_DIR", root.join("target"))
                .env("RUSTC", &rustc)
                .env("RUSTFLAGS", "")
                .env("RUSTUP_AUTO_INSTALL", "0")
                .env("RCH_CARGO_WRAPPER_BYPASS", "1")
                .env_remove("RUSTUP_TOOLCHAIN")
                .env_remove("CARGO_ENCODED_RUSTFLAGS")
                .env_remove("CARGO_BUILD_RUSTC")
                .env_remove("CARGO_BUILD_TARGET")
                .env_remove("CARGO_BUILD_TARGET_DIR")
                .env_remove("CARGO_BUILD_RUSTFLAGS")
                .env_remove("RUSTC_WRAPPER")
                .env_remove("RUSTC_WORKSPACE_WRAPPER")
                .env_remove("CARGO_BUILD_RUSTC_WRAPPER")
                .env_remove("CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER")
                .env_remove("RCH_BUILD_SOURCE");
            for key in rch_common::BUILD_COMMIT_ENV_VARS {
                process.env(key, "e".repeat(40));
            }
            let output = process.output().unwrap();
            let stdout = String::from_utf8(output.stdout).unwrap();
            assert!(
                output.status.success(),
                "{name}: {stdout}\n{}",
                String::from_utf8_lossy(&output.stderr)
            );
            assert_eq!(
                stdout.trim_end(),
                *expected_stdout,
                "{name}: stderr={}",
                String::from_utf8_lossy(&output.stderr)
            );
        }

        let env_i_command = format!(
            "env -i PATH={} HOME={} RUSTC={} CARGO_HOME={} CARGO_TARGET_DIR={} RUSTUP_AUTO_INSTALL=0 RCH_CARGO_WRAPPER_BYPASS=1 {} run --quiet --offline --jobs 1",
            shell_words::quote(path.to_str().unwrap()),
            shell_words::quote(root.to_str().unwrap()),
            shell_words::quote(rustc.to_str().unwrap()),
            shell_words::quote(root.join("cargo-home").to_str().unwrap()),
            shell_words::quote(root.join("target").to_str().unwrap()),
            shell_words::quote(executable.to_str().unwrap()),
        );
        let bound = super::bind_build_source_stamp(&env_i_command, &source_a).unwrap();
        let bound = super::super::source_fidelity::bind_build_source_aliases(
            &bound,
            &alias("RCH_GIT_COMMIT", &alias_c),
        );
        let output = std::process::Command::new("sh")
            .args(["-c", &bound])
            .current_dir(&root)
            .output()
            .unwrap();
        let stdout = String::from_utf8(output.stdout).unwrap();
        assert!(
            output.status.success(),
            "env -i: {stdout}\n{}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(
            stdout.trim_end(),
            source_a,
            "env -i: stderr={}",
            String::from_utf8_lossy(&output.stderr)
        );
        std::fs::write(
            root.join(".cargo/config.toml"),
            format!("[env]\nVERGEN_GIT_SHA = '{alias_d}'\n"),
        )
        .unwrap();
        let output = std::process::Command::new("sh")
            .args(["-c", &bound])
            .current_dir(&root)
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "env -i with config: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(
            String::from_utf8(output.stdout).unwrap().trim_end(),
            alias_d,
            "Cargo config must apply after caller env -i clears restored aliases"
        );
        eprintln!(
            "build-source real Cargo evidence retained at {}",
            root.display()
        );
    }

    #[test]
    fn managed_xwin_build_preserves_plugin_argv_and_original_output_policy() {
        for command in [
            "cargo xwin build --release --target=x86_64-pc-windows-msvc --bin cli",
            "cargo +nightly xwin build --release '--target=aarch64-pc-windows-msvc' --bin cli",
            "cargo-xwin build --release --target=x86_64-pc-windows-msvc --bin cli",
            "cargo-xwin xwin build --release --target=x86_64-pc-windows-msvc --bin cli",
        ] {
            let managed = super::ManagedCargoCommand::new(command, Some("/managed/cache")).unwrap();
            let original = shell_words::split(command).unwrap();
            let actual = shell_words::split(managed.execution_command()).unwrap();
            assert_eq!(&actual[..original.len()], original.as_slice(), "{command}");
            assert_eq!(actual[original.len()], "--config");
            assert_eq!(
                actual[original.len() + 1],
                "build.build-dir=\"/managed/cache\""
            );
            assert_eq!(actual.len(), original.len() + 2);
            assert_eq!(managed.policy_command(), command);
            assert!(rch_common::patterns::is_cargo_xwin_build(
                managed.policy_command()
            ));
        }
        for command in [
            "cargo xwin check --bin cli",
            "cargo xwin build --help",
            "cargo xwin install cli",
            "cargo-xwin +nightly build --bin cli",
            "cargo-xwin xwin test --bin cli",
            "cargo xwin build --build-dir=/unmanaged",
            "cargo xwin build --bin cli; echo surprise",
        ] {
            assert!(
                super::ManagedCargoCommand::new(command, Some("/managed/cache")).is_err(),
                "{command}"
            );
        }
    }

    #[test]
    fn source_pair_build_dir_preserves_format_and_refuses_ambiguous_commands() {
        let fmt = "env RUSTUP_TOOLCHAIN=nightly cargo fmt --check";
        assert_eq!(
            managed_clean_overlay_cargo_build_dir(fmt, "/managed").unwrap(),
            fmt
        );
        for command in [
            "",
            "cargo",
            "cargo-zigbuild build --release",
            "nice -n 5 cargo build",
            "env --debug cargo build",
            "cargo --config",
            "cargo test 'unterminated",
            "cargo test; echo surprise",
            "cargo test $(echo filter)",
            "cargo test $FILTER",
            "cargo test > output",
            "sh -c 'cargo test'",
            "env -S 'cargo test'",
            "env -u",
            "rustup run",
            "cargo custom-build",
            "cargo test --build-dir /unmanaged",
            "cargo test --build-dir=/unmanaged",
        ] {
            assert!(
                managed_clean_overlay_cargo_build_dir(command, "/managed").is_err(),
                "{command}"
            );
        }
        assert!(managed_clean_overlay_cargo_build_dir("cargo test", "").is_err());
        assert!(managed_clean_overlay_cargo_build_dir("cargo test", "/bad\npath").is_err());
        // This is a test-binary argument, not an override of Cargo's cache.
        let passthrough =
            managed_clean_overlay_cargo_build_dir("cargo test -- --build-dir=/literal", "/managed")
                .unwrap();
        assert_eq!(
            shell_words::split(&passthrough).unwrap().last().unwrap(),
            "--build-dir=/literal"
        );
    }

    #[test]
    fn target_dir_scope_wrappers_and_cli_precedence_agree_with_removal() {
        for command in [
            "env -- cargo build --target-dir 'caller target'",
            "/usr/bin/time -f cargo -- cargo build --target-dir='caller target'",
            "env -- rustup run nightly cargo +nightly test --target-dir 'caller target' -- --target-dir=program-value",
            "nice -n 10 cargo build --target-dir 'caller target'",
            "CARGO_TARGET_DIR=env-target cargo build --target-dir 'caller target'",
            "env -- CARGO_TARGET_DIR=env-target cargo build --target-dir 'caller target'",
        ] {
            let tokens = shell_words::split(command).unwrap();
            assert_eq!(
                super::extract_cargo_target_dir_from_command_tokens(&tokens).as_deref(),
                Some("caller target"),
                "{command}"
            );
            let (span, _) = super::cargo_target_dir_flag_span(&tokens).unwrap();
            let mut expected = tokens.clone();
            expected.drain(span);
            assert_eq!(
                super::strip_cargo_target_dir_flags_from_command_tokens(&tokens),
                Some(expected),
                "{command}"
            );
            let reporter = super::HookReporter::new(super::OutputVisibility::None);
            let local = super::resolve_forwarded_cargo_target_dir_with_lookup(
                Some(super::CompilationKind::CargoBuild),
                std::path::Path::new("/project"),
                &reporter,
                |_| Some("ambient-target".to_string()),
                Some(&tokens),
            )
            .unwrap();
            assert_eq!(local, std::path::Path::new("/project/caller target"));
            let rewritten = super::rewrite_cargo_target_dir_command_for_remote(
                command,
                Some(&tokens),
                Some(&local),
                &reporter,
            );
            assert!(
                super::cargo_target_dir_flag_span(&shell_words::split(&rewritten).unwrap())
                    .is_none(),
                "caller target-dir survived in remote Cargo argv: {rewritten}"
            );
        }
    }

    #[test]
    fn target_dir_scope_keeps_opaque_values_passthrough_and_invalid_options() {
        for option in [
            "--config",
            "--target",
            "--manifest-path",
            "--lockfile-path",
            "--profile",
            "--package",
            "-p",
            "--exclude",
            "--features",
            "-F",
            "--bin",
            "--example",
            "--test",
            "--bench",
            "--color",
            "--message-format",
            "--jobs",
            "-j",
            "-Z",
            "-C",
            "--artifact-dir",
            "--out-dir",
            "--build-dir",
        ] {
            let tokens = shell_words::split(&format!(
                "env -- cargo build {option} --target-dir=decoy --target-dir actual -- --target-dir=program"
            ))
            .unwrap();
            assert_eq!(
                super::extract_cargo_target_dir_from_command_tokens(&tokens).as_deref(),
                Some("actual"),
                "{option}"
            );
            let stripped =
                super::strip_cargo_target_dir_flags_from_command_tokens(&tokens).unwrap();
            assert!(stripped.iter().any(|word| word == "--target-dir=decoy"));
            assert_eq!(stripped.last().unwrap(), "--target-dir=program");
        }
        for command in [
            "env -- cargo test -- --target-dir=program",
            "cargo build --config --target-dir=decoy",
            "/usr/bin/time -f --target-dir=decoy cargo build",
            "env -u --target-dir=decoy cargo build",
            "printf cargo --target-dir decoy",
            "cargo build --target-dir",
            "cargo build --target-dir=",
            "cargo build --target-dir --release",
            "cargo build --target-dir one --target-dir two",
        ] {
            let tokens = shell_words::split(command).unwrap();
            assert_eq!(
                super::cargo_target_dir_flag_span(&tokens),
                None,
                "{command}"
            );
            assert_eq!(
                super::strip_cargo_target_dir_flags_from_command_tokens(&tokens),
                None,
                "{command}"
            );
        }
    }
}