corgi-build 0.1.0

PoC: deterministic, content-addressed, lock-free cargo-compatible build tool
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
use crate::meta::{self, Metadata, Package, Target};
use crate::store::{sha256_hex, Store};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Condvar, Mutex, OnceLock};
use std::time::Instant;

const TOOL_VERSION: &str = "corgi/0.21";

// Profiles come per unit from cargo's unit graph — inheritance,
// build-override, per-package overrides, and platform defaults already
// resolved by cargo (see meta::UgProfile). The resolved flags are part
// of every action key, and the store is append-only, so profiles
// coexist and never evict each other. Deliberate divergences:
// - lto is not supported yet (warned once, built without);
// - darwin linking units always get split-debuginfo=unpacked with
//   -oso_prefix, whatever the profile says: determinism requires it
//   (staging paths would otherwise leak into debug-map stabs);
// - incremental and rpath are ignored.

#[derive(Clone, Copy, PartialEq)]
pub enum Mode {
    Build,
    /// Build, then execute the root binary exactly as a manual run of the
    /// exported artifact: ambient env, the caller's cwd, inherited stdio.
    Run,
    Check,
    /// Check mode with clippy-driver as the executor for workspace-member
    /// units (their own key namespace; the dependency layer is shared
    /// with plain check).
    Clippy,
    Test,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Kind {
    Lib,
    Bsc, // compile build.rs
    Bsr, // run build.rs
    Bin,
    Test, // test harness executable (rustc --test)
}

struct UnitDep {
    unit: usize,
    extern_name: Option<String>,
}

struct Unit {
    pkg: usize,
    kind: Kind,
    /// compiled for the host triple (proc-macros, build scripts, their deps);
    /// false = compiled for --target
    host: bool,
    is_root: bool,
    target: Target,
    features: Vec<String>,
    deps: Vec<UnitDep>,
    profile: meta::UgProfile,
}

#[derive(Clone, Serialize, Deserialize, Default)]
struct BuildScriptOut {
    cfgs: Vec<String>,
    envs: Vec<(String, String)>,
    link_libs: Vec<String>,
    link_search: Vec<String>,
    link_args: Vec<String>,
    metadata: Vec<(String, String)>,
    stdout: String,
}

#[derive(Clone, Serialize, Deserialize)]
struct OutputFile {
    name: String,
    hash: String,
    exe: bool,
}

#[derive(Clone, Serialize, Deserialize, Default)]
struct ActionResult {
    #[serde(default)]
    outputs: Vec<OutputFile>,
    #[serde(default)]
    stderr: String,
    #[serde(default)]
    bs: Option<BuildScriptOut>,
}

#[derive(Clone)]
/// Early (meta-ready) result of a pipelined lib compile: published the
/// moment rustc reports the rmeta written, while its codegen continues.
/// Enough for dependent compiles to key themselves and start.
struct MetaOut {
    /// Pool-addressed (key-spliced) file name of the rmeta.
    file: String,
    hash: String,
}

/// The crate type a unit compiles as (mirrors the logic in `compile`).
fn unit_crate_type(unit: &Unit) -> String {
    match unit.kind {
        Kind::Lib => {
            if unit.target.kind.iter().any(|k| k == "proc-macro") {
                "proc-macro".to_string()
            } else if unit.is_root && unit.target.crate_types.iter().any(|c| c == "cdylib") {
                unit.target.crate_types.join(",")
            } else {
                "lib".to_string()
            }
        }
        Kind::Bsc | Kind::Bin | Kind::Test => "bin".to_string(),
        Kind::Bsr => String::new(),
    }
}

/// Pipelined producers: pure-rlib libs, which emit an rmeta early.
fn unit_pipelined(unit: &Unit) -> bool {
    matches!(unit.kind, Kind::Lib) && unit_crate_type(unit) == "lib"
}

/// Linking consumers hand every transitive rlib to the linker, so they
/// need full artifacts of their whole closure; pure-rlib compiles only
/// need dependency *metadata*.
fn unit_links(unit: &Unit) -> bool {
    match unit.kind {
        Kind::Bin | Kind::Bsc | Kind::Test => true,
        Kind::Lib => unit_crate_type(unit) != "lib",
        Kind::Bsr => false,
    }
}

/// Under `check`, units outside every execution closure (build scripts,
/// proc-macros) emit metadata only: they neither link nor produce rlibs.
fn is_checked(ctx: &Ctx, idx: usize) -> bool {
    ctx.check_mode.get(idx).copied().unwrap_or(false)
}

fn is_pipelined(ctx: &Ctx, idx: usize) -> bool {
    unit_pipelined(&ctx.units[idx]) || is_checked(ctx, idx)
}

fn is_linking(ctx: &Ctx, idx: usize) -> bool {
    unit_links(&ctx.units[idx]) && !is_checked(ctx, idx)
}

/// A pinned tool ready for scoped injection into build-script runs.
struct ToolRt {
    name: String,
    version: String,
    env: String,
    value: String,
    /// Identity of the *setting*: hash of the pin itself. Scoped actions
    /// key on this, nothing else does.
    id: String,
    bin: String,
    packages: Vec<String>,
}

/// Where an action's wall time went (ns), for the timings report.
#[derive(Default, Clone, Copy)]
struct Phases {
    key_ns: u64,
    cache_ns: u64,
    rustc_ns: u64,
    validate_ns: u64,
    ingest_ns: u64,
    ingest_bytes: u64,
    finish_ns: u64,
}

struct UnitResult {
    key: String,
    cached: bool,
    res: ActionResult,
    main: Option<OutputFile>,
    phases: Phases,
}

pub struct Ctx {
    store: Store,
    verbose: bool,
    rustc: String,
    rustc_version: String,
    host: String,
    cfg_env: Vec<(String, String)>,
    meta: Metadata,
    units: Vec<Unit>,
    pool: PathBuf,
    /// Pool as spelled on rustc command lines: the *logical* store path.
    /// Physical per-store paths leak into linked artifacts (debug-info OSO
    /// references to C objects inside dep rlibs record the archive path).
    pool_logical: PathBuf,
    cargo: String,
    cargo_home: String,
    base_env: Vec<(String, String)>,
    workspace_root: String,
    sysroot: String,
    rustup_home: String,
    devdir: String,
    sandbox: bool,
    darwin_dirs: Vec<String>,
    sdkroot: String,
    src_hash_memo: Mutex<HashMap<usize, String>>,
    src_hash_nanos: std::sync::atomic::AtomicU64,
    file_names_memo: Mutex<HashMap<(String, bool), Vec<String>>>,
    /// target/<dir> layout name from the root units' resolved profile
    /// (cargo maps dev/test to "debug").
    profile_name: String,
    toolchain: String,
    /// Pinned tools resolved for injection: env var, logical path,
    /// identity hash, shim name/bin, and package scope (empty = all).
    tools: Vec<ToolRt>,
    /// Plan-time probe results: (name, value, packages, profiles).
    env_probes: Vec<(String, String, Vec<String>, Vec<String>)>,
    target: Option<String>,
    /// Emit a per-unit timing report (target/corgi-timings/).
    timings: bool,
    /// Dev-loop namespace: local units compile with -Cincremental into
    /// store-managed state. Off under --no-incremental (audit, CI).
    incremental: bool,
    /// GNU-make jobserver: caps machine-wide compiler parallelism at
    /// ~NCPU. rustc gates its LLVM codegen threads on it natively, and
    /// build scripts inherit it (cc/cmake/make all cooperate) — without
    /// it, N concurrent rustcs each assume they own every core.
    jobserver: jobserver::Client,
    /// Per-unit identity (16 hex chars): pkg, crate, kind, platform,
    /// profile, features, dep identities — deliberately source-free, so
    /// -Cmetadata (symbol hashes) is stable across edits and rustc's
    /// incremental state stays valid. -Cextra-filename keeps the full
    /// key16, so pool file names remain globally unique.
    idents: Vec<String>,
    /// Under check: true for units that emit metadata only.
    check_mode: Vec<bool>,
    /// Per-package resolved lint flags (empty for non-members).
    lints: Vec<LintFlags>,
    /// Clippy mode: member checked units run clippy-driver.
    clippy: bool,
    /// clippy-driver path (logical), identity (version + conf hash), and
    /// the workspace clippy.toml when present.
    clippy_driver: String,
    clippy_id: String,
    clippy_conf: Option<PathBuf>,
    /// Logical path of the cross target's std lib dir (immutable tools/
    /// entry); handed to rustc as a bare `-L`.
    target_std_libdir: Option<String>,
    cfg_env_target: Vec<(String, String)>,
    /// Resolved .cargo/config.toml rustflags for target-platform units.
    target_rustflags: Vec<String>,
    /// Same for host units (empty when an explicit --target is set).
    host_rustflags: Vec<String>,
    /// Resolved [env] entries, sorted; applied and keyed on every action.
    config_env: Vec<(String, String)>,
    /// corgi.toml [extra-inputs]: package -> package-root-relative reads
    /// outside the package, granted to its actions and hashed as inputs.
    extra_inputs: ExtraInputs,
}

impl Ctx {
    fn extra_inputs_for(&self, pkg: &Package) -> &[String] {
        self.extra_inputs.get(&pkg.name).map(Vec::as_slice).unwrap_or(&[])
    }
}

#[derive(Serialize)]
struct CompileKey<'a> {
    kind: &'a str,
    tool: &'a str,
    rustc: &'a str,
    host: &'a str,
    pkg: [&'a str; 3],
    src_hash: &'a str,
    crate_name: &'a str,
    edition: &'a str,
    crate_type: &'a str,
    src_rel: &'a str,
    features: &'a [String],
    externs: &'a [(String, String, String)],
    link_closure: &'a [(String, String)],
    cfgs: &'a [String],
    renvs: &'a [(String, String)],
    link_libs: &'a [String],
    link_search: &'a [String],
    link_args: &'a [String],
    out_key: &'a str,
    profile: &'a [String],
    /// resolved lint-level flags (value-keyed inputs; empty for deps)
    lints: &'a [String],
    /// clippy identity (driver version + clippy.toml hash); "" = rustc
    clippy: &'a str,
    /// Incremental namespace: history-seeded, functionally equivalent but
    /// not bit-reproducible. Never mixes with the clean namespace.
    incr: bool,
    /// -Cmetadata value (source-free unit identity).
    ident: &'a str,
    /// debug-map prefix recorded relative to the workspace root ("" = none)
    oso: &'a str,
    env: &'a [(String, String)],
    cap_lints: bool,
    /// Resolved .cargo/config.toml rustflags applied to this unit.
    rustflags: &'a [String],
    /// linker-chain identity; only linking crate types depend on it
    toolchain: &'a str,
    /// cross-compilation target triple ("" = host)
    tgt: &'a str,
}

#[derive(Serialize)]
struct RunKey<'a> {
    kind: &'a str,
    tool: &'a str,
    rustc: &'a str,
    host: &'a str,
    pkg: [&'a str; 3],
    src_hash: &'a str,
    script: [&'a str; 2],
    env: &'a [(String, String)],
    dep_env: &'a [(String, String)],
    /// build scripts may invoke cc themselves
    toolchain: &'a str,
    /// identity hashes of the tools scoped to this package (sorted)
    tools: &'a [String],
}

#[derive(serde::Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct ToolSpec {
    #[serde(skip)]
    name: String,
    version: String,
    url: String,
    sha256: String,
    #[serde(default)]
    bin: String,
    #[serde(default)]
    path: String,
    env: String,
    /// Packages whose actions see and key on this tool; empty = every
    /// build script (right for graph-wide tools like a wasm C compiler).
    #[serde(default)]
    packages: Vec<String>,
    /// How the archive is fetched. Empty = plain unauthenticated download.
    /// "github": a GitHub release asset of a private repo, downloaded via
    /// the gh CLI's stored credentials. Auth affects transport only — the
    /// sha256 pin remains the tool's identity either way.
    #[serde(default)]
    auth: String,
}

#[derive(serde::Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct EnvProbe {
    #[serde(skip)]
    name: String,
    command: String,
    /// Required: the packages whose build scripts receive the value.
    packages: Vec<String>,
    /// Profile names this applies to; empty = all profiles.
    #[serde(default)]
    profiles: Vec<String>,
}

#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct UniverseDef {
    packages: Vec<String>,
}

/// Workspace corgi.toml: sha256-pinned tools, plan-time env probes, and
/// feature universes. Every setting names the packages it applies to, and
/// only those actions key on it — the file itself is never hashed into
/// keys, so comment or command-text edits rebuild nothing. Parsed with
/// the `toml` crate (the parser cargo itself builds on); unknown sections
/// or keys are hard errors via deny_unknown_fields.
#[derive(serde::Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct CorgiToml {
    #[serde(default)]
    tools: std::collections::BTreeMap<String, ToolSpec>,
    #[serde(default)]
    env: std::collections::BTreeMap<String, EnvProbe>,
    #[serde(default)]
    universe: std::collections::BTreeMap<String, UniverseDef>,
    /// Reads outside a package's root that its actions may perform:
    /// package name -> package-root-relative paths, granted and hashed as
    /// inputs. Lives here rather than in package manifests so dependency
    /// packages can be covered too and crate manifests stay untouched.
    #[serde(default, rename = "extra-inputs")]
    extra_inputs: std::collections::BTreeMap<String, Vec<String>>,
}

type Universes = Vec<(String, Vec<String>)>;
type ExtraInputs = std::collections::BTreeMap<String, Vec<String>>;
type CorgiManifest = (Vec<ToolSpec>, Vec<EnvProbe>, Universes, ExtraInputs);

fn read_corgi_toml(dir: &Path) -> Result<Option<CorgiManifest>> {
    let mut found: Option<PathBuf> = None;
    let mut cur = Some(dir);
    while let Some(d) = cur {
        let p = d.join("corgi.toml");
        if p.exists() {
            found = Some(p);
            break;
        }
        cur = d.parent();
    }
    let Some(p) = found else { return Ok(None) };
    let text = fs::read_to_string(&p)?;
    let parsed: CorgiToml =
        toml::from_str(&text).with_context(|| format!("parsing {}", p.display()))?;
    let mut specs: Vec<ToolSpec> = Vec::new();
    for (name, mut t) in parsed.tools {
        t.name = name;
        if t.bin.is_empty() == t.path.is_empty() {
            bail!(
                "tool `{}` in {} needs exactly one of `bin` (executable) or `path` (file/dir)",
                t.name,
                p.display()
            );
        }
        specs.push(t);
    }
    let mut probes: Vec<EnvProbe> = Vec::new();
    for (name, mut e) in parsed.env {
        e.name = name;
        if e.command.is_empty() || e.packages.is_empty() {
            bail!("env `{}` in {} needs a command and a non-empty packages list", e.name, p.display());
        }
        probes.push(e);
    }
    let universes: Universes = parsed.universe.into_iter().map(|(k, v)| (k, v.packages)).collect();
    Ok(Some((specs, probes, universes, parsed.extra_inputs)))
}

/// Resolved lint flags for one workspace member. Lints are inputs like
/// any probe value: corgi is the producer (cargo exposes no API for
/// them — checked: unit graph, cargo metadata, and build-plan, which is
/// removed), the manifests they come from never enter keys, and only
/// these resolved values do.
#[derive(Default, Clone)]
struct LintFlags {
    /// Lints rustc acts on (rust-tool): keyed into every mode.
    rustc_only: Vec<String>,
    /// The full set including clippy:: tool lints: keyed into clippy
    /// actions only — inert flags must not bust check/build caches.
    with_clippy: Vec<String>,
}

/// One resolved entry: (priority, tool, lint, level). Sorted by
/// (priority, tool, lint) — cargo's documented flag ordering.
type LintEntry = (i64, String, String, String);

/// `{ rust: { lint: "level" | { level, priority } }, clippy: {...} }`.
fn lint_entries_from_table(table: &toml::Table) -> Result<Vec<LintEntry>> {
    let mut entries = Vec::new();
    for (tool, lints) in table {
        let Some(lints) = lints.as_table() else {
            bail!("[lints.{tool}] is not a table");
        };
        for (lint, value) in lints {
            let (level, priority) = match value {
                toml::Value::String(level) => (level.clone(), 0),
                toml::Value::Table(cfg) => {
                    if cfg.contains_key("check-cfg") {
                        bail!("[lints] `{tool}::{lint}`: check-cfg configuration is not supported yet");
                    }
                    let level = cfg
                        .get("level")
                        .and_then(|v| v.as_str())
                        .with_context(|| format!("[lints] `{tool}::{lint}` needs a `level`"))?;
                    let priority = cfg.get("priority").and_then(|v| v.as_integer()).unwrap_or(0);
                    (level.to_string(), priority)
                }
                other => bail!("[lints] `{tool}::{lint}`: unsupported value {other:?}"),
            };
            entries.push((priority, tool.clone(), lint.clone(), level));
        }
    }
    Ok(entries)
}

fn lint_entries_to_flags(entries: &[LintEntry]) -> Result<LintFlags> {
    let mut sorted = entries.to_vec();
    sorted.sort();
    let mut out = LintFlags::default();
    for (_, tool, lint, level) in &sorted {
        if tool == "rustdoc" {
            continue; // rustdoc lints apply to rustdoc runs only
        }
        let name = if tool == "rust" { lint.clone() } else { format!("{tool}::{lint}") };
        let flag = match level.as_str() {
            "allow" => format!("-A{name}"),
            "warn" => format!("-W{name}"),
            "deny" => format!("-D{name}"),
            "forbid" => format!("-F{name}"),
            "force-warn" => format!("--force-warn={name}"),
            other => bail!("[lints] `{name}`: unknown level `{other}`"),
        };
        if tool == "rust" {
            out.rustc_only.push(flag.clone());
        }
        out.with_clippy.push(flag);
    }
    Ok(out)
}

/// Per-package resolved lints (workspace members only; deps are capped
/// anyway and cargo never applies your lints to them).
fn resolve_lints(meta: &Metadata) -> Result<Vec<LintFlags>> {
    let members: std::collections::HashSet<&str> =
        meta.workspace_members.iter().map(|s| s.as_str()).collect();
    let ws_path = Path::new(&meta.workspace_root).join("Cargo.toml");
    let ws_text = fs::read_to_string(&ws_path).unwrap_or_default();
    let ws_doc: toml::Table =
        toml::from_str(&ws_text).with_context(|| format!("parsing {}", ws_path.display()))?;
    let ws_entries = match ws_doc.get("workspace").and_then(|w| w.get("lints")).and_then(|l| l.as_table()) {
        Some(t) => lint_entries_from_table(t)?,
        None => Vec::new(),
    };
    let ws_flags = lint_entries_to_flags(&ws_entries)?;
    let mut out = vec![LintFlags::default(); meta.packages.len()];
    for (i, pkg) in meta.packages.iter().enumerate() {
        if !members.contains(pkg.id.as_str()) {
            continue;
        }
        let text = fs::read_to_string(&pkg.manifest_path)
            .with_context(|| format!("reading manifest of {}", pkg.name))?;
        let doc: toml::Table =
            toml::from_str(&text).with_context(|| format!("parsing manifest of {}", pkg.name))?;
        let Some(lints) = doc.get("lints").and_then(|l| l.as_table()) else {
            continue;
        };
        let uses_workspace = lints.get("workspace").and_then(|v| v.as_bool()).unwrap_or(false);
        if uses_workspace {
            if lints.len() > 1 {
                bail!("{}: [lints] mixes `workspace = true` with inline tables", pkg.name);
            }
            out[i] = ws_flags.clone();
        } else {
            out[i] = lint_entries_to_flags(&lint_entries_from_table(lints)?)?;
        }
    }
    Ok(out)
}

/// Bare-name spawns (`Command::new("cmake")`) resolve through a shim dir
/// of symlinks to exactly the tools visible to this action. One dir per
/// distinct subset, named by the subset's identity hash; contents derive
/// from keyed tool ids, so PATH itself never needs keying.
fn ensure_tool_shims(store: &Store, tools: &[&ToolRt]) -> Result<Option<PathBuf>> {
    let with_bin: Vec<&&ToolRt> = tools.iter().filter(|t| !t.bin.is_empty()).collect();
    if with_bin.is_empty() {
        return Ok(None);
    }
    let mut ids: Vec<&str> = with_bin.iter().map(|t| t.id.as_str()).collect();
    ids.sort();
    let subset = crate::store::sha256_hex(ids.join("\n").as_bytes());
    let dir = store.root.join("toolsets").join(&subset[..16]);
    if dir.exists() {
        Store::touch_used(&dir);
        return Ok(Some(dir));
    }
    let tmp = store.tmp_path("shims");
    fs::create_dir_all(&tmp)?;
    for t in &with_bin {
        let target = store
            .root
            .join("tools")
            .join(format!("{}-{}", t.name, t.version))
            .join(&t.bin);
        std::os::unix::fs::symlink(&target, tmp.join(&t.name)).ok();
    }
    fs::create_dir_all(dir.parent().unwrap())?;
    match fs::rename(&tmp, &dir) {
        Ok(()) => {}
        Err(_) if dir.exists() => {
            fs::remove_dir_all(&tmp).ok();
        }
        Err(e) => return Err(e).context("publishing tool shims"),
    }
    Ok(Some(dir))
}

