decompose 0.2.0

A simple and flexible scheduler and orchestrator to manage non-containerized applications
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
use std::collections::BTreeMap;
use std::env;
use std::fs;
use std::fs::OpenOptions;
use std::io::Write;
#[cfg(unix)]
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
#[cfg(unix)]
use std::os::unix::io::AsRawFd;
use std::path::Path;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use anyhow::{Context, Result};
use interprocess::local_socket::ListenerOptions;
use interprocess::local_socket::tokio::Stream;
use interprocess::local_socket::traits::tokio::Listener as _;
use regex::Regex;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::Command as TokioCommand;
use tokio::sync::{Mutex, watch};
use tokio::time::sleep;

use crate::cli::DaemonArgs;
use crate::config::{
    apply_interpolation, build_process_instances, collect_process_subset, load_and_merge_configs,
    load_dotenv_files,
};
use crate::ipc::{Request, Response, to_socket_name};
use crate::model::{
    DependencyCondition, ExitMode, ProcessRuntime, ProcessSnapshot, ProcessStatus, RestartPolicy,
    RuntimePaths,
};
#[cfg(unix)]
use crate::paths::FILE_MODE;
use crate::paths::{create_dir_secure, runtime_paths_for};

/// Compile a `ready_log_line` pattern, falling back to a literal (escaped)
/// match if the user-supplied pattern isn't a valid regex. The escaped
/// fallback is guaranteed-valid regex, so this never panics.
fn compile_ready_pattern(pattern: &str) -> Regex {
    Regex::new(pattern).unwrap_or_else(|_| {
        // `regex::escape` returns a string of literal characters only, which
        // is always a valid regex. If this somehow fails, fall back to a
        // never-matching pattern rather than panicking.
        Regex::new(&regex::escape(pattern))
            .unwrap_or_else(|_| Regex::new("$.^").expect("never-matching pattern is valid regex"))
    })
}

/// Open a file with restrictive 0o600 permissions on Unix, and defensively
/// tighten the mode if the file already existed with looser permissions.
#[cfg(unix)]
fn open_secure_append(path: &Path) -> std::io::Result<fs::File> {
    let file = OpenOptions::new()
        .create(true)
        .append(true)
        .mode(FILE_MODE)
        .open(path)?;
    // If the file existed before this call, `mode` is ignored and we must
    // tighten it explicitly.
    fs::set_permissions(path, fs::Permissions::from_mode(FILE_MODE))?;
    Ok(file)
}

#[cfg(not(unix))]
fn open_secure_append(path: &Path) -> std::io::Result<fs::File> {
    OpenOptions::new().create(true).append(true).open(path)
}

/// Truncate (or create) a file with 0o600 permissions, dropping the handle
/// immediately. Used to reset the daemon log at the start of a session
/// without disturbing the append-mode handle passed to the child process.
#[cfg(unix)]
fn truncate_secure(path: &Path) -> std::io::Result<()> {
    let _ = OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .mode(FILE_MODE)
        .open(path)?;
    fs::set_permissions(path, fs::Permissions::from_mode(FILE_MODE))?;
    Ok(())
}

#[cfg(not(unix))]
fn truncate_secure(path: &Path) -> std::io::Result<()> {
    let _ = OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open(path)?;
    Ok(())
}

#[cfg(unix)]
fn open_secure_lock(path: &Path) -> std::io::Result<fs::File> {
    let file = OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(false)
        .mode(FILE_MODE)
        .open(path)?;
    fs::set_permissions(path, fs::Permissions::from_mode(FILE_MODE))?;
    Ok(file)
}

#[cfg(not(unix))]
fn open_secure_lock(path: &Path) -> std::io::Result<fs::File> {
    OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(false)
        .open(path)
}

/// Write a file atomically-ish with 0o600 permissions.
#[cfg(unix)]
fn write_secure(path: &Path, contents: &[u8]) -> std::io::Result<()> {
    use std::io::Write as _;
    let mut file = OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .mode(FILE_MODE)
        .open(path)?;
    file.write_all(contents)?;
    fs::set_permissions(path, fs::Permissions::from_mode(FILE_MODE))?;
    Ok(())
}

#[cfg(not(unix))]
fn write_secure(path: &Path, contents: &[u8]) -> std::io::Result<()> {
    fs::write(path, contents)
}

#[derive(Debug)]
pub(crate) struct DaemonState {
    instance: String,
    processes: BTreeMap<String, ProcessRuntime>,
    controllers: BTreeMap<String, watch::Sender<bool>>,
    shutdown_requested: bool,
    exit_mode: ExitMode,
    /// CLI-level override for shutdown timeout (from `down --timeout`).
    shutdown_timeout_override: Option<u64>,
    /// Original daemon-launch arguments kept so the `Reload` IPC handler can
    /// re-read config from the same paths the daemon was launched with.
    cwd: std::path::PathBuf,
    config_files: Vec<std::path::PathBuf>,
    env_files: Vec<std::path::PathBuf>,
    disable_dotenv: bool,
    /// Timestamp of the most recent IPC request. The orphan watchdog uses
    /// this to decide whether the daemon still has active clients talking to
    /// it after its parent process exits. Seeded at daemon start, then
    /// updated at the top of every `handle_client` call.
    last_client_activity: Instant,
}

impl DaemonState {
    /// Broadcast a shutdown signal to every running process controller and
    /// transition any still-Pending processes directly to Stopped (they have
    /// no controller of their own). Does not set `shutdown_requested`.
    fn broadcast_stop(&mut self) {
        for tx in self.controllers.values() {
            let _ = tx.send(true);
        }
        for runtime in self.processes.values_mut() {
            if matches!(runtime.status, ProcessStatus::Pending) {
                runtime.status = ProcessStatus::Stopped;
            }
        }
    }

    /// Set `shutdown_requested` and broadcast stop to all controllers. Used
    /// by callers that want to initiate shutdown (exit-mode trigger, fatal
    /// accept error, `Down` RPC).
    fn request_shutdown(&mut self) {
        self.shutdown_requested = true;
        self.broadcast_stop();
    }

    /// Stop a specific set of process instances by name. For each name:
    /// - If the process is `Pending` (has no controller yet), transition it
    ///   directly to `Stopped`.
    /// - Otherwise, send the shutdown signal to its controller so the
    ///   lifecycle task will tear it down.
    ///
    /// Unknown names are silently ignored (callers should resolve/validate
    /// first). Used by the Stop, RemoveOrphans, and Reload IPC handlers,
    /// which all share this "best-effort targeted shutdown" shape.
    fn stop_instances(&mut self, names: &[String]) {
        for name in names {
            if let Some(runtime) = self.processes.get_mut(name)
                && matches!(runtime.status, ProcessStatus::Pending)
            {
                runtime.status = ProcessStatus::Stopped;
                continue;
            }
            if let Some(tx) = self.controllers.get(name) {
                let _ = tx.send(true);
            }
        }
    }
}

/// Poll the shared state until every instance in `names` has reached a
/// terminal status, or until `max_ticks` of `tick` elapses. Returns once
/// either condition holds. Callers use this to gate follow-up work (e.g.
/// respawning or removing entries) on the preceding stop signal actually
/// having landed.
async fn wait_for_terminal(state: &SharedState, names: &[String], tick: Duration, max_ticks: u32) {
    for _ in 0..max_ticks {
        let all_stopped = {
            let guard = state.lock().await;
            names.iter().all(|name| {
                guard
                    .processes
                    .get(name)
                    .map(|r| r.status.is_terminal())
                    .unwrap_or(true)
            })
        };
        if all_stopped {
            return;
        }
        sleep(tick).await;
    }
}

pub(crate) type SharedState = Arc<Mutex<DaemonState>>;

/// Resolve `handle` to the current name, take the state mutex, and run `f`
/// against the matching [`ProcessRuntime`] if one exists. Returns the closure's
/// result, or `None` if the runtime entry is gone (e.g. after a rename).
///
/// This is a thin wrapper over the lock→resolve→`get_mut` pattern repeated
/// throughout the daemon; it exists purely to cut down on ceremony at call
/// sites. Behaviour matches the hand-written form exactly.
pub(crate) async fn with_process_mut<F, R>(
    state: &SharedState,
    handle: &crate::model::NameHandle,
    f: F,
) -> Option<R>
where
    F: FnOnce(&mut ProcessRuntime) -> R,
{
    let name = crate::model::read_name(handle);
    let mut guard = state.lock().await;
    guard.processes.get_mut(&name).map(f)
}

/// Read-only counterpart to [`with_process_mut`]: resolves the name, takes the
/// lock for reading, and runs `f` against `&ProcessRuntime`. Returns `None` if
/// the entry is gone.
pub(crate) async fn with_process<F, R>(
    state: &SharedState,
    handle: &crate::model::NameHandle,
    f: F,
) -> Option<R>
where
    F: FnOnce(&ProcessRuntime) -> R,
{
    let name = crate::model::read_name(handle);
    let guard = state.lock().await;
    guard.processes.get(&name).map(f)
}

