pitchfork-cli 2.35.0

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

use super::hooks::{self, HookType, fire_hook};
use super::{SUPERVISOR, Supervisor};
use crate::config_types::OneshotWait;
use crate::daemon::RunOptions;
use crate::daemon_id::DaemonId;
use crate::daemon_status::DaemonStatus;
use crate::error::PortError;
use crate::inherited_fds::CloseInheritedFds;
use crate::ipc::IpcResponse;
use crate::log_store::LogStore;
use crate::log_store::sqlite::LOG_STORE;
use crate::pitchfork_toml::{ReadyCmd, ReadyHttp, ReadyOutput, ReadyPort, RunCommand};
use crate::procs::PROCS;
use crate::settings::{resolve_shell, settings};
use crate::shell::{HideConsoleWindow, Shell, ShellScript, mise_shell_words};
use crate::supervisor::state::UpsertDaemonOpts;
use crate::{Result, env};
use indexmap::IndexMap;
use miette::IntoDiagnostic;
use once_cell::sync::Lazy;
use regex::Regex;
use std::collections::HashMap;
#[cfg(unix)]
use std::ffi::CString;
use std::sync::{Arc, atomic};
use std::time::Duration;
use tokio::select;
use tokio::sync::oneshot;
use tokio::time;

/// Cache for compiled regex patterns to avoid recompilation on daemon restarts
static REGEX_CACHE: Lazy<std::sync::Mutex<HashMap<String, Regex>>> =
    Lazy::new(|| std::sync::Mutex::new(HashMap::new()));

type HttpProbe = std::pin::Pin<
    Box<
        dyn std::future::Future<Output = std::result::Result<reqwest::Response, reqwest::Error>>
            + Send,
    >,
>;

type PortProbe = std::pin::Pin<
    Box<dyn std::future::Future<Output = std::io::Result<tokio::net::TcpStream>> + Send>,
>;

enum ReadyFailure {
    Exit(Option<i32>),
    Termination(String),
}

fn resolve_configured_ready_port(
    configured_port: u16,
    expected_ports: &[u16],
    resolved_ports: &[u16],
) -> u16 {
    let bump_offset = resolved_ports
        .first()
        .unwrap_or(&0)
        .saturating_sub(*expected_ports.first().unwrap_or(&0));
    if expected_ports.contains(&configured_port) && bump_offset > 0 {
        configured_port
            .checked_add(bump_offset)
            .unwrap_or(configured_port)
    } else {
        configured_port
    }
}

fn active_port_from_ready_port(ready_port: u16, resolved_ports: &[u16]) -> Option<u16> {
    resolved_ports
        .first()
        .copied()
        .filter(|&primary_port| primary_port == ready_port)
}

#[cfg(unix)]
#[derive(Clone, Debug, PartialEq, Eq)]
enum RunIdentity {
    Inherit,
    Switch {
        uid: nix::unistd::Uid,
        gid: nix::unistd::Gid,
        username: Option<CString>,
        /// Home directory from the user's passwd entry.
        home: Option<std::path::PathBuf>,
    },
}

/// Get or compile a regex pattern, caching the result for future use
pub(crate) fn get_or_compile_regex(pattern: &str) -> Option<Regex> {
    let mut cache = REGEX_CACHE.lock().unwrap_or_else(|e| e.into_inner());
    if let Some(re) = cache.get(pattern) {
        return Some(re.clone());
    }
    match Regex::new(pattern) {
        Ok(re) => {
            cache.insert(pattern.to_string(), re.clone());
            Some(re)
        }
        Err(e) => {
            error!("invalid regex pattern '{pattern}': {e}");
            None
        }
    }
}

/// Handle for an in-flight readiness command probe.
///
/// The spawned task owns the `tokio::process::Child` and waits for either the
/// process to exit or the cancel signal. Dropping the handle without cancelling
/// leaves the task running, but the child is started with `kill_on_drop(true)`
/// so it will still be terminated when the task ends.
pub(crate) struct CmdProbe {
    pub(crate) cancel_tx: tokio::sync::oneshot::Sender<()>,
    pub(crate) result_rx: tokio::sync::oneshot::Receiver<std::io::Result<std::process::ExitStatus>>,
}

/// Set the environment pitchfork gives a daemon and its `ready_cmd` probe:
/// the original `PATH`, the daemon's own `env`, `PITCHFORK_DAEMON_ID`,
/// `PITCHFORK_DAEMON_NAMESPACE`, `PITCHFORK_RETRY_COUNT`, and `PORT` /
/// `PORT0..N` for its resolved ports.
fn apply_runtime_env(
    command: &mut tokio::process::Command,
    id: &DaemonId,
    retry_count: u32,
    daemon_env: Option<&IndexMap<String, String>>,
    resolved_ports: &[u16],
) {
    if let Some(ref path) = *env::ORIGINAL_PATH {
        command.env("PATH", path);
    }
    if let Some(env_vars) = daemon_env {
        command.envs(env_vars);
    }
    command
        .env("PITCHFORK_DAEMON_ID", id.qualified())
        .env("PITCHFORK_DAEMON_NAMESPACE", id.namespace())
        .env("PITCHFORK_RETRY_COUNT", retry_count.to_string());
    if let Some(port) = resolved_ports.first() {
        command.env("PORT", port.to_string());
        for (index, port) in resolved_ports.iter().enumerate() {
            command.env(format!("PORT{index}"), port.to_string());
        }
    }
}

/// A probe whose result channel is already closed. The caller treats it the
/// same as a probe that exited non-zero and respawns it after the
/// ready_check_interval, preserving the existing retry behaviour.
fn closed_cmd_probe() -> CmdProbe {
    let (cancel_tx, _) = tokio::sync::oneshot::channel();
    let (_, result_rx) = tokio::sync::oneshot::channel();
    CmdProbe {
        cancel_tx,
        result_rx,
    }
}

/// Spawn a readiness command probe and return a handle that can be used to wait
/// for the exit status or cancel the probe.
///
/// The probe is started with `kill_on_drop(true)` as a cancellation fallback. The
/// spawned task waits for the process to exit; if cancellation is requested, it
/// kills the child and waits for it to reap before reporting the result.
pub(crate) fn spawn_cmd_probe(
    id: &DaemonId,
    cmd: &RunCommand,
    dir: &std::path::Path,
    retry_count: u32,
    daemon_env: Option<&IndexMap<String, String>>,
    resolved_ports: &[u16],
) -> CmdProbe {
    let mut command = match cmd {
        // The argv form: the program and its arguments as written, with no
        // shell to reinterpret them, as for a `run` array.
        RunCommand::Argv(argv) => {
            let Some((program, args)) = argv.split_first().filter(|(p, _)| !p.is_empty()) else {
                warn!("daemon {id}: ready_cmd array has no program to run");
                return closed_cmd_probe();
            };
            let mut c = tokio::process::Command::new(program);
            c.args(args);
            c
        }
        // Use the same shell as daemon run and hooks. A probe is not worth
        // failing the daemon over, so an unparseable setting degrades to the
        // platform's own shell here rather than propagating; run_once has
        // already rejected the start by then, so this only fires for a daemon
        // whose settings changed under it.
        RunCommand::Shell(cmd) => match resolve_shell() {
            Ok(parts) => {
                let (program, args) = parts.split_first().unwrap();
                let mut c = tokio::process::Command::new(program);
                c.shell_script(program, args, cmd);
                c
            }
            Err(e) => {
                warn!("daemon {id}: {e}; using the platform shell for this probe");
                Shell::default_for_platform().command(cmd)
            }
        },
    };
    command
        .current_dir(dir)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .kill_on_drop(true)
        .hide_console_window()
        .close_inherited_fds();
    apply_runtime_env(&mut command, id, retry_count, daemon_env, resolved_ports);
    let mut child = match command.spawn() {
        Ok(child) => child,
        Err(e) => {
            warn!("daemon {id}: failed to spawn command probe: {e}");
            return closed_cmd_probe();
        }
    };

    let (cancel_tx, mut cancel_rx) = tokio::sync::oneshot::channel();
    let (result_tx, result_rx) = tokio::sync::oneshot::channel();

    tokio::spawn(async move {
        let status = tokio::select! {
            status = child.wait() => status,
            _ = &mut cancel_rx => {
                let mut child = child;
                let _ = child.kill().await;
                child.wait().await
            }
        };
        let _ = result_tx.send(status);
    });

    CmdProbe {
        cancel_tx,
        result_rx,
    }
}

/// Cancel an active command probe and clear its handle.
fn stop_cmd_probe_state(probe: &mut Option<CmdProbe>) {
    if let Some(p) = probe.take() {
        let _ = p.cancel_tx.send(());
    }
}

/// Spawn a detached task that kills a daemon's process group after its
/// readiness checks are exhausted. A failed kill must be reported before
/// waiting for the child, which may still be alive.
fn spawn_ready_fail_kill(
    id: DaemonId,
    pid: u32,
    stop_cfg: crate::config_types::StopConfig,
) -> tokio::task::JoinHandle<Result<bool>> {
    tokio::spawn(async move {
        debug!("daemon {id}: terminating pid {pid} after readiness failure");
        PROCS
            .kill_process_group_async(pid, stop_cfg.signal.into(), stop_cfg.timeout)
            .await
    })
}

/// Returns true if any configured readiness check can still succeed.
/// A check with no timeout is unbounded; a timed check can still succeed until its
/// deadline fires. `ready_delay` is only used as a fallback when no other check is
/// configured, so it is not counted here.
#[allow(clippy::too_many_arguments)]
fn any_ready_check_remaining(
    ready_output: Option<&ReadyOutput>,
    output_exhausted: bool,
    ready_port: Option<&ReadyPort>,
    port_exhausted: bool,
    ready_http: Option<&ReadyHttp>,
    http_exhausted: bool,
    ready_cmd: Option<&ReadyCmd>,
    cmd_exhausted: bool,
) -> bool {
    ready_output.is_some_and(|o| o.timeout.is_none() || !output_exhausted)
        || ready_port.is_some_and(|p| p.timeout.is_none() || !port_exhausted)
        || ready_http.is_some_and(|h| h.timeout.is_none() || !http_exhausted)
        || ready_cmd.is_some_and(|c| c.timeout.is_none() || !cmd_exhausted)
}

fn delay_readiness_succeeded(
    ready_notified: bool,
    has_other_ready_check: bool,
    process_exited: bool,
    process_running: bool,
) -> bool {
    !ready_notified && !has_other_ready_check && !process_exited && process_running
}

/// Terminal state recorded for a daemon run that has ended, and whether that
/// ending counts as a successful exit.
///
/// A `oneshot` daemon's whole job is to finish, so a clean exit of its own
/// accord is `Completed` rather than `Stopped` — that is what makes it
/// distinguishable from a service that is merely not running, and what lets
/// `depends` treat it as satisfied. An explicit stop is still a stop: the task
/// was interrupted, not completed.
fn terminal_exit_state(
    exit_reason: &str,
    oneshot: bool,
    exit_code: i32,
    exited_cleanly: bool,
) -> (DaemonStatus, bool) {
    match exit_reason {
        "exit" if oneshot => (DaemonStatus::Completed, true),
        "stop" | "exit" => (DaemonStatus::Stopped, exited_cleanly),
        _ => (DaemonStatus::Errored(exit_code), false),
    }
}

/// Whether a stop that arrived after a run's process was already gone should
/// leave the status its monitor settled on alone.
///
/// Only a completed task is left alone: it had already done its work, so there
/// was nothing for the stop to interrupt, and overwriting it would report a
/// failure to anyone waiting on it. Anything else — a failure above all — is
/// replaced by the stop, so the retry checker does not carry on with a task
/// the user has stopped.
/// Why the argv form of `run` cannot be started, if it cannot.
///
/// Config load checks the array as written, but a template can still render
/// the program to nothing, or to `exec`.
/// Why a daemon's `ready_cmd` or `health_cmd` array (named by `field`)
/// cannot be run, if it cannot: its program, after templates are rendered, is
/// empty or `exec`. Config load rejects both as written, but a template can
/// still render to them, and a probe that can never run would keep the start
/// waiting for readiness, or fail every health check.
fn invalid_probe_program(id: &DaemonId, field: &str, run: Option<&RunCommand>) -> Option<String> {
    let RunCommand::Argv(argv) = run? else {
        return None;
    };
    match argv.first().map(String::as_str) {
        None | Some("") => Some(format!(
            "daemon {id} has no program to run in its {field} array"
        )),
        Some("exec") => Some(format!(
            "daemon {id} starts its {field} array with \"exec\"; a {field} array runs the program directly, so remove \"exec\""
        )),
        Some(_) => None,
    }
}

fn invalid_argv_program(id: &DaemonId, argv: &[String]) -> Option<String> {
    match argv.first().map(String::as_str) {
        None | Some("") => Some(format!(
            "daemon {id} has no program to run: its run array starts with an empty value"
        )),
        Some("exec") => Some(format!(
            "daemon {id} starts its run array with \"exec\"; a run array starts the program directly, so remove \"exec\""
        )),
        Some(_) => None,
    }
}

#[cfg(any(windows, test))]
fn unsupported_windows_options(opts: &RunOptions, supervisor_user: &str) -> Option<String> {
    if opts.pty == Some(true) {
        return Some(format!(
            "daemon {}: pty = true is not supported on Windows; remove pty or set it to false",
            opts.id
        ));
    }
    let configured_user = opts.user.as_deref().unwrap_or_default().trim();
    if !configured_user.is_empty() || !supervisor_user.trim().is_empty() {
        return Some(format!(
            "daemon {}: user switching is not supported on Windows; remove the daemon's user and settings.supervisor.user, or set them to empty strings",
            opts.id
        ));
    }
    None
}

/// Program and arguments to spawn for `words`, run through `mise x` when given.
/// Each word stays one argument, including a script carried by shell-exec.
fn launch_command(words: Vec<String>, mise_bin: Option<&std::path::Path>) -> (String, Vec<String>) {
    match mise_bin {
        Some(mise_bin) => {
            let mut args = vec!["x".to_string(), "--".to_string()];
            args.extend(words);
            (mise_bin.to_string_lossy().to_string(), args)
        }
        None => {
            let mut words = words.into_iter();
            // Never empty: a shell resolves to at least its program, and an
            // empty argv is refused before this is reached.
            let program = words.next().unwrap_or_default();
            (program, words.collect())
        }
    }
}

/// Text of one line read from a daemon's output, its line ending removed.
///
/// Decoded as the log sink decodes lines, so output that is not UTF-8 is
/// logged rather than ending the read. A PTY slave's ONLCR turns `\n` into
/// `\r\n`, so every trailing `\r` goes, as the sink also strips them.
fn output_line_text(line: &[u8]) -> String {
    let line = line.strip_suffix(b"\n").unwrap_or(line);
    crate::cli::log_sink::decode_line(line)
        .trim_end_matches('\r')
        .to_string()
}

/// Wait for the start whose result this is to end, and report that result as
/// the waiting start's own. If its caller was canceled, the detached attempt
/// still owns its readiness result.
async fn await_start_result(
    mut start_result: super::StartResult,
    fallback: Option<super::StartResult>,
) -> IpcResponse {
    if let Ok(result) = start_result.wait_for(Option::is_some).await
        && let Some(result) = result.clone()
    {
        return result;
    }
    if let Some(mut attempt) = fallback
        && let Ok(result) = attempt.wait_for(Option::is_some).await
        && let Some(result) = result.clone()
    {
        return result;
    }
    IpcResponse::DaemonFailed {
        error: "start ended without a readiness result".to_string(),
    }
}

/// Where program status reports (OSC 7501) found in a daemon's output go: the
/// daemon, and the start attempt they belong to.
#[derive(Clone)]
struct StatusTarget {
    id: DaemonId,
    token: u64,
}

/// Send each line of `reader` to `tx` until the output ends or nobody is
/// listening.
///
/// Reading stops only there, never on a line's content: a reader that gave up
/// would stop draining the daemon's pipe or PTY, and the daemon would block,
/// or fail, on its next write.
///
/// Program status reports are picked out of the raw bytes as they arrive, not
/// of the lines: a report ends with a terminator, not a newline, so a daemon
/// that prints one without a newline still has it seen straight away.
async fn forward_output_lines<R>(
    mut reader: R,
    tx: tokio::sync::mpsc::Sender<super::OutputLine>,
    status: Option<StatusTarget>,
) where
    R: tokio::io::AsyncBufRead + Unpin,
{
    use tokio::io::AsyncBufReadExt;
    let mut scanner = crate::program_status::OscScanner::default();
    let mut line = Vec::new();
    loop {
        // A read error ends the output too: a Linux PTY master reports the
        // slave closing, once the daemon is gone, as EIO rather than end of
        // file. Whatever of a last, unterminated line arrived before it is
        // still sent.
        let (consumed, complete, last) = match reader.fill_buf().await {
            Ok([]) => (0, false, true),
            Ok(buf) => {
                let (consumed, complete) = match buf.iter().position(|b| *b == b'\n') {
                    Some(i) => (i + 1, true),
                    None => (buf.len(), false),
                };
                line.extend_from_slice(&buf[..consumed]);
                // Only what is consumed is scanned: the rest is offered again
                // by the next read, and scanning it twice would replay a
                // partial report.
                if let Some(status) = &status {
                    for update in scanner.feed(&buf[..consumed]) {
                        let update = match update {
                            crate::program_status::StatusUpdate::Set(s) => Some(s),
                            crate::program_status::StatusUpdate::Clear => None,
                        };
                        super::log_sink::deliver_program_status(&status.id, status.token, update)
                            .await;
                    }
                }
                (consumed, complete, false)
            }
            Err(_) => (0, false, true),
        };
        reader.consume(consumed);
        if complete || (last && !line.is_empty()) {
            let sent = tx
                .send(super::OutputLine {
                    text: output_line_text(&line),
                    source: super::OutputSource::Local,
                })
                .await;
            line.clear();
            if sent.is_err() {
                break;
            }
        }
        if last {
            break;
        }
    }
}

fn stop_keeps_finalized_status(status: &DaemonStatus) -> bool {
    status.is_completed()
}

/// How long a failed start waits for the daemon's output to become queryable
/// before reporting. Typically satisfied in a few dozen milliseconds; a daemon
/// that failed without printing anything waits the whole of it, so keep it
/// short.
const SINK_OUTPUT_TIMEOUT: Duration = Duration::from_millis(400);

/// Marks a daemon as having its retries managed by a foreground `run` for as
/// long as this value lives, so the background checker does not start an
/// attempt out from under it. Released on every exit from the retry loop,
/// including the early returns.
/// Counts a stop of this daemon once the stop is done, while its lock is
/// still held. See `Supervisor::stop_epochs`.
struct StopEpochGuard(DaemonId);

impl Drop for StopEpochGuard {
    fn drop(&mut self) {
        SUPERVISOR.bump_stop_epoch(&self.0);
    }
}

pub(crate) struct RetryingGuard {
    id: DaemonId,
    cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
}

impl RetryingGuard {
    /// Whether a `stop` or a `disable` has asked this retry sequence to end.
    fn is_cancelled(&self) -> bool {
        self.cancel.load(std::sync::atomic::Ordering::Acquire)
    }
}

impl Drop for RetryingGuard {
    fn drop(&mut self) {
        let mut retrying = SUPERVISOR
            .retrying
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        // Drop this claim's flag only. Another sequence for the same daemon
        // may still be running, and it has to stay both protected from the
        // retry checker and reachable by a stop.
        if let Some(claims) = retrying.get_mut(&self.id) {
            claims.retain(|claim| !std::sync::Arc::ptr_eq(&claim.cancel, &self.cancel));
            if claims.is_empty() {
                retrying.remove(&self.id);
            }
        }
    }
}

impl Supervisor {
    /// Whether a start is already handling this daemon's retries.
    pub(crate) fn is_retrying(&self, id: &DaemonId) -> bool {
        self.retrying
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(id)
            .is_some_and(|claims| !claims.is_empty())
    }

    /// How many times this daemon has been stopped so far.
    pub(crate) fn stop_epoch(&self, id: &DaemonId) -> u64 {
        self.stop_epochs
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(id)
            .copied()
            .unwrap_or(0)
    }

    fn bump_stop_epoch(&self, id: &DaemonId) {
        *self
            .stop_epochs
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .entry(id.clone())
            .or_default() += 1;
    }

    pub(super) fn mark_retrying(&self, id: &DaemonId) -> RetryingGuard {
        self.mark_retrying_with_result(id, None)
    }

    fn mark_retrying_with_result(
        &self,
        id: &DaemonId,
        result: Option<&super::StartResult>,
    ) -> RetryingGuard {
        let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        self.retrying
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .entry(id.clone())
            .or_default()
            .push(super::RetryClaim {
                cancel: cancel.clone(),
                result: result.cloned(),
            });
        RetryingGuard {
            id: id.clone(),
            cancel,
        }
    }

    fn retry_result(
        &self,
        id: &DaemonId,
        own_result: Option<&super::StartResult>,
    ) -> Option<super::StartResult> {
        self.retrying
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(id)?
            .iter()
            .filter(|claim| !claim.cancel.load(atomic::Ordering::Acquire))
            .filter_map(|claim| claim.result.as_ref())
            .find(|result| own_result.is_none_or(|own| !own.same_channel(result)))
            .cloned()
    }

    /// Ask a retry sequence for this daemon, if there is one, to
    /// end. A stop is a decision about the daemon, not about one of its
    /// attempts, so the attempts left must not go ahead behind it.
    pub(crate) fn cancel_retrying(&self, id: &DaemonId) {
        if let Some(claims) = self
            .retrying
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(id)
        {
            // Every claim, not just the newest: a start that is sleeping out a
            // backoff is as much a sequence the stop has to end as the one that
            // claimed the daemon last.
            for claim in claims {
                claim
                    .cancel
                    .store(true, std::sync::atomic::Ordering::Release);
            }
        }
    }

    /// Run a daemon, handling retries if configured
    pub async fn run(&self, opts: RunOptions) -> Result<IpcResponse> {
        let id = opts.id.clone();
        let mut restart_mark = None;
        // This start's result, for every start that finds one of its processes
        // still waiting on its ready check (see `claim_or_defer`). Published
        // only once the start ends, so that a start waiting through a failed
        // attempt that is retried gets the outcome of the retries.
        let (result_tx, result_rx) = tokio::sync::watch::channel(None);
        let wait_ready = opts.wait_ready;
        let result = self
            .run_inner(
                opts,
                None,
                &mut restart_mark,
                wait_ready.then_some(&result_rx),
            )
            .await;
        // A forced start records the daemon it replaces as restarting. If no
        // new process took the record over, the restart did not happen.
        if let Some(mark) = restart_mark {
            self.settle_restarting(&id, mark).await;
        }
        result_tx.send_replace(Some(match &result {
            Ok(response) => response.clone(),
            Err(e) => IpcResponse::Error(e.to_string()),
        }));
        result
    }

    /// Record a daemon left `restarting` with no process as `stopped`: its
    /// restart did not start a new process, and leaving the mark in place
    /// would have `pitchfork wait` follow a restart that is never coming.
    ///
    /// `mark` is the daemon's stop epoch right after the restart's own stop.
    /// Any stop since (a `pitchfork stop`, or another restart's stop that
    /// left its own mark) has the last word, so the record is left alone, as
    /// is one that has moved on (a new process, another status).
    pub(crate) async fn settle_restarting(&self, id: &DaemonId, mark: u64) {
        let lock = self.stop_lock(id).await;
        let _guard = lock.lock().await;
        if self.stop_epoch(id) != mark {
            return;
        }
        let mut state_file = self.state_file.lock().await;
        if state_file
            .daemons
            .get(id)
            .is_some_and(|d| d.pid.is_none() && d.status.is_restarting())
        {
            debug!("daemon {id} was not started again after its restart; recording it as stopped");
            state_file.set_status(id, DaemonStatus::Stopped);
        }
    }