/// Fetch + verify + unpack a pinned tool into the store (atomic, lock-free).
fn ensure_tool(store: &Store, t: &ToolSpec) -> Result<PathBuf> {
    let exported = if !t.bin.is_empty() { &t.bin } else { &t.path };
    let dest = store.root.join("tools").join(format!("{}-{}", t.name, t.version));
    if dest.join(exported).exists() {
        touch_tool_marker(&dest);
        return Ok(dest.join(exported));
    }
    eprintln!("corgi: installing tool {} {} (sha256-pinned)", t.name, t.version);
    let work = store.tmp_path("tool");
    let unpack = work.join("unpack");
    fs::create_dir_all(&unpack)?;
    let archive = work.join("archive");
    match t.auth.as_str() {
        "" => {
            let st =
                Command::new("curl").args(["-sSfL", "-o"]).arg(&archive).arg(&t.url).status()?;
            if !st.success() {
                bail!("download failed: {}", t.url);
            }
        }
        "github" => {
            let (repo, tag, asset) = parse_github_release_url(&t.url).with_context(|| {
                format!("tool {}: auth = \"github\" requires a github.com release-asset url", t.name)
            })?;
            let st = Command::new("gh")
                .args(["release", "download", &tag, "-R", &repo, "--pattern", &asset, "--output"])
                .arg(&archive)
                .status()
                .with_context(|| {
                    format!(
                        "tool {}: running gh (auth = \"github\" needs the GitHub CLI, logged in)",
                        t.name
                    )
                })?;
            if !st.success() {
                bail!(
                    "tool {}: gh release download failed for {} (is `gh auth status` ok?)",
                    t.name,
                    t.url
                );
            }
        }
        other => bail!("tool {}: unknown auth scheme `{other}` (supported: \"github\")", t.name),
    }
    let actual = crate::store::sha256_file(&archive)?;
    if actual != t.sha256 {
        bail!("sha256 mismatch for tool {}: manifest pins {}, archive is {actual}", t.name, t.sha256);
    }
    let st = Command::new("tar").arg("-xf").arg(&archive).arg("-C").arg(&unpack).status()?;
    if !st.success() {
        bail!("unpack failed for tool {}", t.name);
    }
    if !unpack.join(exported).exists() {
        bail!("tool {}: `{exported}` not found inside the archive", t.name);
    }
    fs::create_dir_all(dest.parent().unwrap())?;
    match fs::rename(&unpack, &dest) {
        Ok(()) => {}
        Err(_) if dest.join(exported).exists() => {}
        Err(e) => return Err(e).context("publishing tool"),
    }
    touch_tool_marker(&dest);
    fs::remove_dir_all(&work).ok();
    Ok(dest.join(exported))
}

/// Split a GitHub release-asset url into (owner/repo, tag, asset name):
/// https://github.com/{owner}/{repo}/releases/download/{tag}/{asset}.
fn parse_github_release_url(url: &str) -> Result<(String, String, String)> {
    let rest = url
        .strip_prefix("https://github.com/")
        .with_context(|| format!("not a github.com url: {url}"))?;
    let parts: Vec<&str> = rest.split('/').collect();
    match parts.as_slice() {
        [owner, repo, "releases", "download", tag, asset]
            if !owner.is_empty() && !repo.is_empty() && !tag.is_empty() && !asset.is_empty() =>
        {
            Ok((format!("{owner}/{repo}"), tag.to_string(), asset.to_string()))
        }
        _ => bail!("not a release-asset url (expected .../releases/download/<tag>/<asset>): {url}"),
    }
}

/// Resolve the host triple *without* a rustc: corgi's own build constants.
/// Cross-checked later against the pinned rustc's self-reported host.
/// (Known gap: under Rosetta an x86_64 corgi resolves x86_64-apple-darwin.)
fn host_triple() -> Result<String> {
    let arch = std::env::consts::ARCH;
    let os = match std::env::consts::OS {
        "macos" => "apple-darwin",
        "linux" => "unknown-linux-gnu", // TODO: musl detection
        o => bail!("unsupported host OS {o}"),
    };
    Ok(format!("{arch}-{os}"))
}

/// The pin is mandatory and must be concrete. No floating channels, no
/// ambient-rustup fallback: builds are a function of the repo, full stop.
fn read_toolchain_pin(dir: &Path) -> Result<String> {
    // the pin may live at the workspace root above the package being built
    let mut found: Option<PathBuf> = None;
    let mut cur = Some(dir);
    while let Some(d) = cur {
        if d.join("rust-toolchain.toml").exists() || d.join("rust-toolchain").exists() {
            found = Some(d.to_path_buf());
            break;
        }
        cur = d.parent();
    }
    let dir = found.as_deref().unwrap_or(dir);
    let toml_p = dir.join("rust-toolchain.toml");
    let legacy = dir.join("rust-toolchain");
    let channel = if toml_p.exists() {
        let text = fs::read_to_string(&toml_p)?;
        let doc: toml::Table =
            toml::from_str(&text).with_context(|| format!("parsing {}", toml_p.display()))?;
        doc.get("toolchain")
            .and_then(|t| t.get("channel"))
            .and_then(|c| c.as_str())
            .map(str::to_string)
            .with_context(|| format!("no `channel` key in {}", toml_p.display()))?
    } else if legacy.exists() {
        fs::read_to_string(&legacy)?.trim().to_string()
    } else {
        bail!(
            "corgi requires a pinned toolchain: create rust-toolchain.toml with \
             `[toolchain]\nchannel = \"<exact version>\"` (e.g. \"1.94.1\" or \"nightly-2026-03-25\")"
        );
    };
    if !is_concrete_channel(&channel) {
        bail!(
            "floating toolchain channel `{channel}` is not allowed; \
             pin an exact version like \"1.94.1\" or \"nightly-2026-03-25\""
        );
    }
    Ok(channel)
}

fn is_concrete_channel(c: &str) -> bool {
    let semver = {
        let parts: Vec<&str> = c.split('.').collect();
        parts.len() == 3 && parts.iter().all(|p| !p.is_empty() && p.chars().all(|ch| ch.is_ascii_digit()))
    };
    let dated = c
        .strip_prefix("nightly-")
        .or_else(|| c.strip_prefix("beta-"))
        .map(|d| {
            d.len() == 10
                && d.chars()
                    .enumerate()
                    .all(|(i, ch)| if i == 4 || i == 7 { ch == '-' } else { ch.is_ascii_digit() })
        })
        .unwrap_or(false);
    semver || dated
}

/// Go-style cache expiry: every file is judged by its own mtime, which
/// use-sites keep fresh with throttled touches. No reference counting —
/// blobs are touched whenever a referencing action is used, so a stale
/// blob implies only stale actions point at it. Deleting something in
/// use is benign: probes self-heal by rebuilding.
pub fn gc(store: &Store) -> Result<()> {
    let days: u64 = std::env::var("CORGI_GC_TTL_DAYS").ok().and_then(|v| v.parse().ok()).unwrap_or(5);
    let (files, dirs, bytes) = gc_trim(store, std::time::Duration::from_secs(days * 24 * 3600))?;
    eprintln!(
        "corgi: gc removed {files} files and {dirs} dirs ({:.1} MB) older than {days} days",
        bytes as f64 / 1e6
    );
    Ok(())
}

/// Auto-trim after builds, at most once per day (Go's trim.txt scheme).
fn maybe_auto_gc(store: &Store) {
    let marker = store.root.join("cache").join("trim.txt");
    if let Ok(md) = fs::metadata(&marker) {
        if let Ok(age) = md.modified().and_then(|m| m.elapsed().map_err(std::io::Error::other)) {
            if age < std::time::Duration::from_secs(24 * 3600) {
                return;
            }
        } else {
            return; // clock skew: fine, skip
        }
    }
    let days: u64 = std::env::var("CORGI_GC_TTL_DAYS").ok().and_then(|v| v.parse().ok()).unwrap_or(5);
    if let Err(e) = gc_trim(store, std::time::Duration::from_secs(days * 24 * 3600)) {
        eprintln!("corgi: warning: gc trim failed: {e:#}");
    }
    let _ = store.write_atomic(&marker, b"trimmed\n");
}

fn gc_trim(store: &Store, ttl: std::time::Duration) -> Result<(u64, u64, u64)> {
    let now = std::time::SystemTime::now();
    let cutoff = now.checked_sub(ttl).context("ttl too large")?;
    let stale = |p: &Path| -> bool {
        fs::metadata(p).and_then(|m| m.modified()).map(|m| m < cutoff).unwrap_or(false)
    };
    let mut files = 0u64;
    let mut dirs = 0u64;
    let mut bytes = 0u64;
    // cache/<xx>/* : blobs and action records, each by its own mtime
    for shard in read_dir_paths(&store.root.join("cache"))? {
        if !shard.is_dir() {
            continue;
        }
        for f in read_dir_paths(&shard)? {
            if stale(&f) {
                bytes += fs::metadata(&f).map(|m| m.len()).unwrap_or(0);
                if fs::remove_file(&f).is_ok() {
                    files += 1;
                }
            }
        }
    }
    // pool/* : hardlinks share the blob's inode (and mtime) — same verdict
    for f in read_dir_paths(&store.root.join("pool"))? {
        if stale(&f) && fs::remove_file(&f).is_ok() {
            files += 1;
        }
    }
    // outdirs/: entries judged by their sentinel; sentinel-less dirs are
    // crash leftovers; lock files go only once their entry is gone
    for p in read_dir_paths(&store.root.join("outdirs"))? {
        if p.extension().is_some_and(|e| e == "lock") {
            let entry = p.with_extension("");
            if !entry.exists() && stale(&p) && fs::remove_file(&p).is_ok() {
                files += 1;
            }
            continue;
        }
        if !p.is_dir() {
            continue;
        }
        let ok = p.join(".ok");
        let verdict = if ok.exists() { stale(&ok) } else { stale(&p) };
        if verdict && fs::remove_dir_all(&p).is_ok() {
            dirs += 1;
        }
    }
    // hints/: pure accelerators
    if store.root.join("hints").exists() {
        for f in read_dir_paths(&store.root.join("hints"))? {
            if stale(&f) && fs::remove_file(&f).is_ok() {
                files += 1;
            }
        }
    }
    // tools/: judged by the .corgi-used marker every build refreshes
    for p in read_dir_paths(&store.root.join("tools"))? {
        if !p.is_dir() {
            continue;
        }
        let marker = p.join(".corgi-used");
        if !marker.exists() {
            // Seed a marker rather than judging by dir mtime: tarball-derived
            // dirs keep the archive's embedded (often ancient) timestamps.
            let _ = fs::write(&marker, b"used\n");
            continue;
        }
        if stale(&marker) && fs::remove_dir_all(&p).is_ok() {
            dirs += 1;
        }
    }
    // toolsets/: shim dirs, cheap to rebuild; judged by use-touched mtime.
    for p in read_dir_paths(&store.root.join("toolsets"))? {
        if p.is_dir() && stale(&p) && fs::remove_dir_all(&p).is_ok() {
            dirs += 1;
        }
    }
    // incr/: dev-loop incremental state — fat, rebuildable, judged by
    // dir mtime (rustc session writes refresh it on every use).
    for p in read_dir_paths(&store.root.join("incr"))? {
        if p.is_dir() {
            if stale(&p) && fs::remove_dir_all(&p).is_ok() {
                dirs += 1;
            }
        } else if stale(&p) && fs::remove_file(&p).is_ok() {
            files += 1;
        }
    }
    // cargo-home/: dependency sources are re-fetchable. Registry
    // extractions and git checkouts are judged by their use-touched
    // .cargo-ok (fallback: the dir itself); crate tarballs and git dbs
    // by plain mtime. The sparse index is left alone (small, and cargo
    // refreshes it itself).
    let cargo_home = store.root.join("cargo-home");
    for index_dir in read_dir_paths(&cargo_home.join("registry/src"))? {
        for pkg_dir in read_dir_paths(&index_dir)? {
            if !pkg_dir.is_dir() {
                continue;
            }
            let ok = pkg_dir.join(".cargo-ok");
            let verdict = if ok.exists() { stale(&ok) } else { stale(&pkg_dir) };
            if verdict && fs::remove_dir_all(&pkg_dir).is_ok() {
                dirs += 1;
            }
        }
    }
    for index_dir in read_dir_paths(&cargo_home.join("registry/cache"))? {
        for f in read_dir_paths(&index_dir)? {
            if f.is_file() && stale(&f) {
                let n = fs::metadata(&f).map(|m| m.len()).unwrap_or(0);
                if fs::remove_file(&f).is_ok() {
                    files += 1;
                    bytes += n;
                }
            }
        }
    }
    for repo_dir in read_dir_paths(&cargo_home.join("git/checkouts"))? {
        for checkout_dir in read_dir_paths(&repo_dir)? {
            if !checkout_dir.is_dir() {
                continue;
            }
            let ok = checkout_dir.join(".cargo-ok");
            let verdict = if ok.exists() { stale(&ok) } else { stale(&checkout_dir) };
            if verdict && fs::remove_dir_all(&checkout_dir).is_ok() {
                dirs += 1;
            }
        }
    }
    for db_dir in read_dir_paths(&cargo_home.join("git/db"))? {
        if db_dir.is_dir() && stale(&db_dir) && fs::remove_dir_all(&db_dir).is_ok() {
            dirs += 1;
        }
    }
    // tmp/: anything older than a day is orphaned staging
    let day = now.checked_sub(std::time::Duration::from_secs(24 * 3600)).unwrap_or(cutoff);
    for p in read_dir_paths(&store.root.join("tmp"))? {
        let old = fs::metadata(&p).and_then(|m| m.modified()).map(|m| m < day).unwrap_or(false);
        if old {
            if p.is_dir() {
                if fs::remove_dir_all(&p).is_ok() {
                    dirs += 1;
                }
            } else if fs::remove_file(&p).is_ok() {
                files += 1;
            }
        }
    }
    Ok((files, dirs, bytes))
}

fn read_dir_paths(dir: &Path) -> Result<Vec<PathBuf>> {
    let mut out = Vec::new();
    if let Ok(rd) = fs::read_dir(dir) {
        for e in rd {
            out.push(e?.path());
        }
    }
    Ok(out)
}

/// Refresh a tool/toolchain dir's use marker (throttled like all touches).
fn touch_tool_marker(dir: &Path) {
    let marker = dir.join(".corgi-used");
    if !marker.exists() {
        let _ = fs::write(&marker, b"used\n");
        return;
    }
    Store::touch_used(&marker);
}

/// Install rustc + rust-std + cargo from static.rust-lang.org into the
/// store (sha256-verified, unpacked to tmp, atomic rename — lock-free).
fn ensure_toolchain(store: &Store, channel: &str, triple: &str) -> Result<PathBuf> {
    let dest = store.root.join("tools").join(format!("rust-{channel}-{triple}"));
    let bin = dest.join("bin");
    if bin.join("rustc").is_file() && bin.join("cargo").is_file() {
        touch_tool_marker(&dest);
        return Ok(bin);
    }
    eprintln!("corgi: installing toolchain {channel}-{triple} into {}", dest.display());
    let (base, ver) = if let Some(d) = channel.strip_prefix("nightly-") {
        (format!("https://static.rust-lang.org/dist/{d}"), "nightly".to_string())
    } else if let Some(d) = channel.strip_prefix("beta-") {
        (format!("https://static.rust-lang.org/dist/{d}"), "beta".to_string())
    } else {
        ("https://static.rust-lang.org/dist".to_string(), channel.to_string())
    };
    let work = store.tmp_path("toolchain");
    let install = work.join("install");
    fs::create_dir_all(&install)?;
    for (comp, payload) in [
        ("rustc", "rustc".to_string()),
        ("rust-std", format!("rust-std-{triple}")),
        ("cargo", "cargo".to_string()),
    ] {
        let name = format!("{comp}-{ver}-{triple}");
        let url = format!("{base}/{name}.tar.xz");
        let tarball = work.join(format!("{name}.tar.xz"));
        let st = Command::new("curl")
            .args(["-sSfL", "-o"])
            .arg(&tarball)
            .arg(&url)
            .status()
            .context("running curl")?;
        if !st.success() {
            bail!("download failed: {url}");
        }
        let expected = capture(Command::new("curl").args(["-sSfL", &format!("{url}.sha256")]), "fetching sha256")?;
        let expected = expected.split_whitespace().next().unwrap_or("").to_string();
        let actual = crate::store::sha256_file(&tarball)?;
        if actual != expected {
            bail!("sha256 mismatch for {name}: expected {expected}, got {actual}");
        }
        let st = Command::new("tar").arg("-xf").arg(&tarball).arg("-C").arg(&work).status()?;
        if !st.success() {
            bail!("unpack failed: {name}");
        }
        let payload_dir = work.join(&name).join(&payload);
        let st = Command::new("cp")
            .arg("-R")
            .arg(format!("{}/.", payload_dir.display()))
            .arg(&install)
            .status()?;
        if !st.success() {
            bail!("copying component {comp} failed");
        }
        eprintln!("corgi:   {comp} {ver} verified (sha256 {}…)", &expected[..12]);
    }
    fs::create_dir_all(dest.parent().unwrap())?;
    match fs::rename(&install, &dest) {
        Ok(()) => {}
        Err(_) if dest.join("bin/rustc").is_file() => {} // concurrent racer won
        Err(e) => return Err(e).context("publishing toolchain"),
    }
    touch_tool_marker(&dest);
    fs::remove_dir_all(&work).ok();
    Ok(dest.join("bin"))
}

/// Install the rust-src component as its OWN tools/ entry — never inside
/// the sysroot: rustc devirtualizes std paths when it sees sources there,
/// which would flip every action key. These sources serve debuggers only:
/// one lldb source-map line from the toolchain's /rustc/<commit> prefix to
/// this directory gives complete std source display (see README).
fn ensure_rust_src(store: &Store, channel: &str) -> Result<()> {
    let dest = store.root.join("tools").join(format!("rust-src-{channel}"));
    if dest.join("lib/rustlib/src/rust/library").exists() {
        touch_tool_marker(&dest);
        return Ok(());
    }
    eprintln!("corgi: installing rust-src {channel} (sha256-pinned)");
    let (base, ver) = if let Some(d) = channel.strip_prefix("nightly-") {
        (format!("https://static.rust-lang.org/dist/{d}"), "nightly".to_string())
    } else if let Some(d) = channel.strip_prefix("beta-") {
        (format!("https://static.rust-lang.org/dist/{d}"), "beta".to_string())
    } else {
        ("https://static.rust-lang.org/dist".to_string(), channel.to_string())
    };
    let name = format!("rust-src-{ver}");
    let work = store.tmp_path("rust-src");
    fs::create_dir_all(&work)?;
    let tarball = work.join("t.tar.xz");
    let url = format!("{base}/{name}.tar.xz");
    let st = Command::new("curl").args(["-sSfL", "-o"]).arg(&tarball).arg(&url).status()?;
    if !st.success() {
        bail!("download failed: {url}");
    }
    let expected = capture(Command::new("curl").args(["-sSfL", &format!("{url}.sha256")]), "sha256")?;
    let expected = expected.split_whitespace().next().unwrap_or("").to_string();
    let actual = crate::store::sha256_file(&tarball)?;
    if actual != expected {
        bail!("sha256 mismatch for {name}");
    }
    let st = Command::new("tar").arg("-xf").arg(&tarball).arg("-C").arg(&work).status()?;
    if !st.success() {
        bail!("unpack failed: {name}");
    }
    let payload = work.join(&name).join("rust-src");
    fs::create_dir_all(dest.parent().unwrap())?;
    match fs::rename(&payload, &dest) {
        Ok(()) => {}
        Err(_) if dest.join("lib/rustlib/src/rust/library").exists() => {}
        Err(e) => return Err(e).context("publishing rust-src component"),
    }
    touch_tool_marker(&dest);
    fs::remove_dir_all(&work).ok();
    Ok(())
}