/// Acquire an exclusive, non-blocking advisory lock for this daemon instance.
///
/// Returns the open lock file handle — the caller must keep it alive for the
/// daemon's entire lifetime. The lock is automatically released when the
/// file descriptor is closed (including on crash).
#[cfg(unix)]
fn acquire_instance_lock(paths: &RuntimePaths) -> Result<fs::File> {
    let lock_file = open_secure_lock(&paths.lock)
        .with_context(|| format!("failed to open lock file at {}", paths.lock.display()))?;

    let ret = unsafe { libc::flock(lock_file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
    if ret != 0 {
        anyhow::bail!(
            "another daemon is already running for this project (lock held on {})",
            paths.lock.display()
        );
    }
    Ok(lock_file)
}

#[cfg(not(unix))]
fn acquire_instance_lock(paths: &RuntimePaths) -> Result<fs::File> {
    // Advisory locking is Unix-only; on other platforms we skip it.
    // The socket bind below still provides some protection against duplicates.
    open_secure_lock(&paths.lock)
        .with_context(|| format!("failed to open lock file at {}", paths.lock.display()))
}

#[allow(clippy::too_many_arguments)]
pub fn spawn_daemon_process(
    cwd: &Path,
    config_files: &[std::path::PathBuf],
    instance: &str,
    paths: &RuntimePaths,
    env_files: &[std::path::PathBuf],
    disable_dotenv: bool,
    processes: &[String],
    no_deps: bool,
    parent_pid: Option<u32>,
) -> Result<()> {
    let exe = env::current_exe().context("failed to locate current executable")?;
    if let Some(parent) = paths.daemon_log.parent() {
        create_dir_secure(parent)?;
    }

    // Truncate any leftover log from a previous session so `decompose logs`
    // only shows output from this run. We open+drop a truncating handle here
    // rather than switching `open_secure_append` to truncate mode, because the
    // handle below is passed to the child as its stdout/stderr and must stay
    // in append mode (two `Stdio::from` clones sharing the same file).
    truncate_secure(&paths.daemon_log).with_context(|| {
        format!(
            "failed to truncate daemon log at {}",
            paths.daemon_log.display()
        )
    })?;

    let mut log_file = open_secure_append(&paths.daemon_log).with_context(|| {
        format!(
            "failed to open daemon log at {}",
            paths.daemon_log.display()
        )
    })?;
    writeln!(
        log_file,
        "\n--- daemon started at {} ---",
        humantime::format_rfc3339_seconds(std::time::SystemTime::now())
    )
    .ok();
    let log_err = log_file.try_clone()?;

    let mut cmd = std::process::Command::new(exe);
    cmd.arg("daemon").arg("--cwd").arg(cwd);

    for cf in config_files {
        cmd.arg("--config-file").arg(cf);
    }

    cmd.arg("--instance").arg(instance);

    for ef in env_files {
        cmd.arg("--env-file").arg(ef);
    }

    if disable_dotenv {
        cmd.arg("--disable-dotenv");
    }

    for proc_name in processes {
        cmd.arg("--process").arg(proc_name);
    }

    if no_deps {
        cmd.arg("--no-deps");
    }

    if let Some(pid) = parent_pid {
        cmd.arg("--parent-pid").arg(pid.to_string());
    }

    cmd.stdin(Stdio::null())
        .stdout(Stdio::from(log_file))
        .stderr(Stdio::from(log_err));

    let _child = cmd.spawn().context("failed to spawn daemon process")?;
    Ok(())
}

pub async fn run_daemon(args: DaemonArgs) -> Result<()> {
    env::set_current_dir(&args.cwd).with_context(|| {
        format!(
            "failed to change cwd to {}",
            args.cwd.as_os_str().to_string_lossy()
        )
    })?;

    let paths = runtime_paths_for(&args.instance)?;
    if let Some(parent) = paths.socket.parent() {
        create_dir_secure(parent)?;
    }
    if let Some(parent) = paths.pid.parent() {
        create_dir_secure(parent)?;
    }

    // Acquire an exclusive advisory lock to prevent duplicate daemons.
    // The lock file descriptor must be held for the lifetime of the daemon;
    // it is automatically released when the process exits (even on crash).
    let _lock_file = acquire_instance_lock(&paths)?;

    // Now that we hold the lock, it's safe to clean up a stale socket from
    // a previously crashed daemon.
    if paths.socket.exists() {
        let _ = fs::remove_file(&paths.socket);
    }

    let dotenv = load_dotenv_files(&args.cwd, &args.env_files, args.disable_dotenv)?;

    let mut config = load_and_merge_configs(&args.config_files)?;
    apply_interpolation(&mut config);
    crate::config::validate_project_paths(&config, &args.cwd)?;

    // Determine which services were selected for launch. Non-selected ones
    // stay in the daemon state as NotStarted so they can be addressed later
    // by `start` or incremental `up`.
    let selected: Option<std::collections::HashSet<String>> = if !args.processes.is_empty() {
        Some(collect_process_subset(
            &config,
            &args.processes,
            !args.no_deps,
        )?)
    } else {
        None
    };

    let exit_mode = config.exit_mode;
    let mut process_map = build_process_instances(&config, &args.cwd, &dotenv);

    // Mark non-selected services as NotStarted instead of Pending so the
    // supervisor won't auto-launch them.
    if let Some(ref selected) = selected {
        for (name, runtime) in process_map.iter_mut() {
            if !selected.contains(&runtime.spec.base_name)
                && !selected.contains(name)
                && matches!(runtime.status, ProcessStatus::Pending)
            {
                runtime.status = ProcessStatus::NotStarted;
            }
        }
    }

    write_secure(&paths.pid, std::process::id().to_string().as_bytes()).with_context(|| {
        format!(
            "failed to write pid file to {}",
            paths.pid.as_path().display()
        )
    })?;

    let socket_name = to_socket_name(&paths.socket)?;
    let listener = ListenerOptions::new()
        .name(socket_name)
        .create_tokio()
        .context("failed to create local socket listener")?;

    // Tighten the newly-created socket's file mode. The `interprocess` crate
    // binds the socket with the current umask, which could leave it world-
    // readable or world-writable. We want owner-only access on local sockets.
    #[cfg(unix)]
    if paths.socket.exists() {
        let _ = fs::set_permissions(&paths.socket, fs::Permissions::from_mode(FILE_MODE));
    }

    let state = Arc::new(Mutex::new(DaemonState {
        instance: args.instance.clone(),
        processes: process_map,
        controllers: BTreeMap::new(),
        shutdown_requested: false,
        exit_mode,
        shutdown_timeout_override: None,
        cwd: args.cwd.clone(),
        config_files: args.config_files.clone(),
        env_files: args.env_files.clone(),
        disable_dotenv: args.disable_dotenv,
        last_client_activity: Instant::now(),
    }));

    let (stop_tx, mut stop_rx) = watch::channel(false);
    tokio::spawn(supervisor_loop(state.clone(), stop_tx));

    // Orphan watchdog: when the launching process goes away without calling
    // `down`, auto-exit after a grace period of no IPC activity. Inert when
    // no parent PID was passed (i.e. `up -d`, where the daemon is intended
    // to survive its caller).
    if let Some(parent_pid) = args.parent_pid {
        tokio::spawn(orphan_watchdog(state.clone(), parent_pid));
    }

    loop {
        tokio::select! {
            changed = stop_rx.changed() => {
                if changed.is_ok() && *stop_rx.borrow() {
                    break;
                }
            }
            incoming = listener.accept() => {
                match incoming {
                    Ok(stream) => {
                        let state = state.clone();
                        tokio::spawn(async move {
                            let _ = handle_client(stream, state).await;
                        });
                    }
                    Err(e) => {
                        // Accept errors are almost always transient (e.g.
                        // ECONNABORTED when a client hangs up between the
                        // kernel accepting the connection and us reading it,
                        // or EMFILE if we're briefly out of file descriptors).
                        // We distinguish "fatal" cases — principally EBADF,
                        // which would indicate the listening socket has been
                        // closed out from under us — and shut the daemon
                        // down. Everything else we log and retry after a
                        // short backoff.
                        #[cfg(unix)]
                        let is_fatal = matches!(e.raw_os_error(), Some(libc::EBADF) | Some(libc::ENOTSOCK) | Some(libc::EINVAL));
                        #[cfg(not(unix))]
                        let is_fatal = false;

                        if is_fatal {
                            eprintln!("socket accept failed fatally, shutting down: {e}");
                            // Trigger a graceful shutdown — supervisor will
                            // stop processes and break the outer loop.
                            let mut guard = state.lock().await;
                            guard.request_shutdown();
                            break;
                        } else {
                            eprintln!("socket accept error (transient): {e}");
                            sleep(Duration::from_millis(50)).await;
                        }
                    }
                }
            }
        }
    }

    let _ = fs::remove_file(&paths.socket);
    let _ = fs::remove_file(&paths.pid);
    let _ = fs::remove_file(&paths.lock);
    Ok(())
}

async fn supervisor_loop(state: SharedState, stop_tx: watch::Sender<bool>) {
    loop {
        let mut launchable = Vec::new();
        let mut request_shutdown = false;

        {
            let mut guard = state.lock().await;
            let snapshot = guard.processes.clone();

            // Check exit mode triggers
            if !guard.shutdown_requested {
                let triggered = match guard.exit_mode {
                    ExitMode::WaitAll => false,
                    ExitMode::ExitOnFailure => snapshot.values().any(|p| {
                        matches!(p.status, ProcessStatus::Exited { code } if code != 0)
                            || matches!(p.status, ProcessStatus::FailedToStart { .. })
                    }),
                    ExitMode::ExitOnEnd => snapshot
                        .values()
                        .any(|p| matches!(p.status, ProcessStatus::Exited { .. })),
                };
                if triggered {
                    drop(guard);
                    let mut guard = state.lock().await;
                    guard.request_shutdown();
                    request_shutdown = true;
                } else {
                    for (name, proc_runtime) in &snapshot {
                        if !matches!(proc_runtime.status, ProcessStatus::Pending) {
                            continue;
                        }
                        if proc_runtime.spec.disabled {
                            continue;
                        }
                        if dependencies_met(proc_runtime, &snapshot) {
                            launchable.push(name.clone());
                        }
                    }

                    if guard.shutdown_requested {
                        request_shutdown = true;
                        guard.broadcast_stop();
                    }
                }
            } else {
                request_shutdown = true;
                guard.broadcast_stop();
            }
        }

        for name in launchable {
            start_process(name, state.clone()).await;
        }

        let done = {
            let guard = state.lock().await;
            request_shutdown
                && guard
                    .processes
                    .values()
                    .all(|runtime| runtime.status.is_terminal())
        };

        if done {
            let _ = stop_tx.send(true);
            break;
        }

        sleep(crate::tuning::supervisor_tick()).await;
    }
}

/// Return `true` if the given PID is still alive (or we can't tell).
/// On Unix, uses `kill(pid, 0)`: returns `Ok` if the process exists or we
/// lack permission to signal it (still alive), and `ESRCH` if the PID is
/// unused. PID 0 and 1 are treated as "alive" (PID 1 is init/launchd, which
/// `getppid()` returns on macOS after the real parent exits — we detect
/// orphan state via the caller-supplied PID, not `getppid`).
#[cfg(unix)]
fn parent_alive(pid: u32) -> bool {
    if pid == 0 {
        return true;
    }
    use nix::errno::Errno;
    use nix::sys::signal::kill;
    use nix::unistd::Pid;
    match kill(Pid::from_raw(pid as i32), None) {
        Ok(()) => true,
        Err(Errno::ESRCH) => false,
        // EPERM means the process exists but we can't signal it.
        Err(_) => true,
    }
}

#[cfg(not(unix))]
fn parent_alive(_pid: u32) -> bool {
    // Best-effort: on non-Unix platforms we skip the check entirely.
    true
}

/// Periodically check whether the caller that launched this daemon is still
/// alive. Once the parent PID is gone AND no IPC client has spoken to us in
/// the configured grace period, initiate a graceful shutdown. The grace
/// period lets transient tools (`ps`, `logs`, `start`) keep a daemon alive
/// even after the original terminal disappeared — only a truly abandoned
/// daemon self-exits.
async fn orphan_watchdog(state: SharedState, parent_pid: u32) {
    let tick = crate::tuning::orphan_check_interval();
    let grace = crate::tuning::orphan_timeout();
    loop {
        sleep(tick).await;

        {
            let guard = state.lock().await;
            if guard.shutdown_requested {
                return;
            }
        }

        if parent_alive(parent_pid) {
            continue;
        }

        // Parent is gone. Check whether any client has been in touch
        // recently; if so, defer.
        let should_exit = {
            let guard = state.lock().await;
            guard.last_client_activity.elapsed() >= grace
        };

        if should_exit {
            eprintln!(
                "daemon: parent pid {parent_pid} is gone and no IPC activity for \
                 {}s; initiating shutdown",
                grace.as_secs()
            );
            let mut guard = state.lock().await;
            guard.request_shutdown();
            return;
        }
    }
}

pub(crate) fn dependencies_met(
    candidate: &ProcessRuntime,
    snapshot: &BTreeMap<String, ProcessRuntime>,
) -> bool {
    for (dep_base, cond) in &candidate.spec.depends_on {
        let dep_instances: Vec<&ProcessRuntime> = snapshot
            .values()
            .filter(|p| p.spec.base_name == *dep_base)
            .collect();
        if dep_instances.is_empty() {
            return false;
        }

        let satisfied = match cond {
            DependencyCondition::ProcessStarted => dep_instances.iter().all(|p| p.started_once),
            // `process_healthy` gates on readiness (the readiness probe's
            // pass/fail state). Liveness intentionally does not participate:
            // a process with no readiness probe configured can never satisfy
            // this condition — use `process_started` or `process_log_ready`
            // when that's the desired semantics. See model.rs for the
            // `ready`/`alive` split.
            DependencyCondition::ProcessHealthy => dep_instances.iter().all(|p| p.ready),
            DependencyCondition::ProcessLogReady => dep_instances.iter().all(|p| p.log_ready),
            DependencyCondition::ProcessCompleted => dep_instances.iter().all(|p| {
                matches!(
                    p.status,
                    ProcessStatus::Exited { .. } | ProcessStatus::Stopped
                )
            }),
            DependencyCondition::ProcessCompletedSuccessfully => dep_instances
                .iter()
                .all(|p| matches!(p.status, ProcessStatus::Exited { code: 0 })),
        };

        if !satisfied {
            return false;
        }
    }

    true
}

async fn start_process(name: String, state: SharedState) {
    // Pull the spec and the name handle for a pending process. Non-pending
    // (or missing) entries are silent no-ops — callers may fire
    // start_process opportunistically.
    let (spec, name_handle) = {
        let mut guard = state.lock().await;
        let Some(runtime) = guard.processes.get_mut(&name) else {
            return;
        };
        if !matches!(runtime.status, ProcessStatus::Pending) {
            return;
        }
        (runtime.spec.clone(), runtime.name_handle.clone())
    };

    let ready_pattern: Option<Regex> = spec.ready_log_line.as_deref().map(compile_ready_pattern);

    let Some(mut child) =
        spawn_process_child(&name_handle, &spec, &state, SpawnContext::Initial).await
    else {
        return;
    };

    let pid = child.id().unwrap_or(0);
    with_process_mut(&state, &name_handle, |runtime| {
        runtime.status = ProcessStatus::Running { pid };
        runtime.started_once = true;
    })
    .await;

    spawn_health_probes(&name_handle, &spec, &state);
    attach_output_readers(&mut child, &name_handle, ready_pattern, state.clone());

    let (kill_tx, kill_rx) = watch::channel(false);
    {
        let current = crate::model::read_name(&name_handle);
        let mut guard = state.lock().await;
        guard.controllers.insert(current, kill_tx);
    }

    tokio::spawn(process_lifecycle(
        name_handle,
        spec,
        child,
        kill_rx,
        state.clone(),
    ));
}

/// Identifies whether we're doing the initial spawn or a restart attempt,
/// for shaping the error-context messages emitted on spawn failure.
#[derive(Clone, Copy)]
enum SpawnContext {
    Initial,
    Restart,
}

impl SpawnContext {
    fn build_label(self) -> &'static str {
        match self {
            SpawnContext::Initial => "failed to build shell command",
            SpawnContext::Restart => "failed to build shell command on restart",
        }
    }

    fn spawn_label(self) -> &'static str {
        match self {
            SpawnContext::Initial => "failed to spawn process",
            SpawnContext::Restart => "failed to spawn process on restart",
        }
    }
}

