jerrycan 0.7.12

The AI-native Rust backend platform: framework, CLI, and MCP server. https://jerrycan.cc
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
//! Deterministic design validation → pointed questions (jerrycan_design's engine).

use super::design::*;
use serde::Serialize;

/// One pointed question. `id` is a JSON-pointer into the draft.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct Question {
    pub id: String,
    pub question: String,
}

fn q(id: impl Into<String>, question: impl Into<String>) -> Question {
    Question {
        id: id.into(),
        question: question.into(),
    }
}

fn is_kebab(s: &str) -> bool {
    !s.is_empty()
        && s.starts_with(|c: char| c.is_ascii_lowercase())
        && s.chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}

fn is_snake(s: &str) -> bool {
    !s.is_empty()
        && s.starts_with(|c: char| c.is_ascii_lowercase())
        && s.chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}

fn is_pascal(s: &str) -> bool {
    !s.is_empty()
        && s.starts_with(|c: char| c.is_ascii_uppercase())
        && s.chars().all(|c| c.is_ascii_alphanumeric())
}

/// Identifiers every generated route crate pulls into scope via
/// `use jerrycan::prelude::*;` (issue #114). This MIRRORS `jerrycan_core::prelude`
/// (crates/jerrycan-core/src/lib.rs) plus the re-exported `main` macro — the exact
/// glob the tool-owned `mod.rs`/`repo.rs`/`handlers.rs` write. An entity whose
/// PascalCase name equals one of these emits `pub struct {Name}` in `model.rs`,
/// which the sibling files glob-import via `use super::model::*;` ALONGSIDE the
/// prelude glob: two glob imports bring the same `{Name}` into scope, so every
/// reference is `E0659 ... is ambiguous` and the scaffolded crate does not compile
/// (the round-5 eval hit an entity named `Module`). Kept sorted for auditing; the
/// lowercase method fns / `main` can never collide with a PascalCase entity name
/// but are listed so the reserved set matches the glob exactly.
const RESERVED_PRELUDE_IDENTS: &[&str] = &[
    "App",
    "Clock",
    "CorsConfig",
    "CorsOrigins",
    "Created",
    "Dep",
    "Error",
    "Extension",
    "Headers",
    "IntoResponse",
    "Json",
    "Middleware",
    "MiddlewareFuture",
    "Module",
    "Multipart",
    "Next",
    "NoContent",
    "Path",
    "Query",
    "RawBody",
    "Redirect",
    "RequestCtx",
    "Result",
    "StreamBody",
    "TestApp",
    "TestPart",
    "delete",
    "get",
    "main",
    "now_rfc3339",
    "patch",
    "post",
    "put",
];

/// An enum `values` entry that is safe to interpolate unescaped into generated
/// Rust (issue #54): `^[A-Za-z0-9_-]+$`. Values reach a `"..."` string literal in
/// the generated deserialize allow-list, the 422 error text, and the testgen
/// fixture with no escaping, so anything with a quote/backslash/space would break
/// the generated crate at build time — validate the shape at design time instead.
fn is_enum_value(s: &str) -> bool {
    !s.is_empty()
        && s.bytes()
            .all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-')
}

/// A validation message when a field's server-owned `default` (issue #53a) is
/// invalid, or `None` when the default is absent or valid. Three ways to be
/// wrong: (1) declared without a `db` dependency — the default is applied via the
/// db-mode request DTO, so it is silently inert in memory mode; (2) the value
/// does not type-check against the field's `type`; (3) the value is outside the
/// field's enum `values`. The default is written into a NOT-NULL column verbatim,
/// so a mistyped or out-of-enum literal is a design-time error, not a run-time
/// surprise. A `json` field accepts any JSON value.
fn default_type_error(f: &Field, wants_db: bool) -> Option<String> {
    let value = f.default.as_ref()?;
    if !wants_db {
        return Some(format!(
            "Field `{}` declares a `default` but the design has no `db` dependency — server-owned defaults are applied through the db-mode request DTO (add `db` to `dependencies`, or drop the default).",
            f.name
        ));
    }
    // JC0557 (#110): the `now` sentinel is a DYNAMIC server-set timestamp, valid
    // ONLY on a `datetime` field. Intercept it before the generic type/enum
    // acceptance below so a `"now"` elsewhere is refused (on a `string` it is
    // otherwise a legitimate literal — the refusal is what disambiguates the
    // timestamp intent) and a near-miss casing on a datetime field is never
    // silently mis-read as a static literal. The db requirement above already
    // covers `now`. The EXACT `"now"` on a `datetime` field is left to fall through
    // — it type-checks clean (datetime rides as a String) and carries no bounds.
    if let Some(s) = value.as_str() {
        if s == "now" && f.field_type != FieldType::Datetime {
            return Some(format!(
                "Field `{}` default \"now\" is a server-set-timestamp sentinel — valid only on a `datetime` field (issue #110). Use a static default here, or change the field `type` to `datetime`. See `jerrycan explain JC0557`.",
                f.name
            ));
        }
        if s != "now" && s.eq_ignore_ascii_case("now") && f.field_type == FieldType::Datetime {
            return Some(format!(
                "Field `{}` default {value} looks like the server-set-timestamp sentinel but is mis-cased — set `{}` to the current time on create with exactly `\"now\"` (lowercase), or give a full RFC3339 literal for a static default. See `jerrycan explain JC0557`.",
                f.name, f.name
            ));
        }
    }
    // Enum membership: a default on a string field with `values` must be listed.
    if let Some(values) = &f.values {
        return match value.as_str() {
            Some(s) if values.contains(&s.to_string()) => None,
            _ => Some(format!(
                "Field `{}` default {value} is not one of its enum values [{}] — the default must be a declared value.",
                f.name,
                values.join(", ")
            )),
        };
    }
    let ok = match f.field_type {
        FieldType::String | FieldType::Datetime | FieldType::Uuid => value.is_string(),
        FieldType::Integer => value.is_i64() || value.is_u64(),
        FieldType::Float => value.is_number(),
        FieldType::Boolean => value.is_boolean(),
        FieldType::Json => true,
    };
    if !ok {
        return Some(format!(
            "Field `{}` default {value} does not match its type `{:?}` — the server writes it verbatim, so it must be a valid {:?} literal.",
            f.name, f.field_type, f.field_type
        ));
    }
    // #80 (JC0552): the default must also satisfy the field's OWN range/length
    // constraints — an out-of-bounds default would plant a value the declared
    // bound forbids on every defaulted row.
    let bound = |b: Option<i64>| b.map_or_else(|| "unbounded".into(), |v: i64| v.to_string());
    if matches!(f.field_type, FieldType::Integer) && (f.min.is_some() || f.max.is_some()) {
        // A u64 beyond i64::MAX has no as_i64(): it exceeds any i64 `max` and
        // satisfies any i64 `min`.
        let out = match value.as_i64() {
            Some(v) => f.min.is_some_and(|mn| v < mn) || f.max.is_some_and(|mx| v > mx),
            None => f.max.is_some(),
        };
        if out {
            return Some(format!(
                "Field `{}` default {value} is outside its own declared range [min {}, max {}] — pick an in-range default, or relax the bound. See `jerrycan explain JC0552`.",
                f.name,
                bound(f.min),
                bound(f.max)
            ));
        }
    }
    if matches!(f.field_type, FieldType::String)
        && (f.min_len.is_some() || f.max_len.is_some())
        && let Some(s) = value.as_str()
    {
        let n = s.chars().count() as u64;
        if f.min_len.is_some_and(|mn| n < mn) || f.max_len.is_some_and(|mx| n > mx) {
            return Some(format!(
                "Field `{}` default {value} is {n} code points long, outside its own declared length bounds [min_len {}, max_len {}] — pick a default of a valid length, or relax the bound. See `jerrycan explain JC0552`.",
                f.name,
                f.min_len
                    .map_or_else(|| "unbounded".into(), |v: u64| v.to_string()),
                f.max_len
                    .map_or_else(|| "unbounded".into(), |v: u64| v.to_string())
            ));
        }
    }
    None
}

/// The entity an endpoint's repo operates on (mirrors genroute's resolution):
/// the request_body entity, else the success entity, else the module's first
/// entity. `None` when the module declares no entities. Kept in lockstep with
/// `genroute::endpoint_repo_entity` so design-time checks reason about the same
/// entity the generator wires.
fn endpoint_repo_entity<'a>(m: &'a ModuleDesign, ep: &'a Endpoint) -> Option<&'a str> {
    if m.entities.is_empty() {
        return None;
    }
    ep.request_body
        .as_ref()
        .and_then(|rb| rb.entity.as_deref())
        .or(ep.success.entity.as_deref())
        .or_else(|| m.entities.first().map(|e| e.name.as_str()))
}

/// The per-FIELD shape checks (#47 enum values + #80 range/length JC0552 + the pk
/// `write_only` JC0554 + `default` type-check) for one field, pointed at `fptr`
/// (`.../fields/{j}`). Factored out of `check_relations_and_enums` so an inline-DTO
/// body's fields (issue #122) get the SAME JC0552/JC0543 checks as entity fields —
/// they must not be silently skipped. Byte-identical questions for entity fields
/// (same pointers, same messages) since `fptr` reconstructs the old pointer.
fn check_field_shape(f: &Field, fptr: &str, wants_db: bool, qs: &mut Vec<Question>) {
    if let Some(ref values) = f.values {
        if !matches!(f.field_type, FieldType::String) {
            qs.push(q(
                format!("{fptr}/values"),
                format!(
                    "Field `{}` declares enum `values` but its type is not string — enum values are only allowed on string fields.",
                    f.name
                ),
            ));
        } else if values.is_empty() {
            qs.push(q(
                format!("{fptr}/values"),
                format!(
                    "Field `{}` declares an empty `values` list — list at least one allowed value or drop the field.",
                    f.name
                ),
            ));
        } else if let Some(bad) = values.iter().find(|v| !is_enum_value(v)) {
            // JC0543 (#54): enum values are interpolated UNESCAPED into
            // generated Rust (the deserialize allow-list + 422 text in
            // genroute, the testgen fixture), so a quote or backslash
            // emits a crate that won't compile far from the design.
            // Constrain to an identifier-ish shape (which also excludes
            // spaces etc. under the same interpolation-safety rule).
            qs.push(q(
                format!("{fptr}/values"),
                format!(
                    "Field `{}` enum value `{bad}` is not an identifier (^[A-Za-z0-9_-]+$) — enum values are interpolated unescaped into generated Rust (the deserialize allow-list, the 422 error text, and the test fixtures), so a quote or backslash emits a crate that fails to compile; other non-identifier characters are rejected under the same rule. Use identifier-shaped values (letters, digits, `_`, `-`). See `jerrycan explain JC0543`.",
                    f.name
                ),
            ));
        }
    }
    // #80 (JC0552): field range/length constraints. Refuse
    // misplacement, empty ranges, contradictions with `values`, an
    // unfillable required field, an over-ceiling `min_len`, and ANY
    // constraint on the pk `id` — each pointed at the offending key.
    // The pk check runs first and swallows the rest: ids are
    // server-assigned, and the generated id probes and seeds assume
    // them free.
    if f.name == "id" {
        // JC0554 (#112): the pk id must be returned in every response
        // (the id-echo probe + every cross-scope test key on
        // `body["id"]`), so an EXPLICIT `write_only` on it would
        // response-hide the id and break the generated suite by
        // construction. The `password_hash` auto-classification never
        // applies to `id`, so only the explicit flag is refused here.
        if f.write_only {
            qs.push(q(
                format!("{fptr}/write_only"),
                "Field `id` is the primary key — `write_only` is not allowed on it: the id must be returned in every response (the generated id-echo probe and every cross-scope test key on `body[\"id\"]`), so hiding it breaks the generated suite by construction. Remove `write_only` from `id`. See `jerrycan explain JC0554`.".to_string(),
            ));
        }
        for (key, present) in [
            ("min", f.min.is_some()),
            ("max", f.max.is_some()),
            ("min_len", f.min_len.is_some()),
            ("max_len", f.max_len.is_some()),
        ] {
            if present {
                qs.push(q(
                    format!("{fptr}/{key}"),
                    format!(
                        "Field `id` is the primary key — `{key}` is not allowed on it: ids are server-assigned, and the generated id probes and seeds assume unconstrained ids. Drop `{key}`. See `jerrycan explain JC0552`."
                    ),
                ));
            }
        }
    } else {
        if f.min.is_some() || f.max.is_some() {
            if !matches!(f.field_type, FieldType::Integer) {
                for (key, present) in [("min", f.min.is_some()), ("max", f.max.is_some())] {
                    if present {
                        qs.push(q(
                            format!("{fptr}/{key}"),
                            format!(
                                "Field `{}` declares `{key}` but its type is not integer — `min`/`max` are an inclusive integer range, only allowed on integer fields. Use `min_len`/`max_len` to bound a string's length, or drop `{key}`. See `jerrycan explain JC0552`.",
                                f.name
                            ),
                        ));
                    }
                }
            } else if let (Some(mn), Some(mx)) = (f.min, f.max)
                && mn > mx
            {
                qs.push(q(
                    format!("{fptr}/min"),
                    format!(
                        "Field `{}` declares an empty range: min {mn} > max {mx} — no value can satisfy it, so no in-range fixture is derivable. Lower `min` or raise `max`. See `jerrycan explain JC0552`.",
                        f.name
                    ),
                ));
            } else if f.unique {
                // #80 (T3): the generated suite materializes up to
                // THREE distinct values per field — the probe
                // fixture plus the tenant-1 and tenant-2 seeds —
                // so a `unique` range below that collides on the
                // UNIQUE index and is un-greenable by construction.
                // An ABSENT bound substitutes its i64 extreme (T4):
                // a single `min` near i64::MAX (or `max` near
                // i64::MIN) leaves the same too-narrow range even
                // though only one bound was written.
                let mn = f.min.unwrap_or(i64::MIN);
                let mx = f.max.unwrap_or(i64::MAX);
                if (mx as i128) - (mn as i128) + 1 < 3 {
                    let key = if f.min.is_some() { "min" } else { "max" };
                    qs.push(q(
                        format!("{fptr}/{key}"),
                        format!(
                            "Field `{}` is `unique` but its range [min {mn}, max {mx}] admits only {} distinct value(s) — the generated seeds and probe fixture need up to 3 distinct in-range values (the request fixture and the two tenant seeds), so uniqueness cannot hold. Widen the range to at least 3 values, or drop `unique`. See `jerrycan explain JC0552`.",
                            f.name,
                            (mx as i128) - (mn as i128) + 1
                        ),
                    ));
                }
            }
        }
        if f.min_len.is_some() || f.max_len.is_some() {
            if !matches!(f.field_type, FieldType::String) {
                for (key, present) in [
                    ("min_len", f.min_len.is_some()),
                    ("max_len", f.max_len.is_some()),
                ] {
                    if present {
                        qs.push(q(
                            format!("{fptr}/{key}"),
                            format!(
                                "Field `{}` declares `{key}` but its type is not string — `min_len`/`max_len` bound a string's length in Unicode code points. Use `min`/`max` for an integer range, or drop `{key}`. See `jerrycan explain JC0552`.",
                                f.name
                            ),
                        ));
                    }
                }
            } else if f.values.is_some() {
                let key = if f.min_len.is_some() {
                    "min_len"
                } else {
                    "max_len"
                };
                qs.push(q(
                    format!("{fptr}/{key}"),
                    format!(
                        "Field `{}` combines enum `values` with `{key}` — the enum already fixes the exact allowed strings, so a length bound is contradictory. Drop `{key}` (or drop `values`). See `jerrycan explain JC0552`.",
                        f.name
                    ),
                ));
            } else if let (Some(mn), Some(mx)) = (f.min_len, f.max_len)
                && mn > mx
            {
                qs.push(q(
                    format!("{fptr}/min_len"),
                    format!(
                        "Field `{}` declares an empty range: min_len {mn} > max_len {mx} — no value can satisfy it, so no in-range fixture is derivable. Lower `min_len` or raise `max_len`. See `jerrycan explain JC0552`.",
                        f.name
                    ),
                ));
            } else if f.max_len == Some(0) && f.required {
                qs.push(q(
                    format!("{fptr}/max_len"),
                    format!(
                        "Field `{}` is required but declares `max_len: 0` — an unfillable field: no value satisfies a zero-length required string. Raise `max_len`, or make the field optional (`required: false`). See `jerrycan explain JC0552`.",
                        f.name
                    ),
                ));
            } else if f.max_len == Some(0) && f.unique {
                // #80 (T3): the string twin of the unique-range
                // rule — `max_len: 0` admits ONLY the empty
                // string, so the seeds cannot be distinct. Any
                // max_len >= 1 is fine: the seed derivations lead
                // with distinct characters ('t'/'s'/a digit).
                qs.push(q(
                    format!("{fptr}/max_len"),
                    format!(
                        "Field `{}` is `unique` but declares `max_len: 0` — the empty string is the only possible value, so the generated seeds cannot derive distinct values. Raise `max_len`, or drop `unique`. See `jerrycan explain JC0552`.",
                        f.name
                    ),
                ));
            } else if f.min_len.is_some_and(|n| n > 4096) {
                qs.push(q(
                    format!("{fptr}/min_len"),
                    format!(
                        "Field `{}` declares min_len {} above the 4096 ceiling — generated test fixtures materialize a minimum-length value, so a larger bound is refused. Lower `min_len` to at most 4096. See `jerrycan explain JC0552`.",
                        f.name,
                        f.min_len.unwrap()
                    ),
                ));
            }
        }
    }
    // A server-owned `default` (issue #53a) must type-check against the
    // field type (and enum membership) — the server writes it verbatim
    // into a NOT-NULL column, so a mistyped literal would fail at run
    // time, not design time.
    if let Some(msg) = default_type_error(f, wants_db) {
        qs.push(q(format!("{fptr}/default"), msg));
    }
}

// The fixed membership-principal column `user_id` (`MEMBERSHIP_PRINCIPAL_COLUMN`)
// and the DESIGN-AWARE identity-fk resolution (`Design::identity_fk_column`, #150)
// both live in `design.rs`. They reach this module through the
// `use super::design::*` glob above.

/// A fatal design-shape conflict caught before any scaffolding — distinct from
/// the completeness questions `validate` returns (which a field edit can
/// answer). This one needs a structural redesign, so it carries a stable JC
/// code the CLI (`{ok:false, code, ...}`) and the MCP twin render.
#[derive(Debug)]
pub struct DesignConflict {
    pub code: &'static str,
    pub message: String,
    pub hint: String,
}

/// Reject a design that cannot be generated regardless of completeness. Rules:
/// (JC0566, #150) an explicit `auth.identity` must name a declared entity; and
/// (JC0540, #27) `tenancy.entity` must not BE the auth identity entity — when it
/// is, the tenant's derived fk column equals the membership table's fixed
/// `user_id` column, so the auth_0001 migration declares `user_id` twice and
/// dies with `duplicate column name: user_id` — mid-scaffold, on a half-written
/// tree. Catch them up front instead. Shared by the CLI and MCP so they can't drift.
pub fn design_conflict(d: &Design) -> Option<DesignConflict> {
    // JC0566 (#150): an explicit `auth.identity` must name a DECLARED entity —
    // owner-scoping, the #34 server-injected fk, and public_read all detect
    // ownership by this entity's derived fk column, so a typo'd/absent identity
    // would resolve to a fk NO entity carries and silently disable owner-scoping
    // everywhere behind a green check. The default `"User"` is exempt (a design
    // may use auth without declaring a `User` entity — e.g. an external identity
    // provider), so only an explicitly-set identity is validated.
    if let Some(identity) = d.auth.as_ref().and_then(|a| a.identity.as_deref())
        && d.find_entity(identity).is_none()
    {
        return Some(DesignConflict {
            code: "JC0566",
            message: format!(
                "auth.identity `{identity}` names no declared entity — per-user owner-scoping, the server-injected identity fk (#34), and public_read all detect ownership by the derived column `{}`, so an identity that maps to no entity silently disables owner-scoping (every authenticated caller reads and writes every row) behind a green `check`. Declare an entity named `{identity}`, or drop `auth.identity` to use the default `User`. See `jerrycan explain JC0566`.",
                d.identity_fk_column()
            ),
            hint: format!(
                "declare an entity named `{identity}` (the auth identity), or omit `auth.identity` (defaults to `User`)"
            ),
        });
    }
    // JC0540: tenancy.entity must not derive a fk that collides in the members
    // table. Two collisions, both fatal: (a) it equals the DESIGN identity fk
    // (`snake(auth.identity)_id`, default `user_id`, #150) — the identity entity
    // cannot also be the tenant org (a user cannot be their own org); (b) it
    // equals the FIXED membership-principal `user_id` — the members DDL already
    // declares that column, so scaffolding dies with `duplicate column name`.
    // For the default `"User"` identity the two coincide (byte-identical); a
    // non-`User` identity keeps BOTH guards.
    if let Some(tenancy) = &d.tenancy {
        let tenant_fk = Design::fk_column(&tenancy.entity);
        if tenant_fk == d.identity_fk_column() || tenant_fk == MEMBERSHIP_PRINCIPAL_COLUMN {
            let entity = &tenancy.entity;
            return Some(DesignConflict {
                code: "JC0540",
                message: format!(
                    "tenancy.entity `{entity}` is the auth identity entity — its derived foreign key column `{tenant_fk}` collides with the membership table's authenticated-user column, so scaffolding would die with `duplicate column name: {tenant_fk}`. A user cannot be their own tenant org. For per-user data, drop the `tenancy` block and give each owned entity a `belongs_to` `{entity}` plus tenant-scoped guard methods (all_for/get_for); for orgs/teams, point tenancy.entity at a separate tenant entity (e.g. Org or Workspace). See `jerrycan docs tenancy` / `jerrycan explain JC0540`."
                ),
                hint: format!(
                    "per-user data → `belongs_to` `{entity}` + scoped guard methods; orgs/teams → a separate tenant entity (Org/Workspace)"
                ),
            });
        }
    }
    // JC0548 (#107): with tenancy, `member_roles` backs the generated member-
    // management surface — `member_roles[0]` is the admin role, and every role
    // is interpolated UNESCAPED into generated Rust string literals — so the
    // list must be non-empty, duplicate-free, and identifier-shaped.
    if let Some(conflict) = member_roles_conflict(d) {
        return Some(conflict);
    }
    // JC0541 (#44): an entity literally named `{X}Request` collides with the
    // `{X}Request` DTO/OpenAPI component generated for an entity `X` that omits a
    // server-owned field. Two `struct XRequest` would fail to compile in genroute and
    // silently overwrite each other in the OpenAPI schema map. Only a REAL collision
    // fires — `X` must actually mint the DTO (db mode + a server-owned omission) — so
    // an ordinary `*Request` name that shadows nothing is never rejected.
    if let Some(conflict) = request_dto_name_collision(d) {
        return Some(conflict);
    }
    // JC0561 (#122): an inline-DTO `request_body` mints a `{Pascal(operation_id)}Request`
    // struct + OpenAPI component that shares the DTO namespace with the entity
    // `{Entity}Request`/`{Entity}UpdateRequest` DTOs and with every OTHER inline body.
    // Nothing else validates that name, so a collision slips past a green `check` into
    // an E0428 duplicate struct (same module) or a clobbered OpenAPI schema
    // (cross-module — `components/schemas` is one global map, and operation_id is
    // unique only per-module). Caught here so `check`/MCP refuse it up front.
    if let Some(conflict) = inline_dto_name_collision(d) {
        return Some(conflict);
    }
    // JC0542 (#65): sibling routes that name a shared path position's `{param}`
    // differently panic at `App::build` (JC0500), a clean-scaffold-then-mid-test
    // failure. Caught here as a fatal conflict — it needs a rename or a restructure.
    if let Some(conflict) = router_param_conflict(d) {
        return Some(conflict);
    }
    None
}

/// The JC0548 check (issue #107): a tenancy design's `member_roles` must be
/// non-empty (`member_roles[0]` is the admin role — it gates add/re-role/remove
/// and the last-admin rule, and seeds the creator's membership), duplicate-free
/// (the list becomes the generated `MEMBER_ROLES` allow-list and the OpenAPI
/// `role` enum), and identifier-shaped — the same `^[A-Za-z0-9_-]+$` charset
/// JC0543 enforces for enum values, because role names are interpolated
/// UNESCAPED into generated Rust string literals (the `MEMBER_ROLES` const, the
/// membership seed SQL, `require_role("…")` gates), so a quote or backslash
/// emits a crate that fails to compile far from the design. One message per
/// failure mode, naming the offending role.
fn member_roles_conflict(d: &Design) -> Option<DesignConflict> {
    let tenancy = d.tenancy.as_ref()?;
    let roles = &tenancy.member_roles;
    if roles.is_empty() {
        return Some(DesignConflict {
            code: "JC0548",
            message: "tenancy.member_roles is empty — the member-management surface needs at least one declared role: `member_roles[0]` is the admin role (it gates member add/re-role/remove and the last-admin rule), and the tenant creator's membership is seeded with it. Declare the roles a member may hold, admin first (e.g. [\"owner\", \"member\"]). See `jerrycan explain JC0548`.".to_string(),
            hint: "declare tenancy.member_roles, admin role first (e.g. [\"owner\", \"member\"])"
                .to_string(),
        });
    }
    let mut seen = std::collections::HashSet::new();
    for role in roles {
        if !is_enum_value(role) {
            return Some(DesignConflict {
                code: "JC0548",
                message: format!(
                    "tenancy.member_roles entry `{role}` is not an identifier (^[A-Za-z0-9_-]+$) — role names are interpolated unescaped into generated Rust string literals (the MEMBER_ROLES const, the membership seed, `require_role` gates), so a quote or backslash emits a crate that fails to compile; other non-identifier characters are rejected under the same rule. Use identifier-shaped roles (letters, digits, `_`, `-`). See `jerrycan explain JC0548`."
                ),
                hint: format!(
                    "rename role `{role}` to an identifier-shaped name (letters, digits, `_`, `-`)"
                ),
            });
        }
        if !seen.insert(role.as_str()) {
            return Some(DesignConflict {
                code: "JC0548",
                message: format!(
                    "tenancy.member_roles lists `{role}` more than once — the list becomes the generated MEMBER_ROLES allow-list and the OpenAPI `role` enum, and `member_roles[0]` is the admin role, so a duplicate makes the declared role set ambiguous. List each role exactly once. See `jerrycan explain JC0548`."
                ),
                hint: format!("remove the duplicate `{role}` from tenancy.member_roles"),
            });
        }
    }
    None
}

/// The JC0542 check (issue #65): the runtime router keys each path segment
/// position by a SINGLE `{param}` name (see `jerrycan-core` `router::Trie::insert`
/// — one global trie backs the whole app, so this spans every module + subroute).
/// Two routes that reach the same position through an identical static/param
/// prefix but name that position's parameter differently (`/tickets/{id}` vs
/// `/tickets/{ticket_id}/comments`) make `App::build` abort with JC0500
/// `conflicting path parameters` — after a clean scaffold, mid-test.
///
/// This is a structure-only twin of `router::Trie`, mirroring its insert EXACTLY
/// so the validator neither rejects a design the router accepts nor accepts one it
/// panics on: a static segment and a param segment DIVERGE into different children
/// (`/users/me` + `/users/{id}` is fine), two DIFFERENT literals diverge, the SAME
/// param name at a position agrees (`/{id}` + `/{id}/comments` is fine), two
/// DIFFERENT param names at the same node conflict, and a SECOND raw spelling
/// terminating at an occupied node (`/x` + `/x/` — the router drops empty
/// segments, #140) is the trie's `duplicate route registration`. Analyzed over the
/// mount-resolved route table (`genroute::route_map`), so subroute-mount params
/// (which occupy real positions) are included — PLUS the implicit member routes
/// (`genroute::implicit_member_routes`, issue #107), which `App::build` registers
/// for the tenant module but which never enter the design-endpoint table: a
/// tenant-module endpoint with a custom param name (`GET /{slug}`), or one
/// occupying a reserved `/{fk}/members` path, would otherwise pass validation and
/// abort at startup.
fn router_param_conflict(d: &Design) -> Option<DesignConflict> {
    /// A structure-only twin of `router::Node`: static children keyed by literal,
    /// at most ONE param slot carrying its name and the first route to set it,
    /// plus the trie's endpoint-occupancy marker (#140) — the RAW path of the
    /// first route to TERMINATE here. The runtime groups methods by raw path
    /// string (one `.route()` line per spelling), so a second spelling that
    /// collapses to the same node (`/x` vs `/x/` — empty segments are dropped)
    /// is a second `Trie::insert` and aborts with `duplicate route registration`;
    /// the same raw path re-terminating is the SAME line (methods merged), fine.
    #[derive(Default)]
    struct Node {
        statics: std::collections::HashMap<String, Node>,
        param: Option<(String, String, Box<Node>)>,
        route: Option<String>,
    }
    // The router registers routes from the LOAD-normalized design
    // (`normalize_tenant_detail_routes` rewrites the tenant's own `{id}` detail
    // params to `{tenant_fk}` in `Design::from_path` and the MCP merge paths).
    // Every production caller hands this twin a normalized design already;
    // re-normalizing a clone keeps it faithful for direct (test/programmatic)
    // callers too — idempotent, so never wrong — which matters now that the
    // member routes (named `{tenant_fk}` by construction) join the walk.
    let normalized;
    let d = if d.tenancy.is_some() {
        normalized = {
            let mut n = d.clone();
            n.normalize_tenant_detail_routes();
            n
        };
        &normalized
    } else {
        d
    };
    let design_routes = super::genroute::route_map(d);
    let member_routes = super::genroute::implicit_member_routes(d);
    // A design endpoint that OCCUPIES a reserved member path is a second
    // `.route()` registration of the same path — `App::build` aborts with
    // JC0500 `duplicate route registration` (methods don't disambiguate: the
    // member surface registers its own route lines). Compared as SEGMENT
    // vectors, not raw strings (#140): the router drops empty path segments
    // (`router::segments` filters them), so `/{fk}/members/` — the natural
    // hand-rolled spelling, collection routes are trailing-slash by convention
    // — and `//` variants land on the SAME trie node as the reserved pair. A
    // raw-string compare would pass them clean and abort at startup instead.
    // (Param names already agree here — a mismatch is the trie conflict below.)
    fn segs(p: &str) -> Vec<&str> {
        p.split('/').filter(|s| !s.is_empty()).collect()
    }
    if let Some(taken) = member_routes.iter().find(|mr| {
        let reserved = segs(&mr.path);
        design_routes.iter().any(|dr| segs(&dr.path) == reserved)
    }) {
        let tenant = &d
            .tenancy
            .as_ref()
            .expect("member routes imply tenancy")
            .entity;
        let fk = Design::fk_column(tenant);
        let path = &taken.path;
        return Some(DesignConflict {
            code: "JC0542",
            message: format!(
                "route `{path}` collides with the implicit member-management surface generated for the `{tenant}` tenancy (issue #107) — jerrycan reserves `/{{{fk}}}/members` and `/{{{fk}}}/members/{{user_id}}` under the tenant module, and a second registration of the same path aborts `App::build` at startup with JC0500 `duplicate route registration` (after a clean scaffold, mid-test). Move the design endpoint off the reserved path (any static segment other than `members`), or drop it and use the generated member surface. See `jerrycan explain JC0542`."
            ),
            hint: format!(
                "the member-management surface owns `{path}` — move or rename the design endpoint (a static segment other than `members` avoids the reserved pair), or rely on the generated member routes"
            ),
        });
    }
    let mut root = Node::default();
    for entry in design_routes.into_iter().chain(member_routes) {
        let path = entry.path;
        let mut node = &mut root;
        for seg in path.split('/').filter(|s| !s.is_empty()) {
            if let Some(name) = seg.strip_prefix('{').and_then(|s| s.strip_suffix('}')) {
                // Mirror router.rs: ensure the param slot, then compare its name.
                if node.param.is_none() {
                    node.param = Some((name.to_string(), path.clone(), Box::default()));
                }
                let (existing, first_route, child) = node.param.as_mut().expect("just ensured");
                if existing != name {
                    return Some(DesignConflict {
                        code: "JC0542",
                        message: format!(
                            "routes `{first_route}` and `{path}` both take a path parameter at the same position but name it differently (`{{{existing}}}` vs `{{{name}}}`) — the router keys each path position by a single parameter name, so registering both aborts `App::build` at startup with JC0500 `conflicting path parameters` (after a clean scaffold, mid-test). Unify the name (use `{{{existing}}}` in BOTH routes, or `{{{name}}}` in both), or restructure so the position is not shared (mount the diverging routes under distinct static prefixes). See `jerrycan explain JC0542`."
                        ),
                        hint: format!(
                            "give the shared segment ONE parameter name across every sibling route (rename `{{{name}}}`→`{{{existing}}}` or vice versa), or restructure the nesting so the position is not shared"
                        ),
                    });
                }
                node = child;
            } else {
                node = node.statics.entry(seg.to_string()).or_default();
            }
        }
        // Mirror `Trie::insert`'s occupancy branch (#140): a DIFFERENT raw
        // spelling terminating at an occupied node is a second registration.
        if let Some(first_route) = &node.route {
            if first_route != &path {
                return Some(DesignConflict {
                    code: "JC0542",
                    message: format!(
                        "routes `{first_route}` and `{path}` are two spellings of the same route — the router drops empty path segments (a trailing or doubled `/`), so both occupy the same position and the second registration aborts `App::build` at startup with JC0500 `duplicate route registration` (after a clean scaffold, mid-test). Spell the path identically on both endpoints (identical spellings share one registration, each method intact), or move one endpoint to a distinct path. See `jerrycan explain JC0542`."
                    ),
                    hint: format!(
                        "`{first_route}` and `{path}` collapse to the same router position — use ONE spelling for both endpoints, or give one a distinct path"
                    ),
                });
            }
        } else {
            node.route = Some(path);
        }
    }
    None
}

/// The JC0541 check (issue #44): find an entity literally named `{base}Request`
/// whose `{base}` sibling generates a `{base}Request` DTO. Returns the collision, or
/// `None` when no `*Request` entity shadows a generated DTO name.
fn request_dto_name_collision(d: &Design) -> Option<DesignConflict> {
    fn collect<'a>(m: &'a ModuleDesign, out: &mut Vec<&'a str>) {
        out.extend(m.entities.iter().map(|e| e.name.as_str()));
        for sub in &m.subroutes {
            collect(sub, out);
        }
    }
    let mut names = Vec::new();
    for m in &d.modules {
        collect(m, &mut names);
    }
    for name in &names {
        let Some(base) = name.strip_suffix("Request") else {
            continue;
        };
        if base.is_empty() || !names.contains(&base) || !d.entity_generates_request_dto(base) {
            continue;
        }
        return Some(DesignConflict {
            code: "JC0541",
            message: format!(
                "entity `{name}` collides with the request DTO generated for entity `{base}`: a `{base}` request body that omits a server-owned field (an identity fk, a `default`, or a path-redundant parent fk) emits a `{base}Request` type — a Rust struct AND an OpenAPI `{base}Request` component. With an entity also literally named `{name}`, genroute would define `struct {name}` twice (a compile error) and the OpenAPI document would clobber one schema with the other. Rename the entity (e.g. `{base}Payload` or `{base}Submission`) so it no longer shadows the generated DTO. See `jerrycan explain JC0541`."
            ),
            hint: format!(
                "rename `{name}` (e.g. `{base}Payload`/`{base}Submission`) — the `{base}Request` name is reserved for the generated request DTO"
            ),
        });
    }
    None
}

/// The JC0561 name-collision guard (issue #122): an inline-DTO `request_body` mints
/// a `{Pascal(operation_id)}Request` struct in its module's `model` unit AND an
/// OpenAPI `{Pascal(operation_id)}Request` component (openapi.rs `walk_schemas`).
/// That name shares ONE namespace with (a) the `{Entity}Request` /
/// `{Entity}UpdateRequest` DTOs an entity mints when it omits a server-owned field,
/// (b) an entity literally named `{X}Request` (its own model struct + schema), and
/// (c) EVERY OTHER inline body in the design. A same-module clash is an E0428
/// duplicate struct; a cross-module clash silently clobbers one OpenAPI schema with
/// the other, because `components/schemas` is one GLOBAL map while `operation_id` is
/// unique only per-module — so this walk is DESIGN-GLOBAL. Reserves exactly the names
/// genroute/openapi emit (via `to_pascal` + `entity_generates_request_dto` /
/// `entity_generates_update_request_dto`), so a `*Request` name that shadows nothing
/// is never rejected.
fn inline_dto_name_collision(d: &Design) -> Option<DesignConflict> {
    use std::collections::HashMap;
    // 1. Names each entity contributes to the shared struct/schema namespace: its own
    //    model name (always emitted), plus the request DTOs it actually mints.
    let mut reserved: HashMap<String, String> = HashMap::new();
    fn collect_entities(d: &Design, m: &ModuleDesign, reserved: &mut HashMap<String, String>) {
        for e in &m.entities {
            reserved
                .entry(e.name.clone())
                .or_insert_with(|| format!("the model struct for entity `{}`", e.name));
            if d.entity_generates_request_dto(&e.name) {
                reserved
                    .entry(format!("{}Request", e.name))
                    .or_insert_with(|| {
                        format!("the request DTO generated for entity `{}`", e.name)
                    });
            }
            if d.entity_generates_update_request_dto(&e.name) {
                reserved
                    .entry(format!("{}UpdateRequest", e.name))
                    .or_insert_with(|| format!("the update DTO generated for entity `{}`", e.name));
            }
        }
        for sub in &m.subroutes {
            collect_entities(d, sub, reserved);
        }
    }
    for m in &d.modules {
        collect_entities(d, m, &mut reserved);
    }

    // 2. Every inline body, design-global (operation_id is unique per-module only).
    fn collect_inline<'a>(m: &'a ModuleDesign, out: &mut Vec<(&'a str, &'a Endpoint)>) {
        for ep in &m.endpoints {
            if ep.request_body.as_ref().is_some_and(RequestBody::is_inline) {
                out.push((m.name.as_str(), ep));
            }
        }
        for sub in &m.subroutes {
            collect_inline(sub, out);
        }
    }
    let mut inline = Vec::new();
    for m in &d.modules {
        collect_inline(m, &mut inline);
    }

    // 3. Each inline name must clash with neither an entity DTO/model name nor an
    //    EARLIER inline body's name.
    let mut seen_inline: HashMap<String, (&str, &str)> = HashMap::new();
    for (module, ep) in inline {
        let name = format!("{}Request", to_pascal(&ep.operation_id));
        let op = ep.operation_id.as_str();
        if let Some(origin) = reserved.get(&name) {
            return Some(DesignConflict {
                code: "JC0561",
                message: format!(
                    "the inline `request_body` on endpoint `{op}` (module `{module}`) generates a `{name}` request struct and OpenAPI component, but that name is already {origin}. genroute would define `struct {name}` twice — an E0428 duplicate-struct compile error when both land in one module — and the OpenAPI document would clobber one `{name}` schema with the other. Rename the endpoint's `operation_id` so `Pascal(operation_id)Request` no longer collides, or rename the entity. See `jerrycan explain JC0561`."
                ),
                hint: format!(
                    "the `{name}` name is already taken by {origin} — rename endpoint `{op}`'s operation_id (or the entity) so the inline DTO name is unique"
                ),
            });
        }
        if let Some((prev_op, prev_module)) = seen_inline.get(&name) {
            return Some(DesignConflict {
                code: "JC0561",
                message: format!(
                    "two inline `request_body` DTOs generate the same `{name}` struct and OpenAPI component: endpoint `{prev_op}` (module `{prev_module}`) and endpoint `{op}` (module `{module}`). `operation_id` is unique only within a module, but the OpenAPI `components/schemas` map is global — the second `{name}` clobbers the first, so one endpoint's requestBody points at the wrong shape. Rename one operation_id so each inline DTO `Pascal(operation_id)Request` is design-globally unique. See `jerrycan explain JC0561`."
                ),
                hint: format!(
                    "endpoints `{prev_op}` and `{op}` both mint `{name}` — give one a distinct operation_id"
                ),
            });
        }
        seen_inline.insert(name, (op, module));
    }
    None
}

