autumn-cli 0.10.0

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

use notify_debouncer_mini::{DebouncedEventKind, new_debouncer};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::time::Duration;

/// Debounce interval for checking the shutdown flag in the watch loop.
const SHUTDOWN_CHECK_INTERVAL_MS: u64 = 200;

/// Set to `true` by the SIGINT handler to request a clean shutdown.
static SHUTDOWN_REQUESTED: AtomicBool = AtomicBool::new(false);

/// Default debounce interval for file change events.
const DEBOUNCE_MS: u64 = 500;

/// Top-level files that participate in change routing.
const WATCH_FILES: &[&str] = &[
    "autumn.toml",
    "Cargo.toml",
    "Cargo.lock",
    "build.rs",
    "tailwind.config.js",
];

/// Directories that are always watched recursively, regardless of config.
const DEFAULT_WATCH_DIRS: &[&str] = &["src", "static", "templates", "migrations"];

/// Path of the project config file relative to the dev server's working directory.
const AUTUMN_TOML: &str = "autumn.toml";

/// `[dev]` section of `autumn.toml`. Unknown keys are ignored so future
/// additions to the section don't break older CLIs.
#[derive(Debug, Clone, Default, Deserialize)]
struct DevConfig {
    /// Extra directories to watch recursively, in addition to the defaults.
    /// Paths are relative to the project root.
    #[serde(default)]
    watch_dirs: Vec<String>,
}

/// Minimal slice of `autumn.toml` used to extract the `[dev]` section without
/// pulling in the full `autumn` config crate.
#[derive(Debug, Default, Deserialize)]
struct AutumnTomlDevSlice {
    #[serde(default)]
    dev: DevConfig,
}

const DEV_RELOAD_ENV: &str = "AUTUMN_DEV_RELOAD";
const DEV_RELOAD_STATE_ENV: &str = "AUTUMN_DEV_RELOAD_STATE";
const DEV_RELOAD_STATE_FILE: &str = "live-reload.json";

/// Environment variable naming the cooperative-shutdown file, mirrored from
/// `autumn_web::app::SHUTDOWN_SIGNAL_FILE_ENV`.
///
/// Mirrored rather than imported at the definition site for symmetry with this
/// module's other wire constants; `dev_shutdown_env_var_matches_the_runtime_constant`
/// pins the two together so a rename on either side fails the build's tests
/// rather than silently breaking the Windows dev loop.
// The cooperative-stop machinery below is the NON-UNIX stop path (#1616), but it
// is compiled and unit-tested on every platform on purpose: Windows is the one
// platform this project's contributors and most of its CI never run
// interactively, so logic that only compiled there would be logic nobody ever
// exercised before a user did. `allow(dead_code)` on Unix is the price of that
// coverage — the alternative is `cfg(not(unix))` guards that hide the code from
// Linux CI entirely, which is how the orphaned-Postgres bug survived.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
const DEV_SHUTDOWN_SIGNAL_ENV: &str = "AUTUMN_SHUTDOWN_SIGNAL_FILE";

/// Filename parts of the cooperative-shutdown file, written beside the
/// live-reload state. The dev-loop process id goes between them — see
/// [`child_paths_in`].
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
const DEV_SHUTDOWN_SIGNAL_PREFIX: &str = "dev-shutdown.";
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
const DEV_SHUTDOWN_SIGNAL_SUFFIX: &str = ".signal";

/// Mirror of [`crate::serve::SERVE_READY_FILE_ENV`]; pinned to it by a test.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
const SERVE_READY_FILE_ENV: &str = "AUTUMN_SERVE_READY_FILE";

/// Filename parts of this dev session's ready file — the app writes its
/// resolved drain budget here, and the dev loop's process id keeps two
/// concurrent `autumn dev` runs from reading each other's.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
const DEV_READY_FILE_PREFIX: &str = "dev-ready.";
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
const DEV_READY_FILE_SUFFIX: &str = ".state";

/// Longest time a managed-Postgres stop can take.
///
/// This value equals `STARTUP_TIMEOUT` in `autumn_web::managed_pg`.
/// `postgresql_embedded` uses that limit for `pg_ctl stop` too.
/// The CLI cannot import the constant. A test checks that both values match.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
const MANAGED_PG_STOP_CEILING: Duration = Duration::from_secs(60);

/// Extra time on top of the stop ceiling.
///
/// The app polls for the stop signal every 100 ms. The app must also exit
/// after the stop ends. A busy machine adds more delay.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
const DELIVERY_AND_EXIT_MARGIN: Duration = Duration::from_secs(15);

/// Extra time added to the app's drain budget before `autumn dev` kills the app.
///
/// The `on_shutdown` hooks run inside the drain budget.
/// `emergency_stop_async` runs after the drain and has no time limit.
/// Its worst case is a full managed-Postgres stop.
/// The headroom is that stop limit plus a margin. A slow stop can then finish.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
const COOPERATIVE_STOP_HOOK_HEADROOM: Duration =
    MANAGED_PG_STOP_CEILING.saturating_add(DELIVERY_AND_EXIT_MARGIN);

/// The longest a stop waits for an app that is still starting.
///
/// The app reads the signal file only after it starts. Startup includes
/// managed Postgres `initdb` and migrations. An early stop waits for the app
/// to start, then runs its normal budget. The CI cold start budget is eight
/// minutes. This cap is higher. At the cap, the stop runs its normal budget
/// anyway.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
const COOPERATIVE_STOP_BOOT_CAP: Duration = Duration::from_mins(15);

/// The cooperative-stop budget for an app whose configured graceful-drain
/// budget is `drain_secs` (`prestop_grace_secs + shutdown_timeout_secs`).
///
/// A fixed constant was wrong here. An external stop takes `DrainCause::Signal`,
/// which runs the app's full lifecycle — readiness flip, prestop grace, drain —
/// and only then its `on_shutdown` hooks. Under the prod defaults (grace 5 +
/// timeout 30) an app is still legitimately shutting down at t=35s, so a
/// ten-second kill would reintroduce the orphaned postmaster this change exists
/// to fix, on a perfectly valid configuration.
///
/// Saturating: `drain_secs` comes from user config (`[server]` keys or
/// `AUTUMN_SERVER__*`), and wrapping would produce a tiny budget that hard-kills
/// instantly — the failure mode, arrived at by arithmetic.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
const fn cooperative_stop_budget(drain_secs: u64) -> Duration {
    Duration::from_secs(drain_secs).saturating_add(COOPERATIVE_STOP_HOOK_HEADROOM)
}

/// The stop budget recorded when the currently-running child was spawned, in
/// seconds. `0` means "nothing recorded".
///
/// `autumn.toml` is a watched file, so the stop that follows an edit runs
/// against the NEW config while the child being stopped is still running under
/// the old one. Recording at spawn keeps the two in step; re-resolving at stop
/// would grade the outgoing child against config it never saw — and a half-saved
/// `autumn.toml` would collapse to the defaults, force-killing an app that is
/// still legitimately draining.
static CHILD_STOP_BUDGET_SECS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// Record the budget for the child about to be spawned.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn record_child_stop_budget(budget: Duration) {
    CHILD_STOP_BUDGET_SECS.store(budget.as_secs(), Ordering::SeqCst);
}

/// The budget recorded at the last spawn, if any.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn recorded_child_stop_budget() -> Option<Duration> {
    match CHILD_STOP_BUDGET_SECS.load(Ordering::SeqCst) {
        0 => None,
        secs => Some(Duration::from_secs(secs)),
    }
}

/// The budget to stop the running child with, most authoritative first.
///
/// 1. `reported` — what the app itself said its drain budget is. Beats anything
///    the CLI can derive: an app using `AppBuilder::with_config_loader` can
///    resolve a budget no amount of TOML/env reading reproduces.
/// 2. `recorded` — resolved from config when this child was spawned. Used
///    before the app has finished booting, and never re-read at stop time, so a
///    just-edited (or half-saved) config cannot shorten the window the running
///    child is actually using.
/// 3. `resolve_now` — last resort, when neither is available.
///
/// Pure so those precedence rules are testable directly, including the one that
/// matters most: with a budget already in hand, the config is not consulted.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn stop_budget_for_running_child(
    reported: Option<Duration>,
    recorded: Option<Duration>,
    resolve_now: impl FnOnce() -> Duration,
) -> Duration {
    reported.or(recorded).unwrap_or_else(resolve_now)
}

/// The selected package's directory, resolved once per run.
///
/// `find_manifest_dir` runs `cargo metadata`, which contends with the
/// dependency audit for Cargo's package-cache lock. The package never changes
/// during a run, so a restart reuses the first answer.
fn selected_member_dir(package: Option<&str>) -> Option<PathBuf> {
    static DIR: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();
    DIR.get_or_init(|| package.and_then(find_manifest_dir))
        .clone()
}

/// The directory the app reads its config from: the selected package, else
/// `AUTUMN_MANIFEST_DIR`, else `.`. This is the order the app itself uses.
fn package_dir(package: Option<&str>) -> PathBuf {
    package_dir_from(selected_member_dir(package))
}

/// [`package_dir`] for a member directory that is already resolved.
fn package_dir_from(member_dir: Option<PathBuf>) -> PathBuf {
    member_dir
        .or_else(|| {
            std::env::var_os("AUTUMN_MANIFEST_DIR")
                .filter(|dir| !dir.is_empty())
                .map(PathBuf::from)
        })
        .unwrap_or_else(|| PathBuf::from("."))
}

/// The directories `autumn dev` watches: the project root, and the selected
/// member when it is elsewhere.
static WATCH_ROOTS: std::sync::OnceLock<Vec<PathBuf>> = std::sync::OnceLock::new();

/// Record the watched roots, in the plain and the canonical form: the watcher
/// may report either.
fn register_watch_roots(cwd: &Path, member_dir: Option<&Path>) {
    let mut roots = Vec::new();
    for dir in std::iter::once(cwd).chain(member_dir) {
        roots.push(dir.to_path_buf());
        if let Ok(canonical) = dir.canonicalize() {
            roots.push(canonical);
        }
    }
    roots.dedup();
    let _ = WATCH_ROOTS.set(roots);
}

/// `path` without the most specific of `roots` that contains it, or `path`
/// itself. When roots nest, the member under the workspace, the longest one
/// wins: it leaves the shortest remainder.
fn strip_watch_root<'a>(path: &'a Path, roots: &[PathBuf]) -> &'a Path {
    roots
        .iter()
        .filter_map(|root| path.strip_prefix(root).ok())
        .min_by_key(|rest| rest.components().count())
        .unwrap_or(path)
}

/// The member directory to watch for `.env` edits, if it is not the project
/// root, which is already watched.
fn member_dir_to_watch(member_dir: &Path, cwd: &Path) -> Option<PathBuf> {
    let same = match (member_dir.canonicalize(), cwd.canonicalize()) {
        (Ok(member), Ok(root)) => member == root,
        _ => false,
    };
    (!same).then(|| member_dir.to_path_buf())
}

/// This app's cooperative-stop budget, resolved from its own configuration.
///
/// Delegates to the same profile-aware resolver `autumn serve stop` uses, so the
/// two stop paths cannot disagree about how long the app is entitled to take.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn resolve_cooperative_stop_budget(package: Option<&str>) -> Duration {
    let base_dir = package_dir(package);
    // `autumn dev` always builds in debug, so the default profile is `dev`.
    // `AUTUMN_ENV` or `AUTUMN_PROFILE` still wins.
    let profile = crate::serve::effective_profile(None, false);
    stop_budget_in(&base_dir, &profile)
}

/// The stop budget for the app whose manifest is in `base_dir`.
///
/// Reads `.env` from `base_dir`, as the app does. The CLI does not change its
/// own environment. A plain `std::env` read would miss an `AUTUMN_SERVER__*`
/// value that is set only in `.env`. Then the CLI would kill an app that is
/// still draining. Shell variables win over `.env`. If `.env` is bad, use the
/// plain environment. Do not fail the stop.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn stop_budget_in(base_dir: &Path, profile: &str) -> Duration {
    // The app normalizes aliases and case (`development`, `DEV`), and `.env`
    // loads by the normalized name. Do the same, or `.env` is skipped here.
    let profile =
        autumn_web::config::normalize_profile_name(profile).unwrap_or_else(|| "dev".to_owned());
    let profile = profile.as_str();
    let denv: Box<dyn autumn_web::config::Env> =
        match autumn_web::dotenv::os_env_with_dotenv_in(base_dir, profile) {
            Ok(env) => Box::new(env),
            Err(_) => Box::new(autumn_web::config::OsEnv),
        };
    let (prestop, shutdown) =
        crate::serve::resolve_shutdown_budget_from(base_dir, Some(profile), &|key| {
            denv.var(key).ok().filter(|value| !value.trim().is_empty())
        });
    cooperative_stop_budget(prestop.saturating_add(shutdown))
}

/// How the dev loop's app child was stopped.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StopOutcome {
    /// The app drained and exited on its own, so its `on_shutdown` hooks ran —
    /// including managed Postgres teardown.
    Graceful,
    /// The app did not exit within the budget and was force-killed. Its hooks
    /// may not have run; the caller reports this rather than hiding it.
    Escalated,
    /// The request could not be delivered at all (the signal file was not
    /// writable), so the app was force-killed without ever being asked. Kept
    /// distinct from [`Self::Escalated`] so the warning blames the dev setup
    /// rather than accusing the app of ignoring a request it never received.
    Unreachable,
    /// The app's `autumn-web` predates the signal file (#2458), so it was
    /// force-killed at once. Waiting could not have helped.
    Unsupported,
    /// There was no child to stop.
    NotRunning,
}

/// Whether the running child watches the shutdown-signal file.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ShutdownSupport {
    /// The child's ready file carries the capability marker.
    Supported,
    /// The child wrote a budget-only ready file: an `autumn-web` that predates
    /// the signal file.
    Unsupported,
    /// No report yet. A slow boot looks the same as an old child, so the caller
    /// keeps the cooperative wait.
    Unknown,
}

/// Read the child's shutdown support from its ready-file contents.
///
/// The marker proves support. Without it, only a budget-only file proves an old
/// child: the signal file shipped in the same release as the endpoint line, so
/// a file with an endpoint line is an app that drains, only one that predates
/// the marker. Anything else is `Unknown`, which keeps the safe cooperative wait.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn shutdown_support_from_ready(contents: Option<&str>) -> ShutdownSupport {
    let Some(text) = contents else {
        return ShutdownSupport::Unknown;
    };
    if autumn_web::app::serve_ready_advertises_shutdown_signal(text) {
        return ShutdownSupport::Supported;
    }
    let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty());
    let budget_only =
        lines.next().is_some_and(|l| l.parse::<u64>().is_ok()) && lines.next().is_none();
    if budget_only {
        ShutdownSupport::Unsupported
    } else {
        ShutdownSupport::Unknown
    }
}