/// Build a shell command from `spec`, apply the common stdio/env setup, and
/// spawn the child. On failure, log the error, transition the process to
/// `FailedToStart`, and return `None`. The `ctx` parameter only affects the
/// phrasing of error messages (initial spawn vs. restart).
async fn spawn_process_child(
    name_handle: &crate::model::NameHandle,
    spec: &crate::model::ProcessInstanceSpec,
    state: &SharedState,
    ctx: SpawnContext,
) -> Option<tokio::process::Child> {
    let name = crate::model::read_name(name_handle);
    let mut cmd = match build_shell_command(&spec.command)
        .with_context(|| format!("[{name}] {} for {:?}", ctx.build_label(), spec.command))
    {
        Ok(c) => c,
        Err(e) => {
            mark_failed_to_start(name_handle, state, &e).await;
            return None;
        }
    };
    cmd.current_dir(&spec.working_dir)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .envs(&spec.environment);
    // Put each service in its own process group so that a signal sent to
    // the pgid reaches any backgrounded grandchildren too (the shell
    // forks them out, e.g. `foo & bar`). Without this, `down` only stops
    // the immediate child and leaks grandchildren.
    #[cfg(unix)]
    cmd.process_group(0);

    match cmd.spawn().with_context(|| {
        format!(
            "[{name}] {} (command={:?}, cwd={})",
            ctx.spawn_label(),
            spec.command,
            spec.working_dir.display()
        )
    }) {
        Ok(child) => Some(child),
        Err(e) => {
            mark_failed_to_start(name_handle, state, &e).await;
            None
        }
    }
}

/// Log the (already-contextualised) spawn error and transition the process
/// to `FailedToStart`. Does not remove the controller — the caller decides
/// what cleanup is appropriate for its phase.
async fn mark_failed_to_start(
    name_handle: &crate::model::NameHandle,
    state: &SharedState,
    err: &anyhow::Error,
) {
    let name = crate::model::read_name(name_handle);
    eprintln!("[{name}] {err:#}");
    with_process_mut(state, name_handle, |runtime| {
        runtime.status = ProcessStatus::FailedToStart {
            reason: format!("{err:#}"),
        };
    })
    .await;
}

/// Spawn readiness and liveness probe tasks if configured on the spec.
fn spawn_health_probes(
    name_handle: &crate::model::NameHandle,
    spec: &crate::model::ProcessInstanceSpec,
    state: &SharedState,
) {
    use crate::health_probes::{ProbeKind, spawn_probe_if_present};
    spawn_probe_if_present(
        spec.readiness_probe.as_ref(),
        ProbeKind::Readiness,
        name_handle,
        &spec.working_dir,
        &spec.environment,
        state,
    );
    spawn_probe_if_present(
        spec.liveness_probe.as_ref(),
        ProbeKind::Liveness,
        name_handle,
        &spec.working_dir,
        &spec.environment,
        state,
    );
}

/// How a child process ended, carrying enough information to render a
/// human-readable restart separator. `Code` is the normal-exit path;
/// `Signal` is a Unix signal (or `-1` exit code when the platform didn't
/// provide one).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ExitReason {
    Code(i32),
    Signal(i32),
}

impl ExitReason {
    fn describe(self) -> String {
        match self {
            ExitReason::Code(code) => format!("exit code {code}"),
            ExitReason::Signal(sig) => {
                let name = signal_name(sig);
                match name {
                    Some(n) => format!("signal {n}"),
                    None => format!("signal {sig}"),
                }
            }
        }
    }
}

/// Return the canonical `SIG*` name for a signal number, or `None` if
/// `nix` doesn't know about it. Keeps the restart separator readable
/// without requiring a full libc signal table.
fn signal_name(sig: i32) -> Option<&'static str> {
    use nix::sys::signal::Signal;
    Signal::try_from(sig).ok().map(|s| s.as_str())
}

/// Wait for either a kill signal or the child to exit, returning the
/// resulting terminal [`ProcessStatus`] along with an [`ExitReason`]
/// describing the child's outcome (used for the restart separator).
/// On kill, this also runs the spec-driven shutdown sequence (command,
/// signal, SIGKILL).
async fn wait_for_child_exit(
    name_handle: &crate::model::NameHandle,
    spec: &crate::model::ProcessInstanceSpec,
    child: &mut tokio::process::Child,
    kill_rx: &mut watch::Receiver<bool>,
    state: &SharedState,
) -> (ProcessStatus, Option<ExitReason>) {
    tokio::select! {
        _ = kill_rx.changed() => {
            let timeout_override = {
                let guard = state.lock().await;
                guard.shutdown_timeout_override
            };
            shutdown_child(child, spec, timeout_override).await;
            let _ = name_handle; // handle retained for future logging hooks
            (ProcessStatus::Stopped, None)
        }
        wait_res = child.wait() => {
            match wait_res {
                Ok(exit_status) => {
                    let reason = exit_reason_from_status(&exit_status);
                    let status = match reason {
                        ExitReason::Code(code) => ProcessStatus::Exited { code },
                        // ProcessStatus doesn't distinguish signal vs. code
                        // today; collapse to `code=-1` matching prior
                        // behavior, but keep the richer reason for logging.
                        ExitReason::Signal(_) => ProcessStatus::Exited { code: -1 },
                    };
                    (status, Some(reason))
                }
                Err(e) => (
                    ProcessStatus::FailedToStart {
                        reason: format!("wait failed: {e}"),
                    },
                    None,
                ),
            }
        }
    }
}

/// Map a child `ExitStatus` into an [`ExitReason`], preferring the
/// numeric exit code when available and falling back to the signal
/// number on Unix.
fn exit_reason_from_status(status: &std::process::ExitStatus) -> ExitReason {
    if let Some(code) = status.code() {
        return ExitReason::Code(code);
    }
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        if let Some(sig) = status.signal() {
            return ExitReason::Signal(sig);
        }
    }
    ExitReason::Code(-1)
}

/// Format the separator line that is written to the daemon log between
/// consecutive runs of a process. The line is already prefixed with
/// `[name]` so that `decompose logs <name>` filtering picks it up,
/// matching the format the stdout/stderr readers emit.
fn format_restart_separator(
    name: &str,
    reason: ExitReason,
    attempt: u32,
    max: Option<u32>,
) -> String {
    let attempt_part = match max {
        Some(m) => format!("attempt {attempt}/{m}"),
        None => format!("attempt {attempt}"),
    };
    format!(
        "[{name}] --- restarted ({reason}, {attempt_part}) ---",
        reason = reason.describe()
    )
}

/// Given the terminal status of the most recent child instance, decide
/// whether to restart and update the shared state accordingly. Returns
/// `true` if the caller should respawn, or `false` if the lifecycle task
/// should exit.
async fn apply_restart_decision(
    name_handle: &crate::model::NameHandle,
    state: &SharedState,
    final_status: ProcessStatus,
) -> bool {
    with_process_mut(state, name_handle, |runtime| {
        let do_restart = match (&final_status, runtime.spec.restart_policy) {
            (ProcessStatus::Stopped, _) => false,
            (_, RestartPolicy::No) => false,
            (ProcessStatus::Exited { code: 0 }, RestartPolicy::OnFailure) => false,
            (_, RestartPolicy::OnFailure) | (_, RestartPolicy::Always) => {
                match runtime.spec.max_restarts {
                    Some(max) => runtime.restart_count < max,
                    None => true,
                }
            }
        };
        if do_restart {
            runtime.status = ProcessStatus::Restarting;
            runtime.restart_count += 1;
            true
        } else {
            runtime.status = final_status;
            false
        }
    })
    .await
    .unwrap_or(false)
}

