mise-util 2026.11.14

Environment, directory, and filesystem helpers shared by mise's crates
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
mod bounded;
#[cfg(windows)]
pub mod ctrl_c_group;
use std::collections::{HashSet, VecDeque};
use std::ffi::{OsStr, OsString};
use std::fmt::{Debug, Display, Formatter};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{ExitStatus, Stdio};
#[cfg(panic = "abort")]
use std::sync::TryLockError;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering};
use std::sync::mpsc::{RecvTimeoutError, channel};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::thread;
use std::time::{Duration, Instant};

#[cfg(unix)]
use std::os::unix::process::CommandExt;

use crate::redactions::Redactor;
use duct::{Expression, IntoExecutablePath};
use eyre::Result;
use eyre::{Context, bail};
#[cfg(not(target_os = "windows"))]
use signal_hook::consts::{SIGHUP, SIGQUIT, SIGTERM, SIGUSR1, SIGUSR2};
#[cfg(not(target_os = "windows"))]
use signal_hook::iterator::Signals;
use std::sync::LazyLock as Lazy;
#[cfg(unix)]
use tokio::io::AsyncRead;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader as TokioBufReader};
use tokio::process::Command;

use crate::env;
use crate::env::PATH_KEY;
use crate::env_value::EnvValue;
use crate::errors::ProcessError::ScriptFailed;
use crate::file::display_path;
use crate::path_env::PathEnv;
use crate::progress::SingleReport;
use mise_settings::Settings;

/// Create a command with any number of of positional arguments
///
/// may be different types (anything that implements [`Into<OsString>`](https://doc.rust-lang.org/std/convert/trait.From.html)).
/// See also the [`cmd`](fn.cmd.html) function, which takes a collection of arguments.
///
/// # Example
///
/// ```ignore
///     use std::path::Path;
///     use mise_util::cmd;
///
///     let arg1 = "foo";
///     let arg2 = "bar".to_owned();
///     let arg3 = Path::new("baz");
///
///     let output = cmd!("echo", arg1, arg2, arg3).read();
///
///     assert_eq!("foo bar baz", output.unwrap());
/// ```
#[macro_export]
macro_rules! cmd {
    ( $program:expr $(, $arg:expr )* $(,)? ) => {
        {
            use std::ffi::OsString;
            let args: std::vec::Vec<OsString> = std::vec![$( Into::<OsString>::into($arg) ),*];
            $crate::cmd::cmd($program, args)
        }
    };
}

/// Create a command with any number of of positional arguments, which may be
/// different types (anything that implements
/// [`Into<OsString>`](https://doc.rust-lang.org/std/convert/trait.From.html)).
/// See also the [`cmd`](fn.cmd.html) function, which takes a collection of
/// arguments.
///
/// # Example
///
/// ```ignore
///     use std::path::Path;
///     use mise_util::cmd;
///
///     let arg1 = "foo";
///     let arg2 = "bar".to_owned();
///     let arg3 = Path::new("baz");
///
///     let output = cmd!("echo", arg1, arg2, arg3).read();
///
///     assert_eq!("foo bar baz", output.unwrap());
/// ```
pub fn cmd<T, U>(program: T, args: U) -> Expression
where
    T: IntoExecutablePath,
    U: IntoIterator,
    U::Item: Into<OsString>,
{
    let program = program.to_executable();
    let args: Vec<OsString> = args.into_iter().map(Into::<OsString>::into).collect();

    let display_command = std::iter::once(&program)
        .chain(&args)
        .map(|s| shell_escape::escape(s.to_string_lossy()))
        .collect::<Vec<_>>()
        .join(" ");
    debug!("$ {display_command}");

    duct::cmd(program, args)
}

type OutputObserver<'a> = Box<dyn Fn(&str) + Send + 'a>;

/// The longest line mise reads from a command in one piece. Output with no newline is
/// passed on in pieces of about this size, so a command cannot make mise hold an unbounded
/// line.
const MAX_LINE_BYTES: usize = 1024 * 1024;

/// The longest URL scheme and authority a cut keeps whole, so the URL credential redaction
/// that task logs apply sees `scheme://user:pw@` in one piece.
const URL_AUTHORITY_BYTES: usize = 2048;

/// Like tokio's `Lines`, but a line longer than `max` bytes arrives in pieces. The redactor
/// sees one piece at a time, so where a piece ends is chosen with its match set; see
/// [`Self::cut`].
struct CappedLines<R> {
    reader: R,
    max: usize,
    /// The command's redactor joined with the global one: what every piece is redacted with.
    redactor: Redactor,
    /// How far from `max` a cut may move: the longest secret or a URL authority.
    reach: usize,
    /// Bytes read past the previous cut or newline: the start of the next piece.
    carry: Vec<u8>,
}

impl<R: tokio::io::AsyncBufRead + Unpin> CappedLines<R> {
    fn new(reader: R, redactor: Redactor) -> Self {
        Self::with_max(reader, MAX_LINE_BYTES, redactor)
    }

    fn with_max(reader: R, max: usize, redactor: Redactor) -> Self {
        let reach = redactor.longest_pattern().max(URL_AUTHORITY_BYTES);
        Self {
            reader,
            max,
            redactor,
            reach,
            carry: Vec::new(),
        }
    }

    async fn next_line(&mut self) -> std::io::Result<Option<String>> {
        let mut buf = std::mem::take(&mut self.carry);
        // Enough past `max` to see every match a cut near it could touch, and a `\r\n`.
        let want = self.max + 3 * self.reach + 2;
        if !buf.contains(&b'\n') && buf.len() < want {
            (&mut self.reader)
                .take((want - buf.len()) as u64)
                .read_until(b'\n', &mut buf)
                .await?;
        }
        if buf.is_empty() {
            return Ok(None);
        }
        let newline = buf
            .iter()
            .position(|b| *b == b'\n')
            // A line exactly `max` long may end with `\r\n`, one byte past `max`.
            .filter(|at| *at <= self.max || (*at == self.max + 1 && buf[self.max] == b'\r'));
        if let Some(at) = newline {
            self.carry = buf.split_off(at + 1);
            buf.pop();
            if buf.last() == Some(&b'\r') {
                buf.pop();
            }
        } else if buf.len() > self.max {
            let cut = self.cut(&buf);
            self.carry = buf.split_off(cut);
            // A cut right before the line's end ends the line there.
            if self.carry.first() == Some(&b'\n') {
                self.carry.remove(0);
                if buf.last() == Some(&b'\r') {
                    buf.pop();
                }
            } else if self.carry.starts_with(b"\r\n") {
                self.carry.drain(..2);
            }
        }
        // Otherwise the output ended without a newline, and `buf` is its last line.
        String::from_utf8(buf)
            .map(Some)
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))
    }

    /// Where to end a piece of `buf`, which is longer than `max` and holds no newline in
    /// its first `max` bytes.
    ///
    /// Invariant: a cut never exposes a byte that redacting the whole line would hide. The
    /// matches are the redactor's own (`Redactor::match_spans`, the overlapping matches that
    /// `redact` replaces), so the two cannot drift apart. A cut is safe when every match it
    /// crosses is still covered, on each side, by matches that lie wholly on that side: then
    /// redacting each piece hides exactly the bytes redacting the line hides. (The text can
    /// differ in how many `[redacted]` markers it shows: with `aaaa` registered, a run of
    /// `a` that the line would redact as one is cut at an `aaaa` boundary and redacted per
    /// piece. Keeping such a run whole would let one line grow without bound.) A URL
    /// authority that holds credentials is never cut, so its userinfo is redacted too.
    ///
    /// The cut is the safe character boundary closest below `max`, else the closest above it,
    /// within `reach` of `max`. Matches are found once per cut, in a window of a few times
    /// `reach` around `max`, so the total is linear in the output. If no position in reach is
    /// safe, which takes a chain of distinct overlapping secrets longer than `reach` with no
    /// point where one ends as another starts, the piece ends at `max`.
    fn cut(&self, buf: &[u8]) -> usize {
        let reach = self.reach;
        let from = self.max.saturating_sub(3 * reach);
        let to = (self.max + 3 * reach).min(buf.len());
        let window = &buf[from..to];
        let mut spans: Vec<(usize, usize)> = self
            .redactor
            .match_spans(window)
            .into_iter()
            .map(|(s, e)| (from + s, from + e))
            .collect();
        spans.sort_unstable();
        let urls: Vec<(usize, usize)> = url_authorities(window)
            .map(|(s, e)| (from + s, from + e))
            .collect();
        let longest = self.redactor.longest_pattern();
        // The piece may run to the end of what was read, but not past the line's `\n`.
        let end = buf.len() - usize::from(buf.last() == Some(&b'\n'));
        let boundary = |c: usize| c > 0 && (c == end || (c < end && (buf[c] & 0xC0) != 0x80));
        let below = (self.max.saturating_sub(reach - 1)..=self.max).rev();
        let above = self.max + 1..=(self.max + reach).min(end);
        below
            .chain(above)
            .find(|&c| boundary(c) && cut_is_safe(&spans, &urls, longest, c))
            .unwrap_or_else(|| match std::str::from_utf8(&buf[..self.max]) {
                Err(err) if err.error_len().is_none() => err.valid_up_to(),
                _ => self.max,
            })
    }
}

/// Whether cutting at `c` exposes no byte of a match, given `spans` (sorted, none longer than
/// `longest`) and URL authorities `urls`. See [`CappedLines::cut`].
fn cut_is_safe(
    spans: &[(usize, usize)],
    urls: &[(usize, usize)],
    longest: usize,
    c: usize,
) -> bool {
    if urls.iter().any(|&(s, e)| s < c && c < e) {
        return false;
    }
    // Only matches starting within `2 * longest` of `c` can cross it or cover one that does.
    let lo = spans.partition_point(|&(s, _)| s + 2 * longest < c);
    let hi = spans.partition_point(|&(s, _)| s < c + longest);
    let near = &spans[lo..hi];
    let left: Vec<(usize, usize)> = near.iter().copied().filter(|&(_, e)| e <= c).collect();
    let right: Vec<(usize, usize)> = near.iter().copied().filter(|&(s, _)| s >= c).collect();
    near.iter()
        .filter(|&&(s, e)| s < c && c < e)
        .all(|&(s, e)| covers(&left, s, c) && covers(&right, c, e))
}

/// Whether `spans`, sorted by start, cover every byte of `from..to`.
fn covers(spans: &[(usize, usize)], from: usize, to: usize) -> bool {
    let mut reached = from;
    for &(s, e) in spans {
        if s > reached {
            break;
        }
        reached = reached.max(e);
    }
    reached >= to
}

/// The `scheme://authority` spans in `buf` whose authority holds credentials (an `@`), each
/// at most [`URL_AUTHORITY_BYTES`] long.
fn url_authorities(buf: &[u8]) -> impl Iterator<Item = (usize, usize)> + '_ {
    buf.windows(3)
        .enumerate()
        .filter(|(_, w)| *w == b"://")
        .filter_map(move |(at, _)| {
            let scheme = buf[..at]
                .iter()
                .rev()
                .take(32)
                .take_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'))
                .count();
            let start = at - scheme;
            let authority = &buf[at + 3..];
            let len = authority
                .iter()
                .take(URL_AUTHORITY_BYTES)
                .position(|b| matches!(b, b'/' | b'?' | b'#') || b.is_ascii_whitespace())
                .unwrap_or(authority.len().min(URL_AUTHORITY_BYTES));
            authority[..len]
                .contains(&b'@')
                .then_some((start, at + 3 + len))
        })
}

fn chain_observers<'a, F: Fn(&str) + Send + 'a>(
    previous: Option<OutputObserver<'a>>,
    next: F,
) -> OutputObserver<'a> {
    match previous {
        Some(previous) => Box::new(move |line| {
            previous(line);
            next(line);
        }),
        None => Box::new(next),
    }
}

pub struct CmdLineRunner<'a> {
    cmd: Command,
    pr: Option<&'a dyn SingleReport>,
    pr_arc: Option<Arc<Box<dyn SingleReport>>>,
    stdin: Option<String>,
    redactor: Redactor,
    raw: bool,
    /// Refuse raw mode for this one command, however it was requested.
    never_raw: bool,
    pass_signals: bool,
    on_stdout: Option<Box<dyn Fn(String) + Send + 'a>>,
    on_stderr: Option<Box<dyn Fn(String) + Send + 'a>>,
    stderr_as_stdout: bool,
    observe_stdout: Option<OutputObserver<'a>>,
    /// Called once, after the process started and before its output is read.
    on_spawn: Option<Box<dyn FnOnce() + Send + 'a>>,
    observe_stderr: Option<OutputObserver<'a>>,
    timeout: Option<Duration>,
    sandbox: Option<crate::sandbox::SandboxConfig>,
    inherit_env: bool,
    stdio: PendingStdio,
    kill_on_drop: bool,
    /// Indices of the arguments added with `raw_arg`, which a Ctrl+C group
    /// leader has to add the same way.
    #[cfg(windows)]
    raw_args: Vec<usize>,
    /// Whether the spawned process leads a Ctrl+C group (see [`ctrl_c_group`]):
    /// asked for by [`Self::interrupt_on_timeout`], kept only with a timeout.
    #[cfg(windows)]
    ctrl_c_group: bool,
}