    /// Run the remaining retries approved while `stop_epoch` read
    /// `approved_at`. If the daemon has been stopped since, the attempt is
    /// abandoned instead of started.
    ///
    /// `restart_mark` is set as in [`Self::run_inner`], if a forced attempt
    /// stopped a running instance.
    pub(crate) async fn run_retry(
        &self,
        opts: RunOptions,
        approved_at: u64,
        restart_mark: &mut Option<u64>,
    ) -> Result<IpcResponse> {
        let (result_tx, result_rx) = tokio::sync::watch::channel(None);
        let wait_ready = opts.wait_ready;
        let result = self
            .run_inner(
                opts,
                Some(approved_at),
                restart_mark,
                wait_ready.then_some(&result_rx),
            )
            .await;
        result_tx.send_replace(Some(match &result {
            Ok(response) => response.clone(),
            Err(error) => IpcResponse::Error(error.to_string()),
        }));
        result
    }

    /// Reject unsupported options while the caller holds the daemon's stop lock.
    #[cfg(windows)]
    async fn reject_unsupported_windows_options(
        &self,
        opts: &RunOptions,
    ) -> Result<Option<IpcResponse>> {
        let Some(error) = unsupported_windows_options(opts, &settings().supervisor.user) else {
            return Ok(None);
        };
        // A rejected replacement must leave the running instance alone. A
        // rejected retry has no process and must become terminal, or the
        // background checker will keep retrying its old errored record.
        if self
            .get_daemon(&opts.id)
            .await
            .is_none_or(|d| d.pid.is_none())
        {
            self.upsert_daemon(
                UpsertDaemonOpts::from_run_options(opts, DaemonStatus::Failed(error.clone()))
                    .build(),
            )
            .await?;
        }
        Ok(Some(IpcResponse::DaemonFailed { error }))
    }

    /// `restart_mark` is set to the stop epoch a forced start's own stop of
    /// the running instance left, if it made one (see
    /// [`Self::settle_restarting`]).
    ///
    /// `start_result` is where this start's result will be, registered for
    /// each process it spawns while that process waits on its ready check.
    async fn run_inner(
        &self,
        opts: RunOptions,
        approved_at: Option<u64>,
        restart_mark: &mut Option<u64>,
        start_result: Option<&super::StartResult>,
    ) -> Result<IpcResponse> {
        let id = &opts.id;
        let cmd = opts.cmd.clone();

        // Clear any pending autostop for this daemon since it's being started
        {
            let mut pending = self.pending_autostops.lock().await;
            if pending.remove(id).is_some() {
                info!("cleared pending autostop for {id} (daemon starting)");
            }
        }

        // Serialize against any in-flight stop of this daemon: a stop now
        // waits for the whole process group to exit, so the Stopping window
        // can last seconds instead of milliseconds. Starting through that
        // window would collide with the dying instance (duplicate processes,
        // port conflicts). Acquiring the stop lock waits the stop out; the
        // state is re-read afterwards. The guard is owned and handed to
        // run_once, which holds it until the new daemon's Running state and
        // PID are persisted — releasing it before that point would let a
        // concurrent run pass this same check (duplicate processes) or let a
        // concurrent stop see no PID and return without stopping anything.
        let mut stop_guard = Some(self.stop_lock(id).await.lock_owned().await);
        // Checked here, under the daemon's lock, because that is what a stop
        // takes too: an approval from before the stop cannot slip past it.
        // Writing `stopped` over the record is not enough on its own, since an
        // attempt already approved would read that as a daemon free to start.
        if let Some(approved_at) = approved_at
            && self.stop_epoch(id) != approved_at
        {
            info!("daemon {id} was stopped after this retry was decided on; not starting it");
            return Ok(IpcResponse::DaemonNotRunning);
        }
        // Likewise a disable, for every start the supervisor makes on its own
        // (retries, the schedule, boot): each read the disabled set before
        // waiting for this lock, and `disable` takes it too.
        if (approved_at.is_some() || !opts.requested_by_client)
            && self.state_file.lock().await.disabled.contains(id)
        {
            info!("daemon {id} was disabled before this start; not starting it");
            return Ok(IpcResponse::DaemonNotRunning);
        }
        if let Some(response) = self
            .claim_or_defer(&opts, &mut stop_guard, restart_mark, start_result)
            .await?
        {
            return Ok(response);
        }

        // If wait_ready is true and retry is configured, implement retry loop
        if opts.wait_ready && opts.retry.count() > 0 {
            // Claim this daemon's retries for the duration of the loop. The
            // backoff between attempts leaves the record errored with no PID,
            // which is what `check_retry` scans for, and an attempt started
            // there would leave this call reporting on a run it does not own.
            let retrying_claim = self.mark_retrying_with_result(id, start_result);
            // Use saturating_add to avoid overflow when retry = u32::MAX (infinite)
            let max_attempts = opts.retry.count().saturating_add(1);
            let first_attempt = if approved_at.is_some() {
                opts.retry_count
            } else {
                0
            };
            for attempt in first_attempt..max_attempts {
                let mut retry_opts = opts.clone();
                retry_opts.retry_count = attempt;
                retry_opts.cmd = cmd.clone();

                // The first attempt starts under the guard held since the
                // running check above; later attempts re-acquire it so stops
                // are not locked out during the backoff sleeps.
                let mut guard = Some(match stop_guard.take() {
                    Some(guard) => guard,
                    None => self.stop_lock(id).await.lock_owned().await,
                });
                // The background retry checker may have run this attempt for
                // us and seen it succeed while we slept. Starting again would
                // repeat a task that has already done its work — for a
                // migration or a seed, repeating its side effects.
                //
                // Only after a backoff, though. A completed record on the first
                // attempt is the previous run's, and a start is defined to
                // re-run a completed oneshot; short-circuiting here would make
                // that true only for oneshots without `retry`.
                if attempt > 0
                    && let Some(daemon) = self.get_daemon(id).await
                    && daemon.status.is_completed()
                {
                    info!("daemon {id} completed while waiting to retry; not running it again");
                    return Ok(IpcResponse::DaemonReady { daemon });
                }
                // A disable during the backoff ends the sequence, checked under
                // the guard `disable` takes. It wakes the backoff the way a stop
                // does, so it is checked first to report what happened.
                if attempt > 0 && self.state_file.lock().await.disabled.contains(id) {
                    info!(
                        "daemon {id} was disabled while waiting to retry; abandoning its retries"
                    );
                    return Ok(IpcResponse::DaemonFailed {
                        error: "disabled while retrying".to_string(),
                    });
                }
                // A stop that arrived during the backoff ends the sequence.
                // Without this the loop would start the next attempt on a
                // daemon the user has just stopped, and the stop would look
                // like it had done nothing.
                if retrying_claim.is_cancelled() {
                    info!("daemon {id} was stopped while waiting to retry; abandoning its retries");
                    return Ok(IpcResponse::DaemonFailed {
                        error: "stopped while retrying".to_string(),
                    });
                }
                // Ownership has to be re-checked on every attempt, not just
                // the first. Another start can claim the daemon during the
                // backoff, when this attempt no longer holds its stop lock.
                // Spawning another process here would replace that attempt's
                // monitor registration and leave its process unmonitored.
                if let Some(response) = self
                    .claim_or_defer(&retry_opts, &mut guard, restart_mark, start_result)
                    .await?
                {
                    return Ok(response);
                }
                let Some(guard) = guard else {
                    // Only the deferring paths take the guard, and each of
                    // those returned above.
                    return Ok(IpcResponse::DaemonAlreadyRunning);
                };
                let result = self.run_once(retry_opts, guard, start_result).await?;

                match result {
                    IpcResponse::DaemonReady { daemon } => {
                        return Ok(IpcResponse::DaemonReady { daemon });
                    }
                    IpcResponse::DaemonFailedWithCode {
                        exit_code,
                        resolved_ports,
                    } => {
                        if attempt < opts.retry.count() {
                            // `run_once` reports failure the moment the process
                            // exits, but its monitor finalizes the record only
                            // after draining the process's remaining output.
                            // Until then the record still names this attempt's
                            // PID, and the next attempt's ownership check would
                            // read its own dead predecessor as a competing run
                            // and abandon the retries that are left.
                            let attempt_pid = self.get_daemon(id).await.and_then(|d| d.pid);
                            self.wait_for_exit_finalized(id, attempt_pid).await;
                            let backoff_secs = 2u64.saturating_pow(attempt).min(3600);
                            info!(
                                "daemon {id} failed (attempt {}/{}), retrying in {}s",
                                attempt + 1,
                                max_attempts,
                                backoff_secs
                            );
                            fire_hook(
                                HookType::OnRetry,
                                id.clone(),
                                super::hooks::HookDirs::new(
                                    opts.dir.0.clone(),
                                    opts.watch_base_dir.clone(),
                                ),
                                attempt + 1,
                                opts.env.clone(),
                                resolved_ports,
                                vec![],
                            )
                            .await;
                            // Slept in slices so a stop arriving during a
                            // long backoff — they grow to an hour — is acted
                            // on when it arrives rather than when the sleep
                            // happens to end.
                            let backoff_deadline =
                                tokio::time::Instant::now() + Duration::from_secs(backoff_secs);
                            while tokio::time::Instant::now() < backoff_deadline
                                && !retrying_claim.is_cancelled()
                            {
                                let remaining = backoff_deadline - tokio::time::Instant::now();
                                time::sleep(remaining.min(Duration::from_millis(200))).await;
                            }
                            continue;
                        } else {
                            info!("daemon {id} failed after {max_attempts} attempts");
                            return Ok(IpcResponse::DaemonFailedWithCode {
                                exit_code,
                                resolved_ports,
                            });
                        }
                    }
                    other => return Ok(other),
                }
            }
        }

        // No retry or wait_ready is false
        let guard = match stop_guard.take() {
            Some(guard) => guard,
            None => self.stop_lock(id).await.lock_owned().await,
        };
        self.run_once(opts, guard, start_result).await
    }

    /// Wait for a just-failed attempt's monitor to write its terminal state,
    /// clearing the PID from the record.
    ///
    /// Bounded a little beyond the monitor's own five-second output drain, the
    /// longest it can hold the record after the process has gone. Giving up
    /// early is safe: the ownership check that follows simply sees a PID and
    /// defers, which is what it would have done anyway.
    ///
    /// `pid` names the run being waited for, so a record that has moved on to
    /// another run is not mistaken for this one still finishing.
    async fn wait_for_exit_finalized(&self, id: &DaemonId, pid: Option<u32>) {
        let deadline = tokio::time::Instant::now() + Duration::from_secs(8);
        loop {
            match self.get_daemon(id).await {
                Some(daemon) if pid.map_or(daemon.pid.is_some(), |pid| daemon.pid == Some(pid)) => {
                }
                _ => return,
            }
            if tokio::time::Instant::now() >= deadline {
                debug!("daemon {id}: previous attempt has not finalized yet; continuing anyway");
                return;
            }
            time::sleep(Duration::from_millis(50)).await;
        }
    }

    /// Decide whether this start may take the daemon's record, or must stand
    /// down because a live run already owns it.
    ///
    /// Returns `Some(response)` when the start is rejected or must report an
    /// existing run's outcome, and `None` when the record is free (including
    /// after a forced stop of the previous instance).
    ///
    /// The caller must hold the daemon's stop lock. Unsupported Windows options
    /// are rejected before a forced claim can stop an existing instance, even
    /// when settings changed during a foreground retry's backoff.
    ///
    /// `stop_guard` is released before an in-flight oneshot or another start's
    /// ready check is awaited: that wait lasts as long as the run does, and
    /// holding the lock would block a stop of the very run being waited on.
    async fn claim_or_defer(
        &self,
        opts: &RunOptions,
        stop_guard: &mut Option<tokio::sync::OwnedMutexGuard<()>>,
        restart_mark: &mut Option<u64>,
        own_result: Option<&super::StartResult>,
    ) -> Result<Option<IpcResponse>> {
        let id = &opts.id;
        #[cfg(windows)]
        if let Some(response) = self.reject_unsupported_windows_options(opts).await? {
            return Ok(Some(response));
        }
        if !opts.force
            && let Some(result) = self.retry_result(id, own_result)
        {
            if !opts.wait_ready {
                return Ok(Some(IpcResponse::DaemonAlreadyRunning));
            }
            info!("daemon {id} has a start sequence in progress; waiting for it");
            let fallback = self
                .ready_check(id)
                .filter(|check| check.result.same_channel(&result))
                .map(|check| check.attempt);
            let oneshot = self
                .get_daemon(id)
                .await
                .filter(|daemon| daemon.oneshot)
                .map(|daemon| daemon.pid.unwrap_or(0));
            drop(stop_guard.take());
            if let Some(pid) = oneshot {
                // Preserve the joining caller's oneshot wait budget across backoff.
                return Ok(Some(
                    self.await_running_oneshot(id, opts.oneshot_wait, pid).await,
                ));
            }
            return Ok(Some(await_start_result(result, fallback).await));
        }
        let Some(daemon) = self.get_daemon(id).await else {
            return Ok(None);
        };
        // Entering a directory does not re-run a finished task, at any level of
        // the dependency graph — the layout this exists for reaches the task
        // through a service's `depends`, not by naming it. Decided here rather
        // than in the client because this is the authoritative state: the state
        // file lags it by up to the flush interval, which is exactly the window
        // a second entry lands in after the task completes.
        // `opts.oneshot` rather than the record's: the request carries what
        // config says now, while the stored flag is only refreshed by a run, so
        // a daemon that used to be a task would otherwise stay skipped forever
        // after being turned into a service.
        if opts.on_directory_enter && opts.oneshot && daemon.status.is_completed() {
            debug!("daemon {id} already completed; directory entry leaves it alone");
            return Ok(Some(IpcResponse::DaemonReady { daemon }));
        }
        // Stopping (or restarting) is treated as "not running": the
        // monitoring task will clean it up. Only a live PID under a
        // non-terminal status blocks a start.
        if daemon.status.is_stopping_or_restarting()
            || daemon.status.is_stopped()
            || daemon.status.is_completed()
        {
            return Ok(None);
        }
        let Some(pid) = daemon.pid else {
            return Ok(None);
        };
        if opts.force {
            // A forced start replaces the running instance, so the daemon is
            // recorded as restarting rather than stopped until the new
            // process is up; `run` settles it if the start does not happen.
            self.stop_locked_with(id, true).await?;
            // Read under the daemon's lock, which this start still holds, so
            // the epoch is the one this stop left.
            *restart_mark = Some(self.stop_epoch(id));
            info!("run: stop completed for daemon {id}");
            return Ok(None);
        }
        if daemon.oneshot && opts.wait_ready {
            // An in-flight oneshot has not done its work yet, so reporting
            // "already running" would let dependents start against the state
            // the task is still establishing. Wait for the run already under
            // way instead.
            info!("daemon {id} is an in-flight oneshot (pid {pid}); waiting for it to finish");
            drop(stop_guard.take());
            return Ok(Some(
                self.await_running_oneshot(id, opts.oneshot_wait, pid).await,
            ));
        }
        if opts.wait_ready
            && let Some(check) = self.ready_check(id)
            && check.pid == pid
        {
            // The process is up but its ready check has not passed, so
            // "already running" would let this caller, and whatever depends
            // on the daemon, go on before it is ready. Wait for the start under
            // way instead and report its result as this one's: its check is
            // the one that decides whether this process is ready.
            info!("daemon {id} (pid {pid}) has not passed its ready check; waiting for it");
            drop(stop_guard.take());
            return Ok(Some(
                await_start_result(check.result, Some(check.attempt)).await,
            ));
        }
        if let DaemonStatus::Failed(error) = &daemon.status
            && PROCS.process_group_alive(pid)
        {
            return Ok(Some(IpcResponse::DaemonFailed {
                error: error.clone(),
            }));
        }
        // A record can name a PID that has already exited: `stop` leaves the
        // terminal state to a monitor that still owns the daemon, and that
        // monitor writes it only after draining the process's output. Rejecting
        // a start against a dead PID would fail an ordinary stop-then-start for
        // the length of that drain, so confirm the process is really there
        // before refusing. The oneshot branch above deliberately comes first: a
        // task whose process has exited is about to be recorded as completed,
        // and starting a second copy of it is exactly what waiting prevents.
        // So does the ready check's: a process that exited before passing it
        // is about to be reported as failed by the start waiting on it.
        PROCS.refresh_pids(&[pid]);
        if !PROCS.is_running(pid) {
            debug!(
                "daemon {id}: record still names pid {pid}, which has exited; its monitor has not finalized yet"
            );
            return Ok(None);
        }
        warn!("daemon {id} already running with pid {pid}");
        Ok(Some(IpcResponse::DaemonAlreadyRunning))
    }