/// [`shutdown_support_from_ready`] for the ready file on disk.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn child_shutdown_support(ready_file: &Path) -> ShutdownSupport {
    shutdown_support_from_ready(std::fs::read_to_string(ready_file).ok().as_deref())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ChangeEffect {
    Ignore,
    BrowserReloadOnly,
    TailwindOnly,
    RestartOnly,
    BuildRestart,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
enum ReloadKind {
    #[default]
    None,
    Css,
    Full,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
struct ChangePlan {
    build: bool,
    restart: bool,
    tailwind: bool,
    reload: ReloadKind,
}

impl ChangePlan {
    fn is_empty(self) -> bool {
        !self.build && !self.restart && !self.tailwind && self.reload == ReloadKind::None
    }

    fn register(&mut self, effect: ChangeEffect) {
        match effect {
            ChangeEffect::Ignore => {}
            ChangeEffect::BrowserReloadOnly => {
                self.reload = self.reload.max(ReloadKind::Full);
            }
            ChangeEffect::TailwindOnly => {
                self.tailwind = true;
                self.reload = self.reload.max(ReloadKind::Css);
            }
            ChangeEffect::RestartOnly => {
                self.restart = true;
                self.reload = self.reload.max(ReloadKind::Full);
            }
            ChangeEffect::BuildRestart => {
                self.build = true;
                self.restart = true;
                self.tailwind = false;
                self.reload = ReloadKind::Full;
            }
        }
    }

    const fn finalize(mut self) -> Self {
        if self.build {
            self.tailwind = false;
        }
        self
    }
}

#[derive(Debug)]
struct DevReloadState {
    path: PathBuf,
    version: u64,
    /// The build-error payload for the currently-broken Rust build, if any.
    ///
    /// When set, every ordinary [`Self::signal`] re-emits it so a non-build
    /// reload (CSS/Tailwind/static save routed through the watch loop) keeps
    /// the compile-error overlay up instead of dismissing it and reloading the
    /// still-broken stale app. Only a green Rust build clears it, via
    /// [`Self::signal_build_success`].
    active_build_error: Option<(Vec<BuildDiagnostic>, bool)>,
}

impl DevReloadState {
    fn initialize() -> Result<Self, String> {
        let path = resolve_dev_reload_state_path()?;
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
        }

        let state = Self {
            path,
            version: 0,
            active_build_error: None,
        };
        state.write(ReloadKind::Full)?;
        Ok(state)
    }

    fn path(&self) -> &Path {
        &self.path
    }

    /// Signal an ordinary reload (CSS/Tailwind/full). Bumps the version and
    /// writes fresh state.
    ///
    /// If a Rust build is currently broken (`active_build_error` is `Some`),
    /// the build-error payload is CARRIED FORWARD into the new state so the
    /// overlay survives — a CSS/Tailwind/static save while the code doesn't
    /// compile must not dismiss the overlay and reload the stale app. Only a
    /// green Rust build ([`Self::signal_build_success`]) clears it.
    fn signal(&mut self, kind: ReloadKind) -> Result<(), String> {
        if kind == ReloadKind::None {
            return Ok(());
        }

        self.version = self
            .version
            .checked_add(1)
            .ok_or("live reload version overflowed")?;

        if let Some((diagnostics, stale)) = self.active_build_error.as_ref() {
            let (diagnostics, stale) = (diagnostics.clone(), *stale);
            self.write_build_error(&diagnostics, stale)
        } else {
            self.write(kind)
        }
    }

    /// Bump the version and write a full-reload state carrying compiler
    /// diagnostics so the browser client renders a compile-error overlay
    /// instead of reloading into a broken/stale page.
    ///
    /// The payload is also stashed in `active_build_error` so subsequent
    /// ordinary [`Self::signal`] calls carry it forward and keep the overlay
    /// up until a green build clears it.
    ///
    /// `stale` is true when a previously-built binary is still serving (the
    /// browser is looking at a now-outdated page); false on a cold start (or
    /// on Windows, where the old binary must be stopped before rebuilding)
    /// where no server is up yet.
    fn signal_build_error(
        &mut self,
        diagnostics: &[BuildDiagnostic],
        stale: bool,
    ) -> Result<(), String> {
        self.version = self
            .version
            .checked_add(1)
            .ok_or("live reload version overflowed")?;

        self.active_build_error = Some((diagnostics.to_vec(), stale));
        self.write_build_error(diagnostics, stale)
    }

    /// Clear a previously-signaled build error after a GREEN Rust build, then
    /// write ordinary reload state (with NO `build_error` field) so the client
    /// dismisses the overlay and reloads into the freshly-built app.
    ///
    /// This is the ONLY path that clears the overlay: an ordinary
    /// [`Self::signal`] carries an active build error forward instead.
    fn signal_build_success(&mut self, kind: ReloadKind) -> Result<(), String> {
        self.active_build_error = None;
        // A successful build always warrants a reload to pick up the new
        // binary, so treat `None` as a full reload rather than a no-op.
        let kind = if kind == ReloadKind::None {
            ReloadKind::Full
        } else {
            kind
        };

        self.version = self
            .version
            .checked_add(1)
            .ok_or("live reload version overflowed")?;
        self.write(kind)
    }

    /// Write full-reload state carrying a `build_error` payload.
    fn write_build_error(
        &self,
        diagnostics: &[BuildDiagnostic],
        stale: bool,
    ) -> Result<(), String> {
        let body = serde_json::json!({
            "version": self.version,
            "kind": "full",
            "build_error": {
                "diagnostics": diagnostics,
                "stale": stale,
            },
        });
        std::fs::write(&self.path, body.to_string())
            .map_err(|e| format!("failed to write {}: {e}", self.path.display()))
    }

    fn write(&self, kind: ReloadKind) -> Result<(), String> {
        let kind = match kind {
            ReloadKind::None | ReloadKind::Full => "full",
            ReloadKind::Css => "css",
        };
        let body = serde_json::json!({
            "version": self.version,
            "kind": kind,
        });
        std::fs::write(&self.path, body.to_string())
            .map_err(|e| format!("failed to write {}: {e}", self.path.display()))
    }
}

/// How long `autumn dev` keeps looking for a dependency verdict (issue #1633).
///
/// Nothing waits on the audit. It starts after the initial build — running it
/// beside the build makes its `cargo metadata` contend with Cargo's
/// package-cache lock and slow the build itself — and the watch loop then polls
/// for the result without blocking. A verdict that has not arrived by this
/// deadline is dropped, its auditor process is killed, and the dev loop says
/// nothing. A watchdog thread enforces the deadline, so it holds while the
/// loop is busy in a rebuild. The process is not killed before the deadline,
/// except when the dev session ends.
const DEPENDENCY_AUDIT_DEADLINE: Duration = Duration::from_secs(30);

/// Startup lines for an evaluation that may not have finished in time.
fn dependency_startup_lines(eval: Option<&crate::deps::Evaluation>) -> Vec<String> {
    eval.map(crate::deps::dev_lines).unwrap_or_default()
}

/// A dependency evaluation running beside the dev loop.
///
/// Polled, never awaited: [`report`](Self::report) returns immediately whether
/// or not a verdict has arrived, so the watch loop never stalls on the auditor.
struct DependencyAudit {
    receiver: mpsc::Receiver<crate::deps::Evaluation>,
    stop: crate::deps::StopHandle,
    deadline: std::time::Instant,
    done: bool,
}

impl DependencyAudit {
    fn start(root: &Path) -> Self {
        let running = crate::deps::spawn_evaluation_with_deadline(root, DEPENDENCY_AUDIT_DEADLINE);
        Self {
            receiver: running.receiver,
            stop: running.stop,
            deadline: std::time::Instant::now() + DEPENDENCY_AUDIT_DEADLINE,
            done: false,
        }
    }

    /// Print the verdict once, if one has arrived. Never blocks.
    fn report(&mut self) {
        if self.done {
            return;
        }
        match self.receiver.try_recv() {
            Ok(evaluation) => {
                self.done = true;
                for line in dependency_startup_lines(Some(&evaluation)) {
                    eprintln!("{line}");
                }
            }
            Err(mpsc::TryRecvError::Disconnected) => self.done = true,
            // Still running. Give up once the deadline passes so a wedged
            // auditor cannot keep this poll alive for the whole session.
            Err(mpsc::TryRecvError::Empty) => {
                if std::time::Instant::now() >= self.deadline {
                    self.done = true;
                    // Do not leave the auditor to contend with the next build.
                    self.stop.stop();
                }
            }
        }
    }
}

impl Drop for DependencyAudit {
    /// Ending the dev session ends an audit still in flight.
    fn drop(&mut self) {
        if !self.done {
            self.stop.stop();
        }
    }
}

/// Run the dev server with file watching.
pub fn run(package: Option<&str>, show_config: bool) {
    eprintln!("\u{1F342} autumn dev\n");

    // Warn when maintenance mode is currently active so the operator is not
    // surprised by 503 responses during local development.
    if let Some(config) = crate::maintenance::check_status(None) {
        eprintln!("  \u{26A0}\u{FE0F}  MAINTENANCE MODE IS ON");
        if let Some(msg) = &config.message {
            eprintln!("     Message: {msg}");
        }
        eprintln!("     Run `autumn maintenance off` to disable.");
        eprintln!();
    }

    // Register SIGINT handler so Ctrl+C triggers a graceful shutdown instead
    // of immediately terminating the process (and leaving the child running).
    if let Err(err) = ctrlc::set_handler(move || {
        SHUTDOWN_REQUESTED.store(true, Ordering::SeqCst);
    }) {
        eprintln!("  Warning: failed to set Ctrl-C handler: {err}");
    }

    let mut reload_state = match DevReloadState::initialize() {
        Ok(state) => Some(state),
        Err(error) => {
            eprintln!("  Warning: live reload disabled: {error}");
            None
        }
    };
    // Initial build. There is no prior server here (cold start), so a browser
    // overlay isn't reachable — the CLI doesn't know the app's port and no
    // process is up to answer the state endpoint. We still record the failure
    // in the state file (harmless, and dismissed by the first green build);
    // the terminal errors remain the primary feedback for this case.
    let (built, diagnostics) = cargo_build_capturing(package);

    if !built {
        eprintln!("\u{2717} Initial build failed. Fix errors and save to retry.\n");
        if let Some(state) = reload_state.as_mut()
            && let Err(error) = state.signal_build_error(&diagnostics, false)
        {
            eprintln!("  Warning: live reload signal failed: {error}");
        }
    }

    let binary = find_binary(package, false);
    let mut child = start_server(
        &binary,
        package,
        reload_state.as_ref().map(DevReloadState::path),
        show_config,
    );

    // Dependency findings (issue #1633). Started once every synchronous step
    // that runs Cargo is done — the build, and `find_binary`'s own `cargo
    // metadata` — because cargo-deny runs `cargo metadata` too and the two
    // contend for Cargo's package-cache lock. From here it is only polled,
    // never awaited, so nothing delays startup or the rebuild loop. Quiet by
    // default: an advisory-clean, policy-clean tree adds nothing.
    // Resolve the member directory first: `cargo metadata` contends with the audit.
    let member_dir = selected_member_dir(package);
    let mut dependency_audit = DependencyAudit::start(Path::new("."));

    let normalized_dirs = sanitize_custom_watch_dirs(load_dev_config(Path::new(AUTUMN_TOML)));
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let custom_watch_dirs = resolve_custom_watch_dirs(&normalized_dirs, &cwd);
    register_watch_roots(&cwd, member_dir.as_deref());

    // Set up file watcher
    let (tx, rx) = mpsc::channel();
    let mut debouncer = new_debouncer(Duration::from_millis(DEBOUNCE_MS), tx)
        .expect("failed to create file watcher");

    let watcher = debouncer.watcher();

    // Watch the default directories.
    for dir in DEFAULT_WATCH_DIRS {
        let path = Path::new(dir);
        if path.exists()
            && let Err(e) = watcher.watch(path, notify::RecursiveMode::Recursive)
        {
            eprintln!("  Warning: could not watch {dir}/: {e}");
        }
    }

    // Watch any additional directories from `[dev] watch_dirs` in autumn.toml.
    for dir in &custom_watch_dirs {
        let display = dir.relative.display();
        if let Err(e) = watcher.watch(&dir.relative, notify::RecursiveMode::Recursive) {
            eprintln!("  Warning: could not watch {display}/: {e}");
        } else {
            eprintln!("  Watching custom directory: {display}/");
        }
    }

    // Watch the project root for config and build script changes.
    if let Err(e) = watcher.watch(Path::new("."), notify::RecursiveMode::NonRecursive) {
        eprintln!("  Warning: could not watch project root: {e}");
    }

    // A selected workspace member keeps its `.env` in its own directory, which
    // the app and the stop budget both read.
    if let Some(dir) = member_dir.and_then(|dir| member_dir_to_watch(&dir, &cwd))
        && let Err(e) = watcher.watch(&dir, notify::RecursiveMode::NonRecursive)
    {
        eprintln!("  Warning: could not watch {}: {e}", dir.display());
    }

    eprintln!("  Watching for changes... (press Ctrl+C to stop)\n");

    // Main event loop – periodically checks the shutdown flag so that a
    // Ctrl+C breaks the loop and triggers
    // graceful server shutdown via `stop_server` below.
    loop {
        if SHUTDOWN_REQUESTED.load(Ordering::SeqCst) {
            eprintln!("\n  Shutting down...");
            break;
        }

        dependency_audit.report();

        if !process_events(
            &rx,
            &custom_watch_dirs,
            package,
            &mut child,
            reload_state.as_mut(),
            show_config,
        ) {
            break;
        }
    }

    stop_server(&mut child, package);
}

/// Read `[dev]` from `autumn.toml`. Missing file or unparseable content
/// degrades gracefully to defaults so `autumn dev` still works.
fn load_dev_config(path: &Path) -> DevConfig {
    let Ok(contents) = std::fs::read_to_string(path) else {
        return DevConfig::default();
    };
    parse_dev_config(&contents).unwrap_or_else(|err| {
        eprintln!(
            "  Warning: failed to parse [dev] section in {}: {err}",
            path.display()
        );
        DevConfig::default()
    })
}

fn parse_dev_config(toml_str: &str) -> Result<DevConfig, toml::de::Error> {
    let parsed: AutumnTomlDevSlice = toml::from_str(toml_str)?;
    Ok(parsed.dev)
}

/// Normalize and validate a single `[dev].watch_dirs` entry.
///
/// Returns the normalized path string (with `./` segments collapsed) on
/// success, or `Err(reason)` if the entry must be rejected. Reasons cover
/// absolute paths, parent traversal (`..`), `target/`, and dotted
/// directories (e.g. `.git`) — any of which could subscribe huge or wrong
/// trees and flood the debouncer.
fn normalize_watch_dir(raw: &str) -> Result<String, &'static str> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Err("entry is empty");
    }

    let path = Path::new(trimmed);
    if path.is_absolute() {
        return Err("absolute paths are not allowed; use a project-relative path");
    }

    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            std::path::Component::Normal(part) => {
                if part == std::ffi::OsStr::new("target") {
                    return Err("`target` is reserved for cargo build artifacts");
                }
                if part.to_string_lossy().starts_with('.') {
                    return Err("dotted directories (e.g. `.git`) are not allowed; \
                         the watcher would still pump their events");
                }
                normalized.push(part);
            }
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                return Err("parent traversal (`..`) is not allowed");
            }
            std::path::Component::RootDir | std::path::Component::Prefix(_) => {
                return Err("absolute paths are not allowed; use a project-relative path");
            }
        }
    }

    if normalized.as_os_str().is_empty() {
        return Err("entry resolves to an empty path");
    }

    Ok(normalized.to_string_lossy().into_owned())
}

/// A custom watch directory resolved at startup, with both the relative
/// form (passed to `watcher.watch`) and the absolute form (used to anchor
/// event matching to the project root).
///
/// `notify` backends typically dispatch absolute paths, but on some
/// platforms relative paths can also flow through, so matching tries both.
#[derive(Debug, Clone)]
struct CustomWatchDir {
    /// Relative path as configured. Passed to `watcher.watch()`.
    relative: PathBuf,
    /// Absolute (canonicalized when possible) path used to anchor event
    /// matching to the project root, so a custom dir like `views` can't
    /// false-match against an ancestor directory in the absolute path
    /// (e.g. project at `/home/alice/views/app`).
    absolute: PathBuf,
}

impl CustomWatchDir {
    /// True if `event_path` falls inside this custom watch directory.
    fn matches(&self, event_path: &Path) -> bool {
        event_path.starts_with(&self.absolute) || event_path.starts_with(&self.relative)
    }
}

/// Resolve sanitized relative watch dirs to `CustomWatchDir` entries,
/// dropping any that don't exist on disk. Logs a warning per dropped
/// entry so misconfiguration is visible.
fn resolve_custom_watch_dirs(normalized: &[String], cwd: &Path) -> Vec<CustomWatchDir> {
    normalized
        .iter()
        .filter_map(|rel| {
            let relative = PathBuf::from(rel);
            let cwd_joined = cwd.join(&relative);
            if !cwd_joined.exists() {
                eprintln!("  Warning: configured watch directory {rel}/ does not exist; skipping");
                return None;
            }
            let absolute = std::fs::canonicalize(&cwd_joined).unwrap_or(cwd_joined);
            Some(CustomWatchDir { relative, absolute })
        })
        .collect()
}

/// Filter custom watch dirs to those that are safe and not already covered by
/// the defaults. Keeps the watcher list deterministic and prevents hostile
/// entries (e.g. `target`, absolute paths, `..`) from subscribing huge trees.
fn sanitize_custom_watch_dirs(config: DevConfig) -> Vec<String> {
    let mut seen: Vec<String> = Vec::new();
    for raw in config.watch_dirs {
        let normalized = match normalize_watch_dir(&raw) {
            Ok(value) => value,
            Err(reason) => {
                eprintln!("  Warning: ignoring [dev].watch_dirs entry {raw:?}: {reason}");
                continue;
            }
        };
        if DEFAULT_WATCH_DIRS.contains(&normalized.as_str()) {
            continue;
        }
        if !seen.contains(&normalized) {
            seen.push(normalized);
        }
    }
    seen
}

/// Process a single batch of events from the debouncer channel.
/// Returns false if the channel was closed and the loop should exit.
fn process_events(
    rx: &mpsc::Receiver<Result<Vec<notify_debouncer_mini::DebouncedEvent>, notify::Error>>,
    custom_watch_dirs: &[CustomWatchDir],
    package: Option<&str>,
    child: &mut Option<Child>,
    reload_state: Option<&mut DevReloadState>,
    show_config: bool,
) -> bool {
    match rx.recv_timeout(Duration::from_millis(SHUTDOWN_CHECK_INTERVAL_MS)) {
        Ok(Ok(events)) => {
            let plan = plan_changes(&events, custom_watch_dirs);
            if plan.is_empty() {
                return true;
            }

            let changed = collect_relevant_changes(&events, custom_watch_dirs);
            if changed.is_empty() {
                return true;
            }

            eprintln!("\n  Changed: {}", changed.join(", "));
            eprintln!("  Action: {}", describe_plan(plan));

            execute_plan(plan, package, child, reload_state, show_config);
            true
        }
        Ok(Err(error)) => {
            eprintln!("  Watch error: {error:?}");
            true
        }
        Err(mpsc::RecvTimeoutError::Timeout) => true,
        Err(mpsc::RecvTimeoutError::Disconnected) => {
            eprintln!("  Watch channel error: channel disconnected");
            false
        }
    }
}

/// Execute a computed change plan.
fn execute_plan(
    plan: ChangePlan,
    package: Option<&str>,
    child: &mut Option<Child>,
    mut reload_state: Option<&mut DevReloadState>,
    show_config: bool,
) {
    if plan.build {
        // The order of "stop old binary" vs. "cargo build" is platform-gated.
        //
        // On Unix/macOS, replacing a running binary file mid-build is safe
        // (inode semantics), so we build FIRST with the old binary still
        // serving. A failed rebuild then leaves the stale app up to answer the
        // live-reload endpoint and render the diagnostics overlay.
        //
        // On Windows the running `target/debug/<app>.exe` is LOCKED while the
        // process is alive, so `cargo build` can't relink over it (access
        // denied / linker failure). There we must stop the old binary BEFORE
        // building. The tradeoff: a failed Windows rebuild leaves the app down,
        // so the overlay's stale-page serving isn't available and the client
        // falls back to a normal reconnect (documented limitation).
        let stop_before_build = cfg!(windows);

        if stop_before_build {
            stop_server(child, package);
        }

        let (built, diagnostics) = cargo_build_capturing(package);

        if built {
            if !stop_before_build {
                stop_server(child, package);
            }
            if restart_server(
                package,
                child,
                reload_state.as_ref().map(|s| s.path()),
                show_config,
            ) && let Some(reload_state) = reload_state.as_mut()
                && let Err(error) = reload_state.signal_build_success(ReloadKind::Full)
            {
                // A green build is the only thing that clears the overlay.
                eprintln!("  Warning: live reload signal failed: {error}");
            }
        } else {
            eprintln!("  \u{2717} Build failed. Waiting for changes...\n");
            // On Unix the (stale) binary is still running, so it keeps
            // answering the live-reload state endpoint and the browser renders
            // the overlay. On Windows we already stopped it above, so nothing
            // is serving: `child.is_some()` is false there and the client
            // falls back to a normal reconnect.
            let stale = child.is_some();
            if let Some(reload_state) = reload_state.as_mut()
                && let Err(error) = reload_state.signal_build_error(&diagnostics, stale)
            {
                eprintln!("  Warning: live reload signal failed: {error}");
            }
        }
        return;
    }

    let mut applied_reload = ReloadKind::None;

    if plan.tailwind && tailwind_build() {
        applied_reload = applied_reload.max(ReloadKind::Css);
    }

    if plan.restart {
        stop_server(child, package);
        if restart_server(
            package,
            child,
            reload_state.as_ref().map(|s| s.path()),
            show_config,
        ) {
            applied_reload = ReloadKind::Full;
        }
    } else if plan.reload == ReloadKind::Full {
        applied_reload = ReloadKind::Full;
    }

    // Ordinary (non-build) reload. If a Rust build is still broken,
    // `signal` carries the build-error overlay forward instead of dismissing
    // it, so this CSS/Tailwind/static change doesn't reload the stale app.
    if let Some(reload_state) = reload_state.as_mut()
        && let Err(error) = reload_state.signal(applied_reload)
    {
        eprintln!("  Warning: live reload signal failed: {error}");
    }
}

/// Collect display paths for all relevant file changes from a debounced batch.
///
/// Returns an empty vec if no changes are relevant.
fn collect_relevant_changes(
    events: &[notify_debouncer_mini::DebouncedEvent],
    custom_watch_dirs: &[CustomWatchDir],
) -> Vec<String> {
    events
        .iter()
        .filter(|e| is_relevant_change(&e.path, e.kind, custom_watch_dirs))
        .map(|e| e.path.display().to_string())
        .collect()
}

fn plan_changes(
    events: &[notify_debouncer_mini::DebouncedEvent],
    custom_watch_dirs: &[CustomWatchDir],
) -> ChangePlan {
    let mut plan = ChangePlan::default();
    for event in events {
        plan.register(classify_change(&event.path, event.kind, custom_watch_dirs));
    }
    plan.finalize()
}

/// Build a `cargo build` command for the given package.
pub fn build_cargo_command(package: Option<&str>, release: bool) -> Command {
    let mut cmd = Command::new("cargo");
    cmd.arg("build");
    if release {
        cmd.arg("--release");
    }
    if let Some(pkg) = package {
        cmd.args(["-p", pkg]);
    }
    cmd
}

/// A single compiler error extracted from `cargo build --message-format=json`.
///
/// Serialized into the live-reload state file so the browser overlay can
/// render the failure without the CLI needing to talk to the app directly.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct BuildDiagnostic {
    /// Error code (e.g. `E0425`), when the compiler assigned one.
    code: Option<String>,
    /// Primary human-readable message (`message.message`).
    message: String,
    /// File of the primary span, empty when the error has no primary span.
    file: String,
    /// 1-based line of the primary span (0 when absent).
    line: u32,
    /// 1-based column of the primary span (0 when absent).
    column: u32,
    /// Full multi-line rendered diagnostic (`message.rendered`).
    rendered: String,
}

/// Parse `cargo build --message-format=json` stdout into ordered error
/// diagnostics.
///
/// Keeps only `compiler-message` records at `error` level (warnings are out of
/// scope) and preserves the compiler's emission order. Non-JSON lines and other
/// message kinds (artifacts, build-finished) are skipped. Mirrors the JSON
/// walking pattern used by [`crate::dev_loop_bench::cargo_executable_path`].
fn parse_build_diagnostics(stdout: &[u8]) -> Vec<BuildDiagnostic> {
    let text = String::from_utf8_lossy(stdout);
    let mut diagnostics = Vec::new();

    for line in text.lines() {
        let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
            continue;
        };
        if value.get("reason").and_then(serde_json::Value::as_str) != Some("compiler-message") {
            continue;
        }
        let Some(message) = value.get("message") else {
            continue;
        };
        if message.get("level").and_then(serde_json::Value::as_str) != Some("error") {
            continue;
        }

        let code = message
            .get("code")
            .and_then(|code| code.get("code"))
            .and_then(serde_json::Value::as_str)
            .map(str::to_owned);
        let text_message = message
            .get("message")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default()
            .to_owned();
        let rendered = message
            .get("rendered")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default()
            .to_owned();

        let primary = message
            .get("spans")
            .and_then(serde_json::Value::as_array)
            .and_then(|spans| {
                spans.iter().find(|span| {
                    span.get("is_primary").and_then(serde_json::Value::as_bool) == Some(true)
                })
            });
        let (file, line, column) = primary.map_or_else(
            || (String::new(), 0, 0),
            |span| {
                let file = span
                    .get("file_name")
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or_default()
                    .to_owned();
                let line = span
                    .get("line_start")
                    .and_then(serde_json::Value::as_u64)
                    .and_then(|n| u32::try_from(n).ok())
                    .unwrap_or(0);
                let column = span
                    .get("column_start")
                    .and_then(serde_json::Value::as_u64)
                    .and_then(|n| u32::try_from(n).ok())
                    .unwrap_or(0);
                (file, line, column)
            },
        );

        diagnostics.push(BuildDiagnostic {
            code,
            message: text_message,
            file,
            line,
            column,
            rendered,
        });
    }

    diagnostics
}