/// Stdio for a command, applied when it is spawned. `Command` cannot hand its
/// stdio back, so it is held here for whichever command is finally spawned.
#[derive(Default)]
struct PendingStdio {
    stdin: Option<Stdio>,
    stdout: Option<Stdio>,
    stderr: Option<Stdio>,
}

impl PendingStdio {
    /// What `CmdLineRunner::new` starts with: no stdin, both outputs piped.
    fn defaults() -> Self {
        Self {
            stdin: Some(Stdio::null()),
            stdout: Some(Stdio::piped()),
            stderr: Some(Stdio::piped()),
        }
    }

    fn apply(&mut self, cmd: &mut Command) {
        if let Some(stdin) = self.stdin.take() {
            cmd.stdin(stdin);
        }
        if let Some(stdout) = self.stdout.take() {
            cmd.stdout(stdout);
        }
        if let Some(stderr) = self.stderr.take() {
            cmd.stderr(stderr);
        }
    }
}

const GUARD_RUNNING: u8 = 0;
const GUARD_CANCELLED: u8 = 1;
const GUARD_TIMED_OUT: u8 = 2;

/// How long a timed-out command gets to exit after being asked to (SIGTERM, or
/// Ctrl+C on Windows) before it is killed.
const TIMEOUT_GRACE: Duration = Duration::from_secs(5);

#[cfg(unix)]
fn in_terminal_foreground_pgrp() -> bool {
    let pgrp = nix::unistd::getpgrp();
    nix::unistd::tcgetpgrp(std::io::stdin()) == Ok(pgrp)
        || nix::unistd::tcgetpgrp(std::io::stdout()) == Ok(pgrp)
        || nix::unistd::tcgetpgrp(std::io::stderr()) == Ok(pgrp)
}

/// Whether a SIGINT came from a process (`kill`, `sigqueue`) rather than from
/// the terminal since `kill_all` last looked. Only Linux can tell: macOS gives
/// a terminal Ctrl-C the same `si_code` and a sender pid, just like `kill`.
///
/// A SIGINT that arrives before `kill_all` has handled the previous one must
/// not hide that earlier origin, so the handler only ever sets this and
/// `kill_all` takes it.
///
/// `si_code` doesn't say whom the sender targeted: `kill -INT -<pgid>` also
/// reports SI_USER, so children in that group get the SIGINT twice. Nothing
/// tells the two apart, and a second SIGINT beats none: a child that never
/// gets one keeps mise waiting on it.
#[cfg(target_os = "linux")]
static SIGINT_FROM_PROCESS: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

/// Watch SIGINT from the signal handler itself: note it for
/// [`crate::cancel::is_cancelled`], and on Linux record where it came from, so
/// `kill_all` still passes on a SIGINT that was sent to mise alone. Call this
/// before handling Ctrl-C.
#[cfg(unix)]
pub fn track_sigint() {
    static ONCE: std::sync::Once = std::sync::Once::new();
    ONCE.call_once(|| {
        // SAFETY: the actions only store to atomics, which is
        // async-signal-safe.
        #[cfg(target_os = "linux")]
        let registered = unsafe {
            signal_hook_registry::register_sigaction(nix::libc::SIGINT, |info| {
                // The terminal sends SI_KERNEL. `kill` sends SI_USER (0),
                // and `sigqueue`, `tgkill` and the like send negative codes.
                if info.si_code <= 0 {
                    SIGINT_FROM_PROCESS.store(true, std::sync::atomic::Ordering::Relaxed);
                }
                crate::cancel::note_signal();
            })
        };
        #[cfg(not(target_os = "linux"))]
        let registered = unsafe {
            signal_hook::low_level::register(
                signal_hook::consts::SIGINT,
                crate::cancel::note_signal,
            )
        };
        if let Err(e) = registered {
            debug!("failed to track SIGINT: {e}");
        }
    });
}

/// Whether the SIGINT `kill_all` is about to pass on has already reached the
/// children that share mise's process group.
#[cfg(unix)]
fn sigint_reached_own_pgrp() -> bool {
    // Take the flag even when it isn't needed, so it never outlives its SIGINT.
    #[cfg(target_os = "linux")]
    let from_process = SIGINT_FROM_PROCESS.swap(false, std::sync::atomic::Ordering::Relaxed);
    #[cfg(not(target_os = "linux"))]
    let from_process = false;
    // An outer mise that owns our process group signals all of it with
    // `killpg`, so the children we share it with got that SIGINT directly,
    // however it looks to us. Without this, a nested mise would pass it on a
    // second time. The cost is a `kill -INT` sent to this nested mise alone,
    // which its children never see; the outer mise, whose Ctrl-C reaches us
    // here, is the realistic sender, and nothing in a SIGINT tells the two
    // apart.
    if std::env::var_os(TASK_PGID_MANAGED_ENV).is_some() {
        return true;
    }
    !from_process && in_terminal_foreground_pgrp()
}

#[cfg(unix)]
fn signal_process_tree(pid: u32, signal: nix::sys::signal::Signal) {
    let pid = nix::unistd::Pid::from_raw(pid as i32);
    if !should_use_pgroup() || nix::sys::signal::killpg(pid, signal).is_err() {
        let _ = nix::sys::signal::kill(pid, signal);
    }
}

/// Those of `pids` for which anything that [`signal_process_tree`] would reach
/// is still running.
#[cfg(unix)]
fn alive_process_trees(pids: &HashSet<u32>) -> HashSet<u32> {
    #[cfg(target_os = "linux")]
    if let Some(alive) = alive_process_trees_procfs(pids) {
        return alive;
    }
    pids.iter()
        .copied()
        .filter(|&pid| {
            let pid = nix::unistd::Pid::from_raw(pid as i32);
            (should_use_pgroup() && nix::sys::signal::killpg(pid, None).is_ok())
                || nix::sys::signal::kill(pid, None).is_ok()
        })
        .collect()
}

/// Signal 0 also reaches zombies, which an init that never reaps keeps around,
/// so read process states instead. `None` when /proc cannot be read.
#[cfg(target_os = "linux")]
fn alive_process_trees_procfs(pids: &HashSet<u32>) -> Option<HashSet<u32>> {
    let use_pgroup = should_use_pgroup();
    let entries = std::fs::read_dir("/proc").ok()?;
    let mut alive = HashSet::new();
    for entry in entries.flatten() {
        let Some(pid) = entry.file_name().to_str().and_then(|s| s.parse().ok()) else {
            continue;
        };
        let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else {
            continue;
        };
        // "pid (comm) state ppid pgrp ..."; comm may itself contain ") ".
        let Some(fields) = stat.rfind(')').map(|i| &stat[i + 1..]) else {
            continue;
        };
        let mut fields = fields.split_whitespace();
        let (Some(state), Some(_ppid), Some(pgrp)) = (fields.next(), fields.next(), fields.next())
        else {
            continue;
        };
        if state == "Z" {
            continue;
        }
        if pids.contains(&pid) {
            alive.insert(pid);
        }
        if use_pgroup
            && let Ok(pgrp) = pgrp.parse::<u32>()
            && pids.contains(&pgrp)
        {
            alive.insert(pgrp);
        }
    }
    Some(alive)
}

/// Commands running in a job object, by the PID of their first process.
///
/// A job holds everything the command starts, however the process tree reports
/// its parents: a Cygwin or MSYS2 `fork` can leave a descendant that `taskkill
/// /T` cannot reach through the parent chain, and that keeps the output pipe
/// open. Ending the job ends it. Closing a job does not end the processes in
/// it, so a command that finishes leaves whatever it started running.
#[cfg(windows)]
static RUNNING_JOBS: Lazy<Mutex<std::collections::HashMap<u32, crate::windows_job::Job>>> =
    Lazy::new(Default::default);

/// Start `cmd` suspended, so [`join_job`] can put it in a job before it can
/// start a process the job would miss. `leader` is whether `cmd` is a Ctrl+C
/// group leader, which already has its own creation flag.
#[cfg(windows)]
fn suspend_for_job(cmd: &mut std::process::Command, leader: bool) {
    use std::os::windows::process::CommandExt;
    use windows_sys::Win32::System::Threading::{CREATE_NEW_PROCESS_GROUP, CREATE_SUSPENDED};
    let flags = if leader { CREATE_NEW_PROCESS_GROUP } else { 0 };
    cmd.creation_flags(flags | CREATE_SUSPENDED);
}

/// Put a command started by [`suspend_for_job`] in a job, then let it run. A
/// command that cannot join one (it may already be in a job that forbids it)
/// runs outside, and is ended by `taskkill` as before.
///
/// # Safety
///
/// `process` must be the handle of the command with ID `pid`, open for the call.
#[cfg(windows)]
unsafe fn join_job(pid: u32, process: std::os::windows::io::RawHandle) -> std::io::Result<()> {
    use crate::windows_job::{Job, resume};
    // SAFETY: the caller vouches for `process`.
    match Job::tracking().and_then(|job| unsafe { job.assign(process) }.map(|()| job)) {
        Ok(job) => {
            RUNNING_JOBS.lock().unwrap().insert(pid, job);
        }
        Err(err) => debug!("not tracking {pid} in a job: {err}"),
    }
    resume(pid).map_err(|err| {
        // The caller kills the command and never registers it, so nothing else frees the job.
        forget_job(pid);
        std::io::Error::other(err)
    })
}

#[cfg(windows)]
fn forget_job(pid: u32) {
    RUNNING_JOBS.lock().unwrap().remove(&pid);
}

/// End the job a command runs in, returning whether it had one.
#[cfg(windows)]
fn kill_job(pid: u32) -> bool {
    match RUNNING_JOBS.lock().unwrap().get(&pid) {
        Some(job) => {
            job.kill();
            true
        }
        None => false,
    }
}

#[cfg(windows)]
fn kill_process_tree(pid: u32) {
    if kill_job(pid) {
        return;
    }
    let _ = std::process::Command::new("taskkill")
        .args(["/F", "/T", "/PID", &pid.to_string()])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status();
}

fn wait_for_cancel_or_deadline<'a>(
    cvar: &'a Condvar,
    mut guard: MutexGuard<'a, bool>,
    deadline: std::time::Instant,
) -> (MutexGuard<'a, bool>, bool) {
    loop {
        if *guard {
            return (guard, true);
        }
        let remaining = deadline.saturating_duration_since(std::time::Instant::now());
        if remaining.is_zero() {
            return (guard, false);
        }
        let (g, result) = cvar.wait_timeout(guard, remaining).unwrap();
        guard = g;
        if result.timed_out() {
            return (guard, false);
        }
    }
}

struct TimeoutGuard {
    state: Arc<AtomicU8>,
    cancel: Arc<(Mutex<bool>, Condvar)>,
    timeout: Duration,
}

impl TimeoutGuard {
    /// `interruptible` is whether `pid` can be asked to stop before it is killed:
    /// always on Unix, and on Windows when it leads a Ctrl+C group.
    fn new(timeout: Duration, pid: u32, interruptible: bool) -> Self {
        let state = Arc::new(AtomicU8::new(GUARD_RUNNING));
        let cancel = Arc::new((Mutex::new(false), Condvar::new()));
        let state_clone = state.clone();
        let cancel_clone = cancel.clone();
        thread::spawn(move || {
            let (lock, cvar) = &*cancel_clone;
            let guard = lock.lock().unwrap();
            let deadline = std::time::Instant::now() + timeout;
            let (guard, cancelled) = wait_for_cancel_or_deadline(cvar, guard, deadline);
            if cancelled {
                return;
            }
            if state_clone
                .compare_exchange(
                    GUARD_RUNNING,
                    GUARD_TIMED_OUT,
                    Ordering::AcqRel,
                    Ordering::Acquire,
                )
                .is_err()
            {
                return;
            }
            #[cfg(unix)]
            {
                debug_assert!(interruptible, "Unix can always signal a command");
                signal_process_tree(pid, nix::sys::signal::Signal::SIGTERM);
                drop(guard);
                let guard = lock.lock().unwrap();
                let grace_deadline = std::time::Instant::now() + TIMEOUT_GRACE;
                let (_guard, cancelled) = wait_for_cancel_or_deadline(cvar, guard, grace_deadline);
                if !cancelled {
                    signal_process_tree(pid, nix::sys::signal::Signal::SIGKILL);
                }
            }
            #[cfg(windows)]
            {
                drop(guard);
                // Without a console to raise Ctrl+C on, there is nothing to wait for.
                if interruptible && ctrl_c_group::interrupt(pid) {
                    let guard = lock.lock().unwrap();
                    let grace_deadline = std::time::Instant::now() + TIMEOUT_GRACE;
                    let (_guard, cancelled) =
                        wait_for_cancel_or_deadline(cvar, guard, grace_deadline);
                    if cancelled {
                        return;
                    }
                }
                kill_process_tree(pid);
            }
        });
        Self {
            state,
            cancel,
            timeout,
        }
    }

    fn cancel(&self) {
        self.state
            .compare_exchange(
                GUARD_RUNNING,
                GUARD_CANCELLED,
                Ordering::AcqRel,
                Ordering::Acquire,
            )
            .ok();
        let (lock, cvar) = &*self.cancel;
        *lock.lock().unwrap() = true;
        cvar.notify_one();
    }

    /// How long the command ran before this guard stopped it, if it did. A command
    /// can exit cleanly on SIGTERM or Ctrl+C, so its exit status cannot tell.
    fn timed_out(&self) -> Option<Duration> {
        (self.state.load(Ordering::Acquire) == GUARD_TIMED_OUT).then_some(self.timeout)
    }
}