    /// Wait for a oneshot that is already running to reach a terminal state,
    /// and report it as if this call had started the task itself.
    ///
    /// Polls the state file because the terminal state is written by the
    /// monitoring task of the *other* run; this call has no readiness channel
    /// of its own to await.
    async fn await_running_oneshot(
        &self,
        id: &DaemonId,
        wait: Option<OneshotWait>,
        watched_pid: u32,
    ) -> IpcResponse {
        let interval = settings().supervisor_ready_check_interval();
        // The caller resolved this from the project's settings and sent it, so
        // both processes wait exactly as long. Falling back to this process's
        // own settings would read the directory the supervisor happens to have
        // started in, where a project's `oneshot_timeout` is not visible — and
        // the shorter of the two deadlines would silently win, releasing
        // dependents while the task was still running.
        //
        // `None` here means the setting asked for no limit, so there is no
        // deadline to reach rather than a distant one.
        // One deadline for the whole wait, retries and backoffs included.
        // `oneshot_timeout` is documented as the longest `pitchfork start` will
        // wait, and the client bounds its own request by the same value without
        // restarting it, so a per-attempt budget here would both break that
        // promise — unboundedly, with infinite retries — and put the two sides
        // back to disagreeing about when one task has gone on too long.
        let deadline = wait
            .unwrap_or_else(|| settings().supervisor_oneshot_wait())
            .duration()
            .map(|d| tokio::time::Instant::now() + d);
        // Which run this wait is reporting on. A terminal state is only that
        // run's while the record still names its PID or names none at all; once
        // another PID appears, something else has started the task and the
        // outcome that follows belongs to that run, not this one. Following the
        // handoff keeps the answer useful to a dependent — it still learns
        // whether the task succeeded — without quietly attributing an unrelated
        // run's failure to the one it asked about.
        let mut watched_pid = watched_pid;
        loop {
            let Some(daemon) = self.get_daemon(id).await else {
                return IpcResponse::DaemonNotFound;
            };
            if let Some(current) = daemon.pid
                && current != watched_pid
            {
                info!(
                    "daemon {id}: the run being waited on (pid {watched_pid}) was replaced by pid {current}; following it"
                );
                watched_pid = current;
            }
            match &daemon.status {
                DaemonStatus::Completed => {
                    info!("daemon {id}: the in-flight oneshot completed");
                    return IpcResponse::DaemonReady { daemon };
                }
                DaemonStatus::Errored(code) => {
                    // A failed attempt is persisted before the in-flight `run`
                    // sleeps out its backoff, so an errored record with
                    // attempts left is a gap between tries rather than the
                    // result. Same condition `check_retry` uses to decide
                    // whether another attempt is still owed. A disabled daemon
                    // is owed none: every retry path checks the disabled set,
                    // under the lock `disable` takes, before starting one.
                    if daemon.retry.count() > 0
                        && daemon.retry_count < daemon.retry.count()
                        && !self.state_file.lock().await.disabled.contains(id)
                    {
                        debug!(
                            "daemon {id}: in-flight oneshot failed attempt {} of {}; still waiting",
                            daemon.retry_count + 1,
                            daemon.retry.count() + 1
                        );
                    } else {
                        // -1 records an unobservable exit code; the caller
                        // renders `None` as a plain failure rather than
                        // "exit code -1".
                        let exit_code = Some(*code).filter(|c| *c != -1);
                        return IpcResponse::DaemonFailedWithCode {
                            exit_code,
                            resolved_ports: daemon.resolved_port.clone(),
                        };
                    }
                }
                DaemonStatus::Failed(error) => {
                    return IpcResponse::DaemonFailed {
                        error: error.clone(),
                    };
                }
                DaemonStatus::Stopped => {
                    // Stopped, not completed: the task was interrupted, so it
                    // never established what its dependents are waiting for.
                    warn!("daemon {id}: the in-flight oneshot was stopped before completing");
                    return IpcResponse::DaemonFailedWithCode {
                        exit_code: None,
                        resolved_ports: daemon.resolved_port.clone(),
                    };
                }
                DaemonStatus::Running
                | DaemonStatus::Waiting
                | DaemonStatus::Stopping
                | DaemonStatus::Restarting => {}
            }
            if deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) {
                warn!("daemon {id}: gave up waiting for the in-flight oneshot to finish");
                // Reported as a failure rather than as "already running": the
                // batch start path only counts a result carrying an exit code
                // as failed, so anything else would let dependents start
                // against a task that never finished. 124 is the code a
                // readiness timeout already uses.
                return IpcResponse::DaemonFailedWithCode {
                    exit_code: Some(124),
                    resolved_ports: Vec::new(),
                };
            }
            time::sleep(interval).await;
        }
    }

    /// Register a process's pending readiness result.
    fn register_ready_check(
        &self,
        id: &DaemonId,
        pid: u32,
        start_result: &super::StartResult,
        attempt: &super::StartResult,
    ) {
        self.ready_checks
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .insert(
                id.clone(),
                super::ReadyCheck {
                    pid,
                    result: start_result.clone(),
                    attempt: attempt.clone(),
                },
            );
    }

    /// The process and readiness result currently being checked for `id`.
    fn ready_check(&self, id: &DaemonId) -> Option<super::ReadyCheck> {
        self.ready_checks
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(id)
            .cloned()
    }

    /// Record that the ready check of `id`'s attempt has ended, so a start
    /// from then on finds the daemon ready, or the process gone. Only that
    /// attempt's: a forced start may since have registered its successor's
    /// under the same id, possibly with the same PID.
    fn end_ready_check(&self, id: &DaemonId, attempt: &super::StartResult) {
        let mut ready_checks = self.ready_checks.lock().unwrap_or_else(|e| e.into_inner());
        if ready_checks
            .get(id)
            .is_some_and(|check| check.attempt.same_channel(attempt))
        {
            ready_checks.remove(id);
        }
    }

    /// Run a daemon once (single attempt).
    ///
    /// `stop_guard` is this daemon's stop lock, acquired by `run` before the
    /// already-running check. It is held through spawning until the Running
    /// state and PID are persisted (or an early failure returns), then dropped
    /// before the potentially unbounded readiness wait.
    pub(crate) async fn run_once(
        &self,
        opts: RunOptions,
        stop_guard: tokio::sync::OwnedMutexGuard<()>,
        start_result: Option<&super::StartResult>,
    ) -> Result<IpcResponse> {
        let id = &opts.id;
        // Checked under the daemon's stop lock, which `close()` waits out
        // after setting the flag: a start that took the lock first finishes
        // before `close()` lists the daemons to stop, and one that takes it
        // later stops here. Otherwise a daemon started during shutdown (an IPC
        // start, a cron run, a retry) would be left running once the
        // supervisor has gone.
        if self
            .shutting_down
            .load(std::sync::atomic::Ordering::Acquire)
        {
            info!("not starting daemon {id}: the supervisor is shutting down");
            return Ok(IpcResponse::DaemonFailed {
                error: "the supervisor is shutting down".to_string(),
            });
        }
        // Settings can change while a foreground start waits between retries.
        #[cfg(windows)]
        if let Some(response) = self.reject_unsupported_windows_options(&opts).await? {
            return Ok(response);
        }
        let original_cmd = opts.cmd.clone(); // Save original command for persistence

        // Background starts also publish readiness for concurrent callers.
        let (ready_tx, ready_rx) = if opts.wait_ready || !opts.oneshot {
            let (tx, rx) = oneshot::channel::<std::result::Result<(), ReadyFailure>>();
            (Some(tx), Some(rx))
        } else {
            (None, None)
        };

        // Check port availability and apply auto-bump if configured
        let expected_ports = opts
            .port
            .as_ref()
            .map(|p| p.expect.clone())
            .unwrap_or_default();
        // Holds the resolved ports against other starts until this daemon is
        // ready or gone. Dropped on every early return below.
        let mut port_claim: Option<PortClaim> = None;
        let (resolved_ports, effective_ready_port) = if !expected_ports.is_empty() {
            let port_cfg = opts.port.as_ref().unwrap();
            match claim_ports(
                id,
                &expected_ports,
                port_cfg.auto_bump(),
                port_cfg.max_bump_attempts(),
            )
            .await
            {
                Ok((resolved, claim)) => {
                    port_claim = Some(claim);
                    let ready_port = if let Some(configured_port) =
                        opts.ready_port.as_ref().and_then(|p| p.as_port())
                    {
                        Some(resolve_configured_ready_port(
                            configured_port,
                            &expected_ports,
                            &resolved,
                        ))
                    } else if opts.ready_output.is_none()
                        && opts.ready_http.is_none()
                        && opts.ready_cmd.is_none()
                        && opts.ready_delay.is_none()
                    {
                        // No other ready check configured — use the first expected port as a
                        // TCP port readiness check so the daemon is considered ready once it
                        // starts listening.  Skip port 0 (ephemeral port request).
                        resolved.first().copied().filter(|&p| p != 0)
                    } else {
                        // Another ready check is configured (output/http/cmd/delay).
                        // Don't add an implicit TCP port check — it could race and fire
                        // before the daemon has produced any output.
                        None
                    };
                    info!("daemon {id}: ports {expected_ports:?} resolved to {resolved:?}");
                    (resolved, ready_port)
                }
                Err(e) => {
                    error!("daemon {id}: port check failed: {e}");
                    // Convert PortError to structured IPC response
                    if let Some(port_error) = e.downcast_ref::<PortError>() {
                        match port_error {
                            PortError::Claimed { .. } => {
                                return Ok(IpcResponse::DaemonFailed {
                                    error: e.to_string(),
                                });
                            }
                            PortError::InUse {
                                port,
                                address,
                                process,
                                pid,
                            } => {
                                return Ok(IpcResponse::PortConflict {
                                    port: *port,
                                    process: process.clone(),
                                    pid: *pid,
                                    address: address.clone(),
                                });
                            }
                            PortError::NoAvailablePort {
                                start_port,
                                attempts,
                            } => {
                                return Ok(IpcResponse::NoAvailablePort {
                                    start_port: *start_port,
                                    attempts: *attempts,
                                });
                            }
                        }
                    }
                    return Ok(IpcResponse::DaemonFailed {
                        error: e.to_string(),
                    });
                }
            }
        } else {
            // When ready_port is set without expected_port, check that the port
            // is not already occupied.  If another process is listening on it,
            // the TCP readiness probe would immediately succeed and pitchfork
            // would falsely consider the daemon ready — routing proxy traffic to
            // the wrong process.
            if let Some(port) = opts.ready_port.as_ref().and_then(|p| p.as_port())
                && port > 0
            {
                match claim_ports(id, &[port], false, 0).await {
                    Ok((_, claim)) => port_claim = Some(claim),
                    Err(e)
                        if matches!(
                            e.downcast_ref::<PortError>(),
                            Some(PortError::Claimed { .. })
                        ) =>
                    {
                        return Ok(IpcResponse::DaemonFailed {
                            error: e.to_string(),
                        });
                    }
                    // Taken by a process: reported below with its details.
                    Err(_) => {}
                }
            }
            if let Some(port) = opts.ready_port.as_ref().and_then(|p| p.as_port())
                && port > 0
                && let Some((address, pid, process)) = detect_port_conflict(port).await
            {
                return Ok(IpcResponse::PortConflict {
                    port,
                    process,
                    pid,
                    address: Some(address),
                });
            }
            (
                Vec::new(),
                opts.ready_port.as_ref().and_then(|p| p.as_port()),
            )
        };

        // The program and arguments that start the daemon, before any mise
        // wrapping.
        // The program and arguments that start the daemon, before any mise
        // wrapping, and the script for the shell when `run` is a string.
        if let Some(error) = invalid_probe_program(
            id,
            "ready_cmd",
            opts.ready_cmd.as_ref().map(|c| &c.run),
        )
        .or_else(|| {
            invalid_probe_program(id, "health_cmd", opts.health_cmd.as_ref().map(|c| &c.run))
        }) {
            return Ok(IpcResponse::DaemonFailed { error });
        }

        let (mut words, script) = if opts.no_shell {
            // The argv form of `run`: started as written, with no shell to
            // reinterpret quotes, `%`, `&` or anything else in the arguments.
            if let Some(error) = invalid_argv_program(id, &original_cmd) {
                return Ok(IpcResponse::DaemonFailed { error });
            }
            (original_cmd.clone(), None)
        } else {
            // Resolve the shell for this platform into program + args. The run
            // script is passed verbatim as the final argument, avoiding the lossy
            // split->join round-trip that previously mangled $VAR/glob expansion.
            let words = match resolve_shell() {
                Ok(parts) => parts,
                Err(error) => return Ok(IpcResponse::DaemonFailed { error }),
            };
            // Use the original run string verbatim; fall back to joining cmd for
            // ad-hoc commands (e.g. `pitchfork run -- cmd args`) that have no run string.
            // We don't prepend `exec` because it breaks compound commands (e.g. `exec a && b`
            // silently drops `b`). Users can add `exec` themselves in the run string.
            let script = opts
                .run
                .clone()
                .unwrap_or_else(|| shell_words::join(&original_cmd));
            (words, Some(script))
        };

        let mise_bin = if opts.mise.unwrap_or(settings().general.mise) {
            let mise_bin = settings().resolve_daemon_mise_bin(opts.mise_bin.as_deref());
            if mise_bin.is_none() {
                warn!("daemon {id}: mise=true but mise binary not found, running without mise");
            }
            mise_bin
        } else {
            None
        };
        // A command left unrendered for `mise x` is not runnable without it: the
        // shell would see the template tags. Fail here, where the binary is
        // actually looked up, rather than guessing at render time.
        if mise_bin.is_none() && opts.deferred_template_context.is_some() {
            return Ok(IpcResponse::DaemonFailed {
                error: format!(
                    "daemon {id}: the command uses template variables only mise can render, but mise is not enabled or its binary was not found"
                ),
            });
        }
        // Started directly, the shell gets its script from `shell_script`.
        // Under mise, cmd scripts go through a bridge that restores the raw
        // command line after mise has activated the environment. Deferred
        // templates keep cmd as the outer program so mise uses cmd quoting.
        let script = match &mise_bin {
            Some(mise_bin) => {
                info!(
                    "daemon {id}: wrapping command with mise ({})",
                    mise_bin.display()
                );
                if let Some(script) = script {
                    words =
                        mise_shell_words(words, script, opts.deferred_template_context.is_some());
                }
                None
            }
            None => script,
        };
        let (program, args) = launch_command(words, mise_bin.as_deref());
        #[cfg(unix)]
        let run_identity = match resolve_effective_run_identity(opts.user.as_deref()) {
            Ok(identity) => identity,
            Err(e) => {
                return Ok(IpcResponse::DaemonFailed {
                    error: e.to_string(),
                });
            }
        };
        info!("run: spawning daemon {id} with {program} {args:?} {script:?}");

        // Allocate PTY if configured
        #[cfg(unix)]
        let pty_pair = if opts.pty.unwrap_or(false) {
            match super::pty::openpty() {
                Ok(pair) => {
                    info!("daemon {id}: allocated PTY (pty = true)");
                    Some(pair)
                }
                Err(e) => {
                    warn!("daemon {id}: failed to allocate PTY, falling back to pipes: {e}");
                    None
                }
            }
        } else {
            None
        };

        // Output reaches the monitoring task either from readers this process
        // owns or, when a sink owns the stream, relayed over IPC. The channel is
        // created here rather than in that task so it exists before the sink
        // starts: a daemon whose very first line matches its readiness pattern
        // would otherwise have the match reported with nowhere to deliver it.
        let (output_tx, output_rx) = tokio::sync::mpsc::channel::<super::OutputLine>(256);
        // Registered for every attempt, whichever way its output is captured:
        // the token also tells a daemon's program status reports apart from
        // those of an earlier run's sink.
        let output_relay = super::log_sink::OutputRelay::register(id, output_tx.clone());
        let status_token = output_relay.token();

        // Set up out-of-process capture before building the command, so the
        // daemon can be handed the pipe's write end directly.
        let mut sink_pipe = None;
        let mut sink_writer = None;
        let mut sink_child = None;
        if super::log_sink::is_supported(&opts) {
            let log_format = opts
                .log_format
                .clone()
                .unwrap_or_else(|| settings().logs.log_format.clone());
            let watch_for = super::log_sink::WatchFor::from_opts(id, &opts);
            // The token ties this attempt's sink to this attempt's channel, so
            // a sink still draining a previous attempt cannot report into it.
            let relay_token = status_token;
            match super::log_sink::SinkPipe::new(log_format, watch_for, relay_token) {
                Ok((pipe, writer)) => match pipe.start(id) {
                    Ok(child) => {
                        sink_child = Some(super::log_sink::PendingSink::new(child));
                        sink_pipe = Some(pipe);
                        sink_writer = Some(writer);
                    }
                    Err(e) => {
                        warn!("could not start log sink for {id}, capturing in-process: {e}");
                    }
                },
                Err(e) => {
                    // Fall back to in-process capture rather than refusing to
                    // start the daemon.
                    warn!("could not create log pipe for {id}, capturing in-process: {e}");
                }
            }
        }

        let mut cmd = tokio::process::Command::new(&program);

        #[cfg(unix)]
        if let Some(ref pair) = pty_pair {
            // PTY mode: connect both stdout and stderr to the slave PTY.
            // The child uses the slave for stdin/stdout/stderr, and we read
            // output from the master.
            let slave_file = std::fs::File::from(
                pair.slave
                    .try_clone()
                    .map_err(|e| miette::miette!("failed to dup slave PTY fd: {e}"))?,
            );
            cmd.stdin(std::process::Stdio::from(slave_file.try_clone().map_err(
                |e| miette::miette!("failed to clone slave PTY fd for stdin: {e}"),
            )?));
            cmd.stdout(std::process::Stdio::from(slave_file.try_clone().map_err(
                |e| miette::miette!("failed to clone slave PTY fd for stdout: {e}"),
            )?));
            cmd.stderr(std::process::Stdio::from(slave_file));
        } else if let Some(writer) = sink_writer.take() {
            // Capture belongs to a sibling sink process, so the daemon writes
            // to a pipe this process does not read. See supervisor::log_sink.
            let dup = writer
                .try_clone()
                .map_err(|e| miette::miette!("failed to dup log pipe for stderr: {e}"))?;
            cmd.stdout(std::process::Stdio::from(writer))
                .stderr(std::process::Stdio::from(dup));
        } else {
            cmd.stdout(std::process::Stdio::piped())
                .stderr(std::process::Stdio::piped());
        }

        #[cfg(not(unix))]
        if let Some(writer) = sink_writer.take() {
            let dup = writer
                .try_clone()
                .map_err(|e| miette::miette!("failed to dup log pipe for stderr: {e}"))?;
            cmd.stdout(std::process::Stdio::from(writer))
                .stderr(std::process::Stdio::from(dup));
        } else {
            cmd.stdout(std::process::Stdio::piped())
                .stderr(std::process::Stdio::piped());
        }

        match &script {
            Some(script) => cmd.shell_script(&program, &args, script),
            None => cmd.args(&args),
        };
        cmd.current_dir(&opts.dir)
            .hide_console_window()
            .close_inherited_fds();

        #[cfg(unix)]
        if pty_pair.is_none() {
            cmd.stdin(std::process::Stdio::null());
        }

        #[cfg(not(unix))]
        cmd.stdin(std::process::Stdio::null());

        // Before the runtime env, so a daemon's own `env` entries win.
        #[cfg(unix)]
        apply_identity_env(&mut cmd, &run_identity);
        apply_runtime_env(
            &mut cmd,
            id,
            opts.retry_count,
            opts.env.as_ref(),
            &resolved_ports,
        );
        // After the daemon's own env, since `mise x` needs exactly this value.
        if let Some(context) = &opts.deferred_template_context {
            cmd.env(crate::template::TEMPLATE_CONTEXT_ENV, context);
        }

        // Inject proxy-related environment variables
        inject_proxy_env(&mut cmd, &daemon_proxy_host(&opts).await);

        #[cfg(unix)]
        {
            let run_identity = run_identity.clone();
            let use_pty = pty_pair.is_some();
            unsafe {
                cmd.pre_exec(move || {
                    nix::unistd::setsid().map_err(nix_to_io_error)?;

                    // When using a PTY, set the slave as the controlling terminal.
                    // The slave FD has already been dup'd onto stdin/stdout/stderr
                    // by tokio, so we can use stdin (fd 0) for TIOCSCTTY.
                    if use_pty {
                        let ret = libc::ioctl(0, libc::TIOCSCTTY as _, 0);
                        if ret < 0 {
                            // Non-fatal: the process can still run without
                            // a controlling terminal.
                            #[cfg(target_os = "linux")]
                            eprintln!(
                                "pitchfork: TIOCSCTTY failed: {}",
                                std::io::Error::last_os_error()
                            );
                        }
                    }

                    apply_run_identity(&run_identity)?;
                    Ok(())
                });
            }
        }

        // Timestamp the run so a failed start can wait for this attempt's output
        // specifically, rather than seeing an earlier attempt's.
        let spawn_time = chrono::Local::now();
        // A sink is already running at this point. Both bail-outs below have to
        // reap it explicitly: dropping the handle only reaps on a best-effort
        // basis, and run_once runs once per retry attempt, so a daemon that
        // consistently fails to spawn would otherwise accumulate sinks.
        // A failed spawn returns here; the sink is terminated by PendingSink.
        let mut child = cmd.spawn().into_diagnostic()?;
        // In a job of its own, so its whole process tree can be stopped; see
        // `win_job`.
        #[cfg(windows)]
        if let (Some(pid), Some(process)) = (child.id(), child.raw_handle()) {
            crate::win_job::contain_spawned(process as _, pid);
        }
        let spawned_pid = child.id();
        // Register the daemon as monitored BEFORE persisting the Running
        // state. The orphan reconciler treats any running, unmonitored PID
        // as an orphan; if the state became visible first, a concurrent
        // reconciliation pass could adopt — or under the kill policy,
        // terminate — a daemon that was just legitimately started. The RAII
        // guard unregisters on any early-error path below and is otherwise
        // handed to the monitoring task. Registered as soon as the process
        // exists, so a supervisor forced to exit while this start is still
        // on its way to recording it kills it (see `force_exit`).
        let monitored_guard =
            spawned_pid.map(|pid| super::adopt::MonitoredGuard::register(id.clone(), pid));
        // A process now exists, which is exactly what `last_cron_run` records.
        // Written here rather than from the watcher's view of the response
        // because that view cannot tell a start that failed before spawning
        // from one that spawned and exited before its PID could be read: a
        // port conflict, an unresolvable shell and an instant exit all report
        // `DaemonFailed`. Only the last of those ran, and a cron job that
        // fails that fast is precisely the one whose timing a user needs.
        // Ordered before the `Running` upsert below, which inherits it.
        //
        // Written synchronously rather than left to the background flush, for
        // the same reason `last_cron_triggered` is: a supervisor that dies in
        // the window between the two would come back with no record that this
        // run happened, and for a short-lived job that window is as long as
        // the job itself. A scheduled spawn is rare enough -- at most one per
        // `cron_check_interval` -- for the extra write to cost nothing.
        if opts.cron_started {
            let mut state_file = self.state_file.lock().await;
            if state_file.set_last_cron_run(id, spawn_time)
                && let Err(e) = state_file.write()
            {
                error!("failed to persist last_cron_run for daemon {id}: {e}");
            }
        }
        let (pid, monitored_guard) = match (spawned_pid, monitored_guard) {
            (Some(p), Some(guard)) => (p, guard),
            _ => {
                warn!("Daemon {id} exited before PID could be captured");
                // Unlike a daemon that never started, this one ran and may have
                // said why it gave up, and its output is the only diagnosis
                // available. Its write end is already closed, so the sink is on
                // its way to end of file: let it finish writing before reporting,
                // then reap whatever is left of it.
                if sink_child.is_some() {
                    super::log_sink::wait_for_output(id, spawn_time, SINK_OUTPUT_TIMEOUT).await;
                }
                return Ok(IpcResponse::DaemonFailed {
                    error: "Process exited immediately".to_string(),
                });
            }
        };
        info!("started daemon {id} with pid {pid}");
        PROCS.refresh_pids(&[pid]);
        let monitor_token = monitored_guard.token();

        // Hand the retained read end to a sink and keep one running for as long
        // as this daemon is monitored.
        let using_sink = sink_pipe.is_some();
        // Take the sink out of the guard only once there is a pipe to supervise
        // it with, so it is never left running unsupervised.
        if let Some(pipe) = sink_pipe.take()
            && let Some(child) = sink_child.as_mut().and_then(|pending| pending.take())
        {
            pipe.supervise(id.clone(), monitor_token, child);
        }
        // The attempt's actual resolved ports, captured before the upsert
        // moves them into state. Hooks, readiness probes, and the failure
        // response must reflect this attempt: the state merge keeps the
        // existing resolved_port when an update is empty, so a no-port
        // attempt would otherwise inherit a previous run's stale ports
        // through the upserted record.
        let attempt_resolved_ports = resolved_ports.clone();
        let daemon = self
            .upsert_daemon(
                UpsertDaemonOpts::from_run_options(&opts, DaemonStatus::Running)
                    .set(|o| {
                        o.pid = Some(pid);
                        o.cmd = Some(original_cmd);
                        o.ready_port = effective_ready_port.map(|p| ReadyPort {
                            port: Some(p),
                            template: None,
                            timeout: opts.ready_port.as_ref().and_then(|rp| rp.timeout),
                        });
                        o.port = crate::config_types::PortConfig::from_parts(
                            expected_ports,
                            opts.port.as_ref().map(|p| p.bump).unwrap_or_default(),
                        );
                        o.resolved_port = Some(resolved_ports);
                    })
                    .build(),
            )
            .await?;

        // Registered while the stop lock is still held, so a start that finds
        // this process running also finds the start it has to wait for.
        let (attempt_tx, attempt_rx) = tokio::sync::watch::channel(None);
        if ready_rx.is_some() {
            self.register_ready_check(id, pid, start_result.unwrap_or(&attempt_rx), &attempt_rx);
        }

        // Running state and PID are now persisted: concurrent run/stop calls
        // observe a running daemon and behave correctly, so release the stop
        // lock rather than holding it through the readiness wait below, which
        // can take arbitrarily long.
        drop(stop_guard);

        let id_clone = id.clone();
        // A oneshot is ready only when its process exits 0, so no readiness
        // check may run alongside it — one that fired first would report the
        // task ready before it had done its work, and would suppress the
        // completion notification entirely. Config load rejects explicit
        // `ready_*` fields and the client clears CLI overrides, but the
        // implicit port check is derived here from `port.expect`, so the
        // suppression has to happen here rather than being trusted to callers.
        let ready_delay = (!opts.oneshot).then_some(opts.ready_delay).flatten();
        let ready_output = (!opts.oneshot).then(|| opts.ready_output.clone()).flatten();
        let ready_http = (!opts.oneshot).then(|| opts.ready_http.clone()).flatten();
        let ready_port = (!opts.oneshot).then_some(effective_ready_port).flatten();
        let implicit_ready_port = ready_port.map(|p| ReadyPort {
            port: Some(p),
            template: None,
            timeout: None,
        });
        let ready_port_config = (!opts.oneshot)
            .then(|| opts.ready_port.clone())
            .flatten()
            .or(implicit_ready_port);
        let ready_cmd = (!opts.oneshot).then(|| opts.ready_cmd.clone()).flatten();
        let daemon_dir = opts.dir.0.clone();
        let hook_dirs =
            super::hooks::HookDirs::new(daemon_dir.clone(), opts.watch_base_dir.clone());
        let hook_retry_count = opts.retry_count;
        let hook_retry = opts.retry;
        let hook_daemon_env = opts.env.clone();
        // Ports of THIS attempt, snapshotted before the monitor starts: a retry
        // or restart may replace state.resolved_port before a hook task runs.
        // Sourced from the attempt's local value, not the upserted record —
        // the state merge inherits stale ports for a no-port attempt.
        let hook_resolved_ports = attempt_resolved_ports.clone();
        let readiness_daemon_env = opts.env.clone();
        let readiness_resolved_ports = attempt_resolved_ports.clone();
        let on_output_hook = opts.on_output_hook.clone();
        // Whether this daemon has any port-related config — used to skip the
        // active_port detection task for daemons that never bind a port (e.g. `sleep 60`).
        // When the proxy is enabled, only detect active_port for daemons that are
        // actually referenced by a registered slug, rather than blanket-polling every
        // daemon (which wastes ~7.5 s of listeners::get_all() calls per port-less daemon).
        let has_port_config = opts.port.as_ref().is_some_and(|p| !p.expect.is_empty())
            || (settings().proxy.enable && is_daemon_slug_target(id));
        // When the ready_port check succeeds on the first resolved port we can
        // set active_port directly instead
        // of spawning detect_and_store_active_port (which relies on
        // listeners::get_all() + process-tree traversal and is unreliable on
        // Windows where Git Bash PID mapping can break descendant lookups).
        let daemon_pid = pid;

        // Prepare output readers before spawning the monitoring task.
        // In PTY mode, we read from the PTY master FD.
        // In pipe mode, we read from separate stdout/stderr pipes.
        #[cfg(unix)]
        let pty_reader = pty_pair.map(|p| {
            tokio::io::BufReader::new(tokio::fs::File::from_std(std::fs::File::from(p.master)))
        });
        #[cfg(not(unix))]
        let pty_reader: Option<tokio::io::BufReader<tokio::fs::File>> = None;
        let stdout_reader = if pty_reader.is_none() {
            child.stdout.take().map(tokio::io::BufReader::new)
        } else {
            None
        };
        let stderr_reader = if pty_reader.is_none() {
            child.stderr.take().map(tokio::io::BufReader::new)
        } else {
            None
        };

        if !using_sink
            && pty_reader.is_none()
            && (stdout_reader.is_none() || stderr_reader.is_none())
        {
            error!("Failed to capture stdout/stderr for daemon {id}");
        }

        tokio::spawn(async move {
            let id = id_clone;
            // Registered before the Running upsert above; unregisters when
            // this monitoring task ends.
            let _monitored_guard = monitored_guard;
            // Likewise for sink-relayed output: dropping this stops the
            // supervisor delivering into a channel nobody is reading. Dropped
            // explicitly once the daemon exits, before the drain below.
            let output_relay = output_relay;
            // Held while the daemon runs, so none of its ports (it may bind
            // them one at a time) is handed to another start; released as
            // soon as its exit is observed, or when this task ends.
            let mut port_claim = port_claim;

            // Merge all output sources (PTY master OR stdout+stderr, or a
            // sink's IPC reports) into a single channel.
            let mut output_rx = output_rx;
            let status_target = StatusTarget {
                id: id.clone(),
                token: status_token,
            };
            let status_target = Some(status_target);

            if let Some(reader) = pty_reader {
                // PTY mode: single merged stream from the master.
                // output_tx is moved into the spawn; when the reader ends the
                // channel closes automatically.
                tokio::spawn(forward_output_lines(
                    reader,
                    output_tx,
                    status_target.clone(),
                ));
            } else {
                // Pipe mode: stdout and stderr are merged into the same channel.
                // Both `ready_output` and `on_output_hook` patterns match against
                // lines from either stream, which is the expected behavior (a
                // "server ready" message may appear on stderr in some tools).
                if let Some(stdout) = stdout_reader {
                    tokio::spawn(forward_output_lines(
                        stdout,
                        output_tx.clone(),
                        status_target.clone(),
                    ));
                }
                if let Some(stderr) = stderr_reader {
                    tokio::spawn(forward_output_lines(
                        stderr,
                        output_tx.clone(),
                        status_target.clone(),
                    ));
                }
                // Drop the last sender so the channel closes when all readers
                // finish. The relay holds its own clone, so a sink's reports
                // still have somewhere to go after these end.
                drop(output_tx);
            }
            let log_store = Arc::clone(&LOG_STORE);
            let log_format = opts
                .log_format
                .clone()
                .unwrap_or_else(|| crate::settings::settings().logs.log_format.clone());
            let parse_line = move |line: &str| crate::log_parse::parse(line, &log_format);

            const LOG_BATCH_SIZE: usize = 100;
            const LOG_FLUSH_INTERVAL: Duration = Duration::from_millis(100);
            let mut log_buffer: Vec<crate::log_parse::ParsedLog> =
                Vec::with_capacity(LOG_BATCH_SIZE);
            let mut pending_log_writes: Vec<tokio::task::JoinHandle<()>> = Vec::new();
            let mut log_flush_interval = tokio::time::interval(LOG_FLUSH_INTERVAL);
            log_flush_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);

            let flush_logs =
                |buffer: &mut Vec<crate::log_parse::ParsedLog>,
                 pending: &mut Vec<tokio::task::JoinHandle<()>>| {
                    pending.retain(|handle| !handle.is_finished());
                    if buffer.is_empty() {
                        return;
                    }
                    let store = Arc::clone(&log_store);
                    let id = id.clone();
                    let batch = std::mem::take(buffer);
                    pending.push(tokio::task::spawn_blocking(move || {
                        if let Err(e) = store.append_structured_batch(&id, &batch) {
                            error!("Failed to write batch to log for daemon {id}: {e}");
                        }
                    }))
                };

            // SQLite WAL mode provides automatic durability; no explicit flush needed.

            // Setup readiness checking
            let mut ready_notified = false;
            // Set when a oneshot's process exits 0. Its readiness *is* its
            // completion, so the notification is held back until the
            // `completed` state has been persisted — a caller that returns
            // from `pitchfork start` must not still see the daemon running.
            let mut oneshot_completion_pending = false;
            let mut ready_tx = ready_tx;
            let ready_pattern = ready_output
                .as_ref()
                .and_then(|o| get_or_compile_regex(&o.pattern));
            // Track whether we've already spawned the active_port detection task
            let mut active_port_spawned = false;

            // Validate on_output config early; discard the hook on any error so
            // a bad regex does not silently fall through to the (None, None) => true
            // match arm and fire on every line.
            let on_output_hook = match on_output_hook {
                Some(ref hook) => match hook.validate(id.name()) {
                    Ok(()) => on_output_hook,
                    Err(e) => {
                        error!("{e}");
                        None
                    }
                },
                None => None,
            };

            // Compile the regex pattern after validation so we only attempt this
            // when the hook is known-good (validate() already checked the syntax).
            let on_output_pattern: Option<regex::Regex> = on_output_hook
                .as_ref()
                .and_then(|h| h.regex.as_deref().and_then(get_or_compile_regex));
            let on_output_debounce = on_output_hook
                .as_ref()
                .map(|h| h.debounce_duration())
                .unwrap_or(Duration::from_millis(1000));
            // Last time the on_output hook fired; None means it has never fired.
            let mut on_output_last_fired: Option<std::time::Instant> = None;

            // An unchecked service is ready once spawned. Oneshots still wait for exit.
            let ready_delay = ready_delay.or_else(|| {
                (!opts.oneshot
                    && ready_output.is_none()
                    && ready_http.is_none()
                    && ready_port.is_none()
                    && ready_cmd.is_none())
                .then_some(0)
            });
            let mut delay_timer =
                ready_delay.map(|secs| Box::pin(time::sleep(Duration::from_secs(secs))));

            // Track exhaustion of timed checks
            let mut http_exhausted = false;
            let mut cmd_exhausted = false;
            let mut port_exhausted = false;
            let mut output_exhausted = false;

            // Get settings for intervals
            let s = settings();
            let ready_check_interval = s.supervisor_ready_check_interval();
            let http_client_timeout = s.supervisor_http_client_timeout();

            // Setup output readiness check deadline
            let mut output_deadline = ready_output
                .as_ref()
                .and_then(|o| o.timeout)
                .map(|d| Box::pin(time::sleep(d)));

            // Setup HTTP readiness check interval and deadline
            let mut http_check_interval = ready_http
                .as_ref()
                .map(|_| tokio::time::interval(ready_check_interval));
            let mut http_deadline = ready_http
                .as_ref()
                .and_then(|h| h.timeout)
                .map(|d| Box::pin(time::sleep(d)));
            let http_client = if ready_http.is_some() {
                Some(crate::supervisor::health::supervisor_http_client().await)
            } else {
                None
            };
            let mut http_probe: Option<HttpProbe> = None;

            // Setup TCP port readiness check interval and deadline
            let mut port_check_interval =
                ready_port.map(|_| tokio::time::interval(ready_check_interval));
            let mut port_deadline = ready_port_config
                .as_ref()
                .and_then(|p| p.timeout)
                .map(|d| Box::pin(time::sleep(d)));
            let mut port_probe: Option<PortProbe> = None;

            // Setup command readiness check state. Probes are spawned one at a time;
            // a non-zero result triggers a respawn delay, and a timeout stops the probe.
            let mut cmd_probe: Option<CmdProbe> = None;
            let mut cmd_respawn_delay: Option<_> = None;
            let mut cmd_deadline = ready_cmd
                .as_ref()
                .and_then(|c| c.timeout)
                .map(|d| Box::pin(time::sleep(d)));
            if let Some(ref cmd) = ready_cmd {
                cmd_probe = Some(spawn_cmd_probe(
                    &id,
                    &cmd.run,
                    daemon_dir.as_path(),
                    hook_retry_count,
                    readiness_daemon_env.as_ref(),
                    &readiness_resolved_ports,
                ));
            }

            // Use a channel to communicate process exit status
            let (exit_tx, mut exit_rx) =
                tokio::sync::mpsc::channel::<std::io::Result<std::process::ExitStatus>>(1);

            // Spawn a task to wait for process exit
            let child_pid = child.id().unwrap_or(0);
            tokio::spawn(async move {
                let result = child.wait().await;
                // On non-Linux Unix (e.g. macOS) the zombie reaper may win the
                // race and consume the exit status via waitpid(None, WNOHANG)
                // before Tokio's child.wait() gets to it. When that happens,
                // Tokio returns an ECHILD io::Error. We recover by checking
                // REAPED_STATUSES for the stashed exit code.
                //
                // On Linux this is unnecessary because the reaper uses
                // waitid(WNOWAIT) to peek before reaping, which avoids the
                // race entirely.
                #[cfg(all(unix, not(target_os = "linux")))]
                let result = match &result {
                    Err(e) if e.raw_os_error() == Some(nix::libc::ECHILD) => {
                        if let Some(code) = super::REAPED_STATUSES.lock().await.remove(&child_pid) {
                            warn!(
                                "daemon pid {child_pid} wait() got ECHILD; \
                                 recovered exit code {code} from zombie reaper"
                            );
                            // Synthesize an ExitStatus from the stashed code.
                            // On Unix we can use `ExitStatus::from_raw()` with
                            // a wait-style status word (code << 8 for normal
                            // exit, or raw signal number for signal death).
                            use std::os::unix::process::ExitStatusExt;
                            if code >= 0 {
                                Ok(std::process::ExitStatus::from_raw(code << 8))
                            } else {
                                // Negative code means killed by signal (-sig)
                                Ok(std::process::ExitStatus::from_raw((-code) & 0x7f))
                            }
                        } else {
                            warn!(
                                "daemon pid {child_pid} wait() got ECHILD but no \
                                 stashed status found; reporting as error"
                            );
                            result
                        }
                    }
                    _ => result,
                };
                debug!("daemon pid {child_pid} wait() completed with result: {result:?}");
                let _ = exit_tx.send(result).await;
            });

            #[allow(unused_assignments)]
            // Initial None is a safety net; loop only exits via exit_rx.recv() which sets it
            let mut exit_status = None;

            // If there is no ready check of any kind and no delay, the daemon is
            // considered immediately ready and the active_port detection task would
            // never be triggered inside the select loop.  Kick it off right away so
            // that daemons without any readiness configuration still get their
            // active_port populated (needed for proxy routing).
            if has_port_config
                && ready_pattern.is_none()
                && ready_http.is_none()
                && ready_port.is_none()
                && ready_cmd.is_none()
                && delay_timer.is_none()
            {
                active_port_spawned = true;
                detect_and_store_active_port(id.clone(), daemon_pid);
            }

            // Set when readiness checks exhaust. The group kill runs as a
            // separate task so this loop can exit and the post-loop drain
            // keeps consuming output — children logging during SIGTERM
            // cleanup would otherwise block on a full pipe and never exit.
            // The ready failure is only sent once the kill task completes,
            // so the retry loop cannot respawn into the dying group.
            let mut ready_fail_kill: Option<tokio::task::JoinHandle<Result<bool>>> = None;

            loop {
                // Process exits win; readiness timers precede probes and output.
                select! {
                    biased;
                    Some(result) = exit_rx.recv() => {
                        // Process exited - save exit status and notify if not ready yet
                        exit_status = Some(result);
                        port_claim.take();
                        debug!("daemon {id} process exited, exit_status: {exit_status:?}");
                        if !ready_notified {
                            // Check if process exited successfully
                            let is_success = exit_status.as_ref()
                                .and_then(|r| r.as_ref().ok())
                                .map(|s| s.success())
                                .unwrap_or(false);
                            if is_success && opts.oneshot {
                                debug!("daemon {id} completed, deferring success notification until the completed state is persisted");
                                oneshot_completion_pending = true;
                            } else if let Some(tx) = ready_tx.take() {
                                if is_success {
                                    debug!("daemon {id} exited successfully before ready check, sending success notification");
                                    let _ = tx.send(Ok(()));
                                } else {
                                    let exit_code = exit_status.as_ref()
                                        .and_then(|r| r.as_ref().ok())
                                        .and_then(|s| s.code());
                                    debug!("daemon {id} exited with failure before ready check, sending failure notification with exit_code: {exit_code:?}");
                                    let _ = tx.send(Err(ReadyFailure::Exit(exit_code)));
                                }
                            }
                        } else {
                            debug!("daemon {id} was already marked ready, not sending notification");
                        }
                        break;
                    },
                    _ = async {
                        if let Some(ref mut deadline) = http_deadline {
                            deadline.await;
                        } else {
                            std::future::pending::<()>().await;
                        }
                    }, if !ready_notified && ready_http.is_some() => {
                        http_exhausted = true;
                        http_deadline = None;
                        http_check_interval = None;
                        http_probe = None;
                        warn!("daemon {id}: HTTP readiness check timed out");
                        let any_remaining = any_ready_check_remaining(
                            ready_output.as_ref(),
                            output_exhausted,
                            ready_port_config.as_ref(),
                            port_exhausted,
                            ready_http.as_ref(),
                            http_exhausted,
                            ready_cmd.as_ref(),
                            cmd_exhausted,
                        );
                        if !any_remaining {
                            error!("daemon {id}: all readiness checks exhausted, failing");
                            stop_cmd_probe_state(&mut cmd_probe);
                            ready_fail_kill = Some(spawn_ready_fail_kill(
                                id.clone(),
                                daemon_pid,
                                opts.stop_signal.unwrap_or_default(),
                            ));
                            break;
                        }
                    }
                    _ = async {
                        if let Some(ref mut deadline) = output_deadline {
                            deadline.await;
                        } else {
                            std::future::pending::<()>().await;
                        }
                    }, if !ready_notified && ready_output.is_some() => {
                        output_exhausted = true;
                        output_deadline = None;
                        warn!("daemon {id}: output readiness check timed out");
                        let any_remaining = any_ready_check_remaining(
                            ready_output.as_ref(),
                            output_exhausted,
                            ready_port_config.as_ref(),
                            port_exhausted,
                            ready_http.as_ref(),
                            http_exhausted,
                            ready_cmd.as_ref(),
                            cmd_exhausted,
                        );
                        if !any_remaining {
                            error!("daemon {id}: all readiness checks exhausted, failing");
                            stop_cmd_probe_state(&mut cmd_probe);
                            ready_fail_kill = Some(spawn_ready_fail_kill(
                                id.clone(),
                                daemon_pid,
                                opts.stop_signal.unwrap_or_default(),
                            ));
                            break;
                        }
                    }
                    _ = async {
                        if let Some(ref mut deadline) = port_deadline {
                            deadline.await;
                        } else {
                            std::future::pending::<()>().await;
                        }
                    }, if !ready_notified && ready_port.is_some() => {
                        port_exhausted = true;
                        port_deadline = None;
                        port_check_interval = None;
                        port_probe = None;
                        warn!("daemon {id}: TCP port readiness check timed out");
                        let any_remaining = any_ready_check_remaining(
                            ready_output.as_ref(),
                            output_exhausted,
                            ready_port_config.as_ref(),
                            port_exhausted,
                            ready_http.as_ref(),
                            http_exhausted,
                            ready_cmd.as_ref(),
                            cmd_exhausted,
                        );
                        if !any_remaining {
                            error!("daemon {id}: all readiness checks exhausted, failing");
                            stop_cmd_probe_state(&mut cmd_probe);
                            ready_fail_kill = Some(spawn_ready_fail_kill(
                                id.clone(),
                                daemon_pid,
                                opts.stop_signal.unwrap_or_default(),
                            ));
                            break;
                        }
                    }
                    _ = async {
                        if let Some(ref mut deadline) = cmd_deadline {
                            deadline.await;
                        } else {
                            std::future::pending::<()>().await;
                        }
                    }, if !ready_notified && ready_cmd.is_some() => {
                        cmd_exhausted = true;
                        cmd_deadline = None;
                        stop_cmd_probe_state(&mut cmd_probe);
                        cmd_respawn_delay = None;
                        warn!("daemon {id}: command readiness check timed out");
                        let any_remaining = any_ready_check_remaining(
                            ready_output.as_ref(),
                            output_exhausted,
                            ready_port_config.as_ref(),
                            port_exhausted,
                            ready_http.as_ref(),
                            http_exhausted,
                            ready_cmd.as_ref(),
                            cmd_exhausted,
                        );
                        if !any_remaining {
                            error!("daemon {id}: all readiness checks exhausted, failing");
                            ready_fail_kill = Some(spawn_ready_fail_kill(
                                id.clone(),
                                daemon_pid,
                                opts.stop_signal.unwrap_or_default(),
                            ));
                            break;
                        }
                    }
                    _ = async {
                        if let Some(ref mut timer) = delay_timer {
                            timer.await;
                        } else {
                            std::future::pending::<()>().await;
                        }
                    } => {
                        let has_other_ready_check = ready_pattern.is_some()
                            || ready_http.is_some()
                            || ready_port.is_some()
                            || ready_cmd.is_some();
                        let delay_is_only_readiness = !ready_notified && !has_other_ready_check;
                        let process_exited = exit_status.is_some();
                        let process_running = if delay_is_only_readiness && !process_exited {
                            // A zombie still answers kill(pid, 0), but cannot
                            // become ready while its exit notification is pending.
                            PROCS.is_live(daemon_pid)
                        } else {
                            false
                        };

                        if delay_readiness_succeeded(
                            ready_notified,
                            has_other_ready_check,
                            process_exited,
                            process_running,
                        ) {
                            info!("daemon {id} ready: delay elapsed");
                            ready_notified = true;
                            if let Some(tx) = ready_tx.take() {
                                let _ = tx.send(Ok(()));
                            }
                            fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
                            if !active_port_spawned && has_port_config {
                                active_port_spawned = true;
                                detect_and_store_active_port(id.clone(), daemon_pid);
                            }
                        } else if delay_is_only_readiness {
                            if process_exited {
                                debug!("daemon {id} exited during ready_delay, not marking as ready");
                            } else {
                                debug!("daemon {id} pid {daemon_pid} not running during ready_delay, deferring to exit handler");
                            }
                        }

                        if delay_is_only_readiness {
                            // Clear all deadlines — no other checks are configured
                            // when delay fires as readiness, but clear defensively.
                            output_deadline = None;
                            http_deadline = None;
                            cmd_deadline = None;
                            port_deadline = None;
                            stop_cmd_probe_state(&mut cmd_probe);
                        }
                        // Disable timer after it fires
                        delay_timer = None;
                    }
                    _ = async {
                        if let Some(ref mut interval) = http_check_interval {
                            interval.tick().await;
                        } else {
                            std::future::pending::<()>().await;
                        }
                    }, if !ready_notified && ready_http.is_some() && !http_exhausted && http_probe.is_none() => {
                        if let (Some(http), Some(client)) = (&ready_http, &http_client) {
                            http_probe = Some(Box::pin(client.get(&http.url).timeout(http_client_timeout).send()));
                        }
                    }
                    result = async {
                        if let Some(probe) = http_probe.as_mut() {
                            probe.as_mut().await
                        } else {
                            std::future::pending::<std::result::Result<reqwest::Response, reqwest::Error>>().await
                        }
                    }, if !ready_notified && http_probe.is_some() => {
                        http_probe = None;
                        if let Some(http) = &ready_http {
                            match result {
                                Ok(response) if http.accepts_status(response.status().as_u16()) => {
                                    info!("daemon {id} ready: HTTP check passed (status {})", response.status());
                                    ready_notified = true;
                                    if let Some(tx) = ready_tx.take() {
                                        let _ = tx.send(Ok(()));
                                    }
                                    fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
                                    http_check_interval = None;
                                    http_deadline = None;
                                    stop_cmd_probe_state(&mut cmd_probe);
                                    cmd_deadline = None;
                                    port_deadline = None;
                                    output_deadline = None;
                                    if !active_port_spawned && has_port_config {
                                        active_port_spawned = true;
                                        detect_and_store_active_port(id.clone(), daemon_pid);
                                    }
                                }
                                Ok(response) => {
                                    trace!("daemon {id} HTTP check: status {} (not ready)", response.status());
                                }
                                Err(e) => {
                                    trace!("daemon {id} HTTP check failed: {e}");
                                }
                            }
                        }
                    }
                    _ = async {
                        if let Some(ref mut interval) = port_check_interval {
                            interval.tick().await;
                        } else {
                            std::future::pending::<()>().await;
                        }
                    }, if !ready_notified && ready_port.is_some() && !port_exhausted && port_probe.is_none() => {
                        if let Some(port) = ready_port {
                            port_probe = Some(Box::pin(tokio::net::TcpStream::connect(("127.0.0.1", port))));
                        }
                    }
                    result = async {
                        if let Some(probe) = port_probe.as_mut() {
                            probe.as_mut().await
                        } else {
                            std::future::pending::<std::io::Result<tokio::net::TcpStream>>().await
                        }
                    }, if !ready_notified && port_probe.is_some() => {
                        port_probe = None;
                        if let Some(port) = ready_port {
                            match result {
                                Ok(_) => {
                                    info!("daemon {id} ready: TCP port {port} is listening");
                                    ready_notified = true;
                                    if let Some(tx) = ready_tx.take() {
                                        let _ = tx.send(Ok(()));
                                    }
                                    fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
                                    // Stop checking once ready
                                    port_check_interval = None;
                                    port_deadline = None;
                                    stop_cmd_probe_state(&mut cmd_probe);
                                    http_deadline = None;
                                    cmd_deadline = None;
                                    output_deadline = None;
                                    if !active_port_spawned && has_port_config {
                                        active_port_spawned = true;
                                        // ready_port check just TCP-connected to this
                                        // port, so it is definitely listening. If it
                                        // matches the first resolved port, write
                                        // active_port directly instead of spawning
                                        // detect_and_store_active_port, which sleeps
                                        // 500 ms then relies on listeners::get_all()
                                        // + process-tree traversal — unreliable on
                                        // Windows where Git Bash PID mapping can
                                        // break descendant lookups.
                                        if let Some(active_port) = active_port_from_ready_port(
                                            port,
                                            &readiness_resolved_ports,
                                        ) {
                                            let mut state_file =
                                                SUPERVISOR.state_file.lock().await;
                                            if let Some(d) = state_file.daemons.get(&id)
                                                && d.pid == Some(daemon_pid)
                                            {
                                                state_file.set_active_port(&id, active_port);
                                            }
                                        } else {
                                            detect_and_store_active_port(
                                                id.clone(),
                                                daemon_pid,
                                            );
                                        }
                                    }
                                }
                                Err(_) => {
                                    trace!("daemon {id} port check: port {port} not listening yet");
                                }
                            }
                        }
                    }
                    _ = async {
                        if let Some(ref mut delay) = cmd_respawn_delay {
                            delay.await;
                        } else {
                            std::future::pending::<()>().await;
                        }
                    }, if !ready_notified && ready_cmd.is_some() && !cmd_exhausted && cmd_probe.is_none() => {
                        if let Some(ref cmd) = ready_cmd {
                            cmd_probe = Some(spawn_cmd_probe(
                                &id,
                                &cmd.run,
                                daemon_dir.as_path(),
                                hook_retry_count,
                                readiness_daemon_env.as_ref(),
                                &readiness_resolved_ports,
                            ));
                        }
                        cmd_respawn_delay = None;
                    }
                    result = async {
                        if let Some(probe) = cmd_probe.as_mut() {
                            std::pin::Pin::new(&mut probe.result_rx).await
                        } else {
                            std::future::pending::<Result<Result<std::process::ExitStatus, std::io::Error>, tokio::sync::oneshot::error::RecvError>>().await
                        }
                    }, if !ready_notified && ready_cmd.is_some() && !cmd_exhausted => {
                        // The probe task has finished; remove the handle so it is not
                        // cancelled or reused. This must happen only after this branch
                        // actually wins the select, not while constructing the future.
                        let _ = cmd_probe.take();
                        match result {
                            Ok(Ok(status)) if status.success() => {
                                info!("daemon {id} ready: readiness command succeeded");
                                ready_notified = true;
                                if let Some(tx) = ready_tx.take() {
                                    let _ = tx.send(Ok(()));
                                }
                                fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
                                cmd_respawn_delay = None;
                                cmd_deadline = None;
                                http_deadline = None;
                                port_deadline = None;
                                output_deadline = None;
                                if !active_port_spawned && has_port_config {
                                    active_port_spawned = true;
                                    detect_and_store_active_port(id.clone(), daemon_pid);
                                }
                            }
                            Ok(Ok(_)) | Ok(Err(_)) | Err(_) => {
                                trace!("daemon {id} cmd check: command not ready, will respawn");
                                cmd_respawn_delay = Some(Box::pin(time::sleep(ready_check_interval)));
                            }
                        }
                    }
                    Some(super::OutputLine { text: line, source }) = output_rx.recv() => {
                        // A line relayed by a sink is already in the store —
                        // the sink wrote and flushed it before reporting it —
                        // so it arrives here only to be acted on.
                        if matches!(source, super::OutputSource::Local) {
                            let parsed = parse_line(&line);
                            log_buffer.push(parsed);
                            if log_buffer.len() >= LOG_BATCH_SIZE {
                                flush_logs(&mut log_buffer, &mut pending_log_writes);
                            }
                        }
                        trace!("output: {id} {line}");

                        // Strip ANSI for pattern matching so user-written patterns
                        // work regardless of whether the process emits color codes.
                        let line_clean = console::strip_ansi_codes(&line).to_string();

                        // Check if output matches ready pattern
                        if !ready_notified
                            && !output_exhausted
                            && let Some(ref pattern) = ready_pattern
                            && pattern.is_match(&line_clean)
                        {
                            // Flush buffered logs synchronously before signalling
                            // readiness, so collect_startup_logs sees the line
                            // that triggered the match (and any co-buffered lines)
                            // in SQLite.
                            flush_logs(&mut log_buffer, &mut pending_log_writes);
                            for handle in pending_log_writes.drain(..) {
                                let _ = handle.await;
                            }
                            info!("daemon {id} ready: output matched pattern");
                            ready_notified = true;
                            if let Some(tx) = ready_tx.take() {
                                let _ = tx.send(Ok(()));
                            }
                            fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
                            stop_cmd_probe_state(&mut cmd_probe);
                            http_deadline = None;
                            cmd_deadline = None;
                            port_deadline = None;
                            output_deadline = None;
                            if !active_port_spawned && has_port_config {
                                active_port_spawned = true;
                                detect_and_store_active_port(id.clone(), daemon_pid);
                            }
                        }

                        // Check on_output hook. A sink has already applied the
                        // filter, and says so per line: a line reported only
                        // because it announced readiness must not fire a hook
                        // that filters for something else.
                        if let Some(ref hook) = on_output_hook {
                            let matched = match source {
                                super::OutputSource::Sink { fires_hook } => fires_hook,
                                super::OutputSource::Local => match (&hook.filter, &on_output_pattern) {
                                    (Some(substr), _) => line_clean.contains(substr.as_str()),
                                    (None, Some(re)) => re.is_match(&line_clean),
                                    (None, None) => true,
                                },
                            };
                            if matched {
                                // The debounce is applied here as well as in the
                                // sink. A replacement sink starts with a fresh
                                // clock, and would otherwise let the hook fire
                                // twice inside one configured window.
                                let now = std::time::Instant::now();
                                let elapsed = on_output_last_fired.map(|t| now.duration_since(t));
                                if elapsed.is_none_or(|e| e >= on_output_debounce) {
                                    on_output_last_fired = Some(now);
                                    hooks::fire_output_hook(id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), hook.run.clone(), line_clean.clone()).await;
                                }
                            }
                        }
                        // Let other tasks run during continuous output.
                        tokio::task::yield_now().await;
                    }
                    _ = log_flush_interval.tick() => {
                        flush_logs(&mut log_buffer, &mut pending_log_writes);
                    }
                }
                if ready_notified {
                    http_probe = None;
                    port_probe = None;
                }
            }
            drop(http_probe);
            drop(port_probe);

            // Snapshot the daemon state BEFORE draining output.
            //
            // The drain can take up to 5s (e.g. when child processes keep the
            // stdout pipe open). During that time, a subsequent start() call
            // (e.g. from `pitchfork restart`) can upsert the daemon with a new
            // PID and Running status. If we only checked state AFTER the drain,
            // the monitoring task would see d.pid != Some(old_pid) && !is_stopped()
            // && !is_stopping() and return early without firing on_stop/on_exit
            // hooks.
            //
            // By snapshotting is_stopping before the drain, we preserve the
            // knowledge that stop() was called, so hooks fire correctly even
            // if start() has since changed the state.
            let pre_drain_daemon = SUPERVISOR.get_daemon(&id).await;
            let pre_drain_is_stopping = pre_drain_daemon
                .as_ref()
                .is_some_and(|d| d.status.is_stopped() || d.status.is_stopping_or_restarting());

            // Drain any in-flight output lines that were still in the mpsc
            // channel or the OS pipe buffer when the child exited. Without
            // this, trailing log lines from short-lived daemons get dropped.
            // The reader tasks drop their senders on EOF, so recv() returns
            // None when all data has been consumed. A total deadline of 5 s
            // guards against a stuck reader (e.g. PTY master FD not closing)
            // while ensuring drain doesn't block post-exit cleanup indefinitely.
            //
            // Stop accepting relayed output first: the relay holds a sender of
            // its own, so leaving it registered would keep the channel open and
            // make every drain wait out the whole deadline. Readiness is moot
            // now anyway — the process has exited.
            drop(output_relay);
            let drain_deadline = tokio::time::Instant::now() + super::EXIT_OUTPUT_DRAIN_TIMEOUT;
            loop {
                let now = tokio::time::Instant::now();
                if now >= drain_deadline {
                    break;
                }
                let Ok(Some(line)) =
                    tokio::time::timeout(drain_deadline - now, output_rx.recv()).await
                else {
                    break;
                };
                // Sink-relayed lines are already stored; see the select loop.
                if matches!(line.source, super::OutputSource::Local) {
                    log_buffer.push(parse_line(&line.text));
                }
            }
            // Flush any remaining log lines (including drained) before the process exits.
            // Await the flush to guarantee all buffered logs are persisted before cleanup.
            flush_logs(&mut log_buffer, &mut pending_log_writes);
            for handle in pending_log_writes {
                let _ = handle.await;
            }

            // Clear active_port since the process is no longer running
            {
                let mut state_file = SUPERVISOR.state_file.lock().await;
                state_file.clear_active_port(&id);
                if super::log_sink::is_current_attempt(&id, status_token) {
                    state_file.drop_live_program_status(&id);
                }
            }

            let readiness_failed = ready_fail_kill.is_some();
            let mut termination_error = None;
            if let Some(kill) = ready_fail_kill {
                let result = kill.await.into_diagnostic().and_then(|result| result);
                let failure = match result {
                    Ok(_) => {
                        // The process is gone; free its ports before the drain.
                        port_claim.take();
                        ReadyFailure::Exit(Some(124))
                    }
                    Err(error) => {
                        let error = format!(
                            "failed to terminate daemon {id} after readiness failure: {error}"
                        );
                        error!("{error}");
                        let mut state_file = SUPERVISOR.state_file.lock().await;
                        if state_file.daemons.get(&id).is_some_and(|daemon| {
                            daemon.pid == Some(pid)
                                && !daemon.status.is_stopped()
                                && !daemon.status.is_stopping_or_restarting()
                        }) {
                            state_file.set_status(&id, DaemonStatus::Failed(error.clone()));
                        }
                        termination_error = Some(error.clone());
                        ReadyFailure::Termination(error)
                    }
                };
                if let Some(tx) = ready_tx.take() {
                    let _ = tx.send(Err(failure));
                }
            }

            // Report a failed kill first, but retain this process's record and
            // monitor until its entire group is gone. A leader can exit while
            // an unkillable descendant still holds the daemon's resources.
            if termination_error.is_some() {
                while PROCS.process_group_alive(daemon_pid) {
                    // Match the output flush cadence while waiting for recovery.
                    time::sleep(Duration::from_millis(100)).await;
                }
            }

            // Get the final exit status
            let exit_status = if let Some(status) = exit_status {
                status
            } else {
                // Streams closed but process hasn't exited yet, wait for it
                match exit_rx.recv().await {
                    Some(status) => status,
                    None => {
                        warn!("daemon {id} exit channel closed without receiving status");
                        Err(std::io::Error::other("exit channel closed"))
                    }
                }
            };

            let current_daemon = SUPERVISOR.get_daemon(&id).await;

            // Signal that this monitoring task is processing its exit path.
            // The RAII guard will decrement the counter and notify close()
            // when the task finishes (including all fire_hook registrations),
            // regardless of which return path is taken.
            SUPERVISOR
                .active_monitors
                .fetch_add(1, atomic::Ordering::Release);
            struct MonitorGuard;
            impl Drop for MonitorGuard {
                fn drop(&mut self) {
                    SUPERVISOR
                        .active_monitors
                        .fetch_sub(1, atomic::Ordering::Release);
                    SUPERVISOR.monitor_done.notify_waiters();
                }
            }
            let _monitor_guard = MonitorGuard;
            // Check if this monitoring task is for the current daemon process.
            // If the daemon was intentionally stopped (pre_drain_is_stopping),
            // skip this check — we must still fire on_stop/on_exit hooks even
            // if start() has since changed the PID and status.
            if !pre_drain_is_stopping
                && (current_daemon.is_none()
                    || current_daemon.as_ref().is_some_and(|d| {
                        d.pid != Some(pid)
                            && !d.status.is_stopped()
                            && !d.status.is_stopping_or_restarting()
                    }))
            {
                // Another process has taken over, don't update status. The
                // task itself did finish, so a caller waiting on it is still
                // told so rather than left to time out.
                if oneshot_completion_pending && let Some(tx) = ready_tx.take() {
                    let _ = tx.send(Ok(()));
                }
                return;
            }
            // Capture the intentional-stop flag. Combine pre-drain and
            // post-drain state to handle both race orders:
            //  - stop() set Stopping before drain → pre_drain_is_stopping
            //  - stop() set Stopped during drain → current_daemon.is_stopped()
            let already_stopped = current_daemon
                .as_ref()
                .is_some_and(|d| d.status.is_stopped());
            let is_stopping = already_stopped
                || pre_drain_is_stopping
                || current_daemon
                    .as_ref()
                    .is_some_and(|d| d.status.is_stopping_or_restarting());

            // --- Phase 1: Determine exit_code, exit_reason, and update daemon state ---
            let (exit_code, exit_reason) = match (&exit_status, is_stopping) {
                (Ok(status), true) => {
                    // Intentional stop (by pitchfork). status.code() returns None
                    // on Unix when killed by signal (e.g. SIGTERM); use -1 to
                    // distinguish from a clean exit code 0.
                    (status.code().unwrap_or(-1), "stop")
                }
                (_, false) if readiness_failed => (124, "fail"),
                (Ok(status), false) if status.success() => (status.code().unwrap_or(-1), "exit"),
                (Ok(status), false) => (status.code().unwrap_or(-1), "fail"),
                (Err(_), true) => {
                    // child.wait() error while stopping (e.g. sysinfo reaped the process)
                    (-1, "stop")
                }
                (Err(_), false) => (-1, "fail"),
            };
            // A stop that arrived while this monitor was draining did not get
            // to write anything, so it is applied here. A run that had already
            // succeeded keeps that outcome — there was nothing left to
            // interrupt — but a failed one is recorded as stopped, so the
            // retry checker leaves it alone.

            // Update daemon state unless stop() already did it (won the race),
            // OR the daemon was intentionally stopped before the drain
            // (pre_drain_is_stopping). In the latter case, start() may have
            // upserted Running during the 5s drain, and we must NOT overwrite
            // it with Stopped — that would undo the restart.
            if !already_stopped && !pre_drain_is_stopping {
                if let Ok(status) = &exit_status {
                    info!("daemon {id} exited with status {status}");
                }
                let (mut new_status, last_exit_success) = terminal_exit_state(
                    exit_reason,
                    opts.oneshot,
                    exit_code,
                    exit_status.as_ref().map(|s| s.success()).unwrap_or(true),
                );
                if !is_stopping && let Some(error) = &termination_error {
                    new_status = DaemonStatus::Failed(error.clone());
                }
                // Revalidate ownership inside the same state-lock section that
                // performs the write. The snapshot above was taken without
                // holding the lock, so a restart running on another thread can
                // install a successor in between; overwriting its record would
                // clear a live daemon's PID and undo the restart.
                if !SUPERVISOR
                    .finalize_monitored_exit(
                        &id,
                        pid,
                        monitor_token,
                        new_status,
                        Some(last_exit_success),
                    )
                    .await
                {
                    debug!("daemon {id} exit state was not written; a successor owns the record");
                }
            }

            // The terminal state is now visible, so a caller waiting on this
            // oneshot can return and see it. A task that was stopped partway
            // never did its work, so it does not satisfy anything waiting on
            // it — even when the process caught the signal and exited 0.
            if oneshot_completion_pending && let Some(tx) = ready_tx.take() {
                if exit_reason == "exit" {
                    let _ = tx.send(Ok(()));
                } else {
                    warn!("daemon {id}: oneshot was stopped before completing");
                    let _ = tx.send(Err(ReadyFailure::Exit(None)));
                }
            }

            // --- Phase 2: Fire hooks ---
            let hook_extra_env = vec![
                ("PITCHFORK_EXIT_CODE".to_string(), exit_code.to_string()),
                ("PITCHFORK_EXIT_REASON".to_string(), exit_reason.to_string()),
            ];

            // Determine which hooks to fire based on exit reason
            let hooks_to_fire: Vec<HookType> = match exit_reason {
                "stop" => vec![HookType::OnStop, HookType::OnExit],
                "exit" => vec![HookType::OnExit],
                // "fail": fire on_fail + on_exit only when retries are exhausted
                _ if termination_error.is_some() || hook_retry_count >= hook_retry.count() => {
                    vec![HookType::OnFail, HookType::OnExit]
                }
                _ => vec![],
            };

            for hook_type in hooks_to_fire {
                fire_hook(
                    hook_type,
                    id.clone(),
                    hook_dirs.clone(),
                    hook_retry_count,
                    hook_daemon_env.clone(),
                    hook_resolved_ports.clone(),
                    hook_extra_env.clone(),
                )
                .await;
            }
        });

        if let Some(ready_rx) = ready_rx {
            let wait_ready = opts.wait_ready;
            let oneshot = opts.oneshot;
            let last_attempt = opts.retry_count >= opts.retry.count();
            let started = IpcResponse::DaemonStart {
                daemon: daemon.clone(),
            };
            let ready = async move {
                let id = daemon.id.clone();
                let ready = ready_rx.await;
                SUPERVISOR.end_ready_check(&id, &attempt_rx);
                match ready {
                    Ok(Ok(())) => {
                        info!("daemon {id} is ready");
                        // Re-read rather than returning the snapshot taken at
                        // spawn: a completed oneshot has since been finalized, and
                        // the snapshot would tell the caller it is still running
                        // under a PID that has exited.
                        //
                        // Only when the record still describes this run, though. A
                        // successor that claimed it carries its own PID and start
                        // time, and reporting those as the outcome of the process
                        // this call spawned would misattribute them.
                        let daemon = match SUPERVISOR.get_daemon(&id).await {
                            Some(current) if current.pid.is_none() || current.pid == Some(pid) => {
                                current
                            }
                            // A successor owns the record, so neither it nor the
                            // spawn snapshot describes this run: one carries
                            // another process's identity, the other still says
                            // running under a PID that has exited. A oneshot that
                            // reported ready did finish, so report that outcome
                            // directly rather than either misleading record.
                            _ if oneshot => crate::daemon::Daemon {
                                status: DaemonStatus::Completed,
                                pid: None,
                                start_time: None,
                                boot_time: None,
                                last_exit_success: Some(true),
                                ..daemon
                            },
                            _ => daemon,
                        };
                        IpcResponse::DaemonReady { daemon }
                    }
                    Ok(Err(ReadyFailure::Exit(exit_code))) => {
                        error!("daemon {id} failed before becoming ready");
                        // The caller reports this by querying the log store for
                        // what the daemon printed, so wait for the sink's final
                        // write first. The in-process path got this ordering by
                        // flushing synchronously before signalling.
                        //
                        // Only on the attempt that gives up: `run` retries inline,
                        // and waiting after every attempt would both delay the
                        // backoff and widen the window in which the daemon looks
                        // errored and idle — long enough for the background retry
                        // checker to start an attempt of its own alongside it.
                        if using_sink && last_attempt {
                            super::log_sink::wait_for_output(&id, spawn_time, SINK_OUTPUT_TIMEOUT)
                                .await;
                        }
                        IpcResponse::DaemonFailedWithCode {
                            exit_code,
                            resolved_ports: attempt_resolved_ports,
                        }
                    }
                    Ok(Err(ReadyFailure::Termination(error))) => {
                        IpcResponse::DaemonFailed { error }
                    }
                    Err(_) => {
                        error!("readiness channel closed unexpectedly for daemon {id}");
                        IpcResponse::DaemonStart { daemon }
                    }
                }
            };
            let completion = tokio::spawn(async move {
                let response = ready.await;
                attempt_tx.send_replace(Some(response.clone()));
                response
            });
            if wait_ready {
                completion.await.into_diagnostic()
            } else {
                Ok(started)
            }
        } else {
            Ok(IpcResponse::DaemonStart { daemon })
        }
    }

    /// Stop a running daemon
    pub async fn stop(&self, id: &DaemonId) -> Result<IpcResponse> {
        // Hold the daemon's stop lock for the whole stop (including the
        // whole-group termination wait) so starts and concurrent stops of the
        // same daemon serialize against it instead of racing the Stopping window.
        let lock = self.stop_lock(id).await;
        let _guard = lock.lock().await;
        self.stop_locked(id).await
    }

    /// Stop a running daemon that is about to be started again (a file-watch
    /// restart). Same as [`Self::stop`], except the daemon is recorded as
    /// `restarting` rather than `stopping`/`stopped`, so anything following it
    /// (`pitchfork wait`) does not mistake the stop for the end of its run.
    /// The caller must start the daemon again, or settle the record with
    /// [`Self::settle_restarting`] if it cannot.
    pub(crate) async fn stop_for_restart(&self, id: &DaemonId) -> Result<IpcResponse> {
        let lock = self.stop_lock(id).await;
        let _guard = lock.lock().await;
        self.stop_locked_with(id, true).await
    }

    /// Stop implementation. Caller must hold the daemon's stop lock.
    pub(super) async fn stop_locked(&self, id: &DaemonId) -> Result<IpcResponse> {
        self.stop_locked_with(id, false).await
    }

    /// Stop implementation. Caller must hold the daemon's stop lock.
    ///
    /// With `restarting`, every status this would record as `stopping` or
    /// `stopped` is recorded as `restarting` instead: the daemon is on its way
    /// back, and recording it as stopped, even briefly, would tell anything
    /// watching the record that its run is over.
    pub(super) async fn stop_locked_with(
        &self,
        id: &DaemonId,
        restarting: bool,
    ) -> Result<IpcResponse> {
        let (stopping_status, stopped_status) = if restarting {
            (DaemonStatus::Restarting, DaemonStatus::Restarting)
        } else {
            (DaemonStatus::Stopping, DaemonStatus::Stopped)
        };
        let pitchfork_id = DaemonId::pitchfork();
        if *id == pitchfork_id {
            return Ok(IpcResponse::Error(
                "Cannot stop supervisor via stop command".into(),
            ));
        }
        info!("stopping daemon: {id}");
        // A foreground `start` may be working through this daemon's retries,
        // sleeping out a backoff with no process of its own to kill. Tell it to
        // give up, or it would start the next attempt once the stop has
        // returned.
        self.cancel_retrying(id);
        // ...and the retry checker may already have decided on an attempt it
        // has not started yet. The count is raised when this stop is done
        // rather than now, and while its lock is still held, so a checker that
        // reads the count while the stop is still recording itself reads the
        // old value and stands down when it reaches the lock. Raising it up
        // front would hand that reader a value that still matches once the
        // stop has finished.
        let _stop_epoch_bump = StopEpochGuard(id.clone());
        if let Some(daemon) = self.get_daemon(id).await {
            trace!("daemon to stop: {daemon}");
            if let Some(pid) = daemon.pid {
                trace!("killing pid: {pid}");
                if PROCS.is_running(pid) {
                    // Something is alive on that PID, but the kill below signals
                    // the entire process group: if the PID was recycled while
                    // this record sat unsupervised, that group belongs to an
                    // unrelated process tree. The daemon itself is gone either
                    // way, so report it as not running and clear the record.
                    if !super::signalling_pid_is_authorized(
                        daemon.start_time,
                        PROCS.start_time(pid),
                    ) {
                        warn!(
                            "pid {pid} recorded for daemon {id} belongs to another process now; not signalling it"
                        );
                        self.upsert_daemon(
                            UpsertDaemonOpts::builder(id.clone())
                                .set(|o| {
                                    o.pid = None;
                                    o.status = stopped_status.clone();
                                })
                                .build(),
                        )
                        .await?;
                        return Ok(IpcResponse::DaemonWasNotRunning);
                    }

                    // First set status to Stopping (preserve PID for monitoring task)
                    self.upsert_daemon(
                        UpsertDaemonOpts::builder(id.clone())
                            .set(|o| {
                                o.pid = Some(pid);
                                o.status = stopping_status.clone();
                            })
                            .build(),
                    )
                    .await?;

                    // Kill the entire process group atomically (daemon PID == PGID
                    // because we called setsid() at spawn time)
                    let stop_cfg = daemon.stop_signal.unwrap_or_default();
                    let stop_signal: i32 = stop_cfg.signal.into();
                    if let Err(e) = PROCS
                        .kill_process_group_async(pid, stop_signal, stop_cfg.timeout)
                        .await
                    {
                        debug!("failed to kill pid {pid}: {e}");
                        // Check if the process group is actually gone despite the
                        // error. Checking only the leader here would mark the daemon
                        // Stopped while surviving group members (e.g. one stuck in
                        // uninterruptible sleep) are still alive — letting a restart
                        // collide with them.
                        if PROCS.process_group_alive(pid) {
                            // Group still has live members - set back to Running
                            debug!(
                                "failed to stop pid {pid}: process group still alive after kill"
                            );
                            self.upsert_daemon(
                                UpsertDaemonOpts::builder(id.clone())
                                    .set(|o| {
                                        o.pid = Some(pid); // Preserve PID to avoid orphaning the process
                                        o.status = DaemonStatus::Running;
                                    })
                                    .build(),
                            )
                            .await?;
                            return Ok(IpcResponse::DaemonStopFailed {
                                error: format!(
                                    "process group of {pid} still alive after kill attempt: {e}"
                                ),
                            });
                        }
                        // On Windows the daemon can be gone while processes of
                        // its job remain (see `procs`), which the PID check above
                        // cannot see. The daemon is recorded as stopped, since
                        // it is, but the stop is reported as failed.
                        #[cfg(windows)]
                        {
                            self.upsert_daemon(
                                UpsertDaemonOpts::builder(id.clone())
                                    .set(|o| {
                                        o.pid = None;
                                        o.status = stopped_status.clone();
                                        o.last_exit_success = Some(true);
                                    })
                                    .build(),
                            )
                            .await?;
                            return Ok(IpcResponse::DaemonStopFailed {
                                error: format!("{e}"),
                            });
                        }
                    }

                    // Process successfully stopped
                    // Note: kill_process_group_async waits for the ENTIRE process
                    // group to exit (stop signal -> stop_timeout -> SIGKILL, then a
                    // bounded verification), so a replacement daemon can be started
                    // without colliding with a still-terminating instance. The only
                    // exception is a member stuck in uninterruptible sleep, which is
                    // logged with a warning.
                    self.upsert_daemon(
                        UpsertDaemonOpts::builder(id.clone())
                            .set(|o| {
                                o.pid = None;
                                o.status = stopped_status.clone();
                                o.last_exit_success = Some(true);
                            })
                            .build(),
                    )
                    .await?;
                } else if daemon.oneshot && self.is_monitored(id, pid) {
                    // The task's process is gone but its monitor is still
                    // running, so the run's real outcome has not been written
                    // yet — and for a task that finished on its own that
                    // outcome is `completed`. Writing `stopped` straight over
                    // it would discard a success the task actually achieved
                    // and report failure to anyone waiting on it, purely
                    // because a stop arrived a moment late.
                    //
                    // So wait for whoever is monitoring this run — the native
                    // monitor or an adopted one — to finish, then decide from
                    // what it wrote. Waiting rather than leaving a note for
                    // the monitor to find means there is no window in which
                    // the note lands too late to be read, and nothing left
                    // behind if it is never read at all. The wait is bounded,
                    // as is the monitor's own five-second output drain.
                    //
                    // Only oneshots take this path. A service has no
                    // successful exit to preserve, so it falls through to the
                    // arm below, which records the stop immediately.
                    debug!(
                        "pid {pid} not running but daemon {id} is still monitored; waiting for its monitor to settle the outcome"
                    );
                    self.wait_for_exit_finalized(id, Some(pid)).await;
                    let finished = self.get_daemon(id).await;
                    if finished
                        .as_ref()
                        .is_some_and(|d| stop_keeps_finalized_status(&d.status))
                    {
                        return Ok(IpcResponse::DaemonWasNotRunning);
                    }
                    // The run did not finish its work, so record the stop. A
                    // failure left in place would be picked up by the retry
                    // checker, which would start a task the user just stopped.
                    self.upsert_daemon(
                        UpsertDaemonOpts::builder(id.clone())
                            .set(|o| {
                                o.pid = None;
                                o.status = stopped_status.clone();
                            })
                            .build(),
                    )
                    .await?;
                    return Ok(IpcResponse::DaemonWasNotRunning);
                } else {
                    debug!("pid {pid} not running, process may have exited unexpectedly");
                    // Process already dead and unmonitored, so nothing else
                    // will record an outcome — transition to Stopped so the
                    // retry checker sees a terminal state and stops
                    // scheduling new attempts. This is important for an
                    // explicit `pitchfork stop` on an Errored daemon: the
                    // user wants to abort retries.
                    self.upsert_daemon(
                        UpsertDaemonOpts::builder(id.clone())
                            .set(|o| {
                                o.pid = None;
                                o.status = stopped_status.clone();
                            })
                            .build(),
                    )
                    .await?;
                    return Ok(IpcResponse::DaemonWasNotRunning);
                }
                Ok(IpcResponse::Ok)
            } else {
                debug!("daemon {id} not running");
                // Between a restart's stop and its start there is no process,
                // but the daemon is on its way back. Stopping it now cancels
                // the restart: the restart sees the record has moved on and
                // does not start it again.
                if !restarting && daemon.status.is_restarting() {
                    self.upsert_daemon(
                        UpsertDaemonOpts::builder(id.clone())
                            .set(|o| {
                                o.pid = None;
                                o.status = DaemonStatus::Stopped;
                            })
                            .build(),
                    )
                    .await?;
                    return Ok(IpcResponse::Ok);
                }
                // No process to signal, but a failed record with retries left
                // is not inert: `check_retry` starts the next attempt from it,
                // whether or not a foreground start is also working through
                // them. Record the stop so nothing picks the daemon back up.
                if daemon.status.is_errored() && daemon.retry_count < daemon.retry.count() {
                    self.upsert_daemon(
                        UpsertDaemonOpts::builder(id.clone())
                            .set(|o| {
                                o.pid = None;
                                o.status = stopped_status.clone();
                            })
                            .build(),
                    )
                    .await?;
                    return Ok(IpcResponse::DaemonWasNotRunning);
                }
                Ok(IpcResponse::DaemonNotRunning)
            }
        } else {
            debug!("daemon {id} not found");
            Ok(IpcResponse::DaemonNotFound)
        }
    }
}