/// Run `cargo build` for the given package while capturing compiler
/// diagnostics as JSON.
///
/// Returns `(success, error_diagnostics)`. Diagnostics are echoed to stderr via
/// their `rendered` form so the terminal experience matches a plain build.
/// Used by the watch loop so a failed rebuild can surface errors as a browser
/// overlay; `serve` keeps using [`cargo_build`].
fn cargo_build_capturing(package: Option<&str>) -> (bool, Vec<BuildDiagnostic>) {
    use std::io::{BufRead, BufReader};

    let mut cmd = build_cargo_command(package, false);
    cmd.arg("--message-format=json");
    // Pipe stdout so we can read structured JSON diagnostics line by line as the
    // compiler emits them, while cargo's own progress/status output (the live
    // "Compiling ..." lines) streams straight through on inherited stderr. This
    // keeps the terminal responsive instead of freezing until the build ends.
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::inherit());

    eprintln!("  Compiling...");
    let mut child = match cmd.spawn() {
        Ok(child) => child,
        Err(e) => {
            eprintln!("  \u{2717} Failed to run cargo build: {e}");
            return (false, Vec::new());
        }
    };

    // Accumulate raw stdout so `parse_build_diagnostics` can build the returned
    // Vec once at the end. Error `rendered` blocks are echoed live in compiler
    // order as their lines arrive, so each error appears exactly once and the
    // final parse never re-prints them.
    let mut buffer = String::new();
    if let Some(stdout) = child.stdout.take() {
        let reader = BufReader::new(stdout);
        for line in reader.lines() {
            let Ok(line) = line else {
                // A read error mid-stream: stop consuming and fall back to
                // whatever we captured so far rather than panicking.
                break;
            };
            if let Some(rendered) = compiler_message_rendered(&line) {
                eprint!("{rendered}");
            }
            buffer.push_str(&line);
            buffer.push('\n');
        }
    }

    let diagnostics = parse_build_diagnostics(buffer.as_bytes());
    match child.wait() {
        Ok(status) if status.success() => {
            crate::built_artifact::record(&crate::built_artifact::parse_executables(&buffer));
            eprintln!("  \u{2713} Build succeeded");
            (true, diagnostics)
        }
        Ok(_) => (false, diagnostics),
        Err(e) => {
            eprintln!("  \u{2717} cargo build failed: {e}");
            (false, diagnostics)
        }
    }
}

/// If `line` is a single `cargo build --message-format=json` record that is a
/// `compiler-message` carrying a non-empty `rendered` block, return that text so
/// it can be echoed to the terminal the instant it arrives. This deliberately
/// echoes diagnostics at *every* level (errors, warnings, notes, help, etc.) so
/// the live output matches what plain `cargo build` would print — the overlay
/// payload, built separately by [`parse_build_diagnostics`], stays errors-only.
/// Non-JSON lines and non-`compiler-message` records (artifacts, build scripts,
/// build-finished) yield `None`, as do compiler messages with no `rendered`
/// text.
fn compiler_message_rendered(line: &str) -> Option<String> {
    let value = serde_json::from_str::<serde_json::Value>(line).ok()?;
    if value.get("reason").and_then(serde_json::Value::as_str) != Some("compiler-message") {
        return None;
    }
    let rendered = value
        .get("message")?
        .get("rendered")
        .and_then(serde_json::Value::as_str)
        .unwrap_or_default();
    if rendered.is_empty() {
        return None;
    }
    Some(rendered.to_owned())
}

/// Run `cargo build` for the given package. Returns true on success.
pub fn cargo_build(package: Option<&str>, release: bool) -> bool {
    let mut cmd = build_cargo_command(package, release);

    eprintln!("  Compiling...");
    match crate::built_artifact::run_build(&mut cmd) {
        Ok(status) if status.success() => {
            eprintln!("  \u{2713} Build succeeded");
            true
        }
        Ok(_) => false,
        Err(e) => {
            eprintln!("  \u{2717} Failed to run cargo build: {e}");
            false
        }
    }
}

/// Start the application binary. Returns the child process handle.
fn start_server(
    binary: &Path,
    package: Option<&str>,
    reload_state_path: Option<&Path>,
    show_config: bool,
) -> Option<Child> {
    eprintln!("  Starting server...\n");

    let member_dir = selected_member_dir(package);
    // Read `.env` from the selected package, as the app and the stop budget do.
    // Resolve `.env` fresh right before each spawn so a hot-reload restart
    // picks up an edited `.env`. Values are injected explicitly into the child
    // process (rather than mutating this process's environment); the child also
    // self-loads via the config overlay, so this is belt-and-suspenders and
    // makes a bare `DATABASE_URL` visible to the child. A malformed `.env`
    // fails loudly. Applied BEFORE the explicit `.env(...)` calls below so those
    // win on any key overlap.
    let dotenv_vars = match autumn_web::dotenv::resolve_process_dotenv_in(&package_dir_from(
        member_dir.clone(),
    )) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("  \u{274C} .env: {e}");
            std::process::exit(1);
        }
    };

    let mut command = Command::new(binary);
    command.envs(dotenv_vars);
    // The app reads its config from the selected package. An inherited
    // `AUTUMN_MANIFEST_DIR` would win over the app's own manifest directory.
    if let Some(dir) = &member_dir {
        command.env("AUTUMN_MANIFEST_DIR", dir);
    }
    // See `serve::base_command`: these one-shot modes are dispatched before the
    // server starts, so an inherited flag would turn every hot-reload restart
    // into a manifest dump that exits cleanly and never serves.
    command.env_remove(crate::data_flow::DUMP_ENV);
    command.env_remove(crate::agents::DUMP_ENV);
    command.env_remove(crate::graph::DUMP_ENV);
    // Same reasoning, worse outcome (#1605): `AUTUMN_DB_RETENTION=report|purge`
    // is dispatched before the server starts, so an inherited one would make
    // every hot-reload restart enforce the retention policy and exit -- deleting
    // data on each save rather than merely failing to serve.
    crate::db::retention::clear_inherited_one_shot_env(&mut command);
    // Same for `autumn data capsule` (#1811).
    crate::data_capsule::clear_inherited_one_shot_env(&mut command);
    // Inherit stdio so tracing output (including --show-config) is visible.
    // Previously used Stdio::null(), but server logs are valuable during dev.
    command.stdout(Stdio::inherit()).stderr(Stdio::inherit());
    if let Some(path) = reload_state_path {
        command.env(DEV_RELOAD_ENV, "1");
        command.env(DEV_RELOAD_STATE_ENV, path);
    }
    if show_config {
        command.env("AUTUMN_SHOW_CONFIG", "1");
    }
    // Hand the app its own shutdown and ready files so a stop can run its
    // `on_shutdown` hooks on a platform with no `SIGTERM` (#1616), and so the
    // app can report its drain budget and when it is up. Fresh paths for each
    // child: an old file can never drain this child at boot or pass for its
    // ready file. Only wired where it is the stop mechanism: on Unix
    // `stop_server` signals, and an unset variable keeps the watcher inert.
    #[cfg(not(unix))]
    if let Some(paths) = begin_child_paths() {
        command.env(DEV_SHUTDOWN_SIGNAL_ENV, &paths.signal);
        command.env(SERVE_READY_FILE_ENV, &paths.ready);
        // Resolve the child's stop budget from the config it is about to boot
        // with, and keep it for the stop. `autumn.toml` is watched, so by the
        // time this child is stopped the file may say something different, and
        // the child would still be draining on these numbers.
        record_child_stop_budget(resolve_cooperative_stop_budget(package));
    }

    match command.spawn() {
        Ok(child) => Some(child),
        Err(e) => {
            eprintln!("  \u{2717} Failed to start {}: {e}", binary.display());
            None
        }
    }
}

/// Stop the running server process gracefully.
fn stop_server(child: &mut Option<Child>, package: Option<&str>) {
    #[cfg(unix)]
    {
        let _ = package;
        stop_server_unix(child);
    }
    #[cfg(not(unix))]
    stop_server_cooperative(child, package);
}

/// Unix stop: `SIGTERM`, then `SIGKILL` if the app misses its drain budget.
/// This is the mechanism production uses, so the dev loop uses it too.
#[cfg(unix)]
fn stop_server_unix(child: &mut Option<Child>) {
    if let Some(proc) = child {
        if let Some(pid) = crate::process::validate_pid_for_kill(proc.id())
            && let Err(e) = nix::sys::signal::kill(
                nix::unistd::Pid::from_raw(pid),
                nix::sys::signal::Signal::SIGTERM,
            )
        {
            eprintln!("  Warning: failed to send SIGTERM to process: {e}");
        }
        // Wait briefly for graceful shutdown before forcing
        if crate::process::wait_with_timeout(proc, Duration::from_secs(5)).is_err() {
            let _ = proc.kill();
            let _ = proc.wait();
        }
    }
    *child = None;
}

/// Non-Unix stop: there is no `SIGTERM` here, and `Child::kill` is
/// `TerminateProcess` — it skips the app's `on_shutdown` hooks, so a managed
/// Postgres child was orphaned on every rebuild (#1616). Ask the app to drain
/// through the file it watches, and force-kill only if it will not.
#[cfg(not(unix))]
fn stop_server_cooperative(child: &mut Option<Child>, package: Option<&str>) {
    let Some(paths) = current_child_paths() else {
        // `start_server` sets `AUTUMN_SHUTDOWN_SIGNAL_FILE` from the same
        // paths, so with none the child was never told to watch anything.
        // Waiting out the full budget for a request nobody can receive would
        // make every rebuild slower than the hard kill this replaced. So kill
        // directly, and say why.
        if let Some(proc) = child.as_mut() {
            let _ = proc.kill();
            let _ = proc.wait();
            eprintln!(
                "{}",
                unreachable_warning(
                    "cargo metadata is unreadable, or the target directory is not writable"
                )
            );
        }
        *child = None;
        return;
    };
    let budget = std::cell::Cell::new(Duration::ZERO);
    let outcome = stop_booted_child(child, &paths, COOPERATIVE_STOP_BOOT_CAP, || {
        let resolved = stop_budget_for_running_child(
            child_reported_stop_budget(&paths.ready),
            recorded_child_stop_budget(),
            || resolve_cooperative_stop_budget(package),
        );
        budget.set(resolved);
        resolved
    });
    match outcome {
        StopOutcome::Unsupported => eprintln!("{}", unsupported_warning()),
        StopOutcome::Escalated => eprintln!("{}", escalation_warning(budget.get())),
        StopOutcome::Unreachable => eprintln!(
            "{}",
            unreachable_warning("the target directory is not writable")
        ),
        StopOutcome::Graceful | StopOutcome::NotRunning => {}
    }
}

/// Check if a file change event is relevant enough to trigger a rebuild.
fn is_relevant_change(
    path: &Path,
    kind: DebouncedEventKind,
    custom_watch_dirs: &[CustomWatchDir],
) -> bool {
    classify_change(path, kind, custom_watch_dirs) != ChangeEffect::Ignore
}

fn classify_change(
    path: &Path,
    kind: DebouncedEventKind,
    custom_watch_dirs: &[CustomWatchDir],
) -> ChangeEffect {
    let roots = WATCH_ROOTS.get().map_or(&[][..], Vec::as_slice);
    classify_change_in(path, kind, custom_watch_dirs, roots)
}

/// [`classify_change`] for an explicit set of watch roots.
fn classify_change_in(
    path: &Path,
    kind: DebouncedEventKind,
    custom_watch_dirs: &[CustomWatchDir],
    watch_roots: &[PathBuf],
) -> ChangeEffect {
    if !matches!(kind, DebouncedEventKind::Any) {
        return ChangeEffect::Ignore;
    }
    // Judge the path inside the project, not the directories above it. A
    // workspace under `~/.worktrees/` is not a hidden project. The original
    // path stays for the custom watch directories, which match full paths.
    let original = path;
    let path = strip_watch_root(path, watch_roots);

    // A root-level dotenv file the config loader reads (`.env`, `.env.local`,
    // `.env.<profile>`, `.env.<profile>.local`) must restart the server so an
    // edited `.env` takes effect — even though `should_ignore_path` would
    // otherwise discard it as a dotfile. Checked before that ignore so the
    // dotenv exception wins, while all other dotfiles stay ignored.
    if is_watched_dotenv_file(path) {
        return ChangeEffect::RestartOnly;
    }

    if should_ignore_path(path) {
        return ChangeEffect::Ignore;
    }

    let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else {
        return ChangeEffect::Ignore;
    };

    if WATCH_FILES.contains(&file_name)
        && matches!(file_name, "Cargo.toml" | "Cargo.lock" | "build.rs")
    {
        return ChangeEffect::BuildRestart;
    }

    if WATCH_FILES.contains(&file_name) && file_name == "tailwind.config.js" {
        return ChangeEffect::TailwindOnly;
    }

    if (WATCH_FILES.contains(&file_name) && file_name == "autumn.toml")
        || is_profile_config_file(file_name)
    {
        return ChangeEffect::RestartOnly;
    }

    if has_component(path, "src") && path.extension().and_then(|ext| ext.to_str()) == Some("rs") {
        return ChangeEffect::BuildRestart;
    }

    if has_component(path, "templates") {
        return ChangeEffect::BuildRestart;
    }

    if has_component(path, "migrations")
        && path.extension().and_then(|ext| ext.to_str()) == Some("sql")
    {
        return ChangeEffect::RestartOnly;
    }

    if has_component(path, "static") {
        if path.ends_with(Path::new("static").join("css").join("input.css")) {
            return ChangeEffect::TailwindOnly;
        }

        return ChangeEffect::BrowserReloadOnly;
    }

    // Files inside a user-configured custom watch directory don't have known
    // semantics — restart the server and trigger a full reload so the change
    // is picked up regardless of what the directory contains.
    //
    // Matching is anchored at the project root via the resolved absolute
    // path, so an entry like `views` cannot false-match an ancestor
    // directory of the same name (e.g. project at `/home/alice/views/app`).
    // The relative form is also tried so events emitted as relative paths
    // (rare but possible on some platforms) still match.
    for dir in custom_watch_dirs {
        if dir.matches(original) {
            return ChangeEffect::RestartOnly;
        }
    }

    ChangeEffect::Ignore
}

/// Editor/tooling temp or backup suffixes (the final `.`-segment) that must not
/// trigger a restart even when they decorate a dotenv filename — e.g. a vim swap
/// file `.env.swp` or a backup `.env.tmp`. `.env.example` is a committed
/// template the loader never reads, so it is excluded too.
const DOTENV_NON_LOADED_SUFFIXES: &[&str] =
    &["swp", "swo", "swx", "swpx", "tmp", "bak", "orig", "example"];

/// Whether `name` is a dotenv file the config loader actually reads: `.env`,
/// `.env.local`, `.env.<profile>`, or `.env.<profile>.local`.
///
/// Editor/backup decorations (`.env.swp`, `.env~`, `.env.tmp`, …) are rejected
/// so a save-in-progress swap file does not cause a spurious restart.
fn is_dotenv_loader_filename(name: &str) -> bool {
    if name == ".env" {
        return true;
    }
    // Must be `.env.<something>`; a bare `.env~`/`.env.swp`-style backup that
    // lacks the `.env.` prefix is rejected here, and a trailing `~` backup
    // (e.g. `.env.local~`) is rejected explicitly.
    let Some(rest) = name.strip_prefix(".env.") else {
        return false;
    };
    if rest.is_empty() || name.ends_with('~') {
        return false;
    }
    let last_segment = rest.rsplit('.').next().unwrap_or(rest);
    !DOTENV_NON_LOADED_SUFFIXES.contains(&last_segment)
}

/// Whether `path` is a project-root dotenv file the loader reads (see
/// [`is_dotenv_loader_filename`]).
///
/// Scoped to root-level files: any dotenv-named file living under a dotted
/// directory (e.g. `.git/.env`) or `target/` is rejected, mirroring
/// [`should_ignore_path`] so only the genuine project-root `.env*` files are
/// un-ignored.
fn is_watched_dotenv_file(path: &Path) -> bool {
    let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
        return false;
    };
    if !is_dotenv_loader_filename(name) {
        return false;
    }
    path.parent().is_none_or(|parent| {
        parent.components().all(|component| {
            if let std::path::Component::Normal(part) = component {
                let part = part.to_string_lossy();
                part != "target" && !part.starts_with('.')
            } else {
                true
            }
        })
    })
}

fn should_ignore_path(path: &Path) -> bool {
    if path.ends_with(Path::new("static").join("css").join("autumn.css")) {
        return true;
    }

    if path.ends_with(
        Path::new("target")
            .join("autumn")
            .join(DEV_RELOAD_STATE_FILE),
    ) {
        return true;
    }

    for component in path.components() {
        if let std::path::Component::Normal(name) = component {
            let name = name.to_string_lossy();
            if name == "target" || name.starts_with('.') {
                return true;
            }
        }
    }

    false
}

fn has_component(path: &Path, target: &str) -> bool {
    path.components().any(|component| {
        matches!(
            component,
            std::path::Component::Normal(name) if name == std::ffi::OsStr::new(target)
        )
    })
}

fn is_profile_config_file(file_name: &str) -> bool {
    file_name.starts_with("autumn-")
        && Path::new(file_name)
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("toml"))
        && file_name.len() > "autumn-.toml".len()
}

const fn describe_plan(plan: ChangePlan) -> &'static str {
    match plan {
        ChangePlan {
            build: true,
            restart: true,
            ..
        } => "cargo build + restart + full reload",
        ChangePlan {
            restart: true,
            tailwind: true,
            ..
        } => "Tailwind rebuild + restart + full reload",
        ChangePlan { restart: true, .. } => "restart + full reload",
        ChangePlan {
            tailwind: true,
            reload: ReloadKind::Css,
            ..
        } => "Tailwind rebuild + CSS reload",
        ChangePlan {
            reload: ReloadKind::Full,
            ..
        } => "browser full reload",
        _ => "no-op",
    }
}

fn restart_server(
    package: Option<&str>,
    child: &mut Option<Child>,
    reload_state_path: Option<&Path>,
    show_config: bool,
) -> bool {
    let binary = find_binary(package, false);
    *child = start_server(&binary, package, reload_state_path, show_config);
    child.is_some()
}

fn tailwind_build() -> bool {
    let Some(mut cmd) = build_tailwind_command() else {
        eprintln!(
            "  \u{2717} Tailwind CSS CLI not found. Run `autumn setup` or install `tailwindcss`."
        );
        return false;
    };

    eprintln!("  Rebuilding Tailwind...");
    match cmd.status() {
        Ok(status) if status.success() => {
            eprintln!("  \u{2713} Tailwind rebuild succeeded");
            true
        }
        Ok(_) => {
            eprintln!("  \u{2717} Tailwind rebuild failed");
            false
        }
        Err(error) => {
            eprintln!("  \u{2717} Failed to run Tailwind CLI: {error}");
            false
        }
    }
}

fn build_tailwind_command() -> Option<Command> {
    let tailwind = find_tailwind_cli()?;
    Some(build_tailwind_command_for(&tailwind))
}

fn build_tailwind_command_for(tailwind: &Path) -> Command {
    let mut cmd = Command::new(tailwind);
    cmd.args([
        "-i",
        "static/css/input.css",
        "-o",
        "static/css/autumn.css",
        "--content",
        "src/**/*.rs",
        "--minify",
    ]);
    cmd
}

fn find_tailwind_cli() -> Option<PathBuf> {
    let local = resolve_target_directory().ok().map(|dir| {
        dir.join("autumn").join(if cfg!(windows) {
            "tailwindcss.exe"
        } else {
            "tailwindcss"
        })
    });

    if let Some(local) = local.filter(|path| path.exists()) {
        return Some(local);
    }

    which("tailwindcss")
}

fn which(binary: &str) -> Option<PathBuf> {
    let path_var = std::env::var_os("PATH")?;
    for dir in std::env::split_paths(&path_var) {
        let candidate = dir.join(binary);
        if candidate.exists() {
            return Some(candidate);
        }
        #[cfg(target_os = "windows")]
        {
            let candidate_exe = dir.join(format!("{binary}.exe"));
            if candidate_exe.exists() {
                return Some(candidate_exe);
            }
        }
    }
    None
}

fn resolve_dev_reload_state_path() -> Result<PathBuf, String> {
    Ok(resolve_target_directory()?
        .join("autumn")
        .join(DEV_RELOAD_STATE_FILE))
}

/// The directory for this session's shutdown and ready files: beside the
/// live-reload state, inside the target directory, so `cargo clean` sweeps it.
///
/// **Tolerant.** This resolves through [`try_cargo_metadata`], not
/// [`resolve_target_directory`], which `exit(1)`s on unreadable metadata. A
/// half-saved `Cargo.toml` is an ordinary dev-loop event, and on Windows the
/// stop runs before the rebuild. An exit there would leave the app and its
/// managed Postgres running with nobody to stop them.
///
/// **Cached.** A stop must be cheap and must not run `cargo metadata`.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn dev_state_dir() -> Option<&'static Path> {
    static DIR: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();
    DIR.get_or_init(|| {
        let metadata = try_cargo_metadata()?;
        let target = metadata["target_directory"].as_str()?;
        Some(Path::new(target).join("autumn"))
    })
    .as_deref()
}

