local-ci 0.20.0

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

mod native_step;

use crate::artifact::{self};
use crate::artifact_io;
use crate::context::ExecContext;
use crate::dag::{self, ExecutionTask};
use crate::expr::{self, Ctx, Status};
use crate::frozen::FrozenPlan;
use crate::matrix;
use crate::os_legs;
use crate::plan::{self, Plan, Unit};
use crate::setup::{
    self, PreparedHow, PreparedReceipt, PreparedSetup, PreparedStep, SetupRecipe, TemplateContext,
};
use crate::step_executor::{ScriptPipe, StepExecutor, StepRequest};
use crate::task::{self, combine, outcome_of, JobOutcome, JobStatus, TaskInputs, TaskResult};
use crate::workflow::{Job, Service, Step, Workflow};
use anyhow::{anyhow, bail, Context, Result};
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "result", content = "reason", rename_all = "lowercase")]
pub enum Outcome {
    Pass,
    Fail,
    Skip(String),
    /// Could not be checked here (tool missing, docker down, unsupported construct, timeout).
    Error(String),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StepResult {
    pub label: String,
    #[serde(flatten)]
    pub outcome: Outcome,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exit: Option<i32>,
    pub secs: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub log: Option<PathBuf>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JobResult {
    pub workflow: String,
    pub job: String,
    pub display: String,
    #[serde(flatten)]
    pub outcome: Outcome,
    pub secs: f64,
    pub steps: Vec<StepResult>,
    /// The run was cancelled while the job ran (its `outcome` is an error) or
    /// before it started (a skip). `needs.<id>.result` is `cancelled` then.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub cancelled: bool,
    /// Where the time went. Absent for jobs that did not run and for reused results.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time: Option<JobTime>,
    /// What the job did with the build cache (see [`crate::build_cache`]).
    /// Absent when the cache was not used for it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build_cache: Option<crate::build_cache::JobCache>,
    /// Set when the job ran on the host although its `runs-on` names another
    /// OS, and no leg of the host's OS runs the same steps (see [`crate::os_legs`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub os_note: Option<String>,
}

/// What a job waited for, and how long it really ran, in seconds.
///
/// `secs` of the job counts from the start of its steps and so holds the wait
/// for task-traffic-controller (`wait_queue_secs`); the other waits come before it. The waits
/// of a whole unit (`wait_lock_secs` for the repository lock, `wait_parallel_secs`
/// for a `--parallel` place) are charged to its first job, so that the sum over
/// jobs is not counted twice.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct JobTime {
    /// The job's own running, setup of its services and environment included:
    /// `secs` without `wait_queue_secs`.
    pub work_secs: f64,
    /// For the per-repository lock.
    pub wait_lock_secs: f64,
    /// For one of the `--containers` slots, shared by all runs on the machine.
    pub wait_slot_secs: f64,
    /// For task-traffic-controller to let a step start, summed over the steps.
    pub wait_queue_secs: f64,
    /// For one of the `--parallel` places of this run.
    pub wait_parallel_secs: f64,
    /// When the run began to handle the job, before any wait for it (UNIX
    /// epoch milliseconds; 0 when unknown). For the jobs of one unit, the
    /// moment the unit began to wait.
    #[serde(default)]
    pub requested_at_ms: u64,
    /// When the job's own execution began, after the lock, slot and
    /// `--parallel` waits (UNIX epoch milliseconds; 0 when unknown).
    #[serde(default)]
    pub started_at_ms: u64,
    /// When the job ended (UNIX epoch milliseconds; 0 when unknown).
    /// `finished_at_ms - started_at_ms` is about `work_secs + wait_queue_secs`.
    #[serde(default)]
    pub finished_at_ms: u64,
}

/// The wall clock as UNIX epoch milliseconds, for [`JobTime`].
pub fn now_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
}

/// The waits of a unit before any of its jobs started.
#[derive(Debug, Clone, Copy, Default)]
struct UnitWait {
    lock: f64,
    parallel: f64,
    /// When the unit began to wait (epoch ms; 0: not recorded).
    requested_at_ms: u64,
}

impl UnitWait {
    fn total(self) -> f64 {
        self.lock + self.parallel
    }
}

/// Charge the waits of a unit to its first job that ran (else its first).
fn charge(jobs: &mut [JobResult], w: UnitWait) {
    if w.requested_at_ms > 0 {
        // every job that ran was requested when its unit began to wait
        for t in jobs.iter_mut().filter_map(|j| j.time.as_mut()) {
            t.requested_at_ms = match t.requested_at_ms {
                0 => w.requested_at_ms,
                r => r.min(w.requested_at_ms),
            };
        }
    }
    if w.total() <= 0.0 {
        return;
    }
    let at = jobs.iter().position(|j| j.time.is_some()).unwrap_or(0);
    if let Some(j) = jobs.get_mut(at) {
        let secs = j.secs;
        let t = j.time.get_or_insert_with(|| JobTime {
            work_secs: secs,
            ..JobTime::default()
        });
        t.wait_lock_secs += w.lock;
        t.wait_parallel_secs += w.parallel;
        if t.requested_at_ms == 0 {
            t.requested_at_ms = w.requested_at_ms;
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct UnitResult {
    /// The unit of the plan this is the result of (index into its `units`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unit: Option<usize>,
    pub workflow: String,
    pub jobs: Vec<JobResult>,
    pub waited_secs: f64,
    /// Time spent copying the worktree for this unit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub copy_secs: Option<f64>,
    /// Where the reused result comes from (`abc1234, 2h ago`), when the unit did not run.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cached: Option<String>,
    /// Each job of the unit as the jobs that need it saw it, in the order they
    /// ran. Empty for a reused result (which keeps no outputs).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub outcomes: Vec<JobOutcome>,
}

pub struct Opts {
    pub parallel: usize,
    pub traffic_controller: Option<PathBuf>,
    /// Runs every step in place of local-ci's own child process (and of
    /// `traffic_controller`); see [`crate::step_executor::StepExecutor`].
    pub executor: Option<Arc<dyn crate::step_executor::StepExecutor>>,
    /// Gives jobs that bind fixed ports a block of their own (`--no-portool` turns it off).
    pub portool: Option<PathBuf>,
    /// Exclusive jobs that may run at once, across all runs on the machine.
    pub containers: usize,
    pub job_timeout_min: f64,
    /// Leave the worktrees in place after the run (`--keep`).
    pub keep: bool,
    /// Where removed worktrees go before they are deleted in the background.
    pub trash: PathBuf,
    /// Run every leg of a matrix over `runs-on` labels, also the ones another
    /// OS than the host's would run with the same steps (`--all-os-legs`).
    pub all_os_legs: bool,
}

/// Where one attempt runs: the host paths the plan is materialized at. The
/// plan itself holds no path of the host.
#[derive(Clone, Debug)]
pub struct Workspace {
    /// The checkout of the planned commit the jobs run in.
    pub root: PathBuf,
    /// The repository that checkout belongs to; copies for parallel units are
    /// made from it.
    pub repo_root: PathBuf,
    /// Where logs and the run's artifacts go. It must be new and unique to
    /// this run: [`crate::execute_plan`] refuses one that already has
    /// artifacts, and two runs in one directory would share (and destroy) one
    /// artifact area. [`crate::claim_run_dir`] makes one.
    pub run_dir: PathBuf,
    /// The attempt's own tool directory (shims, scripts, installed tools).
    pub tools: PathBuf,
    /// Held while exclusive units run.
    pub lock_file: PathBuf,
}

pub struct Runner<'a> {
    selected: Option<(
        crate::driver::dispatch::Selection,
        crate::driver::PortableFacts,
    )>,
    pinned: Option<(
        &'a crate::source_execute::PinnedExecution<'a>,
        &'a crate::source_execute::PinnedWorkspace,
        &'a dyn crate::source_execute::PinnedWorkspaceProvider,
    )>,
    pub ctx: &'a ExecContext,
    pub fp: &'a FrozenPlan,
    /// The engine's view of the plan, worked out once from `fp`.
    pub plan: Plan,
    pub repo_root: PathBuf,
    pub wt: PathBuf,
    pub run_dir: PathBuf,
    pub tools: PathBuf,
    pub lock_file: PathBuf,
    pub slug: String,
    pub opts: Opts,
    /// The threads each job may use (see [`crate::cpu`]): its steps are told
    /// in `cpu::JOB_THREAD_ENV` and ask task-traffic-controller for that weight.
    /// `None` (the default): jobs are not limited.
    pub job_threads: Option<usize>,
    /// The build cache for `target/` of Rust jobs (see [`crate::build_cache`]).
    /// `None` (the default): jobs do not use it. `local-ci run` sets it.
    pub build_cache: Option<crate::build_cache::Settings>,
    pub base_path: String,
    /// The keys of the steps that count as setup, from the plan alone.
    hoisted: plan::Hoist,
    /// What each task was told is prepared, and the context its template keys
    /// are made under.
    receipts: Option<(HashMap<String, PreparedReceipt>, TemplateContext)>,
    seq: Arc<AtomicUsize>,
    /// Copies that took a port block of their own.
    synced: Mutex<HashSet<PathBuf>>,
    docker_ok: OnceLock<Result<(), String>>,
    /// Why the units of a workflow (by index in the plan) are not run: an
    /// artifact step of it that cannot be run.
    refused: HashMap<usize, String>,
}

/// What one job did with the build cache.
struct BuildCacheRun {
    key: String,
    /// what the key was made of, recorded in the entry the job saves
    inputs: crate::build_cache::KeyInputs,
    stat: crate::build_cache::JobCache,
    notes: Vec<String>,
    /// false when the job goes without the cache (only `notes` is left)
    active: bool,
}

impl BuildCacheRun {
    fn off(note: String) -> Self {
        BuildCacheRun {
            key: String::new(),
            inputs: Default::default(),
            stat: Default::default(),
            notes: vec![note],
            active: false,
        }
    }
}

/// What [`Runner::run_unit`] keeps of the shards of one split job until the job
/// has its outcome.
#[derive(Default)]
struct ShardHold {
    /// the job, as the plan names it
    job: String,
    /// what the shards that ran reported
    reports: Vec<crate::shard::ShardOutcome>,
    /// how the jobs of the shards ended (an error that kept a shard from
    /// running is a failed one)
    outcomes: Vec<JobOutcome>,
    /// the shards (task ids) done with: run, failed to run, or cancelled
    handled: BTreeSet<String>,
    /// the shards not to run
    cancel: BTreeSet<String>,
    /// a shard could not be run at all
    errored: bool,
    /// where the last result of the shards is in the unit's jobs
    last: Option<usize>,
    /// the job has its outcome
    done: bool,
}

/// The script of the step that runs the tests of the shard `ts`: its command,
/// built where the tests are (`root` is the working directory of the step).
pub(crate) fn shard_script(ts: &dag::TaskShard, root: &Path) -> Result<String, String> {
    use crate::shard::{adapters, Shard};
    let adapter = adapters::from_info(&ts.runner, &root.to_string_lossy())
        .ok_or_else(|| format!("no adapter for runner `{}`", ts.runner.runner))?;
    let inv = adapter.invoke(
        &Shard {
            index: ts.index,
            tests: ts.tests.clone(),
            load: 0,
        },
        ts.count,
        ts.mode,
    );
    adapters::script_of(&inv).ok_or_else(|| "a test name cannot be put in a command".to_string())
}

/// The descriptor a script holding the token is read from, and how a shell is
/// told to read it.
const PIPE_FD: i32 = 3;
const PIPE_SCRIPT: &str = "/dev/fd/3";

fn re(cell: &'static OnceLock<Regex>, pat: &str) -> &'static Regex {
    cell.get_or_init(|| Regex::new(pat).unwrap())
}

/// Replace `secret` in the file at `path` with `***`.
fn mask_in_file(path: &Path, secret: &str) {
    if secret.len() < 4 {
        return;
    }
    if let Ok(text) = fs::read_to_string(path) {
        if text.contains(secret) {
            let _ = fs::write(path, text.replace(secret, "***"));
        }
    }
}

fn slug_of(s: &str) -> String {
    let mut out: String = s
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() {
                c.to_ascii_lowercase()
            } else {
                '-'
            }
        })
        .collect();
    while out.contains("--") {
        out = out.replace("--", "-");
    }
    out.trim_matches('-').chars().take(40).collect()
}

pub fn strip_ansi(s: &str) -> String {
    static R: OnceLock<Regex> = OnceLock::new();
    re(&R, r"\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07]*\x07|\r")
        .replace_all(s, "")
        .into_owned()
}

/// The last `n` non-empty lines of a log, without colour codes.
pub fn tail(path: &Path, n: usize) -> Vec<String> {
    let mut f = match File::open(path) {
        Ok(f) => f,
        Err(_) => return vec![],
    };
    let len = f.metadata().map(|m| m.len()).unwrap_or(0);
    let start = len.saturating_sub(256 * 1024);
    let _ = f.seek(SeekFrom::Start(start));
    let mut buf = Vec::new();
    let _ = f.read_to_end(&mut buf);
    let text = strip_ansi(&String::from_utf8_lossy(&buf));
    let lines: Vec<String> = text
        .lines()
        .filter(|l| !l.trim().is_empty() && !is_controller_line(l))
        .map(String::from)
        .collect();
    lines[lines.len().saturating_sub(n)..].to_vec()
}

/// How a step's command ended. A signal is `Code(128 + signal)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Exit {
    Code(i32),
    Timeout,
    Cancelled,
}

struct Semaphore {
    free: Mutex<usize>,
    cv: Condvar,
}

impl Semaphore {
    fn acquire(&self) {
        let mut f = self.free.lock().unwrap();
        while *f == 0 {
            f = self.cv.wait(f).unwrap();
        }
        *f -= 1;
    }
    fn release(&self) {
        *self.free.lock().unwrap() += 1;
        self.cv.notify_one();
    }
}

/// Compose projects a script brings up: `-p name` / `--project-name name` on a
/// `docker compose` / `docker-compose` command line, or `COMPOSE_PROJECT_NAME=name`.
pub fn compose_projects(script: &str) -> Vec<String> {
    static FLAG: OnceLock<Regex> = OnceLock::new();
    static ENV: OnceLock<Regex> = OnceLock::new();
    let flag = re(
        &FLAG,
        r"(?:^|\s)(?:-p|--project-name)(?:\s+|=)[\x22']?([A-Za-z0-9][A-Za-z0-9_-]*)",
    );
    let env = re(
        &ENV,
        r"\bCOMPOSE_PROJECT_NAME=[\x22']?([A-Za-z0-9][A-Za-z0-9_-]*)",
    );
    let mut out: Vec<String> = env
        .captures_iter(&script.replace("\\\n", " "))
        .map(|c| c[1].to_string())
        .collect();
    for cmd in compose_commands(script) {
        out.extend(
            flag.captures_iter(compose_globals(&cmd))
                .map(|c| c[1].to_string()),
        );
    }
    let mut seen = HashSet::new();
    out.retain(|p| seen.insert(p.clone()));
    out
}

/// The longest name handed to task-traffic-controller's `top`.
const RUN_LABEL_MAX: usize = 60;

/// `workflow / job / step`, for task-traffic-controller's `top`. At most `RUN_LABEL_MAX`
/// characters: the step is cut first, then the whole name.
fn run_label(workflow: &str, job: &str, step: &str) -> String {
    let clip = |s: &str, max: usize| -> String {
        let one_line = s.split_whitespace().collect::<Vec<_>>().join(" ");
        if one_line.chars().count() <= max {
            return one_line;
        }
        let head: String = one_line.chars().take(max.saturating_sub(1)).collect();
        format!("{head}…")
    };
    let head = format!("{} / {} / ", clip(workflow, 100), clip(job, 100));
    let room = RUN_LABEL_MAX.saturating_sub(head.chars().count());
    // keep at least a few characters of the step when the front part is long
    let step = clip(step, room.max(8));
    clip(&format!("{head}{step}"), RUN_LABEL_MAX)
}

/// The prefix task-traffic-controller puts on its own output lines. The one
/// place that knows it.
const CONTROLLER_PREFIX: &str = "task-traffic-controller: ";

/// A line of task-traffic-controller's own output, not the command's.
fn is_controller_line(line: &str) -> bool {
    line.starts_with(CONTROLLER_PREFIX)
}

/// Whether `b`, a step's log read from the start of a line, holds output of the
/// command's own: a line that is not task-traffic-controller's. The line not
/// finished yet counts too, unless it is, or may still become, one of
/// task-traffic-controller's: it writes a line and its newline apart, so a
/// read may end between them. The caller reads that line again from its
/// start, so the next read never begins with the bare newline.
fn command_spoke(b: &[u8]) -> bool {
    let text = String::from_utf8_lossy(b);
    let mut lines = text.split('\n');
    let rest = lines.next_back().unwrap_or_default();
    lines.any(|l| !is_controller_line(l))
        || !rest.is_empty() && !is_controller_line(rest) && !CONTROLLER_PREFIX.starts_with(rest)
}

/// Its ledger lock timing out, so the command never ran.
fn is_ledger_timeout_line(line: &str) -> bool {
    line.strip_prefix(CONTROLLER_PREFIX)
        .is_some_and(|r| r.starts_with("ledger: timed out"))
}

/// The log written since `from` holds only task-traffic-controller's own lines, ending in its
/// ledger lock timing out: the command itself never ran.
fn ledger_timed_out(log: &Path, from: u64) -> bool {
    let Ok(mut f) = File::open(log) else {
        return false;
    };
    let mut b = Vec::new();
    if f.seek(SeekFrom::Start(from)).is_err() || f.read_to_end(&mut b).is_err() {
        return false;
    }
    let text = String::from_utf8_lossy(&b);
    let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
    lines.iter().all(|l| is_controller_line(l)) && lines.iter().any(|l| is_ledger_timeout_line(l))
}

/// Each `docker compose` command line of a script, cut at the next command.
fn compose_commands(script: &str) -> Vec<String> {
    let joined = script.replace("\\\n", " ");
    let mut out = Vec::new();
    for line in joined.lines() {
        for marker in ["docker compose", "docker-compose"] {
            for (at, _) in line.match_indices(marker) {
                let rest = &line[at + marker.len()..];
                out.push(
                    rest.split(['|', ';', '&'])
                        .next()
                        .unwrap_or(rest)
                        .to_string(),
                );
            }
        }
    }
    out
}

/// The Compose files the script's `docker compose` commands read: their `-f`
/// files, or the default names. None for a file named by a variable.
fn compose_files(script: &str) -> Vec<Option<String>> {
    static WORD: OnceLock<Regex> = OnceLock::new();
    let mut out = Vec::new();
    for cmd in compose_commands(script) {
        let words: Vec<&str> = re(&WORD, r"\S+")
            .find_iter(compose_globals(&cmd))
            .map(|m| m.as_str())
            .collect();
        let mut named = false;
        for (i, w) in words.iter().enumerate() {
            let file = match *w {
                "-f" | "--file" => words.get(i + 1).copied(),
                w => w.strip_prefix("--file="),
            };
            if let Some(f) = file {
                named = true;
                let f = f.trim_matches(['"', '\'']);
                out.push((!f.contains('$')).then(|| f.to_string()));
            }
        }
        if !named {
            for f in [
                "compose.yaml",
                "compose.yml",
                "docker-compose.yaml",
                "docker-compose.yml",
            ] {
                out.push(Some(f.to_string()));
            }
        }
    }
    out
}

/// A Compose file that pins a container name or a host port.
fn compose_fixed(text: &str) -> bool {
    static R: OnceLock<Regex> = OnceLock::new();
    re(
        &R,
        r#"(?m)^\s*container_name\s*:|^\s*-\s*["']?(\d{1,3}(\.\d{1,3}){3}:)?\d{2,5}:\d|^\s*published\s*:\s*["']?\d"#,
    )
    .is_match(text)
}

/// `docker run` with a fixed name or host port.
fn docker_run_fixed(script: &str) -> bool {
    static RUN: OnceLock<Regex> = OnceLock::new();
    static FIXED: OnceLock<Regex> = OnceLock::new();
    let fixed = re(
        &FIXED,
        r#"\s--name[=\s]|\s(-p|--publish)[=\s]+["']?(\d{1,3}(\.\d{1,3}){3}:)?\d{2,5}:"#,
    );
    re(&RUN, r"docker\s+(container\s+)?run\b[^|;&\n]*")
        .find_iter(&script.replace("\\\n", " "))
        .any(|m| fixed.is_match(m.as_str()))
}

/// The part of a `docker compose` command line before its subcommand (`up`,
/// `exec`, ...). Only there is `-p` the project: `exec db mkdir -p tmp` is not.
fn compose_globals(args: &str) -> &str {
    // options of `docker compose` itself that take a value
    const VALUED: [&str; 10] = [
        "-f",
        "--file",
        "-p",
        "--project-name",
        "--env-file",
        "--profile",
        "--project-directory",
        "--ansi",
        "--parallel",
        "--progress",
    ];
    static WORD: OnceLock<Regex> = OnceLock::new();
    let mut value_next = false;
    for m in re(&WORD, r"\S+").find_iter(args) {
        let t = m.as_str();
        if t == "\\" {
            continue;
        }
        if value_next {
            value_next = false;
        } else if t.starts_with('-') {
            value_next = VALUED.contains(&t);
        } else {
            return &args[..m.start()];
        }
    }
    args
}

/// Put in front of PATH for the run. Every job shares one checkout, and `npm ci`
/// deletes `node_modules` before installing, so a job installing a directory
/// (directly or from a script) would break another job running there. A
/// directory is installed once per run and lockfile; later installs are no-ops.
/// In a unit's copy `node_modules` holds links into setup's, which the other
/// units read: a command that writes into it first makes the copy's its own.
const NPM_SHIM: &str = r#"#!/bin/sh
# Written by local-ci for one run.
real="__REAL__"
own() {
  [ -f node_modules/.local-ci-shared ] || return 0
  t=$(cat node_modules/.local-ci-shared)
  rm -rf .node_modules.local-ci
  cp -cR "$t" .node_modules.local-ci 2>/dev/null || cp -a --reflink=auto "$t" .node_modules.local-ci || exit 1
  rm -rf node_modules && mv .node_modules.local-ci node_modules
}
sub="$1"
case "$sub" in
  ci|install|i) ;;
  rebuild|rb|uninstall|un|remove|r|update|up|link|ln|prune|dedupe|ddp) own; exec "$real" "$@" ;;
  *) exec "$real" "$@" ;;