/// Whether the timeout had fired by the time the command exited. Taken at exit,
/// not after draining its pipes, which a background process can hold open past
/// the deadline.
fn timed_out_at_exit(guard: Option<&TimeoutGuard>) -> Option<Duration> {
    guard.and_then(TimeoutGuard::timed_out)
}

impl Drop for TimeoutGuard {
    fn drop(&mut self) {
        self.cancel();
    }
}

static OUTPUT_LOCK: Mutex<()> = Mutex::new(());
static RAW_LOCK: Lazy<tokio::sync::RwLock<()>> = Lazy::new(|| tokio::sync::RwLock::new(()));

static RUNNING_PIDS: Lazy<Mutex<HashSet<u32>>> = Lazy::new(Default::default);
/// Set by [`CmdLineRunner::terminate_all`]; nothing started afterwards may keep running.
static TERMINATING: AtomicBool = AtomicBool::new(false);

/// Track a started command for `kill_all`. One that started after
/// `terminate_all` began missed its signals, so it is killed here instead.
fn register_running_pid(pid: u32) {
    RUNNING_PIDS.lock().unwrap().insert(pid);
    if TERMINATING.load(Ordering::SeqCst) {
        #[cfg(unix)]
        signal_process_tree(pid, nix::sys::signal::SIGKILL);
        #[cfg(windows)]
        kill_process_tree(pid);
    }
}

#[cfg(all(panic = "abort", unix))]
fn kill_pids_immediately(pids: &HashSet<u32>) {
    let use_pgroup = should_use_pgroup();
    for pid in pids {
        let pid = nix::unistd::Pid::from_raw(*pid as i32);
        if use_pgroup {
            if nix::sys::signal::killpg(pid, nix::sys::signal::SIGKILL).is_err() {
                let _ = nix::sys::signal::kill(pid, nix::sys::signal::SIGKILL);
            }
        } else {
            let _ = nix::sys::signal::kill(pid, nix::sys::signal::SIGKILL);
        }
    }
}

#[cfg(all(panic = "abort", windows))]
fn kill_pids_immediately(pids: &HashSet<u32>) {
    for pid in pids {
        // Not blocking on the registry, for the reason `kill_all_on_panic` gives.
        if let Ok(jobs) = RUNNING_JOBS.try_lock()
            && let Some(job) = jobs.get(pid)
        {
            job.kill();
            continue;
        }
        let _ = std::process::Command::new("taskkill")
            .args(["/F", "/T", "/PID", &pid.to_string()])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
    }
}

/// Best-effort synchronous cleanup for the panic hook.
///
/// An aborting panic does not run destructors, and there is no time for the
/// normal TERM/grace-period/KILL sequence. Avoid blocking if the panic occurred
/// while the PID registry was locked; a deadlocked panic hook would prevent the
/// process from ever reaching abort.
#[cfg(panic = "abort")]
pub fn kill_all_on_panic() {
    let pids = match RUNNING_PIDS.try_lock() {
        Ok(pids) => pids,
        Err(TryLockError::Poisoned(err)) => err.into_inner(),
        Err(TryLockError::WouldBlock) => return,
    };
    kill_pids_immediately(&pids);
}

/// Stop tracking a command that has finished.
fn unregister_running_pid(pid: u32) {
    RUNNING_PIDS.lock().unwrap().remove(&pid);
    #[cfg(windows)]
    forget_job(pid);
}

pub struct RunningPidGuard(Option<u32>);

impl RunningPidGuard {
    pub fn new(pid: Option<u32>) -> Self {
        if let Some(pid) = pid {
            register_running_pid(pid);
        }
        Self(pid)
    }
}

impl Drop for RunningPidGuard {
    fn drop(&mut self) {
        if let Some(pid) = self.0 {
            unregister_running_pid(pid);
        }
    }
}

/// Env var set on every spawned child when this mise process is managing
/// process groups (calling setpgid/setsid + killpg). A nested mise that sees this
/// var skips its own setpgid so descendants stay in the outer pgid — that
/// way the outer mise's killpg actually reaches the leaves.
#[cfg(unix)]
const TASK_PGID_MANAGED_ENV: &str = "MISE_TASK_PGID_MANAGED";

#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ChildProcessIsolation {
    Inherit,
    ProcessGroup,
    Session,
}

#[cfg(unix)]
fn child_process_isolation(
    child_stdin_is_terminal: bool,
    parent_has_terminal: bool,
    is_macos: bool,
) -> ChildProcessIsolation {
    if child_stdin_is_terminal {
        ChildProcessIsolation::Inherit
    } else if is_macos && parent_has_terminal {
        ChildProcessIsolation::Session
    } else {
        ChildProcessIsolation::ProcessGroup
    }
}

#[cfg(unix)]
fn parent_has_terminal() -> bool {
    use std::io::IsTerminal;

    std::io::stdin().is_terminal()
        || std::io::stdout().is_terminal()
        || std::io::stderr().is_terminal()
}

/// Put an ordinary non-raw command in the process tree managed by mise.
///
/// On macOS, a non-interactive zsh child in its own process group can be
/// stopped by job control when it uses process substitution under a
/// controlling terminal (for example, inside tmux). A separate session keeps
/// the child detached from that terminal while preserving the invariant that
/// its PID is also its process group ID for killpg-based cleanup.
#[cfg(unix)]
fn prepare_execute_child(cmd: &mut std::process::Command) {
    if !should_use_pgroup() {
        return;
    }

    cmd.env(TASK_PGID_MANAGED_ENV, "1");
    let parent_has_terminal = parent_has_terminal();
    unsafe {
        cmd.pre_exec(move || {
            // Use BorrowedFd::borrow_raw rather than std::io::stdin() —
            // pre_exec runs post-fork where OnceLock/malloc are not
            // async-signal-safe.
            let stdin = std::os::fd::BorrowedFd::borrow_raw(0);
            let child_stdin_is_terminal = std::io::IsTerminal::is_terminal(&stdin);
            match child_process_isolation(
                child_stdin_is_terminal,
                parent_has_terminal,
                cfg!(target_os = "macos"),
            ) {
                ChildProcessIsolation::Inherit => Ok(()),
                ChildProcessIsolation::ProcessGroup => {
                    let _ = nix::unistd::setpgid(
                        nix::unistd::Pid::from_raw(0),
                        nix::unistd::Pid::from_raw(0),
                    );
                    Ok(())
                }
                ChildProcessIsolation::Session => {
                    nix::unistd::setsid().map(|_| ()).map_err(Into::into)
                }
            }
        });
    }
}

/// True when this mise should isolate spawned children into process groups and
/// `killpg` them for cleanup.
///
/// We skip pgroup management in two cases:
///
/// 1. **Nested under another mise** (env var present). The outer mise is
///    already managing pgroups; if we set our own, the outer's `killpg`
///    can't reach our descendants and either an orchestrator or the
///    user's Ctrl+C leaves orphans behind.
/// 2. **We're the session leader** — i.e. `getsid(0) == getpid()`. This
///    is what Node's `detached: true` (Playwright's `webServer`) does:
///    it calls `setsid` so the orchestrator can `kill(-pgid, SIGKILL)`
///    the whole tree later. If we then create our own pgroups, the
///    orchestrator's tree-kill stops at us and our descendants survive,
///    holding pipes open and hanging the parent.
///
/// In both cases we share whatever pgid we landed in, so the ancestor
/// that owns it can clean us up.
///
/// Cached on first access: `execute()` decides whether to create a managed
/// process group or session at spawn time, and `kill_all()` decides whether to
/// `killpg` at signal time. They must agree — a child placed in its own pgid by
/// `execute()` must be killed via `killpg`, or only the direct PID gets the
/// signal and grandchildren leak. Computing this once removes any chance of
/// the two callers disagreeing if the env later mutates.
#[cfg(unix)]
fn should_use_pgroup() -> bool {
    static CACHED: Lazy<bool> = Lazy::new(|| {
        if std::env::var_os(TASK_PGID_MANAGED_ENV).is_some() {
            return false;
        }
        let me = nix::unistd::getpid();
        if let Ok(sid) = nix::unistd::getsid(None)
            && sid == me
        {
            return false;
        }
        true
    });
    *CACHED
}

/// Put a non-interactive child in the process tree managed by mise.
///
/// Callers must retain a [`RunningPidGuard`] after spawning the command.
pub fn prepare_noninteractive_child(_cmd: &mut std::process::Command) {
    #[cfg(unix)]
    if should_use_pgroup() {
        _cmd.env(TASK_PGID_MANAGED_ENV, "1");
        unsafe {
            _cmd.pre_exec(|| {
                let _ = nix::unistd::setpgid(
                    nix::unistd::Pid::from_raw(0),
                    nix::unistd::Pid::from_raw(0),
                );
                Ok(())
            });
        }
    }
}

/// Put a child that runs mise tasks in the process tree managed by mise, isolated the way mise
/// isolates its own task commands: in a process group of its own unless its stdin is a terminal.
///
/// A nested mise then keeps its tasks, raw ones included, in that group, so
/// [`signal_child_tree`] reaches all of them. Callers must retain a [`RunningPidGuard`] after
/// spawning the command.
pub fn prepare_task_child(_cmd: &mut std::process::Command) {
    #[cfg(unix)]
    prepare_execute_child(_cmd);
}

/// Send `signal` to a child prepared with [`prepare_task_child`] and everything in its process
/// group, or to the child alone when it was left in mise's own group.
#[cfg(unix)]
pub fn signal_child_tree(pid: u32, signal: nix::sys::signal::Signal) {
    signal_process_tree(pid, signal);
}

/// Grace period after a child's ExitStatus arrives during which we keep
/// reading its stdout/stderr pipes. If a grandchild inherited the pipes
/// and survived (e.g. a nested mise that escaped our pgroup, or an
/// orchestrator's SIGKILL leaving orphans), the readers would otherwise
/// block forever waiting for EOF and the parent would hang. After this
/// deadline we abandon the readers — any tail output is dropped.
const PIPE_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);
/// Extra time the hashing runner gives the readers once `PIPE_DRAIN_TIMEOUT`
/// has passed, so a starved runtime is not mistaken for a held pipe.
const PIPE_DRAIN_GRACE: Duration = Duration::from_secs(1);

/// Maximum amount of stdout retained for commands whose output is hidden
/// behind a progress indicator. The tail is replayed if the command fails.
const FAILURE_OUTPUT_TAIL_BYTES: usize = 64 * 1024;
/// How much of the child's final stderr line the failure carries. Long enough
/// for a loader or compiler diagnostic, short enough to stay on one row.
const STDERR_TAIL_MAX_CHARS: usize = 300;
const FAILURE_OUTPUT_TRUNCATED_NOTICE: &str = "[output truncated; showing last 64 KiB]";

#[derive(Default)]
struct FailureOutputTail {
    lines: VecDeque<String>,
    bytes: usize,
    truncated: bool,
}

impl FailureOutputTail {
    fn push(&mut self, mut line: String) {
        let max_line_bytes = FAILURE_OUTPUT_TAIL_BYTES.saturating_sub(1);
        if line.len() > max_line_bytes {
            let mut start = line.len() - max_line_bytes;
            while !line.is_char_boundary(start) {
                start += 1;
            }
            line = line[start..].to_string();
            self.lines.clear();
            self.bytes = 0;
            self.truncated = true;
        }

        self.bytes = self.bytes.saturating_add(line.len().saturating_add(1));
        self.lines.push_back(line);
        while self.bytes > FAILURE_OUTPUT_TAIL_BYTES {
            if let Some(line) = self.lines.pop_front() {
                self.bytes = self.bytes.saturating_sub(line.len().saturating_add(1));
                self.truncated = true;
            } else {
                break;
            }
        }
    }

    fn into_output(mut self) -> Vec<(String, OutputSource)> {
        if self.truncated {
            self.lines
                .push_front(FAILURE_OUTPUT_TRUNCATED_NOTICE.to_string());
        }
        self.lines
            .into_iter()
            .map(|line| (line, OutputSource::Stdout))
            .collect()
    }
}

enum HashedProcessOutput {
    Stdout(Vec<u8>),
    Stderr(Vec<u8>),
    ReadError(&'static str, std::io::Error),
}

#[cfg(unix)]
async fn read_capped<R: AsyncRead + Unpin>(
    mut reader: R,
    max_bytes: usize,
) -> std::io::Result<(Vec<u8>, usize)> {
    let mut kept = Vec::new();
    let mut total = 0usize;
    let mut buffer = [0; 8192];
    loop {
        let len = reader.read(&mut buffer).await?;
        if len == 0 {
            break;
        }
        total = total.saturating_add(len);
        let remaining = max_bytes.saturating_sub(kept.len());
        kept.extend_from_slice(&buffer[..len.min(remaining)]);
    }
    Ok((kept, total))
}

impl<'a> CmdLineRunner<'a> {
    fn failure_output_tail(&self) -> Option<FailureOutputTail> {
        if self.on_stdout.is_none() && (self.pr.is_some() || self.pr_arc.is_some()) {
            Some(FailureOutputTail::default())
        } else {
            None
        }
    }