/// The shutdown and ready files of one child.
///
/// Each child gets its own pair, so a file left by an earlier child, such as one
/// that could not be deleted, can never pass for this child's.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
#[derive(Debug, Clone, PartialEq, Eq)]
struct ChildPaths {
    /// The app watches this file. Creating it asks the app to drain.
    signal: PathBuf,
    /// The app writes its drain budget here once it is up.
    ready: PathBuf,
}

/// The file names for child number `generation` of one dev-loop run.
///
/// The process id keeps two `autumn dev` runs in one workspace (`-p api` and
/// `-p admin`) apart. A shared file would let one run drain the other's app.
/// The run nonce keeps a later run apart that got the same process id, because
/// the OS reuses ids and an unclean exit can leave files behind.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn child_paths_in(dir: &Path, pid: u32, nonce: u128, generation: u64) -> ChildPaths {
    ChildPaths {
        signal: dir.join(format!(
            "{DEV_SHUTDOWN_SIGNAL_PREFIX}{pid}.{nonce}.{generation}{DEV_SHUTDOWN_SIGNAL_SUFFIX}"
        )),
        ready: dir.join(format!(
            "{DEV_READY_FILE_PREFIX}{pid}.{nonce}.{generation}{DEV_READY_FILE_SUFFIX}"
        )),
    }
}

/// A value that differs between runs: the start time in nanoseconds.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn run_nonce() -> u128 {
    static NONCE: std::sync::OnceLock<u128> = std::sync::OnceLock::new();
    *NONCE.get_or_init(|| {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |elapsed| elapsed.as_nanos())
    })
}

/// Whether `dir` can hold the marker files: it exists, or can be made, and the
/// steps the protocol uses all work in it. The app writes its ready file as a
/// temporary file, renames it into place, and the CLI later removes it. Live
/// reload only warns when its own setup in the same directory fails, so this is
/// checked before the app is told to use the directory.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn state_dir_is_usable(dir: &Path, pid: u32, nonce: u128) -> bool {
    if std::fs::create_dir_all(dir).is_err() {
        return false;
    }
    // The run nonce keeps a later run that got the same process id away from a
    // probe file an earlier run left behind.
    let temporary = dir.join(format!("dev-probe.{pid}.{nonce}.tmp"));
    let renamed = dir.join(format!("dev-probe.{pid}.{nonce}"));
    let usable = std::fs::File::create(&temporary).is_ok()
        && std::fs::rename(&temporary, &renamed).is_ok()
        && std::fs::remove_file(&renamed).is_ok();
    let _ = std::fs::remove_file(&temporary);
    let _ = std::fs::remove_file(&renamed);
    usable
}

/// The paths of the running child, if one was started.
static CHILD_PATHS: std::sync::Mutex<Option<ChildPaths>> = std::sync::Mutex::new(None);

/// How many children this run has started.
static CHILD_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// Pick fresh paths for the child about to start, and remove the last child's
/// files. The removal is best-effort: a file that stays is harmless.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn begin_child_paths() -> Option<ChildPaths> {
    next_child_paths(
        &CHILD_PATHS,
        &CHILD_GENERATION,
        dev_state_dir(),
        std::process::id(),
        run_nonce(),
    )
}

/// [`begin_child_paths`] over explicit state, so it can be tested.
///
/// The last child is forgotten first. If setup fails below, the new child gets
/// no marker paths, and a stop must not use the old child's.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn next_child_paths(
    slot: &std::sync::Mutex<Option<ChildPaths>>,
    generation: &std::sync::atomic::AtomicU64,
    dir: Option<&Path>,
    pid: u32,
    nonce: u128,
) -> Option<ChildPaths> {
    let previous = slot.lock().ok()?.take();
    if let Some(previous) = previous {
        let _ = std::fs::remove_file(previous.signal);
        let _ = std::fs::remove_file(previous.ready);
    }
    let dir = dir?;
    if !state_dir_is_usable(dir, pid, nonce) {
        return None;
    }
    let number = generation.fetch_add(1, Ordering::SeqCst) + 1;
    let paths = child_paths_in(dir, pid, nonce, number);
    *slot.lock().ok()? = Some(paths.clone());
    Some(paths)
}

/// The paths of the running child.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn current_child_paths() -> Option<ChildPaths> {
    CHILD_PATHS.lock().ok()?.clone()
}

/// The stop budget the running child reported for itself, if it has booted.
///
/// The app writes its resolved *drain* budget (`prestop_grace_secs +
/// shutdown_timeout_secs`) to this file at startup-complete. The same headroom
/// still applies after the drain. A missing, blank, or unparseable
/// file means "no report" — never a zero budget, which would hard-kill instantly.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn child_reported_stop_budget(ready_file: &Path) -> Option<Duration> {
    // Line ONE only. The readiness file carries the drain budget on line one and
    // the app's bound address on line two (#1639); parsing the whole file would
    // silently stop reporting a budget, and every rebuild would fall back to the
    // CLI's own config guess — the guess this seam exists to avoid.
    let secs = std::fs::read_to_string(ready_file)
        .ok()?
        .lines()
        .next()?
        .trim()
        .parse::<u64>()
        .ok()?;
    Some(cooperative_stop_budget(secs))
}

/// Ask the running app to shut down gracefully by creating the file it watches.
///
/// The runtime keys off existence alone, so an empty file is the whole protocol.
///
/// # Errors
///
/// Returns the underlying IO error if the file (or its parent) cannot be created.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn request_cooperative_shutdown(path: &Path) -> std::io::Result<()> {
    if let Some(parent) = path.parent()
        && !parent.as_os_str().is_empty()
    {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::File::create(path).map(|_| ())
}

/// Remove a shutdown request so the next child does not drain the moment it
/// boots. Best-effort: a file that is already gone is the desired state.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn clear_cooperative_shutdown(path: &Path) {
    let _ = std::fs::remove_file(path);
}

/// The warning printed when a cooperative stop had to escalate to a hard kill.
///
/// Names the consequence, not just the timeout: #1616's whole complaint is that
/// a skipped teardown was invisible.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn escalation_warning(timeout: Duration) -> String {
    format!(
        "  Warning: the app did not shut down within {}s and was force-stopped. \
         Its shutdown hooks may not have run, so a managed Postgres cluster may \
         still be running and holding its data dir; the next start recovers the \
         cluster through crash recovery, which is slower than a clean stop.",
        timeout.as_secs()
    )
}

/// The warning printed when the shutdown request could not be delivered.
///
/// Distinct from [`escalation_warning`]: nothing is wrong with the app here, so
/// telling the developer it "did not shut down in time" would send them hunting
/// in the wrong place.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn unreachable_warning(error: &str) -> String {
    format!(
        "  Warning: could not write the shutdown-signal file ({error}), so the app \
         was force-stopped without being asked to drain. Its shutdown hooks did \
         not run, so a managed Postgres cluster may still be running and holding \
         its data dir; the next start recovers the cluster through crash \
         recovery, which is slower than a clean stop."
    )
}

/// How a wait for a booting app ended.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BootWait {
    /// The app is up (or no ready file is tracked): the stop budget can start.
    Ready,
    /// The app exited while booting.
    Exited,
    /// The app was still booting at the cap. The caller treats it as up.
    TimedOut,
}

/// Wait until the app finishes booting, exits, or `cap` passes.
///
/// The app watches the signal file only after startup. Its ready file marks
/// that point. With no ready file to track, the app is assumed up.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn wait_until_booted(proc: &mut Child, ready_file: Option<&Path>, cap: Duration) -> BootWait {
    let Some(ready_file) = ready_file else {
        return BootWait::Ready;
    };
    let start = std::time::Instant::now();
    let mut told = false;
    loop {
        if ready_file.exists() {
            return BootWait::Ready;
        }
        match proc.try_wait() {
            Ok(Some(_)) => return BootWait::Exited,
            Ok(None) if start.elapsed() < cap => {
                // A long wait with no output looks like a hang.
                if !told && start.elapsed() >= BOOT_WAIT_NOTICE_AFTER {
                    eprintln!("{}", boot_wait_notice(cap));
                    told = true;
                }
                std::thread::sleep(Duration::from_millis(50));
            }
            Ok(None) | Err(_) => return BootWait::TimedOut,
        }
    }
}

/// How long a stop waits for a booting app before it says what it is doing.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
const BOOT_WAIT_NOTICE_AFTER: Duration = Duration::from_secs(10);

/// What a stop tells the developer while it waits for a booting app.
///
/// An `autumn-web` that is too old to report when it is up never ends the wait
/// early, so the notice also says how to fix that.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn boot_wait_notice(cap: Duration) -> String {
    format!(
        "  The app is still starting. Waiting for it before it is stopped, up to {} \
         minutes. If this app uses an old autumn-web that never reports it is up, \
         run `cargo update -p autumn-web`.",
        cap.as_secs().div_ceil(60)
    )
}

/// The warning printed when the app was force-stopped because its `autumn-web`
/// does not watch the shutdown-signal file.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn unsupported_warning() -> String {
    "  Warning: this app's autumn-web is older than the CLI and cannot drain on \
     request, so it was force-stopped. Its shutdown hooks did not run. A managed \
     Postgres cluster may still be running. The next start recovers it through \
     crash recovery. To fix this, run `cargo update -p autumn-web`."
        .to_owned()
}

/// Force-kill a child that cannot drain on request. Sends no signal file and
/// does not wait: the child would never read it.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn stop_unsupported_child(child: &mut Option<Child>, signal_path: &Path) -> StopOutcome {
    let Some(proc) = child.as_mut() else {
        return StopOutcome::NotRunning;
    };
    let _ = proc.kill();
    let _ = proc.wait();
    clear_cooperative_shutdown(signal_path);
    *child = None;
    StopOutcome::Unsupported
}

/// Stop `child` the way its `support` allows: at once when it cannot drain on
/// request, otherwise through the signal file.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn stop_with_support(
    child: &mut Option<Child>,
    signal_path: &Path,
    support: ShutdownSupport,
    budget: Duration,
) -> StopOutcome {
    match support {
        ShutdownSupport::Unsupported => stop_unsupported_child(child, signal_path),
        ShutdownSupport::Supported | ShutdownSupport::Unknown => {
            stop_child_cooperatively(child, signal_path, budget)
        }
    }
}

/// Stop `child` cooperatively: request a graceful shutdown via the signal file,
/// wait up to `timeout` for it to drain, then force-kill if it has not.
///
/// This is the Windows stop path, but it is compiled on every platform so Linux
/// CI exercises it. On Unix `stop_server` keeps using `SIGTERM`, which is the
/// mechanism production uses and is strictly faster.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn stop_child_cooperatively(
    child: &mut Option<Child>,
    signal_path: &Path,
    timeout: Duration,
) -> StopOutcome {
    let Some(proc) = child.as_mut() else {
        return StopOutcome::NotRunning;
    };

    let outcome = match request_cooperative_shutdown(signal_path) {
        Err(_) => {
            let _ = proc.kill();
            let _ = proc.wait();
            StopOutcome::Unreachable
        }
        Ok(()) if crate::process::wait_with_timeout(proc, timeout).is_ok() => StopOutcome::Graceful,
        Ok(()) => {
            let _ = proc.kill();
            let _ = proc.wait();
            StopOutcome::Escalated
        }
    };

    // Always clear the request, on both paths: the next child must not inherit
    // a stale signal and drain at boot.
    clear_cooperative_shutdown(signal_path);
    *child = None;
    outcome
}

/// Stop `child` after it has finished booting, through the signal file.
///
/// The app reads the signal file only after it starts, so the stop first waits
/// for the ready file, the app's own mark that it is up. That file also says
/// whether the app can drain on request, so it is read after the wait. A child
/// that exits during boot has stopped on its own. If the file never comes, the
/// app is treated as up at `boot_cap`: the write is best-effort.
///
/// `budget` runs after the wait, so it sees the budget the app wrote.
#[cfg_attr(
    unix,
    allow(
        dead_code,
        reason = "the non-Unix stop path, compiled and tested everywhere"
    )
)]
fn stop_booted_child(
    child: &mut Option<Child>,
    paths: &ChildPaths,
    boot_cap: Duration,
    budget: impl FnOnce() -> Duration,
) -> StopOutcome {
    let Some(proc) = child.as_mut() else {
        return StopOutcome::NotRunning;
    };
    let outcome = if wait_until_booted(proc, Some(&paths.ready), boot_cap) == BootWait::Exited {
        clear_cooperative_shutdown(&paths.signal);
        *child = None;
        StopOutcome::Graceful
    } else {
        let support = child_shutdown_support(&paths.ready);
        stop_with_support(child, &paths.signal, support, budget())
    };
    // Clear the ready file too, so the next stop cannot read this child's state.
    let _ = std::fs::remove_file(&paths.ready);
    outcome
}

pub fn resolve_target_directory() -> Result<PathBuf, String> {
    let metadata = cargo_metadata();
    metadata["target_directory"]
        .as_str()
        .map(PathBuf::from)
        .ok_or_else(|| "missing target_directory in cargo metadata".to_owned())
}

/// Tolerant counterpart of [`resolve_target_directory`]: `None` instead of
/// exiting when `cargo metadata` is unavailable or unreadable. Callers that
/// must keep reporting (e.g. `autumn doctor`, which runs many independent
/// checks) use this and fall back to a `target`-relative default rather than
/// aborting the whole run over one unreadable manifest.
///
/// It also never makes rustup install the project's pinned toolchain: doctor
/// runs its checks at the same time, and concurrent installs leave a toolchain
/// half-installed.
pub fn try_resolve_target_directory() -> Option<PathBuf> {
    let mut cargo = Command::new("cargo");
    cargo.args(["metadata", "--format-version=1", "--no-deps"]);
    crate::deps::no_toolchain_installs(&mut cargo);
    let output = cargo.output().ok()?;
    if !output.status.success() {
        return None;
    }
    serde_json::from_slice::<serde_json::Value>(&output.stdout)
        .ok()?
        .get("target_directory")?
        .as_str()
        .map(PathBuf::from)
}

fn cargo_metadata() -> serde_json::Value {
    let output = Command::new("cargo")
        .args(["metadata", "--format-version=1", "--no-deps"])
        .output()
        .expect("failed to run cargo metadata");

    if !output.status.success() {
        eprintln!("\u{2717} Failed to read cargo metadata");
        eprintln!("{}", String::from_utf8_lossy(&output.stderr));
        std::process::exit(1);
    }

    serde_json::from_slice(&output.stdout).expect("parse cargo metadata")
}

/// Best-effort `cargo metadata`: returns `None` instead of exiting when the
/// workspace manifests are missing/invalid. Used by lifecycle paths (e.g.
/// `autumn serve stop`) that must keep working even with a broken `Cargo.toml`.
fn try_cargo_metadata() -> Option<serde_json::Value> {
    let output = Command::new("cargo")
        .args(["metadata", "--format-version=1", "--no-deps"])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    serde_json::from_slice(&output.stdout).ok()
}

/// Directory containing a workspace member's `Cargo.toml`, resolved via
/// `cargo metadata`.
///
/// `autumn serve -p <member>` launched from a workspace root would otherwise run
/// the app with the workspace-root CWD, so the app's config loader (which falls
/// back to CWD when `AUTUMN_MANIFEST_DIR` is unset) skips the member's
/// `autumn.toml`/profile and asset dirs. Callers use this to point the child at
/// the member's directory. Best-effort: returns `None` if metadata can't be read
/// or the package isn't found, so lifecycle commands never fail solely because
/// `cargo metadata` does.
#[must_use]
pub fn find_manifest_dir(package: &str) -> Option<PathBuf> {
    let metadata = try_cargo_metadata()?;
    metadata["packages"].as_array()?.iter().find_map(|pkg| {
        if pkg["name"].as_str() == Some(package) {
            Path::new(pkg["manifest_path"].as_str()?)
                .parent()
                .map(Path::to_path_buf)
        } else {
            None
        }
    })
}

/// Resolve a binary path from parsed cargo metadata JSON.
///
/// Extracted from `find_binary` for testability. Takes the parsed
/// `cargo metadata` output and returns the path to the debug binary.
fn resolve_binary_from_metadata(
    metadata: &serde_json::Value,
    package: Option<&str>,
    cwd: &Path,
) -> Result<PathBuf, String> {
    let target_dir = metadata["target_directory"]
        .as_str()
        .ok_or("missing target_directory in metadata")?;

    let packages = metadata["packages"]
        .as_array()
        .ok_or("missing packages array in metadata")?;

    let matching_packages: Vec<_> = package.map_or_else(
        || {
            packages
                .iter()
                .filter(|pkg| {
                    let manifest = pkg["manifest_path"].as_str().unwrap_or("");
                    Path::new(manifest)
                        .parent()
                        .is_some_and(|dir| dir.starts_with(cwd))
                })
                .collect()
        },
        |pkg_name| {
            packages
                .iter()
                .filter(|pkg| pkg["name"].as_str() == Some(pkg_name))
                .collect()
        },
    );

    let bin_name = matching_packages
        .iter()
        .find_map(|pkg| {
            // Prefer `default-run` so packages with multiple binaries (e.g. a
            // `seed` binary alongside the main server) always start the right one.
            if let Some(name) = pkg["default_run"].as_str() {
                return Some(name.to_owned());
            }
            pkg["targets"].as_array()?.iter().find_map(|t| {
                let is_bin = t["kind"].as_array()?.iter().any(|k| k == "bin");
                if is_bin {
                    t["name"].as_str().map(String::from)
                } else {
                    None
                }
            })
        })
        .ok_or_else(|| {
            package.map_or_else(
                || "no binary target found in current package".to_owned(),
                |pkg_name| format!("no binary target found in package '{pkg_name}'"),
            )
        })?;

    let mut path = PathBuf::from(target_dir);
    path.push("debug");
    path.push(&bin_name);

    if cfg!(target_os = "windows") {
        path.set_extension("exe");
    }

    Ok(path)
}

/// Locate the compiled binary using `cargo metadata`.
///
/// Resolves the debug-profile path; when `release` is set, swaps the profile
/// directory to `release` (used by `autumn serve` for production builds).
pub fn find_binary(package: Option<&str>, release: bool) -> PathBuf {
    let metadata = cargo_metadata();

    let cwd = std::env::current_dir().expect("current dir");

    let path = resolve_binary_from_metadata(&metadata, package, &cwd).unwrap_or_else(|e| {
        eprintln!("\u{2717} {e}");
        if package.is_none() {
            eprintln!("  Hint: use -p <package> to specify the target package");
        }
        std::process::exit(1);
    });

    if release {
        // `.../<target>/debug/<bin>` -> `.../<target>/release/<bin>`.
        if let (Some(target_dir), Some(bin)) =
            (path.parent().and_then(Path::parent), path.file_name())
        {
            return crate::built_artifact::prefer_built(target_dir.join("release").join(bin));
        }
    }
    // `build.target` moves the artifact under `<triple>/`; use Cargo's own path.
    crate::built_artifact::prefer_built(path)
}

#[cfg(test)]
mod tests {
    // ── Cooperative child shutdown (#1616) ─────────────────────────────────
    //
    // The Windows dev loop used to stop the app with `TerminateProcess`
    // (`Child::kill`), which skips the app's `on_shutdown` hooks — so a managed
    // Postgres child was orphaned on every rebuild. `stop_child_cooperatively`
    // is the fix, and it is compiled on every platform so Linux CI actually
    // exercises the logic Windows depends on. It writes the signal file
    // autumn-web watches (`AUTUMN_SHUTDOWN_SIGNAL_FILE`), waits for the child
    // to drain, and only then escalates.

    fn signal_path(dir: &Path) -> PathBuf {
        dir.join("dev-shutdown.signal")
    }