/// Add the clippy component's driver to an installed toolchain (single
/// atomic file rename; presence = complete). Only clippy mode pays for it.
fn ensure_clippy(store: &Store, channel: &str, triple: &str) -> Result<()> {
    let toolchain = store.root.join("tools").join(format!("rust-{channel}-{triple}"));
    let driver = toolchain.join("bin/clippy-driver");
    if driver.is_file() {
        return Ok(());
    }
    eprintln!("corgi: installing clippy {channel} (sha256-pinned)");
    let (base, ver) = if let Some(d) = channel.strip_prefix("nightly-") {
        (format!("https://static.rust-lang.org/dist/{d}"), "nightly".to_string())
    } else if let Some(d) = channel.strip_prefix("beta-") {
        (format!("https://static.rust-lang.org/dist/{d}"), "beta".to_string())
    } else {
        ("https://static.rust-lang.org/dist".to_string(), channel.to_string())
    };
    let name = format!("clippy-{ver}-{triple}");
    let work = store.tmp_path("clippy");
    fs::create_dir_all(&work)?;
    let tarball = work.join("t.tar.xz");
    let url = format!("{base}/{name}.tar.xz");
    let st = Command::new("curl").args(["-sSfL", "-o"]).arg(&tarball).arg(&url).status()?;
    if !st.success() {
        bail!("download failed: {url}");
    }
    let expected = capture(Command::new("curl").args(["-sSfL", &format!("{url}.sha256")]), "sha256")?;
    let expected = expected.split_whitespace().next().unwrap_or("").to_string();
    let actual = crate::store::sha256_file(&tarball)?;
    if actual != expected {
        bail!("sha256 mismatch for {name}");
    }
    let st = Command::new("tar").arg("-xf").arg(&tarball).arg("-C").arg(&work).status()?;
    if !st.success() {
        bail!("unpack failed: {name}");
    }
    let payload = work.join(&name).join("clippy-preview/bin/clippy-driver");
    match fs::rename(&payload, &driver) {
        Ok(()) => {}
        Err(_) if driver.is_file() => {} // concurrent racer won
        Err(e) => return Err(e).context("publishing clippy-driver"),
    }
    fs::remove_dir_all(&work).ok();
    Ok(())
}

/// Install rust-std for a cross target as its OWN immutable tools/ entry
/// (never mutating the toolchain dir). Compiles reach it via a bare `-L`:
/// rustc's crate loader resolves sysroot crates (std, core, ...) from -L
/// paths of kind "all", and the output is bit-identical to std-in-sysroot
/// (verified). Atomic unpack+rename; presence of the dir = complete.
fn ensure_target_std(store: &Store, channel: &str, target: &str) -> Result<()> {
    let dest = store.root.join("tools").join(format!("rust-std-{channel}-{target}"));
    if dest.join("lib/rustlib").join(target).join("lib").exists() {
        touch_tool_marker(&dest);
        return Ok(());
    }
    eprintln!("corgi: installing rust-std for {target} (sha256-pinned)");
    let (base, ver) = if let Some(d) = channel.strip_prefix("nightly-") {
        (format!("https://static.rust-lang.org/dist/{d}"), "nightly".to_string())
    } else if let Some(d) = channel.strip_prefix("beta-") {
        (format!("https://static.rust-lang.org/dist/{d}"), "beta".to_string())
    } else {
        ("https://static.rust-lang.org/dist".to_string(), channel.to_string())
    };
    let name = format!("rust-std-{ver}-{target}");
    let work = store.tmp_path("std");
    fs::create_dir_all(&work)?;
    let tarball = work.join("t.tar.xz");
    let url = format!("{base}/{name}.tar.xz");
    let st = Command::new("curl").args(["-sSfL", "-o"]).arg(&tarball).arg(&url).status()?;
    if !st.success() {
        bail!("download failed: {url}");
    }
    let expected = capture(Command::new("curl").args(["-sSfL", &format!("{url}.sha256")]), "sha256")?;
    let expected = expected.split_whitespace().next().unwrap_or("").to_string();
    let actual = crate::store::sha256_file(&tarball)?;
    if actual != expected {
        bail!("sha256 mismatch for {name}");
    }
    let st = Command::new("tar").arg("-xf").arg(&tarball).arg("-C").arg(&work).status()?;
    if !st.success() {
        bail!("unpack failed: {name}");
    }
    let payload = work.join(&name).join(format!("rust-std-{target}"));
    fs::create_dir_all(dest.parent().unwrap())?;
    match fs::rename(&payload, &dest) {
        Ok(()) => {}
        Err(_) if dest.join("lib/rustlib").join(target).join("lib").exists() => {}
        Err(e) => return Err(e).context("publishing rust-std"),
    }
    touch_tool_marker(&dest);
    fs::remove_dir_all(&work).ok();
    Ok(())
}

/// Invocation options beyond the store and directory.
pub struct BuildOpts {
    pub verbose: bool,
    pub release: bool,
    /// Take every workspace member's units as roots instead of the
    /// package at the build dir (cargo's --workspace).
    pub workspace: bool,
    /// Cargo package name selected by `-p` or `--package`.
    pub package: Option<String>,
    pub target: Option<String>,
    pub mode: Mode,
    pub timings: bool,
    pub no_incremental: bool,
    /// Test-name filter (cargo's positional TESTNAME), passed to every
    /// harness.
    pub test_filter: Option<String>,
    /// Arguments after `--`: the program's argv for `run`, harness
    /// arguments for `test`.
    pub exec_args: Vec<String>,
}

pub fn build(store: Store, dir: &Path, opts: BuildOpts) -> Result<()> {
    let BuildOpts {
        verbose,
        release,
        workspace,
        package,
        target,
        mode,
        timings,
        no_incremental,
        test_filter,
        exec_args,
    } = opts;
    let t0 = Instant::now();
    let dir = dir
        .canonicalize()
        .with_context(|| format!("bad directory {}", dir.display()))?;
    let manifest = dir.join("Cargo.toml");
    if !manifest.exists() {
        bail!("no Cargo.toml in {}", dir.display());
    }

    // Env-injected compiler flags are invisible inputs; the config file
    // is the one honored channel.
    for var in ["RUSTFLAGS", "CARGO_ENCODED_RUSTFLAGS", "CARGO_BUILD_RUSTFLAGS"] {
        if std::env::var_os(var).is_some_and(|v| !v.is_empty()) {
            bail!("{var} is set; corgi only honors rustflags from .cargo/config.toml");
        }
    }
    let (cargo_config, config_dir) = crate::config::discover(&dir)?;

    let channel = read_toolchain_pin(&dir)?;
    let host_guess = host_triple()?;
    ensure_toolchain(&store, &channel, &host_guess)?;
    // Debugger convenience, deliberately outside the sysroot (see
    // ensure_rust_src). Failure is non-fatal: builds don't need sources.
    if let Err(e) = ensure_rust_src(&store, &channel) {
        eprintln!("corgi: warning: rust-src install failed ({e}); std source display in debuggers unavailable");
    }
    // Hand actions only the *logical* toolchain path (via the store alias):
    // physical per-store paths leak into ld's UUID (it hashes the link
    // command line, including libstd rlib paths) and into build-script keys.
    let toolchain_logical = store
        .logical_root()
        .join("tools")
        .join(format!("rust-{channel}-{host_guess}"));
    let rustc = toolchain_logical.join("bin/rustc").display().to_string();
    let cargo_bin = toolchain_logical.join("bin/cargo");
    let rustc_version = capture(Command::new(&rustc).arg("-vV"), "rustc -vV")?;
    let host = rustc_version
        .lines()
        .find_map(|l| l.strip_prefix("host: "))
        .context("rustc -vV: no host line")?
        .trim()
        .to_string();
    if host != host_guess {
        bail!("host triple mismatch: corgi resolved {host_guess}, pinned rustc reports {host}");
    }
    // Rustflags resolve against the platform a unit compiles for; host
    // units (build scripts, proc-macros) only get them when no explicit
    // --target splits the platforms — cargo's rule, load-bearing for
    // cfg-gated code in build scripts.
    let target_rustflags =
        cargo_config.rustflags_for(target.as_deref().unwrap_or(&host_guess))?;
    let host_rustflags: Vec<String> =
        if target.is_some() { Vec::new() } else { target_rustflags.clone() };
    let config_env = cargo_config.env;
    // Build scripts learn the compilation cfg through CARGO_CFG_*; cargo
    // probes rustc with the applicable rustflags so --cfg flags show up.
    let mut cfg_probe = Command::new(&rustc);
    cfg_probe.args(["--print", "cfg"]);
    cfg_probe.args(&host_rustflags);
    let cfg_out = capture(&mut cfg_probe, "rustc --print cfg")?;
    // the toolchain dir *is* the sysroot; use the logical spelling so
    // linker inputs are spelled identically regardless of store location
    let sysroot = toolchain_logical.display().to_string();
    // Sysroot *content* changes emitted bits even at identical rustc
    // versions: an installed rust-src component devirtualizes std paths in
    // panic locations (observed: 13/14 artifacts differ). Fold it into the
    // version string so it reaches every action key.
    let rust_src = Path::new(&sysroot).join("lib/rustlib/src/rust").exists();
    let rustc_version = format!("{rustc_version}rust-src: {rust_src}\n");
    let cfg_env = cargo_cfg_env(&cfg_out);
    let mut target_std_libdir: Option<String> = None;
    if let Some(t) = &target {
        if t != &host_guess {
            ensure_target_std(&store, &channel, t)?;
            target_std_libdir = Some(
                store
                    .logical_root()
                    .join("tools")
                    .join(format!("rust-std-{channel}-{t}"))
                    .join("lib/rustlib")
                    .join(t)
                    .join("lib")
                    .display()
                    .to_string(),
            );
        }
    }
    let cfg_env_target = if let Some(t) = &target {
        let mut probe = Command::new(&rustc);
        probe.args(["--print", "cfg", "--target", t]);
        probe.args(&target_rustflags);
        let o = capture(&mut probe, "rustc --print cfg --target")?;
        cargo_cfg_env(&o)
    } else {
        cfg_env.clone()
    };

    // Dependency sources live in the store: cargo (fetch/metadata/
    // unit-graph) runs with CARGO_HOME at the canonical store path, so
    // registry and git checkouts land at machine-independent locations
    // that exist wherever a corgi store does. Debug info referencing dep
    // sources therefore needs no remapping and no debugger fixups. Side
    // effect (deliberate): the user's ~/.cargo/config.toml no longer
    // silently shapes hermetic builds.
    let cargo_home = store.logical_root().join("cargo-home").display().to_string();

    let t_setup_done = Instant::now();
    // ---- plan-phase cache -------------------------------------------------
    // cargo fetch + metadata + unit-graph cost ~0.8s even when nothing
    // changed. Their outputs are a pure function of: corgi itself, the
    // pinned toolchain, target/profile, the tools manifest (feature
    // universes), every workspace manifest, the lockfile, cargo config, and
    // the member-glob directory listings. A pointer keyed on the cheap
    // always-read inputs leads to an entry that re-validates the rest by
    // content fingerprint. Entry paths are workspace-relative, so a
    // bit-identical checkout in a different directory still hits.
    let (universes, extra_inputs) = match read_corgi_toml(&dir)? {
        Some((_, _, u, x)) => (u, x),
        None => (Universes::new(), ExtraInputs::new()),
    };
    // Only the universes shape the plan (they pick the feature-unification
    // member set); tools and env probes don't, so their edits — or any
    // comment — must not even cost a replan.
    let universe_id = sha256_hex(format!("{universes:?}").as_bytes());
    // check shares build's plan; test resolves a different unit graph
    let plan_kind = if matches!(mode, Mode::Test) { "test" } else { "build" };
    let plan_ptr = sha256_hex(
        format!(
            "plan-ptr\0{TOOL_VERSION}\0{plan_kind}\0{channel}\0{host_guess}\0{}\0{release}\0{}\0{}",
            target.as_deref().unwrap_or(""),
            sha256_hex(&fs::read(&manifest)?),
            universe_id,
        )
        .as_bytes(),
    );
    let mut plan: Option<(String, String)> = None; // (metadata json, unit-graph json)
    if let Some(bytes) = store.load_action(&plan_ptr) {
        if let Ok(entry) = serde_json::from_slice::<PlanEntry>(&bytes) {
            if let Ok(ws_root) = dir.join(&entry.ws_root_rel).canonicalize() {
                if plan_fingerprint(&ws_root, &entry.files, &entry.glob_dirs) == entry.fingerprint {
                    let meta_text =
                        fs::read(store.cache_path(&entry.meta_blob)).ok().and_then(|b| String::from_utf8(b).ok());
                    let ug_text =
                        fs::read(store.cache_path(&entry.ug_blob)).ok().and_then(|b| String::from_utf8(b).ok());
                    if let (Some(mut m), Some(mut u)) = (meta_text, ug_text) {
                        // cargo output embeds absolute paths; re-root them so
                        // bit-identical checkouts elsewhere can share plans
                        let new_root = ws_root.display().to_string();
                        if entry.ws_root_abs != new_root {
                            m = m.replace(&entry.ws_root_abs, &new_root);
                            u = u.replace(&entry.ws_root_abs, &new_root);
                        }
                        plan = Some((m, u));
                    }
                }
            }
        }
    }
    let resolve_now = || -> Result<(String, String)> {
        {
            eprintln!("corgi: resolving/fetching dependencies via cargo (metadata only)");
            // Never bother the user about a stale lockfile: try --locked
            // first (it never writes), and when cargo rejects it, run once
            // unlocked so cargo brings Cargo.lock up to date, then continue.
            // The plan fingerprint hashes the lock *after* this step.
            // The probes must not depend on the caller's environment:
            // RUSTC is pinned (cargo otherwise resolves `rustc` from PATH,
            // and a rustup shim picks its toolchain by cwd), and cwd is the
            // build dir so cargo's own config discovery sees the workspace.
            if capture_with_live_stderr(
                Command::new(&cargo_bin)
                    .args(["fetch", "--locked", "--manifest-path"])
                    .arg(&manifest)
                    .env("CARGO_HOME", &cargo_home)
                    .env("RUSTC", &rustc)
                    .current_dir(&dir),
                "cargo fetch --locked",
            )
            .is_err()
            {
                eprintln!("corgi: Cargo.lock is missing or stale; letting cargo update it");
                capture_with_live_stderr(
                    Command::new(&cargo_bin)
                        .args(["fetch", "--manifest-path"])
                        .arg(&manifest)
                        .env("CARGO_HOME", &cargo_home)
                        .env("RUSTC", &rustc)
                        .current_dir(&dir),
                    "cargo fetch",
                )?;
            }
            // metadata for package details only (paths, links, metadata tables);
            // the actual per-unit resolution comes from cargo's unit-graph below
            let mut meta_cmd = Command::new(&cargo_bin);
            meta_cmd.args(["metadata", "--format-version", "1", "--locked"]);
            meta_cmd.env("CARGO_HOME", &cargo_home);
            meta_cmd.env("RUSTC", &rustc);
            meta_cmd.current_dir(&dir);
            meta_cmd.arg("--manifest-path").arg(&manifest);
            let meta_json = capture_with_live_stderr(&mut meta_cmd, "cargo metadata")?;
            let meta: Metadata = serde_json::from_str(&meta_json).context("parsing cargo metadata")?;
            // Feature unification over a FIXED universe (whole workspace, or the
            // declared member set for cross targets) — never scoped to the requested
            // package, so a dep's features don't depend on what you're building.
            let ws_manifest = Path::new(&meta.workspace_root).join("Cargo.toml");
            let mut ug_cmd = Command::new(&cargo_bin);
            ug_cmd.env("RUSTC_BOOTSTRAP", "1"); // planning only: unlock --unit-graph on stable
            ug_cmd.env("CARGO_HOME", &cargo_home);
            ug_cmd.env("RUSTC", &rustc);
            ug_cmd.current_dir(&dir);
            ug_cmd.args(["build", "--unit-graph", "-Zunstable-options", "--locked"]);
            if matches!(mode, Mode::Test) {
                ug_cmd.arg("--tests");
            }
            if release {
                ug_cmd.arg("--release");
            }
            if let Some(t) = &target {
                ug_cmd.args(["--target", t]);
            }
            match target.as_ref().and_then(|t| universes.iter().find(|(k, _)| k == t)) {
                Some((_, members)) => {
                    for m in members {
                        ug_cmd.args(["-p", m]);
                    }
                }
                None => {
                    ug_cmd.arg("--workspace");
                }
            }
            ug_cmd.arg("--manifest-path").arg(&ws_manifest);
            let ug_json = capture_with_live_stderr(&mut ug_cmd, "cargo build --unit-graph")?;
            save_plan(&store, &plan_ptr, &dir, &meta, &meta_json, &ug_json)?;
            Ok((meta_json, ug_json))
        }
    };
    let from_cache = plan.is_some();
    let (mut meta_json, mut ug_json) = match plan {
        Some(cached) => {
            eprintln!("corgi: plan unchanged (cached resolve; skipping cargo)");
            cached
        }
        None => resolve_now()?,
    };
    let mut meta: Metadata = serde_json::from_str(&meta_json).context("parsing cargo metadata")?;
    // A cached plan says nothing about dependency sources still being
    // extracted in the store (gc may have trimmed them); verify cheaply
    // and re-resolve once if anything is missing.
    if from_cache && meta.packages.iter().any(|p| p.source.is_some() && !p.root().exists()) {
        eprintln!("corgi: dependency sources missing from the store; re-fetching");
        let (m, u) = resolve_now()?;
        meta_json = m;
        ug_json = u;
        meta = serde_json::from_str(&meta_json).context("parsing cargo metadata")?;
    }
    // GC use-marker: dependency sources referenced by this plan stay
    // live. Git checkouts keep their marker at the checkout root, which
    // can be an ancestor of the package root.
    for pkg in &meta.packages {
        if pkg.source.is_none() {
            continue;
        }
        let root = pkg.root();
        let mut marker: Option<PathBuf> = None;
        let mut cursor: Option<&Path> = Some(root.as_path());
        while let Some(c) = cursor {
            if !c.starts_with(&cargo_home) {
                break;
            }
            let ok = c.join(".cargo-ok");
            if ok.exists() {
                marker = Some(ok);
                break;
            }
            cursor = c.parent();
        }
        Store::touch_used(marker.as_deref().unwrap_or(root.as_path()));
    }

    let mut pkgs = HashMap::new();
    for (i, p) in meta.packages.iter().enumerate() {
        pkgs.insert(p.id.clone(), i);
    }
    let root_pi = select_root_package(&meta, &pkgs, workspace, package.as_deref(), mode)?;
    let ug: meta::UnitGraph = serde_json::from_str(&ug_json).context("parsing unit-graph")?;
    let units = translate_unit_graph(&ug, &pkgs, root_pi)?;
    let profile_name = units
        .iter()
        .find(|u| u.is_root)
        .map(|u| u.profile.dir_name())
        .unwrap_or_else(|| if release { "release".into() } else { "debug".into() });
    // Source-free unit identities (memoized DFS over dep edges).
    let idents: Vec<String> = {
        let mut memo: Vec<Option<String>> = vec![None; units.len()];
        fn ident_of(i: usize, units: &[Unit], meta: &Metadata, memo: &mut Vec<Option<String>>) -> String {
            if let Some(v) = &memo[i] {
                return v.clone();
            }
            let u = &units[i];
            let mut dep_ids: Vec<String> =
                u.deps.iter().map(|d| ident_of(d.unit, units, meta, memo)).collect();
            dep_ids.sort();
            let mut features = u.features.clone();
            features.sort();
            let prof = &u.profile;
            let ident = sha256_hex(
                format!(
                    "ident\0{}\0{}\0{}\0{:?}\0{}\0{}\0{}\0{}\0{:?}\0{}\0{}\0{}\0{:?}\0{:?}",
                    TOOL_VERSION,
                    ws_relative_pkg_id(&meta.packages[u.pkg].id, &meta.workspace_root),
                    u.target.name,
                    u.target.kind,
                    u.host,
                    prof.name,
                    prof.opt_level,
                    prof.debuginfo_flag(),
                    prof.codegen_units,
                    prof.panic,
                    prof.debug_assertions,
                    prof.overflow_checks,
                    features,
                    dep_ids
                )
                .as_bytes(),
            )[..16]
                .to_string();
            memo[i] = Some(ident.clone());
            ident
        }
        (0..units.len()).map(|i| ident_of(i, &units, &meta, &mut memo)).collect()
    };
    // One-shot warnings for profile settings we deliberately don't honor.
    if units.iter().any(|u| u.profile.lto_enabled()) {
        eprintln!("corgi: warning: profile requests lto; not supported yet, building without");
    }
    if units.iter().any(|u| u.profile.rpath) {
        eprintln!("corgi: warning: profile requests rpath; ignored");
    }
    if units.iter().any(|u| {
        u.profile.debuginfo_flag() != "0"
            && matches!(u.profile.split_debuginfo.as_deref(), Some("packed") | Some("off"))
    }) {
        eprintln!(
            "corgi: warning: split-debuginfo=packed/off requested; darwin linking units use unpacked (determinism requires it)"
        );
    }
    // Under check, everything needed for *execution* (build scripts, their
    // runs, proc-macros) and their transitive closures still fully
    // compiles; the rest emits metadata only.
    let mut check_mode: Vec<bool> = Vec::new();
    if matches!(mode, Mode::Check | Mode::Clippy) {
        let mut codegen = vec![false; units.len()];
        let mut stack: Vec<usize> = (0..units.len())
            .filter(|&i| {
                matches!(units[i].kind, Kind::Bsc | Kind::Bsr)
                    || (matches!(units[i].kind, Kind::Lib)
                        && unit_crate_type(&units[i]) == "proc-macro")
            })
            .collect();
        while let Some(i) = stack.pop() {
            if codegen[i] {
                continue;
            }
            codegen[i] = true;
            for d in &units[i].deps {
                stack.push(d.unit);
            }
        }
        check_mode = (0..units.len()).map(|i| !codegen[i]).collect();
    }
    let t_plan_done = Instant::now();

    let home = std::env::var("HOME").unwrap_or_default();
    let rustup_home = std::env::var("RUSTUP_HOME").unwrap_or_else(|_| format!("{home}/.rustup"));
    let devdir = capture(Command::new("/usr/bin/xcode-select").arg("-p"), "xcode-select -p")
        .map(|s| s.trim().to_string())
        .unwrap_or_else(|_| "/Library/Developer/CommandLineTools".to_string());
    // toolchain identity beyond rustc: the linker chain shapes final bits
    let cc_v = capture(Command::new("cc").arg("--version"), "cc --version")
        .ok()
        .and_then(|o| o.lines().next().map(str::to_string))
        .unwrap_or_default();
    let ld_v = Command::new("ld")
        .arg("-v")
        .output()
        .map(|o| {
            let all = format!(
                "{}{}",
                String::from_utf8_lossy(&o.stdout),
                String::from_utf8_lossy(&o.stderr)
            );
            all.lines().next().unwrap_or("").to_string()
        })
        .unwrap_or_default();
    let sdk_v = if host.contains("apple") {
        capture(Command::new("/usr/bin/xcrun").arg("--show-sdk-version"), "xcrun --show-sdk-version")
            .map(|s| s.trim().to_string())
            .unwrap_or_default()
    } else {
        String::new()
    };
    // one Xcode identity pin covers the whole Apple tool group
    // (ar, ranlib, clang, ld, metal, xcrun) — they ship together
    let xcode_v = if host.contains("apple") {
        capture(Command::new("/usr/bin/xcodebuild").arg("-version"), "xcodebuild -version")
            .map(|s| s.split_whitespace().collect::<Vec<_>>().join(" "))
            .unwrap_or_default()
    } else {
        String::new()
    };
    let toolchain = format!("cc: {cc_v}\nld: {ld_v}\nsdk: {sdk_v}\nxcode: {xcode_v}");
    // Unconditional where the platform supports it: there is exactly one
    // mode, and it fails hard. Errors name the missing input (denied exec,
    // undeclared read), and the fix is a pinned tool or extra-inputs
    // stanza — loop until green.
    let sandbox = host.contains("apple") && Path::new("/usr/bin/sandbox-exec").is_file();
    if sandbox {
        eprintln!("corgi: hermetic sandbox enabled (seatbelt)");
    }
    // canonical darwin per-user temp/cache dirs: xcrun/clang/ld use these
    // regardless of $TMPDIR; without them every link takes a ~1.5s slow path
    let mut darwin_dirs = Vec::new();
    for key in ["DARWIN_USER_TEMP_DIR", "DARWIN_USER_CACHE_DIR"] {
        if let Ok(d) = capture(Command::new("/usr/bin/getconf").arg(key), "getconf") {
            let d = d.trim().trim_end_matches('/').to_string();
            if !d.is_empty() {
                let canon = if d.starts_with("/var/") { format!("/private{d}") } else { d };
                darwin_dirs.push(canon);
            }
        }
    }
    // resolve the SDK once, outside the sandbox, instead of letting every
    // rustc link shell out to xcrun (slow and an untracked probe)
    let sdkroot = if host.contains("apple") {
        capture(Command::new("/usr/bin/xcrun").arg("--show-sdk-path"), "xcrun --show-sdk-path")
            .map(|s| s.trim().to_string())
            .unwrap_or_default()
    } else {
        String::new()
    };
    let cargo = cargo_bin.display().to_string();
    // Lints are plan-time-resolved inputs (see resolve_lints).
    let lints = resolve_lints(&meta)?;
    let mut clippy_driver = String::new();
    let mut clippy_id = String::new();
    let mut clippy_conf: Option<PathBuf> = None;
    if matches!(mode, Mode::Clippy) {
        ensure_clippy(&store, &channel, &host_guess)?;
        clippy_driver = format!("{}/bin/clippy-driver", toolchain_logical.display());
        let version = capture(Command::new(&clippy_driver).arg("-V"), "clippy-driver -V")?;
        let mut conf_hash = String::new();
        for name in ["clippy.toml", ".clippy.toml"] {
            let candidate = Path::new(&meta.workspace_root).join(name);
            if candidate.is_file() {
                conf_hash = crate::store::sha256_file(&candidate)?;
                clippy_conf = Some(candidate);
                break;
            }
        }
        clippy_id = format!("{}|{conf_hash}", version.trim());
    }
    let mut tools_rt: Vec<ToolRt> = Vec::new();
    let mut env_probes: Vec<(String, String, Vec<String>, Vec<String>)> = Vec::new();
    if let Some((specs, probes, _, _)) = read_corgi_toml(&dir)? {
        for t in &specs {
            ensure_tool(&store, t)?;
            let exported = if !t.bin.is_empty() { &t.bin } else { &t.path };
            let logical = store
                .logical_root()
                .join("tools")
                .join(format!("{}-{}", t.name, t.version))
                .join(exported);
            let scope = if t.packages.is_empty() {
                String::new()
            } else {
                format!(" (packages {:?})", t.packages)
            };
            eprintln!("corgi: tool {} {} -> ${}{scope}", t.name, t.version, t.env);
            // The setting's own identity: exactly the scoped actions key
            // on it, so a pin edit has exactly the declared blast radius.
            let id = sha256_hex(
                format!(
                    "tool\0{}\0{}\0{}\0{}\0{}\0{}\0{}",
                    t.name, t.version, t.url, t.sha256, t.bin, t.path, t.env
                )
                .as_bytes(),
            );
            tools_rt.push(ToolRt {
                name: t.name.clone(),
                version: t.version.clone(),
                env: t.env.clone(),
                value: logical.display().to_string(),
                id,
                bin: t.bin.clone(),
                packages: t.packages.clone(),
            });
        }
        // Plan-time probes: ambient reads happen HERE, outside the
        // sandbox, frozen into keyed values. A probe only runs when some
        // scoped package builds under a scoped profile — dev builds never
        // execute (or key on) a release-only probe.
        for probe in &probes {
            let active = units.iter().any(|u| {
                let pkg_name = &meta.packages[u.pkg].name;
                probe.packages.iter().any(|p| p == pkg_name)
                    && (probe.profiles.is_empty()
                        || probe.profiles.iter().any(|pr| pr == &u.profile.name))
            });
            if !active {
                continue;
            }
            let parts: Vec<&str> = probe.command.split_whitespace().collect();
            if parts.is_empty() {
                bail!("env {} has an empty command", probe.name);
            }
            let out = capture(
                Command::new(parts[0]).args(&parts[1..]).current_dir(Path::new(&meta.workspace_root)),
                &format!("env probe {}", probe.name),
            )?;
            let val = out.trim().to_string();
            eprintln!(
                "corgi: env {}={} (packages {:?}{})",
                probe.name,
                val,
                probe.packages,
                if probe.profiles.is_empty() {
                    String::new()
                } else {
                    format!(", profiles {:?}", probe.profiles)
                }
            );
            env_probes.push((probe.name.clone(), val, probe.packages.clone(), probe.profiles.clone()));
        }
    }
    // Actions never see the ambient PATH: they get [shims:]/usr/bin:/bin,
    // where the shim dir (built per visible tool subset in
    // run_build_script) resolves bare-name spawns to keyed content.
    let mut base_env = vec![("PATH".to_string(), "/usr/bin:/bin".to_string())];
    if let Ok(v) = std::env::var("HOME") {
        base_env.push(("HOME".to_string(), v));
    }

    {
        let building = match root_pi {
            Some(pi) => {
                let root_pkg = &meta.packages[pi];
                format!("{} v{}", root_pkg.name, root_pkg.version)
            }
            None => "workspace".to_string(),
        };
        eprintln!(
            "corgi: building {building}{} units (store {})",
            units.len(),
            store.root.display()
        );
    }

    let pool = store.root.join("pool");
    let pool_logical = store.logical_root().join("pool");
    let file_names_memo = Mutex::new(HashMap::new());
    let workspace_root = meta.workspace_root.clone();
    if let Some(config_location) = &config_dir {
        if config_location != Path::new(&workspace_root) {
            bail!(
                ".cargo/config found at {} but the workspace root is {}; corgi only honors the workspace's own config",
                config_location.display(),
                workspace_root
            );
        }
    }
    let ctx = Ctx {
        store,
        verbose,
        rustc,
        rustc_version,
        host,
        cfg_env,
        meta,
        units,
        pool,
        pool_logical,
        cargo,
        cargo_home,
        base_env,
        workspace_root,
        sysroot,
        rustup_home,
        devdir,
        sandbox,
        darwin_dirs,
        sdkroot,
        src_hash_memo: Mutex::new(HashMap::new()),
        src_hash_nanos: std::sync::atomic::AtomicU64::new(0),
        file_names_memo,
        profile_name,
        toolchain,
        tools: tools_rt,
        env_probes,
        target,
        timings,
        incremental: !no_incremental,
        jobserver: jobserver::Client::new(
            std::thread::available_parallelism().map(|p| p.get()).unwrap_or(4),
        )
        .context("creating jobserver")?,
        idents,
        check_mode,
        lints,
        clippy: matches!(mode, Mode::Clippy),
        clippy_driver,
        clippy_id,
        clippy_conf,
        target_std_libdir,
        cfg_env_target,
        target_rustflags,
        host_rustflags,
        config_env,
        extra_inputs,
    };

    let t_ctx_done = Instant::now();
    let results: Vec<OnceLock<UnitResult>> = (0..ctx.units.len()).map(|_| OnceLock::new()).collect();
    let (executed, cached) = schedule(&ctx, &results)?;
    let t_sched_done = Instant::now();

    if matches!(mode, Mode::Test) {
        fs::create_dir_all("/tmp/corgi/target-tmp").context("creating CARGO_TARGET_TMPDIR")?;
    }

    // Exports anchor at the WORKSPACE root (cargo's target/ convention):
    // building any member from any directory lands artifacts in one place.
    let dtarget = Path::new(&ctx.workspace_root).join("target");

    // Test harnesses run fresh every time (results deliberately uncached
    // for now, so cargo-vs-corgi comparisons stay honest). Unsandboxed,
    // exactly as if run by hand: ambient env untouched (no CARGO_* vars),
    // only cwd = the package root, which the location-free artifact
    // contract requires (baked-in "." manifest paths resolve there).
    if matches!(mode, Mode::Test) {
        let mut failures: Vec<String> = Vec::new();
        for (i, u) in ctx.units.iter().enumerate() {
            if !matches!(u.kind, Kind::Test) || !u.is_root {
                continue;
            }
            let r = results[i].get().context("test harness not built")?;
            let m = r.main.as_ref().context("test artifact missing")?;
            let pkg = &ctx.meta.packages[u.pkg];
            // Export the harness and its CGU objects (debug-map targets)
            // before running, so even a failing test leaves a debuggable
            // binary behind: `lldb target/<profile>/deps/<name>` from the
            // workspace root needs no configuration.
            let dest = dtarget.join(&ctx.profile_name).join("deps").join(&m.name);
            ctx.store.export(&m.hash, &dest, true)?;
            for o in &r.res.outputs {
                if o.name.ends_with(".rcgu.o") {
                    let odest = dtarget.join(&ctx.profile_name).join(&o.name);
                    ctx.store.export(&o.hash, &odest, false)?;
                }
            }
            eprintln!("corgi: running tests: {} ({})", u.target.name, dest.display());
            let mut c = Command::new(&dest);
            c.current_dir(pkg.root());
            if let Some(filter) = &test_filter {
                c.arg(filter);
            }
            c.args(&exec_args);
            let st = c.status().with_context(|| format!("running test {}", u.target.name))?;
            if !st.success() {
                failures.push(u.target.name.clone());
            }
        }
        if !failures.is_empty() {
            eprintln!("corgi: finished in {:.2}s", t0.elapsed().as_secs_f64());
            bail!("{} test target(s) failed: {}", failures.len(), failures.join(", "));
        }
    }

    for (i, u) in ctx.units.iter().enumerate() {
        if !matches!(mode, Mode::Build | Mode::Run) {
            break;
        }
        if matches!(u.kind, Kind::Bin) && u.is_root {
            let t = &u.target;
            let r = results[i].get().context("bin not built")?;
            let m = r.main.as_ref().context("bin artifact missing")?;
            let dest = dtarget.join(&ctx.profile_name).join(&t.name);
            ctx.store.export(&m.hash, &dest, true)?;
            eprintln!("corgi:   bin {}  (sha256 {}…)", dest.display(), &m.hash[..12]);
            for o in &r.res.outputs {
                if o.name.ends_with(".rcgu.o") {
                    // The binary's debug map references these objects
                    // relative to the workspace root.
                    let odest = dtarget.join(&ctx.profile_name).join(&o.name);
                    ctx.store.export(&o.hash, &odest, false)?;
                }
            }
        }
        if matches!(u.kind, Kind::Lib) && u.is_root && !u.host {
            if let (Some(tgt), Some(r)) = (ctx.target.as_deref(), results[i].get()) {
                let k16 = &r.key[..16];
                for o in &r.res.outputs {
                    if o.name.ends_with(".wasm") || o.name.ends_with(".dylib") || o.name.ends_with(".so") {
                        let clean = o.name.replace(&format!("-{k16}"), "");
                        let dest = dtarget.join(tgt).join(&ctx.profile_name).join(&clean);
                        ctx.store.export(&o.hash, &dest, true)?;
                        eprintln!("corgi:   cdylib {}  (sha256 {}…)", dest.display(), &o.hash[..12]);
                    }
                }
            }
        }
    }
    if std::env::var_os("CORGI_TIMING").is_some() {
        use std::sync::atomic::Ordering::Relaxed;
        eprintln!(
            "corgi-timing: setup {:.3}s | plan {:.3}s | identity+tools {:.3}s | schedule {:.3}s (src-hash sum {:.3}s across workers) | export {:.3}s",
            (t_setup_done - t0).as_secs_f64(),
            (t_plan_done - t_setup_done).as_secs_f64(),
            (t_ctx_done - t_plan_done).as_secs_f64(),
            (t_sched_done - t_ctx_done).as_secs_f64(),
            ctx.src_hash_nanos.load(Relaxed) as f64 / 1e9,
            t_sched_done.elapsed().as_secs_f64(),
        );
        eprintln!(
            "corgi-timing: hinted dirs {}, files statted {}, files content-rehashed {}, immutable src-hash hits {}, export-check bytes hashed {}",
            crate::store::HINTED_DIRS.load(Relaxed),
            crate::store::STAT_FILES.load(Relaxed),
            crate::store::REHASHED_FILES.load(Relaxed),
            crate::store::IMMUTABLE_HITS.load(Relaxed),
            crate::store::EXPORT_CHECK_BYTES.load(Relaxed),
        );
    }
    eprintln!(
        "corgi: finished in {:.2}s — {executed} executed, {cached} cached",
        t0.elapsed().as_secs_f64()
    );
    maybe_auto_gc(&ctx.store);
    if matches!(mode, Mode::Run) {
        let root_bins: Vec<usize> = ctx
            .units
            .iter()
            .enumerate()
            .filter(|(_, u)| matches!(u.kind, Kind::Bin) && u.is_root)
            .map(|(i, _)| i)
            .collect();
        let package = root_bins
            .first()
            .map(|&i| &ctx.meta.packages[ctx.units[i].pkg])
            .context("selected package has no runnable binary target")?;
        let bin_index = select_run_binary(
            package.default_run.as_deref(),
            root_bins.iter().map(|&i| (i, ctx.units[i].target.name.as_str())),
        )?;
        let dest = dtarget.join(&ctx.profile_name).join(&ctx.units[bin_index].target.name);
        eprintln!("corgi:  running {}", dest.display());
        // Exactly a manual run of the exported binary: ambient env, the
        // caller's cwd, inherited stdio; corgi sets nothing (no CARGO_*
        // vars). The exit status is the child's, signals reported the way
        // a shell would (128 + signal).
        let status = Command::new(&dest)
            .args(&exec_args)
            .status()
            .with_context(|| format!("running {}", dest.display()))?;
        #[cfg(unix)]
        {
            use std::os::unix::process::ExitStatusExt;
            if let Some(signal) = status.signal() {
                std::process::exit(128 + signal);
            }
        }
        std::process::exit(status.code().unwrap_or(1));
    }
    Ok(())
}