    pub fn new<P: AsRef<OsStr>>(program: P) -> Self {
        Self {
            cmd: Command::new(program),
            pr: None,
            pr_arc: None,
            stdin: None,
            redactor: Default::default(),
            raw: false,
            never_raw: false,
            pass_signals: false,
            on_stdout: None,
            on_stderr: None,
            stderr_as_stdout: false,
            observe_stdout: None,
            on_spawn: None,
            observe_stderr: None,
            timeout: None,
            sandbox: None,
            inherit_env: true,
            stdio: PendingStdio::defaults(),
            kill_on_drop: false,
            #[cfg(windows)]
            raw_args: Vec::new(),
            #[cfg(windows)]
            ctrl_c_group: false,
        }
    }

    pub fn with_sandbox(mut self, sandbox: crate::sandbox::SandboxConfig) -> Self {
        if sandbox.is_active() {
            self.sandbox = Some(sandbox);
        }
        self
    }

    #[cfg(unix)]
    pub fn kill_all(signal: nix::sys::signal::Signal) {
        let use_pgroup = should_use_pgroup();
        let already_delivered = signal == nix::sys::signal::SIGINT && sigint_reached_own_pgrp();
        let own_pgid = nix::unistd::getpgrp();
        let pids = RUNNING_PIDS.lock().unwrap();
        for pid in pids.iter() {
            let pid = *pid as i32;
            let nix_pid = nix::unistd::Pid::from_raw(pid);
            // A terminal Ctrl-C, or an outer mise's `killpg`, already reached
            // children in our pgid. A second SIGINT makes some of them, such
            // as a nested mise or `docker compose`, force-quit instead of
            // shutting down.
            if already_delivered && nix::unistd::getpgid(Some(nix_pid)) == Ok(own_pgid) {
                trace!("{signal}: {pid} already signalled");
                continue;
            }
            if use_pgroup {
                trace!("{signal}: pgid {pid}");
                // Each tracked PID is also the leader of its own pgid (set
                // via setpgid(0,0) in pre_exec), so killpg targets the whole
                // descendant tree. Fall back to plain kill for the rare case
                // where setpgid was skipped (TTY stdin) — still better than
                // silently dropping the signal.
                if nix::sys::signal::killpg(nix_pid, signal).is_err()
                    && let Err(e) = nix::sys::signal::kill(nix_pid, signal)
                {
                    debug!("Failed to kill cmd {pid}: {e}");
                }
            } else {
                trace!("{signal}: {pid}");
                if let Err(e) = nix::sys::signal::kill(nix_pid, signal) {
                    debug!("Failed to kill cmd {pid}: {e}");
                }
            }
        }
    }

    #[cfg(windows)]
    pub fn kill_all() {
        let killers: Vec<_> = {
            let pids = RUNNING_PIDS.lock().unwrap();
            pids.iter()
                .filter(|pid| !kill_job(**pid))
                .filter_map(|pid| {
                    std::process::Command::new("taskkill")
                        .arg("/F")
                        .arg("/T")
                        .arg("/PID")
                        .arg(pid.to_string())
                        .stdout(Stdio::null())
                        .stderr(Stdio::null())
                        .spawn()
                        .inspect_err(|e| warn!("Failed to kill cmd {pid}: {e}"))
                        .ok()
                })
                .collect()
        };
        // Started together and waited on afterwards: a caller that exits as soon
        // as this returns — the Ctrl-C handler does — must not leave a tree it
        // is taking down still standing, and the trees come down concurrently
        // rather than one `taskkill` at a time.
        for mut killer in killers {
            let _ = killer.wait();
        }
    }

    /// Stop every running command the way a per-command timeout does: SIGTERM,
    /// then SIGKILL for whatever has not exited after the grace period. Windows
    /// has no graceful stop yet, so it force-kills the trees at once. Commands
    /// started from here on are killed as they start, for the rest of the process.
    pub async fn terminate_all() {
        TERMINATING.store(true, Ordering::SeqCst);
        #[cfg(unix)]
        {
            // Kept past the leaders' exit: a shell that dies on SIGTERM leaves
            // RUNNING_PIDS while a child ignoring it keeps the group alive.
            let mut pids = RUNNING_PIDS.lock().unwrap().clone();
            for &pid in &pids {
                signal_process_tree(pid, nix::sys::signal::SIGTERM);
            }
            let deadline = Instant::now() + TIMEOUT_GRACE;
            loop {
                // A tree once seen gone is never signalled again: its ID could
                // by now belong to an unrelated process.
                pids = alive_process_trees(&pids);
                if pids.is_empty() || Instant::now() >= deadline {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
            for &pid in &pids {
                signal_process_tree(pid, nix::sys::signal::SIGKILL);
            }
        }
        #[cfg(windows)]
        Self::kill_all();
    }

    pub fn stdin<T: Into<Stdio>>(mut self, cfg: T) -> Self {
        self.stdio.stdin = Some(cfg.into());
        self
    }

    pub fn stdout<T: Into<Stdio>>(mut self, cfg: T) -> Self {
        self.stdio.stdout = Some(cfg.into());
        self
    }

    pub fn stderr<T: Into<Stdio>>(mut self, cfg: T) -> Self {
        self.stdio.stderr = Some(cfg.into());
        self
    }

    pub fn redact(mut self, redactions: impl IntoIterator<Item = String>) -> Self {
        self.redactor = self.redactor.with_additional(redactions);
        self
    }

    /// This command's redactor joined with the global one: every value a line of output may
    /// be redacted for, so [`CappedLines`] cuts a line only where redaction allows.
    fn line_redactor(&self) -> Redactor {
        let global = crate::redactions::GLOBAL_REDACTOR
            .lock()
            .unwrap()
            .patterns_arc();
        if global.is_empty() {
            return self.redactor.clone();
        }
        self.redactor.with_additional(global.iter().cloned())
    }

    pub fn with_on_stdout<F: Fn(String) + Send + 'a>(mut self, on_stdout: F) -> Self {
        self.on_stdout = Some(Box::new(on_stdout));
        self
    }

    pub fn with_on_stderr<F: Fn(String) + Send + 'a>(mut self, on_stderr: F) -> Self {
        self.on_stderr = Some(Box::new(on_stderr));
        self
    }

    pub fn stderr_as_stdout(mut self) -> Self {
        self.stderr_as_stdout = true;
        self
    }

    /// Add an observer for each stdout line. Observers compose: one added
    /// later runs after the earlier ones instead of replacing them, so the
    /// task cache and log export can both watch the same stream.
    pub fn with_stdout_observer<F: Fn(&str) + Send + 'a>(mut self, observer: F) -> Self {
        self.observe_stdout = Some(chain_observers(self.observe_stdout.take(), observer));
        self
    }