esac
shift
for a in "$@"; do
  case "$a" in
    -*) ;;
    *) own; exec "$real" "$sub" "$@" ;;
  esac
done
dir=$(pwd -P)
ws=$(cd "${GITHUB_WORKSPACE:-/}" 2>/dev/null && pwd -P)
sum=$(cksum package-lock.json 2>/dev/null | cut -d' ' -f1)
# relative to the workspace, so a unit's copy of the worktree keeps setup's marks
key=$(printf '%s' "${dir#"$ws"}$LOCAL_CI_INSTALL_SCOPE" | cksum | cut -d' ' -f1)
marks="$LOCAL_CI_MARKS"
mkdir -p "$marks"
until mkdir "$marks/$key.lock" 2>/dev/null; do sleep 1; done
trap 'rmdir "$marks/$key.lock" 2>/dev/null' EXIT INT TERM
if [ -f "$marks/$key-$sum" ] && [ -d node_modules ]; then
  echo "local-ci: node_modules in $dir was installed earlier in this run; skipping npm $sub" >&2
  exit 0
fi
own
"$real" "$sub" "$@"
rc=$?
if [ "$rc" -eq 0 ]; then : > "$marks/$key-$sum"; fi
exit "$rc"
"#;

/// A step that may write into `node_modules`, run outside the npm shim.
fn writes_node_modules(script: &str) -> bool {
    static R: OnceLock<Regex> = OnceLock::new();
    R.get_or_init(|| {
        Regex::new(r"\b(npm (ci|install|i|rebuild|uninstall|update|link|prune|dedupe)|prisma generate|patch-package|yarn|pnpm)\b").unwrap()
    })
    .is_match(script)
}

/// GitHub's file commands: `name=value` lines and `name<<DELIM` blocks.
pub fn parse_file_command(text: &str) -> Vec<(String, String)> {
    let mut out = Vec::new();
    let mut lines = text.lines();
    while let Some(line) = lines.next() {
        if let Some((k, delim)) = line.split_once("<<") {
            if !k.contains('=') {
                let mut val = Vec::new();
                for l in lines.by_ref() {
                    if l == delim {
                        break;
                    }
                    val.push(l);
                }
                out.push((k.to_string(), val.join("\n")));
                continue;
            }
        }
        if let Some((k, v)) = line.split_once('=') {
            if !k.is_empty() {
                out.push((k.to_string(), v.to_string()));
            }
        }
    }
    out
}

struct PortMap {
    declared: Option<u16>,
    container: u16,
    actual: u16,
}

/// Point `localhost:<declared>` (and `*_PORT=<declared>`) at the port docker gave us.
fn rewrite_ports(text: &str, maps: &[PortMap]) -> String {
    let mut s = text.to_string();
    for m in maps {
        if let Some(d) = m.declared {
            let r = Regex::new(&format!(r"\b(localhost|127\.0\.0\.1|0\.0\.0\.0):{d}\b")).unwrap();
            s = r
                .replace_all(&s, format!("${{1}}:{}", m.actual).as_str())
                .into_owned();
            let a = Regex::new(&format!(
                r#"(-e\s+|--env[=\s]\s*)?\b([A-Za-z_][A-Za-z0-9_]*=["']?){d}\b"#
            ))
            .unwrap();
            s = a
                .replace_all(&s, |c: &regex::Captures| {
                    if c.get(1).is_none() && port_key(c[2].trim_end_matches(['=', '"', '\''])) {
                        format!("{}{}", &c[2], m.actual)
                    } else {
                        c[0].to_string()
                    }
                })
                .into_owned();
        }
    }
    s
}

/// `PORT`, `DB_PORT`, `PORT_E2E`, `PGPORT`; not `EXPORT` or `REPORT`.
fn port_key(k: &str) -> bool {
    static R: OnceLock<Regex> = OnceLock::new();
    re(&R, r"(?i)^(([a-z0-9_]*_)?|pg)port(_[a-z0-9_]*)?$").is_match(k)
}

fn port_literal(v: &str) -> Option<u16> {
    v.trim().parse::<u16>().ok().filter(|p| *p >= 1024)
}

/// Ports a script fixes for itself: `TEST_DB_PORT=15432 docker compose …`.
/// `docker run -e X_PORT=…` is the container's own port and stays.
fn assigned_ports(script: &str) -> Vec<u16> {
    static R: OnceLock<Regex> = OnceLock::new();
    re(
        &R,
        r#"(-e\s+|--env[=\s]\s*)?\b([A-Za-z_][A-Za-z0-9_]*)=["']?(\d{4,5})\b"#,
    )
    .captures_iter(script)
    .filter(|c| c.get(1).is_none() && port_key(&c[2]))
    .filter_map(|c| port_literal(&c[3]))
    .collect()
}

/// Give each fixed port a job sets itself a free one, the same in all its steps.
/// Free ports come from the ephemeral range, which portool's blocks stay below.
fn map_literals(ports: impl IntoIterator<Item = u16>, maps: &mut Vec<PortMap>) -> Result<()> {
    // held until all are picked, so the OS hands out a different one each time
    let mut held = Vec::new();
    for p in ports {
        if maps.iter().any(|m| m.declared == Some(p)) {
            continue;
        }
        let actual = loop {
            let l = std::net::TcpListener::bind(("127.0.0.1", 0)).context("no free port")?;
            let a = l.local_addr()?.port();
            held.push(l);
            if !maps.iter().any(|m| m.actual == a) {
                break a;
            }
        };
        maps.push(PortMap {
            declared: Some(p),
            container: p,
            actual,
        });
    }
    Ok(())
}

/// `-p name` / `COMPOSE_PROJECT_NAME=name` with `-<tag>` appended, so two runs
/// never share a project and our `down` never stops one started by hand.
fn rename_compose_projects(script: &str, tag: &str) -> String {
    static FLAG: OnceLock<Regex> = OnceLock::new();
    static ENV: OnceLock<Regex> = OnceLock::new();
    let suffix = format!("-{tag}");
    let rename = |c: &regex::Captures| {
        if c[2].ends_with(&suffix) {
            c[0].to_string()
        } else {
            format!("{}{}{suffix}", &c[1], &c[2])
        }
    };
    let s = re(
        &ENV,
        r#"(\bCOMPOSE_PROJECT_NAME=["']?)([A-Za-z0-9][A-Za-z0-9_-]*)"#,
    )
    .replace_all(script, rename)
    .into_owned();
    let flag = re(
        &FLAG,
        r#"((?:^|\s)(?:-p|--project-name)(?:\s+|=)["']?)([A-Za-z0-9][A-Za-z0-9_-]*)"#,
    );
    let mut out = String::new();
    let mut rest = s.as_str();
    loop {
        let at = ["docker compose", "docker-compose"]
            .iter()
            .filter_map(|m| rest.find(m).map(|i| i + m.len()))
            .min();
        let Some(at) = at else {
            out.push_str(rest);
            break;
        };
        out.push_str(&rest[..at]);
        let seg = &rest[at..];
        // the command ends at the next `|`, `;`, `&` or unescaped newline
        let b = seg.as_bytes();
        let end = (0..b.len())
            .find(|&i| {
                matches!(b[i], b'|' | b';' | b'&')
                    || (b[i] == b'\n' && (i == 0 || b[i - 1] != b'\\'))
            })
            .unwrap_or(b.len());
        let globals = compose_globals(&seg[..end]);
        out.push_str(&flag.replace_all(globals, rename));
        out.push_str(&seg[globals.len()..end]);
        rest = &seg[end..];
    }
    out
}