/// Validate a parsed design. Empty result == complete (status: "complete").
pub fn validate(d: &Design) -> Vec<Question> {
    let mut qs = Vec::new();

    if !is_kebab(&d.name) {
        qs.push(q(
            "/name",
            format!(
                "`{}` is not kebab-case (^[a-z][a-z0-9-]*$) — what should the app be called?",
                d.name
            ),
        ));
    }
    if d.contract_version > 2 {
        qs.push(q(
            "/contract_version",
            "contract_version must be 0, 1, or 2 for this platform version.",
        ));
    }
    if d.modules.is_empty() {
        qs.push(q(
            "/modules",
            "No modules defined — what are the resource areas of this backend (each becomes a route crate)?",
        ));
    }
    // A top-level base_path is emitted verbatim into every mount, so it must be a
    // clean absolute path (like a module mount). Empty/`/` is a documented no-op.
    if let Some(base) = &d.base_path
        && !base.is_empty()
        && base != "/"
    {
        if !base.starts_with('/') {
            qs.push(q(
                "/base_path",
                format!("App base_path `{base}` must start with '/'."),
            ));
        }
        if base.contains("//") || base.ends_with('/') {
            qs.push(q(
                "/base_path",
                format!(
                    "App base_path `{base}` must not contain `//` or end with a trailing slash."
                ),
            ));
        }
    }

    // The `cors` block is emitted into `App::cors(CorsConfig::new(..))` (issue #21).
    // Validate the origins at design time so a misconfig is a pointed question, not
    // a runtime `App::build()` failure the deploy discovers on first boot.
    if let Some(cors) = &d.cors {
        if cors.origins.is_empty() {
            qs.push(q(
                "/cors/origins",
                "CORS is declared with no origins — list the allowed origins (exact scheme://host[:port]) or `*` for any origin.",
            ));
        }
        let is_wildcard = cors.origins.iter().any(|o| o == "*");
        if is_wildcard && cors.origins.len() > 1 {
            qs.push(q(
                "/cors/origins",
                "CORS origins mixes `*` with explicit origins — use either `*` (any origin) alone or an explicit allowlist.",
            ));
        }
        // Fetch spec: a credentialed cross-origin request cannot use a wildcard
        // origin. Core's `App::build` rejects the combination; catch it here so the
        // generated app never fails to boot on it.
        if is_wildcard && cors.allow_credentials {
            qs.push(q(
                "/cors/allow_credentials",
                "CORS allow_credentials cannot be combined with `*` origins (the Fetch spec forbids it) — list explicit origins instead.",
            ));
        }
        // Each explicit origin must be a bare origin (scheme://host[:port]) — no path
        // or trailing slash — since it is matched byte-for-byte against the request's
        // Origin header.
        for (i, o) in cors.origins.iter().enumerate() {
            if o == "*" {
                continue;
            }
            let well_formed = (o.starts_with("http://") || o.starts_with("https://"))
                && !o.ends_with('/')
                && o.matches('/').count() == 2;
            if !well_formed {
                qs.push(q(
                    format!("/cors/origins/{i}"),
                    format!("CORS origin `{o}` is not a bare origin — use scheme://host[:port] with no path or trailing slash (e.g. https://app.example)."),
                ));
            }
        }
    }

    let declared_roles: Vec<&str> = d
        .auth
        .as_ref()
        .map(|a| a.roles.iter().map(String::as_str).collect())
        .unwrap_or_default();
    let auth_declared = d.auth.is_some();

    let mut seen_module_names = std::collections::HashSet::new();
    for (i, m) in d.modules.iter().enumerate() {
        if !seen_module_names.insert(m.name.as_str()) {
            qs.push(q(
                format!("/modules/{i}/name"),
                format!(
                    "Module name `{}` is already used — module names must be unique.",
                    m.name
                ),
            ));
        }
        validate_module(
            m,
            &format!("/modules/{i}"),
            &declared_roles,
            auth_declared,
            d.wants_db(),
            &mut qs,
        );
    }

    // Role coherence: a guarded endpoint (auth_required or required_roles) needs
    // an active auth model — `auth.model: none`/absent can't resolve a session.
    if !d.wants_auth() {
        fn check_guards(m: &ModuleDesign, ptr: &str, qs: &mut Vec<Question>) {
            for (i, ep) in m.endpoints.iter().enumerate() {
                if ep.is_guarded() {
                    qs.push(q(
                        format!("{ptr}/endpoints/{i}"),
                        format!(
                            "Endpoint `{}` is guarded (auth_required/required_roles) but the design has no active auth — set auth.model to `session` or `jwt` first.",
                            ep.operation_id
                        ),
                    ));
                }
            }
            for (i, sub) in m.subroutes.iter().enumerate() {
                check_guards(sub, &format!("{ptr}/subroutes/{i}"), qs);
            }
        }
        for (i, m) in d.modules.iter().enumerate() {
            check_guards(m, &format!("/modules/{i}"), &mut qs);
        }
    }

    if d.wants_db() {
        // contract v1 stores json as a real column (Json); v0 has no json columns,
        // so a json field there is still an unsupported request.
        let json_ok = d.contract_version >= 1;
        fn check_db_fields(m: &ModuleDesign, ptr: &str, json_ok: bool, qs: &mut Vec<Question>) {
            for (i, e) in m.entities.iter().enumerate() {
                for (j, f) in e.fields.iter().enumerate() {
                    if !json_ok && matches!(f.field_type, FieldType::Json) {
                        qs.push(q(
                            format!("{ptr}/entities/{i}/fields/{j}/type"),
                            format!("Field `{}` has type json — json fields are not yet supported in db mode (store as string, or drop the db dependency; structured json columns are a contract-v1 candidate).", f.name),
                        ));
                    } else if f.name == "id"
                        && !matches!(
                            f.field_type,
                            FieldType::Integer | FieldType::String | FieldType::Uuid
                        )
                    {
                        // A declared `id` becomes the table's primary key.
                        qs.push(q(
                            format!("{ptr}/entities/{i}/fields/{j}/type"),
                            format!("Field `id` of entity `{}` becomes the table's primary key in db mode — it must be integer, string, or uuid.", e.name),
                        ));
                    }
                }
                // The fk column a belongs_to derives is generated; an explicit field
                // of the same name would collide with the derived column.
                for b in &e.belongs_to {
                    let derived = b.fk_column();
                    if let Some(j) = e.fields.iter().position(|f| f.name == derived) {
                        qs.push(q(
                            format!("{ptr}/entities/{i}/fields/{j}"),
                            format!(
                                "Field `{derived}` collides with the fk column derived from belongs_to `{}` — the fk column is derived from belongs_to; remove the explicit field or the belongs_to.",
                                b.entity
                            ),
                        ));
                    }
                }
            }
            for (i, sub) in m.subroutes.iter().enumerate() {
                check_db_fields(sub, &format!("{ptr}/subroutes/{i}"), json_ok, qs);
            }
        }
        for (i, m) in d.modules.iter().enumerate() {
            check_db_fields(m, &format!("/modules/{i}"), json_ok, &mut qs);
        }
    }

    // Contract v1 constructs: belongs_to targets and enum-value placement.
    // Collect every declared entity name (modules + subroutes) so a belongs_to
    // may target any entity anywhere in the design.
    let mut entity_names = std::collections::HashSet::new();
    fn collect_entity_names<'a>(m: &'a ModuleDesign, out: &mut std::collections::HashSet<&'a str>) {
        for e in &m.entities {
            out.insert(e.name.as_str());
        }
        for sub in &m.subroutes {
            collect_entity_names(sub, out);
        }
    }
    for m in &d.modules {
        collect_entity_names(m, &mut entity_names);
    }

    fn check_relations_and_enums(
        m: &ModuleDesign,
        ptr: &str,
        entity_names: &std::collections::HashSet<&str>,
        wants_db: bool,
        qs: &mut Vec<Question>,
    ) {
        for (i, e) in m.entities.iter().enumerate() {
            for (k, b) in e.belongs_to.iter().enumerate() {
                if !entity_names.contains(b.entity.as_str()) {
                    qs.push(q(
                        format!("{ptr}/entities/{i}/belongs_to/{k}"),
                        format!(
                            "belongs_to target `{}` is not a declared entity anywhere in the design — define it or fix the reference.",
                            b.entity
                        ),
                    ));
                }
            }
            for (j, f) in e.fields.iter().enumerate() {
                check_field_shape(f, &format!("{ptr}/entities/{i}/fields/{j}"), wants_db, qs);
            }
        }
        for (i, sub) in m.subroutes.iter().enumerate() {
            check_relations_and_enums(
                sub,
                &format!("{ptr}/subroutes/{i}"),
                entity_names,
                wants_db,
                qs,
            );
        }
    }
    let wants_db = d.wants_db();
    for (i, m) in d.modules.iter().enumerate() {
        check_relations_and_enums(
            m,
            &format!("/modules/{i}"),
            &entity_names,
            wants_db,
            &mut qs,
        );
    }

    // JC0544 (#60): a body-carrying create/update endpoint whose entity has a
    // path-redundant parent fk (R5's `entity_path_fk_columns`) but whose OWN path
    // lacks the matching `{param}`. The request DTO is per-entity, so the fk is
    // dropped for EVERY create of the entity; on a route that doesn't carry it in
    // the path the NOT-NULL column can be set from neither the body nor the path —
    // the route is un-implementable (the stub even references a `_{col}` binding
    // that doesn't exist). Reuses the R5 resolution — no duplicated fk logic.
    // `prefix` is the accumulated MOUNT of this module's ancestors; combined with the
    // module's own `effective_mount()` (trailing `/` trimmed) it resolves each
    // endpoint's full path — the SAME "resolved path" notion `entity_path_fk_columns`
    // and `endpoint_tenant_shape` use. A fk carried by the MOUNT (`/clubs/{club_id}`,
    // create at `POST /`) is therefore injectable and must NOT be flagged (issue #82),
    // even though `ep.path` alone lacks the param.
    fn check_dual_create_path_fk(
        d: &Design,
        m: &ModuleDesign,
        ptr: &str,
        prefix: &str,
        qs: &mut Vec<Question>,
    ) {
        let mount = m.effective_mount();
        let mount = mount.strip_suffix('/').unwrap_or(&mount);
        let base = format!("{prefix}{mount}");
        for (i, ep) in m.endpoints.iter().enumerate() {
            let Some(rb) = ep.request_body.as_ref() else {
                continue;
            };
            // An inline-DTO body (issue #122) has no entity and thus no parent fk to
            // relocate — the path-fk create check does not apply.
            let Some(entity) = rb.entity.as_deref() else {
                continue;
            };
            if !matches!(
                ep.method,
                HttpMethod::POST | HttpMethod::PUT | HttpMethod::PATCH
            ) {
                continue;
            }
            let resolved = format!("{base}{}", ep.path);
            let token = |col: &str| resolved.contains(&format!("{{{col}}}"));
            if let Some(col) = d
                .entity_path_fk_columns(entity)
                .into_iter()
                .find(|col| !token(col))
            {
                qs.push(q(
                    format!("{ptr}/endpoints/{i}"),
                    format!(
                        "Endpoint `{}` ({:?} {}) creates `{}`, whose parent foreign key `{col}` is supplied by a path parameter on a sibling nested route — so the generated `{}Request` body drops `{col}`, but this route's own path has no `{{{col}}}` to inject it from. The NOT-NULL `{col}` can be set from neither the body nor the path, so the route is un-implementable. Add `{{{col}}}` to this endpoint's path (mount it under the parent), or split `{}` into a separate entity for the standalone create so its request body keeps `{col}`. See `jerrycan explain JC0544`.",
                        ep.operation_id, ep.method, ep.path, entity, entity, entity
                    ),
                ));
            }
        }
        for (i, sub) in m.subroutes.iter().enumerate() {
            check_dual_create_path_fk(d, sub, &format!("{ptr}/subroutes/{i}"), &base, qs);
        }
    }
    for (i, m) in d.modules.iter().enumerate() {
        check_dual_create_path_fk(d, m, &format!("/modules/{i}"), "", &mut qs);
    }

    // Tenancy: the named entity must resolve, and the Tenant guard needs an
    // authenticated user to scope by.
    if let Some(ref tenancy) = d.tenancy {
        if !entity_names.contains(tenancy.entity.as_str()) {
            qs.push(q(
                "/tenancy/entity",
                format!(
                    "Tenancy entity `{}` is not a declared entity — define it or fix the reference.",
                    tenancy.entity
                ),
            ));
        }
        // The Tenant guard scopes by the authenticated principal, which only an
        // active auth *model* (session/jwt) produces — the bare `auth` dependency
        // stub does not.
        let active_auth_model = d
            .auth
            .as_ref()
            .map(|a| a.model != AuthModel::None)
            .unwrap_or(false);
        if !active_auth_model {
            qs.push(q(
                "/tenancy",
                "Tenancy is declared but the design has no active auth model — the Tenant guard needs an authenticated user; set auth.model to `session` or `jwt` first.",
            ));
        }

        // A `public` endpoint bypasses every guard — including the Tenant guard
        // that scopes a tenant-owned entity to its owner. If such an endpoint's
        // repo entity belongs_to the tenancy root, marking it public would expose
        // one tenant's rows to anyone. Flag the contradiction.
        fn check_public_on_tenant_owned(
            d: &Design,
            m: &ModuleDesign,
            ptr: &str,
            qs: &mut Vec<Question>,
        ) {
            for (i, ep) in m.endpoints.iter().enumerate() {
                // Tenant-owned directly OR transitively (#102): `tenant_path` resolves
                // a grandchild through its parent chain, so a public endpoint on a
                // deeply-owned entity is flagged too — matching the transitive
                // ownership the guard/lint recognize.
                if ep.public
                    && endpoint_repo_entity(m, ep).is_some_and(|name| d.tenant_path(name).is_some())
                {
                    qs.push(q(
                        format!("{ptr}/endpoints/{i}"),
                        "endpoint is public but its entity is tenant-owned — public endpoints bypass the Tenant guard; remove public or move the endpoint off the tenant-owned entity".to_string(),
                    ));
                }
            }
            for (i, sub) in m.subroutes.iter().enumerate() {
                check_public_on_tenant_owned(d, sub, &format!("{ptr}/subroutes/{i}"), qs);
            }
        }
        for (i, m) in d.modules.iter().enumerate() {
            check_public_on_tenant_owned(d, m, &format!("/modules/{i}"), &mut qs);
        }

        // JC0558 (#148): the tenant twin of JC0549(c). In an auth design, an
        // endpoint on the tenant entity OR a tenant-owned entity (directly or
        // transitively) that is neither guarded nor `public` is ANONYMOUS:
        // genroute emits the guard only under `mode.auth && ep.is_guarded()`
        // (genroute.rs:196), so such a handler gets no `Dep<Tenant>` and no
        // `CurrentUser` and any caller can read (or write) any tenant's rows —
        // with a green `jerrycan check`. `check_public_on_tenant_owned` above
        // keys on `ep.public`; the merely unguarded-non-public case was unpoliced
        // (JL0004 covers mutations only; in a childless tenant module JL0006 never
        // scans handlers.rs). Refuse it (correct-by-construction), exempting the
        // signature-authed webhook shape exactly as JL0004 does (it proves itself
        // by signature, not a session).
        //
        // Domain = the tenant ROOT (`name == tenancy.entity`) OR a tenant-owned
        // entity (`tenant_path(name).is_some()`). `tenant_path` deliberately
        // returns None for the tenant itself (design.rs:970 — "the tenant is not
        // tenant-owned"), so the root arm is spelled out explicitly: the issue's
        // headline case ("read any tenant's row by id") is the tenant's OWN
        // unguarded detail route, which `tenant_path` alone would miss.
        //
        // Entity resolution uses the STRICT resolver (`endpoint_repo_entity_strict`
        // — explicit signals only), NOT the lenient `endpoint_repo_entity` the
        // (public-only) mirror uses. WHY (Rule 9): this predicate fires on
        // NON-public endpoints, so it reaches the entity-less custom endpoints the
        // public-only check never touched (e.g. `GET /usage` returning custom JSON
        // in an entity-bearing module, or an entity-less join/leave subroute).
        // The lenient first-entity fallback would tie those to a tenant-owned
        // NEIGHBOR they never read and falsely refuse them; strict returns `None`
        // for an endpoint no explicit signal ties to a repo, so it fires only on a
        // real tenant-scoped read/write — the same strict narrowing JC0549(c) and
        // JC0550 use for exactly this security-sensitive reason.
        if active_auth_model {
            fn check_anonymous_on_tenant_scoped(
                d: &Design,
                tenant: &str,
                m: &ModuleDesign,
                ptr: &str,
                qs: &mut Vec<Question>,
            ) {
                for (i, ep) in m.endpoints.iter().enumerate() {
                    let Some(entity) = endpoint_repo_entity_strict(m, ep) else {
                        continue;
                    };
                    let tenant_scoped = entity == tenant || d.tenant_path(entity).is_some();
                    if tenant_scoped
                        && !ep.public
                        && !ep.is_guarded()
                        && !ep.declares_signature_auth()
                    {
                        qs.push(q(
                            format!("{ptr}/endpoints/{i}"),
                            format!(
                                "Endpoint `{}` ({:?} {}) is on the tenant-scoped entity `{}` but is neither authenticated nor `public` — it emits no `Dep<Tenant>` guard and no `CurrentUser`, so an anonymous caller could read or write any tenant's rows. Set `auth_required: true` so the membership guard scopes it. See `jerrycan explain JC0558`.",
                                ep.operation_id, ep.method, ep.path, entity,
                            ),
                        ));
                    }
                }
                for (i, sub) in m.subroutes.iter().enumerate() {
                    check_anonymous_on_tenant_scoped(
                        d,
                        tenant,
                        sub,
                        &format!("{ptr}/subroutes/{i}"),
                        qs,
                    );
                }
            }
            for (i, m) in d.modules.iter().enumerate() {
                check_anonymous_on_tenant_scoped(
                    d,
                    &tenancy.entity,
                    m,
                    &format!("/modules/{i}"),
                    &mut qs,
                );
            }
        }

        // JC0545 (#102): an entity that reaches the tenant through TWO or more
        // distinct `belongs_to` chains (a diamond) is ambiguous — `tenant_path`
        // resolves it to `None`, which would leave it UNSCOPED and re-open the
        // cross-tenant leak. Generation is gated on validation, so rejecting the
        // design here keeps a half-scoped entity from ever reaching the generator.
        fn check_ambiguous_tenant_path(
            d: &Design,
            m: &ModuleDesign,
            ptr: &str,
            qs: &mut Vec<Question>,
        ) {
            for (i, e) in m.entities.iter().enumerate() {
                if d.tenant_path_branch_count(&e.name) >= 2 {
                    qs.push(q(
                        format!("{ptr}/entities/{i}"),
                        format!(
                            "Entity `{}` reaches the tenant through more than one `belongs_to` path (a diamond graph), so jerrycan cannot decide which chain defines tenant ownership — guessing would scope its reads/writes to the wrong tenant and re-open the cross-tenant leak. Collapse its tenant ownership to a SINGLE `belongs_to` path (drop the redundant parent, or split the entity), so exactly one chain reaches the tenant. See `jerrycan explain JC0545`.",
                            e.name
                        ),
                    ));
                }
            }
            for (i, sub) in m.subroutes.iter().enumerate() {
                check_ambiguous_tenant_path(d, sub, &format!("{ptr}/subroutes/{i}"), qs);
            }
        }
        for (i, m) in d.modules.iter().enumerate() {
            check_ambiguous_tenant_path(d, m, &format!("/modules/{i}"), &mut qs);
        }

        // JC0562 (#175): a tenant-owned entity reachable by BOTH a flat
        // (membership-set, body-fk) route AND a path-scoped (`/{fk}/…`) route is
        // MIXED-shape. The generator emits only ONE scoping shape per entity —
        // `genroute::entity_is_flat_tenant_owned` is `!saw_path && saw_flat`, so a
        // mixed entity is classified NON-flat and its `*_for_memberships` accessors
        // are withheld, yet the flat-write steer still fires: following the generated
        // comment would call a method that isn't emitted (`method not found` behind a
        // green `check`, the #116 class). No corpus design is mixed today; refuse it
        // so the broken shape can't ship. The tenant-owned guard mirrors
        // `entity_is_flat_tenant_owned`'s domain; `entity_tenant_shapes` is the SAME
        // whole-design scan, so this refusal and that classifier can't drift.
        fn check_mixed_tenant_shape(
            d: &Design,
            m: &ModuleDesign,
            ptr: &str,
            qs: &mut Vec<Question>,
        ) {
            for (i, e) in m.entities.iter().enumerate() {
                if d.tenant_path(&e.name).is_none() {
                    continue;
                }
                let (saw_path, saw_flat) = d.entity_tenant_shapes(e);
                if saw_path && saw_flat {
                    qs.push(q(
                        format!("{ptr}/entities/{i}"),
                        format!(
                            "Entity `{}` mixes a flat (body-fk) write and a path-scoped route — the generator can emit only one scoping shape, so following the generated steer would call a `*_for_memberships` method that isn't emitted. Give `{}` a single shape: make every route path-scoped (`/{{fk}}/…`), or every route flat. See `jerrycan explain JC0562`.",
                            e.name, e.name
                        ),
                    ));
                }
            }
            for (i, sub) in m.subroutes.iter().enumerate() {
                check_mixed_tenant_shape(d, sub, &format!("{ptr}/subroutes/{i}"), qs);
            }
        }
        for (i, m) in d.modules.iter().enumerate() {
            check_mixed_tenant_shape(d, m, &format!("/modules/{i}"), &mut qs);
        }

        // JC0553 (#141): with tenancy, jerrycan reserves the `{tenant}_members`
        // membership table and the `pub struct {Tenant}Member` row type (issue
        // #107) for the generated member surface. An entity (other than the
        // tenant) whose RESOLVED table name equals `{tenant}_members` — one named
        // `{Tenant}Member`, whose default table is exactly that, or one with an
        // explicit `table` override onto it — OR whose NAME equals `{Tenant}Member`
        // collides with that surface: the generator would emit the same table
        // twice (a raw `table "..._members" already exists` mid-scaffold, after a
        // clean `check`) or two `struct {Tenant}Member` definitions. Reserved
        // names are computed EXACTLY as the generator names them
        // (`{Design::to_snake(tenant)}_members`, `{tenant}Member`) so the refusal
        // matches what is reserved. Fail loud here with a rename suggestion.
        let reserved_members_table = format!("{}_members", Design::to_snake(&tenancy.entity));
        let reserved_member_struct = format!("{}Member", tenancy.entity);
        fn check_membership_collision(
            d: &Design,
            tenant: &str,
            reserved_table: &str,
            reserved_struct: &str,
            m: &ModuleDesign,
            ptr: &str,
            qs: &mut Vec<Question>,
        ) {
            for (i, e) in m.entities.iter().enumerate() {
                if e.name == tenant {
                    continue;
                }
                let name_collides = e.name == reserved_struct;
                let table_collides = d.table_name(&e.name) == reserved_table;
                if !name_collides && !table_collides {
                    continue;
                }
                // Point at the most actionable location: the name for a name (or
                // name+table) collision — renaming fixes both — else the entity.
                let (id, detail) = if name_collides {
                    (
                        format!("{ptr}/entities/{i}/name"),
                        if table_collides {
                            format!(
                                "its name matches the generated membership row type `pub struct {reserved_struct}` (issue #107), and its default table `{reserved_table}` is the membership table jerrycan generates for `{tenant}`"
                            )
                        } else {
                            format!(
                                "its name matches the generated membership row type `pub struct {reserved_struct}` (issue #107)"
                            )
                        },
                    )
                } else {
                    (
                        format!("{ptr}/entities/{i}"),
                        format!(
                            "its table `{reserved_table}` is the membership table jerrycan generates for `{tenant}`"
                        ),
                    )
                };
                qs.push(q(
                    id,
                    format!(
                        "Entity `{}` collides with the member surface jerrycan generates for tenant `{tenant}`: {detail} — the generator would emit that table/type twice and the scaffold would abort mid-migration with a raw `table \"{reserved_table}\" already exists` (after a clean `check`). Rename the entity (e.g. `{}Record` or a domain-specific name) so it no longer equals the reserved `{reserved_struct}` type or resolves to the reserved `{reserved_table}` table. See `jerrycan explain JC0553`.",
                        e.name, e.name
                    ),
                ));
            }
            for (i, sub) in m.subroutes.iter().enumerate() {
                check_membership_collision(
                    d,
                    tenant,
                    reserved_table,
                    reserved_struct,
                    sub,
                    &format!("{ptr}/subroutes/{i}"),
                    qs,
                );
            }
        }
        for (i, m) in d.modules.iter().enumerate() {
            check_membership_collision(
                d,
                &tenancy.entity,
                &reserved_members_table,
                &reserved_member_struct,
                m,
                &format!("/modules/{i}"),
                &mut qs,
            );
        }
    }

    // JC0550 (#88): the tenant entity's OWN detail route must address the tenant
    // by its pk fk. The load normalization rewrites only the literal `{id}`
    // (→ `{fk}`), so a route addressed by any OTHER param (`/{slug}`,
    // `/by-slug/{slug}`) survives it — and the membership guard, which verifies
    // the tenant NAMED BY THE PATH FK, cannot bind it: the handler would be
    // generated with a bare `CurrentUser` and NO membership check at all,
    // silently. Renaming the param is NOT a fix — the guard parses the path
    // value as the tenant PK type, so a slug would be reinterpreted as a pk —
    // hence a loud refusal (the JC0549 pattern: a latent unimplementable shape
    // becomes a clear fork). Checked over a normalized clone (the
    // `router_param_conflict` precedent): production callers hand `validate()` a
    // load-normalized design already, and re-normalizing is idempotent, so the
    // conventional `/{id}` passes for direct (test/programmatic) callers too.
    //
    // Two resolution rules keep the refusal honest (this check is
    // SECURITY-SENSITIVE, so it follows the JC0549(c) precedent):
    //   - The target entity is resolved with design.rs's STRICT resolver
    //     (`super::design::endpoint_repo_entity_strict` — qualified, because the
    //     module-local lenient `endpoint_repo_entity` above shadows the design.rs
    //     glob and LACKS the collection-creator arm). The local resolver both
    //     OVER-fires — a sibling's bodyless `DELETE /siblings/{id}` in the tenant
    //     module falls back to the first entity (the tenant) and is refused while
    //     the refusal's own message says to use `/{id}` — and UNDER-fires: a
    //     NON-FIRST tenant's bodyless `DELETE /{slug}` falls back to the first
    //     entity (a sibling) and the real no-membership-check hole ships
    //     question-free. Strict resolves the creator arm (the non-first tenant
    //     fires), returns the sibling's own entity (siblings never fire), and
    //     returns `None` for an entity-less custom endpoint (`GET
    //     /export/{format}` never fires). Accepted residual: a creator-less
    //     bodyless tenant detail route with a non-pk param in a single-entity
    //     module resolves to NO entity and is not caught — that shape carries no
    //     signal to resolve its entity (the #143 family).
    //   - The route is a hole only when the tenant fk appears in NONE of its
    //     path params — checked against the MOUNT-RESOLVED path (the node's
    //     `effective_mount()` + `ep.path`, exactly as `endpoint_tenant_shape`
    //     resolves it): a multi-param `/{fk}/{sub}` binds the fk, and so does a
    //     mount-carried fk (subroute mount `/{fk}/history`, path `/{year}`) —
    //     the guard membership-checks the full route either way — so only a
    //     route whose resolved path never names the fk fires.
    if let Some(tenancy) = &d.tenancy {
        let fk = Design::fk_column(&tenancy.entity);
        let normalized = {
            let mut n = d.clone();
            n.normalize_tenant_detail_routes();
            n
        };
        // The trailing path param — the one that addresses the detail row.
        fn trailing_path_param(path: &str) -> Option<&str> {
            let rest = &path[path.rfind('{')? + 1..];
            rest.find('}').map(|end| &rest[..end])
        }
        fn check_tenant_detail_param(
            tenant: &str,
            fk: &str,
            m: &ModuleDesign,
            ptr: &str,
            qs: &mut Vec<Question>,
        ) {
            let fk_token = format!("{{{fk}}}");
            let mount = m.effective_mount();
            let mount = mount.strip_suffix('/').unwrap_or(&mount);
            for (i, ep) in m.endpoints.iter().enumerate() {
                if super::design::endpoint_repo_entity_strict(m, ep) != Some(tenant) {
                    continue;
                }
                let Some(param) = trailing_path_param(&ep.path) else {
                    continue;
                };
                if !format!("{mount}{}", ep.path).contains(&fk_token) {
                    qs.push(q(
                        format!("{ptr}/endpoints/{i}"),
                        format!(
                            "Endpoint `{}` ({:?} {}) is the tenant `{}`'s own detail route but addresses it by `{{{}}}`, not its pk `{{{}}}` — the membership guard verifies the tenant named by the path fk, so a non-pk param (e.g. a slug) cannot be membership-checked and the route would run with no membership check at all. Use `/{{id}}` (auto-normalized to `/{{{}}}`) or `/{{{}}}` directly; slug-based tenant addressing is not yet supported. See `jerrycan explain JC0550`.",
                            ep.operation_id, ep.method, ep.path, tenant, param, fk, fk, fk
                        ),
                    ));
                }
            }
            for (i, sub) in m.subroutes.iter().enumerate() {
                check_tenant_detail_param(tenant, fk, sub, &format!("{ptr}/subroutes/{i}"), qs);
            }
        }
        for (i, m) in normalized.modules.iter().enumerate() {
            check_tenant_detail_param(&tenancy.entity, &fk, m, &format!("/modules/{i}"), &mut qs);
        }
    }

    // JC0549 (#105): the public-read/owner-write shape. `public_read` is a
    // modifier on the per-user ownership shape (#79) — reads public, writes
    // owner-scoped — so (a) it is valid ONLY on an identity-owned, non-tenant
    // entity in an auth design, and (b) every WRITE of a public_read entity must
    // stay owner-gated (a public/unguarded write is the open door: anyone could
    // create/mutate rows the public then reads). Independently of opt-in, (c)
    // closes the latent unguarded-per-user-GET bug: in db+auth mode a per-user
    // entity's repo emits ONLY the owner-scoped accessors and an unguarded
    // handler receives no session user, so an unguarded GET that has NOT opted
    // into public_read is unimplementable — refuse it with a clear fork instead
    // of generating a dead-end stub.
    fn check_public_read(d: &Design, m: &ModuleDesign, ptr: &str, qs: &mut Vec<Question>) {
        for (i, e) in m.entities.iter().enumerate() {
            if !e.public_read {
                continue;
            }
            if !d.wants_auth() {
                qs.push(q(
                    format!("{ptr}/entities/{i}"),
                    format!(
                        "Entity `{}` declares public_read but the design has no active auth model — public_read keeps WRITES owner-gated, which needs an authenticated session; set auth.model to `session` or `jwt`, or drop public_read. See `jerrycan explain JC0549`.",
                        e.name
                    ),
                ));
            }
            if !d.has_identity_fk(e) {
                qs.push(q(
                    format!("{ptr}/entities/{i}"),
                    format!(
                        "Entity `{}` declares public_read but carries no identity fk — public_read is a modifier on the per-user ownership shape (reads public, writes owner-scoped), so the entity needs a `belongs_to` the auth identity entity; add it, or drop public_read. See `jerrycan explain JC0549`.",
                        e.name
                    ),
                ));
            }
            // Tenant-owned directly OR transitively (#102) — mirrors the
            // public-endpoint-on-tenant-owned rejection above: a public read
            // would bypass the Tenant guard and expose one tenant's rows to
            // anyone. public_read is identity-owned-only in v1.
            if d.tenant_path(&e.name).is_some() {
                qs.push(q(
                    format!("{ptr}/entities/{i}"),
                    format!(
                        "Entity `{}` declares public_read but is tenant-owned — public reads would bypass the Tenant guard and expose one tenant's rows to anyone; public_read is identity-owned-only, so remove public_read or move the entity off tenancy. See `jerrycan explain JC0549`.",
                        e.name
                    ),
                ));
            }
        }
        for (i, ep) in m.endpoints.iter().enumerate() {
            if matches!(ep.method, HttpMethod::GET) {
                // (c) The latent-bug closure. Resolved via the STRICT resolver
                // (`design::endpoint_repo_entity_strict` — explicit signals
                // only): an ENTITY-LESS GET (custom-JSON success, no body, no
                // `{param}` collection — the documented hand-written
                // `Json<serde_json::Value>` shape) reads NO entity's repo, so
                // the first-entity fallback must not tie it to a per-user
                // neighbor and falsely refuse an implementable `public: true`
                // custom GET as unimplementable. Per-user ownership IS
                // `Design::entity_is_per_user_owned` — the one shared classifier
                // (#105 §F); db mode is the extra gate because only `sql_repo`
                // suppresses the unscoped reads (a memory repo keeps plain
                // `all`/`get`, so the stub stays implementable there). `public:
                // true` is NOT a carve-out: it is just the second spelling of an
                // unguarded read (public cannot combine with a guard), and the
                // stub it generates is exactly as unimplementable — only the
                // `public_read` entity flag makes an open read coherent here.
                let Some(name) = endpoint_repo_entity_strict(m, ep) else {
                    continue;
                };
                let Some(e) = m.entities.iter().find(|e| e.name == name) else {
                    continue;
                };
                let per_user_owned = d.entity_is_per_user_owned(e);
                if !ep.is_guarded()
                    && d.wants_db()
                    && per_user_owned
                    && !d.entity_is_public_read(&e.name)
                {
                    qs.push(q(
                        format!("{ptr}/endpoints/{i}"),
                        format!(
                            "Endpoint `{}` is an unguarded read on the owner-scoped entity `{}`, which is unimplementable — the entity's repo emits only the owner-scoped accessors and an unguarded handler receives no session user. Set `public_read: true` on `{}` to make its reads public, or keep the GET authenticated (`auth_required: true`). See `jerrycan explain JC0549`.",
                            ep.operation_id, e.name, e.name
                        ),
                    ));
                }
            } else if ep.public || !ep.is_guarded() {
                // (b) A write must stay owner-gated regardless of the flag.
                // Resolve BOTH the LENIENT repo-binding entity (first-entity
                // fallback — the repo the generated stub actually binds) AND the
                // STRICT #56-collection-creator entity (no fallback), and refuse a
                // public/unguarded write when EITHER lands on a public_read entity.
                // The lenient leg preserves the existing over-match (fail-CLOSED);
                // the strict leg catches the UNDER-match — a bodyless `DELETE /{id}`
                // whose public_read entity is NOT the module's first entity, which
                // the lenient fallback mis-attributes to the first (non-public_read)
                // entity so JC0549(b) never fired (#143). Prefer the lenient name
                // when it is itself public_read so first-entity designs stay
                // byte-identical; the `find_map` dedupes to one question per endpoint.
                if let Some(e) = [
                    endpoint_repo_entity(m, ep),
                    endpoint_repo_entity_strict(m, ep),
                ]
                .into_iter()
                .flatten()
                .find_map(|name| m.entities.iter().find(|e| e.name == name && e.public_read))
                {
                    qs.push(q(
                        format!("{ptr}/endpoints/{i}"),
                        format!(
                            "Endpoint `{}` ({:?} {}) is a write on the public_read entity `{}` but is public/unguarded — public_read makes READS public while WRITES stay owner-gated; set `auth_required: true` (and drop `public`) on every write of `{}`. See `jerrycan explain JC0549`.",
                            ep.operation_id, ep.method, ep.path, e.name, e.name
                        ),
                    ));
                }
            }
        }
        for (i, sub) in m.subroutes.iter().enumerate() {
            check_public_read(d, sub, &format!("{ptr}/subroutes/{i}"), qs);
        }
    }
    for (i, m) in d.modules.iter().enumerate() {
        check_public_read(d, m, &format!("/modules/{i}"), &mut qs);
    }

    // JC0559 (#115): a table-level composite `unique` group must be BUILDABLE — the
    // generator emits one `CREATE UNIQUE INDEX (col, …)` per group (genroute), so a
    // group is refused when it: has fewer than 2 columns (a single-column unique must
    // use `Field.unique`, not a 1-col group); names a column that is neither a
    // declared field nor a `belongs_to` fk column of the entity (the index would
    // reference a non-existent column and fail at migration apply); or duplicates
    // another group's column set (order-insensitive — redundant). Applies to every
    // design (no tenancy/auth prerequisite); an entity with an empty `unique` is inert
    // (byte-identity baseline).
    fn check_composite_unique(m: &ModuleDesign, ptr: &str, qs: &mut Vec<Question>) {
        for (i, e) in m.entities.iter().enumerate() {
            if e.unique.is_empty() {
                continue;
            }
            // Valid columns: declared fields ∪ belongs_to fk columns.
            let mut valid: std::collections::HashSet<String> =
                e.fields.iter().map(|f| f.name.clone()).collect();
            for b in &e.belongs_to {
                valid.insert(b.fk_column());
            }
            let mut seen_sets: Vec<std::collections::BTreeSet<String>> = Vec::new();
            for (g, group) in e.unique.iter().enumerate() {
                let gptr = format!("{ptr}/entities/{i}/unique/{g}");
                // Gate on the count of DISTINCT columns, not raw length: a repeated
                // column like `["a", "a"]` has 2 entries but 1 distinct column, so
                // `UNIQUE(a, a)` would silently make column `a` globally unique —
                // caught here alongside the true <2 case.
                let distinct: std::collections::BTreeSet<&String> = group.iter().collect();
                if distinct.len() < 2 {
                    qs.push(q(
                        gptr.clone(),
                        format!(
                            "Entity `{}` composite `unique` group #{g} has fewer than 2 DISTINCT columns ({group:?}) — a table-level composite UNIQUE expresses a `UNIQUE(a, b)` invariant a single field cannot, and a repeated column (`[\"a\", \"a\"]`) would silently make that lone column globally unique. For single-column uniqueness set `unique: true` on the field instead; a composite group needs at least 2 distinct columns. See `jerrycan explain JC0559`.",
                            e.name
                        ),
                    ));
                }
                for col in group {
                    if !valid.contains(col) {
                        qs.push(q(
                            gptr.clone(),
                            format!(
                                "Entity `{}` composite `unique` group #{g} names column `{col}`, which is neither a declared field nor a `belongs_to` fk column of `{}` — the generated `CREATE UNIQUE INDEX` would reference a column that does not exist and fail at migration apply. Use a declared field name or a belongs_to fk column (`snake_case(entity) + \"_id\"`). See `jerrycan explain JC0559`.",
                                e.name, e.name
                            ),
                        ));
                    }
                }
                let set: std::collections::BTreeSet<String> = group.iter().cloned().collect();
                if seen_sets.contains(&set) {
                    qs.push(q(
                        gptr,
                        format!(
                            "Entity `{}` composite `unique` group #{g} ({group:?}) duplicates an earlier group with the same column set (order does not matter) — a redundant index. List each column set once. See `jerrycan explain JC0559`.",
                            e.name
                        ),
                    ));
                } else {
                    seen_sets.push(set);
                }
            }
        }
        for (i, sub) in m.subroutes.iter().enumerate() {
            check_composite_unique(sub, &format!("{ptr}/subroutes/{i}"), qs);
        }
    }
    for (i, m) in d.modules.iter().enumerate() {
        check_composite_unique(m, &format!("/modules/{i}"), &mut qs);
    }

    // JC0564 (#187): a field's `reserve_against` wires the generated atomic
    // `{Entity}Repo::reserve(id, n)` method (the #108-proven conditional UPDATE), so it
    // must name a DISTINCT sibling integer *capacity* field and itself be an integer
    // *counter* — neither the pk `id`. Refuse a non-existent capacity, a non-integer
    // counter or capacity, the pk on either leg, a self-reference, more than one
    // `reserve_against` per entity (the `reserve` name must be unambiguous), or a
    // memory-only design (the atomic UPDATE is emitted on the SQL repo only). Inert for
    // every entity without `reserve_against` (byte-identity baseline).
    fn check_reserve_against(d: &Design, m: &ModuleDesign, ptr: &str, qs: &mut Vec<Question>) {
        for (i, e) in m.entities.iter().enumerate() {
            let reservers: Vec<(usize, &Field)> = e
                .fields
                .iter()
                .enumerate()
                .filter(|(_, f)| f.reserve_against.is_some())
                .collect();
            if reservers.is_empty() {
                continue;
            }
            // (6) at most one `reserve_against` per entity — else the generated `reserve`
            // method name would collide.
            if reservers.len() > 1 {
                let names = reservers
                    .iter()
                    .map(|(_, f)| f.name.as_str())
                    .collect::<Vec<_>>()
                    .join(", ");
                qs.push(q(
                    format!("{ptr}/entities/{i}"),
                    format!(
                        "Entity `{}` declares `reserve_against` on {} fields ({names}) — at most one reserve counter per entity is allowed so the generated `reserve` method name stays unambiguous. Keep `reserve_against` on a single counter field. See `jerrycan explain JC0564`.",
                        e.name,
                        reservers.len(),
                    ),
                ));
            }
            for (fi, f) in &reservers {
                let cap = f.reserve_against.as_deref().unwrap_or_default();
                let fptr = format!("{ptr}/entities/{i}/fields/{fi}");
                // (7) memory-only design — the conditional UPDATE lives on the SQL repo.
                if !d.wants_db() {
                    qs.push(q(
                        fptr.clone(),
                        format!(
                            "Entity `{}` field `{}` declares `reserve_against` but the design has no database — the atomic `reserve` method is generated on the SQL-backed repo only (a memory repo cannot run the conditional UPDATE). Add `db` to `dependencies`, or drop `reserve_against`. See `jerrycan explain JC0564`.",
                            e.name, f.name
                        ),
                    ));
                }
                // (2) the counter field must be integer.
                if f.field_type != FieldType::Integer {
                    qs.push(q(
                        fptr.clone(),
                        format!(
                            "Entity `{}` field `{}` declares `reserve_against` but is `{:?}`, not `integer` — the reserve counter is incremented by an integer amount, so it must be an integer column. Make `{}` integer, or drop `reserve_against`. See `jerrycan explain JC0564`.",
                            e.name, f.name, f.field_type, f.name
                        ),
                    ));
                }
                // (8) the counter must be NOT NULL. A nullable (`required: false`)
                // counter is NULL on insert, so the atomic guard `used + n <= capacity`
                // evaluates to NULL (never true) and `reserve` returns `Ok(false)`
                // FOREVER — silently dead. Require it, ideally with `"default": 0`.
                if !f.required {
                    qs.push(q(
                        fptr.clone(),
                        format!(
                            "Entity `{}` field `{}` declares `reserve_against` but is nullable (`required: false`) — a NULL counter makes the atomic guard `{} + n <= {}` NULL, so `reserve` returns `Ok(false)` forever (it can never reserve). Make `{}` `required: true` (add `\"default\": 0` for a server-owned counter starting at 0). See `jerrycan explain JC0564`.",
                            e.name, f.name, f.name, cap, f.name
                        ),
                    ));
                }
                // (4a) the counter field must not be the pk `id`.
                if f.name == "id" {
                    qs.push(q(
                        fptr.clone(),
                        format!(
                            "Entity `{}` field `id` declares `reserve_against` — the reserve counter cannot be the primary key `id` (server-assigned and identifying the row, not a mutable amount). Move `reserve_against` to a dedicated integer counter field. See `jerrycan explain JC0564`.",
                            e.name
                        ),
                    ));
                }
                // (5) a field cannot reserve against itself.
                if cap == f.name {
                    qs.push(q(
                        fptr.clone(),
                        format!(
                            "Entity `{}` field `{}` declares `reserve_against: \"{}\"` — a field cannot reserve against itself; name the SEPARATE integer capacity ceiling. See `jerrycan explain JC0564`.",
                            e.name, f.name, cap
                        ),
                    ));
                    // A self-reference resolves to this same field, so the capacity
                    // checks below (existence/integer/pk) would only re-report it — skip.
                    continue;
                }
                // (4b) the capacity leg must not be the pk `id`.
                if cap == "id" {
                    qs.push(q(
                        fptr.clone(),
                        format!(
                            "Entity `{}` field `{}` declares `reserve_against: \"id\"` — the capacity ceiling cannot be the primary key `id`. Name a dedicated integer capacity field. See `jerrycan explain JC0564`.",
                            e.name, f.name
                        ),
                    ));
                    continue;
                }
                // (1) the named capacity field must exist on the same entity.
                let Some(capf) = e.fields.iter().find(|g| g.name == cap) else {
                    qs.push(q(
                        fptr.clone(),
                        format!(
                            "Entity `{}` field `{}` declares `reserve_against: \"{}\"`, but `{}` is not a field of `{}` — name the sibling integer capacity field the counter is bounded by. See `jerrycan explain JC0564`.",
                            e.name, f.name, cap, cap, e.name
                        ),
                    ));
                    continue;
                };
                // (3) the capacity field must be integer.
                if capf.field_type != FieldType::Integer {
                    qs.push(q(
                        fptr.clone(),
                        format!(
                            "Entity `{}` field `{}` reserves against `{}`, which is `{:?}`, not `integer` — the capacity ceiling must be an integer column. Make `{}` integer, or point `reserve_against` at an integer field. See `jerrycan explain JC0564`.",
                            e.name, f.name, cap, capf.field_type, cap
                        ),
                    ));
                }
                // (9) the capacity field must be NOT NULL. A nullable capacity is NULL
                // on insert, so the guard `used + n <= capacity` is NULL and `reserve`
                // returns `Ok(false)` forever — the same silent-dead failure as (8).
                if !capf.required {
                    qs.push(q(
                        fptr.clone(),
                        format!(
                            "Entity `{}` field `{}` reserves against `{}`, which is nullable (`required: false`) — a NULL capacity makes the atomic guard `{} + n <= {}` NULL, so `reserve` returns `Ok(false)` forever (it can never reserve). Make `{}` `required: true`. See `jerrycan explain JC0564`.",
                            e.name, f.name, cap, f.name, cap, cap
                        ),
                    ));
                }
            }
        }
        for (i, sub) in m.subroutes.iter().enumerate() {
            check_reserve_against(d, sub, &format!("{ptr}/subroutes/{i}"), qs);
        }
    }
    for (i, m) in d.modules.iter().enumerate() {
        check_reserve_against(d, m, &format!("/modules/{i}"), &mut qs);
    }

    // JC0560 (#119): a `belongs_to` fk column must be BUILDABLE and DISTINCT. The
    // fk column a belongs_to derives (`{as}_id` when aliased, else
    // `snake(entity)_id`) becomes a Model field AND a migration column, so per
    // entity: (1) every `as` must be snake_case (a malformed alias yields an
    // invalid column/Rust field); (2) no two belongs_to may derive the SAME fk
    // column — two un-aliased refs to one target both derive `snake(entity)_id`,
    // or an `as` collides with another belongs_to's fk — which would emit a
    // duplicate Model field and a duplicate migration column; (3) an fk column
    // must not collide with a declared field name or the pk `id`. The alias exists
    // precisely so two references to one entity (a ledger Transfer's
    // from_account/to_account, a self-referential Comment's parent) get DISTINCT
    // columns and distinct DDL constraint names. An entity with 0/1 un-aliased
    // belongs_to and no `as` is inert (byte-identity baseline).
    fn check_belongs_to_aliases(d: &Design, m: &ModuleDesign, ptr: &str, qs: &mut Vec<Question>) {
        // #119 Finding 1: an `as` alias must not land on a RESERVED fk column that
        // the target doesn't own — the identity fk `user_id` (in an auth design) or
        // the tenancy fk — else the alias hijacks identity/tenant scoping and the
        // generated Rust fails opaquely instead of a clean design-time refusal.
        let auth_active = d
            .auth
            .as_ref()
            .map(|a| a.model != AuthModel::None)
            .unwrap_or(false);
        let tenant_fk = d
            .tenancy
            .as_ref()
            .map(|t| (Design::fk_column(&t.entity), t.entity.clone()));
        for (i, e) in m.entities.iter().enumerate() {
            let field_names: std::collections::HashSet<&str> =
                e.fields.iter().map(|f| f.name.as_str()).collect();
            let mut seen: std::collections::HashMap<String, usize> =
                std::collections::HashMap::new();
            for (bi, b) in e.belongs_to.iter().enumerate() {
                let bptr = format!("{ptr}/entities/{i}/belongs_to/{bi}");
                // (1) A malformed alias yields a nonsense `{as}_id` column — refuse
                // it here and skip the collision checks (they'd be noise on garbage).
                if let Some(a) = &b.r#as
                    && !is_snake(a)
                {
                    qs.push(q(
                        bptr,
                        format!(
                            "Entity `{}` belongs_to `{}` has a malformed `as` alias `{a}` — an alias must be snake_case (^[a-z][a-z0-9_]*$); the fk column is derived as `{{as}}_id`. See `jerrycan explain JC0560`.",
                            e.name, b.entity
                        ),
                    ));
                    continue;
                }
                let col = b.fk_column();
                // (4) #119 Finding 1: reject an alias that lands on a reserved fk the
                // target doesn't own — hijacking identity/tenant scoping. The identity
                // fk is DESIGN-AWARE (#150): `snake(auth.identity)_id` (default
                // `user_id`), so an alias that hijacks a non-`User` identity's fk is
                // refused too.
                let identity_fk = d.identity_fk_column();
                if auth_active && col == identity_fk && Design::fk_column(&b.entity) != identity_fk
                {
                    qs.push(q(
                        bptr.clone(),
                        format!(
                            "Entity `{}` belongs_to `{}` with `as` deriving fk column `{col}` — that is the reserved identity fk (the authenticated user's column); only `belongs_to` the identity entity may own `{identity_fk}`. Choose a different `as` alias. See `jerrycan explain JC0560`.",
                            e.name, b.entity
                        ),
                    ));
                }
                if let Some((tfk, tent)) = &tenant_fk
                    && col == *tfk
                    && b.entity != *tent
                {
                    qs.push(q(
                        bptr.clone(),
                        format!(
                            "Entity `{}` belongs_to `{}` with `as` deriving fk column `{col}` — that is the reserved tenancy fk for `{tent}`; aliasing the tenant fk breaks tenant scoping. Choose a different `as` alias. See `jerrycan explain JC0560`.",
                            e.name, b.entity
                        ),
                    ));
                }
                // (3) The fk column is generated; a same-named declared field or the
                // pk `id` would be a duplicate column.
                if col == "id" || field_names.contains(col.as_str()) {
                    let against = if col == "id" {
                        "the pk `id`".to_string()
                    } else {
                        format!("a declared field `{col}`")
                    };
                    qs.push(q(
                        bptr.clone(),
                        format!(
                            "Entity `{}` belongs_to `{}` derives fk column `{col}`, which collides with {against} — the fk column is generated, so it must not duplicate a declared field or the pk `id`. Rename the field or give the belongs_to a distinct `as`. See `jerrycan explain JC0560`.",
                            e.name, b.entity
                        ),
                    ));
                }
                // (2) Two belongs_to deriving the same fk column → duplicate column.
                if let Some(&first) = seen.get(&col) {
                    qs.push(q(
                        bptr,
                        format!(
                            "Entity `{}` belongs_to `{}` derives fk column `{col}`, the SAME column as belongs_to #{first} — two references to one entity collide into a duplicate column. Add a distinct `as` alias to at least one (e.g. `\"as\": \"from_account\"` → `from_account_id`). See `jerrycan explain JC0560`.",
                            e.name, b.entity
                        ),
                    ));
                } else {
                    seen.insert(col, bi);
                }
            }
        }
        for (i, sub) in m.subroutes.iter().enumerate() {
            check_belongs_to_aliases(d, sub, &format!("{ptr}/subroutes/{i}"), qs);
        }
    }
    for (i, m) in d.modules.iter().enumerate() {
        check_belongs_to_aliases(d, m, &format!("/modules/{i}"), &mut qs);
    }

    // Jobs require a database: the engine's default store is Postgres and the
    // generated `jobs(db)` wiring + JOBS_MIGRATIONS run over `jerrycan::db::Db`.
    // A jobs-without-db design can't compile, so reject it here (one error for the
    // whole jobs list, not per-job). The shallow cron-shape check below stays as
    // the design-time guard; the engine deep-parses each expression at serve and
    // fails loud (`Jobs::cron` panics on a bad expression), so a malformed-but-
    // cron-shaped schedule is caught there rather than adding a jerrycan-jobs dep
    // to the CLI just for validation.
    if d.wants_jobs() && !d.wants_db() {
        qs.push(q(
            "/jobs".to_string(),
            "Jobs require a database dependency — add `db` to `dependencies` (background jobs run over a Postgres store).".to_string(),
        ));
    }

    // Jobs: snake_case unique names; a present schedule must look cron-shaped
    // (full cron parsing arrives with the engine in v2.3).
    let mut seen_job_names = std::collections::HashSet::new();
    for (i, job) in d.jobs.iter().enumerate() {
        if !is_snake(&job.name) {
            qs.push(q(
                format!("/jobs/{i}/name"),
                format!(
                    "Job name `{}` must be snake_case (^[a-z][a-z0-9_]*$).",
                    job.name
                ),
            ));
        }
        if !seen_job_names.insert(job.name.as_str()) {
            qs.push(q(
                format!("/jobs/{i}/name"),
                format!(
                    "Job name `{}` is already used — job names must be unique.",
                    job.name
                ),
            ));
        }
        // The queue is interpolated RAW into generated Rust string literals
        // (`.queue("{q}", ...)` / `.cron(..., "{queue}")` in jobsgen.rs), so a
        // queue with a `"` (or any non-identifier char) breaks the generated
        // crate at build time, far from the design. Validate it like every other
        // identifier interpolated into generated Rust (is_snake job names, etc.).
        if let Some(ref queue) = job.queue
            && !is_snake(queue)
        {
            qs.push(q(
                format!("/jobs/{i}/queue"),
                format!("Job queue `{queue}` must be snake_case (^[a-z][a-z0-9_]*$)."),
            ));
        }
        if let Some(ref schedule) = job.schedule {
            let fields: Vec<&str> = schedule.split_whitespace().collect();
            let cron_shaped = fields.len() == 5
                && fields.iter().all(|f| {
                    !f.is_empty()
                        && f.chars()
                            .all(|c| c.is_ascii_digit() || matches!(c, '*' | ',' | '/' | '-'))
                });
            if !cron_shaped {
                qs.push(q(
                    format!("/jobs/{i}/schedule"),
                    format!(
                        "Schedule `{schedule}` is not a 5-field cron expression (minute hour day month weekday, each [0-9*,/-]).",
                    ),
                ));
            }
        }
    }

    // Storage (contract v2). Bucket names/mime patterns are interpolated into
    // generated Rust literals and mounts, so everything is validated up front
    // (the job-queue precedent: reject at design time, not at generated-crate
    // build time). NOTE: `visibility: public` + a tenant-scoped owner is
    // deliberately allowed (public read, scoped write) — no question.
    if let Some(ref storage) = d.storage {
        if d.contract_version < 2 {
            qs.push(q(
                "/storage",
                "The storage block requires contract_version 2 — bump contract_version (v0/v1 designs stay valid without storage).",
            ));
        }
        if !d.wants_db() {
            qs.push(q(
                "/storage",
                "Storage requires a database dependency — add `db` to `dependencies` (object metadata lives in the storage_objects table).",
            ));
        }
        let active_auth_model = d
            .auth
            .as_ref()
            .map(|a| a.model != AuthModel::None)
            .unwrap_or(false);
        if !active_auth_model {
            qs.push(q(
                "/storage",
                "Storage requires an active auth model — bucket mutations (upload/delete/sign) are always guarded; set auth.model to `session` or `jwt`.",
            ));
        }
        let module_mounts: std::collections::HashSet<String> =
            d.modules.iter().map(|m| m.effective_mount()).collect();
        // A custom base_path is emitted verbatim into every bucket mount, so it
        // must be a clean absolute path (leading `/`, no trailing/`//`), like a
        // module mount.
        if let Some(base) = &storage.base_path {
            if !base.starts_with('/') {
                qs.push(q(
                    "/storage/base_path",
                    format!("Storage base_path `{base}` must start with '/'."),
                ));
            }
            if base.contains("//") || (base.len() > 1 && base.ends_with('/')) {
                qs.push(q(
                    "/storage/base_path",
                    format!("Storage base_path `{base}` must not contain `//` or end with a trailing slash."),
                ));
            }
        }
        let base_path = storage.effective_base_path();
        let mut seen_buckets = std::collections::HashSet::new();
        for (i, b) in storage.buckets.iter().enumerate() {
            let bptr = format!("/storage/buckets/{i}");
            if !is_kebab(&b.name) {
                qs.push(q(
                    format!("{bptr}/name"),
                    format!("Bucket `{}` is not kebab-case (^[a-z][a-z0-9-]*$).", b.name),
                ));
            }
            let ident = b.name.replace('-', "_");
            if is_rust_keyword(&ident) {
                qs.push(q(
                    format!("{bptr}/name"),
                    format!("Bucket `{}` becomes the Rust module `{ident}`, which is a keyword — rename it.", b.name),
                ));
            }
            if !seen_buckets.insert(b.name.as_str()) {
                qs.push(q(
                    format!("{bptr}/name"),
                    format!(
                        "Bucket name `{}` is already used — bucket names must be unique.",
                        b.name
                    ),
                ));
            }
            let bucket_mount = format!("{base_path}/{}", b.name);
            if module_mounts.contains(&bucket_mount) {
                qs.push(q(
                    format!("{bptr}/name"),
                    format!("Bucket `{}` mounts at {bucket_mount} which collides with a module mount — rename the bucket, change storage.base_path, or remount the module.", b.name),
                ));
            }
            if let Some(ref owner) = b.owner
                && !entity_names.contains(owner.as_str())
            {
                qs.push(q(
                    format!("{bptr}/owner"),
                    format!("Bucket owner `{owner}` is not a declared entity anywhere in the design — define it or fix the reference."),
                ));
            }
            // JC0545, storage facet (0.5.4): a bucket owner that reaches the
            // tenant through TWO or more `belongs_to` chains (a diamond) makes
            // `tenant_path` resolve `None`, which would SILENTLY degrade the
            // bucket from tenant scope to plain per-user scope — no Tenant
            // guard, no tenant_id stamp. Refuse it at the bucket pointer (the
            // entity-level diamond check above fires too; this one names the
            // bucket that degrades). A tenant-itself or no-tenant-path owner
            // stays User/Unowned as before — only the ≥2-branch case is refused.
            if let Some(ref owner) = b.owner
                && d.tenant_path_branch_count(owner) >= 2
            {
                qs.push(q(
                    format!("{bptr}/owner"),
                    format!(
                        "Bucket `{}` is owned by `{owner}`, which reaches the tenant through more than one `belongs_to` path (a diamond graph) — jerrycan cannot decide which chain defines tenant ownership, and falling back to per-user scope would silently drop the Tenant guard and leak the bucket across tenants. Collapse `{owner}`'s tenant ownership to a SINGLE `belongs_to` path. See `jerrycan explain JC0545`.",
                        b.name
                    ),
                ));
            }
            if b.owner_prefix && b.owner.is_none() {
                qs.push(q(
                    format!("{bptr}/owner_prefix"),
                    format!("Bucket `{}` sets owner_prefix without an owner — owner_prefix stores keys under {{owner_id}}/… and needs `owner`.", b.name),
                ));
            }
            // JC0565 (#133): an OWNER-SCOPED bucket (any `owner` → User,
            // UserInTenant, or Tenant scope — `storagegen::bucket_scope` is not
            // `Unowned`, which is exactly `b.owner.is_some()`) that omits
            // `owner_prefix` puts every owner's keys in ONE global namespace.
            // The unscoped upload duplicate-key check then leaks a cross-owner
            // EXISTENCE ORACLE (B uploading A's key gets a 409, learning A holds
            // it) and lets owners SQUAT each other's keys. `owner_prefix: true`
            // is immune — keys are `{owner_id}/…`, so the blob path, the unique
            // index, and the check are all naturally per-owner. The naive
            // runtime "just scope the check" fix corrupts data (the blob lands
            // at the shared path before the 409) and the full path+index
            // scoping is a 0.7 Supabase-parity break, so refuse the footgun at
            // design time. An Unowned bucket has no per-owner namespace and
            // stays valid with owner_prefix false — do NOT flag it.
            if let Some(ref owner) = b.owner
                && !b.owner_prefix
            {
                qs.push(q(
                    format!("{bptr}/owner_prefix"),
                    format!(
                        "Bucket `{}` is owned by `{owner}` but has no `owner_prefix`, so all owners share ONE global key namespace — one owner can learn of or squat another owner's keys (the cross-owner key oracle, #133). Set `owner_prefix: true` for per-owner key isolation (keys become `{{owner}}/…`). An intentionally SHARED bucket should have no `owner` (Unowned) instead. See `jerrycan explain JC0565`.",
                        b.name
                    ),
                ));
            }
            if let Some(ref max) = b.max_size
                && Design::parse_size(max).is_none()
            {
                qs.push(q(
                    format!("{bptr}/max_size"),
                    format!(
                        "max_size `{max}` is not a size — use ^[0-9]+(B|KB|MB|GB)?$ (e.g. \"5MB\")."
                    ),
                ));
            }
            for (j, m) in b.allowed_mime.iter().enumerate() {
                // The runtime matcher understands exactly type/subtype, type/*
                // and */*. A wildcard TYPE with a concrete subtype (`*/png`)
                // would parse here but can never match — every upload would
                // 415 — so it is rejected as malformed too.
                let well_formed = m.split_once('/').is_some_and(|(t, sub)| {
                    let seg_ok = |s: &str| {
                        !s.is_empty()
                            && s.bytes().all(|c| {
                                c.is_ascii_lowercase()
                                    || c.is_ascii_digit()
                                    || matches!(c, b'.' | b'+' | b'-')
                            })
                    };
                    (seg_ok(t) && (seg_ok(sub) || sub == "*")) || (t == "*" && sub == "*")
                });
                if !well_formed {
                    qs.push(q(
                        format!("{bptr}/allowed_mime/{j}"),
                        format!(
                            "`{m}` is not a supported mime pattern — use type/subtype, type/* or */* (lowercase)."
                        ),
                    ));
                }
            }
            // JC0556 (#132): `write_roles` gates blob upload/delete by tenant
            // role. It is only meaningful on a TENANT-scoped bucket (owner IS
            // the tenancy entity), and each entry must be a declared member_role.
            // A write gate declared where it emits NOTHING (a non-tenant/no-tenancy
            // bucket) would silently leave writes open — a security footgun — so
            // refuse it loud rather than ignore it.
            if !b.write_roles.is_empty() {
                match d.tenancy.as_ref() {
                    Some(t) if b.owner.as_deref() == Some(t.entity.as_str()) => {
                        for (k, wr) in b.write_roles.iter().enumerate() {
                            if !t.member_roles.iter().any(|r| r == wr) {
                                qs.push(q(
                                    format!("{bptr}/write_roles/{k}"),
                                    format!(
                                        "Bucket `{}` write_roles entry `{wr}` is not a declared tenancy member_role — each write role must be one of {:?}. See `jerrycan explain JC0556`.",
                                        b.name, t.member_roles
                                    ),
                                ));
                            }
                        }
                    }
                    _ => {
                        qs.push(q(
                            format!("{bptr}/write_roles"),
                            format!(
                                "Bucket `{}` sets write_roles but is not tenant-scoped (its owner is not the tenancy entity, or the design has no tenancy) — write_roles gates writes by TENANT role and emits no gate here, so a declared write restriction would silently do nothing. Drop write_roles, or make the bucket tenant-owned (owner = the tenancy entity). See `jerrycan explain JC0556`.",
                                b.name
                            ),
                        ));
                    }
                }
            }
        }
    }

    // Realtime (contract v2). Channel names/entities are interpolated into
    // generated wiring, so everything is validated up front. Scope-filtered
    // delivery of changes is the security pillar, so changes require an active
    // auth model; tenant-scoped topics require tenancy.
    if let Some(ref rt) = d.realtime {
        let active_auth_model = d
            .auth
            .as_ref()
            .map(|a| a.model != AuthModel::None)
            .unwrap_or(false);
        if d.contract_version < 2 {
            qs.push(q(
                "/realtime",
                "The realtime block requires contract_version 2 — bump contract_version (v0/v1 designs stay valid without realtime).",
            ));
        }
        if !d.wants_db() {
            qs.push(q(
                "/realtime",
                "Realtime requires a database dependency — add `db` to `dependencies` (Changes stream from Postgres).",
            ));
        }
        // Changes entities must exist and require an active auth model (delivery
        // is scope-filtered by the authenticated principal).
        if !rt.changes.is_empty() && !active_auth_model {
            qs.push(q(
                "/realtime/changes",
                "Realtime changes delivery is scope-filtered by the authenticated principal — set auth.model to `session` or `jwt`.",
            ));
        }
        for (i, entity) in rt.changes.iter().enumerate() {
            if !entity_names.contains(entity.as_str()) {
                qs.push(q(
                    format!("/realtime/changes/{i}"),
                    format!("Realtime changes entity `{entity}` is not a declared entity anywhere in the design — define it or fix the reference."),
                ));
            }
        }
        // JC0547 (#102's realtime facet): a changes entity that reaches the
        // tenant only TRANSITIVELY (a grandchild — its `tenant_path` carries
        // joins) cannot be scoped by a single row-image column: the tenant key
        // lives on an ancestor table neither CDC adapter can read from the row
        // alone, so the channel would fall back to `tenant_column: None` —
        // which the runtime treats as world-visible, broadcasting every
        // tenant's rows to every authenticated principal. Refuse at design
        // time rather than ship the silent leak. The tenant entity itself and
        // direct children (zero joins) stay legal.
        if d.tenancy.is_some() {
            for (i, entity) in rt.changes.iter().enumerate() {
                if d.tenant_path(entity).is_some_and(|p| !p.joins.is_empty()) {
                    qs.push(q(
                        format!("/realtime/changes/{i}"),
                        format!("Realtime `changes` on `{entity}` is not supported: the entity is only TRANSITIVELY tenant-owned (its tenant key lives on an ancestor table), so change events cannot be tenant-scoped from the row image and every tenant's rows would broadcast to every authenticated principal. The changes entity must be the tenant itself or a DIRECT child — flatten the relationship (give `{entity}` its own `belongs_to` the tenant) or drop it from `changes`. See `jerrycan explain JC0547`."),
                    ));
                }
            }
        }
        // #167: a write_only/password_hash column on a changes entity was once
        // refused here (a now-retired code) because the broadcast shipped the RAW
        // row. The realtime engine now PROJECTS those columns out of the
        // broadcast (realtimegen wires them into `ChangeChannelSpec.hidden_columns`
        // and `deliver_change` strips them before delivery), so the combination
        // is safe by construction and no longer refused.
        // Broadcast + presence topics: snake_case, unique within their list,
        // tenant scope needs tenancy, and any non-none scope needs auth.
        let mut check_topics = |topics: &[RealtimeTopic], kind: &str| {
            let mut seen = std::collections::HashSet::new();
            for (i, t) in topics.iter().enumerate() {
                let tptr = format!("/realtime/{kind}/{i}");
                if !is_snake(&t.name) {
                    qs.push(q(
                        format!("{tptr}/name"),
                        format!(
                            "Realtime {kind} topic `{}` is not snake_case (^[a-z][a-z0-9_]*$).",
                            t.name
                        ),
                    ));
                }
                if !seen.insert(t.name.as_str()) {
                    qs.push(q(
                        format!("{tptr}/name"),
                        format!("Realtime {kind} topic name `{}` is already used — topic names must be unique.", t.name),
                    ));
                }
                if t.scope == RealtimeScope::Tenant && d.tenancy.is_none() {
                    qs.push(q(
                        tptr.clone(),
                        format!("Realtime {kind} topic `{}` is tenant-scoped but the design has no tenancy — declare `tenancy` or use scope `auth`/`none`.", t.name),
                    ));
                }
                if t.scope != RealtimeScope::None && !active_auth_model {
                    qs.push(q(
                        tptr,
                        format!("Realtime {kind} topic `{}` needs an active auth model for its scope — set auth.model to `session` or `jwt` (or use scope `none`).", t.name),
                    ));
                }
            }
        };
        check_topics(&rt.broadcast, "broadcast");
        check_topics(&rt.presence, "presence");
    }

    // Rate limiting (issue #83). The `rate_limit` block is emitted into the
    // generated main.rs as `.extend(RateLimit::per_window(limit, window)..)` —
    // like `cors`, a design-declared middleware policy, not a hand-edit of the
    // tool-owned file. Its three interpolated values are validated up front
    // (JC0563) so a misconfig is a pointed question, not a generated-code compile
    // error, a runtime panic, or a silently-broken limiter.
    if let Some(ref rl) = d.rate_limit {
        // A 0-per-window limit rejects every request — surely unintended.
        if rl.limit == 0 {
            qs.push(q(
                "/rate_limit/limit",
                "Rate limit `limit` is 0, which blocks every request (surely unintended) — set a positive request count per window. See `jerrycan explain JC0563`.",
            ));
        }
        // The window must parse to a POSITIVE duration (it becomes
        // Duration::from_secs(N) in the generated wiring).
        if !Design::parse_duration(&rl.window).is_some_and(|secs| secs > 0) {
            qs.push(q(
                "/rate_limit/window",
                format!(
                    "Rate limit `window` `{}` is not a positive duration — use a bare number of seconds or an `<n>s`/`<n>m`/`<n>h`/`<n>d` string (e.g. \"1m\"). See `jerrycan explain JC0563`.",
                    rl.window
                ),
            ));
        }
        // The api-key header is interpolated into `RateLimit::api_key_header(..)`
        // (an HTTP header name), so it must be a valid header token (^[A-Za-z0-9-]+$)
        // — otherwise the generated code panics at startup.
        if let Some(ref header) = rl.api_key_header {
            let valid = !header.is_empty()
                && header
                    .bytes()
                    .all(|c| c.is_ascii_alphanumeric() || c == b'-');
            if !valid {
                qs.push(q(
                    "/rate_limit/api_key_header",
                    format!(
                        "Rate limit `api_key_header` `{header}` is not a valid HTTP header name — use ^[A-Za-z0-9-]+$ (e.g. \"x-api-key\"). See `jerrycan explain JC0563`.",
                    ),
                ));
            }
        }
    }

    qs
}