/// What the plan cache stores: CAS pointers to the cargo metadata and
/// unit-graph JSON, plus everything needed to prove they are still valid.
#[derive(Serialize, Deserialize)]
struct PlanEntry {
    /// Build dir -> workspace root, relative (validates from any checkout).
    ws_root_rel: String,
    /// Workspace root as cargo spelled it at save time; cached JSON embeds
    /// this prefix in absolute paths, so loads from a different checkout
    /// re-root by string replacement.
    ws_root_abs: String,
    /// Workspace-root-relative files whose content shapes the plan.
    files: Vec<String>,
    /// Workspace-root-relative dirs whose set of crate subdirs shapes the
    /// plan (member globs like `crates/*` pick up new directories).
    glob_dirs: Vec<String>,
    fingerprint: String,
    meta_blob: String,
    ug_blob: String,
}

/// Hash every plan input: file contents, plus (for glob dirs) the sorted
/// child directory names that contain a Cargo.toml. Missing files hash as
/// absent, so their later appearance invalidates too.
fn plan_fingerprint(ws_root: &Path, files: &[String], glob_dirs: &[String]) -> String {
    let mut buf: Vec<u8> = Vec::new();
    for f in files {
        buf.extend_from_slice(f.as_bytes());
        buf.push(0);
        if let Ok(b) = fs::read(plan_abs(ws_root, f)) {
            buf.extend_from_slice(&b);
        } else {
            buf.extend_from_slice(b"<absent>");
        }
        buf.push(0xff);
    }
    for d in glob_dirs {
        buf.extend_from_slice(d.as_bytes());
        buf.push(0);
        let mut names: Vec<String> = Vec::new();
        if let Ok(rd) = fs::read_dir(plan_abs(ws_root, d)) {
            for e in rd.flatten() {
                if e.path().join("Cargo.toml").is_file() {
                    names.push(e.file_name().to_string_lossy().into_owned());
                }
            }
        }
        names.sort();
        for n in &names {
            buf.extend_from_slice(n.as_bytes());
            buf.push(0);
        }
        buf.push(0xff);
    }
    sha256_hex(&buf)
}

fn plan_abs(ws_root: &Path, rel: &str) -> PathBuf {
    if rel.starts_with('/') {
        PathBuf::from(rel)
    } else {
        ws_root.join(rel)
    }
}

/// `to` expressed relative to `from` (both absolute).
fn rel_path(from: &Path, to: &Path) -> String {
    let from_parts: Vec<_> = from.components().collect();
    let to_parts: Vec<_> = to.components().collect();
    let mut common = 0;
    while common < from_parts.len() && common < to_parts.len() && from_parts[common] == to_parts[common]
    {
        common += 1;
    }
    let mut parts: Vec<String> = vec!["..".to_string(); from_parts.len() - common];
    for c in &to_parts[common..] {
        parts.push(c.as_os_str().to_string_lossy().into_owned());
    }
    if parts.is_empty() {
        ".".to_string()
    } else {
        parts.join("/")
    }
}

/// Record the resolve outputs so an unchanged workspace skips cargo
/// entirely next time.
fn save_plan(
    store: &Store,
    plan_ptr: &str,
    dir: &Path,
    meta: &Metadata,
    meta_json: &str,
    ug_json: &str,
) -> Result<()> {
    let ws_root = Path::new(&meta.workspace_root)
        .canonicalize()
        .context("canonicalizing workspace root")?;
    let mut files: BTreeSet<String> = BTreeSet::new();
    files.insert("Cargo.toml".to_string());
    files.insert("Cargo.lock".to_string());
    // cargo config can reshape resolution (source replacement, patches);
    // track the workspace-root and build-dir spellings. (Configs in dirs
    // above the workspace are not tracked.)
    for name in [".cargo/config.toml", ".cargo/config"] {
        files.insert(name.to_string());
        files.insert(rel_path(&ws_root, &dir.join(name)));
    }
    let mut glob_dirs: BTreeSet<String> = BTreeSet::new();
    for p in &meta.packages {
        if p.source.is_some() {
            continue; // registry/git packages are pinned by the lockfile
        }
        let mp = Path::new(&p.manifest_path);
        files.insert(rel_path(&ws_root, mp));
        // the dir *containing* crate dirs: a new subdir with a Cargo.toml
        // may enter a `crates/*` members glob
        if let Some(container) = mp.parent().and_then(Path::parent) {
            if container.starts_with(&ws_root) {
                glob_dirs.insert(rel_path(&ws_root, container));
            }
        }
    }
    let files: Vec<String> = files.into_iter().collect();
    let glob_dirs: Vec<String> = glob_dirs.into_iter().collect();
    let entry = PlanEntry {
        ws_root_rel: rel_path(dir, &ws_root),
        ws_root_abs: meta.workspace_root.clone(),
        fingerprint: plan_fingerprint(&ws_root, &files, &glob_dirs),
        files,
        glob_dirs,
        meta_blob: store.insert_bytes(meta_json.as_bytes())?,
        ug_blob: store.insert_bytes(ug_json.as_bytes())?,
    };
    store.save_action(plan_ptr, serde_json::to_string(&entry)?.as_bytes())
}