/// Whether the workflow reaches a service's host port `h` somewhere the
/// rewriting changes: `localhost:<h>`, `KEY_PORT=<h>`, a `*_PORT` env value,
/// or `${{ job.services... }}`. When it never names the port, the code uses it
/// as its default, and the service has to be on it as on GitHub.
fn rewritable_mention(w: &Workflow, job: &Job, h: u16) -> bool {
    let hs = h.to_string();
    let host = Regex::new(&format!(r"\b(localhost|127\.0\.0\.1|0\.0\.0\.0):{h}\b")).unwrap();
    let assign = Regex::new(&format!(r#"\b([A-Za-z_][A-Za-z0-9_]*)=["']?{h}\b"#)).unwrap();
    let in_text = |t: &str| {
        t.contains("job.services.")
            || host.is_match(t)
            || assign.captures_iter(t).any(|c| port_key(&c[1]))
    };
    let in_env = |pairs: &[(String, String)]| {
        pairs
            .iter()
            .any(|(k, v)| (port_key(k) && v.trim() == hs) || in_text(v))
    };
    in_env(&w.env)
        || in_env(&job.env)
        || job
            .steps
            .iter()
            .any(|s| in_env(&s.env) || s.run.as_deref().is_some_and(in_text))
}

fn rewrite_env_value(key: &str, val: &str, maps: &[PortMap]) -> String {
    for m in maps {
        if let Some(d) = m.declared {
            if port_key(key) && val.trim() == d.to_string() {
                return m.actual.to_string();
            }
        }
    }
    rewrite_ports(val, maps)
}

impl<'a> Runner<'a> {
    pub(crate) fn select_derived(
        mut self,
        selection: crate::driver::dispatch::Selection,
        facts: crate::driver::PortableFacts,
    ) -> Self {
        self.selected = Some((selection, facts));
        self
    }

    pub fn new(
        ctx: &'a ExecContext,
        fp: &'a FrozenPlan,
        ws: &Workspace,
        opts: Opts,
    ) -> Result<Self> {
        fp.require_git_source()?;
        Self::construct(ctx, fp, ws, opts, None)
    }

    pub(crate) fn new_pinned(
        ctx: &'a ExecContext,
        input: &'a crate::source_execute::PinnedExecution<'a>,
        ws: &'a crate::source_execute::PinnedWorkspace,
        opts: Opts,
        provider: &'a dyn crate::source_execute::PinnedWorkspaceProvider,
    ) -> Result<Self> {
        input.validate(input.plan)?;
        ws.validate(input)?;
        Self::construct(
            ctx,
            input.plan,
            ws.workspace(),
            opts,
            Some((input, ws, provider)),
        )
    }

    fn validate_source(&self) -> Result<()> {
        match self.pinned {
            Some((input, ws, _)) => {
                input.validate(self.fp)?;
                ws.validate(input)
            }
            None => self.fp.require_git_source(),
        }
    }

    fn source_identity(&self) -> String {
        self.fp
            .source
            .receipt_identity()
            .expect("validated execution source")
    }

    fn workspace_name(&self) -> String {
        if let Some((_, ws, _)) = self.pinned {
            return ws.namespace.clone();
        }
        self.fp
            .source
            .execution_commit
            .as_deref()
            .unwrap_or(&self.fp.digest)
            .chars()
            .take(7)
            .collect()
    }

    fn resource_name(&self) -> String {
        let n = self.seq.fetch_add(1, Ordering::SeqCst);
        match self.pinned {
            Some((_, ws, _)) => format!("local-ci-{}-{n}-{}", ws.namespace, std::process::id()),
            None => format!("local-ci-{}-{n}", std::process::id()),
        }
    }

    fn construct(
        ctx: &'a ExecContext,
        fp: &'a FrozenPlan,
        ws: &Workspace,
        opts: Opts,
        pinned: Option<(
            &'a crate::source_execute::PinnedExecution<'a>,
            &'a crate::source_execute::PinnedWorkspace,
            &'a dyn crate::source_execute::PinnedWorkspaceProvider,
        )>,
    ) -> Result<Self> {
        let base_path = ctx.var("PATH").unwrap_or_default().to_string();
        let plan = fp.to_plan();
        let refused = (0..plan.selected.len())
            .filter_map(|wf| Some((wf, artifact_io::workflow_refusal(&plan, wf)?)))
            .collect();
        Ok(Runner {
            selected: None,
            pinned,
            ctx,
            fp,
            refused,
            hoisted: plan::hoist(&plan),
            plan,
            receipts: None,
            repo_root: ws.repo_root.clone(),
            wt: ws.root.clone(),
            run_dir: ws.run_dir.clone(),
            tools: ws.tools.clone(),
            lock_file: ws.lock_file.clone(),
            slug: fp.repository.clone().unwrap_or_default(),
            opts,
            job_threads: None,
            build_cache: None,
            base_path,
            seq: pinned
                .map(|(_, ws, _)| ws.sequence.clone())
                .unwrap_or_else(|| {
                    // Ordinary runners name resources by process ID. Fresh
                    // attempts in that process must share the counter too.
                    static SEQUENCE: OnceLock<Arc<AtomicUsize>> = OnceLock::new();
                    SEQUENCE
                        .get_or_init(|| Arc::new(AtomicUsize::new(0)))
                        .clone()
                }),
            synced: Mutex::new(HashSet::new()),
            docker_ok: OnceLock::new(),
        })
    }

    fn github_ctx(&self, ws: &Path, w: &Workflow, event: &str, job: &str) -> Value {
        let base = match &self.fp.source.pinned {
            Some(p) => p.base_branch.clone().unwrap_or_default(),
            None => crate::git::branch_name(
                self.fp
                    .source
                    .base
                    .as_deref()
                    .expect("Git execution requires a base"),
            ),
        };
        let head = self.fp.branch.clone().unwrap_or_default();
        let pr = event == "pull_request";
        json!({
            "event_name": event,
            "event": if pr { json!({"pull_request": {"draft": false, "number": 0, "head": {"ref": head, "sha": self.fp.source.execution_commit}, "base": {"ref": base}}, "action": "synchronize"}) } else { json!({"ref": format!("refs/heads/{head}")}) },
            "sha": self.fp.source.execution_commit,
            "ref": if pr { "refs/pull/0/merge".to_string() } else { format!("refs/heads/{head}") },
            "ref_name": if pr { "0/merge".to_string() } else { head.clone() },
            "head_ref": if pr { head.clone() } else { String::new() },
            "base_ref": if pr { base } else { String::new() },
            "repository": self.slug,
            "repository_owner": self.slug.split('/').next().unwrap_or(""),
            "workflow": w.name,
            "job": job,
            "run_id": "0",
            "run_number": "0",
            "run_attempt": "1",
            "actor": "local-ci",
            "server_url": "https://github.com",
            "api_url": "https://api.github.com",
            "workspace": ws.to_string_lossy(),
        })
    }

    fn runner_ctx(&self) -> Value {
        let os = if cfg!(target_os = "macos") {
            "macOS"
        } else {
            "Linux"
        };
        let arch = if cfg!(target_arch = "aarch64") {
            "ARM64"
        } else {
            "X64"
        };
        json!({"os": os, "arch": arch, "temp": self.tools.join("tmp").to_string_lossy(), "tool_cache": self.tools.join("tool-cache").to_string_lossy(), "name": "local-ci"})
    }

    fn base_env(&self, gh: &Value, extra_path: &[String]) -> Vec<(String, String)> {
        let s = |k: &str| gh.get(k).map(expr::to_string).unwrap_or_default();
        let mut path: Vec<String> = vec![self.tools.join("bin").to_string_lossy().into_owned()];
        path.extend(extra_path.iter().rev().cloned());
        path.push(self.tools.join("venv/bin").to_string_lossy().into_owned());
        path.push(
            self.tools
                .join("npm-global/bin")
                .to_string_lossy()
                .into_owned(),
        );
        path.push(self.base_path.clone());
        let ws = s("workspace");
        vec![
            ("CI".into(), "true".into()),
            ("GITHUB_ACTIONS".into(), "true".into()),
            ("LOCAL_CI".into(), "1".into()),
            (
                "LOCAL_CI_MARKS".into(),
                self.marks(Path::new(&ws)).to_string_lossy().into_owned(),
            ),
            ("GITHUB_WORKSPACE".into(), ws),
            ("GITHUB_REF".into(), s("ref")),
            ("GITHUB_REF_NAME".into(), s("ref_name")),
            ("GITHUB_HEAD_REF".into(), s("head_ref")),
            ("GITHUB_BASE_REF".into(), s("base_ref")),
            ("GITHUB_EVENT_NAME".into(), s("event_name")),
            ("GITHUB_REPOSITORY".into(), self.slug.clone()),
            ("GITHUB_WORKFLOW".into(), s("workflow")),
            ("GITHUB_JOB".into(), s("job")),
            ("GITHUB_RUN_ID".into(), "0".into()),
            ("GITHUB_RUN_NUMBER".into(), "0".into()),
            (
                "RUNNER_OS".into(),
                self.runner_ctx()["os"].as_str().unwrap_or("").into(),
            ),
            (
                "RUNNER_TEMP".into(),
                self.tools.join("tmp").to_string_lossy().into_owned(),
            ),
            (
                "NPM_CONFIG_PREFIX".into(),
                self.tools.join("npm-global").to_string_lossy().into_owned(),
            ),
            ("PIP_REQUIRE_VIRTUALENV".into(), "true".into()),
            (
                "LOCAL_CI_TOOLS".into(),
                self.tools.to_string_lossy().into_owned(),
            ),
            // a `git push` from inside a script goes nowhere
            ("GIT_CONFIG_COUNT".into(), "3".into()),
            (
                "GIT_CONFIG_KEY_0".into(),
                "url./dev/null/local-ci-blocks-push/.pushInsteadOf".into(),
            ),
            ("GIT_CONFIG_VALUE_0".into(), "https://".into()),
            (
                "GIT_CONFIG_KEY_1".into(),
                "url./dev/null/local-ci-blocks-push/.pushInsteadOf".into(),
            ),
            ("GIT_CONFIG_VALUE_1".into(), "git@".into()),
            (
                "GIT_CONFIG_KEY_2".into(),
                "url./dev/null/local-ci-blocks-push/.pushInsteadOf".into(),
            ),
            ("GIT_CONFIG_VALUE_2".into(), "ssh://".into()),
            ("GIT_TERMINAL_PROMPT".into(), "0".into()),
            ("PATH".into(), path.join(":")),
        ]
        .into_iter()
        .chain(
            self.fp
                .source
                .execution_commit
                .clone()
                .map(|sha| ("GITHUB_SHA".into(), sha)),
        )
        .collect()
    }

    /// `text` with this machine's GitHub token, if it was asked for, replaced
    /// by `***`: for what is recorded.
    fn hide_token(&self, text: String) -> String {
        match self.ctx.github_token_if_fetched() {
            Some(t) if t.len() >= 4 => text.replace(t, "***"),
            _ => text,
        }
    }

    /// Run one shell step. Output goes to `log`; returns how it ended and how
    /// long task-traffic-controller kept it waiting for its turn. When task-traffic-controller's ledger lock
    /// times out the command never started, so it is tried again, a few times.
    /// A `piped` script holds the GitHub token: it is not written to a file but
    /// handed to the shell over a pipe (see `shell_once`).
    #[allow(clippy::too_many_arguments)]
    fn shell(
        &self,
        native_scope: &native_step::NativeScope,
        cwd: &Path,
        script: &str,
        shell: Option<&str>,
        env: &[(String, String)],
        timeout: Option<Duration>,
        log: &Path,
        key: Option<String>,
        label: &str,
        piped: bool,
        // the weight to ask task-traffic-controller for, when it is not to work it out
        weight: Option<usize>,
    ) -> Result<(Exit, Duration)> {
        let mut attempt = 0;
        let mut queued = Duration::ZERO;
        loop {
            let from = fs::metadata(log).map(|m| m.len()).unwrap_or(0);
            let (r, q) = self.shell_once(
                native_scope,
                cwd,
                script,
                shell,
                env,
                timeout,
                log,
                key.clone(),
                label,
                piped,
                weight,
            )?;
            queued += q;
            let failed = matches!(r, Exit::Code(c) if c != 0);
            if !(failed
                && attempt < 3
                && self.opts.executor.is_none()
                && self.opts.traffic_controller.is_some()
                && ledger_timed_out(log, from))
            {
                return Ok((r, queued));
            }
            attempt += 1;
            std::thread::sleep(Duration::from_secs(attempt));
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn shell_once(
        &self,
        native_scope: &native_step::NativeScope,
        cwd: &Path,
        script: &str,
        shell: Option<&str>,
        env: &[(String, String)],
        timeout: Option<Duration>,
        log: &Path,
        key: Option<String>,
        label: &str,
        piped: bool,
        // the weight to ask task-traffic-controller for, when it is not to work it out
        weight: Option<usize>,
    ) -> Result<(Exit, Duration)> {
        let n = self.seq.fetch_add(1, Ordering::SeqCst);
        let script_name = if self.pinned.is_some() {
            format!("step-{}-{n}.sh", self.workspace_name())
        } else {
            format!("step-{n}.sh")
        };
        let file = self.tools.join("scripts").join(script_name);
        // With task-traffic-controller the script touches this file as its first act, on the
        // line the script starts on, so task-traffic-controller still sees the same command and
        // the script keeps its line numbers. The file's time tells how long the
        // step waited for its turn, even if it prints nothing. Scripts of other
        // shells are not changed (a Python script may begin with
        // `from __future__`); their wait is read from the log.
        let turn = self.tools.join(format!("scripts/step-{n}.turn"));
        let queued =
            self.opts.executor.is_none() && self.opts.traffic_controller.is_some() && key.is_some();
        let marked = queued && matches!(shell.map(str::trim), None | Some("bash") | Some("sh"));
        let sh_family = matches!(shell.map(str::trim), None | Some("bash") | Some("sh"));
        // bash and sh read a script that is not a file one byte at a time, so
        // the lines they have not run yet are still in the pipe, and fd 3 is
        // inherited by everything the script starts. They read the script
        // through a descriptor of their own, so the first act of a script
        // that holds the token is to close fd 3, on the line it starts on.
        // (Python parses the whole script before it runs a line of it, so
        // nothing is left in the pipe by then.)
        let close = if piped && sh_family {
            format!("exec {PIPE_FD}<&-; ")
        } else {
            String::new()
        };
        let body = if marked {
            let mark = shlex::try_quote(&turn.to_string_lossy())
                .map(|q| format!(": > {q} 2>/dev/null || true; "))
                .unwrap_or_default();
            format!("{close}{mark}{script}")
        } else {
            format!("{close}{script}")
        };
        // A script that holds the token never reaches a file: the shell reads
        // it from file descriptor 3, the read end of a pipe (so the argument
        // list shows `/dev/fd/3` and nothing else), and task-traffic-controller passes the
        // descriptor on to its child.
        let f = if piped {
            PIPE_SCRIPT.to_string()
        } else {
            write_private(&file, &body)?;
            file.to_string_lossy().into_owned()
        };
        let mut argv: Vec<String> = match shell.map(str::trim) {
            None | Some("bash") => vec![
                "bash".into(),
                "--noprofile".into(),
                "--norc".into(),
                "-eo".into(),
                "pipefail".into(),
                f,
            ],
            Some("sh") => vec!["sh".into(), "-e".into(), f],
            Some("python") => vec!["python3".into(), f],
            // A shell of our own may open the script twice (`shellcheck {0} &&
            // bash {0}` reads nothing the second time and exits 0), and cannot
            // be told to close fd 3: a script that holds the token is not run.
            Some(custom) if custom.contains("{0}") && piped => bail!(
                "the step's script holds the GitHub token, which is handed over a pipe that `shell: {custom}` cannot read; use bash, sh or python for a step that uses github.token"
            ),
            Some(custom) if custom.contains("{0}") => shlex::split(&custom.replace("{0}", &f))
                .ok_or_else(|| anyhow!("bad shell `{custom}`"))?,
            // keep in step with `plan::shell_supported`
            Some(other) => bail!("unsupported shell `{other}`"),
        };
        if let (Some(c), Some(k), true) = (
            &self.opts.traffic_controller,
            key.clone(),
            self.opts.executor.is_none(),
        ) {
            let mut w = vec![c.to_string_lossy().into_owned(), "exec".into()];
            // The job's share: what its tools were told to use. Without it
            // the controller would charge what the step used before, when it
            // had every core.
            if let Some(n) = weight {
                w.extend(["--weight".into(), n.to_string()]);
            }
            w.extend(["--key".into(), k, "--".into()]);
            w.append(&mut argv);
            argv = w;
        }
        if !cwd.is_dir() {
            fs::write(
                log,
                format!(
                    "local-ci: working-directory {} does not exist\n",
                    cwd.display()
                ),
            )?;
            return Ok((Exit::Code(1), Duration::ZERO));
        }
        if let Some(ex) = &self.opts.executor {
            self.ctx.cancel.external_execution_started();
            return self.shell_via_executor(
                ex.as_ref(),
                n,
                &file,
                argv,
                cwd,
                env,
                timeout,
                log,
                key,
                &body,
                piped,
            );
        }
        let out = OpenOptions::new().create(true).append(true).open(log)?;
        let err = out.try_clone()?;
        let mut cmd = self.ctx.command(&argv[0]);
        if self.pinned.is_some() && self.fp.source.execution_commit.is_none() {
            cmd.env_remove("GITHUB_SHA");
        }
        cmd.args(&argv[1..])
            .current_dir(cwd)
            .stdin(Stdio::null())
            .stdout(out)
            .stderr(err)
            .process_group(0);
        for (k, v) in env {
            cmd.env(k, v);
        }
        // A name for task-traffic-controller's `top`. An environment variable, not
        // `--label`, so a controller that does not know the flag still runs the step.
        if self.opts.traffic_controller.is_some() && !label.is_empty() {
            cmd.env("TASK_TRAFFIC_CONTROLLER_LABEL", label);
        }
        let pipe = if piped {
            let (r, w) = script_pipe(&self.tools.join(format!("scripts/step-{n}.fifo")))?;
            let rfd = std::os::fd::AsRawFd::as_raw_fd(&r);
            // SAFETY: only dup2 and fcntl, which are async-signal-safe, run
            // between fork and exec. dup2 clears close-on-exec on the copy.
            unsafe {
                cmd.pre_exec(move || {
                    if rfd == PIPE_FD {
                        let fl = libc::fcntl(rfd, libc::F_GETFD);
                        if fl < 0 || libc::fcntl(rfd, libc::F_SETFD, fl & !libc::FD_CLOEXEC) < 0 {
                            return Err(std::io::Error::last_os_error());
                        }
                    } else if libc::dup2(rfd, PIPE_FD) < 0 {
                        return Err(std::io::Error::last_os_error());
                    }
                    Ok(())
                });
            }
            Some((r, w))
        } else {
            None
        };
        let child = cmd
            .spawn()
            .with_context(|| format!("cannot start {}", argv[0]))?;
        let wrapped = self.opts.traffic_controller.is_some() && key.is_some();
        let mut child = native_step::NativeStep::new(child, self.ctx.cancel.clone(), wrapped);
        let writer_stop = child.writer_stop();
        if let Some((r, w)) = pipe {
            // the child has its own copy
            drop(r);
            // A thread writes, so that a script larger than the pipe does not
            // block here. It ends when the shell has read it all, when every
            // reader is gone, or when the step is over (`writer_stop`), even
            // if something that outlived the step still holds the read end.
            let body = body.clone();
            let stop = writer_stop.clone();
            child.set_writer(std::thread::spawn(move || {
                write_until_stopped(w, body.as_bytes(), &stop)
            }));
        }
        let spawned = (Instant::now(), std::time::SystemTime::now());
        // With task-traffic-controller the clock starts when the command gets its turn, not while it waits.
        let mut started: Option<Instant> = if self.opts.traffic_controller.is_some() {
            None
        } else {
            Some(Instant::now())
        };
        let mut seen = 0u64;
        let mut term_at: Option<Instant> = None;
        let mut timed_out = false;
        let status = loop {
            if let Some(st) = child.observe()? {
                break st;
            }
            if started.is_none() && marked && turn.exists() {
                started = Some(Instant::now());
            }
            if started.is_none() {
                if let Ok(mut lf) = File::open(log) {
                    let len = lf.metadata().map(|m| m.len()).unwrap_or(0);
                    if len > seen {
                        let _ = lf.seek(SeekFrom::Start(seen));
                        let mut b = Vec::new();
                        let _ = lf.read_to_end(&mut b);
                        if command_spoke(&b) {
                            started = Some(Instant::now());
                        }
                        // a line not finished yet is read again with its end
                        seen += b
                            .iter()
                            .rposition(|&c| c == b'\n')
                            .map_or(0, |i| i as u64 + 1);
                    }
                }
            }
            let over = matches!((timeout, started), (Some(t), Some(s)) if s.elapsed() > t);
            if (over || self.ctx.cancel.is_cancelled()) && term_at.is_none() {
                timed_out = over;
                child.signal(libc::SIGTERM);
                term_at = Some(Instant::now());
            }
            if term_at.is_some_and(|t| t.elapsed() > Duration::from_secs(10)) {
                child.signal(libc::SIGKILL);
            }
            std::thread::sleep(Duration::from_millis(200));
        };
        child.finish(native_scope);
        if !piped {
            let _ = fs::remove_file(&file);
        }
        // Waiting for its turn: until the script touched `turn`, or the first
        // line of output that is not task-traffic-controller's own, or, when neither came
        // (task-traffic-controller gave up, the step was stopped, a silent step of another
        // shell), until it was over.
        let waited = if marked {
            let got_turn = fs::metadata(&turn).and_then(|m| m.modified()).ok();
            let _ = fs::remove_file(&turn);
            match got_turn {
                // a time before the spawn is the file system's rounding
                Some(t) => t.duration_since(spawned.1).unwrap_or(Duration::ZERO),
                None => spawned.0.elapsed(),
            }
        } else if queued {
            started.map_or_else(
                || spawned.0.elapsed(),
                |s| s.saturating_duration_since(spawned.0),
            )
        } else {
            Duration::ZERO
        };
        if timed_out {
            return Ok((Exit::Timeout, waited));
        }
        if self.ctx.cancel.is_cancelled() {
            return Ok((Exit::Cancelled, waited));
        }
        Ok((
            Exit::Code(status.code().unwrap_or(
                128 + std::os::unix::process::ExitStatusExt::signal(&status).unwrap_or(0),
            )),
            waited,
        ))
    }

    /// The step through `ex` (see [`StepExecutor`]) instead of a child process
    /// of ours: the script file or pipe is made here, the command is not.
    #[allow(clippy::too_many_arguments)]
    fn shell_via_executor(
        &self,
        ex: &dyn StepExecutor,
        n: usize,
        file: &Path,
        argv: Vec<String>,
        cwd: &Path,
        env: &[(String, String)],
        timeout: Option<Duration>,
        log: &Path,
        key: Option<String>,
        body: &str,
        piped: bool,
    ) -> Result<(Exit, Duration)> {
        let mut vars = self.ctx.env().clone();
        if self.pinned.is_some() && self.fp.source.execution_commit.is_none() {
            vars.remove("GITHUB_SHA");
        }
        vars.extend(env.iter().cloned());
        let (writer_stop, mut writer, mut script_fd, mut read_end) =
            (Arc::new(AtomicBool::new(false)), None, None, None);
        if piped {
            let (r, w) = script_pipe(&self.tools.join(format!("scripts/step-{n}.fifo")))?;
            script_fd = Some(ScriptPipe {
                read_fd: std::os::fd::AsRawFd::as_raw_fd(&r),
                child_fd: PIPE_FD,
            });
            read_end = Some(r);
            // The thread owns the write end, so the command sees the end of the
            // script once it is written (as in the default path).
            let (body, stop) = (body.to_string(), writer_stop.clone());
            writer = Some(std::thread::spawn(move || {
                write_until_stopped(w, body.as_bytes(), &stop)
            }));
        }
        let req = StepRequest {
            key,
            argv,
            cwd: cwd.to_path_buf(),
            env: vars.into_iter().collect(),
            log: log.to_path_buf(),
            timeout,
            script_pipe: script_fd,
            cancel: self.ctx.cancel.clone(),
        };
        let res = ex.run(&req);
        writer_stop.store(true, Ordering::SeqCst);
        if let Some(h) = writer {
            let _ = h.join();
        }
        drop(read_end);
        if !piped {
            let _ = fs::remove_file(file);
        }
        let done = res?;
        let waited = Duration::try_from_secs_f64(done.queue_wait_secs.unwrap_or(0.0).max(0.0))
            .unwrap_or(Duration::ZERO);
        let exit = match done.exit {
            Exit::Code(_) if self.ctx.cancel.is_cancelled() => Exit::Cancelled,
            e => e,
        };
        Ok((exit, waited))
    }

    fn log_path(&self, wf: &str, job: &str, n: usize, label: &str) -> PathBuf {
        let dir = self.run_dir.join(format!(
            "{}-{}",
            slug_of(
                crate::report::short(&self.fp.config.default_workflows_dir, wf)
                    .trim_end_matches(".yml")
                    .trim_end_matches(".yaml")
            ),
            slug_of(job)
        ));
        let _ = fs::create_dir_all(&dir);
        dir.join(format!("{:02}-{}.log", n, slug_of(label)))
    }

    /// Create the Python venv that `pip install` steps install into, if any step needs one.
    pub fn prepare_tools(&self) -> Result<()> {
        self.validate_source()?;
        for d in [
            "scripts",
            "tmp",
            "npm-global/bin",
            "files",
            "bin",
            "installed",
        ] {
            fs::create_dir_all(self.tools.join(d))?;
        }
        if let Some(npm) = self
            .base_path
            .split(':')
            .map(|d| Path::new(d).join("npm"))
            .find(|p| p.is_file())
        {
            let shim = self.tools.join("bin/npm");
            fs::write(&shim, NPM_SHIM.replace("__REAL__", &npm.to_string_lossy()))?;
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&shim, fs::Permissions::from_mode(0o755))?;
        }
        let wants_pip = self.plan.selected.iter().any(|s| {
            s.wf.jobs.iter().any(|j| {
                j.steps.iter().any(|st| {
                    st.run
                        .as_deref()
                        .is_some_and(|r| r.contains("pip install") || r.contains("pip3 install"))
                })
            })
        });
        if wants_pip {
            let ok = self
                .ctx
                .command("python3")
                .arg("-m")
                .arg("venv")
                .arg(self.tools.join("venv"))
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status()
                .map(|s| s.success())
                .unwrap_or(false);
            if !ok {
                eprintln!(
                    "local-ci: could not create a Python venv; `pip install` steps will be refused"
                );
            }
        }
        Ok(())
    }

    /// What each task of the plan was told is prepared, by task id. Set before
    /// [`Runner::run_units`]; a task without an entry prepares everything itself.
    /// `tctx` is the context the receipts' template keys were made under.
    pub fn set_receipts(
        &mut self,
        receipts: HashMap<String, PreparedReceipt>,
        tctx: TemplateContext,
    ) {
        self.receipts = Some((receipts, tctx));
    }

    /// Do the steps of `recipe` in the workspace, in order, and stop at the first
    /// that does not pass. `key` is the digest of the template key the receipt
    /// is for.
    /// The recipe of each task of the plan, in the plan's order.
    pub fn task_recipes(&self) -> Result<Vec<(String, SetupRecipe)>> {
        self.fp
            .tasks
            .iter()
            .map(|t| {
                Ok((
                    t.id.clone(),
                    setup::derive_in(&self.plan, &self.hoisted, t)?,
                ))
            })
            .collect()
    }

    pub fn run_recipe(&self, recipe: &SetupRecipe, key: &str) -> Result<PreparedSetup> {
        let native_scope = native_step::NativeScope::default();
        self.validate_source()?;
        if recipe.steps.is_empty() {
            return Ok(PreparedSetup {
                receipt: PreparedReceipt::empty(key, &self.source_identity()),
                steps: vec![],
            });
        }
        let workspace = match setup::ensure_workspace_id(&self.wt) {
            Ok(id) => id,
            Err(e) => {
                return Ok(PreparedSetup {
                    receipt: PreparedReceipt::empty(key, &self.source_identity()),
                    steps: vec![StepResult {
                        label: "setup".into(),
                        outcome: Outcome::Error(format!("cannot record the workspace id: {e:#}")),
                        exit: None,
                        secs: 0.0,
                        log: None,
                        note: None,
                    }],
                });
            }
        };
        let covered = setup::covered_by(recipe);
        let dirs: BTreeSet<String> = recipe.steps.iter().map(|s| s.dir.clone()).collect();
        let before = setup::top_level_entries(&self.wt, &dirs);
        let mut out = Vec::new();
        let mut prepared: Vec<PreparedStep> = Vec::new();
        let mut notes: Vec<setup::ReceiptNote> = Vec::new();
        for (i, s) in recipe.steps.iter().enumerate() {
            if let Some(by) = covered.get(&s.id) {
                if prepared.iter().any(|p| &p.id == by) {
                    prepared.push(PreparedStep {
                        id: s.id.clone(),
                        how: PreparedHow::SameAs { step: by.clone() },
                    });
                    continue;
                }
            }
            let label = format!(
                "{}$ {}",
                if s.dir.is_empty() { "." } else { &s.dir },
                s.label
            );
            let found = self
                .plan
                .selected
                .iter()
                .position(|x| x.wf.file == s.workflow)
                .filter(|wi| {
                    self.plan.selected[*wi]
                        .wf
                        .jobs
                        .iter()
                        .any(|j| j.id == s.job)
                });
            let Some(wi) = found else {
                out.push(StepResult {
                    label,
                    outcome: Outcome::Error(format!(
                        "the plan has no job {} in {}",
                        s.job, s.workflow
                    )),
                    exit: None,
                    secs: 0.0,
                    log: None,
                    note: None,
                });
                break;
            };
            let sel = &self.plan.selected[wi];
            let gh = self.github_ctx(&self.wt, &sel.wf, &sel.event, &s.job);
            let mut env = self.base_env(&gh, &[]);
            env.extend(s.env.iter().cloned());
            env.extend(s.ignored_env.iter().cloned());
            let log = self.log_path("setup", "", i + 1, &format!("{}-{}", s.dir, s.label));
            let t0 = Instant::now();
            let cwd = self.wt.join(&s.dir);
            let res = self
                .shell(
                    &native_scope,
                    &cwd,
                    &s.run,
                    s.shell.as_deref(),
                    &env,
                    Some(Duration::from_secs(1800)),
                    &log,
                    Some(format!("local-ci setup {label}")),
                    &run_label(&sel.wf.name, &s.job, &s.label),
                    false,
                    // setup runs before the jobs, alone
                    None,
                )
                .map(|(exit, _)| exit);
            let (outcome, exit) = match res {
                Ok(Exit::Code(0)) => (Outcome::Pass, Some(0)),
                Ok(Exit::Code(c)) => (Outcome::Fail, Some(c)),
                Ok(Exit::Timeout) => (Outcome::Error("timed out".into()), None),
                Ok(Exit::Cancelled) => (Outcome::Error("cancelled".into()), None),
                Err(e) => (Outcome::Error(format!("{e:#}")), None),
            };
            let stop = outcome != Outcome::Pass;
            // an install shared by jobs whose `ignore-env` values differ ran
            // with one set of them: say whose
            let note = setup::ignored_env_note(s);
            if !stop {
                prepared.push(PreparedStep {
                    id: s.id.clone(),
                    how: PreparedHow::Ran,
                });
                if let Some(text) = &note {
                    notes.push(setup::ReceiptNote {
                        step: s.id.clone(),
                        text: text.clone(),
                    });
                }
            }
            out.push(StepResult {
                label,
                outcome,
                exit,
                secs: t0.elapsed().as_secs_f64(),
                log: Some(log),
                note,
            });
            if stop {
                break;
            }
        }
        // Stop script producers before observing the prepared artifact tree.
        drop(native_scope);
        let artifacts = if out.iter().all(|r| r.outcome == Outcome::Pass) {
            setup::artifact_digests(
                &self.wt,
                &before,
                &setup::top_level_entries(&self.wt, &dirs),
            )
        } else {
            vec![]
        };
        Ok(PreparedSetup {
            receipt: PreparedReceipt {
                schema_version: crate::wire::wire_version(),
                template_key: key.into(),
                source: self.source_identity(),
                workspace,
                steps: prepared,
                artifacts,
                notes,
            },
            steps: out,
        })
    }

    pub fn run_units(&self) -> Result<Vec<UnitResult>> {
        self.validate_source()?;
        self.fp.require_git_source()?;
        let sem = Semaphore {
            free: Mutex::new(self.opts.parallel.max(1)),
            cv: Condvar::new(),
        };
        let results: Mutex<Vec<(usize, UnitResult)>> = Mutex::new(Vec::new());
        let isolate = self.plan.units.len() > 1;
        std::thread::scope(|scope| {
            for (i, u) in self.plan.units.iter().enumerate() {
                let sem = &sem;
                let results = &results;
                scope.spawn(move || {
                    // an artifact step of the workflow that cannot be run
                    // fails its units here, and only them
                    if let Some(why) = self.refused.get(&u.wf) {
                        results
                            .lock()
                            .unwrap()
                            .push((i, self.refused_unit(i, u, why)));
                        return;
                    }
                    let t0 = Instant::now();
                    let requested_at_ms = now_ms();
                    let lock = if self.unit_locked(u) {
                        self.lock().ok()
                    } else {
                        None
                    };
                    let locked_at = t0.elapsed().as_secs_f64();
                    sem.acquire();
                    let waited = UnitWait {
                        lock: locked_at,
                        parallel: t0.elapsed().as_secs_f64() - locked_at,
                        requested_at_ms,
                    };
                    let r = if isolate && !self.ctx.cancel.is_cancelled() {
                        self.run_unit_in_copy(i, u, waited)
                    } else {
                        self.run_unit(i, u, waited, &self.wt)
                    };
                    sem.release();
                    drop(lock);
                    results.lock().unwrap().push((i, r));
                });
            }
        });
        let mut r = results.into_inner().unwrap();
        r.sort_by_key(|(i, _)| *i);
        Ok(r.into_iter().map(|(_, u)| u).collect())
    }

    /// The entries of a job that is not run, each an error that says why: one
    /// per matrix variant (`only`: that variant alone) when the matrix is
    /// written out, so the result has what the plan expects of the job.
    fn refused_entries(
        &self,
        wf: usize,
        id: &str,
        why: &str,
        only: Option<usize>,
    ) -> Vec<JobResult> {
        let w = &self.plan.selected[wf].wf;
        let base = self.plan.job(wf, id).name.clone().unwrap_or(id.to_string());
        let displays: Vec<String> = match dag::matrix_plan(self.fp.job(wf, id)) {
            dag::MatrixPlan::Static(v) => v
                .iter()
                .enumerate()
                .filter(|(i, _)| only.is_none_or(|o| o == *i))
                .map(|(_, c)| format!("{base} ({})", matrix::describe(c)))
                .collect(),
            _ => vec![base],
        };
        displays
            .into_iter()
            .map(|display| JobResult {
                workflow: w.file.clone(),
                job: id.to_string(),
                display,
                outcome: Outcome::Error(why.to_string()),
                secs: 0.0,
                steps: vec![],
                cancelled: false,
                time: None,
                build_cache: None,
                os_note: None,
            })
            .collect()
    }

    /// The result of a unit that is not run: each of its jobs is an error that
    /// says why.
    fn refused_unit(&self, ui: usize, u: &Unit, why: &str) -> UnitResult {
        let w = &self.plan.selected[u.wf].wf;
        UnitResult {
            unit: Some(ui),
            workflow: w.file.clone(),
            jobs: u
                .jobs
                .iter()
                .flat_map(|id| self.refused_entries(u.wf, id, why, None))
                .collect(),
            waited_secs: 0.0,
            copy_secs: None,
            cached: None,
            outcomes: vec![],
        }
    }

    /// The result of `task` when its workflow has an artifact step that cannot
    /// be run, `None` when it has none: nothing is started, and each job is an
    /// error that says why.
    pub(crate) fn refused_task(&self, task: &ExecutionTask) -> Option<TaskResult> {
        let wf = self
            .plan
            .selected
            .iter()
            .position(|s| s.wf.file == task.workflow)?;
        let why = self.refused.get(&wf)?;
        let only = task.variant.as_ref().map(|v| v.index);
        Some(TaskResult {
            schema_version: crate::wire::wire_version(),
            task: task.id.clone(),
            jobs: task
                .jobs
                .iter()
                .flat_map(|id| self.refused_entries(wf, id, why, only))
                .collect(),
            outcomes: task
                .jobs
                .iter()
                .map(|id| JobOutcome {
                    job: id.clone(),
                    variant: only,
                    status: JobStatus::Failure,
                    outputs: Default::default(),
                    skipped: Some(why.clone()),
                    ancestor_failed: false,
                })
                .collect(),
            receipt_ignored: None,
            artifacts: vec![],
            shard: None,
        })
    }

    pub(crate) fn lock(&self) -> Result<File> {
        use fs2::FileExt;
        let f = OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(&self.lock_file)?;
        f.lock_exclusive()?;
        Ok(f)
    }

    /// Exclusive jobs can overlap: their fixed ports and Compose projects are
    /// rewritten (see `run_combo`), and portool gives the ports their scripts
    /// pick themselves. Without portool those may still collide, so they keep
    /// the per-repository lock.
    fn isolated(&self) -> bool {
        self.opts.portool.is_some() && self.wt.join(".portool.toml").is_file()
    }

    /// Whether the unit holds the per-repository lock while it runs. Jobs with
    /// `services:` always do: they get no portool ports (see `run_combo`), so a
    /// port their code picks for itself, a test server's, is not their own.
    fn unit_locked(&self, u: &Unit) -> bool {
        u.exclusive
            && (!self.isolated()
                || u.jobs
                    .iter()
                    .any(|id| !self.plan.job(u.wf, id).services.is_empty()))
    }

    /// One of the `--containers` slots, shared by every `local-ci` run on the
    /// machine: each exclusive job holds one while it runs, so databases started
    /// early do not pile up while their tests wait for CPU. None when cancelled.
    fn container_slot(&self) -> Result<Option<File>> {
        use fs2::FileExt;
        let dir = self.lock_file.parent().context("no lock directory")?;
        fs::create_dir_all(dir)?;
        loop {
            for i in 0..self.opts.containers.max(1) {
                let f = OpenOptions::new()
                    .create(true)
                    .truncate(false)
                    .write(true)
                    .open(dir.join(format!("containers-{i}.lock")))?;
                if f.try_lock_exclusive().is_ok() {
                    return Ok(Some(f));
                }
            }
            if self.ctx.cancel.is_cancelled() {
                return Ok(None);
            }
            std::thread::sleep(Duration::from_millis(500));
        }
    }

    /// Whether the job binds something fixed that rewriting does not reach: a
    /// Compose file with `container_name:` or a literal host port, or
    /// `docker run --name` / `-p <host port>:`. A Compose file named by a
    /// variable cannot be read here and counts as fixed.
    fn fixed_resources(&self, ws: &Path, w: &Workflow, job: &Job, cm: &Map<String, Value>) -> bool {
        let ctx = Ctx::new(cm, Status::Success);
        job.steps.iter().any(|s| {
            let Some(run) = &s.run else { return false };
            let script = expr::interpolate(run, &ctx).unwrap_or_else(|_| run.clone());
            let dir = ws.join(plan::step_dir(w, job, s));
            docker_run_fixed(&script)
                || compose_files(&script).iter().any(|f| match f {
                    Some(f) => fs::read_to_string(dir.join(f)).is_ok_and(|t| compose_fixed(&t)),
                    None => true,
                })
        })
    }

    /// Where the npm shim records the installs done in the workspace `ws`.
    fn marks(&self, ws: &Path) -> PathBuf {
        self.tools
            .join("installed")
            .join(ws.file_name().unwrap_or_default())
    }

    /// A copy of `from` at `to`, with the installs the npm shim recorded for it.
    fn copy_of(&self, from: &Path, to: &Path) -> Result<()> {
        self.validate_source()?;
        if let Some((_, _, provider)) = self.pinned {
            provider.fork(from, to)?;
        } else {
            crate::git::clone_worktree(
                self.ctx,
                &self.repo_root,
                from,
                to,
                &self.source_identity(),
                self.fp.config.link_node_modules,
            )?;
        }
        let marks = self.marks(to);
        fs::create_dir_all(&marks)?;
        for e in fs::read_dir(self.marks(from))
            .into_iter()
            .flatten()
            .flatten()
        {
            if e.file_type().is_ok_and(|t| t.is_file()) {
                fs::copy(e.path(), marks.join(e.file_name()))?;
            }
        }
        Ok(())
    }

    fn remove_copy(&self, ws: &Path) {
        if !self.opts.keep {
            let _ = self.release_ports(ws);
            if let Some((_, _, provider)) = self.pinned {
                let _ = provider.remove(ws);
            } else {
                crate::git::remove_worktree(self.ctx, &self.repo_root, ws, &self.opts.trash);
            }
        }
    }

    /// Run the unit in its own copy of the worktree, as each GitHub job gets its
    /// own checkout: a unit that edits tracked files for a while (a negative
    /// control, a formatter) must not change what the units beside it read.
    fn run_unit_in_copy(&self, ui: usize, u: &Unit, waited: UnitWait) -> UnitResult {
        let n = if self.pinned.is_some() {
            self.seq.fetch_add(1, Ordering::SeqCst)
        } else {
            ui + 1
        };
        // the pid stays last in the name: cleanup scripts read it from there
        let ws = self.wt.with_file_name(format!(
            "{}-u{n}-{}",
            self.workspace_name(),
            std::process::id()
        ));
        let t0 = Instant::now();
        // installs done in setup are in the copy too
        let r = match self.copy_of(&self.wt, &ws) {
            Ok(()) => {
                let copy_secs = t0.elapsed().as_secs_f64();
                UnitResult {
                    copy_secs: Some(copy_secs),
                    ..self.run_unit(ui, u, waited, &ws)
                }
            }
            Err(e) => {
                let w = &self.plan.selected[u.wf].wf;
                let reason = format!("cannot copy the worktree: {e:#}");
                let mut jobs: Vec<JobResult> = u
                    .jobs
                    .iter()
                    .map(|id| JobResult {
                        workflow: w.file.clone(),
                        job: id.clone(),
                        display: self.plan.job(u.wf, id).name.clone().unwrap_or(id.clone()),
                        outcome: Outcome::Error(reason.clone()),
                        secs: 0.0,
                        steps: vec![],
                        cancelled: false,
                        time: None,
                        build_cache: None,
                        os_note: None,
                    })
                    .collect();
                charge(&mut jobs, waited);
                UnitResult {
                    unit: Some(ui),
                    workflow: w.file.clone(),
                    jobs,
                    waited_secs: waited.total(),
                    copy_secs: None,
                    cached: None,
                    outcomes: vec![],
                }
            }
        };
        self.remove_copy(&ws);
        r
    }

    /// Give back the port block of `ws`. The worktree of the run itself may hold
    /// one even when no job asked: portool's post-checkout hook takes it.
    pub fn release_ports(&self, ws: &Path) -> Result<()> {
        self.release_ports_checked(ws)
    }

    pub(crate) fn release_ports_checked(&self, ws: &Path) -> Result<()> {
        // Record before source validation: failure must not erase the lease's
        // identity or trigger release in a replaced workspace.
        if self.opts.portool.is_some() {
            self.ctx.cancel.port_release_pending(ws);
        }
        self.validate_source()?;
        let Some(bin) = &self.opts.portool else {
            return Ok(());
        };
        if (ws == self.wt || self.synced.lock().unwrap().contains(ws))
            && ws.join(".portool.toml").is_file()
        {
            crate::portool::release_checked(self.ctx, bin, ws)?;
            self.synced.lock().unwrap().remove(ws);
        }
        self.ctx.cancel.port_release_confirmed(ws);
        Ok(())
    }

    /// Run the tasks of one unit, one after the other, in `ws`.
    ///
    /// The shards of a split job are tasks like the others, so here they run
    /// one after the other too: a local run of a split plan takes the sum of
    /// the shards' times, not the longest of them. What the division by load
    /// (`shard::partition_tests`) improves, the time of the slowest shard, is
    /// the time of the job only where the shards run side by side, on separate
    /// workers (`run_task` per shard, results put together by
    /// `complete::aggregate_shard_group`). With `fail-fast`, the shards after a
    /// failed one are not run (they end `cancelled`).
    fn run_unit(&self, ui: usize, u: &Unit, waited: UnitWait, ws: &Path) -> UnitResult {
        let w = &self.plan.selected[u.wf].wf;
        let locked = self.unit_locked(u);
        // The unit is run as its tasks, in the order the plan gives them, in
        // the one workspace of the unit (a local run's shortcut: a task run
        // elsewhere gets a checkout of its own). The variants of a matrix job
        // are run together, as the job.
        let mut inputs = TaskInputs::default();
        let mut jobs = Vec::new();
        let mut outcomes: Vec<JobOutcome> = Vec::new();
        // the shards of each split job that were handled so far
        let mut shards: HashMap<String, ShardHold> = HashMap::new();
        // A copy of the setup workspace is another workspace: it gets an id of
        // its own, and the receipts of the setup are bound to it, as the copy
        // holds what the setup made.
        let copy_id = (ws != self.wt)
            .then(|| setup::ensure_workspace_id(ws).ok())
            .flatten();
        let origin = setup::workspace_id(&self.wt);
        // The receipts are this run's own. In the setup workspace they are
        // believed as they are. A copy is checked once, here, before any task
        // wrote in it: what the setup made must be in it as the receipt says;
        // after that the tasks of the unit trust the receipt even when one of
        // them wrote next to what the install made. A copy that does not
        // match has its receipts checked again by each task, and ignored.
        let mut copy_checked: HashMap<String, bool> = HashMap::new();
        if copy_id.is_some() {
            if let Some((m, _)) = &self.receipts {
                for t in self.fp.tasks.iter().filter(|t| t.unit == ui) {
                    if let Some(r) = m.get(&t.id) {
                        copy_checked
                            .entry(t.id.clone())
                            .or_insert_with(|| setup::verify_artifacts(r, ws, true).is_ok());
                    }
                }
            }
        }
        for task in self.fp.tasks.iter().filter(|t| t.unit == ui) {
            if task.variant.as_ref().is_some_and(|v| v.index > 0) {
                continue;
            }
            let receipt = self.receipts.as_ref().and_then(|(m, c)| {
                m.get(&task.id).map(|r| match &copy_id {
                    Some(id) if origin.as_deref() == Some(r.workspace.as_str()) => {
                        (r.rebound(id), c)
                    }
                    _ => (r.clone(), c),
                })
            });
            let verify = copy_id.is_some() && !copy_checked.get(&task.id).copied().unwrap_or(false);
            // With `fail-fast`, the shards that come after a failed one are not
            // run: the job has failed whatever they report.
            if let Some(ts) = &task.shard {
                let hold = shards.entry(ts.group.clone()).or_default();
                if hold.cancel.contains(&task.id) {
                    let why = "cancelled: another shard of the job failed (fail-fast)";
                    for id in &task.jobs {
                        let job = self.plan.job(u.wf, id);
                        let r = JobResult {
                            workflow: w.file.clone(),
                            job: id.clone(),
                            display: format!(
                                "{} (shard {}/{})",
                                job.name.clone().unwrap_or_else(|| id.clone()),
                                ts.index + 1,
                                ts.count
                            ),
                            outcome: Outcome::Skip(why.into()),
                            secs: 0.0,
                            steps: vec![],
                            cancelled: true,
                            time: None,
                            build_cache: None,
                            os_note: None,
                        };
                        hold.outcomes.push(outcome_of(id, None, &r, &Map::new()));
                        jobs.push(r);
                    }
                    hold.last = jobs.len().checked_sub(1);
                    hold.handled.insert(task.id.clone());
                    self.settle_shards(task, hold, &mut jobs, &mut outcomes, &mut inputs);
                    continue;
                }
            }
            match self.run_task(
                ws,
                task,
                &inputs,
                receipt.as_ref().map(|(r, c)| (r, *c)),
                verify,
                locked,
                true,
            ) {
                Ok(r) => {
                    // A shard is not the job: the job is its shards together,
                    // checked against the tests they were to run.
                    if let Some(ts) = &task.shard {
                        for o in &r.outcomes {
                            inputs.run_cancelled |= o.status == JobStatus::Cancelled;
                        }
                        jobs.extend(r.jobs);
                        let hold = shards.entry(ts.group.clone()).or_default();
                        hold.last = jobs.len().checked_sub(1);
                        hold.outcomes.extend(r.outcomes);
                        hold.reports.extend(r.shard);
                        hold.handled.insert(task.id.clone());
                        self.settle_shards(task, hold, &mut jobs, &mut outcomes, &mut inputs);
                        continue;
                    }
                    for o in r.outcomes {
                        inputs.run_cancelled |= o.status == JobStatus::Cancelled;
                        outcomes.push(o.clone());
                        inputs.needs.insert(o.job.clone(), o);
                    }
                    jobs.extend(r.jobs);
                }
                Err(e) => {
                    let reason = format!("{e:#}");
                    // The jobs of a task that could not be run failed: the
                    // jobs that need them must see that, not a missing need.
                    // A shard that could not be run is a shard the job is
                    // missing: the job fails once, when its shards are done.
                    for id in &task.jobs {
                        let o = JobOutcome {
                            job: id.clone(),
                            variant: None,
                            status: JobStatus::Failure,
                            outputs: Default::default(),
                            skipped: Some(reason.clone()),
                            ancestor_failed: false,
                        };
                        if let Some(ts) = &task.shard {
                            shards.entry(ts.group.clone()).or_default().outcomes.push(o);
                        } else {
                            outcomes.push(o.clone());
                            inputs.needs.insert(id.clone(), o);
                        }
                    }
                    // every entry of a matrix job failed, not one in its place
                    for id in &task.jobs {
                        let job = self.plan.job(u.wf, id);
                        let base = job.name.clone().unwrap_or(id.clone());
                        let displays: Vec<String> =
                            match crate::dag::matrix_plan(self.fp.job(u.wf, id)) {
                                crate::dag::MatrixPlan::Static(v) => v
                                    .iter()
                                    .map(|c| format!("{base} ({})", matrix::describe(c)))
                                    .collect(),
                                _ => vec![base],
                            };
                        for display in displays {
                            jobs.push(JobResult {
                                workflow: w.file.clone(),
                                job: id.clone(),
                                display,
                                outcome: Outcome::Error(reason.clone()),
                                secs: 0.0,
                                steps: vec![],
                                cancelled: false,
                                time: None,
                                build_cache: None,
                                os_note: None,
                            });
                        }
                    }
                    if let Some(ts) = &task.shard {
                        let hold = shards.entry(ts.group.clone()).or_default();
                        hold.last = jobs.len().checked_sub(1);
                        hold.errored = true;
                        hold.handled.insert(task.id.clone());
                        self.settle_shards(task, hold, &mut jobs, &mut outcomes, &mut inputs);
                    }
                }
            }
        }
        // A split job whose shards did not all come: it has failed, and it
        // has its one outcome now.
        for (group, hold) in shards.iter_mut().filter(|(_, h)| !h.done) {
            self.finish_shards(group, hold, &mut jobs, &mut outcomes, &mut inputs);
        }
        charge(&mut jobs, waited);
        UnitResult {
            unit: Some(ui),
            workflow: w.file.clone(),
            jobs,
            waited_secs: waited.total(),
            copy_secs: None,
            cached: None,
            outcomes,
        }
    }

    /// A shard is handled: with `fail-fast` the shards that have not run are
    /// to be cancelled once one failed, and when all are handled the job has
    /// its outcome.
    fn settle_shards(
        &self,
        task: &ExecutionTask,
        hold: &mut ShardHold,
        jobs: &mut [JobResult],
        outcomes: &mut Vec<JobOutcome>,
        inputs: &mut TaskInputs,
    ) {
        let Some(ts) = &task.shard else { return };
        hold.job = task.jobs.join("+");
        let group = self.fp.shard_groups.iter().find(|g| g.id == ts.group);
        if let Some(g) = group {
            let agg = crate::complete::aggregate_shard_group(g, &hold.reports);
            hold.cancel.extend(agg.cancel);
            if g.fail_fast && hold.errored {
                hold.cancel.extend(
                    g.shards
                        .iter()
                        .filter(|s| !hold.handled.contains(*s))
                        .cloned(),
                );
            }
            if hold.handled.len() < g.shards.len() {
                return;
            }
        }
        self.finish_shards(&ts.group, hold, jobs, outcomes, inputs);
    }

    /// The one outcome of a split job: its shards together, checked against the
    /// tests they were to run, with every shard there and no output on which
    /// they differ. Whatever is wrong makes the job fail.
    fn finish_shards(
        &self,
        group: &str,
        hold: &mut ShardHold,
        jobs: &mut [JobResult],
        outcomes: &mut Vec<JobOutcome>,
        inputs: &mut TaskInputs,
    ) {
        if std::mem::replace(&mut hold.done, true) {
            return;
        }
        let mut problems = match self.fp.shard_groups.iter().find(|g| g.id == group) {
            Some(g) => crate::complete::aggregate_shard_group(g, &hold.reports).problems(),
            None => vec![format!("the plan has no shard group `{group}`")],
        };
        problems.extend(task::conflicting_outputs(&hold.outcomes));
        let mut o = combine(&hold.job, std::mem::take(&mut hold.outcomes));
        if !problems.is_empty() && o.status == JobStatus::Success {
            let why = problems.join("; ");
            o.status = JobStatus::Failure;
            o.skipped = Some(why.clone());
            if let Some(last) = hold.last.and_then(|i| jobs.get_mut(i)) {
                last.outcome = Outcome::Error(why);
            }
        }
        outcomes.push(o.clone());
        inputs.needs.insert(o.job.clone(), o);
    }

    /// Whether a task holds the per-repository lock while it runs (see
    /// `unit_locked`).
    pub(crate) fn task_locked(&self, t: &ExecutionTask) -> bool {
        t.exclusive && (!self.isolated() || !t.services.is_empty())
    }

    /// Run the jobs of `task` in `ws`, in order, against the results `inputs`
    /// holds for the jobs it needs. `locked`: the caller holds the repository
    /// lock. `whole_matrix`: for a task that is one variant of a matrix job,
    /// run all the variants (as one job) instead.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn run_task(
        &self,
        ws: &Path,
        task: &ExecutionTask,
        inputs: &TaskInputs,
        prepared: Option<(&PreparedReceipt, &TemplateContext)>,
        // whether to hash what the receipt describes before believing it: for
        // a receipt that comes from outside, yes; for the run's own receipt
        // in the workspace it was made for (or a copy checked when it was
        // made), no
        verify_contents: bool,
        locked: bool,
        whole_matrix: bool,
    ) -> Result<TaskResult> {
        self.validate_source()?;
        anyhow::ensure!(
            self.selected
                .as_ref()
                .is_none_or(|(selection, _)| &selection.task == task),
            "selected dispatch task mismatch"
        );
        let wi = self
            .plan
            .selected
            .iter()
            .position(|s| s.wf.file == task.workflow)
            .with_context(|| format!("the plan has no workflow {}", task.workflow))?;
        let sel = &self.plan.selected[wi];
        let w = &sel.wf;
        // A shard's task runs its own command in place of one step. When that
        // cannot be done, the task is not run at all: running the job as it is
        // would run every test once per shard, and its result would stand for
        // the whole job.
        if let Some(ts) = &task.shard {
            if let Err(why) = self.check_shard_task(wi, task, ts) {
                bail!("task {} is a shard of a split job, but {why}", task.id);
            }
        }
        for id in &task.jobs {
            let job = self.plan.job(wi, id);
            if let Some(n) = job
                .needs
                .iter()
                .find(|n| !task.jobs.contains(n) && !inputs.needs.contains_key(*n))
            {
                bail!(
                    "task {} needs the result of job `{n}`; none was given",
                    task.id
                );
            }
        }
        let only = match (&task.variant, whole_matrix) {
            (Some(v), false) => Some(v.index),
            _ => None,
        };
        // A receipt is believed only for this commit, this workspace and the
        // template key this task's recipe has here; otherwise the task does all
        // its setup itself and says so.
        let mut receipt_ignored = None;
        let places = match prepared {
            Some((r, tctx)) => match setup::derive_in(&self.plan, &self.hoisted, task)?
                .prepared_places(
                    r,
                    &self.source_identity(),
                    setup::workspace_id(ws).as_deref(),
                    ws,
                    tctx,
                    verify_contents,
                ) {
                Ok(p) => p,
                Err(why) => {
                    receipt_ignored = Some(why);
                    HashMap::new()
                }
            },
            None => HashMap::new(),
        };
        let none = HashSet::new();
        let mut needs_ctx = inputs.context();
        let mut jobs = Vec::new();
        let mut outcomes = Vec::new();
        let mut shard = None;
        for id in &task.jobs {
            let job = self.plan.job(wi, id);
            // `failure()` of a job: a job it needs, or one of theirs, failed
            let ancestor_failed = job.needs.iter().any(|n| {
                outcomes
                    .iter()
                    .find(|o: &&JobOutcome| &o.job == n)
                    .or_else(|| inputs.needs.get(n))
                    .is_some_and(JobOutcome::failed_or_ancestor_failed)
            });
            let results = self.run_job(
                ws,
                w,
                &sel.event,
                job,
                &needs_ctx,
                ancestor_failed,
                inputs.run_cancelled || self.ctx.cancel.is_cancelled(),
                places.get(id).unwrap_or(&none),
                locked,
                only,
                task.shard.as_ref(),
            );
            let parts: Vec<JobOutcome> = results
                .iter()
                .enumerate()
                .map(|(i, (r, o))| outcome_of(id, only.or(Some(i)), r, o))
                .collect();
            let outcome = match only {
                Some(_) => parts.into_iter().next().unwrap_or_else(|| JobOutcome {
                    job: id.clone(),
                    variant: only,
                    status: JobStatus::Success,
                    outputs: Default::default(),
                    skipped: None,
                    ancestor_failed: false,
                }),
                None => combine(id, parts),
            };
            let outcome = JobOutcome {
                ancestor_failed,
                ..outcome
            };
            needs_ctx.insert(id.clone(), task::ctx_of(&outcome));
            let results: Vec<JobResult> = results.into_iter().map(|r| r.0).collect();
            if let Some(ts) = &task.shard {
                shard = Some(self.shard_outcome(ws, w, job, task, ts, results.first()));
            }
            jobs.extend(results);
            outcomes.push(outcome);
        }
        Ok(TaskResult {
            schema_version: crate::wire::wire_version(),
            task: task.id.clone(),
            shard,
            jobs,
            outcomes,
            receipt_ignored,
            artifacts: artifact_io::published_by(
                &self.run_dir,
                &task.workflow,
                &task
                    .jobs
                    .iter()
                    .map(|j| dag::node_id(&task.workflow, j))
                    .collect::<Vec<_>>(),
            ),
        })
    }

    /// Whether the step a shard's command replaces is what the plan says it
    /// is: one plain command of the runner the shard was made for, run by a
    /// shell that reads it as one, in the directory the tests were listed in,
    /// and not allowed to fail without failing the job. The plan is read again
    /// here, not believed: a plan that was changed after the split must not
    /// run every test once per shard.
    fn check_shard_task(
        &self,
        wi: usize,
        task: &ExecutionTask,
        ts: &dag::TaskShard,
    ) -> Result<(), String> {
        use crate::shard::{adapters, SplitMode};
        let w = &self.plan.selected[wi].wf;
        let bad = |what: &str| {
            Err(format!(
                "step {} of its job is not a command of runner `{}` that can be given the shard's tests ({what})",
                ts.step, ts.runner.runner
            ))
        };
        let job = (task.jobs.len() == 1).then(|| self.plan.job(wi, &task.jobs[0]));
        let Some((job, step)) = job.and_then(|j| Some((j, j.steps.get(ts.step)?))) else {
            return bad("there is no such step");
        };
        let Some(run) = step.run.as_ref().filter(|_| step.uses.is_none()) else {
            return bad("it is not a `run` step");
        };
        if step.continue_on_error {
            return bad("it may fail without failing the job");
        }
        if !matches!(
            plan::resolved_shell(w, job, step).as_deref().map(str::trim),
            None | Some("bash") | Some("sh")
        ) {
            return bad("its shell does not read one command");
        }
        if plan::step_dir(w, job, step) != ts.dir {
            return bad("its working directory is not where the tests were listed");
        }
        let Some(parsed) = adapters::parse_command(run) else {
            return bad("it is not one plain command");
        };
        if parsed.runner != ts.runner.runner
            || parsed.args != ts.runner.config
            || !parsed.blocked.is_empty()
        {
            return bad("it is not the command the shards were made from");
        }
        if crate::shard::isolation::reason_in(&w.env, job).is_some() {
            return bad("the job starts a container, a server or a service its shards would share");
        }
        if crate::shard::isolation::coverage_reason(&w.env, job).is_some() {
            return bad("the job collects coverage, which its shards would each measure in part");
        }
        let caps = adapters::from_info(&ts.runner, "").map(|a| a.capabilities());
        let Some(caps) = caps else {
            return bad("the shard has no tests to run");
        };
        if ts.mode == SplitMode::Single || (ts.mode == SplitMode::Listed && ts.tests.is_empty()) {
            return bad("the shard has no tests to run");
        }
        if (ts.mode == SplitMode::Listed && !caps.targets)
            || (ts.mode == SplitMode::Native && !caps.native_shard)
        {
            return bad("the runner cannot divide its tests that way");
        }
        Ok(())
    }

    /// What the shard `ts` of `task` reported, from the log of the step that
    /// ran its tests. A step that did not run (the job's condition, an earlier
    /// step that failed) reported nothing, and the outcome says it failed.
    fn shard_outcome(
        &self,
        ws: &Path,
        w: &Workflow,
        job: &Job,
        task: &ExecutionTask,
        ts: &dag::TaskShard,
        result: Option<&JobResult>,
    ) -> crate::shard::ShardOutcome {
        use crate::shard::{adapters, CommandOutput, ShardOutcome};
        let none = |exit_ok| ShardOutcome {
            job_id: job.id.clone(),
            shard_id: task.id.clone(),
            tests: vec![],
            exit_ok,
            parsed: false,
        };
        let Some(step) = job.steps.get(ts.step) else {
            return none(false);
        };
        let root = ws.join(plan::step_dir(w, job, step));
        let ran = result.and_then(|r| r.steps.get(ts.step));
        let (Some(ran), Some(adapter)) = (
            ran,
            adapters::from_info(&ts.runner, &root.to_string_lossy()),
        ) else {
            return none(false);
        };
        let log = ran
            .log
            .as_ref()
            .and_then(|l| fs::read(l).ok())
            .map(|b| String::from_utf8_lossy(&b).into_owned());
        let out = CommandOutput {
            stdout: log.clone().unwrap_or_default(),
            stderr: String::new(),
            success: ran.outcome == Outcome::Pass && ran.exit == Some(0),
            exit: ran.exit,
        };
        let mut o = adapter.collect_given(&job.id, &task.id, &out, &ts.tests);
        o.parsed &= log.is_some();
        o
    }

    /// One job, all its matrix combinations. Returns each combination's result and outputs.
    #[allow(clippy::too_many_arguments)]
    fn run_job(
        &self,
        ws: &Path,
        w: &Workflow,
        event: &str,
        job: &Job,
        needs: &Map<String, Value>,
        // a job it needs, or one of theirs, failed
        ancestor_failed: bool,
        // the run was cancelled
        run_cancelled: bool,
        // steps (by index) the task's setup already did
        prepared: &HashSet<usize>,
        // the unit holds the per-repository lock
        locked: bool,
        // run only this entry of the matrix
        only: Option<usize>,
        // the part of a split job this runs: its step runs the shard's command
        shard: Option<&dag::TaskShard>,
    ) -> Vec<(JobResult, Map<String, Value>)> {
        let gh = self.github_ctx(ws, w, event, &job.id);
        let skip = |display: String, reason: String| {
            (
                JobResult {
                    workflow: w.file.clone(),
                    job: job.id.clone(),
                    display,
                    outcome: Outcome::Skip(reason),
                    secs: 0.0,
                    steps: vec![],
                    cancelled: false,
                    time: None,
                    build_cache: None,
                    os_note: None,
                },
                Map::new(),
            )
        };
        // the run was cancelled before this entry started
        let cancelled_skip = |display: String| {
            let mut r = skip(display, "cancelled".into());
            r.0.cancelled = true;
            r
        };
        let error = |display: String, reason: String| {
            (
                JobResult {
                    workflow: w.file.clone(),
                    job: job.id.clone(),
                    display,
                    outcome: Outcome::Error(reason),
                    secs: 0.0,
                    steps: vec![],
                    cancelled: false,
                    time: None,
                    build_cache: None,
                    os_note: None,
                },
                Map::new(),
            )
        };

        // The OS each entry's `runs-on` names. Every job runs on the host: the
        // entries of another OS that a leg of the host's OS stands in for are
        // not run, the others run with a note. The shared evaluation stays
        // free of the host; a member a driver selected was placed by its host.
        let host = os_legs::Family::host();
        let legs = if self.selected.is_none() {
            self.os_legs_of(job, &gh, needs, shard)
        } else {
            None
        };
        let evaluated = match &self.selected {
            Some((selection, facts)) => {
                selection.worker_evaluation(gh, self.runner_ctx(), needs, facts)
            }
            None => crate::job_evaluate::evaluate_job(
                job,
                gh,
                self.runner_ctx(),
                needs,
                ancestor_failed,
                run_cancelled,
                only,
                shard,
            ),
        };
        let mut out = Vec::new();
        let mut notes: Vec<(usize, String)> = Vec::new();
        let mut todo = Vec::new();
        for (k, entry) in evaluated.entries.into_iter().enumerate() {
            match entry.decision {
                crate::job_evaluate::Decision::Run(cm) => {
                    let leg = legs.as_ref().and_then(|l| l.get(only.unwrap_or(k)));
                    match leg {
                        Some(OsLeg {
                            os: Some((family, label)),
                            twin: Some(twin),
                        }) => out.push(Some(skip(
                            entry.display,
                            os_legs::not_run_reason(label, *family, host, twin),
                        ))),
                        _ => {
                            if let Some((family, label)) =
                                leg.and_then(|l| l.os.as_ref()).filter(|(f, _)| *f != host)
                            {
                                notes.push((out.len(), os_legs::ran_on_note(label, *family, host)));
                            }
                            todo.push((out.len(), cm, entry.display));
                            out.push(None);
                        }
                    }
                }
                crate::job_evaluate::Decision::Skip(reason) => {
                    out.push(Some(skip(entry.display, reason)))
                }
                crate::job_evaluate::Decision::Error(reason) => {
                    out.push(Some(error(entry.display, reason)))
                }
            }
        }

        let exclusive = plan::is_exclusive(job);
        let failed = AtomicBool::new(false);
        let stop = job.fail_fast.then_some(&failed);
        let one = |ws: &Path, cm: Map<String, Value>, display: String| {
            // Something rewriting cannot reach (a `container_name:`) still needs
            // the lock. Taken before the slot, in the order units take them.
            let requested_at_ms = now_ms();
            let t_lock = Instant::now();
            let lock = if exclusive && !locked && self.fixed_resources(ws, w, job, &cm) {
                self.lock().ok()
            } else {
                None
            };
            let wait_lock = t_lock.elapsed().as_secs_f64();
            let t_slot = Instant::now();
            let slot = if exclusive {
                match self.container_slot() {
                    Ok(Some(s)) => Some(s),
                    Ok(None) => return cancelled_skip(display),
                    // no lock files: run without a slot rather than not at all
                    Err(_) => None,
                }
            } else {
                None
            };
            let wait_slot = t_slot.elapsed().as_secs_f64();
            if self.ctx.cancel.is_cancelled() {
                return cancelled_skip(display);
            }
            if stop.is_some_and(|s| s.load(Ordering::SeqCst)) {
                return skip(display, "fail-fast".into());
            }
            let mut r = self.run_combo(ws, w, job, prepared, cm, display, stop, shard);
            drop(slot);
            drop(lock);
            let secs = r.0.secs;
            let t = r.0.time.get_or_insert_with(|| JobTime {
                work_secs: secs,
                ..JobTime::default()
            });
            t.wait_lock_secs += wait_lock;
            t.wait_slot_secs += wait_slot;
            if t.started_at_ms > 0 {
                t.requested_at_ms = requested_at_ms.min(t.started_at_ms);
            }
            if matches!(r.0.outcome, Outcome::Fail | Outcome::Error(_)) {
                failed.store(true, Ordering::SeqCst);
            }
            r
        };
        // Each combination at once, in its own copy of the workspace, as each
        // gets its own runner on GitHub. Only with task-traffic-controller or an
        // executor, which keep the CPU in check (an executor is called by up to
        // `max_parallel` legs at once), and for exclusive jobs only when they
        // cannot collide.
        let at_once = job.max_parallel.unwrap_or(usize::MAX);
        if todo.len() > 1
            && at_once > 1
            && (self.opts.traffic_controller.is_some() || self.opts.executor.is_some())
            && (!exclusive || !locked)
        {
            let done = Mutex::new(Vec::new());
            let sem = Semaphore {
                free: Mutex::new(at_once),
                cv: Condvar::new(),
            };
            std::thread::scope(|scope| {
                for (i, cm, display) in todo {
                    let (one, done, sem) = (&one, &done, &sem);
                    scope.spawn(move || {
                        sem.acquire();
                        // the pid stays last in the name: cleanup scripts read it from there
                        let copy = self.wt.with_file_name(format!(
                            "{}-c{}-{}",
                            self.workspace_name(),
                            self.seq.fetch_add(1, Ordering::SeqCst),
                            std::process::id()
                        ));
                        let r = match self.copy_of(ws, &copy) {
                            Ok(()) => one(&copy, cm, display),
                            Err(e) => error(display, format!("cannot copy the worktree: {e:#}")),
                        };
                        self.remove_copy(&copy);
                        sem.release();
                        done.lock().unwrap().push((i, r));
                    });
                }
            });
            for (i, r) in done.into_inner().unwrap() {
                out[i] = Some(r);
            }
        } else {
            for (i, cm, display) in todo {
                out[i] = Some(one(ws, cm, display));
            }
        }
        for (i, note) in notes {
            if let Some(Some((r, _))) = out.get_mut(i) {
                r.os_note = Some(note);
            }
        }
        out.into_iter().flatten().collect()
    }

    /// The OS of every entry of the job's matrix, and the name of the entry
    /// of the host's OS that stands in for it. `None` when the job has no
    /// entries to tell apart (its matrix does not expand, or it is not run).
    fn os_legs_of(
        &self,
        job: &Job,
        gh: &Value,
        needs: &Map<String, Value>,
        shard: Option<&dag::TaskShard>,
    ) -> Option<Vec<OsLeg>> {
        job.runs_on.as_ref()?;
        // every entry with its contexts and name, whatever its `if:` and the
        // jobs it needs say (no `if:` would mean `success()`)
        let mut all = job.clone();
        all.cond = Some("always()".into());
        let entries = crate::job_evaluate::evaluate_job(
            &all,
            gh.clone(),
            self.runner_ctx(),
            needs,
            false,
            false,
            None,
            shard,
        )
        .entries;
        let mut contexts = Vec::new();
        let mut displays = Vec::new();
        for entry in entries {
            match entry.decision {
                crate::job_evaluate::Decision::Run(cm) => {
                    contexts.push(cm);
                    displays.push(entry.display);
                }
                _ => return None,
            }
        }
        let os_of: Vec<Option<(os_legs::Family, String)>> = contexts
            .iter()
            .map(|cm| os_legs::family_of_leg(job, cm))
            .collect();
        let twin_of: Vec<Option<usize>> = if self.opts.all_os_legs {
            vec![None; contexts.len()]
        } else {
            let legs: Vec<os_legs::Leg> = os_of
                .iter()
                .zip(&contexts)
                .map(|(o, cm)| os_legs::Leg {
                    family: o.as_ref().map(|(f, _)| *f),
                    matrix: cm
                        .get("matrix")
                        .and_then(Value::as_object)
                        .cloned()
                        .unwrap_or_default(),
                })
                .collect();
            os_legs::twins(os_legs::Family::host(), job, &legs)
        };
        Some(
            os_of
                .into_iter()
                .zip(twin_of)
                .map(|(os, twin)| OsLeg {
                    os,
                    twin: twin.map(|t| displays[t].clone()),
                })
                .collect(),
        )
    }

    /// Evaluate `pairs` into `into`. Says whether a secret that cannot be
    /// supplied was read.
    fn eval_env(
        host: &ExecContext,
        pairs: &[(String, String)],
        cm: &Map<String, Value>,
        into: &mut Map<String, Value>,
        maps: &[PortMap],
    ) -> Result<bool> {
        let mut secrets = false;
        for (k, v) in pairs {
            let mut ctx_map = cm.clone();
            ctx_map.insert("env".into(), Value::Object(into.clone()));
            let ctx = Ctx::new(&ctx_map, Status::Success).with_token(host);
            let val = expr::interpolate(v, &ctx)?;
            secrets |= ctx.used_secrets.get();
            into.insert(k.clone(), Value::String(rewrite_env_value(k, &val, maps)));
        }
        Ok(secrets)
    }

    #[allow(clippy::too_many_arguments)]
    fn run_combo(
        &self,
        ws: &Path,
        w: &Workflow,
        job: &Job,
        prepared: &HashSet<usize>,
        mut cm: Map<String, Value>,
        display: String,
        // set when another entry of a fail-fast matrix failed
        stop: Option<&AtomicBool>,
        // the part of a split job this runs: its step runs the shard's command
        shard: Option<&dag::TaskShard>,
    ) -> (JobResult, Map<String, Value>) {
        let native_scope = native_step::NativeScope::default();
        let t0 = Instant::now();
        let started_at_ms = now_ms();
        let mut stopped = false;
        let mut steps: Vec<StepResult> = Vec::new();
        let mut names = Vec::new();
        let finish = |outcome: Outcome, steps: Vec<StepResult>, t0: Instant| JobResult {
            workflow: w.file.clone(),
            job: job.id.clone(),
            display: display.clone(),
            outcome,
            secs: t0.elapsed().as_secs_f64(),
            steps,
            cancelled: false,
            time: None,
            build_cache: None,
            os_note: None,
        };

        // services
        let mut maps = Vec::new();
        let mut services_ctx = Map::new();
        if !job.services.is_empty() {
            match self.start_services(w, job, &cm, &mut names) {
                Ok((m, sc)) => {
                    maps = m;
                    services_ctx = sc;
                }
                Err(e) => {
                    self.stop_services(&names, &mut steps);
                    let mut r = finish(Outcome::Error(format!("services: {e:#}")), steps, t0);
                    r.cancelled = self.ctx.cancel.is_cancelled();
                    return (r, Map::new());
                }
            }
        }
        cm.insert(
            "job".into(),
            json!({"status": "success", "services": services_ctx}),
        );

        // A job that starts containers or test servers must not bind what
        // another run, or a matrix entry beside it, binds.
        let exclusive = plan::is_exclusive(job);
        let port_env = match &self.opts.portool {
            // Not with `services:`: the job's database is the service, and a
            // script that honours portool's ports would look for its own instead.
            Some(bin)
                if exclusive && job.services.is_empty() && ws.join(".portool.toml").is_file() =>
            {
                // before the sync: it may take a block and still fail
                self.synced.lock().unwrap().insert(ws.to_path_buf());
                match crate::portool::sync(self.ctx, bin, ws) {
                    Ok(v) => v,
                    Err(e) => {
                        self.stop_services(&names, &mut steps);
                        return (
                            finish(Outcome::Error(format!("{e:#}")), steps, t0),
                            Map::new(),
                        );
                    }
                }
            }
            _ => vec![],
        };

        // workflow + job env
        let mut env_ctx = Map::new();
        if let Err(e) = Self::eval_env(self.ctx, &w.env, &cm, &mut env_ctx, &maps)
            .and_then(|_| Self::eval_env(self.ctx, &job.env, &cm, &mut env_ctx, &maps))
            .and_then(|_| {
                if exclusive {
                    let fixed: Vec<u16> = env_ctx
                        .iter()
                        .filter(|(k, _)| port_key(k))
                        .filter_map(|(_, v)| port_literal(&expr::to_string(v)))
                        .collect();
                    map_literals(fixed, &mut maps)?;
                    for (k, v) in env_ctx.iter_mut() {
                        let s = expr::to_string(v);
                        let r = rewrite_env_value(k, &s, &maps);
                        if r != s {
                            *v = Value::String(r);
                        }
                    }
                }
                Ok(())
            })
        {
            self.stop_services(&names, &mut steps);
            return (
                finish(Outcome::Error(format!("env: {e:#}")), steps, t0),
                Map::new(),
            );
        }
        let mut bc = self.build_cache_start(ws, w, job, &cm, &env_ctx);
        let job_min = job.timeout_minutes.unwrap_or(self.opts.job_timeout_min);
        let job_timeout = Duration::from_secs_f64(60.0 * job_min);
        let mut steps_ctx = Map::new();
        let mut extra_env: Vec<(String, String)> = Vec::new();
        let mut extra_path: Vec<String> = Vec::new();
        let mut failed = false;
        // `docker compose` without `-p` would share the project of the main checkout's directory.
        let compose_default = self.resource_name();
        let tag = format!("lc{}", &compose_default["local-ci-".len()..]);
        let mut projects = vec![compose_default.clone()];
        self.ctx.cancel.track_compose(compose_default.clone());
        let mut errored: Option<String> = None;
        // the first error was the run being cancelled
        let mut cancelled = false;
        // task-traffic-controller's queue, summed over the steps
        let mut queue = Duration::ZERO;

        for (n, s) in job.steps.iter().enumerate() {
            let raw_label = s.label();
            let label = if raw_label.contains("${{") {
                let mut lcm = cm.clone();
                lcm.insert("steps".into(), Value::Object(steps_ctx.clone()));
                lcm.insert("env".into(), Value::Object(env_ctx.clone()));
                expr::interpolate(&raw_label, &Ctx::new(&lcm, Status::Success)).unwrap_or(raw_label)
            } else {
                raw_label
            };
            // a label comes to result.json: the token does not
            let label = self.hide_token(label);
            let st0 = Instant::now();
            let push = |steps: &mut Vec<StepResult>,
                        outcome: Outcome,
                        exit: Option<i32>,
                        log: Option<PathBuf>,
                        note: Option<String>| {
                steps.push(StepResult {
                    label: label.clone(),
                    outcome,
                    exit,
                    secs: st0.elapsed().as_secs_f64(),
                    log,
                    note,
                });
            };
            stopped |= stop.is_some_and(|s| s.load(Ordering::SeqCst));
            let status = if self.ctx.cancel.is_cancelled() || stopped {
                Status::Cancelled
            } else if failed || errored.is_some() {
                Status::Failure
            } else {
                Status::Success
            };
            let mut scm = cm.clone();
            scm.insert("steps".into(), Value::Object(steps_ctx.clone()));
            let mut step_env = env_ctx.clone();
            for (k, v) in &extra_env {
                step_env.insert(k.clone(), Value::String(v.clone()));
            }
            scm.insert("env".into(), Value::Object(step_env.clone()));
            let go = expr::condition(
                s.cond.as_deref(),
                &Ctx::new(&scm, status).with_token(self.ctx),
            );
            match go {
                Ok(true) => {}
                Ok(false) => {
                    push(
                        &mut steps,
                        Outcome::Skip(if status == Status::Success {
                            "if: false".into()
                        } else {
                            "earlier step failed".into()
                        }),
                        None,
                        None,
                        None,
                    );
                    record(&mut steps_ctx, &s.id, "skipped", "skipped", Map::new());
                    continue;
                }
                Err(e) => {
                    let e = self.hide_token(format!("{e:#}"));
                    push(
                        &mut steps,
                        Outcome::Error(format!("if: {e}")),
                        None,
                        None,
                        None,
                    );
                    errored.get_or_insert(format!("{label}: if: {e}"));
                    continue;
                }
            }

            if let Some(uses) = &s.uses {
                let (outcome, note) = match artifact::parse_uses(uses) {
                    Some(Ok(kind)) => self.artifact_step(ws, w, job, &display, n, s, &scm, kind),
                    Some(Err(e)) => (Outcome::Error(e), None),
                    None => self.check_action(uses, s, &scm),
                };
                // what a `with:` value expanded to comes to result.json
                let outcome = match outcome {
                    Outcome::Error(e) => Outcome::Error(self.hide_token(e)),
                    Outcome::Skip(e) => Outcome::Skip(self.hide_token(e)),
                    o => o,
                };
                let note = note.map(|n| self.hide_token(n));
                if let Outcome::Error(e) = &outcome {
                    errored.get_or_insert(format!("{label}: {e}"));
                }
                let o = if matches!(outcome, Outcome::Pass) {
                    "success"
                } else {
                    "skipped"
                };
                push(&mut steps, outcome, None, None, note);
                record(&mut steps_ctx, &s.id, o, o, Map::new());
                continue;
            }
            let Some(run) = &s.run else {
                push(
                    &mut steps,
                    Outcome::Skip("no run or uses".into()),
                    None,
                    None,
                    None,
                );
                continue;
            };
            if prepared.contains(&n) {
                push(&mut steps, Outcome::Skip("setup".into()), None, None, None);
                record(&mut steps_ctx, &s.id, "success", "success", Map::new());
                continue;
            }
            if crate::script::remote_effect(run) {
                push(
                    &mut steps,
                    Outcome::Skip("pushes, publishes or deploys".into()),
                    None,
                    None,
                    None,
                );
                record(&mut steps_ctx, &s.id, "skipped", "skipped", Map::new());
                continue;
            }
            if crate::script::global_install(run, &|c| self.ctx.find_tool(c).is_some())
                == crate::script::Install::Needed
            {
                push(
                    &mut steps,
                    Outcome::Skip("installs system packages".into()),
                    None,
                    None,
                    None,
                );
                record(&mut steps_ctx, &s.id, "skipped", "skipped", Map::new());
                continue;
            }
            // interpolate
            let ctx = Ctx::new(&scm, status).with_token(self.ctx);
            let script = expr::interpolate(run, &ctx);
            let mut env_now = step_env.clone();
            // An install that another job runs here with another shell or env
            // is this job's own: the npm shim must not take another job's mark
            // of it for its own.
            if plan::step_key(w, job, s, &self.plan.ignore_env)
                .is_some_and(|k| self.hoisted.conflicting.contains(&k))
            {
                env_now.insert(
                    "LOCAL_CI_INSTALL_SCOPE".into(),
                    Value::String(job.id.clone()),
                );
            }
            let env_res = Self::eval_env(self.ctx, &s.env, &scm, &mut env_now, &maps);
            let secrets = ctx.used_secrets.get() || matches!(env_res, Ok(true));
            let (script, mut env_now) = match (script, env_res) {
                (Ok(sc), Ok(_)) => (sc, env_now),
                (Err(e), _) | (_, Err(e)) => {
                    let e = self.hide_token(format!("{e:#}"));
                    push(&mut steps, Outcome::Error(e.clone()), None, None, None);
                    errored.get_or_insert(format!("{label}: {e}"));
                    continue;
                }
            };
            let script = if exclusive {
                let fixed: Vec<u16> = assigned_ports(&script)
                    .into_iter()
                    .chain(
                        env_now
                            .iter()
                            .filter(|(k, _)| port_key(k))
                            .filter_map(|(_, v)| port_literal(&expr::to_string(v))),
                    )
                    .collect();
                if let Err(e) = map_literals(fixed, &mut maps) {
                    push(
                        &mut steps,
                        Outcome::Error(format!("{e:#}")),
                        None,
                        None,
                        None,
                    );
                    errored.get_or_insert(format!("{label}: {e:#}"));
                    continue;
                }
                for (k, v) in env_now.iter_mut() {
                    let s = expr::to_string(v);
                    let mut r = rewrite_env_value(k, &s, &maps);
                    if k == "COMPOSE_PROJECT_NAME"
                        && !r.is_empty()
                        && !r.ends_with(&format!("-{tag}"))
                    {
                        r = format!("{r}-{tag}");
                    }
                    if r != s {
                        *v = Value::String(r);
                    }
                }
                rename_compose_projects(&rewrite_ports(&script, &maps), &tag)
            } else {
                rewrite_ports(&script, &maps)
            };
            // A script or env that holds the token is run with the script
            // handed over a pipe, never written to a file.
            let token = self.ctx.github_token_if_fetched().filter(|t| !t.is_empty());
            // (A custom shell cannot be given a pipe, see `shell_once`; it is
            // handed a file, so only a script that holds the token is refused,
            // not one that gets the token through its environment.)
            let step_shell = s
                .shell
                .as_deref()
                .or(job.shell.as_deref())
                .or(w.shell.as_deref());
            let custom_shell = !matches!(
                step_shell.map(str::trim),
                None | Some("bash") | Some("sh") | Some("python")
            );
            let piped = token.is_some_and(|t| {
                script.contains(t)
                    || (!custom_shell && env_now.values().any(|v| expr::to_string(v).contains(t)))
            });
            if secrets {
                push(
                    &mut steps,
                    Outcome::Skip("uses secrets".into()),
                    None,
                    None,
                    None,
                );
                record(&mut steps_ctx, &s.id, "skipped", "skipped", Map::new());
                continue;
            }
            let wd = plan::step_dir(w, job, s);
            // the step that runs the tests of a shard runs the shard's command
            // (after the expressions of the step were read: a name is not one)
            let script = match shard.filter(|t| t.step == n) {
                Some(ts) => match shard_script(ts, &ws.join(&wd)).and_then(|script| {
                    if self
                        .opts
                        .executor
                        .as_ref()
                        .is_some_and(|host| host.verify_shard_runner())
                    {
                        crate::shard::adapters::guard_version(&ts.runner, script)
                    } else {
                        Ok(script)
                    }
                }) {
                    Ok(sc) => sc,
                    Err(e) => {
                        push(&mut steps, Outcome::Error(e.clone()), None, None, None);
                        errored.get_or_insert(format!("{label}: {e}"));
                        continue;
                    }
                },
                None => script,
            };
            let files_name = if self.pinned.is_some() {
                self.resource_name()
            } else {
                self.seq.fetch_add(1, Ordering::SeqCst).to_string()
            };
            let files_dir = self.tools.join("files").join(files_name);
            let _ = fs::create_dir_all(&files_dir);
            {
                use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
                let _ = fs::set_permissions(&files_dir, fs::Permissions::from_mode(0o700));
                for f in ["output", "env", "path", "summary"] {
                    let _ = OpenOptions::new()
                        .write(true)
                        .create(true)
                        .truncate(true)
                        .mode(0o600)
                        .open(files_dir.join(f));
                }
            }
            let fc = |name: &str| files_dir.join(name);
            let gh = scm["github"].clone();
            let mut env: Vec<(String, String)> = self.base_env(&gh, &extra_path);
            env.extend(port_env.iter().cloned());
            env.push((
                "GITHUB_OUTPUT".into(),
                fc("output").to_string_lossy().into_owned(),
            ));
            env.push((
                "GITHUB_ENV".into(),
                fc("env").to_string_lossy().into_owned(),
            ));
            env.push((
                "GITHUB_PATH".into(),
                fc("path").to_string_lossy().into_owned(),
            ));
            env.push((
                "GITHUB_STEP_SUMMARY".into(),
                fc("summary").to_string_lossy().into_owned(),
            ));
            env.push(("COMPOSE_PROJECT_NAME".into(), compose_default.clone()));
            let from_env = env_now
                .get("COMPOSE_PROJECT_NAME")
                .map(expr::to_string)
                .filter(|p| !p.is_empty());
            for p in compose_projects(&script) {
                if !projects.contains(&p) {
                    if exclusive && p.ends_with(&format!("-{tag}")) {
                        self.ctx.cancel.track_compose(p.clone());
                    } else {
                        self.ctx.cancel.track_unverified_compose(p.clone());
                    }
                    projects.push(p);
                }
            }
            if let Some(project) = from_env {
                // An external override is not proof of this entry's namespace.
                // Never down that project based only on the supplied name.
                self.ctx.cancel.track_unverified_compose(project.clone());
                if !projects.contains(&project) {
                    projects.push(project);
                }
            }
            // The job's share of the CPU, for the tools that read it. What the
            // caller, the workflow, the job or the step says stays.
            if let Some(threads) = self.job_threads {
                for k in crate::cpu::JOB_THREAD_ENV {
                    if self.ctx.var(k).is_none_or(|v| v.is_empty()) && !env_now.contains_key(k) {
                        env.push((k.into(), threads.to_string()));
                    }
                }
            }
            for (k, v) in &env_now {
                env.push((k.clone(), expr::to_string(v)));
            }
            let log = self.log_path(&w.file, &display, n + 1, &label);
            // The job's time is used up by its running, not by its steps
            // waiting for task-traffic-controller: a step's own timeout starts when it
            // gets its turn, and so does the job's share of it.
            let remaining = job_timeout.saturating_sub(t0.elapsed().saturating_sub(queue));
            if remaining.is_zero() {
                // nothing is left: a step started now would be stopped at once
                let _ = fs::remove_dir_all(&files_dir);
                push(
                    &mut steps,
                    Outcome::Error(format!("not started: the job timed out ({job_min} min)")),
                    None,
                    None,
                    None,
                );
                record(&mut steps_ctx, &s.id, "failure", "failure", Map::new());
                errored.get_or_insert(format!("{label}: the job timed out"));
                continue;
            }
            let own = s.timeout_minutes.map(|m| Duration::from_secs_f64(m * 60.0));
            // stopped at the job's limit, not at the step's own
            let by_job = own.is_none_or(|t| remaining < t);
            let timeout = own.map_or(remaining, |t| t.min(remaining));
            let key = crate::demand::history_key(
                &self.fp.config.default_workflows_dir,
                &w.file,
                &job.id,
                &label,
            );
            let pkg = fs::read_to_string(ws.join(&wd).join("package.json")).ok();
            if writes_node_modules(&plan::with_scripts(&script, pkg.as_deref())) {
                if let Err(e) = crate::git::own_node_modules(self.ctx, ws) {
                    let e = format!("cannot copy node_modules: {e:#}");
                    push(&mut steps, Outcome::Error(e.clone()), None, None, None);
                    errored.get_or_insert(format!("{label}: {e}"));
                    continue;
                }
            }
            let res = self
                .shell(
                    &native_scope,
                    &ws.join(&wd),
                    &script,
                    step_shell,
                    &env,
                    Some(timeout),
                    &log,
                    Some(key),
                    &run_label(
                        &w.name,
                        &display,
                        &if s.name.is_some() {
                            label.clone()
                        } else {
                            format!("step {}", n + 1)
                        },
                    ),
                    piped,
                    self.job_threads,
                )
                .map(|(exit, queued)| {
                    queue += queued;
                    exit
                });
            if let Some(t) = self.ctx.github_token_if_fetched() {
                mask_in_file(&log, t);
            }
            let read = |f: &str| fs::read_to_string(fc(f)).unwrap_or_default();
            let mut outputs = Map::new();
            // Later steps of the job get the value, as on GitHub; it is in
            // memory only (the files are gone below). What leaves the job
            // is checked at the job's outputs.
            for (k, v) in parse_file_command(&read("output")) {
                outputs.insert(k, Value::String(v));
            }
            extra_env.extend(parse_file_command(&read("env")));
            extra_path.extend(
                read("path")
                    .lines()
                    .filter(|l| !l.trim().is_empty())
                    .map(String::from),
            );
            let _ = fs::remove_dir_all(&files_dir);
            match res {
                Ok(Exit::Code(0)) => {
                    push(&mut steps, Outcome::Pass, Some(0), Some(log), None);
                    record(&mut steps_ctx, &s.id, "success", "success", outputs);
                }
                Ok(Exit::Code(c)) => {
                    let ce = s.continue_on_error;
                    push(
                        &mut steps,
                        Outcome::Fail,
                        Some(c),
                        Some(log),
                        if ce {
                            Some("continue-on-error".into())
                        } else {
                            None
                        },
                    );
                    record(
                        &mut steps_ctx,
                        &s.id,
                        "failure",
                        if ce { "success" } else { "failure" },
                        outputs,
                    );
                    if !ce {
                        failed = true;
                    }
                }
                Ok(Exit::Timeout) => {
                    push(
                        &mut steps,
                        Outcome::Error(if by_job {
                            // under 10 seconds with a decimal: never "after 0s"
                            let left = if timeout < Duration::from_secs(10) {
                                format!("{:.1}", timeout.as_secs_f64())
                            } else {
                                timeout.as_secs().to_string()
                            };
                            format!(
                                "timed out after {left}s (what was left of the job's {job_min} min)"
                            )
                        } else {
                            format!("timed out after {}s", timeout.as_secs())
                        }),
                        None,
                        Some(log),
                        None,
                    );
                    record(&mut steps_ctx, &s.id, "failure", "failure", outputs);
                    errored.get_or_insert(format!("{label}: timed out"));
                }
                Ok(Exit::Cancelled) => {
                    push(
                        &mut steps,
                        Outcome::Error("cancelled".into()),
                        None,
                        Some(log),
                        None,
                    );
                    if errored.is_none() {
                        errored = Some("cancelled".into());
                        cancelled = true;
                    }
                }
                Err(e) => {
                    push(
                        &mut steps,
                        Outcome::Error(format!("{e:#}")),
                        None,
                        Some(log),
                        None,
                    );
                    errored.get_or_insert(format!("{label}: {e:#}"));
                }
            }
        }
        // A surviving script must not recreate daemon resources after cleanup.
        drop(native_scope);
        self.stop_services(&names, &mut steps);
        let cleanup = self.ctx.cancel.cleanup_projects(self.ctx, &projects);
        self.record_cleanup_warnings(&mut steps, cleanup);

        // job outputs
        let mut outputs = Map::new();
        let mut ocm = cm.clone();
        ocm.insert("steps".into(), Value::Object(steps_ctx));
        let octx = Ctx::new(&ocm, Status::Success);
        let mut dropped = Vec::new();
        for (k, v) in &job.outputs {
            if let Ok(val) = expr::interpolate(v, &octx) {
                // GitHub does not pass a job output that holds a secret on
                // to the jobs that need it, and nor does this
                if self
                    .ctx
                    .github_token_if_fetched()
                    .is_some_and(|t| !t.is_empty() && val.contains(t))
                {
                    dropped.push(k.clone());
                    // empty, which is what a name nobody set expands to; the
                    // key stays, because a plan expects the job to have set it
                    outputs.insert(k.clone(), Value::String(String::new()));
                    continue;
                }
                outputs.insert(k.clone(), Value::String(val));
            }
        }
        if !dropped.is_empty() {
            let note = format!(
                "job output {} holds the GitHub token: not passed on",
                dropped.join(", ")
            );
            // on the last step: a result has as many steps as the plan has
            if let Some(last) = steps.last_mut() {
                last.note = Some(match last.note.take() {
                    Some(n) => format!("{n}; {note}"),
                    None => note,
                });
            }
        }
        let outcome = if failed {
            Outcome::Fail
        } else if let Some(e) = errored {
            Outcome::Error(e)
        } else if stopped {
            Outcome::Skip("fail-fast: another entry failed".into())
        } else {
            Outcome::Pass
        };
        // A job that passed leaves its `target/` for the next one with the
        // same key. The notes go on the last step: a result has as many steps as
        // the plan has.
        let mut build_cache = None;
        if let Some(b) = bc.as_mut() {
            if b.active && matches!(outcome, Outcome::Pass) {
                self.build_cache_save(b, ws);
            }
            if let Some(last) = steps.last_mut() {
                for n in &b.notes {
                    last.note = Some(match last.note.take() {
                        Some(o) => format!("{o}; {n}"),
                        None => n.clone(),
                    });
                }
            }
            build_cache = b.active.then(|| b.stat.clone());
        }
        let mut result = finish(outcome, steps, t0);
        result.build_cache = build_cache;
        result.cancelled = cancelled && matches!(result.outcome, Outcome::Error(_));
        result.time = Some(JobTime {
            work_secs: (result.secs - queue.as_secs_f64()).max(0.0),
            wait_queue_secs: queue.as_secs_f64(),
            requested_at_ms: started_at_ms,
            started_at_ms,
            finished_at_ms: now_ms().max(started_at_ms),
            ..JobTime::default()
        });
        (result, outputs)
    }

    /// Fill `<ws>/target` from the build cache, if the job is one the cache
    /// is for: a Rust workspace, with the cache on. Never fails the job.
    fn build_cache_start(
        &self,
        ws: &Path,
        w: &Workflow,
        job: &Job,
        cm: &Map<String, Value>,
        env_ctx: &Map<String, Value>,
    ) -> Option<BuildCacheRun> {
        use crate::build_cache as bc;
        let s = self.build_cache.as_ref()?;
        if !bc::applies(ws) {
            return None;
        }
        let mut vars: Vec<(String, String)> = self
            .ctx
            .env()
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        vars.extend(env_ctx.iter().map(|(k, v)| (k.clone(), expr::to_string(v))));
        // the steps' own variables, as they are when the step runs (a step
        // that reads the output of an earlier one is not seen by the key)
        for st in &job.steps {
            // only the variables that reach the build are evaluated
            let own: Vec<(String, String)> = st
                .env
                .iter()
                .filter(|(k, _)| bc::affects_build(k))
                .cloned()
                .collect();
            if own.is_empty() {
                continue;
            }
            let mut into = env_ctx.clone();
            if let Err(e) = Self::eval_env(self.ctx, &own, cm, &mut into, &[]) {
                return Some(BuildCacheRun::off(format!(
                    "build cache: skipped (env of a step: {e:#})"
                )));
            }
            vars.extend(
                own.iter()
                    .filter_map(|(k, _)| Some((k.clone(), expr::to_string(into.get(k)?)))),
            );
        }
        let env = bc::build_env(vars.iter().map(|(k, v)| (k.as_str(), v.as_str())), ws);
        if bc::moves_target(&env) {
            return None;
        }
        let (rustc, cargo) = match bc::toolchain(self.ctx, ws, &self.base_path, s.probe_timeout) {
            Ok(t) => t,
            Err(why) => {
                return Some(BuildCacheRun::off(format!(
                    "build cache: skipped (toolchain: {why})"
                )))
            }
        };
        let inputs = bc::KeyInputs {
            rustc,
            cargo,
            os_arch: bc::os_arch(),
            locks: bc::lock_digests(ws),
            job: format!("{}#{}", w.file, job.id),
            env,
            files: bc::config_digests(ws),
            matrix: cm.get("matrix").map(|m| m.to_string()).unwrap_or_default(),
        };
        let key = bc::key(&inputs);
        let mut run = BuildCacheRun {
            inputs,
            stat: bc::JobCache {
                key: key[..12].to_string(),
                ..Default::default()
            },
            key,
            notes: Vec::new(),
            active: true,
        };
        let t = Instant::now();
        match bc::restore(self.ctx, s, &run.key, ws) {
            bc::Restore::Restored => {
                run.stat.restored = true;
                run.notes.push(format!(
                    "build cache: restored {} in {:.1}s",
                    run.stat.key,
                    t.elapsed().as_secs_f64()
                ));
            }
            bc::Restore::Miss => {}
            bc::Restore::Skipped(why) => {
                run.notes.push(format!("build cache: not restored ({why})"))
            }
        }
        Some(run)
    }

    /// Add the job's `target/` to the build cache, and prune the cache. Never fails the job.
    fn build_cache_save(&self, run: &mut BuildCacheRun, ws: &Path) {
        use crate::build_cache as bc;
        let Some(s) = self.build_cache.as_ref() else {
            return;
        };
        let t = Instant::now();
        let seq = self.seq.fetch_add(1, Ordering::SeqCst);
        match bc::save_with(self.ctx, s, &run.key, ws, seq, Some(&run.inputs)) {
            bc::Save::Saved => {
                run.stat.saved = true;
                run.notes.push(format!(
                    "build cache: saved {} in {:.1}s",
                    run.stat.key,
                    t.elapsed().as_secs_f64()
                ));
                let pruned = bc::prune(self.ctx, s, Some(&run.key));
                if pruned.evicted_keep {
                    run.stat.saved = false;
                }
                for w in pruned.warnings {
                    run.notes.push(format!("build cache: {w}"));
                }
            }
            bc::Save::Exists => {}
            bc::Save::Skipped(why) => run.notes.push(format!("build cache: not saved ({why})")),
        }
    }

    /// `uses:` steps: version checks for setup actions, skips for the rest.
    fn check_action(
        &self,
        uses: &str,
        s: &Step,
        cm: &Map<String, Value>,
    ) -> (Outcome, Option<String>) {
        let name = uses.split('@').next().unwrap_or(uses).to_ascii_lowercase();
        let ctx = Ctx::new(cm, Status::Success).with_token(self.ctx);
        let with = |k: &str| {
            s.with
                .iter()
                .find(|(n, _)| n == k)
                .and_then(|(_, v)| expr::interpolate(v, &ctx).ok())
                .filter(|v| !v.is_empty())
        };
        let tool = |bin: &str, args: &[&str]| -> Option<String> {
            let out = self.ctx.command(bin).args(args).output().ok()?;
            let text = String::from_utf8_lossy(&out.stdout).to_string()
                + &String::from_utf8_lossy(&out.stderr);
            out.status
                .success()
                .then(|| text.lines().next().unwrap_or("").trim().to_string())
        };
        let check = |bin: &str, args: &[&str], want: Option<String>| -> (Outcome, Option<String>) {
            match tool(bin, args) {
                None => (Outcome::Error(format!("`{bin}` not found")), None),
                Some(have) => {
                    let have_v = have.trim_start_matches(|c: char| !c.is_ascii_digit());
                    let note = match want {
                        Some(w)
                            if !have_v
                                .starts_with(w.trim_start_matches('v').trim_end_matches(".x")) =>
                        {
                            Some(format!("wants {w}, have {have}"))
                        }
                        _ => Some(have),
                    };
                    (Outcome::Pass, note)
                }
            }
        };
        let version_file = |key: &str| {
            with(key)
                .and_then(|f| fs::read_to_string(self.wt.join(f)).ok())
                .map(|t| t.trim().to_string())
        };
        match name.as_str() {
            "actions/checkout" => (Outcome::Skip("checkout".into()), None),
            "actions/setup-node" => check(
                "node",
                &["--version"],
                with("node-version").or_else(|| version_file("node-version-file")),
            ),
            "actions/setup-python" => check(
                "python3",
                &["--version"],
                with("python-version").or_else(|| version_file("python-version-file")),
            ),
            "actions/setup-go" => check("go", &["version"], None),
            "actions/setup-java" => check("java", &["-version"], None),
            "ruby/setup-ruby" => check("ruby", &["--version"], with("ruby-version")),
            "subosito/flutter-action" => check("flutter", &["--version"], with("flutter-version")),
            "dart-lang/setup-dart" => check("dart", &["--version"], None),
            n if n.starts_with("dtolnay/rust-toolchain") => check(
                "cargo",
                &["--version"],
                with("toolchain").filter(|t| t.starts_with(|c: char| c.is_ascii_digit())),
            ),
            n if n.starts_with("actions/cache") || n.ends_with("/rust-cache") => {
                (Outcome::Skip("cache".into()), None)
            }
            n if n.contains("upload-artifact") || n.contains("download-artifact") => {
                (Outcome::Skip("artifact".into()), None)
            }
            _ => (Outcome::Skip(format!("action {uses}")), None),
        }
    }

    /// An `actions/upload-artifact@v4` or `actions/download-artifact@v4` step
    /// of this run (see [`crate::artifact_io`]).
    #[allow(clippy::too_many_arguments)]
    fn artifact_step(
        &self,
        ws: &Path,
        w: &Workflow,
        job: &Job,
        display: &str,
        step_index: usize,
        s: &Step,
        cm: &Map<String, Value>,
        kind: artifact::Kind,
    ) -> (Outcome, Option<String>) {
        let ctx = Ctx::new(cm, Status::Success).with_token(self.ctx);
        let mut with = Vec::new();
        for (k, v) in &s.with {
            match expr::interpolate(v, &ctx) {
                Ok(x) => with.push((k.clone(), x)),
                Err(e) => return (Outcome::Error(format!("with.{k}: {e:#}")), None),
            }
        }
        let area = artifact_io::Area::of_run(&self.run_dir, &self.fp.digest, &w.file);
        let node = dag::node_id(&w.file, &job.id);
        let mut holding = self
            .fp
            .tasks
            .iter()
            .filter(|t| t.workflow == w.file && t.jobs.contains(&job.id));
        let task = match (holding.next(), holding.next()) {
            (Some(t), None) => Some(t.id.clone()),
            _ => None,
        };
        let who = artifact_io::Who {
            job: node,
            display: display.to_string(),
            task,
        };
        let request = crate::ArtifactRequest {
            kind,
            area: &area,
            who: &who,
            workflow: &w.file,
            workspace: ws,
            with: &with,
            step_index,
            variant: job
                .matrix
                .as_ref()
                .and_then(|_| cm.get("strategy"))
                .and_then(|s| s.get("job-index"))
                .and_then(Value::as_u64),
            cancel: &self.ctx.cancel,
        };
        let done = match self.opts.executor.as_deref() {
            Some(host) => {
                artifact::validate_run(kind, &with).and_then(|()| host.artifact(&request))
            }
            None => request.run_local(),
        };
        match done {
            Ok(note) => {
                // a step pinned to a commit runs as v4, and says so
                let note = match s.uses.as_deref().and_then(artifact::pin_warning) {
                    Some(w) => format!("{w}; {note}"),
                    None => note,
                };
                (Outcome::Pass, Some(note))
            }
            Err(e) => (Outcome::Error(e), None),
        }
    }

    fn docker_ok(&self) -> Result<(), String> {
        self.docker_ok
            .get_or_init(|| {
                self.docker(
                    &["info", "--format", "{{.ServerVersion}}"],
                    Duration::from_secs(30),
                )
                .map(|_| ())
                .map_err(|error| format!("{error:#}"))
            })
            .clone()
    }

    fn docker(&self, args: &[&str], timeout: Duration) -> Result<String> {
        let output = crate::cleanup::docker_control(self.ctx, args, timeout)?;
        Ok(String::from_utf8_lossy(&output).trim().to_string())
    }

    fn start_services(
        &self,
        w: &Workflow,
        job: &Job,
        cm: &Map<String, Value>,
        names: &mut Vec<String>,
    ) -> Result<(Vec<PortMap>, Map<String, Value>)> {
        self.docker_ok()
            .map_err(|e| anyhow!("docker is not available ({e})"))?;
        let ctx = Ctx::new(cm, Status::Success);
        let mut maps = Vec::new();
        let mut sctx = Map::new();
        for svc in &job.services {
            let image = expr::interpolate(&svc.image, &ctx)?;
            if self
                .docker(&["image", "inspect", &image], Duration::from_secs(30))
                .is_err()
            {
                self.docker(&["pull", "--quiet", &image], Duration::from_secs(600))
                    .with_context(|| format!("pull {image}"))?;
            }
            let name = self.resource_name();
            let mut args: Vec<String> = vec![
                "run".into(),
                "-d".into(),
                "--name".into(),
                name.clone(),
                "--label".into(),
                "local-ci=1".into(),
            ];
            for (k, v) in &svc.env {
                args.push("-e".into());
                args.push(format!("{k}={}", expr::interpolate(v, &ctx)?));
            }
            for (d, c) in &svc.ports {
                args.push("-p".into());
                args.push(match d {
                    // nothing to rewrite: the code finds the service by this port
                    Some(h) if !rewritable_mention(w, job, *h) => format!("127.0.0.1:{h}:{c}"),
                    _ => format!("127.0.0.1::{c}"),
                });
            }
            let opts = expr::interpolate(&svc.options, &ctx)?;
            args.extend(
                shlex::split(&opts).ok_or_else(|| anyhow!("cannot parse options `{opts}`"))?,
            );
            args.push(image.clone());
            let refs: Vec<&str> = args.iter().map(String::as_str).collect();
            self.ctx.cancel.creation_started(name.clone());
            let id = self.docker(&refs, Duration::from_secs(120))?;
            ensure_container_id(&id)?;
            self.ctx.cancel.creation_acknowledged(&name, id.clone());
            names.push(id.clone());
            let mut ports = Map::new();
            for (d, c) in &svc.ports {
                let line =
                    self.docker(&["port", &id, &format!("{c}/tcp")], Duration::from_secs(30))?;
                let actual: u16 = line
                    .lines()
                    .next()
                    .and_then(|l| l.rsplit(':').next())
                    .and_then(|p| p.trim().parse().ok())
                    .ok_or_else(|| anyhow!("no host port for {c}"))?;
                ports.insert(c.to_string(), Value::String(actual.to_string()));
                maps.push(PortMap {
                    declared: *d,
                    container: *c,
                    actual,
                });
            }
            self.wait_healthy(&id, svc, &maps)?;
            sctx.insert(
                svc.id.clone(),
                json!({"id": id, "ports": ports, "network": ""}),
            );
        }
        Ok((maps, sctx))
    }

    fn wait_healthy(&self, name: &str, svc: &Service, maps: &[PortMap]) -> Result<()> {
        let has_health = svc.options.contains("--health-cmd");
        let t0 = Instant::now();
        let limit = Duration::from_secs(180);
        loop {
            if self.ctx.cancel.is_cancelled() {
                bail!("cancelled");
            }
            let state = self.docker(&["inspect", "-f", "{{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}", name], Duration::from_secs(30))?;
            let mut parts = state.split_whitespace();
            let (run, health) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""));
            if run == "exited" || run == "dead" {
                let logs = self
                    .docker(&["logs", "--tail", "15", name], Duration::from_secs(30))
                    .map(|logs| self.hide_token(logs))
                    .unwrap_or_else(|error| format!("diagnostic logs unavailable: {error:#}"));
                bail!("service {} exited:\n{}", svc.id, logs.trim());
            }
            if has_health {
                if health == "healthy" {
                    return Ok(());
                }
                if health == "unhealthy" {
                    bail!("service {} is unhealthy", svc.id);
                }
            } else {
                let mine: Vec<&PortMap> = maps
                    .iter()
                    .filter(|m| svc.ports.iter().any(|(_, c)| *c == m.container))
                    .collect();
                if run == "running"
                    && mine.iter().all(|m| {
                        std::net::TcpStream::connect_timeout(
                            &([127, 0, 0, 1], m.actual).into(),
                            Duration::from_secs(1),
                        )
                        .is_ok()
                    })
                {
                    return Ok(());
                }
            }
            if t0.elapsed() > limit {
                bail!("service {} not ready after {}s", svc.id, limit.as_secs());
            }
            std::thread::sleep(Duration::from_millis(1000));
        }
    }

    fn record_cleanup_warnings(
        &self,
        steps: &mut [StepResult],
        cleanup: Vec<crate::cleanup::CleanupIncomplete>,
    ) {
        for diagnostic in cleanup {
            let warning = format!("warning: {diagnostic}");
            // Cleanup is reported separately from test/check outcomes. A
            // default Compose project is tracked even by Docker-free jobs;
            // probing it must not introduce a Docker dependency for them.
            eprintln!("local-ci: {warning}");
            if let Some(last) = steps.last_mut() {
                last.note = Some(match last.note.take() {
                    Some(note) => format!("{note}; {warning}"),
                    None => warning,
                });
            }
        }
    }

    fn stop_services(&self, names: &[String], steps: &mut [StepResult]) {
        let diagnostics = crate::cleanup::remove_tracked_containers(self.ctx, names);
        if diagnostics.is_empty() {
            let set: HashSet<&String> = names.iter().collect();
            self.ctx.cancel.untrack_containers(&set);
        }
        self.record_cleanup_warnings(steps, diagnostics);
    }
}

