autumn-cli 0.6.0

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

use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
use std::path::Path;

use super::dsl::{Field, FieldKind, IdType, parse_fields};
use super::emit::{Action, Plan, Revert};
use super::model::{
    ModelOptions, augment_fields_for_soft_delete, field_by_name, parse_model_metadata,
    plan_cargo_deps, plan_model_with_options,
};
use super::naming::{humanize_label, pascal, pluralize, snake};
use super::schema_edit::{
    add_mod_declaration, create_table_sql_with_metadata_and_id, ensure_autumn_web_feature,
    ensure_dependency_feature, ensure_dev_dependency_test_support,
    ensure_dev_dependency_tokio_test_features, unique_index_name, update_main_rs,
};
use super::{GenerateError, ensure_project_root, read_or_empty};

/// Extra dependencies the *scaffold* generator's output requires on top of
/// [`super::model::MODEL_DEPS`] — `maud` for HTML rendering and URL-encoded
/// form helpers for blank nullable-field normalization.
pub(super) const SCAFFOLD_EXTRA_DEPS: &[(&str, &str)] = &[
    ("maud", "{ version = \"0.27\", features = [\"axum\"] }"),
    ("serde_urlencoded", "\"0.7\""),
    ("url", "\"2\""),
];

/// Optional metadata applied by `autumn generate scaffold`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[allow(clippy::struct_excessive_bools)] // independent scaffold flags, not a state machine
pub struct ScaffoldOptions {
    /// Model-level field metadata.
    pub model: ModelOptions,
    /// Repository derived-query specs in `method:field` form.
    pub queries: Vec<String>,
    /// Scaffold a JSON-only API resource.
    pub api: bool,
    /// Emit `broadcasts = true` on the repository, a `LiveFragment` impl,
    /// an SSE events route, and an SSE-wired list container in the index view.
    pub live: bool,
    /// Emit per-field inline validation endpoints and `hx-post` attributes on
    /// form inputs (requires `--live`).
    pub live_validation: bool,
    /// Opt out of generating a record-level authorization `Policy`/`Scope` for
    /// the resource (issue #1125). `false` (the default) generates the policy,
    /// registers it, and — when an owner column is detected on the standard
    /// (non-live, non-sharded) path — authorizes the mutating HTML handlers and
    /// scopes the index. `--api` scaffolds never generate a policy.
    pub no_policy: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct QuerySpec {
    method: String,
    field_name: String,
    rust_type: String,
}

/// Whether `src/main.rs` source (as generated by `autumn new`) exposes a
/// shared 4-arg `pub fn layout(...)` that the scaffold's generated routes can
/// render through via `crate::layout(title, current_path, flash, content)`.
///
/// The scan is lexically aware: a `pub fn layout` token that falls inside a
/// line comment (`//`), a (possibly nested) block comment (`/* ... */`), a
/// normal or raw string literal, or a char literal is ignored — only tokens in
/// real code count. This prevents both a *commented* example from falsely
/// satisfying the check and a commented decoy appearing before the real
/// definition from falsely rejecting it. ALL real candidates are considered
/// (not just the first), so any one genuine 4-arg `pub fn layout` accepts.
///
/// `layout` must be a complete token — the character after it is `(`, `<`, or
/// whitespace — so decoys like `pub fn layout_sidebar` are ignored. Malformed
/// input (unterminated paren/comment/string) simply contributes no arity.
pub fn has_shared_layout(main_src: &str) -> bool {
    layout_param_counts(main_src).into_iter().any(|n| n == 4)
}

/// Collect the top-level parameter counts of every real (non-comment,
/// non-string) `pub fn layout(...)` token in `main_src`.
fn layout_param_counts(main_src: &str) -> Vec<usize> {
    const NEEDLE: &[u8] = b"pub fn layout";
    let bytes = main_src.as_bytes();
    let mut counts = Vec::new();
    let mut i = 0;
    // Walk the source tracking lexical state so `pub fn layout` occurrences
    // inside comments/strings/char literals are skipped. When in normal code,
    // a needle match yields a candidate whose arity we parse.
    while i < bytes.len() {
        if bytes[i..].starts_with(NEEDLE) {
            if let Some(count) = layout_arity_at(bytes, i + NEEDLE.len()) {
                counts.push(count);
            }
            i += NEEDLE.len();
            continue;
        }
        match bytes[i] {
            // Line comment: skip to end of line.
            b'/' if bytes.get(i + 1) == Some(&b'/') => {
                i += 2;
                while i < bytes.len() && bytes[i] != b'\n' {
                    i += 1;
                }
            }
            // Block comment: Rust block comments nest, so track depth.
            b'/' if bytes.get(i + 1) == Some(&b'*') => {
                i += 2;
                let mut depth = 1u32;
                while i < bytes.len() && depth > 0 {
                    if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') {
                        depth += 1;
                        i += 2;
                    } else if bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/') {
                        depth -= 1;
                        i += 2;
                    } else {
                        i += 1;
                    }
                }
            }
            // Raw string `r"..."` / `r#"..."#` (also byte variant `br...`).
            b'r' | b'b' if is_raw_string_start(bytes, i) && !prev_is_ident_char(bytes, i) => {
                i = skip_raw_string(bytes, i);
            }
            // Normal string literal (respecting `\"` escapes).
            b'"' => {
                i += 1;
                while i < bytes.len() {
                    match bytes[i] {
                        b'\\' => i += 2,
                        b'"' => {
                            i += 1;
                            break;
                        }
                        _ => i += 1,
                    }
                }
            }
            // Char literal `'x'` / `'\n'` — but not a lifetime like `'a`.
            b'\'' => {
                if bytes.get(i + 1) == Some(&b'\\') {
                    // Escaped char literal: skip to the closing quote.
                    i += 2;
                    while i < bytes.len() && bytes[i] != b'\'' {
                        i += 1;
                    }
                    i += 1;
                } else if bytes.get(i + 2) == Some(&b'\'') {
                    i += 3;
                } else {
                    // Lifetime or label: treat the quote as ordinary punctuation.
                    i += 1;
                }
            }
            _ => i += 1,
        }
    }
    counts
}

/// Whether a raw string literal begins at `start` (`r"`, `r#"`, `br"`, …).
fn is_raw_string_start(bytes: &[u8], start: usize) -> bool {
    let mut i = start;
    if bytes.get(i) == Some(&b'b') {
        i += 1;
    }
    if bytes.get(i) != Some(&b'r') {
        return false;
    }
    i += 1;
    while bytes.get(i) == Some(&b'#') {
        i += 1;
    }
    bytes.get(i) == Some(&b'"')
}

/// Advance past a raw string literal beginning at `start`, matching the opening
/// hash count. Returns the index just past the closing delimiter (or the end of
/// input if the literal is unterminated).
fn skip_raw_string(bytes: &[u8], start: usize) -> usize {
    let mut i = start;
    if bytes.get(i) == Some(&b'b') {
        i += 1;
    }
    // `r`
    i += 1;
    let mut hashes = 0usize;
    while bytes.get(i) == Some(&b'#') {
        hashes += 1;
        i += 1;
    }
    // Opening `"`
    i += 1;
    // Scan for the closing `"` followed by `hashes` `#`.
    while i < bytes.len() {
        if bytes[i] == b'"' {
            let close = i + 1;
            if close + hashes <= bytes.len()
                && bytes[close..close + hashes].iter().all(|&b| b == b'#')
            {
                return close + hashes;
            }
        }
        i += 1;
    }
    bytes.len()
}

/// Whether the byte before `i` is an identifier-continuation char, used to
/// avoid mistaking a trailing `r`/`b` inside an identifier for a raw string.
fn prev_is_ident_char(bytes: &[u8], i: usize) -> bool {
    i > 0 && (bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_')
}

/// Parse the top-level parameter count of a `pub fn layout` whose name ends at
/// `after_name` (the byte index just past `layout`).
///
/// Returns `None` when `layout` is not a complete token (the next char is an
/// identifier char, e.g. `layout_sidebar`) or the parameter list can't be
/// parsed (no matching close paren). Top-level parameters are counted by commas
/// not nested inside `(...)`, `[...]`, or `<...>`, so generic/tuple/array types
/// in a parameter don't inflate the count.
fn layout_arity_at(bytes: &[u8], after_name: usize) -> Option<usize> {
    // `layout` must be a whole token: the following char is `(`, `<`, or
    // whitespace, so `layout_sidebar` and similar decoys don't count.
    match bytes.get(after_name) {
        Some(b'(' | b'<') => {}
        Some(c) if c.is_ascii_whitespace() => {}
        _ => return None,
    }

    let mut i = after_name;
    // Skip whitespace and an optional generic parameter block `<...>` that may
    // precede the argument list.
    while i < bytes.len() && bytes[i].is_ascii_whitespace() {
        i += 1;
    }
    if i < bytes.len() && bytes[i] == b'<' {
        let mut depth = 0i32;
        while i < bytes.len() {
            match bytes[i] {
                b'<' => depth += 1,
                b'>' => {
                    depth -= 1;
                    if depth == 0 {
                        i += 1;
                        break;
                    }
                }
                _ => {}
            }
            i += 1;
        }
        while i < bytes.len() && bytes[i].is_ascii_whitespace() {
            i += 1;
        }
    }
    // The argument list must open here.
    if i >= bytes.len() || bytes[i] != b'(' {
        return None;
    }

    // Walk to the matching `)`, counting commas that sit at the top level of
    // the argument list (paren depth 1, no angle/bracket nesting).
    let mut paren = 0i32;
    let mut angle = 0i32;
    let mut bracket = 0i32;
    let mut commas = 0usize;
    let mut saw_param = false;
    let mut closed = false;
    while i < bytes.len() {
        match bytes[i] {
            b'(' => paren += 1,
            b')' => {
                paren -= 1;
                if paren == 0 {
                    closed = true;
                    break;
                }
            }
            b'[' => bracket += 1,
            b']' => bracket -= 1,
            b'<' => angle += 1,
            // Guard against `->` return arrows / comparison operators nested in
            // a parameter type: only close an actually-open angle group.
            b'>' if angle > 0 => angle -= 1,
            b',' if paren == 1 && angle == 0 && bracket == 0 => commas += 1,
            b' ' | b'\t' | b'\r' | b'\n' | b'>' => {}
            _ => saw_param = true,
        }
        i += 1;
    }
    if !closed {
        return None;
    }
    if !saw_param {
        return Some(0);
    }
    Some(commas + 1)
}

/// Compute the file actions for `autumn generate scaffold`.
///
/// # Errors
/// Surfaces any planning error from the underlying [`plan_model`] call as
/// well as project-layout problems (missing `src/main.rs`).
#[cfg(test)]
pub fn plan_scaffold(
    project_root: &Path,
    name: &str,
    field_tokens: &[String],
    timestamp: &str,
) -> Result<Plan, GenerateError> {
    plan_scaffold_with_options(
        project_root,
        name,
        field_tokens,
        timestamp,
        &ScaffoldOptions::default(),
    )
}

/// Compute the file actions for `autumn generate scaffold`, using optional
/// metadata flags.
///
/// # Errors
/// Surfaces any planning error from the underlying model generation as well
/// as project-layout, repository query, and metadata problems.
pub fn plan_scaffold_with_options(
    project_root: &Path,
    name: &str,
    field_tokens: &[String],
    timestamp: &str,
    options: &ScaffoldOptions,
) -> Result<Plan, GenerateError> {
    // Generation path: run the full plan, including the shared-layout preflight.
    // `autumn destroy scaffold` recomputes the identical plan before reverting
    // it, and must bypass that generate-only preflight (issue #1834); it reaches
    // the builder through `plan_scaffold_with_options_for_revert` instead.
    plan_scaffold_with_options_impl(project_root, name, field_tokens, timestamp, options, false)
}

/// Compute the file actions for `autumn destroy scaffold …`.
///
/// Identical to [`plan_scaffold_with_options`] except it recomputes the plan for
/// the revert path: it skips the generate-only shared-layout preflight so
/// cleanup still succeeds in a project whose shared `pub fn layout` is missing or
/// renamed (e.g. one scaffolded by an older CLI, or one whose `layout` was since
/// renamed). `autumn destroy scaffold` reverts the returned plan; the preflight
/// would otherwise hard-fail the destroy before any generated file is removed,
/// stranding the files it is meant to remove (issue #1834).
///
/// # Errors
/// Same as [`plan_scaffold_with_options`], minus the shared-layout preflight.
pub fn plan_scaffold_with_options_for_revert(
    project_root: &Path,
    name: &str,
    field_tokens: &[String],
    timestamp: &str,
    options: &ScaffoldOptions,
) -> Result<Plan, GenerateError> {
    plan_scaffold_with_options_impl(project_root, name, field_tokens, timestamp, options, true)
}

/// Shared implementation of [`plan_scaffold_with_options`]. `for_revert`
/// suppresses the generate-only shared-layout preflight so `autumn destroy
/// scaffold` (which recomputes this same plan before [`Plan::revert`]) can
/// remove generated files even in a project whose shared `pub fn layout` is
/// missing or renamed — a regression the preflight would otherwise introduce.
#[allow(clippy::too_many_lines)]
fn plan_scaffold_with_options_impl(
    project_root: &Path,
    name: &str,
    field_tokens: &[String],
    timestamp: &str,
    options: &ScaffoldOptions,
    for_revert: bool,
) -> Result<Plan, GenerateError> {
    ensure_project_root(project_root)?;
    // Gate: UUID primary keys are not yet supported for scaffolds. Every scaffold
    // emits a `#[autumn_web::repository]`, whose macro-generated REST API is
    // currently hard-coded to `i64` primary keys (`Path<i64>`, `find_by_id`,
    // cursor pagination), so a UUID-keyed scaffold would not compile. The model
    // generator (`generate model --id uuid`) has no such limitation.
    if options.model.id_type == IdType::Uuid {
        return Err(GenerateError::Config(
            "UUID primary keys are not yet supported for `generate scaffold`: the \
             generated `#[repository]` REST API is currently limited to i64 primary \
             keys. Use `generate model --id uuid` for the model and migration, or \
             omit `--id` to use the default BIGSERIAL key."
                .to_owned(),
        ));
    }
    let mut fields = parse_fields(field_tokens)?;
    super::model::apply_unique_flags(&mut fields, &options.model.uniques)?;
    if !options.api {
        validate_enum_field_names_against_routes_imports(&fields, &pascal(name))?;
    }
    // Resolve shard key before planning the model (propagates to model render).
    let resolved_shard_key = resolve_shard_key(&fields, &options.model)?;
    let model_options_with_key = ModelOptions {
        shard_key: resolved_shard_key,
        ..options.model.clone()
    };
    let options_with_key = ScaffoldOptions {
        model: model_options_with_key,
        queries: options.queries.clone(),
        api: options.api,
        live: options.live,
        live_validation: options.live_validation,
        no_policy: options.no_policy,
    };
    let mut plan = plan_model_with_options(
        project_root,
        name,
        field_tokens,
        timestamp,
        &options_with_key.model,
    )?;
    let metadata = parse_model_metadata(&fields, &options_with_key.model)?;
    let queries = parse_query_specs(&fields, &options_with_key.queries)?;
    let form_fields = fields
        .iter()
        .filter(|field| !metadata.defaults().contains_key(&field.name))
        .cloned()
        .collect::<Vec<_>>();
    let pascal_name = pascal(name);
    let snake_name = snake(name);
    let plural = pluralize(&snake_name);

    // ── Record-level authorization (issue #1125) ───────────────────────────
    // A policy is generated by default for every non-`--api` scaffold unless
    // `--no-policy` is passed.
    let policy_on = !options_with_key.api && !options_with_key.no_policy;
    // Owner-column detection (AC3): drives the ownership check in the generated
    // policy and the authorize/scope wiring in the HTML handlers.
    let owner_column = {
        let columns: Vec<String> = fields.iter().map(|f| f.name.clone()).collect();
        let user_refs: Vec<String> = fields
            .iter()
            .filter(|f| f.kind.is_reference() && f.reference_table().as_deref() == Some("users"))
            .map(|f| f.name.clone())
            .collect();
        super::policy::detect_owner_column(&columns, &user_refs).map(|name| {
            // A nullable owner column (e.g. `user:references?`) is `Option<i64>`
            // and must be compared option-to-option in the generated policy.
            let nullable = fields
                .iter()
                .find(|f| f.name == name)
                .is_some_and(|f| f.nullable);
            super::policy::OwnerColumn { name, nullable }
        })
    };
    // Issue #1830: inline record-level authorization is emitted on EVERY scaffold
    // variant (standard, `--live`, `--sharded`, attachment) whenever a policy is
    // generated — including the no-owner case. The per-variant plumbing differs
    // (repository vs raw diesel vs a reused attachment `State`) but every mutating
    // handler loads its target row and record-authorizes the actor. Routing the
    // mutation through the policy gives the developer ONE place to tighten the
    // rule; the generated no-owner policy authorizes any authenticated user (a
    // no-regression over the prior `#[secured]`-only handlers, which already let
    // any authenticated user mutate any row — see `policy.rs`), so a fresh
    // no-owner scaffold never 403s out of the box.
    let authorize_routes = policy_on;
    // Whether the index is owner-scoped: only when an owner column exists. A
    // no-owner scaffold authorizes its handlers but keeps the unscoped index
    // (there is no column to filter on).
    let owner_authorizes = policy_on && owner_column.is_some();
    // The standard (non-live, non-sharded) diesel OWNER path. Retained as the
    // signal for the cross-user 403 smoke test, which drives real HTTP create/
    // update/delete as two users and is only meaningful with an owner column (the
    // no-owner policy authorizes any authenticated user, so a cross-user denial
    // would not hold) and only wired for the plain diesel path (the live SSE and
    // sharded runtimes need extra harness the smoke test doesn't set up).
    let authorize_wiring = owner_authorizes
        && !options_with_key.model.sharded
        && !options_with_key.live
        && !options_with_key.live_validation;

    // Issue #1841: owner-scoped full-text search is now supported on the STANDARD
    // (non-live, non-sharded) Db path. The `#[repository(..., owner = <col>)]`
    // attr makes the macro emit an owner-filtered `search_page_scoped` (and
    // `list_scoped`), and the generated `GET /{plural}/search` + owner-scoped
    // index call ONLY those scoped methods — never the unscoped `search_page`/
    // `page`. So `--searchable` + owner scoping is safe there and no longer
    // refused.
    //
    // The `--sharded` owner path is NOT yet wired: its index/search still run
    // through per-shard raw diesel / the unscoped `search_page`, and a scoped
    // cross-shard FTS is out of scope here (follow-up). Search is force-disabled
    // for `--live`/`--live-validation` (see `search_enabled`), so the only
    // remaining unsafe combination is owner-scoped `--sharded` `--searchable` —
    // keep refusing exactly that. Returns before the plan is built, so no files
    // are written.
    if !options_with_key.model.searchable.is_empty()
        && owner_authorizes
        && options_with_key.model.sharded
        && !options_with_key.live
        && !options_with_key.live_validation
    {
        return Err(GenerateError::Config(format!(
            "`--searchable` is not yet supported for owner-scoped `--sharded` models: the \
             sharded index/search run per-shard through the UNSCOPED `search_page`, so the \
             generated `GET /{plural}/search` endpoint would expose other users' rows in the \
             same shard that the `#[secured]` index view filters out (owner column `{owner}`). \
             Drop `--sharded` (the standard Db path supports owner-scoped search), remove \
             `--searchable`, drop the owner column, or pass `--no-policy` to opt out of owner \
             scoping. Track: owner-scoped FTS for sharded repositories (follow-up to #1841).",
            owner = owner_column.as_ref().map_or("user_id", |o| o.name.as_str()),
        )));
    }

    // `references` columns whose target model can't be found in the project
    // (same presence test `check_reference_targets` used for its warning —
    // the table presumably exists out-of-band, or gets generated later).
    // Their "select over the referenced table's ids" promotion (issue #1135
    // AC 2) needs the target's `src/schema.rs` entry at compile time, so the
    // routes renderer skips the select machinery for these columns and lets
    // them fall back to the derived numeric id input — a warning-only missing
    // target has always produced compilable output, and importing a
    // nonexistent schema module would break that. A self-referential column
    // (target == this scaffold's own table) is never "missing": its schema
    // entry is being generated right now.
    let missing_reference_targets: BTreeSet<String> = form_fields
        .iter()
        .filter(|f| f.kind.is_reference())
        .filter_map(|f| {
            let table = f.reference_table()?;
            if table == plural {
                return None;
            }
            let base = f.name.strip_suffix("_id").unwrap_or(&f.name);
            if super::model::model_file_exists(project_root, &table, base) {
                None
            } else {
                Some(f.name.clone())
            }
        })
        .collect();
    if !options_with_key.api && !options_with_key.live_validation {
        for f in form_fields.iter().filter(|f| f.kind.is_reference()) {
            if !missing_reference_targets.contains(&f.name) {
                continue;
            }
            let Some(table) = f.reference_table() else {
                continue;
            };
            let base = f.name.strip_suffix("_id").unwrap_or(&f.name);
            plan.warn(format!(
                "'{}' will render as a plain numeric id input in the generated form: \
                 without the '{base}' model, table '{table}' has no `src/schema.rs` entry \
                 to load select options from. Generate the '{base}' model first (or re-run \
                 this scaffold once it exists) to get a select of {table} ids instead.",
                f.name
            ));
        }
    }
    // An explicit `{label:col}` override that names a column the target model
    // doesn't expose as a string would generate a `select {table}::{col}`
    // (loaded as `String`) that fails to compile the generated app. The display
    // resolver falls back to the heuristic display column in that case
    // (see `resolve_reference_display`), so warn the author their label was
    // ignored rather than silently swapping it. Skipped for a missing target
    // (already warned above) and when the model isn't discoverable (the
    // override can't be validated, so it's honored as-is).
    for f in form_fields.iter().filter(|f| f.kind.is_reference()) {
        if missing_reference_targets.contains(&f.name) {
            continue;
        }
        let Some(label) = &f.constraints.label else {
            continue;
        };
        let base = f.name.strip_suffix("_id").unwrap_or(&f.name);
        // Self-ref-aware: a self-reference's columns come from the in-flight
        // fields, so `Category category:references{label:name}` doesn't warn
        // that the not-yet-on-disk model "has no string columns".
        let columns = target_string_columns(project_root, f, &plural, &form_fields);
        if !columns.iter().any(|(c, _)| c == label) {
            // Covers both a wrong column name AND a target with no string
            // columns at all — in the latter case there is nothing to fall back
            // to, so the reference renders its raw id.
            let detail = if columns.is_empty() {
                format!("the '{base}' model has no string columns")
            } else {
                format!(
                    "the '{base}' model's string columns are: {}",
                    columns
                        .iter()
                        .map(|(c, _)| c.as_str())
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            };
            plan.warn(format!(
                "reference label '{label}' on '{}' is not a usable string column ({detail}); \
                 falling back to the default display column (its raw id when there is none).",
                f.name
            ));
        }
    }

    // Repository file under `src/repositories/<snake>.rs`
    let repos_dir = project_root.join("src").join("repositories");
    plan.create(
        repos_dir.join(format!("{snake_name}.rs")),
        render_repository_file(
            &pascal_name,
            &snake_name,
            &queries,
            options_with_key.model.soft_delete,
            options_with_key.api,
            options_with_key.model.sharded,
            options_with_key.live,
            !options_with_key.model.searchable.is_empty(),
            // Issue #1841: emit `owner = <col>` (→ the macro's `list_scoped` /
            // `search_page_scoped` codegen) only on the standard owner-scoped Db
            // path — `authorize_wiring` is exactly `owner present && policy on &&
            // !sharded && !live && !live_validation`, the path whose index/search
            // this PR wires to the scoped methods. Live/sharded owner indexes are
            // left as #1830 emitted them (follow-up), so they get no `owner =`.
            authorize_wiring
                .then(|| owner_column.as_ref().map(|o| o.name.as_str()))
                .flatten(),
        ),
    );
    let repo_mod_path = repos_dir.join("mod.rs");
    plan.modify(
        repo_mod_path.clone(),
        add_mod_declaration(&read_or_empty(&repo_mod_path), &snake_name),
    );
    plan.push_revert(Revert::ModDecl {
        path: repo_mod_path,
        name: snake_name.clone(),
    });

    // Route file under `src/routes/<plural>.rs`
    if !options_with_key.api {
        // The shared-layout preflight applies only to standard scaffolds, which
        // render their HTML views through the application's shared
        // `crate::layout(title, current_path, flash, content)`. Live and
        // live-validation scaffolds are self-contained: they emit their OWN
        // private `fn layout` and never call `crate::layout`, so an app without
        // a shared layout must not block them. This mirrors the renderer's
        // `shared_layout = !live && !live_validation`.
        //
        // `for_revert` additionally skips the preflight on the `autumn destroy
        // scaffold` path: it recomputes this plan before reverting it, and the
        // generate-only guard must not hard-fail cleanup (issue #1834).
        if !options_with_key.live && !options_with_key.live_validation && !for_revert {
            // Issue #1130: scaffolded HTML views render through the application's
            // shared `crate::layout`, so the target app must expose one with the
            // matching signature. Detect it by looking for a `pub fn layout` in
            // `src/main.rs` (as generated by `autumn new`). If it's missing — or
            // present with the wrong arity — fail early with an actionable message
            // rather than emitting routes that call a nonexistent or mismatched
            // `crate::layout`.
            let main_for_layout_check = project_root.join("src").join("main.rs");
            let main_src = match std::fs::read_to_string(&main_for_layout_check) {
                Ok(src) => src,
                // `main.rs` genuinely absent: surface the actionable message below
                // by treating it as an empty source (no `pub fn layout` present).
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
                // Any other io error (e.g. PermissionDenied) must preserve its
                // original `ErrorKind` + OS message rather than being masked.
                Err(e) => return Err(GenerateError::Io(e)),
            };
            // The generated routes call the 4-arg
            // `crate::layout(title, current_path, flash, content)`, so a shared
            // layout must exist AND take exactly 4 parameters. `has_shared_layout`
            // matches `layout` as a complete token (so decoys like
            // `pub fn layout_sidebar` are ignored), ignores `pub fn layout`
            // tokens that appear inside comments or string literals, and rejects
            // an older/custom 2-arg `pub fn layout(title, content)` that would
            // otherwise pass the preflight and then fail to compile.
            if !has_shared_layout(&main_src) {
                return Err(GenerateError::Config(
                    "`autumn generate scaffold` requires a shared `pub fn layout` in src/main.rs \
                     so the generated views can render through \
                     `crate::layout(title, current_path, flash, content)` (4 args). Run this inside \
                     an app created by `autumn new`, or add a shared \
                     `pub fn layout(title: &str, current_path: &str, flash: maud::Markup, content: maud::Markup) -> maud::Markup` \
                     to src/main.rs and re-run. (Use `--api` to scaffold JSON-only endpoints that need no layout.)"
                        .to_owned(),
                ));
            }
        }
        let routes_dir = project_root.join("src").join("routes");
        plan.create(
            routes_dir.join(format!("{plural}.rs")),
            render_routes_file(
                project_root,
                &pascal_name,
                &snake_name,
                &plural,
                &form_fields,
                &fields,
                options_with_key.model.sharded,
                options_with_key.model.soft_delete,
                options_with_key.model.id_type,
                options_with_key.live,
                options_with_key.live_validation,
                metadata.validations(),
                &missing_reference_targets,
                authorize_routes,
                owner_column.as_ref().map(|o| o.name.as_str()),
                &options_with_key.model.searchable,
            ),
        );
        let route_mod_path = routes_dir.join("mod.rs");
        plan.modify(
            route_mod_path.clone(),
            add_mod_declaration(&read_or_empty(&route_mod_path), &plural),
        );
        plan.push_revert(Revert::ModDecl {
            path: route_mod_path,
            name: plural.clone(),
        });
    }

    // Record-level authorization policy + scope (issue #1125). Emitted for every
    // non-`--api` scaffold unless `--no-policy` is passed. The main.rs
    // registration is folded into the shared `updated` content below (a second
    // `Modify` on main.rs would clobber the route wiring, since each is computed
    // against on-disk content).
    if policy_on {
        super::policy::push_policy_files(
            &mut plan,
            project_root,
            &pascal_name,
            &snake_name,
            &plural,
            owner_column.as_ref(),
            // Scaffold always writes the per-resource `src/models/<snake>.rs`
            // layout, so the model type is always `crate::models::<snake>::<Pascal>`.
            &format!("crate::models::{snake_name}::{pascal_name}"),
        );
    }

    // Smoke test under `tests/<snake>.rs`. Uses the same soft-delete-augmented
    // field list as the real migration (see `augment_fields_for_soft_delete`)
    // so the smoke test's throwaway table matches the real schema exactly.
    let smoke_test_fields =
        augment_fields_for_soft_delete(&fields, options_with_key.model.soft_delete)?;
    plan.create(
        project_root.join("tests").join(format!("{snake_name}.rs")),
        render_smoke_test(
            &pascal_name,
            &plural,
            options_with_key.api,
            &smoke_test_fields,
            options_with_key.model.id_type,
            metadata.indexes(),
            metadata.defaults(),
            metadata.validations(),
            authorize_wiring,
        ),
    );

    // `src/main.rs` updates: declare modules + register all new routes.
    let main_path = project_root.join("src").join("main.rs");
    let main_existing = std::fs::read_to_string(&main_path).map_err(|_| {
        GenerateError::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("missing {}", main_path.display()),
        ))
    })?;
    let validated_field_names: Vec<String> = if options_with_key.live_validation {
        metadata.validations().keys().cloned().collect()
    } else {
        Vec::new()
    };
    // Issue #1319: the search box/route exist only for the standard (non-live)
    // HTML index; the model/repository/migration get `searchable` regardless.
    let search_enabled = !options_with_key.model.searchable.is_empty()
        && !options_with_key.live
        && !options_with_key.live_validation;
    // Issue #1326: the state-machine fields whose `transition_{field}` handler
    // the generated `routes::{plural}` module emits and `main.rs` must mount.
    // Only the HTML surface emits these handlers, so this stays empty for `--api`.
    let sm_field_names: Vec<String> = if options_with_key.api {
        Vec::new()
    } else {
        fields
            .iter()
            .filter(|f| f.state_machine.is_some())
            .map(|f| f.name.clone())
            .collect()
    };
    let route_entries = main_route_entries(
        &plural,
        &snake_name,
        options_with_key.api,
        options_with_key.live,
        search_enabled && !options_with_key.api,
        &validated_field_names,
        &sm_field_names,
    );
    let mut mods = vec!["models", "schema", "repositories"];
    if !options_with_key.api {
        mods.push("routes");
    }
    if policy_on {
        mods.push("policies");
    }
    let updated = update_main_rs(&main_existing, &mods, &route_entries);
    // Fold the policy/scope builder registration into the same `updated` content
    // (issue #1125) so main.rs gets a single `Modify` action.
    let updated = if policy_on {
        super::schema_edit::add_policy_registration_to_app(
            &updated,
            &format!("crate::models::{snake_name}::{pascal_name}"),
            &pascal_name,
            &snake_name,
        )
    } else {
        updated
    };
    plan.modify(main_path.clone(), updated);
    // `mod models;`/`mod schema;`/`mod repositories;`/`mod routes;`/`mod policies;`
    // are shared infrastructure declarations, not owned by this resource — see
    // `emit::sync_main_rs_mod_declarations`, which removes one only once its
    // backing module no longer exists on disk. Only this resource's own
    // `routes![]` entries and policy registration are reverted here.
    plan.push_revert(Revert::RoutesEntries {
        path: main_path.clone(),
        entries: route_entries,
    });
    if policy_on {
        plan.push_revert(Revert::PolicyRegistration {
            path: main_path,
            pascal: pascal_name.clone(),
            snake: snake_name.clone(),
        });
    }

    // The Maud `html!` macro pulls in a direct `maud` dep on top of the
    // model's deps. Both modify actions target Cargo.toml, so we combine
    // them into a single deduplicated call — otherwise the second write
    // would clobber the first (each rendering is computed at plan time
    // against the on-disk Cargo.toml).
    plan.actions.retain(|a| !a.path().ends_with("Cargo.toml"));
    let mut combined: Vec<(&str, &str)> = super::model::MODEL_DEPS
        .iter()
        .copied()
        .chain(SCAFFOLD_EXTRA_DEPS.iter().copied())
        .collect();
    // `validator` is needed whenever a routes file is emitted (issue #1124: the
    // generated `{Pascal}Form` always derives `validator::Validate`), and also
    // whenever the model itself carries `#[validate]` rules.
    if !options_with_key.api || metadata.has_validator_rules() {
        combined.push((
            "validator",
            "{ version = \"0.20\", features = [\"derive\"] }",
        ));
    }
    // Not re-checked for missing features here: `plan` above *is* the
    // `plan_model_with_options` plan (reused, not merged), and that call
    // already ran `warn_if_existing_dep_missing_features` for `rust_decimal`
    // when it built its own decimal-conditional dep — re-running the same
    // check against the same (still on-disk, pre-`execute()`) Cargo.toml
    // here would just duplicate the warning.
    if fields.iter().any(|f| f.kind.is_decimal()) {
        combined.push((
            "rust_decimal",
            "{ version = \"1\", features = [\"db-diesel2-postgres\", \"serde\"] }",
        ));
    }
    plan_cargo_deps(
        &mut plan,
        project_root,
        &combined,
        &project_root.join("src/models"),
    );

    // The generated HTML routes render through `autumn_web::form::*` helpers
    // (issue #1124), which are gated behind autumn-web's `maud` feature — enable
    // it whenever a routes file is emitted.
    if !options_with_key.api {
        let cargo_path = project_root.join("Cargo.toml");
        let base = plan
            .actions
            .iter()
            .rev()
            .find_map(|a| match a {
                Action::Modify { path, contents } if path == &cargo_path => Some(contents.clone()),
                _ => None,
            })
            .unwrap_or_else(|| read_or_empty(&cargo_path));
        let updated = ensure_autumn_web_feature(&base, "maud");
        if updated != base {
            plan.actions.retain(|a| a.path() != cargo_path);
            plan.modify(cargo_path.clone(), updated);
        }
        // Pushed unconditionally — see `plan_cargo_deps`'s matching comment:
        // at `destroy` time this same call recomputes the plan against the
        // already-generated Cargo.toml, where "maud" is by definition
        // already present, so `updated != base` above would never be true.
        plan.push_revert(Revert::CargoAutumnWebFeature {
            path: cargo_path,
            feature: "maud".to_owned(),
            owner_dir: Some(project_root.join("src").join("routes")),
        });
    }

    // Issue #1319: a searchable (non-live) index inlines an htmx `<script>` and
    // its results handler extracts `HxRequest`, both gated behind autumn-web's
    // `htmx` feature — enable it. (Live variants enable `htmx` in the block
    // below; api scaffolds have no HTML index, so no search box.)
    if search_enabled && !options_with_key.api {
        let cargo_path = project_root.join("Cargo.toml");
        let base = plan
            .actions
            .iter()
            .rev()
            .find_map(|a| match a {
                Action::Modify { path, contents } if path == &cargo_path => Some(contents.clone()),
                _ => None,
            })
            .unwrap_or_else(|| read_or_empty(&cargo_path));
        let updated = ensure_autumn_web_feature(&base, "htmx");
        if updated != base {
            plan.actions.retain(|a| a.path() != cargo_path);
            plan.modify(cargo_path.clone(), updated);
        }
        plan.push_revert(Revert::CargoAutumnWebFeature {
            path: cargo_path,
            feature: "htmx".to_owned(),
            owner_dir: Some(project_root.join("src").join("routes")),
        });
    }

    // Issue #1236: a scaffold with attachment fields needs autumn-web's `storage`
    // feature (the model's `autumn_web::storage::Blob` column and the blob store)
    // and `multipart` feature (the create/update handlers take an
    // `autumn_web::extract::Multipart` body and stream files to the store with
    // zero JavaScript). Enable both so a freshly scaffolded resource compiles.
    //
    // The generated create/update handlers also mint each blob key as
    // `{plural}/{field}/{nanos}_{uuid}` — the `uuid::Uuid::new_v4()` suffix
    // prevents two uploads for the same field colliding on an identical
    // nanosecond timestamp (including two attachment fields in the SAME
    // multipart request). `MODEL_DEPS` already declares `uuid` (with only the
    // `serde` feature via `plan_cargo_deps` above), so enable its `v4` feature
    // so that call resolves. Reverting the whole `uuid` dep at `destroy` time is
    // handled by `plan_cargo_deps`'s `CargoDeps` revert, so no separate
    // feature-revert is needed here.
    if has_attachment_fields(&fields) {
        let cargo_path = project_root.join("Cargo.toml");
        let base = plan
            .actions
            .iter()
            .rev()
            .find_map(|a| match a {
                Action::Modify { path, contents } if path == &cargo_path => Some(contents.clone()),
                _ => None,
            })
            .unwrap_or_else(|| read_or_empty(&cargo_path));
        let feats: &[&str] = &["storage", "multipart"];
        let mut updated = base.clone();
        for feat in feats {
            updated = ensure_autumn_web_feature(&updated, feat);
        }
        updated = ensure_dependency_feature(&updated, "uuid", "v4");
        if updated != base {
            plan.actions.retain(|a| a.path() != cargo_path);
            plan.modify(cargo_path.clone(), updated);
        }
        // Pushed unconditionally — see `plan_cargo_deps`'s matching comment: at
        // `destroy` time this same call recomputes the plan against the already-
        // generated Cargo.toml, where the features are by definition already
        // present, so `updated != base` above would never be true.
        let models_dir = project_root.join("src").join("models");
        for feat in feats {
            plan.push_revert(Revert::CargoAutumnWebFeature {
                path: cargo_path.clone(),
                feature: (*feat).to_owned(),
                owner_dir: Some(models_dir.clone()),
            });
        }
    }

    // --live requires `ws` (sse::stream), `maud` (LiveFragment/Markup), and `htmx`.
    // --live-validation alone also emits Markup-returning validate handlers and
    // references HTMX_JS_PATH, so it requires `htmx` + `maud` even without `ws`.
    if options_with_key.live || options_with_key.live_validation {
        let cargo_path = project_root.join("Cargo.toml");
        let base = plan
            .actions
            .iter()
            .rev()
            .find_map(|a| match a {
                Action::Modify { path, contents } if path == &cargo_path => Some(contents.clone()),
                _ => None,
            })
            .unwrap_or_else(|| read_or_empty(&cargo_path));
        let mut updated = base.clone();
        let feats: &[&str] = if options.live {
            &["htmx", "maud", "ws"]
        } else {
            &["htmx", "maud"]
        };
        for feat in feats {
            updated = ensure_autumn_web_feature(&updated, feat);
        }
        if updated != base {
            plan.actions.retain(|a| a.path() != cargo_path);
            plan.modify(cargo_path.clone(), updated);
        }
        // Pushed unconditionally — see `plan_cargo_deps`'s matching comment.
        let routes_dir = project_root.join("src").join("routes");
        for feat in feats {
            plan.push_revert(Revert::CargoAutumnWebFeature {
                path: cargo_path.clone(),
                feature: (*feat).to_owned(),
                owner_dir: Some(routes_dir.clone()),
            });
        }
    }

    // The generated smoke test uses `autumn_web::test::TestDb` (a real,
    // throwaway Postgres testcontainer) to back its in-process `TestApp`
    // request. `TestDb` is compiled only when the `test-support` feature is
    // enabled, and that feature must stay out of `[dependencies]` so release
    // builds don't pull in `testcontainers` — so it goes in
    // `[dev-dependencies]` instead.
    {
        let cargo_path = project_root.join("Cargo.toml");
        let base = plan
            .actions
            .iter()
            .rev()
            .find_map(|a| match a {
                Action::Modify { path, contents } if path == &cargo_path => Some(contents.clone()),
                _ => None,
            })
            .unwrap_or_else(|| read_or_empty(&cargo_path));
        let updated = ensure_dev_dependency_test_support(&base, env!("CARGO_PKG_VERSION"));
        if updated != base {
            plan.actions.retain(|a| a.path() != cargo_path);
            plan.modify(cargo_path.clone(), updated);
        }
        // Pushed unconditionally — see `plan_cargo_deps`'s matching comment.
        // `owner_dir` is `src/models` (not `src/routes`) because the smoke
        // test — and thus `test-support` — is generated for EVERY scaffold,
        // including `--api`-only ones that never get a routes file.
        plan.push_revert(Revert::CargoAutumnWebDevFeature {
            path: cargo_path,
            feature: "test-support".to_owned(),
            owner_dir: Some(project_root.join("src").join("models")),
        });
    }

    // The generated smoke test also uses `#[tokio::test]`, which needs the
    // `rt` and `macros` tokio features to compile. Every `autumn new`
    // project already has these (see `templates/Cargo.toml.tmpl`), but a
    // hand-rolled or edited-down Cargo.toml might not -- and `cargo test
    // --tests` still compiles `#[ignore]`d tests, so a missing dev-dependency
    // here would leave the project unable to compile its test targets.
    {
        let cargo_path = project_root.join("Cargo.toml");
        let base = plan
            .actions
            .iter()
            .rev()
            .find_map(|a| match a {
                Action::Modify { path, contents } if path == &cargo_path => Some(contents.clone()),
                _ => None,
            })
            .unwrap_or_else(|| read_or_empty(&cargo_path));
        let updated = ensure_dev_dependency_tokio_test_features(&base);
        if updated != base {
            plan.actions.retain(|a| a.path() != cargo_path);
            plan.modify(cargo_path, updated);
        }
    }

    // ── autumn.toml: exempt the live-validation routes from the submit-token
    // guard (issue #1360). The generated `POST /{plural}/validate/{field}`
    // inline-validation routes `hx-include` the whole form, so without this the
    // one-time `_submit_token` is consumed by a validation POST and the real
    // create/update submit replays a validation fragment instead of mutating.
    // The `hx-params="not _submit_token"` markup filter mitigates this only for
    // the DEFAULT field name; exempting the route by prefix makes it robust for
    // ANY configured `security.submit_token.field_name`. Only meaningful for
    // `--live-validation`, and only when the project actually has an
    // `autumn.toml` to edit (a bare/hand-rolled project keeps the markup
    // filter as its sole, still-effective default-field-name guard).
    if options_with_key.live_validation {
        let autumn_toml_path = project_root.join("autumn.toml");
        if autumn_toml_path.exists() {
            let toml_existing = read_or_empty(&autumn_toml_path);
            // Only record the modify *and* the destroy-time revert when this
            // scaffold actually inserts the exemption. If `/{plural}/validate`
            // is already present (a preexisting, user-owned entry), the append
            // is a no-op and returns `None`; recording a revert then would let a
            // later `autumn destroy` delete an exemption we never added,
            // re-enabling submit-token guarding on live-validation routes.
            if let Some(updated_toml) =
                append_submit_token_validate_exempt_to_toml(&toml_existing, &plural)
            {
                plan.modify(autumn_toml_path.clone(), updated_toml);
                plan.push_revert(Revert::SubmitTokenValidateExempt {
                    path: autumn_toml_path,
                    plural,
                });
            }
        }
    }

    Ok(plan)
}

/// Fixed, unconditional (non-`--live`, non-attachment-gated) names the
/// generated `src/routes/<plural>.rs` file imports for every non-`--api`
/// scaffold — see the `use` block at the top of [`render_routes_file`]'s
/// template. An enum field whose generated type name (`pascal(field)`)
/// matches one of these produces a second, conflicting `use` of the same
/// name (`use crate::models::…::{…, Path}` alongside
/// `use autumn_web::extract::Path;`), which fails with E0252 before the
/// scaffold can compile — confirmed by generating `path:enum{a,b}`.
///
/// Lowercase framework imports (`get`, `html`, `post`, `secured`,
/// `pagination_nav`) can never collide: `pascal()` always capitalizes the
/// first letter, so a `snake_case` field name can't produce a lowercase type
/// name.
const ROUTES_FILE_RESERVED_NAMES: &[&str] = &[
    "Path",
    "Page",
    "PageRequest",
    "Bytes",
    "CsrfFormField",
    "CsrfToken",
    "SubmitFormField",
    "SubmitToken",
    "PagerOptions",
    "Flash",
    "ShardedDb",
    "Db",
    "AutumnError",
    "AutumnResult",
    "Markup",
    "RunQueryDsl",
    "ToString",
    "Changeset",
    "IntoChangeset",
];

/// Reject an `enum{…}` field whose generated type name collides with one of
/// [`ROUTES_FILE_RESERVED_NAMES`], or with the scaffold's own generated
/// `{pascal_name}Form` changeset struct (`render_model_form`). Only relevant
/// when `generate scaffold` will actually emit `src/routes/<plural>.rs`
/// (i.e. not `--api`, which skips that file entirely).
fn validate_enum_field_names_against_routes_imports(
    fields: &[Field],
    pascal_name: &str,
) -> Result<(), GenerateError> {
    let form_ty = format!("{pascal_name}Form");
    for f in fields {
        let Some(enum_ty) = f.enum_type_name() else {
            continue;
        };
        if ROUTES_FILE_RESERVED_NAMES.contains(&enum_ty.as_str()) {
            return Err(GenerateError::InvalidField {
                token: format!("{}:enum{{...}}", f.name),
                reason: format!(
                    "the generated enum type '{enum_ty}' collides with a name the scaffold's \
                     routes file always imports; rename the field"
                ),
            });
        }
        if enum_ty == form_ty {
            return Err(GenerateError::InvalidField {
                token: format!("{}:enum{{...}}", f.name),
                reason: format!(
                    "the generated enum type '{enum_ty}' collides with the scaffold's own \
                     generated '{form_ty}' changeset form struct; rename the field"
                ),
            });
        }
    }
    Ok(())
}

fn parse_query_specs(
    fields: &[Field],
    queries: &[String],
) -> Result<Vec<QuerySpec>, GenerateError> {
    let mut parsed = Vec::with_capacity(queries.len());
    for query in queries {
        let (method, field_name) =
            query
                .split_once(':')
                .ok_or_else(|| GenerateError::InvalidField {
                    token: query.clone(),
                    reason: "expected `method:field`, for example `find_by_tag:tag`".into(),
                })?;
        let method = method.trim();
        let field_name = field_name.trim();
        if !method.starts_with("find_by_") || !is_valid_fn_name(method) {
            return Err(GenerateError::InvalidField {
                token: query.clone(),
                reason: "query method must be a valid `find_by_<field>` function name".into(),
            });
        }
        let method_field = method
            .strip_prefix("find_by_")
            .expect("prefix checked above");
        let field =
            field_by_name(fields, field_name).ok_or_else(|| GenerateError::InvalidField {
                token: query.clone(),
                reason: format!("unknown field '{field_name}'"),
            })?;
        if method_field != field_name {
            return Err(GenerateError::InvalidField {
                token: query.clone(),
                reason: format!(
                    "query method suffix '{method_field}' must match field '{field_name}'"
                ),
            });
        }
        if field.is_enum() {
            // The repository file's `use crate::models::<snake>::{...}` import
            // only brings in the model + New/Update companions — not a
            // per-field generated enum type — so a derived-query parameter of
            // that type wouldn't resolve. Reject rather than emit code that
            // fails to compile.
            return Err(GenerateError::InvalidField {
                token: query.clone(),
                reason: format!("`--query` on enum field '{field_name}' is not yet supported"),
            });
        }
        if parsed.iter().any(|spec: &QuerySpec| spec.method == method) {
            return Err(GenerateError::InvalidField {
                token: query.clone(),
                reason: format!("duplicate query method '{method}'"),
            });
        }
        parsed.push(QuerySpec {
            method: method.to_owned(),
            field_name: field_name.to_owned(),
            rust_type: field.rust_type(),
        });
    }
    // Every `unique` field (issue #1032) gets a `find_by_<field>` repository
    // lookup for free — no `--query` needed — mirroring how a `references`
    // field auto-contributes to the migration's index set without an
    // explicit `--index`. Skipped for a field already covered by an
    // explicit `--query`, and for `enum` fields (same import-path
    // limitation `--query` itself rejects above).
    for field in fields {
        if field.unique
            && !field.is_enum()
            && !parsed.iter().any(|spec| spec.field_name == field.name)
        {
            parsed.push(QuerySpec {
                method: format!("find_by_{}", field.name),
                field_name: field.name.clone(),
                rust_type: field.rust_type(),
            });
        }
    }
    Ok(parsed)
}

fn is_valid_fn_name(name: &str) -> bool {
    let mut chars = name.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    (first.is_ascii_lowercase() || first == '_')
        && chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_')
}

/// Resolve the sharding key field from options and field list.
///
/// Returns `None` when sharding is not enabled. When sharding is enabled,
/// returns the explicitly requested key (validated against model fields and
/// `id`), or falls back to `tenant_id` if present, then `id`.
fn resolve_shard_key(
    fields: &[Field],
    options: &ModelOptions,
) -> Result<Option<String>, GenerateError> {
    if !options.sharded {
        return Ok(None);
    }
    if let Some(ref key) = options.shard_key {
        let valid = key == "id" || field_by_name(fields, key).is_some();
        if !valid {
            return Err(GenerateError::InvalidField {
                token: key.clone(),
                reason: format!(
                    "shard_key field `{key}` does not exist on this model; \
                     pass an existing field name or `id`"
                ),
            });
        }
        return Ok(Some(key.clone()));
    }
    if field_by_name(fields, "tenant_id").is_some() {
        return Ok(Some("tenant_id".to_owned()));
    }
    Ok(Some("id".to_owned()))
}

/// Render a plain `#[repository(Model)]` trait for `autumn db pull --with-repository`.
///
/// No derived queries, soft-delete, or sharding — introspection cannot recover
/// those from the database. The introspected `table` name is passed through
/// explicitly — both as the schema import and as `table = "..."` in the macro —
/// because the repository macro otherwise infers the table from the model name
/// (`Status` -> `statuss`), which is wrong for irregular plurals.
pub(super) fn render_repository_for_pull(
    pascal_name: &str,
    snake_name: &str,
    table: &str,
) -> String {
    format!(
        "//! Generated by `autumn db pull`.\n\
         //!\n\
         //! `#[repository]` auto-generates CRUD methods and JSON REST handlers.\n\
         //! Mount mutating API handlers only after adding a repository policy.\n\
         \n\
         use crate::models::{snake_name}::{{{pascal_name}, New{pascal_name}, Update{pascal_name}}};\n\
         use crate::schema::{table};\n\
         \n\
         #[autumn_web::repository({pascal_name}, table = \"{table}\", api = \"/api/{table}\")]\n\
         pub trait {pascal_name}Repository {{\n\
         }}\n"
    )
}

#[allow(clippy::fn_params_excessive_bools, clippy::too_many_arguments)]
fn render_repository_file(
    pascal_name: &str,
    snake_name: &str,
    queries: &[QuerySpec],
    soft_delete: bool,
    api: bool,
    sharded: bool,
    live: bool,
    searchable: bool,
    owner_column: Option<&str>,
) -> String {
    let plural = pluralize(snake_name);
    let query_body = render_repository_queries(pascal_name, queries);
    let soft_delete_attr = if soft_delete { ", soft_delete" } else { "" };
    let broadcasts_attr = if live { ", broadcasts = true" } else { "" };
    // When `broadcasts = true` is set, `#[repository]` synthesizes internal
    // hooks whose generated `update` body expands an unqualified
    // `{Pascal}DraftExt::from_patch(...)`. Import that trait alongside the other
    // model types so the generated repository compiles (issue #1853). Gated on
    // the same `live` boolean that drives `broadcasts_attr` — the default
    // (non-broadcast) scaffold emits no hooks and no `from_patch`, so it keeps
    // the plain three-name import.
    let draft_ext_import = if live {
        format!(", {pascal_name}DraftExt")
    } else {
        String::new()
    };
    // Issue #1319: `searchable` opts the repository into the FTS `search()` /
    // `search_page(query, &PageRequest)` methods (backed by the model's
    // `#[searchable]` fields + the migration's `search_vector` column).
    let searchable_attr = if searchable { ", searchable" } else { "" };
    // Issue #1841: `owner = <col>` makes `#[repository]` emit owner-filtered
    // `list_scoped` / `search_page_scoped` methods that the owner-scoped index +
    // `/search` handlers call so they never return another user's rows. Only the
    // caller's in-scope standard Db path passes `Some`; every other scaffold
    // (no owner column, `--no-policy`, `--live`, `--sharded`) passes `None` and
    // the attr — and the scoped methods — are omitted.
    let owner_attr = owner_column.map_or(String::new(), |col| format!(", owner = {col}"));
    let sharded_note = if sharded {
        format!(
            "//!\n\
             //! This is a shard-aware repository. Handlers construct it via\n\
             //! `Pg{pascal_name}Repository::from_shard(&db)` where `db` is a `ShardedDb` extractor;\n\
             //! the extractor routes the request to the correct shard automatically.\n"
        )
    } else {
        String::new()
    };
    let api_sharded_note = if sharded && api {
        "//!\n\
         //! Note: auto-generated REST handlers (mounted via `api = ...`) route through\n\
         //! the control pool, not individual shards. Shard-aware REST is planned for a\n\
         //! future release. Use the HTML handlers or build custom shard-aware endpoints\n\
         //! with `ShardedDb` in the meantime.\n"
    } else {
        ""
    };
    let doc_comment = if api {
        format!(
            "//! Generated by `autumn generate scaffold --api`.\n\
             //!\n\
             //! `#[repository]` auto-generates CRUD methods and JSON REST handlers.\n\
             //! When using `--api`, all 5 JSON CRUD endpoints are mounted in `src/main.rs`.\n\
             //! Note: To start the application in a production profile, you must either\n\
             //! add a policy (e.g. `policy = SomePolicy`) to this repository or explicitly\n\
             //! allow unguarded writes by setting `allow_unauthorized_repository_api = true`\n\
             //! under `[security]` in `autumn.toml`.\n\
             {api_sharded_note}\
             {sharded_note}"
        )
    } else {
        format!(
            "//! Generated by `autumn generate scaffold`.\n\
             //!\n\
             //! `#[repository]` auto-generates CRUD methods and JSON REST handlers.\n\
             //! The scaffold registers only read handlers in `src/main.rs` by\n\
             //! default. A record-level `{pascal_name}Policy`/`{pascal_name}Scope` is\n\
             //! generated in `src/policies/{snake_name}.rs` and registered on the app\n\
             //! (unless `--no-policy`); reference it from `#[repository(..., policy =\n\
             //! {pascal_name}Policy)]` to guard the JSON mutating API too.\n\
             {sharded_note}"
        )
    };
    // For API scaffolds with --live, emit the stream route directly in the
    // repository file since there is no separate routes file.
    let api_stream_handler = if api && live {
        format!(
            "\n/// `GET /{plural}/stream` — SSE stream for live OOB fragments.\n\
             ///\n\
             /// Clients subscribe here to receive `hx-swap-oob` fragments whenever a\n\
             /// `{snake_name}` is saved, updated, or deleted via the API.\n\
             #[autumn_web::get(\"/{plural}/stream\")]\n\
             pub async fn stream(\n\
             \x20\x20\x20\x20state: autumn_web::extract::State<autumn_web::AppState>,\n\
             ) -> impl autumn_web::reexports::axum::response::IntoResponse {{\n\
             \x20\x20\x20\x20autumn_web::sse::stream(&state, \"{plural}\")\n\
             }}\n"
        )
    } else {
        String::new()
    };
    let list_id = format!("{plural}-list");
    // API scaffolds have no HTML show route — emit plain text; HTML scaffolds link to show page.
    let fragment_item_content = if api {
        "(self.id)".to_string()
    } else {
        // Link through the routes module's typed path helper so the show URL
        // has a single source of truth (issue #1133). This fragment lives in the
        // repository module, so it reaches `paths::show` via the fully-qualified
        // `crate::routes::{plural}::paths` path.
        format!("a href=(crate::routes::{plural}::paths::show(self.id)) {{ (self.id) }}")
    };
    let live_fragment_impl = if live {
        format!(
            "\nimpl autumn_web::live::LiveFragment for {pascal_name} {{\n\
             \x20\x20\x20\x20fn dom_id_for(id: i64) -> String {{\n\
             \x20\x20\x20\x20\x20\x20\x20\x20format!(\"{snake_name}-{{id}}\")\n\
             \x20\x20\x20\x20}}\n\
             \x20\x20\x20\x20fn dom_id(&self) -> String {{\n\
             \x20\x20\x20\x20\x20\x20\x20\x20Self::dom_id_for(self.id)\n\
             \x20\x20\x20\x20}}\n\
             \x20\x20\x20\x20fn render_fragment(&self) -> maud::Markup {{\n\
             \x20\x20\x20\x20\x20\x20\x20\x20maud::html! {{\n\
             \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20li id=(self.dom_id()) {{\n\
             \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20{fragment_item_content}\n\
             \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20}}\n\
             \x20\x20\x20\x20\x20\x20\x20\x20}}\n\
             \x20\x20\x20\x20}}\n\
             \x20\x20\x20\x20fn insert_swap() -> autumn_web::htmx::OobSwap {{\n\
             \x20\x20\x20\x20\x20\x20\x20\x20autumn_web::htmx::OobSwap::Target(\n\
             \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20autumn_web::htmx::OobMethod::BeforeEnd,\n\
             \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\"#{list_id}\".to_string(),\n\
             \x20\x20\x20\x20\x20\x20\x20\x20)\n\
             \x20\x20\x20\x20}}\n\
             }}\n"
        )
    } else {
        String::new()
    };
    format!(
        "{doc_comment}\n\
         use crate::models::{snake_name}::{{{pascal_name}, New{pascal_name}, Update{pascal_name}{draft_ext_import}}};\n\
         use crate::schema::{plural};\n\
         \n\
         #[autumn_web::repository({pascal_name}, api = \"/api/{plural}\"{soft_delete_attr}{broadcasts_attr}{searchable_attr}{owner_attr})]\n\
         pub trait {pascal_name}Repository {{\n\
{query_body}\
         }}\n\
{live_fragment_impl}\
{api_stream_handler}"
    )
}

fn render_repository_queries(pascal_name: &str, queries: &[QuerySpec]) -> String {
    let mut out = String::with_capacity(queries.len() * 64);
    for query in queries {
        use std::fmt::Write as _;
        let _ = writeln!(
            out,
            "    fn {method}({field}: {rust_type}) -> Vec<{pascal_name}>;",
            method = query.method,
            field = query.field_name,
            rust_type = query.rust_type,
        );
    }
    out
}

/// The `parse_local_datetime` helper the generated `into_new` uses to turn a
/// browser `datetime-local` string (`YYYY-MM-DDTHH:MM`, seconds optional) back
/// into a `chrono::NaiveDateTime`. Emitted only when the model has a
/// `NaiveDateTime`/`DateTime` field.
const PARSE_LOCAL_DATETIME_FN: &str = r#"
/// Parse a browser `datetime-local` value (`YYYY-MM-DDTHH:MM`, seconds and
/// fractional seconds optional) into a `NaiveDateTime`. A malformed value is
/// a 400 (undecodable input) rather than a field validation error.
///
/// Accepts a trailing `%.f` so a value pre-filled from a stored row (see the
/// generated `From<&Row>` impl, which formats with fractional seconds) round-
/// trips exactly on a no-op resubmit instead of being silently truncated to
/// whole seconds — the generated `update` handler writes every column back
/// unconditionally, so any precision lost here would corrupt the stored value.
fn parse_local_datetime(value: &str) -> AutumnResult<chrono::NaiveDateTime> {
    chrono::NaiveDateTime::parse_from_str(value, "%Y-%m-%dT%H:%M:%S%.f")
        .or_else(|_| chrono::NaiveDateTime::parse_from_str(value, "%Y-%m-%dT%H:%M"))
        .map_err(|err| AutumnError::bad_request_msg(format!("invalid datetime: {err}")))
}
"#;

/// The generated pieces backing the changeset round-trip (issue #1124): the
/// public, validating `{Pascal}Form` struct, its fallible conversion into
/// `New{Pascal}` (the success branch), the `From<&{Pascal}>` used to seed the
/// edit-form changeset, and — when a datetime field is present — the shared
/// `parse_local_datetime` helper.
struct ModelFormParts {
    /// `#[derive(...)] pub struct {Pascal}Form { ... }`
    form_struct: String,
    /// The complete `into_new` function (async + `&state` when attachments).
    into_new_fn: String,
    /// `impl From<&{Pascal}> for {Pascal}Form { ... }`
    from_row_impl: String,
    /// `parse_local_datetime` (empty unless a datetime field exists).
    datetime_helper: String,
}

/// Emit the validating form struct, its `New{Pascal}` conversion, and the
/// `From<&{Pascal}>` seed used by the edit form — the substrate for the
/// changeset round-trip (issue #1124).
///
/// The form struct deliberately mirrors the browser's wire shape (strings for
/// enums and datetimes, `#[serde(default)]` bools, `Option<String>` attachment
/// keys, native numerics) so a submission always *decodes* losslessly; the
/// declared `#[validate(...)]` rules then decide validity, and the fallible
/// `into_new` performs the enum/datetime/attachment parsing on the success
/// path (those remain 400s — undecodable input, not validation failures).
#[allow(
    clippy::too_many_lines,
    reason = "One match arm per field-kind widget — splitting it produces less \
              readable output, not more. See render_changeset_form_inputs's \
              module-level comment for the shared invariants."
)]
fn render_model_form(
    pascal_name: &str,
    fields: &[Field],
    validations: &BTreeMap<String, Vec<String>>,
) -> ModelFormParts {
    use std::fmt::Write;
    let mut struct_fields = String::new();
    let mut into_new = String::new();
    let mut from_row = String::new();
    let mut needs_datetime = false;

    for f in fields {
        let name = &f.name;
        // A required numeric carrying a `{min,max}` range (issue #1388) is
        // represented as `Option<T>` on the form struct (issue #1748): a native
        // `T` defaults to `0`, which pre-fills the input and passes both
        // `required` (HTML) and `range` when the range spans the zero default,
        // silently accepting a value the user never typed. `Option<T>` defaults
        // to `None` (renders blank), and the `required` rule below rejects it.
        let is_constrained_required_numeric = is_constrained_required_numeric(f);
        if is_constrained_required_numeric {
            // Emitted alongside the `range` rule so `None` is rejected
            // server-side (a 422 with an inline error) rather than parsed as `0`.
            let _ = writeln!(struct_fields, "    #[validate(required)]");
        }
        if let Some(rules) = validations.get(name) {
            for rule in rules {
                let _ = writeln!(struct_fields, "    #[validate({rule})]");
            }
        }
        if f.kind.is_attachment() {
            // Zero-JS multipart uploads (issue #1236): the attachment is NOT a
            // urlencodable form field, so it is excluded from `{Pascal}Form`
            // entirely. `into_new` seeds the `New{Pascal}` blob column to `None`;
            // the create/update handler streams the multipart file part to the
            // blob store and binds the resulting `Blob` onto `new` afterwards
            // (preserving the existing blob on an update with no new file). No
            // struct field and no `from_row` seed: a file input can't be
            // repopulated (browser security), and the stored attachment is
            // rendered on the show view straight from the row.
            let _ = writeln!(into_new, "        {name}: None,");
        } else if f.kind == FieldKind::Bool {
            // Unchecked checkboxes are absent from submitted form data;
            // `#[serde(default)]` maps that absence to `false` instead of a
            // "missing field" 400.
            if f.nullable {
                let _ = writeln!(struct_fields, "    pub {name}: Option<bool>,");
            } else {
                let _ = writeln!(
                    struct_fields,
                    "    #[serde(default)]\n    pub {name}: bool,"
                );
            }
            let _ = writeln!(into_new, "        {name}: form.{name},");
            let _ = writeln!(from_row, "            {name}: row.{name},");
        } else if f.kind == FieldKind::Bytea {
            // `Vec<u8>` cannot deserialize from a single url-encoded value at
            // all: `serde_urlencoded` hands each field's value to `serde` as
            // a plain string, and `Vec<u8>`'s `Deserialize` impl expects a
            // sequence — so a native-typed Bytea field would fail to decode
            // *any* submission, not just an untouched one. There is no raw-
            // bytes HTML input widget anyway, so it's represented as a
            // lossy-UTF8 `String` on the form (matching what the old
            // hand-rolled edit form already showed via
            // `String::from_utf8_lossy`), converted back to bytes in
            // `into_new`.
            if f.nullable {
                let _ = writeln!(struct_fields, "    pub {name}: Option<String>,");
                let _ = writeln!(
                    into_new,
                    "        {name}: form.{name}.as_ref().map(|value| value.clone().into_bytes()),"
                );
                let _ = writeln!(
                    from_row,
                    "            {name}: row.{name}.as_ref().map(|value| String::from_utf8_lossy(value).into_owned()),"
                );
            } else {
                let _ = writeln!(struct_fields, "    pub {name}: String,");
                let _ = writeln!(
                    into_new,
                    "        {name}: form.{name}.clone().into_bytes(),"
                );
                let _ = writeln!(
                    from_row,
                    "            {name}: String::from_utf8_lossy(&row.{name}).into_owned(),"
                );
            }
        } else if matches!(f.kind, FieldKind::NaiveDateTime | FieldKind::DateTime) {
            // Represented as a `String` on the form (the browser's wire shape),
            // so it always decodes and serializes cleanly for repopulation; the
            // conversion parses it back to the model's datetime type.
            needs_datetime = true;
            let to_utc = if f.kind == FieldKind::DateTime {
                ".and_utc()"
            } else {
                ""
            };
            if f.nullable {
                let _ = writeln!(struct_fields, "    pub {name}: Option<String>,");
                let _ = writeln!(
                    into_new,
                    "        {name}: form.{name}.as_deref().filter(|value| !value.is_empty())\n\
                     \x20\x20\x20\x20\x20\x20\x20\x20.map(|value| parse_local_datetime(value).map(|dt| dt{to_utc}))\n\
                     \x20\x20\x20\x20\x20\x20\x20\x20.transpose()?,"
                );
                let _ = writeln!(
                    from_row,
                    "            {name}: row.{name}.as_ref().map(|dt| dt.format(\"%Y-%m-%dT%H:%M:%S%.f\").to_string()),"
                );
            } else {
                let _ = writeln!(struct_fields, "    pub {name}: String,");
                let _ = writeln!(
                    into_new,
                    "        {name}: parse_local_datetime(&form.{name})?{to_utc},"
                );
                let _ = writeln!(
                    from_row,
                    "            {name}: row.{name}.format(\"%Y-%m-%dT%H:%M:%S%.f\").to_string(),"
                );
            }
        } else if let Some(enum_ty) = f.enum_type_name() {
            // Decoded as a plain `String` then parsed via the enum's `FromStr`
            // in `into_new` (an out-of-set value yields a 400 naming the field).
            let mut arms = String::new();
            for v in &f.variants {
                let _ = write!(arms, "{enum_ty}::{} => \"{v}\".to_string(), ", pascal(v));
            }
            if f.nullable {
                let _ = writeln!(struct_fields, "    pub {name}: Option<String>,");
                let _ = writeln!(
                    into_new,
                    "        {name}: form.{name}.as_deref()\n\
                     \x20\x20\x20\x20\x20\x20\x20\x20.map(|value| value.parse::<{enum_ty}>())\n\
                     \x20\x20\x20\x20\x20\x20\x20\x20.transpose()\n\
                     \x20\x20\x20\x20\x20\x20\x20\x20.map_err(|err| autumn_web::AutumnError::bad_request_msg(format!(\"{name}: {{err}}\")))?,"
                );
                let _ = writeln!(
                    from_row,
                    "            {name}: row.{name}.as_ref().map(|value| match value {{ {arms}}}),"
                );
            } else {
                let _ = writeln!(struct_fields, "    pub {name}: String,");
                let _ = writeln!(
                    into_new,
                    "        {name}: form.{name}.parse::<{enum_ty}>()\n\
                     \x20\x20\x20\x20\x20\x20\x20\x20.map_err(|err| autumn_web::AutumnError::bad_request_msg(format!(\"{name}: {{err}}\")))?,"
                );
                let _ = writeln!(
                    from_row,
                    "            {name}: match &row.{name} {{ {arms}}},"
                );
            }
        } else if is_constrained_required_numeric {
            // A required numeric with a `{min,max}` range (issue #1388) is
            // `Option<T>` on the form struct (issue #1748). `validator`'s
            // `range` rule applies to the inner value only when `Some`, so the
            // range is still enforced server-side; `None` (the blank default)
            // is rejected by the `#[validate(required)]` emitted above rather
            // than parsed as `T::default()` (`0`). A native `T` here would
            // pre-fill `0` and silently pass both `required` and a range that
            // spans the zero default. `into_new` unwraps the validated
            // `Some(_)`; `from_row` wraps a persisted native value in `Some`.
            let rust_type = f.rust_type();
            let _ = writeln!(struct_fields, "    pub {name}: Option<{rust_type}>,");
            let _ = writeln!(
                into_new,
                "        {name}: form.{name}.ok_or_else(|| autumn_web::AutumnError::bad_request_msg(\"{name}: is required\"))?,"
            );
            let _ = writeln!(from_row, "            {name}: Some(row.{name}),");
        } else if !f.nullable
            && matches!(
                f.kind,
                FieldKind::I32
                    | FieldKind::I64
                    | FieldKind::F32
                    | FieldKind::F64
                    | FieldKind::Uuid
                    | FieldKind::Decimal { .. }
                    | FieldKind::References
            )
        {
            // Represented as a `String` on the form, exactly like a required
            // enum/datetime field: `T::default()` for these kinds (`0`, the nil
            // UUID, …) is a real, plausible-looking value, not "blank" — with a
            // native-typed field, the new-form's changeset would render it as
            // the input's pre-filled value (issue #1124 review), silently
            // accepting a value the user never typed instead of forcing
            // deliberate input the way the old hand-rolled (no `value` at all
            // when blank) form did. A nullable field of the same kind doesn't
            // need this: `Option<T>::default()` is already `None`, which
            // serializes to `null` and renders blank via `field_value`.
            let rust_type = f.rust_type();
            let _ = writeln!(struct_fields, "    pub {name}: String,");
            let _ = writeln!(
                into_new,
                "        {name}: form.{name}.parse::<{rust_type}>()\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20.map_err(|err| autumn_web::AutumnError::bad_request_msg(format!(\"{name}: {{err}}\")))?,"
            );
            let _ = writeln!(from_row, "            {name}: row.{name}.to_string(),");
        } else {
            // Issue #1326: a `:states(…)` state-machine column is transition-only,
            // so the EDIT form omits its input (see `render_form_for_helper`) and
            // the update submit carries no value for it. `#[serde(default)]` maps
            // that absence to an empty string instead of a "missing field" 400 —
            // harmless because the update `.set((…))` tuple excludes the column
            // (`render_update_columns`), and the create form still submits the
            // real initial state.
            if f.state_machine.is_some() {
                let _ = writeln!(struct_fields, "    #[serde(default)]");
            }
            // Plain scalars (String/Text, and any nullable numeric/Uuid/Decimal)
            // keep their native type — `Option<T>::default()` is already blank.
            let _ = writeln!(
                struct_fields,
                "    pub {name}: {rust_type},",
                rust_type = f.rust_type()
            );
            let _ = writeln!(into_new, "        {name}: form.{name}.clone(),");
            let _ = writeln!(from_row, "            {name}: row.{name}.clone(),");
        }
    }

    let form_struct = format!(
        "#[derive(serde::Deserialize, serde::Serialize, Default, validator::Validate)]\n\
         pub struct {pascal_name}Form {{\n\
         {struct_fields}}}"
    );

    // `into_new` is always sync now (issue #1236): attachment blobs are streamed
    // and bound in the handler, not resolved here, so no `&state`/`async` is
    // needed. Attachment columns are seeded to `None` and overwritten by the
    // handler after `into_new`.
    let into_new_fn = format!(
        "/// Convert the validated form into `New{pascal_name}` on the success\n\
         /// path. Enum/datetime parsing lives here (a bad value is a 400,\n\
         /// not a validation error — see `{pascal_name}Form`). Attachment\n\
         /// columns are seeded to `None` and set from the streamed upload by\n\
         /// the create/update handler.\n\
         fn into_new(form: &{pascal_name}Form) -> AutumnResult<New{pascal_name}> {{\n    \
         Ok(New{pascal_name} {{\n\
         {into_new}    }})\n\
         }}"
    );

    let from_row_impl = format!(
        "/// Seed a form changeset from a persisted row (edit-form GET).\n\
         impl From<&{pascal_name}> for {pascal_name}Form {{\n    \
         fn from(row: &{pascal_name}) -> Self {{\n        \
         Self {{\n\
         {from_row}        }}\n    \
         }}\n\
         }}"
    );

    let datetime_helper = if needs_datetime {
        PARSE_LOCAL_DATETIME_FN.to_owned()
    } else {
        String::new()
    };

    ModelFormParts {
        form_struct,
        into_new_fn,
        from_row_impl,
        datetime_helper,
    }
}

#[allow(
    clippy::too_many_lines,
    reason = "This is a single template — splitting it produces less readable output, \
              not more. The whole point is one place that prints one file."
)]
#[allow(clippy::too_many_arguments, clippy::fn_params_excessive_bools)]
fn render_routes_file(
    project_root: &Path,
    pascal_name: &str,
    snake_name: &str,
    plural: &str,
    fields: &[Field],
    all_fields: &[Field],
    sharded: bool,
    soft_delete: bool,
    id_type: IdType,
    live: bool,
    live_validation: bool,
    validations: &BTreeMap<String, Vec<String>>,
    missing_reference_targets: &BTreeSet<String>,
    authorize: bool,
    owner: Option<&str>,
    searchable: &[String],
) -> String {
    let id_rust = id_type.rust_type();
    // Issue #1319: the full-text search box + results handler apply only to the
    // standard (non-live) HTML index. The `--live`/`--live-validation` list is a
    // `<ul>` with an SSE out-of-band swap contract that a `data_table` search
    // fragment would break, so gate the search box off for those variants (the
    // model/repository/migration still get `searchable`). Precedent: the label
    // -map gating for the live index.
    let search_enabled = !searchable.is_empty() && !live && !live_validation;
    let validated_fields: Vec<&str> = validations.keys().map(String::as_str).collect();
    let unique_fields: Vec<&Field> = fields.iter().filter(|f| f.unique).collect();
    // Issue #1326: fields carrying a `:states(…)` state machine. Only these
    // scaffolds emit a `show_view` helper, per-field `transition_controls`, and a
    // `POST /{plural}/{{id}}/transitions/{field}` handler. A scaffold with none
    // (the overwhelming common case) keeps the pre-#1326 output byte-identical.
    let sm_fields: Vec<&Field> = fields
        .iter()
        .filter(|f| f.state_machine.is_some())
        .collect();
    let has_state_machine = !sm_fields.is_empty();
    let update_columns = render_update_columns(plural, fields);
    let nullable_field_match = render_nullable_field_match(fields);
    let has_attachments = has_attachment_fields(fields);
    // Issue #1125/#1830: inline record-level authorization on the mutating HTML
    // handlers + owner-scoped index. The caller sets `authorize` whenever an
    // owner column exists, on EVERY variant. Attachment scaffolds already thread
    // a `state: State<AppState>` param through `create`/`update` (for the
    // multipart upload), so those two handlers reuse it rather than injecting a
    // second, conflicting `State` extractor — see `create_update_authz_params` /
    // `create_update_state_expr` below.
    // The owner column name (`user_id`/`author_id`/`owner_id`/a users FK). Only
    // read when `owner_scoped_index` is set (so the caller passed `Some`).
    let owner_col = owner.unwrap_or("user_id");
    // Issue #1830: the index is owner-scoped only when an owner column exists. A
    // no-owner scaffold still record-authorizes its mutating handlers (`authorize`
    // is set), but its index cannot filter by owner, so it keeps the unscoped
    // listing.
    let owner_scoped_index = authorize && owner.is_some();
    // Issue #1841: the STANDARD (non-live, non-live-validation, non-sharded) Db
    // owner path is the only one whose repository carries `owner = <col>` (see
    // `render_repository_file`), so it is the only one whose index/search can call
    // the macro's owner-filtered `list_scoped` / `search_page_scoped`. That path
    // gets the sort/filter data_table + the search box, both safely scoped to the
    // current user. The `--sharded`/`--live`/`--live-validation` owner indexes
    // keep the #1830 manual owner-filtered query (no scoped repo methods emitted).
    let owner_scoped_standard = owner_scoped_index && !sharded && !live && !live_validation;
    // The full extractor pair the authorize wiring needs on handlers that do not
    // already carry a `state:` wrapper. No trailing comma — each insertion site
    // supplies its own delimiter.
    let authz_params_full = if authorize {
        "\n    autumn_web::extract::State(state): autumn_web::extract::State<autumn_web::AppState>,\
         \n    session: autumn_web::session::Session"
    } else {
        ""
    };
    // Attachment `create`/`update` already own a `state: State<AppState>` param;
    // a second `State(state)` would be a duplicate binding (why #1125 excluded
    // attachments), so those two handlers gain ONLY `session` and deref the
    // existing wrapper (`&*state`) in their authorize calls. `edit`/`destroy`
    // never carry `state`, so they take the full pair.
    let authz_params_session_only = if authorize {
        "\n    session: autumn_web::session::Session"
    } else {
        ""
    };
    let create_update_authz_params = if has_attachments {
        authz_params_session_only
    } else {
        authz_params_full
    };
    let edit_destroy_authz_params = authz_params_full;
    // The `AppState` receiver expression for the authorize calls: create/update
    // deref the reused attachment wrapper (`State<T>` → `T`); everything else
    // binds `AppState` directly via the injected `State(state)`.
    let create_update_state_expr = if has_attachments { "&*state" } else { "&state" };
    let edit_destroy_state_expr = "&state";
    // The attachment `update` handler loads `current` after parsing the multipart
    // body (to preserve un-replaced blobs); record-authorize the actor against
    // that same already-loaded row before writing, instead of a second load.
    // Spliced into `update_new_block` right after its `current` load.
    let authz_attachment_update = if authorize && has_attachments {
        format!(
            "autumn_web::authorization::authorize::<{pascal_name}>({create_update_state_expr}, &session, \"update\", &current).await?;\n    "
        )
    } else {
        String::new()
    };
    // Every PRESENT `references` field (its target model — and so its
    // `src/schema.rs` entry — is in the project; `missing_reference_targets`
    // excludes the rest, which the caller already warned about and which fall
    // back to a numeric id). This drives the issue #1146 parent-DISPLAY
    // rendering on index/show, which is generator-emitted *view* markup
    // (`posts::table.find(fk).select(posts::title)`), independent of the form
    // control — so it applies in `--live-validation` mode too.
    let display_reference_fields: Vec<&Field> = fields
        .iter()
        .filter(|f| f.kind.is_reference() && !missing_reference_targets.contains(&f.name))
        .collect();
    // The subset that also renders an in-FORM `<select>` of the referenced
    // table's ids (issue #1135 AC 2) plus its runtime option loaders. Issue
    // #1750: `--live-validation` renders the form through the per-field path
    // (no `form_for`), which used to drop the dropdown — the per-field path now
    // emits a raw runtime-populated `<select>` (see
    // `render_live_reference_select`), so every mode gets the belongs_to
    // dropdown.
    let reference_fields: Vec<&Field> = display_reference_fields.clone();
    let has_reference_selects = !reference_fields.is_empty();

    // Issue #1130: standard scaffolds render every view through the
    // application's shared `crate::layout` (nav bar, stylesheet links,
    // skip-link, footer) rather than a private per-file layout stub, so a
    // scaffolded page looks like the rest of the app and there is only ever one
    // layout definition in the project. Live and live-validation views keep a
    // local `layout` helper because they need extra `<head>` scripts
    // (SSE/idiomorph) and a morph-enabled `<body>` the shared 4-arg shell can't
    // express.
    let shared_layout = !live && !live_validation;
    let layout_fn = if shared_layout {
        "crate::layout"
    } else {
        "layout"
    };
    // The shared `crate::layout(title, current_path, flash, content)` takes a
    // `current_path` (used by `nav_bar` to mark the active link). The resource
    // base path `/{plural}` is a sensible value for every scaffolded view; the
    // private (live) layout has no such argument.
    let cp = |path: &str| -> String {
        if shared_layout {
            format!("\"{path}\", ")
        } else {
            String::new()
        }
    };
    let cp_index = cp(&format!("/{plural}"));
    let cp_show = cp(&format!("/{plural}"));
    let cp_new = cp(&format!("/{plural}/new"));
    let cp_edit = cp(&format!("/{plural}"));
    // Issue #1240: render pending flash through the shared, accessible
    // `flash_messages()` helper (per-severity `role`/`aria-live`) instead of
    // the older `flash.render()`. This is the `flash` argument every view
    // threads into the layout.
    let flash_arg = "flash_messages(&flash.consume().await)";

    // Per-reference display resolution (issue #1146): the `<select>` options,
    // index columns, and show rows render the parent's display column (a
    // `name`/`title`/first-string heuristic, or an explicit `{label:col}`)
    // instead of the raw foreign-key id. A reference whose target has no
    // string column has no entry here and keeps rendering the id. Resolved from
    // the display-scoped set so it's populated in `--live-validation` too.
    let reference_displays: BTreeMap<String, ReferenceDisplay> = display_reference_fields
        .iter()
        .filter_map(|f| {
            resolve_reference_display(project_root, f, plural, all_fields)
                .map(|d| (f.name.clone(), d))
        })
        .collect();
    let model_form = render_model_form(pascal_name, fields, validations);
    // Enum fields need their generated Rust type in scope here — `into_new`
    // parses into it and the `From<&Row>` seed matches against its variants
    // (see `render_model_form`).
    let enum_import_suffix: String =
        fields
            .iter()
            .filter_map(Field::enum_type_name)
            .fold(String::new(), |mut out, ty| {
                let _ = write!(out, ", {ty}");
                out
            });
    // The destroy handler must honour the resource's delete semantics: when the
    // scaffold was generated with `--soft-delete`, mark `deleted_at` (matching
    // the soft-delete repository) instead of issuing a physical `DELETE`.
    let destroy_stmt = if live {
        if sharded {
            format!(
                "let repo = Pg{pascal_name}Repository::from_shard(&db);\n    \
                 repo.delete_by_id(*id).await?;\n    \
                 let deleted = 1;"
            )
        } else {
            "repo.delete_by_id(*id).await?;\n    let deleted = 1;".to_owned()
        }
    } else if soft_delete {
        // Filter on `deleted_at IS NULL` so deleting an already-soft-deleted row
        // affects zero rows and returns 404, matching the physical-delete path.
        format!(
            "let deleted = diesel::update(\n        {plural}::table.find(*id).filter({plural}::deleted_at.is_null()),\n    )\n        \
                 .set({plural}::deleted_at.eq(Some(chrono::Utc::now().naive_utc())))\n        \
                 .execute(&mut *db)\n        .await?;"
        )
    } else {
        format!(
            "let deleted = diesel::delete({plural}::table.find(*id))\n        \
                 .execute(&mut *db)\n        .await?;"
        )
    };

    let create_stmt = if live {
        if sharded {
            format!(
                "let repo = Pg{pascal_name}Repository::from_shard(&db);\n    \
                 repo.save(&new).await?;"
            )
        } else {
            "repo.save(&new).await?;".to_owned()
        }
    } else {
        format!(
            "diesel::insert_into({plural}::table)\n        \
             .values(&new)\n        \
             .execute(&mut *db)\n        .await?;"
        )
    };

    let update_changeset_expr = render_update_changeset_expr(pascal_name, fields);
    let update_stmt = if live {
        if sharded {
            format!(
                "let repo = Pg{pascal_name}Repository::from_shard(&db);\n    \
                 let update_changes = {update_changeset_expr};\n    \
                 repo.update(*id, &update_changes).await?;\n    \
                 let updated = 1;"
            )
        } else {
            format!(
                "let update_changes = {update_changeset_expr};\n    \
                 repo.update(*id, &update_changes).await?;\n    \
                 let updated = 1;"
            )
        }
    } else {
        format!(
            "let updated = diesel::update({plural}::table.find(*id))\n        \
             .set(({update_columns}))\n        \
             .execute(&mut *db)\n        .await?;"
        )
    };

    // Issue #1236: a scaffold with attachment fields submits `multipart/form-data`
    // so the browser can upload files with zero JavaScript (progressive
    // enhancement). Non-attachment scaffolds stay URL-encoded. Used only by the
    // `--live-validation` raw-markup `<form>` tags; the standard `form_for` path
    // sets the enctype automatically via `FieldControl::File`.
    let form_enctype = if has_attachments {
        " enctype=\"multipart/form-data\""
    } else {
        ""
    };

    let db_ty = if sharded { "ShardedDb" } else { "Db" };
    let create_signature = if live && !sharded {
        if has_attachments {
            format!(
                "flash: Flash, state: autumn_web::extract::State<autumn_web::AppState>, repo: Pg{pascal_name}Repository, body: Bytes"
            )
        } else {
            format!("flash: Flash, repo: Pg{pascal_name}Repository, body: Bytes")
        }
    } else {
        if has_attachments {
            format!(
                "flash: Flash, state: autumn_web::extract::State<autumn_web::AppState>, mut db: {db_ty}, body: Bytes"
            )
        } else {
            format!("flash: Flash, mut db: {db_ty}, body: Bytes")
        }
    };

    let update_signature = if live && !sharded {
        if has_attachments {
            format!(
                "flash: Flash,\n    state: autumn_web::extract::State<autumn_web::AppState>,\n    id: Path<{id_rust}>,\n    repo: Pg{pascal_name}Repository,\n    body: Bytes,"
            )
        } else {
            format!(
                "flash: Flash,\n    id: Path<{id_rust}>,\n    repo: Pg{pascal_name}Repository,\n    body: Bytes,"
            )
        }
    } else {
        if has_attachments {
            format!(
                "flash: Flash,\n    state: autumn_web::extract::State<autumn_web::AppState>,\n    id: Path<{id_rust}>,\n    mut db: {db_ty},\n    body: Bytes,"
            )
        } else {
            format!(
                "flash: Flash,\n    id: Path<{id_rust}>,\n    mut db: {db_ty},\n    body: Bytes,"
            )
        }
    };

    let destroy_signature_arg = if live && !sharded {
        format!("repo: Pg{pascal_name}Repository")
    } else {
        format!("mut db: {db_ty}")
    };

    // Issue #1124: every scaffold's create/update now re-renders the form on a
    // rejected submission, so both handlers carry a CSRF token/field the same
    // way `new_form`/`edit_form` do. Inserted right after `flash: Flash` (NOT
    // appended at the end) — axum's `Handler` trait requires the body-consuming
    // `Bytes` extractor to stay the *last* parameter; every other extractor
    // must come before it.
    let create_signature = create_signature.replacen(
        "flash: Flash",
        "flash: Flash, csrf: Option<CsrfToken>, csrf_field: Option<CsrfFormField>, \
         submit_token: Option<SubmitToken>, submit_field: Option<SubmitFormField>",
        1,
    );
    let update_signature = update_signature.replacen(
        "flash: Flash,",
        "flash: Flash,\n    csrf: Option<CsrfToken>,\n    csrf_field: Option<CsrfFormField>,\n    \
         submit_token: Option<SubmitToken>,\n    submit_field: Option<SubmitFormField>,",
        1,
    );

    // Issue #1135: reference selects need a DB handle to load their options
    // in every handler that renders the form. `create`/`update` already carry
    // `mut db` except on the live non-sharded path (which uses the repository
    // extractor); `new_form` never had one. Keep `body: Bytes` last — axum's
    // `Handler` impl requires the body-consuming extractor in final position.
    let (create_signature, update_signature) = if has_reference_selects && live && !sharded {
        (
            create_signature.replacen("body: Bytes", &format!("mut db: {db_ty}, body: Bytes"), 1),
            update_signature.replacen(
                "body: Bytes",
                &format!("mut db: {db_ty},\n    body: Bytes"),
                1,
            ),
        )
    } else {
        (create_signature, update_signature)
    };
    let new_form_db_param = if has_reference_selects {
        format!("mut db: {db_ty},\n    ")
    } else {
        String::new()
    };

    // Issue #1125/#1830: thread the extractors the authorize wiring needs into
    // the mutating handlers. Inserted before the body-consuming `Bytes` extractor
    // in `create`/`update` (axum requires `Bytes` last) and appended to the
    // `destroy` arg list (no body extractor). `create`/`update` on the attachment
    // path reuse their existing `state:` wrapper and add only `session`; every
    // other authorized handler gets the full `State` + `Session` pair.
    let (create_signature, update_signature, destroy_signature_arg) = if authorize {
        (
            create_signature.replacen(
                "body: Bytes",
                &format!("{create_update_authz_params},\n    body: Bytes"),
                1,
            ),
            update_signature.replacen(
                "\n    body: Bytes",
                &format!("{create_update_authz_params},\n    body: Bytes"),
                1,
            ),
            format!("{destroy_signature_arg},{edit_destroy_authz_params}"),
        )
    } else {
        (create_signature, update_signature, destroy_signature_arg)
    };

    // Issue #1236: a scaffold with attachment fields consumes the request body as
    // `multipart/form-data` (streaming file parts to the blob store) instead of
    // `Bytes`. Swap the body-consuming extractor in the last parameter slot; it
    // must stay LAST (axum's `Handler` requirement), which every earlier
    // transform (CSRF, reference-select `db`, authz) already respects by
    // inserting BEFORE `body: Bytes`.
    let (create_signature, update_signature) = if has_attachments {
        (
            create_signature.replace(
                "body: Bytes",
                "mut multipart: autumn_web::extract::Multipart",
            ),
            update_signature.replace(
                "body: Bytes",
                "mut multipart: autumn_web::extract::Multipart",
            ),
        )
    } else {
        (create_signature, update_signature)
    };

    // `decode_form` decodes the urlencoded text fields into `{Pascal}Form`. The
    // attachment path rebuilds a urlencoded body from the multipart text parts
    // and reuses this exact decoder, so the empty-nullable-field filtering lives
    // in one place. `into_new` (always sync now — issue #1236) converts the
    // validated form into `New{Pascal}`; attachment blob columns are seeded to
    // `None` and set by the handler from the streamed upload.
    let decode_call = "decode_form(body)?".to_owned();
    let decode_form_sig = format!("fn decode_form(body: Bytes) -> AutumnResult<{pascal_name}Form>");
    let into_new_call = "into_new(changeset.data())?".to_owned();

    // Issue #1236: for attachment scaffolds the create/update handlers stream the
    // multipart body, collect text parts as urlencoded pairs, save each file part
    // to the blob store, then decode + validate + bind the blobs. These blocks
    // splice into the handler templates in place of the plain `let form = …` /
    // `let new = …` lines.
    let attachment_fields: Vec<&Field> = fields.iter().filter(|f| f.kind.is_attachment()).collect();
    // Issue #1872: the create/update handlers stream each uploaded file to the
    // blob store *before* changeset validation and the DB write, so any early
    // return after the save would orphan the just-uploaded blob. We record only
    // the freshly-saved `<field>_blob`s (into `saved_blob_keys`) — pushed at the
    // point of each save, so the key set is populated incrementally as blobs are
    // persisted — and best-effort delete them before every early-return path that
    // can occur after the first save.
    //
    // Codex P2 (centralized): the *whole* fallible multipart-parse-and-decode
    // span — `next_field()?`, each `save_to_blob_store()?`, `bytes_limited()?`,
    // the UTF-8 `map_err(…)?`, and `decode_form(…)?` — runs inside one
    // `async { … }.await` block typed to the handler's `AutumnError`, whose `Err`
    // is funneled through a single cleanup path (`form_decode_block`). That covers
    // every `?` in the span (current and future) without per-line wrapping, so a
    // malformed boundary / oversized text field / invalid UTF-8 arriving *after* a
    // blob was saved can no longer leak it. The remaining post-parse early returns
    // (changeset validation, `into_new`, the unique-violation 422, the generic DB
    // error, and the update's current-row load / not-found) sit *outside* that
    // block and keep splicing `{blob_cleanup}` before their `return`. A preserved
    // existing blob is never enrolled.
    let blob_cleanup = if has_attachments {
        "for key in &saved_blob_keys {\n        let _ = store.delete(key).await;\n    }\n    "
    } else {
        ""
    };
    let form_decode_block = if has_attachments {
        let mut blob_decls = String::new();
        let mut match_arms = String::new();
        for f in &attachment_fields {
            let name = &f.name;
            let _ = writeln!(
                blob_decls,
                "    let mut {name}_blob: Option<autumn_web::storage::Blob> = None;"
            );
            // Issue #1872: record the freshly-saved blob's key into
            // `saved_blob_keys` *immediately* after each successful save, so any
            // later fallible early return (a subsequent attachment field's save,
            // `decode_form`, validation, the DB write) can best-effort delete it.
            // The save's own `?` (and every other fallible `?` in the parse span)
            // is covered centrally: the whole multipart-parse-and-decode section
            // runs inside a single `async {…}` block whose `Err` is funneled
            // through one cleanup path (see `form_decode_block`), so a failed save
            // cleans up any earlier-saved sibling blobs without per-line wrapping.
            let _ = write!(
                match_arms,
                "            Some(\"{name}\") => {{\n                \
                 if field.file_name().is_some_and(|file_name| !file_name.is_empty()) {{\n                    \
                 let key = format!(\n                        \
                 \"{plural}/{name}/{{}}_{{}}\",\n                        \
                 chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default(),\n                        \
                 uuid::Uuid::new_v4()\n                    \
                 );\n                    \
                 let blob = field.save_to_blob_store(&*store, key).await?;\n                    \
                 saved_blob_keys.push(blob.key.clone());\n                    \
                 {name}_blob = Some(blob);\n                \
                 }}\n            \
                 }}\n"
            );
        }
        format!(
            "let store = state\n        \
             .extension::<autumn_web::storage::BlobStoreState>()\n        \
             .ok_or_else(|| AutumnError::internal_server_error_msg(\"storage not configured\"))?\n        \
             .store()\n        \
             .clone();\n    \
             let mut saved_blob_keys: Vec<String> = Vec::new();\n\
             {blob_decls}    \
             let __parse_result: AutumnResult<{pascal_name}Form> = async {{\n        \
             let mut form_pairs: Vec<(String, String)> = Vec::new();\n        \
             while let Some(field) = multipart.next_field().await? {{\n            \
             let field_name = field.name().map(str::to_owned);\n            \
             match field_name.as_deref() {{\n\
             {match_arms}            \
             Some(other) => {{\n                \
             let value = String::from_utf8(field.bytes_limited().await?)\n                    \
             .map_err(|_| AutumnError::bad_request_msg(\"form field was not valid UTF-8\"))?;\n                \
             form_pairs.push((other.to_owned(), value));\n            \
             }}\n            \
             None => {{}}\n        \
             }}\n        \
             }}\n        \
             let encoded = url::form_urlencoded::Serializer::new(String::new())\n            \
             .extend_pairs(form_pairs.iter().map(|(key, value)| (key.as_str(), value.as_str())))\n            \
             .finish();\n        \
             let form = decode_form(Bytes::from(encoded))?;\n        \
             Ok(form)\n    \
             }}\n    \
             .await;\n    \
             let form = match __parse_result {{\n        \
             Ok(form) => form,\n        \
             Err(err) => {{\n            \
             {blob_cleanup}return Err(err);\n        \
             }}\n    \
             }};"
        )
    } else {
        format!("let form = {decode_call};")
    };
    // Issue #1872: for attachment scaffolds `into_new` runs *after* the blob save,
    // so its fallible parse (`?`) must first clean up the just-saved blob(s). We
    // emit an explicit `match` that runs the cleanup then returns the same error
    // the `?` would have produced.
    let into_new_bind = format!(
        "let mut new = match into_new(changeset.data()) {{\n        \
         Ok(new) => new,\n        \
         Err(err) => {{\n            \
         {blob_cleanup}return Err(err);\n        \
         }}\n    \
         }};"
    );
    // Create: build `New{Pascal}` then bind each streamed blob (a `None` blob
    // means no file was submitted — the column stays NULL, satisfying the
    // optional-empty-as-NULL acceptance criterion).
    let create_new_block = if has_attachments {
        let mut binds = String::new();
        for f in &attachment_fields {
            let name = &f.name;
            let _ = write!(binds, "\n    new.{name} = {name}_blob;");
        }
        format!("{into_new_bind}{binds}")
    } else {
        format!("let new = {into_new_call};")
    };
    // Update: preserve the existing blob when no new file was uploaded
    // (`streamed.or(current)`), so an edit that doesn't touch the file leaves the
    // stored attachment intact instead of nulling it. The current row is loaded
    // through the same handle the update statement uses (repository on the live
    // path, sharded repo on the sharded path, diesel otherwise).
    let update_new_block = if has_attachments {
        // Issue #1872: loading the current row also happens after the blob save,
        // so its fallible steps clean up the just-saved blob(s) before returning.
        let load_current = if live && !sharded {
            format!(
                "let current = match repo.find_by_id(*id).await {{\n        \
                 Ok(Some(current)) => current,\n        \
                 Ok(None) => {{\n            \
                 {blob_cleanup}return Err(AutumnError::not_found_msg(format!(\"{pascal_name} with id {{}} not found\", *id)));\n        \
                 }}\n        \
                 Err(err) => {{\n            \
                 {blob_cleanup}return Err(err);\n        \
                 }}\n    \
                 }};\n    "
            )
        } else if sharded {
            format!(
                "let current = match Pg{pascal_name}Repository::from_shard(&db).find_by_id(*id).await {{\n        \
                 Ok(Some(current)) => current,\n        \
                 Ok(None) => {{\n            \
                 {blob_cleanup}return Err(AutumnError::not_found_msg(format!(\"{pascal_name} with id {{}} not found\", *id)));\n        \
                 }}\n        \
                 Err(err) => {{\n            \
                 {blob_cleanup}return Err(err);\n        \
                 }}\n    \
                 }};\n    "
            )
        } else {
            format!(
                "let current: {pascal_name} = match {plural}::table\n        \
                 .find(*id)\n        \
                 .select({pascal_name}::as_select())\n        \
                 .first(&mut *db)\n        \
                 .await\n    \
                 {{\n        \
                 Ok(current) => current,\n        \
                 Err(err) => {{\n            \
                 {blob_cleanup}return Err(AutumnError::not_found(err));\n        \
                 }}\n    \
                 }};\n    "
            )
        };
        let mut binds = String::new();
        for f in &attachment_fields {
            let name = &f.name;
            let _ = write!(binds, "\n    new.{name} = {name}_blob.or(current.{name});");
        }
        format!("{load_current}{authz_attachment_update}{into_new_bind}{binds}")
    } else {
        format!("let new = {into_new_call};")
    };

    // Shared re-render bodies: the same `layout(...)` markup the GET handlers
    // emit, reused verbatim by the 422 branches so the form can't drift. Both
    // read from a `Changeset<{Pascal}Form>` named `changeset` and the CSRF
    // params now present on every create/update signature.
    //
    // Issue #1135: the standard scaffold renders the whole form through one
    // shared `{snake}_form_for` helper (a single `form_for` call deriving
    // every control from the `FormModel` descriptors), so the view bodies
    // carry zero per-column code. `--live-validation` keeps the per-field
    // emission path: its htmx inline-validation inputs (`text_input_htmx`)
    // have no `FieldControl` equivalent for `form_for` to dispatch to.
    let (new_form_body, edit_form_body, form_for_helper) = if live_validation {
        // Issue #1124: `new_form`, `edit_form`, and both 422 re-render
        // branches render the same inputs from a `Changeset<{Pascal}Form>`
        // variable named `changeset`, so one renderer serves every site and
        // the markup can never drift between them. Preserved values and
        // inline errors come from the changeset via the shipped
        // `autumn_web::form` helpers.
        let changeset_inputs = render_changeset_form_inputs(
            fields,
            "changeset",
            live_validation,
            &validated_fields,
            &reference_fields,
        );
        // Issue #1750: the belongs_to parent `<select>` (rendered inline by
        // `render_changeset_form_inputs` via `render_live_reference_select`)
        // reads a request-time `{name}_options` binding, so — exactly like the
        // standard path — the new/edit form bodies load the options before the
        // markup. The block wraps the `layout(...)` call so it splices into the
        // GET handlers and the 422 re-render branches unchanged.
        let mut option_loads = String::with_capacity(reference_fields.len() * 80);
        for f in &reference_fields {
            let name = &f.name;
            let _ = writeln!(
                option_loads,
                "        let {name}_options = {name}_select_options(&mut db).await?;"
            );
        }
        // Issue #1706: the primary submit control is emitted through the typed
        // `autumn_web::a11y::Button` primitive, whose constructor requires an
        // accessible name — a nameless submit button is a compile error in the
        // generated app. The destructive delete button below stays raw markup:
        // it carries an `onclick` confirm the current `Button` API can't express,
        // and converting would drop the confirmation guard.
        let new_form_layout = format!(
            "{layout_fn}(\"New {pascal_name}\", {cp_new}{flash_arg}, html! {{\n        \
             h1 {{ \"New {pascal_name}\" }}\n        \
             form action=(paths::create()) method=\"post\"{form_enctype} {{\n            \
             (csrf_input(csrf.as_ref(), csrf_field.as_ref()))\n            \
             (submit_token_input(submit_token.as_ref(), submit_field.as_ref()))\n{changeset_inputs}            \
             (autumn_web::a11y::Button::new(\"Create\").submit())\n        \
             }}\n    \
             }})"
        );
        let edit_form_layout = format!(
            "{layout_fn}(&format!(\"Edit {pascal_name} #{{}}\", *id), {cp_edit}{flash_arg}, html! {{\n        \
             h1 {{ \"Edit {pascal_name} #\" (*id) }}\n        \
             form action=(paths::update(*id)) method=\"post\"{form_enctype} {{\n            \
             (csrf_input(csrf.as_ref(), csrf_field.as_ref()))\n            \
             (submit_token_input(submit_token.as_ref(), submit_field.as_ref()))\n{changeset_inputs}            \
             (autumn_web::a11y::Button::new(\"Save\").submit())\n        \
             }}\n        \
             form action=(paths::delete(*id)) method=\"post\" {{\n            \
             (csrf_input(csrf.as_ref(), csrf_field.as_ref()))\n            \
             button type=\"submit\" onclick=\"return confirm('Delete this {pascal_name}?')\" {{ \"Delete\" }}\n        \
             }}\n    \
             }})"
        );
        let (new_form_body, edit_form_body) = if has_reference_selects {
            (
                format!("{{\n{option_loads}        {new_form_layout}\n    }}"),
                format!("{{\n{option_loads}        {edit_form_layout}\n    }}"),
            )
        } else {
            (new_form_layout, edit_form_layout)
        };
        // The referenced-row option loaders are emitted regardless: they
        // populate the in-form `<select>` (issue #1750) AND the issue #1146
        // index parent-label map (`render_index_reference_label_loads` collects
        // each `{name}_select_options(...)` into a `HashMap`).
        let option_loaders =
            render_reference_option_loaders(&display_reference_fields, db_ty, &reference_displays);
        (new_form_body, edit_form_body, option_loaders)
    } else {
        // Reference selects: load the referenced ids before rendering and
        // thread them into the shared helper (issue #1135, AC 2
        // "references→select"). The loads live in a block expression wrapped
        // around the `layout(...)` call so the same body splices into the GET
        // handlers and the 422 re-render branches unchanged.
        let mut option_loads = String::new();
        let mut option_args = String::new();
        for f in &reference_fields {
            let name = &f.name;
            let _ = writeln!(
                option_loads,
                "        let {name}_options = {name}_select_options(&mut db).await?;"
            );
            let _ = write!(option_args, ", &{name}_options");
        }
        // Issue #1326: the shared `{snake}_form_for` helper gains an
        // `exclude_state_fields` flag only when the model has a state-machine
        // column; the create form keeps the column (initial state) while the
        // edit form drops it (transition-only). A no-state-machine model passes
        // no extra argument, keeping the pre-#1326 call byte-identical.
        let form_exclude_create = if has_state_machine { ", false" } else { "" };
        let form_exclude_edit = if has_state_machine { ", true" } else { "" };
        let new_form_layout = format!(
            "{layout_fn}(\"New {pascal_name}\", {cp_new}{flash_arg}, html! {{\n        \
             h1 {{ \"New {pascal_name}\" }}\n        \
             ({snake_name}_form_for(&changeset, paths::create(), \"Create\", csrf.as_ref(), csrf_field.as_ref(), submit_token.as_ref(), submit_field.as_ref(){option_args}{form_exclude_create}))\n    \
             }})"
        );
        let edit_form_layout = format!(
            "{layout_fn}(&format!(\"Edit {pascal_name} #{{}}\", *id), {cp_edit}{flash_arg}, html! {{\n        \
             h1 {{ \"Edit {pascal_name} #\" (*id) }}\n        \
             ({snake_name}_form_for(&changeset, paths::update(*id), \"Save\", csrf.as_ref(), csrf_field.as_ref(), submit_token.as_ref(), submit_field.as_ref(){option_args}{form_exclude_edit}))\n        \
             form action=(paths::delete(*id)) method=\"post\" {{\n            \
             (csrf_input(csrf.as_ref(), csrf_field.as_ref()))\n            \
             button type=\"submit\" onclick=\"return confirm('Delete this {pascal_name}?')\" {{ \"Delete\" }}\n        \
             }}\n    \
             }})"
        );
        let (new_form_body, edit_form_body) = if has_reference_selects {
            (
                format!("{{\n{option_loads}        {new_form_layout}\n    }}"),
                format!("{{\n{option_loads}        {edit_form_layout}\n    }}"),
            )
        } else {
            (new_form_layout, edit_form_layout)
        };
        (
            new_form_body,
            edit_form_body,
            render_form_for_helper(pascal_name, snake_name, fields, missing_reference_targets)
                + &render_reference_option_loaders(&reference_fields, db_ty, &reference_displays),
        )
    };
    let form_model_impl = render_form_model_impl(pascal_name);

    // `unique` fields (issue #1032) still classify DB constraint violations,
    // but now feed the error into the *same* changeset renderer via
    // `Changeset::from_errors`, so a duplicate value shows an inline error
    // through the shipped helpers just like a validation failure.
    let unique_constraints_const = if unique_fields.is_empty() {
        String::new()
    } else {
        render_unique_constraints_const(plural, &unique_fields, all_fields)
    };

    let create_insert_block = if !unique_fields.is_empty() {
        // Issue #1872: `{blob_cleanup}` (empty unless the scaffold has attachment
        // fields) best-effort deletes the just-saved blob(s) on both the
        // unique-violation 422 and the generic DB-error early returns.
        format!(
            "let result: AutumnResult<()> = async {{\n        \
             {create_stmt}\n        \
             Ok(())\n    \
             }}.await;\n    \
             if let Err(err) = result {{\n        \
             if let Some((field, message)) = autumn_web::error::unique_violation_field(&err, UNIQUE_CONSTRAINTS) {{\n            \
             let mut errors = std::collections::HashMap::new();\n            \
             errors.insert(field.to_string(), vec![message.to_string()]);\n            \
             let changeset = Changeset::from_errors(changeset.into_inner(), errors);\n            \
             {blob_cleanup}return Ok((autumn_web::reexports::http::StatusCode::UNPROCESSABLE_ENTITY, {new_form_body}).into_response());\n        \
             }}\n        \
             {blob_cleanup}return Err(err);\n    \
             }}\n    \
             flash.success(\"{pascal_name} created\").await;\n    \
             Ok(autumn_web::Redirect::to(&paths::index()).into_response())"
        )
    } else if has_attachments {
        // Issue #1872: no unique constraints to classify, but the DB write can
        // still fail after the blob save — clean up before returning the error.
        format!(
            "let result: AutumnResult<()> = async {{\n        \
             {create_stmt}\n        \
             Ok(())\n    \
             }}.await;\n    \
             if let Err(err) = result {{\n        \
             {blob_cleanup}return Err(err);\n    \
             }}\n    \
             flash.success(\"{pascal_name} created\").await;\n    \
             Ok(autumn_web::Redirect::to(&paths::index()).into_response())"
        )
    } else {
        format!(
            "{create_stmt}\n    \
             flash.success(\"{pascal_name} created\").await;\n    \
             Ok(autumn_web::Redirect::to(&paths::index()).into_response())"
        )
    };
    // Issue #1125: on the standard authorized path, run the policy's `can_create`
    // check before building/inserting the changeset. Create has no loaded row yet,
    // so this uses `authorize_create` (context-only) rather than `authorize`.
    let authz_create_call = if authorize {
        format!(
            "autumn_web::authorization::authorize_create::<{pascal_name}>({create_update_state_expr}, &session).await?;\n    "
        )
    } else {
        String::new()
    };
    let create_fn = format!(
        "/// `POST /{plural}` — validate the submission and create a {snake_name},\n\
         /// or re-render the form at 422 with inline errors and preserved input.\n\
         #[secured]\n\
         #[post(\"/{plural}\")]\n\
         pub async fn create({create_signature}) -> AutumnResult<autumn_web::reexports::axum::response::Response> {{\n    \
         use autumn_web::reexports::axum::response::IntoResponse as _;\n    \
         {authz_create_call}\
         {form_decode_block}\n    \
         let changeset = form.into_changeset();\n    \
         if !changeset.is_valid() {{\n        \
         {blob_cleanup}return Ok((autumn_web::reexports::http::StatusCode::UNPROCESSABLE_ENTITY, {new_form_body}).into_response());\n    \
         }}\n    \
         {create_new_block}\n    \
         {create_insert_block}\n\
         }}\n"
    );

    let update_apply_block = if !unique_fields.is_empty() {
        // Issue #1872: `{blob_cleanup}` (empty unless the scaffold has attachment
        // fields) best-effort deletes the just-saved blob(s) on the
        // unique-violation 422, the generic DB-error, and the not-found returns.
        format!(
            "let result: AutumnResult<usize> = async {{\n        \
             {update_stmt}\n        \
             Ok(updated)\n    \
             }}.await;\n    \
             let updated = match result {{\n        \
             Ok(updated) => updated,\n        \
             Err(err) => {{\n            \
             if let Some((field, message)) = autumn_web::error::unique_violation_field(&err, UNIQUE_CONSTRAINTS) {{\n                \
             let mut errors = std::collections::HashMap::new();\n                \
             errors.insert(field.to_string(), vec![message.to_string()]);\n                \
             let changeset = Changeset::from_errors(changeset.into_inner(), errors);\n                \
             {blob_cleanup}return Ok((autumn_web::reexports::http::StatusCode::UNPROCESSABLE_ENTITY, {edit_form_body}).into_response());\n            \
             }}\n            \
             {blob_cleanup}return Err(err);\n        \
             }}\n    \
             }};\n    \
             if updated == 0 {{\n        \
             {blob_cleanup}return Err(AutumnError::not_found_msg(format!(\n            \
             \"{pascal_name} with id {{}} not found\", *id\n        \
             )));\n    \
             }}\n    \
             flash.success(\"{pascal_name} updated\").await;\n    \
             Ok(autumn_web::Redirect::to(&paths::show(*id)).into_response())"
        )
    } else if has_attachments {
        // Issue #1872: no unique constraints, but the update write and the
        // not-found guard both early-return after the blob save — clean up first.
        format!(
            "let result: AutumnResult<usize> = async {{\n        \
             {update_stmt}\n        \
             Ok(updated)\n    \
             }}.await;\n    \
             let updated = match result {{\n        \
             Ok(updated) => updated,\n        \
             Err(err) => {{\n            \
             {blob_cleanup}return Err(err);\n        \
             }}\n    \
             }};\n    \
             if updated == 0 {{\n        \
             {blob_cleanup}return Err(AutumnError::not_found_msg(format!(\n            \
             \"{pascal_name} with id {{}} not found\", *id\n        \
             )));\n    \
             }}\n    \
             flash.success(\"{pascal_name} updated\").await;\n    \
             Ok(autumn_web::Redirect::to(&paths::show(*id)).into_response())"
        )
    } else {
        format!(
            "{update_stmt}\n    \
             if updated == 0 {{\n        \
             return Err(AutumnError::not_found_msg(format!(\n            \
             \"{pascal_name} with id {{}} not found\", *id\n        \
             )));\n    \
             }}\n    \
             flash.success(\"{pascal_name} updated\").await;\n    \
             Ok(autumn_web::Redirect::to(&paths::show(*id)).into_response())"
        )
    };
    // Issue #1125/#1830: load the target row and run the policy check *before*
    // touching it, so a forbidden actor is denied (404/403 per config) before any
    // write. Loading first also gives the same not-found behavior the post-update
    // `updated == 0` guard provides. The load handle depends on the variant: the
    // `repo` extractor on `--live`, a `from_shard` repository on `--sharded`, and
    // raw diesel otherwise — all three yield the same `{Pascal}` row type.
    let load_current_stmt = |binding: &str| -> String {
        if live && !sharded {
            format!(
                "let {binding}: {pascal_name} = repo.find_by_id(*id).await?\n        \
                 .ok_or_else(|| AutumnError::not_found_msg(format!(\"{pascal_name} with id {{}} not found\", *id)))?;\n    "
            )
        } else if sharded {
            format!(
                "let {binding}: {pascal_name} = Pg{pascal_name}Repository::from_shard(&db).find_by_id(*id).await?\n        \
                 .ok_or_else(|| AutumnError::not_found_msg(format!(\"{pascal_name} with id {{}} not found\", *id)))?;\n    "
            )
        } else {
            format!(
                "let {binding}: {pascal_name} = {plural}::table\n        \
                 .find(*id)\n        \
                 .select({pascal_name}::as_select())\n        \
                 .first(&mut *db)\n        \
                 .await\n        \
                 .map_err(AutumnError::not_found)?;\n    "
            )
        }
    };
    // Update: on the attachment path the handler already loads `current` (after
    // parsing multipart, to preserve un-replaced blobs) and authorizes there via
    // `authz_attachment_update`, so no up-front preamble is emitted. Every other
    // variant loads + authorizes here.
    let authz_update_preamble = if authorize && !has_attachments {
        format!(
            "{load}autumn_web::authorization::authorize::<{pascal_name}>({state}, &session, \"update\", &current).await?;\n    ",
            load = load_current_stmt("current"),
            state = create_update_state_expr,
        )
    } else {
        String::new()
    };
    // Destroy: no form body, so always load + authorize up front (`&state`, since
    // `destroy` takes the full `State` pair even on the attachment path).
    let authz_destroy_preamble = if authorize {
        format!(
            "{load}autumn_web::authorization::authorize::<{pascal_name}>({state}, &session, \"delete\", &current).await?;\n    ",
            load = load_current_stmt("current"),
            state = edit_destroy_state_expr,
        )
    } else {
        String::new()
    };
    let authz_edit_call = if authorize {
        format!(
            "autumn_web::authorization::authorize::<{pascal_name}>({edit_destroy_state_expr}, &session, \"edit\", &row).await?;\n    "
        )
    } else {
        String::new()
    };
    let update_fn = format!(
        "/// `POST /{plural}/{{id}}/update` — validate and apply form data to a row,\n\
         /// or re-render the edit form at 422 with inline errors and preserved input.\n\
         /// Uses column-by-column `diesel::update().set(...)` (same convention as\n\
         /// `examples/todo-app`) so we don't need `AsChangeset` on `New{pascal_name}`.\n\
         #[secured]\n\
         #[post(\"/{plural}/{{id}}/update\")]\n\
         pub async fn update(\n    \
         {update_signature}\n\
         ) -> AutumnResult<autumn_web::reexports::axum::response::Response> {{\n    \
         use autumn_web::reexports::axum::response::IntoResponse as _;\n    \
         {authz_update_preamble}\
         {form_decode_block}\n    \
         let changeset = form.into_changeset();\n    \
         if !changeset.is_valid() {{\n        \
         {blob_cleanup}return Ok((autumn_web::reexports::http::StatusCode::UNPROCESSABLE_ENTITY, {edit_form_body}).into_response());\n    \
         }}\n    \
         {update_new_block}\n    \
         {update_apply_block}\n\
         }}\n"
    );

    // Template splice bindings for the generated form struct, its conversion,
    // the edit-form seed, and (when present) the datetime parse helper.
    let form_struct = &model_form.form_struct;
    let into_new_fn = &model_form.into_new_fn;
    let from_row_impl = &model_form.from_row_impl;
    let parse_datetime_helper = &model_form.datetime_helper;

    // The `index` handler: when sharded, use from_shard explicitly so the
    // generated code shows the canonical sharding pattern.
    //
    // Live (SSE) variant: keep the <ul>/<li> structure intact. LiveFragment
    // renders `li id=…` and insert_swap() targets `#{plural}-list` via
    // OobSwap::Target(BeforeEnd, …). Swapping to <table> would cause the SSE
    // broadcast to append <li> into a <table> at runtime (invalid HTML). The
    // table migration for the live path is a follow-up once LiveFragment
    // supports <tr> fragments.
    //
    // Non-live variants: use data_table so the index shows real fields out of
    // the box — no hand-authored <table>/<th>/<td> tags needed.
    let li_render = if live {
        format!(
            r#"li id=(format!("{snake_name}-{{}}", row.id)) {{ a href=(paths::show(row.id)) {{ "{pascal_name} #{{}}" (row.id) }} }}"#
        )
    } else {
        String::new() // unused in the non-live path
    };

    // For the live path we keep the original <ul> list so the SSE OOB-swap
    // contract remains valid.
    let live_ul_render = if live {
        format!(
            r#"@if page_req.page() == 1 {{
            ul id="{plural}-list" hx-ext="sse" sse-connect=(paths::events()) sse-swap="message" hx-swap="none" {{
                @for row in &page_data.content {{
                    {li_render}
                }}
            }}
        }} @else {{
            ul id="{plural}-list" {{
                @for row in &page_data.content {{
                    {li_render}
                }}
            }}
        }}"#
        )
    } else {
        String::new()
    };

    // For non-live paths, generate the data_table columns and call. Both the
    // plain AND sharded index promote displayable `references` columns to
    // render the parent's label from a per-view label map (issue #1146,
    // `index_columns_labeled` + `index_label_loads`): the sharded index handler
    // already threads a `ShardedDb`, its `{name}_select_options` loaders are
    // generated with `db_ty` (= `ShardedDb`), and the sharded `show` handler
    // already loads labels through the same connection — so the index reuses
    // that mechanism rather than falling back to raw ids. Only the `--live` SSE
    // list (a `<ul>` of ids, no data-table) keeps id rendering.
    //
    // #1126: sort/filter (the `ListQuery` extractor + `repo.list(..)` + sortable
    // `data_table` headers) is likewise gated OFF for the `--live` variants —
    // their `<ul>` has no column headers to hang sort links on, and the SSE
    // OOB-swap contract owns the list DOM. The `--live` index keeps the plain
    // `repo.page(&page_req)` call. `--live-validation` (without `--live`) renders
    // the normal data_table index, so it DOES get sort/filter.
    let columns_let = if live {
        String::new()
    } else {
        render_columns_vec(pascal_name, fields, &reference_displays, false)
    };
    let index_label_loads = if live {
        String::new()
    } else {
        render_index_reference_label_loads(&display_reference_fields, &reference_displays)
    };
    // The plain index gains `mut db: Db` only when there is a label map to load
    // (otherwise an unused extractor); the sharded index always has a
    // `ShardedDb` (for `from_shard`), promoted to `mut` when it must also run
    // the loader.
    let index_db_param = if index_label_loads.is_empty() {
        ""
    } else {
        "mut db: Db,\n    "
    };
    let sharded_index_db = if index_label_loads.is_empty() {
        "db: ShardedDb"
    } else {
        "mut db: ShardedDb"
    };
    let index_columns_labeled = if index_label_loads.is_empty() {
        columns_let
    } else {
        render_columns_vec(pascal_name, fields, &reference_displays, true)
    };
    // #1126: the data_table config is wired symmetrically with what the server
    // applies — `.query(..)` preserves the current filters on sort links,
    // `.active_sort`/`.active_dir` mark the column the repository ordered by, and
    // `repo.list(&list_query, ..)` applies exactly that sort/filter. Sortable
    // headers are opted-in per column by `render_columns_vec`.
    let table_render = if live {
        String::new()
    } else if owner_scoped_index && !owner_scoped_standard {
        // #1830 owner-scoped `--sharded`/`--live-validation` index: the handler
        // runs a manual owner-filtered query (not a scoped repo method) and does
        // not extract `ListQuery`, so its data_table stays on the plain
        // (non-sort/filter) config. Wiring owner-scoped sort/filter there is a
        // follow-up (issue #1841 covers the standard Db path only).
        format!(
            r#"(autumn_web::widgets::data_table(&page_data.content, &columns, &autumn_web::widgets::DataTableConfig::new("No {plural} yet.").base_path(&paths::index())))"#
        )
    } else {
        format!(
            r#"(autumn_web::widgets::data_table(&page_data.content, &columns, &autumn_web::widgets::DataTableConfig::new("No {plural} yet.").base_path(&paths::index()).query(raw_query.as_deref().unwrap_or_default()).active_sort(list_query.sort().unwrap_or_default()).active_dir(list_query.direction())))"#
        )
    };

    let list_render = if live { &live_ul_render } else { &table_render };
    // The list + pager block the index handler renders. When searchable (AC3),
    // this becomes an `active_search_input` box wired to `GET /{plural}/search`
    // sitting above the single `#{plural}-search-results` container that htmx
    // swaps into. We use the input-only `active_search_input` (not the composite
    // `active_search`, which would render its OWN empty `#{plural}-search-results`
    // container and produce a duplicate id) and render one container ourselves,
    // seeded with the initial `{list_render}` + pager server-side — so the first
    // paint needs no extra AJAX round-trip (no `.initial_load()`) and
    // non-JavaScript visitors still see the full list. The shared `crate::layout`
    // does not load htmx, so an htmx `<script>` is inlined here. When not
    // searchable (or a live variant), it is exactly the previous `{list_render}`
    // + `pagination_nav` pair — byte-for-byte identical (AC4).
    // #1126: the non-live (sort/filter) index handlers preserve the active
    // sort+filter query string on the pager links via `PagerOptions::query`, so
    // paging never drops the current sort/filter (`pager_query` is bound in each
    // handler from the raw query string). The `--live` variants call `repo.page`
    // and extract no `RawQuery`, so they keep the plain pager.
    let pager_line = if live {
        r"(pagination_nav(&page_data, &PagerOptions::new(&paths::index())))".to_string()
    } else {
        r"(pagination_nav(&page_data, &PagerOptions::new(&paths::index()).query(pager_query)))"
            .to_string()
    };
    let index_list_block = if search_enabled {
        format!(
            "script src=(autumn_web::htmx::HTMX_JS_PATH) {{}}\n        \
             (autumn_web::widgets::active_search_input(\"{snake_name}-search\", \"Search {pascal_name}s\", \
             &autumn_web::widgets::ActiveSearchConfig::new(\"/{plural}/search\", \"#{plural}-search-results\")\
             .placeholder(\"Search {pascal_name}s…\")))\n        \
             div id=\"{plural}-search-results\" {{\n            {list_render}\n            {pager_line}\n        }}"
        )
    } else {
        format!("{list_render}\n        {pager_line}")
    };
    let show_rows = render_show_property_rows(all_fields, &reference_displays);
    // The `show` handler pre-loads each displayable reference's parent label
    // (issue #1146) before building its property rows.
    let show_label_loads = render_show_reference_label_loads(all_fields, &reference_displays);

    // Issue #1830: the owner-scoped index runs a manual owner-filtered query on
    // whichever connection the variant threads — `ShardedDb` (pinned to the
    // current shard, exactly like the generated `show`/`create` handlers) when
    // `--sharded`, `Db` otherwise. Both deref (`&mut *db`) to a diesel-async
    // connection the count/load queries run against.
    let owner_index_db_param = if sharded {
        "mut db: ShardedDb"
    } else {
        "mut db: Db"
    };
    let index_handler = if owner_scoped_standard {
        // Issue #1841: standard owner-scoped index. Delegates to the macro's
        // owner-filtered `list_scoped(owner_id, &list_query, &page_req)` — the
        // SECURITY INVARIANT is that this branch NEVER calls the unscoped
        // `repo.list`/`repo.page`, so the allowlisted sort/filter and (when
        // searchable) the search box can be exposed while every row stays scoped
        // to the current user. `owner_id` is resolved from the same
        // `PolicyContext` the mutating handlers authorize against.
        format!(
            r#"/// `GET /{plural}` — paginated, sortable, filterable list of the {snake_name}s
/// the current user owns.
///
/// Accepts `?page=N&size=M` paging plus allowlisted `?sort=col&dir=asc|desc`
/// and `?filter[col]=val` params (the [`ListQuery`] extractor). Unknown or
/// malicious sort/filter keys are ignored against the model's column allowlist,
/// so this never 400s and can never inject SQL. Filtered to the authenticated
/// user's rows (owner column `{owner_col}`) via the repository's owner-scoped
/// `list_scoped` — the same rule the registered `{pascal_name}Scope` enforces
/// for `#[repository(scope = ...)]` index routes. This handler never calls the
/// unscoped `list`/`page`, so it cannot return another user's rows.
#[secured]
#[get("/{plural}")]
pub async fn index(
    list_query: ListQuery,
    RawQuery(raw_query): RawQuery,
    page_req: PageRequest,
    autumn_web::extract::State(state): autumn_web::extract::State<autumn_web::AppState>,
    session: autumn_web::session::Session,
    repo: Pg{pascal_name}Repository,
    {index_db_param}flash: Flash,
) -> AutumnResult<Markup> {{
    let ctx = autumn_web::authorization::PolicyContext::from_request(&state, &session).await;
    let owner_id = ctx.user_id_i64().unwrap_or(-1);
    let page_data: Page<{pascal_name}> = repo.list_scoped(owner_id, &list_query, &page_req).await?;
    let pager_query = raw_query.as_deref().unwrap_or("");
{index_label_loads}{index_columns_labeled}    Ok({layout_fn}("{pascal_name} index", {cp_index}{flash_arg}, html! {{
        h1 {{ "{pascal_name}s" }}
        a href=(paths::new()) {{ "New {pascal_name}" }}
        {index_list_block}
    }}))
}}"#
        )
    } else if owner_scoped_index {
        // Issue #1125/#1830: owner-scoped index for the `--sharded`/`--live`/
        // `--live-validation` variants (whose repositories carry no `owner =`
        // attr, so no scoped repo method exists). Pagination is preserved by
        // running a `COUNT(*)` + `LIMIT/OFFSET` query filtered to the current
        // user's rows, then wrapping the result in `Page::new`. `{list_render}`
        // keeps the `--live` SSE `<ul>` island (a data_table for the non-live
        // variants), so the SSE broadcast contract is unaffected — only the
        // *initial* server-rendered list is owner-scoped.
        format!(
            r#"/// `GET /{plural}` — paginated list of {snake_name}s the current user owns.
///
/// Accepts `?page=N&size=M` query parameters via the [`PageRequest`] extractor.
/// Out-of-range or missing values are clamped silently — list endpoints never
/// return HTTP 400 for bad paging parameters. Filtered to the authenticated
/// user's rows (owner column `{owner_col}`) — the same rule the registered
/// `{pascal_name}Scope` enforces for `#[repository(scope = ...)]` index routes.
#[secured]
#[get("/{plural}")]
pub async fn index(
    page_req: PageRequest,
    autumn_web::extract::State(state): autumn_web::extract::State<autumn_web::AppState>,
    session: autumn_web::session::Session,
    {owner_index_db_param},
    flash: Flash,
) -> AutumnResult<Markup> {{
    let ctx = autumn_web::authorization::PolicyContext::from_request(&state, &session).await;
    let owner_id = ctx.user_id_i64().unwrap_or(-1);
    let total: i64 = {plural}::table
        .filter({plural}::{owner_col}.eq(owner_id))
        .count()
        .get_result(&mut *db)
        .await?;
    let items: Vec<{pascal_name}> = {plural}::table
        .filter({plural}::{owner_col}.eq(owner_id))
        .select({pascal_name}::as_select())
        .limit(page_req.limit())
        .offset(page_req.offset())
        .load(&mut *db)
        .await?;
    let page_data: Page<{pascal_name}> = Page::new(items, total, &page_req);
{index_label_loads}{index_columns_labeled}    Ok({layout_fn}("{pascal_name} index", {cp_index}{flash_arg}, html! {{
        h1 {{ "{pascal_name}s" }}
        (autumn_web::a11y::Link::new("/{plural}/new", "New {pascal_name}"))
        {list_render}
        (pagination_nav(&page_data, &PagerOptions::new("/{plural}")))
    }}))
}}"#
        )
    } else if sharded {
        if live {
            format!(
                r#"/// `GET /{plural}` — paginated list of {snake_name}s.
///
/// Accepts `?page=N&size=M` query parameters via the [`PageRequest`] extractor.
/// Out-of-range or missing values are clamped silently — list endpoints never
/// return HTTP 400 for bad paging parameters.
#[get("/{plural}")]
pub async fn index(
    page_req: PageRequest,
    db: ShardedDb,
    flash: Flash,
) -> AutumnResult<Markup> {{
    let repo = Pg{pascal_name}Repository::from_shard(&db);
    let page_data: Page<{pascal_name}> = repo.page(&page_req).await?;
    Ok({layout_fn}("{pascal_name} index", {cp_index}{flash_arg}, html! {{
        h1 {{ "{pascal_name}s" }}
        (autumn_web::a11y::Link::new(paths::new(), "New {pascal_name}"))
        {index_list_block}
    }}))
}}"#
            )
        } else {
            format!(
                r#"/// `GET /{plural}` — paginated, sortable, filterable list of {snake_name}s.
///
/// Accepts `?page=N&size=M` paging plus allowlisted `?sort=col&dir=asc|desc`
/// and `?filter[col]=val` params (the [`ListQuery`] extractor). Unknown or
/// malicious sort/filter keys are ignored against the model's column allowlist,
/// so this never 400s and can never inject SQL. `from_shard` keeps the query
/// pinned to a single shard.
#[get("/{plural}")]
pub async fn index(
    list_query: ListQuery,
    RawQuery(raw_query): RawQuery,
    page_req: PageRequest,
    {sharded_index_db},
    flash: Flash,
) -> AutumnResult<Markup> {{
    let repo = Pg{pascal_name}Repository::from_shard(&db);
    let page_data: Page<{pascal_name}> = repo.list(&list_query, &page_req).await?;
    let pager_query = raw_query.as_deref().unwrap_or("");
{index_label_loads}{index_columns_labeled}    Ok({layout_fn}("{pascal_name} index", {cp_index}{flash_arg}, html! {{
        h1 {{ "{pascal_name}s" }}
        (autumn_web::a11y::Link::new(paths::new(), "New {pascal_name}"))
        {index_list_block}
    }}))
}}"#
            )
        }
    } else if live {
        format!(
            r#"/// `GET /{plural}` — paginated list of {snake_name}s.
///
/// Accepts `?page=N&size=M` query parameters via the [`PageRequest`] extractor.
/// Out-of-range or missing values are clamped silently — list endpoints never
/// return HTTP 400 for bad paging parameters.
#[get("/{plural}")]
pub async fn index(
    page_req: PageRequest,
    repo: Pg{pascal_name}Repository,
    flash: Flash,
) -> AutumnResult<Markup> {{
    let page_data: Page<{pascal_name}> = repo.page(&page_req).await?;
    Ok({layout_fn}("{pascal_name} index", {cp_index}{flash_arg}, html! {{
        h1 {{ "{pascal_name}s" }}
        (autumn_web::a11y::Link::new(paths::new(), "New {pascal_name}"))
        {index_list_block}
    }}))
}}"#
        )
    } else {
        format!(
            r#"/// `GET /{plural}` — paginated, sortable, filterable list of {snake_name}s.
///
/// Accepts `?page=N&size=M` paging plus allowlisted `?sort=col&dir=asc|desc`
/// and `?filter[col]=val` params (the [`ListQuery`] extractor). Unknown or
/// malicious sort/filter keys are ignored against the model's column allowlist,
/// so this never 400s and can never inject SQL.
#[get("/{plural}")]
pub async fn index(
    list_query: ListQuery,
    RawQuery(raw_query): RawQuery,
    page_req: PageRequest,
    repo: Pg{pascal_name}Repository,
    {index_db_param}flash: Flash,
) -> AutumnResult<Markup> {{
    let page_data: Page<{pascal_name}> = repo.list(&list_query, &page_req).await?;
    let pager_query = raw_query.as_deref().unwrap_or("");
{index_label_loads}{index_columns_labeled}    Ok({layout_fn}("{pascal_name} index", {cp_index}{flash_arg}, html! {{
        h1 {{ "{pascal_name}s" }}
        (autumn_web::a11y::Link::new(paths::new(), "New {pascal_name}"))
        {index_list_block}
    }}))
}}"#
        )
    };

    // #1126: the non-live index handlers extract `ListQuery` (allowlisted
    // sort/filter) and the raw query string (`RawQuery`, to preserve filters on
    // the data_table sort links). The pure `--live` index keeps `repo.page` and
    // needs neither — omit the imports there to avoid unused-import warnings.
    let sort_imports = if live {
        String::new()
    } else {
        "use autumn_web::pagination::ListQuery;\n\
         use autumn_web::reexports::axum::extract::RawQuery;\n"
            .to_owned()
    };

    // Imports: when sharded, drop Db from brace-import and add ShardedDb separately.
    // The stream handler uses the fully-qualified axum path so no extra IntoResponse
    // import is needed.
    let db_import = if sharded {
        "use autumn_web::flash::{Flash, flash_messages};\n\
         use autumn_web::form::{Changeset, IntoChangeset};\n\
         use autumn_web::sharding::ShardedDb;\n\
         use autumn_web::{AutumnError, AutumnResult, Markup, get, html, post, secured};"
            .to_owned()
    } else {
        "use autumn_web::flash::{Flash, flash_messages};\n\
         use autumn_web::form::{Changeset, IntoChangeset};\n\
         use autumn_web::{AutumnError, AutumnResult, Db, Markup, get, html, post, secured};"
            .to_owned()
    };

    // Schema imports: the resource's own table, plus each referenced table so
    // its rows can be loaded — for the form select options AND for the
    // index/show parent-display label loads (issue #1146), which is why this
    // uses the display-scoped set (populated even in `--live-validation`, where
    // the form select is skipped but the display loads remain). Only present
    // targets reach here (`missing_reference_targets` excluded): importing a
    // table whose `diesel::table!` entry doesn't exist would fail to compile,
    // and a missing target has always been a warning, not an error.
    let schema_import = {
        let mut extra_tables: BTreeSet<String> = display_reference_fields
            .iter()
            .filter_map(|f| f.reference_table())
            .collect();
        extra_tables.remove(plural);
        if extra_tables.is_empty() {
            plural.to_owned()
        } else {
            let mut list = plural.to_owned();
            for table in extra_tables {
                let _ = write!(list, ", {table}");
            }
            format!("{{{list}}}")
        }
    };

    // When `--live-validation`, emit one inline-validation handler per validated
    // field. Each handler decodes the *whole* submitted form (htmx's
    // `hx-include="closest form"` posts every field, not just the one that
    // changed) via the same `decode_form` used by `create`/`update`, builds a
    // `Changeset<{pascal_name}Form>` through the struct's derived
    // `#[validate(...)]` rules, and returns `text_input_htmx`'s full field
    // wrapper (label + input + inline error) for that one field. Sharing the
    // changeset/validator machinery with `create`/`update` means there is only
    // one place the validation rules live, and the returned markup matches
    // `text_input_htmx`'s `hx-swap="outerHTML"` contract — swapping in a bare
    // `<span>` would delete the input it's supposed to replace.
    let validate_handlers = if live_validation {
        let mut vh = String::new();
        for (field_name, rules) in validations {
            let rule_comment = rules.join(", ");
            let label = humanize_label(field_name);
            let field = fields.iter().find(|f| f.name == *field_name);
            // Issue #1750: a DSL-constrained `String`/`Text` field renders in
            // the form through the raw-markup constrained control (carrying the
            // #1388 HTML5 attributes `minlength`/`maxlength`/`type="email"`), so
            // its inline-validation fragment must return the SAME markup —
            // otherwise the htmx `outerHTML` swap on the first `change` would
            // shed those client-side guards. The swapped-in field re-wires its
            // own htmx trigger from the identical `validate_url`.
            let constrained = field.and_then(|f| {
                html5_constraint_spec(f).and_then(|(input_type, _attrs)| {
                    // Numerics don't take the htmx path (no wrapper to swap), so
                    // only the text-family constrained controls need a fragment.
                    matches!(f.kind, FieldKind::String | FieldKind::Text).then_some((f, input_type))
                })
            });
            let _ = write!(
                vh,
                "\n\n/// `POST /{plural}/validate/{field_name}` — inline validation fragment.\n"
            );
            let _ = writeln!(
                vh,
                "///\n/// Decodes the full submitted form, validates it against the `{rule_comment}`\n\
                 /// rule declared on `{pascal_name}Form`, and returns the `{field_name}` field's\n\
                 /// wrapper (input + inline error) for htmx's `hx-swap=\"outerHTML\"` on\n\
                 /// `hx-trigger=\"change\"` to swap in place."
            );
            let _ = writeln!(vh, "#[post(\"/{plural}/validate/{field_name}\")]");
            let _ = writeln!(
                vh,
                "pub async fn validate_{field_name}(body: autumn_web::reexports::axum::body::Bytes) -> autumn_web::Markup {{"
            );
            vh.push_str("    let Ok(form) = decode_form(body) else {\n");
            vh.push_str("        return autumn_web::html! {};\n");
            vh.push_str("    };\n");
            vh.push_str("    let changeset = form.into_changeset();\n");
            if let Some((f, input_type)) = constrained {
                // The validate endpoint URL is emitted as a typed path-helper
                // call expression (issue #1133), spliced into `.hx("post", …)`.
                let url = format!("paths::validate_{field_name}()");
                let markup = render_live_constrained_field(f, "changeset", input_type, Some(&url));
                let _ = writeln!(vh, "    autumn_web::html! {{\n        {markup}\n    }}");
            } else {
                // Match `render_changeset_form_inputs`'s helper choice: a
                // non-nullable field keeps `required`/`aria-required` through the
                // htmx round-trip too, otherwise the attribute would vanish from
                // the DOM the moment the field's wrapper gets swapped in.
                let helper = if field.is_some_and(|f| f.nullable) {
                    "text_input_htmx"
                } else {
                    "required_text_input_htmx"
                };
                let _ = writeln!(
                    vh,
                    "    autumn_web::form::{helper}(&changeset, \"{field_name}\", \"{label}\", &paths::validate_{field_name}())"
                );
            }
            vh.push_str("}\n");
        }
        vh
    } else {
        String::new()
    };

    // Issue #1133: emit an `autumn_web::paths![…]` invocation so the routes
    // module gains a `pub mod paths` re-exporting each handler's typed
    // `__autumn_path_*` companion under a clean short name. Every view href,
    // form action, and redirect above calls into this module (e.g.
    // `paths::show(id)`), so the resource's URLs have a single source of truth:
    // the route-macro path strings. `new_form`/`edit_form`/`destroy` carry
    // `name = "new"|"edit"|"delete"` overrides so their helpers read
    // `paths::new()`/`paths::edit(id)`/`paths::delete(id)`.
    let paths_macro = {
        let mut names: Vec<String> = vec![
            "index".to_owned(),
            "show".to_owned(),
            "new".to_owned(),
            "create".to_owned(),
            "edit".to_owned(),
            "update".to_owned(),
            "delete".to_owned(),
        ];
        if live {
            names.push("events".to_owned());
        }
        // One inline-validation endpoint per validated field (live-validation
        // only), each linked from the form's `.hx("post", paths::validate_{f}())`.
        if live_validation {
            for field_name in validations.keys() {
                names.push(format!("validate_{field_name}"));
            }
        }
        // Issue #1326: one transition endpoint per state-machine field, linked
        // from the show page's `transition_controls` form actions
        // (`paths::transition_{field}(id)`).
        for f in &sm_fields {
            let field = &f.name;
            names.push(format!("transition_{field}"));
        }
        let mut out = String::from("\n\nautumn_web::paths![\n");
        for name in &names {
            let _ = writeln!(out, "    {name},");
        }
        out.push_str("];\n");
        out
    };

    // Issue #1319: the FTS results handler backing the index `active_search`
    // box. For htmx requests it returns just the results fragment (swapped into
    // `#{plural}-search-results`); for a plain navigation — a bookmarked search
    // URL, or a shared pager link — it returns the full page so search degrades
    // gracefully without JavaScript. An empty `q` falls back to the standard
    // `page(&page_req)` listing (AC3). Reuses the same `columns` and
    // reference-label loads the index builds so search rows render identically.
    // The pager preserves the request's raw query string (stripping `page`/
    // `size`) via `PagerOptions::query`, so `q` survives pagination without any
    // hand-rolled percent-encoding.
    let search_handler = if search_enabled && owner_scoped_standard {
        // Issue #1841: owner-scoped FTS handler for the standard Db path. The
        // SECURITY INVARIANT is that this branch calls ONLY the owner-filtered
        // repository methods — `repo.search_page_scoped(owner_id, ..)` for a
        // query, and `repo.list_scoped(owner_id, ..)` for the empty-query
        // fallback — NEVER the unscoped `repo.search_page`/`repo.page`, so the
        // `/search` endpoint can never surface another user's rows (the exact
        // leak the pre-#1841 rejection guarded against). `owner_id` comes from
        // the same `PolicyContext` the mutating handlers authorize against.
        let field_list = searchable.join(", ");
        format!(
            r#"

/// `GET /{plural}/search` — owner-scoped full-text search over {field_list}.
///
/// Powers the `active_search` box on the index list. Ranked by relevance via
/// the repository's owner-scoped `search_page_scoped`; an empty `q` falls back
/// to the owner-scoped `list_scoped` listing. htmx requests get only the
/// results fragment; non-htmx navigations (a bookmarked search URL, or a pager
/// link) get a full page so search still works without JavaScript. Every result
/// is filtered to the authenticated user (owner column `{owner_col}`); this
/// handler never calls the unscoped `search_page`/`page`.
#[derive(serde::Deserialize)]
pub struct {pascal_name}SearchQuery {{
    #[serde(default)]
    pub q: String,
}}

#[secured]
#[get("/{plural}/search")]
pub async fn search(
    autumn_web::extract::Query(query): autumn_web::extract::Query<{pascal_name}SearchQuery>,
    autumn_web::reexports::axum::extract::RawQuery(raw_query): autumn_web::reexports::axum::extract::RawQuery,
    list_query: ListQuery,
    page_req: PageRequest,
    hx: autumn_web::htmx::HxRequest,
    autumn_web::extract::State(state): autumn_web::extract::State<autumn_web::AppState>,
    session: autumn_web::session::Session,
    repo: Pg{pascal_name}Repository,
    {index_db_param}flash: Flash,
) -> AutumnResult<Markup> {{
    let ctx = autumn_web::authorization::PolicyContext::from_request(&state, &session).await;
    let owner_id = ctx.user_id_i64().unwrap_or(-1);
    let q = query.q.trim();
    // Preserve the request's raw query string (already percent-encoded) on pager
    // links so `q` survives pagination; `PagerOptions::query` strips the stale
    // `page`/`size` params and re-adds them per link.
    let pager_query = raw_query.as_deref().unwrap_or("");
    let page_data: Page<{pascal_name}> = if q.is_empty() {{
        repo.list_scoped(owner_id, &list_query, &page_req).await?
    }} else {{
        repo.search_page_scoped(owner_id, q, &page_req).await?
    }};
{index_label_loads}{index_columns_labeled}    let results = html! {{
        (autumn_web::widgets::data_table(&page_data.content, &columns, &autumn_web::widgets::DataTableConfig::new("No {plural} found.").base_path("/{plural}/search")))
        (pagination_nav(&page_data, &PagerOptions::new("/{plural}/search").query(pager_query)))
    }};
    if hx.is_htmx {{
        return Ok(results);
    }}
    Ok({layout_fn}("Search {pascal_name}s", {cp_index}{flash_arg}, html! {{
        h1 {{ "Search {pascal_name}s" }}
        a href="/{plural}" {{ "Back to list" }}
        div id="{plural}-search-results" {{ (results) }}
    }}))
}}"#
        )
    } else if search_enabled {
        let field_list = searchable.join(", ");
        let (repo_extractor, repo_bind) = if sharded {
            (
                format!("    {sharded_index_db},\n"),
                format!("    let repo = Pg{pascal_name}Repository::from_shard(&db);\n"),
            )
        } else {
            (
                format!("    repo: Pg{pascal_name}Repository,\n    {index_db_param}"),
                String::new(),
            )
        };
        format!(
            r#"

/// `GET /{plural}/search` — full-text search over {field_list}.
///
/// Powers the `active_search` box on the index list. Ranked by relevance via
/// the repository's `search_page`; an empty `q` falls back to the plain
/// `page(&page_req)` listing. htmx requests get only the results fragment;
/// non-htmx navigations (a bookmarked search URL, or a pager link) get a full
/// page so search still works without JavaScript.
#[derive(serde::Deserialize)]
pub struct {pascal_name}SearchQuery {{
    #[serde(default)]
    pub q: String,
}}

#[get("/{plural}/search")]
pub async fn search(
    autumn_web::extract::Query(query): autumn_web::extract::Query<{pascal_name}SearchQuery>,
    autumn_web::reexports::axum::extract::RawQuery(raw_query): autumn_web::reexports::axum::extract::RawQuery,
    page_req: PageRequest,
    hx: autumn_web::htmx::HxRequest,
{repo_extractor}    flash: Flash,
) -> AutumnResult<Markup> {{
{repo_bind}    let q = query.q.trim();
    // Preserve the request's raw query string (already percent-encoded) on pager
    // links so `q` survives pagination; `PagerOptions::query` strips the stale
    // `page`/`size` params and re-adds them per link.
    let pager_query = raw_query.as_deref().unwrap_or("");
    let page_data: Page<{pascal_name}> = if q.is_empty() {{
        repo.page(&page_req).await?
    }} else {{
        repo.search_page(q, &page_req).await?
    }};
{index_label_loads}{index_columns_labeled}    let results = html! {{
        (autumn_web::widgets::data_table(&page_data.content, &columns, &autumn_web::widgets::DataTableConfig::new("No {plural} found.").base_path("/{plural}/search")))
        (pagination_nav(&page_data, &PagerOptions::new("/{plural}/search").query(pager_query)))
    }};
    if hx.is_htmx {{
        return Ok(results);
    }}
    Ok({layout_fn}("Search {pascal_name}s", {cp_index}{flash_arg}, html! {{
        h1 {{ "Search {pascal_name}s" }}
        (autumn_web::a11y::Link::new("/{plural}", "Back to list"))
        div id="{plural}-search-results" {{ (results) }}
    }}))
}}"#
        )
    } else {
        String::new()
    };

    format!(
        r"//! Generated by `autumn generate scaffold`.
//!
//! HTML route handlers for the resource. Edit freely — once generated,
//! these are ordinary user code.
{attachment_note}
use autumn_web::extract::Path;
use autumn_web::pagination::{{Page, PageRequest}};
{sort_imports}use autumn_web::reexports::axum::body::Bytes;
use autumn_web::reexports::serde_json;
use autumn_web::security::{{CsrfFormField, CsrfToken, SubmitFormField, SubmitToken}};
use autumn_web::ui::pagination::{{PagerOptions, pagination_nav}};
{db_import}
use diesel::prelude::*;
use diesel_async::RunQueryDsl;

use crate::models::{snake_name}::{{{pascal_name}, New{pascal_name}, Update{pascal_name}{enum_import_suffix}}};
use crate::repositories::{snake_name}::{{{pascal_name}Repository, Pg{pascal_name}Repository}};
use crate::schema::{schema_import};",
        attachment_note = if has_attachments {
            "//!\n\
             //! This scaffold includes file-attachment fields. Uploads work with ZERO\n\
             //! JavaScript: the generated `<form>` sets `enctype=\"multipart/form-data\"`,\n\
             //! and the `create`/`update` handlers accept an `autumn_web::extract::Multipart`\n\
             //! body, stream each file part straight to the configured blob store with\n\
             //! `MultipartField::save_to_blob_store` (which enforces\n\
             //! `security.upload.max_file_size_bytes`, default 16 MiB), and persist the\n\
             //! resulting `Blob` on the record. An edit that doesn't re-upload preserves\n\
             //! the existing attachment.\n\
             //!\n\
             //! SIZE CEILING with CSRF on (the prod-profile default): the CSRF middleware\n\
             //! buffers the request body only up to ~2 MiB while scanning for the form\n\
             //! token, so a zero-JS multipart upload larger than ~2 MiB is rejected with\n\
             //! 403 (token not found in the truncated body) BEFORE the handler's\n\
             //! `max_file_size_bytes`/413 check can run. For files above that ceiling, use\n\
             //! the advanced presigned direct-upload path below (it doesn't route the file\n\
             //! bytes through the CSRF-scanned form body).\n\
             //!\n\
             //! The `storage` + `multipart` features are enabled on `autumn-web`\n\
             //! automatically; configure `[storage]` in `autumn.toml` (local disk for dev,\n\
             //! S3 for prod).\n\
             //!\n\
             //! ADVANCED (opt-in): for very large files you can bypass the app process with\n\
             //! presigned direct-to-storage uploads — a CSRF-protected endpoint calls\n\
             //! `store.presign_put()`, the browser PUTs directly to storage, then\n\
             //! `autumn_web::storage::complete_direct_upload()` confirms the object (see the\n\
             //! `direct_upload_input` form helper and the `examples/reddit-clone` app). That\n\
             //! path requires JavaScript; the default multipart path above does not."
        } else {
            ""
        },
    ) + &{
        // Issue #1130: standard scaffolds render through the app's shared
        // `crate::layout`, so no private layout is emitted here. Live and
        // live-validation views keep a local `layout` because they need extra
        // `<head>` scripts (SSE/idiomorph) and a morph-enabled `<body>` the
        // shared 4-arg shell can't express.
        let private_layout = if shared_layout {
            String::new()
        } else {
            // Load htmx + SSE extension whenever live features are active.
            // `--live-validation` alone (without `--live`) still requires htmx
            // for the `hx-post` / `hx-trigger` / `hx-swap` attributes to fire.
            let live_head_scripts = if live {
                "\n                script src=(autumn_web::htmx::HTMX_JS_PATH) {};\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20script src=(autumn_web::htmx::HTMX_SSE_JS_PATH) {};\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20script src=(autumn_web::htmx::IDIOMORPH_JS_PATH) {};"
                    .to_owned()
            } else {
                "\n                script src=(autumn_web::htmx::HTMX_JS_PATH) {};\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20script src=(autumn_web::htmx::HTMX_SSE_JS_PATH) {};"
                    .to_owned()
            };
            let live_body_open = if live {
                r#"body hx-ext="morph""#
            } else {
                "body"
            };
            format!(
                r#"
/// Wrap content in a minimal HTML layout for the live view (needs extra
/// `<head>` scripts and a morph-enabled `<body>` the shared layout omits).
///
/// Pass `flash_messages(&flash.consume().await)` for the `flash` argument so
/// one-shot notices (set with `flash.success(...)` before a redirect) appear
/// on the next page.
fn layout(title: &str, flash: Markup, content: Markup) -> Markup {{
    html! {{
        (autumn_web::PreEscaped("<!DOCTYPE html>"))
        html lang="en" {{
            head {{
                meta charset="utf-8";
                title {{ (title) }}
                link rel="stylesheet" href=(autumn_web::flash::FLASH_CSS_PATH);{live_head_scripts}
            }}
            {live_body_open} {{
                (flash)
                (content)
            }}
        }}
    }}
}}
"#
            )
        };
        // Issue #1326: the `show` detail section. Without a state machine this is
        // exactly the pre-#1326 inline `show` handler (byte-identical output).
        // With one or more `:states(…)` fields it becomes a shared `show_view`
        // helper (rendered by `show` AND each transition handler's 422 re-render),
        // a `show` handler threading CSRF for the transition forms, and one
        // `POST /{plural}/{{id}}/transitions/{field}` handler per state-machine
        // field.
        let show_section = if has_state_machine {
            // `show_view` only touches the DB when it must resolve reference
            // display labels (issue #1146); otherwise the connection is unused, so
            // name it `_db` (and drop `mut`) to keep the generated crate
            // warning-free.
            let show_view_db_param = if show_label_loads.trim().is_empty() {
                format!("_db: {db_ty}")
            } else {
                format!("mut db: {db_ty}")
            };
            let mut show_transition_controls = String::new();
            for f in &sm_fields {
                let field = &f.name;
                let field_upper = f.name.to_uppercase();
                let _ = writeln!(
                    show_transition_controls,
                    "        (autumn_web::widgets::transition_controls(&paths::transition_{field}(row.id), \"{field}\", &row.{field}, {pascal_name}::__AUTUMN_SM_{field_upper}_TRANSITIONS, |to| row.can_transition_{field}_to(to), csrf, csrf_field))"
                );
            }
            let show_view_fn = format!(
                r#"/// Render the {snake_name} detail page — shared by the `show` handler and
/// each state-machine transition handler's 422 re-render, so the detail-page
/// markup has a single source of truth (issue #1326).
async fn show_view(
    {show_view_db_param},
    row: &{pascal_name},
    flash: Markup,
    csrf: Option<&CsrfToken>,
    csrf_field: Option<&CsrfFormField>,
) -> AutumnResult<Markup> {{
{show_label_loads}    let props: Vec<(&str, maud::Markup)> = vec![
{show_rows}    ];
    Ok({layout_fn}(&format!("{pascal_name} #{{}}", row.id), {cp_show}flash, html! {{
        h1 {{ "{pascal_name} #" (row.id) }}
        (autumn_web::widgets::property_list(&props))
{show_transition_controls}        (autumn_web::a11y::Link::new(paths::index(), "Back to list"))
        " "
        (autumn_web::a11y::Link::new(paths::edit(row.id), "Edit"))
    }}))
}}"#
            );
            let show_handler = format!(
                r#"/// `GET /{plural}/{{id}}` — show one {snake_name}.
#[get("/{plural}/{{id}}")]
pub async fn show(
    id: Path<{id_rust}>,
    mut db: {db_ty},
    flash: Flash,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
) -> AutumnResult<Markup> {{
    let row: {pascal_name} = {plural}::table
        .find(*id)
        .select({pascal_name}::as_select())
        .first(&mut *db)
        .await
        .map_err(AutumnError::not_found)?;
    show_view(db, &row, {flash_arg}, csrf.as_ref(), csrf_field.as_ref()).await
}}"#
            );
            // Issue #1326 security fix (IDOR): a transition mutates an existing
            // row, so when record-policy wiring is on (the default for non-`--api`
            // scaffolds) the transition handler must record-authorize the actor
            // against the loaded row *before* writing — using the SAME `"update"`
            // action the `update` handler uses. Without this, any authenticated
            // user who knows another row's id could POST a transition and change
            // its state, bypassing the record policy. Mirrors the `update`/`destroy`
            // authorize preamble: the full `State(state)` + `session: Session`
            // extractor pair (a transition handler never carries a multipart
            // `state`, so there is no attachment-reuse concern) and `&state` as the
            // `AppState` receiver. When policy wiring is off it emits nothing, so
            // the handler is exactly `id/db/flash/csrf/body` as before.
            let transition_authz_params = if authorize {
                "    autumn_web::extract::State(state): autumn_web::extract::State<autumn_web::AppState>,\n    session: autumn_web::session::Session,\n"
            } else {
                ""
            };
            let transition_authz_call = if authorize {
                format!(
                    "    autumn_web::authorization::authorize::<{pascal_name}>(&state, &session, \"update\", &row).await?;\n"
                )
            } else {
                String::new()
            };
            let mut transition_handlers = String::new();
            for f in &sm_fields {
                let field = &f.name;
                let handler = format!(
                    r#"/// `POST /{plural}/{{id}}/transitions/{field}` — apply a `{field}` state
/// transition (issue #1326). A legal edge persists the new `{field}` value and
/// redirects to the detail page; an illegal edge (or a rejected guard)
/// re-renders that page at 422 with the record left unchanged.
#[secured]
#[post("/{plural}/{{id}}/transitions/{field}")]
pub async fn transition_{field}(
    id: Path<{id_rust}>,
    mut db: {db_ty},
    flash: Flash,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
{transition_authz_params}    body: Bytes,
) -> AutumnResult<autumn_web::reexports::axum::response::Response> {{
    use autumn_web::reexports::axum::response::IntoResponse as _;
    let row: {pascal_name} = {plural}::table
        .find(*id)
        .select({pascal_name}::as_select())
        .first(&mut *db)
        .await
        .map_err(AutumnError::not_found)?;
{transition_authz_call}    let submitted: std::collections::HashMap<String, String> =
        url::form_urlencoded::parse(body.as_ref()).into_owned().collect();
    let target = submitted.get("{field}").cloned().unwrap_or_default();
    match row.transition_{field}_to(&target) {{
        Ok(new_state) => {{
            diesel::update({plural}::table.find(*id))
                .set({plural}::{field}.eq(new_state))
                .execute(&mut *db)
                .await?;
            flash.success("{pascal_name} {field} updated").await;
            Ok(autumn_web::Redirect::to(&paths::show(*id)).into_response())
        }}
        Err(err) => {{
            flash.error(err.to_string()).await;
            let view = show_view(
                db,
                &row,
                flash_messages(&flash.consume().await),
                csrf.as_ref(),
                csrf_field.as_ref(),
            )
            .await?;
            Ok((autumn_web::reexports::http::StatusCode::UNPROCESSABLE_ENTITY, view).into_response())
        }}
    }}
}}"#
                );
                if !transition_handlers.is_empty() {
                    transition_handlers.push_str("\n\n");
                }
                transition_handlers.push_str(&handler);
            }
            format!("\n\n{show_view_fn}\n\n{show_handler}\n\n{transition_handlers}\n")
        } else {
            format!(
                r#"

/// `GET /{plural}/{{id}}` — show one {snake_name}.
#[get("/{plural}/{{id}}")]
pub async fn show(id: Path<{id_rust}>, mut db: {db_ty}, flash: Flash) -> AutumnResult<Markup> {{
    let row: {pascal_name} = {plural}::table
        .find(*id)
        .select({pascal_name}::as_select())
        .first(&mut *db)
        .await
        .map_err(AutumnError::not_found)?;
{show_label_loads}    let props: Vec<(&str, maud::Markup)> = vec![
{show_rows}    ];
    Ok({layout_fn}(&format!("{pascal_name} #{{}}", row.id), {cp_show}{flash_arg}, html! {{
        h1 {{ "{pascal_name} #" (row.id) }}
        (autumn_web::widgets::property_list(&props))
        (autumn_web::a11y::Link::new(paths::index(), "Back to list"))
        " "
        (autumn_web::a11y::Link::new(paths::edit(row.id), "Edit"))
    }}))
}}
"#
            )
        };
        format!(
            r#"

fn csrf_input(csrf: Option<&CsrfToken>, field: Option<&CsrfFormField>) -> Markup {{
    let csrf_field_name = field.map(|field| field.0.as_str()).unwrap_or("_csrf");
    html! {{
        @if let Some(csrf) = csrf {{
            input type="hidden" name=(csrf_field_name) value=(csrf.token());
        }}
    }}
}}

/// Emit the hidden one-time submit-token field (issue #1360). Consumed once by
/// the framework's `SubmitTokenLayer`, so a double-click or Back→resubmit
/// replays the first response instead of creating a duplicate row. The field
/// name follows `security.submit_token.field_name` (default `_submit_token`) so
/// a customised name still matches what the layer scans for.
fn submit_token_input(submit_token: Option<&SubmitToken>, field: Option<&SubmitFormField>) -> Markup {{
    let submit_field_name = field.map(|field| field.0.as_str()).unwrap_or("_submit_token");
    html! {{
        @if let Some(submit_token) = submit_token {{
            input type="hidden" name=(submit_field_name) value=(submit_token.token());
        }}
    }}
}}
{private_layout}
{index_handler}{show_section}
/// `GET /{plural}/new` — render the new-{snake_name} form.
#[secured]
#[get("/{plural}/new", name = "new")]
pub async fn new_form(
    {new_form_db_param}flash: Flash,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
    submit_token: Option<SubmitToken>,
    submit_field: Option<SubmitFormField>,
) -> AutumnResult<Markup> {{
    let changeset = Changeset::new({pascal_name}Form::default());
    Ok({new_form_body})
}}

{unique_constraints_const}{create_fn}
/// `GET /{plural}/{{id}}/edit` — render the edit form. Submission goes to
/// the `update` handler below as a plain HTML POST (browsers can't submit
/// PUT directly without JS); the auto-generated JSON `PUT /api/{plural}/{{id}}`
/// remains available for API clients.
#[secured]
#[get("/{plural}/{{id}}/edit", name = "edit")]
pub async fn edit_form(
    id: Path<{id_rust}>,
    mut db: {db_ty},
    flash: Flash,
    csrf: Option<CsrfToken>,
    csrf_field: Option<CsrfFormField>,
    submit_token: Option<SubmitToken>,
    submit_field: Option<SubmitFormField>,{edit_destroy_authz_params}
) -> AutumnResult<Markup> {{
    let row: {pascal_name} = {plural}::table
        .find(*id)
        .select({pascal_name}::as_select())
        .first(&mut *db)
        .await
        .map_err(AutumnError::not_found)?;
    {authz_edit_call}let changeset = Changeset::new({pascal_name}Form::from(&row));
    Ok({edit_form_body})
}}

{update_fn}
/// `POST /{plural}/{{id}}/delete` — delete a row, then redirect to the list.
/// Browsers can't submit `DELETE` without JS, so the show page's delete button
/// posts here; the JSON `DELETE /api/{plural}/{{id}}` stays available for API
/// clients via the auto-generated repository handler. Honours the resource's
/// soft-delete configuration (marks `deleted_at` when `--soft-delete` is set).
#[secured]
#[post("/{plural}/{{id}}/delete", name = "delete")]
pub async fn destroy(
    id: Path<{id_rust}>,
    {destroy_signature_arg},
    flash: Flash,
) -> AutumnResult<autumn_web::Redirect> {{
    {authz_destroy_preamble}{destroy_stmt}
    if deleted == 0 {{
        return Err(AutumnError::not_found_msg(format!(
            "{pascal_name} with id {{}} not found", *id
        )));
    }}
    flash.success("{pascal_name} deleted").await;
    Ok(autumn_web::Redirect::to(&paths::index()))
}}

{form_struct}
{parse_datetime_helper}
{into_new_fn}

{from_row_impl}

{form_model_impl}

{form_for_helper}{decode_form_sig} {{
    let pairs: Vec<_> = url::form_urlencoded::parse(body.as_ref())
        .filter(|(key, value)| !(value.is_empty() && is_nullable_form_field(key)))
        .collect();
    let encoded = url::form_urlencoded::Serializer::new(String::new())
        .extend_pairs(pairs.iter().map(|(key, value)| (key.as_ref(), value.as_ref())))
        .finish();

    let form: {pascal_name}Form = serde_urlencoded::from_str(&encoded)
        .map_err(|err| AutumnError::bad_request_msg(format!("invalid form submission: {{err}}")))?;

    Ok(form)
}}

fn is_nullable_form_field(name: &str) -> bool {{
    {nullable_field_match}
}}
"#
        )
    } + &if live {
        format!(
            r#"

/// `GET /{plural}/events` — Server-Sent Events stream for live updates.
#[get("/{plural}/events")]
pub async fn events(
    state: autumn_web::extract::State<autumn_web::AppState>,
) -> impl autumn_web::reexports::axum::response::IntoResponse {{
    autumn_web::sse::stream(&state, "{plural}")
}}"#
        )
    } else {
        String::new()
    } + &validate_handlers
        + &paths_macro
        + &search_handler
}

/// The `UNIQUE_CONSTRAINTS` module-level const the generated `create`/
/// `update` handlers pass to `autumn_web::error::unique_violation_field`
/// (issue #1032) — one `(constraint_name, field_name, message)` triple per
/// `unique` field, where `constraint_name` matches the name
/// `schema_edit::unique_index_sql` gives the migration's `CREATE UNIQUE
/// INDEX` (`idx_<table>_<field>_unique`).
fn render_unique_constraints_const(
    plural: &str,
    unique_fields: &[&Field],
    all_fields: &[Field],
) -> String {
    use std::fmt::Write as _;
    let mut entries = String::new();
    for f in unique_fields {
        let index_name = unique_index_name(plural, &f.name, all_fields);
        let _ = write!(
            entries,
            "(\"{index_name}\", \"{name}\", \"has already been taken\"),\n    ",
            name = f.name
        );
    }
    format!("const UNIQUE_CONSTRAINTS: &[(&str, &str, &str)] = &[\n    {entries}];\n")
}

fn render_update_changeset_expr(pascal_name: &str, fields: &[Field]) -> String {
    use std::fmt::Write;
    let mut out = format!("Update{pascal_name} {{\n");
    for f in fields {
        let name = &f.name;
        writeln!(
            out,
            "        {name}: autumn_web::hooks::Patch::Set(new.{name}.clone()),"
        )
        .unwrap();
    }
    out.push_str("    }");
    out
}

/// Whether any field in `fields` is a file attachment.
fn has_attachment_fields(fields: &[Field]) -> bool {
    fields.iter().any(|f| f.kind.is_attachment())
}

/// Emit the `FormModel` delegation impl for the generated `{Pascal}Form`
/// (issue #1135). `form_for` derives its controls from the changeset's own
/// type, and the `#[model]` derive already produces the field descriptors on
/// `{Pascal}` — same field names, same declaration order, and both exclude
/// the primary key and `#[default]` columns — so the form struct simply
/// reuses the model's list instead of restating it.
fn render_form_model_impl(pascal_name: &str) -> String {
    format!(
        "/// `form_for` field descriptors (issue #1135): delegate to the\n\
         /// `#[model]`-derived implementation on `{pascal_name}` so the rendered form\n\
         /// always tracks the model's columns.\n\
         impl autumn_web::form::FormModel for {pascal_name}Form {{\n    \
         fn form_fields() -> Vec<autumn_web::form::FormField> {{\n        \
         <{pascal_name} as autumn_web::form::FormModel>::form_fields()\n    \
         }}\n\
         }}"
    )
}

/// Render the shared `{snake}_form_for` helper the generated views call
/// (issue #1135): one `form_for` call renders the open `<form>` tag, the CSRF
/// hidden input, one type-appropriate control per `FormModel` field (with
/// pre-filled values and inline errors from the changeset), and the submit
/// button — so `new_form`, `edit_form`, and both 422 re-render branches carry
/// zero per-column view code, and adding a model column requires no view
/// edits.
///
/// The scaffold layers on only what the derive can't know statically:
/// - enum columns are promoted to a `Select` with one option per declared
///   variant plus a blank placeholder (the derive sees an opaque Rust enum
///   type and falls back to a text control);
/// - decimal columns pin the browser `step` to the column's declared scale
///   (the derive emits a free `step="any"`, losing the column's actual
///   smallest representable increment);
/// - attachment columns are excluded from the derived list and re-appended
///   as a hand-rolled file input plus a hidden input carrying the existing
///   blob key — a file input can't be repopulated, and `FieldControl::File`
///   would flip the form to `multipart/form-data` while scaffold forms stay
///   URL-encoded (uploads go through direct-upload URLs; see
///   docs/guide/storage.md#direct-uploads). The appended markup renders the
///   same inline-error/ARIA skeleton as the derived controls, so changeset
///   errors on the attachment key still surface;
/// - `references` columns are promoted to a `Select` over the referenced
///   table's ids (issue #1135 AC 2). The options are runtime data, so the
///   helper takes one `{column}_options: &[(String, String)]` parameter per
///   reference and the calling handlers load them (see the generated
///   `{column}_select_options` loader). Columns named in
///   `missing_reference_targets` (their referenced model isn't in the
///   project, so there is no schema entry to load options from) keep the
///   derived numeric id input instead — the plan carries a warning saying
///   how to get the select.
#[allow(
    clippy::too_many_lines,
    reason = "one per-field match building the form_for builder calls plus the \
              constrained-field/attachment append markup — a single cohesive template"
)]
fn render_form_for_helper(
    pascal_name: &str,
    snake_name: &str,
    fields: &[Field],
    missing_reference_targets: &BTreeSet<String>,
) -> String {
    use std::fmt::Write as _;
    let mut extra_params = String::new();
    let mut preludes = String::new();
    let mut builder_calls = String::new();
    let mut appends = String::new();
    for f in fields {
        let name = &f.name;
        match f.kind {
            FieldKind::Attachment => {
                // Issue #1236: promote the attachment to `FieldControl::File`.
                // The derive sees an opaque `Blob` column and falls back to a
                // text control, so override it. `FieldControl::File` (a) flips
                // the whole `<form>` to `enctype="multipart/form-data"` so the
                // browser uploads the file with zero JavaScript, (b) renders a
                // plain `<input type="file">` (no hidden key input — uploads no
                // longer round-trip a presign key), and (c) renders the same
                // inline-error/ARIA skeleton as the other controls, so changeset
                // errors on the attachment still surface.
                let _ = write!(
                    builder_calls,
                    "\n        .override_field(\"{name}\", autumn_web::form::FieldControl::File)"
                );
            }
            FieldKind::Enum => {
                let placeholder = if f.nullable {
                    "— Unset —"
                } else {
                    "— Select —"
                };
                let mut options = format!("(\"\".into(), \"{placeholder}\".into())");
                for v in &f.variants {
                    let vlabel = humanize_label(v);
                    let _ = write!(options, ", (\"{v}\".into(), \"{vlabel}\".into())");
                }
                let _ = write!(
                    builder_calls,
                    "\n        .override_field(\"{name}\", autumn_web::form::FieldControl::Select {{ options: vec![{options}] }})"
                );
            }
            FieldKind::Decimal { scale, .. } => {
                let step = decimal_step(scale);
                let _ = write!(
                    builder_calls,
                    "\n        .override_field(\"{name}\", autumn_web::form::FieldControl::Number {{ step: Some(\"{step}\".into()) }})"
                );
            }
            FieldKind::References => {
                // The derive sees a plain `i64` column and emits a number
                // input; the reference renders as a select over the
                // referenced table's ids instead. A blank first option gives
                // required selects browser-native "please select" behavior
                // (nullable references use it to unset the value). When the
                // referenced model is missing from the project the select's
                // option loader could not compile (no schema entry to query),
                // so the column keeps the derived number input.
                if missing_reference_targets.contains(name) {
                    continue;
                }
                let placeholder = if f.nullable {
                    "— Unset —"
                } else {
                    "— Select —"
                };
                let _ = write!(extra_params, ",\n    {name}_options: &[(String, String)]");
                let _ = write!(
                    preludes,
                    "    let mut {name}_select = vec![(String::new(), \"{placeholder}\".to_string())];\n    \
                     {name}_select.extend({name}_options.iter().cloned());\n"
                );
                let _ = write!(
                    builder_calls,
                    "\n        .override_field(\"{name}\", autumn_web::form::FieldControl::Select {{ options: {name}_select }})"
                );
            }
            // A `String`/`Text`/numeric field carrying DSL constraint
            // modifiers (issue #1388) needs HTML5 attributes the derived
            // `FieldControl` can't express (`minlength`/`maxlength`,
            // `min`/`max`, `type="email"`/`type="url"`). Exclude it from the
            // derived render and append an equivalent control that carries the
            // constraints — the same `.exclude()` + `.append()` escape hatch
            // the attachment arm uses. The value is re-filled from the
            // changeset so the 422 re-render keeps entered input, and the
            // inline-error/ARIA skeleton matches the derived controls.
            _ => {
                if let Some((input_type, _)) = html5_constraint_spec(f) {
                    let label = humanize_label(name);
                    let _ = write!(builder_calls, "\n        .exclude(\"{name}\")");
                    if matches!(f.kind, FieldKind::Text) && input_type == "text" {
                        // A `text` DSL column with a length/plain constraint is a
                        // long-form field (Postgres `TEXT`), so its control is a
                        // `<textarea>`, not a single-line `<input>` — the same
                        // element the derived `FieldControl::Textarea` would pick.
                        // (A `text{email}`/`text{url}` field has `input_type` ==
                        // `email`/`url`, which a textarea can't carry — those
                        // inherently single-line, type-dependent controls take the
                        // `<input type="…">` branch below instead.)
                        //
                        // Route the constrained multi-line `<textarea>` through the
                        // typed accessible `a11y::TextArea` primitive (#1933): the
                        // rendered element/attributes/values carry over unchanged
                        // (the label now carries `autumn-field__label`), only
                        // TextArea's attribute order differs. Only the attributes a
                        // textarea honours apply — the length rules from
                        // `html5_constraint_builder_calls` (`minlength`/`maxlength`)
                        // and `required`; the input-only `type`/`min`/`max` are
                        // dropped. The 422 re-render value is the element's text
                        // content (not a `value=` attribute) so entered input
                        // survives, matching `form::textarea_input`. The wrapper
                        // `<div>` and inline-error `<div>` skeleton stay raw and
                        // identical to the single-line `<input>` branch below.
                        let constraint_builders = html5_constraint_builder_calls(f)
                            .map(|(_, calls)| calls)
                            .unwrap_or_default();
                        let required_builders = if f.nullable {
                            ""
                        } else {
                            ".required().aria_required()"
                        };
                        let _ = write!(
                            appends,
                            "\n        .append(html! {{\n            \
                             @let errors = changeset.errors_for(\"{name}\");\n            \
                             div id=\"{name}-field\" class=\"autumn-field\" {{\n                \
                             (autumn_web::a11y::TextArea::new(\"{name}\")\n                    \
                             .label(\"{label}\")\n                    \
                             .label_class(\"autumn-field__label\")\n                    \
                             .value(changeset.field_value(\"{name}\").unwrap_or_default())\n                    \
                             {constraint_builders}{required_builders}\n                    \
                             .class(if errors.is_empty() {{ \"autumn-field__input\" }} else {{ \"autumn-field__input autumn-field__input--invalid\" }})\n                    \
                             .aria_invalid(!errors.is_empty())\n                    \
                             .described_by(if errors.is_empty() {{ \"\" }} else {{ \"{name}-error\" }}))\n                \
                             @if !errors.is_empty() {{\n                    \
                             div id=\"{name}-error\" role=\"alert\" class=\"autumn-field__errors\" {{\n                        \
                             @for error in errors {{ p class=\"autumn-field__error\" {{ (error) }} }}\n                    \
                             }}\n                \
                             }}\n            \
                             }}\n        \
                             }})"
                        );
                    } else {
                        // Route the constrained single-line `<input>` through the
                        // typed accessible `a11y::TextField` primitive (#1706): the
                        // rendered element/attributes/values are unchanged (label now
                        // carries `autumn-field__label`), only TextField's attribute
                        // order differs. The wrapper `<div>` and inline-error `<div>`
                        // stay raw. Constraint attrs become typed builder calls from
                        // the same `html5_constraint_parts` source as the raw form.
                        let constraint_builders = html5_constraint_builder_calls(f)
                            .map(|(_, calls)| calls)
                            .unwrap_or_default();
                        let required_builders = if f.nullable {
                            ""
                        } else {
                            ".required().aria_required()"
                        };
                        let _ = write!(
                            appends,
                            "\n        .append(html! {{\n            \
                             @let errors = changeset.errors_for(\"{name}\");\n            \
                             div id=\"{name}-field\" class=\"autumn-field\" {{\n                \
                             (autumn_web::a11y::TextField::new(\"{name}\")\n                    \
                             .label(\"{label}\")\n                    \
                             .label_class(\"autumn-field__label\")\n                    \
                             .input_type(\"{input_type}\")\n                    \
                             .value(changeset.field_value(\"{name}\").unwrap_or_default())\n                    \
                             {constraint_builders}{required_builders}\n                    \
                             .class(if errors.is_empty() {{ \"autumn-field__input\" }} else {{ \"autumn-field__input autumn-field__input--invalid\" }})\n                    \
                             .aria_invalid(!errors.is_empty())\n                    \
                             .described_by(if errors.is_empty() {{ \"\" }} else {{ \"{name}-error\" }}))\n                \
                             @if !errors.is_empty() {{\n                    \
                             div id=\"{name}-error\" role=\"alert\" class=\"autumn-field__errors\" {{\n                        \
                             @for error in errors {{ p class=\"autumn-field__error\" {{ (error) }} }}\n                    \
                             }}\n                \
                             }}\n            \
                             }}\n        \
                             }})"
                        );
                    }
                }
            }
        }
    }
    // Issue #1326: a `:states(…)` state-machine column is transition-only. The
    // create form keeps it (initial state), but the EDIT form must not offer it
    // as an editable input — status changes flow only through the dedicated
    // `POST /{plural}/{{id}}/transitions/{field}` route. The helper is shared by
    // both forms, so it takes an `exclude_state_fields` flag: the edit call
    // passes `true` and the create call `false`. A model with no state-machine
    // field emits neither the parameter nor the block, keeping the pre-#1326
    // helper byte-identical.
    let sm_field_names: Vec<&str> = fields
        .iter()
        .filter(|f| f.state_machine.is_some())
        .map(|f| f.name.as_str())
        .collect();
    let sm_exclude_block = if sm_field_names.is_empty() {
        String::new()
    } else {
        let _ = write!(extra_params, ",\n    exclude_state_fields: bool");
        let mut excludes = String::new();
        for name in &sm_field_names {
            let _ = write!(excludes, "\n        form = form.exclude(\"{name}\");");
        }
        format!("\n    if exclude_state_fields {{{excludes}\n    }}\n    ")
    };
    format!(
        "/// Render the create/edit form in a single `form_for` call (issue #1135).\n\
         ///\n\
         /// Controls, labels, pre-filled values, and inline errors all derive from\n\
         /// `{pascal_name}Form`'s `FormModel` field descriptors, so adding a model\n\
         /// column requires no edits here — any enum/decimal/attachment overrides\n\
         /// below are the only schema-specific lines, and regeneration maintains\n\
         /// them.\n\
         fn {snake_name}_form_for(\n    \
         changeset: &Changeset<{pascal_name}Form>,\n    \
         action: String,\n    \
         submit_label: &str,\n    \
         csrf: Option<&CsrfToken>,\n    \
         csrf_field: Option<&CsrfFormField>,\n    \
         submit_token: Option<&SubmitToken>,\n    \
         submit_field: Option<&SubmitFormField>{extra_params},\n\
         ) -> Markup {{\n\
         {preludes}    \
         let mut form = autumn_web::form::form_for(changeset, action, \"post\")\n        \
         .submit_label(submit_label){builder_calls}{appends};\n{sm_exclude_block}    \
         // Emit the one-time submit token at the FRONT of the form (issue #1360):\n    \
         // `SubmitTokenLayer` only scans the first chunk of the URL-encoded body,\n    \
         // so a large earlier textarea could otherwise push an appended token past\n    \
         // the scan cap and leave duplicate submits unguarded.\n    \
         form = form.prepend(submit_token_input(submit_token, submit_field));\n    \
         if let Some(csrf) = csrf {{\n        \
         form = form.csrf(csrf.token());\n    \
         }}\n    \
         if let Some(field) = csrf_field {{\n        \
         form = form.csrf_field_name(field.0.as_str());\n    \
         }}\n    \
         form.render()\n\
         }}\n\n"
    )
}

/// Render one async `{column}_select_options` loader per `references` column
/// (issue #1135 AC 2: "references→select"). Each loader queries the
/// referenced table's ids and returns them as `(value, label)` pairs for the
/// `Select` override in the shared `{snake}_form_for` helper. Every handler
/// that renders the form (`new_form`, `edit_form`, and the `create`/`update`
/// 422 re-render branches) calls the loaders before rendering.
///
/// Labels are the raw id rendered as a string: which referenced-table column
/// makes a human-friendly label is a display decision the generator can't
/// know, so the generated doc comment tells the author where to swap in a
/// real label column.
fn render_reference_option_loaders(
    reference_fields: &[&Field],
    db_ty: &str,
    reference_displays: &BTreeMap<String, ReferenceDisplay>,
) -> String {
    use std::fmt::Write as _;
    let mut out = String::new();
    for f in reference_fields {
        let name = &f.name;
        let Some(table) = f.reference_table() else {
            continue;
        };
        match reference_displays.get(name) {
            // A display column was resolved (issue #1146): load `(id, label)`
            // pairs so the `<select>` shows a human-friendly value, not the
            // raw id. A nullable display column coalesces to the id string.
            Some(display) => {
                let column = &display.column;
                let (load_ty, label_expr) = if display.column_nullable {
                    ("Option<String>", "label.unwrap_or_else(|| id.to_string())")
                } else {
                    ("String", "label")
                };
                let _ = write!(
                    out,
                    "/// Load the `(value, label)` select options for the `{name}` reference —\n\
                     /// one option per `{table}` row (value = id, label = `{column}`), ordered\n\
                     /// by id (issues #1135, #1146).\n\
                     async fn {name}_select_options(db: &mut {db_ty}) -> AutumnResult<Vec<(String, String)>> {{\n    \
                     let rows: Vec<(i64, {load_ty})> = {table}::table\n        \
                     .select(({table}::id, {table}::{column}))\n        \
                     .order({table}::id.asc())\n        \
                     .load(&mut **db)\n        \
                     .await?;\n    \
                     Ok(rows.into_iter().map(|(id, label)| (id.to_string(), {label_expr})).collect())\n\
                     }}\n\n"
                );
            }
            // No string column to display (or the target model couldn't be
            // parsed): fall back to the id as both value and label.
            None => {
                let _ = write!(
                    out,
                    "/// Load the `(value, label)` select options for the `{name}` reference —\n\
                     /// one option per `{table}` row, ordered by id (issue #1135).\n\
                     ///\n\
                     /// `{table}` has no string column to label options with, so the id is\n\
                     /// used as both value and label — swap the `map` below to use a real\n\
                     /// label column once one exists.\n\
                     async fn {name}_select_options(db: &mut {db_ty}) -> AutumnResult<Vec<(String, String)>> {{\n    \
                     let ids: Vec<i64> = {table}::table\n        \
                     .select({table}::id)\n        \
                     .order({table}::id.asc())\n        \
                     .load(&mut **db)\n        \
                     .await?;\n    \
                     Ok(ids.into_iter().map(|id| (id.to_string(), id.to_string())).collect())\n\
                     }}\n\n"
                );
            }
        }
    }
    out
}

/// How a `references` field's parent row should be *displayed* (issue #1146):
/// the referenced `table`, the `column` whose value labels the parent, and
/// whether that column is nullable (`Option<String>`).
///
/// Resolved from the referenced model at scaffold time via
/// [`resolve_reference_display`] — an explicit `{label:col}` override, else a
/// `name`/`title`/first-string-column heuristic. `None` (no entry) means the
/// target has no string column, so the raw id is rendered as a fallback.
#[derive(Debug, Clone)]
struct ReferenceDisplay {
    column: String,
    column_nullable: bool,
}

/// The `(name, nullable)` string (`String`/`Text`) columns of a `references`
/// field's target (issue #1146). For a **self-reference** (the target table is
/// the model being generated right now) there is no `src/models/<x>.rs` on disk
/// yet, so the columns come from the in-flight `own_fields`; every other target
/// is read from disk via [`super::model::model_string_columns`].
fn target_string_columns(
    project_root: &Path,
    field: &Field,
    self_plural: &str,
    own_fields: &[Field],
) -> Vec<(String, bool)> {
    if field.reference_table().as_deref() == Some(self_plural) {
        own_fields
            .iter()
            .filter(|f| matches!(f.kind, FieldKind::String | FieldKind::Text))
            .map(|f| (f.name.clone(), f.nullable))
            .collect()
    } else {
        let base = field.name.strip_suffix("_id").unwrap_or(&field.name);
        super::model::model_string_columns(project_root, base)
    }
}

/// Resolve the display column for a `references` field against its target
/// model (issue #1146): an explicit `{label:col}` override wins; otherwise a
/// `name`/`title` column is preferred, else the first `String`/`Text` column.
/// Returns `None` when the target model has no string column (render the id).
///
/// A **self-reference** (the target table is the model being generated right
/// now — e.g. `Category category:references`) has no `src/models/<x>.rs` on
/// disk yet, so its display column is resolved from the in-flight `own_fields`
/// (the columns being generated this invocation) rather than the filesystem.
/// References to OTHER models still resolve via the on-disk lookup.
fn resolve_reference_display(
    project_root: &Path,
    field: &Field,
    self_plural: &str,
    own_fields: &[Field],
) -> Option<ReferenceDisplay> {
    let base = field.name.strip_suffix("_id").unwrap_or(&field.name);
    let is_self_ref = field.reference_table().as_deref() == Some(self_plural);
    let columns = target_string_columns(project_root, field, self_plural, own_fields);
    // The `name`/`title`/first-string-column heuristic, reused both when no
    // explicit label is given and when an explicit one has to be discarded.
    let heuristic = || {
        columns
            .iter()
            .find(|(c, _)| c == "name")
            .or_else(|| columns.iter().find(|(c, _)| c == "title"))
            .or_else(|| columns.first())
            .map(|(c, n)| (c.clone(), *n))
    };
    let (column, column_nullable) = if let Some(label) = &field.constraints.label {
        if let Some((c, n)) = columns.iter().find(|(c, _)| c == label) {
            // Explicit override names a real string column on the target — use
            // it, with its known nullability.
            (c.clone(), *n)
        } else if !is_self_ref
            && field
                .reference_table()
                .is_some_and(|table| !super::model::model_file_exists(project_root, &table, base))
        {
            // The target model genuinely isn't discoverable (not yet generated,
            // unparseable, or a single-file `models.rs` layout we can't read),
            // so the override can't be validated. Honor it as before (assume a
            // non-null `String`), matching the "assume the table exists" posture
            // the missing-target path takes. Not reachable on the normal select
            // path (missing targets are excluded upstream), but keeps the
            // resolver correct for any other caller. A self-reference IS
            // discoverable (via `own_fields`), so it never takes this branch.
            (label.clone(), false)
        } else {
            // The model IS discoverable but `{label}` names no string column —
            // a typo, a non-string column, or a model with NO string columns at
            // all (e.g. `Post { id, count: i32 }` + `{label:count}`). Emitting
            // `select {table}::{label}` (loaded as `String`) would fail to
            // compile the generated app, so fall back to the heuristic display
            // column: generation still succeeds, and the plan carries a warning
            // (emitted in `execute`) telling the author the label was ignored.
            heuristic()?
        }
    } else {
        heuristic()?
    };
    Some(ReferenceDisplay {
        column,
        column_nullable,
    })
}

/// Render the form inputs for a scaffold's `--live-validation` new/edit/
/// re-render views through the shipped, changeset-aware `autumn_web::form`
/// helpers (issue #1124). Standard scaffolds render through a single
/// `form_for` call instead (issue #1135, see [`render_form_for_helper`]);
/// this per-field path survives only for `--live-validation`, whose htmx
/// inline-validation inputs (`text_input_htmx`) have no `FieldControl`
/// equivalent.
///
/// Every helper reads its value and any inline errors from the
/// `Changeset<{Pascal}Form>` bound to `changeset_var` in the calling handler,
/// so preserved input and per-field error messages (`aria-invalid` +
/// `role="alert"`) come for free — and the identical markup is emitted by
/// `new_form`, `edit_form`, and both 422 re-render branches. `FieldKind` maps to
/// the matching helper (`text_input`, `number_input`, `datetime_input`,
/// `checkbox_input`, `select_input`). DSL-constrained text/textarea fields, the
/// `belongs_to` parent `<select>`, and attachments route through the typed
/// accessible `a11y::TextField`/`TextArea`/`Select`/`FileField` primitives
/// (issues #1750/#1951), so the inline-validation controls keep the
/// compile-time label obligation; a file input still can't be repopulated
/// (browser security).
#[allow(clippy::too_many_lines)]
fn render_changeset_form_inputs(
    fields: &[Field],
    changeset_var: &str,
    live_validation: bool,
    validated: &[&str],
    reference_selects: &[&Field],
) -> String {
    use std::fmt::Write as _;
    let cv = changeset_var;
    // The reference fields that render an in-form `<select>` (issue #1750): the
    // present, non-missing `references` columns whose runtime option loader the
    // handler threads into scope. A missing-target reference has no loader, so
    // it keeps the derived per-field control instead.
    let reference_select_names: BTreeSet<&str> =
        reference_selects.iter().map(|f| f.name.as_str()).collect();
    let mut out = String::with_capacity(fields.len() * 150);
    for f in fields {
        let name = &f.name;
        let label = humanize_label(name);
        // A DSL-constrained field (issue #1388) carries HTML5 attributes the
        // shipped `autumn_web::form` helpers can't express; render it as raw
        // markup instead so the live path matches the standard path (#1750).
        let constraint = html5_constraint_spec(f);
        let line = if f.kind.is_reference() && reference_select_names.contains(name.as_str()) {
            // belongs_to parent dropdown (issue #1146), restored in the
            // `--live-validation` per-field path (issue #1750).
            render_live_reference_select(f, cv)
        } else if let (true, Some((input_type, _attrs))) = (
            matches!(
                f.kind,
                FieldKind::I32 | FieldKind::I64 | FieldKind::F32 | FieldKind::F64
            ),
            &constraint,
        ) {
            // A constrained numeric renders a number input carrying its
            // `min`/`max` (and `step="any"` for floats). Numerics don't take the
            // htmx inline-validation path, so no `validate_url`.
            render_live_constrained_field(f, cv, input_type, None)
        } else if f.kind.is_attachment() {
            // Issue #1236: a plain file input, no hidden key. The enclosing
            // `<form>` carries `enctype="multipart/form-data"` so the browser
            // uploads the file with zero JavaScript; an edit that doesn't
            // re-upload preserves the current attachment server-side (the
            // handler binds `streamed.or(current)`). A file input itself can't be
            // repopulated — browser security.
            //
            // Issue #1951: route it through the typed accessible `a11y::FileField`
            // primitive so the file input carries a programmatically-associated
            // `<label for>` (the previous raw `label { … } input;` had an
            // unassociated label). No htmx wiring — attachments never take the
            // inline-validation path.
            format!("(autumn_web::a11y::FileField::new(\"{name}\").label(\"{label}\"))")
        } else {
            // A required (non-nullable) field uses the framework's
            // `required_*` sibling helper — `required` + `aria-required="true"`
            // — matching the pre-#1124 generator's unconditional `required`
            // attribute on every non-nullable input. Nullable fields get the
            // plain helper: leaving them blank is valid, so no browser-native
            // "please fill out this field" prompt should block submission.
            match (f.kind, f.nullable) {
                (FieldKind::Bool, false) => {
                    format!("(autumn_web::form::checkbox_input(&{cv}, \"{name}\", \"{label}\"))")
                }
                // A checkbox can't distinguish "leave false" from "set null", so
                // a nullable bool renders a 3-option select keeping NULL reachable.
                (FieldKind::Bool, true) => format!(
                    "(autumn_web::form::select_input(&{cv}, \"{name}\", \"{label}\", \
                     &[(\"\", \"— Unset —\"), (\"true\", \"Yes\"), (\"false\", \"No\")]))"
                ),
                (FieldKind::I32 | FieldKind::I64, false) => format!(
                    "(autumn_web::form::required_number_input(&{cv}, \"{name}\", \"{label}\", Some(\"1\")))"
                ),
                (FieldKind::I32 | FieldKind::I64, true) => format!(
                    "(autumn_web::form::number_input(&{cv}, \"{name}\", \"{label}\", Some(\"1\")))"
                ),
                (FieldKind::F32 | FieldKind::F64, false) => format!(
                    "(autumn_web::form::required_number_input(&{cv}, \"{name}\", \"{label}\", Some(\"any\")))"
                ),
                (FieldKind::F32 | FieldKind::F64, true) => format!(
                    "(autumn_web::form::number_input(&{cv}, \"{name}\", \"{label}\", Some(\"any\")))"
                ),
                // `step` matches the column's declared scale, so the browser's
                // stepper (and its "please match the requested format"
                // validation) aligns with what the SQL column actually stores.
                (FieldKind::Decimal { scale, .. }, false) => format!(
                    "(autumn_web::form::required_number_input(&{cv}, \"{name}\", \"{label}\", Some(\"{step}\")))",
                    step = decimal_step(scale)
                ),
                (FieldKind::Decimal { scale, .. }, true) => format!(
                    "(autumn_web::form::number_input(&{cv}, \"{name}\", \"{label}\", Some(\"{step}\")))",
                    step = decimal_step(scale)
                ),
                (FieldKind::NaiveDateTime | FieldKind::DateTime, false) => format!(
                    "(autumn_web::form::required_datetime_input(&{cv}, \"{name}\", \"{label}\"))"
                ),
                (FieldKind::NaiveDateTime | FieldKind::DateTime, true) => {
                    format!("(autumn_web::form::datetime_input(&{cv}, \"{name}\", \"{label}\"))")
                }
                (FieldKind::Enum, _) => {
                    let placeholder = if f.nullable {
                        "— Unset —"
                    } else {
                        "— Select —"
                    };
                    let mut options = format!("(\"\", \"{placeholder}\")");
                    for v in &f.variants {
                        let vlabel = humanize_label(v);
                        let _ = write!(options, ", (\"{v}\", \"{vlabel}\")");
                    }
                    let helper = if f.nullable {
                        "select_input"
                    } else {
                        "required_select_input"
                    };
                    format!(
                        "(autumn_web::form::{helper}(&{cv}, \"{name}\", \"{label}\", &[{options}]))"
                    )
                }
                _ => {
                    // String / Text / Uuid / references fall through to a text
                    // input. `--live-validation` on a validated text field wires
                    // the htmx inline-validation variant (no-JS falls back to the
                    // full-form 422 re-render, which works for every kind); a
                    // non-nullable field keeps the `required`/`aria-required`
                    // signal via `required_text_input_htmx` so a validator rule
                    // that happens to permit an empty string (e.g. a max-only
                    // `length` rule) doesn't leave a blank required field with
                    // no client-side guard at all.
                    let validated_htmx = live_validation && validated.contains(&name.as_str());
                    if let Some((input_type, _attrs)) = &constraint {
                        // Issue #1750: a DSL-constrained `String`/`Text` field
                        // carries the #1388 client-side HTML5 attributes
                        // (`minlength`/`maxlength`, `type="email"`/`url`, and a
                        // `<textarea>` for long-form `Text`) the shipped helpers
                        // can't express. Route it through the typed a11y
                        // primitives mirroring the standard `form_for` path
                        // (issue #1951), threading the htmx inline-validation
                        // wiring on via `.hx()` when the field is validated so
                        // real-time validation keeps working alongside the static
                        // constraints. (A constrained field always has a validator
                        // rule, so this is the validated path; the `validate_url`
                        // is threaded only when `live_validation`.)
                        let validate_url =
                            validated_htmx.then(|| format!("paths::validate_{name}()"));
                        render_live_constrained_field(f, cv, input_type, validate_url.as_deref())
                    } else if validated_htmx {
                        let helper = if f.nullable {
                            "text_input_htmx"
                        } else {
                            "required_text_input_htmx"
                        };
                        format!(
                            "(autumn_web::form::{helper}(&{cv}, \"{name}\", \"{label}\", \
                             &paths::validate_{name}()))"
                        )
                    } else if f.nullable {
                        format!("(autumn_web::form::text_input(&{cv}, \"{name}\", \"{label}\"))")
                    } else {
                        format!(
                            "(autumn_web::form::required_text_input(&{cv}, \"{name}\", \"{label}\"))"
                        )
                    }
                }
            }
        };
        let _ = writeln!(out, "            {line}");
    }
    out
}

/// A decimal literal at the given `scale`, formed from a single trailing
/// significant `digit` (1-9) — e.g. `decimal_literal_at_scale(2, 1)` ==
/// `"0.01"`, `decimal_literal_at_scale(0, 2)` == `"2"`. The magnitude never
/// exceeds `9 * 10^-scale` (well under `1` for any `scale >= 1`, and under
/// `10` for `scale == 0`), so the result fits any valid
/// `decimal{precision,scale}` column (the DSL enforces `1 <= precision` and
/// `scale <= precision`) regardless of how tight `precision` is — used both
/// for the `<input step="...">` attribute ([`decimal_step`]) and the SQL
/// sample/duplicate literals the enum-rejection/unique-violation smoke-test
/// generators splice in below ([`sql_sample_literal`], [`unique_sample_literal`],
/// [`unique_sample_literal_variant`]), where a fixed literal like `"1.0"`
/// would overflow a tightly-scaled column such as `decimal{1,1}`.
fn decimal_literal_at_scale(scale: u32, digit: u32) -> String {
    if scale == 0 {
        digit.to_string()
    } else {
        format!("0.{}{digit}", "0".repeat(scale as usize - 1))
    }
}

/// The HTML `step` attribute value for a `decimal{precision,scale}` field,
/// derived from its declared `scale` — `0` steps by whole numbers, `2`
/// produces `"0.01"`, matching the column's actual smallest representable
/// increment (unlike float fields, whose `step="any"` accepts any input).
fn decimal_step(scale: u32) -> String {
    decimal_literal_at_scale(scale, 1)
}

/// The HTML5 `<input>` type and constraint-attribute string a field's DSL
/// constraint modifiers (issue #1388) render to, or `None` when the field has
/// no HTML5 fan-out (so the derived `FieldControl` already renders it right).
///
/// `String`/`Text`: `min`/`max` -> `minlength`/`maxlength`, `email` ->
/// `type="email"`, `url` -> `type="url"`. Numeric: `min`/`max` -> `min`/`max`
/// on a `type="number"` input, and float (`f32`/`f64`) fields also carry
/// `step="any"` so fractional input isn't rejected client-side. Returned
/// attribute string is space-prefixed and ready to splice straight into the
/// generated maud `input`.
/// A single HTML5 validation constraint derived from a field's DSL modifiers
/// (issue #1388). One structured source of truth so the same constraint data
/// can be rendered either as raw `<input>`/`<textarea>` attributes (the
/// still-raw textarea and live-validation paths) or as typed
/// `autumn_web::a11y::TextField` builder calls (the routed `form_for` input
/// path, #1706).
enum Html5Constraint {
    MinLength(String),
    MaxLength(String),
    Min(String),
    Max(String),
    StepAny,
}

impl Html5Constraint {
    /// The raw, space-prefixed attribute form (e.g. ` minlength="3"`).
    fn attr(&self) -> String {
        match self {
            Self::MinLength(v) => format!(" minlength=\"{v}\""),
            Self::MaxLength(v) => format!(" maxlength=\"{v}\""),
            Self::Min(v) => format!(" min=\"{v}\""),
            Self::Max(v) => format!(" max=\"{v}\""),
            Self::StepAny => " step=\"any\"".to_owned(),
        }
    }

    /// The typed `a11y::TextField` builder-call form (e.g. `.minlength(3u32)`).
    fn builder_call(&self) -> String {
        match self {
            Self::MinLength(v) => format!(".minlength({v}u32)"),
            Self::MaxLength(v) => format!(".maxlength({v}u32)"),
            Self::Min(v) => format!(".min(\"{v}\")"),
            Self::Max(v) => format!(".max(\"{v}\")"),
            Self::StepAny => ".step(\"any\")".to_owned(),
        }
    }
}

/// The input `type` plus the structured HTML5 constraints a DSL-constrained
/// (issue #1388) `String`/`Text`/numeric field needs over its derived control.
/// Returns `None` when the field carries nothing the derived `FieldControl`
/// can't already express (a plain `text`/`number` with no constraints), so it
/// stays in the derived render rather than being needlessly excised.
fn html5_constraint_parts(field: &Field) -> Option<(&'static str, Vec<Html5Constraint>)> {
    let c = &field.constraints;
    let mut parts = Vec::new();
    let input_type = match field.kind {
        FieldKind::String | FieldKind::Text => {
            if let Some(min) = &c.min {
                parts.push(Html5Constraint::MinLength(min.clone()));
            }
            if let Some(max) = &c.max {
                parts.push(Html5Constraint::MaxLength(max.clone()));
            }
            if c.email {
                "email"
            } else if c.url {
                "url"
            } else {
                "text"
            }
        }
        FieldKind::I32 | FieldKind::I64 => {
            if let Some(min) = &c.min {
                parts.push(Html5Constraint::Min(min.clone()));
            }
            if let Some(max) = &c.max {
                parts.push(Html5Constraint::Max(max.clone()));
            }
            "number"
        }
        FieldKind::F32 | FieldKind::F64 => {
            if let Some(min) = &c.min {
                parts.push(Html5Constraint::Min(min.clone()));
            }
            if let Some(max) = &c.max {
                parts.push(Html5Constraint::Max(max.clone()));
            }
            // A constrained float must keep `step="any"` — the same step the
            // unconstrained float control (`FieldControl::Number { step: "any" }`)
            // emits. Without it browsers default a `type="number"` input to
            // `step="1"` and reject fractional input like `0.5` for
            // `ratio:f64{min=0,max=1}` client-side, even though the server-side
            // `range` validator and the `f64` type accept it (issue #1388's
            // "client and server agree"). Only emitted when the field is
            // actually constrained (min/max present, so `parts` is non-empty);
            // otherwise the early-return below keeps the field in the derived
            // render rather than needlessly excising it.
            if !parts.is_empty() {
                parts.push(Html5Constraint::StepAny);
            }
            "number"
        }
        _ => return None,
    };
    // Nothing to add over the derived control: a plain `text`/`number` with no
    // constraint attributes is exactly what `form_for` already renders, so
    // don't excise-and-reappend it (which would only reorder the field).
    if parts.is_empty() && input_type != "email" && input_type != "url" {
        return None;
    }
    Some((input_type, parts))
}

/// The input `type` plus the raw, space-prefixed HTML5 attribute string (e.g.
/// ` minlength="3" maxlength="120"`) for the still-raw textarea and
/// live-validation render paths. Formats [`html5_constraint_parts`].
fn html5_constraint_spec(field: &Field) -> Option<(&'static str, String)> {
    let (input_type, parts) = html5_constraint_parts(field)?;
    let attrs = parts.iter().map(Html5Constraint::attr).collect::<String>();
    Some((input_type, attrs))
}

/// The input `type` plus the typed `autumn_web::a11y::TextField` builder-call
/// string (e.g. `.minlength(3u32).maxlength(120u32)`) for the routed `form_for`
/// input path (#1706). Formats [`html5_constraint_parts`].
fn html5_constraint_builder_calls(field: &Field) -> Option<(&'static str, String)> {
    let (input_type, parts) = html5_constraint_parts(field)?;
    let calls = parts
        .iter()
        .map(Html5Constraint::builder_call)
        .collect::<String>();
    Some((input_type, calls))
}

/// Render the maud markup for a DSL-constrained (issue #1388)
/// `String`/`Text`/numeric field in the `--live-validation` per-field path
/// (issue #1750).
///
/// The control is routed through the typed accessible `a11y::TextField` /
/// `a11y::TextArea` primitives (issue #1951): the raw wrapper `<div>` and the
/// inline-error `<div>` skeleton stay as maud lines (mirroring the shipped
/// `autumn_web::form::*` helpers and the standard `form_for` path's
/// `.exclude()` + `.append()` output), but the labelled control itself is a
/// primitive builder chain, so the inline-validation field keeps the
/// compile-time label obligation instead of dropping to raw markup. The
/// `input_type` override and the HTML5 constraints
/// (`minlength`/`maxlength`/`min`/`max`/`step`) become typed builder calls from
/// the same [`html5_constraint_builder_calls`] source the standard path uses.
///
/// When `validate_url` is `Some`, the htmx inline-validation wiring is threaded
/// on too — the `data-autumn-field-wrapper` swap marker stays a raw attribute
/// on the wrapper `<div>`, and the control carries the
/// `hx-post`/`hx-trigger`/`hx-target`/`hx-swap`/`hx-include` +
/// `hx-params="not _submit_token"` attributes via the primitive's `.hx()`
/// escape hatch. The `hx-params` filter keeps the inline-validation POST (which
/// `hx-include`s the whole form) from carrying the one-time `_submit_token`, so
/// validation never consumes the token the real create/update submit needs
/// (issue #1360). Shared by [`render_changeset_form_inputs`] and the
/// inline-validate handlers so the initially-rendered field and the
/// htmx-swapped fragment are byte-identical.
fn render_live_constrained_field(
    field: &Field,
    changeset_var: &str,
    input_type: &str,
    // A Rust expression (as source text) producing the inline-validation URL —
    // the typed path helper `paths::validate_{field}()` (issue #1133). Spliced
    // into `.hx("post", …)` so the URL has a single source of truth.
    validate_url: Option<&str>,
) -> String {
    let name = &field.name;
    let label = humanize_label(name);
    let cv = changeset_var;
    // Typed HTML5-constraint builder calls (`.minlength(3u32)`, `.min("0")`,
    // `.step("any")`, …) from the same `html5_constraint_parts` source the
    // standard `form_for` input path uses, so the two paths can't drift.
    let constraint_builders = html5_constraint_builder_calls(field)
        .map(|(_, calls)| calls)
        .unwrap_or_default();
    let required_builders = if field.nullable {
        ""
    } else {
        ".required().aria_required()"
    };
    // A constrained `Text` column is long-form (Postgres `TEXT`), so it renders
    // a `<textarea>` (matching the derived `FieldControl::Textarea` and the
    // standard path). A `text{email}`/`text{url}` field is inherently
    // single-line (its `input_type` is `email`/`url`), so it takes the `<input>`
    // branch — a textarea can't carry those types.
    let is_textarea = matches!(field.kind, FieldKind::Text) && input_type == "text";
    // htmx inline-validation wiring: the swap-target marker stays a raw
    // attribute on the wrapper `<div>`, while the control carries the htmx
    // attributes through the primitive's `.hx()` escape hatch (issue #1951).
    let (wrapper_marker, hx_builders) = validate_url.map_or_else(
        || (String::new(), String::new()),
        |url| {
            (
                format!(" data-autumn-field-wrapper=\"{name}\""),
                format!(
                    "\n                    .hx(\"post\", {url})\n                    \
                     .hx(\"trigger\", \"change\")\n                    \
                     .hx(\"target\", \"closest [data-autumn-field-wrapper]\")\n                    \
                     .hx(\"swap\", \"outerHTML\")\n                    \
                     .hx(\"include\", \"closest form\")\n                    \
                     .hx(\"params\", \"not _submit_token\")"
                ),
            )
        },
    );
    let errors_tail = format!(
        "\n                @if !errors.is_empty() {{\n                    \
         div id=\"{name}-error\" role=\"alert\" class=\"autumn-field__errors\" {{\n                        \
         @for error in errors {{ p class=\"autumn-field__error\" {{ (error) }} }}\n                    \
         }}\n                \
         }}\n            \
         }}"
    );
    if is_textarea {
        format!(
            "div id=\"{name}-field\" class=\"autumn-field\"{wrapper_marker} {{\n                \
             @let errors = {cv}.errors_for(\"{name}\");\n                \
             (autumn_web::a11y::TextArea::new(\"{name}\")\n                    \
             .label(\"{label}\")\n                    \
             .label_class(\"autumn-field__label\")\n                    \
             .value({cv}.field_value(\"{name}\").unwrap_or_default())\n                    \
             {constraint_builders}{required_builders}\n                    \
             .class(if errors.is_empty() {{ \"autumn-field__input\" }} else {{ \"autumn-field__input autumn-field__input--invalid\" }})\n                    \
             .aria_invalid(!errors.is_empty())\n                    \
             .described_by(if errors.is_empty() {{ \"\" }} else {{ \"{name}-error\" }}){hx_builders}){errors_tail}"
        )
    } else {
        format!(
            "div id=\"{name}-field\" class=\"autumn-field\"{wrapper_marker} {{\n                \
             @let errors = {cv}.errors_for(\"{name}\");\n                \
             (autumn_web::a11y::TextField::new(\"{name}\")\n                    \
             .label(\"{label}\")\n                    \
             .label_class(\"autumn-field__label\")\n                    \
             .input_type(\"{input_type}\")\n                    \
             .value({cv}.field_value(\"{name}\").unwrap_or_default())\n                    \
             {constraint_builders}{required_builders}\n                    \
             .class(if errors.is_empty() {{ \"autumn-field__input\" }} else {{ \"autumn-field__input autumn-field__input--invalid\" }})\n                    \
             .aria_invalid(!errors.is_empty())\n                    \
             .described_by(if errors.is_empty() {{ \"\" }} else {{ \"{name}-error\" }}){hx_builders}){errors_tail}"
        )
    }
}

/// Render the maud markup for a `belongs_to` parent `<select>` in the
/// `--live-validation` per-field path (issue #1750). The standard path renders
/// this through a `form_for` `FieldControl::Select` override, but the per-field
/// path has no `form_for`, so it routes the control through the typed
/// accessible `a11y::Select` primitive (issue #1951) — the raw wrapper `<div>`
/// and inline-error `<div>` skeleton stay as maud lines, while the labelled
/// `<select>` is a primitive builder chain populated at request time from the
/// `{name}_options` loader (a `Vec<(String, String)>` of id/display pairs). A
/// blank placeholder plus `selected_value` driven by the changeset value keeps
/// the chosen parent through a 422 re-render. The `{name}_options` binding is
/// loaded into scope by the calling handler. (There is no htmx wiring here — the
/// `belongs_to` select carries no inline-validation attributes.)
fn render_live_reference_select(field: &Field, changeset_var: &str) -> String {
    let name = &field.name;
    let label = humanize_label(name);
    let cv = changeset_var;
    let placeholder = if field.nullable {
        "— Unset —"
    } else {
        "— Select —"
    };
    let required_builders = if field.nullable {
        ""
    } else {
        ".required().aria_required()"
    };
    format!(
        "div id=\"{name}-field\" class=\"autumn-field\" {{\n                \
         @let errors = {cv}.errors_for(\"{name}\");\n                \
         (autumn_web::a11y::Select::new(\"{name}\")\n                    \
         .label(\"{label}\")\n                    \
         .label_class(\"autumn-field__label\")\n                    \
         {required_builders}\n                    \
         .class(if errors.is_empty() {{ \"autumn-field__input\" }} else {{ \"autumn-field__input autumn-field__input--invalid\" }})\n                    \
         .aria_invalid(!errors.is_empty())\n                    \
         .described_by(if errors.is_empty() {{ \"\" }} else {{ \"{name}-error\" }})\n                    \
         .option(\"\", \"{placeholder}\")\n                    \
         .options({name}_options.iter().map(|(opt_value, opt_label)| autumn_web::a11y::SelectOption::new(opt_value.as_str(), opt_label.as_str())))\n                    \
         .selected_value({cv}.field_value(\"{name}\").unwrap_or_default()))\n                \
         @if !errors.is_empty() {{\n                    \
         div id=\"{name}-error\" role=\"alert\" class=\"autumn-field__errors\" {{\n                        \
         @for error in errors {{ p class=\"autumn-field__error\" {{ (error) }} }}\n                    \
         }}\n                \
         }}\n            \
         }}"
    )
}

/// Produce the cell-body expression for a `data_table` column closure.
///
/// Every arm must evaluate to a type that implements `maud::Render` (`&str`,
/// `String`, `Cow<str>`, integers). `bool`, `Option<T>`, chrono types, `Uuid`,
/// `Vec<u8>`, and `Blob` do NOT implement `Render` in maud 0.27, so we always
/// coerce via `to_string()` / `unwrap_or_default()`.
fn cell_value_expr(field: &Field) -> String {
    let name = &field.name;
    match (field.nullable, field.kind) {
        // Attachment: always Option<Blob>; show presence only, no Blob internals.
        (_, FieldKind::Attachment) => {
            format!("if row.{name}.is_some() {{ \"attachment\" }} else {{ \"—\" }}")
        }
        (true, FieldKind::Bytea) => {
            format!(
                "row.{name}.as_ref().map(|v| String::from_utf8_lossy(v).to_string()).unwrap_or_default()"
            )
        }
        // Nullable String/Text: use as_deref to avoid heap allocation.
        (true, FieldKind::String | FieldKind::Text) => {
            format!("row.{name}.as_deref().unwrap_or_default()")
        }
        // Nullable: Option<T> — no Render impl; unwrap to String.
        (true, _) => format!("row.{name}.as_ref().map(ToString::to_string).unwrap_or_default()"),
        // Non-nullable Bytea: Cow<str> does implement Render.
        (false, FieldKind::Bytea) => format!("String::from_utf8_lossy(&row.{name})"),
        // String/Text: &String implements Render via deref coercion.
        (false, FieldKind::String | FieldKind::Text) => format!("&row.{name}"),
        // Numerics (i32, i64, f32, f64): implement Render directly.
        (false, FieldKind::I32 | FieldKind::I64 | FieldKind::F32 | FieldKind::F64) => {
            format!("row.{name}")
        }
        // Bool, Uuid, chrono types: no Render impl in maud 0.27; convert via Display.
        (false, _) => format!("row.{name}.to_string()"),
    }
}

/// Whether a column of this kind is server-sortable via the generated
/// `list()` method (#1126).
///
/// Mirrors the orderable-type allowlist in the `#[model]` macro: every scalar
/// column is sortable EXCEPT binary blobs (`Bytea`/`Attachment`) and closed-set
/// `Enum` columns (whose Rust type is a generated enum the macro doesn't emit a
/// sort arm for). Emitting `.sortable(..)` only for these keeps the rendered
/// header links symmetric with what the server actually applies — a link that
/// resolves to the default order would be a dead affordance.
const fn kind_is_sortable(kind: FieldKind) -> bool {
    !matches!(
        kind,
        FieldKind::Bytea | FieldKind::Attachment | FieldKind::Enum
    )
}

/// Emit the `let columns: Vec<Column<Pascal>> = vec![…];` block for the index handler.
///
/// Includes an "Id" column, one column per scaffold field (title-cased header),
/// and a trailing "Show" actions column. Scalar columns are marked `.sortable(..)`
/// (the sort key is the column's snake name) so the `data_table` renders header
/// links that the generated `list()` method applies against the model's column
/// allowlist (#1126). The trailing "Show" action column is never sortable.
fn render_columns_vec(
    pascal_name: &str,
    fields: &[Field],
    reference_displays: &BTreeMap<String, ReferenceDisplay>,
    use_label_maps: bool,
) -> String {
    use std::fmt::Write as _;
    let mut out = String::with_capacity(fields.len() * 150 + 300);
    let _ = writeln!(
        out,
        "    let columns: Vec<autumn_web::widgets::Column<{pascal_name}>> = vec!["
    );
    // ID column — always sortable (the default order is `id DESC`).
    let _ = writeln!(
        out,
        "        autumn_web::widgets::Column::new(\"Id\", |row: &{pascal_name}| maud::html! {{ (row.id) }}).sortable(\"id\"),"
    );
    // One column per field
    for f in fields {
        let header = title_case(&f.name);
        let sortable_suffix = if kind_is_sortable(f.kind) {
            format!(".sortable(\"{}\")", f.name)
        } else {
            String::new()
        };
        // A displayable `references` column renders the parent's label from
        // the per-view `{name}_labels` map the handler loaded (issue #1146),
        // instead of the raw foreign-key id. The closure borrows the map,
        // which outlives the `columns` vec in the generated handler.
        let cell_expr = if use_label_maps
            && f.kind.is_reference()
            && reference_displays.contains_key(&f.name)
        {
            let name = &f.name;
            if f.nullable {
                format!(
                    "match &row.{name} {{ Some(v) => {name}_labels.get(&v.to_string()).map(String::as_str).unwrap_or(\"—\"), None => \"—\" }}"
                )
            } else {
                format!(
                    "{name}_labels.get(&row.{name}.to_string()).map(String::as_str).unwrap_or(\"—\")"
                )
            }
        } else {
            cell_value_expr(f)
        };
        let _ = writeln!(
            out,
            "        autumn_web::widgets::Column::new(\"{header}\", |row: &{pascal_name}| maud::html! {{ ({cell_expr}) }}){sortable_suffix},"
        );
    }
    // Show link column
    let _ = writeln!(
        out,
        "        autumn_web::widgets::Column::new(\"\", |row: &{pascal_name}| maud::html! {{ (autumn_web::a11y::Link::new(paths::show(row.id), \"Show\")) }}),"
    );
    let _ = writeln!(out, "    ];");
    out
}

/// Emit the `vec![…]` body for the `props` binding in the `show` handler.
///
/// Produces one `("Label", maud::html! { value_expr })` tuple per row:
/// `id`, every DSL-declared field (humanized label), then `created_at`. A
/// `references` field with a resolved display (issue #1146) renders the
/// pre-loaded `{name}_label` variable (the parent's display value) instead of
/// the raw foreign-key id — see [`render_show_reference_label_loads`].
fn render_show_property_rows(
    fields: &[Field],
    reference_displays: &BTreeMap<String, ReferenceDisplay>,
) -> String {
    let mut out = String::with_capacity(fields.len() * 100 + 150);
    out.push_str("        (\"Id\", maud::html! { (row.id) }),\n");
    for f in fields {
        let label = humanize(&f.name);
        let cell_expr = if f.kind.is_reference() && reference_displays.contains_key(&f.name) {
            format!("{}_label", f.name)
        } else {
            cell_value_expr(f)
        };
        out.push_str("        (\"");
        out.push_str(&label);
        out.push_str("\", maud::html! { (");
        out.push_str(&cell_expr);
        out.push_str(") }),\n");
    }
    out.push_str("        (\"Created at\", maud::html! { (row.created_at.to_string()) }),\n");
    out
}

/// Emit the `let {name}_label: String = …;` bindings the `show` handler
/// evaluates before building its `props`, one per `references` field with a
/// resolved display column (issue #1146). Each does a single per-view lookup
/// of the parent's display value (the batched variant is out of scope, #835),
/// falling back to the id string if the parent row (or its display value) is
/// missing. Empty when the resource has no displayable references.
fn render_show_reference_label_loads(
    fields: &[Field],
    reference_displays: &BTreeMap<String, ReferenceDisplay>,
) -> String {
    use std::fmt::Write as _;
    let mut out = String::new();
    for f in fields {
        let Some(display) = reference_displays.get(&f.name) else {
            continue;
        };
        let Some(table) = f.reference_table() else {
            continue;
        };
        let name = &f.name;
        let column = &display.column;
        // A nullable display column comes back as `Option<String>` and is
        // flattened; a non-null one as `String`. Both coalesce to the id on a
        // miss so the show page never renders a bare blank for a real FK.
        let found_expr = if display.column_nullable {
            format!(
                "{table}::table.find(fk).select({table}::{column}).first::<Option<String>>(&mut *db).await.ok().flatten().unwrap_or_else(|| fk.to_string())"
            )
        } else {
            format!(
                "{table}::table.find(fk).select({table}::{column}).first::<String>(&mut *db).await.unwrap_or_else(|_| fk.to_string())"
            )
        };
        if f.nullable {
            let _ = writeln!(
                out,
                "    let {name}_label: String = match row.{name} {{ Some(fk) => {found_expr}, None => \"—\".to_string() }};"
            );
        } else {
            let _ = writeln!(
                out,
                "    let {name}_label: String = {{ let fk = row.{name}; {found_expr} }};"
            );
        }
    }
    out
}

/// Emit the `let {name}_labels: HashMap<String, String> = …;` bindings the
/// plain (non-sharded) `index` handler evaluates before building its data-table
/// columns, one per `references` field with a resolved display column
/// (issue #1146). Each reuses the field's `{name}_select_options` loader (a
/// simple per-view fetch; the batched variant is out of scope, #835) to map
/// each parent id string to its display label, which the column closures then
/// look up per row. Empty when the resource has no displayable references.
fn render_index_reference_label_loads(
    reference_fields: &[&Field],
    reference_displays: &BTreeMap<String, ReferenceDisplay>,
) -> String {
    use std::fmt::Write as _;
    let mut out = String::new();
    for f in reference_fields {
        if !reference_displays.contains_key(&f.name) {
            continue;
        }
        let name = &f.name;
        let _ = writeln!(
            out,
            "    let {name}_labels: std::collections::HashMap<String, String> =\n        \
             {name}_select_options(&mut db).await?.into_iter().collect();"
        );
    }
    out
}

/// Humanize a `snake_case` field name: capitalize only the first word.
///
/// `created_at` → `"Created at"`, `user_name` → `"User name"`.
/// Matches the humanization convention used in Phoenix / Rails form labels.
fn humanize(s: &str) -> String {
    let replaced = s.replace('_', " ");
    let mut chars = replaced.chars();
    chars.next().map_or_else(String::new, |c| {
        c.to_uppercase().to_string() + chars.as_str()
    })
}

/// Convert `snake_case` field name to `Title Case` header label.
fn title_case(s: &str) -> String {
    s.split('_')
        .map(|word| {
            let mut chars = word.chars();
            chars.next().map_or_else(String::new, |c| {
                c.to_uppercase().to_string() + chars.as_str()
            })
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// A required numeric carrying a `{min,max}` range (issue #1388) that is
/// represented as `Option<T>` on the form struct (issue #1748). Extracted so
/// both the struct/`into_new` emission in [`render_model_form`] and the
/// empty-pair drop set in [`render_nullable_field_match`] agree on which fields
/// are the synthetic Options.
const fn is_constrained_required_numeric(f: &Field) -> bool {
    !f.nullable
        && matches!(
            f.kind,
            FieldKind::I32 | FieldKind::I64 | FieldKind::F32 | FieldKind::F64
        )
        && (f.constraints.min.is_some() || f.constraints.max.is_some())
}

/// Render the body of the generated `is_nullable_form_field` helper — the set
/// of fields whose empty `field=` pair the decoder drops so it deserializes as
/// missing (`None`) rather than being handed to `serde_urlencoded` as `""`.
///
/// This includes the genuinely nullable fields AND the synthetic
/// constrained-required-`Option<T>` numerics (issue #1748): those are
/// `Option<T>` on the form struct but have `nullable == false`, so without this
/// a blank `age=` pair (from curl, a non-browser client, or disabled JS) would
/// reach `serde_urlencoded`, which parses `""` into the inner numeric and
/// returns a **400** *before* `#[validate(required)]` can render the intended
/// **422** inline error. Dropping the empty pair makes the field decode as
/// `None`, so `required` fires and produces the 422 (the #1748 intent).
fn render_nullable_field_match(fields: &[Field]) -> String {
    let names = fields
        .iter()
        .filter(|field| field.nullable || is_constrained_required_numeric(field))
        .map(|field| format!("\"{}\"", field.name))
        .collect::<Vec<_>>();
    if names.is_empty() {
        "false".to_owned()
    } else {
        format!("matches!(name, {})", names.join(" | "))
    }
}

/// Render the column-update tuple body for the `update` handler. Emits
/// `tablename::field.eq(form.field.clone()), …` per user field, leaving the
/// auto-managed `id` and `created_at` columns alone. With no user fields the
/// body is empty (Diesel accepts `set(())` as a no-op update).
///
/// ⚡ Bolt optimization: Avoids intermediate `Vec` allocations during string formatting
/// by pre-allocating capacity and utilizing `std::fmt::Write` sequentially.
fn render_update_columns(plural: &str, fields: &[Field]) -> String {
    use std::fmt::Write;
    // Estimate 50 chars per field
    let mut out = String::with_capacity(fields.len() * 50);
    // Issue #1326: a `:states(…)` state-machine column is transition-only — it is
    // mutated exclusively through the dedicated `POST /{plural}/{{id}}/transitions/
    // {field}` handler (a direct `diesel::update(...).set({field}.eq(new_state))`),
    // never the ordinary update path. Excluding it from the update `.set((…))`
    // tuple (and, in `render_form_for_helper`, from the edit form) stops a plain
    // `POST /{plural}/{{id}}/update` from setting `status=<anything>` and bypassing
    // `transition_{field}_to` / its guards. A model with no state-machine field
    // emits the exact pre-#1326 column set.
    for (i, f) in fields
        .iter()
        .filter(|f| f.state_machine.is_none())
        .enumerate()
    {
        if i > 0 {
            out.push_str(", ");
        }
        write!(
            out,
            "{plural}::{name}.eq(new.{name}.clone())",
            name = f.name
        )
        .unwrap();
    }
    out
}

/// Render one `db.execute_sql("...").await;` call per statement in `sql`,
/// escaping the SQL text so it survives as a Rust string literal in the
/// generated test.
///
/// Postgres's extended query protocol -- which `diesel::sql_query` uses --
/// rejects a single prepared statement that contains more than one SQL
/// command, so a migration's `CREATE TABLE` followed by one or more
/// `CREATE INDEX` statements must be executed one at a time. Reuses
/// [`crate::migrate::safety::split_statements`] (dollar-quote- and
/// comment-aware) rather than a naive `;`-terminated-line splitter, so it
/// stays correct if a future `--default` value embeds a semicolon.
fn render_execute_sql_calls(sql: &str) -> String {
    let mut out = String::new();
    for statement in crate::migrate::safety::split_statements(sql) {
        let escaped = escape_sql_for_rust_literal(&statement);
        let _ = writeln!(out, "db.execute_sql(\"{escaped};\").await;");
    }
    out
}

/// Escape a raw SQL string so it survives verbatim as a Rust string literal
/// (`"..."`) in generated test code — used both for the `db.execute_sql(...)`
/// setup calls above and for the raw `diesel::sql_query(...)` issued by the
/// enum out-of-set rejection smoke test (see `enum_rejection_insert_sql`).
fn escape_sql_for_rust_literal(sql: &str) -> String {
    sql.replace('\\', "\\\\").replace('"', "\\\"")
}

/// Render the `tests/<snake>.rs` smoke test's HTML (non-`--api`) shape: an
/// in-process, real-database read of the scaffolded index route.
///
/// The handler under test is a stand-in for `routes::{plural}::index` rather
/// than a literal re-export of it. A freshly scaffolded project is a binary
/// crate (no `src/lib.rs`), so a `tests/*.rs` integration binary cannot import
/// the project's own handler functions -- see
/// `docs/guide/tutorial/11-testing.md`, which documents this exact
/// constraint and the same "redeclare the handler under test" workaround.
fn render_index_smoke_test(
    pascal_name: &str,
    plural: &str,
    id_schema_type: &str,
    setup_calls: &str,
) -> String {
    format!(
        "//! Smoke test generated by `autumn generate scaffold`.\n\
         //!\n\
         //! Boots a stand-in for the scaffolded `GET /{plural}` route in-process\n\
         //! via `autumn_web::test::{{TestApp, TestClient, TestDb}}` and asserts a\n\
         //! real response against a real (throwaway) Postgres database -- no\n\
         //! running server, no hard-coded server base URL env var, no silent skip.\n\
         //!\n\
         //! The handler below is NOT the generated `routes::{plural}::index`\n\
         //! handler: a `tests/` integration binary cannot import a project's own\n\
         //! code when the project has no `src/lib.rs` (see\n\
         //! `docs/guide/tutorial/11-testing.md`), so this test redeclares a\n\
         //! minimal handler that runs the same kind of query against the same\n\
         //! table instead. That proves the database, migration, and in-process\n\
         //! request pipeline all work -- it does NOT exercise the real handler's\n\
         //! pagination, `data_table` rendering, CSRF, or flash-message logic. For\n\
         //! coverage of that, add unit tests inside `src/routes/{plural}.rs`\n\
         //! itself (it's part of the binary crate, so it can call the real code).\n\
         //!\n\
         //! `cargo test` reports this test as `ignored` (Docker is not assumed to\n\
         //! be available in every environment); run it for real with:\n\
         //!\n\
         //!     cargo test -- --ignored\n\
         \n\
         use autumn_web::prelude::*;\n\
         use autumn_web::test::{{TestApp, TestClient, TestDb}};\n\
         use diesel::prelude::*;\n\
         use diesel_async::RunQueryDsl;\n\
         \n\
         diesel::table! {{\n\
         {plural} (id) {{\n\
         id -> {id_schema_type},\n\
         }}\n\
         }}\n\
         \n\
         #[get(\"/{plural}\")]\n\
         async fn index(mut db: Db) -> AutumnResult<Markup> {{\n\
         let total: i64 = {plural}::table.count().get_result(&mut db).await?;\n\
         Ok(html! {{\n\
         h1 {{ \"{pascal_name}s\" }}\n\
         p {{ (total) \" row(s)\" }}\n\
         }})\n\
         }}\n\
         \n\
         #[tokio::test]\n\
         #[ignore = \"requires Docker (testcontainers) via TestDb; run `cargo test -- --ignored`\"]\n\
         async fn {plural}_index_renders_scaffolded_rows() {{\n\
         let db = TestDb::shared().await;\n\
         {setup_calls}\
         db.execute_sql(\"TRUNCATE {plural} RESTART IDENTITY\").await;\n\
         \n\
         let client: TestClient = TestApp::new().routes(routes![index]).with_db(db.pool()).build();\n\
         \n\
         client.get(\"/{plural}\").send().await\n\
         .assert_ok()\n\
         .assert_body_contains(\"{pascal_name}s\");\n\
         }}\n"
    )
}

/// Render the `tests/<snake>.rs` smoke test's `--api` shape: an in-process,
/// real-database read of the scaffolded JSON list route.
///
/// See [`render_index_smoke_test`] for why the handler under test is a
/// stand-in rather than a literal re-export of the generated
/// `{snake}_api_list` repository handler.
fn render_api_smoke_test(
    plural: &str,
    id_schema_type: &str,
    setup_calls: &str,
    fields: &[Field],
    defaults: &BTreeMap<String, String>,
) -> String {
    // Route the seed through `render_execute_sql_calls` so a multi-statement
    // seed (the no-required-column branch emits one `INSERT ... DEFAULT VALUES`
    // per row) becomes one `db.execute_sql(...)` call apiece -- diesel-async's
    // `execute` uses the extended protocol, which rejects several `;`-separated
    // statements in a single call. The single-statement required-column branch
    // is unaffected (it renders exactly one call).
    let seed_calls = render_execute_sql_calls(&render_api_seed_sql(plural, fields, defaults));
    format!(
        "//! Smoke test generated by `autumn generate scaffold --api`.\n\
         //!\n\
         //! Boots a stand-in for the scaffolded `GET /api/{plural}` route\n\
         //! in-process via `autumn_web::test::{{TestApp, TestClient, TestDb}}`\n\
         //! and asserts a real response against a real (throwaway) Postgres\n\
         //! database -- no running server, no hard-coded server base URL env\n\
         //! var, no silent skip.\n\
         //!\n\
         //! The handler below is NOT the generated repository's JSON list\n\
         //! handler: a `tests/` integration binary cannot import a project's own\n\
         //! code when the project has no `src/lib.rs` (see\n\
         //! `docs/guide/tutorial/11-testing.md`). It reuses the same shipped\n\
         //! `PageRequest` extractor + `Page` envelope the real generated\n\
         //! `--api` list handler paginates with (issue #1237), so it proves the\n\
         //! self-describing envelope shape and that pages advance -- but it does\n\
         //! NOT exercise the real repository handler's serialization or filtering.\n\
         //!\n\
         //! `cargo test` reports this test as `ignored` (Docker is not assumed to\n\
         //! be available in every environment); run it for real with:\n\
         //!\n\
         //!     cargo test -- --ignored\n\
         \n\
         use autumn_web::prelude::*;\n\
         use autumn_web::test::{{TestApp, TestClient, TestDb}};\n\
         use diesel::prelude::*;\n\
         use diesel::dsl::sql;\n\
         use diesel::sql_types::Text;\n\
         use diesel_async::RunQueryDsl;\n\
         \n\
         diesel::table! {{\n\
         {plural} (id) {{\n\
         id -> {id_schema_type},\n\
         }}\n\
         }}\n\
         \n\
         // Stand-in that paginates by default, exactly like the generated\n\
         // `--api` list handler: a bounded `LIMIT/OFFSET` window wrapped in the\n\
         // `Page` envelope, never an unbounded `find_all()`.\n\
         #[get(\"/api/{plural}\")]\n\
         async fn api_list(page: PageRequest, mut db: Db) -> AutumnResult<Page<String>> {{\n\
         let total: i64 = {plural}::table.count().get_result(&mut db).await?;\n\
         let ids: Vec<String> = {plural}::table\n\
         .select(sql::<Text>(\"id::text\"))\n\
         .order({plural}::id.asc())\n\
         .limit(page.limit())\n\
         .offset(page.offset())\n\
         .load(&mut db)\n\
         .await?;\n\
         Ok(Page::new(ids, total, &page))\n\
         }}\n\
         \n\
         #[tokio::test]\n\
         #[ignore = \"requires Docker (testcontainers) via TestDb; run `cargo test -- --ignored`\"]\n\
         async fn {plural}_api_list_paginates_against_a_real_database() {{\n\
         let db = TestDb::shared().await;\n\
         {setup_calls}\
         db.execute_sql(\"TRUNCATE {plural} RESTART IDENTITY\").await;\n\
         // Seed 25 rows -- more than one page at size = 2, and more than the\n\
         // default page size (20). Every required (NOT NULL, no DEFAULT) column\n\
         // gets a valid, per-row-varying sample value, so this works for an\n\
         // ordinary scaffold with required fields -- not just an all-default\n\
         // table a bare `INSERT ... DEFAULT VALUES` could satisfy.\n\
         {seed_calls}\
         \n\
         let client: TestClient = TestApp::new().routes(routes![api_list]).with_db(db.pool()).build();\n\
         \n\
         // Page 1 returns the self-describing `Page` envelope, bounded to `size`.\n\
         let page1: serde_json::Value = client\n\
         .get(\"/api/{plural}?page=1&size=2\")\n\
         .send()\n\
         .await\n\
         .assert_ok()\n\
         .json();\n\
         assert_eq!(page1[\"page\"], 1);\n\
         assert_eq!(page1[\"size\"], 2);\n\
         assert_eq!(page1[\"total_elements\"], 25);\n\
         assert_eq!(page1[\"total_pages\"], 13);\n\
         assert_eq!(page1[\"has_next\"], true);\n\
         assert_eq!(page1[\"content\"].as_array().map(Vec::len), Some(2));\n\
         \n\
         // Page 2 holds different rows -- pagination actually advances.\n\
         let page2: serde_json::Value = client\n\
         .get(\"/api/{plural}?page=2&size=2\")\n\
         .send()\n\
         .await\n\
         .assert_ok()\n\
         .json();\n\
         assert_ne!(page1[\"content\"], page2[\"content\"], \"page 2 must differ from page 1\");\n\
         }}\n"
    )
}

/// Emit `CREATE TABLE IF NOT EXISTS <target> (id BIGSERIAL PRIMARY KEY);` for
/// every distinct table a `references` field points at.
///
/// `TestDb::shared()` starts one Postgres testcontainer per `tests/*.rs`
/// binary (a process-global `OnceLock`), so a scaffold's own smoke test can't
/// assume some *other* scaffolded resource's smoke test already created the
/// referenced table — `CREATE TABLE comments (... REFERENCES posts(id) ...)`
/// would otherwise fail with "relation posts does not exist" whenever
/// `Comment` is scaffolded without also scaffolding `Post` in the same run.
/// A minimal stand-in table (just the `id` column the FK constraint checks
/// against) is enough to satisfy Postgres without duplicating the target's
/// full schema.
///
/// Skips `own_table` — a self-referential `references` field (e.g. a
/// `Category` model with a `category:references` field) targets the model's
/// own table, which is about to be created for real by the very next
/// statement. Postgres allows a self-referential FK within the same
/// `CREATE TABLE`, so no stub is needed there; emitting one anyway would
/// collide with the real (non-`IF NOT EXISTS`) `CREATE TABLE` that follows.
fn render_reference_stub_tables_sql(fields: &[Field], own_table: &str) -> String {
    let mut out = String::new();
    let mut seen = BTreeSet::new();
    for f in fields {
        if let Some(target) = f.reference_table()
            && target != own_table
            && seen.insert(target.clone())
        {
            let _ = writeln!(
                out,
                "CREATE TABLE IF NOT EXISTS {target} (id BIGSERIAL PRIMARY KEY);"
            );
            // Seed two rows (ids 1 and 2, since BIGSERIAL starts there) so a
            // NOT NULL `references` column pointing at this stub has a real
            // id to reference. Without at least one row, any raw INSERT the
            // smoke test issues against the table under test — e.g. the enum
            // out-of-set rejection test's deliberately-invalid INSERT, see
            // `enum_rejection_insert_sql` — would fail on this FK constraint
            // regardless of the column it's actually trying to exercise,
            // masking the real assertion behind an unrelated failure. The
            // second row exists for `unique_sample_literal_variant`: a
            // *non-target* `unique references` column in
            // `unique_violation_insert_sql`'s duplicate insert needs a
            // second real id, distinct from the target's own value, or it
            // would collide with itself across the two inserts the same way
            // the target column is meant to.
            let _ = writeln!(
                out,
                "INSERT INTO {target} DEFAULT VALUES;\nINSERT INTO {target} DEFAULT VALUES;"
            );
        }
    }
    out
}

/// Render the `tests/<snake>.rs` smoke test.
///
/// Delegates to [`render_index_smoke_test`] or [`render_api_smoke_test`]
/// depending on `api`, after computing the exact `CREATE TABLE`/`CREATE
/// INDEX` SQL the generated migration also emits (see
/// [`create_table_sql_with_metadata_and_id`]), so the throwaway table the
/// test creates in `TestDb` matches the real schema. Any `references` field
/// also gets a stub target table created first — see
/// [`render_reference_stub_tables_sql`].
#[allow(clippy::too_many_arguments)]
fn render_smoke_test(
    pascal_name: &str,
    plural: &str,
    api: bool,
    fields: &[Field],
    id_type: IdType,
    indexes: &BTreeSet<String>,
    defaults: &BTreeMap<String, String>,
    validations: &BTreeMap<String, Vec<String>>,
    authorize: bool,
) -> String {
    let stub_tables_sql = render_reference_stub_tables_sql(fields, plural);
    let create_table_sql =
        create_table_sql_with_metadata_and_id(plural, fields, indexes, defaults, id_type);
    let mut setup_calls = render_execute_sql_calls(&stub_tables_sql);
    setup_calls.push_str(&render_execute_sql_calls(&create_table_sql));
    let id_schema_type = id_type.schema_type();

    let base = if api {
        render_api_smoke_test(plural, id_schema_type, &setup_calls, fields, defaults)
    } else {
        render_index_smoke_test(pascal_name, plural, id_schema_type, &setup_calls)
    };

    let base = if fields.iter().any(Field::is_enum) {
        base + &render_enum_rejection_smoke_test(plural, fields, defaults, &setup_calls, api)
    } else {
        base
    };

    let unique_fields: Vec<&Field> = fields.iter().filter(|f| f.unique).collect();
    let base = if unique_fields.is_empty() {
        base
    } else {
        base + &render_unique_violation_smoke_test(
            plural,
            fields,
            &unique_fields,
            defaults,
            &setup_calls,
            api,
        )
    };

    // Issue #1124: prove the changeset round-trip on a real request — a
    // rejected submission gets 422 with the other field preserved and an
    // inline error, not a 400 dead-end. HTML scaffolds only; the `--api` JSON
    // path is out of scope (Problem Details already covers it, issue #598).
    let base = if !api && !validations.is_empty() {
        base + &render_validation_rejection_smoke_test(plural, validations)
    } else {
        base
    };

    // Issue #1127: exercise the full write path (create / update / delete +
    // validation-failure re-render) in-process. HTML scaffolds only — the
    // `--api` JSON resource tests are out of scope (folded into issue #1028).
    // Always emitted for HTML scaffolds (even without declared `--validate`
    // rules): the stand-in carries its own validated field, so a bare
    // `generate scaffold Post` still gets create/update/delete coverage.
    let base = if api {
        base
    } else {
        base + &render_write_path_smoke_test(pascal_name, plural)
    };

    // Issue #1236 (AC6): attachment scaffolds additionally get a multipart
    // write-path test that drives a zero-JS `multipart/form-data` create through
    // the real `Multipart` extractor, streams the uploaded file to a real
    // `LocalBlobStore`, persists the returned `Blob` in a real Postgres row, and
    // asserts the persisted attachment column bound a non-empty blob key.
    let base = if !api && has_attachment_fields(fields) {
        base + &render_attachment_multipart_write_path_smoke_test(plural, fields)
    } else {
        base
    };

    // Issue #1125 (AC4/AC6): when the scaffold authorizes its mutating handlers
    // (owner column, standard path), also emit a cross-user 403 demonstration.
    if authorize {
        base + &render_cross_user_forbidden_smoke_test(plural)
    } else {
        base
    }
}

/// A value that violates a `--validate` rule string (as rendered by
/// `model::render_validation_attr`, e.g. `"length(min = 1, max = 200)"`,
/// `"url"`, `"email"`) — used to build the deliberately-rejected submission in
/// [`render_validation_rejection_smoke_test`].
///
/// Returns `None` when the rule accepts *every* string, including blank — a
/// `length` rule with no `max` and either no `min` or `min = 0` (e.g.
/// `--validate title=length:min=0`) is a no-op that nothing can violate. The
/// caller must fall back to a different validated field rather than submit a
/// value that the real server would happily accept and assert a 422 anyway.
fn invalid_value_violating_rule(rule: &str) -> Option<String> {
    if rule == "url" {
        return Some("not a valid url".to_owned());
    }
    if rule == "email" {
        return Some("not-an-email".to_owned());
    }
    if let Some(args) = rule
        .strip_prefix("length(")
        .and_then(|s| s.strip_suffix(')'))
    {
        let mut min: Option<u64> = None;
        let mut max: Option<u64> = None;
        for part in args.split(',') {
            let part = part.trim();
            if let Some(n) = part.strip_prefix("min = ") {
                min = n.trim().parse().ok();
            } else if let Some(n) = part.strip_prefix("max = ") {
                max = n.trim().parse().ok();
            }
        }
        return match (min, max) {
            // A `min` bound is violated by submitting nothing at all.
            (Some(min), _) if min > 0 => Some(String::new()),
            // A `max`-only bound is violated by exceeding it by one character
            // — a fixed-size literal (e.g. 1000 `x`s) would itself satisfy a
            // looser `max` (say 2000), silently turning the "invalid"
            // submission valid and failing the smoke test's own 422 premise.
            (_, Some(max)) => Some("x".repeat(usize::try_from(max + 1).unwrap_or(usize::MAX))),
            // No `max`, and `min` is either absent or 0 — every string
            // (including blank) satisfies this rule; there is nothing to
            // violate.
            _ => None,
        };
    }
    None
}

/// Upper bound (in characters) on the sample literals
/// [`invalid_value_violating_rule`]/[`valid_value_satisfying_rule`] generate
/// for [`render_validation_rejection_smoke_test`]'s request bodies.
///
/// A declared `length:min=N`/`length:max=N` bound is an arbitrary
/// user-supplied `u64` with no upper limit enforced by the DSL parser — a
/// scaffold like `--validate title=length:min=1000000000` would otherwise
/// have the *generator* (not the generated app) allocate a multi-GB string
/// while rendering the smoke test, before a single file is even written.
/// [`length_bound_exceeds_sample_cap`] gates smoke-test emission on this
/// instead of silently truncating the sample (a truncated sample would
/// satisfy neither a huge `min` — too short — nor accurately violate a huge
/// `max`, making the generated test assert something false).
const MAX_GENERATED_VALIDATION_SAMPLE_LEN: u64 = 4096;

/// Whether a `length(...)` validation rule's declared bound(s) exceed
/// [`MAX_GENERATED_VALIDATION_SAMPLE_LEN`] — see that constant's doc comment.
/// Always `false` for non-length rules (`url`/`email` samples are small,
/// fixed-size literals).
fn length_bound_exceeds_sample_cap(rule: &str) -> bool {
    let Some(args) = rule
        .strip_prefix("length(")
        .and_then(|s| s.strip_suffix(')'))
    else {
        return false;
    };
    args.split(',').any(|part| {
        let part = part.trim();
        part.strip_prefix("min = ")
            .or_else(|| part.strip_prefix("max = "))
            .and_then(|n| n.trim().parse::<u64>().ok())
            .is_some_and(|bound| bound > MAX_GENERATED_VALIDATION_SAMPLE_LEN)
    })
}

/// A value that *satisfies* a `--validate` rule string — the counterpart to
/// [`invalid_value_violating_rule`], used to build the successful submission
/// in [`render_validation_rejection_smoke_test`]. A fixed literal like `"a
/// valid value"` isn't valid for every rule (e.g. it's neither a URL/email,
/// nor within a tight `length:max=5` or `length:min=20` bound), so this
/// derives a value that actually fits the declared rule instead.
fn valid_value_satisfying_rule(rule: &str) -> String {
    if rule == "url" {
        return "https://example.com".to_owned();
    }
    if rule == "email" {
        return "person@example.com".to_owned();
    }
    if let Some(args) = rule
        .strip_prefix("length(")
        .and_then(|s| s.strip_suffix(')'))
    {
        let mut min: Option<u64> = None;
        let mut max: Option<u64> = None;
        for part in args.split(',') {
            let part = part.trim();
            if let Some(n) = part.strip_prefix("min = ") {
                min = n.trim().parse().ok();
            } else if let Some(n) = part.strip_prefix("max = ") {
                max = n.trim().parse().ok();
            }
        }
        let len = match (min, max) {
            (Some(min), Some(max)) => min.max(1).min(max),
            (Some(min), None) => min.max(1),
            (None, Some(max)) => max,
            (None, None) => 1,
        };
        return "a".repeat(usize::try_from(len).unwrap_or(usize::MAX));
    }
    "a valid value".to_owned()
}

/// Render a `#[tokio::test]` proving issue #1124's core guarantee: a
/// submission that violates a declared `--validate` rule gets HTTP 422 with
/// the *other* submitted field preserved and an inline `role="alert"` error
/// message — not a 400 dead-end with input lost — and a fully valid
/// submission still succeeds.
///
/// Like [`render_unique_violation_smoke_test`]'s request-boundary check, this
/// redeclares a stand-in handler rather than importing the project's own code
/// (a `tests/*.rs` integration binary can't import a binary crate's modules —
/// see `docs/guide/tutorial/11-testing.md`). Unlike that raw-SQL stand-in,
/// this one uses the real, shipped `ChangesetForm`/`Changeset` extractor and
/// `text_input` helper directly — the exact mechanism the generated
/// `create`/`update` handlers are built on — so it needs no database at all;
/// it proves the round-trip mechanism itself, independent of the specific
/// scaffolded model's other field kinds (already exercised by the other
/// generated smoke tests).
fn render_validation_rejection_smoke_test(
    plural: &str,
    validations: &BTreeMap<String, Vec<String>>,
) -> String {
    // Pick the first validated field whose declared rule actually has a
    // violating value: a no-op rule (e.g. `length:min=0` with no `max`
    // accepts every string, including blank) or one whose bound exceeds
    // `MAX_GENERATED_VALIDATION_SAMPLE_LEN` (see that constant's doc comment)
    // can't build a real "rejected" submission, so it's skipped in favor of
    // another validated field rather than asserting a 422 the real server
    // would never return.
    let Some((target_name, rule, invalid_value)) = validations.iter().find_map(|(name, rules)| {
        let rule = rules.first().cloned().unwrap_or_default();
        if length_bound_exceeds_sample_cap(&rule) {
            return None;
        }
        let invalid_value = invalid_value_violating_rule(&rule)?;
        Some((name, rule, invalid_value))
    }) else {
        return String::new();
    };
    let valid_value = valid_value_satisfying_rule(&rule);
    let witness_value = "preserved-witness-value";

    format!(
        "\n#[tokio::test]\n\
         async fn {plural}_rejects_invalid_{target_name}_and_preserves_input() {{\n\
         \x20\x20\x20\x20use autumn_web::form::ChangesetForm;\n\
         \x20\x20\x20\x20use autumn_web::test::{{TestApp, TestClient}};\n\
         \n\
         \x20\x20\x20\x20#[derive(serde::Deserialize, serde::Serialize, Default, validator::Validate, Clone)]\n\
         \x20\x20\x20\x20struct Form {{\n\
         \x20\x20\x20\x20\x20\x20\x20\x20#[validate({rule})]\n\
         \x20\x20\x20\x20\x20\x20\x20\x20{target_name}: String,\n\
         \x20\x20\x20\x20\x20\x20\x20\x20other_field: String,\n\
         \x20\x20\x20\x20}}\n\
         \n\
         \x20\x20\x20\x20#[post(\"/{plural}\")]\n\
         \x20\x20\x20\x20async fn create(form: ChangesetForm<Form>) -> impl IntoResponse {{\n\
         \x20\x20\x20\x20\x20\x20\x20\x20match form.into_valid() {{\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Ok(_) => StatusCode::OK.into_response(),\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Err(form) => (\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20StatusCode::UNPROCESSABLE_ENTITY,\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20html! {{\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(autumn_web::form::text_input(&form.changeset, \"{target_name}\", \"{target_name}\"))\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(autumn_web::form::text_input(&form.changeset, \"other_field\", \"other_field\"))\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20}},\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20).into_response(),\n\
         \x20\x20\x20\x20\x20\x20\x20\x20}}\n\
         \x20\x20\x20\x20}}\n\
         \n\
         \x20\x20\x20\x20let client: TestClient = TestApp::new().routes(routes![create]).build();\n\
         \n\
         \x20\x20\x20\x20// A submission violating the declared rule must respond 422, echo the\n\
         \x20\x20\x20\x20// *other* field's submitted value (input is preserved, not lost), and\n\
         \x20\x20\x20\x20// carry an inline, accessible error message (AC2, AC3, AC4).\n\
         \x20\x20\x20\x20let invalid_body = format!(\"{target_name}={invalid_value}&other_field={witness_value}\");\n\
         \x20\x20\x20\x20client.post(\"/{plural}\").form(&invalid_body).send().await\n\
         \x20\x20\x20\x20\x20\x20\x20\x20.assert_status(422)\n\
         \x20\x20\x20\x20\x20\x20\x20\x20.assert_body_contains(\"{witness_value}\")\n\
         \x20\x20\x20\x20\x20\x20\x20\x20.assert_body_contains(\"role=\\\"alert\\\"\");\n\
         \n\
         \x20\x20\x20\x20// A fully valid submission still succeeds (AC5).\n\
         \x20\x20\x20\x20let valid_body = format!(\"{target_name}={valid_value}&other_field={witness_value}\");\n\
         \x20\x20\x20\x20client.post(\"/{plural}\").form(&valid_body).send().await\n\
         \x20\x20\x20\x20\x20\x20\x20\x20.assert_status(200);\n\
         }}\n"
    )
}

/// Render the write-path portion of `tests/<snake>.rs` (issue #1127): one
/// in-process `#[tokio::test]` that exercises the full mutating surface —
/// create (happy path), update, delete, AND the validation-failure re-render —
/// through `autumn_web::test::{TestApp, TestClient}`.
///
/// Like the read index smoke test, this redeclares a *stand-in* CRUD resource
/// rather than importing the project's own handlers (a `tests/*.rs` integration
/// binary can't import a binary crate's modules — see
/// `docs/guide/tutorial/11-testing.md`). It proves the write-path *request
/// mechanism* on the real, shipped primitives the generated handlers are built
/// on — the `ChangesetForm`/`Changeset` round-trip (issue #1124), the typed
/// `text_input` renderer, and `Redirect` — independent of the specific model's
/// columns (already exercised by the other generated smoke tests). Its redirect
/// contract mirrors the generated handlers exactly: those now redirect with
/// `Redirect::to(...)` (a real 303 See Other with a `Location` header), the same
/// primitive `docs/guide/path-helpers.md` recommends over a meta-refresh page —
/// create/delete to the index route, update to the show route:
///
/// * a valid `POST` redirects (303 See Other) to the index route and the row is
///   observable on a follow-up read (create);
/// * a `POST` to the `/{id}/update` route redirects (303) to the show route and
///   the change is observable on a follow-up read (update);
/// * a `POST` to the generated `/{id}/delete` HTML action (issue #1021)
///   redirects (303) and the row is gone on the next read (delete);
/// * an invalid `POST` re-renders the form at 422 with the submitted input
///   preserved and an inline `role="alert"` error — it does NOT redirect and
///   does NOT persist (validation failure, issue #1124).
///
/// It needs no database: a process-local in-memory store stands in for the
/// persistence layer, so the whole write-path suite runs in-process with zero
/// external services and is a visible green (never `#[ignore]`d) — the row-count
/// assertions on each read give it real failure power, so a broken handler (a
/// 200 instead of a redirect, a no-op delete, a create that skips validation)
/// turns it red.
///
/// CSRF: `TestApp::new()` disables CSRF (like Spring Security's test support),
/// so these same-origin form `POST`s carry no `_csrf` token. The real,
/// `form_for`-rendered forms (PR #1587) auto-inject a hidden CSRF field for the
/// browser; the in-process harness does not require it, and this comment
/// records that so the absent token reads as intentional, not a gap.
#[allow(clippy::too_many_lines)] // the emitted test body is one raw-string template
fn render_write_path_smoke_test(pascal_name: &str, plural: &str) -> String {
    const TEMPLATE: &str = r#"
// ── write-path CRUD (issue #1127) ─────────────────────────────────────────
//
// Exercises create / update / delete and the validation-failure re-render in
// one in-process test against a stand-in resource. `TestApp::new()` disables
// CSRF, so these same-origin form POSTs need no `_csrf` token (the real
// form_for-rendered forms inject one for the browser; PR #1587).
#[tokio::test]
async fn __PLURAL___write_path_crud() {
    use autumn_web::test::{TestApp, TestClient};

    // A process-local, in-memory stand-in for the persistence layer: `(id, name)`
    // rows shared across requests within this test. No database required.
    static STORE: std::sync::Mutex<Vec<(i64, String)>> = std::sync::Mutex::new(Vec::new());

    #[derive(serde::Deserialize, serde::Serialize, Default, validator::Validate, Clone)]
    struct Form {
        #[validate(length(min = 1, message = "must not be blank"))]
        name: String,
        witness: String,
    }

    #[get("/__PLURAL__")]
    async fn index() -> Markup {
        let store = STORE.lock().unwrap();
        let count = store.len() as i64;
        html! {
            h1 { "__PLURAL__" }
            p { (count) " row(s)" }
            ul { @for (_, name) in store.iter() { li { (name.as_str()) } } }
        }
    }

    #[post("/__PLURAL__")]
    async fn create(form: ChangesetForm<Form>) -> impl IntoResponse {
        match form.into_valid() {
            Ok(valid) => {
                let mut store = STORE.lock().unwrap();
                let id = store.iter().map(|(i, _)| *i).max().unwrap_or(0) + 1;
                store.push((id, valid.name));
                Redirect::to("/__PLURAL__").into_response()
            }
            Err(form) => (
                StatusCode::UNPROCESSABLE_ENTITY,
                html! {
                    (autumn_web::form::text_input(&form.changeset, "name", "name"))
                    (autumn_web::form::text_input(&form.changeset, "witness", "witness"))
                },
            )
                .into_response(),
        }
    }

    #[post("/__PLURAL__/{id}/update")]
    async fn update(id: Path<i64>, form: ChangesetForm<Form>) -> impl IntoResponse {
        let valid = match form.into_valid() {
            Ok(valid) => valid,
            Err(_) => return StatusCode::UNPROCESSABLE_ENTITY.into_response(),
        };
        {
            let mut store = STORE.lock().unwrap();
            if let Some(row) = store.iter_mut().find(|(i, _)| *i == *id) {
                row.1 = valid.name;
            }
        }
        // Mirror the generated handler: update redirects to the show route.
        Redirect::to(&format!("/__PLURAL__/{}", *id)).into_response()
    }

    #[post("/__PLURAL__/{id}/delete")]
    async fn destroy(id: Path<i64>) -> impl IntoResponse {
        STORE.lock().unwrap().retain(|(i, _)| *i != *id);
        Redirect::to("/__PLURAL__")
    }

    let client: TestClient = TestApp::new()
        .routes(routes![index, create, update, destroy])
        .build();

    // Create (happy path): a valid POST redirects (303 See Other) to the index
    // route and the row is persisted — a follow-up read shows it.
    client
        .post("/__PLURAL__")
        .form("name=first-record&witness=w")
        .send()
        .await
        .assert_status(303)
        .assert_header("location", "/__PLURAL__");
    client
        .get("/__PLURAL__")
        .send()
        .await
        .assert_ok()
        .assert_body_contains("first-record")
        .assert_body_contains("1 row(s)");

    // Validation failure: an invalid create re-renders the form at 422 with the
    // submitted input preserved and an inline error — it does NOT redirect and
    // does NOT persist (the row count stays at 1).
    client
        .post("/__PLURAL__")
        .form("name=&witness=kept-on-error")
        .send()
        .await
        .assert_status(422)
        .assert_body_contains("kept-on-error")
        .assert_body_contains("role=\"alert\"");
    client
        .get("/__PLURAL__")
        .send()
        .await
        .assert_body_contains("1 row(s)");

    // Update (happy path): a POST of changed fields redirects (303) to the show
    // route and the change is observable on a subsequent read. The row count is
    // unchanged, so the value was replaced in place, not appended.
    client
        .post("/__PLURAL__/1/update")
        .form("name=second-record&witness=w")
        .send()
        .await
        .assert_status(303)
        .assert_header("location", "/__PLURAL__/1");
    client
        .get("/__PLURAL__")
        .send()
        .await
        .assert_body_contains("second-record")
        .assert_body_contains("1 row(s)");

    // Delete: the generated HTML delete action removes the row — a POST to the
    // `/delete` route redirects and the row is gone on the next index read.
    client
        .post("/__PLURAL__/1/delete")
        .send()
        .await
        .assert_status(303)
        .assert_header("location", "/__PLURAL__");
    client
        .get("/__PLURAL__")
        .send()
        .await
        .assert_body_contains("0 row(s)");
}
"#;
    TEMPLATE
        .replace("__PASCAL__", pascal_name)
        .replace("__PLURAL__", plural)
}

/// Render the multipart attachment write-path smoke test (issue #1236, AC6).
///
/// Emitted alongside [`render_write_path_smoke_test`] whenever a scaffold has at
/// least one attachment field, and follows the same #1127 in-process style: a
/// process-local stand-in for the persistence layer, no database required, so it
/// runs green without Docker (unlike the `TestDb`-backed index/api smoke tests,
/// which are `#[ignore]`d). It drives a zero-JS `multipart/form-data` create
/// through the real `Multipart` extractor and
/// the real `save_to_blob_store` against a real
/// [`LocalBlobStore`](autumn_web::storage::LocalBlobStore), binds the returned
/// `Blob` on the record, then asserts the persisted record's attachment column
/// holds a non-empty blob key — the AC's literal requirement ("the blob key is
/// bound") — AND that the uploaded bytes actually landed in the store at that
/// key. The handler is an in-test stand-in (a `tests/` binary cannot import the
/// project's own routes) that runs the SAME blob path the generated `create`
/// handler runs.
#[allow(clippy::too_many_lines)] // the emitted test body is one raw-string template
fn render_attachment_multipart_write_path_smoke_test(plural: &str, fields: &[Field]) -> String {
    const TEMPLATE: &str = r#"

// ── multipart attachment write-path (issue #1236, AC6) ─────────────────────
//
// Follows the #1127 in-process write-path style (a process-local stand-in for
// the persistence layer, no database required, so it runs without Docker): a
// zero-JS `multipart/form-data` create drives the REAL `Multipart` extractor
// and the REAL `save_to_blob_store` against a REAL `LocalBlobStore`, binds the
// returned `Blob` on the record, and asserts the persisted record's attachment
// column holds a non-empty blob key AND that the uploaded bytes actually landed
// in the store at that key. The handler is an in-test stand-in (a `tests/`
// binary cannot import the project's own routes) that runs the SAME blob path
// the generated `create` handler runs. `TestApp::new()` disables CSRF, so the
// hand-built body carries no `_csrf` part (the real prod form injects one).
#[tokio::test]
async fn __PLURAL___multipart_upload_binds_blob_key() {
    use autumn_web::storage::local::SigningKey;
    use autumn_web::storage::{BlobStore, BlobStoreState, LocalBlobStore};

    // Process-local stand-in for the persistence layer: the attachment `Blob`
    // bound on each created record (mirrors the `New{Pascal}.{attachment}`
    // column the generated `create` handler sets). No database required.
    static STORE: std::sync::Mutex<Vec<autumn_web::storage::Blob>> =
        std::sync::Mutex::new(Vec::new());

    #[post("/__PLURAL__/upload-probe")]
    async fn create(
        autumn_web::extract::State(state): autumn_web::extract::State<autumn_web::AppState>,
        mut multipart: autumn_web::extract::Multipart,
    ) -> AutumnResult<Redirect> {
        let store = state
            .extension::<BlobStoreState>()
            .expect("blob store configured")
            .store()
            .clone();
        while let Some(field) = multipart.next_field().await? {
            if field.name() == Some("__ATTACH__")
                && field.file_name().is_some_and(|name| !name.is_empty())
            {
                let nanos = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_nanos())
                    .unwrap_or_default();
                let key = format!("__PLURAL__/__ATTACH__/{nanos}");
                let blob = field.save_to_blob_store(&*store, key).await?;
                STORE.lock().unwrap().push(blob);
            }
        }
        Ok(Redirect::to("/__PLURAL__"))
    }

    // A real on-disk blob store so `save_to_blob_store` has a backend.
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or_default();
    let blob_root = std::env::temp_dir().join(format!("__PLURAL__-blob-probe-{nanos}"));
    let blob_store = std::sync::Arc::new(
        LocalBlobStore::new(
            "test",
            blob_root.clone(),
            "/_blobs",
            std::time::Duration::from_secs(60),
            SigningKey::new(b"test-signing-key".to_vec()),
            Vec::new(),
        )
        .expect("build local blob store"),
    );
    let store_handle = blob_store.clone();

    let client: TestClient = TestApp::new()
        .routes(routes![create])
        .state_initializer(move |state| {
            state.insert_extension(BlobStoreState::new(blob_store.clone()));
        })
        .build();

    // Hand-built multipart body (TestClient has no `.multipart()` helper): a
    // text part for a sibling field plus a file part for the attachment field.
    let body = "--BOUND\r\n\
Content-Disposition: form-data; name=\"__TEXT_FIELD__\"\r\n\r\n\
hello\r\n\
--BOUND\r\n\
Content-Disposition: form-data; name=\"__ATTACH__\"; filename=\"upload.png\"\r\n\
Content-Type: image/png\r\n\r\n\
not-an-empty-file\r\n\
--BOUND--\r\n";

    // The multipart create succeeds and redirects (303), exactly like the real
    // generated attachment handler.
    client
        .post("/__PLURAL__/upload-probe")
        .header("content-type", "multipart/form-data; boundary=BOUND")
        .body(body.to_owned())
        .send()
        .await
        .assert_status(303)
        .assert_header("location", "/__PLURAL__");

    // The persisted record bound a non-empty blob key with the expected prefix.
    let bound = STORE
        .lock()
        .unwrap()
        .last()
        .cloned()
        .expect("a record was created with an attachment blob");
    assert!(
        !bound.key.is_empty(),
        "the attachment column must bind a non-empty blob key"
    );
    assert!(
        bound.key.starts_with("__PLURAL__/__ATTACH__/"),
        "bound key: {}",
        bound.key
    );

    // The uploaded bytes actually landed in the store at the bound key.
    let stored_bytes = store_handle
        .get(&bound.key)
        .await
        .expect("blob present in store at the bound key");
    assert_eq!(&stored_bytes[..], b"not-an-empty-file");

    let _ = std::fs::remove_dir_all(&blob_root);
}
"#;
    let attach = fields
        .iter()
        .find(|f| f.kind.is_attachment())
        .map_or("attachment", |f| f.name.as_str());
    // A sibling non-attachment field name for a realistic mixed multipart body
    // (a text part alongside the file part); the stand-in handler ignores it.
    let text_field = fields
        .iter()
        .find(|f| !f.kind.is_attachment())
        .map_or("note", |f| f.name.as_str());
    TEMPLATE
        .replace("__PLURAL__", plural)
        .replace("__ATTACH__", attach)
        .replace("__TEXT_FIELD__", text_field)
}

/// Render the cross-user record-level-authorization smoke test (issue #1125,
/// AC4/AC6): with an owner column present, a user may only update/delete rows
/// they own. A stand-in resource seeded with a row owned by user A is exercised
/// while acting as user B — the mutating routes must be forbidden (403, via the
/// test-level `ForbiddenResponse::Forbidden403`
/// override so the demonstration asserts a concrete 403 rather than the app-wide
/// default hide-existence 404) and B's index must exclude A's rows. Then acting
/// as the owner (A), the same update succeeds. Self-contained (a process-local
/// store stands in for the database), so it runs in-process with no external
/// services, exactly like the write-path CRUD test above.
#[allow(clippy::too_many_lines)] // the emitted test body is one raw-string template
fn render_cross_user_forbidden_smoke_test(plural: &str) -> String {
    const TEMPLATE: &str = r#"

// ── cross-user record-level authorization (issue #1125) ───────────────────
//
// Owner-or-admin update/delete. A row owned by user A is off-limits to user B:
// B's update/delete are forbidden (403) and B's index excludes A's rows, while
// the owner (A) is allowed. `TestApp::new()` disables CSRF; the 403 comes from
// the registered policy + the `ForbiddenResponse::Forbidden403` test override.
#[tokio::test]
async fn __PLURAL___cross_user_mutations_are_forbidden() {
    use autumn_web::authorization::{authorize, BoxFuture, Policy, PolicyContext};
    use autumn_web::test::{TestApp, TestClient};

    #[derive(Clone)]
    struct OwnedRow {
        id: i64,
        owner_id: i64,
    }

    // Process-local stand-in for the persistence layer.
    static STORE: std::sync::Mutex<Vec<OwnedRow>> = std::sync::Mutex::new(Vec::new());

    fn find_row(id: i64) -> Option<OwnedRow> {
        STORE.lock().unwrap().iter().find(|r| r.id == id).cloned()
    }

    #[derive(Default)]
    struct OwnedRowPolicy;

    impl Policy<OwnedRow> for OwnedRowPolicy {
        fn can_update<'a>(&'a self, ctx: &'a PolicyContext, row: &'a OwnedRow) -> BoxFuture<'a, bool> {
            Box::pin(async move { ctx.has_role("admin") || ctx.user_id_i64() == Some(row.owner_id) })
        }
        fn can_delete<'a>(&'a self, ctx: &'a PolicyContext, row: &'a OwnedRow) -> BoxFuture<'a, bool> {
            Box::pin(async move { ctx.has_role("admin") || ctx.user_id_i64() == Some(row.owner_id) })
        }
    }

    #[secured]
    #[get("/owned")]
    async fn index(
        autumn_web::extract::State(state): autumn_web::extract::State<autumn_web::AppState>,
        session: autumn_web::session::Session,
    ) -> autumn_web::AutumnResult<autumn_web::Markup> {
        let ctx = PolicyContext::from_request(&state, &session).await;
        let me = ctx.user_id_i64().unwrap_or(-1);
        let ids: Vec<i64> = STORE
            .lock()
            .unwrap()
            .iter()
            .filter(|r| r.owner_id == me)
            .map(|r| r.id)
            .collect();
        Ok(autumn_web::html! { @for id in &ids { p { "owned-row-" (id) } } })
    }

    #[secured]
    #[post("/owned/{id}/update")]
    async fn update(
        id: autumn_web::extract::Path<i64>,
        autumn_web::extract::State(state): autumn_web::extract::State<autumn_web::AppState>,
        session: autumn_web::session::Session,
    ) -> autumn_web::AutumnResult<autumn_web::Redirect> {
        let row = find_row(*id).ok_or_else(|| autumn_web::AutumnError::not_found_msg("not found"))?;
        authorize::<OwnedRow>(&state, &session, "update", &row).await?;
        Ok(autumn_web::Redirect::to("/owned"))
    }

    #[secured]
    #[post("/owned/{id}/delete")]
    async fn destroy(
        id: autumn_web::extract::Path<i64>,
        autumn_web::extract::State(state): autumn_web::extract::State<autumn_web::AppState>,
        session: autumn_web::session::Session,
    ) -> autumn_web::AutumnResult<autumn_web::Redirect> {
        let row = find_row(*id).ok_or_else(|| autumn_web::AutumnError::not_found_msg("not found"))?;
        authorize::<OwnedRow>(&state, &session, "delete", &row).await?;
        STORE.lock().unwrap().retain(|r| r.id != *id);
        Ok(autumn_web::Redirect::to("/owned"))
    }

    {
        let mut store = STORE.lock().unwrap();
        store.clear();
        // Row 1 is owned by user A (id 1).
        store.push(OwnedRow { id: 1, owner_id: 1 });
    }

    let client: TestClient = TestApp::new()
        .routes(routes![index, update, destroy])
        .policy::<OwnedRow, _>(OwnedRowPolicy::default())
        .forbidden_response(autumn_web::authorization::ForbiddenResponse::Forbidden403)
        .build();

    // Acting as user B (id 2), who owns nothing.
    client.acting_as(2).await;

    // B cannot update or delete A's row.
    client.post("/owned/1/update").send().await.assert_status(403);
    client.post("/owned/1/delete").send().await.assert_status(403);

    // B's index excludes A's rows.
    let body = client.get("/owned").send().await.assert_ok().text();
    assert!(!body.contains("owned-row-1"), "B must not see A's row: {body}");

    // The owner (A, id 1) is allowed to update their own row.
    client.acting_as(1).await;
    client.post("/owned/1/update").send().await.assert_status(303);
}
"#;
    TEMPLATE.replace("__PLURAL__", plural)
}

/// A representative non-`NULL` literal for a `FieldKind`, used to fill in the
/// "other" `NOT NULL` columns of the raw `INSERT` [`render_enum_rejection_smoke_test`]
/// issues directly against the database — every column but the one under
/// test needs *some* valid value so the `INSERT`'s failure is attributable to
/// the target enum column's `CHECK` constraint rather than some other
/// required column being left out.
fn sql_sample_literal(kind: FieldKind) -> String {
    match kind {
        // `Enum`'s "'sample'" here is never actually used: `enum_rejection_insert_sql`
        // special-cases every enum column (the field under test gets the
        // deliberately out-of-set literal; any *other* required enum column
        // gets one of its own real variants instead — see that function).
        FieldKind::String | FieldKind::Text | FieldKind::Enum => "'sample'".to_owned(),
        FieldKind::I32 | FieldKind::I64 | FieldKind::References => "1".to_owned(),
        FieldKind::Bool => "TRUE".to_owned(),
        FieldKind::F32 | FieldKind::F64 => "1.0".to_owned(),
        // Scale-derived rather than a fixed "1.0": a tightly-scaled column
        // like `decimal{1,1}` (valid range `(-1,1)`) would reject a literal
        // "1.0" with a numeric field overflow — see `decimal_literal_at_scale`.
        FieldKind::Decimal { scale, .. } => decimal_literal_at_scale(scale, 1),
        FieldKind::Uuid => "gen_random_uuid()".to_owned(),
        FieldKind::NaiveDateTime | FieldKind::DateTime => "NOW()".to_owned(),
        FieldKind::Bytea => "'\\x00'::bytea".to_owned(),
        // Always nullable (see `FieldKind::Attachment`'s doc comment), so it
        // never needs a sample literal to satisfy a `NOT NULL` constraint.
        FieldKind::Attachment => "NULL".to_owned(),
    }
}

/// How many rows the `--api` smoke test seeds. More than the default page size
/// (20) so the paginated list is guaranteed to span multiple pages regardless
/// of the `size` the test happens to request.
const API_SMOKE_TEST_SEED_ROWS: usize = 25;

/// A per-row seed value expression for a required column in the `--api` smoke
/// test's [`render_api_seed_sql`] INSERT, written in terms of the
/// `generate_series` index bound to `g` (1..=[`API_SMOKE_TEST_SEED_ROWS`]).
///
/// The index is woven into the value for the types that can vary it while
/// staying valid (text, integers, floats, timestamps) so that a `unique`
/// column of one of those types does not collide across the seeded rows; the
/// remaining types fall back to [`sql_sample_literal`]'s constant sample.
/// Those constant types (enum's closed set, a `references` FK id, bool,
/// decimal at a fixed scale, bytea) cannot hold [`API_SMOKE_TEST_SEED_ROWS`]
/// distinct values anyway — an inherent limit that only matters for the
/// unusual scaffold declaring a `unique` column of such a type, where no
/// seeding strategy could satisfy the constraint. `uuid` needs no special
/// case: its `sql_sample_literal` is `gen_random_uuid()`, already distinct
/// per row.
fn sql_seed_value_expr(f: &Field) -> String {
    match f.kind {
        FieldKind::String | FieldKind::Text => "'sample-' || g".to_owned(),
        FieldKind::I32 | FieldKind::I64 => "g".to_owned(),
        FieldKind::F32 | FieldKind::F64 => "g::double precision".to_owned(),
        FieldKind::NaiveDateTime | FieldKind::DateTime => {
            "NOW() + (g || ' seconds')::interval".to_owned()
        }
        // Enum must stay inside its declared set — pick a real variant.
        FieldKind::Enum => {
            format!("'{}'", f.variants.first().expect("enum field has variants"))
        }
        _ => sql_sample_literal(f.kind),
    }
}

/// Build the raw seed `INSERT` for the `--api` smoke test:
/// [`API_SMOKE_TEST_SEED_ROWS`] rows, each with a valid, per-row-varying value
/// for every required (`NOT NULL`, no `DEFAULT`) column — see
/// [`sql_seed_value_expr`].
///
/// Unlike a bare `INSERT ... DEFAULT VALUES`, this satisfies a required column
/// that has no database default (e.g. the `title:string` a plain
/// `autumn generate scaffold Post title:string --api` produces), which
/// `DEFAULT VALUES` cannot — it would fail at runtime on the `NOT NULL`
/// constraint. A single `generate_series(1, N)` drives the row count and its
/// index `g` varies the values.
///
/// When the model has no required columns at all (every field nullable or
/// defaulted, e.g. a fieldless scaffold), it emits N separate
/// `INSERT INTO <plural> DEFAULT VALUES` statements instead — the case the old
/// `INSERT ... DEFAULT VALUES` covered. A single targetless
/// `INSERT ... SELECT FROM generate_series` would be *invalid* here: a
/// zero-column `SELECT` is matched against every table column (`id` included)
/// and fails at runtime with a column-count mismatch rather than inserting N
/// default rows.
fn render_api_seed_sql(
    plural: &str,
    fields: &[Field],
    defaults: &BTreeMap<String, String>,
) -> String {
    let mut columns = Vec::new();
    let mut values = Vec::new();
    for f in fields {
        if !f.nullable && !defaults.contains_key(&f.name) {
            columns.push(f.name.clone());
            values.push(sql_seed_value_expr(f));
        }
    }
    let n = API_SMOKE_TEST_SEED_ROWS;
    if columns.is_empty() {
        // N all-default rows, one valid `DEFAULT VALUES` insert each. The
        // smoke test's setup path (`render_execute_sql_calls`) splits these
        // into one `db.execute_sql(...)` call per statement.
        vec![format!("INSERT INTO {plural} DEFAULT VALUES"); n].join(";\n")
    } else {
        format!(
            "INSERT INTO {plural} ({}) SELECT {} FROM generate_series(1, {n}) AS g",
            columns.join(", "),
            values.join(", ")
        )
    }
}

/// Build a raw `INSERT INTO <plural> (...)` statement that sets `target`'s
/// enum column to a value guaranteed to be outside its declared variant set,
/// and every other required (`NOT NULL`, no `DEFAULT`) column to a valid
/// sample value — see [`sql_sample_literal`].
fn enum_rejection_insert_sql(
    plural: &str,
    fields: &[Field],
    target: &Field,
    defaults: &BTreeMap<String, String>,
) -> String {
    let mut columns = Vec::new();
    let mut values = Vec::new();
    for f in fields {
        if f.name == target.name {
            columns.push(f.name.clone());
            values.push("'__not_a_real_variant__'".to_owned());
        } else if !f.nullable && !defaults.contains_key(&f.name) {
            columns.push(f.name.clone());
            // A scaffold can have more than one required enum column; the
            // generic `sql_sample_literal` fallback ("'sample'") isn't a
            // real variant of any *other* enum field's own closed set, which
            // would trip that field's CHECK too and muddy which column's
            // constraint actually failed.
            let value = if f.is_enum() {
                format!("'{}'", f.variants.first().expect("enum field has variants"))
            } else {
                sql_sample_literal(f.kind)
            };
            values.push(value);
        }
    }
    format!(
        "INSERT INTO {plural} ({}) VALUES ({})",
        columns.join(", "),
        values.join(", ")
    )
}

/// Render one `#[ignore]`d `#[tokio::test]` per enum field that asserts the
/// closed set is enforced at both layers (issue #1030's success metric):
///
/// 1. A raw `INSERT` (bypassing the app entirely) with an out-of-set value
///    for the field must fail — proving the database-level `CHECK`
///    constraint, independent of any application code.
/// 2. For an HTML (non-`--api`) scaffold, a stand-in `POST` handler — same
///    convention as [`render_index_smoke_test`]'s stand-in `GET` handler —
///    rejects an out-of-set form value with `400` naming the field, proving
///    the request-boundary validation (issue #1030's `--query`-free path
///    through `decode_form`'s `FromStr` parse, reproduced here since a
///    `tests/*.rs` binary cannot import the project's own handler code).
/// 3. Either way, the table ends up with zero rows.
fn render_enum_rejection_smoke_test(
    plural: &str,
    fields: &[Field],
    defaults: &BTreeMap<String, String>,
    setup_calls: &str,
    api: bool,
) -> String {
    // `setup_calls` is shared with (and identical to) the base index/api
    // smoke test's own setup, which issues a plain, non-idempotent
    // `CREATE TABLE {plural} (...)` and, for any `--index`/`references`
    // field, a plain `CREATE INDEX idx_{plural}_{field} ...` (matching the
    // real migration). Both tests run against the same `TestDb::shared()`
    // Postgres container in the same test binary, so whichever one runs
    // second would hit "relation already exists" — make *this* test's own
    // copies of both statement kinds idempotent so it works whether it runs
    // alongside the base test or standalone (e.g. `cargo test
    // posts_rejects_out_of_set_status -- --ignored`). The reference-stub-table
    // `CREATE TABLE`s are already `IF NOT EXISTS` (see
    // `render_reference_stub_tables_sql`), so only the main table's statement
    // needs the same treatment; `CREATE INDEX` has no per-index counterpart
    // to worry about, so every occurrence is rewritten.
    let setup_calls = setup_calls.replacen(
        &format!("CREATE TABLE {plural} ("),
        &format!("CREATE TABLE IF NOT EXISTS {plural} ("),
        1,
    );
    let setup_calls = setup_calls.replace("CREATE INDEX idx_", "CREATE INDEX IF NOT EXISTS idx_");
    let setup_calls = setup_calls.as_str();
    let mut out = String::new();
    for target in fields.iter().filter(|f| f.is_enum()) {
        let field_name = &target.name;
        let insert_sql = enum_rejection_insert_sql(plural, fields, target, defaults);
        let escaped_insert = escape_sql_for_rust_literal(&insert_sql);
        let allowed_values = target
            .variants
            .iter()
            .map(|v| format!("\"{v}\""))
            .collect::<Vec<_>>()
            .join(" | ");

        let request_boundary_check = if api {
            String::new()
        } else {
            format!(
                "#[post(\"/{plural}\")]\n\
                 async fn create(body: autumn_web::reexports::axum::body::Bytes) -> AutumnResult<&'static str> {{\n\
                 \x20\x20\x20\x20let value = url::form_urlencoded::parse(body.as_ref())\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20.find(|(k, _)| k == \"{field_name}\")\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20.map(|(_, v)| v.into_owned())\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20.unwrap_or_default();\n\
                 \x20\x20\x20\x20if !matches!(value.as_str(), {allowed_values}) {{\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20return Err(AutumnError::bad_request_msg(format!(\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\"{field_name}: must be one of {variants_display}\"\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20)));\n\
                 \x20\x20\x20\x20}}\n\
                 \x20\x20\x20\x20Ok(\"ok\")\n\
                 }}\n\
                 \n\
                 \x20\x20\x20\x20let client: TestClient = TestApp::new().routes(routes![create]).with_db(db.pool()).build();\n\
                 \n\
                 \x20\x20\x20\x20client.post(\"/{plural}\").form(\"{field_name}=__not_a_real_variant__\").send().await\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20.assert_status(400)\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20.assert_body_contains(\"{field_name}\");\n",
                field_name = field_name,
                allowed_values = allowed_values,
                variants_display = target.variants.join(", "),
            )
        };

        let _ = write!(
            out,
            "\n#[tokio::test]\n\
             #[ignore = \"requires Docker (testcontainers) via TestDb; run `cargo test -- --ignored`\"]\n\
             async fn {plural}_rejects_out_of_set_{field_name}() {{\n\
             \x20\x20\x20\x20let db = TestDb::shared().await;\n\
             {setup_calls}\
             \x20\x20\x20\x20db.execute_sql(\"TRUNCATE {plural} RESTART IDENTITY\").await;\n\
             \n\
             {request_boundary_check}\
             \n\
             \x20\x20\x20\x20let mut conn = db.pool().get().await.expect(\"failed to get db connection\");\n\
             \x20\x20\x20\x20let result = diesel::sql_query(\"{escaped_insert}\").execute(&mut *conn).await;\n\
             \x20\x20\x20\x20assert!(result.is_err(), \"out-of-set {field_name} must violate the CHECK constraint\");\n\
             \n\
             \x20\x20\x20\x20let count: i64 = {plural}::table.count().get_result(&mut *conn).await.unwrap();\n\
             \x20\x20\x20\x20assert_eq!(count, 0, \"the rejected row must not have been written\");\n\
             }}\n",
        );
    }
    out
}

/// A deterministic non-`NULL` literal for a `FieldKind`, used to seed and
/// then re-insert the *same* value in [`render_unique_violation_smoke_test`]
/// so the second insert reliably collides. Unlike [`sql_sample_literal`],
/// this deliberately avoids non-deterministic SQL (`gen_random_uuid()`,
/// `NOW()`) — two evaluations of either would almost certainly differ and
/// the duplicate-insert assertion would never trip.
fn unique_sample_literal(kind: FieldKind) -> String {
    match kind {
        FieldKind::String | FieldKind::Text | FieldKind::Enum => "'dup_value'".to_owned(),
        FieldKind::I32 | FieldKind::I64 => "424242".to_owned(),
        // Must be a real seeded row's id, not an arbitrary literal — a
        // `references` target column is FK-constrained against the stub
        // table `render_reference_stub_tables_sql` seeds exactly one row
        // (id 1) into. An arbitrary id like `424242` would fail on the FK
        // constraint before the insert ever reaches the UNIQUE index this
        // test exists to exercise. Matches `sql_sample_literal`'s existing
        // convention for the same reason.
        FieldKind::References => "1".to_owned(),
        FieldKind::Bool => "TRUE".to_owned(),
        FieldKind::F32 | FieldKind::F64 => "1.5".to_owned(),
        // Scale-derived, distinct from `sql_sample_literal`'s digit-1 value
        // for the same field — see `decimal_literal_at_scale`.
        FieldKind::Decimal { scale, .. } => decimal_literal_at_scale(scale, 2),
        FieldKind::Uuid => "'00000000-0000-0000-0000-000000000001'::uuid".to_owned(),
        FieldKind::NaiveDateTime => "'2024-01-01 00:00:00'::timestamp".to_owned(),
        FieldKind::DateTime => "'2024-01-01 00:00:00+00'::timestamptz".to_owned(),
        FieldKind::Bytea => "'\\xDEADBEEF'::bytea".to_owned(),
        FieldKind::Attachment => "NULL".to_owned(),
    }
}

/// A second, distinct deterministic literal for a `FieldKind` — distinct
/// from both [`unique_sample_literal`] and [`sql_sample_literal`]'s value
/// for the same kind. Used by [`unique_violation_insert_sql`] for a
/// scaffold's *other* unique fields (not the one under test) when building
/// the duplicate insert: if more than one field is `unique`, reusing the
/// exact same value for a non-target unique column on both inserts would
/// trip *that* column's own UNIQUE index too, racing against the target's
/// to decide which violation Postgres actually reports.
fn unique_sample_literal_variant(kind: FieldKind) -> String {
    match kind {
        FieldKind::String | FieldKind::Text | FieldKind::Enum => "'dup_value_2'".to_owned(),
        FieldKind::I32 | FieldKind::I64 => "424243".to_owned(),
        // The second stub row `render_reference_stub_tables_sql` seeds —
        // distinct from `unique_sample_literal`'s "1" for the same reason
        // that one must be a real seeded row's id, not an arbitrary literal.
        FieldKind::References => "2".to_owned(),
        FieldKind::Bool => "FALSE".to_owned(),
        FieldKind::F32 | FieldKind::F64 => "2.5".to_owned(),
        // Scale-derived, distinct from both `sql_sample_literal`'s digit-1
        // and `unique_sample_literal`'s digit-2 value — see
        // `decimal_literal_at_scale`.
        FieldKind::Decimal { scale, .. } => decimal_literal_at_scale(scale, 3),
        FieldKind::Uuid => "'00000000-0000-0000-0000-000000000002'::uuid".to_owned(),
        FieldKind::NaiveDateTime => "'2024-01-02 00:00:00'::timestamp".to_owned(),
        FieldKind::DateTime => "'2024-01-02 00:00:00+00'::timestamptz".to_owned(),
        FieldKind::Bytea => "'\\xBEEFDEAD'::bytea".to_owned(),
        FieldKind::Attachment => "NULL".to_owned(),
    }
}

/// Build a raw `INSERT INTO <plural> (...)` statement that sets `target`'s
/// unique column to a deterministic, repeatable value (see
/// [`unique_sample_literal`]) and every other required (`NOT NULL`, no
/// `DEFAULT`) column to a valid sample value — mirrors
/// [`enum_rejection_insert_sql`]'s shape.
///
/// `is_duplicate_insert` selects which literal a *non-target* `unique`
/// column gets: `false` (the first insert) uses the same
/// [`sql_sample_literal`] every other required column gets; `true` (the
/// second, colliding insert) switches those specific columns to
/// [`unique_sample_literal_variant`] instead, so a scaffold with more than
/// one `unique` field doesn't also duplicate a *different* column's value
/// and race it against `target`'s for which violation Postgres reports.
fn unique_violation_insert_sql(
    plural: &str,
    fields: &[Field],
    target: &Field,
    defaults: &BTreeMap<String, String>,
    is_duplicate_insert: bool,
) -> String {
    let mut columns = Vec::new();
    let mut values = Vec::new();
    for f in fields {
        if f.name == target.name {
            columns.push(f.name.clone());
            let value = if f.is_enum() {
                format!("'{}'", f.variants.first().expect("enum field has variants"))
            } else {
                unique_sample_literal(f.kind)
            };
            values.push(value);
        } else if !f.nullable && !defaults.contains_key(&f.name) {
            columns.push(f.name.clone());
            let value = if is_duplicate_insert && f.unique && f.is_enum() {
                let variant = f.variants.get(1).unwrap_or(&f.variants[0]);
                format!("'{variant}'")
            } else if is_duplicate_insert && f.unique {
                unique_sample_literal_variant(f.kind)
            } else if f.is_enum() {
                format!("'{}'", f.variants.first().expect("enum field has variants"))
            } else {
                sql_sample_literal(f.kind)
            };
            values.push(value);
        }
    }
    format!(
        "INSERT INTO {plural} ({}) VALUES ({})",
        columns.join(", "),
        values.join(", ")
    )
}

/// Render one `#[ignore]`d `#[tokio::test]` per `unique` field (issue #1032)
/// that proves, against a real (throwaway) Postgres database:
///
/// 1. A raw duplicate `INSERT` (bypassing the app entirely) violates the
///    migration's `CREATE UNIQUE INDEX` — the constraint is real, not just
///    documented.
/// 2. The resulting `diesel::result::Error`, converted to `AutumnError` via
///    the same blanket `?`/`From` conversion the generated handler relies
///    on, is correctly classified by `autumn_web::error::
///    unique_violation_field` against the *real* Postgres constraint name —
///    proving the `idx_<table>_<field>_unique` naming convention this
///    generator and the runtime helper both assume actually round-trips
///    through Postgres.
/// 3. For an HTML (non-`--api`) scaffold, a stand-in `POST` handler — same
///    convention as [`render_index_smoke_test`]'s stand-in `GET` handler —
///    turns a duplicate submission into a `422` naming the field, proving
///    the full request-boundary path (issue #1032's success metric: a
///    second POST with the same value gets a field-level error, not a
///    `500`).
fn render_unique_violation_smoke_test(
    plural: &str,
    fields: &[Field],
    unique_fields: &[&Field],
    defaults: &BTreeMap<String, String>,
    setup_calls: &str,
    api: bool,
) -> String {
    // Same idempotency treatment as `render_enum_rejection_smoke_test` (see
    // its comment) — this test's own setup must tolerate running alongside
    // the base index/api smoke test and/or the enum-rejection smoke test in
    // the same `TestDb::shared()` container.
    let setup_calls = setup_calls.replacen(
        &format!("CREATE TABLE {plural} ("),
        &format!("CREATE TABLE IF NOT EXISTS {plural} ("),
        1,
    );
    let setup_calls = setup_calls.replace("CREATE INDEX idx_", "CREATE INDEX IF NOT EXISTS idx_");
    let setup_calls = setup_calls.replace(
        "CREATE UNIQUE INDEX idx_",
        "CREATE UNIQUE INDEX IF NOT EXISTS idx_",
    );
    let setup_calls = setup_calls.as_str();

    let mut out = String::new();
    for target in unique_fields {
        // A unique constraint on an always-`Option`-wrapped attachment blob
        // is a degenerate case (Postgres permits unlimited `NULL`s under a
        // unique index, so there's no violation to provoke) — skip it here,
        // same as `unique`'s handling elsewhere never claims to cover it.
        if target.kind.is_attachment() {
            continue;
        }
        let field_name = &target.name;
        let insert_sql = unique_violation_insert_sql(plural, fields, target, defaults, false);
        let escaped_insert = escape_sql_for_rust_literal(&insert_sql);
        // A scaffold with more than one `unique` field needs a *second*,
        // distinct insert for the DB-level duplicate-insert check below: if
        // it reused `escaped_insert` verbatim, a non-target unique column
        // would collide with itself too, racing against `target`'s own
        // collision to decide which violation Postgres actually reports
        // (issue #1032 review follow-up). Only that DB-level check gets the
        // varied insert — the request-boundary stand-in handler below is a
        // single compiled function invoked via two separate HTTP calls, so
        // it has no way to distinguish "first call" from "second call" and
        // keeps using `escaped_insert` for both, same as before.
        let insert_sql_dup = unique_violation_insert_sql(plural, fields, target, defaults, true);
        let escaped_insert_dup = escape_sql_for_rust_literal(&insert_sql_dup);
        let constraint_name = unique_index_name(plural, field_name, fields);

        let request_boundary_check = if api {
            String::new()
        } else {
            format!(
                "#[post(\"/{plural}\")]\n\
                 async fn create(mut db: Db) -> AutumnResult<autumn_web::reexports::axum::response::Response> {{\n\
                 \x20\x20\x20\x20use autumn_web::reexports::axum::response::IntoResponse as _;\n\
                 \x20\x20\x20\x20let result: AutumnResult<()> = async {{\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20// The client sends this same request twice (see below) to prove\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20// the 200-then-422 path — this one compiled handler runs for both\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20// calls, so it can't statically bake in \"first insert\" vs.\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20// \"duplicate insert\" the way the DB-level check above does.\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20// Reading the row count instead tells the two calls apart at\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20// runtime: 0 means this is the first (must succeed) call, so\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20// every unique column gets its plain sample value; any other\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20// count means this is the second (must collide) call, so\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20// non-target unique columns switch to their distinct variant —\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20// otherwise a scaffold with more than one unique field would\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20// duplicate a *different* column too and Postgres could report\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20// that one instead of {field_name}'s.\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20let existing: i64 = {plural}::table.count().get_result(&mut *db).await?;\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20let insert_sql = if existing == 0 {{ \"{escaped_insert}\" }} else {{ \"{escaped_insert_dup}\" }};\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20diesel::sql_query(insert_sql).execute(&mut *db).await?;\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20Ok(())\n\
                 \x20\x20\x20\x20}}.await;\n\
                 \x20\x20\x20\x20if let Err(err) = result {{\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20if let Some((field, message)) = autumn_web::error::unique_violation_field(\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20&err,\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20&[(\"{constraint_name}\", \"{field_name}\", \"has already been taken\")],\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20) {{\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20return Ok((\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20autumn_web::reexports::http::StatusCode::UNPROCESSABLE_ENTITY,\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20format!(\"{{field}}: {{message}}\"),\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20).into_response());\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20}}\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20return Err(err);\n\
                 \x20\x20\x20\x20}}\n\
                 \x20\x20\x20\x20Ok(autumn_web::reexports::http::StatusCode::OK.into_response())\n\
                 }}\n\
                 \n\
                 \x20\x20\x20\x20db.execute_sql(\"TRUNCATE {plural} RESTART IDENTITY\").await;\n\
                 \x20\x20\x20\x20let client: TestClient = TestApp::new().routes(routes![create]).with_db(db.pool()).build();\n\
                 \n\
                 \x20\x20\x20\x20client.post(\"/{plural}\").send().await.assert_status(200);\n\
                 \x20\x20\x20\x20client.post(\"/{plural}\").send().await\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20.assert_status(422)\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20.assert_body_contains(\"{field_name}\");\n"
            )
        };

        let _ = write!(
            out,
            "\n#[tokio::test]\n\
             #[ignore = \"requires Docker (testcontainers) via TestDb; run `cargo test -- --ignored`\"]\n\
             async fn {plural}_rejects_duplicate_{field_name}() {{\n\
             \x20\x20\x20\x20let db = TestDb::shared().await;\n\
             {setup_calls}\
             \x20\x20\x20\x20db.execute_sql(\"TRUNCATE {plural} RESTART IDENTITY\").await;\n\
             \n\
             \x20\x20\x20\x20let mut conn = db.pool().get().await.expect(\"failed to get db connection\");\n\
             \x20\x20\x20\x20diesel::sql_query(\"{escaped_insert}\").execute(&mut *conn).await.expect(\"first insert must succeed\");\n\
             \x20\x20\x20\x20let dup_result = diesel::sql_query(\"{escaped_insert_dup}\").execute(&mut *conn).await;\n\
             \x20\x20\x20\x20let dup_err = dup_result.expect_err(\"a duplicate {field_name} must violate the UNIQUE index\");\n\
             \n\
             \x20\x20\x20\x20let mapped: AutumnResult<()> = Err(dup_err.into());\n\
             \x20\x20\x20\x20let mapped_err = mapped.unwrap_err();\n\
             \x20\x20\x20\x20let (field, _message) = autumn_web::error::unique_violation_field(\n\
             \x20\x20\x20\x20\x20\x20\x20\x20&mapped_err,\n\
             \x20\x20\x20\x20\x20\x20\x20\x20&[(\"{constraint_name}\", \"{field_name}\", \"has already been taken\")],\n\
             \x20\x20\x20\x20).expect(\"a real Postgres unique_violation error must be classified by field\");\n\
             \x20\x20\x20\x20assert_eq!(field, \"{field_name}\");\n\
             \n\
             {request_boundary_check}\
             }}\n",
        );
    }
    out
}

fn main_route_entries(
    plural: &str,
    snake_name: &str,
    api: bool,
    live: bool,
    search: bool,
    validated_field_names: &[String],
    sm_field_names: &[String],
) -> Vec<String> {
    if api {
        let mut entries = vec![
            format!("repositories::{snake_name}::{snake_name}_api_list"),
            format!("repositories::{snake_name}::{snake_name}_api_get"),
            format!("repositories::{snake_name}::{snake_name}_api_create"),
            format!("repositories::{snake_name}::{snake_name}_api_update"),
            format!("repositories::{snake_name}::{snake_name}_api_delete"),
        ];
        if live {
            entries.push(format!("repositories::{snake_name}::stream"));
        }
        entries
    } else {
        let mut entries = vec![
            format!("routes::{plural}::index"),
            format!("routes::{plural}::show"),
            format!("routes::{plural}::new_form"),
            format!("routes::{plural}::create"),
            format!("routes::{plural}::edit_form"),
            format!("routes::{plural}::update"),
            format!("routes::{plural}::destroy"),
        ];
        if live {
            entries.push(format!("routes::{plural}::events"));
        }
        // Issue #1319: register the FTS results route (non-live only; the box is
        // gated off for live variants — see `render_routes_file`).
        if search {
            entries.push(format!("routes::{plural}::search"));
        }
        for field_name in validated_field_names {
            entries.push(format!("routes::{plural}::validate_{field_name}"));
        }
        // Issue #1326: mount the `POST /{plural}/{{id}}/transitions/{field}`
        // handler emitted for each state-machine field, so the show page's
        // `transition_controls` form actions resolve to a real route rather than
        // 404ing. A scaffold with no state-machine field pushes nothing here and
        // keeps the pre-#1326 mounted route set byte-identical.
        for field_name in sm_field_names {
            entries.push(format!("routes::{plural}::transition_{field_name}"));
        }
        entries.push(format!("repositories::{snake_name}::{snake_name}_api_list"));
        entries.push(format!("repositories::{snake_name}::{snake_name}_api_get"));
        entries
    }
}

/// The submit-token exempt-path prefix for a `--live-validation` resource.
///
/// The generated inline-validation routes are `POST /{plural}/validate/{field}`;
/// this prefix exempts every one of them from the submit-token guard at once
/// (the guard matches `exempt_paths` by prefix — an exact match, a prefix ending
/// in `/`, or a prefix whose remainder begins with `/`, so `/{plural}/validate`
/// covers `/{plural}/validate/title`, `/{plural}/validate/body`, … without
/// touching the guarded `POST /{plural}` create route).
fn submit_token_validate_exempt_prefix(plural: &str) -> String {
    format!("/{plural}/validate")
}

/// The `(start, end)` line span of a top-level `[header]` TOML table — the
/// header line through the last line before the next top-level `[...]` header
/// or EOF. `None` when `header` is absent. Mirrors the auth generator's
/// equivalent so submit-token exemptions merge into an existing block instead
/// of emitting a duplicate table.
fn toml_table_block_range(lines: &[&str], header: &str) -> Option<(usize, usize)> {
    let start = lines.iter().position(|l| l.trim() == header)?;
    let end = lines[start + 1..]
        .iter()
        .position(|l| l.trim_start().starts_with('['))
        .map_or(lines.len(), |rel| start + 1 + rel);
    Some((start, end))
}

/// Ensure `/{plural}/validate` is listed under `[security.submit_token]
/// exempt_paths` so a `--live-validation` scaffold's inline-validation POSTs
/// never consume the one-time submit token (issue #1360).
///
/// This is the route-based, field-name-agnostic half of the fix: the
/// `hx-params="not _submit_token"` markup filter only strips the DEFAULT field
/// name, so an app that customises `security.submit_token.field_name` would
/// otherwise still leak the token into the validation POST and have the real
/// create/update submit replay a validation fragment. Exempting the route makes
/// it robust regardless of the configured field name.
///
/// Returns `Some(updated_toml)` only when it actually inserts the exemption, and
/// `None` when the file is left unchanged — the prefix is already present, or
/// the `exempt_paths` array is too malformed to parse. Callers must gate BOTH
/// the plan's modify action AND the destroy-time ownership revert on `Some`:
/// recording a revert for a no-op would let `autumn destroy` delete a
/// preexisting, user-owned exemption we never added.
///
/// Handles three shapes — no `[security.submit_token]` table (append a fresh
/// one), a table without an `exempt_paths` key (insert the key after the
/// header), and a table whose `exempt_paths` array is merged in place.
fn append_submit_token_validate_exempt_to_toml(existing: &str, plural: &str) -> Option<String> {
    use toml_edit::{Array, DocumentMut, Item, Table, Value};

    let exempt = submit_token_validate_exempt_prefix(plural);

    // Parse format-preservingly so comments, ordering, and hand-crafted array
    // layout survive the edit. A config we can't parse is left untouched (and we
    // claim no ownership) rather than risking corruption via raw string edits.
    let mut doc = existing.parse::<DocumentMut>().ok()?;

    // Navigate to — creating if absent — `[security.submit_token]`. A freshly
    // created `[security]` parent is marked implicit so it renders as the dotted
    // `[security.submit_token]` header (matching the hand-written convention)
    // rather than emitting a bare, empty `[security]` table of its own.
    let security_missing = !doc.as_table().contains_key("security");
    let security = doc
        .as_table_mut()
        .entry("security")
        .or_insert_with(|| Item::Table(Table::new()))
        .as_table_mut()?;
    if security_missing {
        security.set_implicit(true);
    }
    let submit_token = security
        .entry("submit_token")
        .or_insert_with(|| Item::Table(Table::new()))
        .as_table_mut()?;

    // Get or create the `exempt_paths` array.
    let array = submit_token
        .entry("exempt_paths")
        .or_insert_with(|| Item::Value(Value::Array(Array::new())))
        .as_array_mut()?;

    // Idempotent: if the prefix is already listed, return `None` so we don't
    // claim ownership of (and later, on `autumn destroy`, delete) a preexisting,
    // user-owned exemption.
    if array.iter().any(|v| v.as_str() == Some(exempt.as_str())) {
        return None;
    }

    array.push(exempt.as_str());

    Some(doc.to_string())
}

/// Inverse of [`append_submit_token_validate_exempt_to_toml`] (`autumn
/// destroy`, issue #1048): remove `/{plural}/validate` from
/// `[security.submit_token] exempt_paths`, dropping the whole block if that
/// leaves an empty freshly-generated `exempt_paths = [...]` as its only key.
///
/// Conservative: only touches an `exempt_paths` array that still contains the
/// exact prefix this generator inserts, never a hand-edited value.
pub(super) fn remove_submit_token_validate_exempt_from_toml(
    existing: &str,
    plural: &str,
) -> String {
    const HEADER: &str = "[security.submit_token]";
    let exempt = submit_token_validate_exempt_prefix(plural);
    let quoted = format!("\"{exempt}\"");

    let lines: Vec<&str> = existing.lines().collect();
    let Some((start, end)) = toml_table_block_range(&lines, HEADER) else {
        return existing.to_owned();
    };
    let Some(key_idx) = lines[start + 1..end]
        .iter()
        .position(|l| l.trim_start().starts_with("exempt_paths"))
        .map(|rel| start + 1 + rel)
    else {
        return existing.to_owned();
    };
    let close_idx = (key_idx..end)
        .find(|&i| lines[i].contains(']'))
        .unwrap_or(key_idx);
    let joined: String = lines[key_idx..=close_idx].join("\n");
    let (Some(open), Some(close)) = (joined.find('['), joined.rfind(']')) else {
        return existing.to_owned();
    };
    let inner = &joined[open + 1..close];
    if !inner.contains(&quoted) {
        return existing.to_owned();
    }
    // Strip our element from the array's comma-separated items.
    let remaining: Vec<String> = inner
        .split(',')
        .map(str::trim)
        .filter(|item| !item.is_empty() && *item != quoted)
        .map(str::to_owned)
        .collect();

    let mut out_lines: Vec<String> = lines.iter().map(|l| (*l).to_owned()).collect();
    if remaining.is_empty() {
        // The block only carried our exempt_paths line — remove the key, and the
        // whole table too if the key was its sole content.
        let block_only_our_key = (start + 1..end).all(|i| {
            i == key_idx || (key_idx..=close_idx).contains(&i) || lines[i].trim().is_empty()
        });
        if block_only_our_key {
            out_lines.splice(start..end, std::iter::empty::<String>());
        } else {
            out_lines.splice(key_idx..=close_idx, std::iter::empty::<String>());
        }
    } else {
        let rebuilt = format!(
            "{}[{}]{}",
            &joined[..open],
            remaining.join(", "),
            &joined[close + 1..]
        );
        out_lines.splice(key_idx..=close_idx, std::iter::once(rebuilt));
    }

    let mut out = out_lines.join("\n");
    // Collapse any doubled blank lines left by removing the block.
    while out.contains("\n\n\n") {
        out = out.replace("\n\n\n", "\n\n");
    }
    if existing.ends_with('\n') && !out.ends_with('\n') {
        out.push('\n');
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::generate::Flags;
    use crate::generate::dsl::FieldConstraints;
    use std::fs;
    use tempfile::TempDir;

    fn project_with_main(template: &str) -> TempDir {
        let tmp = TempDir::new().unwrap();
        fs::write(tmp.path().join("Cargo.toml"), "[package]\nname=\"x\"\n").unwrap();
        fs::create_dir_all(tmp.path().join("src")).unwrap();
        fs::write(tmp.path().join("src/main.rs"), template).unwrap();
        tmp
    }

    /// Write a minimal existing `src/models/<base>.rs` (i64-keyed) so a
    /// `references` column targeting it counts as present — both for
    /// `check_reference_targets`' warning and for the scaffold's
    /// references→select promotion (issue #1135 AC 2), which needs the
    /// target's schema entry to exist.
    fn write_target_model(tmp: &TempDir, base: &str, pascal: &str) {
        fs::create_dir_all(tmp.path().join("src/models")).unwrap();
        fs::write(
            tmp.path().join(format!("src/models/{base}.rs")),
            format!(
                "#[autumn_web::model]\npub struct {pascal} {{\n    #[id]\n    pub id: i64,\n}}\n"
            ),
        )
        .unwrap();
    }

    fn default_main() -> &'static str {
        r#"use autumn_web::prelude::*;

pub fn layout(title: &str, current_path: &str, flash: maud::Markup, content: maud::Markup) -> maud::Markup {
    let _ = (current_path, flash);
    maud::html! {
        title { (title) }
        (content)
    }
}

#[get("/")]
async fn index() -> &'static str { "ok" }

#[autumn_web::main]
async fn main() {
    autumn_web::app()
        .routes(routes![index])
        .run()
        .await;
}
"#
    }

    /// A `src/main.rs` with no shared `pub fn layout` — used to exercise the
    /// actionable error the scaffold generator raises when the target app has
    /// no shared layout for the HTML views to render through (issue #1130).
    fn main_without_layout() -> &'static str {
        r#"use autumn_web::prelude::*;

#[get("/")]
async fn index() -> &'static str { "ok" }

#[autumn_web::main]
async fn main() {
    autumn_web::app()
        .routes(routes![index])
        .run()
        .await;
}
"#
    }

    #[test]
    fn plan_creates_full_scaffold() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "body:Text".into(),
                "published:bool".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        let paths: Vec<String> = plan
            .actions
            .iter()
            .map(|a| {
                a.path()
                    .strip_prefix(&plan.project_root)
                    .unwrap()
                    .display()
                    .to_string()
                    // Normalize for cross-platform comparisons (Windows uses `\`).
                    .replace('\\', "/")
            })
            .collect();
        for expected in [
            "src/models/post.rs",
            "src/models/mod.rs",
            "migrations/20260427000000_create_posts/up.sql",
            "migrations/20260427000000_create_posts/down.sql",
            "src/schema.rs",
            "src/repositories/post.rs",
            "src/repositories/mod.rs",
            "src/routes/posts.rs",
            "src/routes/mod.rs",
            "tests/post.rs",
            "src/main.rs",
        ] {
            assert!(
                paths.iter().any(|p| p == expected),
                "missing expected action for {expected}; got {paths:?}"
            );
        }
    }

    #[test]
    fn generate_then_destroy_scaffold_round_trips_to_original_project_state() {
        temp_env::with_vars(
            [
                ("AUTUMN_DATABASE__PRIMARY_URL", None::<&str>),
                ("AUTUMN_DATABASE__URL", None::<&str>),
                ("DATABASE_URL", None::<&str>),
            ],
            || {
                let tmp = project_with_main(default_main());
                // Mirrors `autumn new`'s real template Cargo.toml (see
                // `templates/Cargo.toml.tmpl`): `autumn-web`/`maud`/
                // `diesel_migrations` and a `tokio` dev-dep with `rt`+`macros`
                // already present, since a fresh project always ships them.
                let cargo_path = tmp.path().join("Cargo.toml");
                fs::write(
                    &cargo_path,
                    "[package]\nname = \"x\"\n\n\
                     [dependencies]\n\
                     autumn-web = \"0.6.0\"\n\
                     maud = { version = \"0.27\", features = [\"axum\"] }\n\
                     diesel_migrations = \"2\"\n\n\
                     [dev-dependencies]\n\
                     tokio = { version = \"1\", features = [\"rt\", \"macros\"] }\n",
                )
                .unwrap();
                let main_path = tmp.path().join("src/main.rs");
                let original_cargo = fs::read_to_string(&cargo_path).unwrap();
                let original_main = fs::read_to_string(&main_path).unwrap();

                let plan = plan_scaffold(
                    tmp.path(),
                    "Post",
                    &["title:String".into()],
                    "20260427000000",
                )
                .unwrap();
                plan.execute(Flags::default()).unwrap();
                assert!(tmp.path().join("src/models/post.rs").exists());
                assert!(tmp.path().join("src/routes/posts.rs").exists());

                let destroy_plan = plan_scaffold(
                    tmp.path(),
                    "Post",
                    &["title:String".into()],
                    "99999999999999",
                )
                .unwrap();
                destroy_plan.revert(Flags::default()).unwrap();

                for gone in [
                    "src/models/post.rs",
                    "src/models/mod.rs",
                    "src/schema.rs",
                    "src/repositories/post.rs",
                    "src/repositories/mod.rs",
                    "src/routes/posts.rs",
                    "src/routes/mod.rs",
                    "tests/post.rs",
                ] {
                    assert!(!tmp.path().join(gone).exists(), "{gone} should be removed");
                }
                assert!(
                    fs::read_dir(tmp.path().join("migrations"))
                        .map_or(true, |mut d| d.next().is_none()),
                    "migration directory must be removed"
                );
                assert_eq!(fs::read_to_string(&main_path).unwrap(), original_main);
                assert_eq!(fs::read_to_string(&cargo_path).unwrap(), original_cargo);
            },
        );
    }

    #[test]
    fn plan_errors_when_main_rs_missing() {
        // A genuinely absent `src/main.rs` (NotFound) surfaces the same
        // actionable shared-layout Config error as a layout-less main.rs, rather
        // than a raw Io "missing" error — it points the user at `autumn new` /
        // `--api`. Non-NotFound io errors (e.g. PermissionDenied) still preserve
        // their original `ErrorKind` via `GenerateError::Io`.
        let tmp = TempDir::new().unwrap();
        fs::write(tmp.path().join("Cargo.toml"), "").unwrap();
        let err = plan_scaffold(tmp.path(), "Post", &[], "20260427000000").unwrap_err();
        match err {
            GenerateError::Config(msg) => {
                assert!(
                    msg.contains("pub fn layout") && msg.contains("autumn new"),
                    "missing main.rs must yield the actionable shared-layout error: {msg}"
                );
            }
            other => panic!("expected an actionable Config error, got: {other:?}"),
        }
    }

    #[test]
    fn execute_writes_form_for_helper_with_formmodel_delegation() {
        // Issue #1135: per-column control selection (and the required /
        // `aria-required` signal issue #1124 guarded here) now lives in the
        // `#[model]`-derived `FormModel` descriptors — the routes file
        // delegates `PostForm`'s fields to the model's derived impl and
        // renders the whole form through one shared `form_for` helper.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(
            routes.contains("impl autumn_web::form::FormModel for PostForm"),
            "PostForm must implement FormModel: {routes}"
        );
        assert!(
            routes.contains("<Post as autumn_web::form::FormModel>::form_fields()"),
            "PostForm must delegate its descriptors to the derived model impl: {routes}"
        );
        assert!(routes.contains("fn post_form_for("), "{routes}");
        assert!(
            routes.contains("autumn_web::form::form_for(changeset, action, \"post\")"),
            "the shared helper must render through form_for: {routes}"
        );
        assert!(
            !routes.contains("autumn_web::form::required_text_input(&changeset"),
            "no per-field input helpers may remain in the views: {routes}"
        );
    }

    #[test]
    fn execute_references_column_renders_select_with_loaded_options() {
        // Issue #1135 AC 2: "references→select". The `#[model]` derive sees a
        // plain `i64` and emits a number input; the scaffold overrides the
        // reference to a `Select` whose options (the referenced table's ids)
        // are loaded by every handler that renders the form and threaded
        // through the shared `comment_form_for` helper. The `Post` target
        // model exists, so the promotion applies (a missing target falls
        // back to the derived number input — see
        // `execute_references_column_with_missing_target_falls_back_to_number_input`).
        let tmp = project_with_main(default_main());
        write_target_model(&tmp, "post", "Post");
        let plan = plan_scaffold(
            tmp.path(),
            "Comment",
            &["body:Text".into(), "post:references".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/comments.rs")).unwrap();
        // The helper takes the loaded options and promotes the column.
        assert!(
            routes.contains("post_id_options: &[(String, String)],"),
            "helper must take the reference options: {routes}"
        );
        assert!(
            routes.contains(
                "let mut post_id_select = vec![(String::new(), \"— Select —\".to_string())];"
            ),
            "non-nullable reference must get a blank 'please select' placeholder: {routes}"
        );
        assert!(
            routes.contains(
                ".override_field(\"post_id\", autumn_web::form::FieldControl::Select { options: post_id_select })"
            ),
            "reference column must be promoted to a Select: {routes}"
        );
        // A shared loader queries the referenced table's ids.
        assert!(
            routes.contains(
                "async fn post_id_select_options(db: &mut Db) -> AutumnResult<Vec<(String, String)>>"
            ),
            "must emit an options loader: {routes}"
        );
        assert!(
            routes.contains("posts::table") && routes.contains(".select(posts::id)"),
            "loader must query the referenced table's ids: {routes}"
        );
        assert!(
            routes.contains("use crate::schema::{comments, posts};"),
            "referenced table's schema module must be imported: {routes}"
        );
        // Every rendering handler loads the options: new_form/edit_form GETs
        // plus the create/update 422 re-render branches.
        assert_eq!(
            routes
                .matches("let post_id_options = post_id_select_options(&mut db).await?;")
                .count(),
            4,
            "new_form, edit_form, create 422, and update 422 must all load options: {routes}"
        );
        // `new_form` gains the DB handle it previously didn't need.
        assert!(
            routes.contains("pub async fn new_form(\n    mut db: Db,"),
            "new_form must take a DB handle to load reference options: {routes}"
        );
        // The helper call threads the options through.
        assert!(
            routes.contains(
                "csrf_field.as_ref(), submit_token.as_ref(), submit_field.as_ref(), &post_id_options))"
            ),
            "view bodies must pass the loaded options to the helper: {routes}"
        );
    }

    #[test]
    fn execute_nullable_references_column_gets_unset_placeholder() {
        let tmp = project_with_main(default_main());
        write_target_model(&tmp, "post", "Post");
        let plan = plan_scaffold(
            tmp.path(),
            "Comment",
            &["post:Option<references>".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/comments.rs")).unwrap();
        assert!(
            routes.contains(
                "let mut post_id_select = vec![(String::new(), \"— Unset —\".to_string())];"
            ),
            "nullable reference must get an '— Unset —' placeholder: {routes}"
        );
    }

    #[test]
    fn execute_references_column_with_missing_target_falls_back_to_number_input() {
        // Regression test (issue #1135 review): a missing reference target has
        // always been a warning, not an error — the scaffold assumes the table
        // exists out-of-band (or gets generated later) and its output must
        // still compile. The references→select promotion needs the target's
        // `src/schema.rs` entry, so with no `Post` model in the project the
        // `post_id` column must skip the whole select pipeline (schema
        // import, options loader, Select override, threaded options) and keep
        // the derived numeric id input.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Comment",
            &["body:Text".into(), "post:references".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/comments.rs")).unwrap();
        assert!(
            routes.contains("use crate::schema::comments;"),
            "only the resource's own schema module may be imported: {routes}"
        );
        assert!(
            !routes.contains("posts::"),
            "the missing target's schema module must never be referenced: {routes}"
        );
        assert!(
            !routes.contains("post_id_select_options"),
            "no options loader may be emitted for a missing target: {routes}"
        );
        assert!(
            !routes.contains(".override_field(\"post_id\""),
            "the column must keep the derived number input, not a Select: {routes}"
        );
        assert!(
            !routes.contains("post_id_options"),
            "the form helper must not take options for a missing target: {routes}"
        );
        // Without reference selects, `new_form` keeps its no-DB signature.
        assert!(
            !routes.contains("pub async fn new_form(\n    mut db: Db,"),
            "new_form must not gain a DB handle when no options are loaded: {routes}"
        );
    }

    #[test]
    fn execute_mixed_reference_targets_keeps_select_only_for_present_target() {
        // One reference whose target exists (`author` → src/models/author.rs)
        // and one whose target is missing (`post`): only the present target
        // gets the select promotion; the missing one falls back to the
        // derived number input and stays out of the schema import.
        let tmp = project_with_main(default_main());
        write_target_model(&tmp, "author", "Author");
        let plan = plan_scaffold(
            tmp.path(),
            "Comment",
            &["author:references".into(), "post:references".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/comments.rs")).unwrap();
        assert!(
            routes.contains("use crate::schema::{comments, authors};")
                || routes.contains("use crate::schema::{authors, comments};"),
            "only the present target may join the schema import: {routes}"
        );
        assert!(
            routes.contains(
                ".override_field(\"author_id\", autumn_web::form::FieldControl::Select { options: author_id_select })"
            ),
            "the present target must keep its Select promotion: {routes}"
        );
        assert!(
            routes.contains("async fn author_id_select_options"),
            "the present target must keep its options loader: {routes}"
        );
        assert!(
            !routes.contains("posts::") && !routes.contains("post_id_select_options"),
            "the missing target must not produce select machinery: {routes}"
        );
        assert!(
            !routes.contains(".override_field(\"post_id\""),
            "the missing target's column must keep the derived number input: {routes}"
        );
    }

    #[test]
    fn execute_self_referential_reference_keeps_select_without_target_model() {
        // A self-referential column targets the scaffold's own table, whose
        // schema entry this very command generates — it is never "missing",
        // so the select promotion applies even though no `src/models/
        // category.rs` exists beforehand.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Category",
            &["name:String".into(), "category:references".into()],
            "20260427000000",
        )
        .unwrap();
        assert!(
            plan.warnings.is_empty(),
            "a self-reference must not warn: {:?}",
            plan.warnings
        );
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/categories.rs")).unwrap();
        assert!(
            routes.contains(
                ".override_field(\"category_id\", autumn_web::form::FieldControl::Select { options: category_id_select })"
            ),
            "self-referential column must keep the Select promotion: {routes}"
        );
        assert!(
            routes.contains("async fn category_id_select_options"),
            "self-referential column must keep its options loader: {routes}"
        );
        assert!(
            routes.contains("use crate::schema::categories;"),
            "own table needs no extra schema import: {routes}"
        );
    }

    #[test]
    fn execute_writes_a_routes_file_referencing_model() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(routes.contains("use crate::models::post::{Post, NewPost, UpdatePost};"));
        assert!(routes.contains("#[get(\"/posts\")]"));
        assert!(routes.contains("#[get(\"/posts/{id}\")]"));
        assert!(
            !routes.contains("#[secured]\n#[get(\"/posts\")]"),
            "index should be reachable by the five-command scaffold smoke test"
        );
        assert!(
            !routes.contains("#[secured]\n#[get(\"/posts/{id}\")]"),
            "read-only show pages should stay public when generated"
        );
        assert!(routes.contains("#[get(\"/posts/new\", name = \"new\")]"));
        assert!(routes.contains("#[post(\"/posts\")]"));
        assert!(routes.contains("#[get(\"/posts/{id}/edit\", name = \"edit\")]"));
        // The HTML edit form posts to a regular `POST /posts/{id}/update`
        // (browsers can't submit PUT natively); the JSON `PUT /api/posts/{id}`
        // remains available via the auto-generated repository handler.
        assert!(routes.contains("#[post(\"/posts/{id}/update\")]"));
        assert!(routes.contains("pub async fn new_form("));
        assert!(routes.contains("layout(\"New Post\""));
        assert!(routes.contains("posts::title.eq(new.title.clone())"));
        // `execute()` returns the affected row count — `Ok(0)` means the id
        // didn't exist, and we must return 404 instead of redirecting as if
        // the save succeeded. DB errors stay distinct from "not found".
        assert!(routes.contains("if updated == 0"));
        assert!(routes.contains("AutumnError::not_found_msg"));
        // The HTML edit form must point at the new HTML update handler, not
        // the JSON PUT endpoint — browsers cannot submit PUT without JS. The
        // URL is emitted through the typed path helper (issue #1133).
        assert!(routes.contains("paths::update(*id)"));
        assert!(!routes.contains("/api/posts/{}\""));
        // HTML handlers use POST for update and delete (browsers can't submit
        // PUT or DELETE natively); `#[put(` and `#[delete(` appear only in the
        // auto-generated JSON repository handlers, not in the HTML routes file.
        assert!(!routes.contains("#[put("));
        assert!(!routes.contains("#[delete("));
        // The HTML delete route must be present and use POST (not DELETE).
        assert!(routes.contains(r#"#[post("/posts/{id}/delete", name = "delete")]"#));
    }

    // ── enum field: form widgets, boundary validation, imports (issue #1030) ─

    fn plan_and_execute_post_scaffold_with_status_enum(tmp: &TempDir) {
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "status:enum{draft,published,archived}".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
    }

    #[test]
    fn scaffold_create_form_renders_enum_select() {
        let tmp = project_with_main(default_main());
        plan_and_execute_post_scaffold_with_status_enum(&tmp);
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        // Enum fields are promoted to a `Select` control via a `form_for`
        // override (issue #1135) — the `#[model]` derive sees only an opaque
        // Rust enum type, but the scaffold knows the variants statically and
        // emits one `(value, label)` option per variant plus a leading
        // placeholder. The selected option is chosen by the shipped
        // `select_input` helper from the changeset's current value.
        assert!(
            routes.contains(
                ".override_field(\"status\", autumn_web::form::FieldControl::Select { options: vec![(\"\".into(), \"— Select —\".into()), (\"draft\".into(), \"Draft\".into()), (\"published\".into(), \"Published\".into()), (\"archived\".into(), \"Archived\".into())] })"
            ),
            "got:\n{routes}"
        );
    }

    #[test]
    fn scaffold_edit_form_marks_current_enum_variant_selected() {
        // The `From<&Post>` seed maps the persisted variant to its wire token,
        // which `select_input` then marks selected in the edit form (issue
        // #1124 — selection lives in the framework helper, not the template).
        let tmp = project_with_main(default_main());
        plan_and_execute_post_scaffold_with_status_enum(&tmp);
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        assert!(
            routes.contains("Status::Draft => \"draft\".to_string()"),
            "got:\n{routes}"
        );
        assert!(
            routes.contains("Status::Published => \"published\".to_string()"),
            "got:\n{routes}"
        );
    }

    #[test]
    fn scaffold_form_parses_enum_with_field_error() {
        // The enum field is a `String` on `PostForm`, parsed into the enum in
        // `into_new` with a 400 naming the field on an out-of-set value.
        let tmp = project_with_main(default_main());
        plan_and_execute_post_scaffold_with_status_enum(&tmp);
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        assert!(routes.contains("pub status: String,"), "got:\n{routes}");
        assert!(
            routes.contains("form.status.parse::<Status>()"),
            "got:\n{routes}"
        );
        assert!(
            routes.contains("AutumnError::bad_request_msg(format!(\"status: {err}\"))"),
            "got:\n{routes}"
        );
    }

    #[test]
    fn scaffold_routes_import_enum_type() {
        let tmp = project_with_main(default_main());
        plan_and_execute_post_scaffold_with_status_enum(&tmp);
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        assert!(
            routes.contains("use crate::models::post::{Post, NewPost, UpdatePost, Status};"),
            "got:\n{routes}"
        );
    }

    #[test]
    fn scaffold_update_columns_set_enum_directly() {
        let tmp = project_with_main(default_main());
        plan_and_execute_post_scaffold_with_status_enum(&tmp);
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        assert!(
            routes.contains("posts::status.eq(new.status.clone())"),
            "got:\n{routes}"
        );
    }

    #[test]
    fn scaffold_default_enum_field_is_dropped_from_forms() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "status:enum{draft,published,archived}".into(),
            ],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    defaults: vec!["status=draft".into()],
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        // A `--default` field is excluded from the derived `FormModel` list
        // (the model marks it `#[default]`), so the scaffold must not emit a
        // select override for it either — otherwise `form_for` would carry a
        // dangling override for a field it never renders.
        assert!(
            !routes.contains(".override_field(\"status\""),
            "a --default field must be excluded from the create/edit forms: {routes}"
        );
    }

    #[test]
    fn scaffold_query_on_enum_field_is_rejected() {
        let tmp = project_with_main(default_main());
        let err = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into(), "status:enum{draft,published}".into()],
            "20260427000000",
            &ScaffoldOptions {
                queries: vec!["find_by_status:status".into()],
                ..Default::default()
            },
        )
        .unwrap_err();
        assert!(matches!(err, GenerateError::InvalidField { .. }));
    }

    #[test]
    fn scaffold_enum_field_colliding_with_routes_import_is_rejected() {
        // `path:enum{a,b}` would generate `use crate::models::post::{…, Path}`
        // in routes.rs alongside the file's own `use autumn_web::extract::Path;`
        // — two different types both named `Path`, which is E0252. Verified by
        // generating this exact scaffold and observing the duplicate import.
        for field_name in ["path", "page", "bytes", "flash", "db"] {
            let tmp = project_with_main(default_main());
            let err = plan_scaffold(
                tmp.path(),
                "Post",
                &[format!("{field_name}:enum{{a,b}}")],
                "20260427000000",
            )
            .unwrap_err();
            assert!(
                matches!(err, GenerateError::InvalidField { .. }),
                "expected '{field_name}' to be rejected"
            );
        }
    }

    #[test]
    fn scaffold_enum_field_named_to_string_is_rejected() {
        // `to_string:enum{a,b}` pascalizes to `ToString`, imported into
        // routes.rs; a nullable field of that type renders its edit-form
        // value via `row.to_string.as_ref().map(ToString::to_string)`, an
        // unqualified path expression that resolves to the enum instead of
        // the prelude trait and fails to compile.
        let tmp = project_with_main(default_main());
        let err = plan_scaffold(
            tmp.path(),
            "Post",
            &["to_string:Option<enum{a,b}>".into()],
            "20260427000000",
        )
        .unwrap_err();
        assert!(matches!(err, GenerateError::InvalidField { .. }));
    }

    #[test]
    fn scaffold_enum_field_named_changeset_is_rejected() {
        // `changeset:enum{a,b}` pascalizes to `Changeset`, colliding with the
        // `use autumn_web::form::{Changeset, IntoChangeset};` import every
        // non-`--api` scaffold's routes file now carries (issue #1124) — a
        // duplicate `Changeset`/`IntoChangeset` import fails with E0252,
        // exactly like the pre-existing `Path`/`ToString` collisions above.
        for field_name in ["changeset", "into_changeset"] {
            let tmp = project_with_main(default_main());
            let err = plan_scaffold(
                tmp.path(),
                "Post",
                &[format!("{field_name}:enum{{a,b}}")],
                "20260427000000",
            )
            .unwrap_err();
            assert!(
                matches!(err, GenerateError::InvalidField { .. }),
                "expected '{field_name}' to be rejected"
            );
        }
    }

    #[test]
    fn scaffold_enum_field_named_submit_token_is_rejected() {
        // `submit_token:enum{a,b}` pascalizes to `SubmitToken` and
        // `submit_form_field:enum{a,b}` to `SubmitFormField`, colliding with the
        // `use autumn_web::security::{…, SubmitFormField, SubmitToken};` import
        // every non-`--api` scaffold's routes file now carries (issue #1360) — a
        // duplicate `SubmitToken`/`SubmitFormField` import fails with E0252,
        // exactly like the `CsrfToken`/`Changeset` collisions above. Rejecting
        // the field up front yields the actionable field-name error instead of a
        // broken generated file.
        for field_name in ["submit_token", "submit_form_field"] {
            let tmp = project_with_main(default_main());
            let err = plan_scaffold(
                tmp.path(),
                "Post",
                &[format!("{field_name}:enum{{a,b}}")],
                "20260427000000",
            )
            .unwrap_err();
            assert!(
                matches!(err, GenerateError::InvalidField { .. }),
                "expected '{field_name}' to be rejected"
            );
        }
    }

    #[test]
    fn scaffold_enum_field_colliding_with_generated_form_struct_is_rejected() {
        // `post_form:enum{a,b}` on model `Post` pascalizes to `PostForm`,
        // colliding with the scaffold's own generated `pub struct PostForm`
        // changeset form (`render_model_form`, issue #1124) — a duplicate
        // `PostForm` definition fails to compile, exactly like the
        // fixed-name collisions above.
        let tmp = project_with_main(default_main());
        let err = plan_scaffold(
            tmp.path(),
            "Post",
            &["post_form:enum{a,b}".into()],
            "20260427000000",
        )
        .unwrap_err();
        assert!(matches!(err, GenerateError::InvalidField { .. }));
    }

    #[test]
    fn scaffold_enum_field_colliding_with_routes_import_is_accepted_for_api_only() {
        // `--api` scaffolds never emit `src/routes/<plural>.rs`, so the
        // routes-file reserved names don't apply.
        let tmp = project_with_main(default_main());
        plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["path:enum{a,b}".into()],
            "20260427000000",
            &ScaffoldOptions {
                api: true,
                ..Default::default()
            },
        )
        .unwrap();
    }

    #[test]
    fn scaffold_enum_field_named_redirect_is_accepted_and_routes_fully_qualify_redirect() {
        // Regression (PR #1659): the routes file's write handlers issue real 303
        // redirects. If the file imported the framework type via
        // `use autumn_web::Redirect;`, a `redirect:enum{a,b}` field — which
        // pascalizes to `Redirect` and is imported via
        // `use crate::models::post::{…, Redirect}` — would produce two `Redirect`
        // imports and fail with E0252. `Redirect` is deliberately NOT reserved
        // (users may name a model/enum `Redirect`); instead the handlers
        // fully-qualify the framework type as `autumn_web::Redirect`, so the enum
        // field is accepted and both types coexist.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["redirect:enum{a,b}".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        // The model-side `Redirect` enum is imported — this is the type that
        // would have collided with a framework `use autumn_web::Redirect;`.
        assert!(
            routes.contains("Redirect}"),
            "expected the enum `Redirect` to be imported from crate::models: {routes}"
        );
        // The framework redirect is fully-qualified, never imported, so there is
        // no duplicate import and no glob-shadowing.
        assert!(
            !routes.contains("use autumn_web::Redirect;"),
            "routes must not import the framework Redirect (would collide): {routes}"
        );
        assert!(
            routes.contains("autumn_web::Redirect::to("),
            "redirect handlers must fully-qualify autumn_web::Redirect::to: {routes}"
        );
        assert!(
            routes.contains("-> AutumnResult<autumn_web::Redirect>"),
            "destroy handler must fully-qualify its return type: {routes}"
        );
    }

    // ── enum field: nullable (issue #1030) ──────────────────────────────────

    fn plan_and_execute_post_scaffold_with_nullable_status_enum(tmp: &TempDir) {
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "status:Option<enum{draft,published}>".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
    }

    #[test]
    fn scaffold_nullable_enum_create_form_has_unset_placeholder() {
        // A nullable enum renders through `select_input` with an "— Unset —"
        // placeholder as its blank option (issue #1124).
        let tmp = project_with_main(default_main());
        plan_and_execute_post_scaffold_with_nullable_status_enum(&tmp);
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        assert!(
            routes.contains(
                ".override_field(\"status\", autumn_web::form::FieldControl::Select { options: vec![(\"\".into(), \"— Unset —\".into()), (\"draft\".into(), \"Draft\".into()), (\"published\".into(), \"Published\".into())] })"
            ),
            "got:\n{routes}"
        );
    }

    #[test]
    fn scaffold_nullable_enum_edit_form_seed_maps_option_variant() {
        // The `From<&Post>` seed maps `Option<Status>` to an `Option<String>`
        // token; `select_input` then marks the matching option (issue #1124).
        let tmp = project_with_main(default_main());
        plan_and_execute_post_scaffold_with_nullable_status_enum(&tmp);
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        assert!(
            routes.contains(
                "status: row.status.as_ref().map(|value| match value { Status::Draft => \"draft\".to_string(), Status::Published => \"published\".to_string(), }),"
            ),
            "got:\n{routes}"
        );
    }

    #[test]
    fn scaffold_nullable_enum_form_is_option_string_with_transpose() {
        let tmp = project_with_main(default_main());
        plan_and_execute_post_scaffold_with_nullable_status_enum(&tmp);
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        assert!(
            routes.contains("pub status: Option<String>,"),
            "got:\n{routes}"
        );
        assert!(
            routes.contains("form.status.as_deref()") && routes.contains(".transpose()"),
            "got:\n{routes}"
        );
    }

    #[test]
    fn execute_writes_csrf_aware_form_handlers() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(routes.contains(
            "use autumn_web::security::{CsrfFormField, CsrfToken, SubmitFormField, SubmitToken};"
        ));
        assert!(routes.contains("fn csrf_input("));
        assert!(routes.contains("input type=\"hidden\" name=(csrf_field_name"));
        assert!(routes.contains("value=(csrf.token());"));
        assert!(routes.contains("pub async fn new_form("));
        assert!(routes.contains("csrf: Option<CsrfToken>"));
        assert!(routes.contains("csrf_field: Option<CsrfFormField>"));
        assert!(routes.contains("(csrf_input(csrf.as_ref(), csrf_field.as_ref()))"));
        assert!(routes.contains("pub async fn edit_form("));
        // Issue #1360: one-time submit token embedded in create/update forms and
        // threaded through the create/update handlers. The hidden field's `name`
        // is bound at runtime to the configured `security.submit_token.field_name`
        // (via the `SubmitFormField` extractor), not hardcoded — mirroring CSRF —
        // so a custom field name still matches what `SubmitTokenLayer` scans for.
        assert!(routes.contains("fn submit_token_input("));
        assert!(routes.contains(
            "let submit_field_name = field.map(|field| field.0.as_str()).unwrap_or(\"_submit_token\");"
        ));
        assert!(routes.contains(
            "input type=\"hidden\" name=(submit_field_name) value=(submit_token.token());"
        ));
        // The hidden field is never emitted under a hardcoded `_submit_token` name.
        assert!(!routes.contains("name=\"_submit_token\""));
        assert!(routes.contains("submit_token: Option<SubmitToken>"));
        assert!(routes.contains("submit_field: Option<SubmitFormField>"));
        assert!(routes.contains("submit_token.as_ref()"));
        assert!(routes.contains("submit_field.as_ref()"));
        assert!(routes.contains("submit_token_input(submit_token, submit_field)"));
        // Issue #1360 (finding G): the token must be emitted at the FRONT of the
        // form via `.prepend(...)`, not appended after the derived fields —
        // `SubmitTokenLayer` only scans the first chunk of the URL-encoded body,
        // so a large earlier field could otherwise push an appended token past
        // the scan cap and leave duplicate submits unguarded.
        assert!(
            routes.contains("form.prepend(submit_token_input(submit_token, submit_field))"),
            "standard form must prepend the submit token, not append it:\n{routes}"
        );
        assert!(
            !routes.contains("form.append(submit_token_input"),
            "submit token must not be appended after derived fields:\n{routes}"
        );
    }

    // ── Changeset validation round-trip (issue #1124) ──────────────────
    //
    // A rejected submission must re-render the same form at HTTP 422 with the
    // user's input preserved and per-field errors shown inline, instead of the
    // old decode-and-insert path that landed on a 400 error page with input
    // lost. The generator promotes the internal decode struct to a public,
    // validating `{Pascal}Form` (derives Serialize + validator::Validate +
    // Default), and the handlers build a `Changeset` from it.

    #[test]
    fn execute_writes_model_form_struct() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into(), "body:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    validations: vec!["title=length:min=1".into()],
                    ..ModelOptions::default()
                },
                ..ScaffoldOptions::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(
            routes.contains("pub struct PostForm"),
            "generator must emit a named, public form struct: {routes}"
        );
        assert!(
            routes.contains("serde::Serialize"),
            "PostForm must derive Serialize so Changeset::field_value can \
             repopulate inputs: {routes}"
        );
        assert!(
            routes.contains("validator::Validate"),
            "PostForm must derive Validate so into_changeset() validates: {routes}"
        );
        assert!(
            routes.contains("Default"),
            "PostForm must derive Default for the blank new-form changeset: {routes}"
        );
        assert!(
            routes.contains("#[validate(length(min = 1))]"),
            "PostForm must echo the declared validation rule: {routes}"
        );
        assert!(
            routes.contains("impl From<&Post> for PostForm"),
            "generator must emit a From<&Row> to seed the edit-form changeset: {routes}"
        );
    }

    #[test]
    fn execute_writes_changeset_validated_create_handler() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    validations: vec!["title=length:min=1".into()],
                    ..ModelOptions::default()
                },
                ..ScaffoldOptions::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        // AC1: handlers build a changeset from the submitted body.
        assert!(
            routes.contains("into_changeset()"),
            "create/update must build a changeset from the submission: {routes}"
        );
        assert!(
            routes.contains("is_valid()"),
            "handler must branch on changeset validity: {routes}"
        );
        // AC2: failed submission re-renders at 422, not a 400 error page.
        assert!(
            routes.contains("StatusCode::UNPROCESSABLE_ENTITY"),
            "handler must respond 422 on a rejected submission: {routes}"
        );
        // AC7: the create/update handlers re-render at 422 rather than
        // dead-ending on a rejected submission. (A truly undecodable body still
        // 400s in `decode_form`, matching ChangesetForm's own contract — the
        // 422 path is exclusively for validator-rule failures.)
        assert!(
            routes.contains("into_response()"),
            "the changeset re-render returns a Response, not a bare Markup 400: {routes}"
        );
    }

    #[test]
    fn execute_new_and_edit_forms_render_via_form_for() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "rank:i32".into(),
                "published:bool".into(),
                "published_at:NaiveDateTime".into(),
            ],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    validations: vec!["title=length:min=1".into()],
                    ..ModelOptions::default()
                },
                ..ScaffoldOptions::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        // Issue #1135: new/edit render the whole form through one shared
        // `form_for` helper — control selection per column (text/number/
        // checkbox/datetime, required or not) lives in the derived
        // `FormModel` descriptors, so the routes file carries no per-field
        // input lines at all.
        let new_form_start = routes
            .find("pub async fn new_form")
            .expect("new_form handler");
        let create_start = routes.find("pub async fn create(").expect("create handler");
        let new_form_body = &routes[new_form_start..create_start];
        assert_eq!(
            new_form_body.matches("post_form_for(&changeset").count(),
            1,
            "the new view must render via exactly one form_for call: {new_form_body}"
        );
        let edit_form_start = routes
            .find("pub async fn edit_form")
            .expect("edit_form handler");
        let update_start = routes.find("pub async fn update(").expect("update handler");
        let edit_form_body = &routes[edit_form_start..update_start];
        assert_eq!(
            edit_form_body.matches("post_form_for(&changeset").count(),
            1,
            "the edit view must render via exactly one form_for call: {edit_form_body}"
        );
        for helper in [
            "required_text_input",
            "required_number_input",
            "checkbox_input",
            "required_datetime_input",
        ] {
            assert!(
                !routes.contains(&format!("autumn_web::form::{helper}(&changeset")),
                "no per-field {helper} lines may remain: {routes}"
            );
        }
        // The old hand-rolled bare-HTML text input must be gone for standard fields.
        assert!(
            !routes.contains(r#"input type="text" name="title""#),
            "standard fields must no longer be hand-rolled: {routes}"
        );
    }

    #[test]
    fn execute_live_validation_inline_posts_drop_the_submit_token() {
        // Finding F (issue #1360): a `--live-validation` field posts its inline
        // validation with `hx-include="closest form"`, so that POST would carry
        // the hidden one-time `_submit_token` to the guarded `/validate/...`
        // route and consume it — the real create submit would then replay the
        // validation fragment instead of running the mutation. The generated
        // htmx input must drop the token via `hx-params="not _submit_token"`,
        // while the real create/update form still embeds it.
        let tmp = project_with_main(default_main());
        // A DSL-constrained `String` auto-derives a `length` rule, so `title` is
        // validated and renders through the typed `a11y::TextField` primitive
        // carrying the htmx wiring via `.hx()` (issue #1951).
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String{min=3,max=120}".into()],
            "20260427000000",
            &ScaffoldOptions {
                live_validation: true,
                ..ScaffoldOptions::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        // The constrained validated input keeps its inline-validation wiring,
        // now threaded through the primitive's `.hx()` escape hatch and the
        // typed path helper (#1823/#1951) rather than a raw `hx-post` attribute.
        assert!(
            routes.contains(".hx(\"post\", paths::validate_title())"),
            "title must keep its htmx inline-validation wiring via `.hx()`:\n{routes}"
        );
        // ...but filters the one-time submit token out of that POST so the
        // inline validation never consumes it.
        assert!(
            routes.contains(".hx(\"params\", \"not _submit_token\")"),
            "live-validation inputs must drop _submit_token from the inline POST:\n{routes}"
        );
        // The inline-validate handler returns the SAME fragment (byte-identical
        // for the htmx `outerHTML` swap), so it must carry the filter too.
        let validate_title = &routes[routes
            .find("pub async fn validate_title(")
            .expect("validate_title handler")..];
        assert!(
            validate_title[..validate_title[1..]
                .find("#[post(")
                .map_or(validate_title.len(), |rel| rel + 1)]
                .contains(".hx(\"params\", \"not _submit_token\")"),
            "the validate_title fragment must also drop the submit token:\n{validate_title}"
        );
        // The real create/update form still embeds the submit token so the
        // mutation stays guarded against duplicate submits.
        assert!(
            routes.contains("submit_token_input(submit_token.as_ref(), submit_field.as_ref())"),
            "the create/update form must still carry the submit token:\n{routes}"
        );

        // Issue #1951 byte-identity guarantee: htmx swaps `outerHTML` on the
        // whole `[data-autumn-field-wrapper]`, so the field the form first
        // renders and the fragment the `validate_title` handler returns must be
        // byte-identical. Both are emitted by the shared
        // `render_live_constrained_field`, so extract the `title-field` wrapper
        // block from the first (form) occurrence and from the validate handler
        // and assert they match after normalizing insignificant leading
        // whitespace (which maud does not render).
        let extract_block = |src: &str, start: usize| -> String {
            let open = src[start..].find('{').expect("wrapper `{`") + start;
            let mut depth = 0usize;
            for (i, ch) in src[open..].char_indices() {
                match ch {
                    '{' => depth += 1,
                    '}' => {
                        depth -= 1;
                        if depth == 0 {
                            return src[start..=open + i].to_owned();
                        }
                    }
                    _ => {}
                }
            }
            panic!("unbalanced wrapper block");
        };
        let normalize =
            |block: &str| -> String { block.lines().map(str::trim).collect::<Vec<_>>().join("\n") };
        let form_start = routes
            .find("div id=\"title-field\"")
            .expect("form title-field");
        let form_block = extract_block(&routes, form_start);
        let frag_offset = routes
            .find("pub async fn validate_title(")
            .expect("validate_title handler");
        let frag_start = frag_offset
            + routes[frag_offset..]
                .find("div id=\"title-field\"")
                .expect("fragment title-field");
        let frag_block = extract_block(&routes, frag_start);
        assert_eq!(
            normalize(&form_block),
            normalize(&frag_block),
            "the initial-rendered field and the validate_title fragment must be \
             byte-identical (modulo insignificant whitespace) for the htmx \
             outerHTML swap"
        );
    }

    #[test]
    fn execute_writes_edit_form_with_prefilled_values_and_nullable_optional_inputs() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "subtitle:Option<String>".into(),
                "views:Option<i64>".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        // Prefilling on the edit form now flows through the changeset: the
        // `From<&Post>` seed copies each row value into the form, and the
        // changeset-aware helpers repopulate the `value` (issue #1124).
        assert!(
            routes.contains("impl From<&Post> for PostForm"),
            "edit form must seed a changeset from the loaded row: {routes}"
        );
        assert!(
            routes.contains("title: row.title.clone(),"),
            "seed must copy required fields from the loaded row: {routes}"
        );
        assert!(
            routes.contains("subtitle: row.subtitle.clone(),"),
            "seed must copy nullable text fields from the loaded row: {routes}"
        );
        assert!(
            routes.contains("views: row.views.clone(),"),
            "seed must copy nullable numeric fields from the loaded row: {routes}"
        );
        // The nullable numeric control itself comes from the derived
        // `FormModel` descriptors (Option<i64> → non-required number input);
        // the routes file needs no per-field code or override for it.
        assert!(
            !routes.contains(".override_field(\"views\""),
            "plain numeric fields need no form_for override: {routes}"
        );
    }

    #[test]
    fn execute_writes_form_decoder_that_drops_blank_nullable_fields() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "nickname:Option<String>".into(),
                "views:Option<i64>".into(),
                "published_at:Option<NaiveDateTime>".into(),
                "token:Option<Uuid>".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(
            routes.contains("use autumn_web::reexports::axum::body::Bytes;"),
            "generated routes must be able to inspect raw form bytes: {routes}"
        );
        // Issue #1830: no-owner scaffolds now also record-authorize their
        // mutating handlers, so `State`/`Session` are threaded in before the
        // body-consuming `Bytes` extractor (which stays last).
        assert!(
            routes.contains("pub async fn create(flash: Flash, csrf: Option<CsrfToken>, csrf_field: Option<CsrfFormField>, submit_token: Option<SubmitToken>, submit_field: Option<SubmitFormField>, mut db: Db, \n    autumn_web::extract::State(state): autumn_web::extract::State<autumn_web::AppState>,\n    session: autumn_web::session::Session,\n    body: Bytes)"),
            "create must decode after blank nullable normalization: {routes}"
        );
        assert!(
            routes.contains(
                "pub async fn update(\n    flash: Flash,\n    csrf: Option<CsrfToken>,\n    csrf_field: Option<CsrfFormField>,\n    submit_token: Option<SubmitToken>,\n    submit_field: Option<SubmitFormField>,\n    id: Path<i64>,\n    mut db: Db,\n    autumn_web::extract::State(state): autumn_web::extract::State<autumn_web::AppState>,\n    session: autumn_web::session::Session,\n    body: Bytes,\n)"
            ),
            "update must decode after blank nullable normalization: {routes}"
        );
        // Both handlers decode to the form via the generated decoder, then
        // validate through a changeset (issue #1124).
        assert!(
            routes.contains("let form = decode_form(body)?;"),
            "handlers must use the generated decoder: {routes}"
        );
        assert!(
            routes.contains(r#"matches!(name, "nickname" | "views" | "published_at" | "token")"#),
            "decoder must drop blank submissions for every nullable field: {routes}"
        );
    }

    #[test]
    fn execute_writes_a_repository_with_json_api_attribute() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(tmp.path(), "Post", &[], "20260427000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let repo = fs::read_to_string(tmp.path().join("src/repositories/post.rs")).unwrap();
        assert!(repo.contains("#[autumn_web::repository(Post, api = \"/api/posts\")]"));
        assert!(repo.contains("pub trait PostRepository"));
    }

    #[test]
    fn execute_updates_main_rs_with_mods_and_routes() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert!(main.contains("mod models;"));
        assert!(main.contains("mod routes;"));
        assert!(main.contains("mod schema;"));
        assert!(main.contains("mod repositories;"));
        assert!(main.contains("routes::posts::index"));
        assert!(main.contains("routes::posts::show"));
        assert!(main.contains("routes::posts::new_form"));
        assert!(main.contains("routes::posts::create"));
        assert!(main.contains("routes::posts::edit_form"));
        assert!(main.contains("routes::posts::update"));
        assert!(main.contains("routes::posts::destroy"));
        assert!(main.contains("repositories::post::post_api_list"));
        assert!(main.contains("repositories::post::post_api_get"));
        assert!(!main.contains("repositories::post::post_api_create"));
        assert!(!main.contains("repositories::post::post_api_update"));
        assert!(!main.contains("repositories::post::post_api_delete"));
    }

    #[test]
    fn scaffold_emits_flash_messages_and_destroy_handler() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        // Flash (and the shared flash_messages helper) is imported and set on
        // every mutating action before the redirect.
        assert!(
            routes.contains("use autumn_web::flash::{Flash, flash_messages};"),
            "routes file must import Flash and flash_messages: {routes}"
        );
        assert!(routes.contains(r#"flash.success("Post created")"#));
        assert!(routes.contains(r#"flash.success("Post updated")"#));
        assert!(routes.contains(r#"flash.success("Post deleted")"#));
        // A destroy handler now exists, wired as a browser-friendly POST.
        assert!(routes.contains("pub async fn destroy("));
        assert!(routes.contains(r#"#[post("/posts/{id}/delete", name = "delete")]"#));
        // The edit page exposes a delete control that targets it, through the
        // typed path helper (issue #1133).
        assert!(routes.contains("paths::delete(*id)"));
        // Issue #1130: the standard scaffold no longer emits a private layout
        // stub — every view renders through the app's shared `crate::layout`.
        assert!(
            !routes.contains("fn layout(title: &str, flash: Markup, content: Markup)"),
            "standard scaffold must not define a private layout stub: {routes}"
        );
        assert!(
            !routes.contains("Replace with your real layout"),
            "the private-layout doc comment must be gone: {routes}"
        );
        assert!(
            routes.contains("crate::layout("),
            "views must render through the shared crate::layout: {routes}"
        );
        // Issue #1240: flash renders through the shared accessible helper, not
        // the older `flash.render()`.
        assert!(
            !routes.contains("flash.render().await"),
            "flash must not use the old flash.render() path: {routes}"
        );
        assert!(
            routes.contains("flash_messages(&flash.consume().await)"),
            "flash must render through the shared flash_messages() helper: {routes}"
        );

        // main.rs registers the new destroy route.
        let main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert!(
            main.contains("routes::posts::destroy"),
            "main.rs must register the destroy route: {main}"
        );
    }

    /// Issue #1130, AC 1/2/6: every scaffolded view (`index`, `show`,
    /// `new_form`, `edit_form`) renders through the application's shared
    /// `crate::layout(title, current_path, flash, content)` with the correct
    /// four arguments, and the private layout stub (and its "Replace with your
    /// real layout" comment) is gone.
    #[test]
    fn scaffold_views_render_through_shared_layout() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        // No private layout definition survives (AC 1/3/6).
        assert!(
            !routes.contains("fn layout("),
            "no private layout may be defined in the routes file: {routes}"
        );
        assert!(
            !routes.contains("Replace with your real layout"),
            "the private-layout doc comment must be gone: {routes}"
        );

        // Every view renders through the shared layout with a 4-arg call
        // supplying a `current_path` (AC 1/2).
        assert!(
            routes.contains(
                "crate::layout(\"Post index\", \"/posts\", flash_messages(&flash.consume().await),"
            ),
            "index must render through crate::layout with current_path: {routes}"
        );
        assert!(
            routes.contains("crate::layout(&format!(\"Post #{}\", row.id), \"/posts\", flash_messages(&flash.consume().await),"),
            "show must render through crate::layout with current_path: {routes}"
        );
        assert!(
            routes.contains("crate::layout(\"New Post\", \"/posts/new\", flash_messages(&flash.consume().await),"),
            "new_form must render through crate::layout with current_path: {routes}"
        );
        assert!(
            routes.contains("crate::layout(&format!(\"Edit Post #{}\", *id), \"/posts\", flash_messages(&flash.consume().await),"),
            "edit_form must render through crate::layout with current_path: {routes}"
        );
    }

    /// Issue #1240 (create/update sub-AC): the write-path re-render branches of
    /// `create` and `update` render pending flash through the shared
    /// `flash_messages()` helper (accessible role/aria-live), not the bare
    /// `flash.render()`.
    #[test]
    fn scaffold_create_update_render_flash_via_shared_helper() {
        let tmp = project_with_main(default_main());
        // A `unique` field forces the create/update 422 re-render branches to
        // splice the shared form body, exercising the write-path flash arg.
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String:unique".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(
            routes.contains("use autumn_web::flash::{Flash, flash_messages};"),
            "routes must import the shared flash_messages helper: {routes}"
        );
        assert!(
            !routes.contains("flash.render()"),
            "no view may use the older flash.render(): {routes}"
        );
        // The create and update handlers both re-render the form on the 422
        // path; that shared body must carry the shared helper call.
        let occurrences = routes
            .matches("flash_messages(&flash.consume().await)")
            .count();
        assert!(
            occurrences >= 4,
            "index/show/new/edit (and the create/update re-renders) must all use \
             flash_messages; found {occurrences} occurrences: {routes}"
        );
    }

    /// Issue #1130, AC 3: generating multiple resources into the same app
    /// produces zero duplicated layout definitions — no generated routes file
    /// defines `layout` anymore.
    #[test]
    fn scaffold_multiple_resources_have_no_duplicate_layout() {
        let tmp = project_with_main(default_main());
        for (name, ts) in [("Post", "20260427000000"), ("Comment", "20260427000001")] {
            let plan = plan_scaffold(tmp.path(), name, &["title:String".into()], ts).unwrap();
            plan.execute(Flags::default()).unwrap();
        }
        let posts = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        let comments = fs::read_to_string(tmp.path().join("src/routes/comments.rs")).unwrap();
        assert!(
            !posts.contains("fn layout(") && !comments.contains("fn layout("),
            "no generated routes file may define its own layout"
        );
    }

    /// Issue #1130, AC 4: scaffolding HTML views into an app with no shared
    /// `pub fn layout` fails with an actionable error rather than emitting
    /// routes that reference a nonexistent layout.
    #[test]
    fn scaffold_without_shared_layout_errors() {
        let tmp = project_with_main(main_without_layout());
        let err = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap_err();
        match err {
            GenerateError::Config(msg) => {
                assert!(
                    msg.contains("pub fn layout") && msg.contains("autumn new"),
                    "error must be actionable about the missing shared layout: {msg}"
                );
            }
            other => panic!("expected an actionable Config error, got: {other:?}"),
        }
    }

    /// Issue #1834: the shared-layout preflight is a generate-time guard only —
    /// it must NOT fire on the `autumn destroy scaffold` / revert path, or
    /// cleanup would hard-fail in a project whose shared `pub fn layout` is
    /// missing or renamed (e.g. one scaffolded by an older CLI), stranding the
    /// generated files. The revert-only plan builder must therefore succeed even
    /// when `src/main.rs` exposes no shared 4-arg layout, while still planning
    /// the routes file it will remove.
    #[test]
    fn scaffold_for_revert_succeeds_without_shared_layout() {
        let tmp = project_with_main(main_without_layout());
        let plan = plan_scaffold_with_options_for_revert(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions::default(),
        )
        .expect("destroy scaffold must build its revert plan without a shared layout");
        // Sanity: it still plans the HTML routes file a normal scaffold would, so
        // `Plan::revert` has something to remove.
        assert!(
            plan.actions.iter().any(|a| {
                a.path()
                    .display()
                    .to_string()
                    .replace('\\', "/")
                    .ends_with("src/routes/posts.rs")
            }),
            "revert plan should still include the HTML routes file it will remove"
        );

        // And the generate path over the SAME project still fails fast — the
        // guard is bypassed only for revert, never weakened for generation.
        let err = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap_err();
        assert!(
            matches!(err, GenerateError::Config(ref msg) if msg.contains("pub fn layout")),
            "generate path must still reject a missing shared layout: {err:?}"
        );
    }

    /// Issue #1130, AC 4: live scaffolds emit their OWN private 3-arg
    /// `fn layout` and never call `crate::layout`, so the shared-layout
    /// preflight must not run for them. Scaffolding `--live` into an app with
    /// no shared `pub fn layout` must succeed (reach route generation) rather
    /// than wrongly returning the shared-layout Config error.
    #[test]
    fn scaffold_live_without_shared_layout_succeeds() {
        let tmp = project_with_main(main_without_layout());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                live: true,
                ..Default::default()
            },
        )
        .expect("live scaffold is self-contained and needs no shared layout");
        // The live scaffold still emits an HTML routes file — it just renders
        // through its own private layout, not `crate::layout`.
        assert!(
            plan.actions.iter().any(|a| {
                a.path()
                    .display()
                    .to_string()
                    .replace('\\', "/")
                    .ends_with("src/routes/posts.rs")
            }),
            "live scaffold must still plan an HTML routes file"
        );
    }

    /// Issue #1130, AC 4: a `pub fn layout` with the wrong arity (e.g. an older
    /// 2-arg `pub fn layout(title, content)`) does NOT match the 4-arg
    /// `crate::layout(title, current_path, flash, content)` the scaffold emits,
    /// so the routes would fail to compile. Detect this at preflight and return
    /// the actionable Config error rather than passing on a mismatched layout.
    #[test]
    fn scaffold_with_wrong_arity_layout_errors() {
        let wrong_arity_main = r#"use autumn_web::prelude::*;

pub fn layout(title: &str, content: maud::Markup) -> maud::Markup {
    maud::html! {
        title { (title) }
        (content)
    }
}

#[get("/")]
async fn index() -> &'static str { "ok" }

#[autumn_web::main]
async fn main() {
    autumn_web::app()
        .routes(routes![index])
        .run()
        .await;
}
"#;
        let tmp = project_with_main(wrong_arity_main);
        let err = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap_err();
        match err {
            GenerateError::Config(msg) => {
                assert!(
                    msg.contains("pub fn layout") && msg.contains("autumn new"),
                    "a 2-arg `pub fn layout` must not satisfy the shared-layout \
                     check; error must stay actionable: {msg}"
                );
            }
            other => panic!("expected an actionable Config error, got: {other:?}"),
        }
    }

    /// Issue #1130, AC 4: a decoy `pub fn layout_sidebar` (a name that merely
    /// starts with `layout`) must NOT satisfy the shared-layout check — only a
    /// real 4-arg `pub fn layout(...)` counts. Scaffolding against such an app
    /// still fails with the actionable Config error.
    #[test]
    fn scaffold_with_decoy_layout_prefix_errors() {
        let decoy_main = r#"use autumn_web::prelude::*;

pub fn layout_sidebar(title: &str) -> maud::Markup {
    maud::html! { title { (title) } }
}

#[get("/")]
async fn index() -> &'static str { "ok" }

#[autumn_web::main]
async fn main() {
    autumn_web::app()
        .routes(routes![index])
        .run()
        .await;
}
"#;
        let tmp = project_with_main(decoy_main);
        let err = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap_err();
        match err {
            GenerateError::Config(msg) => {
                assert!(
                    msg.contains("pub fn layout") && msg.contains("autumn new"),
                    "a `layout_sidebar` decoy must not satisfy the shared-layout \
                     check; error must stay actionable: {msg}"
                );
            }
            other => panic!("expected an actionable Config error, got: {other:?}"),
        }
    }

    /// Issue #1130, AC 4: a commented-out `pub fn layout` decoy that appears on
    /// a line ABOVE the real 4-arg `pub fn layout(...)` must NOT short-circuit
    /// the shared-layout check. The scanner must ignore the commented match and
    /// find the real one, so the scaffold succeeds (reaches route generation).
    #[test]
    fn scaffold_layout_commented_decoy_above_real_is_accepted() {
        let commented_then_real = r#"use autumn_web::prelude::*;

// pub fn layout(title, content) -- old 2-arg signature, kept for reference
pub fn layout(title: &str, current_path: &str, flash: maud::Markup, content: maud::Markup) -> maud::Markup {
    let _ = (current_path, flash);
    maud::html! {
        title { (title) }
        (content)
    }
}

#[get("/")]
async fn index() -> &'static str { "ok" }

#[autumn_web::main]
async fn main() {
    autumn_web::app()
        .routes(routes![index])
        .run()
        .await;
}
"#;
        let tmp = project_with_main(commented_then_real);
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .expect("a real 4-arg layout below a commented decoy must satisfy the check");
        assert!(
            plan.actions.iter().any(|a| {
                a.path()
                    .display()
                    .to_string()
                    .replace('\\', "/")
                    .ends_with("src/routes/posts.rs")
            }),
            "scaffold must plan an HTML routes file when a real shared layout exists"
        );
    }

    /// Issue #1130, AC 4: a `pub fn layout(...)` token that only appears inside a
    /// comment (with no real crate-root layout function) must NOT satisfy the
    /// shared-layout check — the generated routes would call a nonexistent
    /// `crate::layout`. The scanner must ignore commented tokens and still fail
    /// with the actionable Config error.
    #[test]
    fn scaffold_layout_only_in_comment_errors() {
        let only_comment_main = r#"use autumn_web::prelude::*;

// pub fn layout(title, current_path, flash, content) -- TODO: add a shared layout
#[get("/")]
async fn index() -> &'static str { "ok" }

#[autumn_web::main]
async fn main() {
    autumn_web::app()
        .routes(routes![index])
        .run()
        .await;
}
"#;
        let tmp = project_with_main(only_comment_main);
        let err = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap_err();
        match err {
            GenerateError::Config(msg) => {
                assert!(
                    msg.contains("pub fn layout") && msg.contains("autumn new"),
                    "a commented-only `pub fn layout` must not satisfy the \
                     shared-layout check; error must stay actionable: {msg}"
                );
            }
            other => panic!("expected an actionable Config error, got: {other:?}"),
        }
    }

    /// Issue #1130, AC 4: `--api` scaffolds emit no HTML views, so they need no
    /// shared layout and must still succeed against a layout-less app.
    #[test]
    fn scaffold_api_only_without_layout_succeeds() {
        let tmp = project_with_main(main_without_layout());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                api: true,
                ..Default::default()
            },
        )
        .expect("api-only scaffold needs no shared layout");
        plan.execute(Flags::default()).unwrap();
        assert!(
            !tmp.path().join("src/routes/posts.rs").exists(),
            "api-only scaffold must not emit an HTML routes file"
        );
    }

    #[test]
    fn execute_writes_smoke_test() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(tmp.path(), "Post", &[], "20260427000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();
        assert!(test.contains("posts_index_renders_scaffolded_rows"));
        assert!(!test.contains("AUTUMN_TEST_SESSION_COOKIE"));
        assert!(!test.contains("Cookie: {session_cookie}"));
        assert!(test.contains("/posts"));
    }

    // ── write-path CRUD smoke tests (issue #1127) ─────────────────────────

    #[test]
    fn smoke_test_emits_write_path_crud_and_validation_rerender() {
        // Issue #1127: the generated suite must exercise create/update/delete
        // AND the validation-failure re-render, not just the read index — even
        // for a resource that declares no `--validate` rules of its own (the
        // write-path stand-in carries its own validated field).
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(tmp.path(), "Post", &[], "20260427000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();

        // The write-path test function is present.
        assert!(
            test.contains("async fn posts_write_path_crud()"),
            "write-path CRUD test must be emitted: {test}"
        );

        // Create (happy path): POST that redirects (303) to the index route.
        assert!(
            test.contains(".post(\"/posts\")"),
            "must POST to the create route: {test}"
        );
        assert!(
            test.contains(".assert_status(303)"),
            "create/update/delete must assert a 302/303 redirect: {test}"
        );
        assert!(
            test.contains(".assert_header(\"location\", \"/posts\")"),
            "redirects must be asserted to target the index route: {test}"
        );

        // Update (happy path): POST to the `/update` route.
        assert!(
            test.contains(".post(\"/posts/1/update\")"),
            "must POST to the update route: {test}"
        );

        // Delete: POST to the generated HTML `/delete` action (#1021).
        assert!(
            test.contains(".post(\"/posts/1/delete\")"),
            "must POST to the HTML delete action: {test}"
        );

        // Validation failure: an invalid create re-renders at 422 with an inline
        // error and the preserved input, and does NOT redirect.
        assert!(
            test.contains(".assert_status(422)"),
            "invalid create must re-render at 422: {test}"
        );
        assert!(
            test.contains("role=\\\"alert\\\""),
            "invalid create must assert an inline (role=\"alert\") error: {test}"
        );
    }

    #[test]
    fn write_path_smoke_test_emits_redirect_persist_and_validation_shapes() {
        // String-shape check (this test does not itself run the emitted test):
        // assert the emitted handlers carry the constructs that give the
        // generated test its failure power — a real redirect (not a 200
        // meta-refresh), a cross-request store the create/update/delete mutate,
        // a validation gate, and row-count reads. A broken generated handler
        // (200 instead of a redirect, a no-op delete, a create that skips
        // validation) would then turn the generated test red at runtime; that
        // runtime red-spike is exercised by
        // `generated_validated_scaffold_round_trip_test_passes` in
        // `tests/generate.rs`.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(tmp.path(), "Post", &[], "20260427000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();

        // A real redirect response (303 See Other via `Redirect::to`), not a
        // 200 meta-refresh page — so `assert_status(303)` has teeth.
        assert!(
            test.contains("Redirect::to(\"/posts\")"),
            "create/update/delete stand-ins must issue a real redirect: {test}"
        );
        // A real, cross-request store so persistence is observable on re-read —
        // the create pushes, update mutates, delete removes.
        assert!(
            test.contains("STORE.lock().unwrap()"),
            "handlers must read/write the shared store so persistence is observable: {test}"
        );
        assert!(
            test.contains("store.push(") && test.contains(".retain("),
            "create must persist and delete must remove from the store: {test}"
        );
        // The create actually gates on validation (the 422 branch is reachable).
        assert!(
            test.contains("form.into_valid()"),
            "create must validate the submission through the real changeset round-trip: {test}"
        );
        // The follow-up read proves the row count changed (persist / delete),
        // not just that a status code came back.
        assert!(
            test.contains(".assert_body_contains(\"1 row(s)\")")
                && test.contains(".assert_body_contains(\"0 row(s)\")"),
            "reads must assert the row count so persistence/removal is observable: {test}"
        );
    }

    #[test]
    fn write_path_smoke_test_emits_csrf_posture_note() {
        // Issue #1127: the write-path tests must account for CSRF. `TestApp`
        // disables CSRF by default (mirroring the real form_for-injected token
        // that the in-process harness does not require), and the emitted test
        // documents that so the missing `_csrf` field is intentional, not a bug.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(tmp.path(), "Post", &[], "20260427000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();
        assert!(
            test.contains("CSRF"),
            "the write-path test must document its CSRF posture: {test}"
        );
    }

    // ── in-process TestApp/TestClient smoke test (issue #1023) ────────────

    #[test]
    fn smoke_test_uses_in_process_test_app_not_tcp_stream() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(tmp.path(), "Post", &[], "20260427000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();

        // Uses the real in-process harness -- no raw sockets, no env-var gate.
        assert!(
            test.contains("autumn_web::test::{TestApp, TestClient, TestDb}"),
            "smoke test must use the TestApp/TestClient/TestDb harness: {test}"
        );
        assert!(
            !test.contains("TcpStream"),
            "smoke test must not hand-roll a raw TCP request: {test}"
        );
        assert!(
            !test.contains("AUTUMN_TEST_BASE_URL"),
            "smoke test must not gate on a running server's base URL: {test}"
        );
        assert!(
            !test.contains("eprintln!(\"skipping"),
            "smoke test must not silently skip via an env-gated return: {test}"
        );

        // DB-backed handler: a Docker-backed test is a *visible* `ignored`,
        // never a silent green pass, and carries an explicit reason.
        assert!(
            test.contains("#[ignore = \"requires Docker"),
            "DB-backed smoke test must be explicitly #[ignore]d with a reason: {test}"
        );

        // Real assertions: 200 plus the rendered heading.
        assert!(test.contains(".assert_ok()"));
        assert!(test.contains(".assert_body_contains(\"Posts\")"));
    }

    #[test]
    fn smoke_test_index_handler_returns_wrong_status_fails_the_assertion() {
        // Red-phase spike: if the (re-declared) handler under test returned the
        // wrong status or dropped the heading, `assert_ok`/`assert_body_contains`
        // must be the thing that fails -- i.e. the test has real failure power,
        // not just a status check that always trivially passes.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(tmp.path(), "Post", &[], "20260427000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();

        assert!(
            test.contains("Ok(html! {"),
            "handler must actually render Markup that assert_body_contains can inspect: {test}"
        );
        assert!(
            test.contains("h1 { \"Posts\" }"),
            "handler must render the heading the test asserts on: {test}"
        );
        // The count query touches the real (throwaway) database -- a broken
        // query or handler bubbles up as an Err via `?`, which axum turns into
        // a non-200 response, which `assert_ok()` then catches.
        assert!(test.contains(".get_result(&mut db).await?;"));
    }

    #[test]
    fn smoke_test_wires_dev_dependency_test_support() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(tmp.path(), "Post", &[], "20260427000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let cargo = fs::read_to_string(tmp.path().join("Cargo.toml")).unwrap();
        assert!(
            cargo.contains("[dev-dependencies]"),
            "Cargo.toml must have a [dev-dependencies] section: {cargo}"
        );
        assert!(
            cargo.contains("test-support"),
            "Cargo.toml must enable autumn-web's test-support feature for TestDb: {cargo}"
        );
        // Must not leak into the production dependency set.
        let deps_section = cargo.split("[dev-dependencies]").next().unwrap();
        assert!(
            !deps_section.contains("test-support"),
            "test-support must stay out of [dependencies]: {cargo}"
        );
    }

    #[test]
    fn destroying_the_only_scaffold_keeps_pre_existing_test_support_another_test_still_uses() {
        // issue #1048 PR review: a project may already have `autumn-web`
        // under `[dev-dependencies]` with `test-support` enabled for its
        // OWN hand-written tests, independent of any scaffold.
        // `ensure_dev_dependency_test_support` makes no Cargo.toml edit in
        // that case, but the revert is still recorded unconditionally —
        // must not strip `test-support` out from under that unrelated test
        // when destroying the only scaffold.
        let tmp = project_with_main(default_main());
        fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname=\"x\"\n\n[dev-dependencies]\nautumn-web = { version = \"0.6\", features = [\"test-support\"] }\n",
        )
        .unwrap();
        fs::create_dir_all(tmp.path().join("tests")).unwrap();
        fs::write(
            tmp.path().join("tests/hand_written.rs"),
            "#[tokio::test]\nasync fn it_works() {\n    let _db = autumn_web::test::TestDb::shared().await;\n}\n",
        )
        .unwrap();

        let plan = plan_scaffold(tmp.path(), "Post", &[], "20260427000000").unwrap();
        plan.execute(Flags::default()).unwrap();

        let destroy_plan = plan_scaffold(tmp.path(), "Post", &[], "99999999999999").unwrap();
        destroy_plan.revert(Flags::default()).unwrap();

        let cargo_after = fs::read_to_string(tmp.path().join("Cargo.toml")).unwrap();
        assert!(
            cargo_after.contains("test-support"),
            "pre-existing test-support must survive — the hand-written test still uses \
             TestDb: {cargo_after}"
        );
    }

    #[test]
    fn smoke_test_wires_dev_dependency_tokio_test_features() {
        // Regression test (Codex review, issue #1023): the generated smoke
        // test uses `#[tokio::test]`, which needs the `rt` and `macros`
        // tokio features to compile. A project not created from `autumn
        // new` -- like this test's bare Cargo.toml -- has no tokio
        // dev-dependency at all, so without this wiring the generated test
        // target would fail to compile (cargo test --tests still compiles
        // #[ignore]d tests).
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(tmp.path(), "Post", &[], "20260427000000").unwrap();
        plan.execute(Flags::default()).unwrap();
        let cargo = fs::read_to_string(tmp.path().join("Cargo.toml")).unwrap();
        let tokio_line = cargo
            .lines()
            .find(|l| l.trim_start().starts_with("tokio"))
            .unwrap_or_else(|| panic!("Cargo.toml must have a tokio dev-dependency: {cargo}"));
        assert!(
            tokio_line.contains("\"rt\"") && tokio_line.contains("\"macros\""),
            "tokio dev-dependency must enable rt and macros for #[tokio::test]: {tokio_line}"
        );
    }

    #[test]
    fn delete_button_has_destructive_confirmation() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        // The delete button must require an explicit confirmation so a single
        // misclick cannot silently destroy a row (AC: destructive confirmation).
        assert!(
            routes.contains(r#"onclick="return confirm("#) || routes.contains("hx-confirm="),
            "delete button must have an onclick confirm or hx-confirm: {routes}"
        );
    }

    #[test]
    fn smoke_test_write_path_stays_in_process_never_over_a_socket() {
        // The old create/delete round-trip test hit a *running server* over a
        // raw TcpStream, gated on `AUTUMN_TEST_BASE_URL` -- the very
        // false-positive-green pattern issue #1023 fixed. Issue #1127 restores
        // write-path coverage (create -> redirect, update, delete, plus the
        // validation-failure re-render) but it must stay in-process via the
        // `TestApp`/`TestClient` harness -- never the old socket-based,
        // env-gated, silently-skipping shape.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();
        // None of the old false-positive-green machinery may come back.
        assert!(
            !test.contains("TcpStream"),
            "write-path tests must not hand-roll a raw TCP request: {test}"
        );
        assert!(
            !test.contains("AUTUMN_TEST_BASE_URL"),
            "write-path tests must not gate on a running server's base URL: {test}"
        );
        // The write-path suite is present and in-process alongside the read one:
        // the index/read test plus the write-path CRUD test.
        assert_eq!(
            test.matches("#[tokio::test]").count(),
            2,
            "expected the read smoke test plus the write-path CRUD test: {test}"
        );
        assert!(test.contains("posts_index_renders_scaffolded_rows"));
        assert!(test.contains("posts_write_path_crud"));
    }

    #[test]
    fn dry_run_does_not_modify_main() {
        let tmp = project_with_main(default_main());
        let original = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        let plan = plan_scaffold(tmp.path(), "Post", &[], "20260427000000").unwrap();
        plan.execute(Flags {
            dry_run: true,
            force: false,
        })
        .unwrap();
        let after = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert_eq!(original, after);
    }

    #[test]
    fn collision_lists_existing_files_without_force() {
        let tmp = project_with_main(default_main());
        // Pre-create one of the files so the next run collides.
        let dir = tmp.path().join("src/models");
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join("post.rs"), "// existing").unwrap();
        let plan = plan_scaffold(tmp.path(), "Post", &[], "20260427000000").unwrap();
        let err = plan.execute(Flags::default()).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("post.rs"));
    }

    // ── Soft-delete scaffold generation (issue #689) ──────────────

    #[test]
    fn scaffold_soft_delete_destroy_handler_marks_deleted_at_not_physical_delete() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    soft_delete: true,
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        // The browser delete button must respect soft-delete: mark deleted_at,
        // matching the soft-delete repository, instead of physically deleting.
        assert!(
            routes.contains("posts::deleted_at.eq(Some(chrono::Utc::now().naive_utc()))"),
            "soft-delete destroy must mark deleted_at: {routes}"
        );
        assert!(
            routes.contains("posts::deleted_at.is_null()"),
            "soft-delete destroy must skip already-deleted rows so a repeat delete 404s: {routes}"
        );
        assert!(
            !routes.contains("diesel::delete(posts::table.find(*id))"),
            "soft-delete destroy must not physically delete the row: {routes}"
        );
    }

    #[test]
    fn scaffold_without_soft_delete_destroy_handler_physically_deletes() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(
            routes.contains("diesel::delete(posts::table.find(*id))"),
            "non-soft-delete destroy must issue a physical delete: {routes}"
        );
        assert!(
            !routes.contains("deleted_at.eq("),
            "non-soft-delete destroy must not mark deleted_at: {routes}"
        );
    }

    #[test]
    fn scaffold_soft_delete_repository_annotation_includes_soft_delete() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    soft_delete: true,
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let repo = fs::read_to_string(tmp.path().join("src/repositories/post.rs")).unwrap();
        assert!(
            repo.contains("soft_delete"),
            "repository file must include soft_delete in the #[repository] annotation: {repo}"
        );
    }

    #[test]
    fn scaffold_soft_delete_model_includes_deleted_at_field() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    soft_delete: true,
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let model = fs::read_to_string(tmp.path().join("src/models/post.rs")).unwrap();
        assert!(
            model.contains("deleted_at"),
            "model struct must include deleted_at field when soft_delete is enabled: {model}"
        );
        // Regression test: `deleted_at` must be excluded from `NewX`/`UpdateX`
        // via `#[default]` -- it's DB-managed (NULL on insert, set only by the
        // destroy handler), so neither the create nor update handler ever
        // populates it. Without `#[default]` here, `#[model]` treats it as a
        // required field and the generated `create` handler fails to compile
        // (`NewPost { .. }` missing `deleted_at`).
        assert!(
            model.contains("#[default]\n    pub deleted_at:"),
            "deleted_at must be #[default] (DB-managed, excluded from NewX/UpdateX): {model}"
        );
        // Regression test: the model struct's field order must match the
        // column order `create_table_sql_with_metadata_and_id`/
        // `schema_table_block_with_id` emit for the migration and
        // `schema.rs` (soft-delete field before `created_at`, which is
        // always appended last). The `#[repository]` macro's generated
        // insert-then-`RETURNING` query loads into this struct positionally,
        // so a mismatched order produces a Diesel `CompatibleType` error at
        // compile time rather than at the point of the actual typo.
        let deleted_at_pos = model.find("pub deleted_at:").expect("deleted_at field");
        let created_at_pos = model.find("pub created_at:").expect("created_at field");
        assert!(
            deleted_at_pos < created_at_pos,
            "deleted_at must be declared before created_at, matching schema.rs's column order: {model}"
        );

        let schema = fs::read_to_string(tmp.path().join("src/schema.rs")).unwrap();
        let schema_deleted_at_pos = schema.find("deleted_at ->").expect("deleted_at column");
        let schema_created_at_pos = schema.find("created_at ->").expect("created_at column");
        assert!(
            schema_deleted_at_pos < schema_created_at_pos,
            "schema.rs must declare deleted_at before created_at: {schema}"
        );
    }

    #[test]
    fn scaffold_soft_delete_smoke_test_table_includes_deleted_at() {
        // Regression test (code review, issue #1023): the smoke test's
        // throwaway CREATE TABLE must use the same soft-delete-augmented field
        // list as the real migration, so it doesn't drift from the actual
        // schema for --soft-delete models.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    soft_delete: true,
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let migration = fs::read_to_string(
            tmp.path()
                .join("migrations/20260427000000_create_posts/up.sql"),
        )
        .unwrap();
        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();
        assert!(
            migration.contains("deleted_at"),
            "real migration must include deleted_at: {migration}"
        );
        assert!(
            test.contains("deleted_at"),
            "smoke test's throwaway table must match the real migration schema \
             and include deleted_at for a --soft-delete model: {test}"
        );
    }

    #[test]
    fn scaffold_without_soft_delete_does_not_include_soft_delete_annotation() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let repo = fs::read_to_string(tmp.path().join("src/repositories/post.rs")).unwrap();
        assert!(
            !repo.contains("soft_delete"),
            "repository without soft_delete must not include soft_delete annotation: {repo}"
        );
    }

    #[test]
    fn execute_writes_zero_js_multipart_attachment_handlers() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "avatar:Attachment".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        // Issue #1236: attachments upload with zero JavaScript via a plain
        // `multipart/form-data` submit. The attachment is promoted to
        // `FieldControl::File`, which renders a plain `<input type="file">`
        // (no `.exclude` + hand-rolled append, no hidden key input) and flips
        // the `form_for` `<form>` to `multipart/form-data`.
        assert!(
            routes.contains(".override_field(\"avatar\", autumn_web::form::FieldControl::File)"),
            "{routes}"
        );
        assert!(!routes.contains(".exclude(\"avatar\")"), "{routes}");
        assert!(
            !routes.contains(
                "input type=\"hidden\" name=\"avatar\" value=(changeset.field_value(\"avatar\")"
            ),
            "no hidden presign-key input any more: {routes}"
        );

        // The create/update handlers take a Multipart body (last param) and
        // stream file parts to the blob store — no `body: Bytes`, no presign
        // dead-end (`complete_direct_upload`) in the default path.
        assert!(
            routes.contains("mut multipart: autumn_web::extract::Multipart"),
            "{routes}"
        );
        assert!(
            routes.contains(".save_to_blob_store(&*store, key).await?"),
            "{routes}"
        );
        // The default code path must not CALL the presign helper (the header
        // note may still mention `complete_direct_upload()` as an advanced
        // opt-in — AC5 — so match the invocation, not the bare name).
        assert!(
            !routes.contains("complete_direct_upload(&"),
            "default path must not call the presign helper: {routes}"
        );
        assert!(routes.contains("multipart.next_field().await?"), "{routes}");

        // Preserve-on-update: an edit with no new file keeps the stored blob.
        assert!(
            routes.contains("new.avatar = avatar_blob.or(current.avatar);"),
            "{routes}"
        );
        // Create binds the streamed blob directly (None => NULL column).
        assert!(routes.contains("new.avatar = avatar_blob;"), "{routes}");

        // The attachment is NOT part of the urlencodable form struct any more,
        // and `into_new` is sync (no `&state`), seeding the blob column to None.
        assert!(routes.contains("pub struct PostForm"));
        assert!(!routes.contains("pub avatar: Option<String>"), "{routes}");
        assert!(!routes.contains("async fn into_new("), "{routes}");
        assert!(routes.contains("fn into_new(form: &PostForm)"), "{routes}");
        assert!(routes.contains("avatar: None,"), "{routes}");

        // The header note documents the zero-JS multipart path and demotes the
        // presign path to an advanced opt-in.
        assert!(routes.contains("ZERO"), "{routes}");
        assert!(routes.contains("save_to_blob_store"), "{routes}");
        assert!(routes.contains("ADVANCED (opt-in)"), "{routes}");
        // AC7 (storage + multipart feature auto-enable) needs a real
        // `autumn-web` dependency line to modify, which this stub-Cargo.toml
        // harness doesn't provide; it is proven end-to-end by the integration
        // test `scaffold_attachment_emits_zero_js_multipart_handlers`.
    }

    // ── Typed form-input widgets (issue #1131) ──────────────────────

    #[test]
    fn execute_writes_checkbox_for_bool_field() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "active:bool".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        // Bool fields map to a checkbox in the derived `FormModel`
        // descriptors (issue #1135) — no per-field helper line and no
        // `form_for` override needed in the routes file.
        assert!(
            !routes.contains("autumn_web::form::checkbox_input(&changeset"),
            "{routes}"
        );
        assert!(
            !routes.contains(".override_field(\"active\""),
            "bool fields need no form_for override: {routes}"
        );
        assert!(
            !routes.contains("input type=\"text\" name=\"active\""),
            "bool field must not render input type=\"text\": {routes}"
        );
        // The form struct must default the bool so an unchecked submission
        // (missing key) doesn't 400.
        assert!(
            routes.contains("#[serde(default)]\n    pub active: bool,"),
            "{routes}"
        );
    }

    #[test]
    fn execute_writes_select_for_nullable_bool_field() {
        // A checkbox can't losslessly represent Option<bool> (no way to
        // distinguish "leave false" from "set to null" when unchecked), so
        // nullable bool fields must render a 3-option select instead.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "archived:Option<bool>".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        assert!(
            !routes.contains("input type=\"checkbox\" name=\"archived\""),
            "nullable bool must not render a checkbox: {routes}"
        );
        // A nullable bool maps to a 3-option select (unset/true/false) in the
        // derived `FormModel` descriptors (issue #1135) — no per-field helper
        // line and no `form_for` override needed in the routes file.
        assert!(
            !routes.contains("autumn_web::form::select_input(&changeset"),
            "{routes}"
        );
        assert!(
            !routes.contains(".override_field(\"archived\""),
            "nullable bool fields need no form_for override: {routes}"
        );
        // The form field is an Option<bool> so a blank submission stays None.
        assert!(routes.contains("pub archived: Option<bool>,"), "{routes}");
    }

    #[test]
    fn execute_writes_number_input_for_integer_fields() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "views:i64".into(), "rank:i32".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        // Integer fields map to a stepped number control in the derived
        // `FormModel` descriptors (issue #1135) — no per-field helper line
        // and no `form_for` override needed in the routes file.
        assert!(
            !routes.contains("autumn_web::form::required_number_input(&changeset"),
            "{routes}"
        );
        for field in ["views", "rank"] {
            assert!(
                !routes.contains(&format!(".override_field(\"{field}\"")),
                "integer fields need no form_for override: {routes}"
            );
        }
        assert!(
            !routes.contains("input type=\"text\" name=\"views\""),
            "{routes}"
        );
    }

    #[test]
    fn execute_writes_number_input_with_any_step_for_float_fields() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "price:f64".into(),
                "weight:f32".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        // Float fields map to a free-step number control in the derived
        // `FormModel` descriptors (issue #1135) — no per-field helper line
        // and no `form_for` override needed in the routes file.
        assert!(
            !routes.contains("autumn_web::form::required_number_input(&changeset"),
            "{routes}"
        );
        for field in ["price", "weight"] {
            assert!(
                !routes.contains(&format!(".override_field(\"{field}\"")),
                "float fields need no form_for override: {routes}"
            );
        }
    }

    #[test]
    fn execute_writes_number_input_reads_value_from_changeset() {
        // A required numeric field is represented as a `String` on the form
        // (issue #1124 review): `f64::default()` is `0.0`, a real value, not
        // "blank" — a native-typed field would render `0` as the blank
        // new-form's pre-filled value instead of leaving the input empty.
        // `into_new` parses it back, and a bad value is a 400 (undecodable
        // input), matching the enum/datetime convention.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "price:f64".into(),
                "weight:Option<f32>".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(routes.contains("pub price: String,"), "{routes}");
        assert!(
            routes.contains(
                "price: form.price.parse::<f64>()\n        .map_err(|err| autumn_web::AutumnError::bad_request_msg(format!(\"price: {err}\")))?,"
            ),
            "{routes}"
        );
        assert!(
            routes.contains("price: row.price.to_string(),"),
            "the edit-form seed copies the float from the row: {routes}"
        );
        // A nullable float of the same kind keeps its native Option<T> type —
        // `None` is already blank, no String indirection needed.
        assert!(routes.contains("pub weight: Option<f32>,"), "{routes}");
    }

    #[test]
    fn execute_writes_required_references_field_as_string_on_form() {
        // A required `references` (foreign key) field is `i64` at the model
        // layer, same as any other required integer — it needs the same
        // String-wire treatment as I32/I64/Uuid/Decimal (issue #1124 review):
        // `i64::default()` is `0`, a real (and likely invalid) foreign key
        // value, not "blank".
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Comment",
            &["body:String".into(), "post:references".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/comments.rs")).unwrap();
        assert!(routes.contains("pub post_id: String,"), "{routes}");
        assert!(
            routes.contains(
                "post_id: form.post_id.parse::<i64>()\n        .map_err(|err| autumn_web::AutumnError::bad_request_msg(format!(\"post_id: {err}\")))?,"
            ),
            "{routes}"
        );
        assert!(
            routes.contains("post_id: row.post_id.to_string(),"),
            "{routes}"
        );
    }

    #[test]
    fn execute_writes_required_bytea_field_as_string_on_form() {
        // `Vec<u8>` cannot deserialize from a single url-encoded value at all
        // (issue #1124 review) — represented as a lossy-UTF8 `String` on the
        // form instead, matching what the old hand-rolled edit form already
        // displayed via `String::from_utf8_lossy`, and converted back with
        // `.into_bytes()` on the success path.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "payload:Bytea".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(routes.contains("pub payload: String,"), "{routes}");
        assert!(
            routes.contains("payload: form.payload.clone().into_bytes(),"),
            "{routes}"
        );
        assert!(
            routes.contains("payload: String::from_utf8_lossy(&row.payload).into_owned(),"),
            "{routes}"
        );
    }

    #[test]
    fn execute_writes_nullable_bytea_field_as_option_string_on_form() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "payload:Option<Bytea>".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(routes.contains("pub payload: Option<String>,"), "{routes}");
        assert!(
            routes.contains(
                "payload: form.payload.as_ref().map(|value| value.clone().into_bytes()),"
            ),
            "{routes}"
        );
        assert!(
            routes.contains(
                "payload: row.payload.as_ref().map(|value| String::from_utf8_lossy(value).into_owned()),"
            ),
            "{routes}"
        );
    }

    #[test]
    fn execute_writes_number_input_value_on_edit_form() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "views:i64".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        // The edit form seeds the changeset from the row; the number control
        // (from the derived `FormModel` descriptors) reads the value back
        // through `form_for` (issues #1124/#1135).
        assert!(routes.contains("views: row.views.to_string(),"), "{routes}");
    }

    #[test]
    fn execute_writes_datetime_local_input_for_naive_datetime_field() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "published_at:NaiveDateTime".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        // Datetime fields map to a datetime-local control in the derived
        // `FormModel` descriptors (issue #1135) — no per-field helper line
        // and no `form_for` override needed in the routes file.
        assert!(
            !routes.contains("autumn_web::form::required_datetime_input(&changeset"),
            "{routes}"
        );
        assert!(
            !routes.contains(".override_field(\"published_at\""),
            "datetime fields need no form_for override: {routes}"
        );
        assert!(
            !routes.contains("input type=\"text\" name=\"published_at\""),
            "{routes}"
        );
        // On the form the field is a String (the browser wire shape); it's
        // parsed back into the model type in `into_new`.
        assert!(routes.contains("pub published_at: String,"), "{routes}");
        assert!(
            routes.contains("published_at: parse_local_datetime(&form.published_at)?,"),
            "{routes}"
        );
        // The edit-form seed formats the row's timestamp for the datetime-local
        // control, preserving fractional seconds so a no-op resubmit doesn't
        // truncate the stored value (the update handler writes every column
        // back unconditionally).
        assert!(
            routes.contains(
                "published_at: row.published_at.format(\"%Y-%m-%dT%H:%M:%S%.f\").to_string(),"
            ),
            "{routes}"
        );
    }

    #[test]
    fn execute_writes_datetime_local_input_for_tz_datetime_field() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "scheduled_at:DateTime".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        // The datetime-local control comes from the derived `FormModel`
        // descriptors (issue #1135) — no per-field line or override needed.
        assert!(
            !routes.contains(".override_field(\"scheduled_at\""),
            "{routes}"
        );
        assert!(routes.contains("pub scheduled_at: String,"), "{routes}");
        // A tz-aware field parses to naive-local then attaches UTC.
        assert!(
            routes.contains("scheduled_at: parse_local_datetime(&form.scheduled_at)?.and_utc(),"),
            "{routes}"
        );
    }

    #[test]
    fn execute_writes_datetime_local_input_for_nullable_datetime_field() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "published_at:Option<NaiveDateTime>".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        // Nullable datetime is an Option<String> on the form, parsed only when
        // non-empty in `into_new` (issue #1124).
        assert!(
            routes.contains("pub published_at: Option<String>,"),
            "{routes}"
        );
        assert!(
            routes.contains("form.published_at.as_deref().filter(|value| !value.is_empty())"),
            "{routes}"
        );
        // The old serde deserialize-with helpers are no longer needed.
        assert!(
            !routes.contains("fn deserialize_option_naive_datetime_local"),
            "{routes}"
        );
    }

    #[test]
    fn execute_writes_text_input_only_for_genuine_string_fields() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "body:Text".into(),
                "active:bool".into(),
                "views:i64".into(),
                "published_at:NaiveDateTime".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        // Control selection per kind (text vs checkbox vs number vs
        // datetime-local, required or not) lives in the derived `FormModel`
        // descriptors (issue #1135): the routes file renders everything
        // through the single shared `form_for` helper, with no per-field
        // helper lines and no overrides for these plain kinds.
        assert!(routes.contains("fn post_form_for("), "{routes}");
        for helper in [
            "text_input",
            "required_text_input",
            "checkbox_input",
            "required_number_input",
            "required_datetime_input",
        ] {
            assert!(
                !routes.contains(&format!("autumn_web::form::{helper}(&changeset")),
                "no per-field {helper} lines may remain: {routes}"
            );
        }
        assert!(!routes.contains(".override_field("), "{routes}");
        // No hand-rolled bare text inputs remain for the non-string fields.
        assert!(
            !routes.contains("input type=\"text\" name=\"active\""),
            "{routes}"
        );
        assert!(
            !routes.contains("input type=\"text\" name=\"views\""),
            "{routes}"
        );
        assert!(
            !routes.contains("input type=\"text\" name=\"published_at\""),
            "{routes}"
        );
    }

    #[test]
    fn plan_scaffold_api_only_skips_html() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                api: true,
                ..Default::default()
            },
        )
        .unwrap();
        let paths: Vec<String> = plan
            .actions
            .iter()
            .map(|a| {
                a.path()
                    .strip_prefix(&plan.project_root)
                    .unwrap()
                    .display()
                    .to_string()
                    .replace('\\', "/")
            })
            .collect();
        assert!(!paths.iter().any(|p| p.contains("src/routes/posts.rs")));
        assert!(!paths.iter().any(|p| p.contains("src/routes/mod.rs")));
    }

    #[test]
    fn plan_scaffold_api_only_mounts_all_five_json_endpoints() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                api: true,
                ..Default::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert!(main.contains("repositories::post::post_api_create"));
        assert!(main.contains("repositories::post::post_api_update"));
        assert!(main.contains("repositories::post::post_api_delete"));
        assert!(main.contains("repositories::post::post_api_list"));
        assert!(main.contains("repositories::post::post_api_get"));
        assert!(!main.contains("routes::posts::index"));
    }

    // ── sharding tests ─────────────────────────────────────────────────────

    fn sharded_options_with_key(key: &str) -> ScaffoldOptions {
        ScaffoldOptions {
            model: ModelOptions {
                sharded: true,
                shard_key: Some(key.into()),
                ..Default::default()
            },
            ..Default::default()
        }
    }

    #[test]
    fn resolves_shard_key_explicit_field() {
        let fields = parse_fields(&["tenant_id:i64".into(), "name:String".into()]).unwrap();
        let opts = ModelOptions {
            sharded: true,
            shard_key: Some("tenant_id".into()),
            ..Default::default()
        };
        let key = resolve_shard_key(&fields, &opts).unwrap();
        assert_eq!(key, Some("tenant_id".to_owned()));
    }

    #[test]
    fn resolves_shard_key_explicit_id() {
        let fields = parse_fields(&["name:String".into()]).unwrap();
        let opts = ModelOptions {
            sharded: true,
            shard_key: Some("id".into()),
            ..Default::default()
        };
        let key = resolve_shard_key(&fields, &opts).unwrap();
        assert_eq!(key, Some("id".to_owned()));
    }

    #[test]
    fn resolves_shard_key_invalid_field_errors() {
        let fields = parse_fields(&["name:String".into()]).unwrap();
        let opts = ModelOptions {
            sharded: true,
            shard_key: Some("bogus".into()),
            ..Default::default()
        };
        assert!(
            resolve_shard_key(&fields, &opts).is_err(),
            "unknown shard_key field must return an error"
        );
    }

    #[test]
    fn resolves_shard_key_defaults_to_tenant_id_when_present() {
        let fields = parse_fields(&["tenant_id:i64".into(), "name:String".into()]).unwrap();
        let opts = ModelOptions {
            sharded: true,
            shard_key: None,
            ..Default::default()
        };
        let key = resolve_shard_key(&fields, &opts).unwrap();
        assert_eq!(key, Some("tenant_id".to_owned()));
    }

    #[test]
    fn resolves_shard_key_defaults_to_id_when_no_tenant_id() {
        let fields = parse_fields(&["name:String".into()]).unwrap();
        let opts = ModelOptions {
            sharded: true,
            shard_key: None,
            ..Default::default()
        };
        let key = resolve_shard_key(&fields, &opts).unwrap();
        assert_eq!(key, Some("id".to_owned()));
    }

    #[test]
    fn resolves_shard_key_none_when_not_sharded() {
        let fields = parse_fields(&["tenant_id:i64".into()]).unwrap();
        let opts = ModelOptions {
            sharded: false,
            shard_key: None,
            ..Default::default()
        };
        let key = resolve_shard_key(&fields, &opts).unwrap();
        assert!(key.is_none());
    }

    #[test]
    fn routes_use_sharded_db_when_sharded() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Account",
            &["tenant_id:i64".into(), "name:String".into()],
            "20260427000000",
            &sharded_options_with_key("tenant_id"),
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/accounts.rs")).unwrap();
        // ShardedDb must be imported from the correct path (not crate root).
        assert!(
            routes.contains("use autumn_web::sharding::ShardedDb;"),
            "sharded routes must import ShardedDb from autumn_web::sharding: {routes}"
        );
        // Db must NOT appear in the brace-import or as a handler param type.
        assert!(
            !routes.contains("mut db: Db"),
            "sharded routes must not use Db extractor: {routes}"
        );
        // ShardedDb must be used in handler signatures.
        assert!(
            routes.contains("mut db: ShardedDb"),
            "sharded routes must use ShardedDb in handler signatures: {routes}"
        );
        // index must call from_shard explicitly for a literal proof.
        assert!(
            routes.contains("from_shard(&db)"),
            "sharded index handler must call from_shard(&db): {routes}"
        );
    }

    /// `generate scaffold --sharded` on a `SQLite` app is rejected via the
    /// shared `plan_model_with_options` gate (issue #1614 AC #4) — sharding is
    /// permanently Postgres-only, so scaffold must refuse it the same way the
    /// model generator does. Proves one gate covers both entry points.
    #[test]
    fn scaffold_sharded_on_sqlite_app_is_rejected_as_postgres_only() {
        temp_env::with_vars(
            [
                ("AUTUMN_DATABASE__PRIMARY_URL", None::<&str>),
                ("AUTUMN_DATABASE__URL", None::<&str>),
                ("DATABASE_URL", None::<&str>),
            ],
            || {
                let tmp = project_with_main(default_main());
                fs::write(
                    tmp.path().join("autumn.toml"),
                    "[database]\nprimary_url = \"sqlite://app.db\"\n",
                )
                .unwrap();
                let err = plan_scaffold_with_options(
                    tmp.path(),
                    "Account",
                    &["tenant_id:i64".into(), "name:String".into()],
                    "20260427000000",
                    &sharded_options_with_key("tenant_id"),
                )
                .unwrap_err();
                let msg = err.to_string();
                assert!(
                    matches!(err, GenerateError::Config(_)),
                    "expected Config error, got: {err:?}"
                );
                assert!(
                    msg.contains("Postgres") && msg.contains("--sharded"),
                    "scaffold --sharded on SQLite must be rejected as Postgres-only: {msg}"
                );
            },
        );
    }

    #[test]
    fn routes_use_db_when_not_sharded() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(
            routes.contains("mut db: Db"),
            "non-sharded routes must still use Db"
        );
        assert!(
            !routes.contains("ShardedDb"),
            "non-sharded routes must not reference ShardedDb"
        );
    }

    #[test]
    fn repository_notes_sharded() {
        let rendered = render_repository_file(
            "Account",
            "account",
            &[],
            false,
            false,
            true,
            false,
            false,
            None,
        );
        assert!(
            rendered.contains("shard-aware"),
            "sharded repository doc must mention shard-aware: {rendered}"
        );
        assert!(
            rendered.contains("from_shard"),
            "sharded repository doc must mention from_shard: {rendered}"
        );
    }

    #[test]
    fn repository_notes_api_sharded_caveat() {
        let rendered = render_repository_file(
            "Account",
            "account",
            &[],
            false,
            true,
            true,
            false,
            false,
            None,
        );
        assert!(
            rendered.contains("control pool"),
            "sharded api repository doc must note control pool: {rendered}"
        );
    }

    #[test]
    fn repository_no_sharded_note_when_not_sharded() {
        let rendered =
            render_repository_file("Post", "post", &[], false, false, false, false, false, None);
        assert!(
            !rendered.contains("shard-aware"),
            "non-sharded repository must not mention shard-aware: {rendered}"
        );
    }

    #[test]
    fn plan_scaffold_api_only_emits_json_smoke_test() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into(), "published:bool".into()],
            "20260427000000",
            &ScaffoldOptions {
                api: true,
                ..Default::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let test_file = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();
        assert!(test_file.contains("/api/posts"));
        assert!(
            test_file.contains("autumn_web::test::{TestApp, TestClient, TestDb}"),
            "api smoke test must use the in-process harness: {test_file}"
        );
        assert!(!test_file.contains("TcpStream"));
        assert!(!test_file.contains("AUTUMN_TEST_BASE_URL"));
        assert!(
            test_file.contains("#[ignore = \"requires Docker"),
            "DB-backed api smoke test must be explicitly ignored with a reason: {test_file}"
        );
        assert!(!test_file.contains("contains(\"Posts\")"));
        // With a required column (`title:String`), the seed drives 25 rows off
        // a single `generate_series` and must NOT fall back to `DEFAULT VALUES`
        // (which cannot satisfy the `NOT NULL` column).
        assert!(
            test_file.contains("FROM generate_series(1, 25) AS g"),
            "required-column seed must use generate_series: {test_file}"
        );
        assert!(
            !test_file.contains("INSERT INTO posts DEFAULT VALUES"),
            "required-column seed must not fall back to DEFAULT VALUES: {test_file}"
        );
    }

    #[test]
    fn plan_scaffold_api_only_seeds_default_rows_when_no_required_columns() {
        // Regression (PR #1707 review): a model with no required (NOT NULL,
        // no-default) column must still seed 25 rows. The old fix degenerated
        // to a targetless `INSERT INTO <plural> SELECT FROM generate_series`,
        // which is INVALID Postgres — a zero-column SELECT is matched against
        // every column (id included) and fails with a column-count mismatch.
        // The seed must instead emit 25 valid all-default `DEFAULT VALUES`
        // inserts, one per `db.execute_sql(...)` call.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Widget",
            &["label:Option<String>".into()],
            "20260427000000",
            &ScaffoldOptions {
                api: true,
                ..Default::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let test_file = fs::read_to_string(tmp.path().join("tests/widget.rs")).unwrap();
        assert!(test_file.contains("/api/widgets"));
        // The invalid targetless form must never be emitted.
        assert!(
            !test_file.contains("SELECT FROM generate_series"),
            "must not emit the invalid targetless generate_series seed: {test_file}"
        );
        assert!(
            !test_file.contains("generate_series"),
            "no-required-column seed must not use generate_series at all: {test_file}"
        );
        // Exactly 25 valid all-default inserts, each in its own execute_sql call.
        assert_eq!(
            test_file
                .matches("db.execute_sql(\"INSERT INTO widgets DEFAULT VALUES;\").await;")
                .count(),
            25,
            "expected 25 DEFAULT VALUES inserts (one per row): {test_file}"
        );
        // Envelope assertions stay consistent with a 25-row seed at size = 2.
        assert!(test_file.contains("total_elements\"], 25"));
        assert!(test_file.contains("total_pages\"], 13"));
    }

    // ── data_table scaffold integration ────────────────────────────────

    #[test]
    fn index_uses_data_table_not_ul() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "body:Text".into(),
                "published:bool".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(routes.contains("data_table("), "{routes}");
        assert!(routes.contains("DataTableConfig::new("), "{routes}");
        assert!(routes.contains("Column::new(\"Title\""), "{routes}");
        assert!(
            !routes.contains("ul id=\"posts-list\""),
            "still uses ul: {routes}"
        );
    }

    /// Issue #1319 AC4: with `--searchable` omitted, threading an empty
    /// `searchable` set through the generator produces output byte-for-byte
    /// identical to today's default scaffold (the flag is purely additive).
    #[test]
    fn searchable_omitted_is_byte_identical_to_default() {
        let fields = ["title:String".to_string(), "body:Text".to_string()];

        let tmp_default = project_with_main(default_main());
        plan_scaffold(tmp_default.path(), "Post", &fields, "20260427000000")
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let tmp_empty = project_with_main(default_main());
        plan_scaffold_with_options(
            tmp_empty.path(),
            "Post",
            &fields,
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    searchable: Vec::new(),
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap()
        .execute(Flags::default())
        .unwrap();

        for rel in [
            "src/routes/posts.rs",
            "src/models/post.rs",
            "src/repositories/post.rs",
            "migrations/20260427000000_create_posts/up.sql",
            "migrations/20260427000000_create_posts/down.sql",
            "src/main.rs",
        ] {
            let a = fs::read_to_string(tmp_default.path().join(rel)).unwrap();
            let b = fs::read_to_string(tmp_empty.path().join(rel)).unwrap();
            assert_eq!(a, b, "empty --searchable must not change `{rel}`");
            assert!(
                !b.contains("searchable")
                    && !b.contains("active_search")
                    && !b.contains("search_vector"),
                "non-searchable `{rel}` must carry no FTS artifacts:\n{b}"
            );
        }
    }

    /// Issue #1319 AC5: naming a non-text field in `--searchable` fails
    /// generation with a clear, field-naming error rather than emitting a model
    /// that won't compile.
    #[test]
    fn searchable_non_text_field_is_rejected() {
        let tmp = project_with_main(default_main());
        let err = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into(), "views:i64".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    searchable: vec!["views".into()],
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap_err();
        let msg = err.to_string();
        assert!(
            matches!(err, GenerateError::Config(_)),
            "expected Config error, got: {err:?}"
        );
        assert!(
            msg.contains("views") && (msg.contains("text") || msg.contains("String")),
            "error must name the offending field and mention text-only: {msg}"
        );
    }

    /// Issue #1319: a `--searchable` scaffold with a uuid primary key is
    /// rejected before any files are written. The scaffold command already gates
    /// off ALL uuid primary keys (the `#[repository]` REST API is i64-only), so
    /// this combination surfaces that broader gate; a metadata-layer guard in
    /// `parse_model_metadata` (see `model.rs`) is the defense-in-depth backstop
    /// specific to the FTS `search_page` i64 hardcoding.
    #[test]
    fn searchable_with_uuid_primary_key_is_rejected() {
        let tmp = project_with_main(default_main());
        let err = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into(), "body:Text".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    searchable: vec!["title".into(), "body".into()],
                    id_type: IdType::Uuid,
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap_err();
        assert!(
            matches!(err, GenerateError::Config(_)),
            "expected Config error, got: {err:?}"
        );
        assert!(
            err.to_string().to_lowercase().contains("uuid"),
            "error must name uuid as unsupported: {err}"
        );
        // No files written: the scaffold plan fails before touching the tree.
        assert!(
            !tmp.path().join("src/models/post.rs").exists()
                && !tmp.path().join("src/repositories/post.rs").exists(),
            "rejected uuid+searchable scaffold must not write any files"
        );
    }

    /// Issue #1841: `--searchable` on a standard owner-scoped model is now
    /// ALLOWED (was rejected pre-#1841). The repository macro carries the
    /// `owner = <col>` attr so it emits owner-filtered `list_scoped` /
    /// `search_page_scoped`, and the generated index + `/search` handlers call
    /// ONLY those scoped methods — never the unscoped `page`/`search_page` — so
    /// no cross-user leak. This test asserts that safe wiring is emitted.
    #[test]
    fn searchable_with_owner_scoped_model_emits_scoped_wiring() {
        let tmp = project_with_main(default_main());
        // `user_id` is an owner column, so the default policy makes the index
        // owner-scoped (`authorize_wiring`). Pairing that with `--searchable`
        // is now supported via the macro's owner-scoped codegen.
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &[
                "user_id:i64".into(),
                "title:String".into(),
                "body:Text".into(),
            ],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    searchable: vec!["title".into(), "body".into()],
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .expect("standard owner-scoped + searchable must be allowed (#1841)");
        plan.execute(Flags::default()).unwrap();

        // The repository declares `owner = user_id` so the macro generates the
        // scoped methods.
        let repo = fs::read_to_string(tmp.path().join("src/repositories/post.rs")).unwrap();
        assert!(
            repo.contains(", owner = user_id)"),
            "owner-scoped repository must carry `owner = user_id` on the attr: {repo}"
        );

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        // The `/search` route uses the scoped method (and its empty-query
        // fallback the scoped list) — never the unscoped `search_page`/`page`.
        assert!(
            routes.contains("repo.search_page_scoped(owner_id, q, &page_req)"),
            "owner-scoped /search must call search_page_scoped: {routes}"
        );
        // The owner-scoped index uses the scoped list with sort/filter.
        assert!(
            routes.contains("repo.list_scoped(owner_id, &list_query, &page_req)"),
            "owner-scoped index/search must call list_scoped: {routes}"
        );
        // Sort/filter data_table wiring is present on the owner-scoped standard
        // index (active_sort / query), closing the #1854 gap.
        assert!(
            routes.contains(".active_sort(list_query.sort().unwrap_or_default())"),
            "owner-scoped standard index must render the sort/filter data_table: {routes}"
        );
        // The search box is rendered on the owner-scoped index.
        assert!(
            routes.contains("active_search_input"),
            "owner-scoped searchable index must render the search box: {routes}"
        );
    }

    /// Issue #1841 security invariant: the owner-scoped `/search` and index
    /// branches must NEVER call the unscoped repository methods, or they would
    /// re-open the pre-#1841 cross-user leak. This is the regression guard: the
    /// `search`/`index` handler bodies must not contain a bare
    /// `repo.search_page(`/`repo.page(` call.
    #[test]
    fn owner_scoped_searchable_never_calls_unscoped_repo_methods() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &[
                "user_id:i64".into(),
                "title:String".into(),
                "body:Text".into(),
            ],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    searchable: vec!["title".into(), "body".into()],
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(
            !routes.contains("repo.search_page(") && !routes.contains("repo.page("),
            "owner-scoped searchable routes must NEVER call the unscoped \
             repo.search_page(/repo.page( (cross-user leak): {routes}"
        );
    }

    /// The owner-scoped guard is scoped to owner scoping: `--no-policy` opts out
    /// of the secured index, so `--searchable` with an owner column is allowed
    /// (index and search are both unscoped — consistent, no leak relative to the
    /// list view).
    #[test]
    fn searchable_with_owner_column_but_no_policy_is_allowed() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &[
                "user_id:i64".into(),
                "title:String".into(),
                "body:Text".into(),
            ],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    searchable: vec!["title".into(), "body".into()],
                    ..Default::default()
                },
                no_policy: true,
                ..Default::default()
            },
        );
        assert!(
            plan.is_ok(),
            "--searchable + owner column + --no-policy must be allowed: {plan:?}"
        );
    }

    /// Issue #1319 AC5: naming a field that does not exist in `--searchable`
    /// fails generation with a clear error.
    #[test]
    fn searchable_unknown_field_is_rejected() {
        let tmp = project_with_main(default_main());
        let err = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    searchable: vec!["nope".into()],
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap_err();
        assert!(
            matches!(err, GenerateError::Config(_)),
            "expected Config error, got: {err:?}"
        );
        assert!(
            err.to_string().contains("nope"),
            "must name the field: {err}"
        );
    }

    /// Issue #1319 AC1/AC3/AC6: a `--searchable` scaffold wires the model,
    /// repository, migration, and index/search route coherently.
    #[test]
    fn searchable_scaffold_wires_model_repo_and_index() {
        let tmp = project_with_main(default_main());
        plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into(), "body:Text".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    searchable: vec!["title".into(), "body".into()],
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap()
        .execute(Flags::default())
        .unwrap();

        let model = fs::read_to_string(tmp.path().join("src/models/post.rs")).unwrap();
        assert!(
            model.contains("#[searchable(language = \"english\")]"),
            "model must opt into search: {model}"
        );
        assert!(
            model.contains("#[searchable(weight = \"A\")]")
                && model.contains("#[searchable(weight = \"B\")]"),
            "each named text field must be weighted: {model}"
        );

        let repo = fs::read_to_string(tmp.path().join("src/repositories/post.rs")).unwrap();
        assert!(
            repo.contains("api = \"/api/posts\", searchable)"),
            "repository must carry `searchable`: {repo}"
        );

        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260427000000_create_posts/up.sql"),
        )
        .unwrap();
        assert!(
            up.contains("search_vector tsvector") && up.contains("USING gin(search_vector)"),
            "migration must add the generated column + GIN index: {up}"
        );

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        // Input-only `active_search_input` (the composite `active_search` would
        // render its own empty results container — a duplicate id).
        assert!(
            routes.contains("active_search_input(\"post-search\"")
                && !routes.contains("widgets::active_search(\"post-search\"")
                && routes.contains("\"/posts/search\", \"#posts-search-results\""),
            "index must render the input-only search box wired to the results route: {routes}"
        );
        // The `active_search` target must exist as a real element that renders
        // the initial list server-side (no `.initial_load()` AJAX round-trip, no
        // `<noscript>` fallback wrapper), exactly once on the index page.
        assert!(
            routes.contains("div id=\"posts-search-results\"")
                && !routes.contains(".initial_load(")
                && !routes.contains("noscript"),
            "index must render the results container server-side without initial_load/noscript: {routes}"
        );
        let index_fn = routes
            .split("pub async fn index(")
            .nth(1)
            .and_then(|s| s.split("pub async fn ").next())
            .expect("an index handler must be emitted");
        assert_eq!(
            index_fn.matches("id=\"posts-search-results\"").count(),
            1,
            "the index page must render the results container exactly once: {index_fn}"
        );
        assert!(
            routes.contains("pub async fn search(")
                && routes.contains("repo.search_page(q, &page_req)"),
            "a search results handler must call search_page: {routes}"
        );
        // The results pager must preserve the request query (so `q` survives
        // pagination) instead of pointing at a bare `/posts/search`.
        assert!(
            routes.contains("PagerOptions::new(\"/posts/search\").query(pager_query)"),
            "search pager must preserve the query string across pages: {routes}"
        );
        assert!(
            routes.contains("repo.page(&page_req).await?"),
            "empty q must fall back to page(): {routes}"
        );

        let main_rs = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert!(
            main_rs.contains("routes::posts::search"),
            "search route must be registered in main.rs: {main_rs}"
        );
    }

    /// Issue #1319: `search_vector` is a stored generated column, so it must NOT
    /// leak into `schema.rs` or the model struct (the macro loads rows by id).
    #[test]
    fn searchable_column_is_not_in_schema_or_struct() {
        let tmp = project_with_main(default_main());
        plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into(), "body:Text".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    searchable: vec!["title".into(), "body".into()],
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap()
        .execute(Flags::default())
        .unwrap();
        let schema = fs::read_to_string(tmp.path().join("src/schema.rs")).unwrap();
        let model = fs::read_to_string(tmp.path().join("src/models/post.rs")).unwrap();
        assert!(
            !schema.contains("search_vector"),
            "search_vector must not be in schema.rs: {schema}"
        );
        assert!(
            !model.contains("pub search_vector"),
            "search_vector must not be a struct field: {model}"
        );
    }

    /// Issue #1319: the search box is gated off for `--live` variants (the SSE
    /// `<ul>` OOB contract differs), but the model/repository/migration still
    /// receive `searchable`.
    #[test]
    fn searchable_search_box_gated_off_for_live() {
        let tmp = project_with_main(default_main());
        plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into(), "body:Text".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    searchable: vec!["title".into(), "body".into()],
                    ..Default::default()
                },
                live: true,
                ..Default::default()
            },
        )
        .unwrap()
        .execute(Flags::default())
        .unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(
            !routes.contains("active_search(")
                && !routes.contains("active_search_input(")
                && !routes.contains("pub async fn search("),
            "live variant must not emit a search box: {routes}"
        );
        let repo = fs::read_to_string(tmp.path().join("src/repositories/post.rs")).unwrap();
        assert!(
            repo.contains(", searchable)"),
            "live repo must still carry searchable: {repo}"
        );
    }

    #[test]
    fn kind_is_sortable_excludes_blobs_and_enums() {
        // #1126: only kinds the model macro emits a sort arm for get a
        // `.sortable(..)` header — otherwise the link would be a dead affordance.
        assert!(kind_is_sortable(FieldKind::String));
        assert!(kind_is_sortable(FieldKind::Text));
        assert!(kind_is_sortable(FieldKind::I32));
        assert!(kind_is_sortable(FieldKind::I64));
        assert!(kind_is_sortable(FieldKind::Bool));
        assert!(kind_is_sortable(FieldKind::F64));
        assert!(kind_is_sortable(FieldKind::Uuid));
        assert!(kind_is_sortable(FieldKind::DateTime));
        assert!(kind_is_sortable(FieldKind::References));
        assert!(kind_is_sortable(FieldKind::Decimal {
            precision: 12,
            scale: 2
        }));
        // Excluded: binary blobs and closed-set enums.
        assert!(!kind_is_sortable(FieldKind::Bytea));
        assert!(!kind_is_sortable(FieldKind::Attachment));
        assert!(!kind_is_sortable(FieldKind::Enum));
    }

    #[test]
    fn index_wires_allowlisted_sort_filter() {
        // #1126: the generated index extracts ListQuery, calls repo.list, and
        // marks scalar columns sortable with a symmetric data_table config.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "body:Text".into(),
                "published:bool".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(routes.contains("list_query: ListQuery,"), "{routes}");
        assert!(
            routes.contains("repo.list(&list_query, &page_req)"),
            "{routes}"
        );
        assert!(routes.contains(".sortable(\"id\")"), "{routes}");
        assert!(routes.contains(".sortable(\"title\")"), "{routes}");
        assert!(
            routes.contains(".active_dir(list_query.direction())"),
            "{routes}"
        );
    }

    #[test]
    fn index_data_table_cell_handles_nullable_field() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:Option<String>".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(routes.contains("unwrap_or_default"), "{routes}");
    }

    #[test]
    fn index_data_table_has_show_link_column() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(routes.contains("paths::show(row.id)"), "{routes}");
        assert!(routes.contains("row.id"), "{routes}");
    }

    #[test]
    fn sharded_index_uses_data_table() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["tenant_id:i64".into(), "title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    sharded: true,
                    shard_key: Some("tenant_id".into()),
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(routes.contains("data_table("), "{routes}");
        assert!(routes.contains("from_shard"), "{routes}");
    }

    #[test]
    fn live_index_keeps_sse_list_container() {
        let tmp = project_with_main(default_main());
        fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname=\"x\"\n\n[dependencies]\nautumn-web = \"0.5.0\"\n",
        )
        .unwrap();
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                live: true,
                ..Default::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        // Live variant must keep the ul/li SSE contract intact
        assert!(routes.contains("ul id=\"posts-list\""), "{routes}");
        assert!(routes.contains("sse-connect=(paths::events())"), "{routes}");
    }

    #[test]
    fn plan_scaffold_live_views() {
        let tmp = project_with_main(default_main());
        fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname=\"x\"\n\n[dependencies]\nautumn-web = \"0.5.0\"\n",
        )
        .unwrap();
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                live: true,
                ..Default::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(routes.contains("/posts/events"));
        assert!(routes.contains("autumn_web::sse::stream"));
        assert!(routes.contains("hx-ext=\"sse\""));
        assert!(routes.contains("sse-connect=(paths::events())"));
        assert!(routes.contains("hx-swap=\"none\""));
        assert!(routes.contains("autumn_web::htmx::HTMX_JS_PATH"));
        assert!(routes.contains("autumn_web::htmx::HTMX_SSE_JS_PATH"));
        assert!(routes.contains("title: autumn_web::hooks::Patch::Set(new.title.clone())"));

        let main_rs = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert!(main_rs.contains("routes::posts::events"));

        let repo = fs::read_to_string(tmp.path().join("src/repositories/post.rs")).unwrap();
        assert!(repo.contains("broadcasts = true"));

        let cargo = fs::read_to_string(tmp.path().join("Cargo.toml")).unwrap();
        assert!(cargo.contains("\"ws\""));
        assert!(cargo.contains("\"maud\""));
        assert!(cargo.contains("\"htmx\""));
    }

    // ── property_list scaffold conformance (issue #1120) ──────────────────

    #[test]
    fn show_uses_property_list_widget_with_declared_fields() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "body:Text".into(),
                "published:bool".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        // show handler references property_list widget
        assert!(
            routes.contains("autumn_web::widgets::property_list"),
            "show must use property_list widget: {routes}"
        );
        // Each declared field appears with humanized label
        assert!(
            routes.contains("\"Title\""),
            "show must list 'title' field: {routes}"
        );
        assert!(
            routes.contains("\"Body\""),
            "show must list 'body' field: {routes}"
        );
        assert!(
            routes.contains("\"Published\""),
            "show must list 'published' field: {routes}"
        );
        // id and created_at always present
        assert!(routes.contains("\"Id\""), "show must include id: {routes}");
        assert!(
            routes.contains("\"Created at\""),
            "show must include created_at: {routes}"
        );
    }

    #[test]
    fn show_property_list_label_humanization() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &[
                "published_at:NaiveDateTime".into(),
                "user_name:String".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        // humanized: first word capitalized, rest lowercase (snake_case → "Word rest")
        assert!(
            routes.contains("\"Published at\""),
            "humanize must produce 'Published at': {routes}"
        );
        assert!(
            routes.contains("\"User name\""),
            "humanize must produce 'User name': {routes}"
        );
    }

    #[test]
    fn show_includes_defaulted_fields_in_property_list() {
        // Regression test: fields with `#[default]` are excluded from the
        // form (form_fields), but must still appear in the show property list.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into(), "views:i64".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    defaults: vec!["views=0".to_string()],
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(
            routes.contains("\"Views\""),
            "show must include defaulted field 'views': {routes}"
        );
    }

    // ── state-machine transitions scaffold conformance (issue #1326) ──────

    #[test]
    fn scaffold_without_state_machine_emits_no_transition_wiring() {
        // AC5: a model WITHOUT any `:states(…)` field keeps the pre-#1326 `show`
        // handler and route set byte-for-byte — no `show_view` helper, no
        // `/transitions/` route, and the original three-arg `show` signature.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "body:Text".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();
        assert!(
            !routes.contains("/transitions/"),
            "no-state-machine scaffold must not emit any transition route: {routes}"
        );
        assert!(
            !routes.contains("fn show_view"),
            "no-state-machine scaffold must not extract a show_view helper: {routes}"
        );
        assert!(
            !routes.contains("transition_controls"),
            "no-state-machine scaffold must not render transition controls: {routes}"
        );
        // The original inline `show` signature is unchanged (no CSRF params).
        assert!(
            routes.contains(
                "pub async fn show(id: Path<i64>, mut db: Db, flash: Flash) -> AutumnResult<Markup> {"
            ),
            "no-state-machine `show` signature must be unchanged: {routes}"
        );
    }

    #[test]
    fn scaffold_with_state_machine_emits_transition_route_and_controls() {
        // A model WITH a `:states(…)` field generates the transition route, the
        // `transition_{field}_to` call, both the 303 success and 422 error
        // branches, a shared `show_view`, and a `transition_controls(` call.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Order",
            &[
                "status:String:states(draft -> published: can_publish, published -> archived)"
                    .into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let routes = fs::read_to_string(tmp.path().join("src/routes/orders.rs")).unwrap();
        // The transition route: `POST /orders/{id}/transitions/status`.
        assert!(
            routes.contains("#[post(\"/orders/{id}/transitions/status\")]"),
            "must emit the transition POST route: {routes}"
        );
        assert!(
            routes.contains("pub async fn transition_status("),
            "must emit the transition handler: {routes}"
        );
        // The handler drives the macro-emitted state-machine method.
        assert!(
            routes.contains("row.transition_status_to(&target)"),
            "transition handler must call transition_status_to: {routes}"
        );
        // Success branch: 303 redirect to the show page.
        assert!(
            routes.contains("Ok(autumn_web::Redirect::to(&paths::show(*id)).into_response())"),
            "transition handler must 303-redirect on a legal edge: {routes}"
        );
        // Error branch: 422 re-render of the detail page, record unchanged.
        assert!(
            routes.contains("autumn_web::reexports::http::StatusCode::UNPROCESSABLE_ENTITY"),
            "transition handler must 422 on an illegal edge: {routes}"
        );
        // The detail page markup is shared through `show_view`.
        assert!(
            routes.contains("async fn show_view("),
            "must extract a shared show_view helper: {routes}"
        );
        // The show view renders transition controls fed by the macro const.
        assert!(
            routes.contains("autumn_web::widgets::transition_controls(&paths::transition_status(row.id), \"status\", &row.status, Order::__AUTUMN_SM_STATUS_TRANSITIONS,"),
            "show view must render transition_controls for the state-machine field: {routes}"
        );
        // The transition endpoint is registered in the paths! module.
        assert!(
            routes.contains("transition_status,"),
            "paths! must register the transition route name: {routes}"
        );
        // Security (issue #1326 IDOR fix): with record-policy wiring on (the
        // default for non-`--api` scaffolds), the transition handler threads the
        // same `State` + `Session` pair as `update` and record-authorizes the
        // actor against the loaded row with the `"update"` action BEFORE writing,
        // so a transition cannot bypass the record policy.
        assert!(
            routes.contains(
                "autumn_web::extract::State(state): autumn_web::extract::State<autumn_web::AppState>,"
            ),
            "transition handler must thread the State extractor when policy wiring is on: {routes}"
        );
        assert!(
            routes.contains("session: autumn_web::session::Session,"),
            "transition handler must thread the Session extractor when policy wiring is on: {routes}"
        );
        assert!(
            routes.contains(
                "autumn_web::authorization::authorize::<Order>(&state, &session, \"update\", &row).await?;"
            ),
            "transition handler must record-authorize the actor against the loaded row: {routes}"
        );
    }

    #[test]
    fn scaffold_with_state_machine_no_policy_emits_no_authz_preamble() {
        // AC5 / IDOR-fix gating: a `--no-policy` scaffold still emits the
        // transition route, but WITHOUT the authorize preamble — exactly the
        // pre-fix `id/db/flash/csrf/body` handler. The authz preamble must appear
        // only in the state-machine transition route AND only when policy is on.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Order",
            &[
                "status:String:states(draft -> published: can_publish, published -> archived)"
                    .into(),
            ],
            "20260427000000",
            &ScaffoldOptions {
                no_policy: true,
                ..Default::default()
            },
        )
        .unwrap();
        let routes = action_contents(&plan, "src/routes/orders.rs");
        // The transition route is still generated…
        assert!(
            routes.contains("pub async fn transition_status("),
            "--no-policy state-machine scaffold must still emit the transition handler: {routes}"
        );
        // …but with no record-policy authorization wiring.
        assert!(
            !routes.contains("authorize::<Order>"),
            "--no-policy transition handler must not wire authorize: {routes}"
        );
        assert!(
            !routes.contains("session: autumn_web::session::Session"),
            "--no-policy transition handler must not thread a Session extractor: {routes}"
        );
    }

    #[test]
    fn scaffold_with_state_machine_mounts_transition_route_in_main() {
        // P1 (issue #1326): the generated `main.rs` router must actually MOUNT
        // each state-machine field's `transition_{field}` handler — otherwise the
        // show page's `transition_controls` form POSTs to an unmounted route and
        // 404s. The handler being present in the `routes::{plural}` module and in
        // the name-only `paths!` helper is not enough; it must be in the router's
        // `routes![…]` set.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Order",
            &[
                "status:String:states(draft -> published, published -> archived)".into(),
                "title:String".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert!(
            main.contains("routes::orders::transition_status"),
            "main.rs must MOUNT the transition handler, not just declare it in paths!: {main}"
        );
        // Mounted alongside the standard CRUD handlers.
        assert!(
            main.contains("routes::orders::update") && main.contains("routes::orders::destroy"),
            "standard CRUD handlers must still be mounted: {main}"
        );
    }

    #[test]
    fn scaffold_without_state_machine_mounts_no_transition_route_in_main() {
        // AC5: a model with no `:states(…)` field mounts exactly the pre-#1326
        // route set — no `transition_` entry, no `/transitions/` path.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "body:Text".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert!(
            !main.contains("transition_"),
            "no-state-machine scaffold must mount no transition route: {main}"
        );
        assert!(
            !main.contains("/transitions/"),
            "no-state-machine scaffold must reference no transition path: {main}"
        );
    }

    #[test]
    fn scaffold_state_machine_field_is_transition_only_on_update() {
        // P2 (issue #1326): a `:states(…)` column is transition-only. It must be
        // EXCLUDED from the ordinary update surfaces — the edit-form input and the
        // update handler's `.set((…))` tuple — so a plain `POST /{plural}/{id}/
        // update` (or a JSON body) cannot set `status=<anything>` and bypass
        // `transition_status_to` / its guards. It must be KEPT on the create
        // surface (initial state), the `New{Model}` insert path, and the show
        // page's transition controls.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Order",
            &[
                "status:String:states(draft -> published, published -> archived)".into(),
                "title:String".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/orders.rs")).unwrap();

        // ── excluded from the ordinary UPDATE path ───────────────────────────
        // The update handler's `.set((…))` tuple must NOT set the state column
        // (that form — `orders::status.eq(new.status.clone())` — is the bypass;
        // the transition route instead sets `orders::status.eq(new_state)`).
        assert!(
            !routes.contains("orders::status.eq(new.status.clone())"),
            "the update `.set((…))` tuple must exclude the state-machine column: {routes}"
        );
        assert!(
            routes.contains("orders::title.eq(new.title.clone())"),
            "the update `.set((…))` tuple must still set non-state columns: {routes}"
        );
        // The edit form drops the state input; the shared helper takes the flag
        // and the edit call passes `true`.
        assert!(
            routes.contains("exclude_state_fields: bool"),
            "the shared form helper must take an exclude_state_fields flag: {routes}"
        );
        assert!(
            routes.contains("form = form.exclude(\"status\");"),
            "the form helper must exclude the state column when asked: {routes}"
        );
        assert!(
            routes.contains(
                "order_form_for(&changeset, paths::update(*id), \"Save\", csrf.as_ref(), csrf_field.as_ref(), submit_token.as_ref(), submit_field.as_ref(), true)"
            ),
            "the EDIT form call must exclude the state field (pass `true`): {routes}"
        );

        // ── kept on the CREATE path + New{Model} insert ──────────────────────
        assert!(
            routes.contains(
                "order_form_for(&changeset, paths::create(), \"Create\", csrf.as_ref(), csrf_field.as_ref(), submit_token.as_ref(), submit_field.as_ref(), false)"
            ),
            "the CREATE form call must keep the state field (pass `false`): {routes}"
        );
        // `OrderForm` keeps the column (serde-defaulted so an update submit that
        // omits it still decodes) and `into_new` seeds the initial state.
        assert!(
            routes.contains("#[serde(default)]\n    pub status: String,"),
            "OrderForm must keep a serde-defaulted state column: {routes}"
        );
        assert!(
            routes.contains("status: form.status.clone(),"),
            "into_new must seed the initial state on create: {routes}"
        );

        // ── kept on the SHOW page's transition controls ──────────────────────
        assert!(
            routes.contains("transition_controls(&paths::transition_status(row.id), \"status\""),
            "the show view must still render the state column's transition controls: {routes}"
        );
    }

    #[test]
    fn scaffold_without_state_machine_keeps_field_on_update_surfaces() {
        // AC5: a no-state-machine model's update form/handler are unchanged — no
        // exclude flag, every field set on the update path.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "body:Text".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let routes = fs::read_to_string(tmp.path().join("src/routes/posts.rs")).unwrap();

        assert!(
            !routes.contains("exclude_state_fields"),
            "no-state-machine form helper must not gain an exclude flag: {routes}"
        );
        assert!(
            routes.contains("posts::title.eq(new.title.clone())")
                && routes.contains("posts::body.eq(new.body.clone())"),
            "no-state-machine update must set every column: {routes}"
        );
    }

    #[test]
    fn smoke_test_default_value_containing_semicolon_does_not_corrupt_sql() {
        // Regression test (PR review, issue #1023): `create_table_sql_with_metadata_and_id`
        // emits `DEFAULT '...'` verbatim for a String/Text `--default`, so a
        // value containing a semicolon (e.g. a bio with "; " in it) must not
        // be split into two broken `db.execute_sql(...)` calls.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    defaults: vec!["title=hello;world".to_string()],
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();
        assert!(
            test.contains("DEFAULT 'hello;world'"),
            "generated default literal must survive intact: {test}"
        );
        // Every db.execute_sql(...) call's string literal argument must itself
        // be balanced/complete SQL -- i.e. the CREATE TABLE statement was not
        // split mid-literal. Count occurrences of "CREATE TABLE" (must be
        // exactly one, not spread across two calls).
        assert_eq!(
            test.matches("CREATE TABLE").count(),
            1,
            "CREATE TABLE must appear in a single execute_sql call, not split across two: {test}"
        );
    }

    // ── enum field: generated out-of-set rejection smoke test (issue #1030) ─

    #[test]
    fn scaffold_smoke_test_asserts_out_of_set_post_rejected() {
        let tmp = project_with_main(default_main());
        plan_and_execute_post_scaffold_with_status_enum(&tmp);

        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();
        assert!(
            test.contains("CHECK (status IN ('draft', 'published', 'archived'))"),
            "the raw-INSERT test needs the real CHECK constraint in its setup SQL: {test}"
        );
        assert!(
            test.contains("fn posts_rejects_out_of_set_status"),
            "got:\n{test}"
        );
        assert!(test.contains(".assert_status(400)"), "got:\n{test}");
        assert!(
            test.contains(".assert_body_contains(\"status\")"),
            "got:\n{test}"
        );
        assert!(
            test.contains("is_err()"),
            "must assert the raw out-of-set INSERT fails at the DB layer: {test}"
        );
        assert!(
            test.contains("posts::table.count()"),
            "must assert zero rows were written: {test}"
        );
    }

    #[test]
    fn scaffold_enum_rejection_test_uses_idempotent_create_table() {
        // Regression test: both the base index test and the enum-rejection
        // test run against the same shared `TestDb` in the same test binary
        // and both issue a `CREATE TABLE posts (...)` as part of setup —
        // without `IF NOT EXISTS` on (at least) one of them, whichever test
        // runs second fails with "relation \"posts\" already exists" instead
        // of reaching its actual assertions.
        let tmp = project_with_main(default_main());
        plan_and_execute_post_scaffold_with_status_enum(&tmp);
        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();

        let enum_test_pos = test
            .find("fn posts_rejects_out_of_set_status")
            .unwrap_or_else(|| panic!("expected the enum rejection test: {test}"));
        let enum_test_setup = &test[enum_test_pos..];
        assert!(
            enum_test_setup.contains("CREATE TABLE IF NOT EXISTS posts ("),
            "the enum-rejection test's own CREATE TABLE must be idempotent: {enum_test_setup}"
        );

        let base_test_setup = &test[..enum_test_pos];
        assert!(
            base_test_setup.contains("CREATE TABLE posts (")
                && !base_test_setup.contains("CREATE TABLE IF NOT EXISTS posts ("),
            "the base index test's own setup must be unchanged (plain CREATE TABLE, \
             matching the real migration exactly): {base_test_setup}"
        );
    }

    #[test]
    fn scaffold_enum_rejection_test_uses_idempotent_create_index() {
        // Regression test: `setup_calls` also contains `CREATE INDEX` for any
        // `--index`/`references` field, not just the `CREATE TABLE` — the
        // enum-rejection test's own copy of that index statement needs the
        // same `IF NOT EXISTS` treatment, or it panics with "relation
        // \"idx_posts_title\" already exists" when it runs after the base test.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "status:enum{draft,published,archived}".into(),
            ],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    indexes: vec!["title".into()],
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();
        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();

        let enum_test_pos = test
            .find("fn posts_rejects_out_of_set_status")
            .unwrap_or_else(|| panic!("expected the enum rejection test: {test}"));
        let enum_test_setup = &test[enum_test_pos..];
        assert!(
            enum_test_setup.contains("CREATE INDEX IF NOT EXISTS idx_posts_title"),
            "the enum-rejection test's own CREATE INDEX must be idempotent: {enum_test_setup}"
        );

        let base_test_setup = &test[..enum_test_pos];
        assert!(
            base_test_setup.contains("CREATE INDEX idx_posts_title")
                && !base_test_setup.contains("CREATE INDEX IF NOT EXISTS idx_posts_title"),
            "the base index test's own setup must be unchanged (plain CREATE INDEX, \
             matching the real migration exactly): {base_test_setup}"
        );
    }

    #[test]
    fn scaffold_api_smoke_test_asserts_check_constraint_but_no_http_assertion() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "status:enum{draft,published,archived}".into(),
            ],
            "20260427000000",
            &ScaffoldOptions {
                api: true,
                ..Default::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();
        assert!(
            test.contains("fn posts_rejects_out_of_set_status"),
            "got:\n{test}"
        );
        assert!(
            test.contains("is_err()"),
            "must assert the raw out-of-set INSERT fails at the DB layer: {test}"
        );
        assert!(
            !test.contains(".assert_status(400)"),
            "the --api smoke test has no HTML form route to POST to: {test}"
        );
    }

    #[test]
    fn scaffold_smoke_test_absent_when_no_enum_fields() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();
        assert!(
            !test.contains("rejects_out_of_set"),
            "no enum field means no rejection test: {test}"
        );
    }

    #[test]
    fn scaffold_validation_smoke_test_max_only_rule_exceeds_bound() {
        // Regression guard: a fixed-size "invalid" literal (e.g. 1000 `x`s)
        // would itself satisfy a looser `max` bound like 2000, silently
        // turning the smoke test's "invalid" submission valid and failing its
        // own `.assert_status(422)` premise. The generated invalid value must
        // scale with the declared `max` (here, more than 5 characters), and
        // the generated valid value must stay within it (at most 5).
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    validations: vec!["title=length:max=5".into()],
                    ..ModelOptions::default()
                },
                ..ScaffoldOptions::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();
        let invalid_line = test
            .lines()
            .find(|l| l.contains("let invalid_body"))
            .expect("invalid_body line present");
        let invalid_title = invalid_line
            .split("title=")
            .nth(1)
            .and_then(|s| s.split('&').next())
            .expect("title value in invalid_body");
        assert!(
            invalid_title.len() > 5,
            "invalid value must exceed the declared max=5 bound: {invalid_line}"
        );

        let valid_line = test
            .lines()
            .find(|l| l.contains("let valid_body"))
            .expect("valid_body line present");
        let valid_title = valid_line
            .split("title=")
            .nth(1)
            .and_then(|s| s.split('&').next())
            .expect("title value in valid_body");
        assert!(
            valid_title.len() <= 5,
            "valid value must satisfy the declared max=5 bound: {valid_line}"
        );
    }

    #[test]
    fn scaffold_validation_smoke_test_skips_absurdly_large_bound() {
        // Regression guard (issue #1124 review): a declared bound like
        // `length:min=1000000000` has no cheap, correct sample to generate —
        // capping the sample length would either fail to violate a huge `max`
        // or fail to satisfy a huge `min`, asserting something false. The
        // generator must skip emitting this smoke test entirely rather than
        // allocating a multi-GB string in the CLI process itself.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    validations: vec!["title=length:min=1000000000".into()],
                    ..ModelOptions::default()
                },
                ..ScaffoldOptions::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();
        assert!(
            !test.contains("rejects_invalid_title_and_preserves_input"),
            "an absurdly large bound must not generate a smoke test: {test}"
        );
    }

    #[test]
    fn scaffold_validation_smoke_test_skips_noop_min_zero_rule() {
        // Regression guard (issue #1124 review): `length:min=0` with no `max`
        // is a no-op — every string, including blank, already satisfies it.
        // Emitting a smoke test that submits a value and asserts 422 anyway
        // would fail against the real server. The generator must skip the
        // test entirely when this is the only validated field.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    validations: vec!["title=length:min=0".into()],
                    ..ModelOptions::default()
                },
                ..ScaffoldOptions::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();
        assert!(
            !test.contains("rejects_invalid_title_and_preserves_input"),
            "a no-op length:min=0 rule must not generate a smoke test: {test}"
        );
    }

    #[test]
    fn scaffold_validation_smoke_test_falls_back_past_noop_rule() {
        // When one validated field's rule is a no-op (`length:min=0`) but
        // another has a genuinely violatable rule, the smoke test must be
        // built around the violatable field instead of skipping entirely.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into(), "body:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    validations: vec![
                        "title=length:min=0".into(),
                        "body=length:min=1,max=200".into(),
                    ],
                    ..ModelOptions::default()
                },
                ..ScaffoldOptions::default()
            },
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();
        assert!(
            test.contains("rejects_invalid_body_and_preserves_input"),
            "the violatable body rule must be used instead of the no-op title rule: {test}"
        );
        assert!(
            !test.contains("rejects_invalid_title_and_preserves_input"),
            "the no-op title rule must not be used for the smoke test: {test}"
        );
    }

    #[test]
    fn scaffold_validation_rejects_min_greater_than_max() {
        // Regression guard (issue #1124 review): `length:min=5,max=3` is a
        // self-contradictory rule no string can ever satisfy — accepting it
        // would generate a field that's permanently invalid and a smoke test
        // whose "valid submission" assertion is always false. It must be
        // rejected at generate-time instead.
        let tmp = project_with_main(default_main());
        let err = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    validations: vec!["title=length:min=5,max=3".into()],
                    ..ModelOptions::default()
                },
                ..ScaffoldOptions::default()
            },
        )
        .unwrap_err();
        assert!(
            matches!(err, GenerateError::InvalidField { .. }),
            "expected min > max to be rejected, got {err:?}"
        );
    }

    #[test]
    fn scaffold_multiple_enum_fields_each_use_own_variant_as_other_columns_sample() {
        // A second required enum column's raw-INSERT sample value must be one
        // of *its own* variants, not the generic `'sample'` placeholder —
        // otherwise it would trip its own CHECK too and the test would no
        // longer isolate the failure to the column actually under test.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &[
                "status:enum{draft,published,archived}".into(),
                "priority:enum{low,high}".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();
        assert!(
            test.contains(
                "INSERT INTO posts (status, priority) VALUES ('__not_a_real_variant__', 'low')"
            ),
            "got:\n{test}"
        );
        assert!(
            test.contains(
                "INSERT INTO posts (status, priority) VALUES ('draft', '__not_a_real_variant__')"
            ),
            "got:\n{test}"
        );
    }

    #[test]
    fn scaffold_enum_rejection_test_isolates_check_failure_from_required_references_field() {
        // Regression test: a required `references` field co-occurring with
        // the enum field under test must not make the raw out-of-set INSERT
        // fail for the wrong reason (an FK violation on a dangling stub-table
        // reference) instead of the CHECK constraint actually being tested.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &[
                "author:references".into(),
                "status:enum{draft,published,archived}".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let test = fs::read_to_string(tmp.path().join("tests/post.rs")).unwrap();
        assert!(
            test.contains("INSERT INTO authors DEFAULT VALUES;"),
            "the stub `authors` table must be seeded so author_id=1 is a valid FK: {test}"
        );
        assert!(
            test.contains(
                "INSERT INTO posts (author_id, status) VALUES (1, '__not_a_real_variant__')"
            ),
            "got:\n{test}"
        );
    }

    // ── references field: scaffold + smoke-test wiring (issue #1026) ───────

    #[test]
    fn scaffold_references_field_emits_fk_column_constraint_and_index() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Comment",
            &["body:Text".into(), "post:references".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let up = fs::read_to_string(
            tmp.path()
                .join("migrations/20260427000000_create_comments/up.sql"),
        )
        .unwrap();
        assert!(
            up.contains("post_id BIGINT NOT NULL REFERENCES posts(id)"),
            "up.sql: {up}"
        );
        assert!(
            up.contains("CREATE INDEX idx_comments_post_id ON comments (post_id);"),
            "up.sql: {up}"
        );
    }

    #[test]
    fn scaffold_references_field_warns_when_target_model_missing() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Comment",
            &["post:references".into()],
            "20260427000000",
        )
        .unwrap();
        // Two warnings: the shared "assuming table exists" one from
        // `check_reference_targets`, plus the scaffold-specific note that the
        // form falls back to a numeric id input (no schema entry to load
        // select options from) and how to get the select instead.
        assert_eq!(plan.warnings.len(), 2, "warnings: {:?}", plan.warnings);
        assert!(plan.warnings[0].contains("posts"));
        assert!(
            plan.warnings[1].contains("numeric id input"),
            "warnings: {:?}",
            plan.warnings
        );
        assert!(
            plan.warnings[1].contains("Generate the 'post' model first"),
            "warnings: {:?}",
            plan.warnings
        );
    }

    #[test]
    fn scaffold_smoke_test_creates_a_stub_referenced_table_before_the_real_one() {
        // The generated smoke test runs in its own throwaway `TestDb` (one
        // Postgres testcontainer per `tests/*.rs` binary, per-process — see
        // `TestDb::shared()`), so it can't rely on some *other* scaffolded
        // resource's smoke test having already created the referenced table.
        // A `CREATE TABLE comments (... REFERENCES posts(id) ...)` would fail
        // with "relation posts does not exist" unless the comments smoke test
        // creates a minimal stand-in `posts` table itself first.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Comment",
            &["body:Text".into(), "post:references".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let test = fs::read_to_string(tmp.path().join("tests/comment.rs")).unwrap();
        let stub_pos = test
            .find("CREATE TABLE IF NOT EXISTS posts")
            .unwrap_or_else(|| panic!("expected a stub `posts` table in the smoke test: {test}"));
        let real_pos = test.find("CREATE TABLE comments").unwrap_or_else(|| {
            panic!("expected the real `comments` table in the smoke test: {test}")
        });
        assert!(
            stub_pos < real_pos,
            "the stub referenced table must be created before the table under test: {test}"
        );
    }

    #[test]
    fn scaffold_smoke_test_emits_one_stub_per_distinct_reference_target() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Follow",
            &["follower:references".into(), "followee:references".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let test = fs::read_to_string(tmp.path().join("tests/follow.rs")).unwrap();
        assert!(test.contains("CREATE TABLE IF NOT EXISTS followers"));
        assert!(test.contains("CREATE TABLE IF NOT EXISTS followees"));
    }

    #[test]
    fn render_reference_stub_tables_sql_dedupes_identical_targets() {
        // Two references that resolve to the same target table must only
        // emit one `CREATE TABLE IF NOT EXISTS` for it. Constructed directly
        // (bypassing `parse_fields`, which enforces unique column names) so
        // the collision is deterministic rather than relying on two English
        // words coincidentally pluralising to the same string.
        let fields = vec![
            Field {
                name: "author_id".to_string(),
                kind: FieldKind::References,
                nullable: false,
                variants: Vec::new(),
                unique: false,
                constraints: FieldConstraints::default(),
                state_machine: None,
            },
            Field {
                name: "author_id".to_string(),
                kind: FieldKind::References,
                nullable: true,
                variants: Vec::new(),
                unique: false,
                constraints: FieldConstraints::default(),
                state_machine: None,
            },
        ];
        assert_eq!(
            fields[0].reference_table(),
            fields[1].reference_table(),
            "test setup: both fields must target the same table"
        );
        let sql = render_reference_stub_tables_sql(&fields, "unrelated_table");
        assert_eq!(
            sql.matches("CREATE TABLE IF NOT EXISTS").count(),
            1,
            "identical targets must be de-duplicated: {sql}"
        );
    }

    #[test]
    fn render_reference_stub_tables_sql_seeds_a_row_so_fk_id_1_is_valid() {
        // Regression test: a raw INSERT the smoke test issues against the
        // table under test (e.g. the enum out-of-set rejection test) uses a
        // NOT NULL `references` column's sample literal ("1" — see
        // `sql_sample_literal`); without a seeded row, that INSERT would
        // fail on the FK constraint regardless of what it's actually trying
        // to exercise. Two rows are seeded (ids 1 and 2) — the second is for
        // `unique_sample_literal_variant`'s "1" (target) vs. "2" (a
        // non-target `unique references` column in the duplicate insert)
        // distinction; see that function's doc comment.
        let fields = super::super::dsl::parse_fields(&["author:references".into()]).unwrap();
        let sql = render_reference_stub_tables_sql(&fields, "posts");
        assert_eq!(
            sql,
            "CREATE TABLE IF NOT EXISTS authors (id BIGSERIAL PRIMARY KEY);\n\
             INSERT INTO authors DEFAULT VALUES;\n\
             INSERT INTO authors DEFAULT VALUES;\n",
            "got:\n{sql}"
        );
    }

    #[test]
    fn render_reference_stub_tables_sql_seeds_only_once_per_distinct_target() {
        let fields = vec![
            Field {
                name: "author_id".to_string(),
                kind: FieldKind::References,
                nullable: false,
                variants: Vec::new(),
                unique: false,
                constraints: FieldConstraints::default(),
                state_machine: None,
            },
            Field {
                name: "author_id".to_string(),
                kind: FieldKind::References,
                nullable: true,
                variants: Vec::new(),
                unique: false,
                constraints: FieldConstraints::default(),
                state_machine: None,
            },
        ];
        let sql = render_reference_stub_tables_sql(&fields, "unrelated_table");
        assert_eq!(
            sql.matches("CREATE TABLE IF NOT EXISTS authors").count(),
            1,
            "two fields pointing at the same target must still only stub \
             (and seed) that table once, not once per field; got:\n{sql}"
        );
        assert_eq!(
            sql.matches("INSERT INTO authors DEFAULT VALUES;").count(),
            2,
            "got:\n{sql}"
        );
    }

    #[test]
    fn render_reference_stub_tables_sql_skips_own_table() {
        // A self-referential `references` field (e.g. `Category` with
        // `category:references`) targets the model's own table, which the
        // real (non-`IF NOT EXISTS`) `CREATE TABLE` creates right after —
        // stubbing it first would collide with that statement.
        let fields = super::super::dsl::parse_fields(&["category:references".into()]).unwrap();
        assert_eq!(fields[0].reference_table().as_deref(), Some("categories"));
        let sql = render_reference_stub_tables_sql(&fields, "categories");
        assert!(sql.is_empty(), "must not stub the model's own table: {sql}");
    }

    #[test]
    fn scaffold_self_referential_reference_compiles_one_create_table() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Category",
            &["name:String".into(), "category:references".into()],
            "20260427000000",
        )
        .unwrap();
        plan.execute(Flags::default()).unwrap();

        let test = fs::read_to_string(tmp.path().join("tests/category.rs")).unwrap();
        assert_eq!(
            test.matches("CREATE TABLE").count(),
            1,
            "a self-referential FK must not stub its own table before creating it for real: {test}"
        );
        assert!(test.contains("category_id BIGINT NOT NULL REFERENCES categories(id)"));
    }

    // ── decimal sample literals fit tightly-scaled columns (issue #1038) ────

    #[test]
    fn decimal_literal_at_scale_never_reaches_one() {
        // Every sample literal must stay strictly under `1` for scale >= 1,
        // so it fits even the tightest valid column (`decimal{scale,scale}`,
        // whose range is `(-1,1)`) regardless of how large `precision` is.
        for scale in 1..=6 {
            for digit in [1, 2, 3] {
                let literal = decimal_literal_at_scale(scale, digit);
                let value: f64 = literal.parse().unwrap();
                assert!(
                    value.abs() < 1.0,
                    "decimal_literal_at_scale({scale}, {digit}) = {literal} must be < 1"
                );
            }
        }
    }

    #[test]
    fn decimal_sample_literals_are_pairwise_distinct_at_every_scale() {
        for scale in 0..=6 {
            let a = sql_sample_literal(FieldKind::Decimal {
                precision: scale.max(1) + 1,
                scale,
            });
            let b = unique_sample_literal(FieldKind::Decimal {
                precision: scale.max(1) + 1,
                scale,
            });
            let c = unique_sample_literal_variant(FieldKind::Decimal {
                precision: scale.max(1) + 1,
                scale,
            });
            assert!(a != b && b != c && a != c, "scale {scale}: {a}, {b}, {c}");
        }
    }

    #[test]
    fn enum_rejection_insert_sql_fits_tightly_scaled_decimal_column() {
        // Regression test: a `decimal{1,1}` column (valid range `(-1,1)`)
        // combined with a required enum column used to get a fixed "1.0"
        // sample literal from `sql_sample_literal`, which Postgres's
        // `NUMERIC(1,1)` rejects as a numeric field overflow — breaking a
        // generated test that has nothing to do with the enum behavior it's
        // meant to exercise.
        let status = Field {
            name: "status".to_string(),
            kind: FieldKind::Enum,
            nullable: false,
            variants: vec!["a".to_string(), "b".to_string()],
            unique: false,
            constraints: FieldConstraints::default(),
            state_machine: None,
        };
        let weight = Field {
            name: "weight".to_string(),
            kind: FieldKind::Decimal {
                precision: 1,
                scale: 1,
            },
            nullable: false,
            variants: Vec::new(),
            unique: false,
            constraints: FieldConstraints::default(),
            state_machine: None,
        };
        let fields = vec![status.clone(), weight];
        let sql = enum_rejection_insert_sql("items", &fields, &status, &BTreeMap::new());
        assert!(
            sql.contains("weight) VALUES ('__not_a_real_variant__', 0.1)"),
            "expected a scale-fitting 0.1 literal for NUMERIC(1,1), got: {sql}"
        );
    }

    #[test]
    fn scaffold_decimal_field_warns_when_existing_rust_decimal_dep_lacks_diesel_feature() {
        let tmp = project_with_main(default_main());
        fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname=\"x\"\n\n[dependencies]\nrust_decimal = \"1\"\n",
        )
        .unwrap();
        let plan = plan_scaffold(
            tmp.path(),
            "Product",
            &["price:decimal".into()],
            "20260427000000",
        )
        .unwrap();
        assert_eq!(plan.warnings.len(), 1, "warnings: {:?}", plan.warnings);
        assert!(plan.warnings[0].contains("rust_decimal"));
        assert!(plan.warnings[0].contains("db-diesel2-postgres"));
    }

    // ── Record-level authorization scaffolding (issue #1125) ───────────────

    fn scaffold_paths(plan: &Plan) -> Vec<String> {
        plan.actions
            .iter()
            .map(|a| {
                a.path()
                    .strip_prefix(&plan.project_root)
                    .unwrap()
                    .display()
                    .to_string()
                    .replace('\\', "/")
            })
            .collect()
    }

    fn action_contents(plan: &Plan, suffix: &str) -> String {
        plan.actions
            .iter()
            .find(|a| {
                a.path()
                    .to_string_lossy()
                    .replace('\\', "/")
                    .ends_with(suffix)
            })
            .map(|a| match a {
                Action::Create { contents, .. } | Action::Modify { contents, .. } => {
                    contents.clone()
                }
                _ => String::new(),
            })
            .unwrap_or_default()
    }

    #[test]
    fn default_scaffold_emits_policy_file_and_registration() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "user_id:i64".into()],
            "20260427000000",
        )
        .unwrap();
        let paths = scaffold_paths(&plan);
        assert!(
            paths.iter().any(|p| p == "src/policies/post.rs"),
            "{paths:?}"
        );
        assert!(
            paths.iter().any(|p| p == "src/policies/mod.rs"),
            "{paths:?}"
        );

        let policy = action_contents(&plan, "src/policies/post.rs");
        assert!(
            policy.contains("impl Policy<Post> for PostPolicy"),
            "{policy}"
        );
        assert!(policy.contains("Some(post.user_id)"), "{policy}");

        let main = action_contents(&plan, "src/main.rs");
        assert!(
            main.contains(".policy::<crate::models::post::Post, _>"),
            "{main}"
        );
        assert!(
            main.contains(".scope::<crate::models::post::Post, _>"),
            "{main}"
        );
        assert!(main.contains("mod policies;"), "{main}");
    }

    #[test]
    fn owner_scaffold_authorizes_mutating_handlers_and_scopes_index() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "user_id:i64".into()],
            "20260427000000",
        )
        .unwrap();
        let routes = action_contents(&plan, "src/routes/posts.rs");
        // edit / update / destroy carry an inline authorize call.
        assert_eq!(
            routes
                .matches("autumn_web::authorization::authorize::<Post>")
                .count(),
            3,
            "edit/update/destroy must each authorize: {routes}"
        );
        assert!(routes.contains("\"edit\", &row"), "{routes}");
        assert!(routes.contains("\"update\", &current"), "{routes}");
        assert!(routes.contains("\"delete\", &current"), "{routes}");
        // The HTML create handler runs the policy's `can_create` check before
        // inserting, threading `State`/`Session` like the other mutations.
        assert!(
            routes
                .contains("autumn_web::authorization::authorize_create::<Post>(&state, &session)"),
            "create must authorize_create: {routes}"
        );
        assert!(routes.contains("pub async fn create("), "{routes}");
        // Issue #1841: the standard owner-scoped index now applies the owner
        // scope through the repository's owner-filtered `list_scoped` (which also
        // brings allowlisted sort/filter), not a hand-rolled diesel query — and
        // it must NEVER fall back to the unscoped `repo.list`/`repo.page`.
        assert!(
            routes.contains("repo.list_scoped(owner_id, &list_query, &page_req)"),
            "index must scope through list_scoped: {routes}"
        );
        assert!(
            !routes.contains("repo.list(&list_query") && !routes.contains("repo.page("),
            "owner-scoped index must not call the unscoped list/page: {routes}"
        );
        assert!(
            routes.contains("PolicyContext::from_request(&state, &session)"),
            "{routes}"
        );
        // The cross-user 403 smoke test is emitted.
        let smoke = action_contents(&plan, "tests/post.rs");
        assert!(
            smoke.contains("cross_user_mutations_are_forbidden"),
            "{smoke}"
        );
        assert!(smoke.contains("ForbiddenResponse::Forbidden403"), "{smoke}");
    }

    #[test]
    fn live_owner_scaffold_authorizes_mutating_handlers_and_scopes_index() {
        // Issue #1830: `--live` variants now record-authorize their mutating
        // handlers and owner-scope the index, loading the current row through the
        // repository (not raw diesel) while keeping the SSE `<ul>` island.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into(), "author_id:i64".into()],
            "20260427000000",
            &ScaffoldOptions {
                live: true,
                ..Default::default()
            },
        )
        .unwrap();
        let routes = action_contents(&plan, "src/routes/posts.rs");
        // edit / update / destroy each carry an inline authorize call.
        assert_eq!(
            routes
                .matches("autumn_web::authorization::authorize::<Post>")
                .count(),
            3,
            "live edit/update/destroy must each authorize: {routes}"
        );
        assert!(routes.contains("\"edit\", &row"), "{routes}");
        assert!(routes.contains("\"update\", &current"), "{routes}");
        assert!(routes.contains("\"delete\", &current"), "{routes}");
        // The row is loaded via the repository extractor, not raw diesel.
        assert!(
            routes.contains("let current: Post = repo.find_by_id(*id).await?"),
            "live variant must load current row via the repository: {routes}"
        );
        assert!(
            routes
                .contains("autumn_web::authorization::authorize_create::<Post>(&state, &session)"),
            "live create must authorize_create: {routes}"
        );
        // Index is owner-scoped but keeps the SSE list contract.
        assert!(
            routes.contains("posts::author_id.eq(owner_id)"),
            "live index must filter by owner: {routes}"
        );
        assert!(
            routes.contains("PolicyContext::from_request(&state, &session)"),
            "{routes}"
        );
        assert!(
            routes.contains("ul id=\"posts-list\"")
                && routes.contains("sse-connect=(paths::events())"),
            "live owner index must keep the SSE ul island: {routes}"
        );
    }

    #[test]
    fn sharded_owner_scaffold_authorizes_mutating_handlers_and_scopes_index() {
        // Issue #1830: `--sharded` variants record-authorize their mutating
        // handlers and owner-scope the index, loading the current row through a
        // `from_shard` repository and querying the pinned `ShardedDb` connection.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into(), "author_id:i64".into()],
            "20260427000000",
            &ScaffoldOptions {
                model: ModelOptions {
                    sharded: true,
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .unwrap();
        let routes = action_contents(&plan, "src/routes/posts.rs");
        assert_eq!(
            routes
                .matches("autumn_web::authorization::authorize::<Post>")
                .count(),
            3,
            "sharded edit/update/destroy must each authorize: {routes}"
        );
        assert!(routes.contains("\"edit\", &row"), "{routes}");
        assert!(routes.contains("\"update\", &current"), "{routes}");
        assert!(routes.contains("\"delete\", &current"), "{routes}");
        // The row is loaded via `from_shard(&db).find_by_id(...)`.
        assert!(
            routes.contains(
                "let current: Post = PgPostRepository::from_shard(&db).find_by_id(*id).await?"
            ),
            "sharded variant must load current row via from_shard: {routes}"
        );
        assert!(
            routes
                .contains("autumn_web::authorization::authorize_create::<Post>(&state, &session)"),
            "sharded create must authorize_create: {routes}"
        );
        // Owner-scoped index runs on the ShardedDb connection (no bare `Db`).
        assert!(
            routes.contains("posts::author_id.eq(owner_id)"),
            "sharded index must filter by owner: {routes}"
        );
        assert!(
            routes.contains("mut db: ShardedDb") && !routes.contains("mut db: Db"),
            "sharded handlers must use ShardedDb, not Db: {routes}"
        );
    }

    #[test]
    fn attachment_owner_scaffold_authorizes_reusing_state_wrapper() {
        // Issue #1830: attachment scaffolds already thread a `state:` wrapper for
        // the multipart upload, so the authorize wiring reuses it (`&*state`) and
        // adds only `session` — no duplicate `State(state)` extractor.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &[
                "title:String".into(),
                "author_id:i64".into(),
                "avatar:Attachment".into(),
            ],
            "20260427000000",
        )
        .unwrap();
        let routes = action_contents(&plan, "src/routes/posts.rs");
        // create/update deref the reused wrapper; edit/destroy take the full pair.
        assert!(
            routes
                .contains("autumn_web::authorization::authorize_create::<Post>(&*state, &session)"),
            "attachment create must authorize_create via &*state: {routes}"
        );
        assert!(
            routes.contains(
                "autumn_web::authorization::authorize::<Post>(&*state, &session, \"update\", &current)"
            ),
            "attachment update must authorize via &*state: {routes}"
        );
        assert!(
            routes.contains(
                "autumn_web::authorization::authorize::<Post>(&state, &session, \"delete\", &current)"
            ),
            "attachment destroy must authorize via &state: {routes}"
        );
        assert!(
            routes.contains(
                "autumn_web::authorization::authorize::<Post>(&state, &session, \"edit\", &row)"
            ),
            "attachment edit must authorize via &state: {routes}"
        );
        // The create/update handlers must NOT gain a second `State(state)`
        // extractor — the reused wrapper stays the sole `state` binding.
        assert!(
            !routes.contains(
                "autumn_web::extract::State(state): autumn_web::extract::State<autumn_web::AppState>,\n    body: Bytes"
            ) && !routes.contains(
                "autumn_web::extract::State(state): autumn_web::extract::State<autumn_web::AppState>,\n    mut multipart"
            ),
            "attachment create/update must not inject a duplicate State extractor: {routes}"
        );
        // Owner-scoped index still emitted for the attachment path. Issue #1841:
        // the standard Db owner index now scopes via the repository's
        // owner-filtered `list_scoped` (with sort/filter) rather than a manual
        // diesel query — and never falls back to the unscoped list/page.
        assert!(
            routes.contains("repo.list_scoped(owner_id, &list_query, &page_req)"),
            "attachment index must scope through list_scoped: {routes}"
        );
        assert!(
            routes.contains("PolicyContext::from_request(&state, &session)"),
            "attachment index must resolve owner_id from the policy context: {routes}"
        );
    }

    #[test]
    fn no_policy_flag_reverts_to_secured_only() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into(), "user_id:i64".into()],
            "20260427000000",
            &ScaffoldOptions {
                no_policy: true,
                ..Default::default()
            },
        )
        .unwrap();
        let paths = scaffold_paths(&plan);
        assert!(
            !paths.iter().any(|p| p.starts_with("src/policies/")),
            "--no-policy must not emit a policies file: {paths:?}"
        );
        let routes = action_contents(&plan, "src/routes/posts.rs");
        assert!(
            !routes.contains("authorize::<Post>"),
            "--no-policy must not wire authorize: {routes}"
        );
        assert!(
            !routes.contains("authorize_create::<Post>"),
            "--no-policy must not wire authorize_create: {routes}"
        );
        let main = action_contents(&plan, "src/main.rs");
        assert!(
            !main.contains(".policy::<"),
            "--no-policy must not register a policy: {main}"
        );
    }

    #[test]
    fn no_owner_scaffold_authorizes_via_authenticated_policy_without_scoping_index() {
        // Issue #1830: no-owner scaffolds now record-authorize their mutating
        // handlers too (routing the mutation through the enforceable policy), and
        // the generated no-owner policy authorizes any authenticated user — so a
        // fresh scaffold never 403s out of the box. There is no owner column, so
        // the index is NOT owner-scoped.
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "body:Text".into()],
            "20260427000000",
        )
        .unwrap();
        // Policy generated (authenticated check + SECURITY TODO) and registered.
        let policy = action_contents(&plan, "src/policies/post.rs");
        assert!(
            policy.contains("// SECURITY TODO: this only checks authentication"),
            "{policy}"
        );
        assert!(
            policy.contains("Box::pin(async move { ctx.is_authenticated() })"),
            "no-owner can_update/can_delete must authenticate-check: {policy}"
        );
        let main = action_contents(&plan, "src/main.rs");
        assert!(
            main.contains(".policy::<crate::models::post::Post, _>"),
            "{main}"
        );
        // Mutating handlers are now inline-authorized (edit/update/destroy) and
        // create runs authorize_create — routed through the enforceable policy.
        let routes = action_contents(&plan, "src/routes/posts.rs");
        assert_eq!(
            routes
                .matches("autumn_web::authorization::authorize::<Post>")
                .count(),
            3,
            "no-owner edit/update/destroy must each authorize: {routes}"
        );
        assert!(
            routes
                .contains("autumn_web::authorization::authorize_create::<Post>(&state, &session)"),
            "no-owner create must authorize_create: {routes}"
        );
        // But the index is NOT owner-scoped (no owner column to filter on).
        assert!(
            !routes.contains(".eq(owner_id)"),
            "no-owner index must not be owner-scoped: {routes}"
        );
        assert!(
            !routes.contains("PolicyContext::from_request(&state, &session)"),
            "no-owner index must not build a PolicyContext for owner filtering: {routes}"
        );
    }

    #[test]
    fn api_scaffold_never_generates_policy() {
        let tmp = project_with_main(default_main());
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into(), "user_id:i64".into()],
            "20260427000000",
            &ScaffoldOptions {
                api: true,
                ..Default::default()
            },
        )
        .unwrap();
        let paths = scaffold_paths(&plan);
        assert!(
            !paths.iter().any(|p| p.starts_with("src/policies/")),
            "--api must not emit a policy: {paths:?}"
        );
    }

    #[test]
    fn policy_registration_survives_scaffold_destroy_round_trip() {
        let tmp = project_with_main(default_main());
        let main_path = tmp.path().join("src/main.rs");
        let original_main = fs::read_to_string(&main_path).unwrap();

        plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "user_id:i64".into()],
            "20260427000000",
        )
        .unwrap()
        .execute(Flags::default())
        .unwrap();
        assert!(tmp.path().join("src/policies/post.rs").exists());
        assert!(
            fs::read_to_string(&main_path)
                .unwrap()
                .contains(".policy::<")
        );

        plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into(), "user_id:i64".into()],
            "20260427000000",
        )
        .unwrap()
        .revert(Flags::default())
        .unwrap();
        assert!(!tmp.path().join("src/policies/post.rs").exists());
        assert!(!tmp.path().join("src/policies").exists());
        assert_eq!(fs::read_to_string(&main_path).unwrap(), original_main);
    }

    // ── submit-token live-validation exempt_paths (issue #1360) ──────────────

    #[test]
    fn submit_token_exempt_appends_fresh_block_when_absent() {
        let existing = "[server]\nport = 3000\n";
        let out = append_submit_token_validate_exempt_to_toml(existing, "posts")
            .expect("absent exemption must be inserted");
        assert!(out.contains("[security.submit_token]"), "{out}");
        assert!(
            out.contains("exempt_paths = [\"/posts/validate\"]"),
            "{out}"
        );
        // The original content is preserved.
        assert!(out.contains("[server]"), "{out}");
    }

    #[test]
    fn submit_token_exempt_is_idempotent() {
        let existing = "[security.submit_token]\nexempt_paths = [\"/posts/validate\"]\n";
        let out = append_submit_token_validate_exempt_to_toml(existing, "posts");
        assert_eq!(
            out, None,
            "re-adding the same prefix must be a no-op returning None"
        );
    }

    #[test]
    fn submit_token_exempt_merges_into_existing_array() {
        let existing =
            "[security.submit_token]\nttl_secs = 900\nexempt_paths = [\"/webhooks/x\"]\n";
        let out = append_submit_token_validate_exempt_to_toml(existing, "posts")
            .expect("a new prefix must be merged into the existing array");
        assert!(out.contains("\"/webhooks/x\""), "{out}");
        assert!(out.contains("\"/posts/validate\""), "{out}");
        assert!(out.contains("ttl_secs = 900"), "{out}");
        // No duplicate exempt_paths key.
        assert_eq!(out.matches("exempt_paths").count(), 1, "{out}");
    }

    #[test]
    fn submit_token_exempt_merges_into_commented_multiline_array() {
        // A hand-edited, multiline `exempt_paths` array with item comments must
        // merge into VALID TOML: the format-preserving edit inserts the new path
        // as a real array element before the closing bracket, never splicing it
        // after a `#` comment (which would produce e.g.
        // `[..., # api, "/posts/validate"]` — invalid TOML that corrupts the
        // config).
        let existing = "\
[security.submit_token]
exempt_paths = [
    \"/api\", # public api, never guarded
    \"/webhooks/x\",
]
";
        let out = append_submit_token_validate_exempt_to_toml(existing, "posts")
            .expect("a new prefix must be merged into the commented array");
        // The merged output is valid TOML.
        let parsed: toml::Value =
            toml::from_str(&out).unwrap_or_else(|e| panic!("merged TOML must parse: {e}\n{out}"));
        // Both preexisting entries and the new prefix are present.
        let paths = parsed["security"]["submit_token"]["exempt_paths"]
            .as_array()
            .expect("exempt_paths must be an array");
        let values: Vec<&str> = paths.iter().filter_map(toml::Value::as_str).collect();
        assert!(values.contains(&"/api"), "{out}");
        assert!(values.contains(&"/webhooks/x"), "{out}");
        assert!(values.contains(&"/posts/validate"), "{out}");
        // The item comment survives the edit.
        assert!(out.contains("# public api, never guarded"), "{out}");
        // No duplicate exempt_paths key.
        assert_eq!(out.matches("exempt_paths").count(), 1, "{out}");
    }

    #[test]
    fn submit_token_exempt_inserts_key_when_block_lacks_it() {
        let existing = "[security.submit_token]\nttl_secs = 900\n";
        let out = append_submit_token_validate_exempt_to_toml(existing, "posts")
            .expect("a block lacking the key must gain one");
        assert!(
            out.contains("exempt_paths = [\"/posts/validate\"]"),
            "{out}"
        );
        assert!(out.contains("ttl_secs = 900"), "{out}");
    }

    #[test]
    fn submit_token_exempt_prefix_covers_only_validation_routes() {
        // Field-name-agnostic: the exemption is a route prefix, independent of
        // `security.submit_token.field_name`. It must cover the per-field
        // validation routes but never the guarded create route.
        assert_eq!(
            submit_token_validate_exempt_prefix("posts"),
            "/posts/validate"
        );
    }

    #[test]
    fn remove_submit_token_exempt_drops_fresh_block() {
        let existing = "[server]\nport = 3000\n";
        let added = append_submit_token_validate_exempt_to_toml(existing, "posts")
            .expect("fresh block must be added");
        let removed = remove_submit_token_validate_exempt_from_toml(&added, "posts");
        assert!(!removed.contains("/posts/validate"), "{removed}");
        assert!(!removed.contains("[security.submit_token]"), "{removed}");
        assert!(removed.contains("[server]"), "{removed}");
    }

    #[test]
    fn remove_submit_token_exempt_keeps_other_entries() {
        let existing =
            "[security.submit_token]\nexempt_paths = [\"/webhooks/x\", \"/posts/validate\"]\n";
        let removed = remove_submit_token_validate_exempt_from_toml(existing, "posts");
        assert!(removed.contains("\"/webhooks/x\""), "{removed}");
        assert!(!removed.contains("/posts/validate"), "{removed}");
        assert!(removed.contains("[security.submit_token]"), "{removed}");
    }

    #[test]
    fn remove_submit_token_exempt_ignores_hand_edited_value() {
        // Never touch an array that no longer carries our exact prefix.
        let existing = "[security.submit_token]\nexempt_paths = [\"/custom/only\"]\n";
        let removed = remove_submit_token_validate_exempt_from_toml(existing, "posts");
        assert_eq!(removed, existing);
    }

    #[test]
    fn live_validation_scaffold_exempts_validation_routes_in_autumn_toml() {
        // End-to-end at plan level: a `--live-validation` scaffold with a
        // CUSTOM submit-token field name still exempts the generated
        // `/posts/validate/*` routes, because the exemption is route-based
        // (field-name-agnostic) rather than relying on the `hx-params` filter,
        // which only strips the default `_submit_token` name.
        let tmp = project_with_main(default_main());
        // A customised field name in autumn.toml — the exemption must not depend
        // on it.
        fs::write(
            tmp.path().join("autumn.toml"),
            "[security.submit_token]\nfield_name = \"_confirm\"\n",
        )
        .unwrap();
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260712000000",
            &ScaffoldOptions {
                live_validation: true,
                ..Default::default()
            },
        )
        .unwrap();

        let toml_action = plan
            .actions
            .iter()
            .rev()
            .find_map(|a| match a {
                Action::Modify { path, contents } if path.ends_with("autumn.toml") => {
                    Some(contents.clone())
                }
                _ => None,
            })
            .expect("live-validation scaffold must modify autumn.toml");
        assert!(
            toml_action.contains("\"/posts/validate\""),
            "autumn.toml must exempt the validation route prefix:\n{toml_action}"
        );
        // The custom field name is left untouched.
        assert!(
            toml_action.contains("field_name = \"_confirm\""),
            "{toml_action}"
        );
    }

    #[test]
    fn non_live_validation_scaffold_does_not_touch_autumn_toml_exempt() {
        let tmp = project_with_main(default_main());
        fs::write(tmp.path().join("autumn.toml"), "[server]\nport = 3000\n").unwrap();
        let plan = plan_scaffold(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260712000000",
        )
        .unwrap();
        let touches_toml = plan
            .actions
            .iter()
            .any(|a| a.path().ends_with("autumn.toml"));
        assert!(
            !touches_toml,
            "a plain scaffold (no --live-validation) must not add submit-token exemptions"
        );
    }

    #[test]
    fn live_validation_scaffold_records_revert_only_when_exemption_inserted() {
        // Absent exemption: the scaffold both modifies autumn.toml AND records a
        // `SubmitTokenValidateExempt` revert so `autumn destroy` cleans up the
        // entry it added.
        let tmp = project_with_main(default_main());
        fs::write(
            tmp.path().join("autumn.toml"),
            "[security.submit_token]\nfield_name = \"_confirm\"\n",
        )
        .unwrap();
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260712000000",
            &ScaffoldOptions {
                live_validation: true,
                ..Default::default()
            },
        )
        .unwrap();

        let touches_toml = plan
            .actions
            .iter()
            .any(|a| a.path().ends_with("autumn.toml"));
        assert!(
            touches_toml,
            "an absent exemption must be inserted via a modify action"
        );
        let has_revert = plan.reverts.iter().any(|r| {
            matches!(
                r,
                Revert::SubmitTokenValidateExempt { plural, .. } if plural == "posts"
            )
        });
        assert!(
            has_revert,
            "inserting the exemption must record a SubmitTokenValidateExempt revert"
        );
    }

    #[test]
    fn live_validation_scaffold_skips_revert_when_exemption_preexists() {
        // The exemption is ALREADY present (e.g. a user hand-added it, possibly
        // with a custom field name). The scaffold must NOT modify autumn.toml and
        // must NOT record a revert — otherwise a later `autumn destroy` would
        // delete a user-owned entry, re-enabling submit-token guarding on the
        // live-validation routes.
        let tmp = project_with_main(default_main());
        fs::write(
            tmp.path().join("autumn.toml"),
            "[security.submit_token]\nfield_name = \"_confirm\"\nexempt_paths = [\"/posts/validate\"]\n",
        )
        .unwrap();
        let plan = plan_scaffold_with_options(
            tmp.path(),
            "Post",
            &["title:String".into()],
            "20260712000000",
            &ScaffoldOptions {
                live_validation: true,
                ..Default::default()
            },
        )
        .unwrap();

        let touches_toml = plan
            .actions
            .iter()
            .any(|a| a.path().ends_with("autumn.toml"));
        assert!(
            !touches_toml,
            "a preexisting exemption must not be re-modified"
        );
        let has_revert = plan
            .reverts
            .iter()
            .any(|r| matches!(r, Revert::SubmitTokenValidateExempt { .. }));
        assert!(
            !has_revert,
            "a preexisting, user-owned exemption must not be claimed via a revert"
        );
    }
}