/// Main lifecycle loop for a running process: waits for exit, applies the
/// restart policy, backs off, and re-spawns. Runs as its own task; exits
/// when the process reaches a non-restarting terminal state.
async fn process_lifecycle(
    name_handle: crate::model::NameHandle,
    mut spec: crate::model::ProcessInstanceSpec,
    mut child: tokio::process::Child,
    mut kill_rx: watch::Receiver<bool>,
    state: SharedState,
) {
    loop {
        let (final_status, exit_reason) =
            wait_for_child_exit(&name_handle, &spec, &mut child, &mut kill_rx, &state).await;

        let should_restart = apply_restart_decision(&name_handle, &state, final_status).await;
        if !should_restart {
            let name = crate::model::read_name(&name_handle);
            let mut guard = state.lock().await;
            guard.controllers.remove(&name);
            break;
        }

        // Emit a separator line into the daemon log so that humans (and
        // `decompose logs svc`) can visually distinguish the previous run
        // from the next attempt. The separator flows through the same
        // stdout stream the child line-readers use, so name-prefix
        // filtering picks it up unchanged.
        if let Some(reason) = exit_reason {
            let (attempt, max) = with_process(&state, &name_handle, |r| {
                (r.restart_count, r.spec.max_restarts)
            })
            .await
            .unwrap_or((0, None));
            let name = crate::model::read_name(&name_handle);
            println!("{}", format_restart_separator(&name, reason, attempt, max));
        }

        // Backoff delay. Look up the current spec under the lock, since a
        // reload could have swapped it out while we were waiting.
        let backoff = with_process(&state, &name_handle, |r| r.spec.backoff_seconds)
            .await
            .unwrap_or(1);
        sleep(Duration::from_secs(backoff)).await;

        // Pick up any new spec the reload may have installed.
        let next_spec = with_process(&state, &name_handle, |r| r.spec.clone()).await;
        let Some(next_spec) = next_spec else { break };
        spec = next_spec;

        let Some(new_child) =
            spawn_process_child(&name_handle, &spec, &state, SpawnContext::Restart).await
        else {
            let name = crate::model::read_name(&name_handle);
            let mut guard = state.lock().await;
            guard.controllers.remove(&name);
            break;
        };
        child = new_child;
        let pid = child.id().unwrap_or(0);
        with_process_mut(&state, &name_handle, |runtime| {
            runtime.status = ProcessStatus::Running { pid };
            runtime.log_ready = false;
            runtime.ready = false;
            // A freshly spawned process is assumed alive until its
            // liveness probe (if any) proves otherwise — matches the
            // `ProcessRuntime::alive` default documented in model.rs.
            runtime.alive = true;
        })
        .await;

        let ready_pattern: Option<Regex> =
            spec.ready_log_line.as_deref().map(compile_ready_pattern);
        attach_output_readers(&mut child, &name_handle, ready_pattern, state.clone());

        // Fresh kill channel for this restart iteration, replacing the one
        // whose sender was dropped when `broadcast_stop` last fired.
        let (new_kill_tx, new_kill_rx) = watch::channel(false);
        {
            let name = crate::model::read_name(&name_handle);
            let mut guard = state.lock().await;
            guard.controllers.insert(name, new_kill_tx);
        }
        kill_rx = new_kill_rx;
    }
}

/// Spawn tasks that read lines from the child's stdout and stderr pipes,
/// printing them with a `[name]` prefix and optionally matching a
/// `ready_log_line` regex to set the `log_ready` flag on the process runtime.
fn attach_output_readers(
    child: &mut tokio::process::Child,
    name_handle: &crate::model::NameHandle,
    ready_pattern: Option<Regex>,
    state: SharedState,
) {
    let log_ready_flag = Arc::new(AtomicBool::new(false));

    if let Some(stdout) = child.stdout.take() {
        let handle = name_handle.clone();
        let pattern = ready_pattern.clone();
        let flag = log_ready_flag.clone();
        let state_clone = state.clone();
        tokio::spawn(async move {
            let mut lines = BufReader::new(stdout).lines();
            while let Ok(Some(line)) = lines.next_line().await {
                let proc_name = crate::model::read_name(&handle);
                println!("[{proc_name}] {line}");
                if let Some(ref re) = pattern
                    && !flag.load(Ordering::Relaxed)
                    && re.is_match(&line)
                {
                    flag.store(true, Ordering::Relaxed);
                    with_process_mut(&state_clone, &handle, |runtime| {
                        runtime.log_ready = true;
                    })
                    .await;
                }
            }
        });
    }

    if let Some(stderr) = child.stderr.take() {
        let handle = name_handle.clone();
        let pattern = ready_pattern;
        let flag = log_ready_flag;
        let state_clone = state;
        tokio::spawn(async move {
            let mut lines = BufReader::new(stderr).lines();
            while let Ok(Some(line)) = lines.next_line().await {
                let proc_name = crate::model::read_name(&handle);
                eprintln!("[{proc_name}] {line}");
                if let Some(ref re) = pattern
                    && !flag.load(Ordering::Relaxed)
                    && re.is_match(&line)
                {
                    flag.store(true, Ordering::Relaxed);
                    with_process_mut(&state_clone, &handle, |runtime| {
                        runtime.log_ready = true;
                    })
                    .await;
                }
            }
        });
    }
}

async fn shutdown_child(
    child: &mut tokio::process::Child,
    spec: &crate::model::ProcessInstanceSpec,
    timeout_override: Option<u64>,
) {
    let total_timeout =
        Duration::from_secs(timeout_override.unwrap_or(spec.shutdown_timeout_seconds));
    let deadline = tokio::time::Instant::now() + total_timeout;

    // Step 1: Run optional shutdown command. Bound it by the overall
    // shutdown timeout so a hung cleanup script can't block us forever.
    if let Some(ref cmd_str) = spec.shutdown_command {
        match build_shell_command(cmd_str) {
            Ok(mut cmd) => {
                cmd.current_dir(&spec.working_dir).envs(&spec.environment);
                let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
                if remaining.is_zero() {
                    eprintln!(
                        "[{}] shutdown command {:?} skipped: no time budget remaining",
                        spec.name, cmd_str
                    );
                } else {
                    match tokio::time::timeout(remaining, cmd.output()).await {
                        Ok(Ok(output)) => {
                            if !output.status.success() {
                                let code = output
                                    .status
                                    .code()
                                    .map(|c| c.to_string())
                                    .unwrap_or_else(|| "signal".to_string());
                                eprintln!(
                                    "[{}] shutdown command {:?} exited with status {code}",
                                    spec.name, cmd_str
                                );
                            }
                        }
                        Ok(Err(e)) => {
                            eprintln!(
                                "[{}] shutdown command {:?} failed to spawn: {e}",
                                spec.name, cmd_str
                            );
                        }
                        Err(_) => {
                            eprintln!(
                                "[{}] shutdown command {:?} timed out; proceeding to SIGTERM",
                                spec.name, cmd_str
                            );
                        }
                    }
                }
            }
            Err(e) => {
                eprintln!("[{}] shutdown command failed to build: {e}", spec.name);
            }
        }
    }

    // Step 2: Send signal to the process group so backgrounded grandchildren
    // exit too. Each spawned service has its own pgid (set via
    // `cmd.process_group(0)`), and the leader's pid doubles as the pgid.
    let signal = spec.shutdown_signal.unwrap_or(15);
    if let Some(pid) = child.id() {
        #[cfg(unix)]
        {
            use nix::sys::signal::{self, Signal};
            use nix::unistd::Pid;
            if let Ok(sig) = Signal::try_from(signal) {
                let _ = signal::kill(Pid::from_raw(-(pid as i32)), sig);
            }
        }
        #[cfg(not(unix))]
        {
            let _ = signal; // suppress unused warning
            let _ = child.start_kill();
        }
    }

    // Step 3: Wait for the remaining portion of the total timeout. If the
    // shutdown command ate most of it, we'll move on to SIGKILL quickly —
    // which is the right behaviour: the user's time budget is over.
    let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
    let terminated = if remaining.is_zero() {
        false
    } else {
        tokio::time::timeout(remaining, child.wait()).await.is_ok()
    };

    if !terminated {
        // Step 4: Force kill the group (covers grandchildren).
        #[cfg(unix)]
        {
            if let Some(pid) = child.id() {
                use nix::sys::signal::{self, Signal};
                use nix::unistd::Pid;
                let _ = signal::kill(Pid::from_raw(-(pid as i32)), Signal::SIGKILL);
            }
        }
        let _ = child.start_kill();
        let _ = child.wait().await;
    }
}

/// Build a shell command for executing a user-supplied command string.
///
/// Commands come from user-authored config files (trusted input), matching
/// Docker Compose semantics where `command:` is always interpreted by a shell.
/// The shell is configurable via the `COMPOSE_SHELL` env var (default: `sh`).
pub(crate) fn build_shell_command(command: &str) -> Result<TokioCommand> {
    if cfg!(windows) {
        let mut cmd = TokioCommand::new("cmd");
        cmd.arg("/C").arg(command);
        Ok(cmd)
    } else {
        let shell = env::var("COMPOSE_SHELL").unwrap_or_else(|_| "sh".to_string());

        // Validate the shell exists and is plausibly executable.
        let shell_path = Path::new(&shell);
        if shell_path.is_absolute() {
            if !shell_path.exists() {
                anyhow::bail!("shell {shell:?} (from COMPOSE_SHELL) does not exist");
            }
        } else {
            // For bare names, verify they can be found on PATH.
            if which::which(&shell).is_err() {
                anyhow::bail!("shell {shell:?} (from COMPOSE_SHELL) not found on PATH");
            }
        }

        let mut cmd = TokioCommand::new(&shell);
        cmd.arg("-c").arg(command);
        Ok(cmd)
    }
}

/// Resolve a list of service names (base names or replica-qualified names)
/// into the set of runtime instance names in the daemon's process map.
///
/// If `services` is empty, returns all runtime names (sorted).
/// If any service name doesn't match at least one runtime, returns Err with
/// the list of unknown names.
fn resolve_services(
    state: &DaemonState,
    services: &[String],
) -> std::result::Result<Vec<String>, Vec<String>> {
    if services.is_empty() {
        return Ok(state.processes.keys().cloned().collect());
    }

    let mut unknown = Vec::new();
    let mut matched = std::collections::BTreeSet::new();
    for svc in services {
        let mut found = false;
        for (name, runtime) in &state.processes {
            if runtime.spec.base_name == *svc || runtime.spec.name == *svc {
                matched.insert(name.clone());
                found = true;
            }
        }
        if !found {
            unknown.push(svc.clone());
        }
    }

    if unknown.is_empty() {
        Ok(matched.into_iter().collect())
    } else {
        Err(unknown)
    }
}

fn describe_services(services: &[String]) -> String {
    if services.is_empty() {
        "all services".to_string()
    } else {
        services.join(", ")
    }
}

/// Resolve services and convert any unknown-name error into a
/// `Response::Error` so IPC handlers can exit early with `?`-style control
/// flow. Mirrors the check/format used by Stop/Start/Kill/Restart.
fn resolve_services_or_error(
    state: &DaemonState,
    services: &[String],
) -> std::result::Result<Vec<String>, Response> {
    resolve_services(state, services).map_err(|unknown| Response::Error {
        message: format!("unknown service(s): {}", unknown.join(", ")),
    })
}

/// Classification of a service across an old and new config snapshot.
///
/// A service's hash excludes `replicas` (see [`crate::config::compute_config_hash`]),
/// so a pure replica-count change lands in [`ReloadPlan::scaled`] — the daemon
/// adds or drops replica instances without disturbing the ones that remain.
/// Hash divergence always means `changed` (full recreate of every replica),
/// regardless of how the replica count moved.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct ReloadPlan {
    pub added: Vec<String>,
    pub removed: Vec<String>,
    pub changed: Vec<String>,
    pub unchanged: Vec<String>,
    /// Services whose hash is identical but whose replica count changed.
    /// Maps base-name → `(old_count, new_count)`. Handled by the daemon as
    /// spawn-up / stop-highest-index rather than a full recreate.
    pub scaled: BTreeMap<String, (u16, u16)>,
    /// Services whose only change across the reload is the `disabled` flag.
    /// Maps base-name → new `disabled` value. Handled without a recreate:
    /// true → stop the running instance and park it; false → flip Disabled
    /// to Pending so the supervisor launches it.
    pub disabled_toggled: BTreeMap<String, bool>,
}

/// Summary of a single service's hash and replica count, keyed by the stable
/// base-name. Used as a simple input shape for [`compute_reload_plan`] so it
/// can be unit-tested without booting a full daemon.
#[derive(Debug, Clone)]
pub(crate) struct ServiceFingerprint {
    pub config_hash: String,
    pub replicas: u16,
    pub disabled: bool,
}

