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
//! Router construction and configuration.
//!
//! This module handles assembling the final [`axum::Router`] from the various
//! components configured in [`AppBuilder`](crate::app::AppBuilder), including
//! user routes, static files, middleware, error pages, and framework endpoints
//! like actuators and probes.

use std::sync::Arc;
use std::time::Duration;

use crate::app::ScopedGroup;
use crate::config::AutumnConfig;
#[cfg(feature = "maud")]
use crate::error_pages::{self, SharedRenderer};
use crate::extract::State;
use crate::idempotency::{IdempotencyLayer, IdempotencyStore, MemoryIdempotencyStore};
use crate::middleware::RequestIdLayer;
use crate::middleware::dev;
use crate::middleware::exception_filter::{
    ExceptionFilter, ExceptionFilterLayer, ProblemDetailsFilter,
};
use crate::route::Route;
use crate::state::AppState;
use axum::middleware::Next;
use axum::response::IntoResponse;
use http::{Request, StatusCode};
use thiserror::Error;

pub const DEFAULT_FAVICON_PATH: &str = "/favicon.ico";

/// Errors that can occur during the router build process.
///
/// These errors are typically fatal and represent configuration or routing
/// definition issues that must be fixed before the application can start.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum RouterBuildError {
    /// The session backend configuration is invalid (e.g. Redis without a URL).
    #[error("invalid session backend configuration: {0}")]
    InvalidSessionBackend(#[from] crate::session::SessionBackendConfigError),
    /// The idempotency backend configuration is invalid.
    #[error("invalid idempotency backend configuration: {0}")]
    #[allow(dead_code)] // constructed only in the `redis` feature path
    InvalidIdempotencyBackend(String),
    /// The submit-token backend configuration is invalid for production — an
    /// explicit `[security.submit_token].backend = "memory"` cannot safely
    /// deduplicate submits across replicas. Mirrors the idempotency
    /// production-memory fail-fast.
    #[error("invalid submit-token backend configuration: {0}")]
    InvalidSubmitTokenBackend(String),
    /// A user-defined route conflicts with a framework-provided route.
    #[error("framework route overlap at {path}: {existing} conflicts with {incoming}")]
    FrameworkRouteOverlap {
        /// The HTTP path where the overlap occurred.
        path: String,
        /// The name of the existing framework route.
        existing: &'static str,
        /// The name of the incoming user route.
        incoming: &'static str,
    },
    /// An `OpenApiConfig` path (e.g. `openapi_json_path` or
    /// `swagger_ui_path`) is not a valid route path (must start with `/`
    /// and be non-empty).
    #[cfg(feature = "openapi")]
    #[error("invalid OpenAPI {field} path: {value:?} (must start with '/' and be non-empty)")]
    InvalidOpenApiPath {
        /// Which config field carried the invalid path.
        field: &'static str,
        /// The offending value from the user's config.
        value: String,
    },
    /// `openapi_json_path` and `swagger_ui_path` collide on the same
    /// URL. Mounting both would cause axum to panic on overlapping
    /// method routes at startup.
    #[cfg(feature = "openapi")]
    #[error(
        "openapi_json_path and swagger_ui_path both resolve to {path:?}; they must differ or `swagger_ui_path` must be `None`"
    )]
    DuplicateOpenApiPath {
        /// The path that both fields pointed at.
        path: String,
    },
    /// An `OpenAPI` mount path overlaps with an existing `GET` handler,
    /// which would panic at `axum::Router::merge` time.
    #[cfg(feature = "openapi")]
    #[error(
        "OpenAPI {field} path {path:?} collides with an existing GET route; choose a different `OpenApiConfig::{field}`"
    )]
    OpenApiPathCollision {
        /// Which config field carried the colliding path.
        field: &'static str,
        /// The colliding path.
        path: String,
    },
    /// A route is annotated with an API version that is not registered.
    #[error("route '{route_name}' uses unregistered API version '{version}'")]
    UnregisteredApiVersion { route_name: String, version: String },
    /// The MCP mount path (from [`AppBuilder::mount_mcp`](crate::app::AppBuilder::mount_mcp))
    /// is not a valid route path. axum requires paths to start with `/`, so an
    /// invalid path is surfaced here rather than panicking at mount time.
    #[cfg(feature = "mcp")]
    #[error("invalid MCP mount path: {value:?} (must start with '/' and be non-empty)")]
    InvalidMcpPath {
        /// The offending mount path.
        value: String,
    },
    /// The MCP mount path collides with an existing application route at the
    /// same path. Mounting the MCP endpoint there would panic at
    /// `axum::Router::merge` time on overlapping method routes, so this is
    /// surfaced as a recoverable error instead.
    #[cfg(feature = "mcp")]
    #[error(
        "MCP mount path {path:?} collides with an existing {method} route; choose a different `mount_mcp` path"
    )]
    McpPathCollision {
        /// The colliding mount path.
        path: String,
        /// The HTTP method of the existing route at that path.
        method: String,
    },
    /// Two user- or plugin-registered routes resolve to the same
    /// `(method, path)` after scope-prefix resolution. Mounting both would
    /// panic inside `axum::routing::MethodRouter::merge` at startup on
    /// overlapping method routes (issue #1012), so the collision preflight
    /// surfaces it as a recoverable [`RouterBuildError`] BEFORE any router
    /// is mounted and names both handlers so the offending call sites are
    /// obvious in the log.
    ///
    /// Opaque routers registered via
    /// [`AppBuilder::merge`](crate::app::AppBuilder::merge) or
    /// [`AppBuilder::nest`](crate::app::AppBuilder::nest) are NOT introspectable
    /// through axum's public API, so a collision that involves one of those
    /// routers cannot be detected up front and will still surface as an axum
    /// startup panic — the preflight emits a `tracing::warn!` in that case so
    /// operators know the check was skipped (mirrors the existing OpenAPI/MCP
    /// merge-router warnings).
    #[error(
        "duplicate user route: {existing:?} and {incoming:?} both resolve to {method} {path:?}; \
         choose a different path for one of them or remove the duplicate registration"
    )]
    DuplicateUserRoute {
        /// The HTTP method both handlers registered.
        method: String,
        /// The URL path both handlers registered (post scope-prefix resolution).
        path: String,
        /// The `route.name` of the first (already-seen) handler.
        existing: String,
        /// The `route.name` of the second (duplicate) handler that triggered
        /// the collision.
        incoming: String,
    },
    /// Two user- or plugin-registered routes normalize to the SAME Axum path
    /// shape but use DIFFERENT exact path templates — e.g. their capture names
    /// differ (`/users/{id}` vs `/users/{slug}`) or a normal capture meets a
    /// catch-all at the same position (`/u/{id}` vs `/u/{*rest}`).
    ///
    /// axum's matchit router rejects the second template as a route conflict
    /// *before* method-router merging, so — unlike an exact-duplicate path,
    /// which axum happily merges across distinct HTTP methods
    /// ([`DuplicateUserRoute`](Self::DuplicateUserRoute)) — these two templates
    /// can never coexist REGARDLESS of method. Issue #1012 surfaces the clash
    /// here (naming both handlers and both original templates) instead of
    /// letting the matchit conflict panic inside `Router::route` at startup.
    ///
    /// Opaque `AppBuilder::merge` / `AppBuilder::nest` routers are exempt for
    /// the same reason as [`DuplicateUserRoute`](Self::DuplicateUserRoute).
    #[error(
        "conflicting route shapes: {existing:?} ({existing_path:?}) and {incoming:?} ({incoming_path:?}) \
         resolve to the same Axum path shape but use different path templates; axum's matchit router \
         rejects this as a route conflict regardless of HTTP method — rename the captures so both use the \
         same template, or make their static paths distinct"
    )]
    ConflictingRouteShape {
        /// The `route.name` of the first (already-seen) handler.
        existing: String,
        /// The original path template registered by the first handler.
        existing_path: String,
        /// The `route.name` of the second handler that triggered the conflict.
        incoming: String,
        /// The original path template registered by the second handler.
        incoming_path: String,
    },
}

/// Build the fully-configured Axum router from routes, config, and state.
///
/// Extracted from `AppBuilder::run` so the router construction logic is
/// testable without binding a real TCP listener.
///
/// # Panics
///
/// Panics when framework router assembly encounters invalid configuration.
/// Use [`try_build_router`] to handle configuration errors explicitly.
#[allow(dead_code)]
pub fn build_router(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: AppState,
) -> axum::Router {
    try_build_router(route_list, config, state)
        .unwrap_or_else(|error| panic!("invalid router configuration: {error}"))
}

/// Checked variant of [`build_router`] that returns configuration errors
/// instead of panicking.
///
/// # Errors
///
/// Returns [`RouterBuildError`] when router assembly encounters invalid
/// framework configuration, such as an unusable session backend.
pub struct RouterContext {
    pub exception_filters: Vec<Arc<dyn ExceptionFilter>>,
    pub scoped_groups: Vec<ScopedGroup>,
    pub merge_routers: Vec<axum::Router<AppState>>,
    pub nest_routers: Vec<(String, axum::Router<AppState>)>,
    /// Custom Tower layers registered via
    /// [`AppBuilder::layer`](crate::app::AppBuilder::layer). Applied inside
    /// [`RequestIdLayer`] and the session layer on the ingress path so user
    /// middleware observes the generated request ID and session context.
    ///
    /// **SSG/ISG mode trade-off**: when `dist_dir` is active, layers are
    /// moved outside the static-first middleware so they can process
    /// pre-rendered responses (e.g. compression).  As a side effect they also
    /// run *before* `RequestIdLayer`, session, `MetricsLayer`, and
    /// `ExceptionFilterLayer` for all requests (static and dynamic).  Layers
    /// that depend on extensions set by those framework layers — such as the
    /// request ID or session data — will not find them in SSG mode.
    pub custom_layers: Vec<crate::app::CustomLayerRegistration>,
    /// Pre-static gate layers registered via
    /// [`AppBuilder::static_gate`](crate::app::AppBuilder::static_gate).
    /// Applied as the **outermost** middleware — outside the session layer and
    /// ahead of the static-first middleware — so they can auth-gate / redirect
    /// a request before a cached SSG/ISG page is served. Unlike
    /// [`custom_layers`](Self::custom_layers), these always run in this
    /// outermost position in both static and fully-dynamic modes, and never
    /// see the session extension.
    pub static_gate_layers: Vec<crate::app::CustomLayerRegistration>,
    #[cfg(feature = "maud")]
    pub error_page_renderer: Option<SharedRenderer>,
    /// Custom session store installed via
    /// [`AppBuilder::with_session_store`](crate::app::AppBuilder::with_session_store).
    /// When `Some`, [`apply_session_layer`](crate::session::apply_session_layer)
    /// uses it directly and skips the config-driven backend selection.
    pub session_store: Option<Arc<dyn crate::session::BoxedSessionStore>>,
    /// `OpenAPI` generation configuration. When `Some`, the router mounts
    /// an `openapi.json` endpoint and (optionally) a Swagger UI page
    /// describing the application's routes.
    ///
    /// Gated behind the `openapi` feature.
    #[cfg(feature = "openapi")]
    pub openapi: Option<crate::openapi::OpenApiConfig>,
    /// MCP (Model Context Protocol) runtime config. When `Some`, the router
    /// mounts a Streamable-HTTP MCP endpoint that projects opted-in routes as
    /// agent-callable tools and dispatches `tools/call` through the real
    /// handler pipeline.
    ///
    /// Gated behind the `mcp` feature.
    #[cfg(feature = "mcp")]
    pub mcp: Option<crate::mcp::McpRuntime>,
}

/// Checked variant of [`build_router`] that returns configuration errors
/// instead of panicking.
///
/// # Errors
///
/// Returns [`RouterBuildError`] when router assembly encounters invalid
/// framework configuration, such as an unusable session backend.
pub fn try_build_router(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: AppState,
) -> Result<axum::Router, RouterBuildError> {
    let startup_barrier_state = state.clone();
    let router = try_build_router_inner(
        route_list,
        config,
        state,
        RouterContext {
            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(),
            #[cfg(feature = "maud")]
            error_page_renderer: None,
            session_store: None,
            #[cfg(feature = "openapi")]
            openapi: None,
            #[cfg(feature = "mcp")]
            mcp: None,
        },
    )?;
    Ok(apply_startup_barrier(
        router,
        config,
        &startup_barrier_state,
    ))
}

/// Build a router that includes user-supplied raw Axum routers.
///
/// Like [`build_router`], but also merges and nests additional raw
/// Axum routers. This is primarily useful for integration testing;
/// in production, use [`AppBuilder::merge`](crate::app::AppBuilder::merge) and [`AppBuilder::nest`](crate::app::AppBuilder::nest).
///
/// # Panics
///
/// Panics when framework router assembly encounters invalid configuration.
/// Use [`try_build_router_merged`] to handle configuration errors explicitly.
#[allow(dead_code)]
pub fn build_router_merged(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: AppState,
    merge_routers: Vec<axum::Router<AppState>>,
    nest_routers: Vec<(String, axum::Router<AppState>)>,
) -> axum::Router {
    try_build_router_merged(route_list, config, state, merge_routers, nest_routers)
        .unwrap_or_else(|error| panic!("invalid router configuration: {error}"))
}

/// Checked variant of [`build_router_merged`] that returns configuration
/// errors instead of panicking.
///
/// # Errors
///
/// Returns [`RouterBuildError`] when router assembly encounters invalid
/// framework configuration, such as an unusable session backend.
#[allow(dead_code)]
pub fn try_build_router_merged(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: AppState,
    merge_routers: Vec<axum::Router<AppState>>,
    nest_routers: Vec<(String, axum::Router<AppState>)>,
) -> Result<axum::Router, RouterBuildError> {
    let startup_barrier_state = state.clone();
    let router = try_build_router_inner(
        route_list,
        config,
        state,
        RouterContext {
            exception_filters: Vec::new(),
            scoped_groups: Vec::new(),
            merge_routers,
            nest_routers,
            custom_layers: Vec::new(),
            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,
        },
    )?;
    Ok(apply_startup_barrier(
        router,
        config,
        &startup_barrier_state,
    ))
}

pub fn try_build_router_inner(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: AppState,
    ctx: RouterContext,
) -> Result<axum::Router, RouterBuildError> {
    // Fully-dynamic path: no outer SecurityHeadersLayer is applied after this
    // returns, so build_router_pre_state applies it (outermost, wrapping the
    // gate).
    let router = build_router_pre_state(route_list, config, &state, ctx, None, false)?;
    Ok(router.with_state(state))
}

/// Build a probe-only router for the [`Worker`](crate::config::ProcessRole::Worker)
/// process role.
///
/// A worker replica runs job workers and the cron scheduler but serves no user
/// routes. It still binds the HTTP listener so orchestrators can supervise it,
/// exposing **only** the framework liveness/readiness/startup/health probes
/// (per `config.health.*`) and the actuator (`/actuator/*`, so `/actuator/jobs`
/// works). This mirrors how [`try_build_router_with_static_inner`] finalizes the
/// full router — same startup barrier and `with_state` — so probe/actuator
/// behavior is identical, only the user route table is absent.
///
/// # Errors
///
/// Returns [`RouterBuildError`] when the actuator prefix collides with a probe
/// path (the same guard the full build path applies).
pub fn try_build_probe_only_router(
    config: &AutumnConfig,
    state: AppState,
) -> Result<axum::Router, RouterBuildError> {
    let barrier_state = state.clone();
    // A worker replica serves no user routes, so nothing can shadow a probe.
    let no_user_routes = std::collections::HashSet::new();
    let (mounted_probe_paths, router) =
        mount_probe_endpoints(axum::Router::<AppState>::new(), config, &no_user_routes);
    let router = mount_actuator_endpoints(router, config, &mounted_probe_paths)?;
    let router = router.with_state(state);
    Ok(apply_startup_barrier(router, config, &barrier_state))
}

/// Prepared MCP exposure carried through `build_router_pre_state`: the mount
/// path, the derived tool catalog, and the optional whole-endpoint auth layer.
#[cfg(feature = "mcp")]
type McpPrepared = (
    String,
    Vec<crate::mcp::McpToolInfo>,
    Option<crate::mcp::McpEndpointLayer>,
);

/// Like [`try_build_router_inner`] but returns `Router<AppState>` before
/// [`with_state`](axum::Router::with_state) is called.  Used by
/// [`try_build_router_with_static_inner`] so that user layers and the static
/// file middleware can be applied to the typed router before state is baked in.
#[allow(clippy::too_many_lines)]
fn build_router_pre_state(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: &AppState,
    #[cfg_attr(not(feature = "mcp"), allow(unused_mut))] mut ctx: RouterContext,
    // When custom_layers are extracted from ctx before this call (SSG path),
    // the caller pre-computes the flag so the idempotency selector still sees
    // the real layer list even though ctx.custom_layers is empty.
    opaque_app_layers_override: Option<bool>,
    // When true (SSG/ISG path), the `SecurityHeadersLayer` is NOT applied here:
    // `try_build_router_with_static_inner` applies a single one OUTSIDE the
    // static-first middleware (wrapping cached pages, dynamic misses, and the
    // gate), so applying it here too would double-apply it (which breaks CSP
    // nonces). In the fully-dynamic path this is `false` and the layer is
    // applied as the outermost framework layer below, wrapping the gate.
    defer_security_headers: bool,
) -> Result<axum::Router<AppState>, RouterBuildError> {
    // Verify registered API versions
    let versions = state.extension::<crate::app::RegisteredApiVersions>();
    let registered_versions: std::collections::HashSet<&str> = versions
        .as_ref()
        .map(|v| v.0.iter().map(|av| av.version.as_str()).collect())
        .unwrap_or_default();

    let check_route_version = |route: &Route| -> Result<(), RouterBuildError> {
        if let Some(version) = route
            .api_version
            .filter(|ver| !registered_versions.contains(*ver))
        {
            return Err(RouterBuildError::UnregisteredApiVersion {
                route_name: route.name.to_string(),
                version: version.to_string(),
            });
        }
        Ok(())
    };

    for route in &route_list {
        check_route_version(route)?;
    }
    for group in &ctx.scoped_groups {
        for route in &group.routes {
            check_route_version(route)?;
        }
    }

    // Fail-fast if two user- or plugin-registered routes resolve to the same
    // `(method, path)` — `group_and_mount_routes` below would otherwise hand
    // overlapping method routes to `axum::routing::MethodRouter::merge`,
    // which panics inside `Router::route` at startup (issue #1012). Runs
    // BEFORE the OpenAPI/MCP preflights so a duplicate user route surfaces
    // as `DuplicateUserRoute` regardless of which optional subsystem is
    // configured, and BEFORE any router is mounted so the failure is
    // structured rather than an axum panic.
    reject_duplicate_user_routes(
        &route_list,
        &ctx.scoped_groups,
        &ctx.merge_routers,
        &ctx.nest_routers,
    )?;

    // Fail-fast if an OpenAPI mount path collides with a user or
    // framework GET route — axum panics on overlapping method routes,
    // so surface this as a recoverable error before we start merging.
    #[cfg(feature = "openapi")]
    reject_openapi_path_collisions(
        ctx.openapi.as_ref(),
        &route_list,
        &ctx.scoped_groups,
        &ctx.merge_routers,
        &ctx.nest_routers,
        config,
    )?;

    // Build the OpenAPI spec BEFORE moving the routes into axum, because
    // group_and_mount_routes consumes the Route list.
    #[cfg(feature = "openapi")]
    let openapi_router = build_openapi_router(
        &route_list,
        &ctx.scoped_groups,
        ctx.openapi.as_ref(),
        &config.session.cookie_name,
        versions.as_ref().map_or(&[], |v| v.0.as_slice()),
    )?;

    // Prepare MCP exposure *before* `route_list` is moved into axum below.
    // Validate the mount path up front (a typo like `"mcp"` surfaces as a
    // recoverable error, mirroring the OpenAPI path validation, instead of an
    // axum panic), derive the tool catalog, and carry the optional endpoint
    // auth layer to be applied once the router is assembled.
    #[cfg(feature = "mcp")]
    let mcp_prepared: Option<McpPrepared> = if let Some(rt) = ctx.mcp.take() {
        let path = rt.mount_path.as_str();
        // The mount path must be a single static endpoint: reject empty,
        // non-absolute, doubled-slash, and dynamic (`{capture}` / `{*rest}`)
        // paths so MCP cannot shadow a whole path class and so the exact-path
        // collision preflight reserves the concrete URL it actually matches.
        // Colon-prefixed segments (`/:mcp`, axum 0.7 capture syntax) are also
        // rejected: axum 0.8's `Router::route` panics on them during assembly
        // (`validate_v07_paths`), so catching them here yields the recoverable
        // `InvalidMcpPath` error instead of a startup crash.
        if path.is_empty()
            || !path.starts_with('/')
            || path.contains("//")
            || path.contains('{')
            || path.contains('*')
            || path.split('/').any(|segment| segment.starts_with(':'))
        {
            return Err(RouterBuildError::InvalidMcpPath {
                value: rt.mount_path,
            });
        }
        // The MCP endpoint mounts GET+POST at `mount_path`. If a user, framework,
        // or OpenAPI route already owns that exact path, the later `merge` would
        // panic on overlapping method routes; surface it as a recoverable error
        // first (mirroring the OpenAPI collision preflight).
        reject_mcp_path_collisions(
            path,
            &route_list,
            &ctx.scoped_groups,
            config,
            ctx.openapi.as_ref(),
            &ctx.merge_routers,
            &ctx.nest_routers,
        )?;
        let docs = collect_openapi_docs(&route_list, &ctx.scoped_groups);
        // Pass the app's OpenAPI config (if any) so MCP tool `inputSchema`s
        // reuse the same registered component schemas as the served spec.
        let tools = crate::mcp::derive_tools(&docs, rt.expose_all, ctx.openapi.as_ref());
        Some((rt.mount_path, tools, rt.endpoint_layer))
    } else {
        None
    };

    // Build the per-route timeout override table before `route_list` and the
    // scoped groups are consumed by the mounting steps below.
    let route_timeouts = build_route_timeout_table(&route_list, &ctx.scoped_groups);

    let idempotency_layers = build_idempotency_layers(config, state)?;
    // Both `.layer(..)` custom layers and `.static_gate(..)` gate layers are
    // opaque app layers for idempotency: an auth/tenant layer in either slot
    // must force fail-closed replay so a cached mutation can't be served to a
    // different principal carrying the same Idempotency-Key.
    let opaque_app_layers_present = opaque_app_layers_override.unwrap_or_else(|| {
        custom_layers_require_fail_closed_idempotency(&ctx.custom_layers)
            || custom_layers_require_fail_closed_idempotency(&ctx.static_gate_layers)
    });
    // Capture the paths a user handler already owns BEFORE `route_list` is
    // consumed below, so the auto-mounted probes can yield to a user route at
    // the same path instead of panicking on an overlapping `GET` (issue #1971).
    let user_get_paths = collect_user_get_paths(&route_list, &ctx.scoped_groups);

    let mut router = group_and_mount_routes(
        route_list,
        idempotency_layers.as_ref(),
        opaque_app_layers_present,
        state,
    );

    let dev_reload_enabled = dev::is_enabled_with_env(&crate::config::OsEnv);

    router = mount_framework_routes(router, config, dev_reload_enabled);

    let (mounted_probe_paths, router_with_probes) =
        mount_probe_endpoints(router, config, &user_get_paths);
    router = router_with_probes;

    router = mount_actuator_endpoints(router, config, &mounted_probe_paths)?;

    #[cfg(feature = "openapi")]
    if let Some(openapi_router) = openapi_router {
        router = router.merge(openapi_router);
    }

    // Static file serving. Fingerprinted assets (e.g. `autumn.a1b2c3d4.css`)
    // are served with `Cache-Control: public, max-age=31536000, immutable`; all
    // other static files use the default browser policy.
    //
    // When the app embedded its `static/` tree (feature = "embed-assets" plus a
    // registered dir), serve `/static/*` from the binary — no disk read, no
    // sidecar directory. Otherwise serve from the project's `static/` directory
    // on disk (the dev default, preserving hot-reload).
    #[cfg(feature = "embed-assets")]
    let embedded_static = crate::assets::embedded_static_dir().is_some();
    #[cfg(not(feature = "embed-assets"))]
    let embedded_static = false;

    if embedded_static {
        #[cfg(feature = "embed-assets")]
        {
            router = router.route(
                "/static/{*path}",
                axum::routing::get(crate::assets::serve_embedded),
            );
        }
    } else {
        let env = crate::config::OsEnv;
        let static_dir = crate::app::project_dir("static", &env);
        router = router.nest_service("/static", tower_http::services::ServeDir::new(&static_dir));
    }
    router = router.layer(axum::middleware::from_fn(
        crate::assets::asset_cache_control,
    ));

    router = mount_scoped_groups(
        router,
        ctx.scoped_groups,
        idempotency_layers.as_ref(),
        state,
    );

    router = mount_raw_routers(
        router,
        ctx.merge_routers,
        ctx.nest_routers,
        idempotency_layers.as_ref(),
    );

    // Extract the pre-static gate layers (AppBuilder::static_gate) before
    // applying the rest of the middleware. They are applied LAST — after the MCP
    // dispatch clone is taken below — so a `tools/call` replay never traverses
    // the page-cache gate. In the SSG/ISG path the caller already drained these
    // into `try_build_router_with_static_inner`, so this take yields an empty
    // list there.
    let static_gate_layers = std::mem::take(&mut ctx.static_gate_layers);

    // Built once and shared (by clone — it wraps an `Arc` in-flight counter)
    // between the direct-route stack below and the late-mounted `/mcp`
    // envelope further down, so both ingress surfaces admit against the same
    // ceiling instead of each getting its own independent (never-shared)
    // counter. See `apply_middleware`'s `load_shed_layer` parameter doc.
    let load_shed_layer = build_load_shed_layer(config, state);
    #[cfg(feature = "mcp")]
    let mcp_load_shed_layer = load_shed_layer.clone();

    router = apply_middleware(
        router,
        config,
        state,
        ctx.exception_filters,
        ctx.custom_layers,
        #[cfg(feature = "maud")]
        ctx.error_page_renderer,
        ctx.session_store,
        route_timeouts,
        load_shed_layer,
    )?;

    if dev_reload_enabled {
        router = router
            .layer(axum::middleware::from_fn(dev::disable_static_cache))
            .layer(axum::middleware::from_fn(dev::inject_live_reload));
    }

    // Dev request inspector: mount UI and apply recording middleware.
    // Only active when profile = "dev"; returns 404 for all other profiles.
    let is_dev_profile = matches!(config.profile.as_deref(), Some("dev" | "development"));
    if is_dev_profile {
        // Capture the matched route pattern for the dev error overlay.
        // Applied as a route_layer so MatchedPath is already set when this runs.
        router = router.route_layer(axum::middleware::from_fn(
            crate::middleware::dev::capture_matched_path_middleware,
        ));
    }
    if is_dev_profile {
        let buf = crate::inspector::InspectorBuffer::new(config.dev.inspector_capacity);
        let inspector_path = config.dev.inspector_path.clone();
        let threshold = config.dev.inspector_n_plus_one_threshold;

        // Mount the inspector UI routes.
        router = router.merge(crate::inspector::inspector_router(
            buf.clone(),
            &inspector_path,
        ));
        tracing::debug!(
            path = %inspector_path,
            "Mounted dev request inspector"
        );

        // Apply the recording middleware (outermost layer so it captures
        // all routes). Self-excludes inspector's own path prefix.
        let layer = crate::inspector::InspectorLayer::new(buf, threshold, inspector_path)
            .with_session_cookie_name(config.session.cookie_name.clone());
        router = router.layer(layer);
    }

    #[cfg(feature = "oauth2")]
    let router = router.layer(axum::middleware::from_fn_with_state(
        state.clone(),
        http_interceptor_middleware,
    ));

    // Install the request's app as the ambient event-bus context so any code in
    // the request (handlers, services) that calls the free `events::publish`
    // dispatches against this app rather than the process-global bus — keeping
    // parallel in-process apps (notably tests) isolated.
    let router = router.layer(axum::middleware::from_fn_with_state(
        state.clone(),
        event_app_context_middleware,
    ));

    // Mount the MCP endpoint last so its dispatch target — a clone of the
    // fully-assembled router with state applied — traverses the exact same
    // routes, layers, and middleware an HTTP request would. The clone is
    // taken *before* the MCP route is added, so `tools/call` never recurses
    // into the MCP endpoint itself.
    //
    // `static_gate` is intentionally NOT in this dispatch clone, in EITHER mode:
    // the gate layers are applied after this clone is taken (below, after the MCP
    // merge, in the fully-dynamic path; outside the static-first middleware in the
    // SSG/ISG path). A `static_gate` is a page-cache gate whose only action is a
    // browser redirect/reject, which is meaningless for a JSON-RPC `tools/call`.
    // MCP/API auth belongs in route-level guards / `#[secured]` / session, which
    // DO traverse this clone.
    //
    // KNOWN LIMITATION (static/ISR mode): when an app has a `dist` manifest,
    // `try_build_router_with_static_inner` also drains the global custom layers
    // (`AppBuilder::layer`) and applies them outside the static-first middleware,
    // after this clone is taken. So in static mode a `tools/call` replay does not
    // pass through hand-rolled global `.layer(...)` middleware (it would in the
    // fully-dynamic path, where custom layers are applied via `apply_middleware`
    // before the clone). Restoring full parity for custom layers would require
    // making the appliers re-usable (they are `FnOnce` today), so this is left
    // documented rather than fixed for that narrow combination.
    #[cfg(feature = "mcp")]
    let router = if let Some((mount_path, tools, endpoint_layer)) = mcp_prepared {
        // The framework's outermost `SecurityHeadersLayer` is applied AFTER this
        // clone (below, with the gate), so the dispatch snapshot would otherwise
        // miss it. That layer also injects `CspNonce` into request extensions, so
        // without it a `tools/call` replay of a handler using the `CspNonce`
        // extractor would 500 when `csp_nonce` is enabled. Re-attach it to the
        // dispatch clone only: a direct HTTP request gets the same layer via the
        // outer application, and the replay's response headers are discarded when
        // `serve_mcp` rebuilds the JSON-RPC envelope, so there is no duplicate
        // live header. (The gate is intentionally NOT re-attached here — a browser
        // redirect/reject is meaningless for JSON-RPC dispatch.)
        let dispatch = router
            .clone()
            .layer(crate::security::SecurityHeadersLayer::from_config(
                &config.security.headers,
            ))
            .with_state(state.clone());
        // For header-based tenancy, forward the configured tenant header on
        // dispatch so tenant-scoped tools resolve the same tenant a direct HTTP
        // call would. Other sources key off already-forwarded headers/Host.
        let tenant_header = (config.tenancy.enabled && config.tenancy.source == "header")
            .then(|| config.tenancy.header_name.clone());
        let wiring = crate::mcp::McpWiring {
            // The CORS config drives the cross-origin Origin allowlist and the
            // endpoint's own OPTIONS preflight responses.
            cors: config.cors.clone(),
            // The same-origin shortcut is gated on the app's trusted-Host
            // policy so it can't be abused for DNS rebinding.
            trusted_hosts: TrustedHostPolicy::from_config(config),
            tenant_header,
            // Forward the configured CSRF header (default `x-csrf-token`) so
            // customized CsrfConfig::token_header deployments work via MCP.
            csrf_header: config.security.csrf.token_header.to_ascii_lowercase(),
            // The envelope is rate-limited below iff rate limiting is enabled;
            // when so, a tools/call is counted there and its replay is exempted
            // from the dispatch pipeline's limiter (avoiding double-counting).
            envelope_rate_limited: config.security.rate_limit.enabled,
            // `dispatch` above is cloned from `router`, which already carries
            // `load_shed_layer` (applied inside `apply_middleware`) — so when
            // the envelope below is ALSO wrapped with that same shared layer,
            // a tools/call must mark its replay exempt (avoiding double-
            // counting against the same in-flight counter).
            envelope_load_shed: mcp_load_shed_layer.is_some(),
        };
        let mut mcp_router =
            crate::mcp::build_mcp_router(&mount_path, tools, dispatch, wiring, endpoint_layer);
        // NOTE: the inbound request-timeout layer for this envelope is applied
        // further down, *outer* to the rate-limit layer (search for
        // `apply_request_timeout_middleware` below). It must wrap the limiter so a
        // stalled Redis rate-limit decision is bounded by `request_timeout_ms`,
        // matching the main stack where `apply_middleware` installs the timeout
        // outer to `apply_rate_limit_middleware`.
        // Gate the envelope under maintenance mode, mirroring the layer
        // `apply_middleware` installs for direct routes. The `/mcp` router is
        // merged after that layer, so without this `initialize`/`tools/list`
        // would keep serving the tool catalog during maintenance (the
        // `tools/call` replay is already gated — the dispatch clone carries the
        // layer). Applied before the `TrustedProxiesLayer` below so it is inner
        // to it: the maintenance IP allow-list then reads the proxy-resolved
        // identity, exactly as the direct-route layer does, instead of a
        // spoofable raw `X-Forwarded-For`.
        mcp_router = mcp_router.layer(build_maintenance_layer(config, state));
        // Admission control / load shedding (#1006), mirroring the layer
        // `apply_middleware` installs for direct routes (see the comment
        // there). The `/mcp` router is merged after that layer, so without
        // this, `initialize`/`tools/list`/`tools/call` would bypass
        // `server.max_concurrent_requests` entirely. Reuses the SAME
        // `load_shed_layer` instance passed to `apply_middleware` above
        // (cloned, sharing its `Arc` in-flight counter) rather than building
        // a second, independently-counting layer — see that call site's
        // comment. `None` (the default) is a no-op, matching direct routes.
        if let Some(load_shed) = mcp_load_shed_layer {
            mcp_router = mcp_router.layer(load_shed);
        }
        // Stamp `ResolvedClientIdentity` on the *outer* `/mcp` request too. The
        // MCP route is merged after `apply_middleware`, so the centralized
        // `TrustedProxiesLayer` above does not wrap it; without this, the
        // endpoint's own DNS-rebinding / same-origin check would fall back to
        // the raw (possibly proxy-rewritten) `Host` and wrongly 403 a
        // same-origin browser client behind a TLS-terminating proxy. The
        // dispatch clone already carries its own copy of this layer.
        mcp_router = apply_trusted_proxies_middleware(mcp_router, config);
        // The MCP route is merged after `apply_upload_middleware`, so axum's
        // built-in 2 MiB `DefaultBodyLimit` — not the app's configured limit —
        // would otherwise govern the `tools/call` envelope's `Bytes` body. Apply
        // the same cap a direct JSON endpoint gets so larger-but-valid tool
        // payloads aren't rejected before dispatch.
        mcp_router = mcp_router.layer(axum::extract::DefaultBodyLimit::max(
            config.security.upload.max_request_size_bytes,
        ));
        // Rate-limit the envelope so `secure_mcp` auth rejections — which never
        // reach the dispatch clone's limiter — are throttled (credential
        // guessing otherwise consumes no per-client bucket). A successful
        // tools/call is counted once here and replayed with `RateLimitExempt`,
        // so it isn't double-counted by the dispatch pipeline's own limiter.
        // No-op when rate limiting is disabled (matching `envelope_rate_limited`).
        //
        // KNOWN LIMITATION (key_strategy = AuthenticatedPrincipal + session
        // auth): the envelope keys on the IP fallback because the session layer
        // — which `populate_rate_limit_principal` reads the principal from — is
        // applied inside `apply_middleware` and does not wrap this late-merged
        // router, so no `RateLimitPrincipal` is resolved here. Because the
        // tools/call replay is then exempted, the dispatch clone's
        // principal-aware limiter is skipped too, so a session-authenticated MCP
        // call does not consume the same per-user bucket a direct request would
        // (the framework only derives `RateLimitPrincipal` from the session).
        mcp_router = apply_rate_limit_middleware(mcp_router, config, state);
        // Bound the whole envelope — the rate-limit decision (a stalled
        // Redis-backed limiter would otherwise tie up `/mcp` indefinitely), the
        // metadata/auth work (initialize, tools/list, and `secure_mcp` auth
        // rejections that never reach the dispatch clone), and the in-process
        // `tools/call` dispatch — by the global inbound deadline. The `/mcp`
        // router is merged after `apply_middleware`, so the timeout layer
        // installed there does NOT wrap it; without this the prod global deadline
        // would not bound this surface. Applied here, outer to the rate-limit
        // layer above (matching the main stack, where `apply_middleware` installs
        // the timeout outer to `apply_rate_limit_middleware`) but inner to the
        // security-header and CORS layers below, so a stalled limiter is bounded
        // while the timeout 503 still flows out through those layers and stays
        // CORS-readable. Route-level overrides do not apply to the fixed mount
        // path, so an empty override table is passed (the layer is a no-op when
        // the global timeout is disabled).
        //
        // KNOWN LIMITATION (tools/call vs per-route timeout): this envelope timer
        // wraps the whole POST, including the in-process `tools/call` dispatch
        // replay, with the global default deadline. The dispatch clone carries
        // its own per-route timeout layer, but it is *inner* to this one, so a
        // tool whose route declares `timeout = "off"` or a longer `timeout_ms`
        // is still capped at the global default when invoked via MCP (it runs
        // unbounded / longer over a direct HTTP call). Honoring the per-route
        // policy here would require propagating the dispatched route's timeout
        // out to this single fixed-path endpoint, which has no per-route
        // distinction at the layer level; the global deadline is kept as a
        // safety bound instead. `mirror_cors = false`: the 503 already flows out
        // through this router's own (outer) `CorsLayer` from `apply_mcp_cors_layer`.
        mcp_router = apply_request_timeout_middleware(
            mcp_router,
            config,
            state.metrics.clone(),
            std::sync::Arc::new(std::collections::HashMap::new()),
            false,
        );
        // Security headers (HSTS/CSP/etc.), mirroring the `SecurityHeadersLayer`
        // `apply_middleware` installs for direct routes. The `/mcp` router is
        // merged after that layer, so without this the envelope's responses —
        // `initialize`/`tools/list`, auth 401/403, and rate-limit 429 — would
        // ship without the configured `security.headers` every direct route
        // carries. (The `tools/call` replay's headers are produced on the
        // dispatch clone and discarded when `serve_mcp` rebuilds the JSON-RPC
        // response, so the envelope needs its own copy.)
        mcp_router = mcp_router.layer(crate::security::SecurityHeadersLayer::from_config(
            &config.security.headers,
        ));
        // CORS grant outermost so every response — including auth 401/403, the
        // 413 body-limit rejection, and a 429 from the limiter above, all
        // produced before `serve_mcp` runs — is readable by an allowlisted
        // browser client instead of being masked as a CORS failure.
        mcp_router = crate::mcp::apply_mcp_cors_layer(mcp_router, &config.cors);
        router.merge(mcp_router)
    } else {
        router
    };

    // Apply the pre-static gate and the framework's outermost `SecurityHeadersLayer`
    // LAST, after the MCP dispatch clone above was taken. This keeps the gate out
    // of the `tools/call` dispatch path in fully-dynamic mode (matching the SSG/ISG
    // path and the documented intent that a browser redirect/reject is meaningless
    // for JSON-RPC dispatch), while still running the gate before session and the
    // static cache for ordinary HTTP requests. `SecurityHeadersLayer` is applied
    // outermost so a gate redirect/401 short-circuit still carries HSTS/CSP/nosniff;
    // a single application keeps CSP nonces consistent.
    //
    // In the SSG/ISG path `defer_security_headers` is true and the gate layers were
    // drained by `try_build_router_with_static_inner` (which applies both the gate
    // and the single outer `SecurityHeadersLayer` outside the static-first
    // middleware), so this block is a no-op there.
    let router = if defer_security_headers {
        router
    } else {
        let router =
            apply_layers_in_registration_order(router, static_gate_layers, "Pre-static gate");
        router.layer(crate::security::SecurityHeadersLayer::from_config(
            &config.security.headers,
        ))
    };

    Ok(router)
}

/// Parse `{name}` captures from a route path.
///
/// Mirrors the compile-time extractor in `autumn_macros::api_doc` so
/// runtime spec assembly (which sees scope prefixes that the macro
/// never does) produces consistent parameter lists.
#[cfg(feature = "openapi")]
pub fn extract_path_params(path: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut remaining = path;

    while let Some(start) = remaining.find('{') {
        let after_brace = &remaining[start + 1..];
        // `{{` is an escaped literal brace (matchit renders `{{`/`}}` as literal
        // `{`/`}`), not a parameter. Skip the escaped brace and continue,
        // mirroring `autumn_macros::api_doc::extract_path_params`. The prior
        // `rfind`-based variant dropped this branch and so injected a phantom
        // param for valid escaped-brace routes (`{{hello}}` -> `hello`).
        if let Some(rest) = after_brace.strip_prefix('{') {
            remaining = rest;
            continue;
        }
        let Some(end_rel) = after_brace.find('}') else {
            break;
        };

        let inner = &after_brace[..end_rel];
        // Isolate the parameter name from any `:constraint` suffix
        // (`{id:[0-9]+}` -> `id`).
        let name = inner.split(':').next().unwrap_or(inner).trim();
        // Brace-free guard: only emit a name that is non-empty and contains no
        // stray brace. On nested/unbalanced input the inner segment may still
        // hold a `{` (e.g. `"{a{b}"` -> inner `"a{b"`); dropping such names
        // keeps the emitted list brace-free, which the macro algorithm alone
        // would not (#1721).
        if !name.is_empty() && !name.contains('{') && !name.contains('}') {
            out.push(name.to_owned());
        }

        remaining = &after_brace[end_rel + 1..];
    }

    out
}

/// Handler that dynamically constructs the `OpenAPI` specification document per request
/// so deprecation and sunset statuses do not go stale.
#[cfg(feature = "openapi")]
async fn serve_openapi_spec(
    state: axum::extract::State<AppState>,
    axum::extract::Extension(config): axum::extract::Extension<
        std::sync::Arc<crate::openapi::OpenApiConfig>,
    >,
    axum::extract::Extension(docs): axum::extract::Extension<
        std::sync::Arc<Vec<crate::openapi::ApiDoc>>,
    >,
) -> impl axum::response::IntoResponse {
    use axum::response::IntoResponse;
    let refs: Vec<&crate::openapi::ApiDoc> = docs.iter().collect();
    let now = state.clock().now();
    let spec = crate::openapi::generate_spec_at(&config, &refs, now);
    let spec_json = serde_json::to_string_pretty(&spec)
        .unwrap_or_else(|e| format!("{{\"error\": \"failed to serialize spec: {e}\"}}"));
    (
        [(http::header::CONTENT_TYPE, "application/json")],
        spec_json,
    )
        .into_response()
}

/// Build an Axum sub-router that serves the generated `OpenAPI` document
/// and (optionally) a Swagger UI HTML page.
///
/// Returns `None` when `OpenAPI` generation is disabled, i.e. the user
/// never called [`AppBuilder::openapi`](crate::app::AppBuilder::openapi).
///
/// The spec is dynamically generated on request to prevent lifecycle status from going stale.
#[cfg(feature = "openapi")]
fn build_openapi_router(
    route_list: &[Route],
    scoped_groups: &[ScopedGroup],
    openapi_config: Option<&crate::openapi::OpenApiConfig>,
    session_cookie_name: &str,
    api_versions: &[crate::app::ApiVersion],
) -> Result<Option<axum::Router<AppState>>, RouterBuildError> {
    let Some(config) = openapi_config else {
        return Ok(None);
    };
    let mut config = config.clone();
    session_cookie_name.clone_into(&mut config.session_cookie_name);
    config.api_versions = api_versions.to_vec();

    // Validate user-provided paths up front so a typo like
    // `"openapi.json"` surfaces as a recoverable RouterBuildError
    // rather than an axum panic (`Paths must start with a '/'`).
    validate_route_path("openapi_json_path", &config.openapi_json_path)?;
    if let Some(path) = &config.swagger_ui_path {
        validate_route_path("swagger_ui_path", path)?;
        // Registering two GET handlers on the same path would cause an
        // axum `Route::route` panic, so reject collisions as a
        // configuration error instead.
        if path == &config.openapi_json_path {
            return Err(RouterBuildError::DuplicateOpenApiPath { path: path.clone() });
        }
    }

    let docs = collect_openapi_docs(route_list, scoped_groups);

    let json_path = config.openapi_json_path.clone();
    let swagger_path = config.swagger_ui_path.clone();
    let title = config.title.clone();

    let mut router = axum::Router::<AppState>::new()
        .route(&json_path, axum::routing::get(serve_openapi_spec))
        .layer(axum::extract::Extension(std::sync::Arc::new(
            config.clone(),
        )))
        .layer(axum::extract::Extension(std::sync::Arc::new(docs)));

    if let Some(path) = swagger_path {
        router = mount_swagger_ui_routes(router, &path, &title, &json_path);
    }

    tracing::debug!(
        openapi_json = %json_path,
        swagger_ui = ?config.swagger_ui_path,
        swagger_ui_version = crate::openapi::SWAGGER_UI_VERSION,
        "Mounted OpenAPI endpoints"
    );

    Ok(Some(router))
}

/// Join a nest/scope prefix with a child route path, matching
/// `axum::Router::nest` normalization.
///
/// `nest("/api", r)` mounts r's `/` at `/api` (not `/api/`), and any
/// other child path `/foo` at `/api/foo`. The collision check and the
/// path emitted into the `OpenAPI` spec must use the same shape or we
/// end up either missing real collisions (the reviewer's case:
/// `/api` + `/` recorded as `/api/` but axum routes it at `/api`) or
/// generating a spec whose URLs don't match what axum serves.
#[allow(dead_code)]
pub fn join_nested_path(prefix: &str, child: &str) -> String {
    if child == "/" || child.is_empty() {
        // axum mounts the root child at the prefix *verbatim*, keeping any
        // trailing slash: `nest("/api", route("/"))` is served at "/api" while
        // `nest("/api/", route("/"))` is served at "/api/" — and `MatchedPath`
        // reports the same string. Preserve the prefix as-is so the per-route
        // timeout table keys by exactly what the runtime looks up; only the
        // empty (root) prefix collapses to "/".
        if prefix.is_empty() {
            "/".to_owned()
        } else {
            prefix.to_owned()
        }
    } else {
        // Non-root children always join on a single slash, matching axum (e.g.
        // `nest("/api/", route("/users"))` resolves to "/api/users").
        let prefix_trimmed = prefix.trim_end_matches('/');
        if child.starts_with('/') {
            format!("{prefix_trimmed}{child}")
        } else {
            format!("{prefix_trimmed}/{child}")
        }
    }
}

/// Shared validator for user-supplied `OpenAPI` mount paths.
///
/// Catches the common typos that would otherwise manifest as axum
/// panics inside `Router::route` at startup:
///
/// * empty or missing leading slash,
/// * unbalanced `{` / `}` pairs,
/// * any `{…}` / `{*…}` capture or wildcard syntax (the mount points
///   are static endpoints — a user that needs templated paths shouldn't
///   be using this field), and
/// * any `*` wildcard character (axum treats these as catch-alls).
///
/// The check intentionally stays conservative: rejecting a few valid-
/// but-weird paths is far better than letting a typo like
/// `"openapi.json"` or `"/docs/{id}"` crash boot.
#[cfg(feature = "openapi")]
fn validate_route_path(field: &'static str, value: &str) -> Result<(), RouterBuildError> {
    let reject = |reason_fragment: &str| {
        Err(RouterBuildError::InvalidOpenApiPath {
            field,
            value: format!("{value:?} {reason_fragment}"),
        })
    };

    if value.is_empty() {
        return reject("(must be non-empty)");
    }
    if !value.starts_with('/') {
        return reject("(must start with '/')");
    }
    // Double-slash inside the path is almost always a typo (e.g.
    // `//v3/api-docs`) and axum normalizes it away on match, so
    // treating it as invalid avoids surprising "route can't be hit"
    // reports in the field.
    if value.contains("//") {
        return reject("(must not contain '//')");
    }

    let mut depth: i32 = 0;
    for ch in value.chars() {
        match ch {
            '{' => depth += 1,
            '}' => {
                depth -= 1;
                if depth < 0 {
                    return reject("(unbalanced '}')");
                }
            }
            '*' => return reject("(wildcard '*' is not allowed in an OpenAPI mount path)"),
            _ => {}
        }
    }
    if depth != 0 {
        return reject("(unbalanced '{')");
    }
    if value.contains('{') {
        return reject("(OpenAPI mount paths must be static; `{…}` captures are not allowed)");
    }
    Ok(())
}

/// Collect the exact `GET`/`WS` paths owned by the user's *typed* route table
/// (top-level routes plus scoped-group routes, after scope-prefix resolution).
///
/// Unlike [`collect_claimed_get_paths`], this deliberately excludes every
/// framework-mounted path: its sole purpose is to let the auto-mounted probe
/// endpoints ([`mount_probe_endpoints`]) detect when a *user* handler already
/// owns a probe path and yield to it, rather than panicking inside
/// `axum::Router::route` on an overlapping `GET` (issue #1971). A `WS` route is
/// a `GET` under the hood, so it claims the path too (mirroring
/// [`collect_claimed_get_paths`]). Opaque routers registered via
/// [`AppBuilder::merge`](crate::app::AppBuilder::merge) /
/// [`AppBuilder::nest`](crate::app::AppBuilder::nest) are not introspectable
/// and so are not covered here — the same limitation the OpenAPI/MCP collision
/// preflights carry.
fn collect_user_get_paths(
    route_list: &[Route],
    scoped_groups: &[ScopedGroup],
) -> std::collections::HashSet<String> {
    let mut owned: std::collections::HashSet<String> = std::collections::HashSet::new();
    for route in route_list {
        if route.method == http::Method::GET || route.method.as_str() == "WS" {
            owned.insert(route.path.to_owned());
        }
    }
    for group in scoped_groups {
        for route in &group.routes {
            if route.method == http::Method::GET || route.method.as_str() == "WS" {
                owned.insert(join_nested_path(&group.prefix, route.path));
            }
        }
    }
    owned
}

/// Gather every path that a `GET` (or `WS`, which mounts as a `GET`) handler
/// will already own by the time a late-merged sub-router (`OpenAPI` or MCP) is
/// added: user routes (top-level + scoped groups) plus framework-mounted `GET`s
/// (probes, actuator, htmx assets, dev live-reload, mail previews). Shared by
/// the `OpenAPI` and MCP mount-collision preflights so they stay in lockstep.
#[cfg(feature = "openapi")]
fn collect_claimed_get_paths(
    route_list: &[Route],
    scoped_groups: &[ScopedGroup],
    config: &AutumnConfig,
) -> std::collections::HashSet<String> {
    let mut claimed: std::collections::HashSet<String> = std::collections::HashSet::new();
    for route in route_list {
        if route.method == http::Method::GET || route.method.as_str() == "WS" {
            claimed.insert(route.path.to_owned());
        }
    }
    for group in scoped_groups {
        for route in &group.routes {
            if route.method == http::Method::GET || route.method.as_str() == "WS" {
                claimed.insert(join_nested_path(&group.prefix, route.path));
            }
        }
    }
    // Framework-mounted GETs.
    claimed.insert(config.health.path.clone());
    claimed.insert(config.health.live_path.clone());
    claimed.insert(config.health.ready_path.clone());
    claimed.insert(config.health.startup_path.clone());
    for path in crate::actuator::actuator_endpoint_paths(
        &config.actuator.prefix,
        config.actuator.sensitive,
        config.actuator.prometheus,
    ) {
        claimed.insert(path);
    }
    #[cfg(feature = "htmx")]
    {
        // Only claim the htmx path when the built-in handler is actually
        // mounted; when htmx is vendored via `autumn assets`, ServeDir serves
        // the file and the path must not appear in the claimed-routes set.
        if !crate::assets::htmx_is_vendored() {
            claimed.insert(crate::htmx::HTMX_JS_PATH.to_owned());
        }
        claimed.insert(crate::htmx::HTMX_CSRF_JS_PATH.to_owned());
        claimed.insert(crate::htmx::AUTUMN_WIDGETS_JS_PATH.to_owned());
        claimed.insert(crate::htmx::IDIOMORPH_JS_PATH.to_owned());
        claimed.insert(crate::htmx::HTMX_SSE_JS_PATH.to_owned());
    }
    // Framework CSS routes (flash/widget stylesheets) merge a GET
    // unconditionally whenever their feature is on, before the late-merged
    // OpenAPI/MCP routers — reserve them so a colliding configured path
    // surfaces the typed collision error instead of panicking in
    // `router.merge`.
    #[cfg(feature = "flash")]
    claimed.insert(crate::flash::FLASH_CSS_PATH.to_owned());
    #[cfg(feature = "maud")]
    claimed.insert(crate::ui::WIDGETS_CSS_PATH.to_owned());
    // Dev live-reload endpoints are only mounted when the env vars
    // that enable them are set, but reserving the paths regardless
    // makes the error message deterministic across dev/prod.
    if dev::is_enabled_with_env(&crate::config::OsEnv) {
        claimed.insert(dev::LIVE_RELOAD_PATH.to_owned());
        claimed.insert(dev::LIVE_RELOAD_SCRIPT_PATH.to_owned());
    }
    // The dev request inspector merges a GET at `config.dev.inspector_path`
    // (only under the dev profile), before the late-merged OpenAPI/MCP routers.
    // Reserve it so a mount path colliding with the inspector surfaces a
    // recoverable error instead of panicking in `router.merge`.
    if matches!(config.profile.as_deref(), Some("dev" | "development")) {
        claimed.insert(config.dev.inspector_path.clone());
    }
    #[cfg(feature = "mail")]
    if config
        .mail
        .preview_routes_enabled(config.profile.as_deref())
    {
        claimed.insert(crate::mail::MAIL_PREVIEW_PATH.to_owned());
        claimed.insert("/_autumn/mail/messages/{message_id}".to_owned());
        claimed.insert("/_autumn/mail/previews/{mailer}/{method}".to_owned());
    }
    // The widget story gallery merges GETs at `/_stories` and
    // `/_stories/{slug}` when `stories.enabled` resolves true, before the
    // late-merged OpenAPI/MCP routers — reserve them so a colliding
    // configured mount path surfaces the typed collision error instead of
    // panicking in `router.merge`.
    #[cfg(feature = "maud")]
    if config.stories.enabled {
        claimed.insert(crate::stories::STORIES_PATH.to_owned());
        claimed.insert("/_stories/{slug}".to_owned());
    }
    // The default unsubscribe endpoint merges a GET (+POST) at `UNSUBSCRIBE_PATH`
    // before the late-merged OpenAPI/MCP routers, so reserve it too — otherwise an
    // OpenAPI/MCP mount configured at `/_autumn/unsubscribe` passes this preflight
    // and then panics in `router.merge` instead of surfacing the typed collision.
    #[cfg(feature = "mail")]
    if config.mail.should_mount_unsubscribe_endpoint() {
        claimed.insert(crate::mail::UNSUBSCRIBE_PATH.to_owned());
    }
    // The tracked-job status endpoint merges a GET before the late-merged
    // OpenAPI/MCP routers, so reserve it too (same rationale as unsubscribe
    // above): an OpenAPI/MCP mount at this path should surface the typed
    // collision instead of panicking in `router.merge`.
    if config.jobs.tracking.route_enabled {
        claimed.insert(crate::job_tracking::JOB_STATUS_ROUTE_PATH.to_owned());
    }
    claimed
}

/// Reject an MCP mount path that overlaps with a route already owning that
/// path. The MCP endpoint mounts `GET`+`POST` at `mount_path`; merging it would
/// panic in axum if a `GET` (any user/framework route) or `POST` (a user route)
/// already lives there. We surface a recoverable
/// [`RouterBuildError::McpPathCollision`] instead, reusing the same claimed-GET
/// gathering as the `OpenAPI` preflight so framework routes (health/probe,
/// actuator, htmx, dev) are covered too — e.g. `mount_mcp(config.health.path)`.
/// The configured `OpenAPI` JSON/UI/asset paths (which merge as `GET`s before
/// the MCP router) are checked as well.
#[cfg(feature = "mcp")]
fn reject_mcp_path_collisions(
    mount_path: &str,
    route_list: &[Route],
    scoped_groups: &[ScopedGroup],
    config: &AutumnConfig,
    openapi: Option<&crate::openapi::OpenApiConfig>,
    merge_routers: &[axum::Router<AppState>],
    nest_routers: &[(String, axum::Router<AppState>)],
) -> Result<(), RouterBuildError> {
    let mut claimed_get = collect_claimed_get_paths(route_list, scoped_groups, config);
    // The OpenAPI JSON/Swagger-UI endpoints (and UI assets) merge as GETs
    // before the MCP router, so a mount path colliding with them would panic.
    if let Some(openapi) = openapi {
        claimed_get.insert(openapi.openapi_json_path.clone());
        if let Some(ui_path) = &openapi.swagger_ui_path {
            claimed_get.insert(ui_path.clone());
            claimed_get.extend(crate::openapi::swagger_ui_asset_paths(ui_path));
        }
    }
    if claimed_get.contains(mount_path) {
        return Err(RouterBuildError::McpPathCollision {
            path: mount_path.to_owned(),
            method: "GET".to_owned(),
        });
    }
    // POST handlers come from user routes (framework routes are GETs).
    let post_owns_path = route_list
        .iter()
        .any(|route| route.method == http::Method::POST && route.path == mount_path)
        || scoped_groups.iter().any(|group| {
            group.routes.iter().any(|route| {
                route.method == http::Method::POST
                    && join_nested_path(&group.prefix, route.path) == mount_path
            })
        });
    if post_owns_path {
        return Err(RouterBuildError::McpPathCollision {
            path: mount_path.to_owned(),
            method: "POST".to_owned(),
        });
    }
    // A nest prefix P owns every route under P (`/P/...`), and those raw routers
    // are mounted before the MCP router. A mount path equal to P or falling
    // under `P/` would be shadowed by (or panic against) the nested router, so
    // reject it up front — mirroring the OpenAPI nest-collision preflight. The
    // framework unconditionally nests the static-file service at `/static`, so
    // reserve that prefix too.
    let nest_prefixes = nest_routers
        .iter()
        .map(|(prefix, _)| prefix.as_str())
        .chain(std::iter::once("/static"));
    for prefix in nest_prefixes {
        let prefix_slash = format!("{prefix}/");
        if mount_path == prefix || mount_path.starts_with(&prefix_slash) {
            return Err(RouterBuildError::McpPathCollision {
                path: mount_path.to_owned(),
                method: "nested router".to_owned(),
            });
        }
    }
    // Raw merged routers are opaque — axum does not expose their route table —
    // so an overlapping handler there would still panic at merge time. Warn so
    // operators know the check can't cover this case (mirrors the OpenAPI one).
    if !merge_routers.is_empty() {
        tracing::warn!(
            mcp_mount_path = %mount_path,
            merged_routers = merge_routers.len(),
            "MCP mount collision check skipped for AppBuilder::merge routers: \
             axum does not expose their route table, so an overlapping handler \
             will still panic at startup. Choose an MCP mount path that doesn't \
             overlap with any merged router's handlers."
        );
    }
    Ok(())
}

/// Reject `OpenAPI` mount paths that overlap with an existing `GET`
/// handler.
///
/// `axum::Router::merge` panics when the merged routers have method
/// handlers on the same path (e.g. two `GET` handlers on
/// `/v3/api-docs`). We surface that as a recoverable
/// [`RouterBuildError::OpenApiPathCollision`] so misconfiguration
/// produces an actionable error instead of a crash on startup.
///
/// We check against:
/// * user routes (top-level + scoped groups) that will be mounted
///   before the `OpenAPI` sub-router merges in,
/// * framework `GET`s: probes, actuator, htmx assets, and dev
///   live-reload when enabled,
/// * nest prefixes from [`AppBuilder::nest`](crate::app::AppBuilder::nest)
///   when the `OpenAPI` path falls under one.
///
/// Raw routers passed to [`AppBuilder::merge`](crate::app::AppBuilder::merge)
/// cannot be introspected — axum does not expose their route table.
/// We emit a `tracing::warn!` so operators know the check is
/// incomplete in that case.
#[cfg(feature = "openapi")]
fn reject_openapi_path_collisions(
    openapi_config: Option<&crate::openapi::OpenApiConfig>,
    route_list: &[Route],
    scoped_groups: &[ScopedGroup],
    merge_routers: &[axum::Router<AppState>],
    nest_routers: &[(String, axum::Router<AppState>)],
    config: &AutumnConfig,
) -> Result<(), RouterBuildError> {
    let Some(openapi) = openapi_config else {
        return Ok(());
    };

    // Gather every path a GET (or WS, which mounts as GET) will already
    // own by the time we merge.
    let claimed = collect_claimed_get_paths(route_list, scoped_groups, config);

    check_openapi_path_against(
        "openapi_json_path",
        &openapi.openapi_json_path,
        &claimed,
        nest_routers,
    )?;
    if let Some(path) = &openapi.swagger_ui_path {
        check_openapi_path_against("swagger_ui_path", path, &claimed, nest_routers)?;
        let mut claimed_with_openapi = claimed;
        claimed_with_openapi.insert(openapi.openapi_json_path.clone());
        for asset_path in crate::openapi::swagger_ui_asset_paths(path) {
            check_openapi_path_against(
                "swagger_ui_path",
                &asset_path,
                &claimed_with_openapi,
                nest_routers,
            )?;
        }
    }

    // Raw merged routers are opaque — we can't inspect their route
    // tables through the axum API. Warn instead of failing so users
    // know the check doesn't cover this code path.
    if !merge_routers.is_empty() {
        tracing::warn!(
            openapi_json_path = %openapi.openapi_json_path,
            swagger_ui_path = ?openapi.swagger_ui_path,
            merged_routers = merge_routers.len(),
            "OpenAPI mount collision check skipped for AppBuilder::merge routers: \
             axum does not expose their route table, so overlapping GET handlers \
             will still panic at startup. Choose OpenAPI paths that don't overlap \
             with any merged router's handlers."
        );
    }

    Ok(())
}

/// Evaluate a single `OpenAPI` path against the claimed-path set plus
/// any nest prefixes. Returns an `OpenApiPathCollision` error on
/// collision.
#[cfg(feature = "openapi")]
fn check_openapi_path_against(
    field: &'static str,
    path: &str,
    claimed: &std::collections::HashSet<String>,
    nest_routers: &[(String, axum::Router<AppState>)],
) -> Result<(), RouterBuildError> {
    if claimed.contains(path) {
        return Err(RouterBuildError::OpenApiPathCollision {
            field,
            path: path.to_owned(),
        });
    }
    // A nest prefix P owns every route under P (`/P/...`), so any
    // OpenAPI path that equals P or starts with `P/` will either
    // panic on merge (exact match) or nest inside the user's router
    // (where axum routing semantics decide which handler wins).
    // Reject both cases so the spec endpoint can't silently vanish.
    for (prefix, _) in nest_routers {
        let prefix_slash = format!("{prefix}/");
        if path == prefix || path.starts_with(&prefix_slash) {
            return Err(RouterBuildError::OpenApiPathCollision {
                field,
                path: path.to_owned(),
            });
        }
    }
    Ok(())
}

/// The HTTP method axum actually mounts a handler under — the effective verb the
/// duplicate preflight and the request-timeout table must both key on so the two
/// never drift.
///
/// `#[ws]` records the synthetic `WS` method, but the macro builds its handler
/// with `axum::routing::get` and [`group_and_mount_routes`] merges it as a `GET`
/// `MethodRouter`. So a `#[ws("/p")]` and a `#[get("/p")]` are the SAME mount as
/// far as axum is concerned and would panic on merge. Every other method mounts
/// under itself.
fn effective_mount_method(method: &http::Method) -> http::Method {
    if method.as_str() == "WS" {
        http::Method::GET
    } else {
        method.clone()
    }
}

/// Probe whether two path templates conflict under matchit — the SAME engine
/// axum 0.8 routes through — by inserting both into a throwaway router. axum's
/// `Router::route` forwards each template to matchit verbatim (brace syntax:
/// `{param}` / `{*wild}`), so a matchit `Conflict` here is exactly the mount
/// panic `reject_duplicate_user_routes` is preventing. Used only on the error
/// path to name the specific prior template a conflicting insert collided with.
fn paths_conflict_under_matchit(existing: &str, incoming: &str) -> bool {
    let mut probe: matchit::Router<()> = matchit::Router::new();
    // If `existing` is itself malformed its insert fails; then it isn't in the
    // tree and can't be the conflict partner — return false so the caller keeps
    // scanning earlier templates.
    if probe.insert(existing, ()).is_err() {
        return false;
    }
    matches!(
        probe.insert(incoming, ()),
        Err(matchit::InsertError::Conflict { .. })
    )
}

/// Fail-fast preflight for issue #1012: reject two user- or plugin-registered
/// routes that resolve to the same `(method, path)` before
/// [`group_and_mount_routes`] hands overlapping method routes to
/// [`axum::routing::MethodRouter::merge`] (which panics inside
/// `Router::route` at startup).
///
/// **Coverage** — mirrors `collect_route_infos`'s scope-prefix resolution so
/// duplicates across the same source, across sources (top-level +
/// scoped/plugin, plugin + plugin), and across `.scoped(...)` groups are
/// caught uniformly. `#[repository]`-generated API routes land in
/// `route_list` like any other route macro output, so they are covered
/// for free.
///
/// **Not covered — opaque routers**:
/// * [`AppBuilder::merge`](crate::app::AppBuilder::merge) — axum does not
///   expose the merged router's route table.
/// * [`AppBuilder::nest`](crate::app::AppBuilder::nest) — same limitation.
///
/// A non-empty opaque table emits a `tracing::warn!` (same pattern as the
/// existing `OpenAPI` and MCP merge-router warnings) so operators know the
/// preflight cannot see inside — an overlap involving one of those routers
/// will still surface as an axum startup panic.
///
/// The first pairwise collision wins: `existing` names the handler that
/// registered the path first (in the iteration order used by the actual
/// mount step), `incoming` names the duplicate that triggered the error.
fn reject_duplicate_user_routes(
    route_list: &[Route],
    scoped_groups: &[ScopedGroup],
    merge_routers: &[axum::Router<AppState>],
    nest_routers: &[(String, axum::Router<AppState>)],
) -> Result<(), RouterBuildError> {
    // `claimed` keys on `(effective_method, exact_path)`; the value is the
    // first-seen handler name so the error can point at BOTH sides of an
    // EXACT-duplicate collision (AC #2). Iterate in the same order the mount
    // pass will: top-level routes first (`group_and_mount_routes`), then scoped
    // groups (`mount_scoped_groups`).
    //
    // NOTE: the key is the EXACT path string, not the normalized shape — axum
    // merges the same exact path across distinct methods (AC #4: `GET /admin` +
    // `POST /admin`, `GET /users/{id}` + `POST /users/{id}`), so a same-shape
    // clash is NOT a duplicate unless the exact path AND effective method both
    // match. The cross-method shape conflict is handled separately below.
    let mut claimed: std::collections::HashMap<(String, String), String> =
        std::collections::HashMap::new();

    // Method-independent path-shape conflicts are delegated to matchit — the
    // SAME engine axum 0.8 routes through — instead of a hand-rolled shape
    // normalizer. Every DISTINCT exact template is inserted into a throwaway
    // `matchit::Router`; an `InsertError::Conflict` means the two templates
    // resolve to overlapping shapes that axum's `Router::route` would reject
    // with a mount panic BEFORE any method merging (`/users/{id}` vs
    // `/users/{slug}`, `/u/{id}` vs `/u/{*rest}`, `/cmd/{tool}/{sub}` vs
    // `/cmd/{*path}`, `/file.{ext}` vs `/file.{kind}`). Delegating to matchit
    // converges every capture-name / escaped-brace / catch-all-vs-dynamic edge
    // case on axum's own semantics — see `matchit_agrees_with_axum_route_conflicts`
    // for the parity guard that fails loudly if matchit ever drifts from axum.
    //
    // IMPORTANT: exact-duplicate templates legitimately MERGE across distinct
    // methods (AC #4: `GET /users/{id}` + `POST /users/{id}`), so identical
    // strings are deduplicated BEFORE insertion — re-inserting the same string
    // would falsely self-conflict. Those fall through to the method-keyed
    // `claimed` check, which alone distinguishes a real duplicate from a legal
    // cross-method registration.
    let mut shape_router: matchit::Router<String> = matchit::Router::new();
    // DISTINCT exact templates inserted into `shape_router`, in insertion order,
    // paired with their handler name. matchit's `InsertError::Conflict { with }`
    // reports the conflicting route as an unescaped/merged node string that need
    // not equal any template we registered, so we recover the conflict partner
    // ourselves by re-probing this list (first prior template that conflicts
    // under matchit wins, matching the "first-seen is `existing`" convention).
    let mut inserted_shapes: Vec<(String, String)> = Vec::new();

    let mut record =
        |method: &http::Method, path: String, name: &str| -> Result<(), RouterBuildError> {
            let effective_method = effective_mount_method(method).to_string();

            // Shape conflict (method-independent) via the matchit oracle. Skip
            // templates whose EXACT string was already inserted: an identical
            // string is a legal cross-method merge, not a shape conflict, and
            // re-inserting it would self-conflict.
            let already_inserted = inserted_shapes.iter().any(|(p, _)| p == &path);
            if !already_inserted {
                match shape_router.insert(&path, name.to_owned()) {
                    Ok(()) => inserted_shapes.push((path.clone(), name.to_owned())),
                    Err(matchit::InsertError::Conflict { .. }) => {
                        // Name the specific prior template this one collides with.
                        let (existing_path, existing_name) = inserted_shapes
                            .iter()
                            .find(|(prior, _)| paths_conflict_under_matchit(prior, &path))
                            .cloned()
                            // Defensive fallback (a full-tree conflict with no
                            // single pairwise partner is not expected for real
                            // route templates): attribute to the first insert.
                            .unwrap_or_else(|| inserted_shapes[0].clone());
                        return Err(RouterBuildError::ConflictingRouteShape {
                            existing: existing_name,
                            existing_path,
                            incoming: name.to_owned(),
                            incoming_path: path,
                        });
                    }
                    // Any other `InsertError` (malformed param/catch-all syntax)
                    // is a single-template validity problem, not a cross-route
                    // conflict; leave it to the existing path-validation seams
                    // and axum itself rather than mislabeling it a shape clash.
                    Err(_) => {}
                }
            }

            // Exact-duplicate check: same effective method AND same exact path
            // → axum's `MethodRouter::merge` would panic. Distinct methods on
            // the same exact path are legal (axum merges them) and fall through.
            let key = (effective_method.clone(), path.clone());
            if let Some(existing) = claimed.get(&key) {
                return Err(RouterBuildError::DuplicateUserRoute {
                    method: effective_method,
                    path,
                    existing: existing.clone(),
                    incoming: name.to_owned(),
                });
            }
            claimed.insert(key, name.to_owned());
            Ok(())
        };

    for route in route_list {
        record(&route.method, route.path.to_owned(), route.name)?;
    }
    for group in scoped_groups {
        for route in &group.routes {
            record(
                &route.method,
                join_nested_path(&group.prefix, route.path),
                route.name,
            )?;
        }
    }

    // Raw merged / nested routers are opaque — axum does not expose their
    // route tables. Warn so operators know the check does not cover those
    // code paths (mirrors the OpenAPI and MCP merge-router warnings).
    if !merge_routers.is_empty() {
        tracing::warn!(
            merged_routers = merge_routers.len(),
            "duplicate-route preflight (#1012) skipped for AppBuilder::merge routers: \
             axum does not expose their route table, so an overlapping handler on a \
             method+path Autumn already owns will still panic at startup. Keep merged \
             routers on disjoint paths from your `.routes()`/`.scoped()` registrations."
        );
    }
    if !nest_routers.is_empty() {
        tracing::warn!(
            nested_routers = nest_routers.len(),
            "duplicate-route preflight (#1012) skipped for AppBuilder::nest routers: \
             axum does not expose their route table, so an overlapping handler on a \
             method+path Autumn already owns will still panic at startup. Keep nested \
             routers on disjoint prefixes from your `.routes()`/`.scoped()` registrations."
        );
    }

    Ok(())
}

fn group_and_mount_routes(
    route_list: Vec<Route>,
    idempotency_layers: Option<&BuiltIdempotencyLayers>,
    opaque_app_layers_present: bool,
    state: &AppState,
) -> axum::Router<AppState> {
    // Group routes by path so multiple methods on the same path
    // (e.g. GET /admin + POST /admin) are merged into a single
    // MethodRouter. Axum 0.7+ panics if .route() is called twice
    // with the same path — merging avoids this.
    let mut grouped: indexmap::IndexMap<&str, axum::routing::MethodRouter<AppState>> =
        indexmap::IndexMap::new();
    for route in &route_list {
        tracing::debug!(
            method = %route.method,
            path = route.path,
            name = route.name,
            "Mounted route"
        );
    }
    for route in route_list {
        let selected_layer = idempotency_layers
            .map(|layers| idempotency_layer_for_route(&route, layers, opaque_app_layers_present));
        let mut handler = route.handler;
        if let Some(layer) = selected_layer {
            handler = handler.layer(layer.clone());
        }
        if let Some(version) = route.api_version {
            handler = handler.layer(axum::middleware::from_fn_with_state(
                state.clone(),
                api_versioning_middleware,
            ));
            handler = handler.layer(axum::Extension(RouteVersionMetadata {
                version: version.to_string(),
                sunset_opt_out: route.sunset_opt_out,
                secured: route.api_doc.secured,
                required_roles: route.api_doc.required_roles,
                has_policy: route.api_doc.has_policy,
            }));
        }
        grouped
            .entry(route.path)
            .and_modify(|existing| {
                *existing = std::mem::take(existing).merge(handler.clone());
            })
            .or_insert(handler);
    }

    let mut router = axum::Router::new();
    for (path, method_router) in grouped {
        router = router.route(path, method_router);
    }
    router
}

const fn idempotency_layer_for_route<'a>(
    route: &Route,
    layers: &'a BuiltIdempotencyLayers,
    opaque_app_layers_present: bool,
) -> &'a IdempotencyLayer {
    if opaque_app_layers_present {
        &layers.manual
    } else if route_uses_generated_replay_stop(route) {
        &layers.route
    } else {
        &layers.manual
    }
}

const fn route_uses_generated_replay_stop(route: &Route) -> bool {
    matches!(
        route.idempotency,
        crate::route::RouteIdempotency::ReplayThroughInner
    )
}

fn custom_layers_require_fail_closed_idempotency(
    custom_layers: &[crate::app::CustomLayerRegistration],
) -> bool {
    custom_layers
        .iter()
        .any(|registered| !is_idempotency_transparent_app_layer(registered))
}

fn is_idempotency_transparent_app_layer(registered: &crate::app::CustomLayerRegistration) -> bool {
    registered
        .type_name
        .starts_with("autumn_web::session::SessionLayer<")
        || registered
            .type_name
            .starts_with("autumn::session::SessionLayer<")
        || registered.type_id
            == std::any::TypeId::of::<crate::session::SessionLayer<crate::session::MemoryStore>>()
        || is_i18n_bundle_extension_layer(registered.type_id)
}

#[cfg(feature = "i18n")]
fn is_i18n_bundle_extension_layer(type_id: std::any::TypeId) -> bool {
    type_id == std::any::TypeId::of::<axum::Extension<Arc<crate::i18n::Bundle>>>()
}

#[cfg(not(feature = "i18n"))]
const fn is_i18n_bundle_extension_layer(_type_id: std::any::TypeId) -> bool {
    false
}

#[cfg_attr(not(feature = "mail"), allow(unused_variables))]
#[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
fn mount_framework_routes(
    mut router: axum::Router<AppState>,
    config: &AutumnConfig,
    dev_reload_enabled: bool,
) -> axum::Router<AppState> {
    #[cfg(not(feature = "mail"))]
    let _ = config;

    // Framework-provided routes
    #[cfg(feature = "htmx")]
    {
        // When htmx is vendored via `autumn assets add htmx@…`, skip the
        // built-in handler so ServeDir serves the correctly-pinned file.
        // Axum explicit routes beat `nest_service`, so without this guard the
        // embedded 2.0.4 bytes would shadow any updated vendored version.
        if crate::assets::htmx_is_vendored() {
            tracing::debug!(
                path = crate::htmx::HTMX_JS_PATH,
                "htmx vendored via `autumn assets`; built-in handler skipped, ServeDir serves it"
            );
        } else {
            router = router.route(crate::htmx::HTMX_JS_PATH, axum::routing::get(htmx_handler));
            tracing::debug!(
                method = "GET",
                path = crate::htmx::HTMX_JS_PATH,
                name = format!("htmx {}", crate::htmx::HTMX_VERSION),
                "Mounted route"
            );
        }
        router = router.route(
            crate::htmx::HTMX_CSRF_JS_PATH,
            axum::routing::get(htmx_csrf_handler),
        );
        router = router.route(
            crate::htmx::AUTUMN_WIDGETS_JS_PATH,
            axum::routing::get(autumn_widgets_handler),
        );
        router = router.route(
            crate::htmx::IDIOMORPH_JS_PATH,
            axum::routing::get(idiomorph_handler),
        );
        router = router.route(
            crate::htmx::HTMX_SSE_JS_PATH,
            axum::routing::get(htmx_sse_handler),
        );
        tracing::debug!(
            method = "GET",
            path = crate::htmx::HTMX_CSRF_JS_PATH,
            name = "htmx csrf helper",
            "Mounted route"
        );
        tracing::debug!(
            method = "GET",
            path = crate::htmx::AUTUMN_WIDGETS_JS_PATH,
            name = "autumn widget runtime",
            "Mounted route"
        );
        tracing::debug!(
            method = "GET",
            path = crate::htmx::IDIOMORPH_JS_PATH,
            name = "idiomorph DOM morphing",
            "Mounted route"
        );
        tracing::debug!(
            method = "GET",
            path = crate::htmx::HTMX_SSE_JS_PATH,
            name = "htmx SSE extension",
            "Mounted route"
        );
    }

    // Framework-provided flash-message stylesheet. Served as a same-origin
    // asset (rather than inline styles) so the `.flash` classes emitted by
    // `Flash::render` stay compatible with a strict `style-src 'self'` CSP.
    #[cfg(feature = "flash")]
    {
        router = router.route(
            crate::flash::FLASH_CSS_PATH,
            axum::routing::get(flash_css_handler),
        );
        tracing::debug!(
            method = "GET",
            path = crate::flash::FLASH_CSS_PATH,
            name = "autumn flash stylesheet",
            "Mounted route"
        );
    }

    // Framework-provided widget stylesheet (#1215). Backs every `autumn-*`
    // class emitted by form/widgets/wizard/pagination/storage/job-tracking so
    // widgets render styled without an app-authored copy — Tailwind or not.
    #[cfg(feature = "maud")]
    {
        router = router.route(
            crate::ui::WIDGETS_CSS_PATH,
            axum::routing::get(widgets_css_handler),
        );
        tracing::debug!(
            method = "GET",
            path = crate::ui::WIDGETS_CSS_PATH,
            name = "autumn widget stylesheet",
            "Mounted route"
        );
    }

    if dev_reload_enabled {
        router = router.route(
            dev::LIVE_RELOAD_PATH,
            axum::routing::get(dev::live_reload_state_handler),
        );
        router = router.route(
            dev::LIVE_RELOAD_SCRIPT_PATH,
            axum::routing::get(dev::live_reload_script_handler),
        );
        tracing::debug!(
            state_path = dev::LIVE_RELOAD_PATH,
            script_path = dev::LIVE_RELOAD_SCRIPT_PATH,
            "Mounted dev live reload endpoints"
        );
    }

    #[cfg(feature = "mail")]
    if config
        .mail
        .preview_routes_enabled(config.profile.as_deref())
    {
        router = router.merge(crate::mail::mail_preview_router(
            config.mail.file_dir.clone(),
        ));
        tracing::debug!(
            path = crate::mail::MAIL_PREVIEW_PATH,
            "Mounted dev mail preview endpoints"
        );
    }

    // Widget story gallery (#1526) — off by default, opt-in in ANY profile
    // via `[stories] enabled = true` (profile-layered). Handlers read the
    // StoryRegistry from the AppState extension installed by
    // `AppBuilder::with_story_gallery`.
    #[cfg(feature = "maud")]
    if config.stories.enabled {
        router = router.merge(crate::stories::story_router());
        tracing::debug!(
            path = crate::stories::STORIES_PATH,
            "Mounted story gallery endpoints"
        );
    }

    // RFC 8058 one-click unsubscribe endpoint — opt-in via
    // `mail.mount_unsubscribe_endpoint` / `AppBuilder::mount_unsubscribe_endpoint`
    // so JSON-only apps never get an HTML endpoint they didn't request.
    #[cfg(feature = "mail")]
    if config.mail.should_mount_unsubscribe_endpoint() {
        router = router.merge(crate::mail::unsubscribe_router());
        tracing::debug!(
            path = crate::mail::UNSUBSCRIBE_PATH,
            "Mounted default unsubscribe endpoint"
        );
    }

    // Tracked-job status endpoint (enqueue_tracked / #[job] JobContext) — on
    // by default; opt out via `jobs.tracking.route_enabled = false`.
    if config.jobs.tracking.route_enabled {
        router = router.merge(crate::job_tracking::status_router());
        tracing::debug!(
            path = crate::job_tracking::JOB_STATUS_ROUTE_PATH,
            "Mounted tracked-job status endpoint"
        );
    }

    router
}

fn mount_probe_endpoints<S>(
    mut router: axum::Router<S>,
    config: &AutumnConfig,
    user_get_paths: &std::collections::HashSet<String>,
) -> (std::collections::HashSet<String>, axum::Router<S>)
where
    S: Clone + Send + Sync + 'static,
    AppState: axum::extract::FromRef<S>,
{
    // Probe endpoints (auto-mounted). Each probe is a `GET`; when a user route
    // already owns that exact path, yield to the user handler instead of
    // handing axum a second `GET` for the same path — which panics at startup
    // with a raw "Overlapping method route" message that names none of the
    // user's code (issue #1971). A user who hand-writes `GET /health` clearly
    // wants their handler, so the built-in steps aside and logs the override.
    let mut mounted_probe_paths = std::collections::HashSet::new();

    let mut mount_probe = |mut router: axum::Router<S>,

                           path: &str,
                           label: &'static str,
                           handler: axum::routing::MethodRouter<S>|

     -> axum::Router<S> {
        if user_get_paths.contains(path) {
            tracing::info!(
                probe = label,
                path,
                "a user route already owns this path; the built-in probe was \
                 not auto-mounted (the user handler wins)"
            );
            // Still record the ceded path: `mount_actuator_endpoints` keys its
            // overlap guard off this set, and a configured probe path stays a
            // collision hazard for the actuator even when a user route (not the
            // built-in probe) owns it. Dropping it here would let an actuator at
            // prefix "/" merge its own `GET /health` onto the user's `GET
            // /health` and axum would panic during construction instead of
            // returning a checked `FrameworkRouteOverlap` (issue #1971 P2).
            mounted_probe_paths.insert(path.to_owned());
            return router;
        }
        if mounted_probe_paths.insert(path.to_owned()) {
            router = router.route(path, handler);
        }
        router
    };

    router = mount_probe(
        router,
        &config.health.live_path,
        "liveness",
        axum::routing::get(crate::probe::live_handler::<AppState>),
    );
    router = mount_probe(
        router,
        &config.health.ready_path,
        "readiness",
        axum::routing::get(crate::probe::ready_handler::<AppState>),
    );
    router = mount_probe(
        router,
        &config.health.startup_path,
        "startup",
        axum::routing::get(crate::probe::startup_handler::<AppState>),
    );
    router = mount_probe(
        router,
        &config.health.path,
        "health",
        axum::routing::get(crate::health::handler::<AppState>),
    );
    tracing::debug!(
        health = %config.health.path,
        live = %config.health.live_path,
        ready = %config.health.ready_path,
        startup = %config.health.startup_path,
        "Mounted probe endpoints"
    );

    (mounted_probe_paths, router)
}

fn mount_actuator_endpoints(
    mut router: axum::Router<AppState>,
    config: &AutumnConfig,
    mounted_probe_paths: &std::collections::HashSet<String>,
) -> Result<axum::Router<AppState>, RouterBuildError> {
    // Actuator endpoints
    let actuator_sensitive = config.actuator.sensitive;
    let actuator_prometheus = config.actuator.prometheus;
    let actuator_paths = crate::actuator::actuator_endpoint_paths(
        &config.actuator.prefix,
        actuator_sensitive,
        actuator_prometheus,
    );
    if let Some(path) = actuator_paths
        .iter()
        .find(|path| mounted_probe_paths.contains(path.as_str()))
    {
        return Err(RouterBuildError::FrameworkRouteOverlap {
            path: path.clone(),
            existing: "probe endpoint",
            incoming: "actuator endpoint",
        });
    }
    router = router.merge(crate::actuator::actuator_router_with_prefix(
        &config.actuator.prefix,
        actuator_sensitive,
        actuator_prometheus,
    ));
    tracing::debug!(
        sensitive = actuator_sensitive,
        prometheus = actuator_prometheus,
        prefix = %config.actuator.prefix,
        "Mounted actuator endpoints"
    );
    Ok(router)
}

fn mount_scoped_groups(
    mut router: axum::Router<AppState>,
    scoped_groups: Vec<ScopedGroup>,
    idempotency_layers: Option<&BuiltIdempotencyLayers>,
    state: &AppState,
) -> axum::Router<AppState> {
    // Mount scoped route groups (each with its own middleware layer).
    for group in scoped_groups {
        let mut sub_router = axum::Router::new();
        for route in group.routes {
            tracing::debug!(
                method = %route.method,
                path = route.path,
                name = route.name,
                scope = %group.prefix,
                "Mounted scoped route"
            );
            // Scoped groups are wrapped by an opaque user-provided layer after
            // the route handlers are built. The idempotency storage key cannot
            // know whether that layer authorizes, audits, or resolves tenant
            // state from non-whitelisted headers/extensions, so cached hits
            // fail closed instead of replaying through a generated stop inside
            // the scoped route.
            let selected_layer = idempotency_layers.map(|layers| &layers.manual);
            let mut handler = route.handler;
            if let Some(layer) = selected_layer {
                handler = handler.layer(layer.clone());
            }
            if let Some(version) = route.api_version {
                handler = handler.layer(axum::middleware::from_fn_with_state(
                    state.clone(),
                    api_versioning_middleware,
                ));
                handler = handler.layer(axum::Extension(RouteVersionMetadata {
                    version: version.to_string(),
                    sunset_opt_out: route.sunset_opt_out,
                    secured: route.api_doc.secured,
                    required_roles: route.api_doc.required_roles,
                    has_policy: route.api_doc.has_policy,
                }));
            }
            sub_router = sub_router.route(route.path, handler);
        }
        sub_router = (group.apply_layer)(sub_router);
        router = router.nest(&group.prefix, sub_router);
    }
    router
}

fn mount_raw_routers(
    mut router: axum::Router<AppState>,
    merge_routers: Vec<axum::Router<AppState>>,
    nest_routers: Vec<(String, axum::Router<AppState>)>,
    idempotency_layers: Option<&BuiltIdempotencyLayers>,
) -> axum::Router<AppState> {
    // Merge user-supplied raw Axum routers (escape hatch).
    // Merged after annotated routes so annotated routes take precedence.
    for raw_router in merge_routers {
        tracing::debug!("Merged raw Axum router");
        let raw_router = if let Some(layers) = idempotency_layers {
            raw_router.layer(layers.manual.clone())
        } else {
            raw_router
        };
        router = router.merge(raw_router);
    }

    // Nest user-supplied raw Axum routers under path prefixes.
    for (prefix, raw_router) in nest_routers {
        tracing::debug!(prefix = %prefix, "Nested raw Axum router");
        // We explicitly apply the fallback to the nested router before nesting,
        // so that unmatched routes within this prefix are protected by global middleware.
        let nested_router =
            raw_router.fallback(crate::middleware::error_page_filter::fallback_404_handler);
        let nested_router = if let Some(layers) = idempotency_layers {
            nested_router.layer(layers.manual.clone())
        } else {
            nested_router
        };
        router = router.nest(&prefix, nested_router);
    }
    router
}

fn apply_compression_middleware<S>(
    mut router: axum::Router<S>,
    config: &AutumnConfig,
) -> axum::Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    if config.compression.enabled {
        use tower_http::compression::predicate::{DefaultPredicate, NotForContentType, Predicate};
        // Extend the default predicate (skips images, gRPC, SSE, small bodies) to also
        // skip binary media and already-compressed formats — compressing these wastes
        // CPU, increases transfer size for archives, and can confuse media players.
        let predicate = DefaultPredicate::new()
            // Binary media — already-encoded by codec, not compressible by gzip/br.
            .and(NotForContentType::const_new("audio/"))
            .and(NotForContentType::const_new("video/"))
            .and(NotForContentType::const_new("application/octet-stream"))
            // Compressed archive formats — re-compressing wastes CPU.
            .and(NotForContentType::const_new("application/zip"))
            .and(NotForContentType::const_new("application/gzip"))
            .and(NotForContentType::const_new("application/x-gzip"))
            .and(NotForContentType::const_new("application/zstd"))
            .and(NotForContentType::const_new("application/x-bzip2"))
            .and(NotForContentType::const_new("application/x-bzip"))
            .and(NotForContentType::const_new("application/x-rar-compressed"))
            .and(NotForContentType::const_new("application/vnd.rar"))
            .and(NotForContentType::const_new("application/x-7z-compressed"))
            // Pre-compressed web fonts — WOFF/WOFF2 embed their own compression,
            // so gzip/br only wastes CPU and can inflate them. Raw fonts
            // (`font/ttf`, `font/otf`) are NOT excluded: they are uncompressed
            // SFNT data that genuinely benefits from transfer compression.
            .and(NotForContentType::const_new("font/woff"))
            .and(NotForContentType::const_new("font/woff2"));
        router =
            router.layer(tower_http::compression::CompressionLayer::new().compress_when(predicate));
        tracing::info!("Response compression enabled (gzip/brotli)");
    }
    router
}

fn apply_cors_middleware<S>(mut router: axum::Router<S>, config: &AutumnConfig) -> axum::Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    // CORS middleware (only applied when allowed_origins is non-empty)
    if !config.cors.allowed_origins.is_empty() {
        let cors = build_cors_layer(&config.cors);
        tracing::info!(
            origins = ?config.cors.allowed_origins,
            credentials = config.cors.allow_credentials,
            "CORS enabled"
        );
        router = router.layer(cors);
    }
    router
}

fn apply_csrf_middleware<S>(
    mut router: axum::Router<S>,
    config: &AutumnConfig,
    signing_keys: Option<std::sync::Arc<crate::security::config::ResolvedSigningKeys>>,
) -> axum::Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    // CSRF middleware (only applied when enabled)
    if config.security.csrf.enabled {
        // The CSRF token scan reads only a bounded prefix of the body
        // (`security.csrf.token_scan_bytes`, 2 MiB default) and streams the
        // remainder through, so the cap comes from CSRF config — NOT from
        // `upload.max_request_size_bytes` (which would force whole uploads into
        // memory and defeat the streaming upload path).
        //
        // Clamp the effective prefix to the global body limit: the CSRF layer
        // must never buffer more than `upload.max_request_size_bytes`. In the
        // normal/high-upload case the small `token_scan_bytes` prefix wins (the
        // `min` keeps it at 2 MiB — it is *not* raised to the upload limit).
        // Only when an operator deliberately lowers the global limit *below* the
        // prefix cap does the upload limit clamp the scan down — the whole body
        // is ≤ that limit anyway, so an early `_csrf` token is still in range,
        // and anything larger is rejected downstream by `DefaultBodyLimit`.
        let effective_scan_bytes = config
            .security
            .csrf
            .token_scan_bytes
            .min(config.security.upload.max_request_size_bytes);
        let mut csrf_layer = crate::security::CsrfLayer::from_config(&config.security.csrf)
            .with_max_scan_bytes(effective_scan_bytes);
        if let Some(keys) = signing_keys {
            csrf_layer = csrf_layer.with_signing_keys(keys);
        }
        for endpoint in &config.security.webhooks.endpoints {
            csrf_layer = csrf_layer.with_exempt_path(&endpoint.path);
        }
        // RFC 8058 one-click unsubscribe POSTs arrive from mailbox providers
        // with no Autumn CSRF cookie/header; exempt the endpoint only when the
        // framework owns it (opt-in), so a custom override keeps its own CSRF.
        #[cfg(feature = "mail")]
        if config.mail.should_mount_unsubscribe_endpoint() {
            csrf_layer = csrf_layer.with_exempt_path(crate::mail::UNSUBSCRIBE_PATH);
        }
        tracing::info!("CSRF protection enabled");
        router = router.layer(csrf_layer);
    }
    router
}

/// Apply the one-time submit-token guard (issue #1360).
///
/// Enabled by default. The layer is applied *inner* to the CSRF layer (it is
/// registered before `apply_csrf_middleware`, so on the request path CSRF is
/// validated first): a request bearing a valid `_csrf` but an already-consumed
/// `_submit_token` is still short-circuited by this guard. The store backend
/// mirrors [`build_idempotency_layers`]; the `redis` backend reuses the
/// `[idempotency.redis]` connection settings.
fn apply_submit_token_middleware<S>(
    mut router: axum::Router<S>,
    config: &AutumnConfig,
    is_production: bool,
) -> Result<axum::Router<S>, RouterBuildError>
where
    S: Clone + Send + Sync + 'static,
{
    let cfg = &config.security.submit_token;
    if !cfg.enabled {
        return Ok(router);
    }

    // Production guard for the resolved consumed-token backend. Submit tokens
    // are DEFAULT-ON, so the resolved backend can land on the per-process memory
    // store in production — which cannot deduplicate submits across replicas.
    // Mirrors the idempotency production-memory guard
    // (`fail_fast_on_invalid_idempotency_config`): an EXPLICIT
    // `[security.submit_token].backend = "memory"` in prod fails fast, while an
    // INHERITED default only warns so upgrading Autumn never becomes
    // "prod won't boot without Redis".
    match cfg.production_memory_guard(config.idempotency.backend, is_production) {
        crate::security::config::SubmitTokenMemoryGuard::Ok => {}
        crate::security::config::SubmitTokenMemoryGuard::WarnInherited => {
            tracing::warn!(
                "[security.submit_token].backend resolved to the in-memory store in production \
                 (inherited from [idempotency].backend, which is unset or memory). \
                 Single-replica deployments are fine, but multi-replica deployments need a shared \
                 backend: configure [idempotency] with backend = \"redis\" (or set \
                 [security.submit_token].backend = \"redis\") so consumed tokens are shared across \
                 replicas — otherwise a duplicate submit can slip through on a different replica."
            );
        }
        crate::security::config::SubmitTokenMemoryGuard::FailExplicit => {
            return Err(RouterBuildError::InvalidSubmitTokenBackend(
                "the in-memory submit-token backend is not safe for multi-replica production use. \
                 Set `[security.submit_token].backend = \"redis\"` in autumn.toml (it reuses the \
                 [idempotency.redis] connection settings), or remove the explicit `backend` \
                 override to inherit `[idempotency].backend`."
                    .to_owned(),
            ));
        }
    }

    let ttl = Duration::from_secs(cfg.ttl_secs);
    // Backend selection: an explicit `[security.submit_token].backend` wins;
    // otherwise inherit `[idempotency].backend` so a Redis-configured app shares
    // one consumed-token store across replicas by default (issue #1360), while a
    // dev app on the default memory idempotency backend keeps memory tokens.
    // `resolved_backend` is the single source of truth so this cannot drift from
    // `build_idempotency_layers`.
    let backend = cfg.resolved_backend(config.idempotency.backend);
    let store: std::sync::Arc<dyn IdempotencyStore> = match backend {
        crate::config::IdempotencyBackend::Memory => {
            std::sync::Arc::new(MemoryIdempotencyStore::new(ttl))
        }
        #[cfg(feature = "redis")]
        crate::config::IdempotencyBackend::Redis => {
            match crate::idempotency::RedisIdempotencyStore::from_config(&config.idempotency) {
                Ok(s) => std::sync::Arc::new(s),
                Err(e) => return Err(RouterBuildError::InvalidIdempotencyBackend(e)),
            }
        }
        #[cfg(not(feature = "redis"))]
        crate::config::IdempotencyBackend::Redis => {
            return Err(RouterBuildError::InvalidIdempotencyBackend(
                "submit_token backend 'redis' requires the autumn-web 'redis' feature \
                 flag; rebuild with --features redis or switch to backend = \"memory\""
                    .to_owned(),
            ));
        }
    };

    let mut layer = crate::security::SubmitTokenLayer::new(store, cfg)
        .with_max_scan_bytes(config.security.upload.max_request_size_bytes);
    for endpoint in &config.security.webhooks.endpoints {
        layer = layer.with_exempt_path(&endpoint.path);
    }
    #[cfg(feature = "mail")]
    if config.mail.should_mount_unsubscribe_endpoint() {
        layer = layer.with_exempt_path(crate::mail::UNSUBSCRIBE_PATH);
    }
    tracing::info!(
        backend = ?backend,
        inherited = cfg.backend.is_none(),
        ttl_secs = cfg.ttl_secs,
        "One-time submit-token protection enabled"
    );
    router = router.layer(layer);
    Ok(router)
}

fn apply_bot_protection_middleware<S>(
    mut router: axum::Router<S>,
    config: &AutumnConfig,
) -> axum::Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    if config.bot_protection.enabled {
        // Use the dedicated captcha_exempt_paths list — NOT csrf.exempt_paths —
        // so that a route exempt from CSRF for non-cookie auth reasons does not
        // automatically bypass bot-protection as well.
        let mut exempt = config.security.captcha_exempt_paths.clone();
        for endpoint in &config.security.webhooks.endpoints {
            exempt.push(endpoint.path.clone());
        }
        // One-click unsubscribe POSTs carry no CAPTCHA token; exempt the
        // framework-owned endpoint when mounted.
        #[cfg(feature = "mail")]
        if config.mail.should_mount_unsubscribe_endpoint() {
            exempt.push(crate::mail::UNSUBSCRIBE_PATH.to_owned());
        }
        let layer =
            crate::security::captcha::BotProtectionLayer::from_config(&config.bot_protection)
                .with_max_scan_bytes(config.security.upload.max_request_size_bytes)
                .with_exempt_paths(exempt);
        tracing::info!(
            provider = ?config.bot_protection.provider,
            dev_bypass = config.bot_protection.dev_bypass,
            "Bot protection (CAPTCHA) enabled"
        );
        router = router.layer(layer);
    }
    router
}

async fn populate_rate_limit_principal(
    axum::extract::State(state): axum::extract::State<AppState>,
    mut req: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    // Populate RateLimitPrincipal from the *verified* session identity only.
    //
    // We deliberately do NOT fall back to a raw Authorization header here: this
    // shim runs as a global layer outer to route-scoped auth (RequireApiToken),
    // so any bearer token visible at this point is still unverified and fully
    // attacker-controlled. Keying the limiter on it would let a caller rotate
    // the token to mint unlimited buckets (defeating the per-IP fallback) or
    // forge another user's principal to exhaust their bucket. When no verified
    // principal is available, the limiter's extract_key falls back to IP keying,
    // which is the correct safe default. API-token routes that want
    // per-principal limiting should place a RateLimitLayer inner to
    // RequireApiToken, which sets the verified principal ID (see
    // RequireApiTokenService::call).
    if let Some(session) = req.extensions().get::<crate::session::Session>() {
        let auth_session_key = state.auth_session_key();
        if let Some(user_id) = session.get(auth_session_key).await {
            req.extensions_mut()
                .insert(crate::security::RateLimitPrincipal(user_id));
        }
    }
    next.run(req).await
}

fn apply_trusted_proxies_middleware<S>(
    router: axum::Router<S>,
    config: &AutumnConfig,
) -> axum::Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    let tp = &config.security.trusted_proxies;
    let layer = crate::security::TrustedProxiesLayer::from_config(tp);
    if tp.trust_forwarded_headers || !tp.ranges.is_empty() || tp.trusted_hops.is_some() {
        tracing::info!(
            ranges = ?tp.ranges,
            trusted_hops = ?tp.trusted_hops,
            "Centralized trusted-proxy resolution enabled"
        );
    }
    router.layer(layer)
}

fn apply_rate_limit_middleware(
    mut router: axum::Router<AppState>,
    config: &AutumnConfig,
    state: &AppState,
) -> axum::Router<AppState> {
    if config.security.rate_limit.enabled {
        let tp = &config.security.trusted_proxies;
        let rl = &config.security.rate_limit;
        let has_top_level_proxy_config =
            tp.trust_forwarded_headers || !tp.ranges.is_empty() || tp.trusted_hops.is_some();
        // Preserve explicit rate-limit proxy config (legacy fields). The shared
        // top-level resolver is only injected when the rate-limit section carries
        // no proxy config of its own, preventing dev defaults from silently
        // overriding an operator's explicit security.rate_limit.trusted_proxies.
        let has_rate_limit_proxy_config =
            rl.trust_forwarded_headers || !rl.trusted_proxies.is_empty();
        // The framework default limiter shares its bucket with the MCP `/mcp`
        // envelope limiter (both built here), so it honors `RateLimitEnvelopeCounted`
        // to avoid double-counting an already-charged `tools/call`. User-installed
        // limiters don't, so MCP replays still consume their per-route buckets.
        let mut layer = crate::security::RateLimitLayer::from_config(rl).honoring_mcp_exempt();
        if has_top_level_proxy_config && !has_rate_limit_proxy_config {
            let resolver = crate::security::ProxyResolver::from_config(tp);
            layer = layer.with_proxy_resolver(resolver);
        }
        tracing::info!(
            rps = config.security.rate_limit.requests_per_second,
            burst = config.security.rate_limit.burst,
            "Rate limiting enabled"
        );
        router = router.layer(layer);

        if config.security.rate_limit.key_strategy
            == crate::security::KeyStrategy::AuthenticatedPrincipal
        {
            router = router.layer(axum::middleware::from_fn_with_state(
                state.clone(),
                populate_rate_limit_principal,
            ));
        }
    }
    router
}

fn apply_upload_middleware<S>(router: axum::Router<S>, config: &AutumnConfig) -> axum::Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    let upload_config = config.security.upload.clone();
    let max_request_size = upload_config.max_request_size_bytes;
    tracing::info!(
        max_request_size_bytes = max_request_size,
        max_file_size_bytes = upload_config.max_file_size_bytes,
        allowed_mime_types = ?upload_config.allowed_mime_types,
        "Request body size limits enabled (applies to all content types)"
    );

    // Apply a global body-size cap covering JSON, form, raw bytes, and multipart.
    // The Multipart extractor further refines this per the UploadConfig extension.
    let router = router.layer(axum::extract::DefaultBodyLimit::max(max_request_size));

    // Insert UploadConfig into extensions so the Multipart extractor can read
    // per-file limits and the allowed MIME-type list.
    router.layer(axum::middleware::from_fn(
        move |mut req: axum::extract::Request, next: axum::middleware::Next| {
            let upload_config = upload_config.clone();
            async move {
                req.extensions_mut().insert(upload_config);
                next.run(req).await
            }
        },
    ))
}

/// Exact-match health/probe paths that must always bypass admission-style
/// gates (maintenance mode, the startup barrier, load shedding): the
/// compat health endpoint plus the `/live`, `/ready`, `/startup` lifecycle
/// probes and the actuator's own `/health` alias. Callers additionally
/// exempt the whole actuator prefix (`with_health_prefix`), since these
/// gates are keyed on exact paths, not prefixes.
fn probe_bypass_paths(config: &AutumnConfig) -> Vec<String> {
    vec![
        config.health.path.clone(),
        config.health.live_path.clone(),
        config.health.ready_path.clone(),
        config.health.startup_path.clone(),
        crate::actuator::actuator_route_path(&config.actuator.prefix, "/health"),
    ]
}

/// Build the [`MaintenanceLayer`](crate::middleware::maintenance::MaintenanceLayer)
/// from config + state, with the health/probe paths that always bypass the gate.
///
/// Shared by [`apply_middleware`] (direct routes) and the late-mounted `/mcp`
/// envelope so both return the documented `503` identically when maintenance
/// mode is active — the `/mcp` router is merged after `apply_middleware`, so
/// without an explicit layer its `initialize`/`tools/list` would keep serving
/// the catalog during maintenance.
fn build_maintenance_layer(
    config: &AutumnConfig,
    state: &AppState,
) -> crate::middleware::maintenance::MaintenanceLayer {
    let maintenance_state = state
        .extension::<crate::maintenance::MaintenanceState>()
        .map(|s| (*s).clone())
        .unwrap_or_default();
    crate::middleware::maintenance::MaintenanceLayer::new(maintenance_state)
        .with_health_prefix(config.actuator.prefix.clone())
        .with_probe_paths(probe_bypass_paths(config))
}

/// Build the admission-control ([`LoadShedLayer`](crate::middleware::LoadShedLayer))
/// layer from config, or `None` when `server.max_concurrent_requests` is unset
/// or `0` — the default, preserving today's unlimited behavior with zero
/// overhead (the layer is simply never applied; see [`apply_middleware`]).
///
/// Reuses the same probe/actuator bypass list as [`build_maintenance_layer`]
/// so health/liveness/readiness probes are never shed under load (#1006).
fn build_load_shed_layer(
    config: &AutumnConfig,
    state: &AppState,
) -> Option<crate::middleware::LoadShedLayer> {
    let limit = config.server.max_concurrent_requests.filter(|&n| n > 0)?;
    // Mirror CORS headers onto a shed 503 the same way the timeout middleware
    // does for the main stack (`mirror_cors = true` there): this layer sits
    // outside `CorsLayer` on direct routes, so without mirroring a
    // cross-origin browser client sees an opaque CORS failure instead of a
    // readable 503. Harmless (but redundant) at the `/mcp` mount point, since
    // that shares this same layer instance yet sits *inside* its own
    // `CorsLayer`, which overwrites these headers with its own regardless.
    let cors =
        (!config.cors.allowed_origins.is_empty()).then(|| std::sync::Arc::new(config.cors.clone()));
    Some(
        crate::middleware::LoadShedLayer::new(limit, state.metrics.clone())
            .with_health_prefix(config.actuator.prefix.clone())
            .with_probe_paths(probe_bypass_paths(config))
            .with_cors(cors),
    )
}

/// Per-route timeout lookup table, keyed by the fully-qualified route template
/// (matching [`axum::extract::MatchedPath`]) and then by HTTP method, so an
/// override on one handler never bleeds onto sibling methods sharing the path
/// (e.g. `GET /items` vs `POST /items`). The nested layout also lets the
/// middleware resolve the deadline from a borrowed `&str` + `&Method`, avoiding
/// any allocation on exempt/disabled routes. Built once at router-assembly time
/// from each [`Route`]'s `timeout` field and shared (cheaply cloned) into the
/// global timeout middleware.
type RouteTimeoutTable = std::sync::Arc<
    std::collections::HashMap<
        String,
        std::collections::HashMap<http::Method, crate::route::RouteTimeout>,
    >,
>;

/// Error surfaced as the cause of the `503` when an inbound request exceeds its
/// wall-clock deadline. Carried into [`crate::error::AutumnError::service_unavailable`]
/// so the response flows through the standard Problem Details / error-page stack
/// (JSON for API clients, HTML for browsers) instead of a raw tower `BoxError`.
#[derive(Debug)]
struct RequestDeadlineExceeded {
    timeout_ms: u64,
}

impl std::fmt::Display for RequestDeadlineExceeded {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "the server did not produce a response within the configured {}ms deadline",
            self.timeout_ms
        )
    }
}

impl std::error::Error for RequestDeadlineExceeded {}

/// Response-extension marker stamped on the `503` produced when the inbound
/// request-timeout deadline cancels the handler future.
///
/// The session layer is applied *outer* to the timeout layer, so when the
/// deadline fires it observes the (still-shared) `Session` handle as dirty even
/// though the handler was cancelled mid-flight. Persisting that partial mutation
/// would commit half-finished state — e.g. a login that set the user id but
/// never finished — so `SessionService` checks for this marker and skips the
/// dirty save/destroy when it is present. Only the timeout handler sets it, so
/// ordinary handler-produced `503`s still persist session changes as before.
#[derive(Clone, Copy, Debug)]
pub struct RequestDeadlineCancelled;

/// Build the per-route timeout override table from the top-level routes and any
/// scoped (prefixed) groups. Group routes are keyed by their nested template so
/// the runtime lookup matches [`axum::extract::MatchedPath`].
fn build_route_timeout_table(
    route_list: &[Route],
    scoped_groups: &[ScopedGroup],
) -> RouteTimeoutTable {
    let mut table: std::collections::HashMap<
        String,
        std::collections::HashMap<http::Method, crate::route::RouteTimeout>,
    > = std::collections::HashMap::new();
    let mut insert = |path: String, method: &http::Method, timeout: crate::route::RouteTimeout| {
        // `Inherit` carries no override, so it never needs a table entry.
        if matches!(timeout, crate::route::RouteTimeout::Inherit) {
            return;
        }
        // Key by (path, *effective request method*) so an override on one handler
        // never bleeds onto sibling methods that share the template, while still
        // resolving when the request reaches the handler through a method alias.
        // `request_timeout_handler` looks up `req.method()`, which differs from
        // the declared method in two cases:
        //   - axum serves `HEAD` through a `#[get]` handler, so a GET override
        //     must also cover HEAD.
        //   - `#[ws]` records the synthetic `WS` method but mounts a `GET`
        //     handler, so the upgrade (and its auth work) arrives as GET.
        // Each (effective method, path) pair is still unique across the router, so
        // `insert` cannot lose a competing entry.
        let by_method = table.entry(path).or_default();
        // Key under the same effective verb the router mounts the handler as, so
        // a `#[ws]` override lands on the GET the upgrade actually arrives as
        // (shared with the duplicate-route preflight via `effective_mount_method`
        // so the two mappings can never drift).
        by_method.insert(effective_mount_method(method), timeout);
        // A real `#[get]` is also served for HEAD in axum; a WS upgrade is not,
        // so only expand HEAD for a genuine GET (not the WS→GET alias).
        if *method == http::Method::GET {
            by_method.insert(http::Method::HEAD, timeout);
        }
    };
    for route in route_list {
        insert(route.path.to_owned(), &route.method, route.timeout);
    }
    for group in scoped_groups {
        for route in &group.routes {
            insert(
                join_nested_path(&group.prefix, route.path),
                &route.method,
                route.timeout,
            );
        }
    }
    std::sync::Arc::new(table)
}

/// Apply the built-in inbound request timeout.
///
/// A single global layer enforces `config.server.timeouts.request_timeout_ms`
/// (the `prod` profile smart-defaults this to 30s) as a per-request wall-clock
/// deadline, with per-route overrides resolved from `route_timeouts` via the
/// matched route template. On expiry the handler returns a framework-standard
/// `503 Service Unavailable` (Problem Details JSON for API clients, the error
/// page for browsers — never a raw tower `BoxError`).
///
/// Streaming responses are exempt by construction: the deadline bounds the time
/// to produce the response head, not the duration of body streaming, so SSE and
/// chunked responses are never interrupted once the head is sent. Long-poll
/// handlers, which block *before* returning the head, are bound by the deadline
/// and must opt out via `timeout = "off"`. WebSocket routes inherit the deadline
/// ([`RouteTimeout::Inherit`](crate::route::RouteTimeout), emitted by `#[ws]`),
/// so it bounds a hung pre-upgrade handshake but never the established socket —
/// that future runs on a separate task via `on_upgrade` and is unbounded by
/// design.
///
/// The layer is a no-op (zero overhead) when the global timeout is disabled and
/// no route declares an `Override`.
///
/// `mirror_cors` makes a synthesized 503 carry the CORS response headers a
/// normal response would. Set it for the main ingress stack, where this layer
/// sits *outside* `CorsLayer` (see the order in `apply_middleware`) so the 503
/// never flows back through it; leave it off for the `/mcp` envelope, whose
/// timeout is applied *inner* to its `CorsLayer` and whose 503 is therefore
/// already CORS-readable.
fn apply_request_timeout_middleware(
    router: axum::Router<AppState>,
    config: &AutumnConfig,
    metrics: crate::middleware::MetricsCollector,
    route_timeouts: RouteTimeoutTable,
    mirror_cors: bool,
) -> axum::Router<AppState> {
    let global = config
        .server
        .timeouts
        .request_timeout_ms
        .filter(|ms| *ms > 0)
        .map(std::time::Duration::from_millis);
    let has_override = route_timeouts
        .values()
        .flat_map(std::collections::HashMap::values)
        .any(|t| matches!(t, crate::route::RouteTimeout::Override(_)));
    if global.is_none() && !has_override {
        return router;
    }
    if let Some(duration) = global {
        tracing::info!(
            timeout_ms = u64::try_from(duration.as_millis()).unwrap_or(u64::MAX),
            "Inbound request timeout enabled"
        );
    }
    // Snapshot the CORS config once iff we must mirror it onto timeout 503s and
    // any origin is configured (otherwise `CorsLayer` itself is absent).
    let cors = (mirror_cors && !config.cors.allowed_origins.is_empty())
        .then(|| std::sync::Arc::new(config.cors.clone()));
    router.layer(axum::middleware::from_fn(move |req, next| {
        request_timeout_handler(
            req,
            next,
            global,
            route_timeouts.clone(),
            metrics.clone(),
            cors.clone(),
        )
    }))
}

async fn request_timeout_handler(
    req: axum::extract::Request,
    next: axum::middleware::Next,
    global: Option<std::time::Duration>,
    route_timeouts: RouteTimeoutTable,
    metrics: crate::middleware::MetricsCollector,
    cors: Option<std::sync::Arc<crate::config::CorsConfig>>,
) -> axum::response::Response {
    // Internal `autumn build` / ISR regeneration renders drive a `#[static_get]`
    // route directly via `oneshot` and tag the request with `RenderDeadlineExempt`
    // (there is no client connection whose deadline should apply). Skip the
    // deadline for these; live inbound requests to the same route do not carry
    // the marker and are bounded normally below.
    if req
        .extensions()
        .get::<crate::static_gen::RenderDeadlineExempt>()
        .is_some()
    {
        return next.run(req).await;
    }

    // Resolve the effective deadline from the matched route template + method,
    // using borrowed lookups so exempt/disabled routes allocate nothing.
    let matched_path_ref = req
        .extensions()
        .get::<axum::extract::MatchedPath>()
        .map(axum::extract::MatchedPath::as_str);
    let route_timeout = matched_path_ref
        .and_then(|p| route_timeouts.get(p))
        .and_then(|by_method| by_method.get(req.method()))
        .copied()
        .unwrap_or(crate::route::RouteTimeout::Inherit);
    let deadline = match route_timeout {
        crate::route::RouteTimeout::Disabled => None,
        crate::route::RouteTimeout::Override(d) => Some(d),
        crate::route::RouteTimeout::Inherit => global,
    };
    let Some(duration) = deadline else {
        // Exempt (disabled route, or global off with a non-Override route) —
        // no allocation on this hot path.
        return next.run(req).await;
    };

    // A deadline is active: now it's worth owning the path for the warn log.
    let matched_path = matched_path_ref.map(ToOwned::to_owned);
    let request_id = req
        .extensions()
        .get::<crate::middleware::RequestId>()
        .cloned();
    // Capture the request Origin before `req` is consumed so a timeout 503 can
    // mirror the CORS headers `CorsLayer` would have added (only when mirroring
    // is enabled — see `apply_request_timeout_middleware`).
    let cors_origin = cors
        .as_ref()
        .and_then(|_| req.headers().get(http::header::ORIGIN).cloned());
    let start = std::time::Instant::now();
    match tokio::time::timeout(duration, next.run(req)).await {
        Ok(response) => response,
        Err(_elapsed) => {
            let elapsed_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
            let route = matched_path.as_deref().unwrap_or("<unmatched>");
            // Structured telemetry: route template + elapsed time so operators
            // can alert on the (already-counted) timeout event.
            tracing::warn!(
                target: "autumn::timeout",
                route = route,
                elapsed_ms = elapsed_ms,
                timeout_ms = u64::try_from(duration.as_millis()).unwrap_or(u64::MAX),
                request_id = request_id.as_ref().map(ToString::to_string),
                "inbound request exceeded deadline"
            );
            metrics.record_request_timeout();
            // Return a 503 via the standard error type so the exception-filter
            // and error-page stack negotiate JSON vs HTML and enrich with the
            // request id — no manual Problem Details assembly, no raw BoxError.
            let mut response =
                crate::error::AutumnError::service_unavailable(RequestDeadlineExceeded {
                    timeout_ms: u64::try_from(duration.as_millis()).unwrap_or(u64::MAX),
                })
                .into_response();
            // Tag the 503 so the outer session layer skips persisting any partial
            // session mutation the cancelled handler made before the deadline.
            response.extensions_mut().insert(RequestDeadlineCancelled);
            // This layer is outside `CorsLayer` in the main stack, so the 503
            // never passes back through it; mirror the CORS headers ourselves so
            // cross-origin browser clients can read the Problem Details body
            // instead of seeing an opaque CORS failure.
            if let Some(cors) = cors.as_deref() {
                mirror_cors_headers(cors, cors_origin.as_ref(), &mut response);
            }
            response
        }
    }
}

struct BuiltIdempotencyLayers {
    route: crate::idempotency::IdempotencyLayer,
    manual: crate::idempotency::IdempotencyLayer,
}

fn build_idempotency_layers(
    config: &AutumnConfig,
    state: &AppState,
) -> Result<Option<BuiltIdempotencyLayers>, RouterBuildError> {
    if !config.idempotency.enabled.unwrap_or(false) {
        return Ok(None);
    }

    let ttl = Duration::from_secs(config.idempotency.ttl_secs);
    let in_flight_ttl = Duration::from_secs(config.idempotency.in_flight_ttl_secs);
    let store: std::sync::Arc<dyn IdempotencyStore> = match config.idempotency.backend {
        crate::config::IdempotencyBackend::Memory => {
            std::sync::Arc::new(MemoryIdempotencyStore::new(ttl))
        }
        #[cfg(feature = "redis")]
        crate::config::IdempotencyBackend::Redis => {
            match crate::idempotency::RedisIdempotencyStore::from_config(&config.idempotency) {
                Ok(s) => std::sync::Arc::new(s),
                Err(e) => return Err(RouterBuildError::InvalidIdempotencyBackend(e)),
            }
        }
        #[cfg(not(feature = "redis"))]
        crate::config::IdempotencyBackend::Redis => {
            return Err(RouterBuildError::InvalidIdempotencyBackend(
                "idempotency backend 'redis' requires the autumn-web 'redis' feature \
                 flag; rebuild with --features redis or switch to backend = \"memory\""
                    .to_owned(),
            ));
        }
    };

    tracing::debug!(
        backend = ?config.idempotency.backend,
        ttl_secs = config.idempotency.ttl_secs,
        in_flight_ttl_secs = config.idempotency.in_flight_ttl_secs,
        "Idempotency-key middleware enabled"
    );

    let base = IdempotencyLayer::new(store)
        .with_ttl(ttl)
        .with_in_flight_ttl(in_flight_ttl)
        .with_metrics(state.metrics.clone());

    Ok(Some(BuiltIdempotencyLayers {
        route: base.clone().replay_through_inner(),
        manual: base.fail_closed_on_replay(),
    }))
}

#[allow(
    clippy::cognitive_complexity,
    clippy::too_many_lines,
    clippy::too_many_arguments
)]
fn apply_middleware(
    mut router: axum::Router<AppState>,
    config: &AutumnConfig,
    state: &AppState,
    exception_filters: Vec<Arc<dyn ExceptionFilter>>,
    custom_layers: Vec<crate::app::CustomLayerRegistration>,
    #[cfg(feature = "maud")] error_page_renderer: Option<SharedRenderer>,
    session_store: Option<Arc<dyn crate::session::BoxedSessionStore>>,
    route_timeouts: RouteTimeoutTable,
    // Built once by the caller (`build_router_pre_state`) and cloned into the
    // late-mounted `/mcp` envelope too, so both ingress surfaces admit
    // against the SAME shared in-flight counter — constructing a second
    // `LoadShedLayer` here would give `/mcp` its own independent (always-zero)
    // counter that never sheds. See `build_load_shed_layer`.
    load_shed_layer: Option<crate::middleware::LoadShedLayer>,
) -> Result<axum::Router<AppState>, RouterBuildError> {
    // 404 fallback handler for unmatched routes must be registered BEFORE global middleware
    // so that unmatched routes are still protected by rate limiting, CSRF, CORS, etc.
    router = router.fallback(crate::middleware::error_page_filter::fallback_404_handler);

    // Resolve signing keys once; shared across session and CSRF layers.
    let is_production = matches!(config.profile.as_deref(), Some("prod" | "production"));
    let signing_keys = std::sync::Arc::new(crate::security::config::resolve_signing_keys(
        &config.security.signing_secret,
    ));
    // Only thread signing keys when a secret is configured (or in production where
    // fail_fast already ensures one is present). In dev without a configured secret
    // the ephemeral key is generated per-process — useful but not required.
    let signing_keys_opt: Option<std::sync::Arc<crate::security::config::ResolvedSigningKeys>> =
        if config.security.signing_secret.secret.is_some() || is_production {
            Some(signing_keys)
        } else {
            None
        };

    router = apply_cors_middleware(router, config);
    let trusted_host_policy = TrustedHostPolicy::from_config(config);
    router = router.layer(axum::middleware::from_fn(move |req, next| {
        trusted_host_middleware(req, next, trusted_host_policy.clone())
    }));
    // Applied before (i.e. inner to) the CSRF layer so CSRF is validated first
    // on the request path; a replayed `_submit_token` is still short-circuited
    // even when the request carries a valid `_csrf` (issue #1360, AC #4).
    router = apply_submit_token_middleware(router, config, is_production)?;
    router = apply_csrf_middleware(router, config, signing_keys_opt.clone());
    router = apply_bot_protection_middleware(router, config);
    // Method-override rejection filter. The outer `MethodOverrideLayer`
    // (applied at the `axum::serve` boundary so it can rewrite the
    // request method before route matching) stamps a
    // [`MethodOverrideRejection`] extension when the override field
    // value is invalid or the body was too large to scan; this inner
    // middleware converts that extension into the corresponding
    // `400`/`413` response. Running it here means the rejection flows
    // through the rest of the response stack (security headers,
    // request IDs, metrics, error-page filter) rather than bypassing
    // them. Placed outside CSRF so a `BodyTooLarge` (empty body)
    // doesn't get masked by a `403` from CSRF's missing-token branch,
    // and a clear `400 invalid _method` outranks "missing CSRF".
    router = router.layer(axum::middleware::from_fn(
        crate::middleware::method_override_rejection_filter,
    ));
    router = apply_rate_limit_middleware(router, config, state);

    // Register MaintenanceLayer automatically (shared construction with the
    // late-mounted `/mcp` envelope — see `build_maintenance_layer`).
    router = router.layer(build_maintenance_layer(config, state));

    // Admission control / load shedding (#1006). Outer to MaintenanceLayer so
    // the cheap in-flight-count check runs before maintenance mode's
    // bypass-header/IP-allowlist evaluation. `None` (the default — no
    // `server.max_concurrent_requests` configured) applies no layer at all,
    // so there is no overhead when the feature is unused.
    if let Some(load_shed) = load_shed_layer {
        router = router.layer(load_shed);
    }

    router = router.layer(axum::middleware::from_fn(
        crate::webhook::webhook_replay_cleanup_middleware,
    ));
    router = apply_upload_middleware(router, config);

    // User-registered Tower layers (AppBuilder::layer). Outermost — applied
    // last so they wrap all framework middleware.  Iterate in reverse so the
    // first registered layer ends up outermost among user layers — matching
    // tower::ServiceBuilder ordering.
    //
    // When a static dist dir is active (SSG/ISG build), these layers are
    // NOT passed here — they are extracted by try_build_router_with_static_inner
    // and applied outside the static-first middleware instead, so they can
    // process pre-rendered responses without creating a session dependency.
    let custom_layer_count = custom_layers.len();
    for registered in custom_layers.into_iter().rev() {
        router = (registered.apply)(router);
    }
    if custom_layer_count > 0 {
        tracing::debug!(count = custom_layer_count, "Custom Tower layers applied");
    }

    // TrustedProxiesLayer is applied after user layers so it is outermost in the
    // ingress request path, stamping ResolvedClientIdentity before any user or
    // framework middleware reads ClientAddr / ClientHost / ClientScheme.
    router = apply_trusted_proxies_middleware(router, config);

    let mut router = router;

    if config.tenancy.enabled {
        router = router.layer(axum::middleware::from_fn_with_state(
            state.clone(),
            crate::tenancy::tenancy_middleware,
        ));
        tracing::debug!("Multi-tenancy middleware enabled");
    }

    // Per-request timeout (inner to RequestId so the request ID set by that
    // layer is available when the timeout fires — see request_timeout_handler).
    //
    // Full ingress layer order (outermost → innermost):
    //   TraceContext → AccessLog-fallback (applied in apply_startup_barrier) →
    //   StartupBarrier → Compression → Metrics → ExceptionFilter → ErrorPageContext →
    //   Session → SecurityHeaders → RequestId → LogContext → AccessLog-primary →
    //   Timeout → [user layers] → Tenancy → BodyLimit/UploadConfig →
    //   MethodOverride → RateLimit → CSRF → CORS → handler
    // `mirror_cors = true`: this layer is outside `CorsLayer` (CORS is applied
    // earlier, hence inner), so its timeout 503 must carry CORS headers itself.
    //
    // KNOWN LIMITATION (session store I/O is not bounded): `Session` sits outside
    // this layer (see order above), so `store.load` runs before the timer starts
    // and `store.save`/`destroy` after it completes. A stalled session backend can
    // therefore tie up a worker despite `request_timeout_ms`. This placement is
    // deliberate: the timer is kept inner to `RequestId` so a timeout 503 (and its
    // warn log) carries `X-Request-Id` for log correlation — moving it outside
    // `Session` would also move it outside `RequestId` and lose that. Operators
    // who need to bound session-store I/O should configure a store-level deadline
    // (e.g. the Redis command/connection timeout); a cancelled inbound request
    // cannot abort an already-issued store call regardless of layer order.
    //
    // The same applies to the edge layers `App::run` wraps around the finished
    // router at the `axum::serve` boundary (`MethodOverrideLayer`,
    // `TrustedProxiesLayer`): they sit outside `RequestId` and therefore outside
    // this timer. In particular `MethodOverrideLayer` buffers an HTML form body
    // (`axum::body::to_bytes`, capped at `upload.max_request_size_bytes`) before
    // the inner router runs, so a slow `_method` form upload is not bounded by
    // `request_timeout_ms`. Moving the timer out there would again lose the
    // `X-Request-Id` correlation; bound this with a server/proxy read timeout
    // instead.
    router = apply_request_timeout_middleware(
        router,
        config,
        state.metrics.clone(),
        route_timeouts,
        true,
    );

    // Error-reporting + panic-catch layer. Placed inner to `RequestIdLayer`
    // (so the request id is available when a handler panics) and outer to the
    // timeout, user layers, and handler (so their panics are caught and turned
    // into a clean 500 instead of aborting the worker task). The resulting 500
    // still flows out through the exception-filter chain for HTML negotiation.
    #[cfg(feature = "reporting")]
    {
        router = router.layer(crate::reporting::ReportingLayer::new(
            state.error_reporters(),
            config.reporting.enabled,
            config.reporting.sample_rate,
        ));
    }

    // Structured per-request access log (#999), primary emitter: one INFO
    // event (target `autumn::access`) per served request at the response
    // boundary. Inner to RequestId (so the request id is available) and to
    // LogContext (so the event is emitted inside the request span); outer to
    // the reporting and timeout layers so panics-turned-500s and timeout
    // responses are logged with the status the client receives. Emitted
    // responses are marked so the outermost fallback (apply_startup_barrier)
    // does not double-log; that fallback covers requests that short-circuit
    // before this layer runs.
    if config.log.access_log {
        router = router.layer(crate::middleware::AccessLogLayer::new(
            config.log.access_log_exclude.clone(),
        ));
    }

    // Server-Timing response header (#1348). Applied outer to AccessLogLayer
    // (it is added after, so it wraps it) — its `total` metric is therefore
    // the outermost wall-clock measure and is `>=` the access-log
    // `duration_ms` by a few microseconds; both share the same
    // `Instant`-based formula. Opt-in via
    // `[observability] server_timing`; defaults on in dev, off in prod so
    // timings never leak to anonymous prod clients without explicit opt-in.
    if crate::config::server_timing_enabled(config) {
        router = router.layer(crate::middleware::ServerTimingLayer::new(true));
    }

    // Request-scoped log context (#1169). Established for every request, inner
    // to `RequestIdLayer` (so the request id is available to seed it) and outer
    // to tenancy, user layers, and the handler (so all of them, and every
    // `tracing` event they emit, inherit the same correlating context). The
    // filter mirrors the error-page scrubber so sensitive custom fields never
    // enter the context output.
    let mut log_context_filter_parameters = config.log.filter_parameters.clone();
    log_context_filter_parameters.extend(crate::encryption::registered_encrypted_column_names());
    let log_context_filter = Arc::new(crate::log::filter::ParameterFilter::new(
        &log_context_filter_parameters,
        &config.log.unfilter_parameters,
    ));
    let router = router.layer(crate::middleware::LogContextLayer::new(log_context_filter));

    // `security_headers` is applied LATER as the framework's outermost layer
    // (after the gate, below) so that a gate short-circuit (redirect/401) still
    // carries HSTS/CSP/nosniff — see the application point after the gate loop.
    // RequestId stays here (inner to session) so the request id seeds the
    // session, logs, and trace context.
    let router = router.layer(RequestIdLayer);

    // Pre-clone signing keys for the RYWW middleware (session mode needs to
    // sign/verify the `autumn.ryw` cookie; `signing_keys_opt` is consumed below).
    #[cfg(feature = "db")]
    let signing_keys_for_ryw = signing_keys_opt.clone();

    let router = crate::session::apply_session_layer(
        router,
        &config.session,
        config.profile.as_deref(),
        session_store,
        signing_keys_opt,
    )?;
    tracing::debug!(backend = ?config.session.backend, "Session management enabled");

    // Read-your-own-writes middleware: installed only when the mode is not
    // `off`. When active, it scopes a per-request task-local `RequestPin`
    // that generated repository read methods consult at acquire time.
    // Inner to Session so the task-local wraps the handler; the `autumn.ryw`
    // cookie is parsed from raw `Cookie` headers and does not require the
    // Session extractor to have run first.
    #[cfg(feature = "db")]
    let router = if config.database.read_your_writes == crate::config::ReadYourWrites::Off {
        router
    } else {
        let ryw_mode = config.database.read_your_writes;
        let window_secs = config.database.pin_after_write_secs;
        let keys = signing_keys_for_ryw;
        if ryw_mode == crate::config::ReadYourWrites::Session && keys.is_none() {
            tracing::warn!(
                "read_your_writes = \"session\" requires a configured \
                 security.signing_secret to sign the autumn.ryw cookie; \
                 cross-request pinning is disabled until a secret is set"
            );
        }
        let metrics = state.metrics().clone();
        router.layer(axum::middleware::from_fn(move |req, next| {
            crate::read_your_writes::middleware(
                req,
                next,
                ryw_mode,
                window_secs,
                keys.clone(),
                metrics.clone(),
            )
        }))
    };

    // Error page filter: renders HTML error pages for browser requests.
    // Always registered (uses default renderer if no custom one is provided).
    let is_dev = config
        .profile
        .as_deref()
        .map_or(cfg!(debug_assertions), |p| p == "dev");

    // When the `maud` feature is enabled, an ErrorPageFilter renders styled HTML
    // error pages for browser requests. Without `maud`, only the
    // ProblemDetailsFilter (JSON error normalization) is installed.
    let mut all_filters: Vec<Arc<dyn ExceptionFilter>> =
        vec![Arc::new(ProblemDetailsFilter { is_dev })];
    #[cfg(feature = "maud")]
    {
        // Encrypted columns (#805) compose into log scrubbing (#697): their names are
        // always scrubbed from trace/error parameter output so ciphertext-backed
        // values never leak through logs even if an app forgets to list them.
        let mut filter_parameters = config.log.filter_parameters.clone();
        filter_parameters.extend(crate::encryption::registered_encrypted_column_names());
        let renderer = error_page_renderer.unwrap_or_else(error_pages::default_renderer);
        let error_page_filter = crate::middleware::error_page_filter::ErrorPageFilter {
            renderer,
            is_dev,
            parameter_filter: crate::log::filter::ParameterFilter::new(
                &filter_parameters,
                &config.log.unfilter_parameters,
            ),
        };
        all_filters.push(Arc::new(error_page_filter));
    }
    all_filters.extend(exception_filters);

    let count = all_filters.len();
    tracing::debug!(
        count,
        "Registered exception filters (including error page filter)"
    );

    // Error page context layer must be inner to the exception filter so
    // WantsHtml is set on the response before the filter inspects it.
    // Full ingress layer order (outermost -> innermost). NOTE: the framework's
    // outermost `SecurityHeadersLayer` and the `static_gate` layers are applied
    // by `build_router_pre_state` AFTER this function returns (and, crucially,
    // after the MCP dispatch clone is taken), so they are NOT in this list:
    //   SecurityHeaders (framework outermost — applied in build_router_pre_state) ->
    //   [static_gate layers — applied in build_router_pre_state, after the MCP
    //   dispatch clone, outside session and the static cache] ->
    //   TraceContext (applied outside the startup barrier so short-circuit
    //   responses still carry traceparent) ->
    //   Compression (outer to ExceptionFilter — see note below) ->
    //   [user layers, when SSG/ISG dist dir active] ->
    //   StaticFileMiddleware (when SSG/ISG enabled) ->
    //   Metrics -> ExceptionFilter -> ErrorPageContext -> Session ->
    //   RequestId -> LogContext -> AccessLog-primary ->
    //   [user layers, non-static build] ->
    //   Tenancy -> RateLimit -> CSRF -> CORS -> handler
    //   (An AccessLog fallback sits outermost, applied in apply_startup_barrier.)
    let router = router
        .layer(crate::middleware::error_page_filter::ErrorPageContextLayer { is_dev })
        .layer(ExceptionFilterLayer::new(all_filters))
        .layer(crate::middleware::MetricsLayer::new(state.metrics.clone()));

    // Response compression is applied outermost (outside ExceptionFilter) so that
    // exception filters which rebuild the response body (e.g. ProblemDetailsFilter
    // normalising AutumnErrors to JSON Problem Details) do so before the body is
    // encoded. If compression were inner to ExceptionFilter, the filter would
    // inherit a Content-Encoding: gzip header on the rebuilt uncompressed body,
    // causing clients to receive uncompressed bytes labeled as gzip.
    // User-registered layers (EtagLayer etc.) remain inner to Compression, so
    // ETags are still computed on the uncompressed body before encoding occurs.
    let router = apply_compression_middleware(router, config);

    // NOTE: the `static_gate` layers and the framework's outermost
    // `SecurityHeadersLayer` are intentionally NOT applied here. They are applied
    // by `build_router_pre_state` after this function returns and after the MCP
    // dispatch clone is taken, so a `tools/call` replay never traverses the
    // page-cache gate (matching the SSG/ISG path and the documented intent).
    Ok(router)
}

/// Apply a set of user-registered layer registrations so that the
/// first-registered layer ends up outermost on ingress — matching
/// [`tower::ServiceBuilder`] ordering. Returns the wrapped router.
fn apply_layers_in_registration_order(
    mut router: axum::Router<AppState>,
    layers: Vec<crate::app::CustomLayerRegistration>,
    what: &str,
) -> axum::Router<AppState> {
    let count = layers.len();
    for registered in layers.into_iter().rev() {
        router = (registered.apply)(router);
    }
    if count > 0 {
        tracing::debug!(count, "{what} Tower layers applied");
    }
    router
}

async fn trusted_host_middleware(
    req: Request<axum::body::Body>,
    next: Next,
    policy: TrustedHostPolicy,
) -> axum::response::Response {
    let path = req.uri().path();
    if (req.method() == http::Method::GET || req.method() == http::Method::HEAD)
        && policy.probe_bypass_paths.contains(path)
    {
        return next.run(req).await;
    }
    let authority = req.uri().authority().map(http::uri::Authority::as_str);
    let host_header = req
        .headers()
        .get(http::header::HOST)
        .and_then(|v| v.to_str().ok());
    let raw_host = authority.or(host_header);
    let parsed_host = raw_host.and_then(extract_host_without_port);
    let host = parsed_host
        .map(str::to_ascii_lowercase)
        .map(|h| h.trim_end_matches('.').to_owned())
        .filter(|h| !h.is_empty());
    let host_source_present = raw_host.is_some();
    if host.is_none() && !host_source_present && policy.allow_missing_host {
        return next.run(req).await;
    }
    if host.as_deref().is_some_and(|host| policy.allows_host(host)) {
        next.run(req).await
    } else {
        tracing::warn!(host = ?host, "trusted host rejected request");
        let body = crate::error::problem_details_json_string(
            StatusCode::BAD_REQUEST,
            "Invalid Host header",
            None,
            None,
            None,
            None,
            true,
        );
        (
            StatusCode::BAD_REQUEST,
            [(http::header::CONTENT_TYPE, "application/problem+json")],
            body,
        )
            .into_response()
    }
}

pub fn extract_host_without_port(header: &str) -> Option<&str> {
    let host = header.trim();
    if host.is_empty() {
        return None;
    }
    if host.starts_with('[') {
        let end = host.find(']')?;
        let literal = host.get(1..end)?;
        if literal.is_empty() || literal.parse::<std::net::IpAddr>().is_err() {
            return None;
        }

        let remainder = host.get(end + 1..)?;
        if remainder.is_empty() {
            return Some(literal);
        }

        let maybe_port = remainder.strip_prefix(':')?;
        if !maybe_port.is_empty() && maybe_port.chars().all(|c| c.is_ascii_digit()) {
            return Some(literal);
        }

        return None;
    }
    let Some((candidate, maybe_port)) = host.rsplit_once(':') else {
        return Some(host);
    };
    if candidate.contains(':') {
        // unbracketed IPv6 literal; keep host verbatim
        return Some(host);
    }
    if !maybe_port.is_empty()
        && maybe_port.chars().all(|c| c.is_ascii_digit())
        && !candidate.is_empty()
    {
        Some(candidate)
    } else {
        None
    }
}

/// Build the router with optional static-file-first serving.
///
/// If `dist_dir` is `Some` and contains a valid `manifest.json`, the
/// returned router intercepts GET/HEAD requests whose path appears in
/// the manifest and serves pre-built HTML directly — before the dynamic
/// router runs.  This matches Next.js SSG/ISR semantics where static
/// pages always win over dynamic handlers.
///
/// Requests not in the manifest (including non-GET/HEAD methods) fall
/// through to the dynamic router unchanged.
///
/// When `dist_dir` is `None` or the manifest is missing, the returned
/// router is identical to [`build_router`].
///
/// This function is public primarily for integration testing.
///
/// # Panics
///
/// Panics when framework router assembly encounters invalid configuration.
/// Use [`try_build_router_with_static`] to handle configuration errors
/// explicitly.
#[allow(dead_code)]
pub fn build_router_with_static(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: AppState,
    dist_dir: Option<&std::path::Path>,
) -> axum::Router {
    try_build_router_with_static(route_list, config, state, dist_dir)
        .unwrap_or_else(|error| panic!("invalid router configuration: {error}"))
}

/// Checked variant of [`build_router_with_static`] that returns configuration
/// errors instead of panicking.
///
/// # Errors
///
/// Returns [`RouterBuildError`] when router assembly encounters invalid
/// framework configuration, such as an unusable session backend.
#[allow(dead_code)]
pub fn try_build_router_with_static(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: AppState,
    dist_dir: Option<&std::path::Path>,
) -> Result<axum::Router, RouterBuildError> {
    try_build_router_with_static_inner(
        route_list,
        config,
        state,
        dist_dir,
        RouterContext {
            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(),
            #[cfg(feature = "maud")]
            error_page_renderer: None,
            session_store: None,
            #[cfg(feature = "openapi")]
            openapi: None,
            #[cfg(feature = "mcp")]
            mcp: None,
        },
    )
}

#[allow(clippy::too_many_lines)]
pub fn try_build_router_with_static_inner(
    route_list: Vec<Route>,
    config: &AutumnConfig,
    state: AppState,
    dist_dir: Option<&std::path::Path>,
    mut ctx: RouterContext,
) -> Result<axum::Router, RouterBuildError> {
    let startup_barrier_state = state.clone();

    let Some(dist) = dist_dir else {
        let app_router = try_build_router_inner(route_list, config, state, ctx)?;
        return Ok(apply_startup_barrier(
            app_router,
            config,
            &startup_barrier_state,
        ));
    };

    let Some(layer) = crate::static_gen::StaticFileLayer::new(dist) else {
        tracing::debug!(
            dist = %dist.display(),
            "No valid manifest.json in dist dir; skipping static file layer"
        );
        let app_router = try_build_router_inner(route_list, config, state, ctx)?;
        return Ok(apply_startup_barrier(
            app_router,
            config,
            &startup_barrier_state,
        ));
    };

    for (route, entry) in &layer.manifest().routes {
        tracing::debug!(
            route = %route,
            file = %entry.file,
            revalidate = ?entry.revalidate,
            "Static route"
        );
    }

    // Extract user layers before building the inner router. They are applied
    // OUTSIDE the static-first middleware (and outside session) so that:
    //   • User layers (e.g. compression) can process pre-rendered responses.
    //   • Static serving remains available even if the session backend is down.
    //   • ISR regeneration uses the inner router (no user layers), ensuring
    //     re-rendered pages are saved as raw HTML rather than pre-transformed.
    //
    // KNOWN LIMITATION (`request_timeout_ms` does not bound these outer layers):
    // the per-request timeout lives inside `inner_router` (applied by
    // `apply_middleware`, inner to `RequestId`). Because `custom_layers` and
    // `static_gate_layers` are reapplied OUTSIDE the static-first middleware
    // (below), they — and the static cache lookup itself — run before the timer
    // starts. So when a `dist` manifest is active, a hung async `static_gate`
    // (e.g. remote JWT/IdP validation) or custom layer is NOT bounded by
    // `request_timeout_ms`, unlike the non-static path where the timer wraps the
    // user layers and tenancy. This is the same trade-off as the documented
    // session-store and edge-layer (`MethodOverrideLayer`, `TrustedProxiesLayer`)
    // limitations in `apply_middleware`: pulling the timer out here to cover them
    // would place it outside `RequestId` (losing `X-Request-Id` on the timeout
    // 503), double-time dynamic misses, and apply a global deadline to cached
    // hits that have no route-table entry. Operators who terminate auth/tenant
    // work in a `static_gate` should bound it with a layer-level or
    // server/proxy read timeout instead.
    //
    // Compute the idempotency flag NOW while custom_layers is still populated,
    // then drain it. build_router_pre_state would otherwise see an empty list
    // and incorrectly treat opaque layers as absent when selecting idempotency
    // behaviour for each route.
    //
    // Pre-static gate layers count here too: a `static_gate` used as a
    // JWT/stateless auth layer is an opaque app layer for idempotency purposes
    // (idempotency keys exclude `Authorization`, so without fail-closed replay a
    // second principal with the same key+body could receive the first
    // principal's cached mutation). Include them BEFORE either list is drained.
    let opaque_present = Some(
        custom_layers_require_fail_closed_idempotency(&ctx.custom_layers)
            || custom_layers_require_fail_closed_idempotency(&ctx.static_gate_layers),
    );
    let custom_layers = std::mem::take(&mut ctx.custom_layers);

    // Pre-static gate layers (AppBuilder::static_gate) are likewise extracted
    // and applied OUTSIDE the static-first middleware (the outermost layer of
    // all), so they run before the static cache lookup serves a pre-rendered
    // page. Draining them here keeps build_router_pre_state from applying them
    // to the inner router (which would place them inside the static middleware
    // and defeat the gate for cached hits).
    let static_gate_layers = std::mem::take(&mut ctx.static_gate_layers);

    // SSG/ISG path: a single SecurityHeadersLayer is applied OUTSIDE the
    // static-first middleware below (wrapping cached pages, dynamic misses, and
    // the gate), so the inner router must NOT apply its own — hence `true`.
    let inner_router =
        build_router_pre_state(route_list, config, &state, ctx, opaque_present, true)?;

    // Attach the inner router for ISR background regeneration. Because user
    // layers are excluded, re-renders produce raw HTML (no compression, etc.)
    // that is then saved to disk and served with user-layer processing applied
    // at request time.
    let has_isr = layer
        .manifest()
        .routes
        .values()
        .any(|e| e.revalidate.is_some());
    let layer = if has_isr {
        // The inner router defers `SecurityHeadersLayer` to the single outer
        // application (see `defer_security_headers`), but ISR background
        // regeneration drives this router directly and never reaches that outer
        // layer. `SecurityHeadersLayer` is also what injects `CspNonce` into
        // request extensions, so without it a handler using the `CspNonce`
        // extractor would 500 during regeneration and the stale file would never
        // refresh. Re-attach the layer here, on the regeneration router only.
        // Its response headers are discarded (only the rendered HTML body is
        // persisted), so this does not affect live-request headers and avoids the
        // duplicate-header / nonce conflict that a second live layer would cause.
        let regen_router = inner_router
            .clone()
            .layer(crate::security::SecurityHeadersLayer::from_config(
                &config.security.headers,
            ))
            .with_state(state.clone());
        layer.with_router(regen_router)
    } else {
        layer
    };
    let layer = Arc::new(layer);

    // Static-first serving: intercept GET/HEAD requests whose path appears
    // in the manifest and serve pre-built HTML directly — BEFORE the dynamic
    // router (and session layer) runs. This preserves availability of static
    // pages even when the session backend is unavailable.
    //
    // Requests not in the manifest (including non-GET/HEAD methods) fall
    // through to the dynamic router unchanged.
    //
    // ISR staleness checking happens inside `resolve()`: stale pages are
    // still served immediately while background regeneration runs
    // (stale-while-revalidate).
    let static_layer = layer;
    let mut router: axum::Router<AppState> = inner_router.layer(axum::middleware::from_fn(
        move |req: axum::extract::Request, next: axum::middleware::Next| {
            let static_layer = static_layer.clone();
            async move {
                let is_get = req.method() == http::Method::GET;
                let is_head = req.method() == http::Method::HEAD;
                if is_get || is_head {
                    let path = req.uri().path();
                    // Normalize trailing slash: /about/ → /about (but keep / as /)
                    let normalized = if path.len() > 1 && path.ends_with('/') {
                        &path[..path.len() - 1]
                    } else {
                        path
                    };
                    if let Some(file_path) = static_layer.resolve(normalized)
                        && let Ok(contents) = tokio::fs::read(&file_path).await
                    {
                        // Derive the Content-Type from the request route's
                        // extension rather than hard-coding text/html. The
                        // response compression layer (applied OUTSIDE this
                        // middleware) negotiates gzip/brotli by content type, so
                        // an accurate MIME type is what lets compressible SSG
                        // pages (HTML/CSS/JS/JSON/XML/text) be encoded while
                        // binary manifest assets (images, fonts, octet-stream)
                        // are left untouched.
                        //
                        // The served file name is NOT a reliable MIME source for
                        // generated routes: `static_gen::url_to_file_path` stores
                        // every non-root route as `<route>/index.html`, so
                        // `/robots.txt` -> `robots.txt/index.html` and
                        // `/sitemap.xml` -> `sitemap.xml/index.html`. Reading the
                        // extension off `index.html` would mislabel those as
                        // text/html. The request route carries the true
                        // extension, so prefer it — but ONLY when its final path
                        // segment ends in an extension the asset table actually
                        // recognizes.
                        //
                        // A bare `contains('.')` check is too loose: a generated
                        // page whose slug merely contains a dot
                        // (`/posts/release.v1`, `/users/alice@example.com`) is
                        // still stored as `<slug>/index.html` HTML, yet `.v1` /
                        // `.com` are not asset extensions. Deriving the MIME from
                        // the route there would mislabel HTML as
                        // `application/octet-stream` and break its compression.
                        // `content_type_for_opt` returns `Some` only for a
                        // recognized extension, so those unrecognized-dot slugs
                        // fall through to the served file name (`index.html` ->
                        // text/html), exactly like extensionless pages.
                        //
                        // Extensionless routes are real pages (`/about` ->
                        // `about/index.html`) and resolve to text/html via the
                        // same file-name fallback. Hand-written manifests that map
                        // an extensionless route directly at an extensioned file
                        // (e.g. `/logo` -> `logo.png`, `/inter` ->
                        // `fonts/inter.woff2`) are likewise covered by it. The URL
                        // path is always '/'-delimited, so inspecting the last
                        // segment is unaffected by platform path separators.
                        let content_type = crate::assets::content_type_for_opt(normalized)
                            .unwrap_or_else(|| {
                                file_path
                                    .file_name()
                                    .and_then(|name| name.to_str())
                                    .map_or("application/octet-stream", |name| {
                                        crate::assets::content_type_for(name)
                                    })
                            });
                        let body = if is_head {
                            axum::body::Body::empty()
                        } else {
                            axum::body::Body::from(contents)
                        };
                        return http::Response::builder()
                            .status(http::StatusCode::OK)
                            .header(http::header::CONTENT_TYPE, content_type)
                            .body(body)
                            .expect("infallible response builder");
                    }
                }
                next.run(req).await
            }
        },
    ));

    // Apply user layers OUTSIDE the static middleware so they wrap it and can
    // process both static and dynamic responses (e.g. compress the HTML on
    // the way out). Iterate in reverse so the first registered layer ends up
    // outermost — matching tower::ServiceBuilder ordering.
    router = apply_layers_in_registration_order(
        router,
        custom_layers,
        "Custom (outside static middleware)",
    );

    // Compression must also be applied OUTSIDE the static-first middleware so
    // that pre-rendered HTML pages (served directly by StaticFileLayer without
    // reaching inner_router) are also compressed. This mirrors the placement in
    // apply_middleware for the dynamic-only path.
    router = apply_compression_middleware(router, config);

    // Pre-static gate layers run before the static cache lookup (they wrap the
    // static-first middleware) so they can redirect / reject a request before a
    // cached SSG/ISG page is served. They are applied INNER to the
    // SecurityHeadersLayer below so that a gate's short-circuit response
    // (redirect / 401) still carries the framework security headers (HSTS/CSP,
    // etc.) — matching the headers a normal cached or dynamic response gets.
    router = apply_layers_in_registration_order(
        router,
        static_gate_layers,
        "Pre-static gate (outside static middleware)",
    );

    // Security headers are applied OUTERMOST so they wrap both cached pages and
    // any gate short-circuit response. This is the SINGLE application for the
    // SSG/ISG path: the inner router skips it (build_router_pre_state is called
    // with `defer_security_headers = true`), so dynamic misses are not
    // double-wrapped (which would break CSP nonces).
    let router = router.layer(crate::security::SecurityHeadersLayer::from_config(
        &config.security.headers,
    ));

    Ok(apply_startup_barrier(
        router.with_state(state),
        config,
        &startup_barrier_state,
    ))
}

#[derive(Clone)]
struct StartupBarrierState {
    app_state: AppState,
    // Canonical exact-match probe/health paths (`probe_bypass_paths`), the
    // single source of truth shared with `TrustedHostPolicy` and the
    // maintenance/load-shed gates — see that function's doc comment.
    probe_paths: Vec<String>,
    actuator_paths: Vec<String>,
    actuator_subtree_paths: Vec<String>,
}

impl StartupBarrierState {
    fn from_config(config: &AutumnConfig, app_state: &AppState) -> Self {
        let actuator_subtree_paths = if config.actuator.sensitive {
            vec![crate::actuator::actuator_route_path(
                &config.actuator.prefix,
                "/loggers",
            )]
        } else {
            Vec::new()
        };

        Self {
            app_state: app_state.clone(),
            probe_paths: probe_bypass_paths(config),
            actuator_paths: crate::actuator::actuator_endpoint_paths(
                &config.actuator.prefix,
                config.actuator.sensitive,
                config.actuator.prometheus,
            ),
            actuator_subtree_paths,
        }
    }

    fn allows_path(&self, path: &str) -> bool {
        self.probe_paths.iter().any(|allowed| path == allowed)
            || self.actuator_paths.iter().any(|allowed| path == allowed)
            || self
                .actuator_subtree_paths
                .iter()
                .any(|allowed| path_matches_route_prefix(path, allowed))
    }
}

fn apply_startup_barrier(
    router: axum::Router,
    config: &AutumnConfig,
    state: &AppState,
) -> axum::Router {
    let barrier_state = StartupBarrierState::from_config(config, state);
    let router = router.layer(axum::middleware::from_fn_with_state(
        barrier_state,
        startup_barrier,
    ));
    // Access-log fallback (#999), applied OUTSIDE the startup barrier, the
    // static-first (SSG/ISR) middleware, the session layer, and the
    // exception-filter chain — every production build path funnels through
    // this function, including after the late MCP endpoint merge. It emits
    // only for responses the primary in-stack layer never saw (it checks the
    // AccessLogEmitted response marker), giving startup 503s, pre-built
    // static page hits, session-store outage 503s, and MCP endpoint requests
    // an access line too. Those short-circuits never ran RequestIdLayer, so
    // the fallback reads `x-request-id` from the response when present and
    // logs without a request id otherwise.
    let router = if config.log.access_log {
        router.layer(crate::middleware::AccessLogLayer::fallback(
            config.log.access_log_exclude.clone(),
        ))
    } else {
        router
    };
    // Server-Timing fallback (#1348), applied OUTSIDE the startup barrier, the
    // static-first (SSG/ISR) middleware, the session layer, and the late MCP
    // merge — exactly the short-circuit paths the primary ServerTimingLayer in
    // `apply_middleware` never sees. Gated on the same `server_timing_enabled`
    // resolver as the primary. It appends only for responses missing the
    // `ServerTimingEmitted` marker, so requests that reach the primary carry a
    // single `total`; short-circuits (startup 503, pre-built static hits) get a
    // `total` here.
    let router = if crate::config::server_timing_enabled(config) {
        router.layer(crate::middleware::ServerTimingLayer::fallback(true))
    } else {
        router
    };
    // W3C Trace Context propagation wraps the startup barrier (and the
    // static-first middleware above it) so short-circuit responses —
    // startup 503s and pre-built static file hits — still extract the
    // incoming `traceparent` and inject the current context into the
    // outgoing response. Applied here rather than inside `apply_middleware`
    // because those outer wrappers can return without ever invoking the
    // inner router. Outer to AccessLog so the access event is emitted while
    // the trace context is current.
    #[cfg(feature = "telemetry-otlp")]
    let router = router.layer(crate::middleware::TraceContextLayer);
    router
}

async fn startup_barrier(
    State(state): State<StartupBarrierState>,
    request: axum::extract::Request,
    next: Next,
) -> axum::response::Response {
    if crate::app::is_static_build_mode()
        || state.app_state.probes().is_startup_complete()
        || state.allows_path(request.uri().path())
    {
        next.run(request).await
    } else {
        (
            StatusCode::SERVICE_UNAVAILABLE,
            "Service is still starting up",
        )
            .into_response()
    }
}

pub fn path_matches_route_prefix(path: &str, prefix: &str) -> bool {
    path == prefix
        || path
            .strip_prefix(prefix)
            .is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
}

/// Build a `tower_http::cors::CorsLayer` from the framework's [`crate::config::CorsConfig`].
///
/// Called only when `config.cors.allowed_origins` is non-empty.
pub fn build_cors_layer(cors: &crate::config::CorsConfig) -> tower_http::cors::CorsLayer {
    use http::header::HeaderName;
    use tower_http::cors::{AllowOrigin, CorsLayer};

    let layer = if cors.allowed_origins.iter().any(|o| o == "*") {
        CorsLayer::new().allow_origin(AllowOrigin::any())
    } else {
        let origins: Vec<http::HeaderValue> = cors
            .allowed_origins
            .iter()
            .filter_map(|o| match o.parse() {
                Ok(v) => Some(v),
                Err(e) => {
                    tracing::warn!(origin = %o, error = %e, "CORS: ignoring malformed allowed_origin");
                    None
                }
            })
            .collect();
        CorsLayer::new().allow_origin(origins)
    };

    let methods: Vec<http::Method> = cors
        .allowed_methods
        .iter()
        .filter_map(|m| match m.parse() {
            Ok(v) => Some(v),
            Err(e) => {
                tracing::warn!(method = %m, error = %e, "CORS: ignoring malformed allowed_method");
                None
            }
        })
        .collect();

    let headers: Vec<HeaderName> = cors
        .allowed_headers
        .iter()
        .filter_map(|h| match h.parse() {
            Ok(v) => Some(v),
            Err(e) => {
                tracing::warn!(header = %h, error = %e, "CORS: ignoring malformed allowed_header");
                None
            }
        })
        .collect();

    layer
        .allow_methods(methods)
        .allow_headers(headers)
        .allow_credentials(cors.allow_credentials)
        .max_age(std::time::Duration::from_secs(cors.max_age_secs))
}

/// Mirror onto a timeout-generated 503 the CORS response headers `CorsLayer`
/// would add to a normal (non-preflight) response.
///
/// In the main ingress stack the per-request timeout layer sits *outside*
/// `CorsLayer` (see the layer order in `apply_middleware`), so a 503 it
/// synthesizes on expiry never flows back through `CorsLayer`. Without this a
/// cross-origin browser client sees an opaque CORS failure instead of the
/// documented Problem Details 503. Only the simple-response subset is needed:
/// the resolved `Access-Control-Allow-Origin` (with `Vary: origin` when it is
/// reflected) and `Access-Control-Allow-Credentials`. Preflight (OPTIONS)
/// requests are answered by `CorsLayer` directly and never reach the timer.
/// Mirror the `Access-Control-*` response headers a real `CorsLayer` would
/// have added, onto a `response` synthesized by a layer that sits outside
/// (outer to) `CorsLayer` in the ingress stack — so its 503 is CORS-readable
/// instead of the client seeing an opaque CORS failure. Shared by the
/// per-request timeout middleware and [`crate::middleware::LoadShedLayer`],
/// the two admission-style gates that can short-circuit before `CorsLayer`
/// runs.
pub fn mirror_cors_headers(
    cors: &crate::config::CorsConfig,
    origin: Option<&http::HeaderValue>,
    response: &mut axum::response::Response,
) {
    use http::header;
    let allow_any = cors.allowed_origins.iter().any(|o| o == "*");
    let allow_origin = if allow_any {
        Some(http::HeaderValue::from_static("*"))
    } else {
        // Echo the request Origin iff it is in the configured allowlist, exactly
        // as `CorsLayer` does for a reflected origin.
        origin.and_then(|value| {
            let value_str = value.to_str().ok()?;
            cors.allowed_origins
                .iter()
                .any(|allowed| allowed == value_str)
                .then(|| value.clone())
        })
    };
    let Some(allow_origin) = allow_origin else {
        // Origin missing or not allowed: a real `CorsLayer` would add nothing.
        return;
    };
    let headers = response.headers_mut();
    headers.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, allow_origin);
    if !allow_any {
        // A reflected origin makes the response origin-dependent; mirror the
        // `Vary: origin` `CorsLayer` adds so shared caches don't serve it to a
        // different origin.
        headers.insert(header::VARY, http::HeaderValue::from_static("origin"));
    }
    if cors.allow_credentials {
        headers.insert(
            header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
            http::HeaderValue::from_static("true"),
        );
    }
}

#[cfg(feature = "htmx")]
pub async fn htmx_handler() -> axum::response::Response {
    use axum::response::IntoResponse;
    (
        [
            (http::header::CONTENT_TYPE, "application/javascript"),
            (
                http::header::CACHE_CONTROL,
                "public, max-age=31536000, immutable",
            ),
        ],
        crate::htmx::HTMX_JS,
    )
        .into_response()
}

/// Gzip/brotli encodings of a compile-time-constant CSS body, computed once
/// per process (via a call-site-owned [`std::sync::OnceLock`], see
/// [`flash_css_handler`]/[`widgets_css_handler`]) rather than redone on every
/// request — the bytes never change, so recompressing them per-request would
/// burn CPU for a byte-identical result each time.
#[cfg(any(feature = "flash", feature = "maud"))]
struct PrecompressedCss {
    gzip: bytes::Bytes,
    brotli: bytes::Bytes,
}

#[cfg(any(feature = "flash", feature = "maud"))]
impl PrecompressedCss {
    fn compute(body: &'static str) -> Self {
        use std::io::Write as _;

        let mut gzip_encoder =
            flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        gzip_encoder
            .write_all(body.as_bytes())
            .expect("in-memory gzip encoding cannot fail");
        let gzip = gzip_encoder
            .finish()
            .expect("in-memory gzip encoding cannot fail");

        let mut brotli_writer = brotli::CompressorWriter::new(Vec::new(), 4096, 11, 22);
        brotli_writer
            .write_all(body.as_bytes())
            .expect("in-memory brotli encoding cannot fail");
        let brotli = brotli_writer.into_inner();

        Self {
            gzip: gzip.into(),
            brotli: brotli.into(),
        }
    }
}

/// `true` when the request's `Accept-Encoding` header accepts `coding`
/// (case-insensitive, comma-separated, honoring an explicit `q=0` opt-out
/// per RFC 7231 §5.3.4). A minimal parser rather than a full content-
/// negotiation crate, since only `gzip`/`br` ever need checking here.
#[cfg(any(feature = "flash", feature = "maud"))]
fn accepts_encoding(headers: &http::HeaderMap, coding: &str) -> bool {
    let Some(value) = headers
        .get(http::header::ACCEPT_ENCODING)
        .and_then(|v| v.to_str().ok())
    else {
        return false;
    };
    value.split(',').any(|part| {
        let mut segments = part.split(';');
        let name = segments.next().unwrap_or("").trim();
        name.eq_ignore_ascii_case(coding)
            && segments
                .find_map(|q| q.trim().strip_prefix("q="))
                .and_then(|q| q.parse::<f32>().ok())
                .is_none_or(|q| q > 0.0)
    })
}

/// Serves a framework-owned, compile-time-constant CSS asset: same-origin,
/// immutably cached, conditional-GET aware (a strong `ETag` hashed from
/// `body`, so a revalidating client gets a bodyless `304` instead of the
/// full asset), and served pre-compressed from `precompressed` when the
/// client's `Accept-Encoding` allows it — computed once per process, not
/// per request. Shared by every framework CSS route ([`flash_css_handler`],
/// [`widgets_css_handler`]) so the caching/content-type/compression policy
/// lives in one place.
#[cfg(any(feature = "flash", feature = "maud"))]
fn static_css_response(
    headers: &http::HeaderMap,
    body: &'static str,
    precompressed: &'static PrecompressedCss,
) -> axum::response::Response {
    use crate::etag::IntoETag as _;
    use axum::response::IntoResponse;

    let (encoded_body, content_encoding): (axum::body::Body, Option<&'static str>) =
        if accepts_encoding(headers, "br") {
            (precompressed.brotli.clone().into(), Some("br"))
        } else if accepts_encoding(headers, "gzip") {
            (precompressed.gzip.clone().into(), Some("gzip"))
        } else {
            (body.into(), None)
        };

    let mut response_headers = http::HeaderMap::new();
    response_headers.insert(
        http::header::CONTENT_TYPE,
        http::HeaderValue::from_static("text/css; charset=utf-8"),
    );
    response_headers.insert(
        http::header::CACHE_CONTROL,
        http::HeaderValue::from_static("public, max-age=31536000, immutable"),
    );
    // Cache intermediaries must key on the request's Accept-Encoding since
    // the body served for this same URL differs (plain/gzip/br).
    response_headers.insert(
        http::header::VARY,
        http::HeaderValue::from_static("Accept-Encoding"),
    );
    if let Some(encoding) = content_encoding {
        response_headers.insert(
            http::header::CONTENT_ENCODING,
            http::HeaderValue::from_static(encoding),
        );
    }

    // A weak validator: the identity/gzip/br byte streams served for this
    // one logical resource are not byte-identical, so a strong ETag (which
    // asserts byte-for-byte equivalence — see `ETag::strong`) would be
    // incorrect here, even though `Vary: Accept-Encoding` already keeps
    // cache entries for different encodings distinct.
    let etag = crate::etag::ETag::weak(body.into_etag().tag().to_owned());

    crate::etag::fresh_when(headers, etag)
        .or((response_headers, encoded_body))
        .into_response()
}

/// Serves the framework's default flash-message stylesheet
/// ([`crate::flash::FLASH_CSS`]) at [`crate::flash::FLASH_CSS_PATH`].
#[cfg(feature = "flash")]
pub async fn flash_css_handler(headers: http::HeaderMap) -> axum::response::Response {
    static PRECOMPRESSED: std::sync::OnceLock<PrecompressedCss> = std::sync::OnceLock::new();
    static_css_response(
        &headers,
        crate::flash::FLASH_CSS,
        PRECOMPRESSED.get_or_init(|| PrecompressedCss::compute(crate::flash::FLASH_CSS)),
    )
}

/// Serves the framework's widget stylesheet ([`crate::ui::WIDGETS_CSS`]) at
/// [`crate::ui::WIDGETS_CSS_PATH`] (#1215).
#[cfg(feature = "maud")]
pub async fn widgets_css_handler(headers: http::HeaderMap) -> axum::response::Response {
    static PRECOMPRESSED: std::sync::OnceLock<PrecompressedCss> = std::sync::OnceLock::new();
    static_css_response(
        &headers,
        crate::ui::WIDGETS_CSS,
        PRECOMPRESSED.get_or_init(|| PrecompressedCss::compute(crate::ui::WIDGETS_CSS)),
    )
}

#[cfg(feature = "htmx")]
pub async fn htmx_csrf_handler() -> axum::response::Response {
    use axum::response::IntoResponse;
    (
        [
            (http::header::CONTENT_TYPE, "application/javascript"),
            (
                http::header::CACHE_CONTROL,
                "public, max-age=31536000, immutable",
            ),
        ],
        crate::htmx::HTMX_CSRF_JS,
    )
        .into_response()
}

#[cfg(feature = "htmx")]
pub async fn autumn_widgets_handler() -> axum::response::Response {
    use axum::response::IntoResponse;
    (
        [
            (http::header::CONTENT_TYPE, "application/javascript"),
            (
                http::header::CACHE_CONTROL,
                "public, max-age=31536000, immutable",
            ),
        ],
        crate::htmx::AUTUMN_WIDGETS_JS,
    )
        .into_response()
}

/// Weak `ETag` for the vendored idiomorph script, derived once from the
/// embedded bytes.
///
/// The idiomorph URL is **not** content-fingerprinted, so it cannot safely use
/// an `immutable` cache. Instead the handler emits this content-derived `ETag`
/// alongside a revalidating `Cache-Control`, letting caches confirm freshness
/// (and pick up new bytes) whenever the vendored script changes.
///
/// The validator is **weak**: when compression is enabled,
/// `apply_compression_middleware` gzips/brotli-encodes this
/// `application/javascript` response after the handler attaches the `ETag`, so
/// the identity, gzip, and br variants share one tag despite differing byte
/// streams. A strong `ETag` asserts byte-for-byte equivalence and would be
/// invalid across those encodings (matching the sibling CSS asset handler).
#[cfg(feature = "htmx")]
static IDIOMORPH_ETAG: std::sync::LazyLock<crate::etag::ETag> = std::sync::LazyLock::new(|| {
    use sha2::{Digest, Sha256};
    use std::fmt::Write as _;

    let digest = Sha256::digest(crate::htmx::IDIOMORPH_JS);
    let mut hex = String::with_capacity(digest.len() * 2);
    for byte in digest {
        let _ = write!(hex, "{byte:02x}");
    }
    crate::etag::ETag::weak(format!("idiomorph-{hex}"))
});

/// Serves the vendored idiomorph DOM-morphing library at [`crate::htmx::IDIOMORPH_JS_PATH`].
///
/// Idiomorph enables smooth DOM morphing via `hx-swap="morph"` in htmx.
///
/// Because the serving URL is not content-fingerprinted, the response uses a
/// revalidating cache policy (`must-revalidate` plus a weak content-derived
/// `ETag`) rather than a year-long `immutable` cache. This ensures clients that
/// cached an earlier version of the script pick up new bytes instead of running
/// a stale copy for up to a year.
#[cfg(feature = "htmx")]
pub async fn idiomorph_handler() -> axum::response::Response {
    use axum::response::IntoResponse;
    let mut response = (
        [
            (http::header::CONTENT_TYPE, "application/javascript"),
            (
                http::header::CACHE_CONTROL,
                "public, max-age=0, must-revalidate",
            ),
        ],
        crate::htmx::IDIOMORPH_JS,
    )
        .into_response();
    response
        .headers_mut()
        .insert(http::header::ETAG, IDIOMORPH_ETAG.header_value());
    response
}

/// Serves the vendored htmx SSE extension at [`crate::htmx::HTMX_SSE_JS_PATH`].
///
/// The SSE extension enables `hx-ext="sse"` for server-sent event streams.
#[cfg(feature = "htmx")]
pub async fn htmx_sse_handler() -> axum::response::Response {
    use axum::response::IntoResponse;
    (
        [
            (http::header::CONTENT_TYPE, "application/javascript"),
            (
                http::header::CACHE_CONTROL,
                "public, max-age=31536000, immutable",
            ),
        ],
        crate::htmx::HTMX_SSE_JS,
    )
        .into_response()
}

#[cfg(feature = "openapi")]
fn collect_openapi_docs(
    route_list: &[Route],
    scoped_groups: &[ScopedGroup],
) -> Vec<crate::openapi::ApiDoc> {
    // Walk both top-level routes and scoped groups. For scoped groups the
    // effective path is `prefix + route.path`; we materialize these into
    // fresh `ApiDoc`s so the rendered spec reflects the actual URL the
    // user will call.
    let mut docs: Vec<crate::openapi::ApiDoc> = Vec::new();
    for route in route_list {
        let mut doc = route.api_doc.clone();
        doc.api_version = route.api_version;
        doc.sunset_opt_out = route.sunset_opt_out;
        docs.push(doc);
    }
    for group in scoped_groups {
        // Extract `{name}` captures from the scope prefix so parameters
        // declared in the prefix (e.g. `/orgs/{org_id}`) show up on the
        // generated operation alongside the child route's own params.
        let prefix_params = 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;
            // Leak the combined path so it fits the `&'static str` shape of
            // ApiDoc. The spec is built once per process; the leak is
            // bounded by the route table size. Using the same
            // normalization as `join_nested_path` keeps the spec's
            // paths aligned with the URLs axum actually routes.
            let full = 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();
                for existing in route.api_doc.path_params {
                    if !merged.iter().any(|n| n == existing) {
                        merged.push(existing);
                    }
                }
                doc.path_params = Box::leak(merged.into_boxed_slice());
            }

            docs.push(doc);
        }
    }
    docs
}

#[cfg(feature = "openapi")]
fn mount_swagger_ui_routes(
    mut router: axum::Router<AppState>,
    path: &str,
    title: &str,
    json_path: &str,
) -> axum::Router<AppState> {
    let [css_path, bundle_path, initializer_path] = crate::openapi::swagger_ui_asset_paths(path);
    let html_body = Arc::new(crate::openapi::swagger_ui_html(
        title,
        &css_path,
        &bundle_path,
        &initializer_path,
    ));
    let initializer_body = Arc::new(crate::openapi::swagger_ui_initializer_js(json_path));
    router = router.route(
        path,
        axum::routing::get(move || {
            let html = html_body.clone();
            async move {
                use axum::response::IntoResponse;
                (
                    [(http::header::CONTENT_TYPE, "text/html; charset=utf-8")],
                    (*html).clone(),
                )
                    .into_response()
            }
        }),
    );
    router = router.route(
        &css_path,
        axum::routing::get(|| async move {
            use axum::response::IntoResponse;
            (
                [(http::header::CONTENT_TYPE, "text/css; charset=utf-8")],
                crate::openapi::SWAGGER_UI_CSS,
            )
                .into_response()
        }),
    );
    router = router.route(
        &bundle_path,
        axum::routing::get(|| async move {
            use axum::body::Bytes;
            use axum::response::IntoResponse;
            (
                [(
                    http::header::CONTENT_TYPE,
                    "application/javascript; charset=utf-8",
                )],
                Bytes::from_static(crate::openapi::SWAGGER_UI_BUNDLE),
            )
                .into_response()
        }),
    );
    router = router.route(
        &initializer_path,
        axum::routing::get(move || {
            let js = initializer_body.clone();
            async move {
                use axum::response::IntoResponse;
                (
                    [(
                        http::header::CONTENT_TYPE,
                        "application/javascript; charset=utf-8",
                    )],
                    (*js).clone(),
                )
                    .into_response()
            }
        }),
    );
    router
}

/// Scope the request's [`AppState`] as the ambient event-bus app for the
/// duration of the request, so the free `events::publish` resolves this app.
async fn event_app_context_middleware(
    state: axum::extract::State<AppState>,
    req: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    crate::events::scope_event_app(state.0.clone(), async move { next.run(req).await }).await
}

#[cfg(feature = "oauth2")]
async fn http_interceptor_middleware(
    state: axum::extract::State<AppState>,
    req: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    use crate::interceptor::{ACTIVE_HTTP_INTERCEPTORS, HttpInterceptor};
    if let Some(interceptor_arc) = state.extension::<Arc<dyn HttpInterceptor>>() {
        let interceptor = (*interceptor_arc).clone();
        let interceptors = vec![interceptor];
        ACTIVE_HTTP_INTERCEPTORS
            .scope(interceptors, async move { next.run(req).await })
            .await
    } else {
        next.run(req).await
    }
}

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

    fn test_state() -> AppState {
        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: Some("test".to_owned()),
            role: crate::config::ProcessRole::Combined,
            started_at: std::time::Instant::now(),
            health_detailed: false,
            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: crate::state::AppState::next_app_id(),
        }
    }

    // ── submit-token production memory guard wiring (Finding O) ─────────────

    #[test]
    fn submit_token_explicit_memory_in_production_fails_router_build() {
        // EXPLICIT `[security.submit_token].backend = "memory"` + production →
        // hard fail at router build, mirroring the idempotency prod-memory guard.
        let mut config = AutumnConfig::default();
        config.security.submit_token.backend = Some(crate::config::IdempotencyBackend::Memory);
        let err = apply_submit_token_middleware(axum::Router::<()>::new(), &config, true)
            .expect_err("explicit memory submit-token backend in prod must fail router build");
        assert!(
            matches!(err, RouterBuildError::InvalidSubmitTokenBackend(_)),
            "expected InvalidSubmitTokenBackend, got {err:?}"
        );
    }

    #[test]
    fn submit_token_inherited_memory_in_production_builds() {
        // INHERITED default (`backend = None`) resolving to Memory in prod must
        // NOT fail — it only warns. Router build succeeds.
        let mut config = AutumnConfig::default();
        config.security.submit_token.backend = None;
        config.idempotency.backend = crate::config::IdempotencyBackend::Memory;
        let _router = apply_submit_token_middleware(axum::Router::<()>::new(), &config, true)
            .expect("inherited memory submit-token backend in prod must still build (warn only)");
    }

    #[test]
    fn submit_token_memory_outside_production_builds() {
        // Non-production → no fail regardless of explicit memory.
        let mut config = AutumnConfig::default();
        config.security.submit_token.backend = Some(crate::config::IdempotencyBackend::Memory);
        let _router = apply_submit_token_middleware(axum::Router::<()>::new(), &config, false)
            .expect("memory submit-token backend outside production must build");
    }

    #[tokio::test]
    async fn build_router_mounts_actuator_at_configured_prefix() {
        let mut config = AutumnConfig::default();
        config.actuator.prefix = "/ops".to_owned();
        config.actuator.sensitive = true;

        let app = build_router(Vec::new(), &config, test_state());

        let prefixed = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/ops/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(prefixed.status(), StatusCode::OK);

        let legacy = app
            .oneshot(
                Request::builder()
                    .uri("/actuator/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(legacy.status(), StatusCode::NOT_FOUND);
    }

    /// Worker-role (#1613) probe-only router: exposes the framework probes and
    /// the actuator, but no user routes. A sample user path 404s.
    #[tokio::test]
    async fn probe_only_router_mounts_probes_and_actuator_but_no_user_routes() {
        let config = AutumnConfig::default();
        let app = try_build_probe_only_router(&config, test_state())
            .expect("probe-only router should build");

        // Probe + actuator paths respond.
        for path in [
            config.health.live_path.as_str(),
            config.health.ready_path.as_str(),
            config.health.startup_path.as_str(),
            config.health.path.as_str(),
            "/actuator/health",
            "/actuator/info",
        ] {
            let response = app
                .clone()
                .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap())
                .await
                .unwrap();
            assert_ne!(
                response.status(),
                StatusCode::NOT_FOUND,
                "probe-only router should serve {path}"
            );
        }

        // A made-up user route is absent (probe-only router has no user table).
        let missing = app
            .oneshot(
                Request::builder()
                    .uri("/definitely-not-a-user-route")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(missing.status(), StatusCode::NOT_FOUND);
    }

    /// Issue #1971: a user route registered at the auto-mounted health path
    /// must WIN. The router build succeeds — no raw axum "Overlapping method
    /// route. Handler for GET /health already exists" panic — the user's own
    /// handler serves `/health`, and the remaining built-in probes (`/live`,
    /// `/ready`, `/startup`) still mount and respond.
    #[tokio::test]
    async fn user_route_at_health_path_overrides_builtin_probe() {
        async fn user_health() -> &'static str {
            "user-health-handler"
        }

        let config = AutumnConfig::default();
        // Precondition: the default health alias is exactly the path we shadow.
        assert_eq!(config.health.path, "/health");

        let route = Route {
            method: http::Method::GET,
            path: "/health",
            handler: axum::routing::get(user_health),
            name: "user_health",
            api_doc: crate::openapi::ApiDoc {
                method: "GET",
                path: "/health",
                operation_id: "user_health",
                success_status: 200,
                ..Default::default()
            },
            repository: None,
            idempotency: crate::route::RouteIdempotency::Direct,
            timeout: crate::route::RouteTimeout::Inherit,
            api_version: None,
            sunset_opt_out: false,
        };

        // Before the fix this panicked inside `axum::Router::route`; now it
        // builds cleanly (`build_router` panics on any RouterBuildError, so a
        // successful return also proves no structured error is raised).
        let app = build_router(vec![route], &config, test_state());

        // `/health` is served by the USER handler, not the framework probe.
        let response = app
            .clone()
            .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();
        assert_eq!(
            &body[..],
            b"user-health-handler",
            "user route must win at the health path"
        );

        // The other built-in probes are untouched and still respond.
        for path in ["/live", "/ready", "/startup"] {
            let resp = app
                .clone()
                .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap())
                .await
                .unwrap();
            assert_ne!(
                resp.status(),
                StatusCode::NOT_FOUND,
                "built-in probe {path} should still be mounted"
            );
        }
    }

    /// The framework-owned widget stylesheet (#1215) is served the same way
    /// as the flash stylesheet: a same-origin, immutably-cached asset — not
    /// inline styles — so a strict `style-src 'self'` CSP still works and the
    /// asset is embeddable in the single binary (#1004) with no loose files.
    #[cfg(feature = "maud")]
    #[tokio::test]
    async fn widgets_css_route_serves_the_shared_stylesheet() {
        let app = build_router(Vec::new(), &AutumnConfig::default(), test_state());

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

        assert_eq!(response.status(), StatusCode::OK);
        let content_type = response
            .headers()
            .get(http::header::CONTENT_TYPE)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(content_type.contains("text/css"), "{content_type}");

        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let body = String::from_utf8(body.to_vec()).unwrap();
        assert!(body.contains(".autumn-field"), "{body}");
        assert!(body.contains(":root"), "{body}");
    }

    /// The widget stylesheet is conditional-GET aware (shared `static_css_response`
    /// helper): a revalidating client sends back the `ETag` it was given and gets
    /// a bodyless `304`, instead of re-downloading the full asset every time the
    /// far-future `Cache-Control` gets bypassed (hard refresh, a CDN stripping
    /// cache headers, etc.).
    #[cfg(feature = "maud")]
    #[tokio::test]
    async fn widgets_css_route_supports_conditional_get() {
        let app = build_router(Vec::new(), &AutumnConfig::default(), test_state());

        let first = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri(crate::ui::WIDGETS_CSS_PATH)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(first.status(), StatusCode::OK);
        let etag = first
            .headers()
            .get(http::header::ETAG)
            .expect("widget stylesheet response should carry an ETag")
            .clone();

        let revalidated = app
            .oneshot(
                Request::builder()
                    .uri(crate::ui::WIDGETS_CSS_PATH)
                    .header(http::header::IF_NONE_MATCH, etag)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(revalidated.status(), StatusCode::NOT_MODIFIED);
        let revalidated_body = axum::body::to_bytes(revalidated.into_body(), usize::MAX)
            .await
            .unwrap();
        assert!(revalidated_body.is_empty());
    }

    /// The widget stylesheet's `ETag` must be weak (`W/"..."`), not strong:
    /// the identity/gzip/br byte streams served under it are not
    /// byte-identical, and a strong `ETag` asserts exactly that (RFC 7232
    /// §2.1).
    #[cfg(feature = "maud")]
    #[tokio::test]
    async fn widgets_css_route_etag_is_weak_not_strong() {
        let app = build_router(Vec::new(), &AutumnConfig::default(), test_state());

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

        let etag = response
            .headers()
            .get(http::header::ETAG)
            .expect("widget stylesheet response should carry an ETag")
            .to_str()
            .unwrap()
            .to_owned();
        assert!(
            etag.starts_with("W/\""),
            "ETag must be weak since encoded variants aren't byte-identical: {etag}"
        );
    }

    /// A client that sends `Accept-Encoding: br` gets the pre-computed brotli
    /// encoding straight back (`Content-Encoding: br`), not a plain body that
    /// the outer `CompressionLayer` then has to compress on the fly.
    #[cfg(feature = "maud")]
    #[tokio::test]
    async fn widgets_css_route_serves_precompressed_brotli_when_accepted() {
        let app = build_router(Vec::new(), &AutumnConfig::default(), test_state());

        let response = app
            .oneshot(
                Request::builder()
                    .uri(crate::ui::WIDGETS_CSS_PATH)
                    .header(http::header::ACCEPT_ENCODING, "br")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_ENCODING)
                .unwrap(),
            "br"
        );
        assert_eq!(
            response.headers().get(http::header::VARY).unwrap(),
            "Accept-Encoding"
        );

        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let mut decoded = Vec::new();
        brotli::BrotliDecompress(&mut std::io::Cursor::new(body.as_ref()), &mut decoded)
            .expect("response body must be valid brotli");
        assert_eq!(String::from_utf8(decoded).unwrap(), crate::ui::WIDGETS_CSS);
    }

    /// Same as the brotli case, for a `gzip`-only client.
    #[cfg(feature = "maud")]
    #[tokio::test]
    async fn widgets_css_route_serves_precompressed_gzip_when_accepted() {
        let app = build_router(Vec::new(), &AutumnConfig::default(), test_state());

        let response = app
            .oneshot(
                Request::builder()
                    .uri(crate::ui::WIDGETS_CSS_PATH)
                    .header(http::header::ACCEPT_ENCODING, "gzip")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_ENCODING)
                .unwrap(),
            "gzip"
        );

        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let mut gz = flate2::read::GzDecoder::new(body.as_ref());
        let mut output = String::new();
        std::io::Read::read_to_string(&mut gz, &mut output)
            .expect("response body must be valid gzip");
        assert_eq!(output, crate::ui::WIDGETS_CSS);
    }

    /// `q=0` is an explicit opt-out (RFC 7231 §5.3.4): a client that lists
    /// `br` but disqualifies it must fall back to the identity encoding
    /// rather than being served brotli anyway.
    #[cfg(feature = "maud")]
    #[tokio::test]
    async fn widgets_css_route_honors_q_zero_opt_out() {
        let app = build_router(Vec::new(), &AutumnConfig::default(), test_state());

        let response = app
            .oneshot(
                Request::builder()
                    .uri(crate::ui::WIDGETS_CSS_PATH)
                    .header(http::header::ACCEPT_ENCODING, "br;q=0, gzip")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_ENCODING)
                .unwrap(),
            "gzip"
        );
    }

    /// No `Accept-Encoding` header at all means identity — no
    /// `Content-Encoding` header, plain-text body (matches the existing
    /// `widgets_css_route_serves_the_shared_stylesheet` assertions).
    #[cfg(feature = "maud")]
    #[tokio::test]
    async fn widgets_css_route_serves_identity_with_no_accept_encoding() {
        let app = build_router(Vec::new(), &AutumnConfig::default(), test_state());

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

        assert_eq!(response.status(), StatusCode::OK);
        assert!(
            !response
                .headers()
                .contains_key(http::header::CONTENT_ENCODING)
        );
    }

    /// Pins the production access-log wiring (#999): the layer is applied in
    /// `apply_startup_barrier`, outside the barrier itself, so even requests
    /// rejected with 503 before the app router runs emit one access event
    /// carrying the status the client receives.
    #[test]
    fn startup_barrier_503s_are_access_logged() {
        use tracing_subscriber::layer::SubscriberExt as _;

        #[derive(Clone, Default)]
        struct Capture {
            events: Arc<std::sync::Mutex<Vec<std::collections::BTreeMap<String, String>>>>,
        }
        struct Visitor<'a>(&'a mut std::collections::BTreeMap<String, String>);
        impl tracing::field::Visit for Visitor<'_> {
            fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
                self.0.insert(field.name().to_owned(), format!("{value:?}"));
            }
            fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
                self.0.insert(field.name().to_owned(), value.to_string());
            }
        }
        impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for Capture {
            fn on_event(
                &self,
                event: &tracing::Event<'_>,
                _ctx: tracing_subscriber::layer::Context<'_, S>,
            ) {
                if event.metadata().target() != crate::middleware::ACCESS_LOG_TARGET {
                    return;
                }
                let mut fields = std::collections::BTreeMap::new();
                event.record(&mut Visitor(&mut fields));
                self.events.lock().unwrap().push(fields);
            }
        }

        let capture = Capture::default();
        let events = Arc::clone(&capture.events);
        let subscriber = tracing_subscriber::registry().with(capture);

        tracing::subscriber::with_default(subscriber, || {
            // With startup incomplete, the barrier rejects non-probe requests
            // with 503 before the app router runs.
            let state = AppState::for_test()
                .with_profile("test")
                .with_startup_complete(false);
            let app = build_router(Vec::new(), &AutumnConfig::default(), state);
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .unwrap();

            // `tracing` callsite `Interest` is a single value cached per
            // callsite across the WHOLE PROCESS, combined from every
            // concurrently active dispatcher. `cargo test` runs this
            // alongside thousands of other unit tests in the same binary,
            // many of which touch the same `autumn::access` callsite without
            // an active capturing subscriber; the combined interest can
            // occasionally end up (re-)cached as "not interested" in the
            // narrow window between rebuilding it and firing the request
            // below. Rebuilding and re-firing converges almost immediately in
            // practice, so retry a few times rather than flake.
            let mut response = None;
            for attempt in 1..=5 {
                tracing::callsite::rebuild_interest_cache();
                let resp = rt.block_on(async {
                    app.clone()
                        .oneshot(
                            Request::builder()
                                .uri("/not-a-probe")
                                .body(Body::empty())
                                .unwrap(),
                        )
                        .await
                        .unwrap()
                });
                let captured = !events.lock().unwrap().is_empty();
                response = Some(resp);
                if captured {
                    break;
                }
                assert!(
                    attempt < 5,
                    "access-log event was not captured after {attempt} attempts \
                     (tracing interest-cache race with a concurrent test)"
                );
            }
            assert_eq!(response.unwrap().status(), StatusCode::SERVICE_UNAVAILABLE);
        });

        let events = events.lock().unwrap().clone();
        assert_eq!(
            events.len(),
            1,
            "a barrier-rejected request should emit one access event: {events:?}"
        );
        assert_eq!(events[0].get("status").map(String::as_str), Some("503"));
        assert!(
            !events[0].contains_key("request_id"),
            "barrier short-circuits before RequestIdLayer, so no request id"
        );
    }

    /// Pins the Server-Timing fallback wiring (#1348): the fallback layer is
    /// applied in `apply_startup_barrier`, outside the barrier itself, so a
    /// request rejected with 503 before the app router (and its primary
    /// `ServerTimingLayer`) runs still carries a `Server-Timing` header. Without
    /// the fallback the header is silently dropped on these short-circuits.
    #[tokio::test]
    async fn startup_barrier_503s_carry_server_timing_header() {
        // Startup incomplete → the barrier 503s non-probe requests before the
        // app router (and the primary ServerTimingLayer) ever run.
        let state = AppState::for_test()
            .with_profile("test")
            .with_startup_complete(false);
        let mut config = AutumnConfig::default();
        config.observability.server_timing = Some(true);

        let app = build_router(Vec::new(), &config, state);
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/not-a-probe")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        let header = response
            .headers()
            .get("server-timing")
            .expect("startup 503 short-circuit should still carry Server-Timing via the fallback")
            .to_str()
            .expect("server-timing header should be valid ASCII");
        assert!(
            header.starts_with("total;dur="),
            "fallback should emit a `total` metric, got {header:?}"
        );
        // Exactly one metric on the short-circuit path — the primary never ran,
        // so there is no second `total`.
        assert_eq!(
            header.matches("total;dur=").count(),
            1,
            "short-circuit response must carry a single total metric: {header:?}"
        );
    }

    #[test]
    fn try_build_router_rejects_invalid_session_backend_config() {
        let mut config = AutumnConfig::default();
        config.session.backend = crate::session::SessionBackend::Redis;

        let error = try_build_router(Vec::new(), &config, test_state())
            .expect_err("missing redis config should fail checked router build");

        assert!(matches!(
            error,
            RouterBuildError::InvalidSessionBackend(
                crate::session::SessionBackendConfigError::MissingRedisUrl
            )
        ));
    }

    #[test]
    fn try_build_router_with_static_rejects_invalid_session_backend_config() {
        let mut config = AutumnConfig::default();
        config.session.backend = crate::session::SessionBackend::Redis;

        let error = try_build_router_with_static(Vec::new(), &config, test_state(), None)
            .expect_err("missing redis config should fail checked static router build");

        assert!(matches!(
            error,
            RouterBuildError::InvalidSessionBackend(
                crate::session::SessionBackendConfigError::MissingRedisUrl
            )
        ));
    }

    #[test]
    fn try_build_router_returns_error_for_probe_actuator_path_overlap() {
        let mut config = AutumnConfig::default();
        config.actuator.prefix = "/".to_owned();

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            try_build_router(Vec::new(), &config, test_state())
        }));

        assert!(result.is_ok(), "try_build_router panicked on route overlap");
        assert!(
            result.unwrap().is_err(),
            "route overlap should be reported as a checked router build error"
        );
    }

    /// Regression for issue #1971 P2: when a user route already owns `/health`,
    /// the built-in probe cedes that path (#1971) — but a root-prefix actuator
    /// still normalizes its own `GET /health` onto it. The ceded probe path must
    /// remain visible to the actuator overlap guard so this surfaces as a checked
    /// `FrameworkRouteOverlap` rather than an axum construction panic (matching
    /// the no-user-route case in
    /// `try_build_router_returns_error_for_probe_actuator_path_overlap`).
    #[test]
    fn probe_actuator_overlap_detected_when_user_route_owns_probe_path() {
        async fn user_health() -> &'static str {
            "user-health-handler"
        }

        let mut config = AutumnConfig::default();
        config.actuator.prefix = "/".to_owned();
        // Precondition: the user route, the ceded probe, and the actuator all
        // land on exactly `/health`.
        assert_eq!(config.health.path, "/health");

        let route = Route {
            method: http::Method::GET,
            path: "/health",
            handler: axum::routing::get(user_health),
            name: "user_health",
            api_doc: crate::openapi::ApiDoc {
                method: "GET",
                path: "/health",
                operation_id: "user_health",
                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 result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            try_build_router(vec![route], &config, test_state())
        }));

        assert!(
            result.is_ok(),
            "try_build_router panicked instead of returning a checked overlap error"
        );
        let build = result.unwrap();
        assert!(
            matches!(
                &build,
                Err(RouterBuildError::FrameworkRouteOverlap {
                    path,
                    incoming: "actuator endpoint",
                    ..
                }) if path == "/health"
            ),
            "root-prefix actuator over a user-owned probe path must yield a checked \
             FrameworkRouteOverlap for /health, got: {:?}",
            build.as_ref().map(|_| "Ok(router)"),
        );
    }

    #[tokio::test]
    async fn apply_cors_middleware_skipped_when_no_origins() {
        let config = AutumnConfig::default();
        assert!(config.cors.allowed_origins.is_empty());

        let base: axum::Router<AppState> =
            axum::Router::new().route("/test", axum::routing::get(|| async { "ok" }));
        let router = apply_cors_middleware(base, &config).with_state(test_state());

        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(),
            "CORS header must be absent when no origins are configured"
        );
    }

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

        let base: axum::Router<AppState> =
            axum::Router::new().route("/test", axum::routing::get(|| async { "ok" }));
        let router = apply_cors_middleware(base, &config).with_state(test_state());

        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_some(),
            "CORS header must be present when origins are configured"
        );
    }

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

        let base: axum::Router<AppState> =
            axum::Router::new().route("/api/widgets", axum::routing::post(|| async { "ok" }));
        let router = apply_cors_middleware(base, &config).with_state(test_state());

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

        let headers = response.headers();
        assert_eq!(
            headers
                .get("access-control-allow-origin")
                .and_then(|v| v.to_str().ok()),
            Some("https://example.com"),
            "preflight must echo the allowed origin"
        );
        assert!(
            headers.get("access-control-allow-methods").is_some(),
            "preflight must advertise allowed methods"
        );
        assert!(
            headers.get("access-control-allow-headers").is_some(),
            "preflight must advertise allowed headers"
        );
        assert!(
            headers.get("access-control-max-age").is_some(),
            "preflight must advertise max-age so browsers can cache it"
        );
    }

    #[tokio::test]
    async fn apply_csrf_middleware_skipped_when_disabled() {
        let config = AutumnConfig::default();
        assert!(!config.security.csrf.enabled);

        let base: axum::Router<AppState> =
            axum::Router::new().route("/form", axum::routing::post(|| async { "posted" }));
        let router = apply_csrf_middleware(base, &config, None).with_state(test_state());

        // Without CSRF the POST should pass through with no CSRF-specific response
        let response = router
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/form")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

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

    #[tokio::test]
    async fn apply_rate_limit_middleware_skipped_when_disabled() {
        let config = AutumnConfig::default();
        assert!(!config.security.rate_limit.enabled);

        let base: axum::Router<AppState> =
            axum::Router::new().route("/ping", axum::routing::get(|| async { "pong" }));
        let state = test_state();
        let router = apply_rate_limit_middleware(base, &config, &state).with_state(state.clone());

        // Fire several rapid requests; none should be throttled.
        for _ in 0..5 {
            let response = router
                .clone()
                .oneshot(Request::builder().uri("/ping").body(Body::empty()).unwrap())
                .await
                .unwrap();
            assert_eq!(response.status(), StatusCode::OK);
        }
    }

    #[tokio::test]
    async fn apply_rate_limit_middleware_returns_429_when_exhausted() {
        let mut config = AutumnConfig::default();
        config.security.rate_limit.enabled = true;
        config.security.rate_limit.requests_per_second = 0.1;
        config.security.rate_limit.burst = 1;
        config.security.rate_limit.trust_forwarded_headers = true;

        let base: axum::Router<AppState> =
            axum::Router::new().route("/ping", axum::routing::get(|| async { "pong" }));
        let state = test_state();
        let router = apply_rate_limit_middleware(base, &config, &state).with_state(state.clone());

        let ok = router
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/ping")
                    .header("X-Forwarded-For", "203.0.113.9")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(ok.status(), StatusCode::OK);

        let blocked = router
            .oneshot(
                Request::builder()
                    .uri("/ping")
                    .header("X-Forwarded-For", "203.0.113.9")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(blocked.status(), StatusCode::TOO_MANY_REQUESTS);
        assert!(blocked.headers().get("retry-after").is_some());
    }

    #[cfg(feature = "mcp")]
    #[tokio::test]
    async fn mcp_envelope_is_gated_during_maintenance() {
        use crate::maintenance::{MaintenanceConfig, MaintenanceState};

        // Trust the host the control request sends so that, with maintenance
        // off, the envelope's host guard lets `initialize` through.
        let mut config = AutumnConfig::default();
        config.security.trusted_hosts.hosts = vec!["app.example".to_owned()];

        let wiring = crate::mcp::McpWiring {
            cors: crate::config::CorsConfig::default(),
            trusted_hosts: TrustedHostPolicy::from_config(&config),
            tenant_header: None,
            csrf_header: "x-csrf-token".to_owned(),
            envelope_rate_limited: false,
            envelope_load_shed: false,
        };
        let mcp_router =
            crate::mcp::build_mcp_router("/mcp", Vec::new(), axum::Router::new(), wiring, None);

        let initialize = || {
            Request::builder()
                .method("POST")
                .uri("/mcp")
                .header("host", "app.example")
                .header("content-type", "application/json")
                .body(Body::from(
                    serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize"}).to_string(),
                ))
                .unwrap()
        };

        // Maintenance ON: the late-mounted envelope returns the documented 503
        // instead of serving the catalog — the gap this layer closes.
        let state = test_state();
        let maintenance = MaintenanceState::new();
        maintenance.enable(MaintenanceConfig::default());
        state.insert_extension(maintenance);
        let gated = mcp_router
            .clone()
            .layer(build_maintenance_layer(&config, &state))
            .with_state(state);
        let resp = gated.oneshot(initialize()).await.unwrap();
        assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);

        // Maintenance OFF (no enabled state): the same envelope serves
        // `initialize` normally, confirming the gate is the only difference.
        let state = test_state();
        let open = mcp_router
            .layer(build_maintenance_layer(&config, &state))
            .with_state(state);
        let resp = open.oneshot(initialize()).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[cfg(feature = "mail")]
    fn dev_mail_preview_config(dir: &std::path::Path) -> AutumnConfig {
        let mut config = AutumnConfig {
            profile: Some("dev".to_owned()),
            mail: crate::mail::MailConfig {
                transport: crate::mail::Transport::File,
                file_dir: dir.to_path_buf(),
                ..Default::default()
            },
            ..Default::default()
        };
        config.security.trusted_hosts.hosts = vec!["example.com".to_owned()];
        config
    }

    #[cfg(any(feature = "mail", feature = "maud"))]
    async fn response_text(response: axum::response::Response) -> String {
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body should collect");
        String::from_utf8(body.to_vec()).expect("body should be utf8")
    }

    #[cfg(feature = "mail")]
    #[tokio::test]
    async fn build_router_mounts_dev_mail_preview_empty_state_for_file_transport() {
        let dir = tempfile::tempdir().expect("tempdir");
        let config = dev_mail_preview_config(dir.path());
        let router = build_router(Vec::new(), &config, test_state());

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

        assert_eq!(response.status(), StatusCode::OK);
        let body = response_text(response).await;
        assert!(
            body.contains("No captured emails"),
            "missing empty state: {body}"
        );
        assert!(
            body.contains("mail.transport = &quot;file&quot;"),
            "empty state should explain capture setup: {body}"
        );
    }

    #[cfg(feature = "mail")]
    #[tokio::test]
    async fn build_router_lists_captured_mail_newest_first() {
        let dir = tempfile::tempdir().expect("tempdir");
        let older = dir.path().join("older.eml");
        let newer = dir.path().join("newer.eml");
        std::fs::write(
            &older,
            "To: first@example.com\nSubject: First\nDate: Tue, 05 May 2026 10:00:00 +0000\nMessage-Id: <first@example.com>\n\nfirst body\n",
        )
        .expect("write older eml");
        std::fs::write(
            &newer,
            "To: second@example.com\nSubject: Second\nDate: Tue, 05 May 2026 10:01:00 +0000\nMessage-Id: <second@example.com>\n\nsecond body\n",
        )
        .expect("write newer eml");
        filetime::set_file_mtime(&older, filetime::FileTime::from_unix_time(100, 0))
            .expect("set older mtime");
        filetime::set_file_mtime(&newer, filetime::FileTime::from_unix_time(200, 0))
            .expect("set newer mtime");

        let config = dev_mail_preview_config(dir.path());
        let router = build_router(Vec::new(), &config, test_state());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/_autumn/mail")
                    .header("host", "example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = response_text(response).await;
        let second = body.find("Second").expect("newer subject should render");
        let first = body.find("First").expect("older subject should render");
        assert!(second < first, "newest message should render first: {body}");
        assert!(
            body.contains("second@example.com"),
            "missing To column: {body}"
        );
        assert!(
            body.contains("Timestamp"),
            "missing timestamp column: {body}"
        );
    }

    #[cfg(feature = "mail")]
    #[tokio::test]
    async fn build_router_mail_preview_detail_renders_html_in_sandboxed_iframe() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("detail.eml"),
            "From: Autumn <noreply@example.com>\nTo: ada@example.com\nReply-To: support@example.com\nSubject: Reset\nDate: Tue, 05 May 2026 10:00:00 +0000\nMessage-Id: <reset@example.com>\nMIME-Version: 1.0\nContent-Type: multipart/alternative; boundary=\"autumn-mail\"\n\n--autumn-mail\nContent-Type: text/plain; charset=utf-8\n\nPlain reset\n--autumn-mail\nContent-Type: text/html; charset=utf-8\n\n<h1>Hello iframe</h1>\n--autumn-mail--\n",
        )
        .expect("write detail eml");

        let config = dev_mail_preview_config(dir.path());
        let router = build_router(Vec::new(), &config, test_state());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/_autumn/mail/messages/detail.eml")
                    .header("host", "example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = response_text(response).await;
        assert!(body.contains("<iframe"), "missing iframe: {body}");
        assert!(body.contains("sandbox"), "iframe must be sandboxed: {body}");
        assert!(body.contains("Hello iframe"), "missing html body: {body}");
        assert!(body.contains("Plain text"), "missing text toggle: {body}");
        assert!(body.contains("Headers"), "missing headers toggle: {body}");
        assert!(
            body.contains("Raw .eml"),
            "missing raw source toggle: {body}"
        );
        assert!(
            body.contains("Message-Id"),
            "missing message id header: {body}"
        );
    }

    #[cfg(feature = "mail")]
    #[tokio::test]
    async fn build_router_does_not_mount_mail_preview_outside_dev() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut config = dev_mail_preview_config(dir.path());
        config.profile = Some("prod".to_owned());
        let router = build_router(Vec::new(), &config, test_state());

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

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

    // ── Widget story gallery mount gating (issue #1526) ─────────────────────
    //
    // Unlike the dev-only mail preview, `/_stories` is opt-in in ANY profile
    // via `[stories] enabled = true` (default false): mounting is gated only
    // on the resolved config flag, while handlers read the `StoryRegistry`
    // from the AppState extension installed by `with_story_gallery`.

    #[cfg(feature = "maud")]
    fn story_gallery_config() -> AutumnConfig {
        let mut config = AutumnConfig::default();
        config.stories.enabled = true;
        config.security.trusted_hosts.hosts = vec!["example.com".to_owned()];
        config
    }

    #[cfg(feature = "maud")]
    fn stories_state_with_builtin() -> AppState {
        let state = test_state();
        state.insert_extension(crate::stories::builtin());
        state
    }

    #[cfg(feature = "maud")]
    async fn get_with_host(router: axum::Router, uri: &str) -> axum::response::Response {
        router
            .oneshot(
                Request::builder()
                    .uri(uri)
                    .header("host", "example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap()
    }

    /// T1 (AC4/AC5): with `[stories] enabled = true` and the builtin registry
    /// installed, the grouped index is served at `/_stories` and pulls in the
    /// framework widget stylesheet.
    #[cfg(feature = "maud")]
    #[tokio::test]
    async fn build_router_mounts_story_gallery_when_enabled() {
        let router = build_router(
            Vec::new(),
            &story_gallery_config(),
            stories_state_with_builtin(),
        );

        let response = get_with_host(router, crate::stories::STORIES_PATH).await;
        assert_eq!(response.status(), StatusCode::OK);
        let body = response_text(response).await;
        assert!(
            body.contains("Data table"),
            "index should list builtin story names: {body}"
        );
        assert!(
            body.contains("autumn-widgets.css"),
            "index should link the framework widget stylesheet: {body}"
        );
    }

    /// T2 (AC4): the detail route serves the live render plus Source and
    /// Rendered HTML tabs.
    #[cfg(feature = "maud")]
    #[tokio::test]
    async fn story_detail_route_serves_render_source_and_html() {
        let router = build_router(
            Vec::new(),
            &story_gallery_config(),
            stories_state_with_builtin(),
        );

        let response = get_with_host(router, "/_stories/data-table").await;
        assert_eq!(response.status(), StatusCode::OK);
        let body = response_text(response).await;
        assert!(
            body.contains("<table"),
            "detail page must contain the live data_table render: {body}"
        );
        assert!(
            body.contains("data_table("),
            "detail page must show the source snippet that produced the render: {body}"
        );
        assert!(
            body.contains("Rendered HTML"),
            "detail page must offer the rendered-HTML tab: {body}"
        );
        assert!(
            body.contains("Source"),
            "detail page must offer the source tab: {body}"
        );
    }

    /// T3 (AC4): a mounted gallery 404s unknown slugs while the index stays up.
    #[cfg(feature = "maud")]
    #[tokio::test]
    async fn story_detail_unknown_slug_is_404() {
        let router = build_router(
            Vec::new(),
            &story_gallery_config(),
            stories_state_with_builtin(),
        );

        let missing = get_with_host(router.clone(), "/_stories/nope").await;
        assert_eq!(missing.status(), StatusCode::NOT_FOUND);

        let index = get_with_host(router, "/_stories").await;
        assert_eq!(
            index.status(),
            StatusCode::OK,
            "index route must exist even when a slug misses"
        );
    }

    /// T4 (AC5/AC6): off by default — no `[stories] enabled = true`, no
    /// routes, even when a registry extension is installed.
    #[cfg(feature = "maud")]
    #[tokio::test]
    async fn build_router_omits_story_gallery_by_default() {
        let mut config = AutumnConfig::default();
        assert!(
            !config.stories.enabled,
            "stories gallery must be off by default"
        );
        config.security.trusted_hosts.hosts = vec!["example.com".to_owned()];

        let router = build_router(Vec::new(), &config, stories_state_with_builtin());
        let response = get_with_host(router, "/_stories").await;
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    /// Loads a layered `autumn.toml` for `profile` via `MockEnv` (no process
    /// env, no `set_current_dir`) and reports the status `/_stories` returns.
    #[cfg(feature = "maud")]
    async fn stories_status_for_layered_profile(toml: &str, profile: &str) -> StatusCode {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("autumn.toml"), toml).expect("write autumn.toml");
        let env = crate::config::MockEnv::new()
            .with("AUTUMN_MANIFEST_DIR", dir.path().to_str().unwrap())
            .with("AUTUMN_ENV", profile);
        let mut config = AutumnConfig::load_with_env(&env).expect("layered config should load");
        config.security.trusted_hosts.hosts = vec!["example.com".to_owned()];

        let router = build_router(Vec::new(), &config, stories_state_with_builtin());
        get_with_host(router, "/_stories").await.status()
    }

    /// T5 (AC6): profile-scoped gating works both ways through the existing
    /// config layering — routes mount iff the resolved flag is true.
    #[cfg(feature = "maud")]
    #[tokio::test]
    async fn story_routes_mount_iff_resolved_profile_flag() {
        // Private app: dev-only gallery, absent in prod.
        let dev_only = r"
[stories]
enabled = false

[profile.dev.stories]
enabled = true
";
        assert_eq!(
            stories_status_for_layered_profile(dev_only, "dev").await,
            StatusCode::OK,
            "dev profile override must mount the gallery"
        );
        assert_eq!(
            stories_status_for_layered_profile(dev_only, "prod").await,
            StatusCode::NOT_FOUND,
            "prod must not mount the gallery when only dev enables it"
        );

        // Public showcase: enabled in prod, absent in dev.
        let public_showcase = r"
[stories]
enabled = false

[profile.prod.stories]
enabled = true
";
        assert_eq!(
            stories_status_for_layered_profile(public_showcase, "prod").await,
            StatusCode::OK,
            "prod profile override must mount the gallery for a public showcase"
        );
        assert_eq!(
            stories_status_for_layered_profile(public_showcase, "dev").await,
            StatusCode::NOT_FOUND,
            "dev must not mount the gallery when only prod enables it"
        );
    }

    /// T6 (AC7): a custom app story registered via
    /// `StoryGallery::builtin().extend(...)` is served alongside builtins.
    #[cfg(feature = "maud")]
    #[tokio::test]
    async fn custom_story_served_alongside_builtins() {
        let custom = crate::stories::story! {
            "App",
            "Greeting",
            {
                maud::html! { span class="app-greeting" { "hi from the app" } }
            }
        };
        let state = test_state();
        state.insert_extension(
            crate::stories::StoryGallery::builtin()
                .extend([custom])
                .into_registry(),
        );

        let router = build_router(Vec::new(), &story_gallery_config(), state);

        let detail = get_with_host(router.clone(), "/_stories/greeting").await;
        assert_eq!(detail.status(), StatusCode::OK);
        let body = response_text(detail).await;
        assert!(
            body.contains("hi from the app"),
            "custom story must render at its slug: {body}"
        );

        let index = get_with_host(router, "/_stories").await;
        let body = response_text(index).await;
        assert!(
            body.contains("Greeting"),
            "index must list the custom story: {body}"
        );
        assert!(
            body.contains("App"),
            "index must show the custom story's group: {body}"
        );
        assert!(
            body.contains("Data table"),
            "builtins must still be listed alongside the custom story: {body}"
        );
    }

    /// Review follow-up (#1526): with `security.headers.csp_nonce.enabled =
    /// true` the default CSP's `style-src` drops `'unsafe-inline'` in favor of
    /// a per-request nonce, so the gallery's inline `<style>` must carry the
    /// exact nonce the CSP header advertises or browsers block all of the
    /// gallery chrome CSS.
    #[cfg(feature = "maud")]
    #[tokio::test]
    async fn story_pages_inline_style_carries_csp_header_nonce() {
        let mut config = story_gallery_config();
        config.security.headers.csp_nonce.enabled = true;

        let router = build_router(Vec::new(), &config, stories_state_with_builtin());

        for uri in ["/_stories", "/_stories/data-table"] {
            let response = get_with_host(router.clone(), uri).await;
            assert_eq!(response.status(), StatusCode::OK);

            let csp = response
                .headers()
                .get("content-security-policy")
                .expect("CSP header must be present")
                .to_str()
                .unwrap()
                .to_owned();
            let nonce = csp
                .split("'nonce-")
                .nth(1)
                .and_then(|rest| rest.split('\'').next())
                .unwrap_or_else(|| panic!("CSP header must advertise a nonce: {csp}"))
                .to_owned();
            assert!(!nonce.is_empty(), "advertised nonce must be non-empty");

            let body = response_text(response).await;
            assert!(
                body.contains(&format!(r#"<style nonce="{nonce}">"#)),
                "{uri} inline style must carry the CSP header nonce {nonce}: {body}"
            );
        }
    }

    /// T17 (AC5, R12): enabled config but no registry extension (the user
    /// forgot `with_story_gallery`) serves a friendly empty state, not a 500.
    #[cfg(feature = "maud")]
    #[tokio::test]
    async fn enabled_without_registry_shows_empty_state() {
        let router = build_router(Vec::new(), &story_gallery_config(), test_state());

        let response = get_with_host(router, "/_stories").await;
        assert_eq!(response.status(), StatusCode::OK);
        let body = response_text(response).await;
        assert!(
            body.contains("with_story_gallery"),
            "empty state should point at AppBuilder::with_story_gallery: {body}"
        );
    }

    #[tokio::test]
    async fn apply_csrf_middleware_blocks_without_token_when_enabled() {
        let mut config = AutumnConfig::default();
        config.security.csrf.enabled = true;

        let base: axum::Router<AppState> =
            axum::Router::new().route("/form", axum::routing::post(|| async { "posted" }));
        let router = apply_csrf_middleware(base, &config, None).with_state(test_state());

        // POST without CSRF token should be rejected
        let response = router
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/form")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_ne!(
            response.status(),
            StatusCode::OK,
            "POST without CSRF token should be rejected when CSRF is enabled"
        );
    }

    #[test]
    fn join_nested_path_normalizes_like_axum() {
        // Reviewer's reported case: scope "/api" + child "/" must
        // produce "/api", not "/api/" — otherwise a user-configured
        // openapi_json_path("/api") won't match the effective mount
        // point and the collision check is unreliable.
        assert_eq!(super::join_nested_path("/api", "/"), "/api");
        // Trailing slash on the prefix is preserved for the root child:
        // axum mounts `nest("/api/", route("/"))` at "/api/" and reports
        // `MatchedPath` as "/api/" (verified by
        // `join_nested_path_matches_axum_matched_path`), so the joined key
        // must keep the slash or the runtime lookup misses.
        assert_eq!(super::join_nested_path("/api/", "/"), "/api/");
        // Normal case: prefix + child.
        assert_eq!(super::join_nested_path("/api", "/users"), "/api/users");
        // Trailing slash on prefix + child starting with slash doesn't
        // produce doubled slashes.
        assert_eq!(super::join_nested_path("/api/", "/users"), "/api/users");
        // Root prefix handles sensibly.
        assert_eq!(super::join_nested_path("", "/"), "/");
        assert_eq!(super::join_nested_path("", "/users"), "/users");
    }

    /// Pins `join_nested_path` to axum's real `MatchedPath` so the per-route
    /// timeout table (and the `OpenAPI` collision check) key by exactly the
    /// string the runtime looks up. The trailing-slash root child is the
    /// subtle case: `nest("/api/", route("/"))` is served at "/api/", not
    /// "/api".
    #[tokio::test]
    async fn join_nested_path_matches_axum_matched_path() {
        use axum::routing::get;
        async fn matched(mp: Option<axum::extract::MatchedPath>) -> String {
            mp.map(|m| m.as_str().to_owned()).unwrap_or_default()
        }
        // (nest prefix, child route, request path that reaches the child)
        for (prefix, child, req) in [
            ("/api", "/", "/api"),
            ("/api/", "/", "/api/"),
            ("/api", "/users", "/api/users"),
            ("/api/", "/users", "/api/users"),
        ] {
            let sub = axum::Router::new().route(child, get(matched));
            let app: axum::Router = axum::Router::new().nest(prefix, sub);
            let resp = tower::ServiceExt::oneshot(
                app,
                axum::http::Request::builder()
                    .uri(req)
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
            assert_eq!(resp.status(), http::StatusCode::OK, "{prefix} + {child}");
            let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
                .await
                .unwrap();
            let axum_matched = String::from_utf8(body.to_vec()).unwrap();
            assert_eq!(
                super::join_nested_path(prefix, child),
                axum_matched,
                "join_nested_path must equal axum MatchedPath for nest({prefix:?}, {child:?})"
            );
        }
    }

    #[cfg(feature = "openapi")]
    #[tokio::test]
    async fn try_build_router_detects_scoped_root_collision() {
        // Scope "/api" + child "/" mounts axum's handler at "/api"
        // (not "/api/"). The collision check must use the same
        // normalization or we'd miss this overlap.
        use crate::openapi::{ApiDoc, OpenApiConfig};
        async fn child() -> &'static str {
            "inner"
        }
        let group = crate::app::ScopedGroup {
            prefix: "/api".to_owned(),
            routes: vec![Route {
                method: http::Method::GET,
                path: "/",
                handler: axum::routing::get(child),
                name: "root",
                api_doc: ApiDoc {
                    method: "GET",
                    path: "/",
                    operation_id: "root",
                    success_status: 200,
                    ..Default::default()
                },
                repository: None,
                idempotency: crate::route::RouteIdempotency::Direct,
                timeout: crate::route::RouteTimeout::Inherit,
                api_version: None,
                sunset_opt_out: false,
            }],
            source: crate::route_listing::RouteSource::User,
            apply_layer: Box::new(|r| r),
        };

        let openapi = OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("/api");
        let config = AutumnConfig::default();
        let ctx = RouterContext {
            exception_filters: Vec::new(),
            scoped_groups: vec![group],
            merge_routers: Vec::new(),
            nest_routers: Vec::new(),
            custom_layers: Vec::new(),
            static_gate_layers: Vec::new(),
            #[cfg(feature = "maud")]
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(Vec::new(), &config, test_state(), ctx)
            .expect_err("scope '/api' + child '/' should collide with openapi path '/api'");
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision {
                field: "openapi_json_path",
                ..
            }
        ));
    }

    /// The widget stylesheet route merges a GET unconditionally whenever
    /// `maud` is on, before the late-merged `OpenAPI` router — an
    /// `openapi_json_path` configured to the same path must be rejected by
    /// the preflight, not panic in `router.merge`.
    #[cfg(all(feature = "openapi", feature = "maud"))]
    #[test]
    fn try_build_router_detects_widgets_css_path_collision() {
        use crate::openapi::OpenApiConfig;

        let openapi =
            OpenApiConfig::new("Demo", "1.0.0").openapi_json_path(crate::ui::WIDGETS_CSS_PATH);
        let config = AutumnConfig::default();
        let ctx = RouterContext {
            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(),
            #[cfg(feature = "maud")]
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(Vec::new(), &config, test_state(), ctx).expect_err(
            "openapi_json_path colliding with the widget stylesheet route should be rejected",
        );
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision {
                field: "openapi_json_path",
                ..
            }
        ));
    }

    /// Same as above for the flash stylesheet route (pre-existing gap, same
    /// class of bug: the flash CSS route was also missing from
    /// `collect_claimed_get_paths`).
    #[cfg(all(feature = "openapi", feature = "flash"))]
    #[test]
    fn try_build_router_detects_flash_css_path_collision() {
        use crate::openapi::OpenApiConfig;

        let openapi =
            OpenApiConfig::new("Demo", "1.0.0").openapi_json_path(crate::flash::FLASH_CSS_PATH);
        let config = AutumnConfig::default();
        let ctx = RouterContext {
            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(),
            #[cfg(feature = "maud")]
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(Vec::new(), &config, test_state(), ctx).expect_err(
            "openapi_json_path colliding with the flash stylesheet route should be rejected",
        );
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision {
                field: "openapi_json_path",
                ..
            }
        ));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn extract_path_params_matches_macro_behavior() {
        // Normal multi-param routes.
        assert_eq!(
            super::extract_path_params("/orgs/{org_id}/users/{id}"),
            vec!["org_id".to_owned(), "id".to_owned()]
        );
        assert_eq!(
            super::extract_path_params("/users/{id}/posts/{slug}"),
            vec!["id".to_owned(), "slug".to_owned()]
        );
        assert!(super::extract_path_params("/static").is_empty());

        // `:constraint` suffixes are stripped to the bare name.
        assert_eq!(
            super::extract_path_params("/users/{id:[0-9]+}"),
            vec!["id".to_owned()]
        );
        // Regex constraint containing its own braces still yields just `id`.
        assert_eq!(
            super::extract_path_params("{id:[0-9]{1,3}}"),
            vec!["id".to_owned()]
        );

        // Escaped literal braces (`{{` / `}}`) are matchit literals, NOT
        // params, and must emit nothing (mirrors the macro's escape skip).
        assert!(super::extract_path_params("{{hello}}").is_empty());
        assert_eq!(
            super::extract_path_params("{{literal}}/{id}"),
            vec!["id".to_owned()]
        );

        // #1721 unbalanced/malformed cases: no phantom or brace-carrying params.
        assert!(super::extract_path_params("{{}").is_empty());
        assert!(super::extract_path_params("{a{b}").is_empty());
        assert!(super::extract_path_params("{").is_empty());
        assert!(super::extract_path_params("}").is_empty());
        assert!(super::extract_path_params("{}").is_empty());
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn extract_path_params_handles_unbalanced_braces() {
        // Regression for #1721: unbalanced/malformed braces must never yield a
        // param name that still contains a brace character. The brace-free
        // guard drops any candidate whose inner segment retains a stray brace,
        // so the emitted names are always non-empty and brace-free (and stray
        // braces yield no spurious params).
        for path in ["{{}", "{", "}", "{a{b}"] {
            for name in super::extract_path_params(path) {
                assert!(
                    !name.contains('{') && !name.contains('}'),
                    "param name should be brace-free for {path:?}: {name:?}"
                );
                assert!(
                    !name.is_empty(),
                    "param name should be non-empty for {path:?}"
                );
            }
        }
        // `"{{}"` yields no param: the leading `{{` is an escaped literal brace
        // that is skipped, leaving only a stray `}`.
        assert!(super::extract_path_params("{{}").is_empty());
        // `"{a{b}"` yields no param: the inner segment `"a{b"` still holds a
        // brace, so the brace-free guard drops it.
        assert!(super::extract_path_params("{a{b}").is_empty());
    }

    #[cfg(feature = "openapi")]
    #[tokio::test]
    async fn openapi_merges_scoped_prefix_path_params() {
        use crate::openapi::{ApiDoc, OpenApiConfig};

        // Scope prefix has `{org_id}`; the child route has `{id}`. The
        // generated ApiDoc must declare BOTH parameters, or Swagger
        // validators reject the document for referencing undeclared
        // path params.
        async fn handler() -> &'static str {
            "ok"
        }
        let child = Route {
            method: http::Method::GET,
            path: "/users/{id}",
            handler: axum::routing::get(handler),
            name: "child",
            api_doc: ApiDoc {
                method: "GET",
                path: "/users/{id}",
                operation_id: "child",
                path_params: &["id"],
                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 group = crate::app::ScopedGroup {
            prefix: "/orgs/{org_id}".to_owned(),
            routes: vec![child],
            source: crate::route_listing::RouteSource::User,
            apply_layer: Box::new(|r| r),
        };

        let config = OpenApiConfig::new("Demo", "1.0.0");
        let router = super::build_openapi_router(&[], &[group], Some(&config), "autumn.sid", &[])
            .expect("openapi sub-router builds")
            .expect("openapi sub-router present when config is Some");
        let state = test_state();
        let router = router.with_state(state);

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/openapi.json")
                    .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 spec: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let params = &spec["paths"]["/orgs/{org_id}/users/{id}"]["get"]["parameters"];
        let names: Vec<&str> = params
            .as_array()
            .unwrap()
            .iter()
            .map(|p| p["name"].as_str().unwrap())
            .collect();
        assert!(names.contains(&"org_id"), "missing org_id: {names:?}");
        assert!(names.contains(&"id"), "missing id: {names:?}");
    }

    #[cfg(feature = "openapi")]
    #[tokio::test]
    async fn openapi_documents_configured_session_cookie_name() {
        use crate::openapi::{ApiDoc, OpenApiConfig};

        async fn handler() -> &'static str {
            "ok"
        }

        let route = Route {
            method: http::Method::GET,
            path: "/protected",
            handler: axum::routing::get(handler),
            name: "protected",
            api_doc: ApiDoc {
                method: "GET",
                path: "/protected",
                operation_id: "protected",
                success_status: 200,
                secured: true,
                ..Default::default()
            },
            repository: None,
            idempotency: crate::route::RouteIdempotency::Direct,
            timeout: crate::route::RouteTimeout::Inherit,
            api_version: None,
            sunset_opt_out: false,
        };

        let protected_routes = vec![route];
        let config = OpenApiConfig::new("Demo", "1.0.0");
        let docs_router =
            super::build_openapi_router(&protected_routes, &[], Some(&config), "demo.sid", &[])
                .expect("openapi sub-router builds")
                .expect("openapi sub-router present when config is Some");
        let docs_router = docs_router.with_state(test_state());

        let response = docs_router
            .oneshot(
                Request::builder()
                    .uri("/openapi.json")
                    .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 spec: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let schemes = &spec["components"]["securitySchemes"];

        assert_eq!(schemes["SessionAuth"]["type"], "apiKey");
        assert_eq!(schemes["SessionAuth"]["in"], "cookie");
        assert_eq!(schemes["SessionAuth"]["name"], "demo.sid");
        assert!(
            schemes.get("BearerAuth").is_none(),
            "secured routes must not be documented as bearer JWT routes"
        );
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_rejects_json_path_without_leading_slash() {
        let config =
            crate::openapi::OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("openapi.json");
        let err = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect_err("non-slash path should be rejected");
        assert!(matches!(
            err,
            RouterBuildError::InvalidOpenApiPath {
                field: "openapi_json_path",
                ..
            }
        ));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_rejects_path_with_captures() {
        // `{id}` captures would be a typo for a mount path — the
        // endpoints are static. Catch it before axum panics.
        let config =
            crate::openapi::OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("/docs/{id}");
        let err = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect_err("captures should be rejected");
        assert!(matches!(err, RouterBuildError::InvalidOpenApiPath { .. }));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_rejects_path_with_unbalanced_brace() {
        let config =
            crate::openapi::OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("/docs/{id");
        let err = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect_err("unbalanced brace should be rejected");
        assert!(matches!(err, RouterBuildError::InvalidOpenApiPath { .. }));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_rejects_path_with_wildcard() {
        let config =
            crate::openapi::OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("/docs/*rest");
        let err = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect_err("wildcard should be rejected");
        assert!(matches!(err, RouterBuildError::InvalidOpenApiPath { .. }));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_rejects_path_with_double_slash() {
        let config =
            crate::openapi::OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("//docs");
        let err = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect_err("double-slash should be rejected");
        assert!(matches!(err, RouterBuildError::InvalidOpenApiPath { .. }));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_rejects_swagger_ui_path_without_leading_slash() {
        let config = crate::openapi::OpenApiConfig::new("Demo", "1.0.0")
            .swagger_ui_path(Some("docs".to_owned()));
        let err = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect_err("non-slash path should be rejected");
        assert!(matches!(
            err,
            RouterBuildError::InvalidOpenApiPath {
                field: "swagger_ui_path",
                ..
            }
        ));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_rejects_empty_json_path() {
        let config = crate::openapi::OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("");
        let err = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect_err("empty path should be rejected");
        assert!(matches!(err, RouterBuildError::InvalidOpenApiPath { .. }));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_accepts_valid_paths() {
        let config = crate::openapi::OpenApiConfig::new("Demo", "1.0.0")
            .openapi_json_path("/api-docs")
            .swagger_ui_path(Some("/ui".to_owned()));
        let out = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect("valid paths must not error");
        assert!(out.is_some());
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn openapi_rejects_duplicate_json_and_swagger_paths() {
        let config = crate::openapi::OpenApiConfig::new("Demo", "1.0.0")
            .openapi_json_path("/docs")
            .swagger_ui_path(Some("/docs".to_owned()));
        let err = super::build_openapi_router(&[], &[], Some(&config), "autumn.sid", &[])
            .expect_err("colliding paths should be rejected before axum panics");
        assert!(matches!(
            err,
            RouterBuildError::DuplicateOpenApiPath { ref path } if path == "/docs"
        ));
    }

    #[cfg(feature = "openapi")]
    async fn collision_test_handler() -> &'static str {
        "user"
    }

    #[cfg(feature = "openapi")]
    #[tokio::test]
    async fn try_build_router_rejects_openapi_path_colliding_with_user_route() {
        let mut config = AutumnConfig::default();
        config.actuator.prefix = "/ops".to_owned();
        let openapi =
            crate::openapi::OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("/my-api-docs");

        let user_route = Route {
            method: http::Method::GET,
            path: "/my-api-docs",
            handler: axum::routing::get(collision_test_handler),
            name: "collides",
            api_doc: crate::openapi::ApiDoc {
                method: "GET",
                path: "/my-api-docs",
                operation_id: "collides",
                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 ctx = RouterContext {
            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(),
            #[cfg(feature = "maud")]
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(vec![user_route], &config, test_state(), ctx)
            .expect_err("user-owned path should prevent OpenAPI mount");
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision { field: "openapi_json_path", ref path } if path == "/my-api-docs"
        ));
    }

    #[cfg(feature = "openapi")]
    #[tokio::test]
    async fn try_build_router_rejects_openapi_path_colliding_with_framework_route() {
        let config = AutumnConfig::default(); // /actuator/health is a GET by default
        let openapi = crate::openapi::OpenApiConfig::new("Demo", "1.0.0")
            .openapi_json_path("/actuator/health");
        let ctx = RouterContext {
            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(),
            #[cfg(feature = "maud")]
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(Vec::new(), &config, test_state(), ctx)
            .expect_err("framework-owned path should prevent OpenAPI mount");
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision {
                field: "openapi_json_path",
                ..
            }
        ));
    }

    #[cfg(feature = "openapi")]
    #[tokio::test]
    async fn try_build_router_rejects_swagger_ui_asset_path_colliding_with_user_route() {
        let config = AutumnConfig::default();
        let openapi = crate::openapi::OpenApiConfig::new("Demo", "1.0.0");

        let user_route = Route {
            method: http::Method::GET,
            path: "/swagger-ui/swagger-ui.css",
            handler: axum::routing::get(collision_test_handler),
            name: "swagger-ui-asset-collides",
            api_doc: crate::openapi::ApiDoc {
                method: "GET",
                path: "/swagger-ui/swagger-ui.css",
                operation_id: "swagger_ui_asset_collides",
                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 ctx = RouterContext {
            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(),
            #[cfg(feature = "maud")]
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(vec![user_route], &config, test_state(), ctx)
            .expect_err("swagger ui asset path should be reserved");
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision {
                field: "swagger_ui_path",
                ref path,
            } if path == "/swagger-ui/swagger-ui.css"
        ));
    }

    #[cfg(all(feature = "openapi", feature = "htmx"))]
    #[tokio::test]
    async fn try_build_router_rejects_openapi_path_colliding_with_htmx_csrf_route() {
        let config = AutumnConfig::default();
        let openapi = crate::openapi::OpenApiConfig::new("Demo", "1.0.0")
            .openapi_json_path(crate::htmx::HTMX_CSRF_JS_PATH);
        let ctx = RouterContext {
            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(),
            #[cfg(feature = "maud")]
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(Vec::new(), &config, test_state(), ctx)
            .expect_err("htmx csrf helper path should be reserved");
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision {
                field: "openapi_json_path",
                ref path,
            } if path == crate::htmx::HTMX_CSRF_JS_PATH
        ));
    }

    #[cfg(feature = "openapi")]
    #[tokio::test]
    async fn try_build_router_rejects_openapi_path_under_nest_prefix() {
        // Nesting `/api` means that router owns everything under
        // `/api/...`. Mounting OpenAPI at `/api/docs` would either
        // panic on merge or silently lose one of the routes, so the
        // collision check rejects it.
        let config = AutumnConfig::default();
        let openapi =
            crate::openapi::OpenApiConfig::new("Demo", "1.0.0").openapi_json_path("/api/docs");
        let nested = axum::Router::<AppState>::new()
            .route("/inner", axum::routing::get(|| async { "inner" }));
        let ctx = RouterContext {
            exception_filters: Vec::new(),
            scoped_groups: Vec::new(),
            merge_routers: Vec::new(),
            nest_routers: vec![("/api".to_owned(), nested)],
            custom_layers: Vec::new(),
            static_gate_layers: Vec::new(),
            #[cfg(feature = "maud")]
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(Vec::new(), &config, test_state(), ctx)
            .expect_err("OpenAPI path under a nest prefix should collide");
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision {
                field: "openapi_json_path",
                ref path,
            } if path == "/api/docs"
        ));
    }

    #[cfg(all(feature = "openapi", feature = "mail"))]
    #[tokio::test]
    async fn try_build_router_rejects_openapi_path_on_unsubscribe_endpoint() {
        // The default one-click unsubscribe endpoint merges a GET at
        // `/_autumn/unsubscribe` before the late-merged OpenAPI router, so the
        // collision preflight must reserve it — otherwise mounting OpenAPI there
        // panics in `router.merge` instead of surfacing the typed collision.
        let mut config = AutumnConfig::default();
        config.mail.mount_unsubscribe_endpoint = true;
        config.mail.unsubscribe_base_url = Some("https://app.example.com".to_owned());
        assert!(config.mail.should_mount_unsubscribe_endpoint());
        let openapi = crate::openapi::OpenApiConfig::new("Demo", "1.0.0")
            .openapi_json_path(crate::mail::UNSUBSCRIBE_PATH);
        let ctx = RouterContext {
            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(),
            #[cfg(feature = "maud")]
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(Vec::new(), &config, test_state(), ctx)
            .expect_err("unsubscribe endpoint path should be reserved");
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision {
                field: "openapi_json_path",
                ref path,
            } if path == crate::mail::UNSUBSCRIBE_PATH
        ));
    }

    #[cfg(feature = "openapi")]
    #[tokio::test]
    async fn try_build_router_rejects_openapi_path_on_job_status_endpoint() {
        // The tracked-job status endpoint merges a GET at
        // `/_autumn/jobs/{token}` before the late-merged OpenAPI router (on by
        // default), so the collision preflight must reserve it too.
        let config = AutumnConfig::default();
        assert!(config.jobs.tracking.route_enabled);
        let openapi = crate::openapi::OpenApiConfig::new("Demo", "1.0.0")
            .openapi_json_path(crate::job_tracking::JOB_STATUS_ROUTE_PATH);
        let ctx = RouterContext {
            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(),
            #[cfg(feature = "maud")]
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(Vec::new(), &config, test_state(), ctx)
            .expect_err("job status endpoint path should be reserved");
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision {
                field: "openapi_json_path",
                ref path,
            } if path == crate::job_tracking::JOB_STATUS_ROUTE_PATH
        ));
    }

    #[cfg(all(feature = "openapi", feature = "maud"))]
    #[tokio::test]
    async fn try_build_router_rejects_openapi_path_on_story_gallery() {
        // The story gallery merges GETs at `/_stories` (+ `/_stories/{slug}`)
        // when `stories.enabled` resolves true, before the late-merged
        // OpenAPI router, so the collision preflight must reserve it —
        // otherwise mounting OpenAPI there panics in `router.merge` instead
        // of surfacing the typed collision.
        let mut config = AutumnConfig::default();
        config.stories.enabled = true;
        let openapi = crate::openapi::OpenApiConfig::new("Demo", "1.0.0")
            .openapi_json_path(crate::stories::STORIES_PATH);
        let ctx = RouterContext {
            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(),
            error_page_renderer: None,
            session_store: None,
            openapi: Some(openapi),
            #[cfg(feature = "mcp")]
            mcp: None,
        };
        let err = super::try_build_router_inner(Vec::new(), &config, test_state(), ctx)
            .expect_err("story gallery path should be reserved while stories are enabled");
        assert!(matches!(
            err,
            RouterBuildError::OpenApiPathCollision {
                field: "openapi_json_path",
                ref path,
            } if path == crate::stories::STORIES_PATH
        ));
    }

    #[cfg(feature = "openapi")]
    #[test]
    fn try_build_router_rejects_openapi_path_on_dev_live_reload() {
        temp_env::with_vars(
            [
                ("AUTUMN_DEV_RELOAD", Some("1")),
                ("AUTUMN_DEV_RELOAD_STATE", Some("/tmp/autumn-reload-test")),
            ],
            || {
                let config = AutumnConfig::default();
                let openapi = crate::openapi::OpenApiConfig::new("Demo", "1.0.0")
                    .openapi_json_path("/__autumn/live-reload");
                let ctx = RouterContext {
                    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(),
                    error_page_renderer: None,
                    session_store: None,
                    openapi: Some(openapi),
                    #[cfg(feature = "mcp")]
                    mcp: None,
                };
                let err = super::try_build_router_inner(Vec::new(), &config, test_state(), ctx)
                    .expect_err("dev reload path should be reserved");
                assert!(matches!(
                    err,
                    RouterBuildError::OpenApiPathCollision {
                        field: "openapi_json_path",
                        ..
                    }
                ));
            },
        );
    }

    // --- Duplicate user-route detection tests (issue #1012) ---

    async fn duplicate_route_handler() -> &'static str {
        "ok"
    }

    /// Build a lightweight [`Route`] for the duplicate-detection tests. The
    /// `MethodRouter` is built with the same HTTP method as `method` so
    /// scenarios that intentionally exercise `GET`+`POST` on the same path
    /// (AC #4) actually merge cleanly at axum level; the caller sees the
    /// duplicate-preflight decision, not an axum method-router-merge panic.
    fn duplicate_test_route(method: http::Method, path: &'static str, name: &'static str) -> Route {
        let handler = match method {
            http::Method::POST => axum::routing::post(duplicate_route_handler),
            http::Method::PUT => axum::routing::put(duplicate_route_handler),
            http::Method::PATCH => axum::routing::patch(duplicate_route_handler),
            http::Method::DELETE => axum::routing::delete(duplicate_route_handler),
            _ => axum::routing::get(duplicate_route_handler),
        };
        let method_str = if method == http::Method::POST {
            "POST"
        } else if method == http::Method::PUT {
            "PUT"
        } else if method == http::Method::PATCH {
            "PATCH"
        } else if method == http::Method::DELETE {
            "DELETE"
        } else {
            "GET"
        };
        Route {
            method,
            path,
            handler,
            name,
            api_doc: crate::openapi::ApiDoc {
                method: method_str,
                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,
        }
    }

    fn duplicate_test_ctx() -> RouterContext {
        RouterContext {
            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(),
            #[cfg(feature = "maud")]
            error_page_renderer: None,
            session_store: None,
            #[cfg(feature = "openapi")]
            openapi: None,
            #[cfg(feature = "mcp")]
            mcp: None,
        }
    }

    /// AC #1, #2, #6: two routes registered on the same (method, path) fail
    /// the build with a structured [`RouterBuildError::DuplicateUserRoute`]
    /// that names both handlers and the offending method + path — no axum
    /// panic escapes.
    #[tokio::test]
    async fn try_build_router_rejects_duplicate_user_route_paths() {
        let config = AutumnConfig::default();
        let a = duplicate_test_route(http::Method::GET, "/", "root_a");
        let b = duplicate_test_route(http::Method::GET, "/", "root_b");
        let err =
            super::try_build_router_inner(vec![a, b], &config, test_state(), duplicate_test_ctx())
                .expect_err("two GET / routes should be rejected before mount");
        let display = err.to_string();
        match err {
            RouterBuildError::DuplicateUserRoute {
                ref method,
                ref path,
                ref existing,
                ref incoming,
            } => {
                assert_eq!(method, "GET");
                assert_eq!(path, "/");
                assert_eq!(existing, "root_a");
                assert_eq!(incoming, "root_b");
            }
            other => panic!("expected DuplicateUserRoute, got {other:?}"),
        }
        assert!(
            display.contains("root_a"),
            "error message must name first handler; got: {display}"
        );
        assert!(
            display.contains("root_b"),
            "error message must name second handler; got: {display}"
        );
        assert!(
            display.contains("GET"),
            "error message must name the HTTP method; got: {display}"
        );
        assert!(
            display.contains('/'),
            "error message must contain the path; got: {display}"
        );
    }

    /// AC #4: distinct methods on the same path (`GET /admin` + `POST /admin`)
    /// must NOT be flagged — axum merges them cleanly into a single
    /// `MethodRouter`.
    #[tokio::test]
    async fn try_build_router_allows_distinct_methods_on_same_path() {
        let config = AutumnConfig::default();
        let get = duplicate_test_route(http::Method::GET, "/admin", "admin_index");
        let post = duplicate_test_route(http::Method::POST, "/admin", "admin_create");
        let _router = super::try_build_router_inner(
            vec![get, post],
            &config,
            test_state(),
            duplicate_test_ctx(),
        )
        .expect("GET + POST on the same path should build cleanly");
    }

    /// AC #3: duplicates that span a top-level route and a scoped group
    /// (once the scope prefix is applied) are detected using the same
    /// preflight — the introspection reuses `RouteInfo`'s scope resolution.
    #[tokio::test]
    async fn try_build_router_rejects_duplicate_across_scoped_group() {
        let config = AutumnConfig::default();
        let top = duplicate_test_route(http::Method::GET, "/api/posts", "top_posts");
        let scoped_child = duplicate_test_route(http::Method::GET, "/posts", "scoped_posts");
        let group = crate::app::ScopedGroup {
            prefix: "/api".to_owned(),
            routes: vec![scoped_child],
            source: crate::route_listing::RouteSource::User,
            apply_layer: Box::new(|r| r),
        };
        let mut ctx = duplicate_test_ctx();
        ctx.scoped_groups.push(group);
        let err = super::try_build_router_inner(vec![top], &config, test_state(), ctx)
            .expect_err("top-level + scoped resolving to same path should be rejected");
        match err {
            RouterBuildError::DuplicateUserRoute {
                ref method,
                ref path,
                ..
            } => {
                assert_eq!(method, "GET");
                assert_eq!(path, "/api/posts");
            }
            other => panic!("expected DuplicateUserRoute, got {other:?}"),
        }
    }

    /// AC #3: two scoped groups whose resolved paths collide are also
    /// caught (a plugin re-registering the same route class as user code).
    #[tokio::test]
    async fn try_build_router_rejects_duplicate_within_scoped_groups() {
        let config = AutumnConfig::default();
        let a = crate::app::ScopedGroup {
            prefix: "/api".to_owned(),
            routes: vec![duplicate_test_route(
                http::Method::GET,
                "/posts",
                "user_posts",
            )],
            source: crate::route_listing::RouteSource::User,
            apply_layer: Box::new(|r| r),
        };
        let b = crate::app::ScopedGroup {
            prefix: "/api".to_owned(),
            routes: vec![duplicate_test_route(
                http::Method::GET,
                "/posts",
                "plugin_posts",
            )],
            source: crate::route_listing::RouteSource::Plugin("blog".to_owned()),
            apply_layer: Box::new(|r| r),
        };
        let mut ctx = duplicate_test_ctx();
        ctx.scoped_groups.push(a);
        ctx.scoped_groups.push(b);
        let err = super::try_build_router_inner(Vec::new(), &config, test_state(), ctx)
            .expect_err("two scoped groups colliding on /api/posts should be rejected");
        assert!(matches!(
            err,
            RouterBuildError::DuplicateUserRoute { ref existing, ref incoming, .. }
                if existing == "user_posts" && incoming == "plugin_posts"
        ));
    }

    /// AC #5: an opaque `AppBuilder::merge` router coexisting with a clean
    /// route table must not cause a false-pass failure — the check is
    /// skipped (with the existing "check skipped" warning) and the build
    /// continues. Regression guard for the collision preflight.
    #[tokio::test]
    async fn try_build_router_skips_duplicate_check_for_opaque_merge_router() {
        let config = AutumnConfig::default();
        let ok_route = duplicate_test_route(http::Method::GET, "/hello", "hello");
        let raw = axum::Router::<AppState>::new()
            .route("/raw", axum::routing::get(duplicate_route_handler));
        let mut ctx = duplicate_test_ctx();
        ctx.merge_routers.push(raw);
        let _router = super::try_build_router_inner(vec![ok_route], &config, test_state(), ctx)
            .expect("opaque merge routers must not fail the duplicate preflight");
    }

    /// AC #5: same regression guard for opaque `AppBuilder::nest` routers.
    #[tokio::test]
    async fn try_build_router_skips_duplicate_check_for_opaque_nest_router() {
        let config = AutumnConfig::default();
        let ok_route = duplicate_test_route(http::Method::GET, "/hello", "hello");
        let nested = axum::Router::<AppState>::new()
            .route("/child", axum::routing::get(duplicate_route_handler));
        let mut ctx = duplicate_test_ctx();
        ctx.nest_routers.push(("/plugin".to_owned(), nested));
        let _router = super::try_build_router_inner(vec![ok_route], &config, test_state(), ctx)
            .expect("opaque nest routers must not fail the duplicate preflight");
    }

    /// Finding 1 (issue #1012 review): two handlers that differ ONLY by capture
    /// name — `/users/{id}` vs `/users/{slug}` — key by literal template so they
    /// look distinct to a naive preflight, but axum's matcher (verified against
    /// axum 0.8.9: matchit reports a "conflict") rejects the second route shape
    /// at mount. Because the two EXACT templates differ, this is a matchit route
    /// conflict (illegal regardless of method), surfaced as
    /// `ConflictingRouteShape` naming both handlers AND both original templates.
    #[tokio::test]
    async fn try_build_router_rejects_duplicate_capture_name_paths() {
        let config = AutumnConfig::default();
        let a = duplicate_test_route(http::Method::GET, "/users/{id}", "by_id");
        let b = duplicate_test_route(http::Method::GET, "/users/{slug}", "by_slug");
        let err =
            super::try_build_router_inner(vec![a, b], &config, test_state(), duplicate_test_ctx())
                .expect_err("capture-name-only difference must be rejected before mount");
        match err {
            RouterBuildError::ConflictingRouteShape {
                ref existing,
                ref existing_path,
                ref incoming,
                ref incoming_path,
            } => {
                assert_eq!(existing, "by_id");
                assert_eq!(existing_path, "/users/{id}");
                assert_eq!(incoming, "by_slug");
                assert_eq!(incoming_path, "/users/{slug}");
            }
            other => panic!("expected ConflictingRouteShape, got {other:?}"),
        }
        // The diagnostic must name BOTH original templates, not the normalized key.
        let display = err.to_string();
        assert!(
            display.contains("/users/{id}") && display.contains("/users/{slug}"),
            "error must show both original path templates; got: {display}"
        );
    }

    /// Finding 1, scoped-group variant: the capture-name normalization must run
    /// AFTER `join_nested_path` prefix resolution, so a scoped `/users/{slug}`
    /// under `/api` collides with a top-level `/api/users/{id}`.
    #[tokio::test]
    async fn try_build_router_rejects_duplicate_capture_name_across_scoped_group() {
        let config = AutumnConfig::default();
        let top = duplicate_test_route(http::Method::GET, "/api/users/{id}", "top_by_id");
        let scoped_child =
            duplicate_test_route(http::Method::GET, "/users/{slug}", "scoped_by_slug");
        let group = crate::app::ScopedGroup {
            prefix: "/api".to_owned(),
            routes: vec![scoped_child],
            source: crate::route_listing::RouteSource::User,
            apply_layer: Box::new(|r| r),
        };
        let mut ctx = duplicate_test_ctx();
        ctx.scoped_groups.push(group);
        let err = super::try_build_router_inner(vec![top], &config, test_state(), ctx)
            .expect_err("scoped capture-name collision must be rejected before mount");
        assert!(
            matches!(
                err,
                RouterBuildError::ConflictingRouteShape {
                    ref existing, ref incoming, ref existing_path, ref incoming_path
                }
                    if existing == "top_by_id" && incoming == "scoped_by_slug"
                        && existing_path == "/api/users/{id}"
                        && incoming_path == "/api/users/{slug}"
            ),
            "expected ConflictingRouteShape naming both handlers + both paths, got {err:?}"
        );
    }

    /// Finding 1 NEGATIVE guard: normalization must not over-flag. Two genuinely
    /// different shapes that axum's matcher accepts (verified: `/users/{id}` and
    /// `/users/{id}/posts` do NOT conflict) must still build cleanly.
    #[tokio::test]
    async fn try_build_router_allows_distinct_route_shapes() {
        let config = AutumnConfig::default();
        let a = duplicate_test_route(http::Method::GET, "/users/{id}", "show");
        let b = duplicate_test_route(http::Method::GET, "/users/{id}/posts", "posts");
        let _router =
            super::try_build_router_inner(vec![a, b], &config, test_state(), duplicate_test_ctx())
                .expect("distinct route shapes must not be flagged as duplicates");
    }

    /// Finding 2 (issue #1012 review): `#[ws]` records the synthetic `WS` method
    /// but `group_and_mount_routes` mounts its handler via `axum::routing::get`,
    /// so `#[get("/live")]` + `#[ws("/live")]` produce two overlapping `GET`
    /// `MethodRouter`s that panic on merge. Normalizing `WS` to its effective
    /// `GET` before keying makes the preflight catch it as `DuplicateUserRoute`.
    ///
    /// Not `#[cfg(feature = "ws")]`-gated: the synthetic `WS` method is a plain
    /// `http::Method` string, and the sibling `build_route_timeout_table_*` test
    /// exercises the same normalization ungated — gating would hide this from the
    /// default `cargo test` run since `ws` is not a default feature.
    #[tokio::test]
    async fn try_build_router_rejects_ws_get_collision() {
        let config = AutumnConfig::default();
        let get = duplicate_test_route(http::Method::GET, "/live", "live_poll");
        let ws = duplicate_test_route(
            http::Method::from_bytes(b"WS").unwrap(),
            "/live",
            "live_socket",
        );
        let err = super::try_build_router_inner(
            vec![get, ws],
            &config,
            test_state(),
            duplicate_test_ctx(),
        )
        .expect_err("GET + WS on the same path must be rejected before mount");
        match err {
            RouterBuildError::DuplicateUserRoute {
                ref method,
                ref path,
                ref existing,
                ref incoming,
            } => {
                assert_eq!(method, "GET", "WS must be normalized to its effective GET");
                assert_eq!(path, "/live");
                assert_eq!(existing, "live_poll");
                assert_eq!(incoming, "live_socket");
            }
            other => panic!("expected DuplicateUserRoute, got {other:?}"),
        }
    }

    /// Finding A (round 2): different HTTP methods whose paths differ ONLY by
    /// capture name (`GET /users/{id}` + `POST /users/{slug}`) key as distinct
    /// `(method, shape)` pairs, so the method-independent shape check must catch
    /// them. Verified against axum 0.8.9: `Router::route("/users/{id}", get)`
    /// then `Router::route("/users/{slug}", post)` PANICS — matchit rejects the
    /// second template as a route conflict BEFORE method merging. The preflight
    /// surfaces it as `ConflictingRouteShape` naming both handlers + both
    /// templates; no axum panic escapes.
    #[tokio::test]
    async fn try_build_router_rejects_cross_method_shape_conflict() {
        let config = AutumnConfig::default();
        let get = duplicate_test_route(http::Method::GET, "/users/{id}", "by_id");
        let post = duplicate_test_route(http::Method::POST, "/users/{slug}", "by_slug");
        let err = super::try_build_router_inner(
            vec![get, post],
            &config,
            test_state(),
            duplicate_test_ctx(),
        )
        .expect_err("cross-method capture-name-only conflict must be rejected before mount");
        match err {
            RouterBuildError::ConflictingRouteShape {
                ref existing,
                ref existing_path,
                ref incoming,
                ref incoming_path,
            } => {
                assert_eq!(existing, "by_id");
                assert_eq!(existing_path, "/users/{id}");
                assert_eq!(incoming, "by_slug");
                assert_eq!(incoming_path, "/users/{slug}");
            }
            other => panic!("expected ConflictingRouteShape, got {other:?}"),
        }
        let display = err.to_string();
        assert!(
            display.contains("by_id") && display.contains("by_slug"),
            "error must name both handlers; got: {display}"
        );
        assert!(
            display.contains("/users/{id}") && display.contains("/users/{slug}"),
            "error must name both original templates; got: {display}"
        );
    }

    /// Finding A, scoped-group variant: the method-independent shape conflict
    /// check must run AFTER `join_nested_path`, so a scoped `POST /users/{slug}`
    /// under `/api` conflicts with a top-level `GET /api/users/{id}`.
    #[tokio::test]
    async fn try_build_router_rejects_cross_method_shape_conflict_across_scoped_group() {
        let config = AutumnConfig::default();
        let top = duplicate_test_route(http::Method::GET, "/api/users/{id}", "top_by_id");
        let scoped_child =
            duplicate_test_route(http::Method::POST, "/users/{slug}", "scoped_by_slug");
        let group = crate::app::ScopedGroup {
            prefix: "/api".to_owned(),
            routes: vec![scoped_child],
            source: crate::route_listing::RouteSource::User,
            apply_layer: Box::new(|r| r),
        };
        let mut ctx = duplicate_test_ctx();
        ctx.scoped_groups.push(group);
        let err = super::try_build_router_inner(vec![top], &config, test_state(), ctx)
            .expect_err("scoped cross-method shape conflict must be rejected before mount");
        assert!(
            matches!(
                err,
                RouterBuildError::ConflictingRouteShape {
                    ref existing, ref incoming, ref existing_path, ref incoming_path
                }
                    if existing == "top_by_id" && incoming == "scoped_by_slug"
                        && existing_path == "/api/users/{id}"
                        && incoming_path == "/api/users/{slug}"
            ),
            "expected ConflictingRouteShape naming both handlers + both paths, got {err:?}"
        );
    }

    /// AC #4 (round 2): the SAME exact capture template on distinct methods
    /// (`GET /users/{id}` + `POST /users/{id}`) is LEGAL — axum merges the two
    /// `MethodRouter`s. Verified against axum 0.8.9: this pair builds cleanly.
    /// The shape check keys on the FIRST exact template per shape, so an
    /// identical template never trips it — only a DIFFERENT template does.
    #[tokio::test]
    async fn try_build_router_allows_same_capture_template_distinct_methods() {
        let config = AutumnConfig::default();
        let get = duplicate_test_route(http::Method::GET, "/users/{id}", "show");
        let post = duplicate_test_route(http::Method::POST, "/users/{id}", "update");
        let _router = super::try_build_router_inner(
            vec![get, post],
            &config,
            test_state(),
            duplicate_test_ctx(),
        )
        .expect("same capture template on GET + POST must build cleanly");
    }

    /// Finding B (round 2): axum/matchit treat `{{`/`}}` as ESCAPED literal
    /// braces, so `/{{foo}}` and `/{{bar}}` are two DISTINCT static routes.
    /// Verified against axum 0.8.9: both build cleanly. The matchit oracle
    /// treats escaped braces as literals (not captures), so this valid app is
    /// not falsely rejected.
    #[tokio::test]
    async fn try_build_router_allows_escaped_brace_literals() {
        let config = AutumnConfig::default();
        let a = duplicate_test_route(http::Method::GET, "/{{foo}}", "lit_foo");
        let b = duplicate_test_route(http::Method::GET, "/{{bar}}", "lit_bar");
        let _router =
            super::try_build_router_inner(vec![a, b], &config, test_state(), duplicate_test_ctx())
                .expect("distinct escaped-literal paths must not be flagged as duplicates");
    }

    /// Finding B guard: an escaped-literal prefix combined with a real capture
    /// keeps the shapes distinct — `/{{x}}/{id}` and `/{{y}}/{id}` differ only in
    /// their literal segment. Verified against axum 0.8.9: both build cleanly.
    #[tokio::test]
    async fn try_build_router_allows_escaped_literal_prefix_with_capture() {
        let config = AutumnConfig::default();
        let a = duplicate_test_route(http::Method::GET, "/{{x}}/{id}", "x_show");
        let b = duplicate_test_route(http::Method::GET, "/{{y}}/{id}", "y_show");
        let _router =
            super::try_build_router_inner(vec![a, b], &config, test_state(), duplicate_test_ctx())
                .expect("distinct escaped-literal prefixes with a shared capture must build");
    }

    /// Adversarial sweep: a mixed literal+capture segment must normalize at the
    /// char level. `/file.{ext}` and `/file.{kind}` share the shape `/file.{…}`.
    /// Verified against axum 0.8.9: this pair PANICS (matchit conflict), so the
    /// preflight must flag it as `ConflictingRouteShape` naming both templates.
    #[tokio::test]
    async fn try_build_router_rejects_mixed_literal_capture_shape_conflict() {
        let config = AutumnConfig::default();
        let a = duplicate_test_route(http::Method::GET, "/file.{ext}", "by_ext");
        let b = duplicate_test_route(http::Method::GET, "/file.{kind}", "by_kind");
        let err =
            super::try_build_router_inner(vec![a, b], &config, test_state(), duplicate_test_ctx())
                .expect_err("mixed literal+capture shape conflict must be rejected before mount");
        assert!(
            matches!(
                err,
                RouterBuildError::ConflictingRouteShape {
                    ref existing_path, ref incoming_path, ..
                }
                    if existing_path == "/file.{ext}" && incoming_path == "/file.{kind}"
            ),
            "expected ConflictingRouteShape naming both templates, got {err:?}"
        );
    }

    /// Adversarial sweep NEGATIVE guard: a mixed literal+capture segment stays
    /// distinct from a fully static segment. `/file.{ext}` and `/file.json` do
    /// NOT share a shape. Verified against axum 0.8.9: this pair builds cleanly,
    /// so the char-level normalization must not over-collapse the static one.
    #[tokio::test]
    async fn try_build_router_allows_mixed_capture_vs_static_segment() {
        let config = AutumnConfig::default();
        let a = duplicate_test_route(http::Method::GET, "/file.{ext}", "by_ext");
        let b = duplicate_test_route(http::Method::GET, "/file.json", "static_json");
        let _router =
            super::try_build_router_inner(vec![a, b], &config, test_state(), duplicate_test_ctx())
                .expect("a capture segment and a static segment must not be flagged as duplicates");
    }

    /// Adversarial sweep: a normal capture and a catch-all at the same terminal
    /// position (`/u/{id}` vs `/u/{*rest}`) collapse to the same placeholder.
    /// Verified against axum 0.8.9: this pair PANICS (matchit conflict), so the
    /// preflight must flag it. Different exact templates → `ConflictingRouteShape`.
    #[tokio::test]
    async fn try_build_router_rejects_catch_all_vs_normal_capture() {
        let config = AutumnConfig::default();
        let a = duplicate_test_route(http::Method::GET, "/u/{id}", "one");
        let b = duplicate_test_route(http::Method::GET, "/u/{*rest}", "rest");
        let err =
            super::try_build_router_inner(vec![a, b], &config, test_state(), duplicate_test_ctx())
                .expect_err("catch-all vs normal capture must be rejected before mount");
        assert!(
            matches!(
                err,
                RouterBuildError::ConflictingRouteShape {
                    ref existing_path, ref incoming_path, ..
                }
                    if existing_path == "/u/{id}" && incoming_path == "/u/{*rest}"
            ),
            "expected ConflictingRouteShape naming both templates, got {err:?}"
        );
    }

    /// New #1012 finding (matchit oracle): a catch-all conflicts with a dynamic
    /// DESCENDANT, not just a sibling capture. `GET /cmd/{tool}/{sub}` +
    /// `POST /cmd/{*path}` slipped past the old hand-rolled shape normalizer
    /// (which only unified captures position-by-position) and axum still panicked
    /// at mount. Delegating to matchit — the engine axum uses — catches it:
    /// verified against axum 0.8.9 that this pair PANICS. The preflight surfaces
    /// it as `ConflictingRouteShape` naming both handlers + both templates; no
    /// axum/matchit panic escapes.
    #[tokio::test]
    async fn try_build_router_rejects_catch_all_vs_dynamic_descendant() {
        let config = AutumnConfig::default();
        let a = duplicate_test_route(http::Method::GET, "/cmd/{tool}/{sub}", "cmd_sub");
        let b = duplicate_test_route(http::Method::POST, "/cmd/{*path}", "cmd_all");
        let err =
            super::try_build_router_inner(vec![a, b], &config, test_state(), duplicate_test_ctx())
                .expect_err("catch-all vs dynamic descendant must be rejected before mount");
        match err {
            RouterBuildError::ConflictingRouteShape {
                ref existing,
                ref existing_path,
                ref incoming,
                ref incoming_path,
            } => {
                assert_eq!(existing, "cmd_sub");
                assert_eq!(existing_path, "/cmd/{tool}/{sub}");
                assert_eq!(incoming, "cmd_all");
                assert_eq!(incoming_path, "/cmd/{*path}");
            }
            other => panic!("expected ConflictingRouteShape, got {other:?}"),
        }
        let display = err.to_string();
        assert!(
            display.contains("/cmd/{tool}/{sub}") && display.contains("/cmd/{*path}"),
            "error must name both original templates; got: {display}"
        );
    }

    /// Negative regression guard for the matchit oracle: a STATIC segment and a
    /// dynamic capture at the same position (`/users/me` + `/users/{id}`) do NOT
    /// conflict — matchit (and thus axum 0.8.9) accepts both, matching static
    /// before dynamic. The oracle must NOT raise a false positive here. Confirmed
    /// by `matchit_agrees_with_axum_route_conflicts`.
    #[tokio::test]
    async fn try_build_router_allows_static_vs_dynamic_segment() {
        let config = AutumnConfig::default();
        let a = duplicate_test_route(http::Method::GET, "/users/me", "me");
        let b = duplicate_test_route(http::Method::GET, "/users/{id}", "by_id");
        let _router =
            super::try_build_router_inner(vec![a, b], &config, test_state(), duplicate_test_ctx())
                .expect("a static segment and a dynamic capture must not be flagged as a conflict");
    }

    /// Parity guard for the #1012 matchit oracle: matchit's `insert` Ok/Err MUST
    /// agree with axum 0.8.9's `Router::route` accept/panic on every case of the
    /// conflict matrix. axum wraps matchit, so they should always agree — this
    /// test fails LOUDLY if a future axum bump (or a `matchit` version that
    /// drifts out of lockstep with the `=0.8.4` pin) changes conflict semantics,
    /// catching silent oracle divergence before it can introduce false
    /// positives/negatives at mount. Deterministic and fast (no async, no I/O).
    #[test]
    fn matchit_agrees_with_axum_route_conflicts() {
        // (template_a, template_b, expect_conflict)
        let matrix: &[(&str, &str, bool)] = &[
            ("/users/{id}", "/users/{slug}", true),
            ("/users/{id}", "/users/{id}/posts", false),
            ("/cmd/{tool}/{sub}", "/cmd/{*path}", true),
            ("/users/me", "/users/{id}", false),
            ("/{{foo}}", "/{{bar}}", false),
            ("/file.{ext}", "/file.{kind}", true),
            ("/file.{ext}", "/file.json", false),
            ("/u/{id}", "/u/{*rest}", true),
        ];

        // Silence axum/matchit's panic backtrace noise while we intentionally
        // trip conflicts under catch_unwind; restore the hook afterwards.
        let prev_hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));

        let mut rows = Vec::new();
        let mut mismatches = Vec::new();
        for &(a, b, expect_conflict) in matrix {
            // axum: does registering BOTH templates panic inside `route()`?
            let axum_panics = std::panic::catch_unwind(|| {
                let _ = axum::Router::<()>::new()
                    .route(a, axum::routing::get(|| async { "a" }))
                    .route(b, axum::routing::get(|| async { "b" }));
            })
            .is_err();

            // matchit: does inserting BOTH templates report a conflict?
            let mut r: matchit::Router<()> = matchit::Router::new();
            r.insert(a, ()).expect("first template must insert cleanly");
            let matchit_conflicts =
                matches!(r.insert(b, ()), Err(matchit::InsertError::Conflict { .. }));

            rows.push(format!(
                "{a:<20} vs {b:<20} axum={} matchit={} expected={}",
                if axum_panics { "PANIC" } else { "ok" },
                if matchit_conflicts { "Err" } else { "Ok" },
                if expect_conflict { "conflict" } else { "ok" },
            ));

            if axum_panics != matchit_conflicts || axum_panics != expect_conflict {
                mismatches.push(rows.last().unwrap().clone());
            }
        }

        std::panic::set_hook(prev_hook);

        assert!(
            mismatches.is_empty(),
            "matchit must agree with axum 0.8.9 AND the expected outcome on every \
             case (oracle divergence => false positives/negatives at mount).\n\
             full matrix:\n{}\nmismatches:\n{}",
            rows.join("\n"),
            mismatches.join("\n"),
        );
    }

    // --- Static file serving (SSG/ISG) tests ---

    // --- SSG/ISG response compression (#752) ---
    //
    // The static-first middleware serves manifest-backed `dist/` files by
    // reading them from disk and building a response directly, short-circuiting
    // before the dynamic router. Compression is applied OUTSIDE that middleware
    // (see `try_build_router_with_static_inner`), and the served response now
    // carries a MIME type derived from the file extension, so the compression
    // layer encodes compressible SSG pages while leaving binary assets alone —
    // matching the transport behaviour of dynamic handler responses.

    /// Build a `dist/` dir + `manifest.json` mapping each `(route, file, bytes)`
    /// tuple to a file on disk. Returns the `TempDir` guard; the dist directory
    /// is at `<tmp>/dist`.
    fn create_ssg_dist(entries: &[(&str, &str, &[u8])]) -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        let dist = dir.path().join("dist");
        let mut routes = std::collections::HashMap::new();
        for (route, file, bytes) in entries {
            let path = dist.join(file);
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent).expect("mkdir");
            }
            std::fs::write(&path, bytes).expect("write file");
            routes.insert(
                (*route).to_owned(),
                crate::static_gen::ManifestEntry {
                    file: (*file).to_owned(),
                    revalidate: None,
                },
            );
        }
        let manifest = crate::static_gen::StaticManifest {
            generated_at: "2026-07-12T00:00:00Z".to_owned(),
            autumn_version: "0.6.0".to_owned(),
            routes,
        };
        std::fs::write(
            dist.join("manifest.json"),
            serde_json::to_string(&manifest).unwrap(),
        )
        .unwrap();
        dir
    }

    fn compression_enabled_config() -> AutumnConfig {
        let mut config = AutumnConfig::default();
        config.compression.enabled = true;
        config
    }

    /// A manifest-backed HTML page is gzip-compressed when the client accepts
    /// gzip and framework compression is enabled, and it carries
    /// `Vary: Accept-Encoding`.
    #[tokio::test]
    async fn ssg_html_hit_is_gzip_compressed() {
        let html = format!(
            "<html><body>{}</body></html>",
            "Lorem ipsum dolor sit amet. ".repeat(64)
        );
        let tmp = create_ssg_dist(&[("/", "index.html", html.as_bytes())]);
        let dist = tmp.path().join("dist");

        let router = try_build_router_with_static(
            Vec::new(),
            &compression_enabled_config(),
            test_state(),
            Some(&dist),
        )
        .expect("router builds");
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/")
                    .header("accept-encoding", "gzip")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_ENCODING)
                .and_then(|v| v.to_str().ok()),
            Some("gzip"),
            "manifest-backed SSG HTML page must be gzip-compressed"
        );
        let vary = response
            .headers()
            .get(http::header::VARY)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");
        assert!(
            vary.to_lowercase().contains("accept-encoding"),
            "Vary must advertise Accept-Encoding, got {vary:?}"
        );
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_TYPE)
                .and_then(|v| v.to_str().ok()),
            Some("text/html; charset=utf-8"),
            "HTML page keeps its text/html content type"
        );
        // The transferred body is the gzip stream, not the raw HTML.
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_ne!(
            body.as_ref(),
            html.as_bytes(),
            "compressed body must differ from the raw HTML"
        );
    }

    /// A manifest-backed *binary* asset is served with its real MIME type and is
    /// NOT compressed, even though the client accepts gzip — proving the fix
    /// does not blindly compress non-text responses.
    #[tokio::test]
    async fn ssg_binary_asset_is_not_compressed_and_keeps_mime() {
        // PNG signature followed by pseudo-random bytes, padded well past the
        // compression size floor so size is not the reason it is skipped.
        let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec();
        bytes.extend((0u32..1024).map(|i| i.wrapping_mul(2_654_435_761).to_le_bytes()[0]));
        let tmp = create_ssg_dist(&[("/logo", "logo.png", &bytes)]);
        let dist = tmp.path().join("dist");

        let router = try_build_router_with_static(
            Vec::new(),
            &compression_enabled_config(),
            test_state(),
            Some(&dist),
        )
        .expect("router builds");
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/logo")
                    .header("accept-encoding", "gzip")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_TYPE)
                .and_then(|v| v.to_str().ok()),
            Some("image/png"),
            "binary manifest asset must keep its real MIME type, not text/html"
        );
        assert_eq!(
            response.headers().get(http::header::CONTENT_ENCODING),
            None,
            "binary asset must not be blindly compressed"
        );
    }

    /// A manifest-backed pre-compressed web font (`.woff2`) is served with its
    /// `font/woff2` MIME type and is NOT gzip-compressed even though the client
    /// accepts gzip: WOFF/WOFF2 embed their own compression, so re-encoding only
    /// wastes CPU. Raw fonts (`.ttf`/`.otf`) are deliberately left compressible.
    #[tokio::test]
    async fn ssg_woff2_font_is_not_compressed_and_keeps_mime() {
        // Pad well past the compression size floor so size is not the reason it
        // is skipped — the font MIME type is.
        let mut bytes = b"wOF2".to_vec();
        bytes.extend((0u32..1024).map(|i| i.wrapping_mul(2_654_435_761).to_le_bytes()[0]));
        let tmp = create_ssg_dist(&[("/inter", "fonts/inter.woff2", &bytes)]);
        let dist = tmp.path().join("dist");

        let router = try_build_router_with_static(
            Vec::new(),
            &compression_enabled_config(),
            test_state(),
            Some(&dist),
        )
        .expect("router builds");
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/inter")
                    .header("accept-encoding", "gzip")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_TYPE)
                .and_then(|v| v.to_str().ok()),
            Some("font/woff2"),
            "woff2 manifest asset must keep its font/woff2 MIME type"
        );
        assert_eq!(
            response.headers().get(http::header::CONTENT_ENCODING),
            None,
            "pre-compressed woff2 font must not be re-compressed"
        );
    }

    /// A manifest-backed asset served from a nested path with a multi-dot file
    /// name (`assets/js/app.min.js`) resolves to the JavaScript MIME type. The
    /// middleware derives the type from the file name alone, so neither the
    /// intermediate directory components nor the extra `.min.` dot cause a
    /// misparse.
    #[tokio::test]
    async fn ssg_nested_multidot_asset_resolves_js_mime() {
        let js = format!("console.log({:?});", "x".repeat(256));
        let tmp = create_ssg_dist(&[("/app.js", "assets/js/app.min.js", js.as_bytes())]);
        let dist = tmp.path().join("dist");

        let router = try_build_router_with_static(
            Vec::new(),
            &compression_enabled_config(),
            test_state(),
            Some(&dist),
        )
        .expect("router builds");
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/app.js")
                    .header("accept-encoding", "gzip")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_TYPE)
                .and_then(|v| v.to_str().ok()),
            Some("text/javascript; charset=utf-8"),
            "nested multi-dot JS asset must resolve to the JavaScript MIME type"
        );
        // JS is a compressible content type, so the layer must still gzip it.
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_ENCODING)
                .and_then(|v| v.to_str().ok()),
            Some("gzip"),
            "compressible JS asset must be gzip-compressed"
        );
    }

    /// An extensionless generated page route (`/about` ->
    /// `about/index.html`, the shape `static_gen::url_to_file_path` produces)
    /// keeps its `text/html; charset=utf-8` type and is gzip-compressed. This
    /// pins the fallback: routes without a file extension must NOT regress to
    /// octet-stream just because the served file is `index.html`.
    #[tokio::test]
    async fn ssg_generated_html_page_keeps_text_html_and_is_compressed() {
        let html = format!("<html><body>{}</body></html>", "About us. ".repeat(128));
        let tmp = create_ssg_dist(&[("/about", "about/index.html", html.as_bytes())]);
        let dist = tmp.path().join("dist");

        let router = try_build_router_with_static(
            Vec::new(),
            &compression_enabled_config(),
            test_state(),
            Some(&dist),
        )
        .expect("router builds");
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/about")
                    .header("accept-encoding", "gzip")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_TYPE)
                .and_then(|v| v.to_str().ok()),
            Some("text/html; charset=utf-8"),
            "extensionless generated page must stay text/html, not octet-stream"
        );
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_ENCODING)
                .and_then(|v| v.to_str().ok()),
            Some("gzip"),
            "generated HTML page must be gzip-compressed"
        );
    }

    /// A generated `.txt` route (`/robots.txt` -> `robots.txt/index.html`) is
    /// served as `text/plain; charset=utf-8` — derived from the request
    /// route's extension, not the on-disk `index.html` file name — and is
    /// gzip-compressed. Reading the MIME off the served file would mislabel it
    /// as text/html.
    #[tokio::test]
    async fn ssg_generated_txt_route_is_text_plain_and_compressed() {
        let body_text = format!("User-agent: *\nDisallow:\n{}", "# note\n".repeat(128));
        let tmp =
            create_ssg_dist(&[("/robots.txt", "robots.txt/index.html", body_text.as_bytes())]);
        let dist = tmp.path().join("dist");

        let router = try_build_router_with_static(
            Vec::new(),
            &compression_enabled_config(),
            test_state(),
            Some(&dist),
        )
        .expect("router builds");
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/robots.txt")
                    .header("accept-encoding", "gzip")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_TYPE)
                .and_then(|v| v.to_str().ok()),
            Some("text/plain; charset=utf-8"),
            "generated .txt route must be text/plain, derived from the route extension"
        );
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_ENCODING)
                .and_then(|v| v.to_str().ok()),
            Some("gzip"),
            "compressible text/plain route must be gzip-compressed"
        );
    }

    /// A generated `.xml` route (`/sitemap.xml` -> `sitemap.xml/index.html`) is
    /// served as `application/xml`, derived from the request route's extension
    /// rather than the served `index.html` file name.
    #[tokio::test]
    async fn ssg_generated_xml_route_is_xml_mime() {
        let xml = format!(
            "<?xml version=\"1.0\"?><urlset>{}</urlset>",
            "<url><loc>https://example.com/</loc></url>".repeat(64)
        );
        let tmp = create_ssg_dist(&[("/sitemap.xml", "sitemap.xml/index.html", xml.as_bytes())]);
        let dist = tmp.path().join("dist");

        let router = try_build_router_with_static(
            Vec::new(),
            &compression_enabled_config(),
            test_state(),
            Some(&dist),
        )
        .expect("router builds");
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/sitemap.xml")
                    .header("accept-encoding", "gzip")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_TYPE)
                .and_then(|v| v.to_str().ok()),
            Some("application/xml"),
            "generated .xml route must be application/xml, derived from the route extension"
        );
    }

    /// A generated HTML page whose slug merely *contains* a dot but ends in an
    /// UNRECOGNIZED extension (`/posts/release.v1` -> `release.v1/index.html`)
    /// stays `text/html; charset=utf-8` and is gzip-compressed. The `.v1`
    /// pseudo-extension is not an asset type, so the MIME must come from the
    /// served `index.html` — not be mislabeled octet-stream by a loose
    /// `contains('.')` heuristic.
    #[tokio::test]
    async fn ssg_dotted_slug_generated_page_stays_html_and_compressed() {
        let html = format!(
            "<html><body>{}</body></html>",
            "Release notes. ".repeat(128)
        );
        let tmp = create_ssg_dist(&[(
            "/posts/release.v1",
            "release.v1/index.html",
            html.as_bytes(),
        )]);
        let dist = tmp.path().join("dist");

        let router = try_build_router_with_static(
            Vec::new(),
            &compression_enabled_config(),
            test_state(),
            Some(&dist),
        )
        .expect("router builds");
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/posts/release.v1")
                    .header("accept-encoding", "gzip")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_TYPE)
                .and_then(|v| v.to_str().ok()),
            Some("text/html; charset=utf-8"),
            "dotted-slug generated page must stay text/html, not octet-stream"
        );
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_ENCODING)
                .and_then(|v| v.to_str().ok()),
            Some("gzip"),
            "dotted-slug generated HTML page must be gzip-compressed"
        );
    }

    /// A generated HTML page whose slug contains an email-like dotted suffix
    /// (`/users/alice@example.com` -> `alice@example.com/index.html`) stays
    /// `text/html; charset=utf-8`. Neither `.com` nor the `@` makes it an
    /// asset, so the MIME comes from the served `index.html`.
    #[tokio::test]
    async fn ssg_email_slug_generated_page_stays_html() {
        let html = format!("<html><body>{}</body></html>", "Profile. ".repeat(64));
        let tmp = create_ssg_dist(&[(
            "/users/alice@example.com",
            "alice@example.com/index.html",
            html.as_bytes(),
        )]);
        let dist = tmp.path().join("dist");

        let router = try_build_router_with_static(
            Vec::new(),
            &compression_enabled_config(),
            test_state(),
            Some(&dist),
        )
        .expect("router builds");
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/users/alice@example.com")
                    .header("accept-encoding", "gzip")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_TYPE)
                .and_then(|v| v.to_str().ok()),
            Some("text/html; charset=utf-8"),
            "email-like dotted-slug generated page must stay text/html"
        );
    }

    /// A dynamic fallback route (not in the manifest) is compressed the same way
    /// as SSG pages, confirming parity between static-first and dynamic
    /// responses.
    #[tokio::test]
    async fn ssg_dynamic_fallback_route_is_gzip_compressed() {
        async fn dynamic() -> impl axum::response::IntoResponse {
            (
                [(http::header::CONTENT_TYPE, "text/html; charset=utf-8")],
                format!(
                    "<html><body>{}</body></html>",
                    "dynamic content ".repeat(64)
                ),
            )
        }
        let route = Route {
            method: http::Method::GET,
            path: "/dynamic",
            handler: axum::routing::get(dynamic),
            name: "dynamic",
            api_doc: crate::openapi::ApiDoc {
                method: "GET",
                path: "/dynamic",
                operation_id: "dynamic",
                success_status: 200,
                ..Default::default()
            },
            api_version: None,
            sunset_opt_out: false,
            repository: None,
            idempotency: crate::route::RouteIdempotency::default(),
            timeout: crate::route::RouteTimeout::default(),
        };

        // Manifest does NOT contain /dynamic, so the request falls through to
        // the dynamic router.
        let tmp = create_ssg_dist(&[("/", "index.html", b"<h1>home</h1>")]);
        let dist = tmp.path().join("dist");

        let router = try_build_router_with_static(
            vec![route],
            &compression_enabled_config(),
            test_state(),
            Some(&dist),
        )
        .expect("router builds");
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/dynamic")
                    .header("accept-encoding", "gzip")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get(http::header::CONTENT_ENCODING)
                .and_then(|v| v.to_str().ok()),
            Some("gzip"),
            "dynamic fallback route must be compressed just like SSG pages"
        );
    }

    fn create_static_dist(revalidate: Option<u64>) -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        let dist = dir.path().join("dist");
        std::fs::create_dir_all(dist.join("about")).expect("mkdir about");
        std::fs::write(dist.join("index.html"), b"<h1>Home</h1>").expect("write index");
        std::fs::write(dist.join("about/index.html"), b"<h1>About</h1>").expect("write about");

        let mut routes = std::collections::HashMap::new();
        routes.insert(
            "/".to_owned(),
            crate::static_gen::ManifestEntry {
                file: "index.html".to_owned(),
                revalidate: None,
            },
        );
        routes.insert(
            "/about".to_owned(),
            crate::static_gen::ManifestEntry {
                file: "about/index.html".to_owned(),
                revalidate,
            },
        );

        let manifest = crate::static_gen::StaticManifest {
            generated_at: "2026-05-18T00:00:00Z".to_owned(),
            autumn_version: "0.5.0".to_owned(),
            routes,
        };
        let json = serde_json::to_string(&manifest).expect("serialize manifest");
        std::fs::write(dist.join("manifest.json"), json).expect("write manifest");
        dir
    }

    #[tokio::test]
    async fn static_serving_serves_get_request_inside_user_layers() {
        let tmp = create_static_dist(None);
        let dist = tmp.path().join("dist");
        let config = AutumnConfig::default();

        let router = try_build_router_with_static(Vec::new(), &config, test_state(), Some(&dist))
            .expect("router builds");

        let response = router
            .oneshot(
                Request::builder()
                    .uri("/about")
                    .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.as_ref(), b"<h1>About</h1>");
    }

    #[tokio::test]
    async fn static_serving_serves_head_request() {
        let tmp = create_static_dist(None);
        let dist = tmp.path().join("dist");
        let config = AutumnConfig::default();

        let router = try_build_router_with_static(Vec::new(), &config, test_state(), Some(&dist))
            .expect("router builds");

        let response = router
            .oneshot(
                Request::builder()
                    .method("HEAD")
                    .uri("/about")
                    .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!(body.is_empty(), "HEAD response body should be empty");
    }

    #[tokio::test]
    async fn static_serving_normalizes_trailing_slash() {
        let tmp = create_static_dist(None);
        let dist = tmp.path().join("dist");
        let config = AutumnConfig::default();

        let router = try_build_router_with_static(Vec::new(), &config, test_state(), Some(&dist))
            .expect("router builds");

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

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

    #[tokio::test]
    async fn static_serving_falls_through_for_unknown_route() {
        let tmp = create_static_dist(None);
        let dist = tmp.path().join("dist");
        let config = AutumnConfig::default();

        let router = try_build_router_with_static(Vec::new(), &config, test_state(), Some(&dist))
            .expect("router builds");

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

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

    #[tokio::test]
    async fn static_serving_skipped_when_no_manifest() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dist = tmp.path().join("dist");
        std::fs::create_dir_all(&dist).expect("mkdir dist");
        let config = AutumnConfig::default();

        let router = try_build_router_with_static(Vec::new(), &config, test_state(), Some(&dist))
            .expect("router builds even without manifest");

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

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

    #[tokio::test]
    async fn static_serving_with_isr_manifest_builds_successfully() {
        let tmp = create_static_dist(Some(3600));
        let dist = tmp.path().join("dist");
        let config = AutumnConfig::default();

        let router = try_build_router_with_static(Vec::new(), &config, test_state(), Some(&dist))
            .expect("router with ISR manifest should build");

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

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

#[cfg(test)]
mod trusted_host_tests {
    use super::*;
    use axum::body::Body;
    use http::Request;
    use tower::util::ServiceExt;

    #[tokio::test]
    async fn trusted_host_allows_matching_and_blocks_nonmatching() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into(), ".example.com".into()];
        let state = crate::state::AppState::for_test();
        let router = build_router(vec![], &cfg, state);

        let ok = router
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "api.example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(ok.status(), StatusCode::NOT_FOUND);

        let blocked = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "evil.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(blocked.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn trusted_host_wildcard_allows_any_host() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["*".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "anything.example")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn trusted_host_bypasses_probe_paths() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/actuator/health")
                    .header("host", "evil.com")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn trusted_host_bypasses_actuator_health_path() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/actuator/health")
                    .header("host", "evil.com")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::OK);
    }

    /// `probe_bypass_paths()` is meant to be the single canonical definition
    /// of "which exact paths bypass admission-style gates" — `TrustedHostPolicy`
    /// and `StartupBarrierState` must derive their own bypass sets from it
    /// rather than each re-implementing the same list, so a change to
    /// `probe_bypass_paths()` (or `config.health.*`) is automatically
    /// reflected in both without touching either of them directly.
    #[test]
    fn probe_bypass_paths_is_the_single_source_for_trusted_host_and_startup_barrier() {
        let mut cfg = AutumnConfig::default();
        cfg.health.path = "/custom-health-check".into();
        let expected = probe_bypass_paths(&cfg);
        assert!(expected.contains(&"/custom-health-check".to_string()));

        let trusted_host = TrustedHostPolicy::from_config(&cfg);
        for path in &expected {
            assert!(
                trusted_host.probe_bypass_paths.contains(path),
                "TrustedHostPolicy must derive its bypass set from probe_bypass_paths(): missing {path}"
            );
        }

        let state = crate::state::AppState::for_test();
        let barrier = StartupBarrierState::from_config(&cfg, &state);
        for path in &expected {
            assert!(
                barrier.allows_path(path),
                "StartupBarrierState must derive its bypass set from probe_bypass_paths(): missing {path}"
            );
        }
    }

    /// Regression guard (#1627): the `StartupBarrierState` allow-list, which is
    /// seeded from `actuator_endpoint_paths`, must permit the mutating
    /// `POST {prefix}/webhooks/replay` route to bypass the startup barrier. A
    /// prior fix removed the path from `actuator_endpoint_paths` to kill a
    /// phantom GET in the route listing, which also silently dropped it from
    /// this bypass set.
    #[cfg(feature = "http-client")]
    #[test]
    fn startup_barrier_allows_webhook_replay_post_path() {
        let mut cfg = AutumnConfig::default();
        cfg.actuator.sensitive = true;
        let state = crate::state::AppState::for_test();
        let barrier = StartupBarrierState::from_config(&cfg, &state);
        let replay_path =
            crate::actuator::actuator_route_path(&cfg.actuator.prefix, "/webhooks/replay");
        assert!(
            barrier.allows_path(&replay_path),
            "startup barrier must allow {replay_path} to bypass admission"
        );
    }

    #[tokio::test]
    async fn trusted_host_release_rejects_loopback_unless_listed() {
        let mut cfg = AutumnConfig {
            profile: Some("prod".into()),
            ..AutumnConfig::default()
        };
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "localhost")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn trusted_host_uses_uri_authority_when_host_header_missing() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("http://EXAMPLE.COM/nope")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn trusted_host_accepts_bracketed_ipv6_loopback_in_dev() {
        let cfg = AutumnConfig::default();
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "[::1]:3000")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn trusted_host_matching_is_case_insensitive() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "EXAMPLE.COM")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn trusted_host_rejects_malformed_port() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "example.com:abc")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn trusted_host_rejects_empty_port_suffix() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "example.com:")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn trusted_host_rejects_bracketed_reg_name() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "[example.com]")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }
    #[tokio::test]
    async fn trusted_host_configured_trailing_dot_matches_normalized_host() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com.".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "example.com")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn trusted_host_accepts_trailing_dot_fqdn() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .uri("/nope")
                    .header("host", "example.com.")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn trusted_host_bypasses_custom_probe_path_only() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        cfg.health.path = "/healthz".into();
        cfg.health.startup_path = "/startupz".into();
        cfg.health.ready_path = "/readyz".into();
        cfg.health.live_path = "/livez".into();
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());

        let bypassed = router
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/healthz")
                    .header("host", "evil.com")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(bypassed.status(), StatusCode::OK);

        let not_bypassed = router
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .header("host", "evil.com")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(not_bypassed.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn trusted_host_does_not_bypass_non_get_probe_path_requests() {
        let mut cfg = AutumnConfig::default();
        cfg.security.trusted_hosts.hosts = vec!["example.com".into()];
        let router = build_router(vec![], &cfg, crate::state::AppState::for_test());
        let response = router
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/health")
                    .header("host", "evil.com")
                    .body(Body::empty())
                    .expect("request should build"),
            )
            .await
            .expect("request should complete");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    // ── Global body-size limit (AC: DefaultBodyLimit covers all content types) ──

    #[tokio::test]
    async fn apply_upload_middleware_rejects_oversized_json_body() {
        let mut config = AutumnConfig::default();
        config.security.upload.max_request_size_bytes = 100; // 100-byte limit

        let base: axum::Router<AppState> = axum::Router::new().route(
            "/data",
            axum::routing::post(|_: axum::body::Bytes| async { "ok" }),
        );
        let router =
            apply_upload_middleware(base, &config).with_state(crate::state::AppState::for_test());

        // 200 bytes of JSON-shaped content exceeds the 100-byte cap.
        let big_body = "x".repeat(200);
        let response = router
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/data")
                    .header("content-type", "application/json")
                    .body(Body::from(big_body))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(
            response.status(),
            StatusCode::PAYLOAD_TOO_LARGE,
            "oversized body must be rejected with 413 regardless of content type"
        );
    }

    #[tokio::test]
    async fn apply_upload_middleware_accepts_body_within_limit() {
        let mut config = AutumnConfig::default();
        config.security.upload.max_request_size_bytes = 1024;

        let base: axum::Router<AppState> = axum::Router::new().route(
            "/data",
            axum::routing::post(|_: axum::body::Bytes| async { "ok" }),
        );
        let router =
            apply_upload_middleware(base, &config).with_state(crate::state::AppState::for_test());

        let response = router
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/data")
                    .header("content-type", "application/json")
                    .body(Body::from("hello"))
                    .unwrap(),
            )
            .await
            .unwrap();

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

    // ── Per-request timeout (AC: 503 on timeout, metrics, WARN log) ──────────

    /// Empty per-route override table (no route-level overrides).
    fn no_route_timeouts() -> RouteTimeoutTable {
        std::sync::Arc::new(std::collections::HashMap::new())
    }

    /// Build a single-entry override table for `GET <path>` (the method the
    /// unit-test routers below register).
    fn get_route_timeouts(path: &str, timeout: crate::route::RouteTimeout) -> RouteTimeoutTable {
        let mut by_method = std::collections::HashMap::new();
        by_method.insert(http::Method::GET, timeout);
        let mut table = std::collections::HashMap::new();
        table.insert(path.to_owned(), by_method);
        std::sync::Arc::new(table)
    }

    #[tokio::test(start_paused = true)]
    async fn request_timeout_returns_503_when_exceeded() {
        let mut config = AutumnConfig::default();
        config.server.timeouts.request_timeout_ms = Some(100);

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> = axum::Router::new().route(
            "/slow",
            axum::routing::get(|| async {
                // This sleep is much longer than the 100ms timeout.
                tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                "ok"
            }),
        );

        // Place timeout inner to RequestIdLayer (matches apply_middleware ordering).
        let router = apply_request_timeout_middleware(
            router,
            &config,
            state.metrics.clone(),
            no_route_timeouts(),
            false,
        )
        .layer(RequestIdLayer)
        .with_state(state);

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

        assert_eq!(
            response.status(),
            StatusCode::SERVICE_UNAVAILABLE,
            "a slow handler must trigger 503"
        );
        assert_eq!(
            response
                .headers()
                .get("content-type")
                .and_then(|v| v.to_str().ok()),
            Some("application/problem+json"),
            "timeout response must use Problem Details content type"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn request_timeout_increments_metric() {
        let mut config = AutumnConfig::default();
        config.server.timeouts.request_timeout_ms = Some(100);

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> = axum::Router::new().route(
            "/slow",
            axum::routing::get(|| async {
                tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                "ok"
            }),
        );

        let router = apply_request_timeout_middleware(
            router,
            &config,
            state.metrics.clone(),
            no_route_timeouts(),
            false,
        )
        .layer(RequestIdLayer)
        .with_state(state.clone());

        router
            .oneshot(Request::builder().uri("/slow").body(Body::empty()).unwrap())
            .await
            .unwrap();

        let snap = state.metrics.snapshot();
        assert_eq!(
            snap.http.request_timeouts_total, 1,
            "autumn_request_timeouts_total must be incremented on timeout"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn render_deadline_exempt_marker_skips_timeout() {
        let mut config = AutumnConfig::default();
        config.server.timeouts.request_timeout_ms = Some(100);

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> = axum::Router::new().route(
            "/slow",
            axum::routing::get(|| async {
                // Far longer than the 100ms deadline; the paused clock advances
                // automatically once the task is otherwise idle.
                tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                "ok"
            }),
        );

        let router = apply_request_timeout_middleware(
            router,
            &config,
            state.metrics.clone(),
            no_route_timeouts(),
            false,
        )
        .layer(RequestIdLayer)
        .with_state(state);

        // A live inbound request (no marker) is bounded by the deadline -> 503.
        let live = router
            .clone()
            .oneshot(Request::builder().uri("/slow").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(
            live.status(),
            StatusCode::SERVICE_UNAVAILABLE,
            "a live request to a slow handler must still time out"
        );

        // An internal build/ISR render carrying `RenderDeadlineExempt` is exempt
        // and runs to completion.
        let exempt = router
            .oneshot(
                Request::builder()
                    .uri("/slow")
                    .extension(crate::static_gen::RenderDeadlineExempt)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            exempt.status(),
            StatusCode::OK,
            "the build/ISR render marker must exempt the request from the deadline"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn request_timeout_503_mirrors_cors_headers() {
        let mut config = AutumnConfig::default();
        config.server.timeouts.request_timeout_ms = Some(100);
        // CORS is configured with a concrete allowlist (the reflected-origin path).
        config.cors.allowed_origins = vec!["https://app.example.com".to_owned()];
        config.cors.allow_credentials = true;

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> = axum::Router::new().route(
            "/slow",
            axum::routing::get(|| async {
                tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                "ok"
            }),
        );

        // `mirror_cors = true`, matching the main ingress stack where the timeout
        // layer is outside `CorsLayer` and the 503 would otherwise be opaque.
        let router = apply_request_timeout_middleware(
            router,
            &config,
            state.metrics.clone(),
            no_route_timeouts(),
            true,
        )
        .layer(RequestIdLayer)
        .with_state(state);

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

        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(
            response
                .headers()
                .get("access-control-allow-origin")
                .and_then(|v| v.to_str().ok()),
            Some("https://app.example.com"),
            "an allowed origin must be reflected on the timeout 503 so browsers can read it"
        );
        assert_eq!(
            response
                .headers()
                .get("access-control-allow-credentials")
                .and_then(|v| v.to_str().ok()),
            Some("true"),
            "credentials flag must be mirrored when configured"
        );
        assert!(
            response
                .headers()
                .get_all("vary")
                .iter()
                .any(|v| v.to_str().is_ok_and(|s| s.eq_ignore_ascii_case("origin"))),
            "a reflected origin must carry Vary: origin"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn request_timeout_503_omits_cors_for_disallowed_origin() {
        let mut config = AutumnConfig::default();
        config.server.timeouts.request_timeout_ms = Some(100);
        config.cors.allowed_origins = vec!["https://app.example.com".to_owned()];

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> = axum::Router::new().route(
            "/slow",
            axum::routing::get(|| async {
                tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                "ok"
            }),
        );

        let router = apply_request_timeout_middleware(
            router,
            &config,
            state.metrics.clone(),
            no_route_timeouts(),
            true,
        )
        .layer(RequestIdLayer)
        .with_state(state);

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

        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert!(
            response
                .headers()
                .get("access-control-allow-origin")
                .is_none(),
            "a disallowed origin must not be reflected, mirroring CorsLayer"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn request_timeout_response_includes_request_id_header() {
        let mut config = AutumnConfig::default();
        config.server.timeouts.request_timeout_ms = Some(100);

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> = axum::Router::new().route(
            "/slow",
            axum::routing::get(|| async {
                tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                "ok"
            }),
        );

        let router = apply_request_timeout_middleware(
            router,
            &config,
            state.metrics.clone(),
            no_route_timeouts(),
            false,
        )
        .layer(RequestIdLayer)
        .with_state(state);

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

        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        // X-Request-Id is added by RequestIdLayer on the egress path.
        assert!(
            response.headers().contains_key("x-request-id"),
            "503 response must carry the X-Request-Id header"
        );

        // The body must be a well-formed Problem Details document.
        let body_bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let body: serde_json::Value = serde_json::from_slice(&body_bytes).unwrap();
        assert_eq!(body["status"], 503);
    }

    #[tokio::test]
    async fn request_timeout_disabled_when_none() {
        let config = AutumnConfig::default(); // request_timeout_ms = None

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> =
            axum::Router::new().route("/fast", axum::routing::get(|| async { "pong" }));

        let router = apply_request_timeout_middleware(
            router,
            &config,
            state.metrics.clone(),
            no_route_timeouts(),
            false,
        )
        .with_state(state);

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

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

    #[tokio::test]
    async fn request_timeout_zero_treated_as_disabled() {
        let mut config = AutumnConfig::default();
        config.server.timeouts.request_timeout_ms = Some(0); // 0 = disabled

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> =
            axum::Router::new().route("/fast", axum::routing::get(|| async { "pong" }));

        let router = apply_request_timeout_middleware(
            router,
            &config,
            state.metrics.clone(),
            no_route_timeouts(),
            false,
        )
        .with_state(state);

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

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

    // Exercises the warn branch when no RequestIdLayer is present (no request_id
    // extension), keeping coverage of the `None` request-id arm.
    #[tokio::test(start_paused = true)]
    async fn request_timeout_503_without_request_id_layer() {
        let mut config = AutumnConfig::default();
        config.server.timeouts.request_timeout_ms = Some(100);

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> = axum::Router::new().route(
            "/slow",
            axum::routing::get(|| async {
                tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                "ok"
            }),
        );

        // No RequestIdLayer — exercises the else branch in request_timeout_handler.
        let router = apply_request_timeout_middleware(
            router,
            &config,
            state.metrics.clone(),
            no_route_timeouts(),
            false,
        )
        .with_state(state);

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

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

    // AC4: a per-route `Override` extends the deadline so a known-slow route
    // outlives the (smaller) global timeout.
    #[tokio::test(start_paused = true)]
    async fn request_timeout_per_route_override_extends_deadline() {
        let mut config = AutumnConfig::default();
        config.server.timeouts.request_timeout_ms = Some(100); // tight global

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> = axum::Router::new().route(
            "/export",
            axum::routing::get(|| async {
                // Longer than the 100ms global, shorter than the 10s override.
                tokio::time::sleep(std::time::Duration::from_secs(2)).await;
                "report"
            }),
        );

        let table = get_route_timeouts(
            "/export",
            crate::route::RouteTimeout::Override(std::time::Duration::from_secs(10)),
        );
        let router =
            apply_request_timeout_middleware(router, &config, state.metrics.clone(), table, false)
                .with_state(state);

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

        assert_eq!(
            response.status(),
            StatusCode::OK,
            "the override must let the slow route complete past the global deadline"
        );
    }

    // AC4: a per-route `Disabled` exempts the route from the global timeout.
    #[tokio::test(start_paused = true)]
    async fn request_timeout_per_route_disabled_exempts_route() {
        let mut config = AutumnConfig::default();
        config.server.timeouts.request_timeout_ms = Some(100);

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> = axum::Router::new().route(
            "/stream",
            axum::routing::get(|| async {
                tokio::time::sleep(std::time::Duration::from_secs(5)).await;
                "done"
            }),
        );

        let table = get_route_timeouts("/stream", crate::route::RouteTimeout::Disabled);
        let router =
            apply_request_timeout_middleware(router, &config, state.metrics.clone(), table, false)
                .with_state(state.clone());

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

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            state.metrics.snapshot().http.request_timeouts_total,
            0,
            "an exempt route must not record a timeout"
        );
    }

    // AC4: an `Override` enables the layer even when the global timeout is off.
    #[tokio::test(start_paused = true)]
    async fn request_timeout_override_active_when_global_disabled() {
        let config = AutumnConfig::default(); // global timeout disabled (None)

        let state = crate::state::AppState::for_test();
        let router: axum::Router<AppState> = axum::Router::new().route(
            "/export",
            axum::routing::get(|| async {
                tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                "report"
            }),
        );

        let table = get_route_timeouts(
            "/export",
            crate::route::RouteTimeout::Override(std::time::Duration::from_millis(100)),
        );
        let router =
            apply_request_timeout_middleware(router, &config, state.metrics.clone(), table, false)
                .with_state(state);

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

        assert_eq!(
            response.status(),
            StatusCode::SERVICE_UNAVAILABLE,
            "a per-route override must be enforced even with the global timeout off"
        );
    }

    #[test]
    fn build_route_timeout_table_is_empty_without_routes() {
        // End-to-end keying (top-level + nested groups) is covered by the
        // `request_timeout` integration tests via the macro attribute; here we
        // assert the no-route base case yields a zero-overhead empty table.
        let table = build_route_timeout_table(&[], &[]);
        assert!(table.is_empty(), "no routes ⇒ empty override table");
    }

    /// Build a minimal `Route` carrying just the fields `build_route_timeout_table`
    /// reads (method, path, timeout); the handler is a no-op.
    fn timeout_route(
        method: http::Method,
        path: &'static str,
        timeout: crate::route::RouteTimeout,
    ) -> Route {
        async fn noop() -> &'static str {
            "ok"
        }
        Route {
            method,
            path,
            handler: axum::routing::get(noop),
            name: "noop",
            api_doc: crate::openapi::ApiDoc::default(),
            repository: None,
            idempotency: crate::route::RouteIdempotency::Direct,
            timeout,
            api_version: None,
            sunset_opt_out: false,
        }
    }

    #[test]
    fn build_route_timeout_table_normalizes_method_aliases() {
        let override_10s = crate::route::RouteTimeout::Override(std::time::Duration::from_secs(10));
        let routes = vec![
            // A GET handler also serves HEAD in axum.
            timeout_route(http::Method::GET, "/export", override_10s),
            // A `#[ws]` route records the synthetic `WS` method but the upgrade
            // arrives as GET.
            timeout_route(
                http::Method::from_bytes(b"WS").unwrap(),
                "/live",
                crate::route::RouteTimeout::Disabled,
            ),
            // A non-aliased method keys only itself.
            timeout_route(http::Method::POST, "/submit", override_10s),
        ];

        let table = build_route_timeout_table(&routes, &[]);

        // GET override is reachable via both GET and HEAD.
        let export = table.get("/export").expect("/export keyed");
        assert_eq!(export.get(&http::Method::GET), Some(&override_10s));
        assert_eq!(
            export.get(&http::Method::HEAD),
            Some(&override_10s),
            "a GET override must also cover the HEAD alias axum serves"
        );

        // WS override is reachable via the GET the upgrade actually uses, and is
        // NOT left under the synthetic `WS` method the lookup never sees.
        let live = table.get("/live").expect("/live keyed");
        assert_eq!(
            live.get(&http::Method::GET),
            Some(&crate::route::RouteTimeout::Disabled),
            "a WS override must be keyed under the GET the upgrade arrives as"
        );
        assert!(
            live.get(&http::Method::from_bytes(b"WS").unwrap())
                .is_none(),
            "the synthetic WS method is never seen at lookup time"
        );

        // A non-aliased method keys only itself — no HEAD bleed.
        let submit = table.get("/submit").expect("/submit keyed");
        assert_eq!(submit.get(&http::Method::POST), Some(&override_10s));
        assert!(submit.get(&http::Method::HEAD).is_none());
    }

    #[test]
    fn build_route_timeout_table_keys_scoped_root_by_axum_matched_path() {
        // A scoped group whose prefix carries a trailing slash mounts its `/`
        // child at "/api/" in axum (verified by
        // `join_nested_path_matches_axum_matched_path`), so the override must be
        // keyed there — not at "/api" — or the runtime `MatchedPath` lookup
        // misses and the per-route timeout is silently never enforced.
        let override_5s = crate::route::RouteTimeout::Override(std::time::Duration::from_secs(5));
        let make_group = |prefix: &str| crate::app::ScopedGroup {
            prefix: prefix.to_owned(),
            routes: vec![timeout_route(http::Method::GET, "/", override_5s)],
            source: crate::route_listing::RouteSource::User,
            apply_layer: Box::new(|r| r),
        };

        let table = build_route_timeout_table(&[], &[make_group("/api/")]);
        assert_eq!(
            table.get("/api/").and_then(|m| m.get(&http::Method::GET)),
            Some(&override_5s),
            "trailing-slash scoped root must key the override at /api/"
        );
        assert!(
            table.get("/api").is_none(),
            "the stripped /api key would never match the runtime lookup"
        );

        // The no-trailing-slash form still keys at "/api".
        let table = build_route_timeout_table(&[], &[make_group("/api")]);
        assert_eq!(
            table.get("/api").and_then(|m| m.get(&http::Method::GET)),
            Some(&override_5s),
        );
    }

    // ----------------------------------------------------------------------
    // static_gate: middleware that runs before the static cache lookup (#848)
    // ----------------------------------------------------------------------

    /// Build a `CustomLayerRegistration` wrapping a `from_fn` gate that
    /// redirects (302 → /login) any request lacking an `x-authed` header.
    fn redirect_gate_registration() -> crate::app::CustomLayerRegistration {
        let gate = axum::middleware::from_fn(
            |req: axum::extract::Request, next: axum::middleware::Next| async move {
                if req.headers().contains_key("x-authed") {
                    next.run(req).await
                } else {
                    http::Response::builder()
                        .status(StatusCode::FOUND)
                        .header(http::header::LOCATION, "/login")
                        .body(Body::empty())
                        .unwrap()
                }
            },
        );
        crate::app::CustomLayerRegistration {
            type_id: std::any::TypeId::of::<()>(),
            type_name: "redirect_gate",
            apply: Box::new(move |router| router.layer(gate)),
        }
    }

    /// Create a minimal dist dir with `manifest.json` mapping `/` → an
    /// `index.html` containing the marker text, and return the temp handle
    /// plus the dist path.
    fn build_cached_dist(marker: &str) -> (tempfile::TempDir, std::path::PathBuf) {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dist = tmp.path().join("dist");
        std::fs::create_dir_all(&dist).expect("create dist");
        std::fs::write(dist.join("index.html"), marker).expect("write index.html");
        let mut routes = std::collections::HashMap::new();
        routes.insert(
            "/".to_owned(),
            crate::static_gen::ManifestEntry {
                file: "index.html".to_owned(),
                revalidate: None,
            },
        );
        let manifest = crate::static_gen::StaticManifest {
            generated_at: "2026-06-14T00:00:00Z".to_owned(),
            autumn_version: "0.3.0".to_owned(),
            routes,
        };
        std::fs::write(
            dist.join("manifest.json"),
            serde_json::to_string(&manifest).expect("serialize manifest"),
        )
        .expect("write manifest");
        (tmp, dist)
    }

    fn ctx_with_static_gate(gate: crate::app::CustomLayerRegistration) -> RouterContext {
        RouterContext {
            exception_filters: Vec::new(),
            scoped_groups: Vec::new(),
            merge_routers: Vec::new(),
            nest_routers: Vec::new(),
            custom_layers: Vec::new(),
            static_gate_layers: vec![gate],
            #[cfg(feature = "maud")]
            error_page_renderer: None,
            session_store: None,
            #[cfg(feature = "openapi")]
            openapi: None,
            #[cfg(feature = "mcp")]
            mcp: None,
        }
    }

    #[tokio::test]
    async fn static_gate_runs_before_cached_static_page() {
        // A cached SSG page exists at "/". The static_gate must intercept the
        // request BEFORE the static-first middleware serves the pre-rendered
        // HTML, redirecting unauthenticated visitors.
        let (_tmp, dist) = build_cached_dist("<h1>cached</h1>");
        let config = AutumnConfig::default();
        let ctx = ctx_with_static_gate(redirect_gate_registration());

        let app = super::try_build_router_with_static_inner(
            Vec::new(),
            &config,
            crate::state::AppState::for_test(),
            Some(dist.as_path()),
            ctx,
        )
        .expect("router builds");

        // Unauthenticated: gate fires before the cached page is served.
        let unauthed = app
            .clone()
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(
            unauthed.status(),
            StatusCode::FOUND,
            "static_gate must redirect before the cached page is served"
        );
        assert_eq!(
            unauthed.headers().get(http::header::LOCATION).unwrap(),
            "/login"
        );

        // Authenticated: gate passes through and the cached HTML is served.
        let authed = app
            .oneshot(
                Request::builder()
                    .uri("/")
                    .header("x-authed", "1")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(authed.status(), StatusCode::OK);
        let body = axum::body::to_bytes(authed.into_body(), usize::MAX)
            .await
            .unwrap();
        assert!(
            String::from_utf8_lossy(&body).contains("cached"),
            "authenticated request should receive the cached page"
        );
    }

    #[tokio::test]
    async fn static_gate_runs_in_dynamic_mode() {
        // With no dist dir, the same gate must still run as the outermost
        // middleware so auth-gating code is portable across SSG and dynamic
        // modes.
        async fn dynamic_handler() -> &'static str {
            "dynamic"
        }
        let route = Route {
            method: http::Method::GET,
            path: "/",
            handler: axum::routing::get(dynamic_handler),
            name: "root",
            api_doc: crate::openapi::ApiDoc {
                method: "GET",
                path: "/",
                operation_id: "root",
                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 ctx = ctx_with_static_gate(redirect_gate_registration());

        let app = super::try_build_router_with_static_inner(
            vec![route],
            &config,
            crate::state::AppState::for_test(),
            None,
            ctx,
        )
        .expect("router builds");

        let unauthed = app
            .clone()
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(unauthed.status(), StatusCode::FOUND);

        let authed = app
            .oneshot(
                Request::builder()
                    .uri("/")
                    .header("x-authed", "1")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(authed.status(), StatusCode::OK);
        let body = axum::body::to_bytes(authed.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(String::from_utf8_lossy(&body), "dynamic");
    }

    #[tokio::test]
    async fn static_gate_redirect_carries_security_headers_ssg() {
        // A gate short-circuit (302) must still carry the framework security
        // headers — SecurityHeadersLayer wraps the gate in the SSG path.
        let (_tmp, dist) = build_cached_dist("<h1>cached</h1>");
        let config = AutumnConfig::default();
        let ctx = ctx_with_static_gate(redirect_gate_registration());

        let app = super::try_build_router_with_static_inner(
            Vec::new(),
            &config,
            crate::state::AppState::for_test(),
            Some(dist.as_path()),
            ctx,
        )
        .expect("router builds");

        let unauthed = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(unauthed.status(), StatusCode::FOUND);
        // X-Content-Type-Options: nosniff is applied by SecurityHeadersLayer by
        // default; its presence proves the layer wraps the gate's response.
        assert_eq!(
            unauthed
                .headers()
                .get("x-content-type-options")
                .expect("gate redirect must carry security headers"),
            "nosniff"
        );
    }

    #[tokio::test]
    async fn static_gate_redirect_carries_security_headers_dynamic() {
        // Same contract in fully-dynamic mode (no dist): SecurityHeadersLayer is
        // the framework's outermost layer, so a gate short-circuit still carries
        // HSTS/CSP/nosniff. Guards against the dynamic/SSG inconsistency.
        async fn dynamic_handler() -> &'static str {
            "dynamic"
        }
        let route = Route {
            method: http::Method::GET,
            path: "/",
            handler: axum::routing::get(dynamic_handler),
            name: "root",
            api_doc: crate::openapi::ApiDoc {
                method: "GET",
                path: "/",
                operation_id: "root",
                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 ctx = ctx_with_static_gate(redirect_gate_registration());

        let app = super::try_build_router_with_static_inner(
            vec![route],
            &config,
            crate::state::AppState::for_test(),
            None,
            ctx,
        )
        .expect("router builds");

        let unauthed = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(unauthed.status(), StatusCode::FOUND);
        assert_eq!(
            unauthed
                .headers()
                .get("x-content-type-options")
                .expect("dynamic gate redirect must carry security headers"),
            "nosniff"
        );
    }

    #[test]
    fn static_gate_layer_requires_fail_closed_idempotency() {
        // A static_gate (e.g. a JWT/auth layer) is an opaque app layer for
        // idempotency: it must force fail-closed replay so a cached mutation
        // can't be served to a different principal sharing an Idempotency-Key.
        let gate = vec![redirect_gate_registration()];
        assert!(super::custom_layers_require_fail_closed_idempotency(&gate));
        // An empty set requires no fail-closed behaviour.
        assert!(!super::custom_layers_require_fail_closed_idempotency(&[]));
    }
}
#[derive(Clone, Debug)]
pub struct TrustedHostPolicy {
    rules: Arc<Vec<String>>,
    allow_any: bool,
    allow_missing_host: bool,
    probe_bypass_paths: Arc<std::collections::HashSet<String>>,
}

impl TrustedHostPolicy {
    pub fn from_config(config: &AutumnConfig) -> Self {
        let mut rules: Vec<String> = config
            .security
            .trusted_hosts
            .hosts
            .iter()
            .map(|h| h.trim().to_ascii_lowercase())
            .map(|h| h.trim_end_matches('.').to_owned())
            .filter(|h| !h.is_empty())
            .collect();
        let is_production = matches!(config.profile.as_deref(), Some("prod" | "production"));
        if !is_production {
            rules.extend(
                ["localhost", "127.0.0.1", "::1"]
                    .into_iter()
                    .map(std::borrow::ToOwned::to_owned),
            );
        }
        let allow_any = rules.iter().any(|h| h == "*");
        let probe_bypass_paths = probe_bypass_paths(config).into_iter().collect();
        Self {
            rules: Arc::new(rules),
            allow_any,
            allow_missing_host: !is_production,
            probe_bypass_paths: Arc::new(probe_bypass_paths),
        }
    }

    /// Whether a request carrying no usable `Host` is allowed through. Mirrors
    /// `trusted_host_middleware`'s missing-host branch for callers (e.g. the MCP
    /// envelope) that enforce the policy outside that middleware.
    ///
    /// Only the `mcp` feature consumes this today; gated so default-feature
    /// builds don't flag it as dead code.
    #[cfg(feature = "mcp")]
    pub const fn allows_missing_host(&self) -> bool {
        self.allow_missing_host
    }

    pub fn allows_host(&self, host: &str) -> bool {
        if self.allow_any {
            return true;
        }
        self.rules.iter().any(|rule| {
            rule.strip_prefix('.').map_or_else(
                || host == rule,
                |suffix| {
                    host == suffix
                        || host
                            .strip_suffix(suffix)
                            .is_some_and(|prefix| prefix.ends_with('.'))
                },
            )
        })
    }
}

/// Metadata carrying API version, sunset opt-out, and security configuration for a route.
#[derive(Clone, Debug)]
pub struct RouteVersionMetadata {
    pub version: String,
    pub sunset_opt_out: bool,
    pub secured: bool,
    pub required_roles: &'static [&'static str],
    pub has_policy: bool,
}

/// Middleware that handles API deprecation, sunsets, and Gone responses.
async fn api_versioning_middleware(
    state: axum::extract::State<AppState>,
    route_version: Option<axum::extract::Extension<RouteVersionMetadata>>,
    request: axum::http::Request<axum::body::Body>,
    next: axum::middleware::Next,
) -> axum::response::Response {
    let Some(axum::extract::Extension(meta)) = route_version else {
        return next.run(request).await;
    };

    let clock = state.clock();
    let now = clock.now();

    let versions = state.extension::<crate::app::RegisteredApiVersions>();
    let matching_version = versions
        .as_ref()
        .and_then(|v| v.0.iter().find(|av| av.version == meta.version));

    let Some(version) = matching_version else {
        return next.run(request).await;
    };

    let is_deprecated = version.deprecated_at.is_some_and(|d| now >= d);
    let is_sunset = version.sunset_at.is_some_and(|s| now >= s);

    if is_sunset && !meta.sunset_opt_out {
        if meta.has_policy {
            return next.run(request).await;
        }
        if meta.secured {
            let session = request.extensions().get::<crate::session::Session>();
            let mut auth_failed = false;
            let mut auth_error = None;
            if let Some(session) = session {
                if let Err(err) = crate::auth::__check_secured_with_key(
                    session,
                    state.auth_session_key(),
                    meta.required_roles,
                )
                .await
                {
                    auth_failed = true;
                    auth_error = Some(err);
                }
            } else {
                auth_failed = true;
                auth_error = Some(crate::error::AutumnError::unauthorized_msg(
                    "authentication required",
                ));
            }
            if auth_failed {
                return auth_error.unwrap().into_response();
            }
        }

        let err = crate::error::AutumnError::gone_msg(format!(
            "API version '{}' has been sunsetted.",
            meta.version
        ));
        let mut response = err.into_response();
        if let Some(sunset) = version.sunset_at {
            let http_date = sunset.format("%a, %d %b %Y %H:%M:%S GMT").to_string();
            if let Ok(val) = axum::http::HeaderValue::from_str(&http_date) {
                response.headers_mut().insert("Sunset", val);
            }
        }
        let deprecation_date = match (version.deprecated_at, version.sunset_at) {
            (Some(d), Some(s)) => Some(d.min(s)),
            (d, s) => d.or(s),
        };
        if let Some(date) = deprecation_date {
            let timestamp = date.timestamp();
            if let Ok(val) = axum::http::HeaderValue::from_str(&format!("@{timestamp}")) {
                response.headers_mut().insert("Deprecation", val);
            }
        }
        return response;
    }

    let mut response = next.run(request).await;

    if is_deprecated || is_sunset {
        let deprecation_date = match (version.deprecated_at, version.sunset_at) {
            (Some(d), Some(s)) => Some(d.min(s)),
            (d, s) => d.or(s),
        };
        if let Some(date) = deprecation_date {
            let timestamp = date.timestamp();
            if let Ok(val) = axum::http::HeaderValue::from_str(&format!("@{timestamp}")) {
                response.headers_mut().insert("Deprecation", val);
            }
        }
    }
    if let Some(sunset) = version.sunset_at.filter(|_| is_deprecated || is_sunset) {
        let http_date = sunset.format("%a, %d %b %Y %H:%M:%S GMT").to_string();
        if let Ok(val) = axum::http::HeaderValue::from_str(&http_date) {
            response.headers_mut().insert("Sunset", val);
        }
    }

    response
}

/// Helper function to perform a sunset check during dynamic handler execution.
/// Returns a `410 Gone` response if the route version has sunsetted.
#[must_use]
pub fn check_sunset(
    state: &crate::state::AppState,
    meta: &RouteVersionMetadata,
) -> Option<axum::response::Response> {
    let clock = state.clock();
    let now = clock.now();

    let versions = state.extension::<crate::app::RegisteredApiVersions>();
    let matching_version = versions
        .as_ref()
        .and_then(|v| v.0.iter().find(|av| av.version == meta.version));

    let version = matching_version?;
    let is_sunset = version.sunset_at.is_some_and(|s| now >= s);

    if is_sunset && !meta.sunset_opt_out {
        let err = crate::error::AutumnError::gone_msg(format!(
            "API version '{}' has been sunsetted.",
            meta.version
        ));
        let mut response = axum::response::IntoResponse::into_response(err);
        if let Some(sunset) = version.sunset_at {
            let http_date = sunset.format("%a, %d %b %Y %H:%M:%S GMT").to_string();
            if let Ok(val) = axum::http::HeaderValue::from_str(&http_date) {
                response.headers_mut().insert("Sunset", val);
            }
        }
        let deprecation_date = match (version.deprecated_at, version.sunset_at) {
            (Some(d), Some(s)) => Some(d.min(s)),
            (d, s) => d.or(s),
        };
        if let Some(date) = deprecation_date {
            let timestamp = date.timestamp();
            if let Ok(val) = axum::http::HeaderValue::from_str(&format!("@{timestamp}")) {
                response.headers_mut().insert("Deprecation", val);
            }
        }
        return Some(response);
    }

    None
}

#[cfg(all(test, feature = "htmx"))]
mod idiomorph_tests {
    use super::*;
    use http::StatusCode;
    use http_body_util::BodyExt;

    #[tokio::test]
    async fn idiomorph_handler_returns_js_with_correct_headers() {
        let response = idiomorph_handler().await;

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

        let ct = response
            .headers()
            .get(http::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");
        assert_eq!(ct, "application/javascript");

        let cc = response
            .headers()
            .get(http::header::CACHE_CONTROL)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");
        // The idiomorph URL is not content-fingerprinted, so the response must
        // revalidate rather than advertise a year-long `immutable` cache. This
        // guards against returning clients running a stale copy after the
        // vendored bytes change.
        assert!(
            cc.contains("must-revalidate"),
            "expected revalidating cache-control, got: {cc}"
        );
        assert!(
            !cc.contains("immutable"),
            "cache-control must not be immutable for a non-fingerprinted URL, got: {cc}"
        );

        // A weak, content-derived ETag lets caches revalidate (and pick up new
        // bytes when the script changes). It is weak rather than strong because
        // compression middleware may re-encode this response after the handler
        // attaches the validator, so the identity/gzip/br variants share a tag
        // despite differing byte streams.
        let etag = response
            .headers()
            .get(http::header::ETAG)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");
        assert!(
            etag.starts_with("W/\"idiomorph-") && etag.ends_with('"'),
            "expected a weak quoted idiomorph ETag, got: {etag}"
        );

        let body = response.into_body().collect().await.unwrap().to_bytes();
        assert!(!body.is_empty(), "idiomorph JS body must be non-empty");
    }
}

#[cfg(test)]
mod proptests {
    //! Property-based invariants for the low-level path/host string helpers.
    //! These are `pub(crate)` (only reachable via the `cfg(fuzzing)` seam
    //! module), so they are exercised here in-crate rather than from an
    //! integration test.
    use super::*;
    use proptest::prelude::*;

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(256))]

        /// Mounting the root child (`"/"` or empty) is the identity on a
        /// non-empty prefix, and idempotent: re-mounting the root child on the
        /// result leaves it unchanged. (An empty prefix collapses to `"/"`.)
        #[test]
        fn join_nested_path_root_child_is_identity(prefix in "/?[a-z0-9/]{0,20}", root in prop::sample::select(vec!["/", ""])) {
            let once = join_nested_path(&prefix, root);
            let expected = if prefix.is_empty() { "/".to_owned() } else { prefix };
            prop_assert_eq!(&once, &expected);
            let twice = join_nested_path(&once, root);
            prop_assert_eq!(once, twice);
        }

        /// `join_nested_path` never introduces a doubled slash at the join seam
        /// for well-formed single-segment children.
        #[test]
        fn join_nested_path_no_double_slash_at_seam(prefix in "/[a-z0-9]{1,8}/?", child in "/[a-z0-9]{1,8}") {
            let joined = join_nested_path(&prefix, &child);
            prop_assert!(!joined.contains("//"), "unexpected `//` in {joined:?}");
        }

        /// `extract_host_without_port` never panics on arbitrary input and,
        /// when it returns something, that something is a substring of the
        /// trimmed input (it only ever strips a port / brackets, never invents
        /// characters).
        #[test]
        fn extract_host_without_port_never_panics(header in ".*") {
            if let Some(host) = extract_host_without_port(&header) {
                prop_assert!(header.contains(host));
            }
        }

        /// `path_matches_route_prefix` never panics and is reflexive: a path
        /// always matches itself as a prefix.
        #[test]
        fn path_matches_route_prefix_reflexive(path in ".*") {
            prop_assert!(path_matches_route_prefix(&path, &path));
        }

        /// `path_matches_route_prefix` is consistent with its documented
        /// contract: a match means either exact equality or a `/`-delimited
        /// boundary immediately after the prefix.
        #[test]
        fn path_matches_route_prefix_boundary(path in "/?[a-z0-9/]{0,24}", prefix in "/?[a-z0-9/]{0,24}") {
            if path_matches_route_prefix(&path, &prefix) {
                let boundary_ok = path == prefix
                    || path.strip_prefix(&prefix).is_some_and(|rest| rest.starts_with('/'));
                prop_assert!(boundary_ok, "match without boundary: path={path:?} prefix={prefix:?}");
            }
        }
    }

    // `extract_path_params` (openapi-only) never panics on arbitrary input and
    // only ever returns non-empty, brace-free parameter names.
    #[cfg(feature = "openapi")]
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(256))]

        #[test]
        fn extract_path_params_never_panics(path in ".*") {
            for name in extract_path_params(&path) {
                prop_assert!(!name.is_empty());
                let has_brace = name.contains('{') || name.contains('}');
                prop_assert!(!has_brace, "param name should be brace-free: {name:?}");
            }
        }

        /// Brace-dense variant of the invariant above. `.*` makes brace
        /// characters astronomically rare, so unbalanced-brace inputs like
        /// `"{{}"` (the #1721 regression) only surface via lucky CI seeds. This
        /// strategy draws exclusively from brace/colon/letter characters so
        /// malformed braces are exercised on nearly every case, and a committed
        /// regression seed (proptest-regressions/router.txt) pins a brace-dense
        /// input (which replays to `"{{iw:}"` under this strategy) that trips the
        /// pre-fix brace-in-name bug deterministically.
        #[test]
        fn extract_path_params_brace_inputs_are_brace_free(path in "[{}a-z:]{0,6}") {
            for name in extract_path_params(&path) {
                prop_assert!(!name.is_empty());
                let has_brace = name.contains('{') || name.contains('}');
                prop_assert!(!has_brace, "param name should be brace-free for {path:?}: {name:?}");
            }
        }
    }
}