    /// Add an observer for each stderr line. See [`Self::with_stdout_observer`].
    pub fn with_stderr_observer<F: Fn(&str) + Send + 'a>(mut self, observer: F) -> Self {
        self.observe_stderr = Some(chain_observers(self.observe_stderr.take(), observer));
        self
    }

    /// Run `on_spawn` once the process has started. It does not run when the command is
    /// cancelled first or fails to start, such as a missing program or a permission error.
    pub fn with_on_spawn<F: FnOnce() + Send + 'a>(mut self, on_spawn: F) -> Self {
        self.on_spawn = Some(Box::new(on_spawn));
        self
    }

    /// Whether a stdout observer is attached. Used to decide whether stdout
    /// must stay piped in output modes that would otherwise inherit it.
    pub fn has_stdout_observer(&self) -> bool {
        self.observe_stdout.is_some()
    }

    /// Whether a stderr observer is attached. See [`Self::has_stdout_observer`].
    pub fn has_stderr_observer(&self) -> bool {
        self.observe_stderr.is_some()
    }

    pub fn current_dir<P: AsRef<Path>>(mut self, dir: P) -> Self {
        self.cmd.current_dir(dir);
        self
    }

    pub fn env_clear(mut self) -> Self {
        self.cmd.env_clear();
        self.inherit_env = false;
        self
    }

    /// Must run after environment/cwd configuration and before custom stdio or
    /// pre-exec setup. Sandboxed commands retain their shell and policy target.
    pub fn optimize_inline(mut self, body: &str, forwarded: &[String], enabled: bool) -> Self {
        if self.sandbox.is_none()
            && let Some(command) = crate::inline_command::direct_command(
                self.cmd.as_std(),
                self.inherit_env,
                body,
                forwarded,
                enabled,
            )
        {
            self.cmd = command.into();
            self.stdio = PendingStdio::defaults();
            self.inherit_env = false;
            #[cfg(windows)]
            self.raw_args.clear();
        }
        self
    }

    pub fn env<K, V>(mut self, key: K, val: V) -> Self
    where
        K: AsRef<OsStr>,
        V: AsRef<OsStr>,
    {
        self.cmd.env(key, val);
        self
    }

    pub fn env_remove<K>(mut self, key: K) -> Self
    where
        K: AsRef<OsStr>,
    {
        self.cmd.env_remove(key);
        self
    }

    pub fn envs<I, K, V>(mut self, vars: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<OsStr>,
        V: AsRef<OsStr>,
    {
        self.cmd.envs(vars);
        self
    }

    pub fn env_values<I, K>(mut self, vars: I) -> Self
    where
        I: IntoIterator<Item = (K, EnvValue)>,
        K: AsRef<OsStr>,
    {
        for (key, value) in vars {
            match value.into_string() {
                Some(value) => self.cmd.env(key, value),
                None => self.cmd.env_remove(key),
            };
        }
        self
    }

    pub fn prepend_path(mut self, paths: Vec<PathBuf>) -> eyre::Result<Self> {
        let existing = self
            .get_env(&PATH_KEY)
            .map(|c| c.to_owned())
            .unwrap_or_else(|| env::var_os(&*PATH_KEY).unwrap());
        let mut path_env = PathEnv::from_iter(env::split_paths(&existing));
        for p in paths {
            path_env.add(p);
        }
        self.cmd.env(&*PATH_KEY, path_env.join());
        Ok(self)
    }

    pub fn get_env(&self, key: &str) -> Option<&OsStr> {
        for (k, v) in self.cmd.as_std().get_envs() {
            if k == key {
                return v;
            }
        }
        None
    }

    pub fn opt_args<S: AsRef<OsStr>>(mut self, arg: &str, values: Option<Vec<S>>) -> Self {
        if let Some(values) = values {
            for value in values {
                self.cmd.arg(arg);
                self.cmd.arg(value);
            }
        }
        self
    }

    pub fn arg<S: AsRef<OsStr>>(mut self, arg: S) -> Self {
        self.cmd.arg(arg.as_ref());
        self
    }

    pub fn args<I, S>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        self.cmd.args(args);
        self
    }

    /// Append a shell's `flags` followed by an inline command `body`. On Windows,
    /// when this runner's program is `cmd[.exe]` and `flags` contain `/c`|`/k`,
    /// the body is handed to cmd *verbatim* (raw args, one outer quote pair via
    /// [`crate::path::cmd_verbatim_args`]) so inner double quotes survive — the
    /// same fix the inline-task path uses. Otherwise (Unix, or a non-cmd Windows
    /// shell) this is exactly `self.args(flags).arg(body)`. See #9355.
    pub fn cmd_body_args(self, flags: &[String], body: &str) -> Self {
        #[cfg(windows)]
        {
            let program = std::path::PathBuf::from(self.cmd.as_std().get_program());
            let runs_command = flags
                .iter()
                .any(|f| f.eq_ignore_ascii_case("/c") || f.eq_ignore_ascii_case("/k"));
            if crate::path::is_cmd_shell_program(&program) && runs_command {
                let cmd_args = crate::path::cmd_verbatim_args(flags, body, &[]);
                return cmd_args.into_iter().fold(self, |r, a| r.raw_arg(a));
            }
        }
        self.args(flags).arg(body)
    }

    /// Append a single argument to the command line *verbatim*, bypassing the
    /// MSVCRT-style quoting std normally applies on Windows. Required when
    /// spawning `cmd.exe /c <script>`: cmd does not understand the `\"`
    /// escaping std would otherwise emit for inner double quotes, so the script
    /// must reach cmd unquoted. See `TaskExecutor::get_cmd_program_and_args`
    /// and discussion #9355.
    #[cfg(windows)]
    pub fn raw_arg<S: AsRef<OsStr>>(mut self, arg: S) -> Self {
        // tokio's `Command` exposes `raw_arg` as an inherent method, so the
        // `std::os::windows::process::CommandExt` trait import is unnecessary.
        self.raw_args.push(self.cmd.as_std().get_args().len());
        self.cmd.raw_arg(arg);
        self
    }

    pub fn with_pr(mut self, pr: &'a dyn SingleReport) -> Self {
        self.pr = Some(pr);
        self
    }
    pub fn with_pr_arc(mut self, pr: Arc<Box<dyn SingleReport>>) -> Self {
        self.pr_arc = Some(pr);
        self
    }
    pub fn raw(mut self, raw: bool) -> Self {
        self.raw = raw;
        self
    }

    /// Never run this command in raw mode, even when the setting asks for it.
    ///
    /// Raw mode hands the child mise's own stdout and stderr, which is the
    /// point of it, and also means nothing passes through the redactor. For a
    /// command whose arguments carry a credential that is not a trade the
    /// `raw` setting can reasonably be making on the user's behalf: they asked
    /// for unfiltered output, not for a token in their scrollback.
    ///
    /// Deliberately per-command rather than "any runner with redactions".
    /// Tasks register redactions too, and silently moving an interactive task
    /// off raw mode would change what it can do.
    pub fn never_raw(mut self) -> Self {
        self.never_raw = true;
        self
    }

    pub fn with_pass_signals(&mut self) -> &mut Self {
        self.pass_signals = true;
        self
    }

    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    pub fn stdin_string(mut self, input: impl Into<String>) -> Self {
        self.stdio.stdin = Some(Stdio::piped());
        self.stdin = Some(input.into());
        self
    }

    pub fn execute(mut self) -> Result<()> {
        let read_lock = raw_read_lock_blocking();
        debug!("$ {self}");
        if (Settings::get().raw || self.raw) && !self.never_raw {
            drop(read_lock);
            let _write_lock = raw_write_lock_blocking();
            return self.execute_raw();
        }
        #[cfg(unix)]
        prepare_execute_child(self.cmd.as_std_mut());
        self.interrupt_on_timeout();
        let mut cp = self
            .spawn_with_etxtbsy_retry()
            .map_err(|err| self.name_missing_program(err))
            .wrap_err_with(|| format!("failed to execute command: {self}"))?;
        let id = cp.id();
        register_running_pid(id);
        trace!("Started process: {id} for {}", self.get_program());
        let (tx, rx) = channel();
        if let Some(stdout) = cp.stdout.take() {
            thread::spawn({
                let name = self.to_string();
                let tx = tx.clone();
                move || {
                    for line in BufReader::new(stdout).lines() {
                        match line {
                            Ok(line) => {
                                let _ = tx.send(ChildProcessOutput::Stdout(line));
                            }
                            Err(e) => warn!("Failed to read stdout for {name}: {e}"),
                        }
                    }
                }
            });
        }
        if let Some(stderr) = cp.stderr.take() {
            thread::spawn({
                let name = self.to_string();
                let tx = tx.clone();
                move || {
                    for line in BufReader::new(stderr).lines() {
                        match line {
                            Ok(line) => {
                                let _ = tx.send(ChildProcessOutput::Stderr(line));
                            }
                            Err(e) => warn!("Failed to read stderr for {name}: {e}"),
                        }
                    }
                }
            });
        }
        if let Some(text) = self.stdin.take() {
            let mut stdin = cp.stdin.take().unwrap();
            thread::spawn(move || {
                stdin.write_all(text.as_bytes()).unwrap();
            });
        }
        #[cfg(not(target_os = "windows"))]
        let mut sighandle = None;
        #[cfg(not(target_os = "windows"))]
        if self.pass_signals && !crate::testing::active() {
            // SIGINT is left to mise's Ctrl-C handler, whose `kill_all`
            // already signals every running command. Forwarding it here too
            // delivered each Ctrl-C twice, which a nested mise (and tools like
            // `docker compose`) take as a second Ctrl-C and force-quit.
            let mut signals = Signals::new([SIGTERM, SIGHUP, SIGQUIT, SIGUSR1, SIGUSR2])?;
            sighandle = Some(signals.handle());
            let tx = tx.clone();
            thread::spawn(move || {
                for sig in &mut signals {
                    let _ = tx.send(ChildProcessOutput::Signal(sig));
                }
            });
        }
        thread::spawn(move || {
            let status = cp.wait().unwrap();
            #[cfg(not(target_os = "windows"))]
            if let Some(sighandle) = sighandle {
                sighandle.close();
            }
            let _ = tx.send(ChildProcessOutput::ExitStatus(status));
        });

        let timeout_guard = self
            .timeout
            .map(|t| TimeoutGuard::new(t, id, self.interruptible()));

        let mut failure_output = self.failure_output_tail();
        // The child's last word, kept for the error itself. The live output is
        // long gone by the time anyone reads `exit code 127`, and under
        // `--quiet` it was never printed at all.
        let mut last_stderr: Option<String> = None;
        let mut status = None;
        let mut timed_out_by_exit = None;
        // Once ExitStatus arrives we set a deadline and switch to recv_timeout
        // so a grandchild that inherited the pipes can't hang us forever
        // waiting for EOF. See PIPE_DRAIN_TIMEOUT.
        let mut drain_deadline: Option<Instant> = None;
        loop {
            let msg = match drain_deadline {
                Some(deadline) => {
                    let remaining = deadline.saturating_duration_since(Instant::now());
                    if remaining.is_zero() {
                        debug!("pipe drain timeout for {id}, abandoning readers");
                        break;
                    }
                    match rx.recv_timeout(remaining) {
                        Ok(m) => m,
                        Err(RecvTimeoutError::Timeout) => {
                            debug!("pipe drain timeout for {id}, abandoning readers");
                            break;
                        }
                        Err(RecvTimeoutError::Disconnected) => break,
                    }
                }
                None => match rx.recv() {
                    Ok(m) => m,
                    Err(_) => break,
                },
            };
            match msg {
                ChildProcessOutput::Stdout(line) => {
                    let line = self.redactor.redact(&line);
                    if let Some(output) = &mut failure_output {
                        self.on_stdout(line.clone());
                        output.push(line);
                    } else {
                        self.on_stdout(line);
                    }
                }
                ChildProcessOutput::Stderr(line) => {
                    let line = self.redactor.redact(&line);
                    if !line.trim().is_empty() {
                        last_stderr = Some(line.clone());
                    }
                    if self.stderr_as_stdout
                        && self.on_stderr.is_none()
                        && let Some(output) = &mut failure_output
                    {
                        self.on_stderr(line.clone());
                        output.push(line);
                    } else {
                        self.on_stderr(line);
                    }
                }
                ChildProcessOutput::ExitStatus(s) => {
                    status = Some(s);
                    timed_out_by_exit = timed_out_at_exit(timeout_guard.as_ref());
                    drain_deadline = Some(Instant::now() + PIPE_DRAIN_TIMEOUT);
                }
                #[cfg(not(windows))]
                ChildProcessOutput::Signal(sig) => {
                    let pid = nix::unistd::Pid::from_raw(id as i32);
                    let nix_sig = nix::sys::signal::Signal::try_from(sig).unwrap();
                    if should_use_pgroup() {
                        debug!("Received signal {sig}, forwarding to pgid {id}");
                        if nix::sys::signal::killpg(pid, nix_sig).is_err() {
                            let _ = nix::sys::signal::kill(pid, nix_sig);
                        }
                    } else {
                        debug!("Received signal {sig}, forwarding to {id}");
                        let _ = nix::sys::signal::kill(pid, nix_sig);
                    }
                }
            }
        }
        // Removed after rx loop drains (not inside ExitStatus arm) so kill_all
        // can still reach this PID while output is being processed.
        unregister_running_pid(id);
        if let Some(g) = &timeout_guard {
            g.cancel();
        }

        let status = status.unwrap();

        if let Some(duration) = timed_out_by_exit {
            bail!("timed out after {duration:?}");
        }
        if !status.success() {
            let mut output = failure_output.map_or_else(Vec::new, FailureOutputTail::into_output);
            if let Some(line) = last_stderr {
                output.push((line, OutputSource::Stderr));
            }
            self.on_error(output, status)?;
        }

        Ok(())
    }

    pub async fn execute_async(self) -> Result<()> {
        self.execute_async_with_cancel_check(|| false).await
    }

    /// Execute a command while preventing cancellation from being lost between
    /// the pre-spawn check and PID registration.
    pub async fn execute_async_with_cancel_check(
        mut self,
        is_cancelled: impl Fn() -> bool + Send + Sync,
    ) -> Result<()> {
        if is_cancelled() {
            return Err(crate::errors::ProcessError::TaskInterrupted.into());
        }
        let read_lock = raw_read_lock().await;
        debug!("$ {self}");
        if (Settings::get().raw || self.raw) && !self.never_raw {
            drop(read_lock);
            let _write_lock = raw_write_lock().await;
            return self.execute_raw_async_with_cancel_check(is_cancelled).await;
        }
        #[cfg(unix)]
        prepare_execute_child(self.cmd.as_std_mut());
        self.interrupt_on_timeout();
        let mut cp = self
            .spawn_async_with_etxtbsy_retry()
            .await
            .map_err(|err| self.name_missing_program(err))
            .wrap_err_with(|| format!("failed to execute command: {self}"))?;
        let id = cp.id().unwrap_or_default();
        register_running_pid(id);
        if is_cancelled() {
            #[cfg(unix)]
            signal_process_tree(id, nix::sys::signal::SIGINT);
            #[cfg(windows)]
            kill_process_tree(id);
        }
        trace!("Started process: {id} for {}", self.get_program());
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let line_redactor = self.line_redactor();
        if let Some(stdout) = cp.stdout.take() {
            let name = self.to_string();
            let tx = tx.clone();
            let line_redactor = line_redactor.clone();
            tokio::spawn(async move {
                let mut lines = CappedLines::new(TokioBufReader::new(stdout), line_redactor);
                loop {
                    match lines.next_line().await {
                        Ok(Some(line)) => {
                            let _ = tx.send(ChildProcessOutput::Stdout(line));
                        }
                        Ok(None) => break,
                        Err(e) => {
                            warn!("Failed to read stdout for {name}: {e}");
                            break;
                        }
                    }
                }
            });
        }
        if let Some(stderr) = cp.stderr.take() {
            let name = self.to_string();
            let tx = tx.clone();
            let line_redactor = line_redactor.clone();
            tokio::spawn(async move {
                let mut lines = CappedLines::new(TokioBufReader::new(stderr), line_redactor);
                loop {
                    match lines.next_line().await {
                        Ok(Some(line)) => {
                            let _ = tx.send(ChildProcessOutput::Stderr(line));
                        }
                        Ok(None) => break,
                        Err(e) => {
                            warn!("Failed to read stderr for {name}: {e}");
                            break;
                        }
                    }
                }
            });
        }
        if let Some(text) = self.stdin.take()
            && let Some(mut stdin) = cp.stdin.take()
        {
            tokio::spawn(async move {
                let _ = stdin.write_all(text.as_bytes()).await;
            });
        }
        #[cfg(not(target_os = "windows"))]
        let mut sighandle = None;
        #[cfg(not(target_os = "windows"))]
        if self.pass_signals && !crate::testing::active() {
            // SIGINT is left to mise's Ctrl-C handler; see `execute`.
            let mut signals = Signals::new([SIGTERM, SIGHUP, SIGQUIT, SIGUSR1, SIGUSR2])?;
            sighandle = Some(signals.handle());
            let tx = tx.clone();
            thread::spawn(move || {
                for sig in &mut signals {
                    let _ = tx.send(ChildProcessOutput::Signal(sig));
                }
            });
        }
        drop(tx);

        let timeout_guard = self
            .timeout
            .map(|t| TimeoutGuard::new(t, id, self.interruptible()));
        let mut failure_output = self.failure_output_tail();
        // The child's last word, kept for the error itself. The live output is
        // long gone by the time anyone reads `exit code 127`, and under
        // `--quiet` it was never printed at all.
        let mut last_stderr: Option<String> = None;
        let mut status = None;
        let mut wait = Box::pin(cp.wait());
        loop {
            tokio::select! {
                result = &mut wait, if status.is_none() => {
                    #[cfg(not(target_os = "windows"))]
                    if let Some(sighandle) = sighandle.take() {
                        sighandle.close();
                    }
                    status = Some(result?);
                    break;
                }
                msg = rx.recv() => {
                    let Some(msg) = msg else {
                        if status.is_none() {
                            #[cfg(not(target_os = "windows"))]
                            if let Some(sighandle) = sighandle.take() {
                                sighandle.close();
                            }
                            status = Some(wait.await?);
                        }
                        break;
                    };
                    match msg {
                        ChildProcessOutput::Stdout(line) => {
                            let line = self.redactor.redact(&line);
                            if let Some(output) = &mut failure_output {
                                self.on_stdout(line.clone());
                                output.push(line);
                            } else {
                                self.on_stdout(line);
                            }
                        }
                        ChildProcessOutput::Stderr(line) => {
                            let line = self.redactor.redact(&line);
                            if !line.trim().is_empty() {
                                last_stderr = Some(line.clone());
                            }
                            if self.stderr_as_stdout
                                && self.on_stderr.is_none()
                                && let Some(output) = &mut failure_output
                            {
                                self.on_stderr(line.clone());
                                output.push(line);
                            } else {
                                self.on_stderr(line);
                            }
                        }
                        ChildProcessOutput::ExitStatus(_) => {}
                        #[cfg(not(windows))]
                        ChildProcessOutput::Signal(sig) => {
                            let pid = nix::unistd::Pid::from_raw(id as i32);
                            let nix_sig = nix::sys::signal::Signal::try_from(sig).unwrap();
                            if should_use_pgroup() {
                                debug!("Received signal {sig}, forwarding to pgid {id}");
                                if nix::sys::signal::killpg(pid, nix_sig).is_err() {
                                    let _ = nix::sys::signal::kill(pid, nix_sig);
                                }
                            } else {
                                debug!("Received signal {sig}, forwarding to {id}");
                                let _ = nix::sys::signal::kill(pid, nix_sig);
                            }
                        }
                    }
                }
            }
        }
        let timed_out_by_exit = timed_out_at_exit(timeout_guard.as_ref());
        let drain_deadline = Instant::now() + PIPE_DRAIN_TIMEOUT;
        loop {
            let remaining = drain_deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                debug!("pipe drain timeout for {id}, abandoning readers");
                break;
            }
            let msg = match tokio::time::timeout(remaining, rx.recv()).await {
                Ok(Some(msg)) => msg,
                Ok(None) => break,
                Err(_) => {
                    debug!("pipe drain timeout for {id}, abandoning readers");
                    break;
                }
            };
            match msg {
                ChildProcessOutput::Stdout(line) => {
                    let line = self.redactor.redact(&line);
                    if let Some(output) = &mut failure_output {
                        self.on_stdout(line.clone());
                        output.push(line);
                    } else {
                        self.on_stdout(line);
                    }
                }
                ChildProcessOutput::Stderr(line) => {
                    let line = self.redactor.redact(&line);
                    if !line.trim().is_empty() {
                        last_stderr = Some(line.clone());
                    }
                    if self.stderr_as_stdout
                        && self.on_stderr.is_none()
                        && let Some(output) = &mut failure_output
                    {
                        self.on_stderr(line.clone());
                        output.push(line);
                    } else {
                        self.on_stderr(line);
                    }
                }
                ChildProcessOutput::ExitStatus(_) => {}
                #[cfg(not(windows))]
                ChildProcessOutput::Signal(_) => {}
            }
        }
        unregister_running_pid(id);
        if let Some(g) = &timeout_guard {
            g.cancel();
        }

        let status = status.unwrap();
        if let Some(duration) = timed_out_by_exit {
            bail!("timed out after {duration:?}");
        }
        if !status.success() {
            let mut output = failure_output.map_or_else(Vec::new, FailureOutputTail::into_output);
            if let Some(line) = last_stderr {
                output.push((line, OutputSource::Stderr));
            }
            self.on_error(output, status)?;
        }

        Ok(())
    }

    /// Run a command while incrementally hashing its raw stdout and stderr.
    ///
    /// Unlike `read`, this never buffers the complete output in memory. The
    /// combined byte limit also prevents commands that emit indefinitely from
    /// consuming unbounded resources.
    pub async fn execute_hashes_async(self, max_output_bytes: usize) -> Result<(String, String)> {
        self.execute_hashes_async_with_drain_timeout(
            max_output_bytes,
            PIPE_DRAIN_TIMEOUT,
            PIPE_DRAIN_GRACE,
        )
        .await
    }

    async fn execute_hashes_async_with_drain_timeout(
        mut self,
        max_output_bytes: usize,
        pipe_drain_timeout: Duration,
        pipe_drain_grace: Duration,
    ) -> Result<(String, String)> {
        let _read_lock = raw_read_lock().await;
        debug!("$ {self}");
        self.kill_on_drop = true;
        // These commands are non-interactive probes: nothing reads stdin and
        // both output streams are piped. Detaching stdin from the terminal
        // means the child can never need the controlling TTY, so unlike
        // `execute()` we can always create a dedicated process group without
        // risking SIGTTIN. That guarantee matters here — cleanup on timeout,
        // an output-limit breach, or a stuck pipe relies on `killpg` reaching
        // descendants, not just the direct child.
        self.stdio.stdin = Some(Stdio::null());
        #[cfg(unix)]
        if should_use_pgroup() {
            self.cmd.env(TASK_PGID_MANAGED_ENV, "1");
            unsafe {
                self.cmd.as_std_mut().pre_exec(|| {
                    let _ = nix::unistd::setpgid(
                        nix::unistd::Pid::from_raw(0),
                        nix::unistd::Pid::from_raw(0),
                    );
                    Ok(())
                });
            }
        }
        self.interrupt_on_timeout();
        let mut cp = self
            .spawn_async_with_etxtbsy_retry()
            .await
            .map_err(|err| self.name_missing_program(err))
            .wrap_err_with(|| format!("failed to execute command: {self}"))?;
        let id = cp.id().unwrap_or_default();
        let _running_pid = RunningPidGuard::new(cp.id());
        trace!("Started process: {id} for {}", self.get_program());

        let (tx, mut rx) = tokio::sync::mpsc::channel(16);
        if let Some(mut stdout) = cp.stdout.take() {
            let tx = tx.clone();
            tokio::spawn(async move {
                let mut buffer = vec![0; 8192];
                loop {
                    match stdout.read(&mut buffer).await {
                        Ok(0) => break,
                        Ok(len) => {
                            if tx
                                .send(HashedProcessOutput::Stdout(buffer[..len].to_vec()))
                                .await
                                .is_err()
                            {
                                break;
                            }
                        }
                        Err(err) => {
                            let _ = tx.send(HashedProcessOutput::ReadError("stdout", err)).await;
                            break;
                        }
                    }
                }
            });
        }
        if let Some(mut stderr) = cp.stderr.take() {
            let tx = tx.clone();
            tokio::spawn(async move {
                let mut buffer = vec![0; 8192];
                loop {
                    match stderr.read(&mut buffer).await {
                        Ok(0) => break,
                        Ok(len) => {
                            if tx
                                .send(HashedProcessOutput::Stderr(buffer[..len].to_vec()))
                                .await
                                .is_err()
                            {
                                break;
                            }
                        }
                        Err(err) => {
                            let _ = tx.send(HashedProcessOutput::ReadError("stderr", err)).await;
                            break;
                        }
                    }
                }
            });
        }
        drop(tx);

        let timeout_guard = self
            .timeout
            .map(|timeout| TimeoutGuard::new(timeout, id, self.interruptible()));
        let mut stdout_hasher = blake3::Hasher::new();
        let mut stderr_hasher = blake3::Hasher::new();
        let mut output_bytes = 0usize;
        let mut consume = |output: HashedProcessOutput| -> Result<()> {
            match output {
                HashedProcessOutput::Stdout(bytes) => {
                    output_bytes = output_bytes.saturating_add(bytes.len());
                    if output_bytes > max_output_bytes {
                        bail!("command output exceeded {max_output_bytes} bytes");
                    }
                    stdout_hasher.update(&bytes);
                }
                HashedProcessOutput::Stderr(bytes) => {
                    output_bytes = output_bytes.saturating_add(bytes.len());
                    if output_bytes > max_output_bytes {
                        bail!("command output exceeded {max_output_bytes} bytes");
                    }
                    stderr_hasher.update(&bytes);
                }
                HashedProcessOutput::ReadError(stream, err) => {
                    bail!("failed to read command {stream}: {err}");
                }
            }
            Ok(())
        };
        let mut status = None;
        let mut wait = Box::pin(cp.wait());
        loop {
            tokio::select! {
                result = &mut wait, if status.is_none() => {
                    status = Some(result?);
                    break;
                }
                output = rx.recv() => {
                    let Some(output) = output else {
                        status = Some(wait.await?);
                        break;
                    };
                    if let Err(err) = consume(output) {
                        #[cfg(unix)]
                        signal_process_tree(id, nix::sys::signal::Signal::SIGKILL);
                        #[cfg(windows)]
                        kill_process_tree(id);
                        let _ = wait.await;
                        return Err(err);
                    }
                }
            }
        }
        let timed_out_by_exit = timed_out_at_exit(timeout_guard.as_ref());
        // The deadline measures wall-clock time, so on a starved machine it can
        // pass while this task and the reader tasks were all unscheduled, with
        // the pipes already closed. When it passes, give the readers one short
        // grace window to deliver what they already have before calling the
        // pipes held.
        let mut drain_deadline = Instant::now() + pipe_drain_timeout;
        let mut graced = false;
        loop {
            // `timeout` polls the channel before the timer, so output that is
            // already queued wins even when the deadline has passed.
            let remaining = drain_deadline.saturating_duration_since(Instant::now());
            let output = match tokio::time::timeout(remaining, rx.recv()).await {
                Ok(Some(output)) => output,
                Ok(None) => break,
                Err(_) if !graced => {
                    graced = true;
                    drain_deadline = Instant::now() + pipe_drain_grace;
                    continue;
                }
                Err(_) => {
                    #[cfg(unix)]
                    signal_process_tree(id, nix::sys::signal::Signal::SIGKILL);
                    #[cfg(windows)]
                    kill_process_tree(id);
                    bail!("command output pipes did not close within {pipe_drain_timeout:?}");
                }
            };
            if let Err(err) = consume(output) {
                #[cfg(unix)]
                signal_process_tree(id, nix::sys::signal::Signal::SIGKILL);
                #[cfg(windows)]
                kill_process_tree(id);
                return Err(err);
            }
        }

        if let Some(guard) = &timeout_guard {
            guard.cancel();
        }
        let status = status.expect("command wait must complete");
        if let Some(timeout) = timed_out_by_exit {
            bail!("timed out after {timeout:?}");
        }
        if !status.success() {
            bail!("exited with non-zero status: {status}");
        }
        Ok((
            stdout_hasher.finalize().to_hex().to_string(),
            stderr_hasher.finalize().to_hex().to_string(),
        ))
    }

    /// Run the command and return stdout, even when raw mode is enabled.
    pub async fn read(mut self) -> Result<String> {
        let _read_lock = raw_read_lock().await;
        debug!("$ {self}");
        self.kill_on_drop = true;
        #[cfg(unix)]
        if should_use_pgroup() {
            self.cmd.env(TASK_PGID_MANAGED_ENV, "1");
            unsafe {
                self.cmd.as_std_mut().pre_exec(|| {
                    let stdin = std::os::fd::BorrowedFd::borrow_raw(0);
                    if !std::io::IsTerminal::is_terminal(&stdin) {
                        let _ = nix::unistd::setpgid(
                            nix::unistd::Pid::from_raw(0),
                            nix::unistd::Pid::from_raw(0),
                        );
                    }
                    Ok(())
                });
            }
        }
        let mut cp = self
            .spawn_async_with_etxtbsy_retry()
            .await
            .map_err(|err| self.name_missing_program(err))
            .wrap_err_with(|| format!("failed to execute command: {self}"))?;
        let id = cp.id();
        let _running_pid = RunningPidGuard::new(id);
        trace!(
            "Started process: {} for {}",
            id.unwrap_or_default(),
            self.get_program()
        );
        if let Some(text) = self.stdin.take()
            && let Some(mut stdin) = cp.stdin.take()
        {
            tokio::spawn(async move {
                let _ = stdin.write_all(text.as_bytes()).await;
            });
        }

        let wait = cp.wait_with_output();
        let output = match self.timeout {
            Some(timeout) => match tokio::time::timeout(timeout, wait).await {
                Ok(output) => output?,
                Err(_) => bail!("timed out after {timeout:?}"),
            },
            None => wait.await?,
        };

        if !output.status.success() {
            let combined_output = captured_output_lines(&self, &output);
            self.replay_captured_stderr(&combined_output);
            self.on_error(combined_output, output.status)?;
        }

        let stdout = String::from_utf8(output.stdout)
            .wrap_err_with(|| format!("{} produced invalid UTF-8 output", self.get_program()))?;
        Ok(stdout.trim_end().to_string())
    }

    #[cfg(unix)]
    pub async fn read_bounded(mut self, max_output_bytes: usize) -> Result<String> {
        let _read_lock = raw_read_lock().await;
        debug!("$ {self}");
        self.kill_on_drop = true;
        #[cfg(unix)]
        if should_use_pgroup() {
            self.cmd.env(TASK_PGID_MANAGED_ENV, "1");
            unsafe {
                self.cmd.as_std_mut().pre_exec(|| {
                    let _ = nix::unistd::setpgid(
                        nix::unistd::Pid::from_raw(0),
                        nix::unistd::Pid::from_raw(0),
                    );
                    Ok(())
                });
            }
        }
        let mut cp = self
            .spawn_async_with_etxtbsy_retry()
            .await
            .map_err(|err| self.name_missing_program(err))
            .wrap_err_with(|| format!("failed to execute command: {self}"))?;
        let id = cp.id().unwrap_or_default();
        let _running_pid = RunningPidGuard::new(cp.id());
        if let Some(text) = self.stdin.take()
            && let Some(mut stdin) = cp.stdin.take()
        {
            tokio::spawn(async move {
                let _ = stdin.write_all(text.as_bytes()).await;
            });
        }
        let stdout = cp.stdout.take().expect("stdout must be piped");
        let stderr = cp.stderr.take().expect("stderr must be piped");
        let stdout_task = tokio::spawn(read_capped(stdout, max_output_bytes));
        let stderr_task = tokio::spawn(read_capped(stderr, max_output_bytes));
        let status = match self.timeout {
            Some(timeout) => match tokio::time::timeout(timeout, cp.wait()).await {
                Ok(status) => status?,
                Err(_) => {
                    #[cfg(unix)]
                    signal_process_tree(id, nix::sys::signal::Signal::SIGKILL);
                    #[cfg(windows)]
                    kill_process_tree(id);
                    let _ = cp.wait().await;
                    bail!("timed out after {timeout:?}");
                }
            },
            None => cp.wait().await?,
        };
        let (stdout, stdout_len) = stdout_task.await??;
        let (stderr, stderr_len) = stderr_task.await??;
        if stdout_len.saturating_add(stderr_len) > max_output_bytes {
            bail!("command output exceeded {max_output_bytes} bytes");
        }
        if !status.success() {
            let output = std::process::Output {
                status,
                stdout: stdout.clone(),
                stderr,
            };
            let combined_output = captured_output_lines(&self, &output);
            self.replay_captured_stderr(&combined_output);
            self.on_error(combined_output, output.status)?;
        }
        let stdout = String::from_utf8(stdout)
            .wrap_err_with(|| format!("{} produced invalid UTF-8 output", self.get_program()))?;
        Ok(stdout.trim_end().to_string())
    }

    fn execute_raw(mut self) -> Result<()> {
        // In raw mode, inherit stdio so the child can interact with the terminal
        // directly. Piped stdout/stderr would deadlock if the child produces >64KB
        // of output since nobody reads the pipes.
        if self.stdin.is_none() {
            self.stdio.stdin = Some(Stdio::inherit());
        }
        self.stdio.stdout = Some(Stdio::inherit());
        self.stdio.stderr = Some(Stdio::inherit());
        self.interrupt_on_timeout();
        let mut cp = self
            .spawn_with_etxtbsy_retry()
            .map_err(|err| self.name_missing_program(err))?;
        let timeout_guard = self
            .timeout
            .map(|t| TimeoutGuard::new(t, cp.id(), self.interruptible()));
        let status = cp.wait()?;
        #[cfg(windows)]
        forget_job(cp.id());
        let timed_out_by_exit = timed_out_at_exit(timeout_guard.as_ref());
        if let Some(g) = &timeout_guard {
            g.cancel();
        }
        if let Some(duration) = timed_out_by_exit {
            bail!("timed out after {duration:?}");
        }
        if !status.success() {
            return self.on_error(vec![], status);
        }
        Ok(())
    }

    async fn execute_raw_async_with_cancel_check(
        mut self,
        is_cancelled: impl Fn() -> bool + Send + Sync,
    ) -> Result<()> {
        if self.stdin.is_none() {
            self.stdio.stdin = Some(Stdio::inherit());
        }
        self.stdio.stdout = Some(Stdio::inherit());
        self.stdio.stderr = Some(Stdio::inherit());
        self.interrupt_on_timeout();
        let mut cp = self
            .spawn_async_with_etxtbsy_retry()
            .await
            .map_err(|err| self.name_missing_program(err))?;
        let id = cp.id().unwrap_or_default();
        if is_cancelled() {
            #[cfg(unix)]
            signal_process_tree(id, nix::sys::signal::SIGINT);
            #[cfg(windows)]
            kill_process_tree(id);
        }
        let timeout_guard = self
            .timeout
            .map(|t| TimeoutGuard::new(t, id, self.interruptible()));
        let status = cp.wait().await?;
        #[cfg(windows)]
        forget_job(id);
        let timed_out_by_exit = timed_out_at_exit(timeout_guard.as_ref());
        if let Some(g) = &timeout_guard {
            g.cancel();
        }
        if let Some(duration) = timed_out_by_exit {
            bail!("timed out after {duration:?}");
        }
        if !status.success() {
            return self.on_error(vec![], status);
        }
        Ok(())
    }

    /// Ask for a Ctrl+C group leader, which only the paths whose [`TimeoutGuard`]
    /// interrupts a timed-out command need.
    #[cfg(windows)]
    fn interrupt_on_timeout(&mut self) {
        self.ctrl_c_group = true;
    }

    #[cfg(unix)]
    fn interrupt_on_timeout(&mut self) {}

    /// Hand the stdio and drop behaviour held on this runner to the command about
    /// to spawn. On Windows a command with a timeout that asked to be interrupted is
    /// spawned through a Ctrl+C group leader, returned here; `self.cmd` stays as is
    /// for error messages.
    fn prepare_spawn(&mut self) -> Option<Command> {
        #[cfg(windows)]
        {
            self.ctrl_c_group &= self.timeout.is_some();
            if self.ctrl_c_group {
                let mut leader = ctrl_c_group::wrap(&self.cmd, self.inherit_env, &self.raw_args);
                self.stdio.apply(&mut leader);
                leader.kill_on_drop(self.kill_on_drop);
                return Some(leader);
            }
        }
        self.stdio.apply(&mut self.cmd);
        self.cmd.kill_on_drop(self.kill_on_drop);
        None
    }

    #[cfg(windows)]
    fn interruptible(&self) -> bool {
        self.ctrl_c_group
    }

    #[cfg(unix)]
    fn interruptible(&self) -> bool {
        true
    }

    /// Spawns the command, then runs the [`Self::with_on_spawn`] callback once it started.
    fn spawn_with_etxtbsy_retry(&mut self) -> std::io::Result<std::process::Child> {
        let child = self.spawn_std_child_with_etxtbsy_retry()?;
        if let Some(on_spawn) = self.on_spawn.take() {
            on_spawn();
        }
        Ok(child)
    }

    /// Retry spawning a process if it fails with ETXTBSY (Text file busy).
    /// This can happen on Linux when executing a binary that was just written/extracted,
    /// as the file descriptor may not be fully closed yet.
    fn spawn_std_child_with_etxtbsy_retry(&mut self) -> std::io::Result<std::process::Child> {
        let mut leader = self.prepare_spawn();
        #[cfg(windows)]
        {
            let is_leader = leader.is_some();
            suspend_for_job(
                leader.as_mut().unwrap_or(&mut self.cmd).as_std_mut(),
                is_leader,
            );
        }
        let mut attempt = 0;
        loop {
            let cmd = leader.as_mut().unwrap_or(&mut self.cmd);
            match cmd.as_std_mut().spawn() {
                #[cfg(windows)]
                Ok(mut child) => {
                    use std::os::windows::io::AsRawHandle;
                    // SAFETY: `child` owns the handle, and is the process with this ID.
                    if let Err(err) = unsafe { join_job(child.id(), child.as_raw_handle()) } {
                        let _ = child.kill();
                        return Err(err);
                    }
                    return Ok(child);
                }
                #[cfg(not(windows))]
                Ok(child) => return Ok(child),
                Err(err) if Self::is_etxtbsy(&err) && attempt < 3 => {
                    attempt += 1;
                    trace!("retrying spawn after ETXTBSY (attempt {}/3)", attempt);
                    // Exponential backoff: 50ms, 100ms, 200ms
                    std::thread::sleep(std::time::Duration::from_millis(50 * (1 << (attempt - 1))));
                }
                Err(err) => return Err(err),
            }
        }
    }

    /// Spawns the command, then runs the [`Self::with_on_spawn`] callback once it started.
    async fn spawn_async_with_etxtbsy_retry(&mut self) -> std::io::Result<tokio::process::Child> {
        let child = self.spawn_child_with_etxtbsy_retry().await?;
        if let Some(on_spawn) = self.on_spawn.take() {
            on_spawn();
        }
        Ok(child)
    }

    async fn spawn_child_with_etxtbsy_retry(&mut self) -> std::io::Result<tokio::process::Child> {
        let mut leader = self.prepare_spawn();
        #[cfg(windows)]
        {
            let is_leader = leader.is_some();
            suspend_for_job(
                leader.as_mut().unwrap_or(&mut self.cmd).as_std_mut(),
                is_leader,
            );
        }
        let mut attempt = 0;
        loop {
            let cmd = leader.as_mut().unwrap_or(&mut self.cmd);
            match cmd.spawn() {
                #[cfg(windows)]
                Ok(mut child) => {
                    // SAFETY: `child` owns the handle, and is the process with this ID.
                    if let (Some(pid), Some(handle)) = (child.id(), child.raw_handle())
                        && let Err(err) = unsafe { join_job(pid, handle) }
                    {
                        let _ = child.start_kill();
                        return Err(err);
                    }
                    return Ok(child);
                }
                #[cfg(not(windows))]
                Ok(child) => return Ok(child),
                Err(err) if Self::is_etxtbsy(&err) && attempt < 3 => {
                    attempt += 1;
                    trace!("retrying spawn after ETXTBSY (attempt {}/3)", attempt);
                    tokio::time::sleep(std::time::Duration::from_millis(50 * (1 << (attempt - 1))))
                        .await;
                }
                Err(err) => return Err(err),
            }
        }
    }

    /// Prepare sandbox restrictions on the command. Must be called before execute()
    /// when sandbox is configured.
    pub async fn apply_sandbox(&mut self) -> eyre::Result<()> {
        let Some(sandbox) = self.sandbox.take() else {
            return Ok(());
        };
        if !sandbox.is_active() {
            return Ok(());
        }

        // Fail early if per-host network filtering is requested
        #[cfg(any(target_os = "linux", target_os = "macos"))]
        sandbox.reject_allow_net()?;
        #[cfg(target_os = "macos")]
        sandbox.reject_unix_sockets()?;

        // Clear the inherited env so the child only sees the filtered vars, which carry the
        // essentials `SandboxConfig::filter_env` keeps (on Windows, `SystemRoot` and the rest
        // of its list). env_clear() also wipes envs explicitly set via .envs(), so save and
        // restore them. macOS does the same when it rebuilds the command for sandbox-exec.
        // `inherit_env` records the clear for whatever rebuilds the command later: on Windows a
        // command with a timeout is started through a Ctrl+C group leader, which would otherwise
        // inherit mise's whole environment and hand it on.
        #[cfg(not(target_os = "macos"))]
        if sandbox.effective_deny_env() {
            let saved: Vec<(std::ffi::OsString, std::ffi::OsString)> = self
                .cmd
                .as_std()
                .get_envs()
                .filter_map(|(k, v)| v.map(|v| (k.to_os_string(), v.to_os_string())))
                .collect();
            self.cmd.env_clear();
            self.inherit_env = false;
            for (k, v) in saved {
                self.cmd.env(k, v);
            }
        }

        #[cfg(target_os = "linux")]
        {
            let initial_program = std::path::PathBuf::from(self.cmd.as_std().get_program());
            // Rules naming a path that does not exist yet get dropped, and the
            // task is then denied. Say so here: pre_exec runs post-fork, where
            // the logger is not available.
            if sandbox.effective_deny_read()
                || sandbox.effective_deny_write()
                || sandbox.effective_deny_unix()
            {
                sandbox.warn_missing_allow_paths();
            }
            // Likewise a kernel that cannot enforce the rules: an error from
            // pre_exec reaches the parent as a bare errno, so refuse it here
            // where the message survives.
            crate::sandbox::landlock_check(&sandbox)?;
            // The child gets a filtered environment, but this process keeps the
            // full one; do not let the child read it back through /proc.
            if sandbox.effective_deny_env() {
                crate::sandbox::hide_environment_from_children()?;
            }
            // Use pre_exec to apply Landlock/seccomp in the child process
            // before it execs the target program. This avoids restricting the mise process.
            let sandbox = sandbox.clone();
            unsafe {
                self.cmd.as_std_mut().pre_exec(move || {
                    if sandbox.effective_deny_read()
                        || sandbox.effective_deny_write()
                        || sandbox.effective_deny_unix()
                        || sandbox.deny_process
                    {
                        crate::sandbox::landlock_apply(&sandbox, &initial_program)
                            .map_err(|e| std::io::Error::other(e.to_string()))?;
                    }
                    if sandbox.effective_deny_net() || sandbox.deny_process {
                        crate::sandbox::seccomp_apply(
                            sandbox.effective_deny_net(),
                            sandbox.deny_process,
                        )
                        .map_err(|e| std::io::Error::other(e.to_string()))?;
                    }
                    Ok(())
                });
            }
        }

        #[cfg(target_os = "macos")]
        {
            // On macOS, rewrite the command to go through sandbox-exec.
            // Build a new Command that wraps the original through sandbox-exec,
            // preserving stdio, cwd, and env from the original.
            let program = self.cmd.as_std().get_program().to_os_string();
            let args: Vec<String> = self
                .cmd
                .as_std()
                .get_args()
                .map(|a| a.to_string_lossy().into_owned())
                .collect();
            let profile =
                crate::sandbox::macos_generate_profile(&sandbox, std::path::Path::new(&program));

            let mut new_cmd = Command::new(crate::sandbox::SANDBOX_EXEC);
            new_cmd.arg("-p").arg(&profile).arg("--").arg(&program);
            for arg in &args {
                new_cmd.arg(arg);
            }
            // Match CmdLineRunner::new() defaults for stdio.
            // execute() reads from piped stdout/stderr; execute_raw() overrides to inherit.
            self.stdio = PendingStdio::defaults();
            if self.stdin.is_some() {
                self.stdio.stdin = Some(Stdio::piped());
            }
            if let Some(dir) = self.cmd.as_std().get_current_dir() {
                new_cmd.current_dir(dir);
            }
            if sandbox.effective_deny_env() {
                new_cmd.env_clear();
                self.inherit_env = false;
            }
            for (k, v) in self.cmd.as_std().get_envs() {
                match v {
                    Some(v) => new_cmd.env(k, v),
                    None => new_cmd.env_remove(k),
                };
            }
            self.cmd = new_cmd;
        }

        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
        if sandbox.restricts_more_than_env() {
            warn!(
                "sandbox file, network and process restrictions are not supported on this platform, running without them"
            );
        }
        Ok(())
    }

    #[cfg(unix)]
    fn is_etxtbsy(err: &std::io::Error) -> bool {
        err.raw_os_error() == Some(nix::errno::Errno::ETXTBSY as i32)
    }

    #[cfg(not(unix))]
    fn is_etxtbsy(_err: &std::io::Error) -> bool {
        false
    }

    fn on_stdout(&self, line: String) {
        let _lock = OUTPUT_LOCK.lock().unwrap();
        if let Some(observer) = &self.observe_stdout {
            observer(&line);
        }
        if let Some(on_stdout) = &self.on_stdout {
            on_stdout(line);
            return;
        }
        if let Some(pr) = self
            .pr
            .or(self.pr_arc.as_ref().map(|arc| arc.as_ref().as_ref()))
        {
            if !line.trim().is_empty() {
                pr.set_process_output(line)
            }
        } else {
            let mut stdout = std::io::stdout().lock();
            let _ = if console::colors_enabled() {
                writeln!(stdout, "{line}\x1b[0m")
            } else {
                writeln!(stdout, "{line}")
            };
        }
    }

    fn on_stderr(&self, line: String) {
        let _lock = OUTPUT_LOCK.lock().unwrap();
        if let Some(observer) = &self.observe_stderr {
            observer(&line);
        }
        if let Some(on_stderr) = &self.on_stderr {
            on_stderr(line);
            return;
        }
        if self.stderr_as_stdout {
            if let Some(pr) = self
                .pr
                .or(self.pr_arc.as_ref().map(|arc| arc.as_ref().as_ref()))
            {
                if !line.trim().is_empty() {
                    pr.set_process_output(line);
                }
            } else {
                let mut stdout = std::io::stdout().lock();
                let _ = writeln!(stdout, "{line}");
            }
            return;
        }
        match self
            .pr
            .or(self.pr_arc.as_ref().map(|arc| arc.as_ref().as_ref()))
        {
            Some(pr) => {
                if !line.trim().is_empty() {
                    pr.println(line)
                }
            }
            None => {
                let mut stderr = std::io::stderr().lock();
                let _ = if console::colors_enabled_stderr() {
                    writeln!(stderr, "{line}\x1b[0m")
                } else {
                    writeln!(stderr, "{line}")
                };
            }
        }
    }

    fn on_error(&self, output: Vec<(String, OutputSource)>, status: ExitStatus) -> Result<()> {
        match self
            .pr
            .or(self.pr_arc.as_ref().map(|arc| arc.as_ref().as_ref()))
        {
            Some(pr) => {
                error!("{} failed", self.get_program());
                if self.on_stdout.is_none() && !pr.shows_process_output() {
                    // Stdout was hidden behind the progress indicator
                    // (pr.set_process_output) so replay it on failure. Only replay
                    // stdout — stderr was already printed during execution
                    // via pr.println. Reporters that already showed stdout as it
                    // arrived would only duplicate it here.
                    let stdout_only: String = output
                        .iter()
                        .filter(|(_, source)| matches!(source, OutputSource::Stdout))
                        .map(|(line, _)| line.as_str())
                        .collect::<Vec<_>>()
                        .join("\n");
                    if !stdout_only.trim().is_empty() {
                        pr.println(stdout_only);
                    }
                }
            }
            None => {
                // eprintln!("{}", output);
            }
        }
        Err(ScriptFailed(
            self.get_program(),
            Some(status),
            stderr_tail_for_error(&output),
        ))?
    }

    fn replay_captured_stderr(&self, output: &[(String, OutputSource)]) {
        for (line, source) in output {
            if matches!(source, OutputSource::Stderr) {
                self.on_stderr(line.clone());
            }
        }
    }

    fn get_program(&self) -> String {
        display_path(PathBuf::from(self.cmd.as_std().get_program()))
    }

    /// Spawning reports a missing program as a bare "No such file or directory
    /// (os error 2)", which reads like a missing file the command touched. Say
    /// which program was not found. The same error also means a missing working
    /// directory, or a script whose interpreter is missing, so the program is
    /// only named once a lookup on the child's PATH confirms it is absent.
    fn name_missing_program(&self, err: std::io::Error) -> std::io::Error {
        if err.kind() != std::io::ErrorKind::NotFound || !self.program_is_missing() {
            return err;
        }
        let program = self.get_program();
        std::io::Error::new(err.kind(), format!("`{program}` not found: {err}"))
    }

    fn program_is_missing(&self) -> bool {
        let cmd = self.cmd.as_std();
        let cwd = cmd.get_current_dir().map(Path::to_path_buf);
        if cwd.as_deref().is_some_and(|dir| !dir.exists()) {
            return false;
        }
        let Some(cwd) = cwd.or_else(|| std::env::current_dir().ok()) else {
            return false;
        };
        // Spawn looks the program up on the child's PATH when the command sets one.
        let path = cmd
            .get_envs()
            .find(|(key, _)| *key == &**crate::env::PATH_KEY)
            .map_or_else(
                || std::env::var_os(&*crate::env::PATH_KEY),
                |(_, v)| v.map(Into::into),
            );
        which::which_in(cmd.get_program(), path, cwd).is_err()
    }

    fn get_args(&self) -> Vec<String> {
        self.cmd
            .as_std()
            .get_args()
            .map(|s| s.to_string_lossy().to_string())
            .collect::<Vec<_>>()
    }
}