/// Diff an old set of service fingerprints against a new one. `deps` maps
/// each *new* service to the base-names it depends on; if a removed service
/// is still referenced by a service that remains, returns an error describing
/// the violation — the caller must abort without touching any running
/// processes.
///
/// `force_recreate` promotes every service present in both snapshots to
/// `changed` regardless of hash equality. `no_recreate` demotes every
/// hash-diverged service to `unchanged` (the existing instances keep
/// running). Added and removed services are unaffected by either flag.
/// The caller is expected to enforce that the two flags are mutually
/// exclusive; this function asserts it in debug builds.
///
/// Classification rules for a service present in both snapshots:
///
/// | hash      | replicas  | flags                 | category   |
/// |-----------|-----------|-----------------------|------------|
/// | equal     | equal     | —                     | unchanged  |
/// | equal     | differ    | —                     | scaled     |
/// | equal     | differ    | `force_recreate=true` | changed    |
/// | equal     | differ    | `no_recreate=true`    | scaled     |
/// | differ    | any       | —                     | changed    |
/// | differ    | any       | `no_recreate=true`    | unchanged  |
/// | any       | any       | `force_recreate=true` | changed    |
///
/// `no_recreate` intentionally does NOT block a `scaled` transition:
/// adding or dropping replicas is not a recreate of existing instances,
/// so the flag's guarantee ("don't touch running processes") holds — we
/// only spawn or kill replicas at the tail of the replica set.
pub(crate) fn compute_reload_plan(
    old: &BTreeMap<String, ServiceFingerprint>,
    new: &BTreeMap<String, ServiceFingerprint>,
    deps: &BTreeMap<String, Vec<String>>,
    force_recreate: bool,
    no_recreate: bool,
) -> std::result::Result<ReloadPlan, String> {
    debug_assert!(
        !(force_recreate && no_recreate),
        "force_recreate and no_recreate are mutually exclusive"
    );

    let mut plan = ReloadPlan::default();

    for (name, new_fp) in new {
        match old.get(name) {
            None => plan.added.push(name.clone()),
            Some(old_fp) => {
                let hash_differs = old_fp.config_hash != new_fp.config_hash;
                let replicas_differ = old_fp.replicas != new_fp.replicas;
                let disabled_toggled = old_fp.disabled != new_fp.disabled;

                if force_recreate {
                    // `--force-recreate` overrides everything: recreate all.
                    plan.changed.push(name.clone());
                } else if hash_differs {
                    // Real config change. `--no-recreate` demotes to unchanged;
                    // otherwise full recreate (which also covers any replica-
                    // count delta — the whole service is being rebuilt).
                    if no_recreate {
                        plan.unchanged.push(name.clone());
                    } else {
                        plan.changed.push(name.clone());
                    }
                } else if replicas_differ {
                    // Hash equal, replicas differ → scale. `--no-recreate`
                    // does not block this: scaling adds/drops replicas at the
                    // tail and leaves the others in place.
                    //
                    // Transitions across the `replicas == 1` boundary are
                    // still `scaled`: the daemon renames the single instance
                    // in place (`foo` ↔ `foo[1]`) so the existing process
                    // keeps its pid across a 1 → N or N → 1 reload. See
                    // `handle_reload` for the re-keying under the state lock.
                    plan.scaled
                        .insert(name.clone(), (old_fp.replicas, new_fp.replicas));
                    if disabled_toggled {
                        plan.disabled_toggled.insert(name.clone(), new_fp.disabled);
                    }
                } else if disabled_toggled {
                    // Only the disabled flag moved. Handled without a recreate:
                    // the daemon stops or un-parks existing instances in place.
                    plan.disabled_toggled.insert(name.clone(), new_fp.disabled);
                } else {
                    plan.unchanged.push(name.clone());
                }
            }
        }
    }

    for name in old.keys() {
        if !new.contains_key(name) {
            plan.removed.push(name.clone());
        }
    }

    // Reject the request if a service that's being removed is still a
    // dependency of a service that remains (or is newly added). We check the
    // *new* dep graph — i.e. what the user's updated config asks for.
    for (svc, svc_deps) in deps {
        for dep in svc_deps {
            if plan.removed.contains(dep) {
                return Err(format!(
                    "cannot reload: service {svc:?} still depends on {dep:?}, which is removed in the new config"
                ));
            }
        }
    }

    plan.added.sort();
    plan.removed.sort();
    plan.changed.sort();
    plan.unchanged.sort();
    Ok(plan)
}

async fn handle_client(stream: Stream, state: SharedState) -> Result<()> {
    let (read_half, mut write_half) = tokio::io::split(stream);
    let mut reader = BufReader::new(read_half);
    let mut line = String::new();
    let read = reader
        .read_line(&mut line)
        .await
        .context("failed to read request line")?;
    if read == 0 {
        return Ok(());
    }

    let req: Request = serde_json::from_str(line.trim()).context("invalid request json")?;

    // Refresh the orphan-watchdog activity clock on every request (not on
    // connection accept), so long-lived connections that drip-feed requests
    // also keep the daemon alive.
    {
        let mut guard = state.lock().await;
        guard.last_client_activity = Instant::now();
    }

    let response = match req {
        Request::Ping => {
            let guard = state.lock().await;
            Response::Pong {
                pid: std::process::id(),
                instance: guard.instance.clone(),
            }
        }
        Request::Ps => handle_ps(&state).await,
        Request::Down { timeout_seconds } => {
            let mut guard = state.lock().await;
            guard.shutdown_timeout_override = timeout_seconds;
            guard.request_shutdown();
            Response::Ack {
                message: "shutdown requested".to_string(),
            }
        }
        Request::Stop { services } => handle_stop(&state, services).await,
        Request::Start { services } => handle_start(&state, services).await,
        Request::Kill { services, signal } => handle_kill(&state, services, signal).await,
        Request::Restart { services } => handle_restart(&state, services).await,
        Request::RemoveOrphans { keep } => handle_remove_orphans(&state, keep).await,
        Request::Reload {
            force_recreate,
            no_recreate,
            remove_orphans,
            no_start,
        } => {
            handle_reload(
                state.clone(),
                force_recreate,
                no_recreate,
                remove_orphans,
                no_start,
            )
            .await
        }
        Request::ServiceRunState { name } => handle_service_run_state(&state, name).await,
    };

    let payload = serde_json::to_string(&response)?;
    write_half.write_all(payload.as_bytes()).await?;
    write_half.write_all(b"\n").await?;
    write_half.flush().await?;
    Ok(())
}

/// Snapshot every tracked process into a `Response::Ps`. Read-only; holds the
/// state lock just long enough to clone the runtime fields.
async fn handle_ps(state: &SharedState) -> Response {
    let guard = state.lock().await;
    let processes = guard
        .processes
        .values()
        .map(ProcessSnapshot::from)
        .collect::<Vec<_>>();

    Response::Ps {
        pid: std::process::id(),
        instance: guard.instance.clone(),
        processes,
    }
}

/// Stop the named services (or all services when `services` is empty).
/// Returns an error response if any name is unknown; otherwise triggers the
/// supervisor to begin shutdown and acks immediately.
async fn handle_stop(state: &SharedState, services: Vec<String>) -> Response {
    let mut guard = state.lock().await;
    match resolve_services_or_error(&guard, &services) {
        Err(resp) => resp,
        Ok(names) => {
            guard.stop_instances(&names);
            Response::Ack {
                message: format!("stopping {}", describe_services(&services)),
            }
        }
    }
}

/// Start the named services (or all services when `services` is empty). Walks
/// the dependency graph so transitively-depended-on services also get flipped
/// out of their terminal state, matching the behaviour `up` relies on.
async fn handle_start(state: &SharedState, services: Vec<String>) -> Response {
    let mut guard = state.lock().await;
    // Empty `services` means "start every eligible service" (e.g. the
    // implicit Start that follows `up`'s Reload). In that mode, services
    // with `disabled: true` must stay parked — they are eligible only when
    // the user names them explicitly.
    let explicit_start = !services.is_empty();
    match resolve_services_or_error(&guard, &services) {
        Err(resp) => resp,
        Ok(names) => {
            // Collect the set of services to start, including their
            // transitive dependencies that are also in a terminal state
            // (e.g. NotStarted). This ensures `start serviceB` also
            // brings up serviceB's deps if they haven't been launched.
            let mut to_start: std::collections::BTreeSet<String> = names.into_iter().collect();
            let mut queue: std::collections::VecDeque<String> = to_start.iter().cloned().collect();
            while let Some(name) = queue.pop_front() {
                if let Some(runtime) = guard.processes.get(&name) {
                    for dep_base in runtime.spec.depends_on.keys() {
                        // Find all runtime instances matching the dep base name
                        let dep_names: Vec<String> = guard
                            .processes
                            .iter()
                            .filter(|(_, r)| r.spec.base_name == *dep_base)
                            .map(|(n, _)| n.clone())
                            .collect();
                        for dep_name in dep_names {
                            if to_start.insert(dep_name.clone()) {
                                queue.push_back(dep_name);
                            }
                        }
                    }
                }
            }

            let mut started = 0;
            for name in &to_start {
                if let Some(runtime) = guard.processes.get_mut(name)
                    && runtime.status.is_terminal()
                {
                    // Skip disabled services under a blanket start: only
                    // an explicit `start NAME` (or a transitive dep pulled
                    // in by one) overrides the disabled flag.
                    if !explicit_start && runtime.spec.disabled {
                        continue;
                    }
                    runtime.status = ProcessStatus::Pending;
                    runtime.log_ready = false;
                    runtime.ready = false;
                    // `alive` defaults to true for a fresh
                    // instance — see ProcessRuntime docs.
                    runtime.alive = true;
                    // Explicit `start` overrides the disabled flag for
                    // this instance; otherwise the supervisor filter
                    // would immediately skip the Pending runtime and
                    // the service would never launch. Transitive deps
                    // pulled in above are overridden too so `start A`
                    // can bring up a disabled dep.
                    if explicit_start {
                        runtime.spec.disabled = false;
                    }
                    started += 1;
                }
            }
            if started == 0 {
                Response::Ack {
                    message: format!("{} already running", describe_services(&services)),
                }
            } else {
                Response::Ack {
                    message: format!("starting {}", describe_services(&services)),
                }
            }
        }
    }
}

/// Send `signal` to every Running instance of the named services. Unknown
/// services error out; services that aren't currently running are silently
/// skipped (the signal only has a target for actively-Running PIDs).
async fn handle_kill(state: &SharedState, services: Vec<String>, signal: i32) -> Response {
    let guard = state.lock().await;
    match resolve_services_or_error(&guard, &services) {
        Err(resp) => resp,
        Ok(names) => {
            for name in &names {
                if let Some(runtime) = guard.processes.get(name)
                    && let ProcessStatus::Running { pid } = runtime.status
                {
                    #[cfg(unix)]
                    {
                        use nix::sys::signal::{self, Signal};
                        use nix::unistd::Pid;
                        if let Ok(sig) = Signal::try_from(signal) {
                            // Signal the whole process group so
                            // backgrounded grandchildren exit too.
                            let _ = signal::kill(Pid::from_raw(-(pid as i32)), sig);
                        }
                    }
                }
            }
            Response::Ack {
                message: format!("killed {}", describe_services(&services)),
            }
        }
    }
}

/// Restart the named services by stopping them and spawning a background task
/// that waits for each to reach a terminal state before flipping them back to
/// `Pending` so the supervisor respawns them.
async fn handle_restart(state: &SharedState, services: Vec<String>) -> Response {
    let mut guard = state.lock().await;
    match resolve_services_or_error(&guard, &services) {
        Err(resp) => resp,
        Ok(names) => {
            guard.stop_instances(&names);
            drop(guard);
            // Spawn a task to wait for stop then reset to Pending
            let state_clone = state.clone();
            let names_clone = names.clone();
            tokio::spawn(async move {
                wait_for_terminal(&state_clone, &names_clone, Duration::from_millis(50), 200).await;
                let mut guard = state_clone.lock().await;
                for name in &names_clone {
                    if let Some(runtime) = guard.processes.get_mut(name) {
                        runtime.status = ProcessStatus::Pending;
                        runtime.log_ready = false;
                        runtime.ready = false;
                        runtime.alive = true;
                    }
                }
            });
            Response::Ack {
                message: format!("restarting {}", describe_services(&services)),
            }
        }
    }
}