/// A pipe for a script that holds the token, made so that neither end is ever
/// open without close-on-exec, so that no command started by another thread
/// can inherit an end (the write end, or the read end with the rest of the
/// script). The write end is non-blocking (see `write_until_stopped`); the
/// read end blocks, as the shell reads with plain blocking reads.
///
/// macOS: `std::io::pipe` is `pipe()` and then `fcntl(FD_CLOEXEC)`, two calls
/// with a window between them, so a FIFO is used: it is opened with
/// `O_CLOEXEC` in the call itself, and its name is removed as soon as both
/// ends are open. A FIFO is not used elsewhere: on Linux, opening
/// `/dev/fd/3` opens the FIFO again through `/proc/self/fd/3`, and a blocking
/// `O_RDONLY` open of a FIFO waits for a writer; a small script is written
/// and the write end closed before the shell starts, so the shell would wait
/// for ever.
#[cfg(target_os = "macos")]
fn script_pipe(path: &Path) -> Result<(File, File)> {
    use std::os::fd::FromRawFd;
    use std::os::unix::ffi::OsStrExt;
    let c = std::ffi::CString::new(path.as_os_str().as_bytes())?;
    let _ = fs::remove_file(path);
    // SAFETY: plain libc calls on a NUL-terminated path; the descriptors are
    // handed to `File`, which owns them from then on.
    unsafe {
        if libc::mkfifo(c.as_ptr(), 0o600) < 0 {
            return Err(std::io::Error::last_os_error()).context("cannot make the script pipe");
        }
        let r = libc::open(
            c.as_ptr(),
            libc::O_RDONLY | libc::O_NONBLOCK | libc::O_CLOEXEC,
        );
        let r_err = std::io::Error::last_os_error();
        let w = if r >= 0 {
            libc::open(
                c.as_ptr(),
                libc::O_WRONLY | libc::O_NONBLOCK | libc::O_CLOEXEC,
            )
        } else {
            -1
        };
        let w_err = std::io::Error::last_os_error();
        let _ = libc::unlink(c.as_ptr());
        if r < 0 || w < 0 {
            if r >= 0 {
                libc::close(r);
            }
            if w >= 0 {
                libc::close(w);
            }
            return Err(if r < 0 { r_err } else { w_err }).context("cannot open the script pipe");
        }
        // the shell reads with plain blocking reads
        let fl = libc::fcntl(r, libc::F_GETFL);
        if fl < 0 || libc::fcntl(r, libc::F_SETFL, fl & !libc::O_NONBLOCK) < 0 {
            let e = std::io::Error::last_os_error();
            libc::close(r);
            libc::close(w);
            return Err(e).context("cannot set up the script pipe");
        }
        Ok((File::from_raw_fd(r), File::from_raw_fd(w)))
    }
}