/// Number of threads spinning in [`raw_write_lock_blocking`].
///
/// These helpers poll `try_write`/`try_read` rather than awaiting, because their
/// callers are sync. `try_write` never registers as a waiting writer, so without
/// this counter a steady stream of readers starves them: `try_read` succeeds
/// whenever no writer *currently holds* the lock, which is every time the writer
/// is between polls. Readers check this first and yield to a pending writer, which
/// is what makes an exclusive acquisition finish in bounded time.
static RAW_WRITERS_WAITING: AtomicUsize = AtomicUsize::new(0);

/// Decrements [`RAW_WRITERS_WAITING`] however the writer leaves its loop.
struct RawWriterWaiting;

impl RawWriterWaiting {
    fn new() -> Self {
        RAW_WRITERS_WAITING.fetch_add(1, Ordering::AcqRel);
        Self
    }
}

impl Drop for RawWriterWaiting {
    fn drop(&mut self) {
        RAW_WRITERS_WAITING.fetch_sub(1, Ordering::AcqRel);
    }
}

/// Async counterpart of [`raw_read_lock_blocking`].
///
/// Awaiting `RAW_LOCK` directly would queue behind an *async* writer but not a sync
/// one, whose `try_write` polls tokio never sees. Consulting the counter makes both
/// kinds of writer visible to both kinds of reader.
///
/// Acquires first and re-checks, rather than checking then acquiring: a writer that
/// registers during the gap between those two steps would otherwise be bypassed by a
/// reader that had already passed the check. Releasing the guard on that path leaves
/// only the case where the reader held the lock before the writer arrived, which no
/// amount of gating can avoid — an `RwLock` writer always waits for current readers.
pub async fn raw_read_lock() -> tokio::sync::RwLockReadGuard<'static, ()> {
    loop {
        let guard = RAW_LOCK.read().await;
        if RAW_WRITERS_WAITING.load(Ordering::Acquire) == 0 {
            return guard;
        }
        drop(guard);
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
}