fn validate_module(
    m: &ModuleDesign,
    ptr: &str,
    declared_roles: &[&str],
    auth_declared: bool,
    wants_db: bool,
    qs: &mut Vec<Question>,
) {
    if !is_kebab(&m.name) {
        qs.push(q(
            format!("{ptr}/name"),
            format!("Module `{}` is not kebab-case — rename it.", m.name),
        ));
    }
    if let Some(ref mount) = m.mount {
        if !mount.starts_with('/') {
            qs.push(q(
                format!("{ptr}/mount"),
                format!("Mount `{mount}` must start with '/'."),
            ));
        }
        if mount.contains("//") || (mount.len() > 1 && mount.ends_with('/')) {
            qs.push(q(
                format!("{ptr}/mount"),
                format!("Mount `{mount}` must not contain `//` or end with a trailing slash."),
            ));
        }
    }
    for (i, e) in m.entities.iter().enumerate() {
        if !is_pascal(&e.name) {
            qs.push(q(
                format!("{ptr}/entities/{i}/name"),
                format!("Entity `{}` must be PascalCase.", e.name),
            ));
        }
        if is_rust_keyword(&e.name) {
            qs.push(q(
                format!("{ptr}/entities/{i}/name"),
                format!(
                    "Entity `{}` is a Rust keyword — it becomes a module/type name that no raw identifier can escape; rename it (e.g. a domain-specific name).",
                    e.name
                ),
            ));
        }
        // JC0546 (#114): an entity named after a `jerrycan::prelude` re-export
        // (the eval hit `Module`) emits `pub struct {Name}` in `model.rs`, which
        // the tool-owned `repo.rs`/`handlers.rs` glob-import via `use super::model::*;`
        // BESIDE `use jerrycan::prelude::*;`. Two glob imports then bring the same
        // `{Name}` into scope, so every reference is `E0659 ... is ambiguous` and the
        // scaffolded crate does not compile. Generation is gated on validation, so
        // rejecting the name here fails loud (like JC0545) instead of scaffolding an
        // app that won't build.
        if RESERVED_PRELUDE_IDENTS.contains(&e.name.as_str()) {
            qs.push(q(
                format!("{ptr}/entities/{i}/name"),
                format!(
                    "Entity `{name}` collides with `{name}`, an identifier re-exported by `jerrycan::prelude`: generated code writes `use jerrycan::prelude::*;` beside `use super::model::*;`, so the entity's `struct {name}` and the prelude's `{name}` are two glob imports of the same name — every reference is `E0659 ... is ambiguous` and the scaffolded crate does not compile. Rename the entity (e.g. `{name}Record` or a domain-specific name) so it no longer shadows a reserved prelude identifier. See `jerrycan explain JC0546`.",
                    name = e.name
                ),
            ));
        }
        // An explicit `table` override is used VERBATIM in DDL/queries, so it must
        // be a safe snake_case identifier — reject anything else up front.
        if let Some(table) = &e.table
            && !is_snake(table)
        {
            qs.push(q(
                format!("{ptr}/entities/{i}/table"),
                format!("Table override `{table}` must be snake_case (^[a-z][a-z0-9_]*$)."),
            ));
        }
        if e.fields.is_empty() {
            qs.push(q(
                format!("{ptr}/entities/{i}/fields"),
                format!(
                    "Entity `{}` has no fields — what data does it carry?",
                    e.name
                ),
            ));
        }
        for (j, f) in e.fields.iter().enumerate() {
            if !is_snake(&f.name) {
                qs.push(q(
                    format!("{ptr}/entities/{i}/fields/{j}/name"),
                    format!("Field `{}` must be snake_case.", f.name),
                ));
            }
            // A keyword field name is fine: codegen emits it as a raw identifier
            // (`type` → `r#type`) with a `#[serde(rename)]` so the wire name is
            // unchanged — a frozen external contract keeps its `type`/`match`/
            // `ref` field. Only `crate`/`self`/`super`, which no `r#` can escape,
            // are still rejected.
            if !can_be_rust_ident(&f.name) {
                qs.push(q(
                    format!("{ptr}/entities/{i}/fields/{j}/name"),
                    format!(
                        "Field `{name}` is a Rust keyword that no raw identifier can escape — rename (e.g. `{name}_field` or a domain-specific name).",
                        name = f.name
                    ),
                ));
            }
        }
    }
    if m.endpoints.is_empty() {
        qs.push(q(
            format!("{ptr}/endpoints"),
            format!(
                "Module `{}` has no endpoints — what operations does it expose?",
                m.name
            ),
        ));
    }

    let entity_names: Vec<&str> = m.entities.iter().map(|e| e.name.as_str()).collect();
    let mut seen_ops = std::collections::HashSet::new();
    let mut seen_routes = std::collections::HashSet::new();
    for (i, ep) in m.endpoints.iter().enumerate() {
        let eptr = format!("{ptr}/endpoints/{i}");
        if !is_snake(&ep.operation_id) {
            qs.push(q(
                format!("{eptr}/operation_id"),
                format!(
                    "operation_id `{}` must be snake_case (it becomes the handler fn name).",
                    ep.operation_id
                ),
            ));
        }
        if !seen_ops.insert(ep.operation_id.as_str()) {
            qs.push(q(
                format!("{eptr}/operation_id"),
                format!(
                    "operation_id `{}` is not unique within module `{}` — handler names must be unique.",
                    ep.operation_id, m.name
                ),
            ));
        }
        if !ep.path.starts_with('/') {
            qs.push(q(
                format!("{eptr}/path"),
                format!("Path `{}` must start with '/'.", ep.path),
            ));
        }
        let param_count = ep.path.matches('{').count();
        if param_count > 3 {
            qs.push(q(format!("{eptr}/path"), format!("Path `{}` has {param_count} parameters — at most three path parameters per endpoint are supported. Split the route or use a subroute.", ep.path)));
        }
        if ep.path.matches('{').count() != ep.path.matches('}').count() {
            qs.push(q(
                format!("{eptr}/path"),
                format!("Path `{}` has unbalanced braces.", ep.path),
            ));
        }
        if !seen_routes.insert((ep.method, ep.path.as_str())) {
            qs.push(q(
                format!("{eptr}/path"),
                format!(
                    "{:?} {} is already registered in module `{}` — routes must be unique.",
                    ep.method, ep.path, m.name
                ),
            ));
        }
        // Success is 2xx, or 3xx for a redirect endpoint (e.g. an OAuth
        // `connect` that 302s the browser to the provider). 1xx/4xx/5xx are not
        // success classes.
        if !(200..=399).contains(&ep.success.status) {
            qs.push(q(
                format!("{eptr}/success/status"),
                format!("Success status {} is not 2xx/3xx.", ep.success.status),
            ));
        }
        if let Some(ref ent) = ep.success.entity
            && !entity_names.contains(&ent.as_str())
        {
            qs.push(q(
                format!("{eptr}/success/entity"),
                format!(
                    "Entity `{ent}` is not defined in module `{}` — define it or fix the reference.",
                    m.name
                ),
            ));
        }
        if let Some(ref rb) = ep.request_body {
            // JC0561 (#122): a `request_body` is EITHER an entity ref (today's
            // shape) XOR an inline DTO (`fields`). Refuse both-set / neither-set,
            // an inline body on an operation with no name (the DTO
            // `{Pascal(operation_id)}Request` would be unnameable), and validate the
            // inline fields with the SAME per-field checks as entity fields.
            let has_entity = rb.entity.is_some();
            let has_fields = !rb.fields.is_empty();
            if has_entity && has_fields {
                qs.push(q(
                    format!("{eptr}/request_body"),
                    format!(
                        "Endpoint `{}` request_body declares BOTH an `entity` and inline `fields` — exactly one is allowed: a `request_body` is either a table-entity reference OR an ad-hoc inline DTO, never both. Drop one. See `jerrycan explain JC0561`.",
                        ep.operation_id
                    ),
                ));
            } else if !has_entity && !has_fields {
                qs.push(q(
                    format!("{eptr}/request_body"),
                    format!(
                        "Endpoint `{}` request_body declares NEITHER an `entity` nor inline `fields` — a `request_body` must be exactly one: a table-entity reference (`{{\"entity\": \"Todo\"}}`) OR an inline DTO (`{{\"fields\": [...]}}`). See `jerrycan explain JC0561`.",
                        ep.operation_id
                    ),
                ));
            } else if let Some(ent) = rb.entity.as_deref() {
                if !entity_names.contains(&ent) {
                    qs.push(q(
                        format!("{eptr}/request_body/entity"),
                        format!(
                            "Entity `{ent}` is not defined in module `{}` — define it or fix the reference.",
                            m.name
                        ),
                    ));
                }
            } else {
                // Inline DTO body (has_fields, no entity). It needs an operation_id
                // to be nameable, and every field must pass the same name/charset
                // and #80 constraint checks as an entity field, plus no duplicates.
                if ep.operation_id.trim().is_empty() {
                    qs.push(q(
                        format!("{eptr}/request_body/fields"),
                        "An inline `request_body` (`fields`) requires an `operation_id` — the generated request struct is named `{Pascal(operation_id)}Request`, so a nameless operation has no DTO name. Give the endpoint an operation_id. See `jerrycan explain JC0561`.".to_string(),
                    ));
                }
                let mut seen_fields = std::collections::HashSet::new();
                for (j, f) in rb.fields.iter().enumerate() {
                    let fptr = format!("{eptr}/request_body/fields/{j}");
                    if !is_snake(&f.name) {
                        qs.push(q(
                            format!("{fptr}/name"),
                            format!("Field `{}` must be snake_case.", f.name),
                        ));
                    }
                    if !can_be_rust_ident(&f.name) {
                        qs.push(q(
                            format!("{fptr}/name"),
                            format!(
                                "Field `{name}` is a Rust keyword that no raw identifier can escape — rename (e.g. `{name}_field` or a domain-specific name).",
                                name = f.name
                            ),
                        ));
                    }
                    if !seen_fields.insert(f.name.as_str()) {
                        qs.push(q(
                            format!("{fptr}/name"),
                            format!(
                                "Inline field `{}` is declared twice in this request_body — the generated `{}Request` struct would carry a duplicate field. Give each field a unique name. See `jerrycan explain JC0561`.",
                                f.name,
                                to_pascal(&ep.operation_id)
                            ),
                        ));
                    }
                    // The SAME #47/#80/default per-field checks as an entity field.
                    check_field_shape(f, &fptr, wants_db, qs);
                    // JC0567 (#235): an inline field is an ad-hoc custom-action body,
                    // NOT a table row — there is no codegen server-set path (no entity
                    // is built, no column is written, no server-set steer is emitted).
                    // So `default`/`write_only`, which the entity path honors via the
                    // Model + request-DTO omission, are silently DROPPED on the inline
                    // path — worse, a REQUIRED defaulted field inverts into a required,
                    // un-defaulted, client-supplied field (the #110 `now` timestamp
                    // becomes client-backdatable). Refuse both up front, directing the
                    // author to omit the field and set/handle it in the handler.
                    if f.default.is_some() {
                        qs.push(q(
                            format!("{fptr}/default"),
                            format!(
                                "Inline field `{}` on endpoint `{}` declares a `default` — a `default` is not supported on an inline `request_body` field: an inline DTO is an ad-hoc custom-action body, not a table row, so there is no codegen server-set path to apply it (no entity is built, no DB column is written, no server-set steer is emitted). It would be silently dropped — and a REQUIRED defaulted field would invert into a required, un-defaulted client field (a `now` timestamp, #110, would become client-backdatable). Omit the field from the inline body and set it in the handler. See `jerrycan explain JC0567`.",
                                f.name, ep.operation_id
                            ),
                        ));
                    }
                    if Design::field_is_write_only(f) {
                        qs.push(q(
                            format!("{fptr}/write_only"),
                            format!(
                                "Inline field `{}` on endpoint `{}` is `write_only` (an explicit flag, or the auto-classified `password_hash` name) — `write_only` is not supported on an inline `request_body` field: it response-hides a column on the generated Model (issue #112), but an inline DTO is a custom-action body with no companion response Model, so the flag has nothing to hide and is silently dropped. Omit the flag (rename a `password_hash` inline field); if a value must not appear in a response, don't echo it from the handler. See `jerrycan explain JC0567`.",
                                f.name, ep.operation_id
                            ),
                        ));
                    }
                }
            }
        }
        for (j, ec) in ep.errors.iter().enumerate() {
            if !(400..=599).contains(&ec.status) {
                qs.push(q(
                    format!("{eptr}/errors/{j}/status"),
                    format!("Error status {} is not 4xx/5xx.", ec.status),
                ));
            }
            if let Some(ref code) = ec.code {
                let ok = code.len() == 6
                    && code.starts_with("JC")
                    && code[2..].chars().all(|c| c.is_ascii_digit());
                if !ok {
                    qs.push(q(
                        format!("{eptr}/errors/{j}/code"),
                        format!("`{code}` does not match ^JC[0-9]{{4}}$."),
                    ));
                }
            }
        }
        for role in &ep.required_roles {
            if !declared_roles.contains(&role.as_str()) {
                let hint = if auth_declared {
                    "add it to auth.roles or fix the reference"
                } else {
                    "declare auth { model, roles } first"
                };
                qs.push(q(
                    format!("{eptr}/required_roles"),
                    format!("Role `{role}` is not declared in auth.roles — {hint}."),
                ));
            }
        }
        // `public` marks a genuinely unauthenticated route (login/register); it
        // contradicts any guard. Flag the combination so a design can't claim both.
        if ep.public && ep.auth_required {
            qs.push(q(
                eptr.clone(),
                format!(
                    "Endpoint `{}` is marked public but also auth_required — a public route is unauthenticated by design; drop one.",
                    ep.operation_id
                ),
            ));
        }
        if ep.public && !ep.required_roles.is_empty() {
            qs.push(q(
                eptr.clone(),
                format!(
                    "Endpoint `{}` is marked public but declares required_roles — a public route is unauthenticated by design; drop the roles or the public flag.",
                    ep.operation_id
                ),
            ));
        }
    }

    for (i, sub) in m.subroutes.iter().enumerate() {
        validate_module(
            sub,
            &format!("{ptr}/subroutes/{i}"),
            declared_roles,
            auth_declared,
            wants_db,
            qs,
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::platform::design::tests::{MINIMAL, V1_FULL, V2_REALTIME, V2_STORAGE};

    fn design(json: &str) -> Design {
        serde_json::from_str(json).unwrap()
    }

    /// Authenticate every non-public endpoint of a design so no tenant /
    /// tenant-owned read is anonymous. The shared tenancy fixtures (V1_FULL /
    /// V2_STORAGE / V2_REALTIME) predate JC0558 (#148) and carry unguarded reads
    /// on their tenant/tenant-owned entities; tests that only care that the
    /// fixture is otherwise question-free (realtime, storage, tenancy checks)
    /// guard the reads first so the JC0558 refusal doesn't mask the assertion.
    fn guard_reads(mut d: Design) -> Design {
        fn walk(m: &mut ModuleDesign) {
            for ep in &mut m.endpoints {
                if !ep.public {
                    ep.auth_required = true;
                }
            }
            for sub in &mut m.subroutes {
                walk(sub);
            }
        }
        for m in &mut d.modules {
            walk(m);
        }
        d
    }

    /// JC0561 (#122): a well-formed inline-DTO `request_body` validates clean, and
    /// the four malformed shapes (both entity+fields, neither, an inline field with
    /// a bad #80 constraint, a duplicate inline field name) are refused with a
    /// JC0561/JC0552 message.
    #[test]
    fn inline_request_body_is_validated_with_jc0561() {
        let base = |body: &str| {
            format!(
                r#"{{
                "name": "shop-api", "contract_version": 0, "dependencies": [],
                "modules": [{{
                    "name": "checkout",
                    "endpoints": [
                        {{ "operation_id": "checkout", "method": "POST", "path": "/",
                          "request_body": {body},
                          "success": {{ "status": 200 }} }}
                    ]
                }}]
            }}"#
            )
        };

        // A clean inline body → no questions.
        let ok = design(&base(
            r#"{ "fields": [ { "name": "coupon", "type": "string" }, { "name": "total", "type": "integer" } ] }"#,
        ));
        assert!(
            validate(&ok).is_empty(),
            "clean inline body: {:?}",
            validate(&ok)
        );

        // BOTH entity and fields → JC0561.
        let both = design(&base(
            r#"{ "entity": "Order", "fields": [ { "name": "coupon", "type": "string" } ] }"#,
        ));
        assert!(
            validate(&both)
                .iter()
                .any(|q| q.question.contains("JC0561") && q.question.contains("BOTH")),
            "both entity+fields must trip JC0561: {:?}",
            validate(&both)
        );

        // NEITHER → JC0561.
        let neither = design(&base(r#"{ }"#));
        assert!(
            validate(&neither)
                .iter()
                .any(|q| q.question.contains("JC0561") && q.question.contains("NEITHER")),
            "empty request_body must trip JC0561: {:?}",
            validate(&neither)
        );

        // An inline field with a misplaced #80 constraint reuses JC0552.
        let bad_constraint = design(&base(
            r#"{ "fields": [ { "name": "coupon", "type": "string", "min": 1 } ] }"#,
        ));
        assert!(
            validate(&bad_constraint)
                .iter()
                .any(|q| q.question.contains("JC0552")),
            "inline field constraint must be validated (JC0552): {:?}",
            validate(&bad_constraint)
        );

        // A duplicate inline field name → JC0561.
        let dup = design(&base(
            r#"{ "fields": [ { "name": "coupon", "type": "string" }, { "name": "coupon", "type": "string" } ] }"#,
        ));
        assert!(
            validate(&dup)
                .iter()
                .any(|q| q.question.contains("JC0561") && q.question.contains("twice")),
            "duplicate inline field must trip JC0561: {:?}",
            validate(&dup)
        );
    }

    /// JC0567 (#235): `default`/`write_only` on an INLINE `request_body` field is
    /// refused — an inline DTO is an ad-hoc custom-action body with no codegen
    /// server-set path, so a `default` would silently invert into a required,
    /// un-defaulted client field (a `now` timestamp becomes client-backdatable) and
    /// a `write_only` inline field has no companion response Model to hide it on. A
    /// clean inline body stays question-free, and — critically — the SAME
    /// `default`/`write_only` on an ENTITY field is NOT refused (the entity path
    /// honors both), so the refusal targets ONLY the inline path.
    #[test]
    fn jc0567_refuses_default_and_write_only_on_inline_fields() {
        let base = |body: &str| -> Design {
            serde_json::from_str(&format!(
                r#"{{ "name": "shop-api", "contract_version": 0, "dependencies": ["db"],
                    "modules": [{{ "name": "checkout", "endpoints": [
                        {{ "operation_id": "checkout", "method": "POST", "path": "/apply",
                          "request_body": {body},
                          "success": {{ "status": 200 }} }}] }}] }}"#,
            ))
            .expect("valid design json")
        };

        // A `default` on an inline field → JC0567.
        let dflt =
            base(r#"{ "fields": [ { "name": "at", "type": "datetime", "default": "now" } ] }"#);
        assert!(
            validate(&dflt)
                .iter()
                .any(|q| q.question.contains("JC0567") && q.question.contains("default")),
            "inline default must trip JC0567: {:?}",
            validate(&dflt)
        );

        // An explicit `write_only` inline field → JC0567.
        let wo =
            base(r#"{ "fields": [ { "name": "secret", "type": "string", "write_only": true } ] }"#);
        assert!(
            validate(&wo)
                .iter()
                .any(|q| q.question.contains("JC0567") && q.question.contains("write_only")),
            "inline write_only must trip JC0567: {:?}",
            validate(&wo)
        );

        // A `password_hash`-named inline field is AUTO-classified write_only → JC0567
        // (the silent-drop the fix closes; `f.write_only` alone would miss it).
        let pw = base(r#"{ "fields": [ { "name": "password_hash", "type": "string" } ] }"#);
        assert!(
            validate(&pw).iter().any(|q| q.question.contains("JC0567")),
            "auto-classified password_hash inline field must trip JC0567: {:?}",
            validate(&pw)
        );

        // A clean inline body (no default/write_only) stays question-free.
        let clean = base(r#"{ "fields": [ { "name": "amount", "type": "integer", "min": 1 } ] }"#);
        assert!(
            validate(&clean).is_empty(),
            "clean inline body must be question-free: {:?}",
            validate(&clean)
        );

        // The SAME default/write_only on an ENTITY field is NOT refused — the entity
        // path drops the default from the DTO and hides write_only on the Model. This
        // proves JC0567 is scoped to the inline path, not `default`/`write_only` at large.
        let entity: Design = serde_json::from_str(
            r#"{ "name": "shop-api", "contract_version": 0, "dependencies": ["db"],
                "modules": [{ "name": "checkout",
                  "entities": [{ "name": "Order", "fields": [
                    { "name": "created_at", "type": "datetime", "default": "now" },
                    { "name": "token", "type": "string", "write_only": true } ] }],
                  "endpoints": [
                    { "operation_id": "create_order", "method": "POST", "path": "/",
                      "request_body": { "entity": "Order" },
                      "success": { "status": 201, "entity": "Order" } }] }] }"#,
        )
        .expect("valid entity design");
        assert!(
            validate(&entity).is_empty(),
            "entity default/write_only must stay question-free: {:?}",
            validate(&entity)
        );
    }

    /// JC0563 (#83): the three interpolated values of a `rate_limit` block are
    /// validated up front so a misconfig is a pointed question — not a
    /// generated-code compile error (bad limit type), a startup panic (a
    /// non-header `api_key_header` reaching `HeaderName::from_static`), or a
    /// silently-broken limiter (a 0 limit that rejects everything). A well-formed
    /// block — including both optional fields — is question-free.
    #[test]
    fn jc0563_refuses_a_malformed_rate_limit_block() {
        let base = |rl: &str| -> Design {
            serde_json::from_str(&format!(
                r#"{{ "name": "rl-app", "contract_version": 0, "dependencies": ["db"],
                    "rate_limit": {rl},
                    "modules": [{{ "name": "m", "endpoints": [
                        {{ "operation_id": "list_m", "method": "GET", "path": "/",
                          "success": {{ "status": 200 }} }}] }}] }}"#,
            ))
            .unwrap()
        };

        // A valid block (both optional fields set) raises no `/rate_limit` question.
        let ok = base(
            r#"{ "limit": 100, "window": "1m", "api_key_header": "x-api-key", "trust_forwarded_for": true }"#,
        );
        assert!(
            !validate(&ok)
                .iter()
                .any(|q| q.id.starts_with("/rate_limit")),
            "valid rate_limit block must be question-free: {:?}",
            validate(&ok)
        );

        // limit == 0 blocks every request → JC0563 on `/rate_limit/limit`.
        let zero = base(r#"{ "limit": 0, "window": "1m" }"#);
        assert!(
            validate(&zero)
                .iter()
                .any(|q| q.id == "/rate_limit/limit" && q.question.contains("JC0563")),
            "limit 0 must trip JC0563: {:?}",
            validate(&zero)
        );

        // An unparseable window → JC0563 on `/rate_limit/window`.
        let bad_window = base(r#"{ "limit": 10, "window": "soon" }"#);
        assert!(
            validate(&bad_window)
                .iter()
                .any(|q| q.id == "/rate_limit/window" && q.question.contains("JC0563")),
            "unparseable window must trip JC0563: {:?}",
            validate(&bad_window)
        );

        // A zero-duration window parses but is non-positive → still JC0563.
        let zero_window = base(r#"{ "limit": 10, "window": "0s" }"#);
        assert!(
            validate(&zero_window)
                .iter()
                .any(|q| q.id == "/rate_limit/window"),
            "zero-duration window must trip JC0563: {:?}",
            validate(&zero_window)
        );

        // An api_key_header that is not a valid HTTP header token → JC0563. A bad
        // token would panic `HeaderName::from_static` in the generated app.
        let bad_header = base(r#"{ "limit": 10, "window": "1m", "api_key_header": "x api key" }"#);
        assert!(
            validate(&bad_header)
                .iter()
                .any(|q| q.id == "/rate_limit/api_key_header" && q.question.contains("JC0563")),
            "invalid api_key_header must trip JC0563: {:?}",
            validate(&bad_header)
        );
    }

    #[test]
    fn valid_realtime_design_is_question_free() {
        let d = guard_reads(serde_json::from_str(V2_REALTIME).unwrap());
        assert!(validate(&d).is_empty(), "{:?}", validate(&d));
    }

    #[test]
    fn realtime_requires_contract_v2() {
        let mut d: Design = serde_json::from_str(V2_REALTIME).unwrap();
        d.contract_version = 1;
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/realtime" && q.question.contains("contract_version"))
        );
    }

    #[test]
    fn realtime_changes_entities_must_exist() {
        let mut d: Design = serde_json::from_str(V2_REALTIME).unwrap();
        d.realtime.as_mut().unwrap().changes[0] = "Ghost".into();
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/realtime/changes/0" && q.question.contains("Ghost"))
        );
    }

    #[test]
    fn realtime_requires_db_and_changes_require_active_auth() {
        let mut d: Design = serde_json::from_str(V2_REALTIME).unwrap();
        d.dependencies.retain(|x| x != "db");
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/realtime" && q.question.contains("db"))
        );

        let mut d2: Design = serde_json::from_str(V2_REALTIME).unwrap();
        d2.auth = None;
        assert!(
            validate(&d2)
                .iter()
                .any(|q| q.id == "/realtime/changes" && q.question.contains("auth"))
        );
    }

    /// JC0547 (#102's realtime facet): a `changes` entity that reaches the
    /// tenant only transitively (a grandchild) has no tenant key in its row
    /// image, so its channel would get `tenant_column: None` — which the
    /// runtime treats as world-visible, silently broadcasting every tenant's
    /// rows to every authenticated principal. The design must be REFUSED up
    /// front; the tenant entity itself and direct children stay legal.
    #[test]
    fn transitive_changes_entity_is_refused_with_jc0547() {
        let mut d: Design = serde_json::from_str(V2_REALTIME).unwrap();
        // Contact → Lead → Workspace: a grandchild of the tenant.
        d.modules[1].entities.push(
            serde_json::from_value(serde_json::json!({
                "name": "Contact",
                "belongs_to": [{ "entity": "Lead" }],
                "fields": [{ "name": "email", "type": "string" }]
            }))
            .unwrap(),
        );
        d.realtime.as_mut().unwrap().changes.push("Contact".into());
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/realtime/changes/1" && q.question.contains("JC0547")),
            "{:?}",
            validate(&d)
        );

        // A DIRECT child (Lead) and the tenant entity itself (Workspace) are
        // both scopable from the row image — no JC0547, no other question.
        let mut ok = guard_reads(serde_json::from_str(V2_REALTIME).unwrap());
        ok.realtime
            .as_mut()
            .unwrap()
            .changes
            .push("Workspace".into());
        assert!(validate(&ok).is_empty(), "{:?}", validate(&ok));
    }

    /// #167 (SECURITY, the lift): a `write_only`/`password_hash` column on a
    /// realtime `changes` entity is now SAFE and validates CLEAN. The changes
    /// broadcast used to ship the RAW row (leaking the response-hidden column
    /// over the WebSocket), and the interim refusal — an earlier `jerrycan
    /// explain` code, now retired and not reused — blocked the combination. With
    /// column projection (realtimegen wires the write_only columns into
    /// `ChangeChannelSpec.hidden_columns`, and `deliver_change` strips them
    /// before delivery), the secret never reaches a subscriber, so the design is
    /// accepted. This test is the replacement for the retired refusal: it PROVES
    /// the lift (the combination no longer produces any validation question).
    #[test]
    fn write_only_column_on_a_changes_entity_validates_clean() {
        // The retired refusal pushed a question at `/realtime/changes/{i}`; the
        // lift means a write_only/password_hash column on a broadcast entity
        // adds NO such question (projection closes the raw-row leak). The base
        // V2_REALTIME already carries unrelated questions (JC0558 anonymous
        // reads), so the precise proof is: adding the column introduces NOTHING,
        // and no question touches the realtime changes path.
        let base: Design = serde_json::from_str(V2_REALTIME).unwrap();
        let base_n = validate(&base).len();
        assert!(
            !validate(&base)
                .iter()
                .any(|q| q.id.starts_with("/realtime/changes/")),
            "baseline: the fixture has no realtime-changes question"
        );

        let assert_lifted = |d: &Design, what: &str| {
            let qs = validate(d);
            assert!(
                !qs.iter().any(|q| q.id.starts_with("/realtime/changes/")),
                "a {what} column on a changes entity must NOT be refused (projected \
                 out of the broadcast): {qs:?}"
            );
            assert_eq!(
                qs.len(),
                base_n,
                "a {what} column adds no new validation question: {qs:?}"
            );
        };

        // password_hash (auto-hidden by name) on the broadcast `Lead`.
        let mut hashed: Design = serde_json::from_str(V2_REALTIME).unwrap();
        hashed.modules[1].entities[0].fields.push(
            serde_json::from_value(
                serde_json::json!({ "name": "password_hash", "type": "string" }),
            )
            .unwrap(),
        );
        assert_lifted(&hashed, "password_hash");

        // The EXPLICIT `write_only: true` flag — the classifier covers both, and
        // both are projected out of the broadcast.
        let mut explicit: Design = serde_json::from_str(V2_REALTIME).unwrap();
        explicit.modules[1].entities[0].fields.push(
            serde_json::from_value(serde_json::json!({
                "name": "api_token", "type": "string", "write_only": true
            }))
            .unwrap(),
        );
        assert_lifted(&explicit, "write_only");
    }

    #[test]
    fn tenant_scoped_topics_require_tenancy_and_snake_case_unique_names() {
        let mut d: Design = serde_json::from_str(V2_REALTIME).unwrap();
        d.tenancy = None;
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/realtime/broadcast/0" && q.question.contains("tenancy"))
        );

        let mut d2: Design = serde_json::from_str(V2_REALTIME).unwrap();
        d2.realtime.as_mut().unwrap().broadcast.push(RealtimeTopic {
            name: "Deal-Room".into(),
            scope: RealtimeScope::None,
        });
        assert!(
            validate(&d2)
                .iter()
                .any(|q| q.id == "/realtime/broadcast/1/name" && q.question.contains("snake_case"))
        );

        let mut d3: Design = serde_json::from_str(V2_REALTIME).unwrap();
        let dup = d3.realtime.as_ref().unwrap().broadcast[0].clone();
        d3.realtime.as_mut().unwrap().broadcast.push(dup);
        assert!(
            validate(&d3)
                .iter()
                .any(|q| q.id == "/realtime/broadcast/1/name" && q.question.contains("unique"))
        );
    }

    #[test]
    fn contract_version_2_is_now_valid_and_3_is_not() {
        let ok: Design = serde_json::from_str(V2_STORAGE).unwrap();
        assert!(
            !validate(&ok).iter().any(|q| q.id == "/contract_version"),
            "{:?}",
            validate(&ok)
        );
        let mut bad: Design = serde_json::from_str(V2_STORAGE).unwrap();
        bad.contract_version = 3;
        assert!(validate(&bad).iter().any(|q| q.id == "/contract_version"));
    }

    #[test]
    fn v2_storage_fixture_is_question_free() {
        let d = guard_reads(serde_json::from_str(V2_STORAGE).unwrap());
        assert!(validate(&d).is_empty(), "{:?}", validate(&d));
    }

    #[test]
    fn storage_requires_contract_v2_db_and_an_active_auth_model() {
        // v1 + storage: rejected (v2 owns the block).
        let mut d: Design = serde_json::from_str(V2_STORAGE).unwrap();
        d.contract_version = 1;
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/storage" && q.question.contains("contract_version 2"))
        );
        // storage without db: rejected (metadata table).
        let mut d: Design = serde_json::from_str(V2_STORAGE).unwrap();
        d.dependencies.retain(|dep| dep != "db");
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/storage" && q.question.contains("db"))
        );
        // storage without an active auth model: rejected (mutations are always guarded).
        let mut d: Design = serde_json::from_str(V2_STORAGE).unwrap();
        d.auth = None;
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/storage" && q.question.contains("auth"))
        );
    }

    #[test]
    fn bucket_names_owners_and_rules_are_validated() {
        // Bad kebab name.
        let mut d: Design = serde_json::from_str(V2_STORAGE).unwrap();
        d.storage.as_mut().unwrap().buckets[0].name = "Avatars".into();
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/storage/buckets/0/name")
        );
        // A name whose snake ident is a Rust keyword breaks the generated crate.
        let mut d: Design = serde_json::from_str(V2_STORAGE).unwrap();
        d.storage.as_mut().unwrap().buckets[0].name = "match".into();
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/storage/buckets/0/name" && q.question.contains("keyword"))
        );
        // Duplicate bucket names.
        let mut d: Design = serde_json::from_str(V2_STORAGE).unwrap();
        let dup = d.storage.as_ref().unwrap().buckets[0].clone();
        d.storage.as_mut().unwrap().buckets.push(dup);
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/storage/buckets/2/name" && q.question.contains("unique"))
        );
        // Unknown owner entity.
        let mut d: Design = serde_json::from_str(V2_STORAGE).unwrap();
        d.storage.as_mut().unwrap().buckets[0].owner = Some("Ghost".into());
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/storage/buckets/0/owner" && q.question.contains("Ghost"))
        );
        // owner_prefix without owner.
        let mut d: Design = serde_json::from_str(V2_STORAGE).unwrap();
        d.storage.as_mut().unwrap().buckets[1].owner = None;
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/storage/buckets/1/owner_prefix")
        );
        // Unparseable max_size.
        let mut d: Design = serde_json::from_str(V2_STORAGE).unwrap();
        d.storage.as_mut().unwrap().buckets[0].max_size = Some("lots".into());
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/storage/buckets/0/max_size")
        );
        // A mime entry that could break generated string literals.
        let mut d: Design = serde_json::from_str(V2_STORAGE).unwrap();
        d.storage.as_mut().unwrap().buckets[0].allowed_mime = vec!["image/\"png".into()];
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/storage/buckets/0/allowed_mime/0")
        );
        // A wildcard TYPE with a concrete subtype (`*/png`) is dead: the
        // runtime matcher only understands `type/subtype`, `type/*` and `*/*`,
        // so `*/png` would silently 415 every upload — reject at design time.
        let mut d: Design = serde_json::from_str(V2_STORAGE).unwrap();
        d.storage.as_mut().unwrap().buckets[0].allowed_mime = vec!["*/png".into()];
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/storage/buckets/0/allowed_mime/0"),
            "*/png must be rejected — it can never match"
        );
        // The supported wildcard shapes stay valid.
        let mut d: Design = serde_json::from_str(V2_STORAGE).unwrap();
        d.storage.as_mut().unwrap().buckets[0].allowed_mime =
            vec!["*/*".into(), "image/*".into(), "application/pdf".into()];
        assert!(
            !validate(&d)
                .iter()
                .any(|q| q.id.starts_with("/storage/buckets/0/allowed_mime")),
            "*/*, type/* and type/subtype are all valid"
        );
    }

    /// JC0565 (#133): an OWNER-SCOPED bucket that omits `owner_prefix` shares
    /// ONE global key namespace across all owners — the cross-owner existence
    /// oracle / key squatting. Refuse it at design time for a User-scoped AND a
    /// Tenant-scoped bucket; the same bucket WITH `owner_prefix` is clean; an
    /// UNOWNED bucket has no per-owner namespace, so `owner_prefix: false` stays
    /// valid there (no false positive). WHY (Rule 9): the refusal is the only
    /// thing standing between a scoped bucket and a shipped cross-owner oracle —
    /// if it stopped firing, the unsafe shape would pass `check` green again.
    #[test]
    fn owner_scoped_bucket_without_owner_prefix_is_refused_with_jc0565() {
        let jc0565_at = |d: &Design, ptr: &str| {
            validate(d)
                .iter()
                .any(|q| q.id == ptr && q.question.contains("JC0565"))
        };

        // User-scoped: avatars (owner User) without owner_prefix → JC0565.
        let mut user: Design = serde_json::from_str(V2_STORAGE).unwrap();
        user.storage.as_mut().unwrap().buckets[0].owner_prefix = false;
        assert!(
            jc0565_at(&user, "/storage/buckets/0/owner_prefix"),
            "a user-scoped bucket without owner_prefix must fire JC0565: {:?}",
            validate(&user)
        );

        // Tenant-scoped: invoices (owner Org == tenancy.entity) without
        // owner_prefix → JC0565 too.
        let mut tenant: Design = serde_json::from_str(V2_STORAGE).unwrap();
        tenant.storage.as_mut().unwrap().buckets[1].owner_prefix = false;
        assert!(
            jc0565_at(&tenant, "/storage/buckets/1/owner_prefix"),
            "a tenant-scoped bucket without owner_prefix must fire JC0565: {:?}",
            validate(&tenant)
        );

        // Both fixture buckets set owner_prefix, so the scoped shape is clean.
        let clean: Design = serde_json::from_str(V2_STORAGE).unwrap();
        assert!(
            !validate(&clean)
                .iter()
                .any(|q| q.question.contains("JC0565")),
            "owner-scoped buckets WITH owner_prefix must not fire JC0565: {:?}",
            validate(&clean)
        );

        // An UNOWNED bucket (no owner) keeps owner_prefix:false VALID — no
        // per-owner namespace, no oracle. Must NOT be flagged (no false positive).
        let mut unowned: Design = serde_json::from_str(V2_STORAGE).unwrap();
        {
            let b = &mut unowned.storage.as_mut().unwrap().buckets[0];
            b.owner = None;
            b.owner_prefix = false;
        }
        assert!(
            !validate(&unowned)
                .iter()
                .any(|q| q.question.contains("JC0565")),
            "an unowned bucket without owner_prefix must not fire JC0565: {:?}",
            validate(&unowned)
        );
    }

    /// JC0556 (#132): `write_roles` gates blob upload/delete by tenant role. It
    /// must name declared member_roles AND sit on a tenant-scoped bucket — a
    /// write gate that emits nothing (non-tenant / no-tenancy) would silently
    /// leave writes open, so it is refused loud rather than ignored.
    #[test]
    fn write_roles_are_validated_with_jc0556() {
        // An entry that is not a declared member_role, on the tenant-scoped
        // invoices bucket (owner Org == tenancy.entity).
        let mut d: Design = serde_json::from_str(V2_STORAGE).unwrap();
        d.storage.as_mut().unwrap().buckets[1].write_roles = vec!["ghost".into()];
        assert!(
            validate(&d).iter().any(
                |q| q.id == "/storage/buckets/1/write_roles/0" && q.question.contains("JC0556")
            ),
            "undeclared write role → JC0556: {:?}",
            validate(&d)
        );
        // A declared member_role on the tenant bucket is accepted.
        let mut ok: Design = serde_json::from_str(V2_STORAGE).unwrap();
        ok.storage.as_mut().unwrap().buckets[1].write_roles = vec!["owner".into()];
        assert!(
            !validate(&ok)
                .iter()
                .any(|q| q.id.starts_with("/storage/buckets/1/write_roles")),
            "a declared member_role on a tenant bucket is valid: {:?}",
            validate(&ok)
        );
        // write_roles on a NON-tenant bucket (avatars, owner User) is refused —
        // the gate would emit nothing there.
        let mut nt: Design = serde_json::from_str(V2_STORAGE).unwrap();
        nt.storage.as_mut().unwrap().buckets[0].write_roles = vec!["owner".into()];
        assert!(
            validate(&nt)
                .iter()
                .any(|q| q.id == "/storage/buckets/0/write_roles" && q.question.contains("JC0556")),
            "write_roles on a non-tenant bucket → JC0556: {:?}",
            validate(&nt)
        );
        // write_roles with no tenancy at all is refused the same way.
        let mut no_ten: Design = serde_json::from_str(V2_STORAGE).unwrap();
        no_ten.tenancy = None;
        no_ten.storage.as_mut().unwrap().buckets[1].write_roles = vec!["owner".into()];
        assert!(
            validate(&no_ten)
                .iter()
                .any(|q| q.id == "/storage/buckets/1/write_roles" && q.question.contains("JC0556")),
            "write_roles without tenancy → JC0556: {:?}",
            validate(&no_ten)
        );
    }

    /// JC0545, storage facet (0.5.4): a bucket owner that reaches the tenant
    /// through TWO `belongs_to` chains (a diamond) makes `tenant_path` resolve
    /// `None`, which would SILENTLY degrade the bucket from tenant scope to
    /// plain per-user scope — no Tenant guard, no tenant_id stamp, a
    /// cross-tenant leak with `check` green. The bucket itself must be
    /// refused; a single (even transitive) chain stays legal.
    #[test]
    fn diamond_bucket_owner_is_refused_with_jc0545() {
        let diamond = |d: &mut Design| {
            // User (avatars' owner) → {Team, Project} → Org: two chains.
            for parent in [
                r#"{ "name": "Team", "belongs_to": [{ "entity": "Org" }],
                     "fields": [{ "name": "id", "type": "integer" }] }"#,
                r#"{ "name": "Project", "belongs_to": [{ "entity": "Org" }],
                     "fields": [{ "name": "id", "type": "integer" }] }"#,
            ] {
                d.modules[0]
                    .entities
                    .push(serde_json::from_str(parent).unwrap());
            }
            d.modules[0].entities[1].belongs_to = vec![
                serde_json::from_str(r#"{ "entity": "Team" }"#).unwrap(),
                serde_json::from_str(r#"{ "entity": "Project" }"#).unwrap(),
            ];
        };
        let mut d: Design = serde_json::from_str(V2_STORAGE).unwrap();
        diamond(&mut d);
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/storage/buckets/0/owner" && q.question.contains("JC0545")),
            "diamond bucket owner → JC0545 at the bucket pointer: {:?}",
            validate(&d)
        );
        // A single transitive chain (drop the Project leg) is NOT ambiguous —
        // the bucket becomes UserInTenant, no refusal.
        let mut single: Design = serde_json::from_str(V2_STORAGE).unwrap();
        diamond(&mut single);
        single.modules[0].entities[1].belongs_to =
            vec![serde_json::from_str(r#"{ "entity": "Team" }"#).unwrap()];
        assert!(
            !validate(&single)
                .iter()
                .any(|q| q.id.starts_with("/storage/buckets/0")),
            "a unique transitive chain is legal: {:?}",
            validate(&single)
        );
    }

    #[test]
    fn bucket_mounts_must_not_collide_with_module_mounts() {
        // WHY: buckets mount at {base_path}/<name> beside the modules — a
        // collision would shadow routes silently at serve time (issue #8). Under
        // the default /storage prefix, a bucket named `avatars` no longer
        // collides with a module at `/orgs`; the collision needs a module mounted
        // at the bucket's actual path (`/storage/avatars`).
        let base = guard_reads(serde_json::from_str(V2_STORAGE).unwrap());
        assert!(
            validate(&base).is_empty(),
            "default /storage prefix keeps buckets clear of the /orgs module: {:?}",
            validate(&base)
        );
        // A module remounted onto the bucket's storage path collides.
        let mut d = base.clone();
        d.modules[0].mount = Some("/storage/avatars".into());
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/storage/buckets/0/name" && q.question.contains("collides")),
            "a module at /storage/avatars collides with the avatars bucket: {:?}",
            validate(&d)
        );
        // A custom base_path recomputes the collision against the new prefix.
        let mut d2: Design = serde_json::from_str(V2_STORAGE).unwrap();
        d2.storage.as_mut().unwrap().base_path = Some("/files".into());
        d2.modules[0].mount = Some("/files/avatars".into());
        assert!(
            validate(&d2)
                .iter()
                .any(|q| q.id == "/storage/buckets/0/name" && q.question.contains("collides")),
            "collision follows the custom base_path: {:?}",
            validate(&d2)
        );
    }

    #[test]
    fn complete_design_yields_no_questions() {
        assert!(validate(&design(MINIMAL)).is_empty());
    }

    /// Inject a `cors` block into MINIMAL (which is otherwise question-free).
    fn with_cors(cors_json: &str) -> Design {
        design(&MINIMAL.replace(
            "\"contract_version\": 0,",
            &format!("\"contract_version\": 0, \"cors\": {cors_json},"),
        ))
    }

    /// A well-formed cors block yields NO questions — a valid cross-origin SPA
    /// policy (issue #21) must validate clean.
    #[test]
    fn well_formed_cors_block_is_question_free() {
        let d = with_cors(
            r#"{ "origins": ["https://app.example", "http://localhost:3000"],
                 "methods": ["GET", "POST"], "headers": ["content-type"],
                 "allow_credentials": true }"#,
        );
        assert!(validate(&d).is_empty(), "{:?}", validate(&d));
        // `*` alone (no credentials) is also valid.
        let any = with_cors(r#"{ "origins": ["*"] }"#);
        assert!(validate(&any).is_empty(), "{:?}", validate(&any));
    }

    /// The CORS footguns become pointed questions, not runtime boot failures:
    /// empty origins, `*` mixed with an allowlist, `*` + credentials (Fetch-spec
    /// forbidden — core's App::build rejects it), and a non-bare origin.
    #[test]
    fn cors_misconfig_yields_pointed_questions() {
        // Empty origins.
        let d = with_cors(r#"{ "origins": [] }"#);
        assert!(
            validate(&d).iter().any(|q| q.id == "/cors/origins"),
            "empty origins must be a question: {:?}",
            validate(&d)
        );
        // `*` mixed with an explicit origin.
        let d = with_cors(r#"{ "origins": ["*", "https://app.example"] }"#);
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/cors/origins" && q.question.contains("mixes")),
            "mixing `*` with explicit origins must be a question: {:?}",
            validate(&d)
        );
        // `*` + credentials — the Fetch-spec violation core rejects at build time.
        let d = with_cors(r#"{ "origins": ["*"], "allow_credentials": true }"#);
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/cors/allow_credentials"),
            "`*` + credentials must be caught at design time: {:?}",
            validate(&d)
        );
        // A non-bare origin (has a path / trailing slash / no scheme).
        for bad in [
            "https://app.example/",
            "app.example",
            "https://app.example/app",
        ] {
            let d = with_cors(&format!(r#"{{ "origins": ["{bad}"] }}"#));
            assert!(
                validate(&d).iter().any(|q| q.id == "/cors/origins/0"),
                "malformed origin `{bad}` must be a question: {:?}",
                validate(&d)
            );
        }
    }

    #[test]
    fn bad_names_yield_pointed_questions_with_json_pointer_ids() {
        let d = design(&MINIMAL.replace("\"name\": \"demo-api\"", "\"name\": \"Demo API\""));
        let qs = validate(&d);
        assert!(
            qs.iter()
                .any(|q| q.id == "/name" && q.question.contains("kebab-case")),
            "{qs:?}"
        );
    }

    #[test]
    fn duplicate_operation_ids_and_routes_are_caught() {
        let d = design(&MINIMAL.replace(
            "\"operation_id\": \"create_todo\"",
            "\"operation_id\": \"list_todos\"",
        ));
        let qs = validate(&d);
        assert!(
            qs.iter()
                .any(|q| q.id.starts_with("/modules/0/endpoints") && q.question.contains("unique"))
        );

        let d2 = design(&MINIMAL.replace(
            "{ \"operation_id\": \"create_todo\", \"method\": \"POST\", \"path\": \"/\",",
            "{ \"operation_id\": \"create_todo\", \"method\": \"GET\", \"path\": \"/\",",
        ));
        let qs2 = validate(&d2);
        assert!(
            qs2.iter()
                .any(|q| q.question.contains("GET /") && q.question.contains("already")),
            "{qs2:?}"
        );
    }

    #[test]
    fn roles_must_be_declared_and_entities_must_exist() {
        let d = design(&MINIMAL.replace(
            "\"required_roles\": [\"admin\"]",
            "\"required_roles\": [\"superuser\"]",
        ));
        let qs = validate(&d);
        assert!(
            qs.iter()
                .any(|q| q.question.contains("superuser") && q.question.contains("auth.roles"))
        );

        let d2 = design(&MINIMAL.replace(
            "\"request_body\": { \"entity\": \"Todo\" }",
            "\"request_body\": { \"entity\": \"Ghost\" }",
        ));
        let qs2 = validate(&d2);
        assert!(qs2.iter().any(|q| q.question.contains("Ghost")));
    }

    #[test]
    fn status_ranges_and_path_shape_are_enforced() {
        // 3xx is a valid success class (redirect endpoints, e.g. OAuth connect).
        let ok3xx = design(&MINIMAL.replace("\"status\": 204", "\"status\": 302"));
        assert!(
            !validate(&ok3xx)
                .iter()
                .any(|q| q.question.contains("success")),
            "302 is a valid (redirect) success status"
        );
        // A 5xx success status is not a success class and must be rejected.
        let d = design(&MINIMAL.replace("\"status\": 204", "\"status\": 500"));
        assert!(validate(&d).iter().any(|q| q.question.contains("2xx/3xx")));
        let d2 = design(&MINIMAL.replace("\"path\": \"/{id}\"", "\"path\": \"{id}\""));
        assert!(
            validate(&d2)
                .iter()
                .any(|q| q.question.contains("start with '/'"))
        );
    }

    #[test]
    fn paths_allow_up_to_three_params_and_validate_mount_prefix() {
        // Two params: now legal (multi-param Path landed in core).
        let d = design(&MINIMAL.replace("\"path\": \"/{id}\"", "\"path\": \"/{id}/tags/{tag}\""));
        assert!(
            !validate(&d)
                .iter()
                .any(|q| q.question.contains("path parameter")),
            "two params must be accepted now"
        );
        // Four params: rejected.
        let d4 = design(&MINIMAL.replace("\"path\": \"/{id}\"", "\"path\": \"/{a}/{b}/{c}/{d}\""));
        assert!(
            validate(&d4)
                .iter()
                .any(|q| q.question.contains("three path parameters"))
        );

        let d2 = design(&MINIMAL.replace(
            "\"name\": \"comments\",",
            "\"name\": \"comments\", \"mount\": \"comments\",",
        ));
        assert!(
            validate(&d2)
                .iter()
                .any(|q| q.id.contains("/mount") && q.question.contains("start with '/'"))
        );

        // A path parameter in a mount prefix is now fully supported: a handler's
        // single Path<T> binds the leaf-most param, tuples address all root→leaf.
        // The validator must NOT discourage it (only the syntax rules apply).
        let d3 = design(&MINIMAL.replace(
            "\"name\": \"comments\",",
            "\"name\": \"comments\", \"mount\": \"/{comment_id}\",",
        ));
        assert!(
            !validate(&d3).iter().any(|q| q.id.contains("/mount")),
            "a param-carrying mount prefix must raise no mount question now: {:?}",
            validate(&d3)
        );
    }

    #[test]
    fn nested_subroute_violations_carry_full_json_pointers() {
        let d = design(&MINIMAL.replace(
            "\"operation_id\": \"list_comments\"",
            "\"operation_id\": \"List-Comments\"",
        ));
        let qs = validate(&d);
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/subroutes/0/endpoints/0/operation_id"),
            "{qs:?}"
        );
    }

    #[test]
    fn unbalanced_path_braces_yield_a_question() {
        let d = design(&MINIMAL.replace("\"path\": \"/{id}\"", "\"path\": \"/{id\""));
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.question.contains("unbalanced braces")),
            "unbalanced braces must be flagged"
        );
    }

    #[test]
    fn json_fields_are_rejected_in_db_mode() {
        // MINIMAL already declares `["db"]`; flip a field to json.
        let d = design(&MINIMAL.replace("\"type\": \"boolean\"", "\"type\": \"json\""));
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.question.contains("json") && q.question.contains("db mode")),
            "db mode can't store json fields yet"
        );
    }

    #[test]
    fn raw_escapable_keyword_field_names_are_accepted() {
        // WHY: `type`/`match`/`ref` are common field names in frozen external
        // wire contracts. Codegen raw-escapes them (`r#type`) with a serde
        // rename, so forcing a rename would push a permanent wire↔storage
        // mapping into every handler. Validation must NOT flag them.
        for kw in ["type", "match", "ref"] {
            let d = design(&MINIMAL.replace("\"name\": \"title\"", &format!("\"name\": \"{kw}\"")));
            assert!(
                !validate(&d)
                    .iter()
                    .any(|q| q.id.contains("/fields/") && q.question.contains("keyword")),
                "keyword field `{kw}` is raw-escapable and must be accepted"
            );
        }
    }

    #[test]
    fn unescapable_keyword_field_names_are_still_rejected() {
        // `self`/`crate`/`super` are keywords no raw identifier can escape
        // (`r#self` is invalid Rust), so a field named one still can't compile.
        for kw in ["self", "crate", "super"] {
            let d = design(&MINIMAL.replace("\"name\": \"title\"", &format!("\"name\": \"{kw}\"")));
            assert!(
                validate(&d)
                    .iter()
                    .any(|q| q.id.contains("/fields/") && q.question.contains("keyword")),
                "unescapable keyword field `{kw}` must be flagged"
            );
        }
    }

    #[test]
    fn required_roles_need_a_role_in_auth_roles_and_auth_model() {
        let mut v: serde_json::Value = serde_json::from_str(MINIMAL).unwrap();
        v["auth"] = serde_json::json!({ "model": "none" });
        v["modules"][0]["endpoints"][2]["required_roles"] = serde_json::json!(["admin"]);
        let d: Design = serde_json::from_value(v).unwrap();
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.question.contains("auth.model") || q.question.contains("auth.roles"))
        );
    }

    #[test]
    fn mount_rejects_trailing_slash_and_double_slash() {
        let d = design(&MINIMAL.replace(
            "\"name\": \"comments\",",
            "\"name\": \"comments\", \"mount\": \"/x/\",",
        ));
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id.contains("/mount") && q.question.contains("trailing slash")),
            "trailing-slash mount must be flagged"
        );
    }

    #[test]
    fn belongs_to_must_target_a_declared_entity() {
        let mut d: Design = serde_json::from_str(V1_FULL).unwrap();
        d.modules[1].entities[0].belongs_to[0].entity = "Ghost".into();
        let qs = validate(&d);
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/1/entities/0/belongs_to/0"
                    && q.question.contains("Ghost")),
            "{qs:?}"
        );
    }

    #[test]
    fn tenancy_entity_must_exist() {
        let mut d: Design = serde_json::from_str(V1_FULL).unwrap();
        d.tenancy.as_mut().unwrap().entity = "Nope".into();
        assert!(validate(&d).iter().any(|q| q.id == "/tenancy/entity"));
    }

    #[test]
    fn tenancy_requires_active_auth() {
        let mut d: Design = serde_json::from_str(V1_FULL).unwrap();
        d.auth = None;
        assert!(validate(&d).iter().any(|q| q.id == "/tenancy"));
    }

    /// #27: a design whose `tenancy.entity` IS the auth identity entity is
    /// otherwise complete (no completeness question), yet cannot scaffold — the
    /// generated `{tenant}_members` table would derive the same fixed `user_id`
    /// column twice. `design_conflict` rejects it up front with JC0540, so the
    /// CLI fails loud before writing a byte instead of dying mid-migration with a
    /// raw SQLite `duplicate column name: user_id`.
    #[test]
    fn tenancy_entity_as_auth_identity_is_a_design_conflict() {
        let fixture = include_str!("../../tests/fixtures/tenant-is-identity.design.json");
        let d: Design = serde_json::from_str(fixture).unwrap();
        // Completeness is clean — the conflict is what the new rule catches.
        assert!(
            validate(&d).is_empty(),
            "fixture must be otherwise complete: {:?}",
            validate(&d)
        );
        let conflict = design_conflict(&d).expect("tenant==identity must be a conflict");
        assert_eq!(conflict.code, "JC0540");
        // Names both fixes: per-user → belongs_to; orgs/teams → a separate entity.
        assert!(
            conflict.message.contains("belongs_to") && conflict.message.contains("tenant entity"),
            "{}",
            conflict.message
        );
        assert!(!conflict.hint.is_empty());
    }

    /// The comparison is derived from the fixed membership `user_id` column, so a
    /// tenancy over a SEPARATE tenant entity (the reference shape) is never
    /// flagged — only the entity whose fk column collides with the identity is.
    #[test]
    fn separate_tenant_entity_is_not_a_conflict() {
        let d: Design = serde_json::from_str(V1_FULL).unwrap();
        assert!(
            design_conflict(&d).is_none(),
            "Workspace tenancy must not be flagged"
        );
        // No tenancy at all: nothing to conflict.
        let plain: Design = serde_json::from_str(MINIMAL).unwrap();
        assert!(design_conflict(&plain).is_none());
    }

    /// #150: an explicit `auth.identity` that names no declared entity is a fatal
    /// conflict (JC0566) — owner-scoping, the #34 server-injected fk, and
    /// public_read all detect ownership by the identity's derived fk column, so an
    /// identity mapping to no entity silently disables owner-scoping everywhere
    /// behind a green `check`. `design_conflict` must refuse it up front.
    #[test]
    fn auth_identity_naming_a_non_entity_is_refused_jc0566() {
        const D: &str = r#"{
            "name": "ghost-api", "contract_version": 1,
            "auth": { "model": "session", "roles": ["admin"], "identity": "Ghost" },
            "dependencies": ["db", "auth"],
            "modules": [{ "name": "accounts",
                "entities": [{ "name": "Account", "fields": [
                    { "name": "email", "type": "string" } ]}],
                "endpoints": [{ "operation_id": "list_accounts", "method": "GET", "path": "/",
                    "auth_required": true,
                    "success": { "status": 200, "entity": "Account", "list": true } }] }]
        }"#;
        let d: Design = serde_json::from_str(D).unwrap();
        let conflict = design_conflict(&d).expect("a non-existent auth.identity must conflict");
        assert_eq!(conflict.code, "JC0566");
        // The message names the missing identity and the derived fk it would resolve to.
        assert!(
            conflict.message.contains("Ghost") && conflict.message.contains("ghost_id"),
            "{}",
            conflict.message
        );
        assert!(!conflict.hint.is_empty());
    }

    /// #150: JC0540 collides the CONFIGURED identity's fk, not the literal
    /// `user_id`. With `auth.identity: "Account"`, a `tenancy.entity: "Account"`
    /// derives `account_id` == the identity fk — the identity entity cannot also be
    /// the tenant org — so it is refused (generalized from the default `user_id`).
    #[test]
    fn auth_identity_colliding_with_tenancy_is_refused_jc0540() {
        const D: &str = r#"{
            "name": "acct-tenant", "contract_version": 1,
            "auth": { "model": "session", "roles": ["admin"], "identity": "Account" },
            "dependencies": ["db", "auth"],
            "tenancy": { "entity": "Account", "member_roles": ["admin"] },
            "modules": [{ "name": "accounts",
                "entities": [{ "name": "Account", "fields": [
                    { "name": "email", "type": "string" } ]}],
                "endpoints": [{ "operation_id": "list_accounts", "method": "GET", "path": "/",
                    "auth_required": true,
                    "success": { "status": 200, "entity": "Account", "list": true } }] }]
        }"#;
        let d: Design = serde_json::from_str(D).unwrap();
        let conflict = design_conflict(&d).expect("identity == tenant must conflict");
        assert_eq!(conflict.code, "JC0540");
        // The message names the DERIVED identity fk (`account_id`), not `user_id`.
        assert!(
            conflict.message.contains("account_id") && !conflict.message.contains("user_id"),
            "{}",
            conflict.message
        );
    }

    /// #150: a valid non-`User` identity (`Account` declared, per-user-owned child
    /// `Note belongs_to Account`, no tenant collision) is CLEAN — the opt-in is
    /// accepted, not refused.
    #[test]
    fn valid_non_user_auth_identity_is_not_a_conflict() {
        const D: &str = r#"{
            "name": "acct-ok", "contract_version": 1,
            "auth": { "model": "session", "roles": ["admin"], "identity": "Account" },
            "dependencies": ["db", "auth"],
            "modules": [
                { "name": "accounts",
                  "entities": [{ "name": "Account", "fields": [
                      { "name": "email", "type": "string" } ]}],
                  "endpoints": [{ "operation_id": "list_accounts", "method": "GET", "path": "/",
                      "auth_required": true,
                      "success": { "status": 200, "entity": "Account", "list": true } }] },
                { "name": "notes",
                  "entities": [{ "name": "Note",
                      "belongs_to": [{ "entity": "Account", "on_delete": "cascade" }],
                      "fields": [{ "name": "title", "type": "string" }] }],
                  "endpoints": [{ "operation_id": "create_note", "method": "POST", "path": "/",
                      "auth_required": true,
                      "request_body": { "entity": "Note" },
                      "success": { "status": 201, "entity": "Note" } }] }
            ]
        }"#;
        let d: Design = serde_json::from_str(D).unwrap();
        assert!(
            design_conflict(&d).is_none(),
            "a valid Account identity must not conflict: {:?}",
            design_conflict(&d).map(|c| c.message)
        );
        // And the completeness pass is clean too (the opt-in is fully wired).
        assert!(
            validate(&d).is_empty(),
            "valid Account-identity design must be complete: {:?}",
            validate(&d)
        );
    }

    /// JC0553 (#141): with tenancy, jerrycan reserves `{tenant}_members` (the
    /// membership table) and `pub struct {Tenant}Member` (the member row type,
    /// issue #107). An entity that resolves to that table, or is named
    /// `{Tenant}Member`, collides with the generated member surface — today a
    /// clean `check` then a raw `table "..._members" already exists`
    /// mid-scaffold. `validate` must refuse it up front, naming the entity, the
    /// tenant, and the reserved name/table.
    #[test]
    fn entity_colliding_with_the_membership_surface_is_refused_with_jc0553() {
        // V1_FULL tenancy is `Workspace` → reserved table `workspace_members`,
        // reserved struct `WorkspaceMember`.
        // (a) An entity NAMED `WorkspaceMember` collides on the struct type AND —
        // via its default table `workspace_members` — the membership table.
        let mut by_name: Design = serde_json::from_str(V1_FULL).unwrap();
        by_name.modules[0].entities.push(
            serde_json::from_str(
                r#"{ "name": "WorkspaceMember", "fields": [{ "name": "note", "type": "string" }] }"#,
            )
            .unwrap(),
        );
        let qs = validate(&by_name);
        let hit = qs
            .iter()
            .find(|q| q.question.contains("JC0553"))
            .unwrap_or_else(|| panic!("WorkspaceMember must trip JC0553: {qs:?}"));
        assert!(
            hit.question.contains("WorkspaceMember")
                && hit.question.contains("`Workspace`")
                && hit.question.contains("workspace_members")
                && hit.question.to_lowercase().contains("rename"),
            "message names the entity, tenant, reserved table, and the rename fix: {}",
            hit.question
        );
        // Points at the entity NAME — the actionable fix location for a name clash.
        assert_eq!(hit.id, "/modules/0/entities/1/name");

        // (b) A differently-NAMED entity whose explicit `table` override IS the
        // membership table collides on the table alone.
        let mut by_table: Design = serde_json::from_str(V1_FULL).unwrap();
        by_table.modules[0].entities.push(
            serde_json::from_str(
                r#"{ "name": "Seat", "table": "workspace_members", "fields": [{ "name": "note", "type": "string" }] }"#,
            )
            .unwrap(),
        );
        let qs = validate(&by_table);
        let hit = qs
            .iter()
            .find(|q| q.question.contains("JC0553"))
            .unwrap_or_else(|| {
                panic!("a table override onto workspace_members must trip JC0553: {qs:?}")
            });
        assert!(
            hit.question.contains("`Seat`") && hit.question.contains("workspace_members"),
            "table-collision message names the entity and the reserved table: {}",
            hit.question
        );
        assert_eq!(hit.id, "/modules/0/entities/1");
    }

    /// The refusal is precise: a non-colliding entity in a tenancy design is
    /// clean, and a `{Tenant}Member`-named entity in a design with NO tenancy is
    /// clean — no membership surface is generated, so nothing is reserved.
    #[test]
    fn membership_collision_check_is_scoped_to_tenancy_and_real_collisions() {
        // (a) A plain, non-colliding entity in the SAME tenancy design: no JC0553.
        let mut ok: Design = serde_json::from_str(V1_FULL).unwrap();
        ok.modules[0].entities.push(
            serde_json::from_str(
                r#"{ "name": "Post", "fields": [{ "name": "title", "type": "string" }] }"#,
            )
            .unwrap(),
        );
        assert!(
            !validate(&ok).iter().any(|q| q.question.contains("JC0553")),
            "a non-colliding entity must not trip JC0553: {:?}",
            validate(&ok)
        );
        // (b) A `WorkspaceMember` entity with NO tenancy: no membership surface is
        // generated, so there is nothing to collide with.
        let mut no_tenancy: Design = serde_json::from_str(V1_FULL).unwrap();
        no_tenancy.tenancy = None;
        no_tenancy.modules[0].entities.push(
            serde_json::from_str(
                r#"{ "name": "WorkspaceMember", "fields": [{ "name": "note", "type": "string" }] }"#,
            )
            .unwrap(),
        );
        assert!(
            !validate(&no_tenancy)
                .iter()
                .any(|q| q.question.contains("JC0553")),
            "no tenancy → no membership table → no collision: {:?}",
            validate(&no_tenancy)
        );
    }

    // ---- #115 (JC0559): composite / multi-column UNIQUE ------------------------

    /// A single-module db design whose `Like` entity declares a composite `unique`
    /// over its two belongs_to fk columns — the primary #115 shape (a like per
    /// (user, post)). Question-free as written: the group is buildable.
    const COMPOSITE_UNIQUE: &str = r#"{
        "name": "likes-api", "contract_version": 1,
        "dependencies": ["db"],
        "modules": [{
            "name": "engagement",
            "entities": [
                { "name": "User", "fields": [{ "name": "email", "type": "string" }] },
                { "name": "Post", "fields": [{ "name": "title", "type": "string" }] },
                { "name": "Like",
                  "belongs_to": [{ "entity": "User" }, { "entity": "Post" }],
                  "unique": [["user_id", "post_id"]],
                  "fields": [{ "name": "reaction", "type": "string" }] }
            ],
            "endpoints": [
                { "operation_id": "create_like", "method": "POST", "path": "/",
                  "request_body": { "entity": "Like" },
                  "success": { "status": 201, "entity": "Like" } }
            ]
        }]
    }"#;

    /// JC0559 (#115): a valid composite `unique` over two belongs_to fk columns
    /// passes clean — the buildable baseline the three refusals are measured
    /// against, and the byte-identity witness (a field column would pass too).
    #[test]
    fn valid_composite_unique_group_over_fk_columns_passes() {
        assert!(
            !validate(&design(COMPOSITE_UNIQUE))
                .iter()
                .any(|q| q.question.contains("JC0559")),
            "a buildable fk-pair composite unique must not trip JC0559: {:?}",
            validate(&design(COMPOSITE_UNIQUE))
        );
    }

    /// A group with fewer than 2 columns is a footgun that duplicates the field
    /// flag — refused, steering to `Field.unique`.
    #[test]
    fn composite_unique_group_under_two_columns_is_refused_with_jc0559() {
        let one_col = COMPOSITE_UNIQUE.replace(r#"[["user_id", "post_id"]]"#, r#"[["user_id"]]"#);
        let qs = validate(&design(&one_col));
        let hit = qs
            .iter()
            .find(|q| q.question.contains("JC0559"))
            .unwrap_or_else(|| panic!("a 1-col group must trip JC0559: {qs:?}"));
        assert!(
            hit.question.contains("fewer than 2 DISTINCT columns")
                && hit.question.contains("unique: true"),
            "message must name the <2-distinct-col rule and the Field.unique remedy: {}",
            hit.question
        );
        assert_eq!(hit.id, "/modules/0/entities/2/unique/0");
    }

    /// A repeated column (`["a", "a"]`) has 2 entries but 1 DISTINCT column, so
    /// `UNIQUE(a, a)` would silently make column `a` globally unique — refused by
    /// the distinct-count gate, not the raw-length one.
    #[test]
    fn composite_unique_group_with_a_repeated_column_is_refused_with_jc0559() {
        let repeated =
            COMPOSITE_UNIQUE.replace(r#"[["user_id", "post_id"]]"#, r#"[["user_id", "user_id"]]"#);
        let qs = validate(&design(&repeated));
        let hit = qs
            .iter()
            .find(|q| q.question.contains("JC0559"))
            .unwrap_or_else(|| panic!("a repeated-column group must trip JC0559: {qs:?}"));
        assert!(
            hit.question.contains("fewer than 2 DISTINCT columns"),
            "message must name the distinct-count rule for a repeated column: {}",
            hit.question
        );
        assert_eq!(hit.id, "/modules/0/entities/2/unique/0");
    }

    /// A column that is neither a declared field nor a belongs_to fk column would
    /// emit a `CREATE UNIQUE INDEX` that fails at apply — refused loud at `check`.
    #[test]
    fn composite_unique_group_with_unknown_column_is_refused_with_jc0559() {
        let bad = COMPOSITE_UNIQUE.replace(
            r#"[["user_id", "post_id"]]"#,
            r#"[["user_id", "widget_id"]]"#,
        );
        let qs = validate(&design(&bad));
        let hit = qs
            .iter()
            .find(|q| q.question.contains("JC0559"))
            .unwrap_or_else(|| panic!("an unknown column must trip JC0559: {qs:?}"));
        assert!(
            hit.question.contains("widget_id") && hit.question.contains("does not exist"),
            "message must name the offending column and the apply-time failure: {}",
            hit.question
        );
    }

    /// A duplicate group (same column set, order-insensitive) is a redundant
    /// index — refused.
    #[test]
    fn composite_unique_duplicate_group_is_refused_with_jc0559() {
        // Two groups over the same column set, columns reversed — order-insensitive.
        let dup = COMPOSITE_UNIQUE.replace(
            r#"[["user_id", "post_id"]]"#,
            r#"[["user_id", "post_id"], ["post_id", "user_id"]]"#,
        );
        let qs = validate(&design(&dup));
        let hit = qs
            .iter()
            .find(|q| q.question.contains("JC0559") && q.question.contains("duplicates"))
            .unwrap_or_else(|| panic!("a duplicate group must trip JC0559: {qs:?}"));
        assert!(
            hit.question.contains("order does not matter"),
            "message must state order-insensitivity: {}",
            hit.question
        );
        assert_eq!(hit.id, "/modules/0/entities/2/unique/1");
    }

    /// Byte-identity floor: an entity with NO composite `unique` raises no JC0559
    /// (the whole check is inert unless a group is declared).
    #[test]
    fn no_composite_unique_raises_no_jc0559() {
        assert!(
            !validate(&design(MINIMAL))
                .iter()
                .any(|q| q.question.contains("JC0559")),
            "a design with no composite unique must never mention JC0559"
        );
    }

    // ---- #187 (JC0564): reserve_against atomic reserve primitive ---------------

    /// A well-formed `reserve_against`: a `used` integer counter bounded by a
    /// SEPARATE `capacity` integer field on a db-backed design. This is the buildable
    /// baseline the seven refusals are measured against — the generated `reserve`
    /// method wires the #108-proven atomic UPDATE from exactly this shape.
    const RESERVE_OK: &str = r#"{
        "name": "reserve-api", "contract_version": 1,
        "dependencies": ["db"],
        "modules": [{
            "name": "venue",
            "entities": [
                { "name": "Booking", "fields": [
                    { "name": "capacity", "type": "integer" },
                    { "name": "used", "type": "integer", "reserve_against": "capacity" }
                ]}
            ],
            "endpoints": [
                { "operation_id": "create_booking", "method": "POST", "path": "/",
                  "request_body": { "entity": "Booking" },
                  "success": { "status": 201, "entity": "Booking" } }
            ]
        }]
    }"#;

    /// The buildable shape passes clean — no JC0564. Also the byte-identity floor:
    /// an entity with no `reserve_against` at all never trips it (MINIMAL below).
    #[test]
    fn well_formed_reserve_against_passes_and_absence_is_inert() {
        assert!(
            !validate(&design(RESERVE_OK))
                .iter()
                .any(|q| q.question.contains("JC0564")),
            "a well-formed reserve_against must not trip JC0564: {:?}",
            validate(&design(RESERVE_OK))
        );
        assert!(
            !validate(&design(MINIMAL))
                .iter()
                .any(|q| q.question.contains("JC0564")),
            "a design with no reserve_against must never mention JC0564"
        );
    }

    /// Helper: mutate RESERVE_OK and return the first JC0564 question, panicking with
    /// the full question list if none fired (the refusal is the whole point).
    fn reserve_refusal(from: &str, to: &str) -> Question {
        let json = RESERVE_OK.replace(from, to);
        let qs = validate(&design(&json));
        qs.into_iter()
            .find(|q| q.question.contains("JC0564"))
            .unwrap_or_else(|| panic!("mutation `{from}` -> `{to}` must trip JC0564"))
    }

    /// (1) `reserve_against` names a field that does not exist on the entity.
    #[test]
    fn reserve_against_nonexistent_capacity_is_refused_with_jc0564() {
        let hit = reserve_refusal(
            r#""reserve_against": "capacity""#,
            r#""reserve_against": "ceiling""#,
        );
        assert!(
            hit.question.contains("is not a field of") && hit.question.contains("ceiling"),
            "message must name the missing capacity field: {}",
            hit.question
        );
    }

    /// (2) the counter field carrying `reserve_against` is not integer.
    #[test]
    fn reserve_against_non_integer_counter_is_refused_with_jc0564() {
        let hit = reserve_refusal(
            r#"{ "name": "used", "type": "integer", "reserve_against": "capacity" }"#,
            r#"{ "name": "used", "type": "string", "reserve_against": "capacity" }"#,
        );
        assert!(
            hit.question.contains("not `integer`") && hit.question.contains("counter"),
            "message must name the non-integer counter rule: {}",
            hit.question
        );
    }

    /// (3) the named capacity field is not integer.
    #[test]
    fn reserve_against_non_integer_capacity_is_refused_with_jc0564() {
        let hit = reserve_refusal(
            r#"{ "name": "capacity", "type": "integer" }"#,
            r#"{ "name": "capacity", "type": "string" }"#,
        );
        assert!(
            hit.question.contains("capacity ceiling must be an integer"),
            "message must name the non-integer capacity rule: {}",
            hit.question
        );
    }

    /// (4a) the counter leg is the primary key `id`.
    #[test]
    fn reserve_against_on_pk_counter_is_refused_with_jc0564() {
        let hit = reserve_refusal(
            r#"{ "name": "used", "type": "integer", "reserve_against": "capacity" }"#,
            r#"{ "name": "id", "type": "integer", "reserve_against": "capacity" }"#,
        );
        assert!(
            hit.question.contains("counter cannot be the primary key"),
            "message must refuse the pk counter: {}",
            hit.question
        );
    }

    /// (4b) the capacity leg is the primary key `id`.
    #[test]
    fn reserve_against_pk_capacity_is_refused_with_jc0564() {
        let hit = reserve_refusal(
            r#""reserve_against": "capacity""#,
            r#""reserve_against": "id""#,
        );
        assert!(
            hit.question
                .contains("capacity ceiling cannot be the primary key"),
            "message must refuse the pk capacity: {}",
            hit.question
        );
    }

    /// (5) a field cannot reserve against itself.
    #[test]
    fn reserve_against_self_reference_is_refused_with_jc0564() {
        let hit = reserve_refusal(
            r#""reserve_against": "capacity""#,
            r#""reserve_against": "used""#,
        );
        assert!(
            hit.question.contains("cannot reserve against itself"),
            "message must refuse the self-reference: {}",
            hit.question
        );
    }

    /// (6) more than one `reserve_against` field on one entity — the generated
    /// `reserve` method name would be ambiguous.
    #[test]
    fn reserve_against_more_than_one_per_entity_is_refused_with_jc0564() {
        let hit = reserve_refusal(
            r#"{ "name": "capacity", "type": "integer" }"#,
            r#"{ "name": "capacity", "type": "integer", "reserve_against": "used" }"#,
        );
        assert!(
            hit.question.contains("at most one"),
            "message must refuse >1 reserve_against per entity: {}",
            hit.question
        );
    }

    /// (7) a memory-only design — the atomic UPDATE is emitted on the SQL repo only.
    #[test]
    fn reserve_against_on_memory_only_design_is_refused_with_jc0564() {
        let hit = reserve_refusal(r#""dependencies": ["db"],"#, r#""dependencies": [],"#);
        assert!(
            hit.question.contains("no database"),
            "message must refuse reserve_against without a database: {}",
            hit.question
        );
    }

    /// (8) a NULLABLE counter (review FIX 2). A `required: false` counter is NULL on
    /// insert, so the guard `used + n <= capacity` is NULL → `reserve` returns
    /// `Ok(false)` forever (silently dead). The counter must be NOT NULL.
    #[test]
    fn reserve_against_nullable_counter_is_refused_with_jc0564() {
        let hit = reserve_refusal(
            r#"{ "name": "used", "type": "integer", "reserve_against": "capacity" }"#,
            r#"{ "name": "used", "type": "integer", "required": false, "reserve_against": "capacity" }"#,
        );
        assert!(
            hit.question.contains("nullable") && hit.question.contains("Ok(false)` forever"),
            "message must refuse a nullable counter and name the silent-dead failure: {}",
            hit.question
        );
    }

    /// (9) a NULLABLE capacity (review FIX 2). A `required: false` capacity is NULL on
    /// insert, so the guard is NULL → `reserve` returns `Ok(false)` forever. The named
    /// capacity field must be NOT NULL.
    #[test]
    fn reserve_against_nullable_capacity_is_refused_with_jc0564() {
        let hit = reserve_refusal(
            r#"{ "name": "capacity", "type": "integer" }"#,
            r#"{ "name": "capacity", "type": "integer", "required": false }"#,
        );
        assert!(
            hit.question.contains("nullable") && hit.question.contains("capacity"),
            "message must refuse a nullable capacity: {}",
            hit.question
        );
    }

    // ---- #119 (JC0560): belongs_to fk alias -----------------------------------

    /// A ledger with two aliased refs to Account (from/to) AND a self-referential
    /// Comment — the whole point of #119. Fk columns from_account_id/to_account_id/
    /// parent_id are all distinct, so it validates clean.
    const FK_ALIAS: &str = r#"{
        "name": "ledger-api", "contract_version": 1,
        "dependencies": ["db"],
        "modules": [{
            "name": "ledger",
            "entities": [
                { "name": "Account", "fields": [{ "name": "name", "type": "string" }] },
                { "name": "Transfer",
                  "belongs_to": [
                      { "entity": "Account", "as": "from_account" },
                      { "entity": "Account", "as": "to_account" }
                  ],
                  "fields": [{ "name": "amount", "type": "integer" }] },
                { "name": "Comment",
                  "belongs_to": [{ "entity": "Comment", "as": "parent" }],
                  "fields": [{ "name": "body", "type": "string" }] }
            ],
            "endpoints": [
                { "operation_id": "create_transfer", "method": "POST", "path": "/transfers",
                  "request_body": { "entity": "Transfer" },
                  "success": { "status": 201, "entity": "Transfer" } }
            ]
        }]
    }"#;

    /// JC0560 (#119): the buildable baseline — two distinct aliases to one entity
    /// and a self-reference pass clean. This is the acceptance witness the refusals
    /// are measured against.
    #[test]
    fn valid_two_ref_and_self_ref_aliases_pass() {
        let qs = validate(&design(FK_ALIAS));
        assert!(
            !qs.iter().any(|q| q.question.contains("JC0560")),
            "a two-ref + self-ref alias design must not trip JC0560: {qs:?}"
        );
    }

    /// Two UN-aliased belongs_to to the same entity both derive `account_id` — a
    /// duplicate Model field + migration column. Refused with the add-`as` fork.
    #[test]
    fn two_unaliased_refs_to_one_entity_are_refused_with_jc0560() {
        let dup = FK_ALIAS.replace(
            r#"{ "entity": "Account", "as": "from_account" },
                      { "entity": "Account", "as": "to_account" }"#,
            r#"{ "entity": "Account" },
                      { "entity": "Account" }"#,
        );
        let qs = validate(&design(&dup));
        let hit = qs
            .iter()
            .find(|q| q.question.contains("JC0560"))
            .unwrap_or_else(|| panic!("two un-aliased refs must trip JC0560: {qs:?}"));
        assert!(
            hit.question.contains("account_id") && hit.question.contains("SAME column"),
            "message must name the colliding column and the add-`as` remedy: {}",
            hit.question
        );
    }

    /// An `as` whose `{as}_id` collides with a DECLARED field is a duplicate column
    /// — refused (the field/fk name space is shared).
    #[test]
    fn alias_colliding_with_a_declared_field_is_refused_with_jc0560() {
        // Add a field `from_account_id` alongside `belongs_to Account as from_account`.
        let clash = FK_ALIAS.replace(
            r#""fields": [{ "name": "amount", "type": "integer" }] }"#,
            r#""fields": [{ "name": "amount", "type": "integer" }, { "name": "from_account_id", "type": "integer" }] }"#,
        );
        let qs = validate(&design(&clash));
        let hit = qs
            .iter()
            .find(|q| q.question.contains("JC0560") && q.question.contains("declared field"))
            .unwrap_or_else(|| panic!("an fk/field collision must trip JC0560: {qs:?}"));
        assert!(
            hit.question.contains("from_account_id"),
            "message must name the colliding column: {}",
            hit.question
        );
    }

    /// A malformed `as` (not snake_case) yields an invalid column/Rust field —
    /// refused before the collision checks even run.
    #[test]
    fn malformed_as_alias_is_refused_with_jc0560() {
        let bad = FK_ALIAS.replace(r#""as": "from_account""#, r#""as": "FromAccount""#);
        let qs = validate(&design(&bad));
        let hit = qs
            .iter()
            .find(|q| q.question.contains("JC0560"))
            .unwrap_or_else(|| panic!("a malformed `as` must trip JC0560: {qs:?}"));
        assert!(
            hit.question.contains("malformed") && hit.question.contains("FromAccount"),
            "message must name the malformed alias and the snake_case rule: {}",
            hit.question
        );
    }

    /// Byte-identity floor: a design with a single un-aliased belongs_to per target
    /// and no `as` raises no JC0560 (the check is inert unless an alias or a
    /// same-entity collision exists).
    #[test]
    fn plain_belongs_to_raises_no_jc0560() {
        assert!(
            !validate(&design(COMPOSITE_UNIQUE))
                .iter()
                .any(|q| q.question.contains("JC0560")),
            "an unaliased belongs_to design must never mention JC0560"
        );
    }

    /// #119 Finding 1: an `as` deriving the reserved identity fk `user_id` on a
    /// target that isn't the identity entity (here `Account`) would hijack per-user
    /// scoping and fail as opaque generated Rust — refused at design time.
    #[test]
    fn alias_landing_on_the_identity_fk_is_refused_with_jc0560() {
        const D: &str = r#"{
            "name": "chat-api", "contract_version": 1,
            "dependencies": ["db", "auth"],
            "auth": { "model": "session" },
            "modules": [{
                "name": "messages",
                "entities": [
                    { "name": "Account", "fields": [{ "name": "name", "type": "string" }] },
                    { "name": "Message",
                      "belongs_to": [{ "entity": "Account", "as": "user" }],
                      "fields": [{ "name": "body", "type": "string" }] }
                ],
                "endpoints": [
                    { "operation_id": "create_message", "method": "POST", "path": "/messages",
                      "request_body": { "entity": "Message" },
                      "success": { "status": 201, "entity": "Message" } }
                ]
            }]
        }"#;
        let qs = validate(&design(D));
        let hit = qs
            .iter()
            .find(|q| q.question.contains("JC0560") && q.question.contains("identity fk"))
            .unwrap_or_else(|| {
                panic!("`as: user` on a non-identity target must trip JC0560: {qs:?}")
            });
        assert!(
            hit.question.contains("user_id"),
            "message must name the reserved identity fk: {}",
            hit.question
        );
    }

    /// #119 Finding 1: an `as` deriving the reserved tenancy fk on a non-tenant
    /// target would break tenant scoping — refused at design time.
    #[test]
    fn alias_landing_on_the_tenancy_fk_is_refused_with_jc0560() {
        const D: &str = r#"{
            "name": "org-api", "contract_version": 1,
            "dependencies": ["db", "auth"],
            "auth": { "model": "session", "roles": ["owner"] },
            "tenancy": { "entity": "Workspace", "member_roles": ["owner"] },
            "modules": [{
                "name": "workspaces",
                "entities": [
                    { "name": "Workspace", "fields": [{ "name": "name", "type": "string" }] },
                    { "name": "Vendor", "fields": [{ "name": "name", "type": "string" }] },
                    { "name": "Note",
                      "belongs_to": [{ "entity": "Vendor", "as": "workspace" }],
                      "fields": [{ "name": "body", "type": "string" }] }
                ],
                "endpoints": [
                    { "operation_id": "create_workspace", "method": "POST", "path": "/",
                      "auth_required": true,
                      "request_body": { "entity": "Workspace" },
                      "success": { "status": 201, "entity": "Workspace" } }
                ]
            }]
        }"#;
        let qs = validate(&design(D));
        assert!(
            qs.iter()
                .any(|q| q.question.contains("JC0560") && q.question.contains("tenancy fk")),
            "`as: workspace` (the tenancy fk) on a non-tenant target must trip JC0560: {qs:?}"
        );
    }

    // ---- #107 (JC0548): tenancy member_roles content ---------------------------

    /// JC0548 (#107): `member_roles[0]` is the admin role the generated member
    /// surface gates on, and every role is interpolated UNESCAPED into generated
    /// Rust string literals — so with tenancy the list must be non-empty,
    /// duplicate-free, and identifier-shaped (JC0543's charset). Each failure
    /// mode gets its own message naming the offender; without the check, an
    /// empty list silently demotes the admin convention to a fallback role and a
    /// quoted role emits a crate that fails to compile far from the design.
    #[test]
    fn tenancy_member_roles_must_be_nonempty_unique_identifiers() {
        let base: Design = serde_json::from_str(V1_FULL).unwrap();
        // Empty: the admin-role convention has nothing to stand on.
        let mut empty = base.clone();
        empty.tenancy.as_mut().unwrap().member_roles = vec![];
        let c = design_conflict(&empty).expect("empty member_roles must be a conflict");
        assert_eq!(c.code, "JC0548");
        assert!(
            c.message.contains("empty") && c.message.contains("admin"),
            "empty message names the failure and the admin convention: {}",
            c.message
        );
        assert!(!c.hint.is_empty());
        // Duplicate: names the repeated role.
        let mut dup = base.clone();
        dup.tenancy.as_mut().unwrap().member_roles =
            vec!["owner".into(), "member".into(), "owner".into()];
        let c = design_conflict(&dup).expect("duplicated member_roles must be a conflict");
        assert_eq!(c.code, "JC0548");
        assert!(
            c.message.contains("`owner`") && c.message.contains("more than once"),
            "duplicate message names the repeated role: {}",
            c.message
        );
        // Charset: a quote breaks the unescaped interpolation into generated Rust
        // (the same rule JC0543 enforces for enum values); names the offender.
        let mut bad = base.clone();
        bad.tenancy.as_mut().unwrap().member_roles = vec!["owner".into(), "ow\"ner".into()];
        let c = design_conflict(&bad).expect("non-identifier role must be a conflict");
        assert_eq!(c.code, "JC0548");
        assert!(
            c.message.contains("ow\"ner") && c.message.contains("[A-Za-z0-9_-]"),
            "charset message names the offending role and the rule: {}",
            c.message
        );
        // Identifier-shaped, duplicate-free lists pass — including the shipped
        // tenancy conformance design.
        assert!(design_conflict(&base).is_none(), "valid roles must pass");
        let mut hyphen = base.clone();
        hyphen.tenancy.as_mut().unwrap().member_roles =
            vec!["team-lead".into(), "read_only".into(), "Member2".into()];
        assert!(
            design_conflict(&hyphen).is_none(),
            "`-`/`_`/mixed-case roles are identifier-shaped: {:?}",
            design_conflict(&hyphen).map(|c| c.message)
        );
        let reference: Design = serde_json::from_str(CONFORMANCE_REFERENCE).unwrap();
        assert!(
            design_conflict(&reference).is_none(),
            "conformance member_roles must not trip JC0548: {:?}",
            design_conflict(&reference).map(|c| c.message)
        );
    }

    /// Issue #44 (positive): an entity literally named `{X}Request` alongside an
    /// entity `X` whose guarded body omits the identity fk generates two `XRequest`
    /// definitions (Rust struct + OpenAPI component). `design_conflict` rejects it up
    /// front with JC0541 and names the rename fix — cheap insurance for agent-authored
    /// designs, since genroute would otherwise die with a duplicate-struct compile
    /// error mid-scaffold.
    #[test]
    fn entity_shadowing_a_generated_request_dto_is_a_conflict() {
        // Collection (db + auth + identity fk) mints a `CollectionRequest` DTO; an
        // entity literally named `CollectionRequest` collides with it.
        let d: Design = serde_json::from_str(
            r#"{
            "name": "clash", "contract_version": 1,
            "auth": { "model": "session", "roles": ["admin"] },
            "dependencies": ["db", "auth"],
            "modules": [{
                "name": "collections",
                "entities": [
                    { "name": "User", "fields": [{ "name": "email", "type": "string" }] },
                    { "name": "Collection",
                      "belongs_to": [{ "entity": "User", "on_delete": "cascade" }],
                      "fields": [{ "name": "title", "type": "string" }] },
                    { "name": "CollectionRequest", "fields": [{ "name": "note", "type": "string" }] }
                ],
                "endpoints": [
                    { "operation_id": "create_collection", "method": "POST", "path": "/",
                      "auth_required": true,
                      "request_body": { "entity": "Collection" },
                      "success": { "status": 201, "entity": "Collection" } }
                ]
            }]
        }"#,
        )
        .unwrap();
        let conflict = design_conflict(&d).expect("XRequest shadowing a DTO must be a conflict");
        assert_eq!(conflict.code, "JC0541");
        assert!(
            conflict.message.contains("CollectionRequest")
                && conflict.message.contains("Collection")
                && conflict.message.to_lowercase().contains("rename"),
            "message names the collision and the rename fix: {}",
            conflict.message
        );
        assert!(conflict.hint.contains("rename"), "{}", conflict.hint);
    }

    /// Issue #44 (negative): the lint fires ONLY on a REAL collision, not on any
    /// `*Request` suffix. (a) A `{X}Request` entity whose `X` sibling generates NO DTO
    /// (memory mode, no omission) is fine — nothing is shadowed. (b) A `*Request`
    /// entity with no matching base entity is fine. (c) A base `X` that mints a DTO
    /// but has no `XRequest` sibling is fine.
    #[test]
    fn request_suffix_without_a_real_collision_is_not_flagged() {
        // (a) Same names, but MEMORY mode → Collection mints no DTO → no collision.
        let mem: Design = serde_json::from_str(
            r#"{
            "name": "ok-mem", "contract_version": 1,
            "auth": { "model": "session", "roles": ["admin"] },
            "dependencies": ["auth"],
            "modules": [{
                "name": "collections",
                "entities": [
                    { "name": "User", "fields": [{ "name": "email", "type": "string" }] },
                    { "name": "Collection",
                      "belongs_to": [{ "entity": "User", "on_delete": "cascade" }],
                      "fields": [{ "name": "title", "type": "string" }] },
                    { "name": "CollectionRequest", "fields": [{ "name": "note", "type": "string" }] }
                ],
                "endpoints": [
                    { "operation_id": "create_collection", "method": "POST", "path": "/",
                      "auth_required": true,
                      "request_body": { "entity": "Collection" },
                      "success": { "status": 201, "entity": "Collection" } }
                ]
            }]
        }"#,
        )
        .unwrap();
        assert!(
            design_conflict(&mem).is_none(),
            "memory mode mints no DTO — no collision"
        );
        // (b) A lone `*Request` entity with no matching base entity is fine.
        let orphan: Design = serde_json::from_str(
            r#"{
            "name": "ok-orphan", "contract_version": 1, "dependencies": ["db"],
            "modules": [{
                "name": "audit",
                "entities": [
                    { "name": "AuditRequest", "fields": [{ "name": "note", "type": "string" }] }
                ],
                "endpoints": [
                    { "operation_id": "create_audit", "method": "POST", "path": "/",
                      "request_body": { "entity": "AuditRequest" },
                      "success": { "status": 201, "entity": "AuditRequest" } }
                ]
            }]
        }"#,
        )
        .unwrap();
        assert!(
            design_conflict(&orphan).is_none(),
            "a `*Request` name shadowing nothing is fine"
        );
        // (c) A base that mints a DTO but has no `XRequest` sibling is fine.
        let d: Design = serde_json::from_str(SERVER_FK_LITE).unwrap();
        assert!(
            design_conflict(&d).is_none(),
            "a generated DTO with no shadowing entity is fine"
        );
    }

    /// A minimal db+auth+identity-fk design (Collection mints CollectionRequest) with
    /// NO shadowing entity — the JC0541 negative control.
    const SERVER_FK_LITE: &str = r#"{
        "name": "lite", "contract_version": 1,
        "auth": { "model": "session", "roles": ["admin"] },
        "dependencies": ["db", "auth"],
        "modules": [{
            "name": "collections",
            "entities": [
                { "name": "User", "fields": [{ "name": "email", "type": "string" }] },
                { "name": "Collection",
                  "belongs_to": [{ "entity": "User", "on_delete": "cascade" }],
                  "fields": [{ "name": "title", "type": "string" }] }
            ],
            "endpoints": [
                { "operation_id": "create_collection", "method": "POST", "path": "/",
                  "auth_required": true,
                  "request_body": { "entity": "Collection" },
                  "success": { "status": 201, "entity": "Collection" } }
            ]
        }]
    }"#;

    /// Issue #122 (JC0561 name collision, Finding 1): an inline-DTO body reopens the
    /// JC0541 collision class. An entity `Checkout` with a `default` field mints a
    /// `CheckoutRequest` DTO (Rust struct + OpenAPI component); an inline body on
    /// `operation_id: "checkout"` ALSO mints `CheckoutRequest` — a same-module E0428
    /// duplicate struct AND a clobbered OpenAPI schema, otherwise behind a green
    /// `check`. `design_conflict` must refuse it up front with JC0561.
    #[test]
    fn inline_dto_name_colliding_with_an_entity_dto_is_a_conflict() {
        let d: Design = serde_json::from_str(
            r#"{
            "name": "shop", "contract_version": 1, "dependencies": ["db"],
            "modules": [{
                "name": "shop",
                "entities": [
                    { "name": "Checkout", "fields": [
                        { "name": "note", "type": "string" },
                        { "name": "confirmed", "type": "boolean", "default": false } ] }
                ],
                "endpoints": [
                    { "operation_id": "create_checkout", "method": "POST", "path": "/",
                      "request_body": { "entity": "Checkout" },
                      "success": { "status": 201, "entity": "Checkout" } },
                    { "operation_id": "checkout", "method": "POST", "path": "/run",
                      "request_body": { "fields": [ { "name": "amount", "type": "integer" } ] },
                      "success": { "status": 200 } }
                ]
            }]
        }"#,
        )
        .unwrap();
        // Sanity: the entity really does mint the DTO the inline name will clash with.
        assert!(
            d.entity_generates_request_dto("Checkout"),
            "fixture must mint CheckoutRequest for the collision to be real"
        );
        let c = design_conflict(&d)
            .expect("inline `checkout` clashing with CheckoutRequest DTO conflicts");
        assert_eq!(c.code, "JC0561");
        assert!(
            c.message.contains("CheckoutRequest")
                && c.message.contains("checkout")
                && c.message.contains("Checkout"),
            "message names the collision and both sides: {}",
            c.message
        );
    }

    /// Issue #122 (JC0561 name collision, Finding 2): `operation_id` is unique only
    /// PER-MODULE, but OpenAPI `components/schemas` is one GLOBAL map. Two modules
    /// each with an inline `operation_id: "checkout"` both register `CheckoutRequest`
    /// — the second clobbers the first, pointing one endpoint's requestBody at the
    /// wrong shape, behind a green `check`. `design_conflict` must refuse cross-module.
    #[test]
    fn two_inline_dtos_with_the_same_name_cross_module_is_a_conflict() {
        let d: Design = serde_json::from_str(
            r#"{
            "name": "shop", "contract_version": 1, "dependencies": ["db"],
            "modules": [
                { "name": "storefront",
                  "endpoints": [
                    { "operation_id": "checkout", "method": "POST", "path": "/pay",
                      "request_body": { "fields": [ { "name": "amount", "type": "integer" } ] },
                      "success": { "status": 200 } }
                  ] },
                { "name": "kiosk",
                  "endpoints": [
                    { "operation_id": "checkout", "method": "POST", "path": "/buy",
                      "request_body": { "fields": [ { "name": "total", "type": "integer" } ] },
                      "success": { "status": 200 } }
                  ] }
            ]
        }"#,
        )
        .unwrap();
        let c = design_conflict(&d)
            .expect("two modules' inline `checkout` DTOs clash on the global schema map");
        assert_eq!(c.code, "JC0561");
        assert!(
            c.message.contains("CheckoutRequest")
                && c.message.contains("storefront")
                && c.message.contains("kiosk"),
            "message names the shared name and both modules: {}",
            c.message
        );
    }

    /// Issue #122 (JC0561 name collision, negative): the guard fires ONLY on a REAL
    /// clash. (a) A lone valid inline body (constrained + optional field) mints a
    /// unique `CheckoutRequest` — fine. (b) An entity whose NAME an inline body's
    /// Pascal shares, but which mints NO DTO (memory mode), collides with nothing —
    /// the entity is `Checkout` (model), the inline is `CheckoutRequest` (distinct).
    #[test]
    fn inline_dto_name_without_a_real_collision_is_not_flagged() {
        // (a) A single well-formed inline body — no other DTO with that name.
        let ok: Design = serde_json::from_str(
            r#"{
            "name": "shop", "contract_version": 1, "dependencies": ["db"],
            "modules": [{
                "name": "checkout",
                "endpoints": [
                    { "operation_id": "checkout", "method": "POST", "path": "/",
                      "request_body": { "fields": [
                        { "name": "amount", "type": "integer", "min": 1 },
                        { "name": "note", "type": "string", "required": false } ] },
                      "success": { "status": 200 } }
                ]
            }]
        }"#,
        )
        .unwrap();
        assert!(
            design_conflict(&ok).is_none(),
            "a lone valid inline body must pass: {:?}",
            design_conflict(&ok).map(|c| c.message)
        );
        // (b) Entity `Checkout` in MEMORY mode mints no `CheckoutRequest` DTO, so the
        //     inline `CheckoutRequest` shadows nothing (entity model name is `Checkout`).
        let mem: Design = serde_json::from_str(
            r#"{
            "name": "shop", "contract_version": 1, "dependencies": [],
            "modules": [{
                "name": "shop",
                "entities": [
                    { "name": "Checkout", "fields": [
                        { "name": "confirmed", "type": "boolean", "default": false } ] }
                ],
                "endpoints": [
                    { "operation_id": "checkout", "method": "POST", "path": "/run",
                      "request_body": { "fields": [ { "name": "amount", "type": "integer" } ] },
                      "success": { "status": 200 } }
                ]
            }]
        }"#,
        )
        .unwrap();
        assert!(
            !mem.entity_generates_request_dto("Checkout"),
            "memory mode mints no DTO"
        );
        assert!(
            design_conflict(&mem).is_none(),
            "memory-mode entity name sharing the inline Pascal but minting no DTO is fine: {:?}",
            design_conflict(&mem).map(|c| c.message)
        );
    }

    // ---- #105 (JC0549): public-read/owner-write shape --------------------------

    /// A complete, valid public-read/owner-write design (#105): identity-owned
    /// `Post` opted into `public_read`, unguarded GETs (the public reads), and
    /// guarded writes. Entity order puts `Post` first so the bodyless DELETE's
    /// repo-entity fallback resolves to it, mirroring genroute.
    const PUBLIC_READ_FEED: &str = r#"{
        "name": "feed", "contract_version": 1,
        "auth": { "model": "session", "roles": ["admin"] },
        "dependencies": ["db", "auth"],
        "modules": [{
            "name": "posts",
            "entities": [
                { "name": "Post", "public_read": true,
                  "belongs_to": [{ "entity": "User", "on_delete": "cascade" }],
                  "fields": [{ "name": "title", "type": "string" }] },
                { "name": "User", "fields": [{ "name": "email", "type": "string" }] }
            ],
            "endpoints": [
                { "operation_id": "list_posts", "method": "GET", "path": "/",
                  "success": { "status": 200, "entity": "Post", "list": true } },
                { "operation_id": "get_post", "method": "GET", "path": "/{id}",
                  "success": { "status": 200, "entity": "Post" } },
                { "operation_id": "create_post", "method": "POST", "path": "/",
                  "auth_required": true,
                  "request_body": { "entity": "Post" },
                  "success": { "status": 201, "entity": "Post" } },
                { "operation_id": "update_post", "method": "PUT", "path": "/{id}",
                  "auth_required": true,
                  "request_body": { "entity": "Post" },
                  "success": { "status": 200, "entity": "Post" } },
                { "operation_id": "delete_post", "method": "DELETE", "path": "/{id}",
                  "auth_required": true,
                  "success": { "status": 204 } }
            ]
        }]
    }"#;

    fn jc0549(qs: &[Question]) -> Vec<&Question> {
        qs.iter()
            .filter(|q| q.question.contains("JC0549"))
            .collect()
    }

    /// #105 (positive): the blessed shape — public_read on an identity-owned,
    /// non-tenant entity in an auth design, with unguarded GETs and guarded
    /// writes — is exactly what the flag exists for, so it must sail through
    /// validation untouched.
    #[test]
    fn public_read_per_user_design_passes_validation() {
        let d: Design = serde_json::from_str(PUBLIC_READ_FEED).unwrap();
        let qs = validate(&d);
        assert!(
            qs.is_empty(),
            "a valid public_read design must pass: {qs:?}"
        );
        assert!(
            design_conflict(&d).is_none(),
            "no structural conflict either"
        );
    }

    /// #105: public_read on a tenant-owned entity would let its public reads
    /// bypass the Tenant guard (one tenant's rows exposed to anyone) — refused,
    /// mirroring the public-endpoint-on-tenant-owned rejection.
    #[test]
    fn public_read_on_tenant_owned_entity_is_rejected() {
        let mut d: Design = serde_json::from_str(PUBLIC_READ_FEED).unwrap();
        d.tenancy = Some(
            serde_json::from_str(r#"{ "entity": "Org", "member_roles": ["owner"] }"#).unwrap(),
        );
        d.modules[0].entities.push(
            serde_json::from_str(
                r#"{ "name": "Org", "fields": [{ "name": "label", "type": "string" }] }"#,
            )
            .unwrap(),
        );
        d.modules[0].entities[0]
            .belongs_to
            .push(serde_json::from_str(r#"{ "entity": "Org" }"#).unwrap());
        let qs = validate(&d);
        let hits = jc0549(&qs);
        assert!(
            hits.iter()
                .any(|q| q.question.contains("tenant-owned") && q.question.contains("Post")),
            "tenant-owned public_read must raise JC0549 naming the entity: {qs:?}"
        );
    }

    /// #105: public_read is a modifier on the per-user ownership shape — an
    /// entity with no identity fk has no owner to scope writes to, so the flag
    /// is meaningless and refused with the belongs_to fix.
    #[test]
    fn public_read_on_non_identity_entity_is_rejected() {
        let mut d: Design = serde_json::from_str(PUBLIC_READ_FEED).unwrap();
        d.modules[0].entities[0].belongs_to.clear();
        let qs = validate(&d);
        let hits = jc0549(&qs);
        assert!(
            hits.iter()
                .any(|q| q.question.contains("identity fk") && q.question.contains("Post")),
            "public_read without an identity fk must raise JC0549: {qs:?}"
        );
    }

    /// #105: without an active auth model there is no session to owner-gate the
    /// writes with — public_read would be public-read/public-write.
    #[test]
    fn public_read_without_auth_model_is_rejected() {
        let mut d: Design = serde_json::from_str(PUBLIC_READ_FEED).unwrap();
        d.auth = None;
        d.dependencies.retain(|dep| dep != "auth");
        let qs = validate(&d);
        let hits = jc0549(&qs);
        assert!(
            hits.iter()
                .any(|q| q.question.contains("no active auth model")),
            "public_read without auth must raise JC0549: {qs:?}"
        );
    }

    /// #105: the open door. public_read makes READS public; a write that is
    /// itself public or unguarded would let anyone mutate the rows everyone
    /// reads — every write of the entity must stay owner-gated.
    #[test]
    fn public_or_unguarded_write_on_public_read_entity_is_rejected() {
        // (a) an explicit `public: true` write.
        let mut d: Design = serde_json::from_str(PUBLIC_READ_FEED).unwrap();
        let create = d.modules[0]
            .endpoints
            .iter_mut()
            .find(|ep| ep.operation_id == "create_post")
            .unwrap();
        create.auth_required = false;
        create.public = true;
        let qs = validate(&d);
        assert!(
            jc0549(&qs)
                .iter()
                .any(|q| q.question.contains("create_post") && q.question.contains("write")),
            "a public write on a public_read entity must raise JC0549: {qs:?}"
        );
        // (b) a merely unguarded write (no auth_required, not public).
        let mut d2: Design = serde_json::from_str(PUBLIC_READ_FEED).unwrap();
        d2.modules[0]
            .endpoints
            .iter_mut()
            .find(|ep| ep.operation_id == "delete_post")
            .unwrap()
            .auth_required = false;
        let qs2 = validate(&d2);
        assert!(
            jc0549(&qs2)
                .iter()
                .any(|q| q.question.contains("delete_post")),
            "an unguarded write on a public_read entity must raise JC0549: {qs2:?}"
        );
    }

    /// #143: the write-leg under-match. When the public_read entity is NOT the
    /// module's first entity, a bodyless `DELETE /{id}` (204, no body, no success
    /// entity) resolves via the LENIENT first-entity fallback to the OTHER entity
    /// (here `User`, not public_read) — so the old write-leg saw a non-public_read
    /// entity and shipped GREEN with an unimplementable public-write stub. The
    /// STRICT #56 collection-creator resolution ties the DELETE to `Post` (the
    /// `POST /` creator's body entity), which IS public_read, so firing on EITHER
    /// resolution now raises JC0549(b) naming `Post`. Reordering alone (write still
    /// guarded) must stay clean — the refusal is caused by the unguarded write.
    #[test]
    fn public_unguarded_write_on_a_non_first_public_read_entity_is_rejected() {
        // Baseline: the public_read entity SECOND, every write guarded — clean.
        let mut base: Design = serde_json::from_str(PUBLIC_READ_FEED).unwrap();
        base.modules[0].entities.swap(0, 1); // [User, Post] — Post (public_read) second
        assert!(
            validate(&base).is_empty(),
            "reordering entities alone must stay clean: {:?}",
            validate(&base)
        );

        // Unguard the bodyless DELETE: the lenient fallback lands on `User`
        // (non-public_read, first), the strict #56 resolution on `Post`.
        let mut d = base.clone();
        d.modules[0]
            .endpoints
            .iter_mut()
            .find(|ep| ep.operation_id == "delete_post")
            .unwrap()
            .auth_required = false;
        let qs = validate(&d);
        assert!(
            jc0549(&qs)
                .iter()
                .any(|q| q.question.contains("delete_post") && q.question.contains("`Post`")),
            "an unguarded write whose STRICT resolution is the non-first public_read entity must raise JC0549(b) naming Post: {qs:?}"
        );
    }

    // ---- #175 (JC0562): mixed-shape tenant entity refusal ----------------------

    fn jc0562(qs: &[Question]) -> Vec<&Question> {
        qs.iter()
            .filter(|q| q.question.contains("JC0562"))
            .collect()
    }

    /// A tenant-owned `Lead` reachable by BOTH a FLAT read (`GET /`, membership-set)
    /// AND a PATH-SCOPED read (`GET /{workspace_id}/all`, tenant fk in path). Both
    /// endpoints resolve to `Lead`; the two shapes give `entity_tenant_shapes` →
    /// `(saw_path, saw_flat)` both true.
    const MIXED_SHAPE: &str = r#"{
        "name": "crm", "contract_version": 1,
        "auth": { "model": "session", "roles": ["owner", "member"] },
        "dependencies": ["db", "auth"],
        "tenancy": { "entity": "Workspace", "member_roles": ["owner", "member"] },
        "modules": [
            { "name": "workspaces",
              "entities": [{ "name": "Workspace", "fields": [{ "name": "name", "type": "string" }] }],
              "endpoints": [
                  { "operation_id": "list_workspaces", "method": "GET", "path": "/",
                    "auth_required": true,
                    "success": { "status": 200, "entity": "Workspace", "list": true } } ] },
            { "name": "leads",
              "entities": [{ "name": "Lead",
                  "belongs_to": [{ "entity": "Workspace", "on_delete": "cascade" }],
                  "fields": [{ "name": "title", "type": "string" }] }],
              "endpoints": [
                  { "operation_id": "list_leads_flat", "method": "GET", "path": "/",
                    "auth_required": true,
                    "success": { "status": 200, "entity": "Lead", "list": true } },
                  { "operation_id": "list_leads_scoped", "method": "GET", "path": "/{workspace_id}/all",
                    "auth_required": true,
                    "success": { "status": 200, "entity": "Lead", "list": true } }
              ] }
        ]
    }"#;

    /// #175: a mixed-shape entity. The generator emits only ONE scoping shape —
    /// `entity_is_flat_tenant_owned` is `!saw_path && saw_flat`, so seeing a
    /// path-scoped route classifies `Lead` NON-flat and withholds its
    /// `*_for_memberships` accessors, yet the flat-write steer would still call
    /// them (method-not-found behind a green `check`, the #116 class). JC0562
    /// refuses it, naming the entity.
    #[test]
    fn mixed_shape_tenant_entity_is_rejected() {
        let d: Design = serde_json::from_str(MIXED_SHAPE).unwrap();
        let qs = validate(&d);
        assert!(
            jc0562(&qs).iter().any(|q| q.question.contains("`Lead`")),
            "a flat-AND-path-scoped tenant entity must raise JC0562 naming Lead: {qs:?}"
        );
    }

    /// A PURE-FLAT tenant entity (every route membership-set) is the blessed flat
    /// shape — JC0562 must stay silent (byte-identity baseline).
    #[test]
    fn pure_flat_tenant_entity_does_not_trip_jc0562() {
        let mut d: Design = serde_json::from_str(MIXED_SHAPE).unwrap();
        d.modules[1]
            .endpoints
            .retain(|ep| ep.operation_id != "list_leads_scoped");
        let qs = validate(&d);
        assert!(
            jc0562(&qs).is_empty(),
            "a pure-flat tenant entity must not trip JC0562: {qs:?}"
        );
    }

    /// A PURE-PATH-SCOPED tenant entity (every route carries the tenant fk) is the
    /// nested shape — JC0562 must stay silent (byte-identity baseline).
    #[test]
    fn pure_path_scoped_tenant_entity_does_not_trip_jc0562() {
        let mut d: Design = serde_json::from_str(MIXED_SHAPE).unwrap();
        d.modules[1]
            .endpoints
            .retain(|ep| ep.operation_id != "list_leads_flat");
        let qs = validate(&d);
        assert!(
            jc0562(&qs).is_empty(),
            "a pure-path-scoped tenant entity must not trip JC0562: {qs:?}"
        );
    }

    /// #105 §E (the latent-bug closure, independent of opt-in): an unguarded GET
    /// on a per-user owner-scoped entity that has NOT opted into public_read
    /// generates an unimplementable stub today — the repo emits only owner-scoped
    /// accessors while the handler gets no session user. JC0549 turns the silent
    /// dead-end into a clear fork: opt into public_read, or guard the GET.
    #[test]
    fn unguarded_get_on_owner_scoped_entity_without_public_read_is_rejected() {
        let mut d: Design = serde_json::from_str(PUBLIC_READ_FEED).unwrap();
        d.modules[0].entities[0].public_read = false;
        let qs = validate(&d);
        let hits = jc0549(&qs);
        assert_eq!(
            hits.len(),
            2,
            "both unguarded GETs (list + detail) must be flagged: {qs:?}"
        );
        assert!(
            hits.iter().all(|q| q.question.contains("unimplementable")
                && q.question.contains("public_read: true")
                && q.question.contains("auth_required: true")),
            "the message must present the fork (opt in, or guard the GET): {qs:?}"
        );

        // Memory mode keeps the unscoped repo reads, so the stub IS
        // implementable there — no JC0549.
        let mut mem: Design = serde_json::from_str(PUBLIC_READ_FEED).unwrap();
        mem.modules[0].entities[0].public_read = false;
        mem.dependencies.retain(|dep| dep != "db");
        assert!(
            jc0549(&validate(&mem)).is_empty(),
            "memory mode has no owner-scoped repo suppression"
        );
    }

    /// #105 §E, the `public: true` spelling of the same residual (the shape the
    /// Supabase migrator used to emit for a public-read owner table): `public`
    /// is just an unguarded read with the lint carve-out, and its stub is
    /// exactly as unimplementable — the old `!ep.public` exemption let it slide
    /// through validation into a dead-end scaffold. Only the `public_read`
    /// entity flag makes an open read coherent; WITH the flag the same
    /// public-marked GETs are the blessed migrated-feed shape.
    #[test]
    fn public_get_on_owner_scoped_entity_without_public_read_is_rejected() {
        let mut d: Design = serde_json::from_str(PUBLIC_READ_FEED).unwrap();
        d.modules[0].entities[0].public_read = false;
        for ep in &mut d.modules[0].endpoints {
            if matches!(ep.method, HttpMethod::GET) {
                ep.public = true;
            }
        }
        let qs = validate(&d);
        let hits = jc0549(&qs);
        assert_eq!(
            hits.len(),
            2,
            "both public GETs (list + detail) must be flagged: {qs:?}"
        );

        let mut ok: Design = serde_json::from_str(PUBLIC_READ_FEED).unwrap();
        for ep in &mut ok.modules[0].endpoints {
            if matches!(ep.method, HttpMethod::GET) {
                ep.public = true;
            }
        }
        let qs2 = validate(&ok);
        assert!(
            qs2.is_empty(),
            "public GETs + the public_read flag is the migrated feed shape: {qs2:?}"
        );
    }

    // ---- #148 (JC0558): anonymous read/write on tenant / tenant-owned ----------

    fn jc0558(qs: &[Question]) -> Vec<&Question> {
        qs.iter()
            .filter(|q| q.question.contains("JC0558"))
            .collect()
    }

    /// A SAFE tenancy design: a tenant root (`Club`) and a tenant-owned child
    /// (`Event` belongs_to Club), every read authenticated. It must validate
    /// question-free — that is the byte-identity baseline JC0558 preserves.
    const JC0558_BASE: &str = r#"{
        "name": "clubs", "contract_version": 1,
        "auth": { "model": "session", "roles": ["owner", "member"] },
        "dependencies": ["db", "auth"],
        "tenancy": { "entity": "Club", "member_roles": ["owner", "member"] },
        "modules": [
            { "name": "clubs",
              "entities": [{ "name": "Club", "fields": [
                  { "name": "id", "type": "integer" },
                  { "name": "name", "type": "string" } ]}],
              "endpoints": [
                  { "operation_id": "list_clubs", "method": "GET", "path": "/",
                    "auth_required": true,
                    "success": { "status": 200, "entity": "Club", "list": true } },
                  { "operation_id": "show_club", "method": "GET", "path": "/{id}",
                    "auth_required": true,
                    "success": { "status": 200, "entity": "Club" } }
              ] },
            { "name": "events",
              "entities": [{ "name": "Event",
                  "belongs_to": [{ "entity": "Club", "on_delete": "cascade" }],
                  "fields": [
                      { "name": "id", "type": "integer" },
                      { "name": "title", "type": "string" } ]}],
              "endpoints": [
                  { "operation_id": "list_events", "method": "GET", "path": "/",
                    "auth_required": true,
                    "success": { "status": 200, "entity": "Event", "list": true } }
              ] }
        ]
    }"#;

    /// (c) The blessed shape: every tenant/tenant-owned read is authenticated,
    /// so no handler is anonymous — JC0558 must stay silent and the whole design
    /// is question-free (the safe-design byte-identity baseline).
    #[test]
    fn jc0558_does_not_fire_when_every_tenant_read_is_authenticated() {
        let d: Design = serde_json::from_str(JC0558_BASE).unwrap();
        let qs = validate(&d);
        assert!(
            qs.is_empty(),
            "the safe tenancy design must pass clean: {qs:?}"
        );
    }

    /// (a) An unguarded, non-`public` GET on the TENANT ROOT entity is anonymous
    /// — genroute emits no Dep<Tenant>/CurrentUser, so any caller reads any
    /// tenant's row by id. JC0558 must refuse it, naming the tenant entity.
    #[test]
    fn jc0558_fires_on_an_unguarded_read_of_the_tenant_entity() {
        let mut d: Design = serde_json::from_str(JC0558_BASE).unwrap();
        // show_club is the tenant's own detail route (`GET /{id}` on Club).
        d.modules[0]
            .endpoints
            .iter_mut()
            .find(|ep| ep.operation_id == "show_club")
            .unwrap()
            .auth_required = false;
        let qs = validate(&d);
        assert!(
            jc0558(&qs)
                .iter()
                .any(|q| q.question.contains("show_club") && q.question.contains("`Club`")),
            "an unguarded read on the tenant root must trip JC0558 naming Club: {qs:?}"
        );
    }

    /// (b) The same anonymous shape on a tenant-OWNED (belongs_to) entity — an
    /// unguarded read of `Event` exposes every tenant's events. JC0558 fires.
    #[test]
    fn jc0558_fires_on_an_unguarded_read_of_a_tenant_owned_entity() {
        let mut d: Design = serde_json::from_str(JC0558_BASE).unwrap();
        d.modules[1]
            .endpoints
            .iter_mut()
            .find(|ep| ep.operation_id == "list_events")
            .unwrap()
            .auth_required = false;
        let qs = validate(&d);
        assert!(
            jc0558(&qs)
                .iter()
                .any(|q| q.question.contains("list_events") && q.question.contains("`Event`")),
            "an unguarded read on a tenant-owned entity must trip JC0558 naming Event: {qs:?}"
        );
    }

    /// (d) The `!ep.public` exemption: a `public` route bypasses JC0558. On a
    /// tenant-OWNED entity the open-read contradiction is the separate
    /// public-on-tenant-owned refusal; JC0558 itself must not double-fire.
    #[test]
    fn jc0558_does_not_fire_on_a_public_route() {
        let mut d: Design = serde_json::from_str(JC0558_BASE).unwrap();
        let read = d.modules[1]
            .endpoints
            .iter_mut()
            .find(|ep| ep.operation_id == "list_events")
            .unwrap();
        read.auth_required = false;
        read.public = true;
        let qs = validate(&d);
        assert!(
            jc0558(&qs).is_empty(),
            "JC0558 must not fire on a public route (the public-on-tenant-owned refusal owns it): {qs:?}"
        );
        // The public read on a tenant-owned entity IS refused — by the
        // public-on-tenant-owned check, proving JC0558 correctly stood down.
        assert!(
            qs.iter()
                .any(|q| q.question.contains("public") && q.question.contains("tenant-owned")),
            "a public read on a tenant-owned entity is still refused (just not by JC0558): {qs:?}"
        );
    }

    /// (e) An entity-less join/leave subroute (the membership escape hatch) reads
    /// no repo — the STRICT resolver returns None, so JC0558 must not tie it to a
    /// tenant-owned neighbor via a first-entity fallback and falsely refuse it.
    #[test]
    fn jc0558_does_not_fire_on_an_entityless_subroute() {
        let mut d: Design = serde_json::from_str(JC0558_BASE).unwrap();
        // Graft an entity-less subroute under the clubs module with an unguarded,
        // non-public endpoint. No entities ⇒ strict resolves to None ⇒ no fire.
        d.modules[0].subroutes.push(
            serde_json::from_str(
                r#"{ "name": "membership", "mount": "/{club_id}/membership",
                     "endpoints": [
                         { "operation_id": "join_club", "method": "POST", "path": "/join",
                           "success": { "status": 200 } } ] }"#,
            )
            .unwrap(),
        );
        let qs = validate(&d);
        assert!(
            jc0558(&qs).is_empty(),
            "an entity-less subroute reads no tenant repo — JC0558 must not fire: {qs:?}"
        );
    }

    /// (f) A signature-authenticated webhook (Stripe-style) is intentionally
    /// unguarded — it proves itself by signature (JL0004 exempts it, so JC0558
    /// must too). The exemption is load-bearing: without the signature error the
    /// SAME unguarded endpoint on the tenant-owned entity WOULD trip JC0558.
    #[test]
    fn jc0558_does_not_fire_on_a_signature_authed_webhook() {
        let webhook = |signature: bool| -> Design {
            let mut d: Design = serde_json::from_str(JC0558_BASE).unwrap();
            let errors = if signature {
                r#", "errors": [{ "status": 400, "when": "Stripe signature is missing or invalid" }]"#
            } else {
                ""
            };
            d.modules[1].endpoints.push(
                serde_json::from_str(&format!(
                    r#"{{ "operation_id": "event_webhook", "method": "POST", "path": "/webhook",
                         "success": {{ "status": 200, "entity": "Event" }}{errors} }}"#
                ))
                .unwrap(),
            );
            d
        };
        // With the signature error case: exempt — no JC0558 for the webhook.
        let qs = validate(&webhook(true));
        assert!(
            !jc0558(&qs)
                .iter()
                .any(|q| q.question.contains("event_webhook")),
            "a signature-authed webhook must be exempt from JC0558: {qs:?}"
        );
        // Without it: the exemption is what suppresses the refusal (Rule 9).
        let qs_bare = validate(&webhook(false));
        assert!(
            jc0558(&qs_bare)
                .iter()
                .any(|q| q.question.contains("event_webhook")),
            "an unguarded non-signature webhook on a tenant-owned entity DOES trip JC0558: {qs_bare:?}"
        );
    }

    /// (g) A per-user (identity-owned, NON-tenant) entity's unguarded read is
    /// JC0549's lane, not JC0558's: `tenant_path` is None, so the tenant twin
    /// must stay out of it (JC0549(c) claims the unguarded per-user read).
    #[test]
    fn jc0558_does_not_fire_on_a_per_user_non_tenant_entity() {
        let d: Design = serde_json::from_str(
            r#"{
            "name": "mixed", "contract_version": 1,
            "auth": { "model": "session", "roles": ["owner"] },
            "dependencies": ["db", "auth"],
            "tenancy": { "entity": "Club", "member_roles": ["owner"] },
            "modules": [
                { "name": "clubs",
                  "entities": [
                      { "name": "Club", "fields": [
                          { "name": "id", "type": "integer" },
                          { "name": "name", "type": "string" } ]},
                      { "name": "User", "fields": [
                          { "name": "id", "type": "integer" },
                          { "name": "email", "type": "string" } ]}
                  ],
                  "endpoints": [
                      { "operation_id": "show_club", "method": "GET", "path": "/{id}",
                        "auth_required": true,
                        "success": { "status": 200, "entity": "Club" } }
                  ] },
                { "name": "notes",
                  "entities": [{ "name": "Note",
                      "belongs_to": [{ "entity": "User" }],
                      "fields": [
                          { "name": "id", "type": "integer" },
                          { "name": "body", "type": "string" } ]}],
                  "endpoints": [
                      { "operation_id": "list_notes", "method": "GET", "path": "/",
                        "success": { "status": 200, "entity": "Note", "list": true } }
                  ] }
            ]
        }"#,
        )
        .unwrap();
        let qs = validate(&d);
        assert!(
            jc0558(&qs).is_empty(),
            "an unguarded per-user (non-tenant) read is JC0549's domain, not JC0558's: {qs:?}"
        );
        // The boundary: JC0549(c) owns that unguarded per-user read.
        assert!(
            qs.iter().any(|q| q.question.contains("JC0549")),
            "JC0549(c) claims the unguarded per-user read (the twin's lane): {qs:?}"
        );
    }

    /// The strict-resolution pin (#105 whole-branch review): an ENTITY-LESS
    /// `public: true` GET (`GET /config`, custom-JSON success, no body, no
    /// `{param}` — the documented hand-written `Json<serde_json::Value>`
    /// shape) in a PLAIN per-user module VALIDATES question-free. WHY (Rule
    /// 9): JC0549(c) resolved the endpoint's repo entity through the lenient
    /// first-entity fallback, tied `/config` to the owner-scoped `Post` it
    /// never reads, and FALSELY refused an implementable design base accepted
    /// — the check must fire only for GETs an explicit signal ties to the
    /// owner-scoped entity. The unguarded-read refusal on the REAL entity
    /// reads (explicit `success.entity`/`{id}`) must keep firing.
    #[test]
    fn entityless_public_get_in_a_plain_per_user_module_passes_validation() {
        let mut d: Design = serde_json::from_str(PUBLIC_READ_FEED).unwrap();
        d.modules[0].entities[0].public_read = false;
        // Guard the entity reads (the valid #79 prong) so only /config varies.
        for ep in &mut d.modules[0].endpoints {
            ep.auth_required = true;
        }
        let config: Endpoint = serde_json::from_str(
            r#"{ "operation_id": "get_config", "method": "GET", "path": "/config",
                 "public": true, "success": { "status": 200 } }"#,
        )
        .unwrap();
        d.modules[0].endpoints.push(config);
        let qs = validate(&d);
        assert!(
            qs.is_empty(),
            "an entity-less public custom-JSON GET reads no entity's repo and must not be refused: {qs:?}"
        );

        // The refusal still fires when an EXPLICIT signal ties the unguarded
        // GET to the owner-scoped entity — the strict resolver narrows the
        // check, it does not disable it.
        let mut still: Design = serde_json::from_str(PUBLIC_READ_FEED).unwrap();
        still.modules[0].entities[0].public_read = false;
        let qs2 = validate(&still);
        assert_eq!(
            jc0549(&qs2).len(),
            2,
            "explicit unguarded reads of the owner-scoped entity stay refused: {qs2:?}"
        );
    }

    /// #105 §E (negative): guarding the GETs is the other prong of the fork —
    /// a fully owner-scoped entity (#79) with authenticated reads stays exactly
    /// as valid as before.
    #[test]
    fn guarded_get_on_owner_scoped_entity_passes_validation() {
        let mut d: Design = serde_json::from_str(PUBLIC_READ_FEED).unwrap();
        d.modules[0].entities[0].public_read = false;
        for ep in &mut d.modules[0].endpoints {
            ep.auth_required = true;
        }
        let qs = validate(&d);
        assert!(
            qs.is_empty(),
            "the guarded per-user shape must keep passing: {qs:?}"
        );
    }

    #[test]
    fn jobs_validate_name_uniqueness_and_cron_shape() {
        let mut d: Design = serde_json::from_str(V1_FULL).unwrap();
        d.jobs[0].schedule = Some("not cron".into());
        assert!(validate(&d).iter().any(|q| q.id == "/jobs/0/schedule"));
        let mut d2: Design = serde_json::from_str(V1_FULL).unwrap();
        d2.jobs.push(d2.jobs[0].clone());
        assert!(validate(&d2).iter().any(|q| q.id == "/jobs/1/name"));
    }

    #[test]
    fn jobs_validate_queue_is_snake_case() {
        // The queue is interpolated RAW into generated Rust string literals
        // (`.queue("{q}", ...)`); a `"` in the queue would break the generated
        // crate at build time, far from the design. Validation must reject a
        // non-identifier queue up front, mirroring the job-name check.
        let mut d: Design = serde_json::from_str(V1_FULL).unwrap();
        d.jobs[0].queue = Some("not a queue\"".into());
        assert!(
            validate(&d).iter().any(|q| q.id == "/jobs/0/queue"),
            "a non-snake_case job queue must be a validation error"
        );
        // A valid snake_case queue passes.
        let mut ok: Design = serde_json::from_str(V1_FULL).unwrap();
        ok.jobs[0].queue = Some("billing".into());
        assert!(!validate(&ok).iter().any(|q| q.id == "/jobs/0/queue"));
    }

    #[test]
    fn jobs_require_a_database_dependency() {
        // Jobs run over a Postgres store; the generated `jobs(db)` wiring +
        // JOBS_MIGRATIONS need `jerrycan::db::Db`. A jobs-without-db design can't
        // compile, so validation rejects it before generation.
        let mut d: Design = serde_json::from_str(V1_FULL).unwrap();
        d.dependencies.retain(|dep| dep != "db");
        assert!(d.wants_jobs() && !d.wants_db());
        assert!(
            validate(&d).iter().any(|q| q.id == "/jobs"),
            "jobs without a db dependency must be a validation error"
        );
        // With db present (the unmodified fixture), no jobs-require-db error.
        let ok: Design = serde_json::from_str(V1_FULL).unwrap();
        assert!(!validate(&ok).iter().any(|q| q.id == "/jobs"));
    }

    #[test]
    fn enum_values_only_on_string_fields_and_nonempty() {
        let mut d: Design = serde_json::from_str(V1_FULL).unwrap();
        d.modules[0].entities[0].fields[0].values = Some(vec!["x".into()]); // id: integer
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/values")
        );
        let mut d2: Design = serde_json::from_str(V1_FULL).unwrap();
        d2.modules[0].entities[0].fields[1].values = Some(vec![]); // empty
        assert!(
            validate(&d2)
                .iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/1/values")
        );
    }

    #[test]
    fn field_default_must_type_check_against_field_type_and_enum() {
        // Issue #53a: a server-owned `default` is written verbatim into a NOT-NULL
        // column, so a mistyped or out-of-enum literal is a design-time error, not
        // a run-time surprise. Valid defaults raise no question.
        let base = |field: &str| {
            design(&format!(
                r#"{{ "name": "news", "contract_version": 0, "dependencies": ["db"],
                    "modules": [{{ "name": "subs",
                        "entities": [{{ "name": "Subscriber", "fields": [{field}] }}],
                        "endpoints": [{{ "operation_id": "create_subscriber", "method": "POST", "path": "/",
                            "request_body": {{ "entity": "Subscriber" }},
                            "success": {{ "status": 201, "entity": "Subscriber" }} }}] }}] }}"#
            ))
        };
        // A boolean default `false` and an enum default `"active"` are valid.
        let ok = base(
            r#"{ "name": "confirmed", "type": "boolean", "default": false },
               { "name": "status", "type": "string", "values": ["active", "expired"], "default": "active" }"#,
        );
        assert!(
            !validate(&ok).iter().any(|q| q.id.ends_with("/default")),
            "valid defaults raise no question: {:?}",
            validate(&ok)
        );
        // A string literal on a boolean field is rejected.
        let bad_type = base(r#"{ "name": "confirmed", "type": "boolean", "default": "false" }"#);
        assert!(
            validate(&bad_type)
                .iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/default"),
            "mistyped default must be a question: {:?}",
            validate(&bad_type)
        );
        // A default outside the enum `values` is rejected.
        let bad_enum = base(
            r#"{ "name": "status", "type": "string", "values": ["active", "expired"], "default": "draft" }"#,
        );
        assert!(
            validate(&bad_enum)
                .iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/default"),
            "out-of-enum default must be a question: {:?}",
            validate(&bad_enum)
        );
        // A default without a `db` dependency is inert (no request DTO) → rejected.
        let no_db: Design = serde_json::from_str(
            r#"{ "name": "news", "contract_version": 0, "dependencies": [],
                "modules": [{ "name": "subs",
                    "entities": [{ "name": "Subscriber", "fields": [
                        { "name": "email", "type": "string" },
                        { "name": "confirmed", "type": "boolean", "default": false } ] }],
                    "endpoints": [{ "operation_id": "list_subs", "method": "GET", "path": "/",
                        "success": { "status": 200 } }] }] }"#,
        )
        .unwrap();
        assert!(
            validate(&no_db)
                .iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/1/default"
                    && q.question.contains("no `db` dependency")),
            "a default without db must be a question: {:?}",
            validate(&no_db)
        );
    }

    #[test]
    fn now_default_is_clean_on_datetime_and_jc0557_elsewhere() {
        // Issue #110: the `"now"` sentinel is a DYNAMIC server-set timestamp valid
        // ONLY on a `datetime` field. The exact lowercase `"now"` on a datetime is
        // clean (the server sets it via now_rfc3339); `"now"` on any other type, or a
        // mis-cased near-miss on a datetime, is JC0557 — never silently stored as a
        // literal.
        let base = |field: &str| {
            design(&format!(
                r#"{{ "name": "notes", "contract_version": 0, "dependencies": ["db"],
                    "modules": [{{ "name": "notes",
                        "entities": [{{ "name": "Note", "fields": [{field}] }}],
                        "endpoints": [{{ "operation_id": "create_note", "method": "POST", "path": "/",
                            "request_body": {{ "entity": "Note" }},
                            "success": {{ "status": 201, "entity": "Note" }} }}] }}] }}"#
            ))
        };
        // Exact `"now"` on a datetime field raises NO question.
        let ok = base(r#"{ "name": "created_at", "type": "datetime", "default": "now" }"#);
        assert!(
            !validate(&ok).iter().any(|q| q.id.ends_with("/default")),
            "a datetime default:\"now\" is clean: {:?}",
            validate(&ok)
        );
        // `"now"` on a string field → JC0557 (it would otherwise be a valid literal).
        let bad_string = base(r#"{ "name": "label", "type": "string", "default": "now" }"#);
        assert!(
            validate(&bad_string)
                .iter()
                .any(|q| q.id.ends_with("/fields/0/default")
                    && q.question.contains("JC0557")
                    && q.question.contains("datetime")),
            "\"now\" on a string field must be JC0557: {:?}",
            validate(&bad_string)
        );
        // `"now"` on an integer field → JC0557 (not the generic type-mismatch).
        let bad_int = base(r#"{ "name": "count", "type": "integer", "default": "now" }"#);
        assert!(
            validate(&bad_int)
                .iter()
                .any(|q| q.id.ends_with("/fields/0/default") && q.question.contains("JC0557")),
            "\"now\" on an integer field must be JC0557: {:?}",
            validate(&bad_int)
        );
        // A mis-cased near-miss (`"NOW"`) on a datetime field → JC0557 (never read
        // as a static literal).
        let bad_case = base(r#"{ "name": "created_at", "type": "datetime", "default": "NOW" }"#);
        assert!(
            validate(&bad_case)
                .iter()
                .any(|q| q.id.ends_with("/fields/0/default")
                    && q.question.contains("JC0557")
                    && q.question.contains("mis-cased")),
            "\"NOW\" on a datetime field must be JC0557: {:?}",
            validate(&bad_case)
        );
        // A `default:"now"` without `db` reuses the existing db-required path.
        let no_db: Design = serde_json::from_str(
            r#"{ "name": "notes", "contract_version": 0, "dependencies": [],
                "modules": [{ "name": "notes",
                    "entities": [{ "name": "Note", "fields": [
                        { "name": "created_at", "type": "datetime", "default": "now" } ] }],
                    "endpoints": [{ "operation_id": "list_notes", "method": "GET", "path": "/",
                        "success": { "status": 200 } }] }] }"#,
        )
        .unwrap();
        assert!(
            validate(&no_db)
                .iter()
                .any(|q| q.id.ends_with("/default") && q.question.contains("no `db` dependency")),
            "a now default without db reuses the db-required message: {:?}",
            validate(&no_db)
        );
    }

    // ---- #80 (JC0552): field range/length constraints -------------------------

    /// One entity, one create endpoint, the given field JSON — the minimal
    /// otherwise-clean design the constraint checks run against.
    fn constraint_base(field: &str) -> Design {
        design(&format!(
            r#"{{ "name": "shop", "contract_version": 0, "dependencies": ["db"],
                "modules": [{{ "name": "items",
                    "entities": [{{ "name": "Item", "fields": [{field}] }}],
                    "endpoints": [{{ "operation_id": "create_item", "method": "POST", "path": "/",
                        "request_body": {{ "entity": "Item" }},
                        "success": {{ "status": 201, "entity": "Item" }} }}] }}] }}"#
        ))
    }

    /// WHY (#80): a declared, well-placed constraint is the whole point of the
    /// feature — it must validate CLEAN so the design proceeds to generation
    /// (min_len exactly at the 4096 ceiling included).
    #[test]
    fn valid_field_constraints_are_question_free() {
        let ok = constraint_base(
            r#"{ "name": "quantity", "type": "integer", "min": 1, "max": 600 },
               { "name": "bio", "type": "string", "max_len": 280 },
               { "name": "body", "type": "string", "min_len": 4096, "required": false }"#,
        );
        assert!(validate(&ok).is_empty(), "{:?}", validate(&ok));
    }

    /// `min`/`max` are an integer range — on a string or json field no generated
    /// comparison exists, so placement is refused per offending key.
    #[test]
    fn range_keys_are_refused_on_non_integer_fields() {
        let qs = validate(&constraint_base(
            r#"{ "name": "bio", "type": "string", "min": 1 }"#,
        ));
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/min"
                    && q.question.contains("integer")
                    && q.question.contains("JC0552")),
            "{qs:?}"
        );
        let qs = validate(&constraint_base(
            r#"{ "name": "custom", "type": "json", "max": 5 }"#,
        ));
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/max"
                    && q.question.contains("JC0552")),
            "{qs:?}"
        );
    }

    /// `min_len`/`max_len` count Unicode code points of a string — on an integer
    /// field there is no length to bound.
    #[test]
    fn length_keys_are_refused_on_non_string_fields() {
        let qs = validate(&constraint_base(
            r#"{ "name": "quantity", "type": "integer", "max_len": 10 }"#,
        ));
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/max_len"
                    && q.question.contains("string")
                    && q.question.contains("JC0552")),
            "{qs:?}"
        );
    }

    /// min > max (and min_len > max_len) is an empty range: no value satisfies
    /// it, so no in-range fixture is derivable — un-greenable by construction.
    #[test]
    fn empty_ranges_are_refused() {
        let qs = validate(&constraint_base(
            r#"{ "name": "quantity", "type": "integer", "min": 10, "max": 1 }"#,
        ));
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/min"
                    && q.question.contains("empty range")
                    && q.question.contains("JC0552")),
            "{qs:?}"
        );
        let qs = validate(&constraint_base(
            r#"{ "name": "bio", "type": "string", "min_len": 10, "max_len": 2 }"#,
        ));
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/min_len"
                    && q.question.contains("empty range")
                    && q.question.contains("JC0552")),
            "{qs:?}"
        );
    }

    /// Enum `values` already fix the exact allowed strings — a length bound on
    /// top is a contradiction (mirrors "values only on string").
    #[test]
    fn length_keys_are_refused_alongside_enum_values() {
        let qs = validate(&constraint_base(
            r#"{ "name": "status", "type": "string", "values": ["active", "expired"], "max_len": 5 }"#,
        ));
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/max_len"
                    && q.question.contains("values")
                    && q.question.contains("JC0552")),
            "{qs:?}"
        );
    }

    /// A required string with `max_len: 0` can never be filled; the same bound
    /// on an optional field is legal (the client omits it).
    #[test]
    fn max_len_zero_on_a_required_field_is_unfillable() {
        let qs = validate(&constraint_base(
            r#"{ "name": "bio", "type": "string", "max_len": 0 }"#,
        ));
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/max_len"
                    && q.question.contains("required")
                    && q.question.contains("JC0552")),
            "{qs:?}"
        );
        let optional = constraint_base(
            r#"{ "name": "title", "type": "string" },
               { "name": "bio", "type": "string", "max_len": 0, "required": false }"#,
        );
        assert!(
            !validate(&optional)
                .iter()
                .any(|q| q.question.contains("JC0552")),
            "{:?}",
            validate(&optional)
        );
    }

    /// The pk `id` is server-assigned — the id-echo probe and the seeds assume
    /// free ids, so ANY constraint key on `id` is refused (even a well-typed one).
    #[test]
    fn constraint_keys_on_the_pk_id_are_refused() {
        let mut d: Design = serde_json::from_str(V1_FULL).unwrap();
        d.modules[0].entities[0].fields[0].min = Some(1); // id: integer
        let qs = validate(&d);
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/min"
                    && q.question.contains("primary key")
                    && q.question.contains("JC0552")),
            "{qs:?}"
        );
        let mut d2: Design = serde_json::from_str(V1_FULL).unwrap();
        d2.modules[0].entities[0].fields[0].max_len = Some(8);
        let qs = validate(&d2);
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/max_len"
                    && q.question.contains("primary key")),
            "{qs:?}"
        );
    }

    /// #112 (JC0554): an EXPLICIT `write_only: true` on the pk `id` is refused —
    /// the id must be returned in every response (the id-echo probe + every
    /// cross-scope test key on `body["id"]`), so response-hiding it breaks the
    /// generated suite by construction. The same flag on any OTHER field — even
    /// alongside `unique` — is fine (write_only is orthogonal to DB/input keys).
    #[test]
    fn explicit_write_only_on_the_pk_id_is_refused_with_jc0554() {
        let base = |id_extra: &str, token_extra: &str| -> Design {
            design(&format!(
                r#"{{ "name": "secrets-api", "contract_version": 1, "dependencies": ["db"],
                    "modules": [{{ "name": "accounts",
                        "entities": [{{ "name": "Account", "fields": [
                            {{ "name": "id", "type": "integer"{id_extra} }},
                            {{ "name": "api_token", "type": "string"{token_extra} }} ] }}],
                        "endpoints": [{{ "operation_id": "list_accounts", "method": "GET",
                            "path": "/",
                            "success": {{ "status": 200, "entity": "Account", "list": true }} }}]
                    }}] }}"#
            ))
        };
        // write_only on a NON-id field, even `unique`, is accepted (no refusal).
        let ok = base("", r#", "write_only": true, "unique": true"#);
        assert!(
            validate(&ok).is_empty(),
            "write_only on a normal field (even unique) is fine: {:?}",
            validate(&ok)
        );
        // Explicit write_only on the pk id → JC0554.
        let bad = base(r#", "write_only": true"#, "");
        let qs = validate(&bad);
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/write_only"
                    && q.question.contains("primary key")
                    && q.question.contains("JC0554")),
            "explicit write_only on id must raise JC0554: {qs:?}"
        );
    }

    /// testgen must materialize `"a".repeat(min_len)` — an unbounded `min_len`
    /// would emit a multi-megabyte fixture, so it is capped at 4096.
    #[test]
    fn min_len_above_the_fixture_ceiling_is_refused() {
        let qs = validate(&constraint_base(
            r#"{ "name": "body", "type": "string", "min_len": 4097 }"#,
        ));
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/min_len"
                    && q.question.contains("4096")
                    && q.question.contains("JC0552")),
            "{qs:?}"
        );
    }

    /// #80 (T3): a `unique` field needs room for the distinct values the
    /// generated suite materializes — the probe fixture plus the tenant-1 and
    /// tenant-2 seeds, i.e. up to THREE distinct in-range values per field. A
    /// range admitting fewer makes the design un-greenable by construction
    /// (the seeds would collide on the UNIQUE index), so it is refused.
    #[test]
    fn unique_with_a_range_below_three_values_is_refused() {
        for field in [
            r#"{ "name": "slots", "type": "integer", "unique": true, "min": 5, "max": 5 }"#,
            r#"{ "name": "slots", "type": "integer", "unique": true, "min": 1, "max": 2 }"#,
        ] {
            let qs = validate(&constraint_base(field));
            assert!(
                qs.iter()
                    .any(|q| q.id == "/modules/0/entities/0/fields/0/min"
                        && q.question.contains("unique")
                        && q.question.contains("JC0552")),
                "{field}: {qs:?}"
            );
        }
        // Three or more distinct values: clean (the seeds fit).
        let ok = constraint_base(
            r#"{ "name": "slots", "type": "integer", "unique": true, "min": 1, "max": 600 },
               { "name": "trio", "type": "integer", "unique": true, "min": 1, "max": 3 }"#,
        );
        assert!(validate(&ok).is_empty(), "{:?}", validate(&ok));
        // Without `unique` a single-value range is legal (no distinctness need).
        let ok = constraint_base(r#"{ "name": "slots", "type": "integer", "min": 5, "max": 5 }"#);
        assert!(validate(&ok).is_empty(), "{:?}", validate(&ok));
    }

    /// #80 (T4): the cardinality rule must hold with a SINGLE declared bound
    /// too — the absent bound substitutes its i64 extreme. A `unique` field
    /// with only `min: i64::MAX - 1` admits two representable values, so the
    /// distinct seed derivation collides exactly as with a written `max`; the
    /// pre-fix arm required BOTH bounds and let this un-greenable design
    /// validate clean.
    #[test]
    fn unique_with_a_single_bound_near_the_extreme_is_refused() {
        // min-only at the top extreme: [i64::MAX - 1, i64::MAX] = 2 values.
        let qs = validate(&constraint_base(
            r#"{ "name": "slots", "type": "integer", "unique": true, "min": 9223372036854775806 }"#,
        ));
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/min"
                    && q.question.contains("unique")
                    && q.question.contains("JC0552")),
            "{qs:?}"
        );
        // max-only at the bottom extreme: [i64::MIN, i64::MIN + 1] = 2 values.
        let qs = validate(&constraint_base(
            r#"{ "name": "slots", "type": "integer", "unique": true, "max": -9223372036854775807 }"#,
        ));
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/max"
                    && q.question.contains("unique")
                    && q.question.contains("JC0552")),
            "{qs:?}"
        );
        // An open-ended single bound leaves astronomic room: clean.
        let ok =
            constraint_base(r#"{ "name": "slots", "type": "integer", "unique": true, "min": 1 }"#);
        assert!(validate(&ok).is_empty(), "{:?}", validate(&ok));
    }

    /// #80 (T3): the string twin — `max_len: 0` admits ONLY the empty string,
    /// so a `unique` field can never seed distinct values. Any `max_len >= 1`
    /// stays clean: the seed derivations lead with distinct characters
    /// ('t'/'s'/a digit), so even one code point suffices.
    #[test]
    fn unique_with_max_len_zero_is_refused() {
        let qs = validate(&constraint_base(
            r#"{ "name": "slug", "type": "string", "unique": true, "max_len": 0, "required": false }"#,
        ));
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/max_len"
                    && q.question.contains("unique")
                    && q.question.contains("JC0552")),
            "{qs:?}"
        );
        let ok = constraint_base(
            r#"{ "name": "slug", "type": "string", "unique": true, "max_len": 1 }"#,
        );
        assert!(validate(&ok).is_empty(), "{:?}", validate(&ok));
    }

    /// A server-owned `default` is written verbatim, so it must satisfy the
    /// field's OWN constraints — an out-of-bounds default would plant a value
    /// the declared bound forbids on every defaulted row.
    #[test]
    fn default_must_satisfy_the_fields_own_constraints() {
        let qs = validate(&constraint_base(
            r#"{ "name": "quantity", "type": "integer", "min": 1, "max": 600, "default": 601 }"#,
        ));
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/default"
                    && q.question.contains("range")
                    && q.question.contains("JC0552")),
            "{qs:?}"
        );
        let qs = validate(&constraint_base(
            r#"{ "name": "bio", "type": "string", "max_len": 3, "default": "toolong" }"#,
        ));
        assert!(
            qs.iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/0/default"
                    && q.question.contains("length")
                    && q.question.contains("JC0552")),
            "{qs:?}"
        );
        // In-range defaults stay clean — length counts CODE POINTS, not bytes.
        let ok = constraint_base(
            r#"{ "name": "quantity", "type": "integer", "min": 1, "max": 600, "default": 42 },
               { "name": "bio", "type": "string", "max_len": 5, "default": "héllo" }"#,
        );
        assert!(validate(&ok).is_empty(), "{:?}", validate(&ok));
    }

    #[test]
    fn explicit_fk_named_field_conflicts_with_belongs_to() {
        let mut d: Design = serde_json::from_str(V1_FULL).unwrap();
        d.modules[1].entities[0].fields.push(Field {
            name: "workspace_id".into(),
            field_type: FieldType::Integer,
            required: true,
            unique: false,
            index: false,
            values: None,
            default: None,
            min: None,
            max: None,
            min_len: None,
            max_len: None,
            write_only: false,
            reserve_against: None,
        });
        assert!(
            validate(&d)
                .iter()
                .any(|q| q.id.ends_with("/fields/3") && q.question.contains("derived")),
            "{:?}",
            validate(&d)
        );
    }

    #[test]
    fn public_endpoint_cannot_also_be_auth_required() {
        // A public endpoint that also demands auth contradicts itself: `public`
        // is the JL0004 carve-out for genuinely unauthenticated routes (login/
        // register), so combining it with a guard is a design error. WHY (Rule 9):
        // the flag exists to mark a route as needing NO credential — a guarded
        // public route would silently re-trip the very lint it claims exemption from.
        let mut v: serde_json::Value = serde_json::from_str(MINIMAL).unwrap();
        v["modules"][0]["endpoints"][1]["public"] = serde_json::json!(true);
        v["modules"][0]["endpoints"][1]["auth_required"] = serde_json::json!(true);
        let d: Design = serde_json::from_value(v).unwrap();
        let qs = validate(&d);
        assert!(
            qs.iter().any(|q| q.id == "/modules/0/endpoints/1"
                && q.question.contains("public")
                && q.question.contains("auth_required")),
            "{qs:?}"
        );
    }

    #[test]
    fn public_endpoint_cannot_require_roles() {
        let mut v: serde_json::Value = serde_json::from_str(MINIMAL).unwrap();
        v["modules"][0]["endpoints"][2]["public"] = serde_json::json!(true);
        // endpoints[2] (delete_todo) already declares required_roles: ["admin"].
        let d: Design = serde_json::from_value(v).unwrap();
        let qs = validate(&d);
        assert!(
            qs.iter().any(|q| q.id == "/modules/0/endpoints/2"
                && q.question.contains("public")
                && q.question.contains("required_roles")),
            "{qs:?}"
        );
    }

    #[test]
    fn reference_shaped_v1_design_is_question_free() {
        let d = guard_reads(serde_json::from_str(V1_FULL).unwrap());
        assert!(validate(&d).is_empty(), "{:?}", validate(&d));
    }

    #[test]
    fn public_endpoint_on_tenant_owned_entity_is_rejected() {
        // A public endpoint skips every guard — including the Tenant guard that
        // scopes a tenant-owned entity to its owner. WHY (Rule 9): marking such an
        // endpoint public would expose one tenant's rows to anyone, silently
        // defeating tenancy; the design must not be able to claim that exemption
        // on an entity that belongs_to the tenancy root.
        let mut d: Design = serde_json::from_str(V1_FULL).unwrap();
        // V1_FULL module[1] is `leads`; its `Lead` entity belongs_to Workspace
        // (the tenancy entity), and list_leads resolves to Lead via success.entity.
        d.modules[1].endpoints[0].public = true;
        let qs = validate(&d);
        assert!(
            qs.iter().any(|q| q.id == "/modules/1/endpoints/0"
                && q.question.contains("public")
                && q.question.contains("tenant-owned")),
            "{qs:?}"
        );
    }

    #[test]
    fn public_endpoints_on_non_tenant_owned_entities_do_not_false_positive() {
        // The reference-slice north-star design has public register/login in the
        // `users` module; User is NOT tenant-owned, so the resolution (request_body
        // entity for register, first-entity fallback for login) must not flag them.
        let reference = include_str!("../../../../conformance/designs/reference-slice.design.json");
        let d: Design = serde_json::from_str(reference).unwrap();
        let qs = validate(&d);
        assert!(
            qs.is_empty(),
            "reference-slice must validate question-free; public users endpoints must not false-positive: {qs:?}"
        );
    }

    // ---- #65 (JC0542): sibling routes with conflicting path-param names -------

    const CONFORMANCE_REFERENCE: &str =
        include_str!("../../../../conformance/designs/reference-slice.design.json");
    const CONFORMANCE_TODO: &str =
        include_str!("../../../../conformance/designs/todo-api.design.json");

    /// The HelpDesk repro (hit by 4/5 eval builds): `/{id}` and `/{ticket_id}/comments`
    /// in one module share segment position 2 but name its param differently. The
    /// runtime router (one global trie) aborts `App::build` with JC0500 after a clean
    /// scaffold; `design_conflict` must reject it up front with JC0542 naming BOTH
    /// routes, BOTH names, and BOTH remedies (unify / restructure).
    #[test]
    fn sibling_routes_with_different_param_names_are_a_conflict() {
        let d: Design = serde_json::from_str(
            r#"{
            "name": "helpdesk", "contract_version": 1, "dependencies": ["db"],
            "modules": [{
                "name": "tickets",
                "entities": [
                    { "name": "Ticket", "fields": [{ "name": "subject", "type": "string" }] },
                    { "name": "Comment", "fields": [{ "name": "body", "type": "string" }] }
                ],
                "endpoints": [
                    { "operation_id": "show_ticket", "method": "GET", "path": "/{id}",
                      "success": { "status": 200, "entity": "Ticket" } },
                    { "operation_id": "list_comments", "method": "GET", "path": "/{ticket_id}/comments",
                      "success": { "status": 200, "entity": "Comment", "list": true } }
                ]
            }]
        }"#,
        )
        .unwrap();
        let c = design_conflict(&d).expect("mismatched sibling param names must be a conflict");
        assert_eq!(c.code, "JC0542");
        assert!(
            c.message.contains("/tickets/{id}")
                && c.message.contains("/tickets/{ticket_id}/comments"),
            "names both conflicting routes: {}",
            c.message
        );
        assert!(
            c.message.contains("{id}") && c.message.contains("{ticket_id}"),
            "names both param names: {}",
            c.message
        );
        assert!(
            c.message.to_lowercase().contains("unify")
                && c.message.to_lowercase().contains("restructure"),
            "names both remedies: {}",
            c.message
        );
        assert!(!c.hint.is_empty());
    }

    /// The router accepts several sibling shapes the validator must NOT reject:
    /// (a) the SAME param name at a shared position (`/{id}` + `/{id}/comments`),
    /// (b) a literal vs a param at a position (`/{id}` + `/archive` — distinct trie
    /// children), and (c) a param-carrying subroute mount whose name is consistent
    /// with the parent. Plus BOTH shipped conformance designs.
    #[test]
    fn consistent_and_divergent_sibling_paths_are_not_conflicts() {
        // (a) same param name at the shared position.
        let same: Design = serde_json::from_str(
            r#"{
            "name": "ok-same", "contract_version": 1, "dependencies": ["db"],
            "modules": [{ "name": "tickets",
                "entities": [{ "name": "Ticket", "fields": [{ "name": "s", "type": "string" }] }],
                "endpoints": [
                    { "operation_id": "show_ticket", "method": "GET", "path": "/{id}",
                      "success": { "status": 200, "entity": "Ticket" } },
                    { "operation_id": "list_comments", "method": "GET", "path": "/{id}/comments",
                      "success": { "status": 200 } }
                ] }]
        }"#,
        )
        .unwrap();
        assert!(
            design_conflict(&same).is_none(),
            "identical param names at the shared position are fine"
        );
        // (b) a literal segment vs a param at the same position diverges.
        let literal: Design = serde_json::from_str(
            r#"{
            "name": "ok-literal", "contract_version": 1, "dependencies": ["db"],
            "modules": [{ "name": "tickets",
                "entities": [{ "name": "Ticket", "fields": [{ "name": "s", "type": "string" }] }],
                "endpoints": [
                    { "operation_id": "show_ticket", "method": "GET", "path": "/{id}",
                      "success": { "status": 200, "entity": "Ticket" } },
                    { "operation_id": "list_archived", "method": "GET", "path": "/archive",
                      "success": { "status": 200 } }
                ] }]
        }"#,
        )
        .unwrap();
        assert!(
            design_conflict(&literal).is_none(),
            "a literal and a param at the same position are distinct trie children"
        );
        // (c) a param-carrying subroute mount whose param agrees with the parent.
        let mounted: Design = serde_json::from_str(
            r#"{
            "name": "ok-mount", "contract_version": 1, "dependencies": ["db"],
            "modules": [{ "name": "workspaces", "mount": "/ws",
                "entities": [{ "name": "Ws", "fields": [{ "name": "s", "type": "string" }] }],
                "endpoints": [
                    { "operation_id": "show_ws", "method": "GET", "path": "/{id}",
                      "success": { "status": 200, "entity": "Ws" } }
                ],
                "subroutes": [{ "name": "leads", "mount": "/{id}/leads",
                    "endpoints": [
                        { "operation_id": "show_lead", "method": "GET", "path": "/{lead_id}",
                          "success": { "status": 200 } }
                    ] }]
            }]
        }"#,
        )
        .unwrap();
        assert!(
            design_conflict(&mounted).is_none(),
            "a param-mount child consistent with the parent must not be flagged: {:?}",
            design_conflict(&mounted).map(|c| c.message)
        );
        // Both shipped conformance designs (params all named `id`) stay clean.
        for src in [CONFORMANCE_REFERENCE, CONFORMANCE_TODO] {
            let d: Design = serde_json::from_str(src).unwrap();
            assert!(
                design_conflict(&d).is_none(),
                "conformance design must not trip JC0542: {:?}",
                design_conflict(&d).map(|c| c.message)
            );
        }
    }

    // ---- #107: the implicit member routes join the JC0542 walk ----------------

    /// A minimal Club-tenancy design (db + auth, so the member surface is
    /// emitted) whose tenant module has one detail endpoint at `detail_path`.
    fn club_tenancy(detail_path: &str) -> Design {
        serde_json::from_str(&format!(
            r#"{{
            "name": "clubs-api", "contract_version": 1,
            "auth": {{ "model": "session", "roles": ["owner", "member"] }},
            "dependencies": ["db", "auth"],
            "tenancy": {{ "entity": "Club", "member_roles": ["owner", "member"] }},
            "modules": [{{
                "name": "clubs",
                "entities": [{{ "name": "Club", "fields": [
                    {{ "name": "id", "type": "integer" }},
                    {{ "name": "slug", "type": "string" }} ]}}],
                "endpoints": [
                    {{ "operation_id": "show_club", "method": "GET", "path": "{detail_path}",
                      "auth_required": true,
                      "success": {{ "status": 200, "entity": "Club" }} }}
                ]
            }}]
        }}"#
        ))
        .unwrap()
    }

    /// A tenant module with a CUSTOM-param endpoint — `GET /{slug}` where the
    /// conventional `/{id}` would have been normalized to `/{club_id}`. The
    /// tool-owned member routes register `/{club_id}/members…` at `App::build`,
    /// so `{slug}` vs `{club_id}` at the shared position aborts startup with
    /// JC0500 — previously AFTER a clean check, breaking the "green check ⇒ it
    /// runs" promise. The walk must include the member routes and reject the
    /// design up front with JC0542 naming both routes.
    #[test]
    fn tenant_custom_param_collides_with_the_member_routes() {
        let c = design_conflict(&club_tenancy("/{slug}"))
            .expect("a custom tenant param must conflict with the member routes");
        assert_eq!(c.code, "JC0542");
        assert!(
            c.message.contains("/clubs/{slug}") && c.message.contains("/clubs/{club_id}/members"),
            "names the design route AND the member route: {}",
            c.message
        );
        assert!(
            c.message.contains("{slug}") && c.message.contains("{club_id}"),
            "names both param names: {}",
            c.message
        );
        // #88: the SAME `/{slug}` design is also refused by validate() — it is
        // the tenant's own detail route addressed by a non-pk param (JC0550).
        // Both codes are legitimate: JC0542 names the router conflict with the
        // member routes, JC0550 the unverifiable membership.
        let qs = validate(&club_tenancy("/{slug}"));
        assert!(
            qs.iter().any(|q| q.question.contains("JC0550")),
            "a db+auth `/{{slug}}` tenant detail route must also trip JC0550: {qs:?}"
        );
    }

    /// The conventional shape stays green: a tenant detail route written as
    /// `/{id}` is load-normalized to `/{club_id}` (`normalize_tenant_detail_routes`),
    /// which AGREES with the member routes' param — the walk must apply the same
    /// normalization the router sees, so the design passes exactly when
    /// `App::build` succeeds (no false positive on every ordinary tenancy app).
    #[test]
    fn normalized_tenant_detail_route_agrees_with_the_member_routes() {
        assert!(
            design_conflict(&club_tenancy("/{id}")).is_none(),
            "the normalized `/{{club_id}}` detail route must not conflict: {:?}",
            design_conflict(&club_tenancy("/{id}")).map(|c| c.message)
        );
        // Same param name written explicitly: also fine.
        assert!(
            design_conflict(&club_tenancy("/{club_id}")).is_none(),
            "an explicit `/{{club_id}}` detail route must not conflict"
        );
    }

    /// A design endpoint OCCUPYING a reserved member path (`GET /{club_id}/members`)
    /// is a second `.route()` registration of the same path — `App::build` aborts
    /// with JC0500 `duplicate route registration` (methods don't disambiguate).
    /// JC0542 must reject it at design time, naming the reserved surface.
    #[test]
    fn design_endpoint_on_a_reserved_member_path_is_a_conflict() {
        let c = design_conflict(&club_tenancy("/{club_id}/members"))
            .expect("a design endpoint on the reserved member path must conflict");
        assert_eq!(c.code, "JC0542");
        assert!(
            c.message.contains("/clubs/{club_id}/members")
                && c.message.contains("member-management"),
            "names the reserved path and the member surface: {}",
            c.message
        );
        assert!(
            c.message.contains("duplicate route registration"),
            "states the startup failure it prevents: {}",
            c.message
        );
        assert!(!c.hint.is_empty());
    }

    /// #140: SLASH-VARIANTS of a reserved member path — `/{club_id}/members/`
    /// (the natural hand-rolled shape: collection routes are trailing-slash by
    /// convention), a doubled-slash spelling, and the item path with a trailing
    /// slash. The router drops empty path segments (`segments()` filters them),
    /// so each spelling registers the SAME trie node as the member surface and
    /// `App::build` aborts with JC0500 `duplicate route registration` —
    /// previously AFTER a clean check (the occupancy compare was raw-string).
    /// The check must compare segment vectors and reject every spelling up
    /// front with JC0542.
    #[test]
    fn slash_variants_of_a_reserved_member_path_are_a_conflict() {
        for shape in [
            "/{club_id}/members/",
            "/{club_id}//members",
            "/{club_id}/members/{user_id}/",
        ] {
            let c = design_conflict(&club_tenancy(shape))
                .unwrap_or_else(|| panic!("`{shape}` must conflict with the member surface"));
            assert_eq!(c.code, "JC0542", "`{shape}` must be JC0542");
            assert!(
                c.message.contains("member-management"),
                "`{shape}` must name the member surface: {}",
                c.message
            );
        }
    }

    // ---- #88 (JC0550): a non-pk tenant detail param is refused -----------------

    /// #88: a tenant entity's OWN detail route addressed by a non-pk param
    /// survives normalization (only the literal `{id}` is renamed), the
    /// membership guard cannot bind an fk, and the handler was generated with
    /// a bare `CurrentUser` and NO membership check at all — silently. JC0550
    /// turns that silent hole into a design-time refusal naming the operation,
    /// the offending param, and the fk. Covers BOTH the first-position
    /// `/{slug}` (which db+auth JC0542 also catches via the member routes) and
    /// the non-first-position `/by-slug/{slug}`, which JC0542 cannot see (the
    /// static segment diverges from `{club_id}` in the trie) — the reachable
    /// silent hole.
    #[test]
    fn tenant_own_non_pk_detail_param_is_refused_with_jc0550() {
        for path in ["/{slug}", "/by-slug/{slug}"] {
            let qs = validate(&club_tenancy(path));
            let hit = qs
                .iter()
                .find(|q| q.question.contains("JC0550"))
                .unwrap_or_else(|| panic!("`{path}` must trip JC0550: {qs:?}"));
            assert!(
                hit.question.contains("show_club")
                    && hit.question.contains("GET")
                    && hit.question.contains("`Club`")
                    && hit.question.contains("{slug}")
                    && hit.question.contains("{club_id}"),
                "JC0550 must name the operation, method, tenant, param, and fk: {}",
                hit.question
            );
        }
    }

    /// The pk shapes stay green: the conventional `/{id}` (load-normalized to
    /// `/{club_id}`) and the explicit `/{club_id}` both address the tenant by
    /// its pk, so the guard binds the fk by name and JC0550 must not fire —
    /// every ordinary tenancy app validates exactly as before.
    #[test]
    fn tenant_pk_detail_routes_do_not_trip_jc0550() {
        for path in ["/{id}", "/{club_id}"] {
            let qs = validate(&club_tenancy(path));
            assert!(
                !qs.iter().any(|q| q.question.contains("JC0550")),
                "`{path}` must not trip JC0550: {qs:?}"
            );
        }
    }

    /// A tenant-strict endpoint whose fk arrives via the SUBROUTE MOUNT
    /// (mount `/{club_id}/history`, path `/{year}`, success = tenant) is
    /// fully guard-bound: `endpoint_tenant_shape` resolves the route as
    /// `mount + path`, sees the fk, classifies it PathScoped, and genroute
    /// emits the membership-checking `Dep<Tenant>` from the full route. WHY
    /// (Rule 9): JC0550 matching `ep.path` alone falsely refused this shape
    /// (fail-closed, but a refusal of a correct design) — the predicate must
    /// match the same mount-resolved path the guard actually binds.
    #[test]
    fn mount_carried_tenant_fk_does_not_trip_jc0550() {
        let d: Design = serde_json::from_str(
            r#"{ "name": "clubs-api", "contract_version": 1,
                "auth": { "model": "session", "roles": ["owner", "member"] },
                "dependencies": ["db", "auth"],
                "tenancy": { "entity": "Club", "member_roles": ["owner", "member"] },
                "modules": [
                    { "name": "clubs",
                      "entities": [{ "name": "Club", "fields": [
                          { "name": "name", "type": "string" } ]}],
                      "endpoints": [
                          { "operation_id": "get_club", "method": "GET", "path": "/{id}",
                            "auth_required": true,
                            "success": { "status": 200, "entity": "Club" } } ],
                      "subroutes": [
                          { "name": "history", "mount": "/{club_id}/history",
                            "entities": [{ "name": "Snapshot",
                                "belongs_to": [{ "entity": "Club" }],
                                "fields": [{ "name": "year", "type": "integer" }] }],
                            "endpoints": [
                                { "operation_id": "get_club_year", "method": "GET",
                                  "path": "/{year}", "auth_required": true,
                                  "success": { "status": 200, "entity": "Club" } } ] } ] }
                ] }"#,
        )
        .unwrap();
        let qs = validate(&d);
        assert!(
            !qs.iter().any(|q| q.question.contains("JC0550")),
            "a mount-carried tenant fk is guard-bound from the full route — \
             JC0550 must not refuse it: {qs:?}"
        );
    }

    /// A CHILD entity's `/{slug}` detail route is NOT the tenant's own detail
    /// route — its handler binds the child's repo, and child scoping is
    /// JL0006's domain, not the tenant guard's fk binding — so JC0550 must
    /// stay silent (only the tenant's OWN detail route is refused).
    #[test]
    fn child_entity_slug_detail_route_does_not_trip_jc0550() {
        let d: Design = serde_json::from_str(
            r#"{ "name": "clubs-api", "contract_version": 1,
                "auth": { "model": "session", "roles": ["owner", "member"] },
                "dependencies": ["db", "auth"],
                "tenancy": { "entity": "Club", "member_roles": ["owner", "member"] },
                "modules": [
                    { "name": "clubs",
                      "entities": [{ "name": "Club", "fields": [
                          { "name": "id", "type": "integer" },
                          { "name": "name", "type": "string" } ]}],
                      "endpoints": [
                          { "operation_id": "get_club", "method": "GET", "path": "/{id}",
                            "auth_required": true,
                            "success": { "status": 200, "entity": "Club" } } ] },
                    { "name": "books",
                      "entities": [{ "name": "Book",
                          "belongs_to": [{ "entity": "Club" }],
                          "fields": [{ "name": "id", "type": "integer" },
                                     { "name": "slug", "type": "string" }] }],
                      "endpoints": [
                          { "operation_id": "get_book", "method": "GET", "path": "/{slug}",
                            "auth_required": true,
                            "success": { "status": 200, "entity": "Book" } } ] }
                ] }"#,
        )
        .unwrap();
        let qs = validate(&d);
        assert!(
            !qs.iter().any(|q| q.question.contains("JC0550")),
            "a child entity's `/{{slug}}` detail route must not trip JC0550: {qs:?}"
        );
    }

    /// A SIBLING entity hosted in the tenant module with a bodyless
    /// `DELETE /trophies/{id}` (204, no `success.entity`) is NOT the tenant's
    /// own detail route: with a `POST /trophies` creator the strict resolver
    /// binds the SIBLING, and without one it binds no entity at all — JC0550
    /// must stay silent in both shapes. The module-local lenient resolver's
    /// first-entity fallback resolved the with-creator shape to the TENANT and
    /// falsely refused `{id}` — while the refusal's own message says to use
    /// `/{id}`.
    #[test]
    fn sibling_bodyless_delete_in_tenant_module_does_not_trip_jc0550() {
        for with_creator in [true, false] {
            let creator = if with_creator {
                r#"{ "operation_id": "create_trophy", "method": "POST", "path": "/trophies",
                     "request_body": { "entity": "Trophy" },
                     "success": { "status": 201, "entity": "Trophy" } },"#
            } else {
                ""
            };
            let d: Design = serde_json::from_str(&format!(
                r#"{{ "name": "clubs-api", "contract_version": 1,
                    "auth": {{ "model": "session", "roles": ["owner", "member"] }},
                    "dependencies": ["db", "auth"],
                    "tenancy": {{ "entity": "Club", "member_roles": ["owner", "member"] }},
                    "modules": [{{
                        "name": "clubs",
                        "entities": [
                            {{ "name": "Club", "fields": [
                                {{ "name": "id", "type": "integer" }},
                                {{ "name": "name", "type": "string" }} ]}},
                            {{ "name": "Trophy",
                               "belongs_to": [{{ "entity": "Club" }}],
                               "fields": [
                                {{ "name": "id", "type": "integer" }},
                                {{ "name": "title", "type": "string" }} ]}}],
                        "endpoints": [
                            {{ "operation_id": "get_club", "method": "GET", "path": "/{{id}}",
                               "auth_required": true,
                               "success": {{ "status": 200, "entity": "Club" }} }},
                            {creator}
                            {{ "operation_id": "delete_trophy", "method": "DELETE",
                               "path": "/trophies/{{id}}", "auth_required": true,
                               "success": {{ "status": 204 }} }}
                        ]
                    }}]
                }}"#
            ))
            .unwrap();
            let qs = validate(&d);
            assert!(
                !qs.iter().any(|q| q.question.contains("JC0550")),
                "a sibling's bodyless `DELETE /trophies/{{id}}` (creator present: {with_creator}) must not trip JC0550: {qs:?}"
            );
        }
    }

    /// The under-fire hole, closed: the tenant declared as a NON-FIRST entity
    /// in its module, with a bodyless `DELETE /{slug}` whose collection creator
    /// (`POST /`, body = tenant) IS the tenant. The lenient first-entity
    /// fallback resolved it to the sibling and shipped the no-membership-check
    /// hole question-free; the strict creator arm resolves the tenant and
    /// refuses. Asserted for db+auth AND db-less/memory-mode tenancy — in
    /// memory mode there is no implicit member surface, so JC0542 cannot catch
    /// the shape and JC0550 is the ONLY design-time refusal.
    #[test]
    fn non_first_tenant_bodyless_slug_delete_trips_jc0550() {
        for deps in [r#"["db", "auth"]"#, r#"["auth"]"#] {
            let d: Design = serde_json::from_str(&format!(
                r#"{{ "name": "clubs-api", "contract_version": 1,
                    "auth": {{ "model": "session", "roles": ["owner", "member"] }},
                    "dependencies": {deps},
                    "tenancy": {{ "entity": "Club", "member_roles": ["owner", "member"] }},
                    "modules": [{{
                        "name": "clubs",
                        "entities": [
                            {{ "name": "Trophy",
                               "belongs_to": [{{ "entity": "Club" }}],
                               "fields": [
                                {{ "name": "id", "type": "integer" }},
                                {{ "name": "title", "type": "string" }} ]}},
                            {{ "name": "Club", "fields": [
                                {{ "name": "id", "type": "integer" }},
                                {{ "name": "slug", "type": "string" }} ]}}],
                        "endpoints": [
                            {{ "operation_id": "create_club", "method": "POST", "path": "/",
                               "request_body": {{ "entity": "Club" }},
                               "success": {{ "status": 201, "entity": "Club" }} }},
                            {{ "operation_id": "delete_club", "method": "DELETE", "path": "/{{slug}}",
                               "auth_required": true,
                               "success": {{ "status": 204 }} }}
                        ]
                    }}]
                }}"#
            ))
            .unwrap();
            let qs = validate(&d);
            let hit = qs
                .iter()
                .find(|q| q.question.contains("JC0550"))
                .unwrap_or_else(|| {
                    panic!(
                        "deps {deps}: a non-first tenant's bodyless `DELETE /{{slug}}` must trip JC0550: {qs:?}"
                    )
                });
            assert!(
                hit.question.contains("delete_club")
                    && hit.question.contains("{slug}")
                    && hit.question.contains("{club_id}"),
                "JC0550 must name the operation, param, and fk: {}",
                hit.question
            );
        }
    }

    /// An entity-less CUSTOM endpoint in a single-entity tenant module — a
    /// `GET /export/{format}` with a custom-JSON success (no `success.entity`,
    /// no body, no creator at `/export`) — reads NO entity's repo, so it is
    /// not the tenant's detail route: strict resolution returns `None` and
    /// JC0550 must stay silent. The lenient fallback tied it to the tenant and
    /// falsely refused `{format}` as an unverifiable tenant param.
    #[test]
    fn entity_less_custom_get_does_not_trip_jc0550() {
        let d: Design = serde_json::from_str(
            r#"{ "name": "clubs-api", "contract_version": 1,
                "auth": { "model": "session", "roles": ["owner", "member"] },
                "dependencies": ["db", "auth"],
                "tenancy": { "entity": "Club", "member_roles": ["owner", "member"] },
                "modules": [{
                    "name": "clubs",
                    "entities": [{ "name": "Club", "fields": [
                        { "name": "id", "type": "integer" },
                        { "name": "name", "type": "string" } ]}],
                    "endpoints": [
                        { "operation_id": "create_club", "method": "POST", "path": "/",
                          "request_body": { "entity": "Club" },
                          "success": { "status": 201, "entity": "Club" } },
                        { "operation_id": "export_clubs", "method": "GET",
                          "path": "/export/{format}", "auth_required": true,
                          "success": { "status": 200 } }
                    ]
                }]
            }"#,
        )
        .unwrap();
        let qs = validate(&d);
        assert!(
            !qs.iter().any(|q| q.question.contains("JC0550")),
            "an entity-less custom `GET /export/{{format}}` must not trip JC0550: {qs:?}"
        );
    }

    /// A multi-param tenant route that CARRIES the fk — `GET /{club_id}/{version}`
    /// on the tenant — binds the fk (the guard membership-checks the tenant
    /// named by it), so JC0550 must not fire: the predicate is "no fk among the
    /// path params", not "the trailing param is not the fk".
    #[test]
    fn multi_param_tenant_route_with_fk_present_does_not_trip_jc0550() {
        let d: Design = serde_json::from_str(
            r#"{ "name": "clubs-api", "contract_version": 1,
                "auth": { "model": "session", "roles": ["owner", "member"] },
                "dependencies": ["db", "auth"],
                "tenancy": { "entity": "Club", "member_roles": ["owner", "member"] },
                "modules": [{
                    "name": "clubs",
                    "entities": [{ "name": "Club", "fields": [
                        { "name": "id", "type": "integer" },
                        { "name": "name", "type": "string" } ]}],
                    "endpoints": [
                        { "operation_id": "get_club_version", "method": "GET",
                          "path": "/{club_id}/{version}", "auth_required": true,
                          "success": { "status": 200, "entity": "Club" } }
                    ]
                }]
            }"#,
        )
        .unwrap();
        let qs = validate(&d);
        assert!(
            !qs.iter().any(|q| q.question.contains("JC0550")),
            "a multi-param tenant route carrying the fk must not trip JC0550: {qs:?}"
        );
    }

    /// #140: two spellings of ONE route — `GET /archive` and `POST /archive/`
    /// — emit two `.route()` lines (`route_lines` groups by RAW path), which
    /// the router collapses onto one trie node: the second registration aborts
    /// `App::build` with JC0500 `duplicate route registration`, after a clean
    /// check. The twin must mirror the trie's endpoint occupancy so the design
    /// fails `check` up front, naming both spellings.
    #[test]
    fn slash_variant_duplicate_design_routes_are_a_conflict() {
        let d: Design = serde_json::from_str(
            r#"{
            "name": "dup-slash", "contract_version": 1, "dependencies": ["db"],
            "modules": [{ "name": "tickets",
                "entities": [{ "name": "Ticket", "fields": [{ "name": "s", "type": "string" }] }],
                "endpoints": [
                    { "operation_id": "list_archived", "method": "GET", "path": "/archive",
                      "success": { "status": 200 } },
                    { "operation_id": "archive_ticket", "method": "POST", "path": "/archive/",
                      "success": { "status": 201 } }
                ] }]
        }"#,
        )
        .unwrap();
        let c = design_conflict(&d).expect("slash-variant duplicate routes must be a conflict");
        assert_eq!(c.code, "JC0542");
        assert!(
            c.message.contains("`/tickets/archive`") && c.message.contains("`/tickets/archive/`"),
            "names both spellings: {}",
            c.message
        );
        assert!(
            c.message.contains("duplicate route registration"),
            "states the startup failure it prevents: {}",
            c.message
        );
        assert!(!c.hint.is_empty());
    }

    // ---- #54 (JC0543): enum value content ------------------------------------

    /// An enum value with a space (or quote/backslash) breaks the UNESCAPED
    /// interpolation into generated Rust; validation rejects it at design time with
    /// JC0543 guidance, naming the offending value. Identifier-shaped values
    /// (letters, digits, `_`, `-`) pass.
    #[test]
    fn enum_values_must_be_identifier_shaped() {
        // V1_FULL module[0]=workspaces, entity[0]=Workspace, field[1]=plan (string enum).
        let mut bad: Design = serde_json::from_str(V1_FULL).unwrap();
        bad.modules[0].entities[0].fields[1].values = Some(vec!["in progress".into()]);
        assert!(
            validate(&bad)
                .iter()
                .any(|q| q.id == "/modules/0/entities/0/fields/1/values"
                    && q.question.contains("JC0543")
                    && q.question.contains("in progress")),
            "a space-bearing enum value must be rejected: {:?}",
            validate(&bad)
        );
        // A quote is rejected too (the direct interpolation footgun).
        let mut quoted: Design = serde_json::from_str(V1_FULL).unwrap();
        quoted.modules[0].entities[0].fields[1].values = Some(vec!["a\"b".into()]);
        assert!(
            validate(&quoted)
                .iter()
                .any(|q| q.id.ends_with("/values") && q.question.contains("JC0543"))
        );
        // `-` and `_` and mixed case are legitimate identifier shapes.
        let mut ok: Design = serde_json::from_str(V1_FULL).unwrap();
        ok.modules[0].entities[0].fields[1].values =
            Some(vec!["in-progress".into(), "on_hold".into(), "Done2".into()]);
        assert!(
            !validate(&ok).iter().any(|q| q.id.ends_with("/values")),
            "identifier-shaped values must pass: {:?}",
            validate(&ok)
        );
        // Both shipped conformance designs' enum values stay clean.
        for src in [CONFORMANCE_REFERENCE, CONFORMANCE_TODO] {
            let d: Design = serde_json::from_str(src).unwrap();
            assert!(
                !validate(&d).iter().any(|q| q.question.contains("JC0543")),
                "conformance enum values must not trip JC0543"
            );
        }
    }

    // ---- #60 (JC0544): dual-create path-fk omission --------------------------

    /// The dual-create shape from issue #60: `Checkin belongs_to Habit`, with a
    /// nested `POST /{habit_id}/checkins` AND a standalone `POST /checkins`. The
    /// per-entity `CheckinRequest` drops `habit_id` for both, so the standalone
    /// route can set the NOT-NULL fk from neither the body nor the path — it is
    /// un-implementable. Validation flags ONLY the standalone route with JC0544,
    /// naming the route and BOTH fixes; the nested route (which carries the param)
    /// is left alone.
    #[test]
    fn dual_create_standalone_route_missing_path_fk_is_flagged() {
        let d: Design = serde_json::from_str(DUAL_CREATE).unwrap();
        let qs = validate(&d);
        let flagged: Vec<&Question> = qs
            .iter()
            .filter(|q| q.question.contains("JC0544"))
            .collect();
        assert_eq!(
            flagged.len(),
            1,
            "only the standalone POST /checkins is un-implementable: {qs:?}"
        );
        let f = flagged[0];
        assert!(
            f.question.contains("create_checkin_flat") && f.question.contains("habit_id"),
            "names the un-implementable route and the fk: {}",
            f.question
        );
        assert!(
            f.question.to_lowercase().contains("split") && f.question.contains("{habit_id}"),
            "names both fixes (add the path param / split the entity): {}",
            f.question
        );
    }

    /// A nested-ONLY create (`POST /{habit_id}/checkins`, no standalone) carries the
    /// fk in its path, so it is implementable and must NOT be flagged — and both
    /// shipped conformance designs (no dual-create shape) stay JC0544-free.
    #[test]
    fn nested_only_create_and_conformance_shapes_do_not_trip_dual_create() {
        let nested: Design = serde_json::from_str(NESTED_ONLY).unwrap();
        assert!(
            !validate(&nested)
                .iter()
                .any(|q| q.question.contains("JC0544")),
            "a nested-only create carries its fk in the path: {:?}",
            validate(&nested)
        );
        for src in [CONFORMANCE_REFERENCE, CONFORMANCE_TODO] {
            let d: Design = serde_json::from_str(src).unwrap();
            assert!(
                !validate(&d).iter().any(|q| q.question.contains("JC0544")),
                "conformance design must not trip JC0544"
            );
        }
    }

    /// Issue #82 + #125-create: a tenant child mounted at `/clubs/{club_id}` whose
    /// create is `POST /` carries its parent fk in the MOUNT. Now that
    /// `entity_path_fk_columns` is mount-aware it reports `club_id` as path-redundant
    /// — but the RESOLVED path DOES carry `{club_id}`, so the route IS implementable
    /// (the handler injects the path/tenant value). JC0544 must resolve the mount the
    /// same way and NOT flag it; otherwise `require_complete` would block the exact
    /// nested-mount app 0.5.2 blesses. (A mount-BLIND JC0544 would fire here because
    /// `ep.path == "/"` lacks `{club_id}` even though the mount supplies it.)
    #[test]
    fn nested_mount_create_carries_fk_in_the_mount_and_is_not_flagged() {
        let d: Design = serde_json::from_str(NESTED_MOUNT_CREATE).unwrap();
        assert!(
            !validate(&d).iter().any(|q| q.question.contains("JC0544")),
            "a mount-nested create carries its fk in the RESOLVED path, so it must not \
             trip JC0544: {:?}",
            validate(&d)
        );
    }

    // ---- #114 (JC0546): entity name collides with a prelude re-export ---------

    /// An entity named `Module` (a `jerrycan::prelude` re-export) makes the
    /// generated crate emit `pub struct Module` beside `use jerrycan::prelude::*;`
    /// and `use super::model::*;` — two glob imports of `Module`, so every
    /// reference is `E0659 ... is ambiguous` and the scaffold does not compile.
    /// `validate` must reject the design up front with JC0546 (fail-loud like
    /// JC0545), naming the entity, the reserved identifier, and the rename fix —
    /// so `jerrycan new` never scaffolds a crate that won't build.
    #[test]
    fn entity_named_after_a_prelude_reexport_is_rejected_with_jc0546() {
        // MINIMAL's PascalCase entity `Todo` (name + every reference) → `Module`.
        let d = design(&MINIMAL.replace("Todo", "Module"));
        let qs = validate(&d);
        let flagged: Vec<&Question> = qs
            .iter()
            .filter(|q| q.question.contains("JC0546"))
            .collect();
        assert_eq!(
            flagged.len(),
            1,
            "the single `Module` entity is flagged exactly once: {qs:?}"
        );
        let f = flagged[0];
        assert!(
            f.id.ends_with("/name"),
            "the question points at the entity's /name: {}",
            f.id
        );
        assert!(
            f.question.contains("Module")
                && f.question.to_lowercase().contains("prelude")
                && f.question.to_lowercase().contains("rename"),
            "names the entity, the reserved prelude identifier, and the rename fix: {}",
            f.question
        );
    }

    /// The default `Todo` name shadows nothing, and the shipped conformance
    /// designs use ordinary entity names — none may trip JC0546 (the negative
    /// control: the guard fires only on a real reserved-name collision).
    #[test]
    fn ordinary_entity_names_do_not_trip_jc0546() {
        assert!(
            !validate(&design(MINIMAL))
                .iter()
                .any(|q| q.question.contains("JC0546")),
            "an ordinary entity name is not a prelude collision"
        );
        for src in [CONFORMANCE_REFERENCE, CONFORMANCE_TODO] {
            let d: Design = serde_json::from_str(src).unwrap();
            assert!(
                !validate(&d).iter().any(|q| q.question.contains("JC0546")),
                "conformance design must not trip JC0546"
            );
        }
    }

    /// #129 drift tripwire: `RESERVED_PRELUDE_IDENTS` is a HAND-MAINTAINED mirror
    /// of the identifiers `jerrycan::prelude` re-exports (the glob every generated
    /// route crate writes: `use jerrycan::prelude::*;`). If a future `pub use` is
    /// added to the prelude but NOT to the set, JC0546 stops firing for it and an
    /// entity named after it silently reopens #114 — the scaffold emits an
    /// uncompilable `E0659` crate. This reads the prelude SOURCE (jerrycan-core's
    /// `pub mod prelude` + the facade's re-exported `main`) and asserts the set is
    /// a SUPERSET of every re-exported ident, so any drift fails CI. Test-only;
    /// like `embedded_sync`, it skips in a published tarball where the sibling
    /// core-crate source is absent.
    #[test]
    fn reserved_prelude_idents_is_a_superset_of_the_prelude_reexports() {
        use std::path::Path;

        // The body of the single `pub mod prelude { ... }` block, by brace match.
        fn prelude_body(src: &str) -> String {
            let start = src.find("pub mod prelude").expect("a prelude module");
            let open = start + src[start..].find('{').expect("prelude has a body");
            let mut depth = 0usize;
            for (i, b) in src[open..].bytes().enumerate() {
                match b {
                    b'{' => depth += 1,
                    b'}' => {
                        depth -= 1;
                        if depth == 0 {
                            return src[open + 1..open + i].to_string();
                        }
                    }
                    _ => {}
                }
            }
            panic!("unbalanced braces in the prelude module");
        }

        // (idents, globs) re-exported by a prelude body. Handles `pub use a::b::C;`,
        // `... as D;`, grouped `pub use a::{B, C as D};`, and glob `pub use x::*;`
        // (reported separately — a glob cannot be enumerated against the set).
        fn reexports(body: &str) -> (Vec<String>, Vec<String>) {
            fn push_item(
                item: &str,
                prefix: &str,
                idents: &mut Vec<String>,
                globs: &mut Vec<String>,
            ) {
                let item = item.trim();
                if item.is_empty() {
                    return;
                }
                if item == "*" {
                    globs.push(prefix.trim_end_matches("::").to_string());
                } else if let Some(base) = item.strip_suffix("::*") {
                    globs.push(format!("{prefix}{base}"));
                } else if let Some((_, rename)) = item.split_once(" as ") {
                    idents.push(rename.trim().to_string());
                } else {
                    idents.push(item.rsplit("::").next().unwrap().trim().to_string());
                }
            }
            // Strip line comments so a `//` in a doc line can't leak a token.
            let cleaned: String = body
                .lines()
                .map(|l| l.split_once("//").map_or(l, |(code, _)| code))
                .collect::<Vec<_>>()
                .join("\n");
            let mut idents = Vec::new();
            let mut globs = Vec::new();
            for stmt in cleaned.split(';') {
                let Some(rest) = stmt.trim().strip_prefix("pub use ") else {
                    continue;
                };
                let rest = rest.trim();
                if let Some(brace) = rest.find("::{") {
                    let prefix = &rest[..brace + 2]; // path up to and incl. the trailing "::"
                    let group = rest[brace + 3..].trim_end_matches('}');
                    for item in group.split(',') {
                        push_item(item, prefix, &mut idents, &mut globs);
                    }
                } else {
                    push_item(rest, "", &mut idents, &mut globs);
                }
            }
            (idents, globs)
        }

        let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR")); // crates/jerrycan
        let core_lib = crate_dir.join("../jerrycan-core/src/lib.rs");
        if !core_lib.exists() {
            return; // published tarball: the sibling core-crate source is absent
        }
        let facade_lib = crate_dir.join("src/lib.rs");
        let core_src = std::fs::read_to_string(&core_lib).unwrap();
        let facade_src = std::fs::read_to_string(&facade_lib).unwrap();

        let (core_idents, core_globs) = reexports(&prelude_body(&core_src));
        let (facade_idents, facade_globs) = reexports(&prelude_body(&facade_src));

        // The core prelude re-exports concrete items only. A glob there could not
        // be statically enumerated against the set — fail loud, never pass blind.
        assert!(
            core_globs.is_empty(),
            "jerrycan-core prelude gained a glob re-export {core_globs:?}: RESERVED_PRELUDE_IDENTS cannot mirror a glob — enumerate it or update this tripwire (#129)"
        );
        // The facade prelude's ONLY permitted glob is the core prelude it re-exports
        // (enumerated above via `core_idents`); any OTHER glob is un-mirrorable.
        assert_eq!(
            facade_globs,
            vec!["jerrycan_core::prelude".to_string()],
            "facade prelude globs changed to {facade_globs:?}: only `jerrycan_core::prelude::*` is enumerable — a new glob reopens the #129 drift blind spot"
        );

        // Every ident the generated `use jerrycan::prelude::*;` pulls into scope
        // must be reserved, or an entity named after it reopens #114 (JC0546 goes
        // silent). Superset — extra reserved names are fine, missing ones are not.
        let reexported: Vec<String> = core_idents.into_iter().chain(facade_idents).collect();
        assert!(
            !reexported.is_empty(),
            "the prelude parser found no re-exports — the parser or the prelude shape changed"
        );
        for id in &reexported {
            assert!(
                RESERVED_PRELUDE_IDENTS.contains(&id.as_str()),
                "`jerrycan::prelude` re-exports `{id}` but RESERVED_PRELUDE_IDENTS (questions.rs) omits it — add `\"{id}\"`, or an entity named `{id}` scaffolds an uncompilable E0659 crate (#114/#129). Current set: {RESERVED_PRELUDE_IDENTS:?}"
            );
        }
    }

    /// A tenant child created at `POST /` under a module mounted at `/clubs/{club_id}`
    /// — the fk `club_id` is supplied by the MOUNT, not `ep.path`.
    const NESTED_MOUNT_CREATE: &str = r#"{ "name": "clubs-api", "contract_version": 1,
        "auth": { "model": "session", "roles": ["owner", "member"] },
        "dependencies": ["db", "auth"],
        "tenancy": { "entity": "Club", "member_roles": ["owner", "member"] },
        "modules": [
            { "name": "clubs",
              "entities": [{ "name": "Club", "fields": [
                  { "name": "id", "type": "integer" }, { "name": "name", "type": "string" } ]}],
              "endpoints": [
                  { "operation_id": "create_club", "method": "POST", "path": "/", "auth_required": true,
                    "request_body": { "entity": "Club" },
                    "success": { "status": 201, "entity": "Club" } } ] },
            { "name": "books", "mount": "/clubs/{club_id}",
              "entities": [{ "name": "Book",
                  "belongs_to": [{ "entity": "Club" }],
                  "fields": [{ "name": "id", "type": "integer" }, { "name": "title", "type": "string" }] }],
              "endpoints": [
                  { "operation_id": "create_book", "method": "POST", "path": "/", "auth_required": true,
                    "request_body": { "entity": "Book" },
                    "success": { "status": 201, "entity": "Book" } } ] }
        ] }"#;

    /// The #60 repro: one entity created both nested and standalone.
    const DUAL_CREATE: &str = r#"{
        "name": "habits", "contract_version": 1, "dependencies": ["db"],
        "modules": [{
            "name": "habits",
            "entities": [
                { "name": "Habit", "fields": [
                    { "name": "id", "type": "integer" }, { "name": "title", "type": "string" } ] },
                { "name": "Checkin",
                  "belongs_to": [{ "entity": "Habit", "on_delete": "cascade" }],
                  "fields": [
                    { "name": "id", "type": "integer" }, { "name": "note", "type": "string" } ] }
            ],
            "endpoints": [
                { "operation_id": "create_checkin_nested", "method": "POST", "path": "/{habit_id}/checkins",
                  "request_body": { "entity": "Checkin" },
                  "success": { "status": 201, "entity": "Checkin" } },
                { "operation_id": "create_checkin_flat", "method": "POST", "path": "/checkins",
                  "request_body": { "entity": "Checkin" },
                  "success": { "status": 201, "entity": "Checkin" } }
            ]
        }]
    }"#;

    /// The same entity created ONLY under its parent's path — implementable.
    const NESTED_ONLY: &str = r#"{
        "name": "habits", "contract_version": 1, "dependencies": ["db"],
        "modules": [{
            "name": "habits",
            "entities": [
                { "name": "Habit", "fields": [
                    { "name": "id", "type": "integer" }, { "name": "title", "type": "string" } ] },
                { "name": "Checkin",
                  "belongs_to": [{ "entity": "Habit", "on_delete": "cascade" }],
                  "fields": [
                    { "name": "id", "type": "integer" }, { "name": "note", "type": "string" } ] }
            ],
            "endpoints": [
                { "operation_id": "create_checkin_nested", "method": "POST", "path": "/{habit_id}/checkins",
                  "request_body": { "entity": "Checkin" },
                  "success": { "status": 201, "entity": "Checkin" } }
            ]
        }]
    }"#;
}