autumn-web 0.6.0

An opinionated, convention-over-configuration web framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
//! Application builder -- the entry point for configuring and running
//! an Autumn server.
//!
//! Every Autumn application follows the same pattern:
//!
//! 1. Call [`app()`] to create an [`AppBuilder`].
//! 2. Register routes with [`.routes()`](AppBuilder::routes).
//! 3. Call [`.run()`](AppBuilder::run) to start serving.
//!
//! # Example
//!
//! ```rust,no_run
//! use autumn_web::prelude::*;
//!
//! #[get("/hello")]
//! async fn hello() -> &'static str { "Hello!" }
//!
//! #[autumn_web::main]
//! async fn main() {
//!     autumn_web::app()
//!         .routes(routes![hello])
//!         .run()
//!         .await;
//! }
//! ```

use std::any::{Any, TypeId};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use futures::FutureExt as _;
use tracing::Instrument as _;

use crate::config::{AutumnConfig, ConfigLoader};
#[cfg(feature = "maud")]
use crate::error_pages::{ErrorPageRenderer, SharedRenderer};
use crate::middleware::exception_filter::ExceptionFilter;
#[cfg(feature = "db")]
use crate::migrate;
use crate::route::Route;
use crate::state::AppState;

/// Create a new [`AppBuilder`].
///
/// This is the primary entry point for constructing an Autumn application.
/// Chain [`.routes()`](AppBuilder::routes) calls to register handlers, then
/// call [`.run()`](AppBuilder::run) to start the server.
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/")]
/// async fn index() -> &'static str { "hi" }
///
/// #[autumn_web::main]
/// async fn main() {
///     autumn_web::app()
///         .routes(routes![index])
///         .run()
///         .await;
/// }
/// ```
#[must_use]
pub fn app() -> AppBuilder {
    AppBuilder {
        routes: Vec::new(),
        api_versions: Vec::new(),
        route_sources: Vec::new(),
        current_plugin: None,
        tasks: Vec::new(),
        one_off_tasks: Vec::new(),
        jobs: Vec::new(),
        listeners: Vec::new(),
        static_metas: Vec::new(),
        exception_filters: Vec::new(),
        scoped_groups: Vec::new(),
        merge_routers: Vec::new(),
        nest_routers: Vec::new(),
        custom_layers: Vec::new(),
        static_gate_layers: Vec::new(),
        startup_hooks: Vec::new(),
        state_initializers: Vec::new(),
        shutdown_hooks: Vec::new(),
        extensions: HashMap::new(),
        registered_plugins: HashSet::new(),
        plugin_config_roots: BTreeSet::new(),
        #[cfg(feature = "maud")]
        error_page_renderer: None,
        #[cfg(feature = "db")]
        migrations: Vec::new(),
        config_loader_factory: None,
        #[cfg(feature = "db")]
        pool_provider_factory: None,
        #[cfg(feature = "db")]
        shard_provider_factory: None,
        #[cfg(feature = "db")]
        shard_router: None,
        #[cfg(feature = "db")]
        directory_shard_router: false,
        telemetry_provider: None,
        session_store: None,
        #[cfg(feature = "ws")]
        channels_backend: None,
        #[cfg(feature = "storage")]
        blob_store: None,
        cache_backend: None,
        #[cfg(feature = "reporting")]
        error_reporters: Vec::new(),
        alert_channels: Vec::new(),
        #[cfg(feature = "openapi")]
        openapi: None,
        #[cfg(feature = "mcp")]
        mcp: None,
        audit_logger: None,
        #[cfg(feature = "i18n")]
        i18n_bundle: None,
        #[cfg(feature = "i18n")]
        i18n_auto_load: false,
        #[cfg(feature = "embed-assets")]
        embedded_static: None,
        #[cfg(all(feature = "embed-assets", feature = "i18n"))]
        embedded_locales: None,
        policy_registrations: Vec::new(),
        #[cfg(feature = "mail")]
        mail_delivery_queue_factory: None,
        #[cfg(feature = "mail")]
        suppression_store: None,
        #[cfg(feature = "mail")]
        mail_suppression_store: None,
        #[cfg(feature = "mail")]
        mount_unsubscribe_endpoint: false,
        #[cfg(feature = "mail")]
        mail_previews: Vec::new(),
        #[cfg(feature = "maud")]
        story_gallery: None,
        declared_routes: Vec::new(),
        idempotency_enabled: false,
        #[cfg(feature = "mail")]
        mail_interceptor: None,
        job_interceptor: None,
        #[cfg(feature = "db")]
        db_interceptor: None,
        #[cfg(feature = "ws")]
        channels_interceptor: None,
        #[cfg(feature = "oauth2")]
        http_interceptor: None,
        seo_sources: Vec::new(),
        metrics_sources: Vec::new(),
        health_indicators: Vec::new(),
        #[cfg(feature = "inbound-mail")]
        inbound_mail_router: None,
    }
}

/// Count the raw routers omitted from `autumn routes` output because their
/// endpoints can't be enumerated — the value `autumn routes audit` treats as a
/// hard failure (an unprovable route defeats the coverage guarantee).
///
/// Every `.merge()` router is rootless — it has no mount prefix to match
/// declarations against — so it is always opaque and always counts. A `.nest()`
/// router carries a mount prefix, so it is treated as **covered** (enumerable,
/// not omitted) when at least one declared route (from
/// [`declare_plugin_routes`](AppBuilder::declare_plugin_routes)) has a path that
/// falls under that prefix. This makes the documented
/// `app.nest(prefix, router).declare_plugin_routes(routes)` pattern audit-clean
/// without any dedicated bookkeeping: the declared routes prove the mount.
///
/// Soundness (fail-closed) is preserved: a bare `nest(prefix, raw_router)` with
/// no declared route under `prefix` stays uncovered and counts, and every
/// `merge()` counts unconditionally.
fn omitted_router_count<'a>(
    merge_routers: usize,
    nest_prefixes: impl IntoIterator<Item = &'a str>,
    declared_routes: &[crate::route_listing::RouteInfo],
) -> usize {
    let uncovered_nests = nest_prefixes
        .into_iter()
        .filter(|prefix| !nest_prefix_is_covered(prefix, declared_routes))
        .count();
    merge_routers + uncovered_nests
}

/// A nested mount at `prefix` is "covered" when at least one declared route's
/// path falls under that prefix, proving the nested router's endpoints are
/// enumerable in the `autumn routes` listing.
fn nest_prefix_is_covered(
    prefix: &str,
    declared_routes: &[crate::route_listing::RouteInfo],
) -> bool {
    declared_routes
        .iter()
        .any(|route| path_is_under_prefix(&route.path, prefix))
}

/// Whether `path` is mounted under `prefix` — i.e. equal to the prefix or a
/// descendant of it at a path-segment boundary (`/admin` covers `/admin` and
/// `/admin/users`, but not `/administrators`). A root prefix (`/` or empty)
/// covers everything.
fn path_is_under_prefix(path: &str, prefix: &str) -> bool {
    let prefix = prefix.trim_end_matches('/');
    if prefix.is_empty() {
        return true;
    }
    path == prefix
        || path
            .strip_prefix(prefix)
            .is_some_and(|rest| rest.starts_with('/'))
}

type StartupHookFuture = Pin<Box<dyn Future<Output = crate::AutumnResult<()>> + Send>>;
type StartupHook = Box<dyn Fn(AppState) -> StartupHookFuture + Send + Sync>;
type StateInitializer = Box<dyn FnOnce(&AppState) + Send>;
type ShutdownHookFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
type ShutdownHook = Box<dyn Fn() -> ShutdownHookFuture + Send + Sync>;

// ── Tier-1 subsystem factories ────────────────────────────────
//
// `ConfigLoader` and `DatabasePoolProvider` use RPIT (`-> impl Future + Send`)
// in their trait methods, so `Box<dyn Trait>` is not dyn-compatible. We store
// boxed factory closures that capture the concrete impl at the call site and
// erase its future type via `Pin<Box<dyn Future>>`. `TelemetryProvider`'s
// `init` is sync, so it's stored as a normal `Box<dyn>`.
type ConfigLoaderFactory = Box<
    dyn FnOnce() -> Pin<
            Box<dyn Future<Output = Result<AutumnConfig, crate::config::ConfigError>> + Send>,
        > + Send,
>;
#[cfg(feature = "db")]
type PoolProviderFactory = Box<
    dyn FnOnce(
            crate::config::DatabaseConfig,
        ) -> Pin<
            Box<
                dyn Future<
                        Output = Result<Option<crate::db::DatabaseTopology>, crate::db::PoolError>,
                    > + Send,
            >,
        > + Send,
>;
/// Captured [`DatabasePoolProvider::create_shard_topology`] calls: builds
/// one topology per configured shard, in declaration order.
#[cfg(feature = "db")]
type ShardProviderFactory = Box<
    dyn FnOnce(
            crate::config::DatabaseConfig,
        ) -> Pin<
            Box<
                dyn Future<Output = Result<Vec<crate::db::DatabaseTopology>, crate::db::PoolError>>
                    + Send,
            >,
        > + Send,
>;

/// Closure that registers a policy or scope on the runtime
/// [`PolicyRegistry`](crate::authorization::PolicyRegistry).
type PolicyRegistration = Box<dyn FnOnce(&crate::authorization::PolicyRegistry) + Send>;

/// Represents an API version registration.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct ApiVersion {
    /// The version name (e.g. "v1", "v2").
    pub version: String,
    /// When this version was deprecated.
    pub deprecated_at: Option<chrono::DateTime<chrono::Utc>>,
    /// When this version was sunsetted.
    pub sunset_at: Option<chrono::DateTime<chrono::Utc>>,
}

/// A wrapper for registered API versions in the app state.
#[derive(Clone, Debug)]
pub struct RegisteredApiVersions(pub Vec<ApiVersion>);

/// Builder for configuring and launching an Autumn application.
///
/// Created by [`app()`]. Collect routes with [`.routes()`](Self::routes),
/// then call [`.run()`](Self::run) to start the HTTP server.
///
/// The builder follows the **builder pattern**: each method consumes `self`
/// and returns a new `AppBuilder`, allowing chained calls.
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/a")]
/// async fn route_a() -> &'static str { "a" }
///
/// #[get("/b")]
/// async fn route_b() -> &'static str { "b" }
///
/// #[autumn_web::main]
/// async fn main() {
///     autumn_web::app()
///         .routes(routes![route_a])
///         .routes(routes![route_b])
///         .run()
///         .await;
/// }
/// ```
#[allow(clippy::struct_excessive_bools)]
pub struct AppBuilder {
    pub(crate) routes: Vec<Route>,
    /// Registered API versions.
    pub api_versions: Vec<ApiVersion>,
    /// Parallel to `routes`: registration origin for each route.
    route_sources: Vec<crate::route_listing::RouteSource>,
    /// Non-None while a plugin's `build()` is executing; routes and scoped
    /// groups added during that window are attributed to this plugin.
    current_plugin: Option<String>,
    tasks: Vec<crate::task::TaskInfo>,
    one_off_tasks: Vec<crate::task::OneOffTaskInfo>,
    pub(crate) jobs: Vec<crate::job::JobInfo>,
    /// Registered event listeners; durable ones are synthesized into jobs at
    /// build time and the rest dispatch synchronously via the event registry.
    pub(crate) listeners: Vec<crate::events::ListenerInfo>,
    pub(crate) static_metas: Vec<crate::static_gen::StaticRouteMeta>,
    pub(crate) exception_filters: Vec<Arc<dyn ExceptionFilter>>,
    pub(crate) scoped_groups: Vec<ScopedGroup>,
    pub(crate) merge_routers: Vec<axum::Router<AppState>>,
    pub(crate) nest_routers: Vec<(String, axum::Router<AppState>)>,
    /// Custom Tower layers registered via [`AppBuilder::layer`], applied
    /// inside `RequestIdLayer` on ingress so they observe the request ID.
    pub(crate) custom_layers: Vec<CustomLayerRegistration>,
    /// Pre-static gate layers registered via [`AppBuilder::static_gate`],
    /// applied outermost (outside session and before the static cache lookup)
    /// so they can auth-gate / redirect requests before a cached SSG/ISG page
    /// is served.
    pub(crate) static_gate_layers: Vec<CustomLayerRegistration>,
    pub(crate) startup_hooks: Vec<StartupHook>,
    pub(crate) state_initializers: Vec<StateInitializer>,
    pub(crate) shutdown_hooks: Vec<ShutdownHook>,
    pub(crate) extensions: HashMap<TypeId, Box<dyn Any + Send>>,
    /// Plugin names that have already been applied, for duplicate detection.
    pub(crate) registered_plugins: HashSet<String>,
    /// Top-level config roots plugins have declared as their own opaque config
    /// sections via [`config_section`](AppBuilder::config_section). Threaded into
    /// the default config loader so `server.strict_config` treats them as
    /// known-and-opaque instead of unknown-key hard errors.
    pub(crate) plugin_config_roots: BTreeSet<String>,
    /// Custom error page renderer (overrides built-in pages).
    #[cfg(feature = "maud")]
    error_page_renderer: Option<SharedRenderer>,
    /// Embedded Diesel migrations, registered via `.migrations()`.
    #[cfg(feature = "db")]
    migrations: Vec<migrate::EmbeddedMigrations>,
    /// Custom config loader (tier-1 subsystem replacement). When `None`, the
    /// default [`TomlEnvConfigLoader`](crate::config::TomlEnvConfigLoader) runs.
    config_loader_factory: Option<ConfigLoaderFactory>,
    /// Custom DB pool provider (tier-1 subsystem replacement). When `None`,
    /// the default [`DieselDeadpoolPoolProvider`](crate::db::DieselDeadpoolPoolProvider) runs.
    #[cfg(feature = "db")]
    pool_provider_factory: Option<PoolProviderFactory>,
    /// Companion to `pool_provider_factory` for `[[database.shards]]`
    /// topologies; captured from the same provider in `with_pool_provider`.
    #[cfg(feature = "db")]
    shard_provider_factory: Option<ShardProviderFactory>,
    /// Custom shard routing strategy. When `None` and shards are
    /// configured, the default [`HashShardRouter`](crate::sharding::HashShardRouter)
    /// is used.
    #[cfg(feature = "db")]
    shard_router: Option<Arc<dyn crate::sharding::ShardRouter>>,
    /// Builder opt-in for the control-DB [`DirectoryShardRouter`](crate::sharding::DirectoryShardRouter),
    /// applied to `config.database.directory_shard_router` at build time.
    #[cfg(feature = "db")]
    directory_shard_router: bool,
    /// Custom telemetry provider (tier-1 subsystem replacement). When `None`,
    /// the default [`TracingOtlpTelemetryProvider`](crate::telemetry::TracingOtlpTelemetryProvider) runs.
    telemetry_provider: Option<Box<dyn crate::telemetry::TelemetryProvider>>,
    /// Custom session store (tier-1 subsystem replacement). When `Some`,
    /// `apply_session_layer` skips the config-driven `memory`/`redis` selection
    /// and uses this store directly.
    session_store: Option<Arc<dyn crate::session::BoxedSessionStore>>,
    /// Custom channel backend (tier-1 subsystem replacement). When `Some`,
    /// `AppState` skips config-driven `in_process`/`redis` channel selection.
    #[cfg(feature = "ws")]
    channels_backend: Option<Arc<dyn crate::channels::ChannelsBackend>>,
    /// Custom blob store installed via
    /// [`AppBuilder::with_blob_store`]. When `Some`, `preflight_storage`
    /// is skipped and this store is installed directly onto `AppState`.
    #[cfg(feature = "storage")]
    blob_store: Option<crate::storage::SharedBlobStore>,
    /// Shared cache backend installed via [`AppBuilder::with_cache_backend`].
    /// When `Some`, installed onto `AppState` as `shared_cache` before startup
    /// hooks run.
    cache_backend: Option<Arc<dyn crate::cache::Cache>>,
    /// Error reporters registered via [`AppBuilder::with_error_reporter`].
    /// Installed onto `AppState` so the
    /// [`ReportingLayer`](crate::reporting::ReportingLayer) delivers panic and
    /// 5xx [`ErrorEvent`](crate::reporting::ErrorEvent)s to each. Empty means
    /// the built-in [`LogReporter`](crate::reporting::LogReporter) is used.
    #[cfg(feature = "reporting")]
    pub(crate) error_reporters: Vec<Arc<dyn crate::reporting::ErrorReporter>>,
    /// Operator-alert channels registered via [`AppBuilder::with_alert_channel`].
    /// Combined with the built-in mail/webhook channels derived from
    /// `[alerts]` config and installed onto `AppState` so the built-in
    /// condition hooks can fan out to each. Empty means only config-derived
    /// destinations are used. See [`crate::alerts`].
    pub(crate) alert_channels: Vec<Arc<dyn crate::alerts::AlertChannel>>,
    /// `OpenAPI` generation configuration. When `Some`, the router mounts
    /// `/v3/api-docs` (serving `openapi.json`) and `/swagger-ui` (if the
    /// Swagger UI path is set). When `None`, no docs endpoints are mounted.
    ///
    /// Gated behind the `openapi` feature: apps that don't need a
    /// served `OpenAPI` document shouldn't pay for the spec types or the
    /// runtime collision-check machinery.
    #[cfg(feature = "openapi")]
    openapi: Option<crate::openapi::OpenApiConfig>,
    /// MCP (Model Context Protocol) runtime config. `Some` once
    /// [`AppBuilder::mount_mcp`] is called; the contained `expose_all` flag is
    /// flipped by [`AppBuilder::expose_all_as_mcp`]. Gated behind the `mcp`
    /// feature (which implies `openapi`).
    #[cfg(feature = "mcp")]
    mcp: Option<crate::mcp::McpRuntime>,
    /// Shared audit logger used for append-only compliance events.
    audit_logger: Option<Arc<crate::audit::AuditLogger>>,
    /// Loaded i18n translation bundle. When `Some`, an `axum::Extension`
    /// layer publishing this bundle is added at `run()` time so the
    /// [`Locale`](crate::i18n::Locale) extractor can resolve translations.
    #[cfg(feature = "i18n")]
    i18n_bundle: Option<Arc<crate::i18n::Bundle>>,
    /// Whether to load the i18n bundle after the active config loader resolves
    /// [`AutumnConfig`]. This keeps `.i18n_auto()` aligned with
    /// `.with_config_loader(...)`.
    #[cfg(feature = "i18n")]
    i18n_auto_load: bool,
    /// Embedded `static/` tree (incl. the fingerprint manifest) registered via
    /// [`embedded_static`](AppBuilder::embedded_static). When set, `/static/*`
    /// is served from the binary and `asset_url()` resolves against the embedded
    /// manifest — no `static/` sidecar directory is read at runtime.
    #[cfg(feature = "embed-assets")]
    embedded_static: Option<crate::assets::EmbeddedStaticDir>,
    /// Embedded i18n locale bundles registered via
    /// [`embedded_locales`](AppBuilder::embedded_locales). When set (and no
    /// explicit bundle was provided), the bundle is loaded from the binary
    /// instead of the `i18n/` directory on disk.
    #[cfg(all(feature = "embed-assets", feature = "i18n"))]
    embedded_locales: Option<&'static include_dir::Dir<'static>>,
    /// Deferred [`Policy`](crate::authorization::Policy) and
    /// [`Scope`](crate::authorization::Scope) registrations applied
    /// to [`AppState::policy_registry`] just before the router is
    /// built. Stored as boxed closures so we can carry the
    /// generic type parameters across the builder boundary.
    policy_registrations: Vec<PolicyRegistration>,
    /// Durable mail delivery queue factory registered at builder time. Invoked
    /// with the freshly-built [`AppState`] before `install_mailer` runs so it
    /// can capture framework-managed resources (DB pool, channels, etc.).
    #[cfg(feature = "mail")]
    mail_delivery_queue_factory: Option<MailDeliveryQueueFactory>,
    #[cfg(feature = "mail")]
    pub(crate) suppression_store: Option<crate::mail::SuppressionStoreHandle>,
    #[cfg(feature = "mail")]
    pub(crate) mail_suppression_store: Option<crate::mail::suppression::SuppressionStoreHandle>,
    #[cfg(feature = "mail")]
    pub(crate) mount_unsubscribe_endpoint: bool,
    /// Mail template previews registered for the dev preview UI.
    #[cfg(feature = "mail")]
    mail_previews: Vec<crate::mail::MailPreview>,
    /// Widget story gallery registered for the `/_stories` UI (#1526).
    #[cfg(feature = "maud")]
    story_gallery: Option<crate::stories::StoryGallery>,
    /// Routes explicitly declared by plugins for listing purposes, to complement
    /// opaque `nest_routers`. Included in `autumn routes` output even though
    /// the underlying Axum router is not enumerable.
    declared_routes: Vec<crate::route_listing::RouteInfo>,
    /// Whether `.idempotent()` was called on this builder. Applied to the
    /// loaded `AutumnConfig` before router assembly so that startup validation
    /// and `apply_middleware` both see `config.idempotency.enabled = true`.
    idempotency_enabled: bool,
    #[cfg(feature = "mail")]
    mail_interceptor: Option<Arc<dyn crate::interceptor::MailInterceptor>>,
    job_interceptor: Option<Arc<dyn crate::interceptor::JobInterceptor>>,
    #[cfg(feature = "db")]
    db_interceptor: Option<Arc<dyn crate::interceptor::DbConnectionInterceptor>>,
    #[cfg(feature = "ws")]
    channels_interceptor: Option<Arc<dyn crate::interceptor::ChannelsInterceptor>>,
    #[cfg(feature = "oauth2")]
    http_interceptor: Option<Arc<dyn crate::interceptor::HttpInterceptor>>,
    /// Sitemap sources registered via [`AppBuilder::seo_source`].
    /// Each source provides dynamic URL entries for `/sitemap.xml`.
    seo_sources: Vec<Arc<dyn crate::seo::SitemapSource>>,

    /// Plugin-contributed metrics sources registered via [`AppBuilder::metrics_source`].
    pub(crate) metrics_sources: Vec<(String, Arc<dyn crate::actuator::MetricsSource>)>,
    /// Custom health indicators registered via [`AppBuilder::health_indicator`].
    pub(crate) health_indicators: Vec<(
        String,
        crate::actuator::IndicatorGroup,
        Arc<dyn crate::actuator::HealthIndicator>,
    )>,
    /// Inbound mail router registered via [`AppBuilder::inbound_mail_router`].
    /// HTTP webhook routes are derived from the router's endpoint configs and
    /// merged into the Axum router at startup.
    #[cfg(feature = "inbound-mail")]
    pub(crate) inbound_mail_router: Option<Arc<crate::inbound_mail::InboundMailRouter>>,
}

/// Boxed builder closure that constructs a durable
/// [`MailDeliveryQueue`](crate::mail::MailDeliveryQueue) from the live
/// [`AppState`].
#[cfg(feature = "mail")]
pub(crate) type MailDeliveryQueueFactory = Box<
    dyn FnOnce(&AppState) -> crate::AutumnResult<Arc<dyn crate::mail::MailDeliveryQueue>> + Send,
>;

/// A group of routes sharing a common path prefix and middleware layer.
///
/// Created by [`AppBuilder::scoped`]. The routes are mounted under the
/// prefix with the middleware applied only to this group.
pub struct ScopedGroup {
    pub prefix: String,
    pub routes: Vec<Route>,
    /// Registration origin: user application or a named plugin.
    pub source: crate::route_listing::RouteSource,
    /// Closure that applies the layer to a sub-router.
    pub apply_layer: Box<dyn FnOnce(axum::Router<AppState>) -> axum::Router<AppState> + Send>,
}

/// A deferred router mutator that applies a user-registered
/// [`tower::Layer`] to the app-wide router.
///
/// Stored on [`AppBuilder`] by [`AppBuilder::layer`] and drained inside
/// `apply_middleware` where the final layer stack is assembled.
pub(crate) type CustomLayerApplier =
    Box<dyn FnOnce(axum::Router<AppState>) -> axum::Router<AppState> + Send>;

/// Metadata and deferred application closure for a user-registered layer.
pub(crate) struct CustomLayerRegistration {
    /// Concrete type for the registered layer.
    pub(crate) type_id: TypeId,
    /// Concrete type name for generic layer families that need router-time
    /// classification without unstable specialization.
    pub(crate) type_name: &'static str,
    /// Deferred router mutation that applies the layer.
    pub(crate) apply: CustomLayerApplier,
}

mod sealed {
    pub trait Sealed {}
}

/// Marker trait for types that can be registered with
/// [`AppBuilder::layer`] as an app-wide Tower middleware.
///
/// Any [`tower::Layer`] whose produced service is a compatible axum
/// service (i.e. `Service<Request, Response = Response, Error = Infallible>`,
/// plus the usual `Clone + Send + Sync + 'static` bounds and a `Send`
/// future) implements this trait automatically via a blanket impl.
///
/// The trait is **sealed**: it exists only to surface a clean
/// `IntoAppLayer is not implemented for YourType` error message when a
/// candidate layer fails to meet axum's service bounds, instead of a
/// 40-line associated-type wall. You cannot implement it manually, and
/// you should not need to — just bring your own `tower::Layer`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not a usable Autumn app-wide Tower layer",
    label = "this type does not implement `tower::Layer<axum::routing::Route>` with the required service bounds",
    note = "`AppBuilder::layer(..)` requires:\n    L: tower::Layer<axum::routing::Route> + Clone + Send + Sync + 'static,\n    L::Service: Service<axum::extract::Request, Response = axum::response::Response, Error = Infallible> + Clone + Send + Sync + 'static,\n    <L::Service as Service<axum::extract::Request>>::Future: Send + 'static\nSee docs/guide/middleware.md for common patterns and how to wrap raw-error layers (e.g. TimeoutLayer) with HandleErrorLayer."
)]
pub trait IntoAppLayer: sealed::Sealed + Send + Sync + 'static {
    /// Apply this layer to the given router. Not intended for direct use.
    #[doc(hidden)]
    fn apply_to(self, router: axum::Router<AppState>) -> axum::Router<AppState>;
}

impl<L> sealed::Sealed for L
where
    L: tower::Layer<axum::routing::Route> + Clone + Send + Sync + 'static,
    L::Service: tower::Service<
            axum::extract::Request,
            Response = axum::response::Response,
            Error = std::convert::Infallible,
        > + Clone
        + Send
        + Sync
        + 'static,
    <L::Service as tower::Service<axum::extract::Request>>::Future: Send + 'static,
{
}

impl<L> IntoAppLayer for L
where
    L: tower::Layer<axum::routing::Route> + Clone + Send + Sync + 'static,
    L::Service: tower::Service<
            axum::extract::Request,
            Response = axum::response::Response,
            Error = std::convert::Infallible,
        > + Clone
        + Send
        + Sync
        + 'static,
    <L::Service as tower::Service<axum::extract::Request>>::Future: Send + 'static,
{
    fn apply_to(self, router: axum::Router<AppState>) -> axum::Router<AppState> {
        router.layer(self)
    }
}

impl AppBuilder {
    /// Register a collection of routes with the application.
    ///
    /// Can be called multiple times -- routes are combined additively.
    /// Use the [`routes!`](crate::routes) macro to collect annotated
    /// handlers into the expected `Vec<Route>`.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use autumn_web::prelude::*;
    /// # #[get("/users")] async fn list_users() -> &'static str { "" }
    /// # #[get("/posts")] async fn list_posts() -> &'static str { "" }
    /// # #[autumn_web::main]
    /// # async fn main() {
    /// autumn_web::app()
    ///     .routes(routes![list_users])
    ///     .routes(routes![list_posts])
    ///     .run()
    ///     .await;
    /// # }
    /// ```
    #[must_use]
    pub fn routes(mut self, routes: Vec<Route>) -> Self {
        let source = self
            .current_plugin
            .as_ref()
            .map_or(crate::route_listing::RouteSource::User, |name| {
                crate::route_listing::RouteSource::Plugin(name.clone())
            });
        for _ in &routes {
            self.route_sources.push(source.clone());
        }
        self.routes.extend(routes);
        self
    }

    /// Register scheduled background tasks with the application.
    ///
    /// Tasks run alongside the HTTP server and are stopped during
    /// graceful shutdown. Use the [`tasks!`](crate::tasks) macro
    /// to collect `#[scheduled]` handlers.
    #[must_use]
    pub fn tasks(mut self, tasks: Vec<crate::task::TaskInfo>) -> Self {
        self.tasks.extend(tasks);
        self
    }

    /// Register one-off operational tasks runnable with `autumn task <name>`.
    ///
    /// Use the [`one_off_tasks!`](crate::one_off_tasks) macro to collect
    /// `#[task]` handlers.
    #[must_use]
    pub fn one_off_tasks(mut self, tasks: Vec<crate::task::OneOffTaskInfo>) -> Self {
        self.one_off_tasks.extend(tasks);
        self
    }

    /// Register ad-hoc background jobs with the application.
    #[must_use]
    pub fn jobs(mut self, jobs: Vec<crate::job::JobInfo>) -> Self {
        self.jobs.extend(jobs);
        self
    }

    /// Register event listeners with the application.
    ///
    /// Collect them with `listeners![..]`. Durable listeners are wired onto the
    /// job runtime automatically (no separate `jobs![..]` entry needed); sync
    /// listeners run in-request when their event is published. Decoupled from
    /// emitters: adding a listener never touches the code that publishes.
    #[must_use]
    pub fn listeners(mut self, listeners: Vec<crate::events::ListenerInfo>) -> Self {
        self.listeners.extend(listeners);
        self
    }

    /// Register static route metadata for build-time rendering.
    ///
    /// Use the [`static_routes!`](crate::static_routes) macro to collect
    /// `#[static_get]` handlers' metadata.
    #[must_use]
    pub fn static_routes(mut self, metas: Vec<crate::static_gen::StaticRouteMeta>) -> Self {
        self.static_metas.extend(metas);
        self
    }

    /// Register a [`SitemapSource`](crate::seo::SitemapSource) for dynamic sitemap entries.
    ///
    /// When called at least once, the framework automatically serves `/sitemap.xml` and
    /// `/robots.txt`. Dynamic sources (e.g. blog posts from a database) produce entries
    /// collected at request time.
    ///
    /// Combine with `[seo] base_url` in `autumn.toml` to auto-inject the `Sitemap:`
    /// directive in `robots.txt` and compute canonical URLs.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use autumn_web::prelude::*;
    /// use autumn_web::seo::{SitemapEntry, SitemapSource};
    /// use std::pin::Pin;
    /// use std::future::Future;
    ///
    /// struct PostsSitemap;
    ///
    /// impl SitemapSource for PostsSitemap {
    ///     fn entries(&self) -> Pin<Box<dyn Future<Output = Vec<SitemapEntry>> + Send>> {
    ///         Box::pin(async {
    ///             vec![SitemapEntry::new("https://example.com/posts/hello")]
    ///         })
    ///     }
    /// }
    ///
    /// # #[autumn_web::main]
    /// # async fn main() {
    /// # #[get("/")] async fn index() -> &'static str { "" }
    /// autumn_web::app()
    ///     .routes(routes![index])
    ///     .seo_source(PostsSitemap)
    ///     .run()
    ///     .await;
    /// # }
    /// ```
    #[must_use]
    pub fn seo_source<S: crate::seo::SitemapSource + 'static>(mut self, source: S) -> Self {
        self.seo_sources.push(Arc::new(source));
        self
    }

    /// Enable `OpenAPI` (Swagger) spec auto-generation.
    ///
    /// When called, the framework inspects every registered route's
    /// [`ApiDoc`](crate::openapi::ApiDoc) metadata — inferred at compile
    /// time from the route path, HTTP method, extractor types, and any
    /// [`#[api_doc(...)]`](crate::api_doc) overrides — and serves an
    /// `OpenAPI` 3.0 JSON document at `OpenApiConfig::openapi_json_path`
    /// (default `/v3/api-docs`). If
    /// `OpenApiConfig::swagger_ui_path` is set (default `/swagger-ui`),
    /// a Swagger UI HTML page is served there too.
    ///
    /// Routes marked `#[api_doc(hidden)]` are excluded.
    ///
    /// **Gated behind the `openapi` Cargo feature.** Add
    /// `features = ["openapi"]` to your `autumn-web` dependency to
    /// enable it; the default build excludes the runtime spec types
    /// and endpoints to keep the binary small.
    ///
    /// # Examples
    ///
    /// Zero-config:
    ///
    /// ```rust,ignore
    /// use autumn_web::prelude::*;
    /// use autumn_web::openapi::OpenApiConfig;
    ///
    /// # #[get("/hello")] async fn hello() -> &'static str { "hi" }
    /// # #[autumn_web::main]
    /// # async fn main() {
    /// autumn_web::app()
    ///     .routes(routes![hello])
    ///     .openapi(OpenApiConfig::new("My API", "1.0.0"))
    ///     .run()
    ///     .await;
    /// # }
    /// ```
    ///
    /// With custom paths:
    ///
    /// ```rust,ignore
    /// use autumn_web::openapi::OpenApiConfig;
    ///
    /// let config = OpenApiConfig::new("My API", "1.0.0")
    ///     .description("Full product API")
    ///     .openapi_json_path("/openapi.json")
    ///     .swagger_ui_path(Some("/docs".to_owned()));
    /// ```
    #[cfg(feature = "openapi")]
    #[must_use]
    pub fn openapi(mut self, config: crate::openapi::OpenApiConfig) -> Self {
        self.openapi = Some(config);
        self
    }

    /// Mount a Model Context Protocol (MCP) endpoint at `path` (e.g. `/mcp`).
    ///
    /// Projects opted-in routes — those tagged `#[api_doc(mcp)]` — as
    /// agent-callable MCP tools over Streamable HTTP, handling `initialize`,
    /// `tools/list`, and `tools/call`. A tool's `name`, `description`, and
    /// `inputSchema` are derived from the handler's existing
    /// [`ApiDoc`](crate::openapi::ApiDoc), so the tool catalog cannot drift
    /// from the handler's typed contract. `tools/call` dispatches through the
    /// real handler pipeline, so `#[secured]`, authorization, rate limits, and
    /// validation apply identically to agent and HTTP calls.
    ///
    /// Opt-in is per-endpoint; nothing is exposed implicitly. Use
    /// [`expose_all_as_mcp`](Self::expose_all_as_mcp) for the whole-API hatch.
    ///
    /// Only **JSON** endpoints are projected: a route is eligible when it
    /// returns `Json<T>` (the structural signal for a JSON response). The
    /// generated tool's `body` input is derived solely from a `Json<T>`
    /// request extractor, so a handler that returns `Json<T>` but reads its
    /// body via `Form<T>`, `Multipart`, `Bytes`, or `String` should **not** be
    /// opted in — the tool would carry no body input and replay an empty
    /// request. Use JSON request bodies for endpoints exposed as MCP tools.
    ///
    /// `tools/call` replays through the same pipeline as a direct HTTP request,
    /// so `#[secured]`, route guards, rate limits, and validation apply
    /// identically. One caveat applies only in **static/ISR mode** (an app with
    /// a `dist` manifest): a global [`layer`](Self::layer) is applied outside
    /// the static-first middleware and is therefore *not* traversed by MCP
    /// `tools/call` replays. Prefer `#[secured]` or route-level guards (which do
    /// apply) for MCP-exposed handlers in that mode.
    ///
    /// Requires the `mcp` Cargo feature.
    ///
    /// ```rust,ignore
    /// autumn_web::app()
    ///     .routes(routes![list_todos, create_todo])
    ///     .mount_mcp("/mcp")
    ///     .run()
    ///     .await;
    /// ```
    #[cfg(feature = "mcp")]
    #[must_use]
    pub fn mount_mcp(mut self, path: impl Into<String>) -> Self {
        let path = path.into();
        if let Some(rt) = self.mcp.as_mut() {
            rt.mount_path = path;
        } else {
            self.mcp = Some(crate::mcp::McpRuntime::new(path));
        }
        self
    }

    /// Whole-API escape hatch: expose **every** eligible read (`GET`) endpoint
    /// as an MCP tool without per-endpoint tags.
    ///
    /// This is an explicit, separate opt-in — never the default. It still
    /// honors per-endpoint exclusions (`#[api_doc(mcp = false)]`) and the
    /// JSON-only rule, and **mutating verbs (`POST`/`PUT`/`PATCH`/`DELETE`)
    /// still require an explicit `#[api_doc(mcp)]` opt-in** even under the
    /// hatch.
    ///
    /// On its own this mounts the endpoint at the default `/mcp`; chain
    /// [`mount_mcp`](Self::mount_mcp) to serve it at a different path.
    ///
    /// Requires the `mcp` Cargo feature.
    #[cfg(feature = "mcp")]
    #[must_use]
    pub fn expose_all_as_mcp(mut self) -> Self {
        if let Some(rt) = self.mcp.as_mut() {
            rt.expose_all = true;
        } else {
            let mut rt = crate::mcp::McpRuntime::new("/mcp");
            rt.expose_all = true;
            self.mcp = Some(rt);
        }
        self
    }

    /// Gate the **entire** MCP endpoint — the catalog (`initialize`/
    /// `tools/list`) as well as tool dispatch — behind a tower `layer`.
    ///
    /// The `/mcp` envelope is otherwise reachable without the app's global
    /// middleware. Pass an auth layer (e.g.
    /// [`RequireApiToken`](crate::auth::RequireApiToken)) here to require a
    /// credential for the whole endpoint, the way you'd protect a normal
    /// route group. Combine with [`mount_mcp`](Self::mount_mcp); the MCP
    /// transport's spec-required `Origin` validation (sourced from your CORS
    /// `allowed_origins`) always applies regardless of this layer.
    ///
    /// Requires the `mcp` Cargo feature.
    #[cfg(feature = "mcp")]
    #[must_use]
    pub fn secure_mcp<L>(mut self, layer: L) -> Self
    where
        L: tower::Layer<axum::routing::Route> + Clone + Send + Sync + 'static,
        L::Service: tower::Service<
                axum::http::Request<axum::body::Body>,
                Response = axum::http::Response<axum::body::Body>,
                Error = std::convert::Infallible,
            > + Clone
            + Send
            + Sync
            + 'static,
        <L::Service as tower::Service<axum::http::Request<axum::body::Body>>>::Future:
            Send + 'static,
    {
        let applier: crate::mcp::McpEndpointLayer = Box::new(move |router| router.layer(layer));
        if let Some(rt) = self.mcp.as_mut() {
            rt.endpoint_layer = Some(applier);
        } else {
            let mut rt = crate::mcp::McpRuntime::new("/mcp");
            rt.endpoint_layer = Some(applier);
            self.mcp = Some(rt);
        }
        self
    }

    /// Register a global exception filter.
    ///
    /// Exception filters intercept error responses produced by
    /// [`AutumnError`](crate::AutumnError) before they are sent to the
    /// client. Filters run in registration order.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use autumn_web::middleware::{ExceptionFilter, AutumnErrorInfo};
    /// use axum::response::Response;
    ///
    /// struct LogFilter;
    /// impl ExceptionFilter for LogFilter {
    ///     fn filter(&self, error: &AutumnErrorInfo, response: Response) -> Response {
    ///         eprintln!("Error: {}", error.message);
    ///         response
    ///     }
    /// }
    ///
    /// # use autumn_web::prelude::*;
    /// # #[get("/")] async fn index() -> &'static str { "" }
    /// # #[autumn_web::main]
    /// # async fn main() {
    /// autumn_web::app()
    ///     .exception_filter(LogFilter)
    ///     .routes(routes![index])
    ///     .run()
    ///     .await;
    /// # }
    /// ```
    #[must_use]
    pub fn exception_filter(mut self, filter: impl ExceptionFilter) -> Self {
        self.exception_filters.push(Arc::new(filter));
        self
    }

    /// Register a custom error page renderer.
    ///
    /// The renderer replaces the built-in default error pages (404, 422, 500,
    /// and generic errors). Implement [`ErrorPageRenderer`] to provide your
    /// own branded error pages.
    ///
    /// Only one renderer can be active. Calling this method multiple times
    /// replaces the previous renderer.
    ///
    /// Requires the `maud` feature.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use autumn_web::error_pages::{ErrorPageRenderer, ErrorContext};
    /// use maud::{Markup, html};
    ///
    /// struct MyErrors;
    ///
    /// impl ErrorPageRenderer for MyErrors {
    ///     fn render_error(&self, ctx: &ErrorContext) -> Markup {
    ///         html! {
    ///             h1 { (ctx.status.as_u16()) " - Custom error page" }
    ///         }
    ///     }
    /// }
    ///
    /// # use autumn_web::prelude::*;
    /// # #[get("/")] async fn index() -> &'static str { "" }
    /// # #[autumn_web::main]
    /// # async fn main() {
    /// autumn_web::app()
    ///     .error_pages(MyErrors)
    ///     .routes(routes![index])
    ///     .run()
    ///     .await;
    /// # }
    /// ```
    #[must_use]
    #[cfg(feature = "maud")]
    pub fn error_pages(mut self, renderer: impl ErrorPageRenderer) -> Self {
        self.error_page_renderer = Some(Arc::new(renderer));
        self
    }

    /// Register a group of routes with a shared path prefix and middleware.
    ///
    /// The `layer` is applied only to routes within this group, not to the
    /// rest of the application. The routes are mounted under `prefix`.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use autumn_web::prelude::*;
    /// use autumn_web::middleware::RequestIdLayer; // any Tower Layer
    ///
    /// # #[get("/")]  async fn index() -> &'static str { "" }
    /// # #[get("/users")] async fn list_users() -> &'static str { "" }
    /// # #[autumn_web::main]
    /// # async fn main() {
    /// autumn_web::app()
    ///     .routes(routes![index])
    ///     .scoped("/api", RequestIdLayer, routes![list_users])
    ///     .run()
    ///     .await;
    /// # }
    /// ```
    #[must_use]
    pub fn scoped<L>(mut self, prefix: &str, layer: L, routes: Vec<Route>) -> Self
    where
        L: tower::Layer<axum::routing::Route> + Clone + Send + Sync + 'static,
        L::Service: tower::Service<
                axum::http::Request<axum::body::Body>,
                Response = axum::http::Response<axum::body::Body>,
                Error = std::convert::Infallible,
            > + Clone
            + Send
            + Sync
            + 'static,
        <L::Service as tower::Service<axum::http::Request<axum::body::Body>>>::Future:
            Send + 'static,
    {
        let source = self
            .current_plugin
            .as_ref()
            .map_or(crate::route_listing::RouteSource::User, |name| {
                crate::route_listing::RouteSource::Plugin(name.clone())
            });
        self.scoped_groups.push(ScopedGroup {
            prefix: prefix.to_owned(),
            routes,
            source,
            apply_layer: Box::new(move |router| router.layer(layer)),
        });
        self
    }

    /// Apply a custom [`tower::Layer`] to the entire application.
    ///
    /// This is the escape hatch for integrating any middleware from the
    /// Tower / Tower-HTTP ecosystem (timeouts, rate limiting, bespoke
    /// tracing, request signing, etc.) without forking the framework.
    ///
    /// The generic bound is [`IntoAppLayer`], a sealed trait with a blanket
    /// impl for every `tower::Layer` that meets axum's service requirements
    /// — in practice this means any standard Tower layer whose service
    /// produces `Infallible` errors. If your layer produces real errors
    /// (like `TimeoutLayer`'s `BoxError`), wrap it with
    /// [`axum::error_handling::HandleErrorLayer`] before passing it here.
    ///
    /// # Ordering
    ///
    /// User layers are applied **inside** Autumn's request-ID layer on the
    /// ingress path, which means your middleware always sees the generated
    /// `RequestId` in the request extensions. The full stack (outermost to
    /// innermost on ingress) is:
    ///
    /// `Metrics -> ExceptionFilter -> ErrorPageContext -> Session ->`
    /// `SecurityHeaders -> RequestId -> [user layers, registration order]`
    /// `-> CSRF -> CORS -> route handler`
    ///
    /// When `.layer()` is called multiple times, the **first** call becomes
    /// the outermost user layer on ingress (matching `tower::ServiceBuilder`
    /// semantics): the layer from the first `.layer(...)` call sees the
    /// request first on the way in and the response last on the way out.
    ///
    /// # Scope
    ///
    /// This layer applies **globally** to every route in the app, including
    /// routes added later by plugins, routes mounted via `.merge` / `.nest`,
    /// and the built-in `404` fallback. Use [`AppBuilder::scoped`] when you
    /// need middleware scoped to a group of routes.
    ///
    /// Shared state (pools, metrics registries, rate-limit stores, etc.)
    /// should be wrapped in `Arc` so the layer can satisfy the
    /// `Clone + Send + Sync + 'static` bounds without moving the state.
    ///
    /// See [the middleware guide](https://github.com/madmax983/autumn/blob/trunk/docs/guide/middleware.md)
    /// for ready-made recipes.
    ///
    /// # Examples
    ///
    /// Adding a Tower timeout layer in one line (Tower's `TimeoutLayer`
    /// returns `BoxError`, so it must be paired with `HandleErrorLayer` to
    /// satisfy axum's `Infallible` error requirement):
    ///
    /// ```rust,no_run
    /// use std::time::Duration;
    /// use autumn_web::prelude::*;
    /// use axum::{error_handling::HandleErrorLayer, http::StatusCode};
    /// use tower::{ServiceBuilder, timeout::TimeoutLayer};
    ///
    /// # #[get("/")] async fn index() -> &'static str { "ok" }
    /// # #[autumn_web::main]
    /// # async fn main() {
    /// autumn_web::app()
    ///     .routes(routes![index])
    ///     .layer(
    ///         ServiceBuilder::new()
    ///             .layer(HandleErrorLayer::new(|_| async {
    ///                 StatusCode::REQUEST_TIMEOUT
    ///             }))
    ///             .layer(TimeoutLayer::new(Duration::from_secs(5))),
    ///     )
    ///     .run()
    ///     .await;
    /// # }
    /// ```
    #[must_use]
    pub fn layer<L: IntoAppLayer>(mut self, layer: L) -> Self {
        self.custom_layers.push(CustomLayerRegistration {
            type_id: TypeId::of::<L>(),
            type_name: std::any::type_name::<L>(),
            apply: Box::new(move |router| layer.apply_to(router)),
        });
        self
    }

    /// Returns `true` when a custom layer of type `L` has already been
    /// registered via [`AppBuilder::layer`].
    ///
    /// Intended for plugin pre-flight validation before the app is started.
    #[must_use]
    pub fn has_layer<L: 'static>(&self) -> bool {
        let layer_type = TypeId::of::<L>();
        self.custom_layers
            .iter()
            .any(|registered| registered.type_id == layer_type)
    }

    /// Enable the HTTP idempotency-key middleware for this application.
    ///
    /// Mutating requests (`POST`, `PUT`, `PATCH`, `DELETE`) that carry an
    /// `Idempotency-Key` header are deduplicated: the first response is cached
    /// and replayed byte-for-byte on subsequent identical requests.
    /// Session-mutating responses are cached after the outer session middleware
    /// has finalized `Set-Cookie`, so retries can observe the successful
    /// mutation without re-entering the handler.
    ///
    /// Raw Axum routers registered with [`merge`](Self::merge) or
    /// [`nest`](Self::nest) are opaque to Autumn. They are protected from
    /// duplicate mutating retries by failing closed on cache hits; install
    /// idempotency and replay-stop layers inside those routers when raw routes
    /// need successful cached-response replay after their own route-local
    /// checks.
    ///
    /// The storage backend and TTL are taken from the `[idempotency]` block in
    /// `autumn.toml` (defaulting to in-process memory with a 24 h TTL).
    /// For multi-replica deployments set `backend = "redis"` and configure
    /// `[idempotency.redis]`.
    ///
    /// # Startup validation
    ///
    /// In production (`AUTUMN_PROFILE=production`) the memory backend is
    /// rejected unless `allow_memory_in_production = true` is set explicitly.
    #[must_use]
    pub const fn idempotent(mut self) -> Self {
        self.idempotency_enabled = true;
        self
    }

    /// Returns the registered custom layer types in registration order.
    ///
    /// This includes only user-installed layers from
    /// [`AppBuilder::layer`], not framework-managed middleware.
    #[must_use]
    pub fn get_layer_types(&self) -> Vec<TypeId> {
        self.custom_layers
            .iter()
            .map(|registered| registered.type_id)
            .collect()
    }

    /// Register a Tower layer that runs **before** the static file middleware
    /// and the static cache lookup — Autumn's equivalent of Next.js *Edge
    /// Middleware*.
    ///
    /// Cached SSG/ISG pages are served by the static-first middleware before
    /// the inner router (session, auth) is ever reached, so framework auth
    /// layers cannot gate pre-rendered responses. A `static_gate` layer runs
    /// outermost — outside the session layer and ahead of the static cache —
    /// so it can redirect or reject a request before a cached page is served.
    ///
    /// This is the right place for auth gating that protects pre-rendered
    /// routes: redirect unauthenticated visitors to a login page while leaving
    /// the cached HTML free of user-specific content. Personalised content
    /// still requires a fully dynamic route or client-side fetching.
    ///
    /// # Position and limitations
    ///
    /// * Runs as the **outermost** user middleware in *both* SSG/ISG and
    ///   fully-dynamic modes, so the same gate behaves identically regardless
    ///   of whether static generation is active.
    /// * Has access to request **headers and cookies**, but **NOT** the
    ///   session [`Extension`](axum::Extension) — the session layer runs inside
    ///   it. Verify a signed/JWT session cookie directly (e.g. with the same
    ///   signing key configured for the session) rather than relying on
    ///   session-populated extensions.
    /// * Like [`layer`](Self::layer), it applies globally to every route.
    /// * **Page-cache gate, not API auth.** The gate guards GET/HEAD page
    ///   serving and acts by issuing a browser redirect/reject. It is **not**
    ///   applied to MCP `tools/call` dispatch (a JSON-RPC call, where a redirect
    ///   is meaningless) in *either* mode: the gate is applied after the MCP
    ///   dispatch clone is taken. Gate MCP tools and JSON APIs with route-level
    ///   guards / `#[secured]` / session auth, which always traverse the
    ///   dispatch path. A well-behaved gate should therefore no-op on non-GET
    ///   requests (such as the `/mcp` JSON-RPC POST transport).
    /// * Short-circuit responses (the redirect/reject) are wrapped by the
    ///   framework's security-header layer, so they still carry HSTS/CSP, etc.
    /// * Because the gate runs **outside** the request stack (it must run before
    ///   session and the static cache), a gate short-circuit does **not** pass
    ///   through trusted-host validation or the per-request timeout — same as any
    ///   middleware registered with [`layer`](Self::layer) that runs before
    ///   those framework layers. Keep gate work bounded (prefer local
    ///   cookie/JWT checks over unbounded remote calls), and rely on the
    ///   framework's trusted-host policy for the routes the gate forwards to.
    ///
    /// Layers are wrapped in registration order with the first-registered gate
    /// outermost, matching [`tower::ServiceBuilder`] semantics.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use autumn_web::prelude::*;
    /// use axum::{
    ///     extract::Request,
    ///     http::{header, Method, StatusCode},
    ///     middleware::Next,
    ///     response::Response,
    /// };
    ///
    /// async fn require_auth(req: Request, next: Next) -> Response {
    ///     // Only gate page navigation. Pass non-GET/HEAD requests (JSON APIs,
    ///     // form POSTs, the `/mcp` JSON-RPC transport, CORS preflights) straight
    ///     // through so a browser redirect never turns them into a 302.
    ///     let is_page = matches!(req.method(), &Method::GET | &Method::HEAD);
    ///     // Inspect a signed session cookie directly — no session Extension
    ///     // is available this far out in the stack.
    ///     if !is_page || req.headers().contains_key("x-authed") {
    ///         next.run(req).await
    ///     } else {
    ///         Response::builder()
    ///             .status(StatusCode::FOUND)
    ///             .header(header::LOCATION, "/login")
    ///             .body(axum::body::Body::empty())
    ///             .unwrap()
    ///     }
    /// }
    ///
    /// # #[get("/")] async fn index() -> &'static str { "ok" }
    /// # #[autumn_web::main]
    /// # async fn main() {
    /// autumn_web::app()
    ///     .routes(routes![index])
    ///     .static_gate(axum::middleware::from_fn(require_auth))
    ///     .run()
    ///     .await;
    /// # }
    /// ```
    #[must_use]
    pub fn static_gate<L: IntoAppLayer>(mut self, layer: L) -> Self {
        self.static_gate_layers.push(CustomLayerRegistration {
            type_id: TypeId::of::<L>(),
            type_name: std::any::type_name::<L>(),
            apply: Box::new(move |router| layer.apply_to(router)),
        });
        self
    }

    /// Returns `true` when a pre-static gate layer of type `L` has already
    /// been registered via [`AppBuilder::static_gate`].
    ///
    /// Intended for plugin pre-flight validation before the app is started.
    #[must_use]
    pub fn has_static_gate<L: 'static>(&self) -> bool {
        let layer_type = TypeId::of::<L>();
        self.static_gate_layers
            .iter()
            .any(|registered| registered.type_id == layer_type)
    }

    /// Returns the registered pre-static gate layer types in registration
    /// order.
    ///
    /// This includes only user-installed gates from
    /// [`AppBuilder::static_gate`], not regular layers or framework
    /// middleware.
    #[must_use]
    pub fn get_static_gate_types(&self) -> Vec<TypeId> {
        self.static_gate_layers
            .iter()
            .map(|registered| registered.type_id)
            .collect()
    }

    /// Merge a raw Axum router into the application.
    ///
    /// This is an escape hatch for when Autumn's route macros are not
    /// sufficient -- for example, when integrating a third-party Axum
    /// middleware crate or mounting a hand-built WebSocket handler.
    ///
    /// The merged router shares the same [`AppState`] (database pool,
    /// config, etc.) and Autumn's global middleware (request IDs,
    /// security headers, session management) applies to its routes.
    /// When `.idempotent()` is enabled, retries that hit an existing raw-route
    /// idempotency record fail closed instead of rerunning the raw handler or
    /// replaying around opaque route-local checks. Install idempotency and
    /// replay-stop layers inside the raw router when successful replay is
    /// required.
    ///
    /// Merged routes are added **after** Autumn's annotated routes.
    /// If both define the same method+path pair, Axum treats that as an
    /// overlap and router construction will fail.
    ///
    /// Can be called multiple times -- routers are accumulated.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use autumn_web::prelude::*;
    /// use autumn_web::AppState;
    ///
    /// #[get("/")]
    /// async fn index() -> &'static str { "hi" }
    ///
    /// #[autumn_web::main]
    /// async fn main() {
    ///     let raw = axum::Router::<AppState>::new()
    ///         .route("/ws", axum::routing::get(|| async { "websocket" }));
    ///
    ///     autumn_web::app()
    ///         .routes(routes![index])
    ///         .merge(raw)
    ///         .run()
    ///         .await;
    /// }
    /// ```
    #[must_use]
    pub fn merge(mut self, router: axum::Router<AppState>) -> Self {
        self.merge_routers.push(router);
        self
    }

    /// Mount a raw Axum router under a path prefix.
    ///
    /// This is an escape hatch similar to [`merge`](Self::merge), but the
    /// router's routes are nested under the given `path` prefix. Useful
    /// for mounting a self-contained API version or third-party router.
    ///
    /// The nested router shares the same [`AppState`] and Autumn's global
    /// middleware applies to its routes. When `.idempotent()` is enabled,
    /// retries that hit an existing raw-route idempotency record fail closed
    /// instead of rerunning the raw handler or replaying around opaque
    /// route-local checks. Install idempotency and replay-stop layers inside
    /// the raw router when successful replay is required.
    ///
    /// Can be called multiple times with different prefixes.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use autumn_web::prelude::*;
    /// use autumn_web::AppState;
    ///
    /// #[get("/")]
    /// async fn index() -> &'static str { "hi" }
    ///
    /// #[autumn_web::main]
    /// async fn main() {
    ///     let v2 = axum::Router::<AppState>::new()
    ///         .route("/users", axum::routing::get(|| async { "v2 users" }));
    ///
    ///     autumn_web::app()
    ///         .routes(routes![index])
    ///         .nest("/api/v2", v2)
    ///         .run()
    ///         .await;
    /// }
    /// ```
    #[must_use]
    pub fn nest(mut self, path: &str, router: axum::Router<AppState>) -> Self {
        self.nest_routers.push((path.to_owned(), router));
        self
    }

    /// Explicitly register route metadata for listing via `autumn routes`.
    ///
    /// Plugins that mount routes via [`AppBuilder::nest`] (which is opaque to
    /// the route listing) can call this method so that `autumn routes --format json`
    /// shows their routes with the correct plugin attribution.
    ///
    /// Routes are automatically attributed to the current plugin when called from
    /// within a plugin's `build()` method. The `source` field of each supplied
    /// `RouteInfo` is overwritten with that attribution.
    ///
    /// Declaring routes also makes a [`nest`](Self::nest) mount *coverage-clean*
    /// for `autumn routes audit`: a nested router is normally opaque and counts
    /// as an omitted, unprovable router that hard-fails the gate, but when at
    /// least one declared route's path falls under the nest's prefix, the mount
    /// is treated as enumerable and no longer counts. So the documented
    /// `app.nest(prefix, router).declare_plugin_routes(routes)` pattern — with
    /// `routes` covering everything the raw router serves under `prefix` — passes
    /// the audit. A bare `nest`/`merge` with no covering declaration stays
    /// opaque and still fails closed.
    #[must_use]
    pub fn declare_plugin_routes(
        mut self,
        routes: impl IntoIterator<Item = crate::route_listing::RouteInfo>,
    ) -> Self {
        let source = self
            .current_plugin
            .as_deref()
            .map_or(crate::route_listing::RouteSource::User, |name| {
                crate::route_listing::RouteSource::Plugin(name.to_owned())
            });
        for mut route in routes {
            route.source = source.clone();
            self.declared_routes.push(route);
        }
        self
    }

    /// Register an async startup hook that runs after [`AppState`] exists and
    /// before the server begins accepting requests.
    ///
    /// This is intended for background runtimes that need the fully built app
    /// state, such as workers or pollers that share the database pool.
    #[must_use]
    pub fn on_startup<F, Fut>(mut self, hook: F) -> Self
    where
        F: Fn(AppState) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = crate::AutumnResult<()>> + Send + 'static,
    {
        self.startup_hooks
            .push(Box::new(move |state| Box::pin(hook(state))));
        self
    }

    /// Register a synchronous initializer that mutates [`AppState`] after
    /// framework-managed extensions are installed and before job workers start.
    #[must_use]
    pub fn state_initializer<F>(mut self, initializer: F) -> Self
    where
        F: FnOnce(&AppState) + Send + 'static,
    {
        self.state_initializers.push(Box::new(initializer));
        self
    }

    /// Register an async shutdown hook that runs during graceful shutdown.
    ///
    /// Hooks execute in reverse registration order so later-added runtimes
    /// shut down before earlier infrastructure they might depend on.
    #[must_use]
    pub fn on_shutdown<F, Fut>(mut self, hook: F) -> Self
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.shutdown_hooks.push(Box::new(move || Box::pin(hook())));
        self
    }

    /// Register a single API version. If a version with the same name already exists, it is updated.
    #[must_use]
    pub fn api_version(mut self, version: ApiVersion) -> Self {
        if let Some(pos) = self
            .api_versions
            .iter()
            .position(|v| v.version == version.version)
        {
            self.api_versions[pos] = version;
        } else {
            self.api_versions.push(version);
        }
        self
    }

    /// Register multiple API versions, replacing duplicates.
    #[must_use]
    pub fn api_versions(mut self, versions: impl IntoIterator<Item = ApiVersion>) -> Self {
        for version in versions {
            if let Some(pos) = self
                .api_versions
                .iter()
                .position(|v| v.version == version.version)
            {
                self.api_versions[pos] = version;
            } else {
                self.api_versions.push(version);
            }
        }
        self
    }

    /// Store or replace a typed builder extension.
    ///
    /// External crates use this to accumulate configuration across fluent
    /// extension-trait calls without Autumn needing to know the concrete type.
    #[must_use]
    pub fn with_extension<T>(mut self, value: T) -> Self
    where
        T: Any + Send + 'static,
    {
        self.extensions.insert(TypeId::of::<T>(), Box::new(value));
        self
    }

    /// Mutate a typed builder extension, inserting a default value first when
    /// the extension has not been registered yet.
    ///
    /// # Panics
    ///
    /// Panics if the internal extension type map is corrupted and the value
    /// stored under `T`'s [`TypeId`] cannot be downcast back to `T`.
    #[must_use]
    pub fn update_extension<T, Init, Update>(mut self, init: Init, update: Update) -> Self
    where
        T: Any + Send + 'static,
        Init: FnOnce() -> T,
        Update: FnOnce(&mut T),
    {
        let type_id = TypeId::of::<T>();
        let entry = self
            .extensions
            .entry(type_id)
            .or_insert_with(|| Box::new(init()));
        let typed = entry
            .downcast_mut::<T>()
            .expect("extension type map corrupted");
        update(typed);
        self
    }

    /// Borrow a typed builder extension if it has been registered.
    #[must_use]
    pub fn extension<T>(&self) -> Option<&T>
    where
        T: Any + Send + 'static,
    {
        self.extensions.get(&TypeId::of::<T>())?.downcast_ref::<T>()
    }

    #[cfg(feature = "mail")]
    #[must_use]
    pub fn with_mail_interceptor(
        mut self,
        interceptor: impl crate::interceptor::MailInterceptor,
    ) -> Self {
        self.mail_interceptor = Some(Arc::new(interceptor));
        self
    }

    #[must_use]
    pub fn with_job_interceptor(
        mut self,
        interceptor: impl crate::interceptor::JobInterceptor,
    ) -> Self {
        self.job_interceptor = Some(Arc::new(interceptor));
        self
    }

    #[cfg(feature = "db")]
    #[must_use]
    pub fn with_db_interceptor(
        mut self,
        interceptor: impl crate::interceptor::DbConnectionInterceptor,
    ) -> Self {
        self.db_interceptor = Some(Arc::new(interceptor));
        self
    }

    #[cfg(feature = "ws")]
    #[must_use]
    pub fn with_channels_interceptor(
        mut self,
        interceptor: impl crate::interceptor::ChannelsInterceptor,
    ) -> Self {
        self.channels_interceptor = Some(Arc::new(interceptor));
        self
    }

    #[cfg(feature = "oauth2")]
    #[must_use]
    pub fn with_http_interceptor(
        mut self,
        interceptor: impl crate::interceptor::HttpInterceptor,
    ) -> Self {
        self.http_interceptor = Some(Arc::new(interceptor));
        self
    }

    /// Register a pre-loaded i18n translation bundle.
    ///
    /// Most apps prefer [`Self::i18n_auto`] which loads from the
    /// `i18n/` directory using the configured `[i18n]` block. Use this
    /// directly when you need to construct a [`Bundle`](crate::i18n::Bundle)
    /// from non-filesystem sources (in-memory tests, embedded `.ftl` files,
    /// translation-management-system clients, etc.).
    #[cfg(feature = "i18n")]
    #[must_use]
    pub fn i18n(mut self, bundle: crate::i18n::Bundle) -> Self {
        self.i18n_bundle = Some(Arc::new(bundle));
        self.i18n_auto_load = false;
        self
    }

    /// Auto-load the i18n translation bundle from the configured directory
    /// (`i18n/` by default), reading the `[i18n]` block from the active
    /// [`AutumnConfig`].
    ///
    /// Fails fast during [`Self::run`] if the configured default locale's file is
    /// missing — the spec calls out this as the desired behaviour: a
    /// half-localized app is worse than a clearly-broken one. The error
    /// path here panics with the typed [`LoadError`](crate::i18n::LoadError)
    /// formatted as a string so it surfaces in the same banner as other
    /// fatal startup errors.
    ///
    /// # Panics
    ///
    /// Panics when configuration cannot be loaded, the configured i18n
    /// directory is unreadable, or the default locale bundle is missing or
    /// invalid.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use autumn_web::prelude::*;
    ///
    /// #[get("/")]
    /// async fn index() -> &'static str { "ok" }
    ///
    /// #[autumn_web::main]
    /// async fn main() {
    ///     # #[cfg(feature = "i18n")]
    ///     autumn_web::app()
    ///         .i18n_auto()
    ///         .routes(routes![index])
    ///         .run()
    ///         .await;
    /// }
    /// ```
    #[cfg(feature = "i18n")]
    #[must_use]
    pub fn i18n_auto(mut self) -> Self {
        self.i18n_bundle = None;
        self.i18n_auto_load = true;
        self
    }

    // ── Tier-1 subsystem replacement hooks ─────────────────────
    //
    // Each `with_*` method swaps a framework-default subsystem for a
    // user-provided trait impl. The defaults preserve current behaviour, so
    // applications that don't customize see no change. Plugins typically chain
    // these in their `build()` body to ship a subsystem (e.g. an
    // `AwsSecretsConfigPlugin` that calls `app.with_config_loader(...)`).
    // See `docs/guides/extensibility.md`.

    /// Install a custom [`ConfigLoader`],
    /// replacing the default TOML + env loader.
    ///
    /// Useful when your config lives somewhere other than `autumn.toml` —
    /// AWS Secrets Manager, Vault, a JSON file, an HTTP fetch, etc. Emits a
    /// `tracing::warn!` if a loader was already installed.
    #[must_use]
    pub fn with_config_loader<L>(mut self, loader: L) -> Self
    where
        L: crate::config::ConfigLoader,
    {
        if self.config_loader_factory.is_some() {
            tracing::warn!(
                "config loader replaced; the previously-installed loader was overwritten"
            );
        }
        self.config_loader_factory = Some(Box::new(move || {
            Box::pin(async move { loader.load().await })
        }));
        self
    }

    /// Install a custom [`crate::db::DatabasePoolProvider`],
    /// replacing the default `deadpool + diesel-async` pool factory.
    ///
    /// Useful for adding metrics/circuit-breaker wrappers, switching to a
    /// per-shard pool, or driving a non-default backend at the same
    /// `Pool<AsyncPgConnection>` interface. Emits a `tracing::warn!` if a
    /// provider was already installed.
    #[cfg(feature = "db")]
    #[must_use]
    pub fn with_pool_provider<P>(mut self, provider: P) -> Self
    where
        P: crate::db::DatabasePoolProvider,
    {
        if self.pool_provider_factory.is_some() {
            tracing::warn!(
                "database pool provider replaced; the previously-installed provider was overwritten"
            );
        }
        // The provider serves both the control topology and any configured
        // shard topologies; share it between the two captured closures.
        let provider = Arc::new(provider);
        let shard_provider = Arc::clone(&provider);
        self.pool_provider_factory =
            Some(Box::new(move |config: crate::config::DatabaseConfig| {
                Box::pin(async move { provider.create_topology(&config).await })
            }));
        self.shard_provider_factory =
            Some(Box::new(move |config: crate::config::DatabaseConfig| {
                Box::pin(async move {
                    let mut topologies = Vec::with_capacity(config.shards.len());
                    for shard in &config.shards {
                        topologies
                            .push(shard_provider.create_shard_topology(shard, &config).await?);
                    }
                    Ok(topologies)
                })
            }));
        self
    }

    /// Install a custom [`ShardRouter`](crate::sharding::ShardRouter),
    /// replacing the default slot-hash router for `[[database.shards]]`
    /// routing.
    ///
    /// Useful for directory/lookup routing — e.g. a control-plane table
    /// that pins hot tenants to dedicated shards. Custom routers can
    /// still compose with the deterministic hash via
    /// [`ShardSet::slot_for_key`](crate::sharding::ShardSet::slot_for_key)
    /// and
    /// [`ShardSet::shard_for_slot`](crate::sharding::ShardSet::shard_for_slot).
    #[cfg(feature = "db")]
    #[must_use]
    pub fn with_shard_router<R>(mut self, router: R) -> Self
    where
        R: crate::sharding::ShardRouter,
    {
        if self.shard_router.is_some() {
            tracing::warn!(
                "shard router replaced; the previously-installed router was overwritten"
            );
        }
        self.shard_router = Some(Arc::new(router));
        self
    }

    /// Route tenants through the control-plane `_autumn_shard_directory` table
    /// via a [`DirectoryShardRouter`](crate::sharding::DirectoryShardRouter).
    ///
    /// The router is bound to the control primary pool at build time. Tenants
    /// with a directory row are pinned to the named shard; everyone else falls
    /// back to the slot-hash router. Apply the framework migrations to the
    /// control database (`autumn migrate`) so `_autumn_shard_directory` exists.
    ///
    /// An explicit [`with_shard_router`](Self::with_shard_router) takes
    /// precedence over this flag.
    #[cfg(feature = "db")]
    #[must_use]
    pub const fn with_directory_shard_router(mut self) -> Self {
        self.directory_shard_router = true;
        self
    }

    /// Install a custom [`TelemetryProvider`](crate::telemetry::TelemetryProvider),
    /// replacing the default `tracing-subscriber + OTLP` initializer.
    ///
    /// Useful for shipping a Datadog tracer, Honeycomb beeline, Sentry
    /// integration, or any other observability backend. Emits a
    /// `tracing::warn!` if a provider was already installed.
    #[must_use]
    pub fn with_telemetry_provider<T>(mut self, provider: T) -> Self
    where
        T: crate::telemetry::TelemetryProvider,
    {
        if self.telemetry_provider.is_some() {
            tracing::warn!(
                "telemetry provider replaced; the previously-installed provider was overwritten"
            );
        }
        self.telemetry_provider = Some(Box::new(provider));
        self
    }

    /// Install a custom [`SessionStore`](crate::session::SessionStore),
    /// bypassing the config-driven `memory`/`redis` backend selection.
    ///
    /// Useful for backing sessions with a database, encrypted cookie store,
    /// or enterprise SSO bridge. Emits a `tracing::warn!` if a store was
    /// already installed.
    #[must_use]
    pub fn with_session_store<S>(mut self, store: S) -> Self
    where
        S: crate::session::SessionStore,
    {
        if self.session_store.is_some() {
            tracing::warn!(
                "session store replaced; the previously-installed store was overwritten"
            );
        }
        self.session_store = Some(Arc::new(store));
        self
    }

    /// Install a custom [`ChannelsBackend`](crate::channels::ChannelsBackend),
    /// bypassing the config-driven `in_process`/`redis` backend selection.
    ///
    /// Useful for NATS, Postgres `LISTEN/NOTIFY`, test harnesses, or a
    /// sharded pub/sub fabric. Emits a `tracing::warn!` if a backend was
    /// already installed.
    #[cfg(feature = "ws")]
    #[must_use]
    pub fn with_channels_backend<B>(mut self, backend: B) -> Self
    where
        B: crate::channels::ChannelsBackend,
    {
        if self.channels_backend.is_some() {
            tracing::warn!(
                "channels backend replaced; the previously-installed backend was overwritten"
            );
        }
        self.channels_backend = Some(Arc::new(backend));
        self
    }

    /// Install a custom [`BlobStore`](crate::storage::BlobStore),
    /// bypassing the config-driven `local`/`s3` backend selection.
    ///
    /// The typical use case is the `autumn-storage-s3` plugin:
    ///
    /// ```rust,ignore
    /// use autumn_storage_s3::S3BlobStore;
    ///
    /// # async fn example() {
    /// let config = autumn_web::config::TomlEnvConfigLoader::new()
    ///     .load().await.unwrap();
    /// let store = S3BlobStore::from_config(&config.storage.s3)
    ///     .await.unwrap();
    /// autumn_web::app()
    ///     .with_blob_store(store)
    ///     .run()
    ///     .await;
    /// # }
    /// ```
    ///
    /// Emits a `tracing::warn!` if a store was already installed (last
    /// call wins).
    ///
    /// # Note on `LocalBlobStore`
    ///
    /// **Do not** pass a [`LocalBlobStore`](crate::storage::LocalBlobStore)
    /// here. The local backend requires the framework to mount a `/_blobs`
    /// serving route (for HMAC-signed presigned URLs); that route is only
    /// wired up when the store is provisioned through the config-driven path
    /// (`backend = "local"` in `autumn.toml`). Calling
    /// `.with_blob_store(LocalBlobStore::new(...))` will silently succeed but
    /// presigned URLs will return 404. Use the `[storage]` config section for
    /// local storage.
    #[cfg(feature = "storage")]
    #[must_use]
    pub fn with_blob_store<B>(mut self, store: B) -> Self
    where
        B: crate::storage::BlobStore,
    {
        if self.blob_store.is_some() {
            tracing::warn!("blob store replaced; the previously-installed store was overwritten");
        }
        self.blob_store = Some(std::sync::Arc::new(store));
        self
    }

    /// Register a shared cache backend for the application.
    ///
    /// Once registered, `#[cached]` functions will use this backend as their
    /// primary store (falling back to their per-function Moka cache only if the
    /// global backend is absent). `CacheResponseLayer::from_app` returns a layer
    /// wired to this same backend.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use autumn_cache_redis::RedisCache;
    ///
    /// let cache = RedisCache::connect("redis://redis:6379", "myapp:cache").await?;
    /// autumn_web::app()
    ///     .with_cache_backend(cache)
    ///     .run()
    ///     .await;
    /// ```
    #[must_use]
    pub fn with_cache_backend<C: crate::cache::Cache>(mut self, cache: C) -> Self {
        if self.cache_backend.is_some() {
            tracing::warn!(
                "cache backend replaced; the previously-installed backend was overwritten"
            );
        }
        self.cache_backend = Some(Arc::new(cache) as Arc<dyn crate::cache::Cache>);
        self
    }

    /// Register an [`ErrorReporter`](crate::reporting::ErrorReporter) for
    /// unhandled panics and 5xx responses.
    ///
    /// Reporters receive a structured
    /// [`ErrorEvent`](crate::reporting::ErrorEvent) for every caught handler
    /// panic and every server-error response, carrying request context (route,
    /// method, request id, status) and — for panics — the panic payload and a
    /// backtrace (when `RUST_BACKTRACE` is set). Call this multiple times to
    /// chain reporters; each receives every event. When none are registered,
    /// the built-in [`LogReporter`](crate::reporting::LogReporter) is used.
    ///
    /// Mirrors [`with_blob_store`](Self::with_blob_store) /
    /// [`with_cache_backend`](Self::with_cache_backend).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use autumn_web::reporting::{ErrorEvent, ErrorReporter, ReportFuture};
    ///
    /// struct MyReporter;
    /// impl ErrorReporter for MyReporter {
    ///     fn report<'a>(&'a self, event: &'a ErrorEvent) -> ReportFuture<'a> {
    ///         Box::pin(async move { eprintln!("error: {} {}", event.status, event.message); })
    ///     }
    /// }
    ///
    /// # #[autumn_web::main]
    /// # async fn main() {
    /// autumn_web::app()
    ///     .with_error_reporter(MyReporter)
    /// #   .routes(vec![])
    /// #   ;
    /// # }
    /// ```
    #[cfg(feature = "reporting")]
    #[must_use]
    pub fn with_error_reporter<R: crate::reporting::ErrorReporter>(mut self, reporter: R) -> Self {
        self.error_reporters
            .push(Arc::new(reporter) as Arc<dyn crate::reporting::ErrorReporter>);
        self
    }

    /// Register an operator-alert delivery channel.
    ///
    /// Alerts for the built-in conditions (dead-lettered jobs, Down health
    /// indicators, 5xx-rate spikes, scheduled-task failures) are delivered to
    /// every registered [`AlertChannel`](crate::alerts::AlertChannel) **plus**
    /// the built-in mail/webhook channels derived from `[alerts]` config.
    ///
    /// This is the extension seam for additional transports (`PagerDuty`, Slack,
    /// Discord — follow-up #1630): implement
    /// [`AlertChannel`](crate::alerts::AlertChannel) and register it here. The
    /// framework core never changes. Most apps need no code at all — configuring
    /// an `email` and/or `webhook_url` under `[alerts]` is sufficient.
    ///
    /// ```rust,no_run
    /// use autumn_web::alerts::{Alert, AlertChannel, AlertDeliveryError, AlertDeliveryFuture};
    ///
    /// struct PagerDuty;
    /// impl AlertChannel for PagerDuty {
    ///     fn name(&self) -> &'static str { "pagerduty" }
    ///     fn deliver<'a>(&'a self, alert: &'a Alert) -> AlertDeliveryFuture<'a> {
    ///         Box::pin(async move {
    ///             let _ = (&alert.dedup_key, alert.severity);
    ///             Ok::<(), AlertDeliveryError>(())
    ///         })
    ///     }
    /// }
    ///
    /// # #[autumn_web::main]
    /// # async fn main() {
    /// autumn_web::app()
    ///     .with_alert_channel(PagerDuty)
    /// #   .routes(vec![])
    /// #   ;
    /// # }
    /// ```
    #[must_use]
    pub fn with_alert_channel<C: crate::alerts::AlertChannel>(mut self, channel: C) -> Self {
        self.alert_channels
            .push(Arc::new(channel) as Arc<dyn crate::alerts::AlertChannel>);
        self
    }

    /// Register a [`FlagStore`](crate::feature_flags::FlagStore) backend for
    /// feature-flag evaluation.
    ///
    /// After registration, the [`Flags`](crate::feature_flags::Flags) extractor
    /// and `#[feature_flag]` macro are available in route handlers. Without a
    /// registered store, both return `500 Internal Server Error`.
    ///
    /// For tests use [`InMemoryFlagStore`](crate::feature_flags::InMemoryFlagStore);
    /// in production use the Postgres-backed
    /// `autumn_web::feature_flags::pg::PgFlagStore`.
    ///
    /// # Sharing the store with the poll listener
    ///
    /// When using `PgFlagStore` in a multi-replica deployment, pass an `Arc`
    /// clone so the app service and the poll listener share the **same** cache:
    ///
    /// ```rust,ignore
    /// use std::sync::Arc;
    /// use std::time::Duration;
    /// use autumn_web::feature_flags::pg::PgFlagStore;
    ///
    /// let store = Arc::new(PgFlagStore::new(&config.database.primary_url));
    /// PgFlagStore::spawn_poll_listener(Arc::clone(&store), Duration::from_secs(1));
    /// autumn_web::app()
    ///     .with_flag_store(Arc::clone(&store))
    ///     .run()
    ///     .await;
    /// ```
    ///
    /// `Arc<PgFlagStore>` implements `FlagStore`, so the same `Arc` is
    /// accepted directly without creating a separate cache instance.
    ///
    /// # Basic example
    ///
    /// ```rust,ignore
    /// use autumn_web::feature_flags::InMemoryFlagStore;
    /// use std::sync::Arc;
    ///
    /// autumn_web::app()
    ///     .with_flag_store(InMemoryFlagStore::new())
    ///     .run()
    ///     .await;
    /// ```
    #[must_use]
    pub fn with_flag_store<S>(self, store: S) -> Self
    where
        S: crate::feature_flags::FlagStore,
    {
        let service = crate::feature_flags::FeatureFlagService::new(Arc::new(store) as Arc<_>);
        self.state_initializer(move |state| {
            state.insert_extension(service);
        })
    }

    /// Register a feature-flag store with a group-membership resolver.
    ///
    /// The resolver is called during flag evaluation to check whether an actor
    /// belongs to a named group listed in a flag's `group_allowlist`. Without
    /// registering a resolver, group gates are silently ignored.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use autumn_web::feature_flags::{InMemoryFlagStore, GroupResolver};
    /// use std::sync::Arc;
    ///
    /// let resolver: GroupResolver = Arc::new(|actor_id, group| {
    ///     group == "staff" && actor_id.starts_with("staff:")
    /// });
    ///
    /// autumn_web::app()
    ///     .with_flag_store_and_resolver(InMemoryFlagStore::new(), resolver)
    ///     .run()
    ///     .await;
    /// ```
    #[must_use]
    pub fn with_flag_store_and_resolver<S>(
        self,
        store: S,
        resolver: crate::feature_flags::GroupResolver,
    ) -> Self
    where
        S: crate::feature_flags::FlagStore,
    {
        let service = crate::feature_flags::FeatureFlagService::new(Arc::new(store) as Arc<_>)
            .with_group_resolver(resolver);
        self.state_initializer(move |state| {
            state.insert_extension(service);
        })
    }

    /// Register an experiment store, enabling the [`Experiments`] extractor.
    ///
    /// Wrap any [`ExperimentStore`] implementation. Use [`InMemoryExperimentStore`]
    /// for development and tests; use
    /// [`pg::PgExperimentStore`](crate::experiments::pg::PgExperimentStore)
    /// for production against the `autumn_experiments` tables.
    ///
    /// # Production example (Postgres-backed)
    ///
    /// ```rust,ignore
    /// use std::sync::Arc;
    /// use std::time::Duration;
    /// use autumn_web::experiments::pg::PgExperimentStore;
    ///
    /// let store = Arc::new(PgExperimentStore::new(&config.database.primary_url));
    /// PgExperimentStore::spawn_poll_listener(Arc::clone(&store), Duration::from_secs(5));
    /// autumn_web::app()
    ///     .with_experiment_store(Arc::clone(&store))
    ///     .run()
    ///     .await;
    /// ```
    ///
    /// # Development / test example
    ///
    /// ```rust,ignore
    /// use autumn_web::experiments::InMemoryExperimentStore;
    ///
    /// autumn_web::app()
    ///     .with_experiment_store(InMemoryExperimentStore::new())
    ///     .run()
    ///     .await;
    /// ```
    ///
    /// [`Experiments`]: crate::experiments::Experiments
    /// [`ExperimentStore`]: crate::experiments::ExperimentStore
    /// [`InMemoryExperimentStore`]: crate::experiments::InMemoryExperimentStore
    #[must_use]
    pub fn with_experiment_store<S>(self, store: S) -> Self
    where
        S: crate::experiments::ExperimentStore,
    {
        let service = crate::experiments::ExperimentService::new(Arc::new(store) as Arc<_>);
        self.state_initializer(move |state| {
            state.insert_extension(service);
        })
    }

    /// Register an experiment store with a custom [`ExposureSink`].
    ///
    /// Use when you want to forward exposure events to an analytics pipeline
    /// rather than the default `tracing` log.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use autumn_web::experiments::{InMemoryExperimentStore, NoOpExposureSink};
    /// use std::sync::Arc;
    ///
    /// autumn_web::app()
    ///     .with_experiment_store_and_sink(
    ///         InMemoryExperimentStore::new(),
    ///         Arc::new(NoOpExposureSink),
    ///     )
    ///     .run()
    ///     .await;
    /// ```
    ///
    /// [`ExposureSink`]: crate::experiments::ExposureSink
    #[must_use]
    pub fn with_experiment_store_and_sink<S>(
        self,
        store: S,
        sink: Arc<dyn crate::experiments::ExposureSink>,
    ) -> Self
    where
        S: crate::experiments::ExperimentStore,
    {
        let service = crate::experiments::ExperimentService::new(Arc::new(store) as Arc<_>)
            .with_exposure_sink(sink);
        self.state_initializer(move |state| {
            state.insert_extension(service);
        })
    }

    /// Register a durable [`MailDeliveryQueue`](crate::mail::MailDeliveryQueue) for
    /// [`Mailer::deliver_later`](crate::mail::Mailer::deliver_later).
    ///
    /// Must be called before [`run`](Self::run). Plugins call this inside their
    /// `apply` implementation to satisfy the production delivery guard without
    /// requiring `mail.allow_in_process_deliver_later_in_production`.
    ///
    /// Use [`Self::with_mail_delivery_queue_factory`] when the queue needs
    /// framework-managed resources (the DB pool, channels, etc.) that only
    /// exist after the [`AppState`] is constructed.
    #[cfg(feature = "mail")]
    #[must_use]
    pub fn with_mail_delivery_queue(
        mut self,
        queue: impl crate::mail::MailDeliveryQueue + 'static,
    ) -> Self {
        let arc: Arc<dyn crate::mail::MailDeliveryQueue> = Arc::new(queue);
        self.mail_delivery_queue_factory = Some(Box::new(move |_state| Ok(arc)));
        self
    }

    /// Register a factory that builds the durable
    /// [`MailDeliveryQueue`](crate::mail::MailDeliveryQueue) from the
    /// fully-built [`AppState`].
    ///
    /// Use this when the queue captures framework-managed resources — for
    /// example a DB-outbox queue that needs the connection pool returned by
    /// [`AppState::pool`]. The factory runs once, immediately before
    /// `install_mailer`, with the live `AppState`. Returning `Err` aborts
    /// startup with the propagated error.
    #[cfg(feature = "mail")]
    #[must_use]
    pub fn with_mail_delivery_queue_factory<F, Q>(mut self, factory: F) -> Self
    where
        F: FnOnce(&AppState) -> crate::AutumnResult<Q> + Send + 'static,
        Q: crate::mail::MailDeliveryQueue + 'static,
    {
        self.mail_delivery_queue_factory = Some(Box::new(move |state| {
            factory(state).map(|q| Arc::new(q) as Arc<dyn crate::mail::MailDeliveryQueue>)
        }));
        self
    }

    /// Register a [`SuppressionStore`](crate::mail::SuppressionStore) used by
    /// List-Unsubscribe sends to skip opted-out recipients and by the default
    /// unsubscribe endpoint to record opt-outs.
    ///
    /// When the `db` feature is enabled and a connection pool is configured, a
    /// Diesel-backed store is auto-wired, so most apps never call this — use it
    /// to plug a custom backend. Mirrors
    /// [`Self::with_mail_delivery_queue`].
    #[cfg(feature = "mail")]
    #[must_use]
    pub fn with_suppression_store(
        mut self,
        store: impl crate::mail::SuppressionStore + 'static,
    ) -> Self {
        self.suppression_store = Some(crate::mail::SuppressionStoreHandle::new(store));
        self
    }

    /// Register a bounce/complaint
    /// [`SuppressionStore`](crate::mail::suppression::SuppressionStore) so
    /// [`Mailer::send`](crate::mail::Mailer::send) skips addresses that have
    /// hard-bounced or complained (issue #1247).
    ///
    /// Zero-config apps need not call this: the framework wires an in-memory
    /// default store automatically. Use this to plug the durable
    /// [`PgSuppressionStore`](crate::mail::suppression::PgSuppressionStore) (or
    /// a custom backend) for multi-instance deploys that must share suppression
    /// across replicas. Mirrors [`Self::with_suppression_store`].
    #[cfg(feature = "mail")]
    #[must_use]
    pub fn with_mail_suppression_store(
        mut self,
        store: impl crate::mail::suppression::SuppressionStore + 'static,
    ) -> Self {
        self.mail_suppression_store =
            Some(crate::mail::suppression::SuppressionStoreHandle::new(store));
        self
    }

    /// Mount the framework's default RFC 8058 one-click unsubscribe endpoint at
    /// `/_autumn/unsubscribe` (`GET` confirmation page + `POST` one-click).
    ///
    /// Opt-in: a plain JSON API never gets an HTML endpoint it didn't ask for.
    /// Requires `mail.unsubscribe_base_url` to be configured. When mounted, the
    /// path is automatically exempted from CSRF and CAPTCHA (mailbox-provider
    /// POSTs carry neither token). To serve a custom unsubscribe page instead,
    /// skip this and register your own route at the path.
    #[cfg(feature = "mail")]
    #[must_use]
    pub const fn mount_unsubscribe_endpoint(mut self) -> Self {
        self.mount_unsubscribe_endpoint = true;
        self
    }

    /// Register an inbound mail router that creates webhook HTTP endpoints and
    /// dispatches parsed [`InboundEmail`](crate::inbound_mail::InboundEmail)
    /// values to registered handlers.
    ///
    /// Calling this method twice replaces the previously registered router.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use autumn_web::inbound_mail::{
    ///     InboundMailRouter, InboundMailEndpointConfig,
    ///     InboundMailHandlerInfo, ProcessingMode, RecipientPattern,
    /// };
    ///
    /// autumn_web::app()
    ///     .inbound_mail_router(
    ///         InboundMailRouter::new()
    ///             .endpoint(InboundMailEndpointConfig::mailgun("/inbound/mailgun", "key"))
    ///             .handler(InboundMailHandlerInfo {
    ///                 name: "support",
    ///                 pattern: RecipientPattern::Exact("support@company.com".to_string()),
    ///                 processing: ProcessingMode::Background,
    ///                 handler: handle_support,
    ///             })
    ///     )
    ///     .routes(routes![...])
    ///     .run()
    ///     .await;
    /// ```
    #[cfg(feature = "inbound-mail")]
    #[must_use]
    pub fn inbound_mail_router(mut self, router: crate::inbound_mail::InboundMailRouter) -> Self {
        self.inbound_mail_router = Some(Arc::new(router));
        self
    }

    /// Register mail template previews for the dev mail preview UI.
    ///
    /// Pair this with `#[mailer_preview]` and `mail_previews![...]`.
    #[cfg(feature = "mail")]
    #[must_use]
    pub fn mail_previews(
        mut self,
        previews: impl IntoIterator<Item = crate::mail::MailPreview>,
    ) -> Self {
        self.mail_previews.extend(previews);
        self
    }

    /// Register the widget story gallery served at `/_stories` (#1526).
    ///
    /// Routes mount only when the resolved config has `[stories] enabled =
    /// true` (off by default, opt-in per profile). Start from
    /// [`StoryGallery::builtin`](crate::stories::StoryGallery::builtin) for
    /// the framework widget set and
    /// [`extend`](crate::stories::StoryGallery::extend) it with your app's
    /// own `story!{...}` entries. See `docs/guide/stories.md`.
    #[cfg(feature = "maud")]
    #[must_use]
    pub fn with_story_gallery(mut self, gallery: crate::stories::StoryGallery) -> Self {
        self.story_gallery = Some(gallery);
        self
    }

    /// Register an additional audit sink for structured audit events.
    ///
    /// Multiple calls accumulate sinks. Logged events are fanned out to all
    /// configured sinks.
    #[must_use]
    pub fn with_audit_sink<S>(mut self, sink: S) -> Self
    where
        S: crate::audit::AuditSink,
    {
        let logger = self
            .audit_logger
            .take()
            .map_or_else(crate::audit::AuditLogger::new, |logger| (*logger).clone())
            .with_sink(Arc::new(sink));
        self.audit_logger = Some(Arc::new(logger));
        self
    }

    /// Register a [`Policy`](crate::authorization::Policy)
    /// implementation for resource type `R`.
    ///
    /// Multiple policies per resource are not supported: registering
    /// `R` twice causes a startup-time panic with a clear error
    /// message.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use autumn_web::authorization::{Policy, PolicyContext};
    ///
    /// #[derive(Default)]
    /// struct PostPolicy;
    /// impl Policy<Post> for PostPolicy { /* ... */ }
    ///
    /// autumn_web::app()
    ///     .routes(routes![...])
    ///     .policy::<Post, _>(PostPolicy)
    ///     .run()
    ///     .await;
    /// ```
    #[must_use]
    pub fn policy<R, P>(mut self, policy: P) -> Self
    where
        R: Send + Sync + 'static,
        P: crate::authorization::Policy<R>,
    {
        self.policy_registrations.push(Box::new(move |registry| {
            registry.register_policy::<R, _>(policy);
        }));
        self
    }

    /// Register a [`Scope`](crate::authorization::Scope) implementation
    /// for resource type `R`. The scope filters list endpoints
    /// (`GET /<api>` for `#[repository(api = "...", scope = ...)]`)
    /// to records the current user is allowed to read.
    ///
    /// Default impls return an empty list so a missing scope opt-in
    /// fails closed.
    #[must_use]
    pub fn scope<R, S>(mut self, scope: S) -> Self
    where
        R: Send + Sync + 'static,
        S: crate::authorization::Scope<R>,
    {
        self.policy_registrations.push(Box::new(move |registry| {
            registry.register_scope::<R, _>(scope);
        }));
        self
    }

    /// Apply a [`Plugin`](crate::plugin::Plugin) to the builder.
    ///
    /// The plugin's [`build`](crate::plugin::Plugin::build) runs exactly once
    /// per [`AppBuilder`]. Registering two plugins that share a
    /// [`name`](crate::plugin::Plugin::name) is a no-op after the first: the
    /// duplicate emits a `tracing::warn!` and the builder is returned
    /// unchanged.
    #[must_use]
    #[track_caller]
    pub fn plugin<P>(mut self, plugin: P) -> Self
    where
        P: crate::plugin::Plugin,
    {
        let name = plugin.name();
        if self.registered_plugins.contains(name.as_ref()) {
            tracing::warn!(
                plugin = name.as_ref(),
                "plugin already registered; skipping duplicate"
            );
            return self;
        }
        let name_str = name.into_owned();
        self.registered_plugins.insert(name_str.clone());
        // Save outer plugin context so nested plugin() calls don't permanently
        // clear it; restore it after this plugin's build() returns.
        let outer_plugin = self.current_plugin.replace(name_str);
        let mut result = plugin.build(self);
        result.current_plugin = outer_plugin;
        result
    }

    /// Apply a [`Plugins`](crate::plugin::Plugins) bundle (a plugin or tuple
    /// of plugins) to the builder, in declaration order.
    #[must_use]
    pub fn plugins<P>(self, plugins: P) -> Self
    where
        P: crate::plugin::Plugins,
    {
        plugins.apply(self)
    }

    /// Return `true` if a plugin with the given [`Plugin::name`](crate::plugin::Plugin::name)
    /// has already been applied to this builder.
    #[must_use]
    pub fn has_plugin(&self, name: &str) -> bool {
        self.registered_plugins.contains(name)
    }

    /// Declare a plugin-owned top-level config section so it coexists with
    /// `server.strict_config = true`.
    ///
    /// Core's [`AutumnConfig`](crate::config::AutumnConfig) schema is closed: any
    /// top-level `[root]` table it does not know about is an unknown key. Under
    /// `strict_config`, an unknown root is a **hard** boot error. A plugin that
    /// reads its own top-level table — for example `autumn-media-plugin` reading
    /// `[media]` via raw TOML — would therefore make a `strict_config` app fail
    /// at boot with `unknown key "media"`.
    ///
    /// Calling `config_section("media")` registers `[media]` as a **known,
    /// opaque** section: the strict unknown-key check accepts the root and does
    /// **not** validate its contents (the plugin owns that — core has no schema
    /// for it). The seam is **fail-closed**: only the roots a plugin explicitly
    /// declares are exempt; every other unknown top-level root still hard-fails,
    /// so a typo like `[medai]` is still caught.
    ///
    /// Call this from your [`Plugin::build`](crate::plugin::Plugin::build)
    /// implementation, where the plugin is applied to the builder:
    ///
    /// ```ignore
    /// impl Plugin for MediaPlugin {
    ///     fn build(self, app: AppBuilder) -> AppBuilder {
    ///         app.config_section("media") // `[media]` is now strict-config-safe
    ///         // … register routes, jobs, startup hooks, …
    ///     }
    /// }
    /// ```
    ///
    /// The declared roots are threaded into the default config loader
    /// ([`TomlEnvConfigLoader`](crate::config::TomlEnvConfigLoader)); a fully
    /// custom loader installed via
    /// [`with_config_loader`](AppBuilder::with_config_loader) owns its own
    /// strict-config handling and is unaffected.
    ///
    /// Future: an optional eager per-section validation hook (handing each
    /// plugin its raw `[root]` table at boot to validate uniformly) could be
    /// layered on top of this registry later. It is deliberately deferred — the
    /// media plugin already fail-fast-validates its own `[media]` config in its
    /// startup hook, and an eager hook adds callback-storage and error-surface
    /// plumbing this declarative seam does not need.
    #[must_use]
    pub fn config_section(mut self, root: impl Into<String>) -> Self {
        self.plugin_config_roots.insert(root.into());
        self
    }

    /// Return `true` if the given top-level config root has been declared as a
    /// plugin config section via [`config_section`](AppBuilder::config_section).
    ///
    /// Mirrors [`has_plugin`](AppBuilder::has_plugin); useful for tests and
    /// builder introspection.
    #[must_use]
    pub fn has_config_section(&self, root: &str) -> bool {
        self.plugin_config_roots.contains(root)
    }

    /// Register a named [`MetricsSource`](crate::actuator::MetricsSource) that contributes
    /// metric families to `/actuator/prometheus` and `/actuator/metrics`.
    ///
    /// The `name` is a stable identifier used for:
    /// - Duplicate-registration detection (same behaviour as duplicate plugins: a
    ///   `tracing::warn!` is emitted and the second registration is skipped).
    /// - The `source` label in the `autumn_metrics_source_errors_total` counter
    ///   that increments when a source panics during a scrape.
    ///
    /// `Plugin::build` implementations can call this to wire a source with no
    /// extra application-level glue code.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use autumn_web::actuator::{MetricsSource, MetricFamily, MetricKind, MetricSample};
    /// use autumn_web::app::AppBuilder;
    /// use std::sync::Arc;
    ///
    /// struct QueueMetrics;
    ///
    /// impl MetricsSource for QueueMetrics {
    ///     fn collect(&self) -> Vec<MetricFamily> {
    ///         vec![MetricFamily {
    ///             name: "myapp_queue_depth".to_string(),
    ///             help: "Current queue depth".to_string(),
    ///             kind: MetricKind::Gauge,
    ///             samples: vec![MetricSample { labels: vec![], value: 42.0 }],
    ///         }]
    ///     }
    /// }
    ///
    /// autumn_web::app()
    ///     .metrics_source("myapp_queue", Arc::new(QueueMetrics));
    /// ```
    #[must_use]
    pub fn metrics_source(
        mut self,
        name: impl Into<String>,
        source: Arc<dyn crate::actuator::MetricsSource>,
    ) -> Self {
        let name = name.into();
        if self.metrics_sources.iter().any(|(n, _)| n == &name) {
            tracing::warn!(
                source_name = %name,
                "MetricsSource '{}' is already registered; skipping duplicate",
                name
            );
            return self;
        }
        self.metrics_sources.push((name, source));
        self
    }

    /// Register a custom [`HealthIndicator`](crate::actuator::HealthIndicator) with the application.
    ///
    /// The indicator's [`check`](crate::actuator::HealthIndicator::check) method is called on every
    /// `/actuator/health` request (and on `/ready` for `Readiness`-group indicators).
    ///
    /// Duplicate registration names are silently ignored (a warning is logged).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use std::sync::Arc;
    /// use autumn_web::actuator::{HealthCheckOutput, HealthIndicator};
    ///
    /// struct StripeIndicator;
    /// impl HealthIndicator for StripeIndicator {
    ///     fn check(&self) -> futures::future::BoxFuture<'_, HealthCheckOutput> {
    ///         Box::pin(async move { HealthCheckOutput::up() })
    ///     }
    /// }
    ///
    /// autumn_web::app()
    ///     .health_indicator("stripe", Arc::new(StripeIndicator));
    /// ```
    #[must_use]
    pub fn health_indicator(
        mut self,
        name: impl Into<String>,
        indicator: Arc<dyn crate::actuator::HealthIndicator>,
    ) -> Self {
        let name = name.into();
        // "db" is a reserved built-in component name. Allowing a custom indicator
        // under this name would produce an inconsistent response: the custom result
        // would still gate the aggregate status while the built-in pool check owns
        // the components.db / checks.database display. The "db:shard:" prefix is
        // reserved for the framework's per-shard indicators for the same reason.
        #[cfg(feature = "db")]
        if name == "db" || name.starts_with("db:shard:") {
            tracing::warn!(
                indicator_name = %name,
                "\"db\" and \"db:shard:*\" are reserved built-in health indicator names; \
                 registration skipped. Use a different name for your custom indicator."
            );
            return self;
        }
        if self.health_indicators.iter().any(|(n, _, _)| n == &name) {
            tracing::warn!(
                indicator_name = %name,
                "HealthIndicator '{}' is already registered; skipping duplicate",
                name
            );
            return self;
        }
        let group = indicator.group();
        self.health_indicators.push((name, group, indicator));
        self
    }

    /// Register embedded Diesel migrations with the application.
    ///
    /// When migrations are registered:
    /// - They always target the primary/write database role
    ///   (`database.primary_url`, falling back to legacy `database.url`).
    /// - In **dev** mode, pending migrations run automatically on startup.
    /// - In **prod** mode, pending migrations are logged as warnings but
    ///   not applied -- use a one-shot `autumn migrate` job before rolling web
    ///   replicas.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use autumn_web::migrate::{EmbeddedMigrations, embed_migrations};
    ///
    /// const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
    ///
    /// #[autumn_web::main]
    /// async fn main() {
    ///     autumn_web::app()
    ///         .routes(routes![...])
    ///         .migrations(MIGRATIONS)
    ///         .run()
    ///         .await;
    /// }
    /// ```
    #[cfg(feature = "db")]
    #[must_use]
    pub fn migrations(mut self, migrations: migrate::EmbeddedMigrations) -> Self {
        self.migrations.push(migrations);
        self
    }

    /// Embed the app's `static/` tree into the binary for single-binary deploys.
    ///
    /// Pass the directory produced by [`embed_static!`](crate::embed_static)
    /// (requires the `embed-assets` feature). When set, `/static/*` is served
    /// from the binary and `asset_url()` resolves against the embedded
    /// fingerprint manifest — copying only the release binary into an empty
    /// directory serves every referenced asset with no `static/` sidecar.
    /// Because the manifest and the files are baked from the same build,
    /// fingerprint-vs-manifest drift is impossible.
    ///
    /// This is a release-time concern: leave it unset in development so CSS/JS
    /// hot-reload keeps serving from disk.
    ///
    /// ```rust,ignore
    /// static STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();
    ///
    /// #[autumn_web::main]
    /// async fn main() {
    ///     autumn_web::app().embedded_static(&STATIC).run().await;
    /// }
    /// ```
    #[cfg(feature = "embed-assets")]
    #[must_use]
    pub const fn embedded_static(mut self, dir: &'static include_dir::Dir<'static>) -> Self {
        self.embedded_static = Some(crate::assets::EmbeddedStaticDir(dir));
        self
    }

    /// Embed the app's i18n locale bundles into the binary.
    ///
    /// Pass the directory produced by [`embed_locales!`](crate::embed_locales)
    /// (requires the `embed-assets` and `i18n` features). When set (and no
    /// explicit [`i18n`](AppBuilder::i18n) bundle was provided), all configured
    /// locales render from the binary with no `i18n/` sidecar directory.
    ///
    /// ```rust,ignore
    /// static LOCALES: autumn_web::include_dir::Dir = autumn_web::embed_locales!();
    ///
    /// #[autumn_web::main]
    /// async fn main() {
    ///     autumn_web::app().embedded_locales(&LOCALES).run().await;
    /// }
    /// ```
    #[cfg(all(feature = "embed-assets", feature = "i18n"))]
    #[must_use]
    pub const fn embedded_locales(mut self, dir: &'static include_dir::Dir<'static>) -> Self {
        self.embedded_locales = Some(dir);
        self
    }

    /// Start the HTTP server.
    ///
    /// This method performs the full application lifecycle:
    ///
    /// 1. Loads configuration from `autumn.toml` (or defaults).
    /// 2. Initializes the tracing subscriber.
    /// 3. Validates that at least one route is registered.
    /// 4. Creates the database connection pool (if configured).
    /// 5. Builds the Axum router from collected routes.
    /// 6. Mounts built-in routes (health check, htmx JS, static files).
    /// 7. Binds to the configured address and port.
    /// 8. Serves requests with graceful shutdown on Ctrl+C (or `SIGTERM`
    ///    on Unix).
    ///
    /// # Panics
    ///
    /// Panics if no routes have been registered via [`.routes()`](Self::routes).
    /// This is intentional -- an application with no routes is always a
    /// developer error.
    #[allow(clippy::too_many_lines)]
    #[allow(clippy::cognitive_complexity)]
    pub async fn run(self) {
        // ── Build mode ─────────────────────────────────────────────────
        // When AUTUMN_BUILD_STATIC=1, render static routes to dist/ and exit
        // instead of starting the HTTP server. This is triggered by `autumn build`.
        if is_static_build_mode() {
            self.run_build_mode().await;
            return;
        }

        // ── Route dump mode ────────────────────────────────────────────
        // When AUTUMN_DUMP_ROUTES=1, print the route listing JSON and exit.
        // This is triggered by `autumn routes` to introspect the app's
        // route table without booting the server or connecting to a database.
        if is_dump_routes_mode() {
            self.run_dump_routes_mode().await;
            return;
        }

        // ── Jobs manifest dump mode ────────────────────────────────────
        // When AUTUMN_DUMP_JOBS=1, print the effective drained-queue manifest
        // (TOML `queues = [...]`) and exit. Triggered by `autumn jobs manifest`
        // so a topology-aware `autumn doctor` sees exactly what the runtime
        // drains without booting the server or connecting to a database.
        if is_dump_jobs_mode() {
            self.run_dump_jobs_mode().await;
            return;
        }

        if is_list_one_off_tasks_mode() {
            self.run_list_one_off_tasks_mode();
            return;
        }

        if let Some(task_name) = one_off_task_name_from_env() {
            self.run_one_off_task_mode(task_name).await;
            return;
        }

        // ── Migrate one-shot mode ──────────────────────────────────────
        // When AUTUMN_MIGRATE=1, apply pending embedded migrations to the
        // configured database(s) and EXIT — never start the HTTP server or bind
        // a port. Triggered by `autumn deploy`'s redeploy cutover, which runs
        // migrations BEFORE flipping traffic (issue #1607): a non-zero exit here
        // aborts the deploy with the old release still serving (AC-3). Unlike the
        // startup auto-migration path it applies regardless of profile, because
        // the deploy invokes it explicitly.
        if is_migrate_only_mode() {
            self.run_migrate_only_mode().await;
            return;
        }

        let Self {
            routes,
            api_versions,
            route_sources: _,
            current_plugin: _,
            tasks,
            one_off_tasks: _,
            mut jobs,
            listeners,
            static_metas,
            exception_filters,
            scoped_groups,
            merge_routers,
            nest_routers,
            custom_layers,
            static_gate_layers,
            startup_hooks,
            state_initializers,
            shutdown_hooks,
            extensions: _,
            registered_plugins: _,
            plugin_config_roots,
            #[cfg(feature = "maud")]
            error_page_renderer,
            #[cfg(feature = "db")]
            migrations,
            config_loader_factory,
            #[cfg(feature = "db")]
            pool_provider_factory,
            #[cfg(feature = "db")]
            shard_provider_factory,
            #[cfg(feature = "db")]
            shard_router,
            #[cfg(feature = "db")]
            directory_shard_router,
            telemetry_provider,
            session_store,
            #[cfg(feature = "ws")]
            channels_backend,
            #[cfg(feature = "storage")]
            blob_store,
            cache_backend,
            #[cfg(feature = "reporting")]
            error_reporters,
            alert_channels,
            #[cfg(feature = "openapi")]
            openapi,
            #[cfg(feature = "mcp")]
            mcp,
            audit_logger,
            #[cfg(feature = "i18n")]
            i18n_bundle,
            #[cfg(feature = "i18n")]
            i18n_auto_load,
            #[cfg(feature = "embed-assets")]
            embedded_static,
            #[cfg(all(feature = "embed-assets", feature = "i18n"))]
            embedded_locales,
            policy_registrations,
            #[cfg(feature = "mail")]
            mail_delivery_queue_factory,
            #[cfg(feature = "mail")]
            suppression_store,
            #[cfg(feature = "mail")]
            mail_suppression_store,
            #[cfg(feature = "mail")]
            mount_unsubscribe_endpoint,
            #[cfg(feature = "mail")]
            mail_previews,
            #[cfg(feature = "maud")]
            story_gallery,
            declared_routes: _,
            idempotency_enabled,
            #[cfg(feature = "mail")]
            mail_interceptor,
            job_interceptor,
            #[cfg(feature = "db")]
            db_interceptor,
            #[cfg(feature = "ws")]
            channels_interceptor,
            #[cfg(feature = "oauth2")]
            http_interceptor,
            seo_sources,
            metrics_sources,
            health_indicators,
            #[cfg(feature = "inbound-mail")]
            inbound_mail_router,
        } = self;

        let all_routes = routes;

        // 1 & 2. Load configuration and initialize logging/telemetry
        let (mut config, telemetry_guard) = load_config_and_telemetry(
            config_loader_factory,
            telemetry_provider,
            plugin_config_roots,
        )
        .await;

        // Process role selects which slice of the runtime this replica runs. A
        // split role (web/worker) requires a durable jobs backend the separate
        // HTTP and worker processes can share. Any backend that isn't a
        // recognized durable one (`postgres`/`redis`) — the in-process `local`
        // queue, a typo, or a blank value — falls through to the per-process
        // local runtime: the web replica would enqueue into an in-memory queue no
        // worker can drain, and a worker replica's queue starts empty. Reject it
        // here — before any boot work — rather than in `validate()` so the doctor
        // can still load the config. Combined role is always fine.
        let role = config.role;
        if crate::config::split_role_requires_durable_backend(role, &config.jobs.backend) {
            tracing::error!(
                role = role.as_str(),
                jobs_backend = %config.jobs.backend,
                "process role '{}' requires a durable jobs backend: backend '{}' is not \
                 a recognized durable backend and falls through to the in-process 'local' \
                 runtime, which cannot be shared across a split web/worker topology. \
                 Set jobs.backend = \"postgres\" or \"redis\", or run the combined role.",
                role.as_str(),
                config.jobs.backend,
            );
            #[cfg(feature = "managed-pg")]
            crate::managed_pg::emergency_stop_async().await;
            std::process::exit(1);
        }

        #[cfg(feature = "mail")]
        if mount_unsubscribe_endpoint {
            config.mail.mount_unsubscribe_endpoint = true;
        }

        // Apply builder-level flag: `.idempotent()` enables the middleware when
        // neither `autumn.toml` nor the environment explicitly disable it.
        // The env var `AUTUMN_IDEMPOTENCY__ENABLED` is re-checked here so
        // operators can disable idempotency at runtime (e.g. during a Redis
        // incident) without code changes, even when `.idempotent()` is called.
        if idempotency_enabled {
            let env_disabled = std::env::var("AUTUMN_IDEMPOTENCY__ENABLED")
                .is_ok_and(|v| matches!(v.to_lowercase().as_str(), "false" | "0" | "no" | "off"));
            // Only apply the builder default when neither the env var nor the
            // loaded config file explicitly sets enabled = false.
            if !env_disabled && config.idempotency.enabled != Some(false) {
                config.idempotency.enabled = Some(true);
            }
        }

        // Register the embedded `static/` tree (if any) before the router is
        // built so `/static/*` serves from the binary and `asset_url()` resolves
        // against the embedded manifest, then prefer embedded locales over disk
        // auto-loading when no explicit bundle was provided.
        #[cfg(feature = "embed-assets")]
        register_embedded_static_dir(embedded_static);

        #[cfg(all(feature = "embed-assets", feature = "i18n"))]
        let i18n_bundle = embedded_i18n_bundle(i18n_bundle, embedded_locales, &config);

        #[cfg(feature = "i18n")]
        let i18n_bundle =
            resolve_i18n_bundle(i18n_bundle, i18n_auto_load, &config, &crate::config::OsEnv);

        // 3. Validate routes
        assert!(
            !all_routes.is_empty(),
            "No routes registered. Did you forget to call .routes()?"
        );

        // 4. Log banner with profile info
        let profile_display = config.profile.as_deref().unwrap_or("none");
        tracing::info!(
            version = env!("CARGO_PKG_VERSION"),
            profile = profile_display,
            "Autumn starting"
        );

        // 4b. Startup transparency log (AUTUMN_SHOW_CONFIG=1 or log level <= DEBUG)
        let show_config = std::env::var("AUTUMN_SHOW_CONFIG").as_deref() == Ok("1");
        if show_config {
            log_startup_transparency(&all_routes, &tasks, &scoped_groups, &config);
        }

        // 4c. Fail-fast on invalid session config — but only when no custom
        // SessionStore was installed via with_session_store(...). Done before
        // setup_database so a doomed boot doesn't run migrations first.
        fail_fast_on_invalid_session_config(&config, session_store.is_some());

        // 4d. Validate signing secret — production must have a stable, private,
        // entropy-meeting secret before the server binds. Dev/test are exempt.
        fail_fast_on_invalid_signing_secret(&config);
        fail_fast_on_missing_encryption_keys(&config);
        fail_fast_on_invalid_trusted_hosts(&config);

        // 4e. Signed webhook configs must resolve to usable key material
        // before the app binds. Missing secrets should fail before a real
        // provider retry loop starts hammering a broken endpoint.
        fail_fast_on_invalid_webhook_config(&config);

        // 4f. Idempotency backend must be production-ready when enabled.
        fail_fast_on_invalid_idempotency_config(&config);

        // 4f. Provision the configured BlobStore *before* `setup_database`.
        // `LocalBlobStore::new` does real IO (creates + canonicalizes the
        // root) and the storage code may `process::exit(1)` on failure
        // (unwritable root, or `storage.backend = "s3"` with no plugin).
        // Doing it before migrations means a doomed boot can't mutate
        // the DB schema first.
        // A custom store installed via `.with_blob_store(...)` bypasses
        // config-driven instantiation entirely (no IO, no fail-fast).
        #[cfg(feature = "storage")]
        let storage_bootstrap = blob_store.map_or_else(
            || preflight_storage(&config),
            |store| {
                Some(StorageBootstrap {
                    store,
                    serving: None,
                })
            },
        );

        // 5. Create database pool and run migrations (if configured)
        #[cfg(feature = "db")]
        let database = setup_database(
            &config,
            migrations,
            pool_provider_factory,
            shard_provider_factory,
            shard_router,
            directory_shard_router,
            RepositoryCommitHookQueueMigrationMode::Runtime,
        )
        .await
        .unwrap_or_else(|e| {
            tracing::error!("{e}");
            std::process::exit(1);
        });
        #[cfg(feature = "db")]
        let pool = database.topology;
        #[cfg(feature = "db")]
        let shards = database.shards;
        #[cfg(feature = "db")]
        let replica_readiness = database.replica_readiness;
        #[cfg(feature = "db")]
        let replica_migration_check = database.replica_migration_check;

        #[cfg(feature = "db")]
        if pool.is_some() || shards.is_some() {
            // Pool sizes multiply across shards: surface the total so
            // N-shard deployments notice the aggregate connection count.
            let shard_max_connections = shards
                .as_ref()
                .map_or(0, crate::sharding::ShardSet::total_max_connections);
            let control_max_connections = pool.as_ref().map_or(0, |topology| {
                topology.primary().status().max_size
                    + topology.replica().map_or(0, |p| p.status().max_size)
            });
            let total_max_connections = control_max_connections + shard_max_connections;
            tracing::info!(
                primary_max_connections = config.database.effective_primary_pool_size(),
                replica_configured = config.database.replica_url.is_some(),
                replica_max_connections = config.database.effective_replica_pool_size(),
                shard_count = shards.as_ref().map_or(0, crate::sharding::ShardSet::len),
                total_max_connections,
                "Database topology configured"
            );
            // Pool sizes multiply across shards; warn before the aggregate
            // silently exhausts Postgres's server-side `max_connections`.
            let warn_threshold = config.database.max_connections_warn_threshold;
            if crate::config::should_warn_total_connections(total_max_connections, warn_threshold) {
                tracing::warn!(
                    total_max_connections,
                    warn_threshold,
                    "Aggregate database connection count is high: the control \
                     topology and all shard pools together may open \
                     {total_max_connections} connections (warn threshold \
                     {warn_threshold}). Ensure each Postgres server's \
                     max_connections (plus headroom for migrations and \
                     psql) exceeds the pools that target it, or lower \
                     database.pool_size. Set \
                     database.max_connections_warn_threshold = 0 to silence."
                );
            }
        } else {
            tracing::info!("Database not configured");
        }

        // 5b. Fail-fast on `#[repository(api = ...)]` endpoints that
        // were mounted without a paired `policy = ...` argument when
        // running in `prod` profile and the explicit escape hatch is
        // off. Hides exactly the footgun called out in the issue:
        // "a developer who flips the `api =` switch on a
        // `#[repository]` exposes mutate endpoints that any
        // authenticated user can call against any record."
        validate_repository_api_policies(&all_routes, &scoped_groups, &config);

        // 6. Build the router (with optional static-file layer)
        let mut state = build_state(
            &config,
            #[cfg(feature = "db")]
            pool.as_ref(),
            #[cfg(feature = "db")]
            shards,
            #[cfg(feature = "ws")]
            channels_backend,
        );

        // Wire the in-memory log capture buffer from the telemetry guard into the
        // app state so the `/actuator/logfile` endpoint can serve it.
        if let Some(buf) = telemetry_guard.log_buffer.clone() {
            state.insert_extension(buf);
        }
        // Wire the live-subscriber reload handle into the loggers actuator so
        // `PUT /actuator/loggers/{name}` affects the running subscriber, not
        // just an in-memory map (issue #1044).
        if let Some(handle) = telemetry_guard.filter_reload.clone() {
            state.log_levels().attach_reload_handle(handle);
        }

        // Instantiate MaintenanceState, load flag synchronously at startup, insert as extension, and start background poller task
        let maintenance_state = crate::maintenance::MaintenanceState::new();
        let flag_path = std::path::Path::new(crate::maintenance::MAINTENANCE_FLAG_FILE);
        if let Ok(Some(cfg)) = crate::maintenance::MaintenanceState::load_from_file(flag_path) {
            maintenance_state.enable(cfg);
        }
        state.insert_extension(maintenance_state.clone());

        let poller_state = maintenance_state.clone();
        tokio::spawn(async move {
            let path = std::path::Path::new(crate::maintenance::MAINTENANCE_FLAG_FILE);
            let interval = std::time::Duration::from_millis(500);
            loop {
                let load_res = tokio::task::spawn_blocking(move || {
                    crate::maintenance::MaintenanceState::load_from_file(path)
                })
                .await;

                match load_res {
                    Ok(Ok(Some(cfg))) => {
                        if poller_state.get() != Some(cfg.clone()) {
                            poller_state.enable(cfg);
                        }
                    }
                    Ok(Ok(None)) => {
                        if poller_state.is_active() {
                            poller_state.disable();
                        }
                    }
                    Ok(Err(e)) => {
                        tracing::error!(error = %e, "failed to load maintenance flag file");
                    }
                    Err(e) => {
                        tracing::error!(error = %e, "maintenance poller task panicked");
                    }
                }
                tokio::time::sleep(interval).await;
            }
        });

        // Resolve the canary deploy-version label (AUTUMN_DEPLOY_VERSION /
        // AUTUMN_CANARY) once at startup and publish it so the actuator metrics
        // endpoint can tag every metric family with version="stable|canary".
        let canary_state = crate::canary::CanaryState::from_env();
        if canary_state.is_canary() {
            tracing::info!(
                version = canary_state.version(),
                "canary: replica labelled as canary cohort"
            );
        }
        state.insert_extension(canary_state);

        // A rollback flag present at startup means a controller already retired
        // this replica. Flip /ready to draining immediately so a supervisor
        // restart cannot put a rolled-back replica back into the canary cohort;
        // `canary_rollback_signal` then drives the clean drain → exit.
        if crate::canary::CanaryState::rollback_flag_present(std::path::Path::new(
            crate::canary::CANARY_ROLLBACK_FLAG_FILE,
        )) {
            tracing::warn!(
                "canary: rollback flag present at startup; /ready will report draining until \
                 the flag is cleared (`autumn canary promote`)"
            );
            state.begin_shutdown();
        }

        #[cfg(feature = "mail")]
        if let Some(interceptor) = mail_interceptor {
            state.insert_extension(interceptor);
        }
        if let Some(interceptor) = job_interceptor {
            state.insert_extension(interceptor);
        }
        #[cfg(feature = "db")]
        if let Some(interceptor) = db_interceptor {
            state.insert_extension(interceptor);
        }
        #[cfg(feature = "ws")]
        if let Some(interceptor) = channels_interceptor {
            state.insert_extension(interceptor.clone());
            state.channels = crate::channels::Channels::with_shared_backend(std::sync::Arc::new(
                crate::channels::InterceptedChannelsBackend::new(
                    state.channels.backend().clone(),
                    vec![interceptor],
                ),
            ));
            #[cfg(feature = "presence")]
            {
                state.presence = crate::presence::Presence::new(state.channels.clone());
            }
        }
        #[cfg(feature = "oauth2")]
        if let Some(interceptor) = http_interceptor {
            state.insert_extension(interceptor);
        }

        // Populate the metrics source registry from builder registrations.
        // Duplicate names were already rejected in `metrics_source()`, so
        // all entries here are unique.
        for (name, source) in metrics_sources {
            if let Err(e) = state.metrics_source_registry.register(name, source) {
                tracing::warn!("{e}");
            }
        }

        // Populate the health indicator registry from builder registrations.
        for (name, group, indicator) in health_indicators {
            if let Err(e) = state
                .health_indicator_registry
                .register(name, group, indicator)
            {
                tracing::warn!("{e}");
            }
        }

        // When ACME is configured, register a `HealthOnly` indicator backed by a
        // shared status the renewal task writes. Built here (before the router)
        // so it is baked into `/actuator/health`; the same `AcmeStatus` handle is
        // reused by the renewal task spawned at bind time below.
        #[cfg(feature = "acme")]
        let acme_status: Option<crate::acme::renewal::AcmeStatus> = if let Some(acme_cfg) =
            config.server.tls.as_ref().and_then(|t| t.acme.as_ref())
        {
            let status = crate::acme::renewal::AcmeStatus::new();
            let indicator = std::sync::Arc::new(crate::acme::renewal::AcmeHealthIndicator::new(
                status.clone(),
                acme_cfg.renew_before_days,
            ));
            if let Err(e) = state.health_indicator_registry.register(
                "acme",
                crate::actuator::IndicatorGroup::HealthOnly,
                indicator,
            ) {
                tracing::warn!("{e}");
            }
            Some(status)
        } else {
            None
        };

        #[cfg(feature = "db")]
        configure_replica_migration_check(&state, replica_migration_check);
        #[cfg(feature = "db")]
        apply_replica_migration_readiness(&state, replica_readiness);
        if let Some(cache) = cache_backend {
            crate::cache::set_global_cache(cache.clone());
            state.shared_cache = Some(cache);
        } else {
            crate::cache::clear_global_cache();
        }
        state.insert_extension(RegisteredApiVersions(api_versions));

        // Capture a clone of the registered reporter chain for the ACME renewal
        // task (spawned below) so each renewal failure reaches the same
        // Sentry/etc. sinks a request-path 5xx would. Empty is fine — failures
        // still log via `tracing` inside the loop.
        #[cfg(all(feature = "acme", feature = "reporting"))]
        let acme_reporters = error_reporters.clone();

        // Install registered error reporters so the reporting layer (wired in
        // `apply_middleware`) can deliver panic + 5xx events. Empty is fine —
        // the layer falls back to the built-in `LogReporter`.
        #[cfg(feature = "reporting")]
        if !error_reporters.is_empty() {
            state.insert_extension(crate::reporting::RegisteredReporters(error_reporters));
        }
        // Apply deferred policy / scope registrations onto the live
        // app state. Done before the router is built so any panic
        // from double-registration surfaces during startup, not
        // mid-request.
        for register in policy_registrations {
            register(state.policy_registry());
        }
        // Now that registrations have been applied, verify that
        // every `#[repository(policy = X)]`-annotated route has
        // an X actually registered on the live registry. Catches
        // the "wired the macro arg, forgot the `.policy(...)`
        // builder call" footgun before any 500 lands.
        validate_repository_policies_registered(&all_routes, &scoped_groups, &state, &config);
        #[cfg(feature = "mail")]
        if let Some(handle) = suppression_store {
            state.insert_extension(handle);
        }
        #[cfg(feature = "mail")]
        if let Some(handle) = mail_suppression_store {
            state.insert_extension(handle);
        }
        #[cfg(feature = "mail")]
        crate::mail::install_mailer_with_factory(
            &state,
            &config.mail,
            mail_delivery_queue_factory,
            true,
        )
        .unwrap_or_else(|error| {
            tracing::error!(error = %error, "Failed to configure mailer");
            exit_stop_managed_pg();
            std::process::exit(1);
        });
        #[cfg(feature = "mail")]
        state.insert_extension(crate::mail::MailPreviewRegistry::new(mail_previews));
        #[cfg(feature = "maud")]
        install_story_registry(&state, story_gallery);
        // Operator alerts: build the built-in mail/webhook channels from
        // `[alerts]` config, combine with any builder-registered channels, and
        // start the background evaluation loop. No-op when nothing is
        // configured. Installed after the mailer so the mail channel can bind
        // to the live `Mailer` extension.
        crate::alerts::install_from_config(&state, &config.alerts, alert_channels);
        if let Some(logger) = audit_logger {
            state.insert_extension::<crate::audit::AuditLogger>((*logger).clone());
        }
        #[cfg(feature = "i18n")]
        let custom_layers = install_i18n_bundle_layer(custom_layers, &state, i18n_bundle);

        // Install the preflighted blob store on the freshly-built
        // AppState, and remember the serving router so it gets merged
        // into the user's router below.
        #[cfg(feature = "storage")]
        let storage_router = storage_bootstrap.and_then(|b| b.install(&state));
        install_webhook_registry(&state, &config);
        run_state_initializers(state_initializers, &state);
        finalize_event_bus(listeners, &mut jobs, &state);

        let env = crate::config::OsEnv;
        let dist_dir = project_dir("dist", &env);
        let dist_ref = if dist_dir.exists() {
            Some(dist_dir.as_path())
        } else {
            None
        };
        #[cfg_attr(
            not(any(feature = "storage", feature = "inbound-mail")),
            allow(unused_mut)
        )]
        let mut merge_routers = merge_routers;
        #[cfg(feature = "storage")]
        if let Some(router) = storage_router {
            merge_routers.push(router);
        }

        // Register SEO routes (/robots.txt and /sitemap.xml) when any SEO
        // configuration is present or dynamic sources are registered.
        if !seo_sources.is_empty() || crate::seo::has_seo_config(&config.seo) {
            let seo_cfg = &config.seo;
            let raw_profile = config.profile.as_deref().unwrap_or("dev");
            let profile = crate::seo::effective_seo_profile(raw_profile, seo_cfg.robots.allow_all);
            let static_paths: Vec<&str> = static_metas.iter().map(|m| m.path).collect();
            let (robots_body, sitemap_body) = crate::seo::assemble_seo_bodies(
                profile,
                seo_cfg.base_url.as_deref(),
                seo_cfg.robots.sitemap_url.as_deref(),
                &seo_cfg.robots.additional_rules,
                &seo_sources,
                &static_paths,
            )
            .await;
            let seo_router = crate::seo::build_seo_router_from_bodies(robots_body, sitemap_body);
            let is_seo_path = |p: &str| p == "/robots.txt" || p == "/sitemap.xml";
            let seo_collision = all_routes.iter().any(|r| is_seo_path(r.path))
                || static_metas.iter().any(|m| is_seo_path(m.path))
                || scoped_groups.iter().any(|g| {
                    let prefix = g.prefix.trim_end_matches('/');
                    g.routes
                        .iter()
                        .any(|r| is_seo_path(&format!("{prefix}{}", r.path)))
                });
            if seo_collision {
                tracing::warn!(
                    "seo: /robots.txt or /sitemap.xml is already registered by the application; \
                     skipping automatic SEO routes to prevent a startup panic"
                );
            } else {
                merge_routers.push(seo_router);
            }
        }

        #[cfg(feature = "inbound-mail")]
        if let Some(ref im_router) = inbound_mail_router {
            let mut registered_inbound: std::collections::HashSet<String> =
                std::collections::HashSet::new();
            for (path, axum_router) in crate::inbound_mail::build_routes(im_router) {
                // Preflight collision check: if an annotated POST route already
                // claims this path, merging an opaque router at the same path
                // would cause Axum to panic at startup.  Warn and skip instead
                // so the application can still start and the conflict is visible.
                if all_routes
                    .iter()
                    .any(|r| r.method == http::Method::POST && r.path == path)
                    || scoped_groups.iter().any(|g| {
                        g.routes.iter().any(|r| {
                            r.method == http::Method::POST
                                && crate::router::join_nested_path(&g.prefix, r.path)
                                    == path.as_str()
                        })
                    })
                    || nest_routers.iter().any(|(nest_path, _)| {
                        let p = nest_path.as_str();
                        path.as_str() == p
                            || path.starts_with(p)
                                && (p.ends_with('/') || path.as_bytes().get(p.len()) == Some(&b'/'))
                    })
                {
                    tracing::warn!(
                        path = %path,
                        "inbound_mail: skipping webhook route — a POST handler is \
                         already registered at this path by the application"
                    );
                    continue;
                }
                // Also guard against two inbound endpoints sharing the same path,
                // which would cause the same Axum merge panic.
                if !registered_inbound.insert(path.clone()) {
                    tracing::warn!(
                        path = %path,
                        "inbound_mail: skipping duplicate inbound webhook path"
                    );
                    continue;
                }
                // Exempt each inbound webhook path from both CSRF and CAPTCHA:
                // these routes receive provider-signed POST requests that never
                // carry a CSRF or CAPTCHA token.
                config.security.csrf.exempt_paths.push(path.clone());
                config.security.captcha_exempt_paths.push(path);
                merge_routers.push(axum_router);
            }
        }
        // Worker role does not serve user routes: build a probe-only router that
        // exposes just the framework liveness/readiness probes and the actuator,
        // so orchestrators can supervise the process and `/actuator/jobs` works.
        // Web and combined roles build the full application router. All the
        // route/router-context inputs assembled above are simply dropped in the
        // worker branch.
        let router_build = if role.serves_http() {
            crate::router::try_build_router_with_static_inner(
                all_routes,
                &config,
                state.clone(),
                dist_ref,
                crate::router::RouterContext {
                    exception_filters,
                    scoped_groups,
                    merge_routers,
                    nest_routers,
                    custom_layers,
                    static_gate_layers,
                    #[cfg(feature = "maud")]
                    error_page_renderer,
                    session_store,
                    // Respect the [openapi] profile gate: if disabled in config,
                    // suppress the endpoint even when .openapi(...) was called.
                    #[cfg(feature = "openapi")]
                    openapi: if config.openapi_runtime.enabled {
                        openapi
                    } else {
                        None
                    },
                    #[cfg(feature = "mcp")]
                    mcp,
                },
            )
        } else {
            crate::router::try_build_probe_only_router(&config, state.clone())
        };
        let router = router_build.unwrap_or_else(|error| {
            tracing::error!(error = %error, "Failed to build router");
            exit_stop_managed_pg();
            std::process::exit(1);
        });

        // 7. Bind and initialize pre-serve runtime dependencies. Once those
        // are ready, start listening before startup hooks finish so `/startup`
        // can honestly report startup progress.
        // Bind the configured transport. A `server.unix_socket` path selects a
        // Unix domain socket (local daemon mode); otherwise bind TCP on
        // `host:port` as before. `bound_desc` is the human/log description and
        // `unix_socket_cleanup` is the socket to unlink on clean exit (axum does
        // not remove it for us), as `(path, dev, inode)` so cleanup can confirm
        // the file is still the one *this* process bound before removing it.
        // Validate `[server.tls]` wiring before we bind anything, so a
        // misconfiguration is a clear pre-bind failure. Two cases fail fast:
        // (1) the section is present but this binary was built without the
        // `tls` feature — otherwise it would be silently ignored and the app
        // would serve plain HTTP on a port operators expect to be HTTPS;
        // (2) TLS is combined with a Unix socket, which the direct-HTTPS path
        // does not serve over (TLS terminates on `host:port`).
        if let Some(tls_cfg) = config.server.tls.as_ref() {
            // Reject an incoherent `[server.tls]` (both static + ACME, neither,
            // a half-set cert pair, an empty/wildcard ACME domain set, …) before
            // binding, with a named message. Pure config validation, so it runs
            // regardless of build features.
            if let Err(msg) = tls_cfg.validate() {
                tracing::error!("Invalid [server.tls] configuration: {msg}");
                #[cfg(feature = "managed-pg")]
                crate::managed_pg::emergency_stop_async().await;
                std::process::exit(1);
            }
            #[cfg(not(feature = "tls"))]
            {
                tracing::error!(
                    "[server.tls] is configured but this binary was built without the `tls` \
                     feature; rebuild with `--features tls`, or remove [server.tls] to serve \
                     plain HTTP"
                );
                #[cfg(feature = "managed-pg")]
                crate::managed_pg::emergency_stop_async().await;
                std::process::exit(1);
            }
            // `[server.tls.acme]` needs the `acme` feature; otherwise it would be
            // silently ignored and the app would serve a self-signed placeholder
            // (or fail) on a port operators expect to serve a real ACME cert.
            #[cfg(all(feature = "tls", not(feature = "acme")))]
            if tls_cfg.acme.is_some() {
                tracing::error!(
                    "[server.tls.acme] is configured but this binary was built without the \
                     `acme` feature; rebuild with `--features acme`, or configure a static \
                     cert_path/key_path instead"
                );
                #[cfg(feature = "managed-pg")]
                crate::managed_pg::emergency_stop_async().await;
                std::process::exit(1);
            }
            #[cfg(feature = "tls")]
            if config.server.unix_socket.is_some() {
                tracing::error!(
                    "[server.tls] cannot be combined with server.unix_socket; direct TLS \
                     terminates on host:port. Unset one of them"
                );
                #[cfg(feature = "managed-pg")]
                crate::managed_pg::emergency_stop_async().await;
                std::process::exit(1);
            }
        }

        // Root shutdown token for all background tasks. Created before the bind
        // block so the TLS listener's background acceptor task can take a child
        // token and stop cleanly on shutdown (issue #1603).
        let server_shutdown = tokio_util::sync::CancellationToken::new();

        // Carries the cert/key reload wiring from the TLS bind path to the
        // background reload task spawned once `server_shutdown` exists.
        #[cfg(feature = "tls")]
        let mut tls_reload_state: Option<TlsReloadState> = None;

        // Carries the ACME challenge listener + renewal task wiring from the TLS
        // bind path to the sibling tasks spawned once `server_shutdown` exists.
        #[cfg(feature = "acme")]
        let mut acme_bind_state: Option<AcmeBindState> = None;

        let (bound_listener, bound_desc, unix_socket_cleanup): (
            BoundListener,
            String,
            Option<(std::path::PathBuf, u64, u64)>,
        ) = if let Some(socket_path) = config.server.unix_socket.as_deref() {
            let _ = socket_path;
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;

                let path = std::path::Path::new(socket_path);
                if let Err(e) = prepare_unix_socket_path(path) {
                    tracing::error!(socket = %socket_path, "Failed to prepare unix socket: {e}");
                    // `setup_database` already started the managed Postgres child;
                    // `process::exit` skips `on_shutdown`, so stop it first.
                    #[cfg(feature = "managed-pg")]
                    crate::managed_pg::emergency_stop_async().await;
                    std::process::exit(1);
                }
                // Bind under an owner-only umask so the socket is created `0600`
                // from the start — a plain bind would briefly leave it
                // group/other-connectable (umask-dependent), and `chmod` afterward
                // does not revoke a connection already established in that window.
                // This matters for a user-configured `server.unix_socket` in a
                // shared dir; the CLI's own socket also sits in a `0700` parent.
                // `umask` is process-wide, so serialize the save/bind/restore: a
                // concurrent UDS bind in the same process (integration tests, or an
                // app running several servers) could otherwise interleave these
                // pairs and either bind under the wrong umask — reopening the
                // bind→chmod window this closes — or leave `0177` set permanently.
                // The guard is released before the `.await` in the error arm below.
                let bind_result = {
                    static UMASK_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
                    let _umask_guard = UMASK_LOCK
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    let prev_umask =
                        nix::sys::stat::umask(nix::sys::stat::Mode::from_bits_truncate(0o177));
                    let result = tokio::net::UnixListener::bind(path);
                    nix::sys::stat::umask(prev_umask);
                    result
                };
                let listener = match bind_result {
                    Ok(listener) => listener,
                    Err(e) => {
                        tracing::error!(socket = %socket_path, "Failed to bind unix socket: {e}");
                        #[cfg(feature = "managed-pg")]
                        crate::managed_pg::emergency_stop_async().await;
                        std::process::exit(1);
                    }
                };
                // Owner-only access, belt-and-suspenders after the umask bind.
                // Fail *closed* — if we cannot enforce `0600` (chmod error, an ACL
                // /filesystem that rejects it), refuse to serve rather than expose
                // a reachable control socket. Remove the socket we just bound so
                // nothing keeps listening on it.
                if let Err(e) =
                    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
                {
                    tracing::error!(socket = %socket_path, "Failed to enforce owner-only permissions on unix socket: {e}");
                    let _ = std::fs::remove_file(path);
                    #[cfg(feature = "managed-pg")]
                    crate::managed_pg::emergency_stop_async().await;
                    std::process::exit(1);
                }
                // Capture the bound socket's identity so a later successor that
                // rebinds the same path isn't unlinked by our shutdown.
                let (dev, ino) = {
                    use std::os::unix::fs::MetadataExt;
                    std::fs::metadata(path).map_or((0, 0), |m| (m.dev(), m.ino()))
                };
                (
                    BoundListener::Unix(listener),
                    format!("unix:{socket_path}"),
                    Some((path.to_path_buf(), dev, ino)),
                )
            }
            #[cfg(not(unix))]
            {
                tracing::error!(
                    "server.unix_socket is only supported on Unix platforms; \
                     unset it or use server.host/server.port"
                );
                std::process::exit(1);
            }
        } else {
            let addr = format!("{}:{}", config.server.host, config.server.port);
            let listener = match tokio::net::TcpListener::bind(&addr).await {
                Ok(listener) => listener,
                Err(e) => {
                    tracing::error!(addr = %addr, "Failed to bind: {e}");
                    // Stop the managed Postgres child started by `setup_database`
                    // before bailing; `process::exit` skips `on_shutdown`.
                    #[cfg(feature = "managed-pg")]
                    crate::managed_pg::emergency_stop_async().await;
                    std::process::exit(1);
                }
            };
            // When `[server.tls]` is set (and the `tls` feature is built in),
            // wrap the just-bound TCP listener in a rustls acceptor so the same
            // host:port serves HTTPS. Fail fast on any cert/key problem — the
            // pre-bind guard already rejected a Unix-socket combination and a
            // feature-less build, so reaching here with `tls = Some` means the
            // feature is on.
            #[cfg(feature = "tls")]
            {
                if let Some(tls_cfg) = config.server.tls.as_ref() {
                    // ACME mode: build the resolver from a stored cert if present,
                    // else a self-signed placeholder so `:443` binds immediately;
                    // the renewal task swaps the real cert in once issued.
                    #[cfg(feature = "acme")]
                    if let Some(acme_cfg) = tls_cfg.acme.as_ref() {
                        let https_port = config.server.port;
                        match build_acme_tls_listener(
                            listener,
                            tls_cfg,
                            acme_cfg,
                            https_port,
                            acme_status.clone(),
                            server_shutdown.child_token(),
                        )
                        .await
                        {
                            Ok((tls_listener, bind_state)) => {
                                acme_bind_state = Some(bind_state);
                                (
                                    BoundListener::Tls(tls_listener),
                                    format!("https://{addr} (ACME)"),
                                    None,
                                )
                            }
                            Err(e) => {
                                tracing::error!(error = %e, "Failed to configure [server.tls.acme]");
                                #[cfg(feature = "managed-pg")]
                                crate::managed_pg::emergency_stop_async().await;
                                std::process::exit(1);
                            }
                        }
                    } else {
                        match build_tls_listener(listener, tls_cfg, server_shutdown.child_token()) {
                            Ok((tls_listener, reload)) => {
                                tls_reload_state = Some(reload);
                                (
                                    BoundListener::Tls(tls_listener),
                                    format!("https://{addr}"),
                                    None,
                                )
                            }
                            Err(e) => {
                                tracing::error!(error = %e, "Failed to configure [server.tls]");
                                #[cfg(feature = "managed-pg")]
                                crate::managed_pg::emergency_stop_async().await;
                                std::process::exit(1);
                            }
                        }
                    }
                    #[cfg(not(feature = "acme"))]
                    match build_tls_listener(listener, tls_cfg, server_shutdown.child_token()) {
                        Ok((tls_listener, reload)) => {
                            tls_reload_state = Some(reload);
                            (
                                BoundListener::Tls(tls_listener),
                                format!("https://{addr}"),
                                None,
                            )
                        }
                        Err(e) => {
                            tracing::error!(error = %e, "Failed to configure [server.tls]");
                            #[cfg(feature = "managed-pg")]
                            crate::managed_pg::emergency_stop_async().await;
                            std::process::exit(1);
                        }
                    }
                } else {
                    (BoundListener::Tcp(listener), addr, None)
                }
            }
            #[cfg(not(feature = "tls"))]
            {
                (BoundListener::Tcp(listener), addr, None)
            }
        };

        let shutdown_timeout = config.server.shutdown_timeout_secs;
        let prestop_grace = config.server.prestop_grace_secs;

        if let Err(error) = initialize_job_runtime(
            jobs,
            &state,
            &server_shutdown,
            &config.jobs,
            role.runs_workers(),
        ) {
            tracing::error!(error = %error, "job runtime initialization failed");
            // Post-DB failure: `process::exit` skips `on_shutdown`, so stop any
            // managed Postgres before bailing.
            #[cfg(feature = "managed-pg")]
            crate::managed_pg::emergency_stop_async().await;
            std::process::exit(1);
        }

        #[cfg(feature = "db")]
        {
            #[cfg(feature = "ws")]
            crate::repository_commit_hooks::set_global_channels(state.channels().clone());
        }

        // Draining durable after-commit hook rows is background execution, so gate
        // it on the process role exactly like the `#[job]` runtime above: a `web`
        // replica must not claim/execute hook rows (that work belongs to the
        // worker tier), while `worker`/`combined` replicas keep running it.
        // The durable commit-hook worker drains rows via a Postgres queue
        // (LISTEN/NOTIFY + row-locked claiming); under the `sqlite` feature the
        // runtime pool is a SQLite pool the Postgres worker cannot drive, so
        // the worker is not spawned. (SQLite single-node boot does not run the
        // durable-hook worker tier.)
        #[cfg(all(feature = "db", not(feature = "sqlite")))]
        if role.runs_workers()
            && let Some(pool) = state.pool().cloned()
        {
            #[cfg(feature = "ws")]
            {
                let channels = state.channels().clone();
                crate::repository_commit_hooks::start_repository_commit_hook_worker(
                    pool,
                    Some(channels),
                    server_shutdown.child_token(),
                );
            }
            #[cfg(not(feature = "ws"))]
            crate::repository_commit_hooks::start_repository_commit_hook_worker(
                pool,
                server_shutdown.child_token(),
            );
        }
        // Repositories built over a shard pool (`with_pool`) enqueue durable
        // commit hooks into that shard's queue table; drain each one too — again
        // only on a role that runs workers, so a web replica leaves shard hook
        // rows for the worker tier.
        #[cfg(all(feature = "db", not(feature = "sqlite")))]
        if role.runs_workers()
            && let Some(shards) = state.shards()
        {
            for shard in shards.iter() {
                #[cfg(feature = "ws")]
                crate::repository_commit_hooks::start_repository_commit_hook_worker(
                    shard.primary_pool().clone(),
                    Some(state.channels().clone()),
                    server_shutdown.child_token(),
                );
                #[cfg(not(feature = "ws"))]
                crate::repository_commit_hooks::start_repository_commit_hook_worker(
                    shard.primary_pool().clone(),
                    server_shutdown.child_token(),
                );
            }
        }
        // SQLite durable commit-hook worker (#1996 item 5): the runtime pool is a
        // single-node SQLite pool the Postgres queue worker cannot drive, so the
        // SQLite worker (BEGIN IMMEDIATE claim + in-process Notify kick + poll
        // fallback) is spawned instead — same `role.runs_workers()` gate and same
        // `server_shutdown.child_token()` graceful-drain wiring as the Postgres tier.
        #[cfg(all(feature = "db", feature = "sqlite"))]
        if role.runs_workers()
            && let Some(pool) = state.pool().cloned()
        {
            #[cfg(feature = "ws")]
            {
                let channels = state.channels().clone();
                crate::repository_commit_hooks::start_repository_commit_hook_worker(
                    pool,
                    Some(channels),
                    server_shutdown.child_token(),
                );
            }
            #[cfg(not(feature = "ws"))]
            crate::repository_commit_hooks::start_repository_commit_hook_worker(
                pool,
                server_shutdown.child_token(),
            );
        }

        #[cfg(feature = "presence")]
        {
            let presence = state.presence().clone();
            let sweep_shutdown = server_shutdown.child_token();
            tokio::spawn(async move {
                let interval = std::time::Duration::from_secs(15);
                loop {
                    tokio::select! {
                        () = tokio::time::sleep(interval) => {
                            presence.sweep_expired();
                        }
                        () = sweep_shutdown.cancelled() => break,
                    }
                }
            });
        }

        // TLS certificate hot-reload: poll the cert/key file mtimes on an
        // interval and swap the served certificate in place on change (e.g.
        // after a `certbot`/ACME renewal), so a renewal is picked up WITHOUT a
        // restart. A child of `server_shutdown`, exactly like the presence
        // sweep above, so it stops cleanly on shutdown. A failed reload logs an
        // error and keeps serving the previously loaded certificate — a bad
        // renewal never breaks the listener.
        #[cfg(feature = "tls")]
        if let Some(reload) = tls_reload_state.take() {
            let reload_shutdown = server_shutdown.child_token();
            tokio::spawn(async move {
                run_tls_cert_reload(reload, reload_shutdown).await;
            });
        }

        // ACME (issue #1608): bind the `:80` HTTP-01 challenge + HTTP→HTTPS
        // redirect listener and spawn the renewal loop, each a child of
        // `server_shutdown` so they tear down with the main server. The renewal
        // loop runs on every replica (a pure `web` replica must renew its own
        // cert) and leader-elects through the scheduler coordinator so only one
        // replica orders per certificate.
        #[cfg(feature = "acme")]
        if let Some(bind_state) = acme_bind_state.take() {
            let AcmeBindState {
                mut renewal_task,
                tokens,
                http_challenge_port,
                https_port,
            } = bind_state;

            // The `:80` challenge/redirect listener, bound DUAL-STACK so the CA
            // can validate HTTP-01 over both IPv4 and IPv6 (an AAAA-only host is
            // otherwise unreachable on `:80`). Preferred: one `[::]` socket with
            // IPV6_V6ONLY=false; on a platform that refuses it, a separate
            // IPv4 + IPv6 listener pair (each served below). Fail-fast on a bind
            // error: `:80` needs privilege (CAP_NET_BIND_SERVICE) and ACME
            // validation cannot succeed without it.
            let challenge_listeners =
                match crate::acme::challenge::bind_challenge_listeners(http_challenge_port).await {
                    Ok(listeners) => listeners,
                    Err(e) => {
                        tracing::error!(
                            port = http_challenge_port,
                            "Failed to bind the ACME HTTP-01 challenge listener: {e}. Port \
                             {http_challenge_port} typically needs privilege (grant \
                             CAP_NET_BIND_SERVICE), or set [server.tls.acme] http_challenge_port \
                             to a port a front-end forwards :80 to"
                        );
                        #[cfg(feature = "managed-pg")]
                        crate::managed_pg::emergency_stop_async().await;
                        std::process::exit(1);
                    }
                };
            let challenge_router = crate::acme::challenge::challenge_router(tokens, https_port);
            // Serve every bound listener (one for dual-stack, two for the split
            // fallback), each a child of `server_shutdown` so they tear down with
            // the main server. The router is cheap to clone (shared Arc state).
            for challenge_listener in challenge_listeners {
                let router = challenge_router.clone();
                let challenge_shutdown = server_shutdown.child_token();
                tokio::spawn(async move {
                    if let Err(e) = axum::serve(challenge_listener, router)
                        .with_graceful_shutdown(async move {
                            challenge_shutdown.cancelled().await;
                        })
                        .await
                    {
                        tracing::error!(
                            error = %e,
                            "ACME challenge listener stopped with an error"
                        );
                    }
                });
            }

            // Build the coordinator for leader election (regardless of role) and
            // the reporter callback, then spawn the renewal loop.
            //
            // `leadership_degraded` captures the dangerous case: a DISTRIBUTED
            // backend was configured (multi-replica intent) but
            // `coordinator_from_config` could not build the distributed
            // coordinator (no DB pool / `db` feature absent in this process) and
            // we fell back to a per-process in-process one. Keyed off the
            // configured backend AND the actual fallback so it never fires for a
            // genuinely single-replica `in_process` deployment. When set, the
            // renewal loop refuses to order (see `AcmeRenewalTask`) rather than
            // letting every replica grab its own local lease and race the CA.
            let mut leadership_degraded = false;
            let coordinator =
                match crate::scheduler::coordinator_from_config(&config.scheduler, &state) {
                    Ok(c) => c,
                    Err(e) => {
                        tracing::warn!(
                            error = %e,
                            "ACME renewal: falling back to an in-process coordinator"
                        );
                        leadership_degraded = !matches!(
                            config.scheduler.backend,
                            crate::config::SchedulerBackend::InProcess
                        );
                        std::sync::Arc::new(crate::scheduler::InProcessSchedulerCoordinator::new(
                            config.scheduler.resolved_replica_id(),
                        ))
                    }
                };
            renewal_task.leadership_degraded = leadership_degraded;

            // HTTP-01 ACME is single-host in this slice: the token map is
            // per-process and the store is local disk. A distributed scheduler
            // backend means a multi-replica deployment, where the CA's :80
            // validation can hit a replica without the token (404) and
            // non-leaders cannot adopt certs from the non-shared store. Warn
            // loudly rather than silently mis-serving. See #1620.
            //
            // Keyed off the configured backend (operator intent) rather than the
            // built coordinator, so the warning still fires when
            // `coordinator_from_config` fell back to in-process after a Postgres
            // error — exactly the case where the fleet is multi-replica but this
            // process degraded. Exhaustive `matches!` is compiler-enforced if a
            // new distributed backend variant is added.
            if !matches!(
                config.scheduler.backend,
                crate::config::SchedulerBackend::InProcess
            ) {
                tracing::warn!(
                    scheduler_backend = coordinator.backend(),
                    "ACME HTTP-01 validation is not fleet-safe with the local on-disk token \
                     store: behind a load balancer the CA's :80 challenge may reach a replica \
                     without the token (404), and non-leader replicas cannot adopt issued \
                     certificates from a non-shared store. Run ACME on a single host, or use a \
                     shared token store / DNS-01 (#1620)"
                );
            }

            #[cfg(feature = "reporting")]
            let reporter = make_acme_reporter(acme_reporters);
            #[cfg(not(feature = "reporting"))]
            let reporter = make_acme_reporter();
            let renewal_shutdown = server_shutdown.child_token();
            tokio::spawn(async move {
                renewal_task
                    .run(coordinator, reporter, renewal_shutdown)
                    .await;
            });
        }

        tracing::info!(bound = %bound_desc, "Listening");

        let server_shutdown_wait = server_shutdown.clone();
        // Wrap the built router with the HTML form method-override layer at
        // the very edge — outside path and method routing — so a plain
        // browser `<form method="post">` carrying `_method=PUT|PATCH|DELETE`
        // can reach the declared PUT/PATCH/DELETE handler. `Router::layer`
        // applies middleware per registered method handler in axum 0.8,
        // which is too late: the inner `MethodRouter` returns `405` before
        // a layered service ever runs. Wrapping the whole router as a
        // tower::Service is the documented way to run middleware before
        // route matching.
        // TrustedProxiesLayer must be outermost (stamped before MethodOverrideLayer
        // reads ResolvedClientIdentity for its same-origin form check).
        let after_method = tower::Layer::layer(
            &crate::middleware::MethodOverrideLayer::new()
                .with_max_scan_bytes(config.security.upload.max_request_size_bytes),
            router,
        );
        let service = tower::Layer::layer(
            &crate::security::TrustedProxiesLayer::from_config(&config.security.trusted_proxies),
            after_method,
        );
        // Spawn the serve task per transport. The two arms differ only in the
        // connect-info type baked into the make-service (`SocketAddr` for TCP,
        // `UdsConnectInfo` for Unix sockets); the graceful-shutdown wiring and
        // the resulting `JoinHandle<io::Result<()>>` are identical. Handlers
        // extracting `ConnectInfo<SocketAddr>` are unsupported under a Unix
        // socket (acceptable: daemon mode is loopback-equivalent and local).
        let server_task = match bound_listener {
            BoundListener::Tcp(listener) => {
                let make_service =
                    axum::ServiceExt::<axum::extract::Request>::into_make_service_with_connect_info::<
                        std::net::SocketAddr,
                    >(service);
                tokio::spawn(async move {
                    axum::serve(listener, make_service)
                        .with_graceful_shutdown(async move {
                            server_shutdown_wait.cancelled().await;
                        })
                        .await
                })
            }
            #[cfg(unix)]
            BoundListener::Unix(listener) => {
                // UDS requests carry no TCP peer, so stamp a loopback identity
                // before `TrustedProxiesLayer` runs — local daemon requests then
                // resolve a `ClientAddr` (and IP-based maintenance/rate-limit
                // behavior works) exactly like a localhost TCP connection.
                let service = tower::Layer::layer(
                    &axum::middleware::from_fn(stamp_loopback_connect_info),
                    service,
                );
                let make_service =
                    axum::ServiceExt::<axum::extract::Request>::into_make_service_with_connect_info::<
                        UdsConnectInfo,
                    >(service);
                tokio::spawn(async move {
                    axum::serve(listener, make_service)
                        .with_graceful_shutdown(async move {
                            server_shutdown_wait.cancelled().await;
                        })
                        .await
                })
            }
            // HTTPS arm: mirrors the TCP arm exactly. The peer is a real TCP
            // `SocketAddr`, so the SAME `ConnectInfo<SocketAddr>` connect-info,
            // `TrustedProxiesLayer`/`ClientAddr` resolution, SSE/WebSocket(wss)
            // streaming, and graceful-shutdown wiring apply unchanged — the only
            // difference is the rustls handshake performed inside the listener's
            // `accept`. The no-op `tap_io` wrapper lets axum's blanket
            // `Connected<IncomingStream<TapIo<L, F>>> for L::Addr` supply the
            // peer `SocketAddr`, since the concrete `SocketAddr: Connected`
            // impl is provided only for `tokio::net::TcpListener`.
            #[cfg(feature = "tls")]
            BoundListener::Tls(listener) => {
                use axum::serve::ListenerExt as _;
                let listener = listener.tap_io(|_io| {});
                let make_service =
                    axum::ServiceExt::<axum::extract::Request>::into_make_service_with_connect_info::<
                        std::net::SocketAddr,
                    >(service);
                tokio::spawn(async move {
                    axum::serve(listener, make_service)
                        .with_graceful_shutdown(async move {
                            server_shutdown_wait.cancelled().await;
                        })
                        .await
                })
            }
        };

        let shutdown_state = state.clone();
        let shutdown_signal_token = server_shutdown.clone();
        #[cfg(feature = "ws")]
        let websocket_shutdown = state.shutdown.clone();
        // Clone metrics so the drain-watchdog can record aborted requests.
        let shutdown_metrics = state.metrics.clone();

        // Shared timestamp: set by shutdown_task when the listener is cancelled
        // (phase 5). Main reads it after server_task completes to measure only
        // actual drain time for hook budget — not the app's full uptime.
        let drain_started_at: std::sync::Arc<std::sync::OnceLock<std::time::Instant>> =
            std::sync::Arc::new(std::sync::OnceLock::new());
        let drain_started_clone = std::sync::Arc::clone(&drain_started_at);

        // Notified by main just before server_task.await (after startup hooks
        // complete). If SIGTERM arrives during startup hooks the watchdog waits
        // here so the drain deadline is always measured from when drain starts.
        let drain_phase_notify = std::sync::Arc::new(tokio::sync::Notify::new());
        let drain_phase_notify_for_watchdog = std::sync::Arc::clone(&drain_phase_notify);
        // Boolean companion so the watchdog can skip the wait when SIGTERM arrives
        // after startup has already finished (the common case).
        let server_entered_drain = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let server_entered_drain_for_watchdog = std::sync::Arc::clone(&server_entered_drain);

        // Shutdown task: handles the rolling-deploy lifecycle phases.
        //
        // Phases:
        //   1. SIGTERM / Ctrl-C received
        //   2. /ready → 503  (probe flips before listener closes)
        //   3. prestop_grace elapses  (load-balancer deregistration window)
        //   4. WebSocket sessions receive close frame
        //   5. TCP listener stops accepting new connections; jobs/scheduler
        //      stop dequeuing (they share server_shutdown CancellationToken)
        //   6. In-flight requests drain within shutdown_timeout_secs; if the
        //      deadline is exceeded the watchdog exits with code 1 and
        //      records autumn_shutdown_aborted_requests_total.
        //
        // Phases 7-9 (on_shutdown hooks, telemetry flush, DB pool close) run
        // in main after server_task completes — within the remaining portion
        // of the same shutdown_timeout_secs budget, not an additional window.
        let shutdown_task = tokio::spawn(async move {
            // Phase 1: Wait for OS signal.
            shutdown_signal().await;
            tracing::info!(
                phase = "signal_received",
                prestop_grace_secs = prestop_grace,
                shutdown_timeout_secs = shutdown_timeout,
                "shutdown: graceful shutdown initiated"
            );

            // Phase 2: flip /ready → 503 strictly before the listener closes.
            shutdown_state.begin_shutdown();
            tracing::info!(phase = "ready_draining", "shutdown: /ready now 503");

            // Phase 3: prestop grace — wait for load balancers to deregister.
            if prestop_grace > 0 {
                tokio::time::sleep(std::time::Duration::from_secs(prestop_grace)).await;
            }
            tracing::info!(phase = "listener_stopping", "shutdown: stopping listener");

            // Phase 4: send WebSocket close frames.
            #[cfg(feature = "ws")]
            websocket_shutdown.cancel();

            // Phase 5: stop listener and signal jobs/scheduler to stop dequeuing.
            // Record drain-start before cancelling so main gets the right hook
            // budget even in the startup-overlap case.
            let _ = drain_started_clone.set(std::time::Instant::now());
            shutdown_signal_token.cancel();

            // Phase 6: drain watchdog — if in-flight drain exceeds the budget,
            // record aborted count and force non-zero exit before hooks run.
            //
            // Always measure the deadline from when drain actually starts so that
            // in-flight requests always get the full shutdown_timeout_secs window:
            //
            //   Normal (SIGTERM after startup): server_entered_drain is already
            //   true, skip the wait, sleep the full budget.
            //
            //   Startup-overlap (SIGTERM during hooks): wait for notify, then
            //   sleep the full budget. Without this, hooks completing just before
            //   the watchdog fires would let it exit(1) immediately with no fresh
            //   drain window for requests that arrived after hooks completed.
            if !server_entered_drain_for_watchdog.load(std::sync::atomic::Ordering::Acquire) {
                tracing::warn!(
                    phase = "signal_during_startup",
                    "shutdown: SIGTERM during startup hooks; waiting for drain phase \
                     to begin before enforcing the drain deadline"
                );
                // Suspend until main fires notify_one() at drain start.
                // Orchestrator hard-kill backstop: if hooks never complete, the
                // orchestrator's kill_timeout / terminationGracePeriodSeconds kills us.
                drain_phase_notify_for_watchdog.notified().await;
            }
            tokio::time::sleep(std::time::Duration::from_secs(shutdown_timeout)).await;
            // Guard against the boundary race where server_task completes at
            // exactly the deadline before main has called shutdown_task.abort().
            // Zero active requests means drain completed cleanly; return and let
            // main complete the cleanup path.
            if shutdown_metrics.snapshot().http.requests_active == 0 {
                return;
            }
            let aborted = shutdown_metrics.snapshot().http.requests_active;
            shutdown_metrics.record_shutdown_aborted(aborted);
            tracing::error!(
                phase = "in_flight_drain",
                timeout_secs = shutdown_timeout,
                autumn_shutdown_aborted_requests_total = aborted,
                exit_code = 1,
                "shutdown: in_flight_drain phase exceeded deadline; terminating"
            );
            // The watchdog's `process::exit` skips the remaining `on_shutdown`
            // hooks — including a managed-Postgres `stop()` — so a drain that
            // overruns its budget would orphan the postmaster. Stop it here too.
            #[cfg(feature = "managed-pg")]
            crate::managed_pg::emergency_stop_async().await;
            std::process::exit(1);
        });

        if let Err(error) = run_startup_hooks(&startup_hooks, state.clone()).await {
            tracing::error!(error = %error, "startup hook failed");
            server_shutdown.cancel();
            server_task.abort();
            // `process::exit` skips `on_shutdown`; stop any managed Postgres.
            #[cfg(feature = "managed-pg")]
            crate::managed_pg::emergency_stop_async().await;
            std::process::exit(1);
        }

        if !state.probes().is_shutting_down() {
            // Web role runs no cron scheduler (workers/combined only). Skipping
            // the scheduler must not regress readiness: mark_startup_complete and
            // signal_serve_ready below still run.
            if role.runs_workers() && !tasks.is_empty() {
                let res = start_task_scheduler_with_config(
                    tasks,
                    &state,
                    &server_shutdown,
                    &config.scheduler,
                );
                if let Err(err) = res {
                    tracing::error!(error = %err, "scheduled task runtime initialization failed");
                    server_shutdown.cancel();
                    server_task.abort();
                    // `process::exit` skips `on_shutdown`; stop any managed Postgres.
                    #[cfg(feature = "managed-pg")]
                    crate::managed_pg::emergency_stop_async().await;
                    std::process::exit(1);
                }
            }
            state.probes().mark_startup_complete();
            signal_serve_ready(
                config
                    .server
                    .prestop_grace_secs
                    .saturating_add(config.server.shutdown_timeout_secs),
            );
        }

        // Signal the drain phase. The watchdog checks the flag for the common
        // case (SIGTERM arrives after startup) and waits on the notify for the
        // rare case (SIGTERM arrived during startup hooks). Both must be set so
        // the watchdog never re-enforces the deadline before drain actually starts.
        server_entered_drain.store(true, std::sync::atomic::Ordering::Release);
        drain_phase_notify.notify_one();

        // Wait for the server to drain all in-flight requests.  The drain
        // watchdog in shutdown_task will force-exit if drain takes too long.
        let server_result = server_task.await.unwrap_or_else(|e| {
            tracing::error!("Server task join error: {e}");
            // `process::exit` skips the `on_shutdown` hooks, so stop a managed
            // Postgres child here to avoid orphaning it on an accept-loop/join
            // failure (direct/foreground runs have no CLI reaper).
            exit_stop_managed_pg();
            std::process::exit(1);
        });
        // Drain completed within the deadline; abort the watchdog.
        shutdown_task.abort();
        server_result.unwrap_or_else(|e| {
            tracing::error!("Server error: {e}");
            exit_stop_managed_pg();
            std::process::exit(1);
        });

        // Phase 7: run on_shutdown hooks within the *remaining* portion of
        // shutdown_timeout_secs (drain + hooks share one budget, not two).
        // Plugin ordering: plugins register during build() before app hooks,
        // so app hooks run before plugin hooks (LIFO = last-registered first).
        let drain_elapsed = drain_started_at
            .get()
            .map_or(std::time::Duration::ZERO, std::time::Instant::elapsed);
        let hook_budget =
            std::time::Duration::from_secs(shutdown_timeout).saturating_sub(drain_elapsed);
        run_shutdown_hooks_with_timeout(&shutdown_hooks, hook_budget, hook_budget).await;
        // If request drain consumed the whole `shutdown_timeout_secs`, the
        // managed-Postgres `on_shutdown` hook may have been budgeted away above.
        // Stop the cluster directly here (idempotent — a no-op once the hook
        // already stopped it) so a direct/foreground run, which has no CLI
        // reaper, never leaves the postmaster holding the data dir/port.
        #[cfg(feature = "managed-pg")]
        crate::managed_pg::emergency_stop_async().await;

        // Remove the Unix socket file on clean exit; axum does not unlink it.
        // (An abnormal force-exit may leave it behind, but the next bind's
        // `prepare_unix_socket_path` reclaims a stale socket.) Only unlink if the
        // socket is still the one we bound — a successor that rebound the same
        // path after we closed has a different inode, and removing it would make
        // the new server unreachable.
        #[cfg(unix)]
        if let Some((path, dev, ino)) = &unix_socket_cleanup {
            use std::os::unix::fs::MetadataExt;
            let still_ours =
                std::fs::metadata(path).is_ok_and(|m| m.dev() == *dev && m.ino() == *ino);
            if still_ours {
                let _ = std::fs::remove_file(path);
            }
        }
        #[cfg(not(unix))]
        let _ = &unix_socket_cleanup;

        tracing::info!(exit_code = 0, "shutdown: all phases completed cleanly");
    }

    /// Render all registered static routes to `dist/` and exit.
    ///
    /// Triggered when `AUTUMN_BUILD_STATIC=1` is set (by `autumn build`).
    /// Builds the Axum router, renders each static route through it, and
    /// writes HTML + manifest to the `dist/` directory.
    #[allow(clippy::too_many_lines)]
    async fn run_build_mode(self) {
        let Self {
            routes,
            api_versions,
            route_sources: _,
            current_plugin: _,
            tasks: _,
            one_off_tasks: _,
            jobs: _,
            listeners,
            static_metas,
            exception_filters: _,
            scoped_groups,
            merge_routers: _,
            nest_routers: _,
            custom_layers,
            static_gate_layers: _,
            startup_hooks: _,
            state_initializers,
            shutdown_hooks: _,
            extensions: _,
            registered_plugins: _,
            plugin_config_roots,
            #[cfg(feature = "maud")]
                error_page_renderer: _,
            #[cfg(feature = "db")]
                migrations: _,
            config_loader_factory,
            #[cfg(feature = "db")]
            pool_provider_factory,
            #[cfg(feature = "db")]
            shard_provider_factory,
            #[cfg(feature = "db")]
            shard_router,
            #[cfg(feature = "db")]
            directory_shard_router,
            telemetry_provider,
            session_store,
            #[cfg(feature = "ws")]
            channels_backend,
            #[cfg(feature = "storage")]
            blob_store,
            cache_backend,
            #[cfg(feature = "reporting")]
            error_reporters,
            alert_channels: _,
            #[cfg(feature = "openapi")]
            openapi,
            #[cfg(feature = "mcp")]
                mcp: _,
            audit_logger: _,
            #[cfg(feature = "i18n")]
            i18n_bundle,
            #[cfg(feature = "i18n")]
            i18n_auto_load,
            #[cfg(feature = "embed-assets")]
            embedded_static,
            #[cfg(all(feature = "embed-assets", feature = "i18n"))]
            embedded_locales,
            policy_registrations,
            #[cfg(feature = "mail")]
            mail_delivery_queue_factory,
            #[cfg(feature = "mail")]
            suppression_store,
            #[cfg(feature = "mail")]
            mail_suppression_store,
            #[cfg(feature = "mail")]
            mount_unsubscribe_endpoint,
            #[cfg(feature = "mail")]
            mail_previews,
            #[cfg(feature = "maud")]
            story_gallery,
            declared_routes: _,
            idempotency_enabled,
            #[cfg(feature = "mail")]
            mail_interceptor,
            job_interceptor,
            #[cfg(feature = "db")]
            db_interceptor,
            #[cfg(feature = "ws")]
            channels_interceptor,
            #[cfg(feature = "oauth2")]
            http_interceptor,
            seo_sources,
            metrics_sources,
            health_indicators,
            #[cfg(feature = "inbound-mail")]
                inbound_mail_router: _,
        } = self;

        let _ = &api_versions;
        let _ = &metrics_sources;
        let _ = &health_indicators;
        let all_routes = routes;

        // Load config (same as normal startup)
        let (mut config, telemetry_guard) = load_config_and_telemetry(
            config_loader_factory,
            telemetry_provider,
            plugin_config_roots,
        )
        .await;

        #[cfg(feature = "mail")]
        if mount_unsubscribe_endpoint {
            config.mail.mount_unsubscribe_endpoint = true;
        }
        if idempotency_enabled {
            let env_disabled = std::env::var("AUTUMN_IDEMPOTENCY__ENABLED")
                .is_ok_and(|v| matches!(v.to_lowercase().as_str(), "false" | "0" | "no" | "off"));
            // Only apply the builder default when neither the env var nor the
            // loaded config file explicitly sets enabled = false.
            if !env_disabled && config.idempotency.enabled != Some(false) {
                config.idempotency.enabled = Some(true);
            }
        }

        // Register the embedded `static/` tree (if any) before the router is
        // built so `/static/*` serves from the binary and `asset_url()` resolves
        // against the embedded manifest, then prefer embedded locales over disk
        // auto-loading when no explicit bundle was provided.
        #[cfg(feature = "embed-assets")]
        register_embedded_static_dir(embedded_static);

        #[cfg(all(feature = "embed-assets", feature = "i18n"))]
        let i18n_bundle = embedded_i18n_bundle(i18n_bundle, embedded_locales, &config);

        #[cfg(feature = "i18n")]
        let i18n_bundle =
            resolve_i18n_bundle(i18n_bundle, i18n_auto_load, &config, &crate::config::OsEnv);

        // Snapshot ApiDocs before all_routes is moved into the router builder.
        // Includes top-level routes and scoped groups (with prefixed paths) so
        // the emitted dist/openapi.json matches what the runtime spec serves.
        #[cfg(feature = "openapi")]
        let api_docs_snapshot: Vec<crate::openapi::ApiDoc> = {
            let mut docs: Vec<crate::openapi::ApiDoc> = all_routes
                .iter()
                .map(|r| {
                    let mut doc = r.api_doc.clone();
                    doc.api_version = r.api_version;
                    doc.sunset_opt_out = r.sunset_opt_out;
                    doc
                })
                .collect();
            for group in &scoped_groups {
                // Mirror the same normalization as the runtime OpenAPI builder:
                // use join_nested_path for correct trailing-slash handling, and
                // merge prefix path params so they appear in the operation.
                let prefix_params = crate::router::extract_path_params(&group.prefix);
                for route in &group.routes {
                    let mut doc = route.api_doc.clone();
                    doc.api_version = route.api_version;
                    doc.sunset_opt_out = route.sunset_opt_out;
                    let full = crate::router::join_nested_path(&group.prefix, route.api_doc.path);
                    doc.path = Box::leak(full.into_boxed_str());
                    if !prefix_params.is_empty() {
                        let mut merged: Vec<&'static str> = prefix_params
                            .iter()
                            .map(|p| &*Box::leak(p.clone().into_boxed_str()))
                            .collect();
                        merged.extend_from_slice(doc.path_params);
                        doc.path_params = Box::leak(merged.into_boxed_slice());
                    }
                    docs.push(doc);
                }
            }
            docs
        };

        if static_metas.is_empty() {
            eprintln!("No static routes registered. Nothing to build.");
            eprintln!("Hint: use .static_routes(static_routes![...]) on your AppBuilder.");
            std::process::exit(1);
        }

        // Fail-fast on invalid session config — only when no custom store
        // was installed. Symmetrical to the same check in run() so static
        // builds don't run migrations against a doomed boot either.
        fail_fast_on_invalid_session_config(&config, session_store.is_some());
        fail_fast_on_invalid_signing_secret(&config);
        fail_fast_on_missing_encryption_keys(&config);
        fail_fast_on_invalid_trusted_hosts(&config);

        // Preflight the configured BlobStore the same way `run()` does.
        // Static routes can read presigned URLs out of `BlobStoreState`
        // during pre-rendering (e.g. `<img src=blob.url()>`); without
        // the bootstrap they'd 500 during `autumn build` even though
        // the server path works. A custom store from `.with_blob_store()`
        // bypasses config-driven instantiation.
        #[cfg(feature = "storage")]
        let storage_bootstrap = blob_store.map_or_else(
            || preflight_storage(&config),
            |store| {
                Some(StorageBootstrap {
                    store,
                    serving: None,
                })
            },
        );

        // Build state (with DB if configured)
        #[cfg(feature = "db")]
        let database = setup_database(
            &config,
            vec![],
            pool_provider_factory,
            shard_provider_factory,
            shard_router,
            directory_shard_router,
            RepositoryCommitHookQueueMigrationMode::StaticBuild,
        )
        .await
        .unwrap_or_else(|e| {
            eprintln!("{e}");
            std::process::exit(1);
        });
        #[cfg(feature = "db")]
        let pool = database.topology;
        #[cfg(feature = "db")]
        let shards = database.shards;
        #[cfg(feature = "db")]
        let replica_readiness = database.replica_readiness;
        #[cfg(feature = "db")]
        let replica_migration_check = database.replica_migration_check;

        let mut state = build_state(
            &config,
            #[cfg(feature = "db")]
            pool.as_ref(),
            #[cfg(feature = "db")]
            shards,
            #[cfg(feature = "ws")]
            channels_backend,
        );
        if let Some(buf) = telemetry_guard.log_buffer.clone() {
            state.insert_extension(buf);
        }
        // Wire the live-subscriber reload handle into the loggers actuator so
        // `PUT /actuator/loggers/{name}` affects the running subscriber, not
        // just an in-memory map (issue #1044).
        if let Some(handle) = telemetry_guard.filter_reload.clone() {
            state.log_levels().attach_reload_handle(handle);
        }
        state.insert_extension(RegisteredApiVersions(api_versions.clone()));
        #[cfg(feature = "mail")]
        if let Some(interceptor) = mail_interceptor {
            state.insert_extension(interceptor);
        }
        if let Some(interceptor) = job_interceptor {
            state.insert_extension(interceptor);
        }
        #[cfg(feature = "db")]
        if let Some(interceptor) = db_interceptor {
            state.insert_extension(interceptor);
        }
        #[cfg(feature = "ws")]
        if let Some(interceptor) = channels_interceptor {
            state.insert_extension(interceptor.clone());
            state.channels = crate::channels::Channels::with_shared_backend(std::sync::Arc::new(
                crate::channels::InterceptedChannelsBackend::new(
                    state.channels.backend().clone(),
                    vec![interceptor],
                ),
            ));
            #[cfg(feature = "presence")]
            {
                state.presence = crate::presence::Presence::new(state.channels.clone());
            }
        }
        #[cfg(feature = "oauth2")]
        if let Some(interceptor) = http_interceptor {
            state.insert_extension(interceptor);
        }
        #[cfg(feature = "db")]
        configure_replica_migration_check(&state, replica_migration_check);
        #[cfg(feature = "db")]
        apply_replica_migration_readiness(&state, replica_readiness);
        if let Some(cache) = cache_backend {
            crate::cache::set_global_cache(cache.clone());
            state.shared_cache = Some(cache);
        } else {
            crate::cache::clear_global_cache();
        }
        #[cfg(feature = "reporting")]
        if !error_reporters.is_empty() {
            state.insert_extension(crate::reporting::RegisteredReporters(error_reporters));
        }
        // Static-site builds are short-lived and don't run the request loop,
        // so deliver_later is never invoked. install_mailer_with_factory skips
        // the queue factory when enforce_durable_guard is false (the factory
        // may open Redis/Harvest connections unavailable here), and the guard
        // itself is bypassed too — the Mailer is still installed so static
        // routes that extract `Mailer` for immediate `send` calls resolve.
        #[cfg(feature = "mail")]
        if let Some(handle) = suppression_store {
            state.insert_extension(handle);
        }
        #[cfg(feature = "mail")]
        if let Some(handle) = mail_suppression_store {
            state.insert_extension(handle);
        }
        #[cfg(feature = "mail")]
        crate::mail::install_mailer_with_factory(
            &state,
            &config.mail,
            mail_delivery_queue_factory,
            false,
        )
        .unwrap_or_else(|error| {
            eprintln!("Failed to configure mailer: {error}");
            exit_stop_managed_pg();
            std::process::exit(1);
        });
        #[cfg(feature = "mail")]
        state.insert_extension(crate::mail::MailPreviewRegistry::new(mail_previews));
        #[cfg(feature = "maud")]
        install_story_registry(&state, story_gallery);
        // run_build_mode used ProbeState::default(), which does not start as pending
        state.probes = crate::probe::ProbeState::default();

        // Apply deferred policy / scope registrations onto the live
        // app state — same as `run()`. Static routes can carry
        // `#[authorize]` checks or live behind `#[repository(policy =
        // ..., scope = ...)]` index endpoints; without registering
        // here, every such pre-render call would 500 at build time
        // with `no policy/scope registered`, and `render_static_routes`
        // would treat that as a build failure even though
        // `.policy(...)` / `.scope(...)` was configured on the
        // builder.
        for register in policy_registrations {
            register(state.policy_registry());
        }

        #[cfg(feature = "i18n")]
        let custom_layers = install_i18n_bundle_layer(custom_layers, &state, i18n_bundle);

        // Install the preflighted storage and remember the serving
        // router so static generation hits the same `/_blobs/...`
        // routes the server path serves.
        #[cfg(feature = "storage")]
        let storage_router = storage_bootstrap.and_then(|b| b.install(&state));
        install_webhook_registry(&state, &config);
        run_state_initializers(state_initializers, &state);
        // Static generation has no job runtime, so register only sync listeners.
        // Durable listeners are dropped entirely (not just their jobs) so a
        // static route publishing such an event is a clean no-op for the durable
        // side effect rather than a "job runtime not initialized" error.
        let sync_listeners: Vec<_> = listeners
            .into_iter()
            .filter(|listener| listener.mode == crate::events::DispatchMode::Sync)
            .collect();
        finalize_event_bus(sync_listeners, &mut Vec::new(), &state);

        // Build the full router (same as production). Use the inner builder
        // so the custom session store installed via with_session_store(...)
        // is honored during static generation — apps that swap in a custom
        // store specifically to avoid Redis/external backends at build time
        // would otherwise silently fall back to the config-driven backend.
        // Custom Tower layers registered via .layer(...) are likewise
        // applied so static output matches the production response pipeline.
        #[cfg_attr(not(feature = "storage"), allow(unused_mut))]
        let mut merge_routers: Vec<axum::Router<AppState>> = Vec::new();
        #[cfg(feature = "storage")]
        if let Some(router) = storage_router {
            merge_routers.push(router);
        }
        let router = crate::router::try_build_router_inner(
            all_routes,
            &config,
            state,
            crate::router::RouterContext {
                exception_filters: Vec::new(),
                scoped_groups,
                merge_routers,
                nest_routers: Vec::new(),
                custom_layers,
                static_gate_layers: Vec::new(),
                #[cfg(feature = "maud")]
                error_page_renderer: None,
                session_store,
                #[cfg(feature = "openapi")]
                openapi: None,
                #[cfg(feature = "mcp")]
                mcp: None,
            },
        )
        .unwrap_or_else(|error| {
            eprintln!("Failed to build router: {error}");
            exit_stop_managed_pg();
            std::process::exit(1);
        });

        let env = crate::config::OsEnv;
        let dist_dir = project_dir("dist", &env);

        eprintln!("Building {} static route(s)...", static_metas.len());

        match crate::static_gen::render_static_routes(router, &static_metas, &dist_dir).await {
            Ok(()) => {
                eprintln!(
                    "\n  \u{2713} Static build complete \u{2192} {}",
                    dist_dir.display()
                );
            }
            Err(e) => {
                eprintln!("\n  \u{2717} Static build failed: {e}");
                exit_stop_managed_pg();
                std::process::exit(1);
            }
        }

        // When OpenAPI is configured, write the spec to dist/ so consumers
        // can retrieve a machine-readable API contract alongside the HTML.
        #[cfg(feature = "openapi")]
        if let Some(mut openapi_config) = openapi {
            openapi_config.api_versions = api_versions;
            let openapi_config =
                openapi_config.session_cookie_name(config.session.cookie_name.clone());
            let docs: Vec<&crate::openapi::ApiDoc> = api_docs_snapshot.iter().collect();
            let spec = crate::openapi::generate_spec(&openapi_config, &docs);
            match crate::openapi::write_openapi_spec_to_dist(&spec, &dist_dir) {
                Ok(()) => {
                    eprintln!(
                        "  \u{2713} OpenAPI spec written \u{2192} {}/openapi.json",
                        dist_dir.display()
                    );
                }
                Err(e) => {
                    eprintln!("  \u{26A0} Failed to write OpenAPI spec: {e}");
                }
            }
        }

        // Write robots.txt and sitemap.xml to dist/ — only when SEO is explicitly
        // configured or dynamic sources are registered, and never overwrite files
        // already produced by a custom #[static_get("/robots.txt")] route.
        if !seo_sources.is_empty() || crate::seo::has_seo_config(&config.seo) {
            let seo_cfg = &config.seo;
            let raw_profile = config.profile.as_deref().unwrap_or("dev");
            let profile = crate::seo::effective_seo_profile(raw_profile, seo_cfg.robots.allow_all);
            let static_paths: Vec<&str> = static_metas.iter().map(|m| m.path).collect();
            let (robots_body, sitemap_body) = crate::seo::assemble_seo_bodies(
                profile,
                seo_cfg.base_url.as_deref(),
                seo_cfg.robots.sitemap_url.as_deref(),
                &seo_cfg.robots.additional_rules,
                &seo_sources,
                &static_paths,
            )
            .await;
            // Write each file only if it wasn't already produced by a
            // custom #[static_get] route.
            let robots_path = dist_dir.join("robots.txt");
            let sitemap_path = dist_dir.join("sitemap.xml");
            if robots_path.exists() {
                eprintln!(
                    "  \u{2713} SEO: robots.txt already present (custom static route), skipping"
                );
            } else {
                match tokio::fs::write(&robots_path, robots_body).await {
                    Ok(()) => eprintln!(
                        "  \u{2713} SEO: robots.txt written \u{2192} {}",
                        robots_path.display()
                    ),
                    Err(e) => eprintln!("  \u{26A0} Failed to write robots.txt: {e}"),
                }
            }
            if sitemap_path.exists() {
                eprintln!(
                    "  \u{2713} SEO: sitemap.xml already present (custom static route), skipping"
                );
            } else {
                match tokio::fs::write(&sitemap_path, sitemap_body).await {
                    Ok(()) => eprintln!(
                        "  \u{2713} SEO: sitemap.xml written \u{2192} {}",
                        sitemap_path.display()
                    ),
                    Err(e) => eprintln!("  \u{26A0} Failed to write sitemap.xml: {e}"),
                }
            }
        }

        // Build finished: stop the managed Postgres child `setup_database` may
        // have started. Build mode discards the app's `on_shutdown` hooks, so
        // without this even a *successful* `autumn build` would leak the cluster.
        #[cfg(feature = "managed-pg")]
        crate::managed_pg::emergency_stop_async().await;
    }

    /// Dump the application's route listing as JSON and exit.
    ///
    /// Triggered when `AUTUMN_DUMP_ROUTES=1` is set (by `autumn routes`).
    /// Exits with code 0 on success, code 1 on JSON serialization failure.
    /// Does not connect to a database or bind a TCP port.
    #[allow(clippy::too_many_lines)]
    async fn run_dump_routes_mode(self) {
        let Self {
            routes,
            api_versions,
            route_sources,
            scoped_groups,
            merge_routers,
            nest_routers,
            declared_routes,
            config_loader_factory,
            telemetry_provider,
            #[cfg(feature = "openapi")]
            openapi,
            plugin_config_roots,
            ..
        } = self;

        // Validate that all versioned routes use a registered API version
        let registered_versions: std::collections::HashSet<&str> =
            api_versions.iter().map(|av| av.version.as_str()).collect();

        for route in &routes {
            if let Some(ver) = route
                .api_version
                .filter(|ver| !registered_versions.contains(*ver))
            {
                eprintln!(
                    "Failed to build router: route '{}' uses unregistered API version '{}'",
                    route.name, ver
                );
                std::process::exit(1);
            }
        }

        for group in &scoped_groups {
            for route in &group.routes {
                if let Some(ver) = route
                    .api_version
                    .filter(|ver| !registered_versions.contains(*ver))
                {
                    eprintln!(
                        "Failed to build router: route '{}' uses unregistered API version '{}'",
                        route.name, ver
                    );
                    std::process::exit(1);
                }
            }
        }

        // Raw Axum routers registered via .merge()/.nest() are opaque: there is
        // no public API to enumerate their routes, so they are omitted from the
        // listing and hard-fail `autumn routes audit` (their auth posture can't
        // be proven). The exception is a `.nest(prefix, router)` whose endpoints
        // were declared via `declare_plugin_routes` — when a declared route's
        // path falls under the nest prefix, those endpoints ARE enumerable
        // (folded into `declared_routes`) and must not be counted as omitted.
        // Every `.merge()` is rootless and always counts; a bare `.nest()` with
        // no covering declaration stays opaque and counts.
        let hidden = omitted_router_count(
            merge_routers.len(),
            nest_routers.iter().map(|(prefix, _)| prefix.as_str()),
            &declared_routes,
        );
        if hidden > 0 {
            eprintln!(
                "[autumn routes] warning: {hidden} raw router(s) added via \
                 .merge()/.nest() are not enumerable and are omitted from this listing"
            );
            // Machine-readable marker consumed by `autumn routes audit` to
            // hard-fail the coverage gate: omitted routes can't be proven.
            eprintln!(
                "{marker}{hidden}",
                marker = crate::route_listing::OMITTED_ROUTES_MARKER
            );
        }

        let (config, _telemetry_guard) = load_config_and_telemetry(
            config_loader_factory,
            telemetry_provider,
            plugin_config_roots,
        )
        .await;

        // Emit the resolved security configuration for the manifest's `declared`
        // dimensions (CSRF, security headers). Gated on `AUTUMN_DUMP_SECURITY`
        // so only `autumn routes audit` sees it — kept off stdout so the
        // routes-only JSON parse path stays byte-compatible.
        if is_dump_security_mode() {
            let security = crate::route_listing::SecurityDump::from_config(&config);
            match serde_json::to_string(&security) {
                Ok(json) => eprintln!(
                    "{marker}{json}",
                    marker = crate::route_listing::SECURITY_CONFIG_MARKER
                ),
                Err(e) => eprintln!("Failed to serialize security config: {e}"),
            }
        }

        let mut infos = match crate::route_listing::collect_route_infos(
            &routes,
            &route_sources,
            &scoped_groups,
            &api_versions,
        ) {
            Ok(infos) => infos,
            Err(e) => {
                eprintln!("Failed to build router: {e}");
                std::process::exit(1);
            }
        };
        infos.extend(declared_routes);
        crate::route_listing::append_framework_routes(&mut infos, &config);
        #[cfg(feature = "openapi")]
        if let Some(ref oa) = openapi {
            crate::route_listing::append_openapi_routes(&mut infos, oa);
        }
        crate::route_listing::append_dev_reload_routes(&mut infos);
        crate::route_listing::sort_route_infos(&mut infos);

        let json = serde_json::to_string_pretty(&infos).unwrap_or_else(|e| {
            eprintln!("Failed to serialize route listing: {e}");
            std::process::exit(1);
        });
        println!("{json}");
        std::process::exit(0);
    }

    /// Dump the effective drained-queue manifest as TOML and exit.
    ///
    /// Triggered when `AUTUMN_DUMP_JOBS=1` is set (by `autumn jobs manifest`).
    /// Emits a single top-level `queues = [...]` array — the configured
    /// `[jobs.queues]` set unioned with every `#[job(queue = "…")]`-declared
    /// queue, ordered highest priority first exactly as the runtime drains — so a
    /// topology-aware `autumn doctor` consumes the ground-truth set the app runs
    /// with. Does not connect to a database or bind a TCP port. Always exits 0.
    async fn run_dump_jobs_mode(self) {
        let Self {
            jobs,
            listeners,
            config_loader_factory,
            telemetry_provider,
            plugin_config_roots,
            ..
        } = self;

        let (config, _telemetry_guard) = load_config_and_telemetry(
            config_loader_factory,
            telemetry_provider,
            plugin_config_roots,
        )
        .await;

        // Fold in the synthesized durable-listener jobs exactly as the boot path
        // does, so the manifest reflects the same effective drained-queue set the
        // runtime drains (including the `default` queue those jobs land on).
        let manifest = dump_jobs_manifest(&config.jobs.queues, jobs, listeners);
        print!("{manifest}");
        std::process::exit(0);
    }

    /// Dump registered one-off tasks as JSON and exit.
    ///
    /// Triggered by `AUTUMN_LIST_TASKS=1` from `autumn task --list`.
    fn run_list_one_off_tasks_mode(self) {
        let Self { one_off_tasks, .. } = self;

        if let Err(error) = crate::task::validate_unique_one_off_task_names(&one_off_tasks) {
            eprintln!("Invalid task registration: {error}");
            std::process::exit(1);
        }

        let listing = crate::task::list_one_off_tasks(&one_off_tasks);
        let json = serde_json::to_string_pretty(&listing).unwrap_or_else(|error| {
            eprintln!("Failed to serialize task listing: {error}");
            std::process::exit(1);
        });
        println!("{json}");
        std::process::exit(0);
    }

    /// Apply pending embedded migrations and exit (the `AUTUMN_MIGRATE=1`
    /// one-shot), WITHOUT starting the HTTP server or binding a port.
    ///
    /// Reuses the exact applier the startup auto-migration path uses
    /// ([`run_pending_locked`](crate::migrate::run_pending_locked), the public
    /// wrapper over the same locked engine `auto_migrate` drives) and the same
    /// framework-migration fold ([`migrations_with_repository_framework_migrations`]),
    /// so the applied set matches a normal boot. Unlike that path it applies
    /// regardless of profile — the deploy invokes it explicitly — and it targets
    /// the writable primary(ies) only (control primary + each shard primary),
    /// exactly like `autumn migrate` / the deploy DB preflight; replicas are never
    /// migration targets. The framework-internal directory / shard-map guard
    /// tables are deliberately NOT applied here: the app applies them
    /// unconditionally at startup, so the candidate's own boot creates them.
    ///
    /// Exits 0 after applying (printing a redacted count — never a URL or secret)
    /// and 1 on the first failure, so a failed migration aborts the deploy before
    /// cutover with the old release still serving (AC-3).
    #[cfg(feature = "db")]
    async fn run_migrate_only_mode(self) {
        let Self {
            migrations,
            config_loader_factory,
            telemetry_provider,
            plugin_config_roots,
            ..
        } = self;

        // The telemetry guard is dropped at end of scope; a migrate-only run does
        // not need tracing wired, but loading config the same way keeps env/profile
        // resolution identical to a normal boot.
        let (config, _telemetry_guard) = load_config_and_telemetry(
            config_loader_factory,
            telemetry_provider,
            plugin_config_roots,
        )
        .await;

        // Fold in the framework migration sets a normal boot would apply, using the
        // SAME helper as `setup_database`, so the applied set is identical.
        let migrations = migrations_with_repository_framework_migrations(
            migrations,
            crate::repository_commit_hooks::has_repository_commit_hook_descriptors(),
            crate::version_history::has_versioned_repository_descriptors(),
            RepositoryCommitHookQueueMigrationMode::Runtime,
        );

        // Writable targets only: the control primary, then each shard primary.
        let control_url = config.database.effective_primary_url().map(str::to_owned);
        let shard_targets: Vec<(String, String)> = config
            .database
            .shards
            .iter()
            .map(|shard| (format!("shard:{}", shard.name), shard.primary_url.clone()))
            .collect();

        if migrations.is_empty() || (control_url.is_none() && shard_targets.is_empty()) {
            eprintln!(
                "autumn migrate: no database configured or no migrations registered — nothing to apply"
            );
            std::process::exit(0);
        }

        // SQLite migrate-only guard (issue #1614, PR3): sharding is Postgres-only,
        // so a `sqlite:` control target with shards configured, or any `sqlite:`
        // shard target, fails fast here with the actionable sharding error — the
        // SAME `sqlite_sharding_unsupported_guard` normal boot applies, so the two
        // paths cannot drift. A plain `sqlite:` control target (no shards) is NOT
        // gated: its migrations are applied by the SQLite apply path in the loop
        // below. An all-Postgres / empty-shard configuration is never gated,
        // leaving the Postgres path byte-identical.
        #[cfg(feature = "sqlite")]
        {
            let sqlite_guard_shard_urls: Vec<&str> =
                shard_targets.iter().map(|(_, url)| url.as_str()).collect();
            if let Err(e) = sqlite_sharding_unsupported_guard(
                control_url.as_deref(),
                !shard_targets.is_empty(),
                &sqlite_guard_shard_urls,
            ) {
                eprintln!("autumn migrate: {e}");
                // `process::exit` skips `on_shutdown`/`Drop`; stop any managed
                // Postgres child first, mirroring `apply_pending_or_exit`.
                #[cfg(feature = "managed-pg")]
                crate::managed_pg::emergency_stop();
                std::process::exit(1);
            }
        }

        // The diesel harness and the advisory-lock poll block, so apply off the
        // Tokio worker threads. Each target's failure exits non-zero from inside.
        let applied_total = tokio::task::spawn_blocking(move || {
            let mut total = 0_usize;
            if let Some(url) = &control_url {
                // SQLite single-writer control target (issue #1614, PR3): apply with
                // NO advisory lock via the SQLite harness. Sharding is rejected above,
                // so a SQLite control target here is always unsharded (shard_targets
                // is empty). Every non-SQLite target keeps the byte-identical locked
                // Postgres applier.
                #[cfg(feature = "sqlite")]
                let is_sqlite_control = crate::config::DatabaseBackend::detect(url)
                    == Some(crate::config::DatabaseBackend::Sqlite);
                #[cfg(not(feature = "sqlite"))]
                let is_sqlite_control = false;
                if is_sqlite_control {
                    #[cfg(feature = "sqlite")]
                    for mig in &migrations {
                        total += apply_pending_sqlite_or_exit(url, mig, "control");
                    }
                } else {
                    for mig in &migrations {
                        total += apply_pending_or_exit(url, mig, "control");
                    }
                }
            }
            // Shards hold tenant data, not the control-plane schema; skip the
            // control framework set for shard targets (mirrors `run_startup_migrations`).
            // A `sqlite:` shard is rejected by the guard above, so every shard here
            // is Postgres.
            for (label, url) in &shard_targets {
                for mig in migrations
                    .iter()
                    .filter(|mig| !migration_set_is_control_framework(mig))
                {
                    total += apply_pending_or_exit(url, mig, label);
                }
            }
            total
        })
        .await
        .unwrap_or_else(|error| {
            eprintln!("autumn migrate: migration task panicked: {error}");
            std::process::exit(1);
        });

        eprintln!(
            "autumn migrate: applied {applied_total} pending migration(s); database is up to date"
        );
        std::process::exit(0);
    }

    /// The `AUTUMN_MIGRATE=1` one-shot on a build compiled WITHOUT database
    /// support: there is nothing to migrate, so report and exit 0 (never starting
    /// the server) so a DB-free app's deploy still runs the step harmlessly.
    #[cfg(not(feature = "db"))]
    #[allow(clippy::unused_async)]
    async fn run_migrate_only_mode(self) {
        eprintln!("autumn migrate: this build has no database support — nothing to migrate");
        std::process::exit(0);
    }

    /// Run a registered one-off task with full application context and exit.
    ///
    /// Triggered by `AUTUMN_RUN_TASK=<name>` from `autumn task <name>`.
    #[allow(clippy::too_many_lines)]
    #[allow(clippy::cognitive_complexity)]
    async fn run_one_off_task_mode(self, requested_name: String) {
        let Self {
            one_off_tasks,
            mut jobs,
            listeners,
            #[cfg(feature = "i18n")]
            custom_layers,
            #[cfg(not(feature = "i18n"))]
                custom_layers: _,
            startup_hooks,
            state_initializers,
            shutdown_hooks,
            config_loader_factory,
            #[cfg(feature = "db")]
            migrations,
            #[cfg(feature = "db")]
            pool_provider_factory,
            #[cfg(feature = "db")]
            shard_provider_factory,
            #[cfg(feature = "db")]
            shard_router,
            #[cfg(feature = "db")]
            directory_shard_router,
            telemetry_provider,
            session_store,
            #[cfg(feature = "ws")]
            channels_backend,
            #[cfg(feature = "storage")]
            blob_store,
            audit_logger,
            #[cfg(feature = "i18n")]
            i18n_bundle,
            #[cfg(feature = "i18n")]
            i18n_auto_load,
            #[cfg(feature = "embed-assets")]
            embedded_static,
            #[cfg(all(feature = "embed-assets", feature = "i18n"))]
            embedded_locales,
            policy_registrations,
            cache_backend,
            #[cfg(feature = "mail")]
            mail_delivery_queue_factory,
            #[cfg(feature = "mail")]
            suppression_store,
            #[cfg(feature = "mail")]
            mail_suppression_store,
            #[cfg(feature = "mail")]
                mount_unsubscribe_endpoint: _,
            #[cfg(feature = "mail")]
            mail_interceptor,
            job_interceptor,
            #[cfg(feature = "db")]
            db_interceptor,
            #[cfg(feature = "ws")]
            channels_interceptor,
            #[cfg(feature = "oauth2")]
            http_interceptor,
            plugin_config_roots,
            ..
        } = self;

        if let Err(error) = crate::task::validate_unique_one_off_task_names(&one_off_tasks) {
            eprintln!("Invalid task registration: {error}");
            std::process::exit(1);
        }

        let Some((task_name, task_handler)) = one_off_tasks
            .iter()
            .find(|task| task.name == requested_name)
            .map(|task| (task.name.clone(), task.handler))
        else {
            eprintln!("No one-off task named '{requested_name}' is registered.");
            print_available_one_off_tasks(&one_off_tasks);
            std::process::exit(1);
        };

        let args = one_off_task_args_from_env().unwrap_or_else(|error| {
            eprintln!("Invalid task args: {error}");
            std::process::exit(1);
        });

        let (config, telemetry_guard) = load_config_and_telemetry(
            config_loader_factory,
            telemetry_provider,
            plugin_config_roots,
        )
        .await;

        // Register the embedded `static/` tree (if any) before the router is
        // built so `/static/*` serves from the binary and `asset_url()` resolves
        // against the embedded manifest, then prefer embedded locales over disk
        // auto-loading when no explicit bundle was provided.
        #[cfg(feature = "embed-assets")]
        register_embedded_static_dir(embedded_static);

        #[cfg(all(feature = "embed-assets", feature = "i18n"))]
        let i18n_bundle = embedded_i18n_bundle(i18n_bundle, embedded_locales, &config);

        #[cfg(feature = "i18n")]
        let i18n_bundle =
            resolve_i18n_bundle(i18n_bundle, i18n_auto_load, &config, &crate::config::OsEnv);

        fail_fast_on_invalid_session_config(&config, session_store.is_some());
        fail_fast_on_invalid_signing_secret(&config);
        fail_fast_on_missing_encryption_keys(&config);
        fail_fast_on_invalid_trusted_hosts(&config);

        #[cfg(feature = "storage")]
        let storage_bootstrap = blob_store.map_or_else(
            || preflight_storage(&config),
            |store| {
                Some(StorageBootstrap {
                    store,
                    serving: None,
                })
            },
        );

        #[cfg(feature = "db")]
        let database = setup_database(
            &config,
            migrations,
            pool_provider_factory,
            shard_provider_factory,
            shard_router,
            directory_shard_router,
            RepositoryCommitHookQueueMigrationMode::Runtime,
        )
        .await
        .unwrap_or_else(|error| {
            eprintln!("{error}");
            std::process::exit(1);
        });
        #[cfg(feature = "db")]
        let pool = database.topology;
        #[cfg(feature = "db")]
        let shards = database.shards;
        #[cfg(feature = "db")]
        let replica_readiness = database.replica_readiness;
        #[cfg(feature = "db")]
        let replica_migration_check = database.replica_migration_check;

        let mut state = build_state(
            &config,
            #[cfg(feature = "db")]
            pool.as_ref(),
            #[cfg(feature = "db")]
            shards,
            #[cfg(feature = "ws")]
            channels_backend,
        );
        if let Some(buf) = telemetry_guard.log_buffer.clone() {
            state.insert_extension(buf);
        }
        // Wire the live-subscriber reload handle into the loggers actuator so
        // `PUT /actuator/loggers/{name}` affects the running subscriber, not
        // just an in-memory map (issue #1044).
        if let Some(handle) = telemetry_guard.filter_reload.clone() {
            state.log_levels().attach_reload_handle(handle);
        }
        #[cfg(feature = "mail")]
        if let Some(interceptor) = mail_interceptor {
            state.insert_extension(interceptor);
        }
        if let Some(interceptor) = job_interceptor {
            state.insert_extension(interceptor);
        }
        #[cfg(feature = "db")]
        if let Some(interceptor) = db_interceptor {
            state.insert_extension(interceptor);
        }
        #[cfg(feature = "ws")]
        if let Some(interceptor) = channels_interceptor {
            state.insert_extension(interceptor.clone());
            state.channels = crate::channels::Channels::with_shared_backend(std::sync::Arc::new(
                crate::channels::InterceptedChannelsBackend::new(
                    state.channels.backend().clone(),
                    vec![interceptor],
                ),
            ));
            #[cfg(feature = "presence")]
            {
                state.presence = crate::presence::Presence::new(state.channels.clone());
            }
        }
        #[cfg(feature = "oauth2")]
        if let Some(interceptor) = http_interceptor {
            state.insert_extension(interceptor);
        }
        #[cfg(feature = "db")]
        configure_replica_migration_check(&state, replica_migration_check);
        #[cfg(feature = "db")]
        apply_replica_migration_readiness(&state, replica_readiness);
        if let Some(cache) = cache_backend {
            crate::cache::set_global_cache(cache.clone());
            state.shared_cache = Some(cache);
        } else {
            crate::cache::clear_global_cache();
        }

        for register in policy_registrations {
            register(state.policy_registry());
        }

        #[cfg(feature = "mail")]
        if let Some(handle) = suppression_store {
            state.insert_extension(handle);
        }
        #[cfg(feature = "mail")]
        if let Some(handle) = mail_suppression_store {
            state.insert_extension(handle);
        }
        #[cfg(feature = "mail")]
        crate::mail::install_mailer_with_factory(
            &state,
            &config.mail,
            mail_delivery_queue_factory,
            true,
        )
        .unwrap_or_else(|error| {
            eprintln!("Failed to configure mailer: {error}");
            exit_stop_managed_pg();
            std::process::exit(1);
        });

        if let Some(logger) = audit_logger {
            state.insert_extension::<crate::audit::AuditLogger>((*logger).clone());
        }

        #[cfg(feature = "i18n")]
        let _custom_layers = install_i18n_bundle_layer(custom_layers, &state, i18n_bundle);

        #[cfg(feature = "storage")]
        let _storage_router = storage_bootstrap.and_then(|bootstrap| bootstrap.install(&state));
        run_state_initializers(state_initializers, &state);
        finalize_event_bus(listeners, &mut jobs, &state);

        let task_shutdown = tokio_util::sync::CancellationToken::new();
        if let Err(error) = initialize_job_runtime(jobs, &state, &task_shutdown, &config.jobs, true)
        {
            eprintln!("job runtime initialization failed: {error}");
            #[cfg(feature = "managed-pg")]
            crate::managed_pg::emergency_stop_async().await;
            std::process::exit(1);
        }

        #[cfg(feature = "db")]
        {
            #[cfg(feature = "ws")]
            crate::repository_commit_hooks::set_global_channels(state.channels().clone());
        }

        // Postgres-only durable commit-hook worker; not spawned under sqlite
        // (the runtime pool is a SQLite pool the Postgres worker cannot drive).
        #[cfg(all(feature = "db", not(feature = "sqlite")))]
        if let Some(pool) = state.pool().cloned() {
            #[cfg(feature = "ws")]
            {
                let channels = state.channels().clone();
                crate::repository_commit_hooks::start_repository_commit_hook_worker(
                    pool,
                    Some(channels),
                    task_shutdown.child_token(),
                );
            }
            #[cfg(not(feature = "ws"))]
            crate::repository_commit_hooks::start_repository_commit_hook_worker(
                pool,
                task_shutdown.child_token(),
            );
        }
        // Repositories built over a shard pool (`with_pool`) enqueue durable
        // commit hooks into that shard's queue table; drain each one too.
        #[cfg(all(feature = "db", not(feature = "sqlite")))]
        if let Some(shards) = state.shards() {
            for shard in shards.iter() {
                #[cfg(feature = "ws")]
                crate::repository_commit_hooks::start_repository_commit_hook_worker(
                    shard.primary_pool().clone(),
                    Some(state.channels().clone()),
                    task_shutdown.child_token(),
                );
                #[cfg(not(feature = "ws"))]
                crate::repository_commit_hooks::start_repository_commit_hook_worker(
                    shard.primary_pool().clone(),
                    task_shutdown.child_token(),
                );
            }
        }
        // SQLite durable commit-hook worker on the one-off task-runner path
        // (#1996 item 5); see the server-path spawn above for the rationale.
        #[cfg(all(feature = "db", feature = "sqlite"))]
        if let Some(pool) = state.pool().cloned() {
            #[cfg(feature = "ws")]
            {
                let channels = state.channels().clone();
                crate::repository_commit_hooks::start_repository_commit_hook_worker(
                    pool,
                    Some(channels),
                    task_shutdown.child_token(),
                );
            }
            #[cfg(not(feature = "ws"))]
            crate::repository_commit_hooks::start_repository_commit_hook_worker(
                pool,
                task_shutdown.child_token(),
            );
        }

        if let Err(error) = run_startup_hooks(&startup_hooks, state.clone()).await {
            eprintln!("startup hook failed: {error}");
            task_shutdown.cancel();
            #[cfg(feature = "managed-pg")]
            crate::managed_pg::emergency_stop_async().await;
            std::process::exit(1);
        }
        state.probes().mark_startup_complete();

        tracing::info!(task = %task_name, "Running one-off task");
        let span = tracing::info_span!("one_off_task", task = %task_name);
        #[cfg(feature = "oauth2")]
        let result = {
            use crate::interceptor::{ACTIVE_HTTP_INTERCEPTORS, HttpInterceptor};
            let interceptors: Vec<std::sync::Arc<dyn HttpInterceptor>> = state
                .extension::<std::sync::Arc<dyn HttpInterceptor>>()
                .map(|interceptor_arc| vec![(*interceptor_arc).clone()])
                .unwrap_or_default();
            ACTIVE_HTTP_INTERCEPTORS
                .scope(
                    interceptors,
                    (task_handler)(state.clone(), args).instrument(span),
                )
                .await
        };
        #[cfg(not(feature = "oauth2"))]
        let result = (task_handler)(state.clone(), args).instrument(span).await;

        task_shutdown.cancel();
        run_shutdown_hooks(&shutdown_hooks).await;
        // If the generated `pg.stop()` hook errored/timed out it keeps the
        // handle for a retry, but a one-off task then exits — so retry the stop
        // here (idempotent; a no-op once the hook stopped it cleanly) to avoid
        // orphaning the postmaster on the data dir/port.
        #[cfg(feature = "managed-pg")]
        crate::managed_pg::emergency_stop_async().await;

        match result {
            Ok(()) => {
                tracing::info!(task = %task_name, "One-off task completed");
            }
            Err(error) => {
                tracing::error!(task = %task_name, error = %error, "One-off task failed");
                eprintln!("Task '{task_name}' failed: {error}");
                for cause in error.source_chain() {
                    eprintln!("Caused by: {cause}");
                }
                std::process::exit(1);
            }
        }
    }
}

pub(crate) fn is_static_build_mode() -> bool {
    std::env::var("AUTUMN_BUILD_STATIC").as_deref() == Ok("1")
}

/// Stop a managed Postgres child from a synchronous `process::exit` path in a
/// non-server entrypoint (static build, one-off task). Those modes don't run
/// `on_shutdown` before their failure exits, and `process::exit` skips `Drop`,
/// so a managed cluster started by `setup_database` would otherwise be orphaned
/// on the data dir/port.
///
/// These call sites run on a Tokio worker thread; the (blocking, own-runtime)
/// `emergency_stop` would panic if entered there, so run it on a fresh thread
/// with no ambient runtime. No-op unless the `managed-pg` feature is active.
// The body is empty without `managed-pg` (so it can't be `const` with it).
#[allow(clippy::missing_const_for_fn)]
fn exit_stop_managed_pg() {
    #[cfg(feature = "managed-pg")]
    {
        let _ = std::thread::spawn(crate::managed_pg::emergency_stop).join();
    }
}

pub(crate) fn is_dump_routes_mode() -> bool {
    std::env::var("AUTUMN_DUMP_ROUTES").as_deref() == Ok("1")
}

/// Whether the dump should also emit the resolved security configuration
/// ([`SECURITY_CONFIG_MARKER`](crate::route_listing::SECURITY_CONFIG_MARKER)).
///
/// Set by `autumn routes audit` (which needs the CSRF / headers config to build
/// the `declared` manifest dimensions) but not by the plain `autumn routes`
/// listing, so that command's stderr stays free of the marker line.
pub(crate) fn is_dump_security_mode() -> bool {
    std::env::var("AUTUMN_DUMP_SECURITY").as_deref() == Ok("1")
}

pub(crate) fn is_dump_jobs_mode() -> bool {
    std::env::var("AUTUMN_DUMP_JOBS").as_deref() == Ok("1")
}

pub(crate) fn is_list_one_off_tasks_mode() -> bool {
    std::env::var("AUTUMN_LIST_TASKS").as_deref() == Ok("1")
}

/// Whether `AUTUMN_MIGRATE=1` requests the migrate-only one-shot: apply pending
/// embedded migrations and exit without starting the HTTP server. Set by
/// `autumn deploy`'s redeploy cutover (issue #1607) so migrations land before
/// traffic is flipped to the new release.
pub(crate) fn is_migrate_only_mode() -> bool {
    std::env::var("AUTUMN_MIGRATE").as_deref() == Ok("1")
}

fn one_off_task_name_from_env() -> Option<String> {
    std::env::var("AUTUMN_RUN_TASK")
        .ok()
        .map(|value| value.trim().to_owned())
        .filter(|value| !value.is_empty())
}

fn one_off_task_args_from_env() -> Result<Vec<String>, String> {
    match std::env::var("AUTUMN_TASK_ARGS_JSON") {
        Ok(raw) if !raw.trim().is_empty() => serde_json::from_str(&raw)
            .map_err(|error| format!("AUTUMN_TASK_ARGS_JSON must be a JSON string array: {error}")),
        _ => Ok(Vec::new()),
    }
}

fn print_available_one_off_tasks(tasks: &[crate::task::OneOffTaskInfo]) {
    let listing = crate::task::list_one_off_tasks(tasks);
    if listing.is_empty() {
        eprintln!("No one-off tasks are registered. Add .one_off_tasks(one_off_tasks![...]).");
        return;
    }

    eprintln!("Available tasks:");
    for task in listing {
        if task.description.is_empty() {
            eprintln!("  {}", task.name);
        } else {
            eprintln!("  {:<24} {}", task.name, task.description);
        }
    }
}

/// Start scheduled tasks in background Tokio tasks.
///
/// Each task runs in its own spawned task with error logging.
/// Uses `tokio::time` for fixed-delay scheduling and `croner` for cron-based
/// scheduling. The `shutdown` token is used to stop cron loops gracefully when
/// the server receives a termination signal.
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cognitive_complexity)]
#[allow(dead_code)]
fn start_task_scheduler(
    tasks: Vec<crate::task::TaskInfo>,
    state: &AppState,
    shutdown: &tokio_util::sync::CancellationToken,
) {
    if let Err(error) = start_task_scheduler_with_config(
        tasks,
        state,
        shutdown,
        &crate::config::SchedulerConfig::default(),
    ) {
        tracing::error!(error = %error, "scheduled task runtime initialization failed");
    }
}

#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cognitive_complexity)]
fn start_task_scheduler_with_config(
    tasks: Vec<crate::task::TaskInfo>,
    state: &AppState,
    shutdown: &tokio_util::sync::CancellationToken,
    scheduler_config: &crate::config::SchedulerConfig,
) -> crate::AutumnResult<()> {
    tracing::info!(count = tasks.len(), "Starting scheduled tasks");
    let coordinator = crate::scheduler::coordinator_from_config(scheduler_config, state)?;
    let lease_ttl = std::time::Duration::from_secs(scheduler_config.lease_ttl_secs);
    for task_info in &tasks {
        let schedule_desc = task_info.schedule.to_string();
        tracing::info!(
            name = %task_info.name,
            schedule = %schedule_desc,
            coordination = %task_info.coordination,
            scheduler_backend = coordinator.backend(),
            replica_id = coordinator.replica_id(),
            lease_ttl_secs = scheduler_config.lease_ttl_secs,
            "Registered task"
        );
    }

    let mut cron_tasks: Vec<CronTaskSpec> = Vec::new();

    for task_info in tasks {
        let state = state.clone();
        let name = task_info.name.clone();
        let handler = task_info.handler;
        let coordination = task_info.coordination;
        let schedule_desc = task_info.schedule.to_string();
        state.task_registry.register_scheduled(
            &name,
            &schedule_desc,
            coordination,
            coordinator.backend(),
            coordinator.replica_id(),
        );

        match task_info.schedule {
            crate::task::Schedule::FixedDelay(delay) => {
                let coordinator = Arc::clone(&coordinator);
                let shutdown = shutdown.child_token();
                tokio::spawn(async move {
                    loop {
                        state
                            .task_registry
                            .record_next_run_at(&name, &format_next_task_run_after(delay));
                        tokio::select! {
                            () = shutdown.cancelled() => break,
                            () = tokio::time::sleep(delay) => {
                                execute_fixed_delay_task(
                                    name.clone(),
                                    state.clone(),
                                    handler,
                                    delay,
                                    coordination,
                                    Arc::clone(&coordinator),
                                    lease_ttl,
                                )
                                .await;
                            }
                        }
                    }
                });
            }
            crate::task::Schedule::Cron {
                expression,
                timezone,
            } => {
                cron_tasks.push(CronTaskSpec {
                    name,
                    expression,
                    timezone,
                    coordination,
                    handler,
                });
            }
        }
    }

    run_cron_scheduler(cron_tasks, state, shutdown, &coordinator, lease_ttl);

    Ok(())
}

#[allow(unused_variables, clippy::needless_pass_by_value)]
fn send_ws_sys_task_msg(
    state: &AppState,
    event: &str,
    name: &str,
    extra: Vec<(&str, serde_json::Value)>,
) {
    #[cfg(feature = "ws")]
    {
        // âš¡ Bolt Optimization:
        // Use serde_json::json! to avoid multiple String allocations (`.to_string()`)
        // and repetitive `Map::insert` calls for `sys:tasks` websocket messages.
        let mut msg = serde_json::json!({
            "event": event,
            "task": name,
            "timestamp": chrono::Utc::now().to_rfc3339(),
        });
        if let Some(map) = msg.as_object_mut() {
            for (k, v) in extra {
                map.insert(k.to_string(), v);
            }
        }
        let _ = state.channels().sender("sys:tasks").send(msg.to_string());
    }
}

async fn execute_task_result(
    state: &AppState,
    handler: crate::task::TaskHandler,
    start: std::time::Instant,
    name: &str,
    schedule: &'static str,
) -> Result<u64, (u64, String)> {
    // A fresh span per run so OTLP-enabled deployments see each invocation
    // as its own trace rather than inheriting whatever was current on the
    // scheduler thread.
    let task_span = tracing::info_span!(
        parent: None,
        "scheduled_task",
        otel.kind = "internal",
        task = %name,
        schedule = schedule,
    );
    let future = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        (handler)(state.clone()).instrument(task_span)
    })) {
        Ok(future) => future,
        Err(panic) => {
            let duration_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
            return Err((duration_ms, format_scheduled_task_panic(panic.as_ref())));
        }
    };
    let result = std::panic::AssertUnwindSafe(future).catch_unwind().await;
    let duration_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);

    match result {
        Ok(Ok(())) => Ok(duration_ms),
        Ok(Err(e)) => Err((duration_ms, e.to_string())),
        Err(panic) => Err((duration_ms, format_scheduled_task_panic(panic.as_ref()))),
    }
}

fn format_scheduled_task_panic(panic: &(dyn Any + Send)) -> String {
    let detail = panic
        .downcast_ref::<String>()
        .map(String::as_str)
        .or_else(|| panic.downcast_ref::<&'static str>().copied())
        .unwrap_or("non-string panic payload");
    format!("scheduled task handler panicked: {detail}")
}

async fn execute_task_result_with_optional_lease_ttl(
    state: &AppState,
    handler: crate::task::TaskHandler,
    start: std::time::Instant,
    name: &str,
    schedule: &'static str,
    lease_ttl: Option<std::time::Duration>,
) -> Result<u64, (u64, String)> {
    let Some(lease_ttl) = lease_ttl else {
        return execute_task_result(state, handler, start, name, schedule).await;
    };

    tokio::time::timeout(
        lease_ttl,
        execute_task_result(state, handler, start, name, schedule),
    )
    .await
    .unwrap_or_else(|_| {
        let duration_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
        Err((
            duration_ms,
            format!(
                "scheduled task exceeded lease TTL of {}s",
                lease_ttl.as_secs()
            ),
        ))
    })
}

/// Handle the execution of a single fixed-delay task.
#[allow(clippy::cognitive_complexity)]
async fn execute_fixed_delay_task(
    name: String,
    state: AppState,
    handler: crate::task::TaskHandler,
    delay: std::time::Duration,
    coordination: crate::task::TaskCoordination,
    coordinator: Arc<dyn crate::scheduler::SchedulerCoordinator>,
    lease_ttl: std::time::Duration,
) {
    let tick_key = crate::scheduler::fixed_delay_tick_key(
        &name,
        delay,
        crate::time::clock_unix_duration(state.clock()),
    );
    let lease = match coordinator
        .try_acquire(&name, &tick_key, coordination)
        .await
    {
        Ok(Some(lease)) => lease,
        Ok(None) => {
            tracing::debug!(task = %name, tick = %tick_key, "Scheduled task tick already claimed");
            return;
        }
        Err(error) => {
            tracing::warn!(task = %name, tick = %tick_key, error = %error, "Failed to acquire scheduled task lease");
            return;
        }
    };
    state
        .task_registry
        .record_leader(&name, lease.leader_id(), &tick_key);
    tracing::debug!(task = %name, "Running scheduled task");
    state.task_registry.record_start(&name);

    send_ws_sys_task_msg(&state, "started", &name, vec![]);

    let start = std::time::Instant::now();
    let lease_ttl = lease_ttl_for_run(&lease, coordination, lease_ttl);
    match execute_task_result_with_optional_lease_ttl(
        &state,
        handler,
        start,
        &name,
        "fixed_delay",
        lease_ttl,
    )
    .await
    {
        Ok(duration_ms) => {
            state.task_registry.record_success(&name, duration_ms);
            crate::alerts::notify_scheduled_task_recovered(&state, &name);
            tracing::debug!(task = %name, "Task completed");
            send_ws_sys_task_msg(
                &state,
                "success",
                &name,
                vec![("duration_ms", serde_json::json!(duration_ms))],
            );
        }
        Err((duration_ms, error_str)) => {
            state
                .task_registry
                .record_failure(&name, duration_ms, &error_str);
            crate::alerts::notify_scheduled_task_failure(&state, &name, &error_str);
            tracing::warn!(task = %name, error = %error_str, "Task failed");
            send_ws_sys_task_msg(
                &state,
                "failure",
                &name,
                vec![
                    ("duration_ms", serde_json::json!(duration_ms)),
                    ("error", serde_json::json!(error_str)),
                ],
            );
        }
    }

    if let Err(error) = lease.release().await {
        tracing::warn!(task = %name, tick = %tick_key, error = %error, "Failed to release scheduled task lease");
    }
}

/// Handle the execution of a single cron task.
#[allow(clippy::cognitive_complexity)]
async fn execute_cron_task(
    name: String,
    state: AppState,
    handler: crate::task::TaskHandler,
    coordination: crate::task::TaskCoordination,
    coordinator: Arc<dyn crate::scheduler::SchedulerCoordinator>,
    lease_ttl: std::time::Duration,
    scheduled_unix_secs: u64,
) {
    let tick_key = crate::scheduler::cron_tick_key(&name, scheduled_unix_secs);
    let lease = match coordinator
        .try_acquire(&name, &tick_key, coordination)
        .await
    {
        Ok(Some(lease)) => lease,
        Ok(None) => {
            tracing::debug!(task = %name, tick = %tick_key, "Cron task tick already claimed");
            return;
        }
        Err(error) => {
            tracing::warn!(task = %name, tick = %tick_key, error = %error, "Failed to acquire cron task lease");
            return;
        }
    };
    state
        .task_registry
        .record_leader(&name, lease.leader_id(), &tick_key);
    tracing::debug!(task = %name, "Running cron task");
    state.task_registry.record_start(&name);

    send_ws_sys_task_msg(&state, "started", &name, vec![]);

    let start = std::time::Instant::now();
    let lease_ttl = lease_ttl_for_run(&lease, coordination, lease_ttl);
    match execute_task_result_with_optional_lease_ttl(
        &state, handler, start, &name, "cron", lease_ttl,
    )
    .await
    {
        Ok(duration_ms) => {
            state.task_registry.record_success(&name, duration_ms);
            crate::alerts::notify_scheduled_task_recovered(&state, &name);
            tracing::debug!(task = %name, "Cron task completed");
            send_ws_sys_task_msg(
                &state,
                "success",
                &name,
                vec![("duration_ms", serde_json::json!(duration_ms))],
            );
        }
        Err((duration_ms, error_str)) => {
            state
                .task_registry
                .record_failure(&name, duration_ms, &error_str);
            crate::alerts::notify_scheduled_task_failure(&state, &name, &error_str);
            tracing::warn!(task = %name, error = %error_str, "Cron task failed");
            send_ws_sys_task_msg(
                &state,
                "failure",
                &name,
                vec![
                    ("duration_ms", serde_json::json!(duration_ms)),
                    ("error", serde_json::json!(error_str)),
                ],
            );
        }
    }

    if let Err(error) = lease.release().await {
        tracing::warn!(task = %name, tick = %tick_key, error = %error, "Failed to release cron task lease");
    }
}

struct CronTaskSpec {
    name: String,
    expression: String,
    timezone: Option<String>,
    coordination: crate::task::TaskCoordination,
    handler: crate::task::TaskHandler,
}

fn lease_ttl_for_run(
    lease: &crate::scheduler::SchedulerLease,
    coordination: crate::task::TaskCoordination,
    lease_ttl: std::time::Duration,
) -> Option<std::time::Duration> {
    (coordination == crate::task::TaskCoordination::Fleet && lease.backend() == "postgres")
        .then_some(lease_ttl)
}

fn run_cron_scheduler(
    tasks: Vec<CronTaskSpec>,
    state: &AppState,
    shutdown: &tokio_util::sync::CancellationToken,
    coordinator: &Arc<dyn crate::scheduler::SchedulerCoordinator>,
    lease_ttl: std::time::Duration,
) {
    if tasks.is_empty() {
        return;
    }

    tracing::info!(count = tasks.len(), "Cron scheduler started");
    for task in tasks {
        let state = state.clone();
        let coordinator = Arc::clone(coordinator);
        let shutdown = shutdown.child_token();
        tokio::spawn(async move {
            run_cron_task_loop(task, state, shutdown, coordinator, lease_ttl).await;
        });
    }
}

#[allow(clippy::cognitive_complexity)]
async fn run_cron_task_loop(
    task: CronTaskSpec,
    state: AppState,
    shutdown: tokio_util::sync::CancellationToken,
    coordinator: Arc<dyn crate::scheduler::SchedulerCoordinator>,
    lease_ttl: std::time::Duration,
) {
    let CronTaskSpec {
        name,
        expression,
        timezone,
        coordination,
        handler,
    } = task;

    let cron = match expression.parse::<croner::Cron>() {
        Ok(cron) => cron,
        Err(error) => {
            tracing::error!(task = %name, expression = %expression, error = %error, "Failed to create cron job");
            return;
        }
    };
    let timezone = timezone
        .as_deref()
        .and_then(|timezone| {
            timezone.parse::<chrono_tz::Tz>().map_or_else(
                |_| {
                    tracing::warn!(task = %name, timezone = %timezone, "Unrecognized timezone; falling back to UTC");
                    None
                },
                Some,
            )
        })
        .unwrap_or(chrono_tz::UTC);
    let mut cursor = chrono::Utc::now().with_timezone(&timezone);

    loop {
        let now = chrono::Utc::now().with_timezone(&timezone);
        let scheduled_at = match next_cron_occurrence_after(&cron, &cursor, &now) {
            Ok(scheduled_at) => scheduled_at,
            Err(error) => {
                tracing::error!(task = %name, expression = %expression, error = %error, "Failed to compute next cron tick");
                return;
            }
        };
        state.task_registry.record_next_run_at(
            &name,
            &scheduled_at.with_timezone(&chrono::Utc).to_rfc3339(),
        );
        let sleep_for = cron_sleep_duration_until(&scheduled_at);
        tokio::select! {
            () = shutdown.cancelled() => break,
            () = tokio::time::sleep(sleep_for) => {
                let woke_at = chrono::Utc::now().with_timezone(&timezone);
                match cron_occurrence_is_overdue(&cron, &scheduled_at, &woke_at) {
                    Ok(true) => {
                        tracing::warn!(
                            task = %name,
                            scheduled_at = %scheduled_at,
                            woke_at = %woke_at,
                            "Skipping overdue cron task tick"
                        );
                        cursor = woke_at;
                        continue;
                    }
                    Ok(false) => {}
                    Err(error) => {
                        tracing::error!(task = %name, expression = %expression, error = %error, "Failed to evaluate cron tick lateness");
                        return;
                    }
                }
                let scheduled_unix_secs = u64::try_from(scheduled_at.timestamp()).unwrap_or_default();
                tokio::spawn(execute_cron_task(
                    name.clone(),
                    state.clone(),
                    handler,
                    coordination,
                    Arc::clone(&coordinator),
                    lease_ttl,
                    scheduled_unix_secs,
                ));
                cursor = scheduled_at;
            }
        }
    }
}

fn format_next_task_run_after(delay: std::time::Duration) -> String {
    let now = chrono::Utc::now();
    let Ok(delay) = chrono::TimeDelta::from_std(delay) else {
        return now.to_rfc3339();
    };
    (now + delay).to_rfc3339()
}

fn next_cron_occurrence_after<Tz: chrono::TimeZone>(
    cron: &croner::Cron,
    cursor: &chrono::DateTime<Tz>,
    now: &chrono::DateTime<Tz>,
) -> Result<chrono::DateTime<Tz>, croner::errors::CronError> {
    let anchor = if cursor < now { now } else { cursor };
    cron.find_next_occurrence(anchor, false)
}

fn cron_occurrence_is_overdue<Tz: chrono::TimeZone>(
    cron: &croner::Cron,
    scheduled_at: &chrono::DateTime<Tz>,
    now: &chrono::DateTime<Tz>,
) -> Result<bool, croner::errors::CronError> {
    let next_after_scheduled = cron.find_next_occurrence(scheduled_at, false)?;
    Ok(&next_after_scheduled <= now)
}

fn cron_sleep_duration_until<Tz: chrono::TimeZone>(
    scheduled_at: &chrono::DateTime<Tz>,
) -> std::time::Duration {
    scheduled_at
        .with_timezone(&chrono::Utc)
        .signed_duration_since(chrono::Utc::now())
        .to_std()
        .unwrap_or_default()
}

async fn run_startup_hooks(hooks: &[StartupHook], state: AppState) -> crate::AutumnResult<()> {
    for hook in hooks {
        hook(state.clone()).await?;
    }
    Ok(())
}

fn run_state_initializers(initializers: Vec<StateInitializer>, state: &AppState) {
    for initializer in initializers {
        initializer(state);
    }
}

/// Wire the typed event bus into the app at build time.
///
/// Builds the [`EventRegistry`](crate::events::EventRegistry) from registered
/// listeners, installs it onto `state` for the [`Events`](crate::events::Events)
/// extractor, appends a job per durable listener so they ride the job runtime
/// (retry + DLQ + restart-safety), and initializes the process-global bus used
/// by the module-level `events::publish`.
/// Build the [`EventRegistry`](crate::events::EventRegistry) from `listeners` and
/// append the synthesized `default`-queue [`JobInfo`](crate::job::JobInfo) for
/// each durable listener to `jobs`, returning the registry.
///
/// This is the pure, DB-free half of [`finalize_event_bus`]: it needs no live
/// `AppState` or database, only the listener set. Both the boot path (through
/// `finalize_event_bus`, which additionally wires the global bus onto live state)
/// and the deliberately DB-free `AUTUMN_DUMP_JOBS=1` dump path
/// ([`dump_jobs_manifest`]) funnel through here, so the emitted manifest can
/// never omit the durable-listener jobs the runtime actually drains.
fn synthesize_durable_listener_jobs(
    listeners: Vec<crate::events::ListenerInfo>,
    jobs: &mut Vec<crate::job::JobInfo>,
) -> crate::events::EventRegistry {
    let registry = crate::events::EventRegistry::from_listeners(listeners);
    jobs.extend(registry.durable_job_infos());
    registry
}

fn finalize_event_bus(
    listeners: Vec<crate::events::ListenerInfo>,
    jobs: &mut Vec<crate::job::JobInfo>,
    state: &AppState,
) {
    let registry = synthesize_durable_listener_jobs(listeners, jobs);
    state.insert_extension(registry.clone());
    crate::events::init_global_event_bus(&registry, state, None);
}

/// Compute the `AUTUMN_DUMP_JOBS=1` jobs manifest for the dump path.
///
/// Mirrors the boot path's job set: the builder's registered `jobs` PLUS the
/// synthesized `default`-queue jobs that [`finalize_event_bus`] appends for
/// durable listeners before the runtime starts. Without folding those in, an app
/// that registers a durable listener and configures `[jobs.queues]` without
/// `default` would emit a manifest omitting `default`, letting a topology-aware
/// `autumn doctor` accept a fleet where no tier drains the durable-listener jobs.
///
/// Only the pure job-synthesis half of `finalize_event_bus` runs here
/// (via [`synthesize_durable_listener_jobs`]); the dump path is deliberately
/// DB-free, so the live-state/global-bus wiring is skipped. Factored out so the
/// boot and dump paths share one job-preparation seam and so it is unit testable
/// without the process-exiting dump entrypoint.
fn dump_jobs_manifest(
    cfg: &crate::config::JobQueuesConfig,
    mut jobs: Vec<crate::job::JobInfo>,
    listeners: Vec<crate::events::ListenerInfo>,
) -> String {
    synthesize_durable_listener_jobs(listeners, &mut jobs);
    crate::job::render_jobs_manifest(cfg, &jobs)
}

fn initialize_job_runtime(
    jobs: Vec<crate::job::JobInfo>,
    state: &AppState,
    shutdown: &tokio_util::sync::CancellationToken,
    config: &crate::config::JobConfig,
    run_workers: bool,
) -> crate::AutumnResult<()> {
    crate::job::clear_global_job_client();
    if jobs.is_empty() {
        Ok(())
    } else {
        crate::job::start_runtime(jobs, state, shutdown, config, run_workers)
    }
}

/// A bound network listener for the server, abstracting over the transport.
///
/// `run()` binds one of these based on `config.server.unix_socket`: a TCP
/// listener on `host:port` (the default) or a Unix domain socket (local
/// daemon mode). The two carry different connect-info types, so the serve
/// task is spawned per-variant.
enum BoundListener {
    /// TCP listener on `host:port`.
    Tcp(tokio::net::TcpListener),
    /// Unix domain socket listener (local daemon transport).
    #[cfg(unix)]
    Unix(tokio::net::UnixListener),
    /// TLS-terminating listener on `host:port` (direct HTTPS, issue #1603).
    #[cfg(feature = "tls")]
    Tls(crate::tls::TlsListener),
}

/// Current UNIX time in seconds, saturating on the (impossible) pre-epoch case.
#[cfg(feature = "tls")]
fn now_unix() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
}

/// State carried from the TLS bind path to the background reload task.
#[cfg(feature = "tls")]
struct TlsReloadState {
    resolver: std::sync::Arc<crate::tls::ReloadableCertResolver>,
    provider: std::sync::Arc<rustls::crypto::CryptoProvider>,
    cert_path: std::path::PathBuf,
    key_path: std::path::PathBuf,
    interval: std::time::Duration,
}

/// Bind a TLS-terminating listener over `tcp`, loading and validating the
/// configured certificate and key (fail-fast on any problem).
#[cfg(feature = "tls")]
fn build_tls_listener(
    tcp: tokio::net::TcpListener,
    cfg: &crate::config::TlsConfig,
    shutdown: tokio_util::sync::CancellationToken,
) -> Result<(crate::tls::TlsListener, TlsReloadState), crate::tls::TlsError> {
    let provider = crate::tls::crypto_provider();
    // The pre-bind `TlsConfig::validate()` guarantees both paths are set in
    // static-cert mode (the only mode that reaches this function; ACME mode is
    // handled separately), so unwrapping here is validated, not hopeful.
    let cert_path = cfg
        .cert_path
        .as_deref()
        .expect("validated: static [server.tls] sets cert_path");
    let key_path = cfg
        .key_path
        .as_deref()
        .expect("validated: static [server.tls] sets key_path");
    let certified = crate::tls::load_certified_key(cert_path, key_path, &provider, now_unix())?;
    let resolver = std::sync::Arc::new(crate::tls::ReloadableCertResolver::new(certified));
    let server_config = crate::tls::build_server_config(
        std::sync::Arc::clone(&provider),
        std::sync::Arc::clone(&resolver),
    )?;
    // A zero handshake timeout would drop every connection instantly; clamp to
    // at least one second, mirroring the reload-interval clamp below.
    let handshake_timeout = std::time::Duration::from_secs(cfg.handshake_timeout_secs.max(1));
    let listener = crate::tls::TlsListener::new(tcp, server_config, handshake_timeout, shutdown);
    let reload = TlsReloadState {
        resolver,
        provider,
        cert_path: cert_path.to_path_buf(),
        key_path: key_path.to_path_buf(),
        // A zero interval would busy-loop; clamp to at least one second.
        interval: std::time::Duration::from_secs(cfg.reload_interval_secs.max(1)),
    };
    Ok((listener, reload))
}

/// Carries the ACME challenge-listener + renewal-task wiring from the bind path
/// to the sibling tasks spawned once `server_shutdown` exists.
#[cfg(feature = "acme")]
struct AcmeBindState {
    renewal_task: crate::acme::renewal::AcmeRenewalTask,
    tokens: crate::acme::challenge::Http01Tokens,
    http_challenge_port: u16,
    https_port: u16,
}

/// Build a TLS listener for ACME mode: serve a stored certificate if one is
/// present, else a self-signed placeholder so `:443` binds immediately. The
/// returned [`AcmeBindState`] carries everything the renewal task and challenge
/// listener need.
#[cfg(feature = "acme")]
async fn build_acme_tls_listener(
    tcp: tokio::net::TcpListener,
    tls_cfg: &crate::config::TlsConfig,
    acme_cfg: &crate::config::AcmeConfig,
    https_port: u16,
    status: Option<crate::acme::renewal::AcmeStatus>,
    shutdown: tokio_util::sync::CancellationToken,
) -> Result<(crate::tls::TlsListener, AcmeBindState), String> {
    use crate::acme::store::{AcmeStore, CertId, FsAcmeStore};

    let provider = crate::tls::crypto_provider();
    let cert_id = CertId::from_domains(&acme_cfg.domains);
    let directory_label = crate::acme::directory_label(&acme_cfg.directory);
    let store: std::sync::Arc<dyn AcmeStore> = std::sync::Arc::new(FsAcmeStore::new(
        acme_cfg.cache_dir.clone(),
        directory_label,
    ));
    let status = status.unwrap_or_default();

    // Prefer a valid stored certificate; fall back to a self-signed placeholder
    // so the port comes up while the first issuance runs in the background.
    let (initial, serving_stored_cert) = match store.load_cert(&cert_id).await {
        Ok(Some(stored)) => match crate::tls::certified_key_from_pem(
            stored.chain_pem.as_bytes(),
            stored.key_pem.as_bytes(),
            &provider,
        ) {
            Ok(ck) => {
                if let Ok(not_after) =
                    crate::tls::leaf_not_after_from_pem(stored.chain_pem.as_bytes())
                {
                    status.set_cert_not_after(not_after);
                }
                (ck, true)
            }
            Err(e) => {
                tracing::warn!(
                    "stored ACME certificate is unusable ({e}); serving a self-signed \
                     placeholder until the renewal task issues a real one"
                );
                (acme_placeholder_key(&acme_cfg.domains, &provider)?, false)
            }
        },
        Ok(None) => (acme_placeholder_key(&acme_cfg.domains, &provider)?, false),
        Err(e) => {
            tracing::warn!(
                "failed to read the stored ACME certificate ({e}); serving a self-signed \
                 placeholder"
            );
            (acme_placeholder_key(&acme_cfg.domains, &provider)?, false)
        }
    };

    let resolver = std::sync::Arc::new(crate::tls::ReloadableCertResolver::new(initial));
    let server_config = crate::tls::build_server_config(
        std::sync::Arc::clone(&provider),
        std::sync::Arc::clone(&resolver),
    )
    .map_err(|e| e.to_string())?;
    let handshake_timeout = std::time::Duration::from_secs(tls_cfg.handshake_timeout_secs.max(1));
    let listener = crate::tls::TlsListener::new(tcp, server_config, handshake_timeout, shutdown);

    let tokens = crate::acme::challenge::Http01Tokens::new();
    let renewal_task = crate::acme::renewal::AcmeRenewalTask {
        resolver,
        provider,
        store,
        cert_id,
        tokens: tokens.clone(),
        status,
        config: acme_cfg.clone(),
        serving_stored_cert,
        // Filled in at the renewal spawn site once the scheduler coordinator has
        // been built and any distributed → in-process fallback is known.
        leadership_degraded: false,
        renew_window_misconfigured: std::sync::atomic::AtomicBool::new(false),
    };
    Ok((
        listener,
        AcmeBindState {
            renewal_task,
            tokens,
            http_challenge_port: acme_cfg.http_challenge_port,
            https_port,
        },
    ))
}

/// Build a `CertifiedKey` from a fresh self-signed placeholder for `domains`.
#[cfg(feature = "acme")]
fn acme_placeholder_key(
    domains: &[String],
    provider: &rustls::crypto::CryptoProvider,
) -> Result<std::sync::Arc<rustls::sign::CertifiedKey>, String> {
    let placeholder = crate::acme::renewal::self_signed_placeholder(domains)?;
    crate::tls::certified_key_from_pem(
        placeholder.chain_pem.as_bytes(),
        placeholder.key_pem.as_bytes(),
        provider,
    )
}

/// Build the ACME renewal failure reporter: dispatch each failure as an
/// [`ErrorEvent`](crate::reporting::ErrorEvent) to the registered reporter chain
/// on a detached task, so failures reach Sentry/etc. when configured (failures
/// also always log via `tracing` inside the loop).
#[cfg(all(feature = "acme", feature = "reporting"))]
fn make_acme_reporter(
    reporters: Vec<std::sync::Arc<dyn crate::reporting::ErrorReporter>>,
) -> crate::acme::renewal::ReporterFn {
    std::sync::Arc::new(move |message: String| {
        if reporters.is_empty() {
            return;
        }
        let reporters = reporters.clone();
        tokio::spawn(async move {
            let event = crate::reporting::ErrorEvent {
                status: axum::http::StatusCode::INTERNAL_SERVER_ERROR,
                message,
                problem_type: None,
                request_id: None,
                route: Some("acme-renewal".to_owned()),
                method: None,
                panic: None,
            };
            for reporter in &reporters {
                reporter.report(&event).await;
            }
        });
    })
}

/// The no-op ACME reporter used when the `reporting` feature is off (failures
/// still log via `tracing`).
#[cfg(all(feature = "acme", not(feature = "reporting")))]
fn make_acme_reporter() -> crate::acme::renewal::ReporterFn {
    std::sync::Arc::new(|_message: String| {})
}

/// Modification times of the cert and key files, `None` for a file that could
/// not be stat'd. Reloads trigger on any change to this pair.
#[cfg(feature = "tls")]
fn tls_file_mtimes(
    cert: &std::path::Path,
    key: &std::path::Path,
) -> (Option<std::time::SystemTime>, Option<std::time::SystemTime>) {
    let mtime = |p: &std::path::Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();
    (mtime(cert), mtime(key))
}

/// Background task: poll the cert/key file mtimes and hot-swap the served
/// certificate on change. Never breaks the listener — a failed reload keeps the
/// previously loaded certificate and retries on the next tick.
#[cfg(feature = "tls")]
async fn run_tls_cert_reload(state: TlsReloadState, shutdown: tokio_util::sync::CancellationToken) {
    // Stat and PEM-read the cert/key on a blocking thread — both touch the
    // filesystem and must not run on a tokio worker. On a `JoinError` (the
    // blocking pool shutting down) just skip the tick and retry next time.
    let stat_mtimes = |cert: std::path::PathBuf, key: std::path::PathBuf| {
        tokio::task::spawn_blocking(move || tls_file_mtimes(&cert, &key))
    };

    let mut last = match stat_mtimes(state.cert_path.clone(), state.key_path.clone()).await {
        Ok(mtimes) => mtimes,
        Err(e) => {
            tracing::warn!(error = %e, "TLS reload: initial mtime read failed; assuming unknown");
            (None, None)
        }
    };
    loop {
        tokio::select! {
            () = tokio::time::sleep(state.interval) => {}
            () = shutdown.cancelled() => break,
        }

        let current = match stat_mtimes(state.cert_path.clone(), state.key_path.clone()).await {
            Ok(mtimes) => mtimes,
            Err(e) => {
                tracing::warn!(error = %e, "TLS reload: mtime read task failed; skipping tick");
                continue;
            }
        };
        if current == last {
            continue;
        }

        let cert_path = state.cert_path.clone();
        let key_path = state.key_path.clone();
        let provider = std::sync::Arc::clone(&state.provider);
        let loaded = tokio::task::spawn_blocking(move || {
            crate::tls::load_certified_key(&cert_path, &key_path, &provider, now_unix())
        })
        .await;
        let loaded = match loaded {
            Ok(result) => result,
            Err(e) => {
                tracing::warn!(error = %e, "TLS reload: load task failed; skipping tick");
                continue;
            }
        };

        match loaded {
            Ok(next) => {
                state.resolver.store(next);
                // Only advance the baseline on a successful load, so a partial
                // write observed mid-renewal is retried on the next tick.
                last = current;
                tracing::info!(
                    cert = %state.cert_path.display(),
                    "Reloaded TLS certificate after detecting a change on disk"
                );
            }
            Err(e) => {
                tracing::error!(
                    error = %e,
                    cert = %state.cert_path.display(),
                    "TLS certificate reload failed; keeping the previously loaded certificate"
                );
            }
        }
    }
}

/// Connection info for a Unix-domain-socket request.
///
/// axum's `into_make_service_with_connect_info::<C>` requires `C:
/// Connected<IncomingStream>`. Unlike TCP there is no peer `SocketAddr` for a
/// Unix socket, so this carries no data — it exists purely to satisfy the
/// connect-info bound on the UDS serve path.
#[cfg(unix)]
#[derive(Clone, Debug)]
struct UdsConnectInfo;

#[cfg(unix)]
impl
    axum::extract::connect_info::Connected<
        axum::serve::IncomingStream<'_, tokio::net::UnixListener>,
    > for UdsConnectInfo
{
    fn connect_info(_stream: axum::serve::IncomingStream<'_, tokio::net::UnixListener>) -> Self {
        Self
    }
}

/// Stamp a loopback peer (`127.0.0.1`) on Unix-domain-socket requests.
///
/// A UDS connection has no TCP peer `SocketAddr`, so without this the
/// trusted-proxy resolver and the [`ClientAddr`](crate::extract::ClientAddr)
/// extractor resolve no client address — breaking any route or middleware that
/// requires `ClientAddr` and any IP-based maintenance/rate-limit behavior. Local
/// daemon requests are loopback-equivalent, so present them as a `127.0.0.1`
/// connection (matching how an equivalent localhost TCP request is treated).
/// Installed before `TrustedProxiesLayer` on the UDS serve path only.
#[cfg(unix)]
async fn stamp_loopback_connect_info(
    mut req: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    if req
        .extensions()
        .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
        .is_none()
    {
        let loopback =
            std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), 0);
        req.extensions_mut()
            .insert(axum::extract::ConnectInfo(loopback));
    }
    next.run(req).await
}

/// Signal `autumn serve --daemon`'s supervisor that startup is complete.
///
/// The CLI passes a path via `AUTUMN_SERVE_READY_FILE` and polls for it; we
/// create it here, immediately after [`mark_startup_complete`], so the
/// supervisor's notion of "ready" means the socket is bound and serving *and*
/// startup hooks/migrations have finished — with no dependence on the app's HTTP
/// middleware (the startup barrier, maintenance mode, rate limiting, or custom
/// health paths, which an HTTP readiness probe would all have to thread).
///
/// The file's contents are the app's *resolved* graceful-drain budget in seconds
/// (`prestop_grace_secs + shutdown_timeout_secs`). The supervisor records this so
/// `autumn serve stop` waits for the budget the app will actually drain for —
/// even when a custom `with_config_loader` set it — instead of reconstructing it
/// from TOML/env and risking a premature `SIGKILL`.
///
/// Best-effort: a write failure only delays readiness detection until the
/// supervisor's timeout, and a non-daemon run leaves the variable unset (no-op).
///
/// [`mark_startup_complete`]: crate::probe::ProbeState::mark_startup_complete
fn signal_serve_ready(drain_budget_secs: u64) {
    let Some(path) = std::env::var_os("AUTUMN_SERVE_READY_FILE") else {
        return;
    };
    if path.is_empty() {
        return;
    }
    let path = std::path::PathBuf::from(path);
    // Write to a temp sibling and rename into place so the supervisor — which
    // polls for the file's existence and then reads the budget from it — never
    // observes a half-written file: it appears atomically with its full
    // contents. A plain `write` would make the path exist before the bytes land.
    let mut tmp = path.clone();
    tmp.as_mut_os_string().push(".tmp");
    if let Err(e) = std::fs::write(&tmp, drain_budget_secs.to_string())
        .and_then(|()| std::fs::rename(&tmp, &path))
    {
        let _ = std::fs::remove_file(&tmp);
        tracing::warn!(error = %e, path = %path.display(),
            "could not write serve readiness file");
    }
}

/// Prepare a Unix-socket path for binding: remove a *stale* socket left by a
/// previous run, but refuse to touch a non-socket file (guards against
/// clobbering a regular file) or a socket with a **live** listener (probed via
/// `connect`; clobbering it would silently make that service unreachable —
/// instead we fail like a TCP `EADDRINUSE`). A missing path is fine.
///
/// # Errors
///
/// Returns an error if the path exists and is not a socket, names a live
/// listener, or the stale socket cannot be removed.
#[cfg(unix)]
fn prepare_unix_socket_path(path: &std::path::Path) -> std::io::Result<()> {
    use std::os::unix::fs::FileTypeExt;
    match std::fs::symlink_metadata(path) {
        Ok(meta) if meta.file_type().is_socket() => {
            match std::os::unix::net::UnixStream::connect(path) {
                // A successful connect means another process is listening here.
                Ok(_) => Err(std::io::Error::new(
                    std::io::ErrorKind::AddrInUse,
                    format!(
                        "refusing to bind unix socket: {} is already in use by a \
                         live listener",
                        path.display()
                    ),
                )),
                // `ECONNREFUSED` (no listener) — or the path vanishing — means the
                // socket is stale; reclaim it.
                Err(e)
                    if matches!(
                        e.kind(),
                        std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::NotFound
                    ) =>
                {
                    std::fs::remove_file(path)
                }
                // `EACCES`/`EPERM` (or any other error): the socket may be a live,
                // operator-managed listener whose mode/ACL denies us. Connecting
                // failed, but liveness is unproven — refuse rather than clobber a
                // possibly-live service.
                Err(e) => Err(std::io::Error::new(
                    std::io::ErrorKind::AddrInUse,
                    format!(
                        "refusing to bind unix socket: cannot determine whether {} \
                         is live ({e}); not removing it",
                        path.display()
                    ),
                )),
            }
        }
        Ok(_) => Err(std::io::Error::new(
            std::io::ErrorKind::AlreadyExists,
            format!(
                "refusing to bind unix socket: {} exists and is not a socket",
                path.display()
            ),
        )),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(e),
    }
}

async fn run_shutdown_hooks(hooks: &[ShutdownHook]) {
    for hook in hooks.iter().rev() {
        hook().await;
    }
}

/// Run shutdown hooks in reverse-registration order (LIFO), enforcing a
/// per-hook timeout and a hard total-budget ceiling.
///
/// Plugin ordering rule: plugins register hooks during `build()`, which is
/// called before any app `on_shutdown` calls, so app hooks run **before**
/// plugin hooks (LIFO means last-registered runs first).
///
/// Overruns are logged at WARN but do not block the remaining budget.
async fn run_shutdown_hooks_with_timeout(
    hooks: &[ShutdownHook],
    per_hook_budget: std::time::Duration,
    total_budget: std::time::Duration,
) {
    let deadline = tokio::time::Instant::now() + total_budget;
    for hook in hooks.iter().rev() {
        let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
        if remaining.is_zero() {
            tracing::warn!("shutdown: total hook budget exhausted; skipping remaining hooks");
            break;
        }
        let timeout = remaining.min(per_hook_budget);
        // Hook overruns are intentionally non-fatal (exit 0 per ADR addendum).
        // Only drain deadline exhaustion (phase 6) triggers exit(1).
        if tokio::time::timeout(timeout, hook()).await.is_err() {
            tracing::warn!(
                per_hook_budget_ms = timeout.as_millis(),
                "shutdown: hook overran per-hook timeout; continuing with remaining budget"
            );
        }
    }
}

/// Log a structured startup transparency report.
///
/// Activated by setting `AUTUMN_SHOW_CONFIG=1` (or `autumn dev --show-config`).
/// Prints all registered routes, scheduled tasks, active middleware, and
/// resolved configuration to the `INFO` log so developers can see exactly
/// what the macros and conventions configured.
#[allow(clippy::cognitive_complexity)]
fn log_startup_transparency(
    routes: &[Route],
    tasks: &[crate::task::TaskInfo],
    scoped_groups: &[ScopedGroup],
    config: &AutumnConfig,
) {
    tracing::info!(
        "Registered routes:{}",
        format_route_lines(routes, scoped_groups, config)
    );

    if let Some(task_lines) = format_task_lines(tasks) {
        tracing::info!("Scheduled tasks:{task_lines}");
    }

    tracing::info!("Active middleware: {}", format_middleware_list(config));

    tracing::info!("Configuration:{}", format_config_summary(config));
}

/// Fail the boot fast (before any DB side effects) when the default
/// session backend is misconfigured.
///
/// `AutumnConfig::validate()` is intentionally session-agnostic so that a
/// custom [`SessionStore`](crate::session::SessionStore) installed via
/// [`AppBuilder::with_session_store`] can override an otherwise-invalid
/// `session.backend = "redis"`-without-`redis.url` config. But when no
/// custom store is installed, the config-driven path will fail later in
/// `apply_session_layer` — and by then, `setup_database` has already run
/// migrations, leaving DB side effects from a doomed boot. This helper
/// runs the same `backend_plan` check `apply_session_layer` does, but
/// before any side effects, and only when the override path is inactive.
fn fail_fast_on_invalid_session_config(config: &AutumnConfig, has_custom_session_store: bool) {
    if has_custom_session_store {
        return;
    }
    if let Err(error) = config.session.backend_plan(config.profile.as_deref()) {
        eprintln!("Invalid session backend config: {error}");
        std::process::exit(1);
    }
}

/// Resolve at-rest column-encryption keys at boot (#805).
///
/// On success this installs the process-global key ring. When encrypted columns
/// are registered but the key material under `active_record_encryption` is
/// missing or malformed, the behaviour mirrors the signing-secret check (#597):
/// a **hard failure in production** (the server must not bind with unusable
/// encryption), but only a **warning in dev/test** so zero-config local
/// development and the example apps continue to run. Apps that do not opt into
/// encrypted columns are unaffected (no registered columns -> no-op).
fn fail_fast_on_missing_encryption_keys(config: &AutumnConfig) {
    if let Err(diagnostic) = crate::encryption::init_attribute_encryption(config.credentials()) {
        let is_production = matches!(config.profile.as_deref(), Some("prod" | "production"));
        if is_production {
            eprintln!("Attribute encryption misconfiguration: {diagnostic}");
            std::process::exit(1);
        }
        eprintln!(
            "warning: attribute encryption is not fully configured (dev): {diagnostic}\n  \
             note: encrypted-column reads/writes will fail until keys are set; \
             this is a hard error in production."
        );
    }
}

/// Fail immediately if the signing secret is misconfigured for the active profile.
///
/// In production, a missing, too-short, or demo-valued signing secret is a
/// hard failure — the server must not bind. In dev/test the check is skipped
/// so zero-config local development continues to work.
fn fail_fast_on_invalid_signing_secret(config: &AutumnConfig) {
    use crate::security::config::validate_signing_secret;

    let is_production = matches!(config.profile.as_deref(), Some("prod" | "production"));
    let secret = config.security.signing_secret.secret.as_deref();

    if let Err(error) = validate_signing_secret(secret, is_production) {
        eprintln!("Invalid signing secret configuration: {error}");
        eprintln!(
            "  hint: generate a secret with `openssl rand -hex 32` and set \
             AUTUMN_SECURITY__SIGNING_SECRET"
        );
        std::process::exit(1);
    }

    // Previous secrets accepted during rotation must meet the same bar as the
    // current secret — a weak previous key can still be used to forge tokens.
    if is_production {
        for (i, prev) in config
            .security
            .signing_secret
            .previous_secrets
            .iter()
            .enumerate()
        {
            if let Err(error) = validate_signing_secret(Some(prev.as_str()), true) {
                eprintln!("Invalid signing secret configuration: previous_secrets[{i}]: {error}");
                eprintln!(
                    "  hint: every previous secret must meet the same entropy requirement \
                     as the current secret"
                );
                std::process::exit(1);
            }
        }
    }
}

fn fail_fast_on_invalid_webhook_config(config: &AutumnConfig) {
    let is_production = matches!(config.profile.as_deref(), Some("prod" | "production"));
    if let Err(error) = config.security.webhooks.validate(is_production) {
        eprintln!("Invalid signed webhook configuration: {error}");
        std::process::exit(1);
    }
}

fn fail_fast_on_invalid_trusted_hosts(config: &AutumnConfig) {
    let is_production = matches!(config.profile.as_deref(), Some("prod" | "production"));
    if !is_production {
        return;
    }
    let hosts: Vec<String> = config
        .security
        .trusted_hosts
        .hosts
        .iter()
        .map(|h| h.trim().to_owned())
        .filter(|h| !h.is_empty())
        .collect();
    if hosts.is_empty() {
        eprintln!(
            "[security.trusted_hosts] is required in production; set hosts = [\"example.com\"] or explicit entries"
        );
        std::process::exit(1);
    }
    if hosts.iter().any(|h| h == "*") {
        tracing::warn!("trusted host validation disabled via wildcard '*' in production");
    }
}

fn fail_fast_on_invalid_idempotency_config(config: &AutumnConfig) {
    if !config.idempotency.enabled.unwrap_or(false) {
        return;
    }
    let is_production = matches!(config.profile.as_deref(), Some("prod" | "production"));
    if is_production
        && config.idempotency.backend == crate::config::IdempotencyBackend::Memory
        && !config.idempotency.allow_memory_in_production
    {
        eprintln!(
            "The in-memory idempotency backend is not safe for multi-replica production use.\n\
             Set `[idempotency] backend = \"redis\"` in autumn.toml, or set \
             `allow_memory_in_production = true` to suppress this check."
        );
        std::process::exit(1);
    }
    #[cfg(feature = "redis")]
    if config.idempotency.backend == crate::config::IdempotencyBackend::Redis {
        let url_missing = config
            .idempotency
            .redis
            .url
            .as_deref()
            .is_none_or(|u| u.trim().is_empty());
        if url_missing {
            eprintln!(
                "Redis idempotency backend requires a connection URL.\n\
                 Set AUTUMN_IDEMPOTENCY__REDIS__URL or `[idempotency.redis] url` in autumn.toml."
            );
            std::process::exit(1);
        }
    }
}

pub(crate) fn install_webhook_registry(state: &AppState, config: &AutumnConfig) {
    if let Err(error) =
        crate::webhook::install_registry_from_config(state, &config.security.webhooks)
    {
        eprintln!("Invalid signed webhook configuration: {error}");
        std::process::exit(1);
    }
}

/// Constructed [`BlobStore`](crate::storage::BlobStore) plus the
/// optional axum router that serves signed URLs for the Local backend.
/// Returned by [`preflight_storage`] before any DB side effects so a
/// doomed boot can't run migrations first; installed onto
/// [`AppState`] later via [`StorageBootstrap::install`].
#[cfg(feature = "storage")]
struct StorageBootstrap {
    store: crate::storage::SharedBlobStore,
    serving: Option<axum::Router<AppState>>,
}

#[cfg(feature = "storage")]
impl StorageBootstrap {
    /// Install the preflighted store on `AppState` and return the
    /// optional serving router so the caller can merge it into the
    /// app router.
    fn install(self, state: &AppState) -> Option<axum::Router<AppState>> {
        state.insert_extension::<crate::storage::BlobStoreState>(
            crate::storage::BlobStoreState::new(self.store),
        );
        self.serving
    }
}

/// Provision the configured [`BlobStore`](crate::storage::BlobStore)
/// before any database side effects. Construction is the side-effecting
/// step (creates + canonicalizes the storage root, may
/// `process::exit(1)` on a misconfiguration); we deliberately run it
/// before `setup_database` so a doomed boot doesn't apply migrations
/// first. Installation onto `AppState` happens later via
/// [`StorageBootstrap::install`].
#[cfg(feature = "storage")]
#[allow(clippy::too_many_lines)] // Single switch over backend variants reads as one unit.
fn preflight_storage(config: &AutumnConfig) -> Option<StorageBootstrap> {
    use crate::storage::StorageBackendPlan;

    let plan = config
        .storage
        .backend_plan(config.profile.as_deref())
        .unwrap_or_else(|error| {
            // Cover the cases `backend_plan` rejects up front:
            // `LocalInProduction` (prod + local without ack),
            // `MissingS3Bucket`/`MissingS3Region`/`S3FeatureDisabled`.
            // Each is a configuration mistake — fail the boot loudly
            // rather than running migrations and then dying.
            tracing::error!(%error, "invalid storage backend config; aborting startup");
            std::process::exit(1);
        });

    match plan {
        StorageBackendPlan::Disabled => None,
        StorageBackendPlan::Local {
            provider_id,
            root,
            mount_path,
            default_url_expiry_secs,
            warn_in_production,
        } => Some(bootstrap_local_storage(
            config,
            &provider_id,
            &root,
            &mount_path,
            default_url_expiry_secs,
            warn_in_production,
        )),
        StorageBackendPlan::S3 { .. } => {
            // `storage.backend = "s3"` requires the `autumn-storage-s3` plugin.
            // Construct an `S3BlobStore` and register it with `.with_blob_store()`
            // before calling `.run()` — when you do, the custom store bypasses
            // this path entirely and `preflight_storage` is never called.
            tracing::error!(
                "storage.backend=s3 requires the `autumn-storage-s3` plugin. \
                 Add it to your Cargo.toml, build an S3BlobStore from your config, \
                 and call `.with_blob_store(store)` on your AppBuilder. \
                 Aborting startup."
            );
            std::process::exit(1);
        }
    }
}

#[cfg(feature = "storage")]
fn bootstrap_local_storage(
    config: &AutumnConfig,
    provider_id: &str,
    root: &std::path::Path,
    mount_path: &str,
    default_url_expiry_secs: u64,
    warn_in_production: bool,
) -> StorageBootstrap {
    use crate::storage::{LocalBlobStore, SharedBlobStore, local::SigningKey};

    if warn_in_production {
        tracing::warn!(
            "prod profile is using the local-disk blob store; \
             bytes won't survive replica turnover. Set \
             storage.backend=s3 or storage.allow_local_in_production=true \
             to acknowledge"
        );
    }

    // Signing key precedence:
    // 1. security.signing_secret (canonical, shared with session/CSRF)
    // 2. storage.local.signing_key (legacy override — still respected)
    // 3. Random ephemeral key (dev only — warns in prod)
    let (signing_key, previous_signing_keys) = config
        .security
        .signing_secret
        .secret
        .as_deref()
        .filter(|s| !s.is_empty())
        .map_or_else(
            || {
                config
                    .storage
                    .local
                    .signing_key
                    .as_deref()
                    .filter(|s| !s.is_empty())
                    .map_or_else(
                        || {
                            if matches!(config.profile.as_deref(), Some("prod" | "production")) {
                                tracing::warn!(
                                    "no signing secret configured in prod; blob URL signatures \
                                     won't survive a process restart. Set \
                                     AUTUMN_SECURITY__SIGNING_SECRET."
                                );
                            }
                            (SigningKey::random(), vec![])
                        },
                        |legacy| (SigningKey::new(legacy.as_bytes().to_vec()), vec![]),
                    )
            },
            |secret| {
                let current = SigningKey::new(secret.as_bytes().to_vec());
                let previous = config
                    .security
                    .signing_secret
                    .previous_secrets
                    .iter()
                    .map(|s| SigningKey::new(s.as_bytes().to_vec()))
                    .collect::<Vec<_>>();
                (current, previous)
            },
        );

    let store = match LocalBlobStore::new(
        provider_id.to_string(),
        root.to_path_buf(),
        mount_path.to_string(),
        std::time::Duration::from_secs(default_url_expiry_secs),
        signing_key,
        previous_signing_keys,
    ) {
        Ok(store) => store,
        Err(err) => {
            // The operator explicitly chose `storage.backend = "local"`
            // — a non-writable root means uploads can't possibly
            // work, so abort the boot rather than letting upload
            // handlers serve 500s after deploy.
            tracing::error!(
                error = %err,
                root = %root.display(),
                "failed to initialize local blob store; aborting startup"
            );
            std::process::exit(1);
        }
    };

    let serving = crate::storage::local::serve_router(&store);
    let arc: SharedBlobStore = std::sync::Arc::new(store);

    tracing::info!(
        provider = %provider_id,
        root = %root.display(),
        mount = %mount_path,
        "Local blob store mounted"
    );

    StorageBootstrap {
        store: arc,
        serving: Some(serving),
    }
}
async fn load_config_and_telemetry(
    config_loader: Option<ConfigLoaderFactory>,
    telemetry_provider: Option<Box<dyn crate::telemetry::TelemetryProvider>>,
    plugin_config_roots: BTreeSet<String>,
) -> (AutumnConfig, crate::telemetry::TelemetryGuard) {
    // 1. Load configuration via the installed loader, falling back to the
    //    five-layer TOML + env default.
    //
    // A custom `config_loader` factory owns its entire load + strict-config
    // handling (it bypasses the default TOML path), so it does not receive the
    // declared plugin config roots — such a loader is responsible for accepting
    // its own plugin-owned sections. The default `TomlEnvConfigLoader` is handed
    // the roots so `server.strict_config` treats each plugin-declared `[root]`
    // (e.g. `[media]`) as known-and-opaque instead of an unknown-key hard error.
    let mut config = match config_loader {
        Some(factory) => factory().await,
        None => {
            crate::config::TomlEnvConfigLoader::new()
                .with_plugin_config_roots(plugin_config_roots)
                .load()
                .await
        }
    }
    .unwrap_or_else(|e| {
        eprintln!("Failed to load configuration: {e}");
        std::process::exit(1);
    });

    // `autumn serve --daemon` binds the app on a private Unix socket and then
    // discovers/health-probes it by path. A custom `with_config_loader` can
    // construct its `ServerConfig` from scratch and silently drop the
    // `AUTUMN_SERVER__UNIX_SOCKET` env override, leaving the daemon on TCP where
    // the supervisor can't reach it. The CLI therefore also passes the socket
    // out-of-band via `AUTUMN_SERVE_FORCE_UNIX_SOCKET`, applied here *after* the
    // loader runs so no loader can drop it.
    if let Ok(forced) = std::env::var("AUTUMN_SERVE_FORCE_UNIX_SOCKET")
        && !forced.is_empty()
    {
        config.server.unix_socket = Some(forced);
    }

    // 2. Initialize logging/telemetry via the installed provider, falling
    //    back to the default `tracing-subscriber + OTLP` initializer.
    let provider: Box<dyn crate::telemetry::TelemetryProvider> = telemetry_provider
        .unwrap_or_else(|| Box::new(crate::telemetry::TracingOtlpTelemetryProvider::new()));
    let telemetry_guard = provider
        .init(&config.log, &config.telemetry, config.profile.as_deref())
        .unwrap_or_else(|error| {
            eprintln!("Failed to initialize telemetry: {error}");
            std::process::exit(1);
        });

    (config, telemetry_guard)
}

/// Register the embedded `static/` tree (if any) as the process-wide asset
/// source. Called by each `run` path before the router is built so `/static/*`
/// serves from the binary and `asset_url()` resolves against the embedded
/// manifest.
#[cfg(feature = "embed-assets")]
fn register_embedded_static_dir(embedded_static: Option<crate::assets::EmbeddedStaticDir>) {
    if let Some(dir) = embedded_static {
        crate::assets::register_embedded_static(dir);
    }
}

/// Prefer an embedded locale bundle over disk auto-loading when no explicit
/// bundle was provided. Returns `explicit` unchanged when it is `Some` or when
/// no embedded locales were registered.
#[cfg(all(feature = "embed-assets", feature = "i18n"))]
fn embedded_i18n_bundle(
    explicit: Option<Arc<crate::i18n::Bundle>>,
    embedded_locales: Option<&'static include_dir::Dir<'static>>,
    config: &AutumnConfig,
) -> Option<Arc<crate::i18n::Bundle>> {
    explicit.or_else(|| {
        embedded_locales.map(|dir| {
            Arc::new(
                crate::i18n::Bundle::load_from_embedded(dir, &config.i18n)
                    .unwrap_or_else(|e| panic!("embedded_locales: {e}")),
            )
        })
    })
}

#[cfg(feature = "i18n")]
fn resolve_i18n_bundle(
    explicit_bundle: Option<Arc<crate::i18n::Bundle>>,
    auto_load: bool,
    config: &AutumnConfig,
    env: &dyn crate::config::Env,
) -> Option<Arc<crate::i18n::Bundle>> {
    if explicit_bundle.is_some() {
        return explicit_bundle;
    }
    if !auto_load {
        return None;
    }

    let dir = project_dir(&config.i18n.dir, env);
    Some(Arc::new(
        crate::i18n::Bundle::load_from_dir(&dir, &config.i18n)
            .unwrap_or_else(|e| panic!("i18n_auto: {e}")),
    ))
}

#[cfg(feature = "i18n")]
fn install_i18n_bundle_layer(
    mut custom_layers: Vec<CustomLayerRegistration>,
    state: &AppState,
    bundle: Option<Arc<crate::i18n::Bundle>>,
) -> Vec<CustomLayerRegistration> {
    let Some(bundle) = bundle else {
        return custom_layers;
    };

    tracing::info!(
        locales = ?bundle.locales(),
        default = bundle.default_locale(),
        "i18n bundle loaded"
    );
    state.insert_extension::<Arc<crate::i18n::Bundle>>(bundle.clone());
    // Use the existing IntoAppLayer plumbing so the Extension is visible to
    // every request. axum::Extension<T> is itself a tower::Layer when T:
    // Clone + Send + Sync + 'static.
    let ext_layer = axum::Extension(bundle);
    custom_layers.push(CustomLayerRegistration {
        type_id: TypeId::of::<axum::Extension<Arc<crate::i18n::Bundle>>>(),
        type_name: std::any::type_name::<axum::Extension<Arc<crate::i18n::Bundle>>>(),
        apply: Box::new(move |router| router.layer(ext_layer)),
    });
    custom_layers
}

#[cfg(feature = "db")]
struct DatabaseBootstrap {
    topology: Option<crate::db::DatabaseTopology>,
    shards: Option<crate::sharding::ShardSet>,
    replica_readiness: Option<crate::migrate::ReplicaMigrationReadiness>,
    replica_migration_check: Option<(String, String)>,
}

/// Build the `ShardSet` for a sharded app (or `None` when no `[[database.shards]]`
/// are configured). Resolves the shard router first: an explicit
/// `with_shard_router` wins; otherwise `directory_routing_enabled` opts into the
/// control-DB directory router (bound to the just-built control primary pool);
/// otherwise the hash router. The directory flag is documented as having no
/// effect without shards, so a shardless profile that leaves it enabled must not
/// fail startup — hence the early `None` return.
///
/// `spawn_directory_listener` gates the directory-router cache-invalidation
/// listener: it opens control-DB connections, so it is spawned only at real
/// runtime, never during a static build (`autumn build`) which must not touch
/// the database.
#[cfg(feature = "db")]
async fn resolve_shard_set(
    config: &AutumnConfig,
    shard_router: Option<Arc<dyn crate::sharding::ShardRouter>>,
    shard_provider: Option<ShardProviderFactory>,
    directory_routing_enabled: bool,
    spawn_directory_listener: bool,
    topology: Option<&crate::db::DatabaseTopology>,
) -> Result<Option<crate::sharding::ShardSet>, String> {
    if !config.database.has_shards() {
        return Ok(None);
    }
    let router: Arc<dyn crate::sharding::ShardRouter> = match shard_router {
        Some(explicit) => explicit,
        None if directory_routing_enabled => {
            let control_primary = topology
                .map(crate::db::DatabaseTopology::primary)
                .ok_or_else(|| {
                    "directory_shard_router is enabled but no control database is configured. \
                     The directory router needs a control `database.primary_url`/`url` to read \
                     the tenant→shard directory. Set one, or disable directory routing to use \
                     the hash router."
                        .to_owned()
                })?;
            // Directory routing resolves the tenant→shard key by checking out a
            // *second* control connection during extraction. A handler that
            // already holds `Db` (or another control checkout) before extracting
            // `ShardedDb` / a sharded repository would then deadlock on a control
            // pool sized to 1 — the first checkout cannot be released until the
            // handler runs. Require at least 2 control connections so these
            // mixed control+tenant handlers always make progress.
            let control_max = control_primary.status().max_size;
            if control_max < 2 {
                return Err(format!(
                    "directory_shard_router requires a control database pool of at least 2 \
                     connections, but the configured maximum is {control_max}. Directory \
                     routing checks out a second control connection during extraction to \
                     resolve the tenant→shard key, which deadlocks a pool sized to 1 when a \
                     handler already holds a control connection (e.g. `Db` + `ShardedDb`). \
                     Increase the control pool size (database.pool.max_size), or disable \
                     directory routing to use the hash router."
                ));
            }
            // Bound directory lookups with the configured database statement
            // timeout (capped to Postgres' i32 millisecond range).
            let timeout_ms = config.database.statement_timeout.map_or(0, |d| {
                u64::try_from(d.as_millis())
                    .unwrap_or(i32::MAX as u64)
                    .min(i32::MAX as u64)
            });
            let dir_router = Arc::new(
                crate::sharding::DirectoryShardRouter::new(control_primary.clone())
                    .with_statement_timeout_ms(timeout_ms),
            );
            // Spawn the cache-invalidation listener on the control DB so a re-pin
            // (e.g. during a slot move) evicts cached tenant→shard mappings fleet-
            // wide the moment it commits (LISTEN/NOTIFY) rather than waiting out
            // the TTL. Skipped during a static build (no DB access); needs the
            // control URL, without one we silently fall back to TTL-only refresh.
            if spawn_directory_listener {
                // Prefer the provider-resolved control URL carried on the
                // topology (managed Postgres has no `database.primary_url` in
                // config); fall back to the configured URL. Without this a
                // managed control DB would get no LISTEN/NOTIFY task (absent
                // URL) or listen on a stale pre-provider URL.
                if let Some(control_url) = topology
                    .and_then(crate::db::DatabaseTopology::migration_url)
                    .or_else(|| config.database.effective_primary_url())
                {
                    // Detach: the listener runs for the life of the process;
                    // dropping the JoinHandle leaves the task running rather than
                    // aborting it.
                    drop(
                        crate::sharding::DirectoryShardRouter::spawn_invalidation_listener(
                            Arc::clone(&dir_router),
                            control_url.to_owned(),
                            crate::sharding::DEFAULT_DIRECTORY_INVALIDATION_SWEEP_INTERVAL,
                        ),
                    );
                } else {
                    // Directory routing is active but there is no control URL to
                    // open a dedicated LISTEN connection — e.g. a custom
                    // `DatabasePoolProvider` supplied the control pool without
                    // `database.primary_url`/`url`. The router still serves
                    // lookups from the provided pool, but re-pins won't be
                    // invalidated fleet-wide on commit; they only take effect
                    // after the cache TTL expires. Warn rather than fall back
                    // silently so operators relying on the directory for slot
                    // moves can configure a control URL (or accept TTL-only
                    // refresh) deliberately.
                    tracing::warn!(
                        "directory shard routing is enabled but no control database URL is \
                         configured (database.primary_url/url is unset, e.g. a custom \
                         DatabasePoolProvider supplied the control pool); the cache-\
                         invalidation LISTEN/NOTIFY task cannot be started, so directory \
                         re-pins will only take effect after the cache TTL expires rather \
                         than fleet-wide on commit"
                    );
                }
            }
            dir_router
        }
        None => Arc::new(crate::sharding::HashShardRouter),
    };
    let set = match shard_provider {
        Some(factory) => {
            let topologies = factory(config.database.clone())
                .await
                .map_err(|e| format!("Failed to create shard pools: {e}"))?;
            // A custom shard provider established shard pools without routing
            // through the built-in `create_shard_topology` factory (which
            // validates `database.statement_timeout` internally), so enforce the
            // same fail-closed guard here — but only now that pools WERE actually
            // established. `resolve_shard_set` already returned early for a
            // shardless profile, so this Some-gated check never rejects a
            // no-database path; a shard set that establishes SQLite pools under a
            // nonzero timeout still fails closed.
            #[cfg(feature = "sqlite")]
            crate::db::reject_sqlite_statement_timeout(config.database.statement_timeout)
                .map_err(|e| format!("Failed to create shard pools: {e}"))?;
            crate::sharding::build_shard_set(&config.database, topologies, router)
        }
        None => crate::sharding::create_shard_set(&config.database, router)
            .map(|set| set.expect("has_shards() checked above")),
    }
    .map_err(|e| format!("Failed to configure shards: {e}"))?;
    Ok(Some(set))
}

#[cfg(feature = "db")]
// The `sqlite` feature adds a small fail-fast startup-migration guard block
// (issue #1614) that pushes this orchestration fn just over the line limit.
#[allow(clippy::too_many_lines)]
async fn setup_database(
    config: &AutumnConfig,
    migrations: Vec<crate::migrate::EmbeddedMigrations>,
    pool_provider: Option<PoolProviderFactory>,
    shard_provider: Option<ShardProviderFactory>,
    shard_router: Option<Arc<dyn crate::sharding::ShardRouter>>,
    directory_shard_router: bool,
    hook_queue_migration_mode: RepositoryCommitHookQueueMigrationMode,
) -> Result<DatabaseBootstrap, String> {
    let migrations = migrations_with_repository_framework_migrations(
        migrations,
        crate::repository_commit_hooks::has_repository_commit_hook_descriptors(),
        crate::version_history::has_versioned_repository_descriptors(),
        hook_queue_migration_mode,
    );
    // Directory routing is only actually active when the app did NOT supply an
    // explicit shard router: an explicit `with_shard_router(...)` takes
    // precedence over `directory_shard_router` in `resolve_shard_set`, so in
    // that case the `DirectoryShardRouter` is never constructed and the
    // directory table is never consulted. Gate the migration on the same
    // condition so an explicit-router app doesn't create `_autumn_shard_directory`
    // (or warn about a pending directory migration) for a table it won't use.
    let use_directory_router = shard_router.is_none()
        && (directory_shard_router || config.database.directory_shard_router);
    // The tenant→shard directory table is a CONTROL-plane table: create it at
    // startup only when directory routing is active (and shards exist), and
    // only on the control target — not via the shared list above, which is also
    // applied to every shard. Like the other runtime framework migrations, it is
    // suppressed during a static build (`autumn build`, AUTUMN_BUILD_STATIC=1):
    // the build only renders assets and must not touch the database, so it must
    // not create `_autumn_shard_directory`.
    let directory_migration_required = directory_migration_is_required(
        use_directory_router,
        config.database.has_shards(),
        hook_queue_migration_mode,
    );
    let shard_map_migration_required =
        shard_map_migration_is_required(config.database.has_shards(), hook_queue_migration_mode);
    let check_replica_migrations = !migrations.is_empty();
    let topology = match pool_provider {
        Some(factory) => factory(config.database.clone()).await,
        None => crate::db::create_topology(&config.database),
    }
    .map_err(|e| format!("Failed to create database pool: {e}"))?;
    // Fail-closed statement-timeout guard — enforced only once a control pool has
    // ACTUALLY been established (the provider, built-in or custom, returned
    // `Some(..)`). The built-in `create_topology`/`create_shard_topology`
    // factories validate `database.statement_timeout` internally, but a custom
    // `with_pool_provider` provider can build its own SQLite pool without routing
    // through them — the default `DatabasePoolProvider::create_topology` only
    // delegates to the provider's `create_pool`, and both
    // `create_topology`/`create_shard_topology` are overridable — so a custom
    // provider could otherwise silently discard the timeout and break the
    // fail-closed guarantee. Under the `sqlite` feature `RuntimeBackend` is always
    // SQLite, so an established pool plus a nonzero timeout is exactly the
    // fail-closed condition. A provider that returns `Ok(None)` opts into the
    // explicitly-supported no-database mode — no pool/statement exists to need a
    // timeout — so it must still boot, matching the built-in path (which returns
    // `Ok(None)` before reaching its own timeout check). Gating on
    // `topology.is_some()` preserves that opt-out for custom providers too. This
    // is idempotent with the built-in factories' own checks (double-guard is
    // safe); the shard-topology dispatch in `resolve_shard_set` applies the same
    // Some-gated guard.
    #[cfg(feature = "sqlite")]
    if topology.is_some() {
        crate::db::reject_sqlite_statement_timeout(config.database.statement_timeout)
            .map_err(|e| format!("Failed to create database pool: {e}"))?;
    }

    // Spawn the directory invalidation listener only at real runtime — a static
    // build must not open control-DB connections.
    let runtime_boot = hook_queue_migration_mode == RepositoryCommitHookQueueMigrationMode::Runtime;
    let shards = match resolve_shard_set(
        config,
        shard_router,
        shard_provider,
        use_directory_router,
        runtime_boot,
        topology.as_ref(),
    )
    .await
    {
        Ok(shards) => shards,
        Err(e) => {
            // The (managed) control topology is already up at this point, so a
            // later setup failure — directory control-pool sizing, shard pool
            // construction — must stop the managed Postgres child before the
            // caller's `process::exit` (which skips `on_shutdown`/`Drop`).
            // No-op when no managed cluster was started.
            #[cfg(feature = "managed-pg")]
            crate::managed_pg::emergency_stop_async().await;
            return Err(e);
        }
    };

    // Skip migrations when the provider opted out of a database (returned
    // `Ok(None)`) — even if `database.url` is configured. Custom providers
    // signal "this app runs without a DB" by returning None; running
    // migrations against the URL anyway would defeat the opt-out.
    //
    // A provider may also resolve its primary URL at runtime (managed Postgres)
    // and carry it on the topology; prefer it so migrations target the pool that
    // was actually built rather than a stale/absent configured URL.
    let provider_migration_url = topology
        .as_ref()
        .and_then(|t| t.migration_url())
        .map(str::to_owned);

    // SQLite sharding guard (issue #1614, PR3): the SQLite startup-migration
    // path now applies registered migrations to a `sqlite://` control target
    // (`run_startup_migrations` routes them through
    // `crate::migrate::auto_migrate_sqlite`), so registered migrations no longer
    // fail fast here. What remains unsupported on SQLite is **sharding** — the
    // directory/shard-map control migrations and per-shard fan-out are
    // Postgres/sharding-specific — so a sqlite control target with sharding
    // enabled fails fast here, as does any `sqlite:` shard `primary_url` (the
    // shard loop routes each shard through the Postgres-only harness). Empty when
    // unsharded or when the shard loop won't run, so the Postgres path is
    // unaffected. See `sqlite_sharding_unsupported_guard`.
    #[cfg(feature = "sqlite")]
    let sqlite_guard_shard_urls: Vec<&str> = if shards.is_some() {
        config
            .database
            .shards
            .iter()
            .map(|shard| shard.primary_url.as_str())
            .collect()
    } else {
        Vec::new()
    };
    #[cfg(feature = "sqlite")]
    #[allow(clippy::question_mark)] // managed-pg child must be stopped before returning
    if let Err(e) = sqlite_sharding_unsupported_guard(
        if topology.is_some() {
            provider_migration_url
                .as_deref()
                .or_else(|| config.database.effective_primary_url())
        } else {
            None
        },
        directory_migration_required
            || shard_map_migration_required
            || config.database.has_shards(),
        &sqlite_guard_shard_urls,
    ) {
        #[cfg(feature = "managed-pg")]
        crate::managed_pg::emergency_stop_async().await;
        return Err(e);
    }

    run_startup_migrations(
        config,
        topology.is_some(),
        shards.is_some(),
        provider_migration_url,
        migrations,
        directory_migration_required,
        shard_map_migration_required,
    )
    .await;

    let (replica_readiness, replica_migration_check) = if topology
        .as_ref()
        .is_some_and(|topology| check_replica_migrations && topology.replica().is_some())
    {
        match (
            config.database.effective_primary_url(),
            config.database.replica_url.as_deref(),
        ) {
            (Some(primary_url), Some(replica_url)) => {
                let primary_url = primary_url.to_owned();
                let replica_url = replica_url.to_owned();
                let readiness = crate::migrate::check_replica_migration_readiness_blocking(
                    primary_url.clone(),
                    replica_url.clone(),
                )
                .await;
                (Some(readiness), Some((primary_url, replica_url)))
            }
            _ => (None, None),
        }
    } else {
        (None, None)
    };

    if check_replica_migrations && let Some(set) = &shards {
        check_shard_replica_migration_parity(config, set).await;
    }

    // Boot-time guard: compare the current auto-split slot map against the map
    // persisted on first boot. Refuses to start if they differ, preventing
    // silent data misrouting from topology changes. Inert during static builds,
    // when no control DB is configured, and in explicit-slot mode.
    #[allow(clippy::question_mark)]
    if let Err(e) = Box::pin(enforce_shard_map_guard(
        config,
        topology.as_ref(),
        runtime_boot,
    ))
    .await
    {
        // Needs explicit `if let` (not `?`) so the managed-pg child can be stopped
        // before unwinding — `?` would skip the cfg-gated emergency stop call.
        #[cfg(feature = "managed-pg")]
        crate::managed_pg::emergency_stop_async().await;
        return Err(e);
    }

    Ok(DatabaseBootstrap {
        topology,
        shards,
        replica_readiness,
        replica_migration_check,
    })
}

/// Apply the embedded migration sets control-first, then to each shard in
/// declaration order, failing fast on the first apply error: a
/// half-migrated fleet that boots is worse than a crashed deploy, and
/// already-migrated targets are idempotently skipped on retry.
///
/// `run_pending_locked` polls with `std::thread::sleep` (up to 60 s under
/// contention), so the whole sequence runs off the Tokio worker threads in
/// one blocking task that owns the embedded migration sets.
/// Apply pending migrations for one target in the `AUTUMN_MIGRATE=1` one-shot,
/// returning the number applied — or exiting non-zero on failure.
///
/// Uses the same locked applier the startup path uses
/// ([`run_pending_locked`](crate::migrate::run_pending_locked)). Failure messages
/// are REDACTED to a value-free reason plus the target label (`control` /
/// `shard:<name>`): the underlying [`MigrationError`](crate::migrate::MigrationError)
/// can wrap a driver string that embeds the connection URL, and the deploy path
/// must never print a DB URL or secret.
#[cfg(feature = "db")]
fn apply_pending_or_exit(
    database_url: &str,
    migrations: &crate::migrate::EmbeddedMigrations,
    target: &str,
) -> usize {
    match crate::migrate::run_pending_locked(
        database_url,
        crate::migrate::EmbeddedMigrationsRef(migrations),
        None,
    ) {
        Ok(result) => result.applied.len(),
        Err(error) => {
            let reason = match error {
                crate::migrate::MigrationError::Connection(_) => {
                    "could not connect to the database"
                }
                crate::migrate::MigrationError::Migration(_) => "a migration failed to apply",
                _ => "migration error",
            };
            eprintln!("autumn migrate: {reason} (target {target})");
            // `process::exit` skips `on_shutdown`/`Drop`; stop any managed
            // Postgres child first so a failure doesn't orphan the data dir/port.
            #[cfg(feature = "managed-pg")]
            crate::managed_pg::emergency_stop();
            std::process::exit(1);
        }
    }
}

/// Apply pending migrations for one `SQLite` target in the `AUTUMN_MIGRATE=1`
/// one-shot, returning the number applied — or exiting non-zero on failure
/// (issue #1614, PR3).
///
/// The `SQLite` counterpart to [`apply_pending_or_exit`]: it uses the unlocked
/// [`run_pending_sqlite`](crate::migrate::run_pending_sqlite) harness (`SQLite`
/// is single-writer, so there is no advisory lock and no cross-process race to
/// serialize) and REDACTS failure messages to a value-free reason plus the
/// target label, exactly like the Postgres path, so a driver string embedding
/// the database path is never printed.
#[cfg(feature = "sqlite")]
fn apply_pending_sqlite_or_exit(
    database_url: &str,
    migrations: &crate::migrate::EmbeddedMigrations,
    target: &str,
) -> usize {
    // Reject ANY in-memory target (private OR shared-cache) with registered
    // migrations up front, BEFORE `run_pending_sqlite` (whose `Migration` error
    // would be redacted to a value-free reason below, hiding the guidance). The
    // migrated schema never survives to the runtime pool — a private `:memory:`
    // connection is its own empty database, and a shared in-memory database is
    // destroyed when its last connection closes (issue #1614 follow-up).
    if let Some(err) = crate::migrate::reject_in_memory_migrations(
        database_url,
        &crate::migrate::EmbeddedMigrationsRef(migrations),
    ) {
        eprintln!("autumn migrate: {err} (target {target})");
        std::process::exit(1);
    }
    match crate::migrate::run_pending_sqlite(
        database_url,
        crate::migrate::EmbeddedMigrationsRef(migrations),
    ) {
        Ok(result) => result.applied.len(),
        Err(error) => {
            let reason = match error {
                crate::migrate::MigrationError::Connection(_) => {
                    "could not connect to the database"
                }
                crate::migrate::MigrationError::Migration(_) => "a migration failed to apply",
                _ => "migration error",
            };
            eprintln!("autumn migrate: {reason} (target {target})");
            std::process::exit(1);
        }
    }
}

/// Guard the startup-migration path against a **sharded** `SQLite` deployment.
///
/// PR3 (#1614) wired a working `SQLite` startup-migration path: registered
/// migrations now apply to a `sqlite://` control target through diesel's
/// `MigrationHarness` on a `SqliteConnection`, with no advisory lock (see
/// [`crate::migrate::run_pending_sqlite`] / [`crate::migrate::auto_migrate_sqlite`],
/// routed from [`run_startup_migrations`]). So registered migrations are no
/// longer rejected here — a `sqlite://` control target with `.migrations(...)`
/// boots and applies its schema.
///
/// What remains unsupported is **sharding on `SQLite`**: the shard-directory and
/// shard-map control tables and the per-shard fan-out are Postgres/sharding
/// primitives (advisory locks, Postgres DDL), and a single-node `SQLite`
/// deployment has no shards. Two situations are therefore rejected here with an
/// actionable message rather than attempting to create Postgres-shaped sharding
/// tables on `SQLite`:
///
///   * a `SQLite` **control** target for which the sharding control migrations
///     are required or shards are configured (`control_sharding_required` —
///     `directory_migration_required || shard_map_migration_required ||
///     config.database.has_shards()`); and
///   * any `SQLite` **shard** `primary_url`: the shard loop in
///     [`run_startup_migrations`] migrates every shard through the Postgres-only
///     harness, so a `sqlite:` shard is sharding-on-`SQLite` regardless of the
///     control backend. `shard_urls` is empty when the app is unsharded or the
///     shard loop won't run, so the Postgres path is unaffected.
///
/// Uses the same [`crate::config::DatabaseBackend::detect`] predicate as
/// `db::build_pool`, so the gate and the pool routing agree on what "is a
/// `SQLite` URL" means.
#[cfg(feature = "sqlite")]
fn sqlite_sharding_unsupported_guard(
    control_url: Option<&str>,
    control_sharding_required: bool,
    shard_urls: &[&str],
) -> Result<(), String> {
    fn is_sqlite(url: &str) -> bool {
        crate::config::DatabaseBackend::detect(url) == Some(crate::config::DatabaseBackend::Sqlite)
    }
    if control_url.is_some_and(is_sqlite) && control_sharding_required {
        return Err(
            "SQLite deployments do not support sharding. The configured sqlite:// control target \
             has sharding enabled (shards and/or the directory/shard-map control migrations), \
             which is a Postgres-only capability \u{2014} remove the shard configuration to run \
             on SQLite, or use a Postgres control database. Tracking: #1614."
                .to_owned(),
        );
    }
    if shard_urls.iter().copied().any(is_sqlite) {
        return Err(
            "SQLite deployments do not support sharding. A configured shard targets a SQLite \
             database, and per-shard migration/fan-out is a Postgres-only capability \u{2014} \
             remove the SQLite shard configuration to run on SQLite, or use Postgres shard \
             targets. Tracking: #1614."
                .to_owned(),
        );
    }
    Ok(())
}

#[cfg(all(test, feature = "sqlite"))]
mod sqlite_sharding_unsupported_guard_tests {
    use super::sqlite_sharding_unsupported_guard;

    #[test]
    fn sqlite_control_target_with_sharding_fails_fast() {
        // PR3: a sqlite:// control URL with sharding enabled must fail fast with
        // an actionable, sharding-named boot error — sharding is Postgres-only.
        for url in [
            "sqlite:///var/lib/app.db",
            "sqlite://./relative.db",
            "sqlite::memory:",
        ] {
            let err = sqlite_sharding_unsupported_guard(Some(url), true, &[])
                .expect_err("sqlite control target + sharding must be rejected");
            assert!(
                err.contains("do not support sharding"),
                "message must name the sharding situation clearly: {err}"
            );
            assert!(
                err.contains("#1614"),
                "message must point at the tracking issue: {err}"
            );
        }
    }

    #[test]
    fn sqlite_control_target_without_sharding_boots() {
        // PR3 behavior: a sqlite target with registered (non-sharding)
        // migrations now boots — they are applied by `auto_migrate_sqlite`.
        for url in [
            "sqlite:///var/lib/app.db",
            "sqlite://./relative.db",
            "sqlite::memory:",
        ] {
            assert!(
                sqlite_sharding_unsupported_guard(Some(url), false, &[]).is_ok(),
                "sqlite target without sharding must boot (migrations now applied): {url}"
            );
        }
    }

    #[test]
    fn postgres_target_is_unchanged() {
        // The default Postgres path is untouched, sharding required or not.
        for url in [
            "postgres://u@h/db",
            "postgresql://user:pass@db:5432/app",
            "host=db user=app sslmode=require",
        ] {
            assert!(
                sqlite_sharding_unsupported_guard(Some(url), true, &[]).is_ok(),
                "postgres target must never be gated: {url}"
            );
            assert!(
                sqlite_sharding_unsupported_guard(Some(url), false, &[]).is_ok(),
                "postgres target must never be gated: {url}"
            );
        }
    }

    #[test]
    fn absent_control_url_boots() {
        // No control URL (no-DB / opt-out provider): nothing to gate.
        assert!(sqlite_sharding_unsupported_guard(None, true, &[]).is_ok());
        assert!(sqlite_sharding_unsupported_guard(None, false, &[]).is_ok());
    }

    #[test]
    fn sqlite_shard_target_fails_fast() {
        // A `sqlite:` shard `primary_url` is sharding-on-SQLite regardless of the
        // control backend and regardless of migrations — the shard loop routes it
        // through the Postgres-only harness. It must be rejected with the
        // actionable sharding error.
        for shards in [
            &["sqlite:///var/lib/shard0.db"][..],
            &["sqlite:///var/lib/shard0.db", "postgres://u@h/shard1"][..],
        ] {
            let err = sqlite_sharding_unsupported_guard(None, false, shards)
                .expect_err("a sqlite shard target must be rejected");
            assert!(
                err.contains("do not support sharding") && err.contains("shard"),
                "message must name the SQLite shard situation clearly: {err}"
            );
            assert!(
                err.contains("#1614"),
                "message must point at the tracking issue: {err}"
            );
        }
    }

    #[test]
    fn postgres_shard_targets_are_unchanged() {
        // All-Postgres shards are never gated, sharding required or not.
        assert!(
            sqlite_sharding_unsupported_guard(
                Some("postgres://u@h/control"),
                true,
                &["postgres://u@h/shard0", "postgres://u@h/shard1"],
            )
            .is_ok(),
            "all-postgres shard targets must never be gated"
        );
    }

    #[test]
    fn migrate_only_mode_reuses_the_boot_guard_for_sqlite_targets() {
        // `run_migrate_only_mode` (the `AUTUMN_MIGRATE=1` one-shot) applies the
        // SAME guard as normal boot BEFORE its migration loop, so the boot and
        // migrate-only paths cannot drift. A sqlite control/shard target with
        // sharding still fails fast; a plain sqlite control target now proceeds
        // (its migrations are applied by the sqlite apply path).

        // A sqlite CONTROL migrate target with sharding → actionable error.
        let err = sqlite_sharding_unsupported_guard(Some("sqlite:///var/lib/app.db"), true, &[])
            .expect_err("sqlite migrate control target with sharding must be rejected");
        assert!(
            err.contains("do not support sharding") && err.contains("#1614"),
            "migrate-only sqlite control error must be the actionable sharding message: {err}"
        );

        // A sqlite SHARD migrate target → actionable error.
        let shard_err = sqlite_sharding_unsupported_guard(
            Some("postgres://u@h/control"),
            true,
            &["sqlite:///var/lib/shard0.db"],
        )
        .expect_err("sqlite migrate shard target must be rejected");
        assert!(
            shard_err.contains("do not support sharding") && shard_err.contains("shard"),
            "migrate-only sqlite shard error must be the actionable sharding message: {shard_err}"
        );

        // An all-Postgres migrate configuration (control + shards) is never gated.
        assert!(
            sqlite_sharding_unsupported_guard(
                Some("postgres://u@h/control"),
                true,
                &["postgres://u@h/shard0"],
            )
            .is_ok(),
            "an all-postgres migrate configuration must proceed unchanged"
        );

        // A plain sqlite migrate control target (no sharding) proceeds — its
        // migrations are applied by the sqlite apply path.
        assert!(
            sqlite_sharding_unsupported_guard(Some("sqlite:///var/lib/app.db"), false, &[]).is_ok(),
            "sqlite control target without sharding must never be gated"
        );
    }
}

#[cfg(feature = "db")]
#[allow(clippy::too_many_arguments, clippy::fn_params_excessive_bools)]
async fn run_startup_migrations(
    config: &AutumnConfig,
    control_configured: bool,
    shards_configured: bool,
    provider_migration_url: Option<String>,
    migrations: Vec<crate::migrate::EmbeddedMigrations>,
    directory_migration_required: bool,
    shard_map_migration_required: bool,
) {
    let control_url = if control_configured {
        // Prefer a provider-resolved URL (e.g. managed Postgres, whose socket
        // URL isn't in config) carried on the topology: the runtime pool is
        // built from it, so embedded startup migrations must target it — even if
        // a stale `database.url`/`primary_url` is still configured (an existing
        // app adopting the provider). Fall back to the configured URL otherwise.
        provider_migration_url
            .or_else(|| config.database.effective_primary_url().map(str::to_owned))
    } else {
        None
    };
    let shard_targets: Vec<(String, String)> = if shards_configured {
        config
            .database
            .shards
            .iter()
            .map(|shard| (format!("shard:{}", shard.name), shard.primary_url.clone()))
            .collect()
    } else {
        Vec::new()
    };
    let profile = config.profile.clone();
    let auto_in_prod = config.database.auto_migrate_in_production;
    let migration_result = tokio::task::spawn_blocking(move || {
        // SQLite single-writer startup-migration path (issue #1614, PR3): apply
        // the registered migrations to a `sqlite://` control target with NO
        // advisory lock. Sharding (directory / shard-map / per-shard fan-out) is
        // Postgres-only and is rejected upstream in `setup_database`
        // (`sqlite_sharding_unsupported_guard`), so there is nothing shard- or
        // directory-related to do on this path — the directory/shard-map framework
        // migrations below are skipped for a SQLite control target. The Postgres
        // path is left byte-identical for every non-SQLite target.
        #[cfg(feature = "sqlite")]
        if let Some(url) = control_url.as_deref()
            && crate::config::DatabaseBackend::detect(url)
                == Some(crate::config::DatabaseBackend::Sqlite)
        {
            for mig in &migrations {
                crate::migrate::auto_migrate_sqlite(
                    url,
                    profile.as_deref(),
                    auto_in_prod,
                    mig,
                    "control",
                );
            }
            return;
        }

        if let Some(url) = control_url {
            for mig in &migrations {
                crate::migrate::auto_migrate(
                    &url,
                    profile.as_deref(),
                    auto_in_prod,
                    mig,
                    "control",
                );
            }
            // The shard directory table lives on the control plane only, so it
            // is applied here and never to the per-shard targets below.
            if directory_migration_required {
                crate::migrate::auto_migrate(
                    &url,
                    profile.as_deref(),
                    auto_in_prod,
                    &crate::sharding::SHARD_DIRECTORY_MIGRATIONS,
                    "control",
                );
            }
            // The shard-map guard table also lives on the control plane only.
            // Always allow auto-applying this framework-internal table: the guard
            // depends on it existing and returns a hard error when it's missing,
            // so skipping the migration in production would block startup.
            if shard_map_migration_required {
                crate::migrate::auto_migrate(
                    &url,
                    profile.as_deref(),
                    true,
                    &crate::sharding::SHARD_MAP_MIGRATIONS,
                    "control",
                );
            }
        }
        // Shards hold tenant data, not the control-plane schema. If the app
        // registered the full control `FRAMEWORK_MIGRATIONS` set (as some
        // examples do), skip it for shard targets — otherwise startup would
        // create the control tables on every shard and (with auto-migrate off)
        // keep reporting them as pending, even though `autumn migrate --shard`
        // applies only the shard-required framework migrations.
        for (target, url) in &shard_targets {
            for mig in migrations
                .iter()
                .filter(|mig| !migration_set_is_control_framework(mig))
            {
                crate::migrate::auto_migrate(url, profile.as_deref(), auto_in_prod, mig, target);
            }
        }
    })
    .await;
    if let Err(e) = migration_result {
        tracing::error!(error = %e, "Migration task panicked");
        // Same orphan hazard as a migration failure: `process::exit` skips
        // `on_shutdown`, so stop any managed Postgres before bailing. We are back
        // on the Tokio runtime here (after the `spawn_blocking` await), so use the
        // async stop — the sync `emergency_stop` would panic nesting a runtime.
        #[cfg(feature = "managed-pg")]
        crate::managed_pg::emergency_stop_async().await;
        std::process::exit(1);
    }
}

/// Per-shard replica migration parity feeds each shard's runtime state
/// (the analogue of `ProbeState`'s control-replica dependency), which
/// gates that shard's replica reads per its `replica_fallback`.
#[cfg(feature = "db")]
async fn check_shard_replica_migration_parity(
    config: &AutumnConfig,
    set: &crate::sharding::ShardSet,
) {
    for (shard_config, shard) in config.database.shards.iter().zip(set.iter()) {
        let Some(replica_url) = shard_config.replica_url.as_deref() else {
            continue;
        };
        // Remember the URLs so the per-shard health indicator can re-run
        // the parity comparison on later readiness probes, and claim the
        // recheck throttle slot for the check that runs right here.
        shard
            .runtime()
            .configure_migration_check(shard_config.primary_url.clone(), replica_url.to_owned());
        let _ = shard.runtime().parity_check_due();
        let readiness = crate::migrate::check_replica_migration_readiness_blocking(
            shard_config.primary_url.clone(),
            replica_url.to_owned(),
        )
        .await;
        if readiness.is_ready() {
            shard.runtime().mark_replica_migrations_ready();
        } else if let Some(detail) = readiness.detail() {
            tracing::warn!(
                shard = %shard.name(),
                detail = %detail,
                "shard replica migrations are not ready"
            );
            shard.runtime().mark_replica_migrations_unready(detail);
        }
    }
}

#[cfg(feature = "db")]
const REPOSITORY_COMMIT_HOOK_QUEUE_MIGRATION: &str =
    "20260515000000_create_repository_commit_hook_queue";

#[cfg(feature = "db")]
const VERSION_HISTORY_MIGRATION: &str = "20260526000000_create_version_history";

/// Whether startup should create the control-plane `_autumn_shard_directory`
/// table. It is required only when directory routing is enabled AND shards are
/// configured AND we are in a real runtime boot — never during a static build
/// (`autumn build`, `AUTUMN_BUILD_STATIC=1`), which renders assets and must not
/// touch the database, mirroring how the other runtime framework migrations are
/// suppressed in [`migrations_with_repository_framework_migrations`].
#[cfg(feature = "db")]
const fn directory_migration_is_required(
    directory_routing_enabled: bool,
    has_shards: bool,
    mode: RepositoryCommitHookQueueMigrationMode,
) -> bool {
    directory_routing_enabled
        && has_shards
        && matches!(mode, RepositoryCommitHookQueueMigrationMode::Runtime)
}

/// Whether startup should create the control-plane `_autumn_shard_map` table.
/// Required whenever shards are configured and we are in a real runtime boot —
/// never during a static build (`autumn build`, `AUTUMN_BUILD_STATIC=1`).
/// The guard itself is further gated to auto-split mode inside
/// `enforce_shard_map_guard`; the table is always created when shards are
/// present so an app can switch from explicit to auto-split later without a
/// manual migration.
#[cfg(feature = "db")]
const fn shard_map_migration_is_required(
    has_shards: bool,
    mode: RepositoryCommitHookQueueMigrationMode,
) -> bool {
    has_shards && matches!(mode, RepositoryCommitHookQueueMigrationMode::Runtime)
}

/// Row type for reading `_autumn_shard_map`.
#[cfg(feature = "db")]
#[derive(diesel::QueryableByName)]
struct ShardMapRow {
    #[diesel(sql_type = diesel::sql_types::Text)]
    shard_name: String,
    #[diesel(sql_type = diesel::sql_types::Text)]
    slots: String,
}

/// Check and persist the shard slot map in `_autumn_shard_map`.
///
/// This is the DB-backed core of the boot-time guard: it reads existing rows,
/// delegates to the pure [`crate::config::check_stored_slot_map`] for the
/// comparison, and persists the map on first boot (no rows yet). Factored out
/// of `enforce_shard_map_guard` so integration tests can drive it directly
/// without a full `AutumnConfig`.
///
/// # Errors
///
/// Returns a `String` error when the computed auto-split map differs from the
/// stored map, indicating a topology change that would silently misroute data.
#[cfg(feature = "db")]
pub async fn run_shard_map_guard(
    control_pool: &deadpool::managed::Pool<
        diesel_async::pooled_connection::AsyncDieselConnectionManager<
            diesel_async::AsyncPgConnection,
        >,
    >,
    computed: &[crate::config::ShardSlotAssignment],
    auto_split: bool,
) -> Result<(), String> {
    use diesel_async::RunQueryDsl as _;

    if !auto_split {
        return Ok(());
    }

    let mut conn = match control_pool.get().await {
        Ok(conn) => conn,
        Err(e) => {
            return Err(format!(
                "shard-map guard could not acquire a control connection: {e} — \
                 ensure the control database is reachable to enforce topology \
                 change detection"
            ));
        }
    };

    let rows: Vec<ShardMapRow> = match diesel::sql_query(
        "SELECT shard_name, slots FROM _autumn_shard_map ORDER BY shard_name",
    )
    .load::<ShardMapRow>(&mut conn)
    .await
    {
        Ok(rows) => rows,
        Err(e) => {
            return Err(format!(
                "shard-map guard could not read _autumn_shard_map: {e} — \
                 run `autumn migrate` to create the control schema before \
                 starting with auto-split shards"
            ));
        }
    };

    let stored: Vec<crate::config::ShardSlotAssignment> = rows
        .into_iter()
        .map(|r| crate::config::ShardSlotAssignment {
            name: r.shard_name,
            ranges: r.slots,
        })
        .collect();
    let stored_opt = if stored.is_empty() {
        None
    } else {
        Some(stored.as_slice())
    };

    crate::config::check_stored_slot_map(auto_split, computed, stored_opt)?;

    // First boot: persist the current map so future boots can compare against it.
    // Wrapped in a transaction so a mid-loop failure leaves no partial rows —
    // partial rows would cause a spurious mismatch error on the next boot attempt.
    if stored.is_empty() {
        use diesel_async::AsyncConnection as _;
        let assignments: Vec<_> = computed.to_vec();
        conn.transaction::<(), diesel::result::Error, _>(async move |conn| {
            for assignment in &assignments {
                diesel::sql_query(
                    "INSERT INTO _autumn_shard_map (shard_name, slots) VALUES ($1, $2) \
                     ON CONFLICT (shard_name) DO UPDATE \
                     SET slots = EXCLUDED.slots, updated_at = NOW()",
                )
                .bind::<diesel::sql_types::Text, _>(&assignment.name)
                .bind::<diesel::sql_types::Text, _>(&assignment.ranges)
                .execute(conn)
                .await?;
            }
            Ok(())
        })
        .await
        .map_err(|e| format!("shard-map guard could not persist map: {e}"))?;
    }

    Ok(())
}

/// Boot-time shard-map guard: compare the auto-split slot map against the
/// persisted map and refuse to start if they differ.
///
/// No-op when:
/// - not a runtime boot (static build),
/// - no shards configured,
/// - no control database topology, or
/// - the slot map uses explicit `slots` declarations (auto-split is inactive).
// Sharding (the shard-map guard, auto-split, and control-DB shard map) is a
// Postgres-only feature: `run_shard_map_guard` drives Postgres `sql_query`
// against a `Pool<AsyncPgConnection>` control pool. Under the `sqlite` feature
// the runtime topology's pool is a SQLite pool that cannot feed it, and SQLite
// deployments are single-node/unsharded, so the guard is a no-op.
#[cfg(all(feature = "db", feature = "sqlite"))]
#[allow(clippy::unused_async)]
async fn enforce_shard_map_guard(
    config: &AutumnConfig,
    topology: Option<&crate::db::DatabaseTopology>,
    runtime_boot: bool,
) -> Result<(), String> {
    let _ = (config, topology, runtime_boot);
    Ok(())
}

#[cfg(all(feature = "db", not(feature = "sqlite")))]
async fn enforce_shard_map_guard(
    config: &AutumnConfig,
    topology: Option<&crate::db::DatabaseTopology>,
    runtime_boot: bool,
) -> Result<(), String> {
    if !runtime_boot || !config.database.has_shards() {
        return Ok(());
    }
    let Some(topology) = topology else {
        return Ok(());
    };
    if !config.database.shards_auto_split() {
        return Ok(());
    }
    let computed = config
        .database
        .resolved_shard_assignments()
        .map_err(|e| format!("shard-map guard: {e}"))?;
    run_shard_map_guard(topology.primary(), &computed, true).await
}

#[cfg(feature = "db")]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum RepositoryCommitHookQueueMigrationMode {
    Runtime,
    StaticBuild,
}

#[cfg(feature = "db")]
fn migrations_with_repository_framework_migrations(
    mut migrations: Vec<crate::migrate::EmbeddedMigrations>,
    hook_queue_required: bool,
    version_history_required: bool,
    mode: RepositoryCommitHookQueueMigrationMode,
) -> Vec<crate::migrate::EmbeddedMigrations> {
    if hook_queue_required
        && mode == RepositoryCommitHookQueueMigrationMode::Runtime
        && !shard_applied_sets_include(&migrations, REPOSITORY_COMMIT_HOOK_QUEUE_MIGRATION)
    {
        migrations.push(crate::repository_commit_hooks::REPOSITORY_COMMIT_HOOK_MIGRATIONS);
    }
    if version_history_required
        && mode == RepositoryCommitHookQueueMigrationMode::Runtime
        && !shard_applied_sets_include(&migrations, VERSION_HISTORY_MIGRATION)
    {
        migrations.push(crate::version_history::VERSION_HISTORY_MIGRATIONS);
    }
    migrations
}

/// Whether `migration_name` is already present in a set that shard targets will
/// actually apply — i.e. a *non*-control-framework set.
///
/// The full control [`FRAMEWORK_MIGRATIONS`](crate::migrate::FRAMEWORK_MIGRATIONS)
/// set is deliberately excluded: `run_startup_migrations` strips it from shard
/// targets, so a migration present *only* inside it never reaches the shards. If
/// de-duplication counted it, a sharded app that registers `FRAMEWORK_MIGRATIONS`
/// (and uses commit hooks / versioning) would skip appending the standalone
/// shard-required set yet have the control set filtered out on shards — leaving
/// shards without `_autumn_repository_commit_hook_queue` / `_autumn_version_history`.
/// Matching only shard-applied sets ensures the standalone set is appended
/// whenever the shards would otherwise be missing it. Re-applying it to the
/// control target is harmless: it shares the migration version already recorded
/// by the control framework set, so Diesel skips it there.
#[cfg(feature = "db")]
fn shard_applied_sets_include(
    migrations: &[crate::migrate::EmbeddedMigrations],
    migration_name: &str,
) -> bool {
    use diesel::migration::{Migration, MigrationSource as _};
    use diesel::pg::Pg;

    migrations
        .iter()
        .filter(|set| !migration_set_is_control_framework(set))
        .any(|source| {
            let Ok(source_migrations): Result<Vec<Box<dyn Migration<Pg>>>, _> = source.migrations()
            else {
                return false;
            };

            source_migrations
                .iter()
                .any(|migration| migration.name().to_string() == migration_name)
        })
}

/// Whether a migration set is the control-plane
/// [`FRAMEWORK_MIGRATIONS`](crate::migrate::FRAMEWORK_MIGRATIONS), so it can be
/// skipped on shard targets.
///
/// Identified by containing a *control-only* migration — one in
/// `FRAMEWORK_MIGRATIONS` but not in the shard-required version-history /
/// commit-hook sets. Those two sets' migrations are duplicated into the control
/// `migrations/` directory, so a plain name overlap would also (wrongly) match
/// the standalone `VERSION_HISTORY_MIGRATIONS` / `REPOSITORY_COMMIT_HOOK_MIGRATIONS`
/// sets and strip them from shards.
#[cfg(feature = "db")]
fn migration_set_is_control_framework(set: &crate::migrate::EmbeddedMigrations) -> bool {
    use diesel::migration::{Migration, MigrationSource as _};
    use diesel::pg::Pg;

    fn names(set: &crate::migrate::EmbeddedMigrations) -> std::collections::HashSet<String> {
        let migrations: Vec<Box<dyn Migration<Pg>>> = set.migrations().unwrap_or_default();
        migrations.iter().map(|m| m.name().to_string()).collect()
    }

    let mut control_only = names(&crate::migrate::FRAMEWORK_MIGRATIONS);
    for shard_required in [
        &crate::version_history::VERSION_HISTORY_MIGRATIONS,
        &crate::repository_commit_hooks::REPOSITORY_COMMIT_HOOK_MIGRATIONS,
    ] {
        for name in names(shard_required) {
            control_only.remove(&name);
        }
    }

    names(set).iter().any(|name| control_only.contains(name))
}

#[cfg(feature = "db")]
fn apply_replica_migration_readiness(
    state: &AppState,
    readiness: Option<crate::migrate::ReplicaMigrationReadiness>,
) {
    let Some(readiness) = readiness else {
        return;
    };

    if readiness.is_ready() {
        state.probes().mark_replica_migrations_ready();
    } else if let Some(detail) = readiness.detail() {
        state.probes().mark_replica_migrations_unready(detail);
    }
}

#[cfg(feature = "db")]
fn configure_replica_migration_check(state: &AppState, check: Option<(String, String)>) {
    let Some((primary_url, replica_url)) = check else {
        return;
    };

    state
        .probes()
        .configure_replica_migration_check(primary_url, replica_url);
}

/// Refuse to start when a `#[repository(api = ...)]`-mounted route
/// has no paired `policy = ...` argument in `prod` profile builds.
///
/// The issue text spells out the rationale: silently shipping
/// auto-generated CRUD endpoints with no record-level authz is a
/// security regression. The escape hatch is
/// `[security] allow_unauthorized_repository_api = true`.
/// Pure offender-collection logic for
/// [`validate_repository_api_policies`].
///
/// Walks both top-level routes and routes registered under
/// `.scoped(prefix, layer, routes)` groups, returning every
/// `#[repository(api = ...)]`-mounted *mutating* route that has no
/// paired `policy = ...` argument. Read-only mounts (GET
/// `*_api_list` / `*_api_get`) are intentionally excluded — they
/// don't fit the "any authenticated user can write to any record"
/// footgun the issue calls out. Read-leak concerns are handled
/// separately by `scope = ...`.
///
/// Returned in (resource type name, api path) form, deduped per
/// `(type, path)` pair so a repository with multiple unguarded
/// methods only shows up once.
fn collect_unguarded_repository_writes(
    routes: &[Route],
    scoped_groups: &[ScopedGroup],
) -> Vec<(String, String)> {
    let mut offenders: Vec<(String, String)> = Vec::new();
    let mut seen: std::collections::HashSet<(&'static str, &'static str)> =
        std::collections::HashSet::new();
    let mut record_route = |route: &Route| {
        if let Some(meta) = route.repository
            && !meta.has_policy
            && is_mutating_method(&route.method)
            && seen.insert((meta.resource_type_name, meta.api_path))
        {
            offenders.push((meta.resource_type_name.to_owned(), meta.api_path.to_owned()));
        }
    };
    for route in routes {
        record_route(route);
    }
    for group in scoped_groups {
        for route in &group.routes {
            record_route(route);
        }
    }
    offenders
}

/// Format a list of `(type, path)` offenders into the bulleted
/// listing the startup tracing emits. Pure so the format string
/// can be unit-tested without going through `tracing` machinery.
fn format_unguarded_repository_listing(offenders: &[(String, String)]) -> String {
    use std::fmt::Write;
    let mut s = String::new();
    let mut first = true;
    for (name, path) in offenders {
        if !first {
            s.push('\n');
        }
        first = false;
        write!(s, "  - #[repository({name}, api = \"{path}\")]").unwrap();
    }
    s
}

fn validate_repository_api_policies(
    routes: &[Route],
    scoped_groups: &[ScopedGroup],
    config: &AutumnConfig,
) {
    let profile = config.profile.as_deref().unwrap_or("default");
    let strict =
        is_production_profile(profile) && !config.security.allow_unauthorized_repository_api;

    let offenders = collect_unguarded_repository_writes(routes, scoped_groups);
    if offenders.is_empty() {
        return;
    }

    let listing = format_unguarded_repository_listing(&offenders);

    if strict {
        tracing::error!(
            "refusing to start: the following #[repository(api = ...)] mutating endpoints have no paired `policy = ...` argument:\n{listing}\n\
             Add `policy = SomePolicy` to each, or set `[security] allow_unauthorized_repository_api = true` to opt out explicitly."
        );
        std::process::exit(1);
    } else {
        tracing::warn!(
            "the following #[repository(api = ...)] mutating endpoints have no paired `policy = ...` argument; \
             auto-generated POST/PUT/PATCH/DELETE handlers will accept writes from any authenticated user:\n{listing}\n\
             This will become a startup-time error in `prod` profile builds."
        );
    }
}

/// Refuse to start when a `#[repository(policy = X)]`-annotated
/// route exists but the corresponding `.policy::<R, _>(X)`
/// registration was never actually applied to the live
/// [`PolicyRegistry`](crate::authorization::PolicyRegistry).
///
/// `validate_repository_api_policies` runs *before* the registry is
/// populated and only checks the macro-set `has_policy` flag. This
/// runs *after* registrations are applied and walks the same routes,
/// invoking the macro-emitted `policy_check` probe to confirm the
/// policy is really there. Without this, forgetting the
/// `.policy::<R, _>(...)` builder call would compile, boot, and
/// then 500 on every protected request.
/// `(resource_type_name, api_path)` pair identifying a repository
/// route that's missing its required runtime registration.
type MissingRepositoryRegistration = (String, String);

/// Pure offender-collection logic for
/// [`validate_repository_policies_registered`].
///
/// Walks the same routes + scoped groups and invokes the macro-
/// emitted `policy_check` / `scope_check` probes against the live
/// registry, returning `(missing_policies, missing_scopes)` deduped
/// per `(type, path)` pair. Pure so the listing logic can be unit-
/// tested without going through the actual `tracing::error!` +
/// `std::process::exit(1)` strict path.
fn collect_unregistered_repository_handlers(
    routes: &[Route],
    scoped_groups: &[ScopedGroup],
    registry: &crate::authorization::PolicyRegistry,
) -> (
    Vec<MissingRepositoryRegistration>,
    Vec<MissingRepositoryRegistration>,
) {
    let mut missing_policies: Vec<(String, String)> = Vec::new();
    let mut missing_scopes: Vec<(String, String)> = Vec::new();
    let mut seen_policies: std::collections::HashSet<(&'static str, &'static str)> =
        std::collections::HashSet::new();
    let mut seen_scopes: std::collections::HashSet<(&'static str, &'static str)> =
        std::collections::HashSet::new();
    let mut record_route = |route: &Route| {
        if let Some(meta) = route.repository {
            if let Some(check) = meta.policy_check
                && !check(registry)
                && seen_policies.insert((meta.resource_type_name, meta.api_path))
            {
                missing_policies
                    .push((meta.resource_type_name.to_owned(), meta.api_path.to_owned()));
            }
            if let Some(check) = meta.scope_check
                && !check(registry)
                && seen_scopes.insert((meta.resource_type_name, meta.api_path))
            {
                missing_scopes.push((meta.resource_type_name.to_owned(), meta.api_path.to_owned()));
            }
        }
    };
    for route in routes {
        record_route(route);
    }
    for group in scoped_groups {
        for route in &group.routes {
            record_route(route);
        }
    }
    (missing_policies, missing_scopes)
}

/// Format a `(type, path)` listing for missing-policy startup
/// errors. Pure so the format string can be unit-tested.
fn format_missing_policy_listing(missing: &[(String, String)]) -> String {
    use std::fmt::Write;
    let mut s = String::new();
    let mut first = true;
    for (name, path) in missing {
        if !first {
            s.push('\n');
        }
        first = false;
        write!(s, "  - #[repository({name}, api = \"{path}\", policy = ...)]: call `.policy::<{name}, _>(...)` on the app builder").unwrap();
    }
    s
}

/// Format a `(type, path)` listing for missing-scope startup
/// errors. Pure so the format string can be unit-tested.
fn format_missing_scope_listing(missing: &[(String, String)]) -> String {
    use std::fmt::Write;
    let mut s = String::new();
    let mut first = true;
    for (name, path) in missing {
        if !first {
            s.push('\n');
        }
        first = false;
        write!(s, "  - #[repository({name}, api = \"{path}\", scope = ...)]: call `.scope::<{name}, _>(...)` on the app builder").unwrap();
    }
    s
}

#[allow(clippy::cognitive_complexity)]
fn validate_repository_policies_registered(
    routes: &[Route],
    scoped_groups: &[ScopedGroup],
    state: &AppState,
    config: &AutumnConfig,
) {
    let profile = config.profile.as_deref().unwrap_or("default");
    let strict = is_production_profile(profile);

    let (missing_policies, missing_scopes) =
        collect_unregistered_repository_handlers(routes, scoped_groups, state.policy_registry());

    if missing_policies.is_empty() && missing_scopes.is_empty() {
        return;
    }

    if !missing_policies.is_empty() {
        let listing = format_missing_policy_listing(&missing_policies);

        if strict {
            tracing::error!(
                "refusing to start: the following #[repository] routes declare a `policy = ...` argument, but no policy is registered for the resource type. Without registration, every protected request would fail at runtime with `500 no policy registered`:\n{listing}"
            );
        } else {
            tracing::warn!(
                "the following #[repository] routes declare `policy = ...` but no matching `.policy::<R, _>(...)` registration is on the app builder. Protected requests will 500 at runtime:\n{listing}\n\
                 This will become a startup-time error in `prod` profile builds."
            );
        }
    }

    if !missing_scopes.is_empty() {
        let listing = format_missing_scope_listing(&missing_scopes);

        if strict {
            tracing::error!(
                "refusing to start: the following #[repository] routes declare a `scope = ...` argument, but no scope is registered for the resource type. Without registration, every list request would fail at runtime with `500 missing scope registration`:\n{listing}"
            );
        } else {
            tracing::warn!(
                "the following #[repository] routes declare `scope = ...` but no matching `.scope::<R, _>(...)` registration is on the app builder. List requests will 500 at runtime:\n{listing}\n\
                 This will become a startup-time error in `prod` profile builds."
            );
        }
    }

    if strict {
        std::process::exit(1);
    }
}

const fn is_mutating_method(method: &http::Method) -> bool {
    matches!(
        *method,
        http::Method::POST | http::Method::PUT | http::Method::PATCH | http::Method::DELETE
    )
}

/// Returns `true` for the framework's accepted production profile
/// names. Mirrors the `prod | production` matching used elsewhere
/// (`app.rs::run_build_mode`, `migrate.rs::should_auto_apply`,
/// etc.) so the repository startup guards don't silently weaken in
/// deployments that pick the long-form alias.
fn is_production_profile(profile: &str) -> bool {
    matches!(profile, "prod" | "production")
}

#[cfg(test)]
mod validate_repository_api_policies_tests {
    use super::*;
    use crate::RepositoryApiMeta;

    fn build_route(
        method: http::Method,
        path: &'static str,
        meta: Option<RepositoryApiMeta>,
    ) -> Route {
        Route {
            method,
            path,
            handler: axum::routing::any(|| async { "" }),
            name: "test_route",
            api_doc: crate::openapi::ApiDoc::default(),
            repository: meta,
            idempotency: crate::route::RouteIdempotency::Direct,
            timeout: crate::route::RouteTimeout::Inherit,
            api_version: None,
            sunset_opt_out: false,
        }
    }

    fn unguarded(path: &'static str, type_name: &'static str) -> RepositoryApiMeta {
        RepositoryApiMeta {
            resource_type_name: type_name,
            api_path: path,
            has_policy: false,
            policy_check: None,
            scope_check: None,
        }
    }

    /// Tests in this module historically used a duplicated copy of
    /// the offender-collection logic. Now they call the production
    /// helper directly so coverage tracks the real code path.
    fn collect_offenders(routes: &[Route]) -> Vec<(String, String)> {
        collect_unguarded_repository_writes(routes, &[])
    }

    #[test]
    fn read_only_mount_without_policy_is_not_an_offender() {
        let routes = vec![
            build_route(
                http::Method::GET,
                "/api/posts",
                Some(unguarded("/api/posts", "Post")),
            ),
            build_route(
                http::Method::GET,
                "/api/posts/{id}",
                Some(unguarded("/api/posts", "Post")),
            ),
        ];
        let offenders = collect_offenders(&routes);
        assert!(
            offenders.is_empty(),
            "read-only mounts should not trigger the unauthorized-repo guard"
        );
    }

    #[test]
    fn write_mount_without_policy_is_an_offender() {
        let routes = vec![build_route(
            http::Method::POST,
            "/api/posts",
            Some(unguarded("/api/posts", "Post")),
        )];
        let offenders = collect_offenders(&routes);
        assert_eq!(offenders.len(), 1);
        assert_eq!(offenders[0].0, "Post");
        assert_eq!(offenders[0].1, "/api/posts");
    }

    #[test]
    fn mixed_mount_only_dedups_one_offender_per_repository() {
        let routes = vec![
            build_route(
                http::Method::GET,
                "/api/posts",
                Some(unguarded("/api/posts", "Post")),
            ),
            build_route(
                http::Method::POST,
                "/api/posts",
                Some(unguarded("/api/posts", "Post")),
            ),
            build_route(
                http::Method::PUT,
                "/api/posts/{id}",
                Some(unguarded("/api/posts", "Post")),
            ),
            build_route(
                http::Method::DELETE,
                "/api/posts/{id}",
                Some(unguarded("/api/posts", "Post")),
            ),
        ];
        let offenders = collect_offenders(&routes);
        assert_eq!(offenders.len(), 1);
    }

    #[test]
    fn is_mutating_method_classifies_methods() {
        assert!(is_mutating_method(&http::Method::POST));
        assert!(is_mutating_method(&http::Method::PUT));
        assert!(is_mutating_method(&http::Method::PATCH));
        assert!(is_mutating_method(&http::Method::DELETE));
        assert!(!is_mutating_method(&http::Method::GET));
        assert!(!is_mutating_method(&http::Method::HEAD));
        assert!(!is_mutating_method(&http::Method::OPTIONS));
    }

    // ── registry-aware validation (post-registration) ─────────────

    use crate::authorization::{Policy, PolicyRegistry};

    #[derive(Debug, Clone, PartialEq)]
    struct TestPost;

    #[derive(Default)]
    struct TestPostPolicy;
    impl Policy<TestPost> for TestPostPolicy {}

    fn guarded_with_check(path: &'static str, type_name: &'static str) -> RepositoryApiMeta {
        RepositoryApiMeta {
            resource_type_name: type_name,
            api_path: path,
            has_policy: true,
            policy_check: Some(|registry: &PolicyRegistry| registry.has_policy::<TestPost>()),
            scope_check: None,
        }
    }

    fn collect_missing(routes: &[Route], registry: &PolicyRegistry) -> Vec<(String, String)> {
        let (missing_policies, _) = collect_unregistered_repository_handlers(routes, &[], registry);
        missing_policies
    }

    #[test]
    fn registry_check_flags_routes_missing_their_policy_registration() {
        // Macro emits `policy = X` but no `.policy::<TestPost, _>(...)`
        // call on the builder — registry has nothing.
        let registry = PolicyRegistry::default();
        let routes = vec![build_route(
            http::Method::POST,
            "/api/posts",
            Some(guarded_with_check("/api/posts", "TestPost")),
        )];
        let missing = collect_missing(&routes, &registry);
        assert_eq!(missing.len(), 1);
        assert_eq!(missing[0].0, "TestPost");
        assert_eq!(missing[0].1, "/api/posts");
    }

    #[test]
    fn registry_check_passes_when_policy_is_registered() {
        let registry = PolicyRegistry::default();
        registry.register_policy::<TestPost, _>(TestPostPolicy);
        let routes = vec![build_route(
            http::Method::POST,
            "/api/posts",
            Some(guarded_with_check("/api/posts", "TestPost")),
        )];
        let missing = collect_missing(&routes, &registry);
        assert!(missing.is_empty(), "policy is registered, no offenders");
    }

    #[test]
    fn registry_check_skips_routes_without_policy_check_fn() {
        // Routes mounted without `policy = ...` carry
        // `policy_check: None` and are not subject to this check —
        // they're handled by `validate_repository_api_policies` which
        // looks at `has_policy` instead.
        let registry = PolicyRegistry::default();
        let routes = vec![build_route(
            http::Method::POST,
            "/api/posts",
            Some(unguarded("/api/posts", "TestPost")),
        )];
        let missing = collect_missing(&routes, &registry);
        assert!(missing.is_empty());
    }

    #[test]
    fn registry_check_dedups_one_offender_per_repository() {
        let registry = PolicyRegistry::default();
        let routes = vec![
            build_route(
                http::Method::GET,
                "/api/posts",
                Some(guarded_with_check("/api/posts", "TestPost")),
            ),
            build_route(
                http::Method::POST,
                "/api/posts",
                Some(guarded_with_check("/api/posts", "TestPost")),
            ),
            build_route(
                http::Method::DELETE,
                "/api/posts/{id}",
                Some(guarded_with_check("/api/posts", "TestPost")),
            ),
        ];
        let missing = collect_missing(&routes, &registry);
        assert_eq!(missing.len(), 1);
    }

    // ── Scope registration validation ─────────────────────────────

    use crate::authorization::{BoxFuture, PolicyContext, Scope};

    #[derive(Default)]
    struct TestPostScope;
    impl Scope<TestPost> for TestPostScope {
        fn list<'a>(
            &'a self,
            _ctx: &'a PolicyContext,
            _conn: &'a mut crate::db::RuntimeConnection,
        ) -> BoxFuture<'a, crate::AutumnResult<Vec<TestPost>>> {
            Box::pin(async { Ok(Vec::new()) })
        }
    }

    fn scope_only_meta(path: &'static str, type_name: &'static str) -> RepositoryApiMeta {
        RepositoryApiMeta {
            resource_type_name: type_name,
            api_path: path,
            has_policy: false,
            policy_check: None,
            scope_check: Some(|registry: &PolicyRegistry| registry.scope::<TestPost>().is_some()),
        }
    }

    fn collect_missing_scopes(
        routes: &[Route],
        registry: &PolicyRegistry,
    ) -> Vec<(String, String)> {
        let (_, missing_scopes) = collect_unregistered_repository_handlers(routes, &[], registry);
        missing_scopes
    }

    #[test]
    fn scope_check_flags_unregistered_scope() {
        let registry = PolicyRegistry::default();
        let routes = vec![build_route(
            http::Method::GET,
            "/api/posts",
            Some(scope_only_meta("/api/posts", "TestPost")),
        )];
        let missing = collect_missing_scopes(&routes, &registry);
        assert_eq!(missing.len(), 1);
        assert_eq!(missing[0].0, "TestPost");
    }

    #[test]
    fn scope_check_passes_when_scope_is_registered() {
        let registry = PolicyRegistry::default();
        registry.register_scope::<TestPost, _>(TestPostScope);
        let routes = vec![build_route(
            http::Method::GET,
            "/api/posts",
            Some(scope_only_meta("/api/posts", "TestPost")),
        )];
        let missing = collect_missing_scopes(&routes, &registry);
        assert!(missing.is_empty());
    }

    #[test]
    fn scope_check_skips_routes_without_scope_check_fn() {
        let registry = PolicyRegistry::default();
        let routes = vec![build_route(
            http::Method::POST,
            "/api/posts",
            Some(unguarded("/api/posts", "TestPost")),
        )];
        let missing = collect_missing_scopes(&routes, &registry);
        assert!(missing.is_empty());
    }

    // ── prod / production profile parity ────────────────────────

    #[test]
    fn is_production_profile_matches_both_aliases() {
        assert!(is_production_profile("prod"));
        assert!(is_production_profile("production"));
        assert!(!is_production_profile("dev"));
        assert!(!is_production_profile("staging"));
        assert!(!is_production_profile("test"));
        assert!(!is_production_profile("default"));
        // Case-sensitive (matches the framework's elsewhere
        // matching pattern in app.rs::run_build_mode and
        // migrate.rs).
        assert!(!is_production_profile("Prod"));
        assert!(!is_production_profile("Production"));
    }

    // ── Formatter helpers ─────────────────────────────────────────

    #[test]
    fn format_unguarded_listing_renders_one_bullet_per_offender() {
        let offenders = vec![
            ("Post".to_owned(), "/api/posts".to_owned()),
            ("Comment".to_owned(), "/api/comments".to_owned()),
        ];
        let listing = format_unguarded_repository_listing(&offenders);
        assert!(listing.contains("Post"));
        assert!(listing.contains("/api/posts"));
        assert!(listing.contains("Comment"));
        assert!(listing.contains("/api/comments"));
        assert_eq!(listing.matches("\n  - ").count() + 1, 2);
    }

    #[test]
    fn format_unguarded_listing_empty_input_yields_empty_string() {
        let listing = format_unguarded_repository_listing(&[]);
        assert!(listing.is_empty());
    }

    #[test]
    fn format_missing_policy_listing_includes_policy_call_hint() {
        let missing = vec![("Post".to_owned(), "/api/posts".to_owned())];
        let listing = format_missing_policy_listing(&missing);
        assert!(listing.contains("Post"));
        assert!(listing.contains("/api/posts"));
        assert!(listing.contains(".policy::<Post, _>"));
        assert!(listing.contains("policy = ..."));
    }

    #[test]
    fn format_missing_scope_listing_includes_scope_call_hint() {
        let missing = vec![("Post".to_owned(), "/api/posts".to_owned())];
        let listing = format_missing_scope_listing(&missing);
        assert!(listing.contains("Post"));
        assert!(listing.contains("/api/posts"));
        assert!(listing.contains(".scope::<Post, _>"));
        assert!(listing.contains("scope = ..."));
    }

    // ── Scoped-groups path coverage ──────────────────────────────

    #[test]
    fn collect_unguarded_walks_scoped_groups() {
        // The scoped-group path catches `#[repository(api = ...)]`
        // mounts that live inside `.scoped(prefix, layer, routes)`.
        // Without walking them, the prod-mode guard would silently
        // miss those routes.
        let group_route = build_route(
            http::Method::POST,
            "/api/posts",
            Some(unguarded("/api/posts", "Post")),
        );
        let group = ScopedGroup {
            prefix: "/scoped".to_owned(),
            routes: vec![group_route],
            source: crate::route_listing::RouteSource::User,
            apply_layer: Box::new(|r| r),
        };
        let offenders = collect_unguarded_repository_writes(&[], std::slice::from_ref(&group));
        assert_eq!(offenders.len(), 1);
        assert_eq!(offenders[0].0, "Post");
    }

    #[test]
    fn collect_unregistered_walks_scoped_groups() {
        let group_route = build_route(
            http::Method::POST,
            "/api/posts",
            Some(guarded_with_check("/api/posts", "TestPost")),
        );
        let group = ScopedGroup {
            prefix: "/scoped".to_owned(),
            routes: vec![group_route],
            source: crate::route_listing::RouteSource::User,
            apply_layer: Box::new(|r| r),
        };
        let registry = PolicyRegistry::default();
        let (missing, _) =
            collect_unregistered_repository_handlers(&[], std::slice::from_ref(&group), &registry);
        assert_eq!(missing.len(), 1);
        assert_eq!(missing[0].0, "TestPost");
    }
}

/// Publish the builder's story gallery (if any) as the [`StoryRegistry`]
/// (`crate::stories::StoryRegistry`) `AppState` extension read by the
/// `/_stories` handlers. Shared by the `run()` and build/SSG
/// state-construction paths so the two stay in lockstep.
#[cfg(feature = "maud")]
fn install_story_registry(state: &AppState, story_gallery: Option<crate::stories::StoryGallery>) {
    if let Some(gallery) = story_gallery {
        state.insert_extension(gallery.into_registry());
    }
}

fn build_state(
    config: &AutumnConfig,
    #[cfg(feature = "db")] database_topology: Option<&crate::db::DatabaseTopology>,
    #[cfg(feature = "db")] shards: Option<crate::sharding::ShardSet>,
    #[cfg(feature = "ws")] channels_backend: Option<Arc<dyn crate::channels::ChannelsBackend>>,
) -> AppState {
    #[cfg(feature = "ws")]
    let shutdown = tokio_util::sync::CancellationToken::new();
    #[cfg(feature = "ws")]
    let channels = channels_backend.map_or_else(
        || {
            crate::channels::Channels::from_config(&config.channels, shutdown.child_token())
                .unwrap_or_else(|error| {
                    tracing::error!(error = %error, "Failed to configure channels backend");
                    std::process::exit(1);
                })
        },
        crate::channels::Channels::with_shared_backend,
    );

    let state = AppState {
        extensions: std::sync::Arc::new(std::sync::RwLock::new(std::collections::HashMap::new())),
        #[cfg(feature = "db")]
        pool: database_topology.map(|topology| topology.primary().clone()),
        #[cfg(feature = "db")]
        replica_pool: database_topology.and_then(|topology| topology.replica().cloned()),
        #[cfg(feature = "db")]
        shards,
        profile: config.profile.clone(),
        role: config.role,
        started_at: std::time::Instant::now(),
        health_detailed: config.health.detailed,
        probes: crate::probe::ProbeState::pending_startup(),
        metrics: crate::middleware::MetricsCollector::new(),
        log_levels: crate::actuator::LogLevels::new(&config.log.level),
        task_registry: crate::actuator::TaskRegistry::new(),
        job_registry: crate::actuator::JobRegistry::new(),
        config_props: crate::actuator::ConfigProperties::from_config(config),
        metrics_source_registry: crate::actuator::MetricsSourceRegistry::new(),
        health_indicator_registry: crate::actuator::HealthIndicatorRegistry::new(),
        #[cfg(feature = "presence")]
        presence: crate::presence::Presence::new(channels.clone()),
        #[cfg(feature = "ws")]
        channels,
        #[cfg(feature = "ws")]
        shutdown,
        policy_registry: crate::authorization::PolicyRegistry::default(),
        forbidden_response: config.security.forbidden_response,
        auth_session_key: config.auth.session_key.clone(),
        shared_cache: None,
        clock: std::sync::Arc::new(crate::time::SystemClock),
        app_id: AppState::next_app_id(),
    };
    #[cfg(feature = "db")]
    if state.replica_pool.is_some() {
        state
            .probes()
            .configure_replica_dependency(config.database.replica_fallback);
    }
    // Surface every shard in /ready and /actuator/health as a
    // `db:shard:<name>` component (replica readiness refresh + pool stats).
    #[cfg(feature = "db")]
    if let Some(set) = state.shards() {
        crate::sharding::register_shard_health_indicators(set, &state.health_indicator_registry);
    }
    state.insert_extension(config.clone());
    state.insert_extension(crate::step_up::StepUpGlobalConfig {
        default_max_age_secs: config.auth.step_up.default_max_age_secs,
    });
    #[cfg(feature = "http-client")]
    state.insert_extension(crate::http_client::SharedReqwestClient {
        client: crate::http_client::Client::build_inner(&config.http.client),
        timeout_secs: config.http.client.timeout_secs,
    });
    state
}

/// Build the route listing string for the transparency log.
fn format_route_lines(
    routes: &[Route],
    scoped_groups: &[ScopedGroup],
    config: &AutumnConfig,
) -> String {
    use std::fmt::Write as _;

    let mut out = String::new();
    for route in routes {
        let _ = write!(
            out,
            "\n    {} {:<8} -> {}",
            route.path, route.method, route.name
        );
    }
    for group in scoped_groups {
        for route in &group.routes {
            let _ = write!(
                out,
                "\n    {}{} {:<8} -> {} (scoped)",
                group.prefix, route.path, route.method, route.name
            );
        }
    }
    let mut probe_paths = std::collections::HashSet::new();
    for (path, name) in [
        (config.health.live_path.as_str(), "live"),
        (config.health.ready_path.as_str(), "ready"),
        (config.health.startup_path.as_str(), "startup"),
        (config.health.path.as_str(), "health"),
    ] {
        if probe_paths.insert(path) {
            let _ = write!(out, "\n    {} {:<8} -> {}", path, "GET", name);
        }
    }
    let _ = write!(
        out,
        "\n    {} {:<8} -> actuator",
        crate::actuator::actuator_route_glob(&config.actuator.prefix),
        "GET"
    );
    #[cfg(feature = "htmx")]
    {
        out.push_str("\n    /static/js/htmx.min.js GET -> htmx");
        out.push_str("\n    /static/js/autumn-htmx-csrf.js GET -> htmx csrf");
    }
    out
}

/// Build the scheduled task listing string. Returns `None` if there are no tasks.
fn format_task_lines(tasks: &[crate::task::TaskInfo]) -> Option<String> {
    use std::fmt::Write as _;

    if tasks.is_empty() {
        return None;
    }

    let mut out = String::new();
    for task in tasks {
        let schedule = task.schedule.to_string();
        let _ = write!(out, "\n    {} ({schedule})", task.name);
    }
    Some(out)
}

/// Build the active middleware listing string.
fn format_middleware_list(config: &AutumnConfig) -> String {
    let mut items = vec![
        "RequestId",
        "SecurityHeaders",
        "Session (in-memory)",
        "ErrorPages",
    ];
    if !config.cors.allowed_origins.is_empty() {
        items.push("CORS");
    }
    if config.security.csrf.enabled {
        items.push("CSRF");
    }
    items.push("Metrics");
    items.join(", ")
}

/// Mask a database URL password for safe logging.
fn mask_database_url(url: &str, pool_size: usize) -> String {
    if let Ok(mut parsed_url) = url::Url::parse(url) {
        if parsed_url.password().is_some() {
            let _ = parsed_url.set_password(Some("****"));
            return format!("{parsed_url} (pool_size={pool_size})");
        }
        format!("{parsed_url} (pool_size={pool_size})")
    } else {
        // Fallback: If URL parsing fails, mask the entire URL string to prevent any
        // potential data exposure (e.g. if the malformed string still contained a password)
        format!("**** (pool_size={pool_size})")
    }
}

/// Build the configuration summary string.
fn format_config_summary(config: &AutumnConfig) -> String {
    let profile = config.profile.as_deref().unwrap_or("none");
    let db_status = config.database.effective_primary_url().map_or_else(
        || "not configured".to_owned(),
        |url| {
            let primary = mask_database_url(url, config.database.effective_primary_pool_size());
            if config.database.replica_url.is_some() {
                format!(
                    "primary={primary}, replica=configured (pool_size={})",
                    config.database.effective_replica_pool_size()
                )
            } else {
                primary
            }
        },
    );
    let telemetry_status = if config.telemetry.enabled {
        let endpoint = config
            .telemetry
            .otlp_endpoint
            .as_deref()
            .unwrap_or("<missing endpoint>");
        format!("{:?} -> {endpoint}", config.telemetry.protocol)
    } else {
        "disabled".to_owned()
    };
    format!(
        "\
        \n    profile:    {profile}\
        \n    server:     {}:{}\
        \n    database:   {db_status}\
        \n    log_level:  {}\
        \n    log_format: {:?}\
        \n    telemetry:  {telemetry_status}\
        \n    health:     {} (detailed={})\
        \n    actuator:   sensitive={}\
        \n    shutdown:   prestop={}s drain={}s",
        config.server.host,
        config.server.port,
        config.log.level,
        config.log.format,
        config.health.path,
        config.health.detailed,
        config.actuator.sensitive,
        config.server.prestop_grace_secs,
        config.server.shutdown_timeout_secs,
    )
}

/// Resolve a project-relative subdirectory (e.g. `"dist"` or `"static"`)
/// against `AUTUMN_MANIFEST_DIR` if set, otherwise use it as-is.
pub(crate) fn project_dir(subdir: &str, env: &dyn crate::config::Env) -> std::path::PathBuf {
    env.var("AUTUMN_MANIFEST_DIR").map_or_else(
        |_| std::path::PathBuf::from(subdir),
        |d| std::path::PathBuf::from(d).join(subdir),
    )
}

/// Wait for a shutdown signal (Ctrl+C, SIGTERM on Unix, or a canary rollback
/// flag file written by a controller).
///
/// Returns when any signal is received. Axum's `with_graceful_shutdown`
/// then stops accepting new connections and drains in-flight requests.
///
/// The canary rollback arm lets a progressive-delivery controller drain and
/// retire a bad canary replica without sending `SIGTERM` by hand: it writes
/// [`crate::canary::CANARY_ROLLBACK_FLAG_FILE`] and Autumn runs the identical
/// graceful-shutdown sequence (ready → 503, prestop grace, drain, clean exit).
async fn shutdown_signal() {
    let ctrl_c = async {
        tokio::signal::ctrl_c()
            .await
            .expect("Failed to install Ctrl+C handler");
        tracing::info!("Received Ctrl+C, starting graceful shutdown");
    };

    #[cfg(unix)]
    let terminate = async {
        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
            .expect("Failed to install SIGTERM handler")
            .recv()
            .await;
        tracing::info!("Received SIGTERM, starting graceful shutdown");
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    let canary_rollback = async {
        canary_rollback_signal(std::path::Path::new(
            crate::canary::CANARY_ROLLBACK_FLAG_FILE,
        ))
        .await;
        tracing::info!("Canary rollback signalled, starting graceful shutdown");
    };

    tokio::select! {
        () = ctrl_c => {},
        () = terminate => {},
        () = canary_rollback => {},
    }
}

/// Resolve when the canary rollback flag file is present at `path`.
///
/// A rollback signal is intentionally **sticky across restarts**: if the flag is
/// already present at boot (e.g. a supervisor restarted the process after a
/// rollback), this resolves immediately so the replica drains and exits again
/// rather than rejoining the canary cohort. The replica keeps draining until a
/// controller clears the signal with `autumn canary promote` (or scales the
/// replica to zero). At startup the framework also flips `/ready` to draining
/// when the flag is present, so a restarted rolled-back replica never serves
/// canary traffic.
///
/// Uses async stat so the 500 ms poll never blocks the executor thread.
async fn canary_rollback_signal(path: &std::path::Path) {
    let interval = std::time::Duration::from_millis(500);
    loop {
        if tokio::fs::metadata(path).await.is_ok() {
            return;
        }
        tokio::time::sleep(interval).await;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use std::sync::atomic::{AtomicUsize, Ordering};
    use tower::ServiceExt;

    // ── omitted-router accounting for `autumn routes audit` ──────────────────

    // #1974 item 7: a plugin declares a top-level config section from its
    // `build()` via `config_section`, so `server.strict_config` treats that root
    // as known-and-opaque. Prove the declaration lands on the builder and that
    // the registry is fail-closed (an undeclared root is not registered).
    #[test]
    fn plugin_declares_config_section_via_build() {
        struct DummyMediaPlugin;
        impl crate::plugin::Plugin for DummyMediaPlugin {
            fn build(self, app: AppBuilder) -> AppBuilder {
                app.config_section("media")
            }
        }

        let builder = app().plugin(DummyMediaPlugin);
        assert!(
            builder.has_config_section("media"),
            "a plugin's build() must declare its [media] config section"
        );
        assert!(
            !builder.has_config_section("definitely_not_a_root"),
            "only explicitly-declared roots are registered — the seam is fail-closed"
        );
    }

    /// Compute the omitted-router count for a builder using the same inputs
    /// `run_dump_routes_mode` feeds `omitted_router_count`: the merge count, the
    /// nest prefixes, and the declared routes that prove nest coverage.
    fn omitted_for(builder: &AppBuilder) -> usize {
        omitted_router_count(
            builder.merge_routers.len(),
            builder
                .nest_routers
                .iter()
                .map(|(prefix, _)| prefix.as_str()),
            &builder.declared_routes,
        )
    }

    /// Regression (#1604): the DOCUMENTED plugin pattern —
    /// `app.nest(prefix, router).declare_plugin_routes(routes)`, which the
    /// first-party `AdminPlugin` uses — declares route metadata whose paths fall
    /// under the nest prefix. That coverage makes the nested raw router
    /// enumerable, so it must NOT be counted among the opaque, omitted routers
    /// that hard-fail the audit gate. Before the fix, prefix coverage was
    /// ignored and the mere presence of the nested raw router pushed
    /// `hidden > 0`, false-failing the audit even though every admin route was
    /// declared and classified.
    #[test]
    fn documented_nest_then_declare_is_not_counted_as_omitted() {
        let raw =
            axum::Router::<AppState>::new().route("/ping", axum::routing::get(|| async { "pong" }));
        let declared = vec![crate::route_listing::RouteInfo {
            method: "GET".to_owned(),
            path: "/admin/ping".to_owned(),
            handler: "admin::ping".to_owned(),
            ..Default::default()
        }];

        // The plain documented pattern: nest the raw router, then declare its
        // covering route metadata. No dedicated `nest_declared` bookkeeping.
        let builder = app().nest("/admin", raw).declare_plugin_routes(declared);

        // The raw router is still mounted (serving path is unchanged) …
        assert_eq!(builder.nest_routers.len(), 1);
        // … and its declared metadata was folded into `declared_routes`.
        assert_eq!(builder.declared_routes.len(), 1);

        // ⇒ zero omitted routers: the declared route `/admin/ping` falls under
        // the `/admin` nest prefix, so the mount is covered and the audit gate
        // must NOT fire.
        assert_eq!(
            omitted_for(&builder),
            0,
            "a nest whose endpoints are declared is enumerable and must not count as omitted",
        );
    }

    /// The soundness guarantee must survive: a raw router mounted via bare
    /// `nest()` or `merge()` without covering declarations is unenumerable and
    /// must still count as omitted so `autumn routes audit` fails closed.
    #[test]
    fn undeclared_nest_and_merge_still_count_as_omitted() {
        let raw_nest =
            axum::Router::<AppState>::new().route("/x", axum::routing::get(|| async { "x" }));
        let raw_merge =
            axum::Router::<AppState>::new().route("/y", axum::routing::get(|| async { "y" }));

        let builder = app().nest("/v2", raw_nest).merge(raw_merge);

        assert_eq!(builder.nest_routers.len(), 1);
        assert_eq!(builder.merge_routers.len(), 1);
        // Nothing was declared, so nothing covers the nest.
        assert!(builder.declared_routes.is_empty());

        assert_eq!(
            omitted_for(&builder),
            2,
            "an undeclared nest and a merge are both opaque and must be reported",
        );
    }

    /// An undeclared `merge()` is rootless — it cannot be prefix-matched — so it
    /// stays omitted even when unrelated declared routes exist. Guards against a
    /// declaration for one mount silently covering an unrelated raw `merge()`.
    #[test]
    fn declared_routes_do_not_cover_a_rootless_merge() {
        let raw_merge =
            axum::Router::<AppState>::new().route("/y", axum::routing::get(|| async { "y" }));

        let builder =
            app()
                .merge(raw_merge)
                .declare_plugin_routes(vec![crate::route_listing::RouteInfo {
                    method: "GET".to_owned(),
                    path: "/admin/ok".to_owned(),
                    handler: "admin::ok".to_owned(),
                    ..Default::default()
                }]);

        assert_eq!(
            omitted_for(&builder),
            1,
            "a merge has no prefix to match declarations against and must always count",
        );
    }

    /// A declared nest alongside an *undeclared* nest: only the undeclared one
    /// is omitted. Prefix-matching must cover the `/admin` mount (a declared
    /// route falls under it) without spilling onto the unrelated `/raw` mount
    /// (no declared route falls under it).
    #[test]
    fn mixed_declared_and_undeclared_nests_count_only_the_undeclared() {
        let declared_raw =
            axum::Router::<AppState>::new().route("/ok", axum::routing::get(|| async { "ok" }));
        let undeclared_raw = axum::Router::<AppState>::new()
            .route("/opaque", axum::routing::get(|| async { "opaque" }));

        let builder = app()
            .nest("/admin", declared_raw)
            .declare_plugin_routes(vec![crate::route_listing::RouteInfo {
                method: "GET".to_owned(),
                path: "/admin/ok".to_owned(),
                handler: "admin::ok".to_owned(),
                ..Default::default()
            }])
            .nest("/raw", undeclared_raw);

        assert_eq!(builder.nest_routers.len(), 2);
        assert_eq!(builder.declared_routes.len(), 1);
        assert_eq!(
            omitted_for(&builder),
            1,
            "only the bare nest() is omitted; the declared mount is covered",
        );
    }

    /// A declared route whose path merely *shares a leading substring* with a
    /// nest prefix (`/administrators` vs `/admin`) must NOT cover the nest:
    /// prefix-matching honours path-segment boundaries, so this bare nest still
    /// counts as omitted and the audit fails closed.
    #[test]
    fn prefix_match_respects_path_segment_boundaries() {
        let raw = axum::Router::<AppState>::new().route("/x", axum::routing::get(|| async { "x" }));

        let builder = app().nest("/admin", raw).declare_plugin_routes(vec![
            crate::route_listing::RouteInfo {
                method: "GET".to_owned(),
                path: "/administrators".to_owned(),
                handler: "other::index".to_owned(),
                ..Default::default()
            },
        ]);

        assert_eq!(
            omitted_for(&builder),
            1,
            "`/administrators` is not under the `/admin` nest prefix; the nest stays omitted",
        );
    }

    #[test]
    fn is_dump_jobs_mode_only_true_for_exactly_one() {
        // `autumn jobs manifest` sets AUTUMN_DUMP_JOBS=1 to select the manifest
        // dump path in `run()`. Any other value (or an unset var) must fall
        // through to the normal boot path.
        temp_env::with_var("AUTUMN_DUMP_JOBS", Some("1"), || {
            assert!(is_dump_jobs_mode(), "`1` must select the jobs-dump path");
        });
        temp_env::with_var("AUTUMN_DUMP_JOBS", Some("0"), || {
            assert!(!is_dump_jobs_mode(), "`0` must not select the dump path");
        });
        temp_env::with_var("AUTUMN_DUMP_JOBS", Some("true"), || {
            assert!(
                !is_dump_jobs_mode(),
                "only the literal `1` enables the mode"
            );
        });
        temp_env::with_var("AUTUMN_DUMP_JOBS", None::<&str>, || {
            assert!(!is_dump_jobs_mode(), "unset must not select the dump path");
        });
    }

    #[test]
    fn dump_jobs_manifest_includes_synthesized_durable_listener_default_queue() {
        // Regression (#1802, Codex P2): an app that registers a durable listener
        // and configures `[jobs.queues]` WITHOUT `default` still drains `default`
        // at runtime — `finalize_event_bus` synthesizes a `default`-queue
        // `JobInfo` for each durable listener before the runtime starts. The
        // `AUTUMN_DUMP_JOBS=1` manifest must reflect that same set through the
        // shared `synthesize_durable_listener_jobs` seam, or a topology-aware
        // `autumn doctor` would accept a fleet where no tier drains those jobs.
        fn listener_handler(
            _state: AppState,
            _payload: serde_json::Value,
        ) -> std::pin::Pin<
            Box<dyn std::future::Future<Output = crate::AutumnResult<()>> + Send + 'static>,
        > {
            Box::pin(async move { Ok(()) })
        }
        let durable = crate::events::ListenerInfo {
            event_name: "UserSignedUp",
            listener_name: "app::send_welcome_email".to_string(),
            mode: crate::events::DispatchMode::Durable,
            job_name: Some("__event_listener::send_welcome_email".to_string()),
            max_attempts: 4,
            initial_backoff_ms: 250,
            handler: listener_handler,
        };
        let cfg = crate::config::JobQueuesConfig::strict_list(["critical"]);

        // The dump path holds no builder-registered jobs, only the durable
        // listener; the manifest must still surface `default` (where that
        // listener's synthesized job runs) alongside the configured `critical`.
        let manifest = dump_jobs_manifest(&cfg, Vec::new(), vec![durable]);
        assert_eq!(manifest, "queues = [\"critical\", \"default\"]\n");
    }

    #[cfg(feature = "db")]
    const APP_TEST_MIGRATIONS: crate::migrate::EmbeddedMigrations =
        diesel_migrations::embed_migrations!("test_migrations");

    /// Shared no-op `MailDeliveryQueue` used by builder tests so the trait
    /// impl body is defined once and exercised by at least one test.
    #[cfg(feature = "mail")]
    struct MailTestNoopQueue;

    #[cfg(feature = "mail")]
    impl crate::mail::MailDeliveryQueue for MailTestNoopQueue {
        fn enqueue<'a>(
            &'a self,
            _mail: crate::mail::Mail,
        ) -> std::pin::Pin<
            Box<dyn std::future::Future<Output = Result<(), crate::mail::MailError>> + Send + 'a>,
        > {
            Box::pin(async { Ok(()) })
        }
    }

    #[cfg(feature = "mail")]
    fn test_mail() -> crate::mail::Mail {
        crate::mail::Mail::builder()
            .to("test@example.com")
            .subject("hi")
            .text("hello")
            .build()
            .expect("test mail should build")
    }

    /// Helper to build a test router with default config and no database.
    pub fn test_router(routes: Vec<Route>) -> axum::Router {
        let config = AutumnConfig::default();
        let state = AppState {
            extensions: std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            #[cfg(feature = "db")]
            pool: None,
            #[cfg(feature = "db")]
            replica_pool: None,
            #[cfg(feature = "db")]
            shards: None,
            profile: None,
            role: crate::config::ProcessRole::Combined,
            started_at: std::time::Instant::now(),
            health_detailed: true,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            job_registry: crate::actuator::JobRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            metrics_source_registry: crate::actuator::MetricsSourceRegistry::new(),
            health_indicator_registry: crate::actuator::HealthIndicatorRegistry::new(),
            #[cfg(feature = "ws")]
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "presence")]
            presence: crate::presence::Presence::new(crate::channels::Channels::new(32)),
            #[cfg(feature = "ws")]
            shutdown: tokio_util::sync::CancellationToken::new(),
            policy_registry: crate::authorization::PolicyRegistry::default(),
            forbidden_response: crate::authorization::ForbiddenResponse::default(),
            auth_session_key: "user_id".to_owned(),
            shared_cache: None,
            clock: std::sync::Arc::new(crate::time::SystemClock),
            app_id: AppState::next_app_id(),
        };
        crate::router::build_router(routes, &config, state)
    }

    #[tokio::test]
    async fn canary_rollback_signal_resolves_when_flag_newly_written() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("canary-rollback.json");

        // Flag is absent at boot; writing it after start must resolve the signal.
        let writer_path = path.clone();
        let writer = tokio::spawn(async move {
            tokio::time::sleep(std::time::Duration::from_millis(150)).await;
            crate::canary::CanaryState::write_rollback_flag(
                &writer_path,
                &crate::canary::RollbackSignal::default(),
            )
            .unwrap();
        });

        let signalled = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            canary_rollback_signal(&path),
        )
        .await;
        assert!(signalled.is_ok(), "rollback signal should resolve");
        writer.await.unwrap();
    }

    #[tokio::test]
    async fn canary_rollback_signal_resolves_immediately_when_flag_present_at_boot() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("canary-rollback.json");
        // A rollback flag is sticky across restarts: present at boot must trigger
        // again so a supervisor restart cannot rejoin a rolled-back replica.
        crate::canary::CanaryState::write_rollback_flag(
            &path,
            &crate::canary::RollbackSignal::default(),
        )
        .unwrap();

        let signalled = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            canary_rollback_signal(&path),
        )
        .await;
        assert!(
            signalled.is_ok(),
            "a flag present at boot must trigger rollback (sticky across restarts)"
        );
    }

    #[cfg(feature = "db")]
    #[test]
    fn build_state_applies_replica_fallback_policy_to_read_routing() {
        let mut config = AutumnConfig::default();
        config.database.primary_url = Some("postgres://localhost/primary".to_owned());
        config.database.primary_pool_size = Some(5);
        config.database.replica_url = Some("postgres://localhost/replica".to_owned());
        config.database.replica_pool_size = Some(2);
        config.database.replica_fallback = crate::config::ReplicaFallback::Primary;
        let topology = crate::db::create_topology(&config.database)
            .expect("topology should build")
            .expect("database should be configured");

        let state = build_state(
            &config,
            Some(&topology),
            None,
            #[cfg(feature = "ws")]
            None,
        );
        state
            .probes()
            .mark_replica_unready("replica migrations lag primary");

        assert_eq!(state.read_pool().expect("read pool").status().max_size, 5);
    }

    #[test]
    fn build_state_exposes_resolved_process_role() {
        use crate::config::ProcessRole;

        // Default config resolves to the combined role: existing single-process
        // apps see no behavior change and get both HTTP + workers.
        let mut config = AutumnConfig::default();
        let state = build_state(
            &config,
            #[cfg(feature = "db")]
            None,
            #[cfg(feature = "db")]
            None,
            #[cfg(feature = "ws")]
            None,
        );
        assert_eq!(state.role(), ProcessRole::Combined);
        assert!(state.role().serves_http());
        assert!(state.role().runs_workers());

        // A worker-role config flows through the exact same resolution the
        // framework uses to gate the job runtime, reachable via `state.role()`.
        config.role = ProcessRole::Worker;
        let state = build_state(
            &config,
            #[cfg(feature = "db")]
            None,
            #[cfg(feature = "db")]
            None,
            #[cfg(feature = "ws")]
            None,
        );
        assert_eq!(state.role(), ProcessRole::Worker);
        assert!(state.role().runs_workers());
        assert!(!state.role().serves_http());
    }

    #[cfg(feature = "db")]
    #[tokio::test]
    async fn custom_pool_provider_preserves_configured_replica_topology() {
        struct PassthroughPoolProvider;

        impl crate::db::DatabasePoolProvider for PassthroughPoolProvider {
            async fn create_pool(
                &self,
                config: &crate::config::DatabaseConfig,
            ) -> Result<
                Option<
                    diesel_async::pooled_connection::deadpool::Pool<crate::db::RuntimeConnection>,
                >,
                crate::db::PoolError,
            > {
                crate::db::create_pool(config)
            }
        }

        let mut config = AutumnConfig::default();
        config.database.primary_url = Some("postgres://localhost/primary".to_owned());
        config.database.primary_pool_size = Some(5);
        config.database.replica_url = Some("postgres://localhost/replica".to_owned());
        config.database.replica_pool_size = Some(2);
        config.database.replica_fallback = crate::config::ReplicaFallback::FailReadiness;
        let AppBuilder {
            pool_provider_factory,
            ..
        } = app().with_pool_provider(PassthroughPoolProvider);

        let database = setup_database(
            &config,
            Vec::new(),
            pool_provider_factory,
            None,
            None,
            false,
            RepositoryCommitHookQueueMigrationMode::Runtime,
        )
        .await
        .expect("custom provider should build database topology");
        let topology = database.topology.expect("database should be configured");

        assert_eq!(topology.primary().status().max_size, 5);
        assert_eq!(
            topology
                .replica()
                .expect("custom provider should create replica pool")
                .status()
                .max_size,
            2
        );

        let state = build_state(
            &config,
            Some(&topology),
            None,
            #[cfg(feature = "ws")]
            None,
        );
        state
            .probes()
            .mark_replica_connection_unready("replica connection failed");

        assert!(state.read_pool().is_none());
        let (status, _) = crate::probe::readiness_response(&state).await;
        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
    }

    // Finding 2 (Codex P2), corrected: the fail-closed `statement_timeout` guard
    // must fire once a custom provider has ACTUALLY established a pool — a custom
    // provider can build its own SQLite pool without routing through the built-in
    // `create_topology`/`create_pool` factories (the default `create_topology`
    // only delegates to the provider's `create_pool`, and both are overridable),
    // so `setup_database` enforces the guard at dispatch. But it must run only for
    // an established pool (`Some(..)`), NOT before the provider returns: a provider
    // that returns `Ok(None)` opts into the explicitly-supported no-database mode
    // (no pool/statement to bound), which must still boot even with a nonzero
    // `statement_timeout` — matching the built-in path, which returns `Ok(None)`
    // before its own timeout check. (CI's sqlite job runs the named integration
    // targets, not `--lib`; `setup_database` and the shared guard are
    // crate-private, so this boundary is only reachable from a unit test — hence a
    // focused `--lib` test rather than an entry in the runtime target.)
    //
    // Case (a): a custom provider that establishes a real in-memory SQLite pool
    // (`Ok(Some(..))`) under a nonzero `statement_timeout` must fail closed with
    // the actionable error, so the original F2 bypass stays closed.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn custom_pool_provider_with_established_sqlite_pool_fails_closed_on_statement_timeout() {
        // Builds a real in-memory SQLite pool WITHOUT routing the timeout through
        // the built-in factory — the exact F2 bypass a custom provider could use.
        struct RealSqlitePoolProvider;

        impl crate::db::DatabasePoolProvider for RealSqlitePoolProvider {
            async fn create_pool(
                &self,
                config: &crate::config::DatabaseConfig,
            ) -> Result<
                Option<
                    diesel_async::pooled_connection::deadpool::Pool<crate::db::RuntimeConnection>,
                >,
                crate::db::PoolError,
            > {
                // Clear `statement_timeout` locally so the built-in `create_pool`
                // guard does not fire inside the provider — this provider hands
                // back a live SQLite pool that silently dropped the timeout, which
                // is exactly the fail-closed condition the dispatch guard closes.
                let mut relaxed = config.clone();
                relaxed.statement_timeout = None;
                crate::db::create_pool(&relaxed)
            }
        }

        let mut config = AutumnConfig::default();
        config.database.primary_url = Some("sqlite::memory:".to_owned());
        config.database.statement_timeout = Some(std::time::Duration::from_secs(30));
        let AppBuilder {
            pool_provider_factory,
            shard_provider_factory,
            ..
        } = app().with_pool_provider(RealSqlitePoolProvider);

        let Err(err) = setup_database(
            &config,
            Vec::new(),
            pool_provider_factory,
            shard_provider_factory,
            None,
            false,
            RepositoryCommitHookQueueMigrationMode::Runtime,
        )
        .await
        else {
            panic!(
                "sqlite + statement_timeout must fail closed once the provider establishes a pool"
            );
        };
        assert!(
            err.contains("database.statement_timeout") && err.contains("SQLite"),
            "dispatch guard error must name the config key and SQLite, got: {err}"
        );
    }

    // Case (b) — the exact regression Codex flagged: a custom provider that opts
    // into no-database mode (`Ok(None)`) must STILL boot even with a nonzero
    // `database.statement_timeout`, because no pool/statement exists to bound. The
    // Some-gated guard must not reject this the way the pre-dispatch guard did.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn custom_pool_provider_no_database_mode_boots_with_statement_timeout() {
        struct NoDatabaseProvider;

        impl crate::db::DatabasePoolProvider for NoDatabaseProvider {
            async fn create_pool(
                &self,
                _config: &crate::config::DatabaseConfig,
            ) -> Result<
                Option<
                    diesel_async::pooled_connection::deadpool::Pool<crate::db::RuntimeConnection>,
                >,
                crate::db::PoolError,
            > {
                // Explicit no-database opt-out.
                Ok(None)
            }
        }

        let mut config = AutumnConfig::default();
        // A URL may even be configured; the provider's `Ok(None)` still wins.
        config.database.primary_url = Some("sqlite::memory:".to_owned());
        config.database.statement_timeout = Some(std::time::Duration::from_secs(30));
        let AppBuilder {
            pool_provider_factory,
            shard_provider_factory,
            ..
        } = app().with_pool_provider(NoDatabaseProvider);

        let bootstrap = setup_database(
            &config,
            Vec::new(),
            pool_provider_factory,
            shard_provider_factory,
            None,
            false,
            RepositoryCommitHookQueueMigrationMode::Runtime,
        )
        .await
        .expect("no-database provider must boot even with a nonzero statement_timeout");
        assert!(
            bootstrap.topology.is_none(),
            "no-database mode must yield no control topology"
        );
        assert!(
            bootstrap.shards.is_none(),
            "no-database mode must yield no shard set"
        );
    }

    #[cfg(feature = "db")]
    fn sharded_test_config() -> AutumnConfig {
        let mut config = AutumnConfig::default();
        config.database.primary_url = Some("postgres://localhost/control".to_owned());
        config.database.shards = vec![
            crate::config::ShardConfig {
                name: "shard0".to_owned(),
                primary_url: "postgres://localhost/shard0".to_owned(),
                slots: Some(vec![crate::config::SlotSpec::Range("0-8191".to_owned())]),
                replica_url: None,
                primary_pool_size: Some(3),
                replica_pool_size: None,
                replica_fallback: None,
            },
            crate::config::ShardConfig {
                name: "shard1".to_owned(),
                primary_url: "postgres://localhost/shard1".to_owned(),
                slots: Some(vec![crate::config::SlotSpec::Range(
                    "8192-16383".to_owned(),
                )]),
                replica_url: Some("postgres://localhost/shard1_ro".to_owned()),
                primary_pool_size: None,
                replica_pool_size: Some(2),
                replica_fallback: None,
            },
        ];
        config
    }

    #[cfg(feature = "db")]
    #[tokio::test]
    async fn setup_database_builds_shard_set_from_config() {
        let config = sharded_test_config();

        let database = setup_database(
            &config,
            Vec::new(),
            None,
            None,
            None,
            false,
            RepositoryCommitHookQueueMigrationMode::Runtime,
        )
        .await
        .expect("sharded config should bootstrap");

        assert!(database.topology.is_some(), "control role configured");
        let shards = database.shards.expect("shards configured");
        assert_eq!(shards.len(), 2);
        assert_eq!(
            shards
                .by_name("shard0")
                .expect("shard0")
                .primary_pool()
                .status()
                .max_size,
            3
        );
        assert_eq!(
            shards
                .by_name("shard1")
                .expect("shard1")
                .replica_pool()
                .expect("shard1 replica")
                .status()
                .max_size,
            2
        );

        let state = build_state(
            &config,
            database.topology.as_ref(),
            Some(shards),
            #[cfg(feature = "ws")]
            None,
        );
        let state_shards = state.shards().expect("state should expose shards");
        assert_eq!(state_shards.len(), 2);
        // Routing works end-to-end through state-held shards.
        let routed = state_shards.route("tenant-1").await.expect("route");
        assert!(["shard0", "shard1"].contains(&routed.name()));
    }

    #[cfg(feature = "db")]
    #[tokio::test]
    async fn custom_pool_provider_builds_shard_topologies() {
        struct CountingProvider(std::sync::Arc<std::sync::atomic::AtomicUsize>);

        impl crate::db::DatabasePoolProvider for CountingProvider {
            async fn create_pool(
                &self,
                config: &crate::config::DatabaseConfig,
            ) -> Result<
                Option<
                    diesel_async::pooled_connection::deadpool::Pool<crate::db::RuntimeConnection>,
                >,
                crate::db::PoolError,
            > {
                crate::db::create_pool(config)
            }

            async fn create_shard_topology(
                &self,
                shard: &crate::config::ShardConfig,
                defaults: &crate::config::DatabaseConfig,
            ) -> Result<crate::db::DatabaseTopology, crate::db::PoolError> {
                self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                crate::db::create_shard_topology(shard, defaults)
            }
        }

        let config = sharded_test_config();
        let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let AppBuilder {
            pool_provider_factory,
            shard_provider_factory,
            ..
        } = app().with_pool_provider(CountingProvider(calls.clone()));

        let database = setup_database(
            &config,
            Vec::new(),
            pool_provider_factory,
            shard_provider_factory,
            None,
            false,
            RepositoryCommitHookQueueMigrationMode::Runtime,
        )
        .await
        .expect("provider should build shard topologies");

        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 2);
        assert_eq!(database.shards.expect("shards").len(), 2);
    }

    #[cfg(feature = "db")]
    #[test]
    fn repository_commit_hook_worker_starts_after_job_runtime_initialization() {
        let source = include_str!("app.rs").replace("\r\n", "\n");
        let server_init = "initialize_job_runtime(
            jobs,
            &state,
            &server_shutdown,";
        let server_worker = "start_repository_commit_hook_worker(\n                pool,\n                server_shutdown.child_token(),\n            );";
        let task_init = "initialize_job_runtime(jobs, &state, &task_shutdown, &config.jobs, true)";
        let task_worker = "start_repository_commit_hook_worker(\n                pool,\n                task_shutdown.child_token(),\n            );";

        assert!(
            source
                .find(server_init)
                .expect("normal server path should initialize jobs")
                < source
                    .find(server_worker)
                    .expect("normal server path should start repository hook worker"),
            "normal server startup must initialize jobs before repository commit hooks can enqueue them"
        );
        assert!(
            source
                .find(task_init)
                .expect("task runner path should initialize jobs")
                < source
                    .find(task_worker)
                    .expect("task runner path should start repository hook worker"),
            "task runner startup must initialize jobs before repository commit hooks can enqueue them"
        );
    }

    #[cfg(feature = "db")]
    #[test]
    fn repository_commit_hook_workers_are_gated_on_worker_role() {
        // Draining durable after-commit hook rows is background execution, so the
        // primary-pool and shard commit-hook worker starts on the normal server
        // path must both be guarded by `role.runs_workers()` — a web-role replica
        // must not claim/execute hook rows (that work belongs to the worker tier).
        let source = include_str!("app.rs").replace("\r\n", "\n");
        let primary_gate =
            "if role.runs_workers()\n            && let Some(pool) = state.pool().cloned()";
        let shard_gate = "if role.runs_workers()\n            && let Some(shards) = state.shards()";
        assert!(
            source.contains(primary_gate),
            "primary-pool commit-hook worker must be gated on role.runs_workers()"
        );
        assert!(
            source.contains(shard_gate),
            "shard commit-hook workers must be gated on role.runs_workers()"
        );
    }

    #[test]
    fn state_initializers_run_before_job_runtime_initialization() {
        let source = include_str!("app.rs").replace("\r\n", "\n");
        let server_start = source
            .find("pub async fn run(self)")
            .expect("normal server path should exist");
        let build_mode_start = source
            .find("async fn run_build_mode(self)")
            .expect("static build path should follow server path");
        let task_start = source
            .find("async fn run_one_off_task_mode(self, requested_name: String)")
            .expect("task runner path should exist");
        let server_source = &source[server_start..build_mode_start];
        let task_source = &source[task_start..];
        let server_init = "initialize_job_runtime(
            jobs,
            &state,
            &server_shutdown,";
        let task_init = "initialize_job_runtime(jobs, &state, &task_shutdown, &config.jobs, true)";
        let server_initializer = server_source
            .find("run_state_initializers(state_initializers, &state);")
            .expect("normal server path should run state initializers");
        let task_initializer = task_source
            .find("run_state_initializers(state_initializers, &state);")
            .expect("task runner path should run state initializers");
        let server_job = server_source
            .find(server_init)
            .expect("normal server path should initialize jobs");
        let task_job = task_source
            .find(task_init)
            .expect("task runner path should initialize jobs");

        assert!(
            server_initializer < server_job,
            "normal server startup must install state-initialized resources before job workers start"
        );
        assert!(
            task_initializer < task_job,
            "task runner startup must install state-initialized resources before job workers start"
        );
    }

    #[test]
    fn static_builds_run_state_initializers_before_router_build() {
        let source = include_str!("app.rs").replace("\r\n", "\n");
        let build_mode_start = source
            .find("async fn run_build_mode(self)")
            .expect("static build path should exist");
        let dump_mode_start = source
            .find("async fn run_dump_routes_mode(self)")
            .expect("route dump path should follow static build path");
        let build_mode_source = &source[build_mode_start..dump_mode_start];
        let state_initializer = build_mode_source
            .find("run_state_initializers(state_initializers, &state);")
            .expect("static build path should run state initializers");
        let router_build = build_mode_source
            .find("let router = crate::router::try_build_router_inner(")
            .expect("static build path should build a router");

        assert!(
            state_initializer < router_build,
            "static builds must install state-initialized resources before rendering routes"
        );
    }

    #[test]
    fn migrate_only_one_shot_applies_and_exits_without_serving() {
        // The runtime effect (applying against Postgres, exiting without binding a
        // port) needs a DB + a subprocess harness because `run()` ends in
        // `process::exit`; that live apply is exercised by the shared
        // `run_pending_locked` engine's own DB-backed tests. Here we lock the
        // *dispatch decision* and the *reuse/exit contract* structurally: with
        // AUTUMN_MIGRATE=1 the migrate-and-exit path is chosen and the
        // server-start path is NOT taken.
        let source = include_str!("app.rs").replace("\r\n", "\n");
        let run_start = source.find("pub async fn run(self)").expect("run() exists");
        let run_end = source
            .find("async fn run_build_mode(self)")
            .expect("build mode follows run()");
        let run_body = &source[run_start..run_end];

        // The AUTUMN_MIGRATE=1 dispatch is an early one-shot: it sits BEFORE the
        // server-start machinery (the `let Self {` destructure that begins the
        // serving path) and returns, so a migrate run never binds a port.
        let dispatch = run_body
            .find("if is_migrate_only_mode() {")
            .expect("run() dispatches the migrate one-shot");
        let server_start = run_body
            .find("let Self {")
            .expect("run() destructures self to start the server");
        assert!(
            dispatch < server_start,
            "AUTUMN_MIGRATE must be handled before the server-start path"
        );
        let migrate_branch = &run_body[dispatch..server_start];
        assert!(
            migrate_branch.contains("self.run_migrate_only_mode().await;")
                && migrate_branch.contains("return;"),
            "the migrate one-shot must run then return before server start"
        );

        // The handler applies per target and exits — never starting the server.
        let handler_start = source
            .find("async fn run_migrate_only_mode(self)")
            .expect("migrate handler exists");
        let handler_end = source
            .find("async fn run_one_off_task_mode(self, requested_name: String)")
            .expect("one-off task handler follows the migrate handler");
        let handler = &source[handler_start..handler_end];
        assert!(
            handler.contains("apply_pending_or_exit"),
            "the migrate handler applies pending migrations per target"
        );
        assert!(
            handler.contains("std::process::exit(0)"),
            "the migrate handler exits after applying"
        );

        // Issue #1614, PR3: the migrate one-shot must apply the SAME SQLite
        // sharding guard as normal boot BEFORE its migration loop, so a sharded
        // `sqlite:` target exits with the actionable sharding error instead of a
        // generic `PgConnection` failure — and the two paths cannot drift because
        // both call `sqlite_sharding_unsupported_guard`.
        let guard_call = handler
            .find("sqlite_sharding_unsupported_guard(")
            .expect("migrate handler applies the SQLite sharding guard");
        let first_apply = handler
            .find("apply_pending_or_exit")
            .expect("migrate handler applies per target");
        assert!(
            guard_call < first_apply,
            "the SQLite guard must run BEFORE the migration loop / apply_pending_or_exit"
        );
        assert!(
            !handler.contains("initialize_job_runtime")
                && !handler.contains("try_build_router_inner"),
            "the migrate one-shot must not start the server"
        );

        // The per-target applier reuses `run_pending_locked` (the exact engine
        // `auto_migrate` drives — no duplicated migration logic) and exits
        // non-zero on failure so a bad migration aborts before cutover (AC-3).
        let helper_start = source
            .find("fn apply_pending_or_exit(")
            .expect("apply_pending_or_exit exists");
        let helper = &source[helper_start..helper_start + 1200];
        assert!(
            helper.contains("crate::migrate::run_pending_locked("),
            "must reuse the shared locked applier, not duplicate migration logic"
        );
        assert!(
            helper.contains("std::process::exit(1)"),
            "a failed migration must exit non-zero (abort before cutover)"
        );
    }

    #[cfg(feature = "db")]
    #[test]
    fn hooked_repository_apps_include_hook_queue_framework_migration() {
        let migrations = migrations_with_repository_framework_migrations(
            vec![APP_TEST_MIGRATIONS],
            true,
            false,
            RepositoryCommitHookQueueMigrationMode::Runtime,
        );
        let names = migration_names(&migrations);

        assert!(
            names
                .iter()
                .any(|name| name == REPOSITORY_COMMIT_HOOK_QUEUE_MIGRATION),
            "hooked repository apps must auto-register the durable hook queue migration"
        );
        assert!(
            names.iter().all(|name| !name.contains("api_tokens")),
            "hooked repository apps must not auto-register unrelated framework migrations: {names:?}"
        );
    }

    #[cfg(feature = "db")]
    #[test]
    fn runtime_hooked_apps_include_hook_queue_framework_migration_without_app_migrations() {
        let migrations = migrations_with_repository_framework_migrations(
            Vec::new(),
            true,
            false,
            RepositoryCommitHookQueueMigrationMode::Runtime,
        );
        let names = migration_names(&migrations);

        assert!(
            names
                .iter()
                .any(|name| name == REPOSITORY_COMMIT_HOOK_QUEUE_MIGRATION),
            "runtime hooked repository apps must install the durable hook queue even when app migrations are managed elsewhere"
        );
    }

    #[cfg(feature = "db")]
    #[test]
    fn versioned_repository_apps_include_version_history_framework_migration() {
        let migrations = migrations_with_repository_framework_migrations(
            vec![APP_TEST_MIGRATIONS],
            false,
            true,
            RepositoryCommitHookQueueMigrationMode::Runtime,
        );
        let names = migration_names(&migrations);

        assert!(
            names.iter().any(|name| name == VERSION_HISTORY_MIGRATION),
            "versioned repository apps must auto-register the version-history migration"
        );
        assert!(
            names
                .iter()
                .all(|name| !name.contains("repository_commit_hook_queue")),
            "versioned-only repository apps must not auto-register the durable hook queue: {names:?}"
        );
    }

    #[cfg(feature = "db")]
    #[test]
    fn runtime_versioned_apps_include_version_history_framework_migration_without_app_migrations() {
        let migrations = migrations_with_repository_framework_migrations(
            Vec::new(),
            false,
            true,
            RepositoryCommitHookQueueMigrationMode::Runtime,
        );
        let names = migration_names(&migrations);

        assert!(
            names.iter().any(|name| name == VERSION_HISTORY_MIGRATION),
            "runtime versioned repository apps must install version history even when app migrations are managed elsewhere"
        );
    }

    #[cfg(feature = "db")]
    #[test]
    fn static_builds_do_not_auto_add_hook_queue_when_no_migrations_registered() {
        let migrations = migrations_with_repository_framework_migrations(
            Vec::new(),
            true,
            true,
            RepositoryCommitHookQueueMigrationMode::StaticBuild,
        );

        assert!(
            migrations.is_empty(),
            "static/export builds that pass no migrations must not mutate the database"
        );
    }

    #[cfg(feature = "db")]
    #[test]
    fn directory_migration_required_only_at_runtime_with_shards_and_routing() {
        use RepositoryCommitHookQueueMigrationMode::{Runtime, StaticBuild};

        // The happy path: routing on, shards present, real runtime boot.
        assert!(directory_migration_is_required(true, true, Runtime));

        // A static build must never create the directory table, even with
        // routing enabled and shards configured.
        assert!(!directory_migration_is_required(true, true, StaticBuild));

        // Routing disabled, or no shards, means no directory table at all.
        assert!(!directory_migration_is_required(false, true, Runtime));
        assert!(!directory_migration_is_required(true, false, Runtime));
    }

    #[test]
    fn shard_map_migration_required_only_at_runtime_with_shards() {
        use RepositoryCommitHookQueueMigrationMode::{Runtime, StaticBuild};

        // The happy path: shards present, real runtime boot.
        assert!(shard_map_migration_is_required(true, Runtime));

        // A static build must never create the shard-map table.
        assert!(!shard_map_migration_is_required(true, StaticBuild));

        // No shards means no shard-map table.
        assert!(!shard_map_migration_is_required(false, Runtime));
    }

    #[cfg(feature = "db")]
    #[test]
    fn unhooked_apps_do_not_auto_add_hook_queue_framework_migration() {
        let migrations = migrations_with_repository_framework_migrations(
            Vec::new(),
            false,
            false,
            RepositoryCommitHookQueueMigrationMode::Runtime,
        );

        assert!(
            migrations.is_empty(),
            "unhooked apps should not get durable hook queue migrations for free"
        );
    }

    #[cfg(feature = "db")]
    fn migration_names(migrations: &[crate::migrate::EmbeddedMigrations]) -> Vec<String> {
        use diesel::migration::{Migration, MigrationSource as _};
        use diesel::pg::Pg;

        migrations
            .iter()
            .flat_map(|source| {
                let migrations: Vec<Box<dyn Migration<Pg>>> = source.migrations().unwrap();
                migrations
            })
            .map(|migration| migration.name().to_string())
            .collect()
    }

    #[cfg(feature = "db")]
    #[test]
    fn control_framework_filter_skips_control_but_keeps_shard_required_sets() {
        // The full control set is skipped on shards...
        assert!(migration_set_is_control_framework(
            &crate::migrate::FRAMEWORK_MIGRATIONS
        ));
        // ...but the standalone shard-required sets are kept (not flagged),
        // even though their migrations are duplicated into the control
        // `migrations/` directory.
        assert!(!migration_set_is_control_framework(
            &crate::version_history::VERSION_HISTORY_MIGRATIONS
        ));
        assert!(!migration_set_is_control_framework(
            &crate::repository_commit_hooks::REPOSITORY_COMMIT_HOOK_MIGRATIONS
        ));
    }

    #[cfg(feature = "db")]
    #[test]
    fn sharded_app_with_full_framework_still_gets_shard_required_sets() {
        use diesel::migration::{Migration, MigrationSource as _};
        use diesel::pg::Pg;

        // A sharded app that registers the full control FRAMEWORK_MIGRATIONS and
        // also uses commit hooks + versioning. The hook-queue / version-history
        // migrations are present *inside* the control set, but that set is
        // stripped from shard targets by `migration_set_is_control_framework`, so
        // the standalone shard-required sets must still be appended — otherwise
        // shards never get those tables.
        let migrations = migrations_with_repository_framework_migrations(
            vec![crate::migrate::FRAMEWORK_MIGRATIONS],
            true,
            true,
            RepositoryCommitHookQueueMigrationMode::Runtime,
        );

        // The migration names the shard apply loop will actually run: every set
        // that is not the control framework set (which gets stripped on shards).
        let shard_names: Vec<String> = migrations
            .iter()
            .filter(|set| !migration_set_is_control_framework(set))
            .flat_map(|set| {
                let ms: Vec<Box<dyn Migration<Pg>>> = set.migrations().unwrap_or_default();
                ms.into_iter()
                    .map(|m| m.name().to_string())
                    .collect::<Vec<_>>()
            })
            .collect();

        assert!(
            shard_names
                .iter()
                .any(|name| name == REPOSITORY_COMMIT_HOOK_QUEUE_MIGRATION),
            "shards must receive the commit-hook queue migration even when the full \
             control framework set is also registered: {shard_names:?}"
        );
        assert!(
            shard_names
                .iter()
                .any(|name| name == VERSION_HISTORY_MIGRATION),
            "shards must receive the version-history migration even when the full \
             control framework set is also registered: {shard_names:?}"
        );
    }

    #[cfg(feature = "db")]
    #[test]
    fn configure_replica_migration_check_stores_recheck_urls() {
        let mut config = AutumnConfig::default();
        config.database.primary_url = Some("postgres://localhost/primary".to_owned());
        config.database.replica_url = Some("postgres://localhost/replica".to_owned());
        let topology = crate::db::create_topology(&config.database)
            .expect("topology should build")
            .expect("database should be configured");

        let state = build_state(
            &config,
            Some(&topology),
            None,
            #[cfg(feature = "ws")]
            None,
        );

        assert!(
            state.probes().replica_migration_check().is_none(),
            "build_state should not enable migration checks without registered migrations"
        );

        configure_replica_migration_check(
            &state,
            Some((
                "postgres://localhost/primary".to_owned(),
                "postgres://localhost/replica".to_owned(),
            )),
        );

        let check = state
            .probes()
            .replica_migration_check()
            .expect("replica migration check should be configured");

        assert_eq!(check.primary_url, "postgres://localhost/primary");
        assert_eq!(check.replica_url, "postgres://localhost/replica");
    }

    #[cfg(feature = "db")]
    #[tokio::test]
    async fn replica_migration_readiness_marks_ready_endpoint_degraded() {
        let mut config = AutumnConfig::default();
        config.database.primary_url = Some("postgres://localhost/primary".to_owned());
        config.database.primary_pool_size = Some(5);
        config.database.replica_url = Some("postgres://localhost/replica".to_owned());
        config.database.replica_pool_size = Some(2);
        config.database.replica_fallback = crate::config::ReplicaFallback::FailReadiness;
        let topology = crate::db::create_topology(&config.database)
            .expect("topology should build")
            .expect("database should be configured");
        let state = build_state(
            &config,
            Some(&topology),
            None,
            #[cfg(feature = "ws")]
            None,
        );

        apply_replica_migration_readiness(
            &state,
            Some(crate::migrate::ReplicaMigrationReadiness::Stale {
                primary_latest: Some("00000000000002".to_owned()),
                replica_latest: Some("00000000000001".to_owned()),
            }),
        );

        let (status, _) = crate::probe::readiness_response(&state).await;

        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
    }

    #[cfg(feature = "db")]
    #[tokio::test]
    async fn blocking_replica_migration_readiness_reports_unknown_connection_errors() {
        let readiness = crate::migrate::check_replica_migration_readiness_blocking(
            "not-a-primary-url".to_owned(),
            "not-a-replica-url".to_owned(),
        )
        .await;

        assert!(matches!(
            readiness,
            crate::migrate::ReplicaMigrationReadiness::Unknown(_)
        ));
    }

    #[cfg(feature = "ws")]
    #[test]
    fn with_channels_backend_overrides_config_driven_backend_selection() {
        let builder = app().with_channels_backend(crate::channels::LocalChannelsBackend::new(4));
        let AppBuilder {
            channels_backend, ..
        } = builder;
        assert!(channels_backend.is_some());

        let mut config = AutumnConfig::default();
        config.channels.backend = crate::config::ChannelBackend::Redis;
        config.channels.redis.url = None;

        let state = build_state(
            &config,
            #[cfg(feature = "db")]
            None,
            #[cfg(feature = "db")]
            None,
            #[cfg(feature = "ws")]
            channels_backend,
        );
        let mut rx = state.channels().subscribe("override");

        state
            .broadcast()
            .publish("override", "ok")
            .expect("custom local backend should publish");

        assert_eq!(rx.try_recv().expect("message should arrive").as_str(), "ok");
    }

    /// Helper to create a simple GET route for testing.
    pub fn test_get_route(path: &'static str, name: &'static str) -> Route {
        Route {
            method: http::Method::GET,
            path,
            handler: axum::routing::get(|| async { "ok" }),
            name,
            api_doc: crate::openapi::ApiDoc {
                method: "GET",
                path,
                operation_id: name,
                success_status: 200,
                ..Default::default()
            },
            repository: None,
            idempotency: crate::route::RouteIdempotency::Direct,
            timeout: crate::route::RouteTimeout::Inherit,
            api_version: None,
            sunset_opt_out: false,
        }
    }

    #[cfg(feature = "i18n")]
    fn test_i18n_bundle(key: &str, value: &str) -> Arc<crate::i18n::Bundle> {
        let mut messages = std::collections::HashMap::new();
        let mut en = std::collections::HashMap::new();
        en.insert(key.to_owned(), value.to_owned());
        messages.insert("en".to_owned(), en);
        Arc::new(crate::i18n::Bundle::from_messages(
            messages,
            &crate::i18n::I18nConfig::default(),
        ))
    }

    #[cfg(feature = "i18n")]
    #[test]
    fn i18n_auto_defers_loading_until_runtime_config_is_available() {
        let builder = app().i18n_auto();

        assert!(builder.i18n_bundle.is_none());
        assert!(builder.i18n_auto_load);
    }

    #[cfg(feature = "i18n")]
    #[derive(Clone)]
    struct StaticConfigLoader {
        config: AutumnConfig,
    }

    #[cfg(feature = "i18n")]
    impl crate::config::ConfigLoader for StaticConfigLoader {
        async fn load(&self) -> Result<AutumnConfig, crate::config::ConfigError> {
            Ok(self.config.clone())
        }
    }

    #[cfg(feature = "i18n")]
    struct NoopTelemetryProvider;

    #[cfg(feature = "i18n")]
    impl crate::telemetry::TelemetryProvider for NoopTelemetryProvider {
        fn init(
            &self,
            _log: &crate::config::LogConfig,
            _telemetry: &crate::config::TelemetryConfig,
            _profile: Option<&str>,
        ) -> Result<crate::telemetry::TelemetryGuard, crate::telemetry::TelemetryInitError>
        {
            Ok(crate::telemetry::TelemetryGuard::disabled())
        }
    }

    #[cfg(feature = "i18n")]
    #[tokio::test]
    async fn i18n_auto_uses_config_loader_output_for_bundle_dir() {
        let project = tempfile::tempdir().expect("project dir");
        let i18n_dir = project.path().join("custom-i18n");
        std::fs::create_dir_all(&i18n_dir).expect("i18n dir");
        std::fs::write(i18n_dir.join("en.ftl"), "nav.home = Loader Home\n").expect("bundle");

        let mut config = AutumnConfig::default();
        config.i18n.dir = "custom-i18n".to_owned();
        let builder = app()
            .with_config_loader(StaticConfigLoader { config })
            .with_telemetry_provider(NoopTelemetryProvider)
            .i18n_auto();
        let AppBuilder {
            config_loader_factory,
            telemetry_provider,
            i18n_bundle,
            i18n_auto_load,
            plugin_config_roots,
            ..
        } = builder;

        let (loaded_config, _guard) = load_config_and_telemetry(
            config_loader_factory,
            telemetry_provider,
            plugin_config_roots,
        )
        .await;
        let env = crate::config::MockEnv::new().with(
            "AUTUMN_MANIFEST_DIR",
            project.path().to_str().expect("utf-8 path"),
        );
        let bundle = resolve_i18n_bundle(i18n_bundle, i18n_auto_load, &loaded_config, &env)
            .expect("bundle loaded from configured dir");

        assert_eq!(bundle.translate("en", "nav.home", &[]), "Loader Home");
    }

    #[cfg(feature = "i18n")]
    #[tokio::test]
    async fn i18n_bundle_layer_is_applied_to_static_route_rendering() {
        async fn localized(locale: crate::i18n::Locale) -> String {
            locale.t("nav.home")
        }

        let config = AutumnConfig::default();
        let state = AppState::for_test();
        let custom_layers = install_i18n_bundle_layer(
            Vec::new(),
            &state,
            Some(test_i18n_bundle("nav.home", "Home")),
        );
        let router = crate::router::try_build_router_inner(
            vec![Route {
                method: http::Method::GET,
                path: "/about",
                handler: axum::routing::get(localized),
                name: "localized",
                api_doc: crate::openapi::ApiDoc {
                    method: "GET",
                    path: "/about",
                    operation_id: "localized",
                    success_status: 200,
                    ..Default::default()
                },
                repository: None,
                idempotency: crate::route::RouteIdempotency::Direct,
                timeout: crate::route::RouteTimeout::Inherit,
                api_version: None,
                sunset_opt_out: false,
            }],
            &config,
            state,
            crate::router::RouterContext {
                exception_filters: Vec::new(),
                scoped_groups: Vec::new(),
                merge_routers: Vec::new(),
                nest_routers: Vec::new(),
                custom_layers,
                static_gate_layers: Vec::new(),
                #[cfg(feature = "maud")]
                error_page_renderer: None,
                session_store: None,
                #[cfg(feature = "openapi")]
                openapi: None,
                #[cfg(feature = "mcp")]
                mcp: None,
            },
        )
        .expect("router builds");
        let tmp = tempfile::tempdir().expect("dist parent");
        let dist = tmp.path().join("dist");

        crate::static_gen::render_static_routes(
            router,
            &[crate::static_gen::StaticRouteMeta {
                path: "/about",
                name: "localized",
                revalidate: None,
                params_fn: None,
            }],
            &dist,
        )
        .await
        .expect("static render succeeds");

        let html = std::fs::read_to_string(dist.join("about/index.html")).expect("rendered html");
        assert_eq!(html, "Home");
    }

    #[test]
    fn app_builder_routes_adds_routes() {
        let builder = app();
        assert_eq!(builder.routes.len(), 0);

        let builder = builder.routes(vec![test_get_route("/1", "route1")]);
        assert_eq!(builder.routes.len(), 1);

        let builder = builder.routes(vec![
            test_get_route("/2", "route2"),
            test_get_route("/3", "route3"),
        ]);
        assert_eq!(builder.routes.len(), 3);

        assert_eq!(builder.routes[0].path, "/1");
        assert_eq!(builder.routes[1].path, "/2");
        assert_eq!(builder.routes[2].path, "/3");
    }

    #[test]
    fn app_builder_extensions_store_and_update_typed_values() {
        let builder = app()
            .with_extension::<String>("haunted".into())
            .update_extension::<String, _, _>(String::new, |value| value.push_str(" harvest"));

        let value = builder
            .extension::<String>()
            .expect("string extension should be present");
        assert_eq!(value, "haunted harvest");
    }

    #[cfg(feature = "mail")]
    #[tokio::test]
    async fn app_builder_with_mail_delivery_queue_stores_queue_for_install() {
        let builder = app().with_mail_delivery_queue(MailTestNoopQueue);
        let factory = builder
            .mail_delivery_queue_factory
            .expect("with_mail_delivery_queue should store a factory on the builder");

        // Invoke the trivial wrapper closure built by with_mail_delivery_queue
        // and verify it returns the wrapped queue successfully.
        let state = AppState::for_test();
        let queue = factory(&state).expect("trivial factory should produce the queue");
        assert!(Arc::strong_count(&queue) >= 1);
        // Cover the enqueue method body by invoking it once.
        queue
            .enqueue(test_mail())
            .await
            .expect("noop queue should always succeed");
    }

    #[cfg(feature = "mail")]
    #[test]
    fn app_builder_with_mail_delivery_queue_factory_runs_with_app_state() {
        let observed_profile: Arc<std::sync::Mutex<Option<String>>> =
            Arc::new(std::sync::Mutex::new(None));
        let captured = Arc::clone(&observed_profile);
        let builder = app().with_mail_delivery_queue_factory(move |state| {
            *captured.lock().expect("lock") = Some(state.profile().to_owned());
            Ok::<_, crate::AutumnError>(MailTestNoopQueue)
        });

        let factory = builder
            .mail_delivery_queue_factory
            .expect("factory should be stored on the builder");
        let state = AppState::for_test().with_profile("dev");
        let _queue = factory(&state).expect("factory should succeed");

        assert_eq!(
            observed_profile.lock().expect("lock").as_deref(),
            Some("dev"),
            "factory must run with the live AppState"
        );
    }

    #[cfg(feature = "mail")]
    #[test]
    fn app_builder_with_mail_delivery_queue_factory_propagates_errors() {
        let builder = app().with_mail_delivery_queue_factory(|_state| {
            Err::<MailTestNoopQueue, _>(crate::AutumnError::service_unavailable_msg("factory boom"))
        });

        let factory = builder
            .mail_delivery_queue_factory
            .expect("factory present");
        let state = AppState::for_test();
        match factory(&state) {
            Ok(_) => panic!("factory should have errored"),
            Err(err) => assert!(err.to_string().contains("factory boom")),
        }
    }

    #[tokio::test]
    async fn startup_and_shutdown_hooks_run_in_expected_order() {
        let events = Arc::new(std::sync::Mutex::new(Vec::<&'static str>::new()));
        let startup_events = Arc::clone(&events);
        let shutdown_a = Arc::clone(&events);
        let shutdown_b = Arc::clone(&events);
        let builder = app()
            .on_startup(move |_state| {
                let startup_events = Arc::clone(&startup_events);
                async move {
                    startup_events
                        .lock()
                        .expect("events lock poisoned")
                        .push("start");
                    Ok(())
                }
            })
            .on_shutdown(move || {
                let shutdown_a = Arc::clone(&shutdown_a);
                async move {
                    shutdown_a
                        .lock()
                        .expect("events lock poisoned")
                        .push("stop-a");
                }
            })
            .on_shutdown(move || {
                let shutdown_b = Arc::clone(&shutdown_b);
                async move {
                    shutdown_b
                        .lock()
                        .expect("events lock poisoned")
                        .push("stop-b");
                }
            });

        run_startup_hooks(&builder.startup_hooks, AppState::for_test())
            .await
            .expect("startup hooks should succeed");
        run_shutdown_hooks(&builder.shutdown_hooks).await;

        let recorded_events = events.lock().expect("events lock poisoned").clone();
        assert_eq!(recorded_events, vec!["start", "stop-b", "stop-a"]);
    }

    fn startup_noop_job_handler(
        _state: AppState,
        _payload: serde_json::Value,
    ) -> Pin<Box<dyn Future<Output = crate::AutumnResult<()>> + Send + 'static>> {
        Box::pin(async move { Ok(()) })
    }

    #[tokio::test]
    async fn startup_hooks_can_enqueue_jobs_after_runtime_init() {
        let _guard = crate::job::global_job_runtime_test_lock().lock().await;
        crate::job::clear_global_job_client();

        let builder = app()
            .jobs(vec![crate::job::JobInfo {
                version: 1,
                name: "startup-seed".to_string(),
                max_attempts: 1,
                initial_backoff_ms: 1,
                queue: "default".to_string(),
                uniqueness: None,
                concurrency: None,
                handler: startup_noop_job_handler,
            }])
            .on_startup(|_state| async {
                crate::job::enqueue("startup-seed", serde_json::json!({ "kind": "warmup" })).await
            });

        let state = AppState::for_test().with_profile("dev");
        let shutdown = tokio_util::sync::CancellationToken::new();

        initialize_job_runtime(
            builder.jobs.clone(),
            &state,
            &shutdown,
            &crate::config::JobConfig::default(),
            true,
        )
        .expect("job runtime should initialize before startup hooks");

        run_startup_hooks(&builder.startup_hooks, state.clone())
            .await
            .expect("startup hook should be able to enqueue jobs");

        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            loop {
                let snapshot = state.job_registry().snapshot();
                let status = snapshot
                    .get("startup-seed")
                    .expect("job should be registered before startup hooks run");
                if status.total_successes == 1 {
                    break;
                }
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("startup-enqueued job should complete");

        shutdown.cancel();
        crate::job::clear_global_job_client();
    }

    #[tokio::test]
    async fn initialize_job_runtime_propagates_redis_init_errors() {
        let _guard = crate::job::global_job_runtime_test_lock().lock().await;
        crate::job::clear_global_job_client();

        let state = AppState::for_test().with_profile("dev");
        let shutdown = tokio_util::sync::CancellationToken::new();
        let config = crate::config::JobConfig {
            backend: "redis".to_string(),
            ..Default::default()
        };

        let error = initialize_job_runtime(
            vec![crate::job::JobInfo {
                version: 1,
                name: "startup-seed".to_string(),
                max_attempts: 1,
                initial_backoff_ms: 1,
                queue: "default".to_string(),
                uniqueness: None,
                concurrency: None,
                handler: startup_noop_job_handler,
            }],
            &state,
            &shutdown,
            &config,
            true,
        )
        .expect_err("redis init errors should abort startup");

        #[cfg(feature = "redis")]
        assert!(
            error
                .to_string()
                .contains("jobs.backend=redis requires jobs.redis.url"),
            "unexpected error: {error}"
        );

        #[cfg(not(feature = "redis"))]
        assert!(
            error
                .to_string()
                .contains("jobs.backend=redis requested but redis feature is disabled"),
            "unexpected error: {error}"
        );
    }

    #[tokio::test]
    async fn startup_hook_errors_propagate() {
        let builder = app().on_startup(|_state| async {
            Err(crate::AutumnError::service_unavailable_msg(
                "startup ritual failed",
            ))
        });

        let error = run_startup_hooks(&builder.startup_hooks, AppState::for_test())
            .await
            .expect_err("startup hook should fail");
        assert!(error.to_string().contains("startup ritual failed"));
    }

    #[tokio::test]
    async fn build_router_mounts_user_routes() {
        let router = test_router(vec![test_get_route("/test", "test_handler")]);

        let response = router
            .oneshot(Request::builder().uri("/test").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(&body[..], b"ok");
    }

    #[tokio::test]
    async fn build_router_mounts_health_check_at_default_path() {
        let router = test_router(vec![test_get_route("/dummy", "dummy")]);

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["status"], "ok");
    }

    #[tokio::test]
    async fn build_router_mounts_health_check_at_custom_path() {
        let mut config = AutumnConfig::default();
        config.health.path = "/healthz".to_owned();
        let state = AppState {
            extensions: std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            #[cfg(feature = "db")]
            pool: None,
            #[cfg(feature = "db")]
            replica_pool: None,
            #[cfg(feature = "db")]
            shards: None,
            profile: None,
            role: crate::config::ProcessRole::Combined,
            started_at: std::time::Instant::now(),
            health_detailed: true,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            job_registry: crate::actuator::JobRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            metrics_source_registry: crate::actuator::MetricsSourceRegistry::new(),
            health_indicator_registry: crate::actuator::HealthIndicatorRegistry::new(),
            #[cfg(feature = "ws")]
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "presence")]
            presence: crate::presence::Presence::new(crate::channels::Channels::new(32)),
            #[cfg(feature = "ws")]
            shutdown: tokio_util::sync::CancellationToken::new(),
            policy_registry: crate::authorization::PolicyRegistry::default(),
            forbidden_response: crate::authorization::ForbiddenResponse::default(),
            auth_session_key: "user_id".to_owned(),
            shared_cache: None,
            clock: std::sync::Arc::new(crate::time::SystemClock),
            app_id: AppState::next_app_id(),
        };
        let router =
            crate::router::build_router(vec![test_get_route("/dummy", "dummy")], &config, state);

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/healthz")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn build_router_adds_request_id_header() {
        let router = test_router(vec![test_get_route("/test", "test")]);

        let response = router
            .oneshot(Request::builder().uri("/test").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert!(response.headers().contains_key("x-request-id"));
    }

    #[tokio::test]
    async fn build_router_unknown_route_returns_404() {
        let router = test_router(vec![test_get_route("/exists", "exists")]);

        let response = router
            .oneshot(Request::builder().uri("/nope").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn build_router_multiple_routes() {
        let router = test_router(vec![test_get_route("/a", "a"), test_get_route("/b", "b")]);

        let resp_a = router
            .clone()
            .oneshot(Request::builder().uri("/a").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp_a.status(), StatusCode::OK);

        let resp_b = router
            .oneshot(Request::builder().uri("/b").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp_b.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn build_router_post_route() {
        let post_routes = vec![Route {
            method: http::Method::POST,
            path: "/submit",
            handler: axum::routing::post(|| async { "posted" }),
            name: "submit",
            api_doc: crate::openapi::ApiDoc {
                method: "POST",
                path: "/submit",
                operation_id: "submit",
                success_status: 200,
                ..Default::default()
            },
            repository: None,
            idempotency: crate::route::RouteIdempotency::Direct,
            timeout: crate::route::RouteTimeout::Inherit,
            api_version: None,
            sunset_opt_out: false,
        }];
        let config = AutumnConfig::default();
        let state = AppState {
            extensions: std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            #[cfg(feature = "db")]
            pool: None,
            #[cfg(feature = "db")]
            replica_pool: None,
            #[cfg(feature = "db")]
            shards: None,
            profile: None,
            role: crate::config::ProcessRole::Combined,
            started_at: std::time::Instant::now(),
            health_detailed: true,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            job_registry: crate::actuator::JobRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            metrics_source_registry: crate::actuator::MetricsSourceRegistry::new(),
            health_indicator_registry: crate::actuator::HealthIndicatorRegistry::new(),
            #[cfg(feature = "ws")]
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "presence")]
            presence: crate::presence::Presence::new(crate::channels::Channels::new(32)),
            #[cfg(feature = "ws")]
            shutdown: tokio_util::sync::CancellationToken::new(),
            policy_registry: crate::authorization::PolicyRegistry::default(),
            forbidden_response: crate::authorization::ForbiddenResponse::default(),
            auth_session_key: "user_id".to_owned(),
            shared_cache: None,
            clock: std::sync::Arc::new(crate::time::SystemClock),
            app_id: AppState::next_app_id(),
        };
        let router = crate::router::build_router(post_routes, &config, state);

        let response = router
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/submit")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn build_router_merges_methods_on_same_path() {
        let route_list = vec![
            Route {
                method: http::Method::GET,
                path: "/admin",
                handler: axum::routing::get(|| async { "list" }),
                name: "admin_list",
                api_doc: crate::openapi::ApiDoc {
                    method: "GET",
                    path: "/admin",
                    operation_id: "admin_list",
                    success_status: 200,
                    ..Default::default()
                },
                repository: None,
                idempotency: crate::route::RouteIdempotency::Direct,
                timeout: crate::route::RouteTimeout::Inherit,
                api_version: None,
                sunset_opt_out: false,
            },
            Route {
                method: http::Method::POST,
                path: "/admin",
                handler: axum::routing::post(|| async { "created" }),
                name: "create",
                api_doc: crate::openapi::ApiDoc {
                    method: "POST",
                    path: "/admin",
                    operation_id: "create",
                    success_status: 200,
                    ..Default::default()
                },
                repository: None,
                idempotency: crate::route::RouteIdempotency::Direct,
                timeout: crate::route::RouteTimeout::Inherit,
                api_version: None,
                sunset_opt_out: false,
            },
        ];
        let config = AutumnConfig::default();
        let router = crate::router::build_router(route_list, &config, AppState::for_test());

        // GET /admin should return "list"
        let resp = router
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/admin")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(&body[..], b"list");

        // POST /admin should return "created" (not 405!)
        let resp = router
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/admin")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(&body[..], b"created");
    }

    #[cfg(feature = "htmx")]
    #[tokio::test]
    async fn htmx_handler_returns_javascript_with_correct_headers() {
        let app = axum::Router::new().route(
            crate::htmx::HTMX_JS_PATH,
            axum::routing::get(crate::router::htmx_handler),
        );

        let response = app
            .oneshot(
                Request::builder()
                    .uri(crate::htmx::HTMX_JS_PATH)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);

        let content_type = response
            .headers()
            .get("content-type")
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            content_type.contains("application/javascript"),
            "Expected application/javascript, got {content_type}"
        );

        let cache_control = response
            .headers()
            .get("cache-control")
            .unwrap()
            .to_str()
            .unwrap();
        assert!(
            cache_control.contains("immutable"),
            "Expected immutable cache, got {cache_control}"
        );

        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();

        // Body length matches the embedded file
        assert_eq!(body.len(), crate::htmx::HTMX_JS.len());

        // Body starts with valid JavaScript
        let start = std::str::from_utf8(&body[..50]).expect("htmx should be valid UTF-8");
        assert!(
            start.contains("htmx") || start.contains("function"),
            "Response doesn't look like htmx JavaScript: {start}"
        );
    }

    #[cfg(feature = "htmx")]
    #[tokio::test]
    async fn htmx_csrf_handler_returns_csp_compatible_javascript() {
        let app = axum::Router::new().route(
            crate::htmx::HTMX_CSRF_JS_PATH,
            axum::routing::get(crate::router::htmx_csrf_handler),
        );

        let response = app
            .oneshot(
                Request::builder()
                    .uri(crate::htmx::HTMX_CSRF_JS_PATH)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get("content-type")
                .and_then(|value| value.to_str().ok()),
            Some("application/javascript")
        );

        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let js = std::str::from_utf8(&body).expect("csrf helper should be valid utf-8");

        assert!(js.contains("htmx:configRequest"));
        assert!(js.contains("X-CSRF-Token"));
        assert!(!js.contains("<script"));
    }

    #[cfg(feature = "htmx")]
    #[tokio::test]
    async fn build_router_serves_htmx_js() {
        let router = test_router(vec![test_get_route("/dummy", "dummy")]);

        let response = router
            .oneshot(
                Request::builder()
                    .uri(crate::htmx::HTMX_JS_PATH)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let ct = response
            .headers()
            .get("content-type")
            .unwrap()
            .to_str()
            .unwrap();
        assert!(ct.contains("javascript"));
    }

    #[cfg(feature = "htmx")]
    #[tokio::test]
    async fn build_router_serves_htmx_csrf_js() {
        let router = test_router(vec![test_get_route("/dummy", "dummy")]);

        let response = router
            .oneshot(
                Request::builder()
                    .uri(crate::htmx::HTMX_CSRF_JS_PATH)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let csp = response
            .headers()
            .get("content-security-policy")
            .expect("framework JS should still receive security headers")
            .to_str()
            .unwrap();
        assert!(csp.contains("script-src 'self'"), "csp = {csp}");
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let js = std::str::from_utf8(&body).expect("csrf helper should be valid utf-8");
        assert!(js.contains("htmx:configRequest"));
        assert!(js.contains("X-CSRF-Token"));
    }

    #[tokio::test]
    async fn build_router_serves_default_favicon_without_404() {
        let router = test_router(vec![test_get_route("/dummy", "dummy")]);

        let response = router
            .oneshot(
                Request::builder()
                    .uri(crate::router::DEFAULT_FAVICON_PATH)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::NO_CONTENT);
        assert!(
            response.headers().contains_key("content-security-policy"),
            "framework fallback responses should still receive security headers"
        );
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert!(body.is_empty());
    }

    #[tokio::test]
    async fn build_router_does_not_override_user_favicon_route() {
        let router = test_router(vec![test_get_route(
            crate::router::DEFAULT_FAVICON_PATH,
            "favicon",
        )]);

        let response = router
            .oneshot(
                Request::builder()
                    .uri(crate::router::DEFAULT_FAVICON_PATH)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(&body[..], b"ok");
    }

    #[tokio::test]
    async fn build_router_serves_static_files_for_unmatched_paths() {
        use std::collections::HashMap;

        // Create a temp dist/ with a static page
        let tmp = tempfile::tempdir().expect("tempdir");
        let dist = tmp.path().join("dist");
        std::fs::create_dir_all(dist.join("docs")).expect("mkdir");
        std::fs::write(dist.join("docs/index.html"), "<h1>Static Docs</h1>").expect("write");

        let manifest = crate::static_gen::StaticManifest {
            generated_at: "2026-03-27T00:00:00Z".to_owned(),
            autumn_version: "0.2.0".to_owned(),
            routes: HashMap::from([(
                "/docs".to_owned(),
                crate::static_gen::ManifestEntry {
                    file: "docs/index.html".to_owned(),
                    revalidate: None,
                },
            )]),
        };
        let json = serde_json::to_string(&manifest).expect("serialize");
        std::fs::write(dist.join("manifest.json"), json).expect("write manifest");

        // No dynamic route for /docs — only a static file.
        let config = AutumnConfig::default();
        let state = AppState {
            extensions: std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            #[cfg(feature = "db")]
            pool: None,
            #[cfg(feature = "db")]
            replica_pool: None,
            #[cfg(feature = "db")]
            shards: None,
            profile: None,
            role: crate::config::ProcessRole::Combined,
            started_at: std::time::Instant::now(),
            health_detailed: true,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            job_registry: crate::actuator::JobRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            metrics_source_registry: crate::actuator::MetricsSourceRegistry::new(),
            health_indicator_registry: crate::actuator::HealthIndicatorRegistry::new(),
            #[cfg(feature = "ws")]
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "presence")]
            presence: crate::presence::Presence::new(crate::channels::Channels::new(32)),
            #[cfg(feature = "ws")]
            shutdown: tokio_util::sync::CancellationToken::new(),
            policy_registry: crate::authorization::PolicyRegistry::default(),
            forbidden_response: crate::authorization::ForbiddenResponse::default(),
            auth_session_key: "user_id".to_owned(),
            shared_cache: None,
            clock: std::sync::Arc::new(crate::time::SystemClock),
            app_id: AppState::next_app_id(),
        };
        let router = crate::router::build_router_with_static(
            vec![test_get_route("/other", "other_page")],
            &config,
            state,
            Some(dist.as_path()),
        );

        // GET /docs/ should serve the pre-built HTML via static-first
        // middleware (manifest lookup with trailing-slash normalization).
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/docs/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let csp = response
            .headers()
            .get("content-security-policy")
            .expect("static-first HTML should still receive security headers")
            .to_str()
            .unwrap();
        assert!(csp.contains("script-src 'self'"), "csp = {csp}");
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(std::str::from_utf8(&body).unwrap(), "<h1>Static Docs</h1>");
    }

    #[tokio::test]
    async fn build_mode_static_rendering_bypasses_startup_barrier() {
        temp_env::async_with_vars([("AUTUMN_BUILD_STATIC", Some("1"))], async {
            let config = AutumnConfig::default();
            let state = AppState::for_test().with_startup_complete(false);
            let router = crate::router::build_router(
                vec![Route {
                    method: http::Method::GET,
                    path: "/about",
                    handler: axum::routing::get(|| async { "About Page Content" }),
                    name: "about",
                    api_doc: crate::openapi::ApiDoc {
                        method: "GET",
                        path: "/about",
                        operation_id: "about",
                        success_status: 200,
                        ..Default::default()
                    },
                    repository: None,
                    idempotency: crate::route::RouteIdempotency::Direct,
                    timeout: crate::route::RouteTimeout::Inherit,
                    api_version: None,
                    sunset_opt_out: false,
                }],
                &config,
                state,
            );
            let tmp = tempfile::tempdir().unwrap();
            let dist = tmp.path().join("dist");

            let result = crate::static_gen::render_static_routes(
                router,
                &[crate::static_gen::StaticRouteMeta {
                    path: "/about",
                    name: "about",
                    revalidate: None,
                    params_fn: None,
                }],
                &dist,
            )
            .await;

            assert!(result.is_ok(), "build failed: {:?}", result.err());
            let html = std::fs::read_to_string(dist.join("about/index.html")).unwrap();
            assert_eq!(html, "About Page Content");
        })
        .await;
    }

    #[tokio::test]
    async fn build_router_injects_live_reload_script_when_enabled() {
        let reload_file = tempfile::NamedTempFile::new().expect("reload state file");
        std::fs::write(reload_file.path(), r#"{"version":0,"kind":"full"}"#).expect("write");
        temp_env::async_with_vars(
            [
                ("AUTUMN_DEV_RELOAD", Some("1")),
                (
                    "AUTUMN_DEV_RELOAD_STATE",
                    Some(reload_file.path().to_str().expect("utf-8 path")),
                ),
            ],
            async {
                let router = test_router(vec![Route {
                    method: http::Method::GET,
                    path: "/page",
                    handler: axum::routing::get(|| async {
                        axum::response::Html("<html><body><main>ok</main></body></html>")
                    }),
                    name: "page",
                    api_doc: crate::openapi::ApiDoc {
                        method: "GET",
                        path: "/page",
                        operation_id: "page",
                        success_status: 200,
                        ..Default::default()
                    },
                    repository: None,
                    idempotency: crate::route::RouteIdempotency::Direct,
                    timeout: crate::route::RouteTimeout::Inherit,
                    api_version: None,
                    sunset_opt_out: false,
                }]);

                let response = router
                    .oneshot(Request::builder().uri("/page").body(Body::empty()).unwrap())
                    .await
                    .unwrap();

                let body = axum::body::to_bytes(response.into_body(), usize::MAX)
                    .await
                    .unwrap();
                let html = std::str::from_utf8(&body).expect("utf-8");
                assert!(html.contains("/__autumn/live-reload"));
            },
        )
        .await;
    }

    #[tokio::test]
    async fn build_router_mounts_dev_reload_script_endpoint_when_enabled() {
        // The injected <script src="/__autumn/live-reload.js"> tag only works
        // under the default CSP (`script-src 'self'`) if the framework
        // actually serves the JS at that path. This guards against the
        // regression where the script endpoint is forgotten.
        let reload_file = tempfile::NamedTempFile::new().expect("reload state file");
        std::fs::write(reload_file.path(), r#"{"version":0,"kind":"full"}"#).expect("write");
        temp_env::async_with_vars(
            [
                ("AUTUMN_DEV_RELOAD", Some("1")),
                (
                    "AUTUMN_DEV_RELOAD_STATE",
                    Some(reload_file.path().to_str().expect("utf-8 path")),
                ),
            ],
            async {
                let router = test_router(vec![test_get_route("/dummy", "dummy")]);

                let response = router
                    .oneshot(
                        Request::builder()
                            .uri("/__autumn/live-reload.js")
                            .body(Body::empty())
                            .unwrap(),
                    )
                    .await
                    .unwrap();

                assert_eq!(response.status(), StatusCode::OK);
                assert_eq!(
                    response
                        .headers()
                        .get("content-type")
                        .and_then(|v| v.to_str().ok()),
                    Some("application/javascript; charset=utf-8")
                );
                let body = axum::body::to_bytes(response.into_body(), usize::MAX)
                    .await
                    .unwrap();
                let js = std::str::from_utf8(&body).expect("utf-8");
                assert!(js.contains("fetch("), "js body: {js}");
            },
        )
        .await;
    }

    #[tokio::test]
    async fn build_router_mounts_dev_reload_endpoint_when_enabled() {
        let reload_file = tempfile::NamedTempFile::new().expect("reload state file");
        std::fs::write(reload_file.path(), r#"{"version":7,"kind":"css"}"#).expect("write");
        temp_env::async_with_vars(
            [
                ("AUTUMN_DEV_RELOAD", Some("1")),
                (
                    "AUTUMN_DEV_RELOAD_STATE",
                    Some(reload_file.path().to_str().expect("utf-8 path")),
                ),
            ],
            async {
                let router = test_router(vec![test_get_route("/dummy", "dummy")]);

                let response = router
                    .oneshot(
                        Request::builder()
                            .uri("/__autumn/live-reload")
                            .body(Body::empty())
                            .unwrap(),
                    )
                    .await
                    .unwrap();

                assert_eq!(response.status(), StatusCode::OK);
                assert_eq!(
                    response.headers().get("cache-control").unwrap(),
                    "no-store, no-cache, must-revalidate"
                );
                let body = axum::body::to_bytes(response.into_body(), usize::MAX)
                    .await
                    .unwrap();
                assert_eq!(&body[..], br#"{"version":7,"kind":"css"}"#);
            },
        )
        .await;
    }

    #[tokio::test]
    async fn build_router_disables_cache_for_static_assets_in_dev_reload_mode() {
        let project = tempfile::tempdir().expect("project dir");
        let static_dir = project.path().join("static");
        std::fs::create_dir_all(&static_dir).expect("mkdir");
        std::fs::write(static_dir.join("demo.txt"), "hello").expect("write static file");
        let reload_file = tempfile::NamedTempFile::new().expect("reload state file");
        std::fs::write(reload_file.path(), r#"{"version":0,"kind":"full"}"#).expect("write");
        temp_env::async_with_vars(
            [
                (
                    "AUTUMN_MANIFEST_DIR",
                    Some(project.path().to_str().expect("utf-8 path")),
                ),
                ("AUTUMN_DEV_RELOAD", Some("1")),
                (
                    "AUTUMN_DEV_RELOAD_STATE",
                    Some(reload_file.path().to_str().expect("utf-8 path")),
                ),
            ],
            async {
                let router = test_router(vec![test_get_route("/dummy", "dummy")]);

                let response = router
                    .oneshot(
                        Request::builder()
                            .uri("/static/demo.txt")
                            .body(Body::empty())
                            .unwrap(),
                    )
                    .await
                    .unwrap();

                assert_eq!(response.status(), StatusCode::OK);
                assert_eq!(
                    response.headers().get("cache-control").unwrap(),
                    "no-store, no-cache, must-revalidate"
                );
            },
        )
        .await;
    }

    #[test]
    fn app_builder_accepts_static_routes() {
        use crate::static_gen::StaticRouteMeta;
        let metas = vec![StaticRouteMeta {
            path: "/about",
            name: "about",
            revalidate: None,
            params_fn: None,
        }];
        let builder = app().static_routes(metas);
        assert_eq!(builder.static_metas.len(), 1);
    }

    #[test]
    fn project_dir_defaults_to_subdir() {
        // When AUTUMN_MANIFEST_DIR is not set, project_dir returns the
        // subdir name as-is (relative to cwd).
        let env = crate::config::MockEnv::new();
        let dir = super::project_dir("dist", &env);
        assert_eq!(dir, std::path::PathBuf::from("dist"));
    }

    /// Helper to build a test router with custom config.
    pub fn test_router_with_config(routes: Vec<Route>, config: &AutumnConfig) -> axum::Router {
        let state = AppState {
            extensions: std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            #[cfg(feature = "db")]
            pool: None,
            #[cfg(feature = "db")]
            replica_pool: None,
            #[cfg(feature = "db")]
            shards: None,
            profile: None,
            role: crate::config::ProcessRole::Combined,
            started_at: std::time::Instant::now(),
            health_detailed: true,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            job_registry: crate::actuator::JobRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            metrics_source_registry: crate::actuator::MetricsSourceRegistry::new(),
            health_indicator_registry: crate::actuator::HealthIndicatorRegistry::new(),
            #[cfg(feature = "ws")]
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "presence")]
            presence: crate::presence::Presence::new(crate::channels::Channels::new(32)),
            #[cfg(feature = "ws")]
            shutdown: tokio_util::sync::CancellationToken::new(),
            policy_registry: crate::authorization::PolicyRegistry::default(),
            forbidden_response: crate::authorization::ForbiddenResponse::default(),
            auth_session_key: "user_id".to_owned(),
            shared_cache: None,
            clock: std::sync::Arc::new(crate::time::SystemClock),
            app_id: AppState::next_app_id(),
        };
        crate::router::build_router(routes, config, state)
    }

    #[tokio::test]
    async fn cors_wildcard_allows_any_origin() {
        let mut config = AutumnConfig::default();
        config.cors.allowed_origins = vec!["*".to_owned()];
        let router = test_router_with_config(vec![test_get_route("/test", "test")], &config);

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/test")
                    .header("Origin", "https://example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get("access-control-allow-origin")
                .unwrap(),
            "*"
        );
    }

    #[tokio::test]
    async fn cors_specific_origin_reflected() {
        let mut config = AutumnConfig::default();
        config.cors.allowed_origins = vec!["https://example.com".to_owned()];
        let router = test_router_with_config(vec![test_get_route("/test", "test")], &config);

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/test")
                    .header("Origin", "https://example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get("access-control-allow-origin")
                .unwrap(),
            "https://example.com"
        );
    }

    #[tokio::test]
    async fn cors_disabled_when_no_origins() {
        let config = AutumnConfig::default();
        assert!(config.cors.allowed_origins.is_empty());
        let router = test_router_with_config(vec![test_get_route("/test", "test")], &config);

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/test")
                    .header("Origin", "https://example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert!(
            response
                .headers()
                .get("access-control-allow-origin")
                .is_none()
        );
    }

    #[tokio::test]
    async fn cors_preflight_returns_204() {
        let mut config = AutumnConfig::default();
        config.cors.allowed_origins = vec!["https://example.com".to_owned()];
        let router = test_router_with_config(vec![test_get_route("/test", "test")], &config);

        let response = router
            .oneshot(
                Request::builder()
                    .method("OPTIONS")
                    .uri("/test")
                    .header("Origin", "https://example.com")
                    .header("Access-Control-Request-Method", "GET")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert!(
            response
                .headers()
                .contains_key("access-control-allow-methods")
        );
    }

    #[tokio::test]
    async fn build_router_with_static_skips_without_manifest() {
        // When dist/ exists but has no manifest.json, fall back to
        // the app router without the static layer.
        let tmp = tempfile::tempdir().expect("tempdir");
        let dist = tmp.path().join("dist");
        std::fs::create_dir_all(&dist).expect("mkdir");
        // No manifest.json — just an empty dist/

        let config = AutumnConfig::default();
        let state = AppState {
            extensions: std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            #[cfg(feature = "db")]
            pool: None,
            #[cfg(feature = "db")]
            replica_pool: None,
            #[cfg(feature = "db")]
            shards: None,
            profile: None,
            role: crate::config::ProcessRole::Combined,
            started_at: std::time::Instant::now(),
            health_detailed: true,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            job_registry: crate::actuator::JobRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            metrics_source_registry: crate::actuator::MetricsSourceRegistry::new(),
            health_indicator_registry: crate::actuator::HealthIndicatorRegistry::new(),
            #[cfg(feature = "ws")]
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "presence")]
            presence: crate::presence::Presence::new(crate::channels::Channels::new(32)),
            #[cfg(feature = "ws")]
            shutdown: tokio_util::sync::CancellationToken::new(),
            policy_registry: crate::authorization::PolicyRegistry::default(),
            forbidden_response: crate::authorization::ForbiddenResponse::default(),
            auth_session_key: "user_id".to_owned(),
            shared_cache: None,
            clock: std::sync::Arc::new(crate::time::SystemClock),
            app_id: AppState::next_app_id(),
        };
        let router = crate::router::build_router_with_static(
            vec![test_get_route("/test", "test")],
            &config,
            state,
            Some(dist.as_path()),
        );

        let response = router
            .oneshot(Request::builder().uri("/test").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn build_router_with_static_none_dist() {
        // When dist_dir is None, return the app router directly.
        let config = AutumnConfig::default();
        let state = AppState {
            extensions: std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            #[cfg(feature = "db")]
            pool: None,
            #[cfg(feature = "db")]
            replica_pool: None,
            #[cfg(feature = "db")]
            shards: None,
            profile: None,
            role: crate::config::ProcessRole::Combined,
            started_at: std::time::Instant::now(),
            health_detailed: true,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            job_registry: crate::actuator::JobRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            metrics_source_registry: crate::actuator::MetricsSourceRegistry::new(),
            health_indicator_registry: crate::actuator::HealthIndicatorRegistry::new(),
            #[cfg(feature = "ws")]
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "presence")]
            presence: crate::presence::Presence::new(crate::channels::Channels::new(32)),
            #[cfg(feature = "ws")]
            shutdown: tokio_util::sync::CancellationToken::new(),
            policy_registry: crate::authorization::PolicyRegistry::default(),
            forbidden_response: crate::authorization::ForbiddenResponse::default(),
            auth_session_key: "user_id".to_owned(),
            shared_cache: None,
            clock: std::sync::Arc::new(crate::time::SystemClock),
            app_id: AppState::next_app_id(),
        };
        let router = crate::router::build_router_with_static(
            vec![test_get_route("/test", "test")],
            &config,
            state,
            None,
        );

        let response = router
            .oneshot(Request::builder().uri("/test").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }

    // ── Startup transparency helper tests ─────────────────────────

    #[test]
    fn format_route_lines_lists_user_routes() {
        let routes = vec![
            test_get_route("/", "index"),
            test_get_route("/users/{id}", "get_user"),
        ];
        let config = AutumnConfig::default();
        let output = format_route_lines(&routes, &[], &config);
        assert!(output.contains("-> index"));
        assert!(output.contains("/ GET"));
        assert!(output.contains("/users/{id}"));
        assert!(output.contains("-> get_user"));
    }

    #[test]
    fn config_runtime_drift_format_route_lines_uses_actuator_prefix() {
        let mut config = AutumnConfig::default();
        config.actuator.prefix = "/ops".to_owned();
        let output = format_route_lines(&[], &[], &config);
        assert!(output.contains("-> health"));
        assert!(output.contains("/ops/*"));
    }

    #[test]
    fn format_task_lines_none_when_empty() {
        assert!(format_task_lines(&[]).is_none());
    }

    #[test]
    fn format_task_lines_fixed_delay() {
        let tasks = vec![crate::task::TaskInfo {
            name: "cleanup".into(),
            schedule: crate::task::Schedule::FixedDelay(std::time::Duration::from_secs(300)),
            coordination: crate::task::TaskCoordination::Fleet,
            handler: |_| Box::pin(async { Ok(()) }),
        }];
        let output = format_task_lines(&tasks).unwrap();
        assert!(output.contains("cleanup (every 300s)"));
    }

    #[test]
    fn format_task_lines_cron() {
        let tasks = vec![crate::task::TaskInfo {
            name: "nightly".into(),
            schedule: crate::task::Schedule::Cron {
                expression: "0 0 * * *".into(),
                timezone: None,
            },
            coordination: crate::task::TaskCoordination::Fleet,
            handler: |_| Box::pin(async { Ok(()) }),
        }];
        let output = format_task_lines(&tasks).unwrap();
        assert!(output.contains("nightly (cron 0 0 * * *)"));
    }

    #[test]
    fn format_middleware_list_default() {
        let config = AutumnConfig::default();
        let output = format_middleware_list(&config);
        assert!(output.contains("RequestId"));
        assert!(output.contains("SecurityHeaders"));
        assert!(output.contains("Session (in-memory)"));
        assert!(output.contains("Metrics"));
        // CORS and CSRF should not be present with defaults
        assert!(!output.contains("CORS"));
        assert!(!output.contains("CSRF"));
    }

    #[test]
    fn format_middleware_list_with_cors_and_csrf() {
        let config = AutumnConfig {
            cors: crate::config::CorsConfig {
                allowed_origins: vec!["https://example.com".into()],
                ..crate::config::CorsConfig::default()
            },
            security: crate::security::config::SecurityConfig {
                csrf: crate::security::config::CsrfConfig {
                    enabled: true,
                    ..crate::security::config::CsrfConfig::default()
                },
                ..crate::security::config::SecurityConfig::default()
            },
            ..AutumnConfig::default()
        };
        let output = format_middleware_list(&config);
        assert!(output.contains("CORS"));
        assert!(output.contains("CSRF"));
    }

    #[test]
    fn mask_database_url_with_password() {
        let masked = mask_database_url("postgres://user:secret@localhost:5432/mydb", 10);
        assert!(masked.contains("****"));
        assert!(!masked.contains("secret"));
        assert!(masked.contains("postgres://user:****@localhost:5432/mydb"));
        assert!(masked.contains("pool_size=10"));
    }

    #[test]
    fn mask_database_url_without_password() {
        let masked = mask_database_url("postgres://localhost/mydb", 5);
        assert!(!masked.contains("****"));
        assert!(masked.contains("postgres://localhost/mydb"));
        assert!(masked.contains("pool_size=5"));
    }

    #[test]
    fn mask_database_url_edge_cases() {
        // Special chars in password
        // The url crate parses `p@ssw:rd!` where `@` creates problems if unencoded,
        // but url crate seems to treat `user:p` as auth and `@ssw:rd!` as host if it's poorly formed,
        // let's stick to valid URL formats for testing.

        // URL encoded characters
        let masked2 = mask_database_url("postgres://user:p%40ssw%3Ard%21@localhost:5432/mydb", 10);
        assert!(masked2.contains("****"));
        assert!(!masked2.contains("p%40ssw%3Ard%21"));
        assert!(masked2.contains("postgres://user:****@localhost:5432/mydb"));

        // No user, just password
        let masked3 = mask_database_url("postgres://:secret@localhost:5432/mydb", 10);
        assert!(masked3.contains("****"));
        assert!(!masked3.contains("secret"));
        assert!(masked3.contains("postgres://:****@localhost:5432/mydb"));
    }
    #[test]
    fn mask_database_url_invalid_url_fallback() {
        let masked = mask_database_url("this is completely invalid as a URL with supersecret", 10);
        assert!(masked.contains("****"));
        assert!(!masked.contains("supersecret"));
        assert!(masked.contains("pool_size=10"));
    }

    #[test]
    fn format_config_summary_defaults() {
        let config = AutumnConfig::default();
        let output = format_config_summary(&config);
        assert!(output.contains("profile:    none"));
        assert!(output.contains("server:     127.0.0.1:3000"));
        assert!(output.contains("database:   not configured"));
        assert!(output.contains("log_level:"));
        assert!(output.contains("telemetry:  disabled"));
        assert!(output.contains("health:     /health"));
    }

    #[test]
    fn format_config_summary_with_db() {
        let config = AutumnConfig {
            database: crate::config::DatabaseConfig {
                url: Some("postgres://user:pass@host/db".into()),
                pool_size: 20,
                ..crate::config::DatabaseConfig::default()
            },
            ..AutumnConfig::default()
        };
        let output = format_config_summary(&config);
        assert!(output.contains("user:****@host/db"));
        assert!(output.contains("pool_size=20"));
        assert!(!output.contains("pass"));
    }

    #[test]
    fn format_config_summary_with_profile() {
        let config = AutumnConfig {
            profile: Some("prod".into()),
            ..AutumnConfig::default()
        };
        let output = format_config_summary(&config);
        assert!(output.contains("profile:    prod"));
    }

    #[test]
    fn format_config_summary_with_telemetry() {
        let config = AutumnConfig {
            telemetry: crate::config::TelemetryConfig {
                enabled: true,
                service_name: "orders-api".into(),
                otlp_endpoint: Some("http://otel-collector:4317".into()),
                ..crate::config::TelemetryConfig::default()
            },
            ..AutumnConfig::default()
        };
        let output = format_config_summary(&config);
        assert!(output.contains("telemetry:  Grpc -> http://otel-collector:4317"));
    }

    #[test]
    fn log_startup_transparency_runs_without_panic() {
        // Exercises the tracing::info! calls inside log_startup_transparency.
        // No subscriber installed, so output is discarded -- we just verify
        // the function doesn't panic.
        let routes = vec![test_get_route("/", "index")];
        let tasks = vec![crate::task::TaskInfo {
            name: "cleanup".into(),
            schedule: crate::task::Schedule::FixedDelay(std::time::Duration::from_secs(60)),
            coordination: crate::task::TaskCoordination::Fleet,
            handler: |_| Box::pin(async { Ok(()) }),
        }];
        let config = AutumnConfig::default();
        log_startup_transparency(&routes, &tasks, &[], &config);
    }

    #[test]
    fn log_startup_transparency_no_tasks() {
        let routes = vec![test_get_route("/health", "check")];
        let config = AutumnConfig::default();
        log_startup_transparency(&routes, &[], &[], &config);
    }

    #[cfg(feature = "ws")]
    #[tokio::test]
    async fn start_task_scheduler_broadcasts_events() {
        let state = AppState {
            extensions: std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            #[cfg(feature = "db")]
            pool: None,
            #[cfg(feature = "db")]
            replica_pool: None,
            #[cfg(feature = "db")]
            shards: None,
            profile: None,
            role: crate::config::ProcessRole::Combined,
            started_at: std::time::Instant::now(),
            health_detailed: true,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            job_registry: crate::actuator::JobRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "presence")]
            presence: crate::presence::Presence::new(crate::channels::Channels::new(32)),
            shutdown: tokio_util::sync::CancellationToken::new(),
            policy_registry: crate::authorization::PolicyRegistry::default(),
            forbidden_response: crate::authorization::ForbiddenResponse::default(),
            auth_session_key: "user_id".to_owned(),
            shared_cache: None,
            clock: std::sync::Arc::new(crate::time::SystemClock),
            app_id: AppState::next_app_id(),
            metrics_source_registry: crate::actuator::MetricsSourceRegistry::new(),
            health_indicator_registry: crate::actuator::HealthIndicatorRegistry::new(),
        };

        let mut rx = state.channels().subscribe("sys:tasks");

        let task = crate::task::TaskInfo {
            name: "test_broadcaster".into(),
            // 1ms delay so it fires immediately
            schedule: crate::task::Schedule::FixedDelay(std::time::Duration::from_millis(1)),
            coordination: crate::task::TaskCoordination::Fleet,
            handler: |_| Box::pin(async { Ok(()) }),
        };

        // Start scheduler in background so we don't block
        let state_clone = state.clone();
        tokio::spawn(async move {
            super::start_task_scheduler(
                vec![task],
                &state_clone,
                &tokio_util::sync::CancellationToken::new(),
            );
        });

        // First message should be "started"
        let msg1 = tokio::time::timeout(std::time::Duration::from_secs(1), rx.recv())
            .await
            .expect("timeout waiting for start event")
            .expect("channel closed");
        let json1: serde_json::Value = serde_json::from_str(msg1.as_str()).unwrap();
        assert_eq!(json1["event"], "started");
        assert_eq!(json1["task"], "test_broadcaster");

        // Second message should be "success"
        let msg2 = tokio::time::timeout(std::time::Duration::from_secs(1), rx.recv())
            .await
            .expect("timeout waiting for success event")
            .expect("channel closed");
        let json2: serde_json::Value = serde_json::from_str(msg2.as_str()).unwrap();
        assert_eq!(json2["event"], "success");
        assert_eq!(json2["task"], "test_broadcaster");
        assert!(json2.get("duration_ms").is_some());
    }

    #[cfg(feature = "ws")]
    #[tokio::test]
    async fn start_task_scheduler_broadcasts_failure_events() {
        let state = AppState {
            extensions: std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            #[cfg(feature = "db")]
            pool: None,
            #[cfg(feature = "db")]
            replica_pool: None,
            #[cfg(feature = "db")]
            shards: None,
            profile: None,
            role: crate::config::ProcessRole::Combined,
            started_at: std::time::Instant::now(),
            health_detailed: true,
            probes: crate::probe::ProbeState::ready_for_test(),
            metrics: crate::middleware::MetricsCollector::new(),
            log_levels: crate::actuator::LogLevels::new("info"),
            task_registry: crate::actuator::TaskRegistry::new(),
            job_registry: crate::actuator::JobRegistry::new(),
            config_props: crate::actuator::ConfigProperties::default(),
            channels: crate::channels::Channels::new(32),
            #[cfg(feature = "presence")]
            presence: crate::presence::Presence::new(crate::channels::Channels::new(32)),
            shutdown: tokio_util::sync::CancellationToken::new(),
            policy_registry: crate::authorization::PolicyRegistry::default(),
            forbidden_response: crate::authorization::ForbiddenResponse::default(),
            auth_session_key: "user_id".to_owned(),
            shared_cache: None,
            clock: std::sync::Arc::new(crate::time::SystemClock),
            app_id: AppState::next_app_id(),
            metrics_source_registry: crate::actuator::MetricsSourceRegistry::new(),
            health_indicator_registry: crate::actuator::HealthIndicatorRegistry::new(),
        };

        let mut rx = state.channels().subscribe("sys:tasks");

        let task = crate::task::TaskInfo {
            name: "test_failing_task".into(),
            schedule: crate::task::Schedule::FixedDelay(std::time::Duration::from_millis(1)),
            coordination: crate::task::TaskCoordination::Fleet,
            handler: |_| {
                Box::pin(async { Err(crate::AutumnError::bad_request_msg("forced error")) })
            },
        };

        let state_clone = state.clone();
        tokio::spawn(async move {
            super::start_task_scheduler(
                vec![task],
                &state_clone,
                &tokio_util::sync::CancellationToken::new(),
            );
        });

        // First message: started
        let _ = rx.recv().await.unwrap();

        // Second message: failure
        let msg2 = tokio::time::timeout(std::time::Duration::from_secs(1), rx.recv())
            .await
            .expect("timeout waiting for failure event")
            .expect("channel closed");
        let json2: serde_json::Value = serde_json::from_str(msg2.as_str()).unwrap();
        assert_eq!(json2["event"], "failure");
        assert_eq!(json2["task"], "test_failing_task");
        assert_eq!(json2["error"], "forced error");
    }

    #[tokio::test]
    async fn execute_task_result_ok_returns_duration() {
        let state = AppState::for_test();
        let handler: crate::task::TaskHandler = |_| Box::pin(async { Ok(()) });
        let start = std::time::Instant::now();
        let result =
            super::execute_task_result(&state, handler, start, "test_task", "fixed_delay").await;
        assert!(result.is_ok(), "expected Ok from successful handler");
        // duration_ms should be a reasonable value (not MAX)
        assert!(result.unwrap() < u64::MAX);
    }

    #[tokio::test]
    async fn execute_task_result_err_returns_duration_and_message() {
        let state = AppState::for_test();
        let handler: crate::task::TaskHandler =
            |_| Box::pin(async { Err(crate::AutumnError::bad_request_msg("test error")) });
        let start = std::time::Instant::now();
        let result =
            super::execute_task_result(&state, handler, start, "test_task", "fixed_delay").await;
        assert!(result.is_err(), "expected Err from failing handler");
        let (duration_ms, msg) = result.unwrap_err();
        assert!(duration_ms < u64::MAX);
        assert!(msg.contains("test error"));
    }

    fn instantly_panicking_scheduled_handler(
        _state: AppState,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = crate::AutumnResult<()>> + Send>> {
        panic!("panic before scheduled future")
    }

    #[tokio::test]
    async fn execute_task_result_reports_immediate_handler_panics() {
        let state = AppState::for_test();
        let start = std::time::Instant::now();
        let result = super::execute_task_result(
            &state,
            instantly_panicking_scheduled_handler,
            start,
            "test_task",
            "fixed_delay",
        )
        .await;

        let (duration_ms, msg) = result.expect_err("expected Err from panicking handler");
        assert!(duration_ms < u64::MAX);
        assert!(msg.contains("scheduled task handler panicked: panic before scheduled future"));
    }

    #[tokio::test]
    async fn execute_fixed_delay_task_does_not_timeout_in_process_runs() {
        let state = AppState::for_test();
        state.task_registry.register_scheduled(
            "slow_task",
            "every 1s",
            crate::task::TaskCoordination::Fleet,
            "in_process",
            "replica-a",
        );
        let handler: crate::task::TaskHandler = |_| {
            Box::pin(async {
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
                Ok(())
            })
        };
        let coordinator = std::sync::Arc::new(
            crate::scheduler::InProcessSchedulerCoordinator::new("replica-a"),
        );

        super::execute_fixed_delay_task(
            "slow_task".to_owned(),
            state.clone(),
            handler,
            std::time::Duration::from_secs(1),
            crate::task::TaskCoordination::Fleet,
            coordinator,
            std::time::Duration::from_millis(10),
        )
        .await;

        let snapshot = state.task_registry.snapshot();
        let status = &snapshot["slow_task"];
        assert_eq!(status.status, "idle");
        assert_eq!(status.last_result.as_deref(), Some("ok"));
        assert_eq!(status.total_runs, 1);
        assert_eq!(status.total_failures, 0);
        assert!(status.last_error.is_none());
    }

    static SKIPPED_LEASE_HANDLER_CALLS: AtomicUsize = AtomicUsize::new(0);

    struct DenyingSchedulerCoordinator;

    impl crate::scheduler::SchedulerCoordinator for DenyingSchedulerCoordinator {
        fn backend(&self) -> &'static str {
            "postgres"
        }

        fn replica_id(&self) -> &'static str {
            "replica-a"
        }

        fn try_acquire<'a>(
            &'a self,
            _task_name: &'a str,
            _tick_key: &'a str,
            _coordination: crate::task::TaskCoordination,
        ) -> crate::scheduler::SchedulerFuture<
            'a,
            crate::AutumnResult<Option<crate::scheduler::SchedulerLease>>,
        > {
            Box::pin(async { Ok(None) })
        }
    }

    struct GrantingSchedulerCoordinator {
        backend: &'static str,
        tick_keys: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
        release_count: Option<std::sync::Arc<AtomicUsize>>,
    }

    impl crate::scheduler::SchedulerCoordinator for GrantingSchedulerCoordinator {
        fn backend(&self) -> &'static str {
            self.backend
        }

        fn replica_id(&self) -> &'static str {
            "replica-a"
        }

        fn try_acquire<'a>(
            &'a self,
            _task_name: &'a str,
            tick_key: &'a str,
            _coordination: crate::task::TaskCoordination,
        ) -> crate::scheduler::SchedulerFuture<
            'a,
            crate::AutumnResult<Option<crate::scheduler::SchedulerLease>>,
        > {
            Box::pin(async move {
                self.tick_keys.lock().unwrap().push(tick_key.to_owned());
                let lease = self.release_count.as_ref().map_or_else(
                    || crate::scheduler::SchedulerLease::local(self.backend, "replica-a"),
                    |release_count| {
                        crate::scheduler::SchedulerLease::tracked(
                            self.backend,
                            "replica-a",
                            std::sync::Arc::clone(release_count),
                        )
                    },
                );
                Ok(Some(lease))
            })
        }
    }

    fn counted_scheduled_handler(
        _state: AppState,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = crate::AutumnResult<()>> + Send>> {
        Box::pin(async {
            SKIPPED_LEASE_HANDLER_CALLS.fetch_add(1, Ordering::SeqCst);
            Ok(())
        })
    }

    #[tokio::test]
    async fn execute_fixed_delay_task_skips_handler_when_lease_is_not_acquired() {
        SKIPPED_LEASE_HANDLER_CALLS.store(0, Ordering::SeqCst);
        let state = AppState::for_test();
        state.task_registry.register_scheduled(
            "claimed_elsewhere",
            "every 1s",
            crate::task::TaskCoordination::Fleet,
            "postgres",
            "replica-a",
        );
        let coordinator = std::sync::Arc::new(DenyingSchedulerCoordinator);

        super::execute_fixed_delay_task(
            "claimed_elsewhere".to_owned(),
            state.clone(),
            counted_scheduled_handler,
            std::time::Duration::from_secs(1),
            crate::task::TaskCoordination::Fleet,
            coordinator,
            std::time::Duration::from_secs(1),
        )
        .await;

        let snapshot = state.task_registry.snapshot();
        let status = &snapshot["claimed_elsewhere"];
        assert_eq!(SKIPPED_LEASE_HANDLER_CALLS.load(Ordering::SeqCst), 0);
        assert_eq!(status.total_runs, 0);
        assert!(status.current_leader.is_none());
        assert!(status.last_tick.is_none());
    }

    #[tokio::test]
    async fn execute_fixed_delay_task_records_distributed_lease_ttl_timeout() {
        let state = AppState::for_test();
        state.task_registry.register_scheduled(
            "slow_distributed_task",
            "every 1s",
            crate::task::TaskCoordination::Fleet,
            "postgres",
            "replica-a",
        );
        let handler: crate::task::TaskHandler = |_| {
            Box::pin(async {
                tokio::time::sleep(std::time::Duration::from_secs(5)).await;
                Ok(())
            })
        };
        let coordinator = std::sync::Arc::new(GrantingSchedulerCoordinator {
            backend: "postgres",
            tick_keys: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
            release_count: None,
        });

        super::execute_fixed_delay_task(
            "slow_distributed_task".to_owned(),
            state.clone(),
            handler,
            std::time::Duration::from_secs(1),
            crate::task::TaskCoordination::Fleet,
            coordinator,
            std::time::Duration::from_millis(10),
        )
        .await;

        let snapshot = state.task_registry.snapshot();
        let status = &snapshot["slow_distributed_task"];
        assert_eq!(status.status, "idle");
        assert_eq!(status.last_result.as_deref(), Some("failed"));
        assert_eq!(status.total_runs, 1);
        assert_eq!(status.total_failures, 1);
        assert!(
            status
                .last_error
                .as_deref()
                .is_some_and(|error| error.contains("lease TTL"))
        );
    }

    #[tokio::test]
    async fn execute_cron_task_uses_scheduled_occurrence_for_tick_key() {
        let state = AppState::for_test();
        state.task_registry.register_scheduled(
            "cron_review_task",
            "cron */10 * * * * *",
            crate::task::TaskCoordination::Fleet,
            "postgres",
            "replica-a",
        );
        let tick_keys = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let coordinator = std::sync::Arc::new(GrantingSchedulerCoordinator {
            backend: "postgres",
            tick_keys: std::sync::Arc::clone(&tick_keys),
            release_count: None,
        });
        let handler: crate::task::TaskHandler = |_| Box::pin(async { Ok(()) });
        let scheduled_unix_secs = 1_700_000_000;

        super::execute_cron_task(
            "cron_review_task".to_owned(),
            state.clone(),
            handler,
            crate::task::TaskCoordination::Fleet,
            coordinator,
            std::time::Duration::from_secs(30),
            scheduled_unix_secs,
        )
        .await;

        assert_eq!(
            tick_keys.lock().unwrap().as_slice(),
            ["cron_review_task:1700000000"]
        );
    }

    #[tokio::test]
    async fn execute_fixed_delay_task_releases_lease_when_handler_panics() {
        let state = AppState::for_test();
        state.task_registry.register_scheduled(
            "panic_task",
            "every 1s",
            crate::task::TaskCoordination::Fleet,
            "postgres",
            "replica-a",
        );
        let release_count = std::sync::Arc::new(AtomicUsize::new(0));
        let coordinator = std::sync::Arc::new(GrantingSchedulerCoordinator {
            backend: "postgres",
            tick_keys: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
            release_count: Some(std::sync::Arc::clone(&release_count)),
        });
        let handler: crate::task::TaskHandler = |_| {
            Box::pin(async {
                panic!("forced scheduled panic");
                #[allow(unreachable_code)]
                Ok(())
            })
        };

        super::execute_fixed_delay_task(
            "panic_task".to_owned(),
            state.clone(),
            handler,
            std::time::Duration::from_secs(1),
            crate::task::TaskCoordination::Fleet,
            coordinator,
            std::time::Duration::from_secs(30),
        )
        .await;

        let snapshot = state.task_registry.snapshot();
        let status = &snapshot["panic_task"];
        assert_eq!(release_count.load(Ordering::SeqCst), 1);
        assert_eq!(status.status, "idle");
        assert_eq!(status.last_result.as_deref(), Some("failed"));
        assert_eq!(status.total_runs, 1);
        assert_eq!(status.total_failures, 1);
        assert!(
            status
                .last_error
                .as_deref()
                .is_some_and(|error| error.contains("scheduled task handler panicked"))
        );
    }

    #[test]
    fn next_cron_occurrence_skips_overdue_slots() {
        use chrono::TimeZone as _;

        let cron = "0 * * * * *"
            .parse::<croner::Cron>()
            .expect("cron expression should parse");
        let stale_cursor = chrono_tz::UTC
            .with_ymd_and_hms(2026, 5, 5, 12, 0, 0)
            .unwrap();
        let now = chrono_tz::UTC
            .with_ymd_and_hms(2026, 5, 5, 12, 30, 5)
            .unwrap();
        let next = super::next_cron_occurrence_after(&cron, &stale_cursor, &now)
            .expect("next cron occurrence should resolve");

        assert_eq!(
            next,
            chrono_tz::UTC
                .with_ymd_and_hms(2026, 5, 5, 12, 31, 0)
                .unwrap()
        );
    }

    #[test]
    fn cron_occurrence_is_overdue_after_later_slot_passed() {
        use chrono::TimeZone as _;

        let cron = "0 * * * * *"
            .parse::<croner::Cron>()
            .expect("cron expression should parse");
        let scheduled_at = chrono_tz::UTC
            .with_ymd_and_hms(2026, 5, 5, 12, 1, 0)
            .unwrap();
        let slightly_late = chrono_tz::UTC
            .with_ymd_and_hms(2026, 5, 5, 12, 1, 5)
            .unwrap();
        let after_later_slot = chrono_tz::UTC
            .with_ymd_and_hms(2026, 5, 5, 12, 30, 5)
            .unwrap();

        assert!(
            !super::cron_occurrence_is_overdue(&cron, &scheduled_at, &slightly_late)
                .expect("overdue check should resolve")
        );
        assert!(
            super::cron_occurrence_is_overdue(&cron, &scheduled_at, &after_later_slot)
                .expect("overdue check should resolve")
        );
    }

    #[cfg(feature = "storage")]
    mod storage_preflight {
        use super::super::{StorageBootstrap, preflight_storage};
        use crate::AppState;
        use crate::config::AutumnConfig;
        use crate::storage::{BlobStoreState, StorageBackend, StorageConfig, StorageLocalConfig};

        fn config_with_storage(storage: StorageConfig) -> AutumnConfig {
            AutumnConfig {
                profile: Some("dev".into()),
                storage,
                ..AutumnConfig::default()
            }
        }

        #[test]
        fn preflight_returns_none_when_disabled() {
            let cfg = config_with_storage(StorageConfig {
                backend: StorageBackend::Disabled,
                ..StorageConfig::default()
            });
            assert!(preflight_storage(&cfg).is_none());
        }

        #[test]
        fn preflight_provisions_local_backend_against_tempdir() {
            let dir = tempfile::tempdir().unwrap();
            let cfg = config_with_storage(StorageConfig {
                backend: StorageBackend::Local,
                local: StorageLocalConfig {
                    root: dir.path().to_path_buf(),
                    ..StorageLocalConfig::default()
                },
                ..StorageConfig::default()
            });
            let bootstrap = preflight_storage(&cfg).expect("local backend should provision");
            assert_eq!(bootstrap.store.provider_id(), "default");
            assert!(bootstrap.serving.is_some(), "local backend mounts a route");
        }

        #[tokio::test]
        async fn install_registers_blob_store_on_state() {
            let dir = tempfile::tempdir().unwrap();
            let cfg = config_with_storage(StorageConfig {
                backend: StorageBackend::Local,
                local: StorageLocalConfig {
                    root: dir.path().to_path_buf(),
                    ..StorageLocalConfig::default()
                },
                ..StorageConfig::default()
            });
            let bootstrap: StorageBootstrap = preflight_storage(&cfg).unwrap();

            let state = AppState::for_test();
            assert!(state.extension::<BlobStoreState>().is_none());
            let serving = bootstrap.install(&state);
            assert!(serving.is_some());
            assert!(state.extension::<BlobStoreState>().is_some());
        }

        #[test]
        fn with_blob_store_stores_custom_store() {
            use crate::storage::{
                Blob, BlobFuture, BlobMeta, BlobStore, BlobStoreError, ByteStream,
            };
            use bytes::Bytes;
            use std::time::Duration;

            struct FakeStore;
            impl BlobStore for FakeStore {
                fn provider_id(&self) -> &'static str {
                    "fake"
                }
                fn put<'a>(&'a self, _k: &'a str, _ct: &'a str, _b: Bytes) -> BlobFuture<'a, Blob> {
                    Box::pin(async { Err(BlobStoreError::Unsupported("fake".into())) })
                }
                fn put_stream<'a>(
                    &'a self,
                    _k: &'a str,
                    _ct: &'a str,
                    _d: ByteStream<'a>,
                ) -> BlobFuture<'a, Blob> {
                    Box::pin(async { Err(BlobStoreError::Unsupported("fake".into())) })
                }
                fn get<'a>(&'a self, _k: &'a str) -> BlobFuture<'a, Bytes> {
                    Box::pin(async { Err(BlobStoreError::Unsupported("fake".into())) })
                }
                fn delete<'a>(&'a self, _k: &'a str) -> BlobFuture<'a, ()> {
                    Box::pin(async { Err(BlobStoreError::Unsupported("fake".into())) })
                }
                fn head<'a>(&'a self, _k: &'a str) -> BlobFuture<'a, Option<BlobMeta>> {
                    Box::pin(async { Err(BlobStoreError::Unsupported("fake".into())) })
                }
                fn presigned_url<'a>(
                    &'a self,
                    _k: &'a str,
                    _e: Duration,
                ) -> BlobFuture<'a, String> {
                    Box::pin(async { Err(BlobStoreError::Unsupported("fake".into())) })
                }
            }

            let builder = crate::app().with_blob_store(FakeStore);
            assert!(builder.blob_store.is_some());
        }

        #[tokio::test]
        async fn with_blob_store_is_installed_on_state() {
            use crate::storage::{
                Blob, BlobFuture, BlobMeta, BlobStore, BlobStoreError, ByteStream,
            };
            use bytes::Bytes;
            use std::time::Duration;

            struct FakeStore;
            impl BlobStore for FakeStore {
                fn provider_id(&self) -> &'static str {
                    "fake-installed"
                }
                fn put<'a>(&'a self, _k: &'a str, _ct: &'a str, _b: Bytes) -> BlobFuture<'a, Blob> {
                    Box::pin(async { Err(BlobStoreError::Unsupported("fake".into())) })
                }
                fn put_stream<'a>(
                    &'a self,
                    _k: &'a str,
                    _ct: &'a str,
                    _d: ByteStream<'a>,
                ) -> BlobFuture<'a, Blob> {
                    Box::pin(async { Err(BlobStoreError::Unsupported("fake".into())) })
                }
                fn get<'a>(&'a self, _k: &'a str) -> BlobFuture<'a, Bytes> {
                    Box::pin(async { Err(BlobStoreError::Unsupported("fake".into())) })
                }
                fn delete<'a>(&'a self, _k: &'a str) -> BlobFuture<'a, ()> {
                    Box::pin(async { Err(BlobStoreError::Unsupported("fake".into())) })
                }
                fn head<'a>(&'a self, _k: &'a str) -> BlobFuture<'a, Option<BlobMeta>> {
                    Box::pin(async { Err(BlobStoreError::Unsupported("fake".into())) })
                }
                fn presigned_url<'a>(
                    &'a self,
                    _k: &'a str,
                    _e: Duration,
                ) -> BlobFuture<'a, String> {
                    Box::pin(async { Err(BlobStoreError::Unsupported("fake".into())) })
                }
            }

            let builder = crate::app().with_blob_store(FakeStore);
            let bootstrap = builder.blob_store.map(|store| StorageBootstrap {
                store,
                serving: None,
            });
            let state = AppState::for_test();
            assert!(state.extension::<BlobStoreState>().is_none());
            if let Some(b) = bootstrap {
                b.install(&state);
            }
            let installed = state
                .extension::<BlobStoreState>()
                .expect("store should be installed");
            assert_eq!(installed.store().provider_id(), "fake-installed");
        }
    }

    // ── Route source attribution ───────────────────────────────────────────

    /// A minimal plugin that registers one route with a known name.
    struct TestPlugin {
        name: &'static str,
        route: Route,
    }

    impl crate::plugin::Plugin for TestPlugin {
        fn name(&self) -> std::borrow::Cow<'static, str> {
            std::borrow::Cow::Borrowed(self.name)
        }

        fn build(self, app: AppBuilder) -> AppBuilder {
            app.routes(vec![self.route])
        }
    }

    #[test]
    fn routes_registered_before_plugin_are_user_sourced() {
        let user_route = test_get_route("/home", "home");
        let builder = app().routes(vec![user_route]);
        assert_eq!(builder.route_sources.len(), 1);
        assert_eq!(
            builder.route_sources[0],
            crate::route_listing::RouteSource::User
        );
    }

    #[test]
    fn routes_registered_inside_plugin_are_plugin_sourced() {
        let plugin_route = test_get_route("/plugin-page", "plugin_page");
        let plugin = TestPlugin {
            name: "my-plugin",
            route: plugin_route,
        };
        let builder = app().plugin(plugin);
        assert_eq!(builder.route_sources.len(), 1);
        assert_eq!(
            builder.route_sources[0],
            crate::route_listing::RouteSource::Plugin("my-plugin".to_owned())
        );
    }

    #[test]
    fn routes_registered_after_plugin_revert_to_user_sourced() {
        let plugin_route = test_get_route("/plugin-page", "plugin_page");
        let user_route = test_get_route("/home", "home");
        let plugin = TestPlugin {
            name: "my-plugin",
            route: plugin_route,
        };
        let builder = app().plugin(plugin).routes(vec![user_route]);
        assert_eq!(builder.route_sources.len(), 2);
        assert_eq!(
            builder.route_sources[0],
            crate::route_listing::RouteSource::Plugin("my-plugin".to_owned())
        );
        assert_eq!(
            builder.route_sources[1],
            crate::route_listing::RouteSource::User
        );
    }

    /// A plugin that registers a route and then registers a nested plugin.
    struct OuterPlugin;

    impl crate::plugin::Plugin for OuterPlugin {
        fn name(&self) -> std::borrow::Cow<'static, str> {
            "outer".into()
        }

        fn build(self, app: AppBuilder) -> AppBuilder {
            let inner = TestPlugin {
                name: "inner",
                route: test_get_route("/inner", "inner"),
            };
            app.plugin(inner)
                .routes(vec![test_get_route("/outer-after", "outer_after")])
        }
    }

    #[test]
    fn outer_plugin_source_restored_after_nested_plugin() {
        let builder = app().plugin(OuterPlugin);
        // Routes: [/inner from "inner", /outer-after from "outer"]
        assert_eq!(builder.route_sources.len(), 2);
        assert_eq!(
            builder.route_sources[0],
            crate::route_listing::RouteSource::Plugin("inner".to_owned()),
            "first route should be attributed to inner plugin"
        );
        assert_eq!(
            builder.route_sources[1],
            crate::route_listing::RouteSource::Plugin("outer".to_owned()),
            "second route should be re-attributed to outer plugin after nested build"
        );
    }

    // ── shutdown hook timeout tests ───────────────────────────────────────────

    #[tokio::test]
    async fn shutdown_hooks_with_timeout_runs_all_fast_hooks() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let counter = Arc::new(AtomicUsize::new(0));
        let c1 = Arc::clone(&counter);
        let c2 = Arc::clone(&counter);

        let hooks: Vec<ShutdownHook> = vec![
            Box::new(move || {
                let c = Arc::clone(&c1);
                Box::pin(async move {
                    c.fetch_add(1, Ordering::SeqCst);
                })
            }),
            Box::new(move || {
                let c = Arc::clone(&c2);
                Box::pin(async move {
                    c.fetch_add(1, Ordering::SeqCst);
                })
            }),
        ];

        run_shutdown_hooks_with_timeout(
            &hooks,
            std::time::Duration::from_secs(2),
            std::time::Duration::from_secs(10),
        )
        .await;

        assert_eq!(counter.load(Ordering::SeqCst), 2, "both hooks must run");
    }

    #[tokio::test]
    async fn shutdown_hooks_with_timeout_tolerates_slow_hook_overrun() {
        use std::sync::atomic::{AtomicBool, Ordering};
        let fast_ran = Arc::new(AtomicBool::new(false));
        let fr = Arc::clone(&fast_ran);

        let hooks: Vec<ShutdownHook> = vec![
            // hook 0 (first registered → runs LAST in LIFO): fast
            Box::new(move || {
                let fr = Arc::clone(&fr);
                Box::pin(async move {
                    fr.store(true, Ordering::SeqCst);
                })
            }),
            // hook 1 (last registered → runs FIRST in LIFO): slow, exceeds per-hook budget
            Box::new(|| {
                Box::pin(async move {
                    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
                })
            }),
        ];

        // Per-hook budget = 50 ms (hook 0 will overrun).
        // Total budget = 1 s (ample for hook 1 after the overrun is cut short).
        run_shutdown_hooks_with_timeout(
            &hooks,
            std::time::Duration::from_millis(50),
            std::time::Duration::from_secs(1),
        )
        .await;

        assert!(
            fast_ran.load(Ordering::SeqCst),
            "fast hook must still run even after slow hook overruns its per-hook budget"
        );
    }

    // Verify that build_state registers a SharedReqwestClient so that
    // Client::from_state can reuse the shared connection pool on every request.
    #[cfg(feature = "http-client")]
    #[test]
    fn build_state_registers_shared_reqwest_client() {
        let config = AutumnConfig::default();
        let state = build_state(
            &config,
            #[cfg(feature = "db")]
            None,
            #[cfg(feature = "db")]
            None,
            #[cfg(feature = "ws")]
            None,
        );
        assert!(
            state
                .extension::<crate::http_client::SharedReqwestClient>()
                .is_some(),
            "build_state must register a SharedReqwestClient for connection-pool sharing"
        );
    }

    // AC5 plumbing (#1526): `with_story_gallery` stores the gallery on the
    // builder, and `install_story_registry` — the single install step shared
    // by both the run and build/SSG state-construction paths — publishes it
    // as the StoryRegistry extension the `/_stories` handlers read.
    #[cfg(feature = "maud")]
    #[test]
    fn with_story_gallery_installs_story_registry_extension() {
        let builder = crate::app().with_story_gallery(crate::stories::StoryGallery::builtin());
        let gallery = builder
            .story_gallery
            .expect("with_story_gallery must store the gallery on the builder");
        let expected_count = gallery.stories().len();
        assert!(expected_count > 0, "builtin gallery must not be empty");

        let config = AutumnConfig::default();
        let state = build_state(
            &config,
            #[cfg(feature = "db")]
            None,
            #[cfg(feature = "db")]
            None,
            #[cfg(feature = "ws")]
            None,
        );
        install_story_registry(&state, Some(gallery));
        let registry = state
            .extension::<crate::stories::StoryRegistry>()
            .expect("install_story_registry must publish the StoryRegistry extension");
        assert_eq!(
            registry.stories().len(),
            expected_count,
            "every registered story must reach the state extension"
        );

        // Without a registered gallery no extension is installed: the
        // handlers fall back to the empty default and serve the empty state.
        let bare_state = build_state(
            &config,
            #[cfg(feature = "db")]
            None,
            #[cfg(feature = "db")]
            None,
            #[cfg(feature = "ws")]
            None,
        );
        install_story_registry(&bare_state, None);
        assert!(
            bare_state
                .extension::<crate::stories::StoryRegistry>()
                .is_none(),
            "no gallery registered must mean no StoryRegistry extension"
        );
    }
}

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

    #[test]
    fn prepare_unix_socket_path_noop_when_absent() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("missing.sock");
        prepare_unix_socket_path(&path).expect("absent path is fine");
        assert!(!path.exists());
    }

    #[test]
    fn prepare_unix_socket_path_removes_stale_socket() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("stale.sock");
        // Bind then drop a real socket to leave a stale socket file behind.
        let listener = std::os::unix::net::UnixListener::bind(&path).expect("bind socket");
        drop(listener);
        assert!(path.exists(), "socket file should exist before prepare");
        prepare_unix_socket_path(&path).expect("stale socket should be removed");
        assert!(!path.exists(), "stale socket should be unlinked");
    }

    #[test]
    fn prepare_unix_socket_path_refuses_live_socket() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("live.sock");
        // Keep the listener bound so a connect probe succeeds.
        let _listener = std::os::unix::net::UnixListener::bind(&path).expect("bind socket");
        let err = prepare_unix_socket_path(&path).expect_err("must refuse a live socket");
        assert_eq!(err.kind(), std::io::ErrorKind::AddrInUse);
        assert!(path.exists(), "live socket must not be removed");
    }

    #[test]
    fn prepare_unix_socket_path_errors_on_regular_file() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("not-a-socket");
        std::fs::write(&path, b"i am a regular file").expect("write file");
        let err = prepare_unix_socket_path(&path).expect_err("must refuse a non-socket file");
        assert_eq!(err.kind(), std::io::ErrorKind::AlreadyExists);
        assert!(path.exists(), "regular file must not be removed");
    }
}