/// Async counterpart of [`raw_write_lock_blocking`]. Registers as a waiting writer so
/// sync readers yield to it, then queues on the lock as usual.
pub async fn raw_write_lock() -> tokio::sync::RwLockWriteGuard<'static, ()> {
    let _waiting = RawWriterWaiting::new();
    RAW_LOCK.write().await
}

/// Take the shared side of [`RAW_LOCK`]. Held while an ordinary command runs, so a
/// `--raw` command (or vfox's `cmd.stream`) waits for it before taking the terminal.
///
/// Yields to a writer already waiting, so exclusive acquisition cannot be starved.
pub fn raw_read_lock_blocking() -> tokio::sync::RwLockReadGuard<'static, ()> {
    loop {
        if let Ok(guard) = RAW_LOCK.try_read() {
            // Acquire-then-verify, for the reason given on `raw_read_lock`.
            if RAW_WRITERS_WAITING.load(Ordering::Acquire) == 0 {
                return guard;
            }
            drop(guard);
        }
        thread::sleep(Duration::from_millis(10));
    }
}

/// Take the exclusive side of [`RAW_LOCK`], blocking until no other command holds
/// it. Used by `--raw` commands and by vfox's `cmd.stream`, which needs the same
/// exclusivity so an interactive plugin child owns the terminal. (#13254)
pub fn raw_write_lock_blocking() -> tokio::sync::RwLockWriteGuard<'static, ()> {
    let _waiting = RawWriterWaiting::new();
    loop {
        if let Ok(guard) = RAW_LOCK.try_write() {
            return guard;
        }
        thread::sleep(Duration::from_millis(10));
    }
}