fn capture(cmd: &mut Command, what: &str) -> Result<String> {
    let out = cmd.output().with_context(|| format!("running {what}"))?;
    if !out.status.success() {
        bail!("{what} failed:\n{}", String::from_utf8_lossy(&out.stderr));
    }
    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}

fn capture_with_live_stderr(cmd: &mut Command, what: &str) -> Result<String> {
    let out = cmd
        .stderr(Stdio::inherit())
        .output()
        .with_context(|| format!("running {what}"))?;
    if !out.status.success() {
        bail!("{what} failed with {}", out.status);
    }
    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}

fn find_in_path(name: &str) -> Option<PathBuf> {
    let path = std::env::var_os("PATH")?;
    for d in std::env::split_paths(&path) {
        let c = d.join(name);
        if c.is_file() {
            return Some(c);
        }
    }
    None
}

/// `rustc --print cfg` -> CARGO_CFG_* env for build scripts.
fn cargo_cfg_env(cfg_out: &str) -> Vec<(String, String)> {
    let mut map: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for line in cfg_out.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        if let Some((k, v)) = line.split_once('=') {
            map.entry(k.to_string()).or_default().push(v.trim_matches('"').to_string());
        } else {
            map.entry(line.to_string()).or_default();
        }
    }
    map.remove("debug_assertions");
    map.into_iter()
        .map(|(k, mut vs)| {
            vs.sort();
            (format!("CARGO_CFG_{}", k.to_uppercase().replace('-', "_")), vs.join(","))
        })
        .collect()
}