    #[test]
    fn request_cooperative_shutdown_creates_the_file_the_runtime_watches() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = signal_path(tmp.path());
        request_cooperative_shutdown(&path).expect("signal file should be creatable");
        assert!(path.exists(), "the runtime keys off existence alone");
    }

    #[test]
    fn request_cooperative_shutdown_creates_missing_parent_directories() {
        // The signal lives beside the live-reload state under `target/autumn`,
        // which may not exist yet on a cold `autumn dev`.
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("nested").join("autumn").join("stop.signal");
        request_cooperative_shutdown(&path).expect("parents should be created");
        assert!(path.exists());
    }

    #[test]
    fn clear_cooperative_shutdown_removes_a_stale_signal() {
        // A crashed `autumn dev` can leave the file behind; the next spawn must
        // clear it or the fresh child would drain the moment it boots.
        let tmp = tempfile::TempDir::new().unwrap();
        let path = signal_path(tmp.path());
        std::fs::write(&path, b"stop").unwrap();
        clear_cooperative_shutdown(&path);
        assert!(!path.exists());
    }

    #[test]
    fn clear_cooperative_shutdown_is_a_no_op_when_absent() {
        let tmp = tempfile::TempDir::new().unwrap();
        clear_cooperative_shutdown(&signal_path(tmp.path()));
    }

    #[cfg(unix)]
    #[test]
    fn cooperative_stop_lets_a_child_that_honours_the_signal_exit_on_its_own() {
        // Stands in for an Autumn app: polls for the signal file, then exits 0
        // the way a drained app does. The outcome must be `Graceful` — that is
        // the case where `on_shutdown` hooks (managed Postgres teardown) run.
        let tmp = tempfile::TempDir::new().unwrap();
        let path = signal_path(tmp.path());
        let script = format!(
            "while [ ! -f {} ]; do sleep 0.05; done; exit 0",
            path.display()
        );
        let mut child = Some(
            Command::new("/bin/sh")
                .arg("-c")
                .arg(script)
                .spawn()
                .expect("spawn stand-in app"),
        );

        let outcome = stop_child_cooperatively(&mut child, &path, Duration::from_secs(10));
        assert_eq!(outcome, StopOutcome::Graceful);
        assert!(child.is_none(), "a stopped child must be reaped");
        assert!(
            !path.exists(),
            "the signal must be cleared so the next child does not drain at boot"
        );
    }

    #[cfg(unix)]
    #[test]
    fn cooperative_stop_escalates_when_the_child_ignores_the_signal() {
        // An app that hangs (or predates the signal) must still be stopped —
        // degraded, but never silently: the caller reports the escalation.
        let tmp = tempfile::TempDir::new().unwrap();
        let path = signal_path(tmp.path());
        let mut child = Some(
            Command::new("/bin/sh")
                .arg("-c")
                .arg("trap '' TERM; sleep 30")
                .spawn()
                .expect("spawn unresponsive app"),
        );

        let outcome = stop_child_cooperatively(&mut child, &path, Duration::from_millis(300));
        assert_eq!(outcome, StopOutcome::Escalated);
        assert!(child.is_none(), "escalation must still reap the child");
        assert!(!path.exists());
    }

    #[cfg(unix)]
    #[test]
    fn cooperative_stop_reports_unreachable_when_the_request_cannot_be_written() {
        // If the signal file cannot be created, the app was never *asked* to
        // stop. Reporting that as an escalation would blame the app for
        // ignoring a request it never received — and would hide a broken dev
        // setup behind a message about shutdown hooks.
        let tmp = tempfile::TempDir::new().unwrap();
        let blocker = tmp.path().join("blocker");
        std::fs::write(&blocker, b"not a directory").unwrap();
        let path = blocker.join("nested").join("stop.signal");

        let mut child = Some(
            Command::new("/bin/sh")
                .arg("-c")
                .arg("sleep 30")
                .spawn()
                .expect("spawn app"),
        );
        let outcome = stop_child_cooperatively(&mut child, &path, Duration::from_millis(200));
        assert_eq!(outcome, StopOutcome::Unreachable);
        assert!(child.is_none(), "the child must still be stopped");
    }

    const BOOT_CAP: Duration = Duration::from_secs(30);

    // ── A booting app is not yet watching (#2444) ──────────────────────────
    //
    // The app reads the signal file only after it starts (Postgres `initdb`,
    // migrations). The stop deadline must start when the app is up. If it
    // starts earlier, the stop kills the app and leaves the postmaster.

    /// The ready file of an app that can drain on request: the budget, the
    /// endpoint, and the capability marker, as the runtime writes them.
    fn capable_ready_payload() -> String {
        autumn_web::app::serve_ready_payload(30, "tcp 127.0.0.1:3000")
    }

    fn child_paths(dir: &Path) -> ChildPaths {
        ChildPaths {
            signal: signal_path(dir),
            ready: dir.join("dev-ready.state"),
        }
    }

    #[cfg(unix)]
    #[test]
    fn a_stop_during_boot_waits_for_ready_before_it_starts_the_deadline() {
        // Stand-in app: boots for 1s, writes the ready file, then obeys the
        // signal. The deadline must start at ready, not at the stop.
        let tmp = tempfile::TempDir::new().unwrap();
        let paths = child_paths(tmp.path());
        let payload = tmp.path().join("payload");
        std::fs::write(&payload, capable_ready_payload()).unwrap();
        let script = format!(
            "sleep 1; cp {p} {r}; while [ ! -f {s} ]; do sleep 0.05; done; exit 0",
            p = payload.display(),
            r = paths.ready.display(),
            s = paths.signal.display()
        );
        let mut child = Some(
            Command::new("/bin/sh")
                .arg("-c")
                .arg(script)
                .spawn()
                .expect("spawn booting app"),
        );
        let outcome = stop_booted_child(&mut child, &paths, BOOT_CAP, || Duration::from_secs(5));
        assert_eq!(outcome, StopOutcome::Graceful);
    }

    #[cfg(unix)]
    #[test]
    fn a_stop_during_boot_is_graceful_when_the_app_exits_before_ready() {
        let tmp = tempfile::TempDir::new().unwrap();
        let paths = child_paths(tmp.path());
        let mut child = Some(
            Command::new("/bin/sh")
                .arg("-c")
                .arg("sleep 0.5; exit 0")
                .spawn()
                .expect("spawn app"),
        );
        let outcome =
            stop_booted_child(&mut child, &paths, BOOT_CAP, || Duration::from_millis(100));
        assert_eq!(outcome, StopOutcome::Graceful);
        assert!(child.is_none(), "a stopped child must be dropped");
    }

    #[cfg(unix)]
    #[test]
    fn an_old_app_is_stopped_at_once_when_it_finishes_booting() {
        // An old `autumn-web` writes a budget-only ready file and never watches
        // the signal file. The stop waits for that file, which is the only proof
        // of the app's age, then kills it at once. It does not wait the budget.
        let tmp = tempfile::TempDir::new().unwrap();
        let paths = child_paths(tmp.path());
        let script = format!("sleep 0.5; echo 30 > {}; sleep 30", paths.ready.display());
        let mut child = Some(
            Command::new("/bin/sh")
                .arg("-c")
                .arg(script)
                .spawn()
                .expect("spawn old app"),
        );
        let started = std::time::Instant::now();
        let outcome = stop_booted_child(&mut child, &paths, BOOT_CAP, || Duration::from_secs(20));
        assert_eq!(outcome, StopOutcome::Unsupported);
        assert!(started.elapsed() < Duration::from_secs(10));
        assert!(child.is_none(), "the child must be reaped");
    }

    #[cfg(unix)]
    #[test]
    fn a_missing_ready_file_does_not_stall_a_stop_past_cap_plus_budget() {
        // The ready write is best-effort. A live app that never writes it must
        // still be stopped, after the cap and then the normal budget.
        let tmp = tempfile::TempDir::new().unwrap();
        let paths = child_paths(tmp.path());
        let mut child = Some(
            Command::new("/bin/sh")
                .arg("-c")
                .arg("trap '' TERM; sleep 30")
                .spawn()
                .expect("spawn app"),
        );
        let started = std::time::Instant::now();
        let outcome = stop_booted_child(&mut child, &paths, Duration::from_millis(300), || {
            Duration::from_millis(300)
        });
        assert_eq!(outcome, StopOutcome::Escalated);
        assert!(started.elapsed() < Duration::from_secs(10));
        assert!(child.is_none(), "the child must be reaped");
    }

    #[cfg(unix)]
    #[test]
    fn a_missing_ready_file_is_fine_when_the_app_obeys_the_signal() {
        let tmp = tempfile::TempDir::new().unwrap();
        let paths = child_paths(tmp.path());
        let script = format!(
            "while [ ! -f {} ]; do sleep 0.05; done; exit 0",
            paths.signal.display()
        );
        let mut child = Some(
            Command::new("/bin/sh")
                .arg("-c")
                .arg(script)
                .spawn()
                .expect("spawn app"),
        );
        let outcome = stop_booted_child(&mut child, &paths, Duration::from_millis(200), || {
            Duration::from_secs(10)
        });
        assert_eq!(outcome, StopOutcome::Graceful);
    }

    #[cfg(unix)]
    #[test]
    fn a_stop_clears_the_ready_file_for_the_next_child() {
        let tmp = tempfile::TempDir::new().unwrap();
        let paths = child_paths(tmp.path());
        std::fs::write(&paths.ready, capable_ready_payload()).unwrap();
        let mut child = Some(
            Command::new("/bin/sh")
                .arg("-c")
                .arg("exit 0")
                .spawn()
                .expect("spawn app"),
        );
        stop_booted_child(&mut child, &paths, BOOT_CAP, || Duration::from_secs(5));
        assert!(!paths.ready.exists());
    }

    // ── `.env` comes from the selected package (#2444) ─────────────────────

    /// Whether the shell would hide a `.env` effect in these tests. A real
    /// shell variable wins over `.env`, and `AUTUMN_DOTENV` can turn loading off.
    fn the_shell_hides_dotenv_effects() -> bool {
        ["AUTUMN_SERVER__SHUTDOWN_TIMEOUT_SECS", "AUTUMN_DOTENV"]
            .iter()
            .any(|key| std::env::var_os(key).is_some())
    }

    fn dotenv_dir_with_a_300s_timeout() -> tempfile::TempDir {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join(".env"),
            "AUTUMN_SERVER__SHUTDOWN_TIMEOUT_SECS=300\n",
        )
        .unwrap();
        tmp
    }

    #[test]
    fn the_stop_budget_reads_dotenv_from_the_package_dir_not_the_cli_cwd() {
        if the_shell_hides_dotenv_effects() {
            return;
        }
        let tmp = dotenv_dir_with_a_300s_timeout();
        let budget = stop_budget_in(tmp.path(), "dev");
        assert!(
            budget >= cooperative_stop_budget(300),
            "package .env must set the budget, got {budget:?}"
        );
    }

    #[test]
    fn the_stop_budget_loads_dotenv_for_a_profile_alias() {
        // The app treats `development` and `DEV` as `dev` and loads `.env`.
        if the_shell_hides_dotenv_effects() {
            return;
        }
        let tmp = dotenv_dir_with_a_300s_timeout();
        for alias in ["development", "DEV", " dev "] {
            let budget = stop_budget_in(tmp.path(), alias);
            assert!(
                budget >= cooperative_stop_budget(300),
                "`{alias}` must load .env, got {budget:?}"
            );
        }
    }

    #[test]
    fn the_boot_wait_notice_names_the_limit_and_the_fix() {
        let notice = boot_wait_notice(COOPERATIVE_STOP_BOOT_CAP);
        assert!(notice.contains("15 minutes"), "{notice}");
        assert!(notice.contains("cargo update -p autumn-web"), "{notice}");
    }

    #[test]
    fn unreachable_warning_blames_the_signal_file_not_the_app() {
        let warning = unreachable_warning("permission denied");
        assert!(warning.contains("permission denied"), "{warning}");
        assert!(warning.contains("shutdown hooks"), "{warning}");
        // It must NOT claim the app ignored anything.
        assert!(!warning.contains("did not shut down within"), "{warning}");
    }

    #[test]
    fn cooperative_stop_reports_not_running_without_a_child() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = signal_path(tmp.path());
        let mut child = None;
        assert_eq!(
            stop_child_cooperatively(&mut child, &path, Duration::from_secs(1)),
            StopOutcome::NotRunning
        );
    }

    // ── The stop budget must not undercut the app's own (#1616, Codex P1) ──
    //
    // A fixed ten seconds was wrong: `DrainCause::Signal` runs the app's full
    // lifecycle — readiness flip, prestop grace, drain — and THEN its
    // `on_shutdown` hooks. An app configured with the prod defaults (grace 5 +
    // timeout 30) is still legitimately shutting down at t=35s, and a managed
    // Postgres `pg_ctl stop` runs after that under its own 60s ceiling. Killing
    // at t=10s reintroduces the orphaned postmaster this change exists to fix,
    // on a perfectly valid configuration.

    #[test]
    fn the_stop_budget_never_undercuts_the_apps_configured_drain() {
        for drain_secs in [0, 1, 10, 35, 120, 3600] {
            let budget = cooperative_stop_budget(drain_secs);
            assert!(
                budget > Duration::from_secs(drain_secs),
                "a {drain_secs}s drain must not be cut short by a {budget:?} budget"
            );
        }
    }

    #[test]
    fn the_stop_budget_covers_the_managed_postgres_stop_ceiling() {
        // After the drain, `emergency_stop_async` can run a full `pg_ctl stop`.
        // The headroom must cover it. The provider limit for that stop is 60s.
        assert!(
            cooperative_stop_budget(0) >= Duration::from_secs(60),
            "the headroom must cover a managed-Postgres stop"
        );
    }

    #[test]
    fn the_stop_budget_grows_with_a_longer_configured_drain() {
        assert!(cooperative_stop_budget(35) > cooperative_stop_budget(1));
    }

    #[test]
    fn the_stop_budget_saturates_instead_of_overflowing() {
        // The drain budget comes from user config (`[server]` keys, or
        // `AUTUMN_SERVER__*`), so it is attacker-adjacent arithmetic: a
        // `u64::MAX` timeout must clamp, not wrap to a tiny budget that would
        // hard-kill instantly.
        let budget = cooperative_stop_budget(u64::MAX);
        assert!(budget >= Duration::from_secs(60), "{budget:?}");
    }

    // ── The budget must belong to the RUNNING child (#1616, Codex round 3) ──
    //
    // `autumn.toml` is a watched file, so `execute_plan` reaches the stop only
    // AFTER the edit that triggered it has landed. Resolving the budget there
    // grades the outgoing child against the incoming config: lower
    // `shutdown_timeout_secs` from 300 to 1 and the parent force-kills a child
    // that is still legitimately inside its original 300s drain — and a
    // half-saved (malformed) `autumn.toml` collapses to the defaults with the
    // same effect. Either way the `on_shutdown` hooks are skipped and the
    // managed cluster is orphaned, which is the bug this all exists to prevent.

    // ── The child's OWN budget beats any CLI reconstruction (Codex round 5) ──
    //
    // An app using `AppBuilder::with_config_loader` can resolve a budget no
    // amount of TOML/env reading reproduces. The runtime already solved this for
    // `autumn serve`: the app writes its resolved drain budget to the file named
    // by `AUTUMN_SERVE_READY_FILE`, and `signal_serve_ready`'s contract says why
    // — so `stop` "waits for the budget the app will actually drain for ...
    // instead of reconstructing it from TOML/env and risking a premature
    // SIGKILL". `autumn dev` was doing exactly the reconstructing it warns about.

    #[test]
    fn a_child_reported_budget_beats_everything_the_cli_can_reconstruct() {
        let budget = stop_budget_for_running_child(
            Some(Duration::from_secs(360)),
            Some(Duration::from_secs(61)),
            || Duration::from_secs(95),
        );
        assert_eq!(budget, Duration::from_secs(360));
    }

    #[test]
    fn the_recorded_budget_is_used_when_the_child_reported_nothing() {
        // Stopped before it finished booting: no ready file yet, so the
        // spawn-time estimate is the best available answer.
        let budget = stop_budget_for_running_child(None, Some(Duration::from_secs(61)), || {
            Duration::from_secs(95)
        });
        assert_eq!(budget, Duration::from_secs(61));
    }

    #[test]
    fn resolving_is_the_last_resort() {
        let budget = stop_budget_for_running_child(None, None, || Duration::from_secs(95));
        assert_eq!(budget, Duration::from_secs(95));
    }

    #[test]
    fn the_reported_budget_gets_the_same_hook_headroom() {
        // The app reports its drain budget (prestop + shutdown). The headroom
        // still applies. Without it, a slow Postgres stop is killed.
        let tmp = tempfile::TempDir::new().unwrap();
        let ready = tmp.path().join("dev-ready.state");
        std::fs::write(&ready, "300\n").unwrap();
        assert_eq!(
            child_reported_stop_budget(&ready),
            Some(cooperative_stop_budget(300))
        );
    }

    #[test]
    fn the_budget_survives_the_readiness_file_gaining_an_address_line() {
        // The runtime writes the budget on line one and its bound address on
        // line two (#1639). Written by the runtime's OWN writer, so a future
        // format change fails here rather than silently costing every Windows
        // rebuild its drain budget and reintroducing the orphaned-cluster bug.
        let tmp = tempfile::TempDir::new().unwrap();
        let ready = tmp.path().join("dev-ready.state");
        std::fs::write(
            &ready,
            autumn_web::app::serve_ready_payload(300, "tcp 127.0.0.1:3000"),
        )
        .unwrap();
        assert_eq!(
            child_reported_stop_budget(&ready),
            Some(cooperative_stop_budget(300))
        );
    }

    #[test]
    fn a_missing_or_unparseable_report_is_ignored_rather_than_misread() {
        let tmp = tempfile::TempDir::new().unwrap();
        let ready = tmp.path().join("dev-ready.state");
        assert_eq!(child_reported_stop_budget(&ready), None, "absent");
        std::fs::write(&ready, "not-a-number").unwrap();
        assert_eq!(child_reported_stop_budget(&ready), None, "junk");
        std::fs::write(&ready, "  ").unwrap();
        assert_eq!(child_reported_stop_budget(&ready), None, "blank");
    }

    #[test]
    fn the_ready_file_env_var_is_the_one_the_runtime_reads() {
        // `autumn/src/app.rs::signal_serve_ready` reads this exact name; a
        // rename on either side silently returns `autumn dev` to guessing.
        assert_eq!(SERVE_READY_FILE_ENV, "AUTUMN_SERVE_READY_FILE");
        assert_eq!(SERVE_READY_FILE_ENV, crate::serve::SERVE_READY_FILE_ENV);
    }

    #[test]
    fn the_stop_budget_uses_the_value_recorded_when_the_child_was_spawned() {
        let recorded = Some(Duration::from_secs(300));
        let budget = stop_budget_for_running_child(None, recorded, || Duration::from_secs(95));
        assert_eq!(budget, Duration::from_secs(300));
    }

    #[test]
    fn the_stop_budget_does_not_re_read_config_when_one_was_recorded() {
        // Not just "returns the right number": it must not touch the config at
        // all, or a malformed save mid-edit could still influence the stop.
        let consulted = std::cell::Cell::new(false);
        let _ = stop_budget_for_running_child(None, Some(Duration::from_secs(300)), || {
            consulted.set(true);
            Duration::from_secs(95)
        });
        assert!(
            !consulted.get(),
            "a recorded budget must not re-read the (possibly just-edited) config"
        );
    }

    #[test]
    fn the_stop_budget_falls_back_when_nothing_was_recorded() {
        // No child was spawned through `start_server` this session (or the
        // spawn predates the recording); resolving now is the best available
        // answer and is still better than a fixed constant.
        let budget = stop_budget_for_running_child(None, None, || Duration::from_secs(95));
        assert_eq!(budget, Duration::from_secs(95));
    }

    #[test]
    fn the_resolved_budget_covers_an_unconfigured_project() {
        // Resolving against a directory with no `autumn.toml` must still yield a
        // budget that outlasts a managed-Postgres teardown, not zero.
        assert!(resolve_cooperative_stop_budget(None) >= COOPERATIVE_STOP_HOOK_HEADROOM);
    }

    /// Reads `STARTUP_TIMEOUT` from the framework source.
    /// The CLI does not enable `managed-pg`. It cannot import the constant.
    fn managed_pg_stop_ceiling_from_source() -> Duration {
        let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../autumn/src/managed_pg.rs");
        let source = std::fs::read_to_string(&path).expect("read managed_pg.rs");
        let secs = source
            .lines()
            .find(|l| l.contains("const STARTUP_TIMEOUT: Duration"))
            .and_then(|l| l.split("from_secs(").nth(1))
            .and_then(|l| l.split(')').next())
            .and_then(|n| n.trim().parse::<u64>().ok())
            .expect("parse STARTUP_TIMEOUT");
        Duration::from_secs(secs)
    }

    #[test]
    fn the_ceiling_constant_matches_the_framework() {
        assert_eq!(
            MANAGED_PG_STOP_CEILING,
            managed_pg_stop_ceiling_from_source()
        );
    }

    #[test]
    fn the_headroom_exceeds_the_managed_pg_stop_ceiling() {
        assert!(COOPERATIVE_STOP_HOOK_HEADROOM > managed_pg_stop_ceiling_from_source());
    }

    #[test]
    fn escalation_warning_names_the_consequence_not_just_the_timeout() {
        // "silent degradation" is the thing #1616 forbids: if hooks were
        // skipped, the developer has to be told what that means for them.
        let warning = escalation_warning(Duration::from_secs(10));
        assert!(warning.contains("10s"), "{warning}");
        assert!(warning.contains("shutdown hooks"), "{warning}");
        assert!(warning.contains("Postgres"), "{warning}");
    }

    #[test]
    fn child_paths_sit_in_the_given_directory() {
        let dir = Path::new("target").join("autumn");
        let paths = child_paths_in(&dir, 7, 1, 1);
        assert_eq!(paths.signal.parent(), Some(dir.as_path()));
        assert_eq!(paths.ready.parent(), Some(dir.as_path()));
    }

    #[test]
    fn child_paths_carry_the_process_id_and_the_generation() {
        // Two `autumn dev` runs in one workspace share a target directory. A
        // shared file would let one run drain the other's app.
        let dir = Path::new("d");
        let first = child_paths_in(dir, 42, 5, 1);
        let name = first.signal.file_name().and_then(|n| n.to_str()).unwrap();
        assert!(name.starts_with(DEV_SHUTDOWN_SIGNAL_PREFIX), "{name}");
        assert!(name.ends_with(DEV_SHUTDOWN_SIGNAL_SUFFIX), "{name}");
        assert!(name.contains("42"), "{name}");
        assert_ne!(first, child_paths_in(dir, 43, 5, 1), "other process");
        // The OS reuses process ids. A later run with the same id must not
        // reach the files an unclean exit left behind.
        assert_ne!(first, child_paths_in(dir, 42, 6, 1), "same id, later run");
    }

    #[test]
    fn a_writable_state_dir_is_usable_and_is_created_when_missing() {
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("target").join("autumn");
        assert!(state_dir_is_usable(&dir, 7, 1));
        assert!(dir.is_dir());
        assert_eq!(
            std::fs::read_dir(&dir).unwrap().count(),
            0,
            "the probe file must not stay"
        );
    }

    #[test]
    fn a_probe_file_left_by_an_earlier_run_does_not_block_this_one() {
        // A run that died mid-probe leaves its file. A later run with the same
        // process id has another nonce, so it uses other names.
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::write(tmp.path().join("dev-probe.7.1"), b"left behind").unwrap();
        assert!(state_dir_is_usable(tmp.path(), 7, 2));
        assert!(
            tmp.path().join("dev-probe.7.1").exists(),
            "the other run's file is not touched"
        );
    }

    #[test]
    fn a_state_dir_that_cannot_exist_is_not_usable() {
        // `<target>/autumn` is a regular file, so nothing can live in it.
        let tmp = tempfile::TempDir::new().unwrap();
        let blocker = tmp.path().join("autumn");
        std::fs::write(&blocker, b"not a directory").unwrap();
        assert!(!state_dir_is_usable(&blocker, 7, 1));
        assert!(!state_dir_is_usable(&blocker.join("nested"), 7, 1));
    }

    #[test]
    fn a_failed_setup_forgets_the_last_childs_paths() {
        // The next child gets no marker paths. A stop must then use the hard
        // stop, not wait on the last child's removed ready file.
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("autumn");
        let slot = std::sync::Mutex::new(None);
        let generation = std::sync::atomic::AtomicU64::new(0);

        let first = next_child_paths(&slot, &generation, Some(&dir), 7, 1).expect("first child");
        assert_eq!(*slot.lock().unwrap(), Some(first.clone()));
        std::fs::write(&first.signal, b"").unwrap();
        std::fs::write(&first.ready, b"30\n").unwrap();

        // The directory stops being usable: a regular file takes its place.
        std::fs::remove_dir_all(&dir).unwrap();
        std::fs::write(&dir, b"not a directory").unwrap();
        assert_eq!(next_child_paths(&slot, &generation, Some(&dir), 7, 1), None);
        assert_eq!(*slot.lock().unwrap(), None, "the old paths must be gone");

        // With no state directory at all, the result is the same.
        assert_eq!(next_child_paths(&slot, &generation, None, 7, 1), None);
        assert_eq!(*slot.lock().unwrap(), None);
    }

    #[test]
    fn a_new_child_removes_the_last_childs_files() {
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("autumn");
        let slot = std::sync::Mutex::new(None);
        let generation = std::sync::atomic::AtomicU64::new(0);

        let first = next_child_paths(&slot, &generation, Some(&dir), 7, 1).unwrap();
        std::fs::write(&first.signal, b"").unwrap();
        std::fs::write(&first.ready, b"30\n").unwrap();
        let second = next_child_paths(&slot, &generation, Some(&dir), 7, 1).unwrap();

        assert_ne!(first, second);
        assert!(!first.signal.exists() && !first.ready.exists());
        assert_eq!(*slot.lock().unwrap(), Some(second));
    }

    #[test]
    fn each_child_gets_paths_no_earlier_child_used() {
        // An old file that could not be deleted must not pass for the new
        // child's shutdown request or ready file.
        let dir = Path::new("d");
        let first = child_paths_in(dir, 42, 5, 1);
        let second = child_paths_in(dir, 42, 5, 2);
        assert_ne!(first.signal, second.signal);
        assert_ne!(first.ready, second.ready);
    }

    #[test]
    fn the_state_dir_is_cached_across_calls() {
        // The stop path reads this. Resolving per stop would run `cargo
        // metadata` on every rebuild, and could fail on a half-saved
        // Cargo.toml, inside the stop, where a failure orphans the app.
        assert_eq!(dev_state_dir(), dev_state_dir());
    }

    #[test]
    fn dev_shutdown_env_var_matches_the_runtime_constant() {
        assert_eq!(
            DEV_SHUTDOWN_SIGNAL_ENV,
            autumn_web::app::SHUTDOWN_SIGNAL_FILE_ENV,
            "the CLI and the runtime must agree on the wire name"
        );
    }

    // ── Negotiate the shutdown signal (#2458) ──────────────────────────────
    //
    // A project can keep an `autumn-web` that predates the signal file. It never
    // watches the file, so waiting out the budget stalls every edit. The ready
    // file says which kind of child is running.

    #[test]
    fn a_ready_file_with_the_marker_means_the_child_will_drain() {
        let payload = autumn_web::app::serve_ready_payload(1, "tcp 127.0.0.1:3000");
        assert_eq!(
            shutdown_support_from_ready(Some(&payload)),
            ShutdownSupport::Supported
        );
    }

    #[test]
    fn a_budget_only_ready_file_means_the_child_cannot_drain() {
        for old in ["1", "1\n", " 1 \n\n"] {
            assert_eq!(
                shutdown_support_from_ready(Some(old)),
                ShutdownSupport::Unsupported,
                "{old:?}"
            );
        }
    }

    #[test]
    fn a_release_with_an_endpoint_line_but_no_marker_still_drains() {
        // 0.8.0 watches the signal file and reports an endpoint, but has no
        // marker. Killing it would skip its hooks and orphan Postgres.
        assert_eq!(
            shutdown_support_from_ready(Some("1\ntcp 127.0.0.1:3000")),
            ShutdownSupport::Unknown
        );
    }

    #[test]
    fn an_unreadable_ready_file_is_not_proof_of_an_old_child() {
        for junk in ["garbage", "x\ny", "1 2"] {
            assert_eq!(
                shutdown_support_from_ready(Some(junk)),
                ShutdownSupport::Unknown,
                "{junk:?}"
            );
        }
    }

    #[test]
    fn no_ready_file_means_the_child_is_still_booting() {
        // Cannot tell a slow boot from an old child. Keep the cooperative wait.
        assert_eq!(shutdown_support_from_ready(None), ShutdownSupport::Unknown);
    }

    #[test]
    fn a_blank_ready_file_is_not_proof_of_an_old_child() {
        // The app writes the file atomically, so a blank file is not its work.
        assert_eq!(
            shutdown_support_from_ready(Some("  \n")),
            ShutdownSupport::Unknown
        );
    }

    #[test]
    fn the_ready_file_support_is_read_from_disk() {
        let tmp = tempfile::TempDir::new().unwrap();
        let ready = tmp.path().join("dev-ready.state");
        assert_eq!(child_shutdown_support(&ready), ShutdownSupport::Unknown);
        std::fs::write(&ready, "1\n").unwrap();
        assert_eq!(child_shutdown_support(&ready), ShutdownSupport::Unsupported);
        std::fs::write(&ready, autumn_web::app::serve_ready_payload(1, "")).unwrap();
        assert_eq!(child_shutdown_support(&ready), ShutdownSupport::Supported);
    }

    #[cfg(unix)]
    #[test]
    fn an_unsupported_child_is_killed_at_once_without_a_signal_file() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = signal_path(tmp.path());
        let mut child = Some(
            Command::new("/bin/sh")
                .arg("-c")
                .arg("trap '' TERM; sleep 30")
                .spawn()
                .expect("spawn old app"),
        );
        let start = std::time::Instant::now();
        let outcome = stop_unsupported_child(&mut child, &path);
        assert_eq!(outcome, StopOutcome::Unsupported);
        assert!(start.elapsed() < Duration::from_secs(10), "must not wait");
        assert!(child.is_none(), "the child must be reaped");
        assert!(
            !path.exists(),
            "no request is sent to a child that ignores it"
        );
    }

    #[cfg(unix)]
    #[test]
    fn an_unsupported_child_is_never_sent_a_request() {
        // A path under a regular file cannot be created. A request would turn
        // the outcome into `Unreachable`, so `Unsupported` proves none was made.
        let tmp = tempfile::TempDir::new().unwrap();
        let blocker = tmp.path().join("blocker");
        std::fs::write(&blocker, b"not a directory").unwrap();
        let path = blocker.join("nested").join("stop.signal");
        let mut child = Some(
            Command::new("/bin/sh")
                .arg("-c")
                .arg("sleep 30")
                .spawn()
                .expect("spawn old app"),
        );
        assert_eq!(
            stop_unsupported_child(&mut child, &path),
            StopOutcome::Unsupported
        );
    }

    #[cfg(unix)]
    #[test]
    fn the_stop_plan_kills_an_unsupported_child_without_waiting_out_the_budget() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = signal_path(tmp.path());
        let mut child = Some(
            Command::new("/bin/sh")
                .arg("-c")
                .arg("trap '' TERM; sleep 30")
                .spawn()
                .expect("spawn old app"),
        );
        let start = std::time::Instant::now();
        let outcome = stop_with_support(
            &mut child,
            &path,
            ShutdownSupport::Unsupported,
            Duration::from_secs(300),
        );
        assert_eq!(outcome, StopOutcome::Unsupported);
        assert!(start.elapsed() < Duration::from_secs(10), "must not wait");
    }

    #[cfg(unix)]
    #[test]
    fn the_stop_plan_keeps_the_cooperative_wait_when_support_is_unknown() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = signal_path(tmp.path());
        let script = format!(
            "while [ ! -f {} ]; do sleep 0.05; done; exit 0",
            path.display()
        );
        for support in [ShutdownSupport::Unknown, ShutdownSupport::Supported] {
            let mut child = Some(
                Command::new("/bin/sh")
                    .arg("-c")
                    .arg(&script)
                    .spawn()
                    .expect("spawn app"),
            );
            let outcome = stop_with_support(&mut child, &path, support, Duration::from_secs(10));
            assert_eq!(outcome, StopOutcome::Graceful, "{support:?}");
        }
    }

    #[test]
    fn an_unsupported_stop_with_no_child_is_not_running() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut child = None;
        assert_eq!(
            stop_unsupported_child(&mut child, &signal_path(tmp.path())),
            StopOutcome::NotRunning
        );
    }

    #[test]
    fn the_unsupported_warning_names_the_cause_and_the_fix() {
        let warning = unsupported_warning();
        assert!(warning.contains("autumn-web"), "{warning}");
        assert!(warning.contains("cargo update"), "{warning}");
        assert!(warning.contains("Postgres"), "{warning}");
        assert!(!warning.contains("did not shut down within"), "{warning}");
    }

    use super::*;

    // ── is_relevant_change tests ───────────────────────────────────

    #[test]
    fn relevant_rust_file() {
        assert!(is_relevant_change(
            Path::new("src/main.rs"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    #[test]
    fn relevant_toml_config() {
        assert!(is_relevant_change(
            Path::new("autumn.toml"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    #[test]
    fn relevant_cargo_toml() {
        assert!(is_relevant_change(
            Path::new("Cargo.toml"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    #[test]
    fn relevant_css_file() {
        assert!(is_relevant_change(
            Path::new("static/css/style.css"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    #[test]
    fn ignores_generated_tailwind_output() {
        assert!(!is_relevant_change(
            Path::new("static/css/autumn.css"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    #[test]
    fn build_rs_change_requires_build_restart() {
        assert_eq!(
            classify_change(Path::new("build.rs"), DebouncedEventKind::Any, &[]),
            ChangeEffect::BuildRestart
        );
    }

    #[test]
    fn profile_config_change_requires_restart_only() {
        assert_eq!(
            classify_change(Path::new("autumn-dev.toml"), DebouncedEventKind::Any, &[]),
            ChangeEffect::RestartOnly
        );
    }

    #[test]
    fn dotenv_change_requires_restart_only() {
        for name in [".env", ".env.local", ".env.dev", ".env.production.local"] {
            assert_eq!(
                classify_change(Path::new(name), DebouncedEventKind::Any, &[]),
                ChangeEffect::RestartOnly,
                "{name} should restart the dev server",
            );
        }
    }

    #[test]
    fn dotenv_editor_temp_files_are_ignored() {
        // Editor swap/backup files must not trigger spurious restarts.
        for name in [
            ".env.swp",
            ".env.swo",
            ".env~",
            ".env.local~",
            ".env.tmp",
            ".env.bak",
        ] {
            assert_eq!(
                classify_change(Path::new(name), DebouncedEventKind::Any, &[]),
                ChangeEffect::Ignore,
                "{name} should not restart the dev server",
            );
        }
    }

    #[test]
    fn dotenv_change_ignored_for_non_any_event() {
        // A dotenv edit still only restarts on a settled `Any` event.
        assert_eq!(
            classify_change(Path::new(".env"), DebouncedEventKind::AnyContinuous, &[]),
            ChangeEffect::Ignore
        );
    }

    #[test]
    fn nested_dotenv_under_hidden_dir_is_ignored() {
        // Only root-level dotenv files are un-ignored; `.git/.env` stays ignored.
        assert_eq!(
            classify_change(Path::new(".git/.env"), DebouncedEventKind::Any, &[]),
            ChangeEffect::Ignore
        );
    }

    #[test]
    fn a_member_dir_outside_the_root_is_watched() {
        let root = tempfile::TempDir::new().unwrap();
        let member = root.path().join("api");
        std::fs::create_dir(&member).unwrap();
        assert_eq!(member_dir_to_watch(&member, root.path()), Some(member));
    }

    #[test]
    fn a_dotenv_under_a_hidden_ancestor_is_judged_inside_the_watch_root() {
        // The workspace lives under a dot-prefixed directory. Judged by its
        // full path, the member `.env` would be ignored as a hidden file.
        let member = PathBuf::from("/home/alice/.worktrees/project/api");
        let roots = vec![member.clone()];
        let event = member.join(".env");
        assert!(
            !is_watched_dotenv_file(&event),
            "the full path is rejected, which is the bug"
        );
        let inside = strip_watch_root(&event, &roots);
        assert_eq!(inside, Path::new(".env"));
        assert!(is_watched_dotenv_file(inside));
    }

    #[test]
    fn the_most_specific_watch_root_wins_when_roots_nest() {
        // The member sits under a hidden directory inside the workspace. Strip
        // the member root, not the workspace root, or `.env` looks hidden.
        let workspace = PathBuf::from("/work");
        let member = workspace.join(".apps").join("api");
        let event = member.join(".env");
        for roots in [
            vec![workspace.clone(), member.clone()],
            vec![member, workspace],
        ] {
            let inside = strip_watch_root(&event, &roots);
            assert_eq!(inside, Path::new(".env"), "roots: {roots:?}");
            assert!(is_watched_dotenv_file(inside));
        }
    }

    #[test]
    fn a_custom_watch_dir_still_matches_by_the_full_event_path() {
        // The member is nested in the workspace, and the workspace config lists
        // a directory inside it. Stripping the watch root for the hidden-file
        // checks must not stop the full-path match.
        let workspace = PathBuf::from("/work");
        let member = workspace.join("crates").join("api");
        let views = member.join("views");
        let custom = vec![CustomWatchDir {
            relative: PathBuf::from("crates/api/views"),
            absolute: views.clone(),
        }];
        let roots = vec![workspace, member];
        let effect = classify_change_in(
            &views.join("page.html"),
            DebouncedEventKind::Any,
            &custom,
            &roots,
        );
        assert_eq!(effect, ChangeEffect::RestartOnly);
    }

    #[test]
    fn a_hidden_directory_inside_the_watch_root_is_still_ignored() {
        let root = PathBuf::from("/home/alice/.worktrees/project");
        let event = root.join(".git").join(".env");
        assert!(!is_watched_dotenv_file(strip_watch_root(&event, &[root])));
    }

    #[test]
    fn a_path_outside_every_watch_root_is_left_alone() {
        let roots = vec![PathBuf::from("/work/api")];
        let event = Path::new("/elsewhere/.env");
        assert_eq!(strip_watch_root(event, &roots), event);
        assert_eq!(strip_watch_root(event, &[]), event);
    }

    #[test]
    fn the_project_root_is_not_watched_twice() {
        let root = tempfile::TempDir::new().unwrap();
        assert_eq!(member_dir_to_watch(root.path(), root.path()), None);
    }

    #[test]
    fn is_watched_dotenv_file_classifies_variants() {
        assert!(is_watched_dotenv_file(Path::new(".env")));
        assert!(is_watched_dotenv_file(Path::new(".env.local")));
        assert!(is_watched_dotenv_file(Path::new(".env.dev")));
        assert!(is_watched_dotenv_file(Path::new(".env.dev.local")));
        // Root-level file behind an absolute project path still matches.
        assert!(is_watched_dotenv_file(Path::new("/home/alice/app/.env")));
        // Non-loaded / decorated names do not.
        assert!(!is_watched_dotenv_file(Path::new(".env.swp")));
        assert!(!is_watched_dotenv_file(Path::new(".env.example")));
        assert!(!is_watched_dotenv_file(Path::new("env")));
        // A dotenv-named file under a dotted directory is not root-level.
        assert!(!is_watched_dotenv_file(Path::new(".git/.env")));
    }

    #[test]
    fn css_input_change_runs_tailwind_without_build() {
        let events = [notify_debouncer_mini::DebouncedEvent {
            path: PathBuf::from("static/css/input.css"),
            kind: DebouncedEventKind::Any,
        }];
        let plan = plan_changes(&events, &[]);
        assert_eq!(
            plan,
            ChangePlan {
                build: false,
                restart: false,
                tailwind: true,
                reload: ReloadKind::Css,
            }
        );
    }

    #[test]
    fn static_asset_change_triggers_browser_reload_only() {
        let events = [notify_debouncer_mini::DebouncedEvent {
            path: PathBuf::from("static/images/logo.png"),
            kind: DebouncedEventKind::Any,
        }];
        let plan = plan_changes(&events, &[]);
        assert_eq!(
            plan,
            ChangePlan {
                build: false,
                restart: false,
                tailwind: false,
                reload: ReloadKind::Full,
            }
        );
    }

    #[test]
    fn mixed_config_and_css_changes_restart_and_rebuild_css() {
        let events = [
            notify_debouncer_mini::DebouncedEvent {
                path: PathBuf::from("autumn-dev.toml"),
                kind: DebouncedEventKind::Any,
            },
            notify_debouncer_mini::DebouncedEvent {
                path: PathBuf::from("static/css/input.css"),
                kind: DebouncedEventKind::Any,
            },
        ];
        let plan = plan_changes(&events, &[]);
        assert_eq!(
            plan,
            ChangePlan {
                build: false,
                restart: true,
                tailwind: true,
                reload: ReloadKind::Full,
            }
        );
    }

    #[test]
    fn build_restart_overrides_tailwind_only_changes() {
        let events = [
            notify_debouncer_mini::DebouncedEvent {
                path: PathBuf::from("src/main.rs"),
                kind: DebouncedEventKind::Any,
            },
            notify_debouncer_mini::DebouncedEvent {
                path: PathBuf::from("static/css/input.css"),
                kind: DebouncedEventKind::Any,
            },
        ];
        let plan = plan_changes(&events, &[]);
        assert_eq!(
            plan,
            ChangePlan {
                build: true,
                restart: true,
                tailwind: false,
                reload: ReloadKind::Full,
            }
        );
    }

    #[test]
    fn ignores_generated_dev_reload_state_file() {
        assert_eq!(
            classify_change(
                Path::new("target/autumn/live-reload.json"),
                DebouncedEventKind::Any,
                &[],
            ),
            ChangeEffect::Ignore
        );
    }

    #[test]
    fn relevant_html_file() {
        assert!(is_relevant_change(
            Path::new("templates/index.html"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    #[test]
    fn relevant_sql_migration() {
        assert!(is_relevant_change(
            Path::new("migrations/001_init.sql"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    #[test]
    fn relevant_js_file() {
        assert!(is_relevant_change(
            Path::new("static/js/app.js"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    #[test]
    fn relevant_nested_rust_file() {
        assert!(is_relevant_change(
            Path::new("src/routes/api/handlers.rs"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    #[test]
    fn ignores_target_directory() {
        assert!(!is_relevant_change(
            Path::new("target/debug/build/main.rs"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    #[test]
    fn ignores_hidden_files() {
        assert!(!is_relevant_change(
            Path::new(".git/config"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    #[test]
    fn ignores_hidden_directory_nested() {
        assert!(!is_relevant_change(
            Path::new("src/.hidden/module.rs"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    #[test]
    fn ignores_irrelevant_extensions() {
        assert!(!is_relevant_change(
            Path::new("src/notes.txt"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    #[test]
    fn ignores_non_any_events() {
        assert!(!is_relevant_change(
            Path::new("src/main.rs"),
            DebouncedEventKind::AnyContinuous,
            &[],
        ));
    }

    #[test]
    fn cargo_lock_triggers_rebuild() {
        assert!(is_relevant_change(
            Path::new("Cargo.lock"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    #[test]
    fn ignores_file_without_extension() {
        assert!(!is_relevant_change(
            Path::new("src/Makefile"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    #[test]
    fn relevant_image_files_trigger_browser_reload() {
        assert!(is_relevant_change(
            Path::new("static/logo.png"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    #[test]
    fn ignores_target_nested_deeply() {
        assert!(!is_relevant_change(
            Path::new("target/release/deps/libfoo.rs"),
            DebouncedEventKind::Any,
            &[],
        ));
    }

    // ── collect_relevant_changes tests ─────────────────────────────

    #[test]
    fn collect_changes_filters_irrelevant() {
        let events = vec![
            notify_debouncer_mini::DebouncedEvent {
                path: PathBuf::from("src/main.rs"),
                kind: DebouncedEventKind::Any,
            },
            notify_debouncer_mini::DebouncedEvent {
                path: PathBuf::from("README.md"),
                kind: DebouncedEventKind::Any,
            },
            notify_debouncer_mini::DebouncedEvent {
                path: PathBuf::from("src/lib.rs"),
                kind: DebouncedEventKind::Any,
            },
        ];
        let changed = collect_relevant_changes(&events, &[]);
        assert_eq!(changed.len(), 2);
        assert!(changed.iter().any(|c| c.contains("main.rs")));
        assert!(changed.iter().any(|c| c.contains("lib.rs")));
    }

    #[test]
    fn collect_changes_returns_empty_for_no_relevant() {
        let events = vec![
            notify_debouncer_mini::DebouncedEvent {
                path: PathBuf::from("README.md"),
                kind: DebouncedEventKind::Any,
            },
            notify_debouncer_mini::DebouncedEvent {
                path: PathBuf::from("target/debug/app"),
                kind: DebouncedEventKind::Any,
            },
        ];
        let changed = collect_relevant_changes(&events, &[]);
        assert!(changed.is_empty());
    }

    #[test]
    fn collect_changes_handles_empty_events() {
        let changed = collect_relevant_changes(&[], &[]);
        assert!(changed.is_empty());
    }

    // ── build_cargo_command tests ──────────────────────────────────

    #[test]
    fn build_command_without_package() {
        let cmd = build_cargo_command(None, false);
        let args: Vec<_> = cmd.get_args().collect();
        assert_eq!(cmd.get_program(), "cargo");
        assert_eq!(args, &["build"]);
    }

    #[test]
    fn build_command_with_package() {
        let cmd = build_cargo_command(Some("my-app"), false);
        let args: Vec<_> = cmd.get_args().collect();
        assert_eq!(cmd.get_program(), "cargo");
        assert_eq!(args, &["build", "-p", "my-app"]);
    }

    #[test]
    fn build_command_release_adds_flag() {
        let cmd = build_cargo_command(None, true);
        let args: Vec<_> = cmd.get_args().collect();
        assert_eq!(args, &["build", "--release"]);
    }

    #[test]
    fn build_tailwind_command_for_sets_expected_args() {
        let cmd = build_tailwind_command_for(Path::new("tailwindcss"));
        let args: Vec<_> = cmd.get_args().collect();
        assert_eq!(cmd.get_program(), "tailwindcss");
        assert_eq!(
            args,
            &[
                "-i",
                "static/css/input.css",
                "-o",
                "static/css/autumn.css",
                "--content",
                "src/**/*.rs",
                "--minify",
            ]
        );
    }

    // ── start_server tests ─────────────────────────────────────────

    #[test]
    fn start_server_returns_none_for_missing_binary() {
        let result = start_server(Path::new("/nonexistent/binary/path"), None, None, false);
        assert!(result.is_none());
    }

    #[cfg(unix)]
    #[test]
    fn start_server_returns_child_for_valid_binary() {
        let child = start_server(Path::new("/bin/sleep"), None, None, false);
        assert!(child.is_some());
        // Clean up
        let mut child = child.unwrap();
        let _ = child.kill();
        let _ = child.wait();
    }

    // ── resolve_binary_from_metadata tests ─────────────────────────

    /// Build the expected binary path, accounting for `.exe` on Windows.
    fn expected_binary(path: &str) -> PathBuf {
        let mut p = PathBuf::from(path);
        if cfg!(target_os = "windows") {
            p.set_extension("exe");
        }
        p
    }

    fn sample_metadata(target_dir: &str, pkg_name: &str, manifest_dir: &str) -> serde_json::Value {
        serde_json::json!({
            "target_directory": target_dir,
            "packages": [{
                "name": pkg_name,
                "manifest_path": format!("{manifest_dir}/Cargo.toml"),
                "targets": [{
                    "name": pkg_name,
                    "kind": ["bin"],
                    "src_path": format!("{manifest_dir}/src/main.rs")
                }]
            }]
        })
    }

    #[test]
    fn resolve_binary_by_package_name() {
        let metadata = sample_metadata("/tmp/target", "hello", "/projects/hello");
        let result =
            resolve_binary_from_metadata(&metadata, Some("hello"), Path::new("/projects/hello"));
        assert!(result.is_ok());
        let path = result.unwrap();
        assert_eq!(path, expected_binary("/tmp/target/debug/hello"));
    }

    #[test]
    fn resolve_binary_by_cwd() {
        let metadata = sample_metadata("/tmp/target", "hello", "/projects/hello");
        let result = resolve_binary_from_metadata(&metadata, None, Path::new("/projects/hello"));
        assert!(result.is_ok());
        let path = result.unwrap();
        assert_eq!(path, expected_binary("/tmp/target/debug/hello"));
    }

    #[test]
    fn resolve_binary_package_not_found() {
        let metadata = sample_metadata("/tmp/target", "hello", "/projects/hello");
        let result = resolve_binary_from_metadata(
            &metadata,
            Some("nonexistent"),
            Path::new("/projects/hello"),
        );
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .contains("no binary target found in package 'nonexistent'")
        );
    }

    #[test]
    fn resolve_binary_no_match_by_cwd() {
        let metadata = sample_metadata("/tmp/target", "hello", "/projects/hello");
        let result = resolve_binary_from_metadata(&metadata, None, Path::new("/other/directory"));
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .contains("no binary target found in current package")
        );
    }

    #[test]
    fn resolve_binary_missing_target_directory() {
        let metadata = serde_json::json!({"packages": []});
        let result = resolve_binary_from_metadata(&metadata, None, Path::new("/tmp"));
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("target_directory"));
    }

    #[test]
    fn resolve_binary_missing_packages() {
        let metadata = serde_json::json!({"target_directory": "/tmp/target"});
        let result = resolve_binary_from_metadata(&metadata, None, Path::new("/tmp"));
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("packages"));
    }

    #[test]
    fn resolve_binary_skips_lib_targets() {
        let metadata = serde_json::json!({
            "target_directory": "/tmp/target",
            "packages": [{
                "name": "mylib",
                "manifest_path": "/projects/mylib/Cargo.toml",
                "targets": [{
                    "name": "mylib",
                    "kind": ["lib"],
                    "src_path": "/projects/mylib/src/lib.rs"
                }]
            }]
        });
        let result =
            resolve_binary_from_metadata(&metadata, Some("mylib"), Path::new("/projects/mylib"));
        assert!(result.is_err());
    }

    #[test]
    fn resolve_binary_picks_first_bin_in_multi_target() {
        let metadata = serde_json::json!({
            "target_directory": "/tmp/target",
            "packages": [{
                "name": "multi",
                "manifest_path": "/projects/multi/Cargo.toml",
                "targets": [
                    {"name": "multi", "kind": ["lib"]},
                    {"name": "server", "kind": ["bin"]},
                    {"name": "cli", "kind": ["bin"]}
                ]
            }]
        });
        let result =
            resolve_binary_from_metadata(&metadata, Some("multi"), Path::new("/projects/multi"));
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), expected_binary("/tmp/target/debug/server"));
    }

    // Regression: packages with multiple binaries (e.g. `seed` + main server)
    // must start the `default-run` binary, not whichever happens to be listed
    // first in `cargo metadata` targets.
    #[test]
    fn resolve_binary_prefers_default_run_over_first_target() {
        let metadata = serde_json::json!({
            "target_directory": "/tmp/target",
            "packages": [{
                "name": "todo-app",
                "manifest_path": "/projects/todo-app/Cargo.toml",
                "default_run": "todo-app",
                "targets": [
                    {"name": "seed",     "kind": ["bin"]},
                    {"name": "todo-app", "kind": ["bin"]}
                ]
            }]
        });
        let result = resolve_binary_from_metadata(
            &metadata,
            Some("todo-app"),
            Path::new("/projects/todo-app"),
        );
        assert!(result.is_ok());
        // Must return `todo-app`, not `seed` (which appears first in targets).
        assert_eq!(
            result.unwrap(),
            expected_binary("/tmp/target/debug/todo-app")
        );
    }

    #[test]
    fn resolve_binary_with_multiple_packages() {
        let metadata = serde_json::json!({
            "target_directory": "/tmp/target",
            "packages": [
                {
                    "name": "app-a",
                    "manifest_path": "/projects/a/Cargo.toml",
                    "targets": [{"name": "app-a", "kind": ["bin"]}]
                },
                {
                    "name": "app-b",
                    "manifest_path": "/projects/b/Cargo.toml",
                    "targets": [{"name": "app-b", "kind": ["bin"]}]
                }
            ]
        });
        let result = resolve_binary_from_metadata(&metadata, Some("app-b"), Path::new("/projects"));
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), expected_binary("/tmp/target/debug/app-b"));
    }

    // ── stop_server tests ──────────────────────────────────────────

    #[test]
    fn stop_server_with_none_is_noop() {
        let mut child: Option<Child> = None;
        stop_server(&mut child, None);
        assert!(child.is_none());
    }

    #[cfg(unix)]
    #[test]
    fn stop_server_terminates_child() {
        // Spawn a long-running process, then stop it
        let proc = Command::new("sleep")
            .arg("60")
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .expect("spawn sleep");
        let mut child = Some(proc);
        stop_server(&mut child, None);
        assert!(child.is_none());
    }

    // ── find_binary tests ──────────────────────────────────────────

    #[test]
    fn find_binary_resolves_workspace_package() {
        // We're running inside the autumn workspace, so this should find
        // the hello example's binary.
        let path = find_binary(Some("hello"), false);
        assert!(path.ends_with("debug/hello") || path.ends_with("debug/hello.exe"));
    }

    #[test]
    fn find_binary_release_resolves_release_dir() {
        let path = find_binary(Some("hello"), true);
        assert!(path.ends_with("release/hello") || path.ends_with("release/hello.exe"));
    }

    // ── constants tests ────────────────────────────────────────────

    #[test]
    fn debounce_interval_is_reasonable() {
        const { assert!(DEBOUNCE_MS >= 100, "debounce too short, would thrash") };
        const { assert!(DEBOUNCE_MS <= 5000, "debounce too long, sluggish UX") };
    }

    #[test]
    fn watch_dirs_are_non_empty() {
        for dir in DEFAULT_WATCH_DIRS {
            assert!(!dir.is_empty());
        }
    }

    #[test]
    fn watch_files_are_non_empty() {
        for f in WATCH_FILES {
            assert!(!f.is_empty());
        }
    }

    #[test]
    fn dev_reload_state_signal_writes_css_and_full_versions() {
        let reload_file = tempfile::NamedTempFile::new().expect("reload file");
        let path = reload_file.path().to_path_buf();
        let mut state = DevReloadState {
            path,
            version: 0,
            active_build_error: None,
        };

        state.signal(ReloadKind::Css).expect("css signal");
        let body = std::fs::read_to_string(state.path()).expect("read css");
        assert_eq!(body, r#"{"kind":"css","version":1}"#);

        state.signal(ReloadKind::Full).expect("full signal");
        let body = std::fs::read_to_string(state.path()).expect("read full");
        assert_eq!(body, r#"{"kind":"full","version":2}"#);
    }

    #[test]
    fn parse_build_diagnostics_extracts_errors_in_order_excluding_warnings() {
        // A realistic `cargo build --message-format=json` stream: an artifact
        // line, an error, a warning (must be excluded), a non-JSON line, a
        // second error whose primary span is NOT the first span, and a
        // build-finished line.
        let stdout = concat!(
            r#"{"reason":"compiler-artifact","target":{"name":"app"}}"#,
            "\n",
            r#"{"reason":"compiler-message","message":{"code":{"code":"E0425"},"level":"error","message":"cannot find value `foo` in this scope","rendered":"error[E0425]: cannot find value `foo`\n --> src/main.rs:3:5\n","spans":[{"file_name":"src/main.rs","line_start":3,"column_start":5,"is_primary":true}]}}"#,
            "\n",
            r#"{"reason":"compiler-message","message":{"code":null,"level":"warning","message":"unused variable: `x`","rendered":"warning: unused variable\n","spans":[{"file_name":"src/main.rs","line_start":9,"column_start":1,"is_primary":true}]}}"#,
            "\n",
            "   Compiling app v0.1.0 (not json)\n",
            r#"{"reason":"compiler-message","message":{"code":{"code":"E0308"},"level":"error","message":"mismatched types","rendered":"error[E0308]: mismatched types\n --> src/lib.rs:12:9\n","spans":[{"file_name":"src/other.rs","line_start":1,"column_start":1,"is_primary":false},{"file_name":"src/lib.rs","line_start":12,"column_start":9,"is_primary":true}]}}"#,
            "\n",
            r#"{"reason":"build-finished","success":false}"#,
            "\n",
        );

        let diags = parse_build_diagnostics(stdout.as_bytes());

        assert_eq!(diags.len(), 2, "warnings and non-error lines excluded");
        assert_eq!(
            diags[0],
            BuildDiagnostic {
                code: Some("E0425".to_owned()),
                message: "cannot find value `foo` in this scope".to_owned(),
                file: "src/main.rs".to_owned(),
                line: 3,
                column: 5,
                rendered: "error[E0425]: cannot find value `foo`\n --> src/main.rs:3:5\n"
                    .to_owned(),
            }
        );
        // Compiler order is preserved: E0425 first, then E0308.
        assert_eq!(diags[1].code, Some("E0308".to_owned()));
        assert_eq!(diags[1].message, "mismatched types");
        // Primary span wins over the (earlier) non-primary span.
        assert_eq!(diags[1].file, "src/lib.rs");
        assert_eq!(diags[1].line, 12);
        assert_eq!(diags[1].column, 9);
    }

    #[test]
    fn compiler_message_rendered_echoes_all_levels_but_not_other_records() {
        // Warning-level messages must be echoed live so the terminal matches
        // plain `cargo build` output, even though they never enter the overlay.
        let warning = r#"{"reason":"compiler-message","message":{"code":null,"level":"warning","message":"unused variable: `x`","rendered":"warning: unused variable\n"}}"#;
        assert_eq!(
            compiler_message_rendered(warning).as_deref(),
            Some("warning: unused variable\n"),
        );

        // Error-level messages are echoed too.
        let error = r#"{"reason":"compiler-message","message":{"code":{"code":"E0425"},"level":"error","message":"cannot find value `foo`","rendered":"error[E0425]: cannot find value `foo`\n"}}"#;
        assert_eq!(
            compiler_message_rendered(error).as_deref(),
            Some("error[E0425]: cannot find value `foo`\n"),
        );

        // Non-JSON progress lines yield nothing.
        assert_eq!(compiler_message_rendered("   Compiling app v0.1.0"), None);

        // Non-`compiler-message` records (artifacts, build scripts, finished)
        // are never echoed.
        assert_eq!(
            compiler_message_rendered(r#"{"reason":"compiler-artifact","target":{"name":"app"}}"#),
            None,
        );

        // A compiler message with no `rendered` text yields nothing rather than
        // an empty echo.
        assert_eq!(
            compiler_message_rendered(
                r#"{"reason":"compiler-message","message":{"level":"warning","message":"x"}}"#
            ),
            None,
        );
    }

    /// A representative single-error diagnostic list for the build-error tests.
    fn sample_build_diagnostics() -> Vec<BuildDiagnostic> {
        vec![BuildDiagnostic {
            code: Some("E0425".to_owned()),
            message: "cannot find value `foo`".to_owned(),
            file: "src/main.rs".to_owned(),
            line: 3,
            column: 5,
            rendered: "error[E0425]: cannot find value `foo`".to_owned(),
        }]
    }

    #[test]
    fn dev_reload_state_signal_build_error_writes_payload() {
        let reload_file = tempfile::NamedTempFile::new().expect("reload file");
        let path = reload_file.path().to_path_buf();
        let mut state = DevReloadState {
            path,
            version: 0,
            active_build_error: None,
        };

        let diags = sample_build_diagnostics();

        state
            .signal_build_error(&diags, true)
            .expect("build error signal");
        assert_eq!(state.version, 1, "build error bumps the version");

        let body = std::fs::read_to_string(state.path()).expect("read build error");
        let value: serde_json::Value = serde_json::from_str(&body).expect("valid json");
        assert_eq!(value["version"], 1);
        assert_eq!(value["kind"], "full");
        assert_eq!(value["build_error"]["stale"], true);
        assert_eq!(value["build_error"]["diagnostics"][0]["code"], "E0425");
        assert_eq!(
            value["build_error"]["diagnostics"][0]["file"],
            "src/main.rs"
        );
        assert_eq!(value["build_error"]["diagnostics"][0]["line"], 3);
        assert_eq!(value["build_error"]["diagnostics"][0]["column"], 5);
        assert_eq!(
            value["build_error"]["diagnostics"][0]["message"],
            "cannot find value `foo`"
        );
    }

    #[test]
    fn dev_reload_state_signal_carries_build_error_across_non_build_reloads() {
        // P2 regression guard: once a Rust build is broken, an ordinary CSS
        // (or other non-build) reload must NOT dismiss the overlay. It carries
        // the build_error payload forward while still bumping the version so
        // the client re-polls but stays on the overlay instead of reloading the
        // stale app.
        let reload_file = tempfile::NamedTempFile::new().expect("reload file");
        let path = reload_file.path().to_path_buf();
        let mut state = DevReloadState {
            path,
            version: 0,
            active_build_error: None,
        };

        let diags = sample_build_diagnostics();
        state
            .signal_build_error(&diags, true)
            .expect("build error signal");
        assert_eq!(state.version, 1);

        // A Tailwind/CSS save while Rust is broken.
        state.signal(ReloadKind::Css).expect("css signal");
        assert_eq!(state.version, 2, "carrying forward still bumps the version");
        let body = std::fs::read_to_string(state.path()).expect("read carried");
        let value: serde_json::Value = serde_json::from_str(&body).expect("valid json");
        assert_eq!(value["version"], 2);
        assert_eq!(value["kind"], "full", "build error state stays a full kind");
        assert!(
            value.get("build_error").is_some(),
            "a non-build reload must carry the build_error forward"
        );
        assert_eq!(value["build_error"]["stale"], true);
        assert_eq!(value["build_error"]["diagnostics"][0]["code"], "E0425");

        // A plain full reload (e.g. a config-only restart) also carries it.
        state.signal(ReloadKind::Full).expect("full signal");
        assert_eq!(state.version, 3);
        let body = std::fs::read_to_string(state.path()).expect("read carried again");
        let value: serde_json::Value = serde_json::from_str(&body).expect("valid json");
        assert!(
            value.get("build_error").is_some(),
            "a plain full reload must also carry the build_error forward"
        );
    }

    #[test]
    fn dev_reload_state_signal_build_success_clears_overlay() {
        // Only a green Rust build clears the overlay: the explicit
        // success-clear drops the build_error field and bumps the version so
        // the client dismisses the overlay and reloads the freshly-built app.
        let reload_file = tempfile::NamedTempFile::new().expect("reload file");
        let path = reload_file.path().to_path_buf();
        let mut state = DevReloadState {
            path,
            version: 0,
            active_build_error: None,
        };

        let diags = sample_build_diagnostics();
        state
            .signal_build_error(&diags, true)
            .expect("build error signal");
        assert_eq!(state.version, 1);

        state
            .signal_build_success(ReloadKind::Full)
            .expect("success signal");
        assert_eq!(state.version, 2);
        let body = std::fs::read_to_string(state.path()).expect("read cleared");
        let value: serde_json::Value = serde_json::from_str(&body).expect("valid json");
        assert!(
            value.get("build_error").is_none(),
            "a green build must clear the build_error field"
        );
        assert_eq!(value["version"], 2);
        assert_eq!(value["kind"], "full");

        // After a green build, ordinary signals no longer carry an overlay.
        state.signal(ReloadKind::Css).expect("css signal");
        let body = std::fs::read_to_string(state.path()).expect("read post-clear");
        let value: serde_json::Value = serde_json::from_str(&body).expect("valid json");
        assert!(
            value.get("build_error").is_none(),
            "no overlay should persist once cleared by a green build"
        );
        assert_eq!(value["kind"], "css");
        assert_eq!(value["version"], 3);
    }

    #[test]
    fn dev_reload_state_signal_none_is_noop() {
        let reload_file = tempfile::NamedTempFile::new().expect("reload file");
        let path = reload_file.path().to_path_buf();
        let mut state = DevReloadState {
            path,
            version: 41,
            active_build_error: None,
        };

        state.signal(ReloadKind::None).expect("noop signal");
        assert_eq!(state.version, 41);
        assert!(
            std::fs::read_to_string(state.path())
                .unwrap_or_default()
                .is_empty(),
            "noop signal should not write a new state file"
        );
    }

    #[test]
    fn dev_reload_state_signal_rejects_overflow() {
        let reload_file = tempfile::NamedTempFile::new().expect("reload file");
        let path = reload_file.path().to_path_buf();
        let mut state = DevReloadState {
            path,
            version: u64::MAX,
            active_build_error: None,
        };

        let error = state
            .signal(ReloadKind::Full)
            .expect_err("overflow should fail");
        assert!(error.contains("overflowed"));
    }

    #[test]
    fn profile_config_file_requires_named_toml_suffix() {
        assert!(is_profile_config_file("autumn-dev.toml"));
        assert!(is_profile_config_file("autumn-local.TOML"));
        assert!(!is_profile_config_file("autumn-.toml"));
        assert!(!is_profile_config_file("autumn-dev.txt"));
        assert!(!is_profile_config_file("config.toml"));
    }

    #[test]
    fn has_component_matches_exact_path_components() {
        assert!(has_component(Path::new("src/routes/main.rs"), "src"));
        assert!(has_component(
            Path::new("templates/pages/index.html"),
            "templates"
        ));
        assert!(!has_component(Path::new("srcs/routes/main.rs"), "src"));
        assert!(!has_component(
            Path::new("template/index.html"),
            "templates"
        ));
    }

    #[test]
    fn describe_plan_covers_each_user_visible_action() {
        assert_eq!(
            describe_plan(ChangePlan {
                build: true,
                restart: true,
                tailwind: false,
                reload: ReloadKind::Full,
            }),
            "cargo build + restart + full reload"
        );
        assert_eq!(
            describe_plan(ChangePlan {
                build: false,
                restart: true,
                tailwind: true,
                reload: ReloadKind::Full,
            }),
            "Tailwind rebuild + restart + full reload"
        );
        assert_eq!(
            describe_plan(ChangePlan {
                build: false,
                restart: true,
                tailwind: false,
                reload: ReloadKind::Full,
            }),
            "restart + full reload"
        );
        assert_eq!(
            describe_plan(ChangePlan {
                build: false,
                restart: false,
                tailwind: true,
                reload: ReloadKind::Css,
            }),
            "Tailwind rebuild + CSS reload"
        );
        assert_eq!(
            describe_plan(ChangePlan {
                build: false,
                restart: false,
                tailwind: false,
                reload: ReloadKind::Full,
            }),
            "browser full reload"
        );
        assert_eq!(describe_plan(ChangePlan::default()), "no-op");
    }

    #[test]
    fn resolve_target_directory_returns_workspace_target() {
        let target_dir = resolve_target_directory().expect("target directory");
        assert_eq!(
            target_dir.file_name().and_then(|name| name.to_str()),
            Some("target")
        );
    }

    #[test]
    fn resolve_dev_reload_state_path_uses_target_autumn_file() {
        let path = resolve_dev_reload_state_path().expect("reload state path");
        assert!(
            path.ends_with(
                Path::new("target")
                    .join("autumn")
                    .join(DEV_RELOAD_STATE_FILE)
            )
        );
    }

    #[test]
    fn cargo_metadata_includes_target_directory_and_packages() {
        let metadata = cargo_metadata();
        assert!(metadata["target_directory"].is_string());
        assert!(metadata["packages"].is_array());
    }

    #[test]
    fn which_finds_binary_on_path() {
        let dir = tempfile::tempdir().expect("tempdir");
        let binary_name = if cfg!(windows) {
            "mocktailwind.exe"
        } else {
            "mocktailwind"
        };
        let binary = dir.path().join(binary_name);
        std::fs::write(&binary, "echo tailwind").expect("write binary");
        let path = std::env::join_paths([dir.path()]).expect("join path");
        temp_env::with_vars([("PATH", Some(path.as_os_str()))], || {
            let found = which("mocktailwind").expect("binary on PATH");
            assert_eq!(found, binary);
        });
    }

    #[test]
    fn which_returns_none_when_binary_missing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = std::env::join_paths([dir.path()]).expect("join path");
        temp_env::with_vars([("PATH", Some(path.as_os_str()))], || {
            assert!(which("definitely-missing-binary").is_none());
        });
    }

    // ── DevConfig parsing ──────────────────────────────────────────

    #[test]
    fn parse_dev_config_returns_default_when_section_missing() {
        let config = parse_dev_config("[server]\nport = 3000\n").expect("parse");
        assert!(config.watch_dirs.is_empty());
    }

    #[test]
    fn parse_dev_config_reads_watch_dirs() {
        let config = parse_dev_config(
            r#"
[dev]
watch_dirs = ["views", "locales"]
"#,
        )
        .expect("parse");
        assert_eq!(config.watch_dirs, vec!["views", "locales"]);
    }

    #[test]
    fn parse_dev_config_treats_empty_dev_section_as_default() {
        let config = parse_dev_config("[dev]\n").expect("parse");
        assert!(config.watch_dirs.is_empty());
    }

    #[test]
    fn parse_dev_config_rejects_non_string_watch_dirs() {
        let result = parse_dev_config("[dev]\nwatch_dirs = [42]\n");
        assert!(result.is_err());
    }

    #[test]
    fn load_dev_config_returns_default_for_missing_file() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("does-not-exist.toml");
        let config = load_dev_config(&path);
        assert!(config.watch_dirs.is_empty());
    }

    #[test]
    fn load_dev_config_reads_from_disk() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("autumn.toml");
        std::fs::write(&path, "[dev]\nwatch_dirs = [\"views\", \"locales\"]\n")
            .expect("write toml");
        let config = load_dev_config(&path);
        assert_eq!(config.watch_dirs, vec!["views", "locales"]);
    }

    // ── sanitize_custom_watch_dirs ─────────────────────────────────

    #[test]
    fn sanitize_drops_default_dirs() {
        let dirs = sanitize_custom_watch_dirs(DevConfig {
            watch_dirs: vec!["src".into(), "static".into(), "views".into()],
        });
        assert_eq!(dirs, vec!["views"]);
    }

    #[test]
    fn sanitize_drops_blanks_and_dedupes() {
        let dirs = sanitize_custom_watch_dirs(DevConfig {
            watch_dirs: vec![
                "  ".into(),
                "views".into(),
                "views".into(),
                "  locales  ".into(),
                String::new(),
            ],
        });
        assert_eq!(dirs, vec!["views", "locales"]);
    }

    // ── classify_change with custom dirs ───────────────────────────

    /// Build a `CustomWatchDir` for tests. The absolute form is anchored
    /// at the synthetic project root `/repo`.
    fn test_dir(rel: &str) -> CustomWatchDir {
        CustomWatchDir {
            relative: PathBuf::from(rel),
            absolute: PathBuf::from("/repo").join(rel),
        }
    }

    #[test]
    fn custom_watch_dir_change_triggers_restart() {
        let custom = vec![test_dir("views")];
        assert_eq!(
            classify_change(
                Path::new("views/landing.html"),
                DebouncedEventKind::Any,
                &custom,
            ),
            ChangeEffect::RestartOnly,
        );
    }

    #[test]
    fn custom_watch_dir_nested_change_triggers_restart() {
        let custom = vec![test_dir("locales")];
        assert_eq!(
            classify_change(
                Path::new("locales/en/messages.json"),
                DebouncedEventKind::Any,
                &custom,
            ),
            ChangeEffect::RestartOnly,
        );
    }

    #[test]
    fn custom_watch_dir_does_not_override_known_dirs() {
        // A path under `src` keeps its BuildRestart effect even if the user
        // also lists a custom dir.
        let custom = vec![test_dir("views")];
        assert_eq!(
            classify_change(Path::new("src/main.rs"), DebouncedEventKind::Any, &custom),
            ChangeEffect::BuildRestart,
        );
    }

    #[test]
    fn custom_watch_dir_respects_target_ignore() {
        // Even if the user names a custom dir, paths under target/ remain ignored.
        let custom = vec![test_dir("views")];
        assert_eq!(
            classify_change(
                Path::new("target/views/cached.html"),
                DebouncedEventKind::Any,
                &custom,
            ),
            ChangeEffect::Ignore,
        );
    }

    #[test]
    fn unknown_path_with_no_custom_dirs_is_ignored() {
        // Sanity check: without custom dirs configured, a `views/` change
        // is not picked up — it's the user's responsibility to opt in.
        assert_eq!(
            classify_change(
                Path::new("views/landing.html"),
                DebouncedEventKind::Any,
                &[],
            ),
            ChangeEffect::Ignore,
        );
    }

    #[test]
    fn custom_dir_change_plans_a_restart() {
        let events = [notify_debouncer_mini::DebouncedEvent {
            path: PathBuf::from("views/landing.html"),
            kind: DebouncedEventKind::Any,
        }];
        let custom = vec![test_dir("views")];
        let plan = plan_changes(&events, &custom);
        assert_eq!(
            plan,
            ChangePlan {
                build: false,
                restart: true,
                tailwind: false,
                reload: ReloadKind::Full,
            }
        );
    }

    #[test]
    fn custom_watch_dir_with_multi_segment_path_matches() {
        // Multi-segment dir matches both components.
        let custom = vec![test_dir("content/locales")];
        assert_eq!(
            classify_change(
                Path::new("content/locales/en/messages.json"),
                DebouncedEventKind::Any,
                &custom,
            ),
            ChangeEffect::RestartOnly,
        );
    }

    #[test]
    fn custom_watch_dir_does_not_match_unrelated_prefix() {
        // `views2/foo.html` must not be picked up by a `views` entry —
        // matching is component-wise, not byte-prefix.
        let custom = vec![test_dir("views")];
        assert_eq!(
            classify_change(
                Path::new("views2/foo.html"),
                DebouncedEventKind::Any,
                &custom,
            ),
            ChangeEffect::Ignore,
        );
    }

    #[cfg(unix)]
    #[test]
    fn custom_watch_dir_matches_absolute_event_path() {
        // `notify` backends typically dispatch absolute event paths, so
        // matching must work against the resolved absolute form.
        let custom = vec![CustomWatchDir {
            relative: PathBuf::from("views"),
            absolute: PathBuf::from("/home/user/project/views"),
        }];
        assert_eq!(
            classify_change(
                Path::new("/home/user/project/views/landing.html"),
                DebouncedEventKind::Any,
                &custom,
            ),
            ChangeEffect::RestartOnly,
        );
    }

    #[cfg(unix)]
    #[test]
    fn custom_watch_dir_matches_absolute_multi_segment_event_path() {
        let custom = vec![CustomWatchDir {
            relative: PathBuf::from("content/locales"),
            absolute: PathBuf::from("/home/user/project/content/locales"),
        }];
        assert_eq!(
            classify_change(
                Path::new("/home/user/project/content/locales/en/messages.json"),
                DebouncedEventKind::Any,
                &custom,
            ),
            ChangeEffect::RestartOnly,
        );
    }

    #[cfg(unix)]
    #[test]
    fn custom_watch_dir_does_not_match_ancestor_directory() {
        // Regression: matching is anchored to the project root via the
        // resolved absolute path. If the project itself lives under
        // `/home/alice/views/app`, a custom entry `views` must NOT match
        // the root-level `README.md` event, even though `views` appears
        // in the parent path.
        let custom = vec![CustomWatchDir {
            relative: PathBuf::from("views"),
            absolute: PathBuf::from("/home/alice/views/app/views"),
        }];
        assert_eq!(
            classify_change(
                Path::new("/home/alice/views/app/README.md"),
                DebouncedEventKind::Any,
                &custom,
            ),
            ChangeEffect::Ignore,
        );
    }

    // ── CustomWatchDir::matches ────────────────────────────────────

    #[test]
    fn custom_watch_dir_matches_relative_event_path() {
        let dir = test_dir("views");
        assert!(dir.matches(Path::new("views/file.html")));
        assert!(dir.matches(Path::new("views")));
        assert!(!dir.matches(Path::new("other/file.html")));
    }

    #[cfg(unix)]
    #[test]
    fn custom_watch_dir_matches_absolute_event_path_via_helper() {
        let dir = CustomWatchDir {
            relative: PathBuf::from("views"),
            absolute: PathBuf::from("/repo/views"),
        };
        assert!(dir.matches(Path::new("/repo/views/file.html")));
        assert!(!dir.matches(Path::new("/elsewhere/views/file.html")));
    }

    // ── resolve_custom_watch_dirs ──────────────────────────────────

    #[test]
    fn resolve_skips_missing_dirs() {
        let cwd = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir(cwd.path().join("views")).expect("mkdir views");
        let resolved =
            resolve_custom_watch_dirs(&["views".to_owned(), "missing".to_owned()], cwd.path());
        assert_eq!(resolved.len(), 1);
        assert_eq!(resolved[0].relative, PathBuf::from("views"));
        assert!(resolved[0].absolute.ends_with("views"));
        assert!(resolved[0].absolute.is_absolute());
    }

    // ── normalize_watch_dir ────────────────────────────────────────

    #[test]
    fn normalize_strips_curdir_prefix() {
        assert_eq!(normalize_watch_dir("./views"), Ok("views".to_owned()));
    }

    #[test]
    fn normalize_preserves_multi_segment_paths() {
        assert_eq!(
            normalize_watch_dir("content/locales"),
            Ok("content/locales".replace('/', std::path::MAIN_SEPARATOR_STR)),
        );
    }

    #[test]
    fn normalize_rejects_empty_input() {
        assert!(normalize_watch_dir("   ").is_err());
        assert!(normalize_watch_dir("").is_err());
    }

    #[test]
    fn normalize_rejects_parent_traversal() {
        assert!(normalize_watch_dir("../up").is_err());
        assert!(normalize_watch_dir("views/../etc").is_err());
    }

    #[cfg(unix)]
    #[test]
    fn normalize_rejects_absolute_paths_unix() {
        assert!(normalize_watch_dir("/etc/passwd").is_err());
        assert!(normalize_watch_dir("/").is_err());
    }

    #[test]
    fn normalize_rejects_target_anywhere() {
        assert!(normalize_watch_dir("target").is_err());
        assert!(normalize_watch_dir("nested/target/cache").is_err());
    }

    #[test]
    fn normalize_rejects_dotted_components() {
        // Dotted directories like `.git` would still be visited by the
        // watcher even though `should_ignore_path` filters their events
        // later, flooding the debouncer. Reject them up front.
        assert!(normalize_watch_dir(".git").is_err());
        assert!(normalize_watch_dir(".cache").is_err());
        assert!(normalize_watch_dir("nested/.hidden").is_err());
        // `./views` (CurDir prefix) is still allowed — only Normal components
        // starting with `.` are rejected.
        assert!(normalize_watch_dir("./views").is_ok());
    }

    #[test]
    fn normalize_rejects_curdir_only() {
        // `.` alone has no Normal components, so the result would be empty.
        assert!(normalize_watch_dir(".").is_err());
        assert!(normalize_watch_dir("./").is_err());
    }

    #[test]
    fn sanitize_warns_and_skips_unsafe_entries() {
        let dirs = sanitize_custom_watch_dirs(DevConfig {
            watch_dirs: vec![
                "../escape".into(),
                "target".into(),
                "views".into(),
                "./locales".into(),
            ],
        });
        let expected_locales = "locales".to_owned();
        assert_eq!(dirs, vec!["views".to_owned(), expected_locales]);
    }

    // ── #1633: dependency findings in the dev loop ───────────────────────────

    #[test]
    fn an_unfinished_dependency_audit_prints_nothing() {
        // The audit is abandoned on timeout. Startup neither waits for it nor
        // reports on it.
        assert!(dependency_startup_lines(None).is_empty());
    }

    #[test]
    fn a_clean_tree_prints_nothing() {
        let clean = crate::deps::Evaluation::Audited {
            findings: Vec::new(),
            checks: vec!["advisories".to_owned()],
            db_age_days: Some(1),
            auditor: "cargo-deny 0.20.2".to_owned(),
        };
        assert!(dependency_startup_lines(Some(&clean)).is_empty());
    }

    #[test]
    fn the_audit_deadline_is_bounded() {
        // A poll that outlives the session is a leak; a verdict nobody will
        // read is not worth keeping.
        assert!(DEPENDENCY_AUDIT_DEADLINE <= Duration::from_secs(60));
    }

    #[test]
    fn the_dependency_audit_starts_after_the_build_and_is_never_awaited() {
        // Running the auditor beside the build makes its `cargo metadata`
        // contend with Cargo's package-cache lock and slow the build. Awaiting
        // it anywhere would delay startup or a rebuild.
        // Only the module's own code, not this test — the needles below
        // otherwise match the assertions that look for them.
        let source = include_str!("dev.rs");
        let code = &source[..source.find("#[cfg(test)]").expect("test module")];
        let build = code
            .find("let (built, diagnostics) = cargo_build_capturing(package);")
            .expect("initial build");
        let start = code
            .find("let mut dependency_audit = DependencyAudit::start(")
            .expect("audit start");
        assert!(
            build < start,
            "the audit must start after the initial build"
        );
        assert!(
            !code.contains("await_evaluation"),
            "the dev loop must poll the audit, never await it"
        );
    }

    #[test]
    fn a_dependency_audit_that_never_answers_stops_being_polled() {
        let (sender, receiver) = mpsc::channel();
        let stop = crate::deps::StopHandle::default();
        let mut audit = DependencyAudit {
            receiver,
            stop: stop.clone(),
            deadline: std::time::Instant::now(),
            done: false,
        };
        audit.report();
        assert!(audit.done, "an expired deadline must end the polling");
        assert!(
            stop.is_stopped(),
            "an expired deadline must kill the auditor"
        );
        drop(sender);
    }

    #[test]
    fn a_dependency_audit_reports_its_verdict_once() {
        let (sender, receiver) = mpsc::channel();
        let stop = crate::deps::StopHandle::default();
        let mut audit = DependencyAudit {
            receiver,
            stop: stop.clone(),
            deadline: std::time::Instant::now() + Duration::from_secs(60),
            done: false,
        };
        audit.report();
        assert!(!audit.done, "a pending audit stays pending");
        assert!(!stop.is_stopped(), "a pending audit is not killed early");
        sender
            .send(crate::deps::Evaluation::NoPolicy)
            .expect("send");
        audit.report();
        assert!(audit.done, "a delivered verdict ends the polling");
        assert!(!stop.is_stopped(), "a delivered verdict is never killed");
        drop(audit);
        assert!(!stop.is_stopped(), "a finished audit is not killed on drop");
    }

    #[test]
    fn dropping_an_unfinished_audit_stops_it() {
        let (_sender, receiver) = mpsc::channel();
        let stop = crate::deps::StopHandle::default();
        let audit = DependencyAudit {
            receiver,
            stop: stop.clone(),
            deadline: std::time::Instant::now() + Duration::from_secs(60),
            done: false,
        };
        drop(audit);
        assert!(stop.is_stopped());
    }
}