/// A command line with registered secrets removed.
///
/// This rendering is not only for logs. `execute` debug-logs it, but it is also
/// formatted into `failed to execute command: {self}`, and that error is
/// printed by the top-level handler, outside the logger. An
/// argument can legitimately carry a credential (a gem `source` authenticates
/// as basic-auth userinfo on the URL), so redacting where the string is built
/// covers every consumer instead of asking each one to remember.
fn display_command(runner: &CmdLineRunner<'_>) -> String {
    let args = runner.get_args().join(" ");
    crate::redactions::redact_global(&format!("{} {args}", runner.get_program()))
}

impl Display for CmdLineRunner<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", display_command(self))
    }
}

impl Debug for CmdLineRunner<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", display_command(self))
    }
}

/// Tracks whether an output line came from stdout or stderr,
/// so on_error can decide which lines need replaying.
enum OutputSource {
    Stdout,
    Stderr,
}

/// The last thing the child said on stderr, for the error that ends the run.
///
/// One line: an error is rendered on a single row in places like the install
/// summary, and the whole stream was already streamed to the reporter. Callers
/// that route stderr to stdout (`stderr_as_stdout`) replay their output in full
/// instead, so nothing here is the only copy.
fn stderr_tail_for_error(output: &[(String, OutputSource)]) -> Option<String> {
    let line = output
        .iter()
        .rev()
        .find(|(line, source)| matches!(source, OutputSource::Stderr) && !line.trim().is_empty())
        .map(|(line, _)| line.trim())?;
    // By character, not by byte: a diagnostic in a non-ASCII locale would
    // otherwise lose two thirds of its length to UTF-8 encoding.
    let end = line
        .char_indices()
        .nth(STDERR_TAIL_MAX_CHARS)
        .map_or(line.len(), |(index, _)| index);
    if end < line.len() {
        Some(format!("{}…", &line[..end]))
    } else {
        Some(line.to_string())
    }
}

fn captured_output_lines(
    cmd: &CmdLineRunner<'_>,
    output: &std::process::Output,
) -> Vec<(String, OutputSource)> {
    let mut combined = Vec::new();
    for line in String::from_utf8_lossy(&output.stdout).lines() {
        combined.push((cmd.redactor.redact(line), OutputSource::Stdout));
    }
    for line in String::from_utf8_lossy(&output.stderr).lines() {
        combined.push((cmd.redactor.redact(line), OutputSource::Stderr));
    }
    combined
}

enum ChildProcessOutput {
    Stdout(String),
    Stderr(String),
    ExitStatus(ExitStatus),
    #[cfg(not(target_os = "windows"))]
    Signal(i32),
}

/// Run a command asynchronously with `kill_on_drop(true)` so that timeouts
/// (via `tokio::time::timeout`) actually terminate the subprocess.
///
/// This variant **clears** the environment and sets only the provided `env` —
/// use it for backends that pass a full env from `dependency_env()`.
/// `program` is `AsRef<OsStr>` rather than `&str` so callers can pass a resolved path
/// straight through — `Backend::spawn_program` returns an `OsString`, and forcing it
/// through `to_string_lossy()` here would mangle a Windows path that is not valid UTF-8.
pub async fn cmd_read_async<P, I, K, V>(program: P, args: &[&str], env: I) -> Result<String>
where
    P: AsRef<OsStr>,
    I: IntoIterator<Item = (K, V)>,
    K: AsRef<OsStr>,
    V: AsRef<OsStr>,
{
    let program = program.as_ref();
    let display_program = program.to_string_lossy();
    let display_args = args.join(" ");
    debug!("$ {display_program} {display_args}");

    let output = tokio::process::Command::new(program)
        .args(args)
        .env_clear()
        .envs(env)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true)
        .output()
        .await
        .wrap_err_with(|| format!("failed to execute command: {display_program} {display_args}"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "{display_program} {display_args} failed: exit code {}\n{}",
            output.status.code().unwrap_or(-1),
            stderr.trim()
        );
    }

    let stdout = String::from_utf8(output.stdout)
        .wrap_err_with(|| format!("{display_program} produced invalid UTF-8 output"))?;
    Ok(stdout.trim_end().to_string())
}

/// Like [`cmd_read_async`] but **inherits** the current process environment,
/// only adding the provided extra variables on top.
///
/// Use this for core plugins that need the ambient PATH / locale / etc.
pub async fn cmd_read_async_inherited_env<I, K, V>(
    program: &str,
    args: &[&str],
    extra_env: I,
) -> Result<String>
where
    I: IntoIterator<Item = (K, V)>,
    K: AsRef<OsStr>,
    V: AsRef<OsStr>,
{
    let mut cmd = tokio::process::Command::new(program);
    cmd.envs(extra_env);
    cmd_read_async_command(cmd, program, args).await
}

/// [`cmd_read_async_inherited_env`] for a `program` command the caller has
/// already given its environment and working directory.
pub(crate) async fn cmd_read_async_command(
    mut cmd: tokio::process::Command,
    program: &str,
    args: &[&str],
) -> Result<String> {
    let display_args = args.join(" ");
    debug!("$ {program} {display_args}");

    let output = cmd
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true)
        .output()
        .await
        .wrap_err_with(|| format!("failed to execute command: {program} {display_args}"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "{program} {display_args} failed: exit code {}\n{}",
            output.status.code().unwrap_or(-1),
            stderr.trim()
        );
    }

    let stdout = String::from_utf8(output.stdout)
        .wrap_err_with(|| format!("{program} produced invalid UTF-8 output"))?;
    Ok(stdout.trim_end().to_string())
}

#[cfg(all(test, unix))]
mod tests;

#[cfg(all(test, windows))]
mod windows_tests;