#[cfg(unix)]
fn resolve_effective_run_identity(daemon_user: Option<&str>) -> Result<RunIdentity> {
    let s = settings();
    let settings_user = s.supervisor.user.trim();
    let daemon_user = daemon_user.map(str::trim).filter(|user| !user.is_empty());
    let settings_user = (!settings_user.is_empty()).then_some(settings_user);
    let configured = daemon_user.or(settings_user);
    let current_uid = nix::unistd::Uid::effective().as_raw();
    let current_gid = nix::unistd::Gid::effective().as_raw();
    // The recorded invoking user of a boot service stands in for the sudo
    // environment that launchd and systemd do not provide.
    let invoking = env::invoking_user_ids().map(|(uid, gid)| (uid.to_string(), gid.to_string()));
    resolve_run_identity(
        configured,
        current_uid,
        current_gid,
        invoking.as_ref().map(|(uid, _)| uid.as_str()),
        invoking.as_ref().map(|(_, gid)| gid.as_str()),
    )
}

#[cfg(unix)]
fn resolve_run_identity(
    configured: Option<&str>,
    current_uid: u32,
    current_gid: u32,
    sudo_uid: Option<&str>,
    sudo_gid: Option<&str>,
) -> Result<RunIdentity> {
    let current_uid = nix::unistd::Uid::from_raw(current_uid);
    let current_gid = nix::unistd::Gid::from_raw(current_gid);
    if let Some(user) = configured {
        let identity = resolve_configured_user(user)?;
        ensure_can_use_identity(user, &identity, current_uid, current_gid)?;
        if identity.matches(current_uid, current_gid) {
            return Ok(RunIdentity::Inherit);
        }
        return Ok(identity);
    }

    if current_uid.is_root()
        && let Some(identity) = resolve_sudo_identity(sudo_uid, sudo_gid)
    {
        if identity.matches(current_uid, current_gid) {
            return Ok(RunIdentity::Inherit);
        }
        return Ok(identity);
    }

    Ok(RunIdentity::Inherit)
}