fn select_root_package(
    metadata: &Metadata,
    package_indices: &HashMap<String, usize>,
    workspace: bool,
    package: Option<&str>,
    mode: Mode,
) -> Result<Option<usize>> {
    if workspace {
        return Ok(None);
    }
    if let Some(package) = package {
        let workspace_members: BTreeSet<&str> =
            metadata.workspace_members.iter().map(String::as_str).collect();
        let matches: Vec<usize> = metadata
            .packages
            .iter()
            .enumerate()
            .filter(|(_, candidate)| {
                workspace_members.contains(candidate.id.as_str()) && candidate.name == package
            })
            .map(|(index, _)| index)
            .collect();
        return match matches.as_slice() {
            [index] => Ok(Some(*index)),
            [] => bail!("package `{package}` is not a workspace member"),
            _ => bail!("package specification `{package}` is ambiguous"),
        };
    }
    if let Some(root_id) = &metadata.resolve.root {
        return package_indices
            .get(root_id)
            .copied()
            .map(Some)
            .with_context(|| format!("root package {root_id} missing from metadata"));
    }
    if matches!(mode, Mode::Run) {
        let default_members: Vec<usize> = metadata
            .workspace_default_members
            .iter()
            .filter_map(|id| package_indices.get(id).copied())
            .collect();
        return match default_members.as_slice() {
            [index] => Ok(Some(*index)),
            [] => bail!("virtual workspace has no default package; use `-p PACKAGE`"),
            _ => bail!(
                "virtual workspace has multiple default packages: [{}]; use `-p PACKAGE`",
                default_members
                    .iter()
                    .map(|&index| metadata.packages[index].name.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
        };
    }
    bail!("no root package (build from a member directory, or pass --workspace)")
}

fn select_run_binary<'a>(
    default_run: Option<&str>,
    binaries: impl Iterator<Item = (usize, &'a str)>,
) -> Result<usize> {
    let binaries: Vec<(usize, &str)> = binaries.collect();
    if let Some(default_run) = default_run {
        return binaries
            .iter()
            .find(|(_, name)| *name == default_run)
            .map(|(index, _)| *index)
            .with_context(|| {
                format!(
                    "default-run target `{default_run}` is not available; check its required features"
                )
            });
    }
    match binaries.as_slice() {
        [(index, _)] => Ok(*index),
        _ => bail!(
            "`corgi run` could not determine which binary to run; found {}: [{}]",
            binaries.len(),
            binaries.iter().map(|(_, name)| *name).collect::<Vec<_>>().join(", ")
        ),
    }
}

/// Translate cargo's unit-graph into corgi units. Cargo did the real
/// resolution (per-platform features, cfg-gated deps, host/target split);
/// we only re-shape it.
fn translate_unit_graph(
    g: &meta::UnitGraph,
    pkgs: &HashMap<String, usize>,
    root_pi: Option<usize>,
) -> Result<Vec<Unit>> {
    let mut units: Vec<Unit> = Vec::with_capacity(g.units.len());
    for u in &g.units {
        let pi = *pkgs
            .get(&u.pkg_id)
            .with_context(|| format!("unit-graph package {} missing from metadata", u.pkg_id))?;
        let is_bs_target = u.target.kind.iter().any(|k| k == "custom-build");
        let kind = if u.mode == "run-custom-build" {
            Kind::Bsr
        } else if is_bs_target {
            Kind::Bsc
        } else if u.mode == "test" {
            Kind::Test
        } else if u.target.kind.iter().any(|k| k == "bin") {
            Kind::Bin
        } else {
            Kind::Lib
        };
        units.push(Unit {
            pkg: pi,
            kind,
            host: u.platform.is_none(),
            is_root: false,
            target: u.target.clone(),
            features: u.features.clone(),
            deps: vec![],
            profile: u.profile.clone(),
        });
    }
    let kinds: Vec<Kind> = units.iter().map(|u| u.kind).collect();
    for (i, u) in g.units.iter().enumerate() {
        let mut deps = Vec::new();
        for d in &u.dependencies {
            let extern_name = if matches!(kinds[d.index], Kind::Lib) && !matches!(kinds[i], Kind::Bsr) {
                Some(d.extern_crate_name.clone())
            } else {
                None
            };
            deps.push(UnitDep { unit: d.index, extern_name });
        }
        units[i].deps = deps;
    }
    // build-script run units sometimes carry no feature list; inherit from
    // the script's compile unit so CARGO_FEATURE_* stays correct
    for i in 0..units.len() {
        if matches!(units[i].kind, Kind::Bsr) && units[i].features.is_empty() {
            if let Some(b) = units[i].deps.iter().find(|d| matches!(kinds[d.unit], Kind::Bsc)) {
                units[i].features = units[b.unit].features.clone();
            }
        }
    }
    // The graph covers the whole universe; build only the requested
    // subgraph (with universe-unified features): one package's roots, or
    // every root cargo reported when building the whole workspace.
    let mut stack: Vec<usize> = g
        .roots
        .iter()
        .copied()
        .filter(|&r| root_pi.is_none_or(|pi| units[r].pkg == pi))
        .collect();
    if stack.is_empty() {
        bail!("requested package has no buildable roots in the unit graph");
    }
    for &r in &stack {
        units[r].is_root = true;
    }
    let mut keep = vec![false; units.len()];
    while let Some(i) = stack.pop() {
        if keep[i] {
            continue;
        }
        keep[i] = true;
        for d in &units[i].deps {
            stack.push(d.unit);
        }
    }
    let mut map = vec![usize::MAX; units.len()];
    let mut kept: Vec<Unit> = Vec::new();
    for (i, u) in units.into_iter().enumerate() {
        if keep[i] {
            map[i] = kept.len();
            kept.push(u);
        }
    }
    for u in &mut kept {
        for d in &mut u.deps {
            d.unit = map[d.unit];
        }
    }
    Ok(kept)
}

impl Ctx {
    /// Machine-independent spelling of the same path (via the store alias).
    /// This is what actions see, so any OUT_DIR string they embed in
    /// artifacts is identical on every machine.
    fn out_dir_logical(&self, key: &str) -> PathBuf {
        self.store.logical_root().join("outdirs").join(key).join("out")
    }

    fn materialize(&self, action_key: &str, res: &ActionResult) -> Result<()> {
        for o in &res.outputs {
            let pool_name = Store::pool_file_name(&o.name, action_key);
            self.store.materialize_pool(&o.hash, &pool_name, o.exe)?;
        }
        Ok(())
    }

    fn try_cache_hit(&self, key: &str) -> Result<Option<ActionResult>> {
        let Some(bytes) = self.store.load_action(key) else {
            return Ok(None);
        };
        let Ok(res) = serde_json::from_slice::<ActionResult>(&bytes) else {
            return Ok(None);
        };
        for o in &res.outputs {
            let p = self.store.cache_path(&o.hash);
            if !p.exists() {
                return Ok(None); // self-heal: treat as miss
            }
            Store::touch_used(&p);
        }
        if res.bs.is_some() {
            let ok = self.store.root.join("outdirs").join(key).join(".ok");
            if !ok.exists() {
                return Ok(None);
            }
            Store::touch_used(&ok);
        }
        self.materialize(key, &res)?;
        Ok(Some(res))
    }

    fn pkg_src_hash(&self, pi: usize) -> Result<String> {
        let started = Instant::now();
        let result = self.pkg_src_hash_inner(pi);
        self.src_hash_nanos
            .fetch_add(started.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
        result
    }

    fn pkg_src_hash_inner(&self, pi: usize) -> Result<String> {
        if let Some(h) = self.src_hash_memo.lock().unwrap().get(&pi) {
            return Ok(h.clone());
        }
        let pkg = &self.meta.packages[pi];
        let immutable = pkg
            .source
            .as_ref()
            .map(|src| format!("{src}|{}|{}", pkg.name, pkg.version));
        let mut h = self
            .store
            .hash_dir_cached(&pkg.root(), immutable.as_deref())
            .with_context(|| format!("hashing sources of {} v{}", pkg.name, pkg.version))?;
        let extras = self.extra_inputs_for(pkg);
        if !extras.is_empty() {
            let mut acc = h;
            for e in extras {
                let p = pkg.root().join(e).canonicalize().with_context(|| {
                    format!("extra-input `{e}` of {} does not exist", pkg.name)
                })?;
                if !p.starts_with(Path::new(&self.workspace_root)) {
                    bail!("extra-input `{e}` of {} escapes the workspace", pkg.name);
                }
                let eh = if p.is_dir() {
                    self.store.hash_dir_cached(&p, None)?
                } else {
                    crate::store::sha256_file(&p)?
                };
                acc.push_str(&format!("|{e}\0{eh}"));
            }
            h = sha256_hex(acc.as_bytes());
        }
        self.src_hash_memo.lock().unwrap().insert(pi, h.clone());
        Ok(h)
    }

    fn pkg_env(&self, pkg: &Package) -> Vec<(String, String)> {
        let v = &pkg.version;
        let no_build = v.split('+').next().unwrap_or(v);
        let (main, pre) = match no_build.split_once('-') {
            Some((m, p)) => (m, p),
            None => (no_build, ""),
        };
        let mut it = main.split('.');
        let major = it.next().unwrap_or("0");
        let minor = it.next().unwrap_or("0");
        let patch = it.next().unwrap_or("0");
        let mut e: Vec<(String, String)> = vec![
            ("CARGO_PKG_NAME".into(), pkg.name.clone()),
            ("CARGO_PKG_VERSION".into(), v.clone()),
            ("CARGO_PKG_VERSION_MAJOR".into(), major.into()),
            ("CARGO_PKG_VERSION_MINOR".into(), minor.into()),
            ("CARGO_PKG_VERSION_PATCH".into(), patch.into()),
            ("CARGO_PKG_VERSION_PRE".into(), pre.into()),
            ("CARGO_PKG_AUTHORS".into(), pkg.authors.join(":")),
            ("CARGO_PKG_DESCRIPTION".into(), pkg.description.clone().unwrap_or_default()),
            ("CARGO_PKG_HOMEPAGE".into(), pkg.homepage.clone().unwrap_or_default()),
            ("CARGO_PKG_REPOSITORY".into(), pkg.repository.clone().unwrap_or_default()),
            ("CARGO_PKG_LICENSE".into(), pkg.license.clone().unwrap_or_default()),
            ("CARGO_PKG_LICENSE_FILE".into(), pkg.license_file.clone().unwrap_or_default()),
            ("CARGO_PKG_README".into(), pkg.readme.clone().unwrap_or_default()),
            ("CARGO_PKG_RUST_VERSION".into(), pkg.rust_version.clone().unwrap_or_default()),
        ];
        e.sort();
        e
    }
}

/// Wrap a command in a deny-by-default seatbelt sandbox: reads limited to
/// system dirs + toolchain + store + this package, writes limited to the
/// action's own output/scratch dirs, no network. Children inherit it.
fn sandboxed_command(ctx: &Ctx, program: &str, extra_reads: &[&Path], writes: &[&Path]) -> Command {
    if !ctx.sandbox {
        return Command::new(program);
    }
    let mut prof = String::from(concat!(
        "(version 1)\n",
        "(deny default)\n",
        "(allow process-fork)\n",
        "(allow process-info*)\n",
        "(allow file-map-executable)\n",
        "(allow signal (target same-sandbox))\n",
        "(allow sysctl-read)\n",
        "(allow mach-lookup)\n",
        "(allow file-read-metadata)\n",
    ));
    // exec allowlist: the *only* runnable binaries are dispatchers
    // (/usr/bin/cc, the rustup shim) and tools whose identity is part of
    // the action key (rustc, clang/ld via the toolchain hash, build
    // scripts via their content hash)
    prof.push_str("(allow process-exec*\n");
    prof.push_str("  (literal \"/usr/bin/cc\")\n");
    let mut exec_lits = vec![
        format!("{}/bin/rustc", ctx.cargo_home),
        format!("{}/bin/rustc", ctx.sysroot),
    ];
    if let Some(r) = find_in_path(&ctx.rustc) {
        exec_lits.push(r.display().to_string());
    }
    // the whole pinned-toolchain bin dir is keyed content (e.g.
    // proc-macro-crate spawns `cargo locate-project` at macro expansion)
    let toolchain_bin = Path::new(&ctx.sysroot).join("bin");
    if let Ok(canon) = fs::canonicalize(&toolchain_bin) {
        prof.push_str(&format!("  (subpath \"{}\")\n", canon.display()));
    }
    // rust-lld & friends live under lib/rustlib/<triple>/bin — also keyed
    let rustlib = Path::new(&ctx.sysroot).join("lib/rustlib");
    if let Ok(canon) = fs::canonicalize(&rustlib) {
        prof.push_str(&format!("  (subpath \"{}\")\n", canon.display()));
    }
    for p in exec_lits {
        // seatbelt matches canonical paths: ~/.cargo/bin/rustc is a symlink
        // to rustup, so resolve before emitting the rule
        let canon = fs::canonicalize(&p).map(|c| c.display().to_string()).unwrap_or(p);
        prof.push_str(&format!("  (literal \"{canon}\")\n"));
    }
    prof.push_str(&format!("  (subpath \"{}/Toolchains\")\n", ctx.devdir));
    // the Apple tool group, keyed collectively via the Xcode identity in
    // the toolchain hash
    for p in [
        "/usr/bin/ar",
        "/usr/bin/ranlib",
        "/usr/bin/clang",
        "/usr/bin/clang++",
        "/usr/bin/c++",
        "/usr/bin/xcrun",
        "/usr/bin/xcodebuild",
        "/usr/bin/xcode-select",
        "/bin/sh",
    ] {
        prof.push_str(&format!("  (literal \"{p}\")\n"));
    }
    prof.push_str("  (subpath \"/private/var/run/com.apple.security.cryptexd\")\n");
    prof.push_str(&format!("  (subpath \"{}\")\n", ctx.store.root.join("tools").display()));
    // actions may execute binaries they just built in their own writable
    // dirs (autoconf/aws-lc style compile-and-run probes): those binaries
    // are products of keyed inputs, so this stays hermetic
    for w in writes {
        prof.push_str(&format!("  (subpath \"{}\")\n", w.display()));
    }
    prof.push_str(&format!("  (subpath \"{}\")\n", ctx.pool.display()));
    prof.push_str(")\n");
    prof.push_str("(allow file-read*\n  (literal \"/\")\n  (literal \"/dev/null\")\n  (literal \"/dev/urandom\")\n  (literal \"/dev/random\")\n  (literal \"/dev/zero\")\n");
    // Compiles run with cwd = the workspace root (cargo's shape); getcwd
    // needs the directory node itself, but nothing under it beyond the
    // explicitly granted package/extra-input subpaths.
    prof.push_str(&format!("  (literal \"{}\")\n", ctx.workspace_root));
    for p in ["/usr", "/bin", "/sbin", "/System", "/Library", "/Applications", "/opt", "/private/etc", "/private/var/db", "/private/preboot", "/private/var/run/com.apple.security.cryptexd"] {
        prof.push_str(&format!("  (subpath \"{p}\")\n"));
    }
    let mut reads: Vec<String> = vec![
        ctx.sysroot.clone(),
        ctx.cargo_home.clone(),
        ctx.rustup_home.clone(),
        ctx.devdir.clone(),
        ctx.store.root.display().to_string(),
    ];
    for d in &ctx.darwin_dirs {
        reads.push(d.clone());
    }
    for r in extra_reads {
        reads.push(r.display().to_string());
    }
    for r in reads {
        prof.push_str(&format!("  (subpath \"{r}\")\n"));
    }
    prof.push_str(")\n");
    // Align the readable set with the hashed set: the source hash deliberately
    // excludes .git, build output dirs, and Cargo.lock, so reading them must
    // be denied or they become unhashed inputs. Later SBPL rules win.
    prof.push_str("(deny file-read* file-read-metadata\n");
    let mut deny_roots: Vec<String> = vec![ctx.workspace_root.clone()];
    for r in extra_reads {
        deny_roots.push(r.display().to_string());
    }
    deny_roots.sort();
    deny_roots.dedup();
    for r in &deny_roots {
        for d in [".git", "target", "dtarget"] {
            prof.push_str(&format!("  (subpath \"{r}/{d}\")\n"));
        }
        prof.push_str(&format!("  (literal \"{r}/Cargo.lock\")\n"));
    }
    prof.push_str(")\n(allow file-write*\n  (literal \"/dev/null\")\n");
    for d in &ctx.darwin_dirs {
        prof.push_str(&format!("  (subpath \"{d}\")\n"));
    }
    for w in writes {
        prof.push_str(&format!("  (subpath \"{}\")\n", w.display()));
    }
    prof.push_str(")\n");
    let mut c = Command::new("/usr/bin/sandbox-exec");
    c.arg("-p").arg(prof).arg(program);
    c
}

fn describe(ctx: &Ctx, idx: usize) -> String {
    let u = &ctx.units[idx];
    let p = &ctx.meta.packages[u.pkg];
    let what = match u.kind {
        Kind::Lib => {
            if meta::is_proc_macro(p) { "proc-macro" } else { "lib" }.to_string()
        }
        Kind::Bsc => "build.rs compile".to_string(),
        Kind::Bsr => "build.rs run".to_string(),
        Kind::Bin => format!("bin \"{}\"", u.target.name),
        Kind::Test => format!("test \"{}\"", u.target.name),
    };
    let plat = if !u.host {
        ctx.target.as_deref().map(|t| format!("{t}")).unwrap_or_default()
    } else {
        String::new()
    };
    format!("{} v{} ({what}{plat})", p.name, p.version)
}

struct SchedState {
    ready: Vec<usize>,
    indeg: Vec<usize>,
    done: usize,
    in_flight: usize,
    errors: Vec<String>,
    executed: usize,
    cached: usize,
}

fn schedule(ctx: &Ctx, results: &[OnceLock<UnitResult>]) -> Result<(usize, usize)> {
    let n = ctx.units.len();
    // Typed dependency events: a pure-rlib compile can start as soon as its
    // lib deps have *metadata* (rmeta, published mid-codegen); anything that
    // links waits for full artifacts of its entire transitive closure (the
    // linker consumes every rlib, and closure rlib hashes enter its key).
    let mut rdeps_meta: Vec<Vec<usize>> = vec![vec![]; n];
    let mut rdeps_full: Vec<Vec<usize>> = vec![vec![]; n];
    let mut indeg = vec![0usize; n];
    for (i, u) in ctx.units.iter().enumerate() {
        let mut required: std::collections::HashSet<(usize, bool)> = std::collections::HashSet::new();
        let self_meta_ok = !is_linking(ctx, i);
        for d in &u.deps {
            let meta_edge =
                self_meta_ok && d.extern_name.is_some() && is_pipelined(ctx, d.unit);
            required.insert((d.unit, !meta_edge));
        }
        let _ = u;
        if is_linking(ctx, i) {
            // full transitive closure: every reachable unit fully done
            let mut stack: Vec<usize> = u.deps.iter().map(|d| d.unit).collect();
            let mut seen = vec![false; n];
            while let Some(j) = stack.pop() {
                if seen[j] {
                    continue;
                }
                seen[j] = true;
                required.insert((j, true));
                for d in &ctx.units[j].deps {
                    stack.push(d.unit);
                }
            }
        }
        indeg[i] = required.len();
        for (j, full) in required {
            if full {
                rdeps_full[j].push(i);
            } else {
                rdeps_meta[j].push(i);
            }
        }
    }
    let metas: Vec<OnceLock<MetaOut>> = (0..n).map(|_| OnceLock::new()).collect();
    // Per-unit wall-clock samples (ns since scheduling began); cheap
    // enough to collect always, reported only under --timings.
    let t_sched = Instant::now();
    use std::sync::atomic::{AtomicBool as TBool, AtomicU64 as TNs, Ordering::Relaxed};
    let t_start: Vec<TNs> = (0..n).map(|_| TNs::new(0)).collect();
    let t_meta: Vec<TNs> = (0..n).map(|_| TNs::new(0)).collect();
    let t_end: Vec<TNs> = (0..n).map(|_| TNs::new(0)).collect();
    let t_cached: Vec<TBool> = (0..n).map(|_| TBool::new(false)).collect();
    let phase_slots: Vec<OnceLock<Phases>> = (0..n).map(|_| OnceLock::new()).collect();
    let ready: Vec<usize> = (0..n).filter(|&i| indeg[i] == 0).collect();
    let state = Mutex::new(SchedState { ready, indeg, done: 0, in_flight: 0, errors: Vec::new(), executed: 0, cached: 0 });
    let cv = Condvar::new();
    let meta_fired: Vec<std::sync::atomic::AtomicBool> =
        (0..n).map(|_| std::sync::atomic::AtomicBool::new(false)).collect();
    // Called from inside a running rustc the moment its rmeta lands.
    let fire_meta = |idx: usize, m: MetaOut| {
        let _ = metas[idx].set(m);
        if meta_fired[idx].swap(true, std::sync::atomic::Ordering::SeqCst) {
            return;
        }
        t_meta[idx].store(t_sched.elapsed().as_nanos() as u64, Relaxed);
        let mut st = state.lock().unwrap();
        for &j in &rdeps_meta[idx] {
            st.indeg[j] -= 1;
            if st.indeg[j] == 0 {
                st.ready.push(j);
            }
        }
        drop(st);
        cv.notify_all();
    };
    let workers = std::thread::available_parallelism().map(|p| p.get()).unwrap_or(4).min(n.max(1));

    std::thread::scope(|scope| {
        for _ in 0..workers {
            scope.spawn(|| loop {
                let idx = {
                    let mut st = state.lock().unwrap();
                    loop {
                        if let Some(i) = st.ready.pop() {
                            st.in_flight += 1;
                            break i;
                        }
                        // keep-going: failed units never release dependents,
                        // so quiescence (nothing running, nothing ready) ends
                        if st.in_flight == 0 {
                            return;
                        }
                        st = cv.wait(st).unwrap();
                    }
                };
                t_start[idx].store(t_sched.elapsed().as_nanos() as u64, Relaxed);
                let res = run_unit(ctx, idx, results, &metas, &fire_meta);
                t_end[idx].store(t_sched.elapsed().as_nanos() as u64, Relaxed);
                let mut st = state.lock().unwrap();
                st.in_flight -= 1;
                match res {
                    Ok(ur) => {
                        let _ = phase_slots[idx].set(ur.phases);
                        let verb = if ur.cached {
                            "Cached"
                        } else if matches!(ctx.units[idx].kind, Kind::Bsr) {
                            "Ran"
                        } else {
                            "Compiled"
                        };
                        eprintln!("{verb:>9} {}", describe(ctx, idx));
                        if ur.cached {
                            t_cached[idx].store(true, Relaxed);
                            st.cached += 1;
                        } else {
                            st.executed += 1;
                        }
                        // late meta (cache hit, or non-streamed path): fire now
                        if !meta_fired[idx].swap(true, std::sync::atomic::Ordering::SeqCst) {
                            if let Some(rm) = ur.res.outputs.iter().find(|o| o.name.ends_with(".rmeta")) {
                                let _ = metas[idx].set(MetaOut {
                                    file: Store::pool_file_name(&rm.name, &ur.key),
                                    hash: rm.hash.clone(),
                                });
                            }
                            for &j in &rdeps_meta[idx] {
                                st.indeg[j] -= 1;
                                if st.indeg[j] == 0 {
                                    st.ready.push(j);
                                }
                            }
                        }
                        let _ = results[idx].set(ur);
                        st.done += 1;
                        for &j in &rdeps_full[idx] {
                            st.indeg[j] -= 1;
                            if st.indeg[j] == 0 {
                                st.ready.push(j);
                            }
                        }
                    }
                    Err(e) => {
                        eprintln!("   FAILED {} — dependents skipped", describe(ctx, idx));
                        st.errors.push(format!("[{}] {e:#}", describe(ctx, idx)));
                        st.done += 1;
                    }
                }
                drop(st);
                cv.notify_all();
            });
        }
    });

    let st = state.into_inner().unwrap();
    if !st.errors.is_empty() {
        eprintln!("\ncorgi: ===== {} units failed =====", st.errors.len());
        for (i, e) in st.errors.iter().enumerate() {
            let lines: Vec<&str> = e.lines().collect();
            let tail = lines.len().saturating_sub(22);
            let short: String = lines[..2.min(lines.len())]
                .iter()
                .chain(lines[tail.max(2.min(lines.len()))..].iter())
                .cloned()
                .collect::<Vec<_>>()
                .join("\n    ");
            eprintln!("  {}. {short}\n", i + 1);
        }
        bail!("{} units failed (skipped dependents not counted)", st.errors.len());
    }
    if ctx.timings {
        let wall = t_sched.elapsed();
        let mut rows: Vec<TimingRow> = Vec::new();
        let mut cached_walk_ns: u64 = 0;
        for i in 0..n {
            let end = t_end[i].load(Relaxed);
            if end == 0 || t_cached[i].load(Relaxed) {
                if end > 0 {
                    cached_walk_ns += end - t_start[i].load(Relaxed);
                }
                continue;
            }
            let start = t_start[i].load(Relaxed);
            let meta = t_meta[i].load(Relaxed);
            rows.push(TimingRow {
                label: describe(ctx, i),
                start_ns: start,
                meta_ns: if meta > start && meta < end { meta } else { 0 },
                end_ns: end,
                linking: is_linking(ctx, i),
                bsr: matches!(ctx.units[i].kind, Kind::Bsr),
                phases: phase_slots[i].get().copied().unwrap_or_default(),
            });
        }
        if let Err(e) = write_timings_report(ctx, &rows, wall, st.executed, st.cached, cached_walk_ns) {
            eprintln!("corgi: warning: could not write timings report: {e:#}");
        }
    }
    Ok((st.executed, st.cached))
}

struct TimingRow {
    label: String,
    start_ns: u64,
    /// rmeta publication (pipelined units); 0 = none observed
    meta_ns: u64,
    end_ns: u64,
    linking: bool,
    bsr: bool,
    phases: Phases,
}

/// Emit a cargo-timings-style report: a gantt of executed units (front-end
/// vs codegen split for pipelined compiles) plus a duration-sorted table.
fn write_timings_report(
    ctx: &Ctx,
    rows: &[TimingRow],
    wall: std::time::Duration,
    executed: usize,
    cached: usize,
    cached_walk_ns: u64,
) -> Result<()> {
    let wall_ns = wall.as_nanos().max(1) as u64;
    let cpu_ns: u64 = rows.iter().map(|r| r.end_ns - r.start_ns).sum();
    let mut sorted: Vec<&TimingRow> = rows.iter().collect();
    sorted.sort_by_key(|r| r.start_ns);
    let secs = |ns: u64| ns as f64 / 1e9;
    let mut gantt = String::new();
    for r in &sorted {
        let left = r.start_ns as f64 / wall_ns as f64 * 100.0;
        let width = ((r.end_ns - r.start_ns) as f64 / wall_ns as f64 * 100.0).max(0.05);
        let class = if r.bsr {
            "bsr"
        } else if r.linking {
            "link"
        } else {
            "lib"
        };
        let meta_html = if r.meta_ns > 0 {
            let mw = (r.meta_ns - r.start_ns) as f64 / (r.end_ns - r.start_ns) as f64 * 100.0;
            format!("<i style=\"width:{mw:.1}%\"></i>")
        } else {
            String::new()
        };
        let title = if r.meta_ns > 0 {
            format!(
                "{}{:.2}s at {:.2}s (rmeta after {:.2}s)",
                r.label,
                secs(r.end_ns - r.start_ns),
                secs(r.start_ns),
                secs(r.meta_ns - r.start_ns)
            )
        } else {
            format!("{}{:.2}s at {:.2}s", r.label, secs(r.end_ns - r.start_ns), secs(r.start_ns))
        };
        gantt.push_str(&format!(
            "<div class=\"row\"><span class=\"lbl\">{}</span><div class=\"bar {class}\" style=\"margin-left:{left:.2}%;width:{width:.2}%\" title=\"{title}\">{meta_html}</div></div>\n",
            r.label
        ));
    }
    let mut by_dur: Vec<&TimingRow> = rows.iter().collect();
    by_dur.sort_by_key(|r| std::cmp::Reverse(r.end_ns - r.start_ns));
    let mut table = String::new();
    for r in by_dur.iter().take(30) {
        let fe = if r.meta_ns > 0 {
            format!("{:.2}s", secs(r.meta_ns - r.start_ns))
        } else {
            "".to_string()
        };
        let ph = &r.phases;
        let total = r.end_ns - r.start_ns;
        let accounted =
            ph.key_ns + ph.cache_ns + ph.rustc_ns + ph.validate_ns + ph.ingest_ns + ph.finish_ns;
        table.push_str(&format!(
            "<tr><td>{}</td><td>{:.2}s</td><td>{:.2}s</td><td>{fe}</td><td>{:.2}s ({:.0} MB)</td><td>{:.0}ms</td><td>{:.0}ms</td><td>{:.0}ms</td><td>{:.0}ms</td><td>{:.2}s</td></tr>\n",
            r.label,
            secs(total),
            secs(ph.rustc_ns),
            secs(ph.ingest_ns),
            ph.ingest_bytes as f64 / 1e6,
            ph.key_ns as f64 / 1e6,
            ph.cache_ns as f64 / 1e6,
            ph.validate_ns as f64 / 1e6,
            ph.finish_ns as f64 / 1e6,
            secs(total.saturating_sub(accounted)),
        ));
    }
    let sum_rustc: u64 = rows.iter().map(|r| r.phases.rustc_ns).sum();
    let sum_ingest: u64 = rows.iter().map(|r| r.phases.ingest_ns).sum();
    let sum_bytes: u64 = rows.iter().map(|r| r.phases.ingest_bytes).sum();
    let sum_key: u64 = rows.iter().map(|r| r.phases.key_ns).sum();
    let sum_finish: u64 = rows.iter().map(|r| r.phases.finish_ns).sum();
    let html = format!(
        "<!doctype html><meta charset=utf-8><title>corgi timings</title><style>\
body{{font:13px system-ui;margin:20px}}h1{{font-size:18px}}\
.row{{display:flex;align-items:center;height:14px}}\
.lbl{{width:340px;flex:none;font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}}\
.bar{{height:11px;border-radius:2px;position:relative;min-width:1px}}\
.bar.lib{{background:#7cb3e8}}.bar.link{{background:#b07ce8}}.bar.bsr{{background:#e8a67c}}\
.bar i{{display:block;position:absolute;left:0;top:0;bottom:0;background:#2c6cb0;border-radius:2px 0 0 2px}}\
table{{border-collapse:collapse;margin-top:24px}}td,th{{border:1px solid #ccc;padding:2px 8px;text-align:left;font-size:12px}}\
</style>\n<h1>corgi timings</h1>\n<p>wall {:.2}s · {} executed · {} cached · cpu {:.1}s · parallelism {:.1}x</p>\n\
<div>{gantt}</div>\n<h2>slowest units</h2><table><tr><th>unit</th><th>total</th><th>rustc</th><th>front-end</th><th>ingest</th><th>key</th><th>cache</th><th>validate</th><th>finish</th><th>other</th></tr>{table}</table>\n\
<p>phase totals across executed units: rustc {:.1}s · ingest {:.1}s ({:.2} GB hashed) · key {:.1}s · finish {:.1}s · cache-hit walk {:.1}s</p>\n",
        wall.as_secs_f64(),
        executed,
        cached,
        cpu_ns as f64 / 1e9,
        cpu_ns as f64 / wall_ns as f64,
        sum_rustc as f64 / 1e9,
        sum_ingest as f64 / 1e9,
        sum_bytes as f64 / 1e9,
        sum_key as f64 / 1e9,
        sum_finish as f64 / 1e9,
        cached_walk_ns as f64 / 1e9,
    );
    let dir = Path::new(&ctx.workspace_root).join("target/corgi-timings");
    fs::create_dir_all(&dir)?;
    let stamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let path = dir.join(format!("corgi-timing-{stamp}.html"));
    fs::write(&path, &html)?;
    fs::write(dir.join("corgi-timing.html"), &html)?;
    eprintln!("corgi:   timings report: {}", path.display());
    for r in by_dur.iter().take(5) {
        eprintln!(
            "corgi:   slow: {:>7.2}s  {}",
            (r.end_ns - r.start_ns) as f64 / 1e9,
            r.label
        );
    }
    Ok(())
}

fn run_unit(
    ctx: &Ctx,
    idx: usize,
    results: &[OnceLock<UnitResult>],
    metas: &[OnceLock<MetaOut>],
    fire_meta: &(dyn Fn(usize, MetaOut) + Sync),
) -> Result<UnitResult> {
    match ctx.units[idx].kind {
        Kind::Bsr => run_build_script(ctx, idx, results),
        _ => compile(ctx, idx, results, metas, fire_meta),
    }
}

/// Authoritative output names for a compile: rustc itself reports them
/// (`--print file-names`). Two cache layers keep this at zero spawns on
/// warm builds: an in-process memo, and a store entry keyed by
/// (tool, rustc -vV, triple, crate-types).
fn expected_outputs(
    ctx: &Ctx,
    crate_name: &str,
    k16: &str,
    crate_types: &str,
    host: bool,
) -> Result<Vec<String>> {
    let memo_key = (crate_types.to_string(), host);
    let cached = ctx.file_names_memo.lock().unwrap().get(&memo_key).cloned();
    let pattern = match cached {
        Some(p) => p,
        None => {
            let plat = if host { ctx.host.as_str() } else { ctx.target.as_deref().unwrap_or(ctx.host.as_str()) };
            let probe_key = sha256_hex(
                format!("probe-file-names\0{TOOL_VERSION}\0{}\0{plat}\0{crate_types}", ctx.rustc_version).as_bytes(),
            );
            let from_store = ctx
                .store
                .load_action(&probe_key)
                .and_then(|b| serde_json::from_slice::<Vec<String>>(&b).ok());
            let p = match from_store {
                Some(p) => p,
                None => {
                    let mut cmd = Command::new(&ctx.rustc);
                    cmd.args([
                        "--print",
                        "file-names",
                        "--crate-name",
                        "corgiprobe",
                        "--crate-type",
                        crate_types,
                        "-Cextra-filename=-XCORGIX",
                    ]);
                    if !host {
                        if let Some(t) = &ctx.target {
                            cmd.args(["--target", t]);
                        }
                    }
                    cmd.arg("-");
                    cmd.stdin(std::process::Stdio::null());
                    let names = capture(&mut cmd, "rustc --print file-names")?;
                    let p: Vec<String> = names
                        .lines()
                        .map(|l| l.trim().to_string())
                        .filter(|l| !l.is_empty())
                        .collect();
                    if p.is_empty() {
                        bail!("rustc --print file-names reported nothing for {crate_types}");
                    }
                    ctx.store.save_action(&probe_key, &serde_json::to_vec(&p)?)?;
                    p
                }
            };
            ctx.file_names_memo.lock().unwrap().insert(memo_key, p.clone());
            p
        }
    };
    let mut out: Vec<String> = pattern
        .iter()
        .map(|n| n.replace("corgiprobe", crate_name).replace("-XCORGIX", &format!("-{k16}")))
        .collect();
    // pipelined pure-rlib compiles emit metadata alongside the rlib
    if crate_types == "lib" {
        out.push(format!("lib{crate_name}-{k16}.rmeta"));
    }
    Ok(out)
}

/// Run a pipelined rustc, streaming its JSON stderr: the moment the rmeta
/// artifact is reported, hash it into the cache, hard-link it into the
/// pool, and wake dependents — while this same rustc continues codegen.
fn run_rustc_streaming(
    ctx: &Ctx,
    cmd: &mut Command,
    uidx: usize,
    pkg_name: &str,
    action_key: &str,
    fire_meta: &(dyn Fn(usize, MetaOut) + Sync),
) -> Result<(bool, String)> {
    use std::io::BufRead;
    let mut child = cmd
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn()
        .with_context(|| format!("spawning rustc for {pkg_name}"))?;
    let mut rendered = String::new();
    let reader = std::io::BufReader::new(child.stderr.take().unwrap());
    for line in reader.lines() {
        let line = line?;
        match serde_json::from_str::<serde_json::Value>(&line) {
            Ok(v) => {
                let artifact = v.get("artifact").and_then(|a| a.as_str());
                let emit = v.get("emit").and_then(|e| e.as_str());
                if let (Some(path), Some("metadata")) = (artifact, emit) {
                    let bytes = fs::read(path).with_context(|| format!("reading rmeta {path}"))?;
                    let hash = ctx.store.insert_bytes(&bytes)?;
                    let file = Path::new(path)
                        .file_name()
                        .map(|f| f.to_string_lossy().into_owned())
                        .unwrap_or_default();
                    let pool_name = Store::pool_file_name(&file, action_key);
                    ctx.store.materialize_pool(&hash, &pool_name, false)?;
                    fire_meta(uidx, MetaOut { file: pool_name, hash });
                } else if let Some(r) = v.get("rendered").and_then(|r| r.as_str()) {
                    rendered.push_str(r);
                }
            }
            Err(_) => {
                rendered.push_str(&line);
                rendered.push('\n');
            }
        }
    }
    let status = child.wait()?;
    Ok((status.success(), rendered))
}

/// A location-independent spelling of cargo's package id. Path packages
/// carry a `file://` URL of their absolute directory, which would make
/// unit identities (and so -Cmetadata, symbols, and every action key)
/// specific to one checkout; identical worktrees must share all of them.
/// Path packages outside the workspace keep their absolute identity —
/// they really are machine-local.
fn ws_relative_pkg_id(id: &str, workspace_root: &str) -> String {
    if let Some(rest) = id.strip_prefix("path+file://") {
        let (dir, suffix) = rest.split_once('#').unwrap_or((rest, ""));
        if let Ok(rel) = Path::new(dir).strip_prefix(workspace_root) {
            return format!("path+{}#{suffix}", rel.display());
        }
    }
    id.to_string()
}

#[cfg(test)]
mod run_selection_tests {
    use super::{select_root_package, select_run_binary, Mode};
    use crate::meta::Metadata;
    use std::collections::HashMap;

    #[test]
    fn run_uses_the_single_workspace_default_member() {
        let metadata = metadata();
        let package_indices = metadata
            .packages
            .iter()
            .enumerate()
            .map(|(index, package)| (package.id.clone(), index))
            .collect::<HashMap<_, _>>();

        let selected =
            select_root_package(&metadata, &package_indices, false, None, Mode::Run).unwrap();

        assert_eq!(selected, Some(0));
        assert_eq!(metadata.packages[selected.unwrap()].name, "delta");
    }

    #[test]
    fn explicit_package_overrides_the_workspace_default_member() {
        let metadata = metadata();
        let package_indices = metadata
            .packages
            .iter()
            .enumerate()
            .map(|(index, package)| (package.id.clone(), index))
            .collect::<HashMap<_, _>>();

        let selected =
            select_root_package(&metadata, &package_indices, false, Some("helper"), Mode::Run)
                .unwrap();

        assert_eq!(selected, Some(1));
    }

    #[test]
    fn default_run_selects_among_multiple_binaries() {
        let selected =
            select_run_binary(Some("delta"), [(4, "delta-cli"), (9, "delta")].into_iter())
                .unwrap();

        assert_eq!(selected, 9);
        assert!(select_run_binary(None, [(4, "delta-cli"), (9, "delta")].into_iter()).is_err());
    }

    fn metadata() -> Metadata {
        serde_json::from_value(serde_json::json!({
            "workspace_members": ["delta 0.1.0 (path+file:///workspace/crates/delta)", "helper 0.1.0 (path+file:///workspace/crates/helper)"],
            "workspace_default_members": ["delta 0.1.0 (path+file:///workspace/crates/delta)"],
            "packages": [
                {
                    "name": "delta",
                    "version": "0.1.0",
                    "id": "delta 0.1.0 (path+file:///workspace/crates/delta)",
                    "source": null,
                    "manifest_path": "/workspace/crates/delta/Cargo.toml",
                    "edition": "2021",
                    "default_run": "delta",
                    "targets": [],
                    "metadata": {}
                },
                {
                    "name": "helper",
                    "version": "0.1.0",
                    "id": "helper 0.1.0 (path+file:///workspace/crates/helper)",
                    "source": null,
                    "manifest_path": "/workspace/crates/helper/Cargo.toml",
                    "edition": "2021",
                    "targets": [],
                    "metadata": {}
                }
            ],
            "resolve": {"root": null},
            "workspace_root": "/workspace"
        }))
        .unwrap()
    }
}

#[cfg(test)]
mod tool_url_tests {
    use super::parse_github_release_url;

    #[test]
    fn release_asset_urls_split_into_repo_tag_and_asset() {
        let (repo, tag, asset) = parse_github_release_url(
            "https://github.com/zed-industries/delta-terminal/releases/download/build-abc123/ex-terminal-aarch64-macos.tar.gz",
        )
        .unwrap();
        assert_eq!(repo, "zed-industries/delta-terminal");
        assert_eq!(tag, "build-abc123");
        assert_eq!(asset, "ex-terminal-aarch64-macos.tar.gz");
    }

    #[test]
    fn non_release_urls_are_rejected() {
        assert!(parse_github_release_url("https://example.com/a/b/releases/download/t/x").is_err());
        assert!(parse_github_release_url("https://github.com/o/r/archive/main.tar.gz").is_err());
        assert!(parse_github_release_url("https://github.com/o/r/releases/download/tag").is_err());
    }
}

#[cfg(test)]
mod ident_tests {
    use super::ws_relative_pkg_id;

    #[test]
    fn path_package_ids_are_workspace_relative() {
        // Two checkouts of the same repo must produce one identity.
        let a = ws_relative_pkg_id("path+file:///w/one/crates/editor#0.1.0", "/w/one");
        let b = ws_relative_pkg_id("path+file:///w/two/crates/editor#0.1.0", "/w/two");
        assert_eq!(a, "path+crates/editor#0.1.0");
        assert_eq!(a, b);
        // Name-carrying suffixes survive.
        assert_eq!(
            ws_relative_pkg_id("path+file:///w/crates/foo#bar@1.2.3", "/w"),
            "path+crates/foo#bar@1.2.3"
        );
        // Registry ids and out-of-workspace path deps are untouched.
        let registry = "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.0";
        assert_eq!(ws_relative_pkg_id(registry, "/w"), registry);
        let outside = "path+file:///elsewhere/dep#0.1.0";
        assert_eq!(ws_relative_pkg_id(outside, "/w"), outside);
    }
}

fn finish_compile(
    expected: &[String],
    key: String,
    cached: bool,
    res: ActionResult,
    phases: Phases,
) -> Result<UnitResult> {
    // every rustc-reported output must exist: catches emission surprises
    for e in expected {
        if !res.outputs.iter().any(|o| &o.name == e) {
            bail!(
                "rustc-reported output {e} missing (got {:?})",
                res.outputs.iter().map(|o| &o.name).collect::<Vec<_>>()
            );
        }
    }
    // the dependency-linking artifact: the rlib when one is emitted,
    // otherwise the sole reported output (dylib/wasm/executable)
    let main_name = expected
        .iter()
        .find(|e| e.ends_with(".rlib"))
        .or_else(|| expected.first())
        .context("no expected outputs")?;
    let main = res.outputs.iter().find(|o| &o.name == main_name).cloned();
    Ok(UnitResult { key, cached, res, main, phases })
}

fn compile(
    ctx: &Ctx,
    uidx: usize,
    results: &[OnceLock<UnitResult>],
    metas: &[OnceLock<MetaOut>],
    fire_meta: &(dyn Fn(usize, MetaOut) + Sync),
) -> Result<UnitResult> {
    let unit = &ctx.units[uidx];
    let pkg = &ctx.meta.packages[unit.pkg];
    let pkg_root = pkg.root();

    let target: &Target = &unit.target;
    let (crate_name, crate_type): (String, String) = match unit.kind {
        Kind::Lib => {
            let ct = if target.kind.iter().any(|k| k == "proc-macro") {
                "proc-macro".to_string()
            } else if unit.is_root && target.crate_types.iter().any(|c| c == "cdylib") {
                // the deployable: build with its declared crate types
                target.crate_types.join(",")
            } else {
                "lib".to_string()
            };
            (target.name.replace('-', "_"), ct)
        }
        Kind::Bsc | Kind::Bin | Kind::Test => (target.name.replace('-', "_"), "bin".to_string()),
        Kind::Bsr => unreachable!(),
    };
    let crate_type = crate_type.as_str();
    // Cargo's invocation shape: rustc runs from the workspace root and
    // workspace sources are spelled relative to it, so Location::file(),
    // panic messages, and debug info match cargo's byte for byte without
    // a checkout prefix entering the artifact. Sources outside the
    // workspace (registry, git) keep their canonical store spelling.
    let src_rel = Path::new(&target.src_path)
        .strip_prefix(&ctx.workspace_root)
        .map(|p| p.to_string_lossy().into_owned())
        .unwrap_or_else(|_| target.src_path.clone());

    let mut features: Vec<String> = unit.features.clone();
    features.sort();

    let self_checked = is_checked(ctx, uidx);
    let self_pipelined = is_pipelined(ctx, uidx);
    let default_bs = BuildScriptOut::default();
    let mut bs: &BuildScriptOut = &default_bs;
    let mut out_key = String::new();
    let mut externs: Vec<(String, String, String)> = Vec::new();
    for d in &unit.deps {
        if let Some(name) = &d.extern_name {
            if self_pipelined && is_pipelined(ctx, d.unit) {
                // pipelined edge: compile against the dep's rmeta, keyed by
                // the rmeta's bytes (what this action actually consumes)
                let m = metas[d.unit].get().context("dependency rmeta missing")?;
                externs.push((name.clone(), m.file.clone(), m.hash.clone()));
            } else {
                let r = results[d.unit].get().context("dependency result missing")?;
                let m = r.main.as_ref().context("dependency artifact missing")?;
                externs.push((name.clone(), Store::pool_file_name(&m.name, &r.key), m.hash.clone()));
            }
        } else if matches!(ctx.units[d.unit].kind, Kind::Bsr) && ctx.units[d.unit].pkg == unit.pkg {
            let r = results[d.unit].get().context("dependency result missing")?;
            if let Some(b) = &r.res.bs {
                bs = b;
                out_key = r.key.clone();
            }
        }
    }
    externs.sort();

    // Linking units consume every transitive rlib: enumerate the closure's
    // artifacts into the key (the interface chain is cut by rmeta keying,
    // so implementations must be pinned flat, at the link).
    let mut link_closure: Vec<(String, String)> = Vec::new();
    if is_linking(ctx, uidx) {
        let mut seen = vec![false; ctx.units.len()];
        let mut stack: Vec<usize> = unit.deps.iter().map(|d| d.unit).collect();
        while let Some(i) = stack.pop() {
            if seen[i] {
                continue;
            }
            seen[i] = true;
            if let Some(r) = results[i].get() {
                if let Some(m) = &r.main {
                    link_closure.push((m.name.clone(), m.hash.clone()));
                }
            }
            for d in &ctx.units[i].deps {
                stack.push(d.unit);
            }
        }
        link_closure.sort();
        link_closure.dedup();
    }

    let mut link_search: Vec<String> = bs.link_search.clone();
    let mut link_args: Vec<String> = Vec::new();
    if matches!(unit.kind, Kind::Bin) {
        link_args = bs.link_args.clone();
        // native lib search paths from all transitive build scripts must be
        // visible when linking the final binary
        let mut seen = vec![false; ctx.units.len()];
        let mut stack: Vec<usize> = unit.deps.iter().map(|d| d.unit).collect();
        while let Some(i) = stack.pop() {
            if seen[i] {
                continue;
            }
            seen[i] = true;
            if let Some(r) = results[i].get() {
                if let Some(b) = &r.res.bs {
                    for s in &b.link_search {
                        if !link_search.contains(s) {
                            link_search.push(s.clone());
                        }
                    }
                }
            }
            for d in &ctx.units[i].deps {
                stack.push(d.unit);
            }
        }
    }

    let mut env = ctx.pkg_env(pkg);
    env.extend(ctx.config_env.iter().cloned());
    if matches!(unit.kind, Kind::Bin) {
        env.push(("CARGO_BIN_NAME".to_string(), target.name.clone()));
    }
    if matches!(unit.kind, Kind::Test) && target.kind.iter().any(|k| k == "test" || k == "bench") {
        // Cargo sets CARGO_TARGET_TMPDIR only when compiling integration
        // tests and benches: a scratch directory the harness may use at
        // runtime, normally baked in via env!. proc-macro-crate keys its
        // Itself-vs-Name answer off the variable's mere presence. One
        // fixed machine-global path keeps the baked value identical
        // everywhere (a workspace path would trip the location tripwire).
        env.push(("CARGO_TARGET_TMPDIR".to_string(), "/tmp/corgi/target-tmp".to_string()));
    }
    let unit_rustflags: &[String] =
        if unit.host { &ctx.host_rustflags } else { &ctx.target_rustflags };
    let t_phase = Instant::now();
    let mut phases = Phases::default();
    let src_hash = ctx.pkg_src_hash(unit.pkg)?;
    let cap_lints = pkg.source.is_some();

    // Per-unit resolved profile straight from cargo's unit graph.
    // Checked units skip debug info: they emit metadata only.
    let prof = &unit.profile;
    let debuginfo = if self_checked { "0".to_string() } else { prof.debuginfo_flag() };
    let mut pflags: Vec<String> = vec![
        format!(
            "-Copt-level={}",
            if prof.opt_level.is_empty() { "0" } else { prof.opt_level.as_str() }
        ),
        format!("-Cdebug-assertions={}", if prof.debug_assertions { "on" } else { "off" }),
        format!("-Coverflow-checks={}", if prof.overflow_checks { "on" } else { "off" }),
        format!("-Cdebuginfo={debuginfo}"),
        format!("-Cstrip={}", prof.strip_flag()),
        "-Cembed-bitcode=no".to_string(),
    ];
    if let Some(n) = prof.codegen_units {
        pflags.push(format!("-Ccodegen-units={n}"));
    }
    if !prof.panic.is_empty() && prof.panic != "unwind" && !matches!(unit.kind, Kind::Test) {
        pflags.push(format!("-Cpanic={}", prof.panic));
    }
    // Lints and (in clippy mode) the executor swap. Like cargo's
    // workspace wrapper, clippy-driver runs for EVERY unit of local
    // packages — checked units and the codegen closure (proc-macros,
    // build scripts), so their own code is linted too. All of it lives
    // in clippy-keyed actions (--cfg clippy is code-visible); the
    // dependency layer stays plain-rustc and is shared with check.
    let clippy_action = ctx.clippy && pkg.source.is_none();
    let lint_flags: &[String] = if clippy_action {
        &ctx.lints[unit.pkg].with_clippy
    } else {
        &ctx.lints[unit.pkg].rustc_only
    };
    let unit_platform = if unit.host {
        ctx.host.as_str()
    } else {
        ctx.target.as_deref().unwrap_or(ctx.host.as_str())
    };
    // Cargo's resolved profile says which units it would compile
    // incrementally (local packages under dev); we honor exactly that,
    // in a separate key namespace.
    let incr_action = ctx.incremental && prof.incremental;
    // Determinism forces the darwin debug-map treatment on every linking
    // unit with debug info, whatever split-debuginfo the profile asked
    // for: without -oso_prefix the staging path would leak into stabs.
    let oso_split = debuginfo != "0" && is_linking(ctx, uidx) && unit_platform.contains("apple");
    let oso_rel = if oso_split { format!("target/{}/", ctx.profile_name) } else { String::new() };

    let key_json = serde_json::to_string(&CompileKey {
        kind: if clippy_action {
            if self_checked { "clippy" } else { "clippy-compile" }
        } else if self_checked {
            "check"
        } else if matches!(unit.kind, Kind::Test) {
            "compile-test"
        } else {
            "compile"
        },
        tool: TOOL_VERSION,
        rustc: &ctx.rustc_version,
        host: &ctx.host,
        pkg: [&pkg.name, &pkg.version, pkg.source.as_deref().unwrap_or("local")],
        src_hash: &src_hash,
        crate_name: &crate_name,
        edition: &target.edition,
        crate_type,
        src_rel: &src_rel,
        features: &features,
        externs: &externs,
        link_closure: &link_closure,
        cfgs: &bs.cfgs,
        renvs: &bs.envs,
        link_libs: &bs.link_libs,
        link_search: &link_search,
        link_args: &link_args,
        out_key: &out_key,
        profile: &pflags,
        lints: lint_flags,
        clippy: if clippy_action { &ctx.clippy_id } else { "" },
        incr: incr_action,
        ident: &ctx.idents[uidx],
        oso: &oso_rel,
        env: &env,
        cap_lints,
        rustflags: unit_rustflags,
        toolchain: if crate_type == "lib" || self_checked { "" } else { &ctx.toolchain },
        tgt: if unit.host { "" } else { ctx.target.as_deref().unwrap_or("") },
    })?;
    let key = sha256_hex(key_json.as_bytes());
    let k16: String = key[..16].to_string();
    // Incremental units use the identity hash, not the action key, in
    // -Cextra-filename: rustc's dep graph embeds the output file names,
    // so a key-derived (source-dependent) value marks every saved session
    // red on each edit. Clean-namespace units keep the key-unique k16.
    let ef16: String = if incr_action { ctx.idents[uidx].clone() } else { k16.clone() };
    phases.key_ns = t_phase.elapsed().as_nanos() as u64;

    let t_cache = Instant::now();
    let hit = ctx.try_cache_hit(&key)?;
    phases.cache_ns = t_cache.elapsed().as_nanos() as u64;
    if let Some(res) = hit {
        let expected: Vec<String> = if self_checked {
            res.outputs.iter().map(|o| o.name.clone()).collect()
        } else {
            expected_outputs(ctx, &crate_name, &ef16, crate_type, unit.host)?
        };
        if expected.iter().all(|e| res.outputs.iter().any(|o| &o.name == e)) {
            if !res.stderr.is_empty() && pkg.source.is_none() {
                eprint!("{}", res.stderr);
            }
            return finish_compile(&expected, key, true, res, phases);
        }
        // A record that does not cover the expected outputs was written by
        // a buggy or interrupted run: heal by dropping it and re-executing.
        eprintln!(
            "corgi: discarding corrupt action record for {} ({crate_name})",
            pkg.name
        );
        fs::remove_file(ctx.store.action_path(&key)).ok();
    }

    // Incremental state: store-managed, scoped per (checkout, crate,
    // crate-type, mode, platform, profile) so histories never cross;
    // flock-guarded for the duration of the compile (rustc tolerates a
    // stale dir by falling back to a clean session).
    let mut incr_lock: Option<fs::File> = None;
    let incr_dir: Option<PathBuf> = if incr_action {
        let kind_tag = match unit.kind {
            Kind::Bin => "bin",
            Kind::Lib => "lib",
            Kind::Bsc => "bsc",
            Kind::Bsr => "bsr",
            Kind::Test => "test",
        };
        let mode_tag = if clippy_action {
            "clippy"
        } else if self_checked {
            "check"
        } else {
            "full"
        };
        let identity = sha256_hex(
            format!(
                "incr\0{}\0{}\0{}\0{}\0{}\0{}\0{}\0{}\0{}",
                ctx.workspace_root,
                pkg.name,
                crate_name,
                crate_type,
                kind_tag,
                mode_tag,
                unit_platform,
                ctx.profile_name,
                // The unit identity separates same-name units (a lib
                // compiled for the target and again as a host-side
                // dependency of a proc-macro): each needs its own state
                // and, above all, its own pinned output directory.
                ctx.idents[uidx]
            )
            .as_bytes(),
        );
        let dir = ctx.store.root.join("incr").join(&identity[..16]);
        fs::create_dir_all(&dir)?;
        let lock = fs::File::create(ctx.store.root.join("incr").join(format!("{}.lock", &identity[..16])))?;
        lock.lock().with_context(|| format!("locking incremental state for {crate_name}"))?;
        incr_lock = Some(lock);
        Some(dir)
    } else {
        None
    };
    // Incremental units compile with a pinned output context: rustc's
    // dep graph embeds the output directory path, so a per-run tmp dir
    // marks every saved session red. The stable dir is wiped first —
    // artifacts are re-emitted from session state, and ingestion scans
    // the whole dir so it must never see stale files. Clean-namespace
    // units keep per-run tmp dirs.
    let stage_root = if let Some(d) = &incr_dir {
        let out = d.join("out");
        fs::remove_dir_all(&out).ok();
        out
    } else {
        ctx.store.tmp_path("rustc")
    };
    // With -oso_prefix stripping the stage root, recorded debug-map paths
    // read `target/<profile>/<cgu>.o` — exactly where the objects are
    // exported relative to the workspace root.
    let outdir = if oso_split { stage_root.join(&oso_rel) } else { stage_root.clone() };
    fs::create_dir_all(&outdir)?;
    let scratch = if let Some(d) = &incr_dir { d.join("tmp") } else { ctx.store.tmp_path("scratch") };
    fs::create_dir_all(&scratch)?;
    let extra_in: Vec<PathBuf> = ctx
        .extra_inputs_for(pkg)
        .iter()
        .filter_map(|e| pkg_root.join(e).canonicalize().ok())
        .collect();
    let mut reads: Vec<&Path> = vec![&pkg_root];
    reads.extend(extra_in.iter().map(|p| p.as_path()));
    if clippy_action {
        if let Some(conf) = &ctx.clippy_conf {
            reads.push(conf.as_path());
        }
    }
    let executor = if clippy_action { ctx.clippy_driver.as_str() } else { ctx.rustc.as_str() };
    let mut writes: Vec<&Path> = vec![&outdir, &scratch];
    if let Some(d) = &incr_dir {
        writes.push(d.as_path());
    }
    let mut cmd = sandboxed_command(ctx, executor, &reads, &writes);
    cmd.current_dir(&ctx.workspace_root);
    cmd.env_clear();
    cmd.env("TMPDIR", &scratch);
    if !ctx.sdkroot.is_empty() {
        cmd.env("SDKROOT", &ctx.sdkroot);
    }
    for (k, v) in &ctx.base_env {
        cmd.env(k, v);
    }
    for (k, v) in &env {
        cmd.env(k, v);
    }
    cmd.env("CARGO_CRATE_NAME", &crate_name);
    // Cargo-identical manifest env: absolute, and deliberately not part
    // of any action key. Sharing depends on artifacts being independent
    // of the checkout location, and the ingest byte-scan proves exactly
    // that before a record is saved — code that bakes these values into
    // an output fails the build instead of silently pinning a checkout.
    cmd.env("CARGO_MANIFEST_DIR", &pkg_root);
    cmd.env("CARGO_MANIFEST_PATH", &pkg.manifest_path);
    cmd.env("CARGO", &ctx.cargo);
    for (k, v) in &bs.envs {
        cmd.env(k, v);
    }
    if !out_key.is_empty() {
        cmd.env("OUT_DIR", ctx.out_dir_logical(&out_key));
    }

    cmd.arg("--sysroot").arg(&ctx.sysroot);
    cmd.arg("--crate-name").arg(&crate_name);
    cmd.arg("--edition").arg(&target.edition);
    cmd.arg(&src_rel);
    cmd.arg("--crate-type").arg(crate_type);
    if self_checked {
        cmd.arg("--emit=metadata,dep-info");
        cmd.arg("--error-format=json");
        cmd.arg("--json=artifacts");
    } else if self_pipelined {
        cmd.arg("--emit=metadata,link,dep-info");
        cmd.arg("--error-format=json");
        cmd.arg("--json=artifacts");
    } else {
        cmd.arg("--emit=link,dep-info");
    }
    if matches!(unit.kind, Kind::Test) {
        cmd.arg("--test");
    }
    if !unit.host {
        if let Some(t) = &ctx.target {
            cmd.arg("--target").arg(t);
            if let Some(libdir) = &ctx.target_std_libdir {
                cmd.arg("-L").arg(libdir);
            }
        }
    }
    for f in &pflags {
        cmd.arg(f);
    }
    for f in lint_flags {
        cmd.arg(f);
    }
    if clippy_action {
        // cfg(clippy) is a documented, code-visible condition — precisely
        // why clippy artifacts live in their own key namespace.
        cmd.arg("--cfg").arg("clippy");
        cmd.env("CLIPPY_CONF_DIR", &ctx.workspace_root);
    }
    if let Some(d) = &incr_dir {
        cmd.arg(format!("-Cincremental={}", d.display()));
        if std::env::var_os("CORGI_INCR_INFO").is_some() {
            // Debug aid: rustc reports session hard-link counts on stderr.
            // RUSTC_BOOTSTRAP flips the tracked unstable-features option,
            // so toggling this costs one full-red loop each way and keeps
            // its own session lineage while set.
            cmd.arg("-Zincremental-info");
            cmd.env("RUSTC_BOOTSTRAP", "1");
        }
    }
    if oso_split {
        cmd.arg("-Csplit-debuginfo=unpacked");
        cmd.arg(format!("-Clink-arg=-Wl,-oso_prefix,{}/", stage_root.display()));
    }
    cmd.arg(format!("-Cmetadata={}", ctx.idents[uidx]));
    cmd.arg(format!("-Cextra-filename=-{ef16}"));
    cmd.arg("--out-dir").arg(&outdir);
    cmd.arg("-L").arg(format!("dependency={}", ctx.pool_logical.display()));
    for (name, file, _) in &externs {
        cmd.arg("--extern").arg(format!("{name}={}", ctx.pool_logical.join(file).display()));
    }
    // A proc-macro target gets the compiler's own `proc_macro` crate in
    // every mode — including its --test harness, which compiles as a plain
    // test bin where rustc no longer injects it implicitly. Cargo passes
    // --extern proc_macro whenever the unit's target is a proc-macro.
    if crate_type == "proc-macro" || target.kind.iter().any(|k| k == "proc-macro") {
        cmd.arg("--extern").arg("proc_macro");
    }
    if crate_type == "proc-macro" && ctx.host.contains("apple") {
        // ld64 defaults the dylib install name to the (temporary) output
        // path; pin it to a deterministic value instead.
        cmd.arg(format!("-Clink-arg=-Wl,-install_name,/dc/lib{crate_name}-{ef16}.dylib"));
    }
    for f in &features {
        cmd.arg("--cfg").arg(format!("feature=\"{f}\""));
    }
    for c in &bs.cfgs {
        cmd.arg("--cfg").arg(c);
    }
    for l in &bs.link_libs {
        cmd.arg("-l").arg(l);
    }
    for s in &link_search {
        cmd.arg("-L").arg(s);
    }
    for a in &link_args {
        cmd.arg(format!("-Clink-arg={a}"));
    }
    if cap_lints {
        cmd.arg("--cap-lints").arg("allow");
    }
    cmd.arg("--remap-path-prefix").arg(format!("{}=/dc/sysroot", ctx.sysroot));
    // Workspace paths become relative: debuggers resolve them against
    // their own cwd, so lldb run from the workspace root needs no
    // source-map. Dependency sources need no remap at all — their real
    // cargo-home is the canonical store path. Packages rooted anywhere
    // else (path deps outside the workspace) keep a stable token so
    // their machine-local location never leaks into artifacts.
    cmd.arg("--remap-path-prefix").arg(format!("{}=.", ctx.workspace_root));
    if !pkg_root.starts_with(&ctx.workspace_root) && !pkg_root.starts_with(&ctx.cargo_home) {
        cmd.arg("--remap-path-prefix")
            .arg(format!("{}=/dc/pkg/{}-{}", pkg_root.display(), pkg.name, pkg.version));
    }
    // Config rustflags go last, as cargo appends them: later flags win, so
    // the config can override anything tool-chosen.
    for flag in unit_rustflags {
        cmd.arg(flag);
    }

    if ctx.verbose {
        eprintln!("corgi: exec {cmd:?}");
    }
    ctx.jobserver.configure(&mut cmd);
    // One token per running compiler (its implicit thread); rustc acquires
    // more from the shared pool for extra codegen threads and releases
    // them as codegen units finish.
    let job_token = ctx.jobserver.acquire().context("acquiring jobserver token")?;
    let t_rustc = Instant::now();
    let (success, stderr) = if self_pipelined {
        run_rustc_streaming(ctx, &mut cmd, uidx, &pkg.name, &key, fire_meta)?
    } else {
        let out = cmd.output().with_context(|| format!("spawning rustc for {}", pkg.name))?;
        (out.status.success(), String::from_utf8_lossy(&out.stderr).into_owned())
    };
    phases.rustc_ns = t_rustc.elapsed().as_nanos() as u64;
    drop(job_token); // compiler exited; hashing/ingestion is not codegen
    fs::remove_dir_all(&scratch).ok();
    if !success {
        fs::remove_dir_all(&stage_root).ok();
        bail!("rustc failed for {} v{} ({}):\n{}", pkg.name, pkg.version, crate_name, stderr);
    }
    if !stderr.trim().is_empty() {
        eprint!("{stderr}");
    }

    // Enforce input containment: rustc's dep-info lists every file it read
    // for this crate (mod files, include!/include_str!/include_bytes!).
    // All of them must lie inside the hashed package dir or a keyed
    // location (OUT_DIR in the store, sysroot) — otherwise the action key
    // is missing an input and we refuse to cache a lie.
    let dep_file = outdir.join(format!("{crate_name}-{ef16}.d"));
    if let Ok(d) = fs::read_to_string(&dep_file) {
        let mut allowed: Vec<PathBuf> = vec![
            ctx.store.root.clone(),
            ctx.store.logical_root().to_path_buf(),
            PathBuf::from(&ctx.sysroot),
        ];
        if clippy_action {
            // clippy-driver reports its config in dep-info; the content is
            // already keyed (clippy_id carries the clippy.toml hash).
            if let Some(conf) = &ctx.clippy_conf {
                allowed.push(conf.clone());
            }
        }
        for e in ctx.extra_inputs_for(pkg) {
            if let Ok(p) = pkg_root.join(e).canonicalize() {
                allowed.push(p); // declared -> hashed -> allowed
            }
        }
        let t_val = Instant::now();
        let workspace_relative_pkg = pkg_root.strip_prefix(&ctx.workspace_root).ok();
        validate_dep_info(&d, &pkg_root, workspace_relative_pkg, &allowed).with_context(|| {
            format!("hermeticity violation compiling {} v{}", pkg.name, pkg.version)
        })?;
        phases.validate_ns = t_val.elapsed().as_nanos() as u64;
        fs::remove_file(&dep_file).ok(); // references the tmp outdir; never cached
    }

    let mut outputs = Vec::new();
    let mut entries: Vec<PathBuf> = fs::read_dir(&outdir)?
        .map(|e| e.map(|e| e.path()))
        .collect::<std::io::Result<_>>()?;
    entries.sort();
    let t_ingest = Instant::now();
    for p in entries {
        let name = p.file_name().unwrap().to_string_lossy().into_owned();
        let exe = !name.contains('.')
            || name.ends_with(".dylib")
            || name.ends_with(".so")
            || name.ends_with(".dll");
        phases.ingest_bytes += fs::metadata(&p).map(|m| m.len()).unwrap_or(0);
        // Location-leak tripwire: artifacts must be location-free to be
        // shared across checkouts. Any channel that bakes the workspace
        // path into an output (env!, proc-macro env reads, cwd
        // resolution) is caught here, on the bytes, before the action is
        // recorded.
        let (hash, leaked) =
            ctx.store.insert_file_scan(&p, ctx.workspace_root.as_bytes())?;
        if leaked {
            bail!(
                "output {name} embeds the workspace path ({}); artifacts must be \
location-free — resolve paths at runtime instead of baking them in at build time",
                ctx.workspace_root
            );
        }
        outputs.push(OutputFile { name, hash, exe });
    }
    phases.ingest_ns = t_ingest.elapsed().as_nanos() as u64;
    fs::remove_dir_all(&stage_root).ok();
    // The pinned output dir has been read and removed; only now may
    // another action of this unit wipe and reuse it.
    incr_lock.take();

    let t_finish = Instant::now();
    let res = ActionResult { outputs, stderr, bs: None };
    let expected: Vec<String> = if self_checked {
        res.outputs.iter().map(|o| o.name.clone()).collect()
    } else {
        expected_outputs(ctx, &crate_name, &ef16, crate_type, unit.host)?
    };
    // Never record an action whose outputs are incomplete: a poisoned
    // record would replay the failure from cache on every future run.
    for e in &expected {
        if !res.outputs.iter().any(|o| &o.name == e) {
            bail!(
                "rustc-reported output {e} missing (got {:?})",
                res.outputs.iter().map(|o| &o.name).collect::<Vec<_>>()
            );
        }
    }
    ctx.store.save_action(&key, &serde_json::to_vec(&res)?)?;
    ctx.materialize(&key, &res)?;
    phases.finish_ns = t_finish.elapsed().as_nanos() as u64;
    finish_compile(&expected, key, false, res, phases)
}

fn run_build_script(ctx: &Ctx, uidx: usize, results: &[OnceLock<UnitResult>]) -> Result<UnitResult> {
    let unit = &ctx.units[uidx];
    let pkg = &ctx.meta.packages[unit.pkg];
    let pkg_root = pkg.root();

    let mut script: Option<OutputFile> = None;
    let mut script_key = String::new();
    let mut dep_env: Vec<(String, String)> = Vec::new();
    for d in &unit.deps {
        let r = results[d.unit].get().context("dep result missing")?;
        match ctx.units[d.unit].kind {
            Kind::Bsc => {
                script = r.main.clone();
                script_key = r.key.clone();
            }
            Kind::Bsr => {
                let dpkg = &ctx.meta.packages[ctx.units[d.unit].pkg];
                if let (Some(links), Some(b)) = (&dpkg.links, &r.res.bs) {
                    let l = links.to_uppercase().replace('-', "_");
                    for (k, v) in &b.metadata {
                        dep_env.push((
                            format!("DEP_{l}_{}", k.to_uppercase().replace('-', "_")),
                            v.clone(),
                        ));
                    }
                }
            }
            _ => {}
        }
    }
    let script = script.context("build script binary missing")?;

    let mut env = ctx.pkg_env(pkg);
    let plat_triple = if unit.host {
        ctx.host.clone()
    } else {
        ctx.target.clone().unwrap_or_else(|| ctx.host.clone())
    };
    env.push(("TARGET".into(), plat_triple));
    env.push(("HOST".into(), ctx.host.clone()));
    env.push(("PROFILE".into(), unit.profile.env_name().into()));
    env.push((
        "OPT_LEVEL".into(),
        if unit.profile.opt_level.is_empty() {
            "0".into()
        } else {
            unit.profile.opt_level.clone()
        },
    ));
    // Deliberately not the profile's value: C compiled with -g embeds its
    // machine-local build dir. C debug info needs its own treatment later.
    env.push(("DEBUG".into(), "false".into()));
    env.push(("NUM_JOBS".into(), "4".into()));
    env.push(("RUSTC".into(), ctx.rustc.clone()));
    env.push(("RUSTDOC".into(), "rustdoc".into()));
    env.push(("CARGO".into(), ctx.cargo.clone()));
    // Cargo hands build scripts the rustflags of the unit they configure,
    // joined with the 0x1f separator.
    env.push((
        "CARGO_ENCODED_RUSTFLAGS".into(),
        (if unit.host { &ctx.host_rustflags } else { &ctx.target_rustflags }).join("\x1f"),
    ));
    env.extend(ctx.config_env.iter().cloned());
    if let Some(links) = &pkg.links {
        env.push(("CARGO_MANIFEST_LINKS".into(), links.clone()));
    }
    // Scoped settings: only the tools and env probes naming this package
    // reach it, and only their identity hashes enter this action's key.
    let visible_tools: Vec<&ToolRt> = ctx
        .tools
        .iter()
        .filter(|t| t.packages.is_empty() || t.packages.iter().any(|p| p == &pkg.name))
        .collect();
    for t in &visible_tools {
        env.push((t.env.clone(), t.value.clone()));
    }
    for (name, value, pkgs, profiles) in &ctx.env_probes {
        if pkgs.iter().any(|p| p == &pkg.name)
            && (profiles.is_empty() || profiles.iter().any(|pr| pr == &unit.profile.name))
        {
            env.push((name.clone(), value.clone())); // keyed via the env vec
        }
    }
    let mut tool_ids: Vec<String> = visible_tools.iter().map(|t| t.id.clone()).collect();
    tool_ids.sort();
    let plat_cfg = if unit.host { &ctx.cfg_env } else { &ctx.cfg_env_target };
    for (k, v) in plat_cfg {
        env.push((k.clone(), v.clone()));
    }
    let mut features = unit.features.clone();
    features.sort();
    for f in &features {
        env.push((format!("CARGO_FEATURE_{}", f.to_uppercase().replace('-', "_")), "1".into()));
    }
    env.sort();
    dep_env.sort();

    let src_hash = ctx.pkg_src_hash(unit.pkg)?;
    let key_json = serde_json::to_string(&RunKey {
        kind: "run-build-script",
        tool: TOOL_VERSION,
        rustc: &ctx.rustc_version,
        host: &ctx.host,
        pkg: [&pkg.name, &pkg.version, pkg.source.as_deref().unwrap_or("local")],
        src_hash: &src_hash,
        script: [&script.name, &script.hash],
        env: &env,
        dep_env: &dep_env,
        toolchain: &ctx.toolchain,
        tools: &tool_ids,
    })?;
    let key = sha256_hex(key_json.as_bytes());

    if let Some(res) = ctx.try_cache_hit(&key)? {
        return Ok(UnitResult { key, cached: true, res, main: None, phases: Phases::default() });
    }

    // The script runs *in place* at outdirs/<key>/out, so every path a tool
    // embeds -- literally or derived (cc names objects by a hash of their
    // input path, which no byte-patch can rewrite) -- is the canonical
    // location on every machine. Atomicity comes from a sentinel written
    // last; mutual exclusion from flock, which the kernel releases on any
    // process death. The lock is per-action: it is only ever contended by a
    // concurrent build doing this exact work, and the loser wakes to a
    // finished sentinel.
    let final_parent = ctx.store.root.join("outdirs").join(&key);
    fs::create_dir_all(ctx.store.root.join("outdirs"))?;
    let lock_file = fs::File::create(ctx.store.root.join("outdirs").join(format!("{key}.lock")))?;
    lock_file.lock().with_context(|| format!("locking OUT_DIR for {}", pkg.name))?;
    // While we waited: a concurrent winner may have finished the work.
    if let Some(res) = ctx.try_cache_hit(&key)? {
        return Ok(UnitResult { key, cached: true, res, main: None, phases: Phases::default() });
    }
    if final_parent.exists() {
        // No sentinel (the cache probe above would have hit): crash leftover.
        fs::remove_dir_all(&final_parent).context("clearing partial OUT_DIR")?;
    }
    let stage_out = final_parent.join("out");
    fs::create_dir_all(&stage_out)?;
    let stage_logical = ctx.out_dir_logical(&key);
    let script_path = ctx.pool.join(Store::pool_file_name(&script.name, &script_key));
    let scratch = ctx.store.tmp_path("scratch");
    fs::create_dir_all(&scratch)?;
    let extra_in: Vec<PathBuf> = ctx
        .extra_inputs_for(pkg)
        .iter()
        .filter_map(|e| pkg_root.join(e).canonicalize().ok())
        .collect();
    let mut reads: Vec<&Path> = vec![&pkg_root];
    reads.extend(extra_in.iter().map(|p| p.as_path()));
    let writes: Vec<&Path> = vec![&final_parent, &scratch];
    let mut cmd = sandboxed_command(ctx, &script_path.to_string_lossy(), &reads, &writes);
    cmd.current_dir(&pkg_root);
    cmd.env_clear();
    cmd.env("TMPDIR", &scratch);
    if !ctx.sdkroot.is_empty() {
        cmd.env("SDKROOT", &ctx.sdkroot);
    }
    for (k, v) in &ctx.base_env {
        cmd.env(k, v);
    }
    if let Some(shims) = ensure_tool_shims(&ctx.store, &visible_tools)? {
        cmd.env("PATH", format!("{}:/usr/bin:/bin", shims.display()));
    }
    for (k, v) in &env {
        cmd.env(k, v);
    }
    for (k, v) in &dep_env {
        cmd.env(k, v);
    }
    cmd.env("OUT_DIR", &stage_logical);
    // Cargo-identical manifest env; unkeyed for the same reason as in
    // compiles. Generated code that embeds it is rejected at the
    // consuming compile's ingest; data files are covered by the OUT_DIR
    // scan before this action commits.
    cmd.env("CARGO_MANIFEST_DIR", &pkg_root);
    cmd.env("CARGO_MANIFEST_PATH", &pkg.manifest_path);
    ctx.jobserver.configure(&mut cmd);
    let _job_token = ctx.jobserver.acquire().context("acquiring jobserver token")?;
    if ctx.verbose {
        eprintln!("corgi: exec {cmd:?}");
    }
    let out = cmd.output().with_context(|| format!("running build script for {}", pkg.name))?;
    fs::remove_dir_all(&scratch).ok();
    let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
    let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
    if !out.status.success() {
        fs::remove_dir_all(&final_parent).ok();
        bail!(
            "build script failed for {} v{}:\n--- stdout\n{}--- stderr\n{}",
            pkg.name,
            pkg.version,
            stdout,
            stderr
        );
    }

    let mut warnings = Vec::new();
    let bs = parse_directives(&stdout, &mut warnings)?;
    for w in warnings {
        eprintln!("corgi: warning ({} build script): {w}", pkg.name);
    }

    scan_dir_for_workspace_path(&stage_out, &ctx.workspace_root)?;
    let res = ActionResult { outputs: vec![], stderr, bs: Some(bs) };
    // Commit order: sentinel (OUT_DIR complete), then the action record.
    // A crash between the two leaves a probe-miss either way; the next
    // builder re-acquires the lock and redoes the work.
    ctx.store.write_atomic(&final_parent.join(".ok"), b"ok\n")?;
    ctx.store.save_action(&key, &serde_json::to_vec(&res)?)?;
    Ok(UnitResult { key, cached: false, res, main: None, phases: Phases::default() })
}

/// Location-leak tripwire for build-script outputs: OUT_DIR is shared at
/// its canonical store path, so nothing under it may embed the checkout
/// location. Generated code is also covered at its consumer's ingest;
/// this catches data files a crate only reads at runtime.
fn scan_dir_for_workspace_path(dir: &Path, workspace_root: &str) -> Result<()> {
    for entry in fs::read_dir(dir)? {
        let path = entry?.path();
        if path.is_dir() {
            scan_dir_for_workspace_path(&path, workspace_root)?;
        } else if path.is_file() {
            let (_, leaked) = crate::store::sha256_file_scan(&path, workspace_root.as_bytes())?;
            if leaked {
                bail!(
                    "build script output {} embeds the workspace path ({workspace_root}); \
                     outputs must be location-free — resolve paths at runtime instead of \
                     baking them in at build time",
                    path.display()
                );
            }
        }
    }
    Ok(())
}

fn validate_dep_info(
    dep: &str,
    pkg_root: &Path,
    workspace_relative_pkg: Option<&Path>,
    allowed_abs: &[PathBuf],
) -> Result<()> {
    for line in dep.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let Some((_, rest)) = line.split_once(':') else { continue };
        for tok in rest.split_whitespace() {
            // NOTE(poc): no handling of backslash-escaped spaces in paths
            let p = Path::new(tok);
            if p.is_absolute() {
                if !(p.starts_with(pkg_root) || allowed_abs.iter().any(|a| p.starts_with(a))) {
                    bail!(
                        "undeclared input read during compilation: {tok}\n\
                         this file is outside the package and OUT_DIR, so it is not part of\n\
                         the action key; caching it would be unsound"
                    );
                }
            } else {
                // Relative paths resolve against the compile cwd — the
                // workspace root — and must stay inside this package.
                match workspace_relative_pkg {
                    Some(prefix) if p.starts_with(prefix) => {}
                    _ => bail!("undeclared input outside the package: {tok}"),
                }
            }
        }
    }
    Ok(())
}

fn parse_directives(stdout: &str, warnings: &mut Vec<String>) -> Result<BuildScriptOut> {
    let mut bs = BuildScriptOut { stdout: stdout.to_string(), ..Default::default() };
    for line in stdout.lines() {
        let line = line.trim();
        let rest = if let Some(r) = line.strip_prefix("cargo::") {
            r
        } else if let Some(r) = line.strip_prefix("cargo:") {
            r
        } else {
            continue;
        };
        let Some((k, v)) = rest.split_once('=') else { continue };
        match k {
            "rustc-cfg" => bs.cfgs.push(v.to_string()),
            "rustc-env" => {
                if let Some((ek, ev)) = v.split_once('=') {
                    bs.envs.push((ek.to_string(), ev.to_string()));
                }
            }
            "rustc-link-lib" => bs.link_libs.push(v.to_string()),
            "rustc-link-search" => bs.link_search.push(v.to_string()),
            "rustc-flags" => {
                let toks: Vec<&str> = v.split_whitespace().collect();
                let mut i = 0;
                while i < toks.len() {
                    let t = toks[i];
                    if (t == "-l" || t == "-L") && i + 1 < toks.len() {
                        i += 1;
                        if t == "-l" {
                            bs.link_libs.push(toks[i].to_string());
                        } else {
                            bs.link_search.push(toks[i].to_string());
                        }
                    } else if let Some(rest) = t.strip_prefix("-l") {
                        bs.link_libs.push(rest.to_string());
                    } else if let Some(rest) = t.strip_prefix("-L") {
                        bs.link_search.push(rest.to_string());
                    }
                    i += 1;
                }
            }
            "rustc-link-arg" | "rustc-link-arg-bins" => bs.link_args.push(v.to_string()),
            "warning" => warnings.push(v.to_string()),
            "error" => bail!("build script error: {v}"),
            "metadata" => {
                if let Some((mk, mv)) = v.split_once('=') {
                    bs.metadata.push((mk.to_string(), mv.to_string()));
                }
            }
            "rerun-if-changed" | "rerun-if-env-changed" | "rustc-check-cfg" | "rustc-cdylib-link-arg" => {}
            other => bs.metadata.push((other.to_string(), v.to_string())),
        }
    }
    Ok(bs)
}