/// Linux and the other unixes: an anonymous pipe. The standard library makes
/// it with `pipe2(O_CLOEXEC)` on Linux, the BSDs and the like (one call, so
/// there is no window; see `library/std/src/sys/pal/unix/pipe.rs` in the
/// Rust source, and `strace -e trace=pipe2` on a program that calls
/// `std::io::pipe`).
#[cfg(not(target_os = "macos"))]
fn script_pipe(_path: &Path) -> Result<(File, File)> {
    use std::os::fd::{AsRawFd, OwnedFd};
    let (r, w) = std::io::pipe().context("cannot make the script pipe")?;
    let w = File::from(OwnedFd::from(w));
    // SAFETY: fcntl on a descriptor `w` owns. The write end is its own open
    // file description, so this does not touch the read end.
    unsafe {
        let fl = libc::fcntl(w.as_raw_fd(), libc::F_GETFL);
        if fl < 0 || libc::fcntl(w.as_raw_fd(), libc::F_SETFL, fl | libc::O_NONBLOCK) < 0 {
            return Err(std::io::Error::last_os_error()).context("cannot set up the script pipe");
        }
    }
    Ok((File::from(OwnedFd::from(r)), w))
}

/// Write `data` to the non-blocking `w`, until it is all written, the other
/// end is closed, or `stop` is set (the step is over). A reader that outlives
/// its step (a background process that kept the descriptor) cannot keep this
/// thread blocked in `write`.
fn write_until_stopped(mut w: File, data: &[u8], stop: &AtomicBool) {
    let mut rest = data;
    while !rest.is_empty() && !stop.load(Ordering::SeqCst) {
        match w.write(rest) {
            Ok(0) => return,
            Ok(n) => rest = &rest[n..],
            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                std::thread::sleep(Duration::from_millis(5))
            }
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
            Err(_) => return,
        }
    }
}

