autumn-cli 0.6.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
//! `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";

#[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()))
    }
}

/// 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,
        reload_state.as_ref().map(DevReloadState::path),
        show_config,
    );

    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);

    // 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}");
    }

    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;
        }

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

    stop_server(&mut child);
}

/// 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);
        }

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

        if built {
            if !stop_before_build {
                stop_server(child);
            }
            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);
        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() => {
            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 cmd.status() {
        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,
    reload_state_path: Option<&Path>,
    show_config: bool,
) -> Option<Child> {
    eprintln!("  Starting server...\n");

    // 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() {
        Ok(v) => v,
        Err(e) => {
            eprintln!("  \u{274C} .env: {e}");
            std::process::exit(1);
        }
    };

    let mut command = Command::new(binary);
    command.envs(dotenv_vars);
    // 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");
    }

    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>) {
    if let Some(proc) = child {
        // Send SIGTERM on Unix for graceful shutdown
        #[cfg(unix)]
        {
            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();
            }
        }

        #[cfg(not(unix))]
        {
            let _ = proc.kill();
            let _ = proc.wait();
        }
    }
    *child = None;
}

/// 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 {
    if !matches!(kind, DebouncedEventKind::Any) {
        return ChangeEffect::Ignore;
    }

    // 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(path) {
            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, 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))
}

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())
}

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");
        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 target_dir.join("release").join(bin);
        }
    }
    path
}

#[cfg(test)]
mod tests {
    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 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, 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, 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);
        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);
        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]);
    }
}