#[cfg(unix)]
fn resolve_configured_user(user: &str) -> Result<RunIdentity> {
    if user.chars().all(|c| c.is_ascii_digit()) {
        let uid = user
            .parse::<u32>()
            .map_err(|e| miette::miette!("invalid run user UID '{}': {}", user, e))?;
        let user_record = nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))
            .into_diagnostic()?
            .ok_or_else(|| miette::miette!("run user UID '{}' does not exist", user))?;
        return run_identity_from_user_record(user_record);
    }

    let user_record = nix::unistd::User::from_name(user)
        .into_diagnostic()?
        .ok_or_else(|| miette::miette!("run user '{}' does not exist", user))?;
    run_identity_from_user_record(user_record)
}

#[cfg(unix)]
fn run_identity_from_user_record(user: nix::unistd::User) -> Result<RunIdentity> {
    let username = CString::new(user.name)
        .map_err(|e| miette::miette!("run user name contains an interior nul byte: {}", e))?;
    Ok(RunIdentity::Switch {
        uid: user.uid,
        gid: user.gid,
        username: Some(username),
        home: Some(user.dir),
    })
}

#[cfg(unix)]
fn resolve_sudo_identity(sudo_uid: Option<&str>, sudo_gid: Option<&str>) -> Option<RunIdentity> {
    let uid = sudo_uid?.parse::<u32>().ok()?;
    let gid = sudo_gid?.parse::<u32>().ok()?;
    let user = nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))
        .ok()
        .flatten();
    let (username, home) = match user {
        Some(user) => (CString::new(user.name).ok(), Some(user.dir)),
        None => (None, None),
    };
    Some(RunIdentity::Switch {
        uid: nix::unistd::Uid::from_raw(uid),
        gid: nix::unistd::Gid::from_raw(gid),
        username,
        home,
    })
}