/// Write a file only its owner can read: step scripts may hold values that
/// must not be shared.
fn write_private(path: &Path, content: &str) -> std::io::Result<()> {
    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
    let mut f = OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .mode(0o600)
        .open(path)?;
    fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
    f.write_all(content.as_bytes())
}

/// What the OS legs say of one entry of a matrix.
struct OsLeg {
    /// the OS its `runs-on` names, with the label
    os: Option<(os_legs::Family, String)>,
    /// the name of the entry of the host's OS that stands in for it
    twin: Option<String>,
}

fn record(
    ctx: &mut Map<String, Value>,
    id: &Option<String>,
    outcome: &str,
    conclusion: &str,
    outputs: Map<String, Value>,
) {
    if let Some(id) = id {
        ctx.insert(
            id.clone(),
            json!({"outcome": outcome, "conclusion": conclusion, "outputs": outputs}),
        );
    }
}

pub fn write_json(path: &Path, v: &impl Serialize) -> Result<()> {
    let mut f = File::create(path)?;
    f.write_all(serde_json::to_string_pretty(v)?.as_bytes())?;
    Ok(())
}

fn ensure_container_id(id: &str) -> Result<()> {
    anyhow::ensure!(
        crate::cleanup::valid_container_id(id),
        "Docker did not acknowledge a complete container ID"
    );
    Ok(())
}