/// Stop and drop every process whose base-name is not in `keep`. Any orphan
/// instance is first sent a stop signal; a background task then waits for the
/// instances to go terminal before removing them from the process map.
async fn handle_remove_orphans(state: &SharedState, keep: Vec<String>) -> Response {
    let mut guard = state.lock().await;
    let keep_set: std::collections::HashSet<&str> = keep.iter().map(|s| s.as_str()).collect();
    let orphans: Vec<String> = guard
        .processes
        .keys()
        .filter(|name| {
            let base = guard.processes[name.as_str()].spec.base_name.as_str();
            !keep_set.contains(base)
        })
        .cloned()
        .collect();
    guard.stop_instances(&orphans);
    // Spawn a task to wait for orphans to stop then remove them
    if !orphans.is_empty() {
        let state_clone = state.clone();
        let orphans_clone = orphans.clone();
        tokio::spawn(async move {
            wait_for_terminal(&state_clone, &orphans_clone, Duration::from_millis(50), 200).await;
            let mut guard = state_clone.lock().await;
            for name in &orphans_clone {
                guard.processes.remove(name);
                guard.controllers.remove(name);
            }
        });
    }
    let msg = if orphans.is_empty() {
        "no orphan processes found".to_string()
    } else {
        format!("removing orphan(s): {}", orphans.join(", "))
    };
    Response::Ack { message: msg }
}

/// Report whether `name` matches any tracked service (by base-name or
/// fully-qualified replica name) and whether any matching replica is Running.
/// Used by `exec` to preflight-check before spawning.
async fn handle_service_run_state(state: &SharedState, name: String) -> Response {
    let guard = state.lock().await;
    let mut known = false;
    let mut any_running = false;
    for runtime in guard.processes.values() {
        if runtime.spec.base_name == name || runtime.spec.name == name {
            known = true;
            if matches!(runtime.status, ProcessStatus::Running { .. }) {
                any_running = true;
                break;
            }
        }
    }
    Response::ServiceRunState { known, any_running }
}