#[cfg(unix)]
fn ensure_can_use_identity(
    configured_user: &str,
    identity: &RunIdentity,
    current_uid: nix::unistd::Uid,
    current_gid: nix::unistd::Gid,
) -> Result<()> {
    let RunIdentity::Switch { uid, gid, .. } = identity else {
        return Ok(());
    };
    if *uid == current_uid && *gid == current_gid {
        return Ok(());
    }
    if current_uid.is_root() {
        return Ok(());
    }
    Err(miette::miette!(
        "daemon is configured to run as '{}', but the supervisor is running as uid={} gid={}. Restart the supervisor with sudo to switch to uid={} gid={}, or choose a user matching the supervisor.",
        configured_user,
        current_uid.as_raw(),
        current_gid.as_raw(),
        uid.as_raw(),
        gid.as_raw()
    ))
}

/// Point HOME, USER and LOGNAME at the user a daemon switches to.
///
/// The supervisor's environment describes the supervisor's own user (usually
/// root), so without this a daemon run as another user would read and write
/// root's home. A value the passwd entry cannot supply is removed rather than
/// left describing root.
#[cfg(unix)]
fn apply_identity_env(command: &mut tokio::process::Command, identity: &RunIdentity) {
    let RunIdentity::Switch { username, home, .. } = identity else {
        return;
    };
    match home.as_ref().filter(|home| !home.as_os_str().is_empty()) {
        Some(home) => command.env("HOME", home),
        None => command.env_remove("HOME"),
    };
    match username.as_ref().and_then(|name| name.to_str().ok()) {
        Some(name) => command.env("USER", name).env("LOGNAME", name),
        None => command.env_remove("USER").env_remove("LOGNAME"),
    };
}

#[cfg(unix)]
fn apply_run_identity(identity: &RunIdentity) -> std::io::Result<()> {
    let RunIdentity::Switch {
        uid, gid, username, ..
    } = identity
    else {
        return Ok(());
    };
    if let Some(username) = username {
        initgroups_for_user(username, *gid)?;
    } else {
        setgroups_to_primary(*gid)?;
    }
    nix::unistd::setgid(*gid).map_err(nix_to_io_error)?;
    nix::unistd::setuid(*uid).map_err(nix_to_io_error)?;
    Ok(())
}

#[cfg(unix)]
impl RunIdentity {
    fn matches(&self, uid: nix::unistd::Uid, gid: nix::unistd::Gid) -> bool {
        matches!(self, RunIdentity::Switch { uid: u, gid: g, .. } if *u == uid && *g == gid)
    }
}

#[cfg(unix)]
fn setgroups_to_primary(gid: nix::unistd::Gid) -> std::io::Result<()> {
    let groups = [gid.as_raw() as libc::gid_t];
    #[cfg(any(target_os = "linux", target_os = "android"))]
    let group_count = groups.len();
    #[cfg(not(any(target_os = "linux", target_os = "android")))]
    let group_count = groups.len() as libc::c_int;
    let rc = unsafe { libc::setgroups(group_count, groups.as_ptr()) };
    if rc == -1 {
        Err(std::io::Error::last_os_error())
    } else {
        Ok(())
    }
}

#[cfg(unix)]
fn initgroups_for_user(username: &CString, gid: nix::unistd::Gid) -> std::io::Result<()> {
    let gid = gid.as_raw();
    #[cfg(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "tvos",
        target_os = "watchos"
    ))]
    let base_gid = i32::try_from(gid)
        .map_err(|_| std::io::Error::other(format!("gid {gid} is out of range")))?;

    #[cfg(not(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "tvos",
        target_os = "watchos"
    )))]
    let base_gid = gid as libc::gid_t;

    // SAFETY: `username` is a valid nul-terminated C string and `base_gid`
    // is derived from a resolved system account or sudo-provided gid.
    let rc = unsafe { libc::initgroups(username.as_ptr(), base_gid) };
    if rc == -1 {
        Err(std::io::Error::last_os_error())
    } else {
        Ok(())
    }
}

#[cfg(unix)]
fn nix_to_io_error(err: nix::errno::Errno) -> std::io::Error {
    std::io::Error::from_raw_os_error(err as i32)
}

/// Check if multiple ports are available and optionally auto-bump to find available ports.
///
/// All ports are bumped by the same offset to maintain relative port spacing.
/// Returns the resolved ports (either the original or bumped ones).
/// Returns an error if any port is in use and auto_bump is disabled,
/// or if no available ports can be found after max attempts.
/// Ports resolved for daemons that are still starting, by the daemon holding them.
static PORT_CLAIMS: Lazy<std::sync::Mutex<HashMap<u16, (DaemonId, u64)>>> =
    Lazy::new(|| std::sync::Mutex::new(HashMap::new()));

/// Serializes port resolution so two starts cannot both see a port unclaimed.
static PORT_RESOLUTION: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

/// Source of per-claim generations, so a claim only releases its own entries.
static PORT_CLAIM_GENERATION: atomic::AtomicU64 = atomic::AtomicU64::new(0);

/// Reserves resolved ports for a daemon attempt; releases them on drop.
#[derive(Debug)]
struct PortClaim {
    generation: u64,
    ports: Vec<u16>,
}

impl Drop for PortClaim {
    fn drop(&mut self) {
        let mut claims = PORT_CLAIMS.lock().unwrap_or_else(|e| e.into_inner());
        for port in &self.ports {
            // A restart of the same daemon may have replaced the entry.
            if claims.get(port).is_some_and(|(_, g)| *g == self.generation) {
                claims.remove(port);
            }
        }
    }
}

/// Resolves ports like `check_ports_available` and claims them for `id`.
///
/// A daemon binds its ports only after it has started up, so the bind check
/// alone lets concurrent starts resolve the same free port. Claims cover that
/// window: another start sees the port as taken (bumping past it or failing)
/// until the claim is dropped.
async fn claim_ports(
    id: &DaemonId,
    expected_ports: &[u16],
    auto_bump: bool,
    max_attempts: u32,
) -> Result<(Vec<u16>, PortClaim)> {
    let _resolution = PORT_RESOLUTION.lock().await;
    let claimed: HashMap<u16, DaemonId> = PORT_CLAIMS
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .iter()
        .filter(|(_, (owner, _))| owner != id)
        .map(|(port, (owner, _))| (*port, owner.clone()))
        .collect();
    let resolved = check_ports_available(expected_ports, auto_bump, max_attempts, &claimed).await?;
    let ports: Vec<u16> = resolved.iter().copied().filter(|&p| p != 0).collect();
    let generation = PORT_CLAIM_GENERATION.fetch_add(1, atomic::Ordering::Relaxed);
    {
        let mut claims = PORT_CLAIMS.lock().unwrap_or_else(|e| e.into_inner());
        for port in &ports {
            claims.insert(*port, (id.clone(), generation));
        }
    }
    Ok((resolved, PortClaim { generation, ports }))
}

async fn check_ports_available(
    expected_ports: &[u16],
    auto_bump: bool,
    max_attempts: u32,
    claimed: &HashMap<u16, DaemonId>,
) -> Result<Vec<u16>> {
    if expected_ports.is_empty() {
        return Ok(Vec::new());
    }

    for bump_offset in 0..=max_attempts {
        // Use wrapping_add to handle overflow correctly - ports wrap around at 65535
        let candidate_ports: Vec<u16> = expected_ports
            .iter()
            .map(|&p| p.wrapping_add(bump_offset as u16))
            .collect();

        // Check if all ports in this set are available
        let mut all_available = true;
        let mut conflicting_port = None;
        let mut conflicting_claim = None;

        for &port in &candidate_ports {
            // Port 0 is a special case - it requests an ephemeral port from the OS.
            // Skip the availability check for port 0 since binding to it always succeeds.
            if port == 0 {
                continue;
            }

            // Use spawn_blocking to avoid blocking the async runtime during TCP bind checks.
            //
            // We check multiple addresses to avoid false-negatives caused by SO_REUSEADDR.
            // On macOS/BSD, the probe sets SO_REUSEADDR (see `bind_probe`), which
            // allows binding 0.0.0.0:port even when 127.0.0.1:port is already in use
            // (because 0.0.0.0 is technically a different address).  Most daemons bind
            // to localhost, so checking 127.0.0.1 is essential to detect real conflicts.
            // We also check [::1] to cover IPv6 loopback listeners.
            //
            // NOTE: This check has a time-of-check-to-time-of-use (TOCTOU) race condition.
            // Another process could grab the port between our check and the daemon actually
            // binding. This is inherent to the approach and acceptable for our use case
            // since we're primarily detecting conflicts with already-running daemons.
            if let Some(owner) = claimed.get(&port) {
                all_available = false;
                conflicting_claim = Some((port, owner.clone()));
                break;
            }
            if let Some(address) = port_bind_conflict(port).await {
                all_available = false;
                conflicting_port = Some((port, address));
                break;
            }
        }

        if all_available {
            // Check for overflow (port wrapped around to 0 due to wrapping_add)
            // If any candidate port is 0 but the original expected port wasn't 0,
            // it means we've wrapped around and should stop
            if candidate_ports.contains(&0) && !expected_ports.contains(&0) {
                return Err(PortError::NoAvailablePort {
                    start_port: expected_ports[0],
                    attempts: bump_offset + 1,
                }
                .into());
            }
            if bump_offset > 0 {
                info!("ports {expected_ports:?} bumped by {bump_offset} to {candidate_ports:?}");
            }
            return Ok(candidate_ports);
        }

        // Port is in use
        if bump_offset == 0
            && !auto_bump
            && let Some((port, daemon)) = conflicting_claim
        {
            return Err(PortError::Claimed {
                port,
                daemon: daemon.to_string(),
            }
            .into());
        }
        if bump_offset == 0
            && !auto_bump
            && let Some((port, address)) = conflicting_port
        {
            let (pid, process) = identify_port_owner(port, address).await;
            return Err(PortError::InUse {
                port,
                address: Some(shown_address(address)),
                process,
                pid,
            }
            .into());
        }
    }

    // No available ports found after max attempts
    Err(PortError::NoAvailablePort {
        start_port: expected_ports[0],
        attempts: max_attempts + 1,
    }
    .into())
}

/// Check whether a port is currently in use by attempting to bind on multiple addresses.
///
/// Returns the address of the first bind that gets `AddrInUse`, meaning another socket
/// holds the port there. Other errors (e.g. `AddrNotAvailable` on an address family
/// the OS doesn't support) are ignored so they don't produce false positives.
async fn port_bind_conflict(port: u16) -> Option<std::net::IpAddr> {
    use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
    tokio::task::spawn_blocking(move || {
        for addr in [
            IpAddr::V4(Ipv4Addr::UNSPECIFIED),
            IpAddr::V4(Ipv4Addr::LOCALHOST),
            IpAddr::V6(Ipv6Addr::LOCALHOST),
        ] {
            match bind_probe((addr, port).into()) {
                Ok(socket) => drop(socket),
                Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => return Some(addr),
                Err(_) => continue,
            }
        }
        None
    })
    .await
    .unwrap_or(None)
}

/// Bind a TCP socket to `addr` for [`port_bind_conflict`].
///
/// The socket never listens. A child forked by another thread while the socket
/// is open keeps a copy until the child execs, so the copy can still be bound
/// when the next address is probed. On Linux, a listening copy would make that
/// bind fail even with `SO_REUSEADDR`, and the port would look taken. A copy
/// that doesn't listen doesn't, because Linux lets sockets that set
/// `SO_REUSEADDR` and don't listen share a port. A copy that doesn't listen
/// can't accept connections either, so a `ready_port` check can't pass on it.
/// A socket listening on the same address and port still makes the bind fail.
#[cfg(unix)]
fn bind_probe(addr: std::net::SocketAddr) -> std::io::Result<tokio::net::TcpSocket> {
    let socket = if addr.is_ipv4() {
        tokio::net::TcpSocket::new_v4()?
    } else {
        tokio::net::TcpSocket::new_v6()?
    };
    socket.set_reuseaddr(true)?;
    socket.bind(addr)?;
    Ok(socket)
}

/// Bind a TCP listener to `addr` for [`port_bind_conflict`].
///
/// Unlike on Unix, the probe listens: Windows may report that a wildcard bind
/// conflicts only when the socket listens. Children don't inherit std's
/// sockets there, so no child can hold a copy of it.
#[cfg(not(unix))]
fn bind_probe(addr: std::net::SocketAddr) -> std::io::Result<std::net::TcpListener> {
    std::net::TcpListener::bind(addr)
}

/// An address as a message shows it: IPv6 in brackets, as in `[::1]`.
fn shown_address(addr: std::net::IpAddr) -> String {
    match addr {
        std::net::IpAddr::V4(v4) => v4.to_string(),
        std::net::IpAddr::V6(v6) => format!("[{v6}]"),
    }
}

/// How well a socket listening on `listening` accounts for a bind to
/// `conflict` failing on the same port, best first, or `None` when it cannot:
/// the same address; a wildcard and a specific address of one family, which
/// conflict with each other; then `[::]`, which also takes IPv4 unless it is
/// IPv6-only. An IPv4-mapped IPv6 address, as a dual-stack socket shows an
/// IPv4 connection, counts as the IPv4 address.
fn listener_match(listening: std::net::IpAddr, conflict: std::net::IpAddr) -> Option<u8> {
    use std::net::IpAddr;
    let listening = listening.to_canonical();
    if listening == conflict {
        return Some(0);
    }
    match (listening, conflict) {
        (IpAddr::V4(_), IpAddr::V4(_)) | (IpAddr::V6(_), IpAddr::V6(_))
            if listening.is_unspecified() || conflict.is_unspecified() =>
        {
            Some(1)
        }
        (IpAddr::V6(v6), IpAddr::V4(_)) if v6.is_unspecified() => Some(2),
        _ => None,
    }
}

/// A TCP socket on this machine, as the port owner lookup sees it.
struct TcpSocket {
    addr: std::net::SocketAddr,
    listening: bool,
    pid: u32,
    process: String,
}

/// The process whose TCP socket on `port` best accounts for the bind to
/// `conflict` failing (see [`listener_match`]), among `sockets`. A listening
/// socket comes first; one that is not listening but is bound to the port,
/// such as a connection a listener accepted, can hold it too. `None` when
/// none can.
///
/// A `[::]` socket holds an IPv4 port only if it is not IPv6-only, which the
/// socket list does not tell, so it is named for an IPv4 conflict only when no
/// IPv4 socket, listening or not, could account for it.
fn pick_port_owner(
    sockets: impl IntoIterator<Item = TcpSocket>,
    port: u16,
    conflict: std::net::IpAddr,
) -> Option<(u32, String)> {
    sockets
        .into_iter()
        .filter(|s| s.addr.port() == port)
        .filter_map(|s| {
            let matched = listener_match(s.addr.ip(), conflict)?;
            let rank = (matched == 2, !s.listening, matched);
            Some((rank, s.pid, s.process))
        })
        .min_by_key(|(rank, _, _)| *rank)
        .map(|(_, pid, process)| (pid, process))
}

/// Best-effort lookup of the process occupying a port via `listeners::get_all()`.
///
/// Only a TCP socket on an address that conflicts with `conflict`, the address
/// whose bind found the port taken, is taken as the holder: another process
/// may listen on the same port on an address that does not. A listening
/// socket is preferred (see [`pick_port_owner`]).
///
/// Returns `(pid, process_name)`.  Falls back to `(0, "unknown")` when no such
/// socket is found or the system call fails (permission error, unsupported OS, etc.).
async fn identify_port_owner(port: u16, conflict: std::net::IpAddr) -> (u32, String) {
    tokio::task::spawn_blocking(move || {
        listeners::get_all()
            .ok()
            .and_then(|list| {
                // UDP sockets share port numbers with TCP but never block a
                // TCP bind.
                let tcp = list
                    .into_iter()
                    .filter(|l| l.protocol == listeners::Protocol::TCP)
                    .map(|l| TcpSocket {
                        addr: l.socket,
                        listening: l.state == listeners::SocketState::Listen,
                        pid: l.process.pid,
                        process: l.process.name,
                    });
                pick_port_owner(tcp, port, conflict)
            })
            .unwrap_or((0, "unknown".to_string()))
    })
    .await
    .unwrap_or((0, "unknown".to_string()))
}

/// Detect whether a port is in use, and if so, where and by which process.
///
/// Combines `port_bind_conflict` (reliable bind probe) with `identify_port_owner`
/// (best-effort process lookup).  Returns `None` when the port is free.
async fn detect_port_conflict(port: u16) -> Option<(String, u32, String)> {
    let address = port_bind_conflict(port).await?;
    let (pid, process) = identify_port_owner(port, address).await;
    Some((shown_address(address), pid, process))
}

#[derive(Debug, PartialEq, Eq)]
enum ActivePortSelection {
    NoCandidates,
    Selected(u16),
    Ambiguous(Vec<u16>),
}

fn discovery_preferred_port(daemon: &crate::daemon::Daemon) -> Option<u16> {
    daemon
        .resolved_port
        .first()
        .copied()
        .or_else(|| {
            daemon
                .port
                .as_ref()
                .and_then(|port| port.expect.first().copied())
        })
        .filter(|&port| port > 0)
}

fn select_active_port(
    listeners: impl IntoIterator<Item = listeners::Listener>,
    descendant_pids: &std::collections::HashSet<u32>,
    preferred_port: Option<u16>,
) -> ActivePortSelection {
    let process_ports: std::collections::BTreeSet<u16> = listeners
        .into_iter()
        .filter(|listener| {
            listener.protocol == listeners::Protocol::TCP
                && listener.state == listeners::SocketState::Listen
                && descendant_pids.contains(&listener.process.pid)
        })
        .map(|listener| listener.socket.port())
        .filter(|&port| port > 0)
        .collect();

    if let Some(port) = preferred_port
        && process_ports.contains(&port)
    {
        return ActivePortSelection::Selected(port);
    }

    match process_ports.len() {
        0 => ActivePortSelection::NoCandidates,
        1 => ActivePortSelection::Selected(*process_ports.first().unwrap()),
        _ => ActivePortSelection::Ambiguous(process_ports.into_iter().collect()),
    }
}

/// Spawn a background task that detects the daemon process's active listening port
/// and stores it in the state file as `active_port`.
///
/// This is called once when the daemon becomes ready. The port is cleared when the daemon stops.
///
/// Port selection strategy:
/// 1. Consider only TCP listening sockets owned by the daemon or its descendants.
/// 2. Prefer the first resolved port, falling back to the first expected port for
///    legacy state without resolved ports.
/// 3. Select a sole distinct candidate; leave `active_port` unset when ambiguous.
fn detect_and_store_active_port(id: DaemonId, pid: u32) {
    tokio::spawn(async move {
        // Retry with exponential backoff so that slow-starting daemons (JVM,
        // Node.js, Python, etc.) that take more than 500 ms to bind their port
        // are still detected.  Total wait budget: 500+1000+2000+4000 = 7.5 s.
        for delay_ms in [500u64, 1000, 2000, 4000] {
            tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;

            // Read daemon state atomically: check if still alive and get the preferred port
            // in a single lock acquisition to avoid TOCTOU and unnecessary lock overhead.
            let preferred_port: Option<u16> = {
                let state_file = SUPERVISOR.state_file.lock().await;
                match state_file.daemons.get(&id) {
                    Some(d) if d.pid.is_none() => {
                        debug!("daemon {id}: aborting active_port detection — process exited");
                        return;
                    }
                    Some(d) => discovery_preferred_port(d),
                    None => None,
                }
            };

            let selection = tokio::task::spawn_blocking(move || {
                let listeners = listeners::get_all().ok()?;

                // Refresh process tree so all_children sees current descendants.
                PROCS.refresh_processes();

                let descendant_pids: std::collections::HashSet<u32> = PROCS
                    .all_children(pid)
                    .into_iter()
                    .chain(std::iter::once(pid))
                    .collect();

                Some(select_active_port(
                    listeners,
                    &descendant_pids,
                    preferred_port,
                ))
            })
            .await
            .ok()
            .flatten()
            .unwrap_or(ActivePortSelection::NoCandidates);

            let port = match selection {
                ActivePortSelection::Selected(port) => port,
                ActivePortSelection::Ambiguous(ports) => {
                    debug!(
                        "daemon {id}: ambiguous active_port candidates {ports:?} for pid {pid} \
                         and its descendants; leaving active_port unset (will retry)"
                    );
                    continue;
                }
                ActivePortSelection::NoCandidates => {
                    debug!(
                        "daemon {id}: no active port detected for pid {pid} or its descendants \
                         (will retry)"
                    );
                    continue;
                }
            };

            debug!("daemon {id} active_port detected: {port}");
            let mut state_file = SUPERVISOR.state_file.lock().await;
            if let Some(d) = state_file.daemons.get(&id) {
                // Guard against PID reuse: if the original process exited and the OS
                // assigned the same PID to an unrelated process that happens to bind
                // a port, we must not route proxy traffic to that unrelated service.
                if d.pid == Some(pid) {
                    state_file.set_active_port(&id, port);
                } else {
                    debug!(
                        "daemon {id}: skipping active_port write — PID mismatch \
                         (expected {pid}, current {:?})",
                        d.pid
                    );
                }
            }
            return;
        }

        debug!(
            "daemon {id}: active port detection exhausted all retries for pid {pid} and its descendants"
        );
    });
}