#[cfg(test)]
pub(crate) mod finalization_test {
    type Probe = Box<dyn FnMut(&str)>;
    std::thread_local! {
        static PROBE: std::cell::RefCell<Option<Probe>> = const { std::cell::RefCell::new(None) };
    }
    pub(crate) fn inspect(boundary: &str) {
        PROBE.with_borrow_mut(|probe| {
            if let Some(probe) = probe {
                probe(boundary);
            }
        });
    }
    pub(crate) fn observe<T>(probe: impl FnMut(&str) + 'static, action: impl FnOnce() -> T) -> T {
        struct Reset;
        impl Drop for Reset {
            fn drop(&mut self) {
                PROBE.with_borrow_mut(|probe| *probe = None);
            }
        }
        PROBE.with_borrow_mut(|slot| {
            assert!(slot.is_none());
            *slot = Some(Box::new(probe));
        });
        let _reset = Reset;
        action()
    }
}

#[cfg(test)]
#[allow(clippy::disallowed_methods)] // tests build their own commands
mod tests {
    use super::*;
    use std::process::Command;

    #[test]
    fn fresh_git_runners_share_process_resource_sequence() {
        let area = tempfile::Builder::new()
            .prefix("localci-resource-sequence-")
            .tempdir_in(fs::canonicalize(std::env::temp_dir()).unwrap())
            .unwrap();
        let root = area.path();
        fs::create_dir_all(root.join(".github/workflows")).unwrap();
        fs::write(root.join(".github/workflows/ci.yml"),
            "on: push\njobs:\n  check:\n    runs-on: fixture\n    steps:\n      - run: echo fixture\n").unwrap();
        for args in [
            vec!["init", "-q", "-b", "main"],
            vec!["add", "."],
            vec!["commit", "-qm", "fixture"],
        ] {
            let status = Command::new("/usr/bin/git")
                .args([
                    "-c",
                    "user.name=fixture",
                    "-c",
                    "user.email=fixture@example.invalid",
                    "-c",
                    "commit.gpgsign=false",
                ])
                .args(args)
                .current_dir(root)
                .env_clear()
                .env("PATH", "/usr/bin:/bin")
                .env("HOME", root)
                .env("GIT_CONFIG_NOSYSTEM", "1")
                .env("GIT_CONFIG_GLOBAL", "/dev/null")
                .status()
                .unwrap();
            assert!(status.success());
        }
        let ctx = ExecContext::new(
            [
                ("PATH".into(), "/usr/bin:/bin".into()),
                ("HOME".into(), root.display().to_string()),
            ]
            .into(),
        );
        let other_ctx = ctx.fresh_attempt();
        let fp = crate::build_frozen_plan(
            &ctx,
            &crate::Target {
                dir: root.into(),
                sha: "HEAD".into(),
                base: Some("HEAD".into()),
                all: true,
                include_disabled: true,
                workflows_dirs: vec![],
                workflows: vec![],
                jobs: vec![],
            },
            &mut crate::Quiet,
        )
        .unwrap();
        let workspace = |name: &str| Workspace {
            root: root.join(name),
            repo_root: root.into(),
            run_dir: root.join(format!("{name}-run")),
            tools: root.join(format!("{name}-tools")),
            lock_file: root.join(format!("{name}-lock")),
        };
        let opts = || Opts {
            parallel: 1,
            traffic_controller: None,
            executor: None,
            portool: None,
            containers: 1,
            job_timeout_min: 1.,
            keep: false,
            trash: root.join("trash"),
            all_os_legs: false,
        };
        let a = Runner::new(&ctx, &fp, &workspace("one"), opts()).unwrap();
        let b = Runner::new(&other_ctx, &fp, &workspace("two"), opts()).unwrap();
        let names = [a.resource_name(), b.resource_name(), a.resource_name()];
        assert_eq!(names.iter().collect::<HashSet<_>>().len(), 3, "{names:?}");
        assert!(Arc::ptr_eq(&a.seq, &b.seq));
        let prefix = format!("local-ci-{}-", std::process::id());
        let values: Vec<usize> = names
            .iter()
            .map(|n| n.strip_prefix(&prefix).unwrap().parse().unwrap())
            .collect();
        assert!(values.windows(2).all(|v| v[0] < v[1]));
        assert_ne!(a.wt, b.wt);
        assert_ne!(a.run_dir, b.run_dir);
    }

    #[test]
    fn run_label_plain() {
        assert_eq!(
            run_label("CI", "build", "Run tests"),
            "CI / build / Run tests"
        );
    }

    #[test]
    fn run_label_matrix_job() {
        assert_eq!(
            run_label("CI", "test (ubuntu, 20)", "step 3"),
            "CI / test (ubuntu, 20) / step 3"
        );
    }

    #[test]
    fn run_label_unnamed_step() {
        assert_eq!(run_label("CI", "lint", "step 8"), "CI / lint / step 8");
    }

    #[test]
    fn run_label_truncates_step_first() {
        let l = run_label("CI", "build", &"x".repeat(200));
        assert_eq!(l.chars().count(), RUN_LABEL_MAX);
        assert!(l.starts_with("CI / build / xxx"));
        assert!(l.ends_with('…'));
    }

    #[test]
    fn run_label_long_front_is_cut_and_one_line() {
        let l = run_label(&"w".repeat(80), &"j".repeat(80), "a\nb");
        assert_eq!(l.chars().count(), RUN_LABEL_MAX);
        assert_eq!(run_label("CI", "j", "a\n  b"), "CI / j / a b");
    }

    #[test]
    // What this checks: the ends of the pipe carry close-on-exec, the write end is
    // non-blocking and the read end blocks, no name is left behind, and what is
    // written can be read back. It does NOT check that no other thread's exec can
    // inherit an end: that window (between `pipe()` and `fcntl` on macOS) cannot
    // be hit from a test, so it is closed by construction (a FIFO opened with
    // `O_CLOEXEC` on macOS, `pipe2(O_CLOEXEC)` through std elsewhere) and reviewed
    // in `script_pipe`, not tested.
    fn the_script_pipe_has_cloexec_a_nonblocking_writer_and_no_name_left() {
        use std::os::fd::AsRawFd;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("p.fifo");
        let (r, w) = script_pipe(&path).unwrap();
        assert!(!path.exists());
        for f in [&r, &w] {
            let fl = unsafe { libc::fcntl(f.as_raw_fd(), libc::F_GETFD) };
            assert!(fl >= 0 && fl & libc::FD_CLOEXEC != 0, "{fl}");
        }
        // the read end blocks, the write end does not
        let (rl, wl) = unsafe {
            (
                libc::fcntl(r.as_raw_fd(), libc::F_GETFL),
                libc::fcntl(w.as_raw_fd(), libc::F_GETFL),
            )
        };
        assert_eq!(rl & libc::O_NONBLOCK, 0);
        assert_ne!(wl & libc::O_NONBLOCK, 0);
        let mut r = r;
        let stop = AtomicBool::new(false);
        write_until_stopped(w, b"abc", &stop);
        let mut got = String::new();
        r.read_to_string(&mut got).unwrap();
        assert_eq!(got, "abc");
    }