/// Re-read the daemon's config from disk, compute a reload plan against the
/// currently-tracked process map, and execute the plan.
///
/// On parse/validate failure: returns `Response::Error` and leaves running
/// processes untouched. On a removed-but-still-depended-on violation: same.
/// Otherwise: stops `changed` instances (they'll be respawned with the new
/// spec by the supervisor), optionally stops+removes `removed` services
/// when `remove_orphans` is true (otherwise they're left running with a
/// warning, matching Docker Compose default behaviour), and inserts
/// `added`/`changed` entries as `Pending` — or `NotStarted` when
/// `no_start` is true — so the supervisor loop launches them in
/// dependency order (or leaves them parked for a later `start`).
async fn handle_reload(
    state: SharedState,
    force_recreate: bool,
    no_recreate: bool,
    remove_orphans: bool,
    no_start: bool,
) -> Response {
    // Defence-in-depth: clap enforces this, but if a malformed IPC request
    // slips through with both flags set, refuse rather than silently picking
    // one interpretation.
    if force_recreate && no_recreate {
        return Response::Error {
            message: "reload: --force-recreate and --no-recreate are mutually exclusive"
                .to_string(),
        };
    }
    // Snapshot the daemon-launch args so we don't hold the state lock across
    // disk I/O.
    let (cwd, config_files, env_files, disable_dotenv) = {
        let guard = state.lock().await;
        (
            guard.cwd.clone(),
            guard.config_files.clone(),
            guard.env_files.clone(),
            guard.disable_dotenv,
        )
    };

    // 1. Load and interpolate the new config. Any failure here aborts the
    //    reload without touching any running processes.
    let dotenv = match load_dotenv_files(&cwd, &env_files, disable_dotenv) {
        Ok(d) => d,
        Err(e) => {
            return Response::Error {
                message: format!("reload: failed to load env files: {e:#}"),
            };
        }
    };

    let mut new_config = match load_and_merge_configs(&config_files) {
        Ok(c) => c,
        Err(e) => {
            return Response::Error {
                message: format!("reload: invalid config: {e:#}"),
            };
        }
    };
    apply_interpolation(&mut new_config);
    if let Err(e) = crate::config::validate_project_paths(&new_config, &cwd) {
        return Response::Error {
            message: format!("reload: invalid config: {e:#}"),
        };
    }

    let new_process_map = build_process_instances(&new_config, &cwd, &dotenv);

    // 2. Build fingerprints keyed by base-name. Replicas share a config_hash,
    //    so collapsing to base-name is sufficient — and replica-count changes
    //    fall out naturally in the diff because we also include `replicas`
    //    (counted by iterating the instance map).
    let new_fingerprints: BTreeMap<String, ServiceFingerprint> = {
        let mut map: BTreeMap<String, (String, u16, bool)> = BTreeMap::new();
        for runtime in new_process_map.values() {
            let entry = map
                .entry(runtime.spec.base_name.clone())
                .or_insert_with(|| (runtime.spec.config_hash.clone(), 0, runtime.spec.disabled));
            entry.1 += 1;
        }
        map.into_iter()
            .map(|(k, (hash, replicas, disabled))| {
                (
                    k,
                    ServiceFingerprint {
                        config_hash: hash,
                        replicas,
                        disabled,
                    },
                )
            })
            .collect()
    };

    let new_deps: BTreeMap<String, Vec<String>> = new_process_map
        .values()
        .map(|r| {
            (
                r.spec.base_name.clone(),
                r.spec.depends_on.keys().cloned().collect(),
            )
        })
        .collect();

    // 3. Snapshot current state under the lock.
    let old_fingerprints: BTreeMap<String, ServiceFingerprint> = {
        let guard = state.lock().await;
        let mut map: BTreeMap<String, (String, u16, bool)> = BTreeMap::new();
        for runtime in guard.processes.values() {
            let entry = map
                .entry(runtime.spec.base_name.clone())
                .or_insert_with(|| (runtime.spec.config_hash.clone(), 0, runtime.spec.disabled));
            entry.1 += 1;
        }
        map.into_iter()
            .map(|(k, (hash, replicas, disabled))| {
                (
                    k,
                    ServiceFingerprint {
                        config_hash: hash,
                        replicas,
                        disabled,
                    },
                )
            })
            .collect()
    };

    // 4. Diff. A removed-but-still-depended-on violation returns early with
    //    an error; nothing has been touched yet.
    let plan = match compute_reload_plan(
        &old_fingerprints,
        &new_fingerprints,
        &new_deps,
        force_recreate,
        no_recreate,
    ) {
        Ok(p) => p,
        Err(msg) => return Response::Error { message: msg },
    };

    // 5. Execute the plan. We only touch running state past this point.

    // 5a. Collect the instance names whose lifecycle we're about to disrupt:
    //     the `changed` set always, plus the `removed` set when the caller
    //     asked us to clean orphans up. Both groups go through the same
    //     stop-then-wait pattern so we can splice in replacements (or drop
    //     the entries entirely, for removed orphans) without racing a
    //     still-shutting-down child.
    let changed_instances: Vec<String> = {
        let guard = state.lock().await;
        guard
            .processes
            .iter()
            .filter(|(_, r)| plan.changed.contains(&r.spec.base_name))
            .map(|(n, _)| n.clone())
            .collect()
    };

    let removed_instances: Vec<String> = if remove_orphans {
        let guard = state.lock().await;
        guard
            .processes
            .iter()
            .filter(|(_, r)| plan.removed.contains(&r.spec.base_name))
            .map(|(n, _)| n.clone())
            .collect()
    } else {
        Vec::new()
    };

    // Scale-down: for every `scaled` entry whose new count is strictly lower,
    // mark the tail replicas (indices `new+1..=old`) for stop+remove. The
    // lower-indexed replicas stay untouched.
    //
    // Special case `new_count == 1`: the surviving replica is `foo[1]`, which
    // must be renamed to the unqualified `foo` (see `rename_plan` below).
    // We still drop everything at index >= 2.
    let scaled_down_instances: Vec<String> = {
        let guard = state.lock().await;
        let mut to_drop = Vec::new();
        for (base, (old_count, new_count)) in &plan.scaled {
            if new_count < old_count {
                for (name, runtime) in &guard.processes {
                    if &runtime.spec.base_name == base && runtime.spec.replica > *new_count {
                        to_drop.push(name.clone());
                    }
                }
            }
        }
        to_drop
    };

    // Rename plan for scale transitions that cross the `replicas == 1` naming
    // boundary. See `build_process_instances`: a single-replica service uses
    // the unqualified base name (`foo`) while a multi-replica service uses
    // `foo[1]`, `foo[2]`, ….
    //
    //   1 → N: the surviving instance `foo`    → `foo[1]`; `foo[2..=N]` spawn
    //   N → 1: the surviving instance `foo[1]` → `foo`;    `foo[2..=N]` stop
    //
    // Tuples are `(old_name, new_name)`; applied atomically under the state
    // lock in the splice block below.
    let rename_plan: Vec<(String, String)> = plan
        .scaled
        .iter()
        .filter_map(|(base, (old_count, new_count))| {
            if *old_count == 1 && *new_count >= 2 {
                Some((base.clone(), format!("{base}[1]")))
            } else if *old_count >= 2 && *new_count == 1 {
                Some((format!("{base}[1]"), base.clone()))
            } else {
                None
            }
        })
        .collect();

    // Instances whose service just flipped disabled: false → true. We stop
    // them here so the splice block below can flip their status to Disabled
    // and clear their running state.
    let disabled_now_true_instances: Vec<String> = {
        let guard = state.lock().await;
        guard
            .processes
            .iter()
            .filter(|(_, r)| {
                plan.disabled_toggled
                    .get(&r.spec.base_name)
                    .copied()
                    .unwrap_or(false)
            })
            .map(|(n, _)| n.clone())
            .collect()
    };

    let to_stop: Vec<String> = changed_instances
        .iter()
        .chain(removed_instances.iter())
        .chain(scaled_down_instances.iter())
        .chain(disabled_now_true_instances.iter())
        .cloned()
        .collect();

    if !to_stop.is_empty() {
        let mut guard = state.lock().await;
        guard.stop_instances(&to_stop);
    }

    // 5b. Wait for the stopped instances to reach a terminal state so the
    //     replacement spawn isn't racing a still-shutting-down child. Poll
    //     briefly; the per-process shutdown timeout applies inside each
    //     controller's lifecycle task, so the outer wait bound just needs to
    //     exceed the worst-case shutdown.
    if !to_stop.is_empty() {
        wait_for_terminal(&state, &to_stop, Duration::from_millis(50), 1200).await;
    }

    // 5c. Under the lock: drop old changed + orphaned + scaled-down entries
    //     and their controllers, apply any rename transitions (1↔N boundary
    //     crossings preserve the existing pid in place), splice in new
    //     `added`/`changed` entries from `new_process_map`, and spawn any
    //     new replicas for scale-up transitions (leaving the existing
    //     replicas in place). With `no_start`, park every freshly inserted
    //     runtime in `NotStarted` so the supervisor leaves them alone;
    //     otherwise they land as `Pending` and the supervisor's next tick
    //     picks them up in dep order.
    let (n_added, n_changed, n_removed, n_scaled_services, replica_delta, n_renamed) = {
        let mut guard = state.lock().await;
        for name in &changed_instances {
            guard.processes.remove(name);
            guard.controllers.remove(name);
        }
        for name in &removed_instances {
            guard.processes.remove(name);
            guard.controllers.remove(name);
        }
        for name in &scaled_down_instances {
            guard.processes.remove(name);
            guard.controllers.remove(name);
        }

        // Apply in-place renames for 1↔N scale transitions. Both the map keys
        // and the shared `name_handle` inside the runtime are updated under
        // the same lock acquisition, so any daemon task that next reads the
        // handle sees the new name and looks up the correctly-keyed entry.
        let mut renamed = 0usize;
        for (old_name, new_name) in &rename_plan {
            let Some(mut runtime) = guard.processes.remove(old_name) else {
                // The surviving instance may have exited between the snapshot
                // and here; nothing to rename.
                continue;
            };
            // Update the `name` carried by the spec (visible through `ps`)
            // and the shared cell every task task consults before touching
            // `processes` / `controllers`.
            runtime.spec.name = new_name.clone();
            if let Ok(mut guard_name) = runtime.name_handle.write() {
                *guard_name = new_name.clone();
            }
            guard.processes.insert(new_name.clone(), runtime);
            if let Some(ctrl) = guard.controllers.remove(old_name) {
                guard.controllers.insert(new_name.clone(), ctrl);
            }
            renamed += 1;
        }

        let mut new_instances_added = 0usize;
        let mut new_instances_changed = 0usize;
        for (instance_name, runtime) in &new_process_map {
            let is_added = plan.added.contains(&runtime.spec.base_name);
            let is_changed = plan.changed.contains(&runtime.spec.base_name);
            // For `scaled` services, only insert replicas whose index exceeds
            // the old count — those are the newly-spawned tail entries.
            // Lower-indexed replicas already exist and must not be touched.
            //
            // For 1 → N transitions (`old_count == 1`), the `old_count` is
            // inclusive of the one existing instance (now renamed to
            // `foo[1]`), so the comparison correctly excludes replica 1 and
            // spawns only indices 2..=N. For N → 1 transitions the condition
            // `new_count > old_count` is false, so nothing is spliced in
            // here; the surviving instance is handled by `rename_plan`.
            let scaled_up_tail =
                plan.scaled
                    .get(&runtime.spec.base_name)
                    .is_some_and(|(old_count, new_count)| {
                        new_count > old_count && runtime.spec.replica > *old_count
                    });
            if !(is_added || is_changed || scaled_up_tail) {
                continue;
            }
            let mut runtime = runtime.clone();
            if no_start && matches!(runtime.status, ProcessStatus::Pending) {
                runtime.status = ProcessStatus::NotStarted;
            }
            guard.processes.insert(instance_name.clone(), runtime);
            if is_added {
                new_instances_added += 1;
            } else if is_changed {
                new_instances_changed += 1;
            }
            // scaled_up_tail contributes to `replica_delta` via plan.scaled,
            // so it doesn't need a separate counter here.
        }
        // Apply disabled-flag toggles on services that were neither recreated
        // nor scaled out of existence. For each toggled base name, walk every
        // runtime of that service:
        //   new disabled == true  → spec.disabled=true, status=Disabled.
        //   new disabled == false → spec.disabled=false, Disabled → Pending.
        let mut n_disabled_toggled = 0usize;
        for (base, new_disabled) in &plan.disabled_toggled {
            // Scaled services may have had their runtimes recreated (hash
            // diverged) or dropped entirely; nothing to toggle for those.
            if plan.changed.contains(base) {
                continue;
            }
            for runtime in guard.processes.values_mut() {
                if runtime.spec.base_name != *base {
                    continue;
                }
                if *new_disabled {
                    runtime.spec.disabled = true;
                    runtime.status = ProcessStatus::Disabled;
                    runtime.log_ready = false;
                    runtime.ready = false;
                    runtime.alive = true;
                } else {
                    runtime.spec.disabled = false;
                    if matches!(runtime.status, ProcessStatus::Disabled) {
                        runtime.status = ProcessStatus::Pending;
                        runtime.log_ready = false;
                        runtime.ready = false;
                        runtime.alive = true;
                    }
                }
                n_disabled_toggled += 1;
            }
        }
        let _ = n_disabled_toggled; // reported below via plan.disabled_toggled.len()

        let removed_count = if remove_orphans {
            removed_instances.len()
        } else {
            plan.removed.len()
        };
        // Net replica delta across all `scaled` services, positive for
        // scale-up, negative for scale-down (reported as a signed count in
        // the ack so operators can see at a glance).
        let delta: i32 = plan
            .scaled
            .values()
            .map(|(old_count, new_count)| i32::from(*new_count) - i32::from(*old_count))
            .sum();
        (
            new_instances_added,
            new_instances_changed,
            removed_count,
            plan.scaled.len(),
            delta,
            renamed,
        )
    };

    if !plan.removed.is_empty() && !remove_orphans {
        eprintln!(
            "reload: orphan service(s) no longer in config (left running): [{}]",
            plan.removed.join(", ")
        );
    }

    let removed_label = if remove_orphans { "removed" } else { "orphan" };
    let delta_sign = if replica_delta >= 0 { "+" } else { "" };
    let rename_suffix = if n_renamed > 0 {
        format!(", {n_renamed} renamed")
    } else {
        String::new()
    };
    Response::Ack {
        message: format!(
            "reloaded: +{n_added} added, {n_changed} changed, \
             {n_scaled_services} scaled ({delta_sign}{replica_delta} replicas), \
             {n_removed} {removed_label}{rename_suffix}",
        ),
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::path::PathBuf;

    use super::*;
    use crate::model::{
        DependencyCondition, ProcessInstanceSpec, ProcessRuntime, ProcessStatus, RestartPolicy,
    };

    fn runtime_with(base: &str, status: ProcessStatus, started_once: bool) -> ProcessRuntime {
        ProcessRuntime {
            spec: ProcessInstanceSpec {
                name: base.to_string(),
                base_name: base.to_string(),
                replica: 1,
                command: "echo".to_string(),
                description: None,
                working_dir: PathBuf::from("/tmp"),
                environment: BTreeMap::new(),
                depends_on: BTreeMap::new(),
                ready_log_line: None,
                restart_policy: RestartPolicy::No,
                backoff_seconds: 1,
                max_restarts: None,
                shutdown_signal: None,
                shutdown_timeout_seconds: 10,
                shutdown_command: None,
                readiness_probe: None,
                liveness_probe: None,
                disabled: false,
                config_hash: String::new(),
            },
            status,
            started_once,
            log_ready: false,
            restart_count: 0,
            ready: false,
            alive: true,
            name_handle: crate::model::make_name_handle(base.to_string()),
        }
    }

    #[test]
    fn dependencies_require_all_replicas_to_satisfy_condition() {
        let mut snapshot = BTreeMap::new();
        snapshot.insert("db[1]".to_string(), {
            let mut r = runtime_with("db", ProcessStatus::Exited { code: 0 }, true);
            r.spec.name = "db[1]".to_string();
            r.spec.replica = 1;
            r
        });
        snapshot.insert("db[2]".to_string(), {
            let mut r = runtime_with("db", ProcessStatus::Exited { code: 1 }, true);
            r.spec.name = "db[2]".to_string();
            r.spec.replica = 2;
            r
        });

        let mut candidate = runtime_with("api", ProcessStatus::Pending, false);
        candidate.spec.depends_on.insert(
            "db".to_string(),
            DependencyCondition::ProcessCompletedSuccessfully,
        );
        assert!(!dependencies_met(&candidate, &snapshot));

        if let Some(db2) = snapshot.get_mut("db[2]") {
            db2.status = ProcessStatus::Exited { code: 0 };
        }
        assert!(dependencies_met(&candidate, &snapshot));
    }

    #[test]
    fn process_started_condition_uses_started_once() {
        let mut snapshot = BTreeMap::new();
        snapshot.insert(
            "db".to_string(),
            runtime_with("db", ProcessStatus::Pending, false),
        );

        let mut candidate = runtime_with("api", ProcessStatus::Pending, false);
        candidate
            .spec
            .depends_on
            .insert("db".to_string(), DependencyCondition::ProcessStarted);
        assert!(!dependencies_met(&candidate, &snapshot));

        if let Some(db) = snapshot.get_mut("db") {
            db.started_once = true;
            db.status = ProcessStatus::Running { pid: 42 };
        }
        assert!(dependencies_met(&candidate, &snapshot));
    }

    #[test]
    fn process_healthy_condition_uses_ready_flag_not_alive() {
        // Regression: when a service configures both readiness and liveness
        // probes, the flags must be independent. `process_healthy` gates on
        // readiness alone, so a process that is `alive` but not `ready`
        // must NOT satisfy the dependency.
        let mut snapshot = BTreeMap::new();
        let mut db = runtime_with("db", ProcessStatus::Running { pid: 42 }, true);
        db.ready = false;
        db.alive = true;
        snapshot.insert("db".to_string(), db);

        let mut candidate = runtime_with("api", ProcessStatus::Pending, false);
        candidate
            .spec
            .depends_on
            .insert("db".to_string(), DependencyCondition::ProcessHealthy);
        assert!(
            !dependencies_met(&candidate, &snapshot),
            "alive-but-not-ready must not satisfy process_healthy"
        );

        // Flip readiness on; liveness unchanged — should now satisfy.
        if let Some(db) = snapshot.get_mut("db") {
            db.ready = true;
        }
        assert!(dependencies_met(&candidate, &snapshot));

        // And the inverse: ready but not alive (liveness probe failing)
        // still satisfies `process_healthy` — liveness drives restarts, not
        // dependency gating.
        if let Some(db) = snapshot.get_mut("db") {
            db.alive = false;
        }
        assert!(
            dependencies_met(&candidate, &snapshot),
            "process_healthy must ignore alive; only readiness gates it"
        );
    }

    #[test]
    fn process_log_ready_condition_uses_log_ready_flag() {
        let mut snapshot = BTreeMap::new();
        let mut db = runtime_with("db", ProcessStatus::Running { pid: 42 }, true);
        db.log_ready = false;
        snapshot.insert("db".to_string(), db);

        let mut candidate = runtime_with("api", ProcessStatus::Pending, false);
        candidate
            .spec
            .depends_on
            .insert("db".to_string(), DependencyCondition::ProcessLogReady);
        assert!(!dependencies_met(&candidate, &snapshot));

        if let Some(db) = snapshot.get_mut("db") {
            db.log_ready = true;
        }
        assert!(dependencies_met(&candidate, &snapshot));
    }

    fn fp(hash: &str, replicas: u16) -> ServiceFingerprint {
        ServiceFingerprint {
            config_hash: hash.to_string(),
            replicas,
            disabled: false,
        }
    }

    fn fp_disabled(hash: &str, replicas: u16, disabled: bool) -> ServiceFingerprint {
        ServiceFingerprint {
            config_hash: hash.to_string(),
            replicas,
            disabled,
        }
    }

    #[test]
    fn reload_plan_classifies_added_removed_changed_unchanged() {
        let mut old = BTreeMap::new();
        old.insert("api".to_string(), fp("h_api_v1", 1));
        old.insert("db".to_string(), fp("h_db", 1));
        old.insert("cache".to_string(), fp("h_cache", 1));

        let mut new = BTreeMap::new();
        // changed: hash differs
        new.insert("api".to_string(), fp("h_api_v2", 1));
        // unchanged
        new.insert("db".to_string(), fp("h_db", 1));
        // added
        new.insert("worker".to_string(), fp("h_worker", 1));
        // "cache" absent from new -> removed

        let deps: BTreeMap<String, Vec<String>> = BTreeMap::new();
        let plan = compute_reload_plan(&old, &new, &deps, false, false).expect("no dep violations");

        assert_eq!(plan.added, vec!["worker".to_string()]);
        assert_eq!(plan.removed, vec!["cache".to_string()]);
        assert_eq!(plan.changed, vec!["api".to_string()]);
        assert_eq!(plan.unchanged, vec!["db".to_string()]);
    }

    #[test]
    fn reload_plan_scales_pure_replica_count_change() {
        // 2 → 3: no naming boundary crossing, hash equal → scaled.
        let mut old = BTreeMap::new();
        old.insert("worker".to_string(), fp("same_hash", 2));

        let mut new = BTreeMap::new();
        new.insert("worker".to_string(), fp("same_hash", 3));

        let plan = compute_reload_plan(&old, &new, &BTreeMap::new(), false, false)
            .expect("no dep violations");
        assert!(
            plan.changed.is_empty(),
            "pure replica change should not recreate: {plan:?}"
        );
        assert!(
            plan.unchanged.is_empty(),
            "pure replica change should not be unchanged: {plan:?}"
        );
        assert_eq!(plan.scaled.get("worker"), Some(&(2, 3)));
    }

    #[test]
    fn reload_plan_scale_down_classifies_as_scaled() {
        // 5 → 2: no naming boundary crossing.
        let mut old = BTreeMap::new();
        old.insert("worker".to_string(), fp("same_hash", 5));

        let mut new = BTreeMap::new();
        new.insert("worker".to_string(), fp("same_hash", 2));

        let plan = compute_reload_plan(&old, &new, &BTreeMap::new(), false, false)
            .expect("no dep violations");
        assert!(plan.changed.is_empty());
        assert_eq!(plan.scaled.get("worker"), Some(&(5, 2)));
    }

    #[test]
    fn reload_plan_replica_change_plus_hash_change_is_changed() {
        // Hash divergence dominates: full recreate regardless of replica delta.
        let mut old = BTreeMap::new();
        old.insert("worker".to_string(), fp("h_v1", 2));

        let mut new = BTreeMap::new();
        new.insert("worker".to_string(), fp("h_v2", 3));

        let plan = compute_reload_plan(&old, &new, &BTreeMap::new(), false, false)
            .expect("no dep violations");
        assert_eq!(plan.changed, vec!["worker".to_string()]);
        assert!(plan.scaled.is_empty());
    }

    #[test]
    fn reload_plan_force_recreate_overrides_scale() {
        let mut old = BTreeMap::new();
        old.insert("worker".to_string(), fp("same_hash", 2));

        let mut new = BTreeMap::new();
        new.insert("worker".to_string(), fp("same_hash", 3));

        let plan = compute_reload_plan(&old, &new, &BTreeMap::new(), true, false)
            .expect("force_recreate valid");
        assert_eq!(plan.changed, vec!["worker".to_string()]);
        assert!(plan.scaled.is_empty());
    }

    #[test]
    fn reload_plan_no_recreate_does_not_block_scale() {
        // `--no-recreate` is about not recreating existing instances. Scaling
        // only adds/drops tail replicas, so it should still apply.
        let mut old = BTreeMap::new();
        old.insert("worker".to_string(), fp("same_hash", 2));

        let mut new = BTreeMap::new();
        new.insert("worker".to_string(), fp("same_hash", 3));

        let plan = compute_reload_plan(&old, &new, &BTreeMap::new(), false, true)
            .expect("no_recreate valid");
        assert!(plan.changed.is_empty());
        assert_eq!(plan.scaled.get("worker"), Some(&(2, 3)));
    }

    #[test]
    fn reload_plan_replica_1_boundary_is_scaled_with_rename() {
        // 1 ↔ N transitions cross the replica-name boundary (`foo` vs `foo[1]`)
        // but are still classified as `scaled` — the daemon renames the
        // surviving instance in place rather than recreating it.
        for (old_count, new_count) in [(1u16, 2u16), (2, 1), (1, 3), (3, 1)] {
            let mut old = BTreeMap::new();
            old.insert("worker".to_string(), fp("same_hash", old_count));
            let mut new = BTreeMap::new();
            new.insert("worker".to_string(), fp("same_hash", new_count));

            let plan = compute_reload_plan(&old, &new, &BTreeMap::new(), false, false)
                .expect("valid transition");
            assert!(
                plan.changed.is_empty(),
                "{old_count}→{new_count} should not be a full recreate"
            );
            assert_eq!(
                plan.scaled.get("worker"),
                Some(&(old_count, new_count)),
                "{old_count}→{new_count} should be scaled"
            );
        }
    }

    #[test]
    fn reload_plan_rejects_removed_service_still_depended_on() {
        let mut old = BTreeMap::new();
        old.insert("api".to_string(), fp("h_api", 1));
        old.insert("db".to_string(), fp("h_db", 1));

        // "db" is gone in the new config, but "api" (which remains) still
        // lists it as a dep.
        let mut new = BTreeMap::new();
        new.insert("api".to_string(), fp("h_api", 1));

        let mut deps: BTreeMap<String, Vec<String>> = BTreeMap::new();
        deps.insert("api".to_string(), vec!["db".to_string()]);

        let err = compute_reload_plan(&old, &new, &deps, false, false)
            .expect_err("must reject removed-but-still-depended-on");
        assert!(err.contains("api"), "error mentions dependent: {err}");
        assert!(err.contains("db"), "error mentions removed dep: {err}");
    }

    #[test]
    fn reload_plan_allows_removal_when_no_remaining_service_depends_on_it() {
        let mut old = BTreeMap::new();
        old.insert("api".to_string(), fp("h_api", 1));
        old.insert("legacy".to_string(), fp("h_legacy", 1));

        let mut new = BTreeMap::new();
        new.insert("api".to_string(), fp("h_api", 1));

        // api does not depend on legacy — removing legacy is fine.
        let deps: BTreeMap<String, Vec<String>> = BTreeMap::new();
        let plan =
            compute_reload_plan(&old, &new, &deps, false, false).expect("removal is allowed");
        assert_eq!(plan.removed, vec!["legacy".to_string()]);
    }

    #[test]
    fn reload_plan_force_recreate_promotes_unchanged_to_changed() {
        let mut old = BTreeMap::new();
        old.insert("api".to_string(), fp("same_hash", 1));
        old.insert("db".to_string(), fp("h_db", 1));

        let mut new = BTreeMap::new();
        // hash-equal in both — without force_recreate this would be unchanged.
        new.insert("api".to_string(), fp("same_hash", 1));
        new.insert("db".to_string(), fp("h_db", 1));

        let deps: BTreeMap<String, Vec<String>> = BTreeMap::new();
        let plan = compute_reload_plan(&old, &new, &deps, true, false)
            .expect("force_recreate is a valid option");

        assert_eq!(
            plan.changed,
            vec!["api".to_string(), "db".to_string()],
            "force_recreate promotes every still-present service to changed"
        );
        assert!(
            plan.unchanged.is_empty(),
            "force_recreate should leave nothing in unchanged"
        );
    }

    #[test]
    fn reload_plan_no_recreate_demotes_hash_diverged_to_unchanged() {
        let mut old = BTreeMap::new();
        old.insert("api".to_string(), fp("h_api_v1", 1));
        old.insert("db".to_string(), fp("h_db", 1));

        let mut new = BTreeMap::new();
        // api's hash differs — normally changed, but no_recreate keeps it.
        new.insert("api".to_string(), fp("h_api_v2", 1));
        new.insert("db".to_string(), fp("h_db", 1));
        // newly-added service should still be added regardless of no_recreate.
        new.insert("worker".to_string(), fp("h_worker", 1));

        let deps: BTreeMap<String, Vec<String>> = BTreeMap::new();
        let plan = compute_reload_plan(&old, &new, &deps, false, true)
            .expect("no_recreate is a valid option");

        assert!(
            plan.changed.is_empty(),
            "no_recreate should keep every still-present service as unchanged"
        );
        assert_eq!(
            plan.unchanged,
            vec!["api".to_string(), "db".to_string()],
            "hash-diverged api was demoted to unchanged"
        );
        assert_eq!(
            plan.added,
            vec!["worker".to_string()],
            "added services aren't affected by no_recreate"
        );
    }

    #[test]
    fn reload_plan_default_flags_preserve_existing_behavior() {
        let mut old = BTreeMap::new();
        old.insert("api".to_string(), fp("h_api_v1", 1));
        old.insert("db".to_string(), fp("h_db", 1));

        let mut new = BTreeMap::new();
        new.insert("api".to_string(), fp("h_api_v2", 1));
        new.insert("db".to_string(), fp("h_db", 1));

        let deps: BTreeMap<String, Vec<String>> = BTreeMap::new();
        let plan =
            compute_reload_plan(&old, &new, &deps, false, false).expect("default flags are valid");

        assert_eq!(plan.changed, vec!["api".to_string()]);
        assert_eq!(plan.unchanged, vec!["db".to_string()]);
    }

    #[test]
    fn reload_plan_records_disabled_toggle_without_recreate() {
        let mut old = BTreeMap::new();
        old.insert("api".to_string(), fp_disabled("h_api", 1, false));
        old.insert("worker".to_string(), fp_disabled("h_w", 1, true));

        let mut new = BTreeMap::new();
        new.insert("api".to_string(), fp_disabled("h_api", 1, true));
        new.insert("worker".to_string(), fp_disabled("h_w", 1, false));

        let deps: BTreeMap<String, Vec<String>> = BTreeMap::new();
        let plan = compute_reload_plan(&old, &new, &deps, false, false).expect("ok");

        // Neither service hash changed, so neither is `changed` or `unchanged`.
        assert!(plan.changed.is_empty());
        assert!(plan.unchanged.is_empty());
        assert_eq!(plan.disabled_toggled.get("api"), Some(&true));
        assert_eq!(plan.disabled_toggled.get("worker"), Some(&false));
    }

    #[test]
    fn restart_separator_formats_exit_code_with_max() {
        let line = format_restart_separator("api", ExitReason::Code(1), 2, Some(5));
        assert_eq!(line, "[api] --- restarted (exit code 1, attempt 2/5) ---");
    }

    #[test]
    fn restart_separator_formats_exit_code_without_max() {
        let line = format_restart_separator("api", ExitReason::Code(1), 2, None);
        assert_eq!(line, "[api] --- restarted (exit code 1, attempt 2) ---");
    }

    #[test]
    fn restart_separator_formats_signal_with_known_name() {
        // SIGTERM is 15 on every Unix platform we care about.
        let line = format_restart_separator("api", ExitReason::Signal(15), 1, None);
        assert_eq!(line, "[api] --- restarted (signal SIGTERM, attempt 1) ---");
    }

    #[test]
    fn restart_separator_formats_unknown_signal() {
        // A signal number nix doesn't know about falls back to the number.
        let line = format_restart_separator("worker", ExitReason::Signal(999), 3, Some(10));
        assert_eq!(
            line,
            "[worker] --- restarted (signal 999, attempt 3/10) ---"
        );
    }

    #[test]
    fn restart_separator_preserves_process_name_prefix_for_filtering() {
        // The `[name]` prefix is what `decompose logs NAME` uses to filter,
        // so it must exactly match the stdout/stderr reader format.
        let line = format_restart_separator("my-service", ExitReason::Code(0), 1, None);
        assert!(
            line.starts_with("[my-service] "),
            "expected name-prefixed line, got {line:?}"
        );
    }
}