#[cfg(test)]
mod port_conflict_tests {
    use super::{
        TcpSocket, check_ports_available, claim_ports, listener_match, pick_port_owner,
        port_bind_conflict, shown_address,
    };
    use crate::error::PortError;
    use std::net::{IpAddr, SocketAddr};

    /// Held by a test that forks continuously, and by any test whose sockets
    /// a forked child must not keep after the test drops them.
    static FORKS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

    #[tokio::test]
    async fn a_taken_port_is_reported_with_its_address_and_holder() {
        let _forks = FORKS.lock().await;
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();

        // Which bind finds it taken depends on the OS: Linux refuses the
        // wildcard bind as well, macOS only the 127.0.0.1 one.
        let address = shown_address(port_bind_conflict(port).await.unwrap());
        assert!(
            ["0.0.0.0", "127.0.0.1"].contains(&address.as_str()),
            "{address}"
        );

        let err = check_ports_available(&[port], false, 0, &Default::default())
            .await
            .unwrap_err();
        match err.downcast_ref::<PortError>() {
            Some(PortError::InUse {
                port: p,
                address: Some(a),
                pid,
                ..
            }) => {
                assert_eq!(*p, port);
                assert_eq!(*a, address);
                // The holder is this test process, which lists its own sockets.
                assert_eq!(*pid, std::process::id());
            }
            other => panic!("unexpected error: {other:?}"),
        }
        drop(listener);
        assert_eq!(port_bind_conflict(port).await, None);
    }

    #[tokio::test]
    async fn a_starting_daemons_ports_are_not_resolved_for_another() {
        use crate::daemon_id::DaemonId;
        let _forks = FORKS.lock().await;
        let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = probe.local_addr().unwrap().port();
        drop(probe);
        let one = DaemonId::new("claim-one", "web");
        let two = DaemonId::new("claim-two", "web");

        let (resolved, claim) = claim_ports(&one, &[port], false, 0).await.unwrap();
        assert_eq!(resolved, vec![port]);

        // Nothing is bound yet, but the port is claimed: without bump the
        // second start fails, with bump it moves past the claimed port.
        let err = claim_ports(&two, &[port], false, 0).await.unwrap_err();
        assert!(
            matches!(err.downcast_ref::<PortError>(), Some(PortError::Claimed { port: p, .. }) if *p == port),
            "{err:?}"
        );
        let (bumped, bumped_claim) = claim_ports(&two, &[port], true, 10).await.unwrap();
        assert_ne!(bumped, vec![port]);
        drop(bumped_claim);

        // Once the first daemon is ready or gone, the port is free again.
        drop(claim);
        let (resolved, _claim) = claim_ports(&two, &[port], false, 0).await.unwrap();
        assert_eq!(resolved, vec![port]);
    }

    #[tokio::test]
    async fn an_old_attempts_claim_does_not_release_its_replacement() {
        use crate::daemon_id::DaemonId;
        let _forks = FORKS.lock().await;
        let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = probe.local_addr().unwrap().port();
        drop(probe);
        let one = DaemonId::new("claim-restart", "web");
        let other = DaemonId::new("claim-other", "web");

        let (_, old) = claim_ports(&one, &[port], false, 0).await.unwrap();
        let (_, new) = claim_ports(&one, &[port], false, 0).await.unwrap();
        drop(old);
        assert!(claim_ports(&other, &[port], false, 0).await.is_err());
        drop(new);
        assert!(claim_ports(&other, &[port], false, 0).await.is_ok());
    }

    #[cfg(unix)]
    #[test]
    fn a_copy_of_a_probe_socket_does_not_look_like_a_listener() {
        use super::bind_probe;
        // A child forked while the probe of 0.0.0.0 is open still holds it
        // when the probe of 127.0.0.1 binds.
        let copy = bind_probe(SocketAddr::from(([0, 0, 0, 0], 0))).unwrap();
        let port = copy.local_addr().unwrap().port();
        let addr = SocketAddr::from(([127, 0, 0, 1], port));
        bind_probe(addr).unwrap();
        // Nor can a ready_port check connect to it: Linux refuses the
        // connection, and macOS lets it time out.
        let timeout = std::time::Duration::from_millis(200);
        assert!(std::net::TcpStream::connect_timeout(&addr, timeout).is_err());
        drop(copy);
    }

    /// While another thread forks, each child holds copies of the probe sockets
    /// open at that moment until it execs. The copies must not make a free
    /// port look taken. Where the forks land is up to the scheduler, so the
    /// test repeats the check many times.
    ///
    /// Linux only: macOS refuses a bind to an address and port while a copy of
    /// an earlier socket bound there is open, even when neither listens. This
    /// test's back-to-back checks of one port would fail on such copies.
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn a_free_port_stays_free_while_another_thread_forks() {
        use crate::inherited_fds::CloseInheritedFds;
        use std::sync::Arc;
        use std::sync::atomic::{AtomicBool, Ordering};

        let _forks = FORKS.lock().await;
        let port = std::net::TcpListener::bind("127.0.0.1:0")
            .unwrap()
            .local_addr()
            .unwrap()
            .port();
        let stop = Arc::new(AtomicBool::new(false));
        let forker = std::thread::spawn({
            let stop = stop.clone();
            move || {
                while !stop.load(Ordering::Relaxed) {
                    // close_inherited_fds makes std fork and exec, as the
                    // supervisor's spawns do, instead of using posix_spawn.
                    std::process::Command::new("true")
                        .close_inherited_fds()
                        .status()
                        .unwrap();
                }
            }
        });
        let mut conflicts = Vec::new();
        for _ in 0..500 {
            conflicts.extend(port_bind_conflict(port).await);
        }
        stop.store(true, Ordering::Relaxed);
        forker.join().unwrap();
        assert!(
            conflicts.is_empty(),
            "free port looked taken on {conflicts:?}"
        );
    }

    fn ip(s: &str) -> IpAddr {
        s.parse().unwrap()
    }

    fn socket(addr: &str, listening: bool, pid: u32) -> TcpSocket {
        TcpSocket {
            addr: addr.parse::<SocketAddr>().unwrap(),
            listening,
            pid,
            process: format!("p{pid}"),
        }
    }

    #[test]
    fn only_a_listener_whose_address_conflicts_is_named() {
        let all = || {
            [
                socket("192.0.2.1:3000", true, 1),
                socket("127.0.0.1:3000", true, 2),
                socket("[::1]:3000", true, 3),
                socket("127.0.0.1:4000", true, 4),
            ]
        };
        // The exact address wins over a wildcard or another address.
        assert_eq!(
            pick_port_owner(all(), 3000, ip("127.0.0.1")),
            Some((2, "p2".into()))
        );
        assert_eq!(
            pick_port_owner(all(), 3000, ip("::1")),
            Some((3, "p3".into()))
        );
        // A wildcard bind conflicts with any listener of its family.
        let v4 = pick_port_owner(all(), 3000, ip("0.0.0.0")).unwrap().0;
        assert!([1, 2].contains(&v4));
        // No socket on a conflicting address: nobody is named.
        assert_eq!(
            pick_port_owner([socket("[::1]:3000", true, 3)], 3000, ip("127.0.0.1")),
            None
        );
        assert_eq!(pick_port_owner(all(), 5000, ip("127.0.0.1")), None);

        // A listener comes before a socket that is not listening, which is
        // named when it is all there is.
        let both = [
            socket("127.0.0.1:3000", false, 5),
            socket("0.0.0.0:3000", true, 6),
        ];
        assert_eq!(
            pick_port_owner(both, 3000, ip("127.0.0.1")),
            Some((6, "p6".into()))
        );
        assert_eq!(
            pick_port_owner([socket("127.0.0.1:3000", false, 5)], 3000, ip("127.0.0.1")),
            Some((5, "p5".into()))
        );

        // `[::]` may be IPv6-only, so an IPv4 socket, even one that is not
        // listening, is named before it for an IPv4 conflict.
        let v6_wildcard = || {
            [
                socket("[::]:3000", true, 7),
                socket("127.0.0.1:3000", false, 8),
            ]
        };
        assert_eq!(
            pick_port_owner(v6_wildcard(), 3000, ip("127.0.0.1")),
            Some((8, "p8".into()))
        );
        assert_eq!(
            pick_port_owner(v6_wildcard(), 3000, ip("0.0.0.0")),
            Some((8, "p8".into()))
        );
        // With no IPv4 socket, it is the only one that can hold the port.
        assert_eq!(
            pick_port_owner([socket("[::]:3000", true, 7)], 3000, ip("127.0.0.1")),
            Some((7, "p7".into()))
        );
        // A dual-stack socket shows an IPv4 connection as IPv4-mapped.
        assert_eq!(
            pick_port_owner(
                [socket("[::ffff:127.0.0.1]:3000", false, 9)],
                3000,
                ip("127.0.0.1")
            ),
            Some((9, "p9".into()))
        );

        assert_eq!(listener_match(ip("0.0.0.0"), ip("127.0.0.1")), Some(1));
        assert_eq!(listener_match(ip("::"), ip("127.0.0.1")), Some(2));
        assert_eq!(listener_match(ip("::1"), ip("127.0.0.1")), None);
        assert_eq!(listener_match(ip("192.0.2.1"), ip("127.0.0.1")), None);
        assert_eq!(shown_address(ip("::1")), "[::1]");
    }
}

#[cfg(test)]
mod active_port_tests {
    use super::*;
    use crate::config_types::PortConfig;
    use listeners::{Listener, Process, Protocol, SocketState};
    use std::net::{IpAddr, Ipv4Addr, SocketAddr};

    fn listener(pid: u32, port: u16, protocol: Protocol, state: SocketState) -> Listener {
        Listener {
            process: Process {
                pid,
                name: "test".to_string(),
                path: "/test".to_string(),
            },
            socket: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port),
            protocol,
            state,
        }
    }

    #[test]
    fn active_port_candidates_exclude_outbound_tcp_and_udp_sockets() {
        let daemon_pid = 100;
        let child_pid = 101;
        let descendant_pids = [daemon_pid, child_pid].into_iter().collect();
        let listeners = vec![
            listener(child_pid, 3004, Protocol::TCP, SocketState::Listen),
            listener(daemon_pid, 47082, Protocol::TCP, SocketState::Established),
            listener(daemon_pid, 5353, Protocol::UDP, SocketState::Unknown),
            listener(999, 9000, Protocol::TCP, SocketState::Listen),
        ];

        assert_eq!(
            select_active_port(listeners, &descendant_pids, None),
            ActivePortSelection::Selected(3004)
        );
    }

    #[test]
    fn bumped_cmd_readiness_prefers_resolved_primary_port() {
        let daemon = crate::daemon::Daemon {
            resolved_port: vec![3004],
            port: Some(PortConfig {
                expect: vec![3000],
                ..PortConfig::default()
            }),
            ..crate::daemon::Daemon::default()
        };
        let descendant_pids = [100].into_iter().collect();
        let listeners = vec![
            listener(100, 9000, Protocol::TCP, SocketState::Listen),
            listener(100, 3004, Protocol::TCP, SocketState::Listen),
        ];

        assert_eq!(discovery_preferred_port(&daemon), Some(3004));
        assert_eq!(
            select_active_port(
                listeners,
                &descendant_pids,
                discovery_preferred_port(&daemon),
            ),
            ActivePortSelection::Selected(3004)
        );
    }

    #[test]
    fn legacy_state_uses_expected_primary_port_for_discovery() {
        let daemon = crate::daemon::Daemon {
            port: Some(PortConfig {
                expect: vec![3000],
                ..PortConfig::default()
            }),
            ..crate::daemon::Daemon::default()
        };

        assert_eq!(discovery_preferred_port(&daemon), Some(3000));
    }

    #[test]
    fn ambiguous_candidates_leave_active_port_unset() {
        let descendant_pids = [100].into_iter().collect();
        let listeners = vec![
            listener(100, 9000, Protocol::TCP, SocketState::Listen),
            listener(100, 3000, Protocol::TCP, SocketState::Listen),
        ];

        assert_eq!(
            select_active_port(listeners, &descendant_pids, None),
            ActivePortSelection::Ambiguous(vec![3000, 9000])
        );
    }

    #[test]
    fn bumped_ready_port_sets_only_the_resolved_primary_without_scanning() {
        assert_eq!(active_port_from_ready_port(3004, &[3004]), Some(3004));
        assert_eq!(active_port_from_ready_port(4003, &[3003, 4003]), None);
    }

    #[test]
    fn delay_readiness_requires_delay_only_and_a_running_process() {
        assert!(delay_readiness_succeeded(false, false, false, true));
        assert!(!delay_readiness_succeeded(false, true, false, true));
        assert!(!delay_readiness_succeeded(false, false, true, false));
        assert!(!delay_readiness_succeeded(false, false, false, false));
        assert!(!delay_readiness_succeeded(true, false, false, true));
    }
}

/// Check whether a daemon (by its qualified ID) is the target of any registered
/// slug in the global config.  This is used to decide whether to run the
/// `detect_and_store_active_port` polling task — only slug-targeted daemons need
/// it, avoiding wasted `listeners::get_all()` calls for port-less daemons.
///
/// Delegates to `proxy::server::is_slug_target()` which uses the same in-memory
/// slug cache as the proxy hot path, so this check is cheap.
fn is_daemon_slug_target(id: &DaemonId) -> bool {
    // read_global_slugs is called once per daemon start — acceptable cost.
    // We intentionally avoid making this async to keep has_port_config evaluation
    // simple and synchronous in run_once().
    let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
    slugs.iter().any(|(slug, entry)| {
        let daemon_name = entry.daemon.as_deref().unwrap_or(slug);
        id.name() == daemon_name
    })
}

#[cfg(test)]
mod oneshot_tests {
    use super::*;

    #[test]
    fn oneshot_clean_exit_is_completed() {
        let (status, success) = terminal_exit_state("exit", true, 0, true);
        assert!(matches!(status, DaemonStatus::Completed));
        assert!(success);
    }

    #[test]
    fn service_clean_exit_is_still_stopped() {
        let (status, success) = terminal_exit_state("exit", false, 0, true);
        assert!(matches!(status, DaemonStatus::Stopped));
        assert!(success);
    }

    #[test]
    fn oneshot_failure_is_errored_so_retry_applies() {
        // check_retry() only picks up errored daemons, so a non-zero exit must
        // not be recorded as completed.
        let (status, success) = terminal_exit_state("fail", true, 3, false);
        assert!(matches!(status, DaemonStatus::Errored(3)));
        assert!(!success);
    }

    #[test]
    fn a_stop_cancels_the_retry_sequence_it_finds() {
        let id = DaemonId::new("retry-cancel-test", "task");
        let claim = SUPERVISOR.mark_retrying(&id);
        assert!(!claim.is_cancelled());
        assert!(SUPERVISOR.is_retrying(&id));
        SUPERVISOR.cancel_retrying(&id);
        assert!(claim.is_cancelled());
        drop(claim);
        assert!(!SUPERVISOR.is_retrying(&id));
    }

    #[test]
    fn a_stop_cancels_every_sequence_for_the_daemon() {
        // Two starts can be working through the same daemon's retries: the
        // first releases the daemon's lock while it sleeps out a backoff. A
        // stop has to end both, not just whichever claimed it last.
        let id = DaemonId::new("retry-cancel-test", "concurrent");
        let first = SUPERVISOR.mark_retrying(&id);
        let second = SUPERVISOR.mark_retrying(&id);
        SUPERVISOR.cancel_retrying(&id);
        assert!(first.is_cancelled());
        assert!(second.is_cancelled());
        drop(second);
        // The first is still going, so the retry checker must still stand off.
        assert!(SUPERVISOR.is_retrying(&id));
        drop(first);
        assert!(!SUPERVISOR.is_retrying(&id));
    }

    #[test]
    fn a_stop_invalidates_an_attempt_decided_on_before_it() {
        // The retry checker reads the epoch when it decides on an attempt and
        // `run_retry` compares it under the daemon's lock, so an approval from
        // before a stop cannot slip past that stop.
        let id = DaemonId::new("stop-epoch-test", "task");
        let approved_at = SUPERVISOR.stop_epoch(&id);
        assert_eq!(SUPERVISOR.stop_epoch(&id), approved_at);
        SUPERVISOR.bump_stop_epoch(&id);
        assert_ne!(SUPERVISOR.stop_epoch(&id), approved_at);
        // An attempt decided on after the stop is still fine to start.
        let approved_after = SUPERVISOR.stop_epoch(&id);
        assert_eq!(SUPERVISOR.stop_epoch(&id), approved_after);
    }

    #[test]
    fn stop_epochs_are_tracked_per_daemon() {
        let stopped = DaemonId::new("stop-epoch-test", "stopped");
        let untouched = DaemonId::new("stop-epoch-test", "untouched");
        let approved_at = SUPERVISOR.stop_epoch(&untouched);
        SUPERVISOR.bump_stop_epoch(&stopped);
        assert_eq!(SUPERVISOR.stop_epoch(&untouched), approved_at);
    }

    #[test]
    fn a_stop_leaves_a_completed_task_alone() {
        // It had already done its work, so the stop had nothing to interrupt.
        assert!(stop_keeps_finalized_status(&DaemonStatus::Completed));
    }

    #[test]
    fn a_stop_replaces_a_failure_so_retries_do_not_resume() {
        // check_retry() picks up errored daemons, so a stop has to overwrite
        // one or it will start the task again.
        assert!(!stop_keeps_finalized_status(&DaemonStatus::Errored(1)));
        assert!(!stop_keeps_finalized_status(&DaemonStatus::Running));
        assert!(!stop_keeps_finalized_status(&DaemonStatus::Stopped));
    }

    #[test]
    fn stopped_oneshot_did_not_complete() {
        let (status, _) = terminal_exit_state("stop", true, 0, true);
        assert!(matches!(status, DaemonStatus::Stopped));
    }
}

#[cfg(all(test, unix))]
mod tests {
    use super::*;

    #[test]
    fn test_resolve_run_identity_empty_without_sudo() {
        let identity = resolve_run_identity(None, 501, 20, None, None).unwrap();
        assert_eq!(identity, RunIdentity::Inherit);
    }

    #[test]
    fn test_resolve_run_identity_sudo_fallback() {
        let identity = resolve_run_identity(None, 0, 0, Some("501"), Some("20")).unwrap();
        let RunIdentity::Switch { uid, gid, .. } = identity else {
            panic!("expected identity switch");
        };
        assert_eq!(uid.as_raw(), 501);
        assert_eq!(gid.as_raw(), 20);
    }

    #[test]
    fn test_resolve_run_identity_ignores_stale_sudo_when_not_root() {
        let identity = resolve_run_identity(None, 501, 20, Some("0"), Some("0")).unwrap();
        assert_eq!(identity, RunIdentity::Inherit);
    }

    #[test]
    fn test_resolve_configured_user_root_name() {
        let identity = resolve_configured_user("root").unwrap();
        let RunIdentity::Switch { uid, username, .. } = identity else {
            panic!("expected identity switch");
        };
        assert_eq!(uid.as_raw(), 0);
        assert_eq!(
            username.as_deref().and_then(|s| s.to_str().ok()),
            Some("root")
        );
    }

    #[test]
    fn test_resolve_configured_user_root_uid() {
        let identity = resolve_configured_user("0").unwrap();
        let RunIdentity::Switch { uid, username, .. } = identity else {
            panic!("expected identity switch");
        };
        assert_eq!(uid.as_raw(), 0);
        assert_eq!(
            username.as_deref().and_then(|s| s.to_str().ok()),
            Some("root")
        );
    }

    #[test]
    fn test_resolve_configured_user_missing_user_fails() {
        let err = resolve_configured_user("pitchfork-user-that-should-not-exist")
            .unwrap_err()
            .to_string();
        assert!(err.contains("does not exist"));
    }

    #[test]
    fn test_resolve_run_identity_requires_root_for_user_switch() {
        let err = resolve_run_identity(Some("root"), 501, 20, None, None)
            .unwrap_err()
            .to_string();
        assert!(err.contains("Restart the supervisor with sudo"));
    }

    #[test]
    fn test_resolve_run_identity_same_user_is_noop() {
        let identity = resolve_run_identity(Some("root"), 0, 0, Some("501"), Some("20")).unwrap();
        assert_eq!(identity, RunIdentity::Inherit);
    }

    #[test]
    fn test_resolve_configured_user_records_home() {
        let identity = resolve_configured_user("root").unwrap();
        let RunIdentity::Switch { home, .. } = identity else {
            panic!("expected identity switch");
        };
        let expected = nix::unistd::User::from_name("root").unwrap().unwrap().dir;
        assert_eq!(home, Some(expected));
    }

    fn switch_to(name: Option<&str>, home: Option<&str>) -> RunIdentity {
        RunIdentity::Switch {
            uid: nix::unistd::Uid::from_raw(501),
            gid: nix::unistd::Gid::from_raw(20),
            username: name.map(|n| CString::new(n).unwrap()),
            home: home.map(std::path::PathBuf::from),
        }
    }

    /// The env a command will run with, as set on the command itself:
    /// `Some(None)` is an explicit removal, `None` means inherited.
    fn command_env(
        command: &tokio::process::Command,
        key: &str,
    ) -> Option<Option<std::ffi::OsString>> {
        command
            .as_std()
            .get_envs()
            .find(|(k, _)| *k == key)
            .map(|(_, v)| v.map(ToOwned::to_owned))
    }

    /// Mirrors the order run_once applies them in.
    fn daemon_command(
        identity: &RunIdentity,
        daemon_env: Option<&IndexMap<String, String>>,
    ) -> tokio::process::Command {
        let mut command = tokio::process::Command::new("true");
        apply_identity_env(&mut command, identity);
        apply_runtime_env(
            &mut command,
            &DaemonId::new("identity-env-test", "api"),
            0,
            daemon_env,
            &[],
        );
        command
    }

    #[test]
    fn test_identity_env_describes_the_switched_user() {
        let command = daemon_command(&switch_to(Some("alice"), Some("/home/alice")), None);
        assert_eq!(
            command_env(&command, "HOME"),
            Some(Some("/home/alice".into()))
        );
        assert_eq!(command_env(&command, "USER"), Some(Some("alice".into())));
        assert_eq!(command_env(&command, "LOGNAME"), Some(Some("alice".into())));
    }

    #[test]
    fn test_identity_env_leaves_inherited_env_alone() {
        let command = daemon_command(&RunIdentity::Inherit, None);
        assert_eq!(command_env(&command, "HOME"), None);
        assert_eq!(command_env(&command, "USER"), None);
        assert_eq!(command_env(&command, "LOGNAME"), None);
    }

    #[test]
    fn test_root_sudo_to_root_preserves_environment() {
        let identity = resolve_run_identity(None, 0, 0, Some("0"), Some("0")).unwrap();
        assert_eq!(identity, RunIdentity::Inherit);
        let command = daemon_command(&identity, None);
        for key in ["HOME", "USER", "LOGNAME"] {
            assert_eq!(command_env(&command, key), None);
        }
    }