    #[test]
    fn the_writer_ends_with_the_step_even_if_a_reader_outlives_it() {
        let dir = tempfile::tempdir().unwrap();
        let (r, w) = script_pipe(&dir.path().join("p.fifo")).unwrap();
        let stop = Arc::new(AtomicBool::new(false));
        let big = vec![b'x'; 4 << 20];
        let s2 = stop.clone();
        let h = std::thread::spawn(move || write_until_stopped(w, &big, &s2));
        // nobody reads: the pipe fills and the writer waits
        std::thread::sleep(Duration::from_millis(300));
        assert!(!h.is_finished());
        stop.store(true, Ordering::SeqCst);
        let t = Instant::now();
        h.join().unwrap();
        assert!(t.elapsed() < Duration::from_secs(2));
        // `r` was held the whole time, as a background process would
        drop(r);
    }

    #[test]
    fn the_writer_ends_when_every_reader_is_gone() {
        let dir = tempfile::tempdir().unwrap();
        let (r, w) = script_pipe(&dir.path().join("p.fifo")).unwrap();
        drop(r);
        let stop = AtomicBool::new(false);
        write_until_stopped(w, &vec![b'x'; 1 << 20], &stop);
    }

    fn job_with_secs(secs: f64) -> JobResult {
        JobResult {
            workflow: "ci.yml".into(),
            job: "j".into(),
            display: "j".into(),
            outcome: Outcome::Pass,
            secs,
            steps: vec![],
            cancelled: false,
            time: None,
            build_cache: None,
            os_note: None,
        }
    }

    #[test]
    fn a_units_waits_are_charged_to_its_first_job_once() {
        let mut jobs = vec![job_with_secs(5.0), job_with_secs(7.0)];
        charge(
            &mut jobs,
            UnitWait {
                lock: 30.0,
                parallel: 2.0,
                ..UnitWait::default()
            },
        );
        assert_eq!(
            jobs[0].time,
            Some(JobTime {
                work_secs: 5.0,
                wait_lock_secs: 30.0,
                wait_parallel_secs: 2.0,
                ..JobTime::default()
            })
        );
        assert_eq!(jobs[1].time, None);
        // nothing waited: nothing recorded
        let mut jobs = vec![job_with_secs(5.0)];
        charge(&mut jobs, UnitWait::default());
        assert_eq!(jobs[0].time, None);
        // a job that did not run is passed over
        let mut ran = job_with_secs(3.0);
        ran.time = Some(JobTime {
            work_secs: 3.0,
            ..JobTime::default()
        });
        let mut jobs = vec![job_with_secs(0.0), ran];
        charge(
            &mut jobs,
            UnitWait {
                lock: 4.0,
                parallel: 0.0,
                ..UnitWait::default()
            },
        );
        assert_eq!(jobs[0].time, None);
        assert_eq!(jobs[1].time.as_ref().unwrap().wait_lock_secs, 4.0);
    }

    #[test]
    fn job_time_stamps_are_serialized_and_old_results_without_them_parse() {
        let t = JobTime {
            work_secs: 1.0,
            requested_at_ms: 1_700_000_000_000,
            started_at_ms: 1_700_000_001_000,
            finished_at_ms: 1_700_000_002_000,
            ..JobTime::default()
        };
        let v = serde_json::to_value(&t).unwrap();
        assert_eq!(v["requested_at_ms"], 1_700_000_000_000u64);
        assert_eq!(v["started_at_ms"], 1_700_000_001_000u64);
        assert_eq!(v["finished_at_ms"], 1_700_000_002_000u64);
        assert_eq!(serde_json::from_value::<JobTime>(v).unwrap(), t);
        let old: JobTime = serde_json::from_str(
            r#"{"work_secs":2.0,"wait_lock_secs":0.0,"wait_slot_secs":0.0,"wait_queue_secs":0.0,"wait_parallel_secs":0.0}"#,
        )
        .unwrap();
        assert_eq!(old.work_secs, 2.0);
        assert_eq!(
            (old.requested_at_ms, old.started_at_ms, old.finished_at_ms),
            (0, 0, 0)
        );
    }

    #[test]
    fn a_unit_stamps_the_request_time_on_every_job_that_ran() {
        let ran = |at: u64| {
            let mut j = job_with_secs(1.0);
            j.time = Some(JobTime {
                work_secs: 1.0,
                requested_at_ms: at,
                started_at_ms: 5_000,
                ..JobTime::default()
            });
            j
        };
        let mut jobs = vec![ran(0), ran(4_000), job_with_secs(0.0)];
        charge(
            &mut jobs,
            UnitWait {
                requested_at_ms: 1_000,
                ..UnitWait::default()
            },
        );
        assert_eq!(jobs[0].time.as_ref().unwrap().requested_at_ms, 1_000);
        assert_eq!(jobs[1].time.as_ref().unwrap().requested_at_ms, 1_000);
        assert_eq!(jobs[2].time, None);
    }

    #[test]
    fn job_time_is_added_to_the_json_and_left_out_when_unknown() {
        let mut j = job_with_secs(5.0);
        let v = serde_json::to_value(&j).unwrap();
        assert!(v.get("time").is_none(), "{v}");
        assert_eq!(v["secs"], 5.0);
        j.time = Some(JobTime {
            work_secs: 4.0,
            wait_queue_secs: 1.0,
            ..JobTime::default()
        });
        let v = serde_json::to_value(&j).unwrap();
        assert_eq!(v["time"]["work_secs"], 4.0);
        assert_eq!(v["time"]["wait_queue_secs"], 1.0);
        assert_eq!(v["time"]["wait_slot_secs"], 0.0);
    }

    #[test]
    fn file_commands() {
        let v = parse_file_command("a=1\nmatrix<<EOF\n{\"x\":\n[1]}\nEOF\nb=two=2\n");
        assert_eq!(
            v,
            vec![
                ("a".into(), "1".into()),
                ("matrix".into(), "{\"x\":\n[1]}".into()),
                ("b".into(), "two=2".into())
            ]
        );
    }

    #[test]
    fn port_rewrites() {
        let maps = vec![PortMap {
            declared: Some(5433),
            container: 5432,
            actual: 49152,
        }];
        assert_eq!(
            rewrite_ports("postgresql://u:p@localhost:5433/db?x=1", &maps),
            "postgresql://u:p@localhost:49152/db?x=1"
        );
        assert_eq!(rewrite_ports("127.0.0.1:54330", &maps), "127.0.0.1:54330");
        assert_eq!(rewrite_env_value("DB_PORT", "5433", &maps), "49152");
        assert_eq!(rewrite_env_value("COUNT", "5433", &maps), "5433");
        assert_eq!(
            rewrite_ports("TEST_DB_PORT=5433 docker compose up; N=5433", &maps),
            "TEST_DB_PORT=49152 docker compose up; N=5433"
        );
        assert_eq!(rewrite_ports("PORT='5433' x", &maps), "PORT='49152' x");
    }

    #[test]
    fn service_ports_the_workflow_never_names() {
        let wf = |env: &str, run: &str| {
            crate::workflow::parse(
                "ci.yml",
                &format!(
                    "on: push\njobs:\n  t:\n    runs-on: ubuntu-latest\n    env: {{{env}}}\n    services:\n      db:\n        image: mysql\n        ports: ['15306:3306']\n    steps:\n      - run: {run}\n"
                ),
            )
            .unwrap()
        };
        let named = |w: &Workflow| rewritable_mention(w, &w.jobs[0], 15306);
        assert!(!named(&wf("", "npm test")));
        assert!(!named(&wf("COUNT: '15306'", "mysql -P 15306")));
        assert!(named(&wf("DB_PORT: '15306'", "npm test")));
        assert!(named(&wf(
            "",
            "DATABASE_URL=mysql://localhost:15306/x npm test"
        )));
        assert!(named(&wf(
            "",
            "PORT=${{ job.services.db.ports[3306] }} npm test"
        )));
    }

    #[test]
    fn fixed_ports_a_job_sets() {
        assert!(port_key("PORT") && port_key("TEST_DB_PORT") && port_key("port_e2e"));
        assert!(!port_key("EXPORT") && !port_key("REPORT") && !port_key("PORTS"));
        assert_eq!(
            assigned_ports("TEST_DB_PORT=15432 docker compose up\nEXPORT=4000 PORT=80 X=5000"),
            vec![15432]
        );
        assert!(
            assigned_ports("docker run -e POSTGRES_PORT=15432 --env=X_PORT=15433 img").is_empty()
        );
        let mut maps = vec![];
        map_literals([15432, 15432, 15433], &mut maps).unwrap();
        assert_eq!(maps.len(), 2);
        assert_ne!(maps[0].actual, maps[1].actual);
        assert_eq!(
            rewrite_ports("docker run -e PGPORT=15432 img; PGPORT=15432", &maps[..1]),
            format!("docker run -e PGPORT=15432 img; PGPORT={}", maps[0].actual)
        );
        assert_eq!(rewrite_env_value("REPORT", "15432", &maps), "15432");
        assert!(maps
            .iter()
            .all(|m| m.actual != 0 && m.declared != Some(m.actual)));
    }

    #[test]
    fn what_rewriting_cannot_reach() {
        assert_eq!(
            compose_files(
                "docker compose -f a.yml --file=b.yml -p x up -d; docker compose -f \"$F\" up"
            ),
            vec![Some("a.yml".into()), Some("b.yml".into()), None]
        );
        assert_eq!(compose_files("docker compose up -f nope").len(), 4);
        assert!(compose_fixed("services:\n  db:\n    container_name: db\n"));
        assert!(compose_fixed("    ports:\n      - \"5432:5432\"\n"));
        assert!(compose_fixed("    ports:\n      - 127.0.0.1:5432:5432\n"));
        assert!(compose_fixed(
            "      - target: 80\n        published: 8080\n"
        ));
        assert!(!compose_fixed(
            "    ports:\n      - \"${DB_PORT:-5432}:5432\"\n      - \"5432\"\n"
        ));
        assert!(docker_run_fixed("docker run -d --name db postgres"));
        assert!(docker_run_fixed("docker run \\\n  -p 5432:5432 postgres"));
        assert!(!docker_run_fixed(
            "docker run -p 127.0.0.1::5432 -e X=1 postgres; docker compose run --name x web"
        ));
    }

    #[test]
    fn ledger_timeouts_are_retried() {
        let dir = tempfile::tempdir().unwrap();
        let log = dir.path().join("step.log");
        fs::write(&log, "earlier output\n").unwrap();
        let from = fs::metadata(&log).unwrap().len();
        let mut f = OpenOptions::new().append(true).open(&log).unwrap();
        writeln!(f, "task-traffic-controller: waiting 0:00 (queue)").unwrap();
        writeln!(
            f,
            "task-traffic-controller: ledger: timed out after 10s waiting for /x/ledger.lock"
        )
        .unwrap();
        assert!(ledger_timed_out(&log, from));
        writeln!(f, "npm ERR! something").unwrap();
        assert!(!ledger_timed_out(&log, from));
        assert!(!ledger_timed_out(&log, 0));
    }

    #[test]
    fn only_the_commands_own_output_starts_its_clock() {
        let p = "task-traffic-controller: waiting 0:08 (queue)";
        assert!(!command_spoke(b""));
        assert!(!command_spoke(format!("{p}\n{p}\n").as_bytes()));
        // a line of the controller's not finished yet, or its prefix so far
        assert!(!command_spoke(p.as_bytes()));
        assert!(!command_spoke(format!("{p}\ntask-traffic").as_bytes()));
        assert!(!command_spoke(format!("{p}\n{p}").as_bytes()));
        // the command's own, finished or not: a progress line with no newline
        // counts, and so does a blank line
        assert!(command_spoke(format!("{p}\nhello\n").as_bytes()));
        assert!(command_spoke(b"building..."));
        assert!(command_spoke(format!("{p}\n50%\r").as_bytes()));
        assert!(command_spoke(b"\n"));
        assert!(command_spoke(format!("{p}\n\n{p}\n").as_bytes()));
    }

    #[test]
    fn only_the_controllers_prefix_marks_its_own_lines() {
        let p = "task-traffic-controller";
        assert!(is_controller_line(&format!("{p}: waiting 0:00 (queue)")));
        assert!(is_ledger_timeout_line(&format!(
            "{p}: ledger: timed out after 10s"
        )));
        assert!(!is_ledger_timeout_line(&format!("{p}: waiting")));
        assert!(!is_controller_line("canirun: waiting"));
        assert!(!is_ledger_timeout_line("canirun: ledger: timed out"));
        assert!(!is_ledger_timeout_line("ledger: timed out"));
    }

    #[test]
    fn compose_projects_get_a_tag() {
        assert_eq!(
            rename_compose_projects(
                "TEST_DB_PORT=1 docker compose \\\n  -p app-int \\\n  -f a.yml up -d",
                "lc1-2"
            ),
            "TEST_DB_PORT=1 docker compose \\\n  -p app-int-lc1-2 \\\n  -f a.yml up -d"
        );
        assert_eq!(
            rename_compose_projects(
                "mkdir -p app && docker compose --project-name=app down",
                "t"
            ),
            "mkdir -p app && docker compose --project-name=app-t down"
        );
        assert_eq!(
            rename_compose_projects("COMPOSE_PROJECT_NAME=\"z\" docker compose up", "t"),
            "COMPOSE_PROJECT_NAME=\"z-t\" docker compose up"
        );
        assert_eq!(
            rename_compose_projects("docker compose -p a-t up", "t"),
            "docker compose -p a-t up"
        );
        assert_eq!(
            rename_compose_projects("docker compose -p a up\nnpm test -p b", "t"),
            "docker compose -p a-t up\nnpm test -p b"
        );
        // after the subcommand, `-p` belongs to it
        assert_eq!(
            rename_compose_projects(
                "docker compose -f x.yml -p a exec db mkdir -p tmp; docker compose run -p 8080:80 web",
                "t"
            ),
            "docker compose -f x.yml -p a-t exec db mkdir -p tmp; docker compose run -p 8080:80 web"
        );
        assert_eq!(
            compose_projects("docker compose exec db psql -p 5432"),
            Vec::<String>::new()
        );
    }

    #[test]
    fn compose_project_names() {
        assert_eq!(
            compose_projects(
                "docker compose -p a up -d; docker compose -p b down; docker compose -p a ps"
            ),
            vec!["a", "b"]
        );
        assert_eq!(
            compose_projects("TEST_DB_PORT=1 docker compose \\\n  -p app-int \\\n  -f a.yml up -d"),
            vec!["app-int"]
        );
        assert_eq!(
            compose_projects("docker compose --project-name=y up"),
            vec!["y"]
        );
        assert!(compose_projects("npm run test -p foo").is_empty());
        assert!(compose_projects("mkdir -p api && docker compose up -d").is_empty());
        assert_eq!(
            compose_projects("COMPOSE_PROJECT_NAME=z docker compose up"),
            vec!["z"]
        );
    }

    #[test]
    fn npm_installs_once_per_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let log = tmp.path().join("calls");
        let fake = tmp.path().join("fake-npm");
        crate::fake_exec::write_executable(
            &fake,
            format!(
                "#!/bin/sh\necho \"$*\" >> {}\nmkdir -p node_modules\n",
                log.display()
            ),
            0o755,
        );
        let shim = tmp.path().join("npm");
        crate::fake_exec::write_executable(
            &shim,
            NPM_SHIM.replace("__REAL__", &fake.to_string_lossy()),
            0o755,
        );
        let ws = tmp.path().join("ws");
        let proj = ws.join("proj");
        fs::create_dir_all(&proj).unwrap();
        fs::write(proj.join("package-lock.json"), "{}").unwrap();
        let npm_in = |ws: &Path, marks: &str, args: &[&str]| {
            let st = Command::new(&shim)
                .args(args)
                .current_dir(ws.join("proj"))
                .env("GITHUB_WORKSPACE", ws)
                .env("LOCAL_CI_MARKS", tmp.path().join(marks))
                .stderr(Stdio::null())
                .status()
                .unwrap();
            assert!(st.success());
        };
        let npm = |args: &[&str]| npm_in(&ws, "marks", args);
        npm(&["ci", "--no-audit"]);
        npm(&["ci"]);
        npm(&["install"]);
        npm(&["install", "left-pad"]);
        npm(&["run", "test"]);
        fs::write(proj.join("package-lock.json"), "{\"changed\":1}").unwrap();
        npm(&["ci"]);
        let calls = fs::read_to_string(&log).unwrap();
        assert_eq!(calls, "ci --no-audit\ninstall left-pad\nrun test\nci\n");

        // A unit's copy of the workspace, with the marks copied, skips too;
        // a copy without them does not.
        let copy = tmp.path().join("copy");
        fs::create_dir_all(copy.join("proj/node_modules")).unwrap();
        fs::copy(
            proj.join("package-lock.json"),
            copy.join("proj/package-lock.json"),
        )
        .unwrap();
        fs::create_dir_all(tmp.path().join("copied-marks")).unwrap();
        for e in fs::read_dir(tmp.path().join("marks")).unwrap().flatten() {
            if e.file_type().unwrap().is_file() {
                fs::copy(
                    e.path(),
                    tmp.path().join("copied-marks").join(e.file_name()),
                )
                .unwrap();
            }
        }
        npm_in(&copy, "copied-marks", &["ci"]);
        npm_in(&copy, "other-marks", &["ci"]);
        let calls = fs::read_to_string(&log).unwrap();
        assert_eq!(calls, "ci --no-audit\ninstall left-pad\nrun test\nci\nci\n");

        // Where node_modules links into setup's, a read leaves it so and a
        // write gets a copy of its own first.
        let shared = tmp.path().join("setup/node_modules");
        fs::create_dir_all(shared.join("x")).unwrap();
        fs::write(shared.join("x/index.js"), "x").unwrap();
        let linked = tmp.path().join("linked");
        let nm = linked.join("proj/node_modules");
        fs::create_dir_all(&nm).unwrap();
        fs::write(linked.join("proj/package-lock.json"), "{}").unwrap();
        std::os::unix::fs::symlink(shared.join("x"), nm.join("x")).unwrap();
        fs::write(
            nm.join(crate::git::SHARED),
            shared.to_string_lossy().as_bytes(),
        )
        .unwrap();
        npm_in(&linked, "copied-marks", &["run", "test"]);
        assert!(nm.join("x").is_symlink());
        npm_in(&linked, "copied-marks", &["rebuild"]);
        assert!(!nm.join("x").is_symlink() && !nm.join(crate::git::SHARED).exists());
        assert_eq!(fs::read_to_string(nm.join("x/index.js")).unwrap(), "x");
        assert!(shared.join("x/index.js").is_file());
        assert!(!linked.join("proj/.node_modules.local-ci").exists());
    }

    #[test]
    fn steps_that_write_node_modules() {
        assert!(writes_node_modules("npx prisma generate"));
        assert!(writes_node_modules("cd api && npm ci"));
        assert!(writes_node_modules("npm i -D left-pad"));
        assert!(writes_node_modules("yarn install --frozen-lockfile"));
        assert!(!writes_node_modules("npm run test"));
        assert!(!writes_node_modules("npm init -y"));
        assert!(!writes_node_modules("npx prisma migrate deploy"));
    }

    #[test]
    fn ansi_and_slugs() {
        assert_eq!(strip_ansi("\x1b[31mred\x1b[0m\r"), "red");
        assert_eq!(
            slug_of("Run integration tests (1/2)"),
            "run-integration-tests-1-2"
        );
    }

    #[test]
    fn a_task_result_survives_a_round_trip_through_json() {
        let step = |o: Outcome, note: Option<&str>| StepResult {
            label: "step".into(),
            outcome: o,
            exit: Some(1),
            secs: 1.5,
            log: Some(PathBuf::from("/l/log")),
            note: note.map(String::from),
        };
        let job = |display: &str, o: Outcome, cancelled: bool, time: Option<JobTime>| JobResult {
            workflow: "ci.yml".into(),
            job: "j".into(),
            display: display.into(),
            outcome: o,
            secs: 2.0,
            steps: vec![
                step(Outcome::Pass, Some("a note")),
                step(Outcome::Fail, None),
            ],
            cancelled,
            time,
            build_cache: None,
            os_note: (display == "c").then(|| "ran on macOS, not Linux (runs-on x)".to_string()),
        };
        let time = JobTime {
            work_secs: 1.0,
            wait_lock_secs: 2.0,
            wait_slot_secs: 3.0,
            wait_queue_secs: 4.0,
            wait_parallel_secs: 5.0,
            requested_at_ms: 1_700_000_000_000,
            started_at_ms: 1_700_000_001_000,
            finished_at_ms: 1_700_000_009_000,
        };
        let r = crate::task::TaskResult {
            schema_version: crate::wire::wire_version(),
            task: "t1".into(),
            jobs: vec![
                job("a", Outcome::Pass, false, Some(time.clone())),
                job("b", Outcome::Fail, true, None),
                job("c", Outcome::Skip("why".into()), false, None),
                job("d", Outcome::Error("boom".into()), false, None),
            ],
            outcomes: vec![crate::task::JobOutcome {
                job: "j".into(),
                variant: Some(1),
                status: crate::task::JobStatus::Success,
                outputs: [("k".to_string(), "v".to_string())].into(),
                skipped: None,
                ancestor_failed: true,
            }],
            receipt_ignored: Some("another commit".into()),
            artifacts: vec!["bundle".into()],
            shard: None,
        };
        let text = serde_json::to_string(&r).unwrap();
        let back: crate::task::TaskResult = serde_json::from_str(&text).unwrap();
        assert_eq!(serde_json::to_string(&back).unwrap(), text);
        assert_eq!(back.jobs[0].time, Some(time));
        assert_eq!(back.jobs[1].outcome, Outcome::Fail);
        assert!(back.jobs[1].cancelled && !back.jobs[0].cancelled);
        assert_eq!(back.jobs[2].outcome, Outcome::Skip("why".into()));
        assert_eq!(back.jobs[3].outcome, Outcome::Error("boom".into()));
        assert_eq!(
            back.jobs[2].os_note.as_deref(),
            Some("ran on macOS, not Linux (runs-on x)")
        );
        assert_eq!(back.jobs[0].os_note, None);
        assert_eq!(back.jobs[0].steps[0].note.as_deref(), Some("a note"));
        assert_eq!(back.jobs[0].steps[1].note, None);
        assert_eq!(back.artifacts, ["bundle"]);
    }
}