    #[test]
    fn test_daemon_env_overrides_identity_env() {
        let mut env = IndexMap::new();
        env.insert("HOME".to_string(), "/srv/app".to_string());
        env.insert("USER".to_string(), "app".to_string());
        let command = daemon_command(&switch_to(Some("alice"), Some("/home/alice")), Some(&env));
        assert_eq!(command_env(&command, "HOME"), Some(Some("/srv/app".into())));
        assert_eq!(command_env(&command, "USER"), Some(Some("app".into())));
        assert_eq!(command_env(&command, "LOGNAME"), Some(Some("alice".into())));
    }

    #[test]
    fn test_identity_env_drops_values_without_a_passwd_entry() {
        // A sudo uid with no passwd entry: the supervisor's values would still
        // describe root, so they are removed instead.
        let command = daemon_command(&switch_to(None, None), None);
        assert_eq!(command_env(&command, "HOME"), Some(None));
        assert_eq!(command_env(&command, "USER"), Some(None));
        assert_eq!(command_env(&command, "LOGNAME"), Some(None));
    }

    #[test]
    fn test_daemon_env_restores_values_without_a_passwd_entry() {
        let mut env = IndexMap::new();
        env.insert("HOME".to_string(), "/srv/app".to_string());
        let command = daemon_command(&switch_to(None, None), Some(&env));
        assert_eq!(command_env(&command, "HOME"), Some(Some("/srv/app".into())));
    }
}

/// Inject proxy-related environment variables into a daemon's command.
///
/// Adds:
/// - `HOST` — the address the daemon should bind to (`127.0.0.1`, omitted in LAN mode)
/// - `PITCHFORK_URL` — the public proxy URL for this daemon (if it has a slug)
/// - `PITCHFORK_CA_FILE` / `NODE_EXTRA_CA_CERTS` — path to the pitchfork CA cert (if HTTPS enabled)
/// - `__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS` — `.<tld>` for Vite host allowlisting
/// - `PITCHFORK_LAN` — set to `"1"` when LAN mode is active
fn inject_proxy_env(cmd: &mut tokio::process::Command, host: &Option<String>) {
    let s = crate::settings::settings();
    let lan_enabled = s.proxy.lan || !s.proxy.lan_ip.is_empty();

    if s.proxy.enable && host.is_some() && !lan_enabled {
        // Only force loopback binding for daemons the proxy actually routes to.
        // In LAN mode, daemons need to bind to 0.0.0.0 to be reachable from the network.
        cmd.env("HOST", "127.0.0.1");
    }

    // PITCHFORK_URL: the daemon's public proxy URL (only if it is routed and proxy is enabled)
    if let Some(url) = build_pitchfork_url(host, &s) {
        cmd.env("PITCHFORK_URL", &url);
    }

    // PITCHFORK_CA_FILE / NODE_EXTRA_CA_CERTS: let daemons verify TLS to each
    // other through the proxy.  `PITCHFORK_CA_FILE` is the runtime-agnostic
    // name; most TLS libraries take a CA bundle path from configuration, and
    // several read one straight out of the environment (for example
    // `SSL_CERT_FILE` for OpenSSL or `REQUESTS_CA_BUNDLE` for Python).
    if s.proxy.enable && s.proxy.https {
        let ca_path = if s.proxy.tls_cert.is_empty() {
            crate::env::PITCHFORK_STATE_DIR.join("proxy").join("ca.pem")
        } else {
            std::path::PathBuf::from(&s.proxy.tls_cert)
        };
        if ca_path.exists() {
            let ca_path = ca_path.to_string_lossy().to_string();
            cmd.env("PITCHFORK_CA_FILE", &ca_path);
            cmd.env("NODE_EXTRA_CA_CERTS", &ca_path);
        }
    }

    // __VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS: Vite host allowlisting
    if s.proxy.enable {
        let tld = if lan_enabled { "local" } else { &s.proxy.tld };
        cmd.env("__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS", format!(".{tld}"));
    }

    // PITCHFORK_LAN: signal to daemons that LAN mode is active
    if lan_enabled {
        cmd.env("PITCHFORK_LAN", "1");
    }
}

/// The hostname the proxy routes to this daemon, without the TLD.
///
/// A daemon registered under a legacy `[slugs]` entry keeps that spelling,
/// because the proxy resolves slugs first. Otherwise the hostname is derived
/// from where the daemon's configuration lives.
async fn daemon_proxy_host(opts: &RunOptions) -> Option<String> {
    // Nothing consumes a hostname while the proxy is off, and deriving one
    // reads configuration and walks the project, so daemon starts skip it.
    if !crate::settings::settings().proxy.enable {
        return None;
    }
    // A slug carried on the run options skips the lookup below, so it needs the
    // same length check that lookup applies; otherwise the daemon is told a URL
    // the proxy refuses to route.
    if let Some(slug) = opts.slug.as_deref()
        && crate::proxy::hostname::hostname_fits(slug)
    {
        return opts.slug.clone();
    }
    // The daemon's own `dir` can point outside its project, so look the config
    // up from where it was defined.
    let config_dir = opts
        .watch_base_dir
        .clone()
        .unwrap_or_else(|| opts.dir.0.clone());
    let id = opts.id.clone();
    // Reading the config, the slug registry and the project's checkouts is all
    // file I/O, so it happens together on a blocking worker rather than on the
    // supervisor's executor. The lookup is the one the CLI and the proxy use,
    // so the daemon is told the address they advertise for it — a registered
    // slug when it has one, otherwise its automatic hostname.
    tokio::task::spawn_blocking(move || {
        let pt = crate::pitchfork_toml::PitchforkToml::all_merged_from(&config_dir).ok()?;
        let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
        crate::proxy::hostname::host_for_daemon(&id, pt.daemons.get(&id), &slugs)
    })
    .await
    .unwrap_or_default()
}

/// Compute the public proxy URL for a daemon.
///
/// Returns `None` if the daemon has no hostname or the proxy is not enabled.
fn build_pitchfork_url(host: &Option<String>, s: &crate::settings::Settings) -> Option<String> {
    crate::proxy::build_proxy_url(host.as_deref(), s)
}

#[cfg(test)]
mod ready_check_tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn any_ready_check_remaining_prefers_unbounded_checks() {
        let http = ReadyHttp::new("http://localhost/health");
        let cmd = ReadyCmd::new("true");

        assert!(any_ready_check_remaining(
            None,
            false,
            None,
            false,
            Some(&http),
            false,
            None,
            false
        ));
        assert!(any_ready_check_remaining(
            None,
            false,
            None,
            false,
            None,
            false,
            Some(&cmd),
            false
        ));
        assert!(any_ready_check_remaining(
            None,
            false,
            Some(&ReadyPort::new(8080)),
            false,
            Some(&http),
            true,
            Some(&cmd),
            true
        ));
    }

    #[test]
    fn any_ready_check_remaining_exhausted_timed_checks() {
        let http = ReadyHttp {
            url: "http://localhost/health".to_string(),
            status: vec![],
            timeout: Some(Duration::from_secs(5)),
        };
        let cmd = ReadyCmd {
            run: "true".into(),
            timeout: Some(Duration::from_secs(5)),
        };

        assert!(any_ready_check_remaining(
            None,
            false,
            None,
            false,
            Some(&http),
            false,
            Some(&cmd),
            false
        ));
        assert!(!any_ready_check_remaining(
            None,
            false,
            None,
            false,
            Some(&http),
            true,
            Some(&cmd),
            true
        ));
    }

    #[tokio::test]
    async fn spawn_cmd_probe_reports_success() {
        let id = DaemonId::new("global", "probe-test");
        let probe = spawn_cmd_probe(&id, &"true".into(), &std::env::temp_dir(), 0, None, &[]);
        let status = probe.result_rx.await.unwrap().unwrap();
        assert!(status.success());
    }

    /// The argv form runs the program with each argument exactly as written:
    /// the probe passes only if the program sees a single argument containing
    /// a space and characters a shell would expand.
    #[cfg(unix)]
    #[tokio::test]
    async fn spawn_cmd_probe_runs_an_argv_without_a_shell() {
        let id = DaemonId::new("global", "probe-test");
        let argv = |arg: &str| -> RunCommand {
            RunCommand::Argv(
                ["test", arg, "=", "a b $HOME %PATH% &"]
                    .map(str::to_string)
                    .to_vec(),
            )
        };
        let probe = spawn_cmd_probe(
            &id,
            &argv("a b $HOME %PATH% &"),
            &std::env::temp_dir(),
            0,
            None,
            &[],
        );
        assert!(probe.result_rx.await.unwrap().unwrap().success());
        // Through a shell, the unquoted string would split and expand, and fail.
        let probe = spawn_cmd_probe(
            &id,
            &"test a b $HOME %PATH% & = 'a b $HOME %PATH% &'".into(),
            &std::env::temp_dir(),
            0,
            None,
            &[],
        );
        assert!(!probe.result_rx.await.unwrap().unwrap().success());
        let probe = spawn_cmd_probe(&id, &argv("different"), &std::env::temp_dir(), 0, None, &[]);
        assert!(!probe.result_rx.await.unwrap().unwrap().success());
    }

    #[tokio::test]
    async fn spawn_cmd_probe_stops_on_request() {
        let id = DaemonId::new("global", "probe-test");
        let probe = spawn_cmd_probe(&id, &"sleep 30".into(), &std::env::temp_dir(), 0, None, &[]);
        let CmdProbe {
            cancel_tx,
            result_rx,
        } = probe;
        let _ = cancel_tx.send(());
        let status = result_rx.await.unwrap().unwrap();
        assert!(!status.success());
    }

    #[tokio::test]
    async fn spawn_cmd_probe_receives_daemon_and_resolved_port_environment() {
        let id = DaemonId::new("worktree", "api");
        let daemon_env = IndexMap::from([("CUSTOM_VALUE".to_string(), "yes".to_string())]);
        // Written for the platform's default shell: cmd.exe reads the probe
        // as written, so it needs cmd's own `%VAR%` syntax there.
        let check = if cfg!(windows) {
            r#"(if "%CUSTOM_VALUE%"=="yes" if "%PORT%"=="4100" if "%PORT0%"=="4100" if "%PORT1%"=="5100" if "%PITCHFORK_DAEMON_ID%"=="worktree/api" if "%PITCHFORK_RETRY_COUNT%"=="2" exit 0) & exit 1"#
        } else {
            r#"test "$CUSTOM_VALUE" = yes && test "$PORT" = 4100 && test "$PORT0" = 4100 && test "$PORT1" = 5100 && test "$PITCHFORK_DAEMON_ID" = worktree/api && test "$PITCHFORK_RETRY_COUNT" = 2"#
        };
        let probe = spawn_cmd_probe(
            &id,
            &check.into(),
            &std::env::temp_dir(),
            2,
            Some(&daemon_env),
            &[4100, 5100],
        );
        let status = probe.result_rx.await.unwrap().unwrap();
        assert!(status.success());
    }

    #[test]
    fn configured_ready_port_follows_expected_port_bump() {
        assert_eq!(resolve_configured_ready_port(3000, &[3000], &[3004]), 3004);
        assert_eq!(
            resolve_configured_ready_port(4000, &[3000, 4000], &[3003, 4003]),
            4003
        );
        assert_eq!(resolve_configured_ready_port(8080, &[3000], &[3004]), 8080);
    }
}

#[cfg(test)]
mod launch_command_tests {
    use super::{invalid_argv_program, launch_command};
    use crate::daemon_id::DaemonId;

    #[test]
    fn refuses_an_argv_whose_program_rendered_empty_or_to_exec() {
        let id = DaemonId::new("proj", "api");
        assert!(invalid_argv_program(&id, &[]).is_some());
        assert!(invalid_argv_program(&id, &words(&["", "server.js"])).is_some());
        assert!(invalid_argv_program(&id, &words(&["exec", "node"])).is_some());
        assert_eq!(invalid_argv_program(&id, &words(&["node", ""])), None);
    }

    #[test]
    fn refuses_a_probe_array_whose_program_rendered_empty_or_to_exec() {
        use super::invalid_probe_program;
        use crate::pitchfork_toml::RunCommand;
        let id = DaemonId::new("proj", "api");
        for field in ["ready_cmd", "health_cmd"] {
            let check =
                |run: Vec<String>| invalid_probe_program(&id, field, Some(&RunCommand::Argv(run)));
            assert!(check(vec![]).unwrap().contains(field));
            assert!(check(words(&["", "-h"])).is_some());
            assert!(check(words(&["exec", "pg_isready"])).is_some());
            assert_eq!(check(words(&["pg_isready", ""])), None);
        }
        // The string form goes through the shell, and no command is fine.
        assert_eq!(
            invalid_probe_program(&id, "health_cmd", Some(&RunCommand::Shell(String::new()))),
            None
        );
        assert_eq!(invalid_probe_program(&id, "health_cmd", None), None);
    }

    fn words(words: &[&str]) -> Vec<String> {
        words.iter().map(|w| w.to_string()).collect()
    }

    #[test]
    fn windows_rejects_only_enabled_unsupported_options() {
        let mut opts = crate::daemon::RunOptions::default();
        assert_eq!(super::unsupported_windows_options(&opts, ""), None);
        opts.pty = Some(false);
        opts.user = Some(" \t".into());
        assert_eq!(super::unsupported_windows_options(&opts, " \t"), None);
        opts.pty = Some(true);
        assert!(
            super::unsupported_windows_options(&opts, "")
                .unwrap()
                .contains("pty = true")
        );
        opts.pty = Some(false);
        opts.user = Some("postgres".into());
        assert!(
            super::unsupported_windows_options(&opts, "")
                .unwrap()
                .contains("user switching")
        );
        opts.user = None;
        assert!(
            super::unsupported_windows_options(&opts, "postgres")
                .unwrap()
                .contains("settings.supervisor.user")
        );
    }

    #[test]
    fn starts_the_first_word_with_the_rest_as_arguments() {
        let argv = words(&["node", "my server.js", "--name=\"a b\"", "&", "%PATH%"]);
        assert_eq!(
            launch_command(argv, None),
            (
                "node".to_string(),
                words(&["my server.js", "--name=\"a b\"", "&", "%PATH%"])
            )
        );
    }

    #[test]
    fn mise_receives_every_word_after_the_separator() {
        let argv = words(&["node", "my server.js", "'single'"]);
        let mise = std::path::Path::new("/opt/mise/bin/mise");
        let (program, args) = launch_command(argv, Some(mise));
        assert_eq!(program, mise.to_string_lossy());
        assert_eq!(
            args,
            words(&["x", "--", "node", "my server.js", "'single'"])
        );
    }
}

#[cfg(all(test, windows))]
mod windows_retry_tests {
    use super::*;
    use crate::config_types::{Dir, Retry};
    use crate::settings::reload_settings;
    use std::process::Stdio;
    use tokio::io::AsyncBufReadExt;

    #[tokio::test]
    async fn forced_retry_claim_revalidates_settings_before_stopping_a_live_instance() {
        const CHILD_ENV: &str = "PITCHFORK_TEST_WINDOWS_RETRY_CLAIM";
        const CHILD_SENTINEL: &str = "windows-retry-claim-child-ran";
        if std::env::var_os(CHILD_ENV).is_none() {
            // Settings and supervisor state are process globals. Give their
            // reload and persistence private directories in an isolated test.
            let temp = tempfile::tempdir().unwrap();
            std::fs::create_dir(temp.path().join("config")).unwrap();
            std::fs::write(
                temp.path().join("pitchfork.toml"),
                "[settings.supervisor]\nuser = ''\n",
            )
            .unwrap();
            let mut command = tokio::process::Command::new(std::env::current_exe().unwrap());
            for (name, _) in std::env::vars_os() {
                if name
                    .to_string_lossy()
                    .to_ascii_uppercase()
                    .starts_with("PITCHFORK_")
                {
                    command.env_remove(name);
                }
            }
            command
                .args([
                    "--exact",
                    "supervisor::lifecycle::windows_retry_tests::forced_retry_claim_revalidates_settings_before_stopping_a_live_instance",
                    "--nocapture",
                ])
                .current_dir(temp.path())
                .env(CHILD_ENV, "1")
                .env("PITCHFORK_CONFIG_DIR", temp.path().join("config"))
                .env("PITCHFORK_STATE_DIR", temp.path().join("state"))
                .env("PITCHFORK_LOGS_DIR", temp.path().join("logs"))
                .env("PITCHFORK_BOOT_EXECUTABLE", temp.path().join("missing.exe"))
                .hide_console_window()
                .kill_on_drop(true);
            let output = time::timeout(Duration::from_secs(30), command.output())
                .await
                .expect("isolated retry claim test timed out")
                .unwrap();
            assert!(
                output.status.success(),
                "isolated retry claim test failed:\nstdout:\n{}\nstderr:\n{}",
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            );
            assert!(String::from_utf8_lossy(&output.stderr).contains(CHILD_SENTINEL));
            return;
        }
        eprintln!("{CHILD_SENTINEL}");

        let mut opts = RunOptions {
            id: DaemonId::new("windows-retry", "live"),
            force: true,
            wait_ready: true,
            retry: Retry(2),
            dir: Dir(env::CWD.clone()),
            ..RunOptions::default()
        };
        let mut restart_mark = None;
        let mut guard = Some(SUPERVISOR.stop_lock(&opts.id).await.lock_owned().await);
        assert!(
            SUPERVISOR
                .claim_or_defer(&opts, &mut guard, &mut restart_mark, None)
                .await
                .unwrap()
                .is_none()
        );
        drop(guard.take());
        let retrying_claim = SUPERVISOR.mark_retrying(&opts.id);

        // Model another start taking the record during the foreground retry's
        // backoff. Keep its process handle open to pin the PID. On a panic,
        // kill_on_drop terminates it; if the isolated test itself is killed,
        // closing its stdin also releases the waiting PowerShell process.
        let powershell = std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap())
            .join("System32/WindowsPowerShell/v1.0/powershell.exe");
        let mut child = tokio::process::Command::new(powershell)
            .args([
                "-NoLogo",
                "-NoProfile",
                "-NonInteractive",
                "-Command",
                "[Console]::Out.WriteLine('READY'); [Console]::In.ReadToEnd() | Out-Null",
            ])
            .current_dir(std::env::var_os("SystemRoot").unwrap())
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .kill_on_drop(true)
            .hide_console_window()
            .spawn()
            .unwrap();
        let mut stdout = tokio::io::BufReader::new(child.stdout.take().unwrap());
        let mut ready = String::new();
        stdout.read_line(&mut ready).await.unwrap();
        assert_eq!(ready.trim_end(), "READY");
        let pid = child.id().unwrap();
        PROCS.refresh_pids(&[pid]);
        assert!(PROCS.is_running(pid));
        assert!(child.try_wait().unwrap().is_none());
        guard = Some(SUPERVISOR.stop_lock(&opts.id).await.lock_owned().await);
        let running = SUPERVISOR
            .upsert_daemon(
                UpsertDaemonOpts::from_run_options(&opts, DaemonStatus::Running)
                    .set(|o| o.pid = Some(pid))
                    .build(),
            )
            .await
            .unwrap();
        assert!(running.start_time.is_some());
        assert_eq!(running.start_time, PROCS.start_time(pid));
        let stop_epoch = SUPERVISOR.stop_epoch(&opts.id);

        std::fs::write(
            env::CWD.join("pitchfork.toml"),
            "[settings.supervisor]\nuser = 'unsupported-account'\n",
        )
        .unwrap();
        reload_settings();
        assert_eq!(settings().supervisor.user, "unsupported-account");
        opts.retry_count = 1;
        let response = SUPERVISOR
            .claim_or_defer(&opts, &mut guard, &mut restart_mark, None)
            .await
            .unwrap();

        // Check the destructive boundary's effects, not just its diagnostic.
        assert!(
            child.try_wait().unwrap().is_none(),
            "the live instance was stopped"
        );
        let preserved = SUPERVISOR.get_daemon(&opts.id).await.unwrap();
        assert_eq!(preserved.pid, Some(pid));
        assert!(preserved.status.is_running());
        assert_eq!(
            serde_json::to_value(&preserved).unwrap(),
            serde_json::to_value(&running).unwrap()
        );
        assert_eq!(SUPERVISOR.stop_epoch(&opts.id), stop_epoch);
        assert!(!retrying_claim.is_cancelled());
        assert!(restart_mark.is_none());
        assert!(matches!(response, Some(IpcResponse::DaemonFailed { .. })));
        drop(guard.take());
        child.kill().await.unwrap();
        child.wait().await.unwrap();

        // The same rejection must settle a retry without a process, so the
        // background checker cannot keep picking up its old errored record.
        opts.id = DaemonId::new("windows-retry", "pidless");
        guard = Some(SUPERVISOR.stop_lock(&opts.id).await.lock_owned().await);
        SUPERVISOR
            .upsert_daemon(
                UpsertDaemonOpts::from_run_options(&opts, DaemonStatus::Errored(7)).build(),
            )
            .await
            .unwrap();
        assert!(matches!(
            SUPERVISOR
                .claim_or_defer(&opts, &mut guard, &mut restart_mark, None)
                .await
                .unwrap(),
            Some(IpcResponse::DaemonFailed { .. })
        ));
        let failed = SUPERVISOR.get_daemon(&opts.id).await.unwrap();
        assert!(failed.status.is_failed());
        assert!(failed.pid.is_none());
        assert_eq!(failed.retry_count, 1);
        assert_eq!(failed.retry, Retry(2));
    }
}

#[cfg(test)]
mod output_reader_tests {
    use super::{forward_output_lines, output_line_text};

    #[test]
    fn line_endings_are_removed() {
        assert_eq!(output_line_text(b"ready\n"), "ready");
        // A PTY's ONLCR, and a program that already wrote `\r\n` through it.
        assert_eq!(output_line_text(b"ready\r\n"), "ready");
        assert_eq!(output_line_text(b"ready\r\r\n"), "ready");
        // The last line of the output may have no newline at all.
        assert_eq!(output_line_text(b"ready"), "ready");
    }

    #[tokio::test]
    async fn a_line_that_is_not_utf8_does_not_end_the_read() {
        // What cut the output off before: `next_line` fails on the second
        // line, and nothing after it was read.
        let output: &[u8] = b"before\nbad \xff\xfe bytes\nafter 1\nafter 2\nlast";
        let (tx, mut rx) = tokio::sync::mpsc::channel(16);
        forward_output_lines(tokio::io::BufReader::new(output), tx, None).await;

        let mut lines = Vec::new();
        while let Some(line) = rx.recv().await {
            lines.push(line.text);
        }
        assert_eq!(lines.len(), 5, "{lines:?}");
        assert_eq!(lines[0], "before");
        assert!(lines[1].starts_with("bad "), "{:?}", lines[1]);
        assert_eq!(&lines[2..], ["after 1", "after 2", "last"]);
    }
}

#[cfg(test)]
mod output_reader_eio_tests {
    use super::forward_output_lines;
    use std::pin::Pin;
    use std::task::{Context, Poll};

    /// Output that ends as a Linux PTY master does once the slave closes:
    /// the last bytes, with no newline, then `EIO` instead of end of file.
    struct EndsWithEio(Option<&'static [u8]>);

    impl tokio::io::AsyncRead for EndsWithEio {
        fn poll_read(
            mut self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buf: &mut tokio::io::ReadBuf<'_>,
        ) -> Poll<std::io::Result<()>> {
            match self.0.take() {
                Some(bytes) => {
                    buf.put_slice(bytes);
                    Poll::Ready(Ok(()))
                }
                None => Poll::Ready(Err(std::io::Error::from_raw_os_error(5))),
            }
        }
    }

    #[tokio::test]
    async fn a_last_line_cut_off_by_eio_is_still_forwarded() {
        let reader = tokio::io::BufReader::new(EndsWithEio(Some(b"first\nlast without newline")));
        let (tx, mut rx) = tokio::sync::mpsc::channel(16);
        forward_output_lines(reader, tx, None).await;

        let mut lines = Vec::new();
        while let Some(line) = rx.recv().await {
            lines.push(line.text);
        }
        assert_eq!(lines, ["first", "last without newline"]);
    }
}

#[cfg(all(test, unix))] // These tests use Unix shells and process groups.
mod readiness_tests;