jerrycan 0.7.13

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
//! Generated acceptance tests: the design contract as runnable assertions.

use jerrycan::platform::design::Design;
use jerrycan::platform::testgen;

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

fn golden(db: bool) -> Design {
    let mut v: serde_json::Value = serde_json::from_str(GOLDEN).unwrap();
    if db {
        v["dependencies"] = serde_json::json!(["db"]);
    }
    serde_json::from_value(v).unwrap()
}

/// Issue #43: the identity-FK omission is db-gated in testgen too, so a MEMORY-mode
/// design's probe body KEEPS `user_id` (there is no `{Entity}Request` DTO to drop it
/// into — the memory struct has no fk columns and serde ignores the extra key). WHY
/// (Rule 9): the omission is a db-mode contract; in memory mode the probe, the
/// OpenAPI request schema, and genroute's `Json<Entity>` must all agree, and genroute
/// keeps the plain entity. The DB-mode twin of the SAME design drops `user_id`.
#[test]
fn memory_mode_probe_body_keeps_the_identity_fk() {
    const IDENTITY_FK: &str = r#"{
        "name": "notes-api", "contract_version": 1,
        "auth": { "model": "session", "roles": ["admin"] },
        "dependencies": ["auth"],
        "modules": [{
            "name": "notes",
            "entities": [
                { "name": "User", "fields": [{ "name": "email", "type": "string" }] },
                { "name": "Note",
                  "belongs_to": [{ "entity": "User", "on_delete": "cascade" }],
                  "fields": [{ "name": "body", "type": "string" }] }
            ],
            "endpoints": [
                { "operation_id": "create_note", "method": "POST", "path": "/",
                  "auth_required": true,
                  "request_body": { "entity": "Note" },
                  "success": { "status": 201, "entity": "Note" } }
            ]
        }]
    }"#;
    let mut v: serde_json::Value = serde_json::from_str(IDENTITY_FK).unwrap();
    // Memory mode (no `db`): the probe keeps user_id.
    let mem: Design = serde_json::from_value(v.clone()).unwrap();
    assert!(!mem.wants_db());
    let mem_gen = testgen::acceptance_rs(&mem, &mem.modules[0]);
    assert!(
        mem_gen.contains("\"user_id\": 1"),
        "memory-mode probe body must keep the identity fk (no DTO to drop it): {mem_gen}"
    );
    // DB mode (same design + `db`): the probe drops user_id (the #34 DTO omission).
    v["dependencies"] = serde_json::json!(["db", "auth"]);
    let dbm: Design = serde_json::from_value(v).unwrap();
    let db_gen = testgen::acceptance_rs(&dbm, &dbm.modules[0]);
    assert!(
        !db_gen.contains("\"user_id\":"),
        "db-mode probe body omits the server-owned identity fk: {db_gen}"
    );
}

#[test]
fn memory_mode_tests_cover_success_and_listed_errors() {
    let design = golden(false);
    let module = &design.modules[0]; // todos (with comments subroute)
    let generated = testgen::acceptance_rs(&design, module);

    assert!(
        generated.contains("GENERATED by jerrycan gen-tests"),
        "tool-owned banner"
    );
    assert!(
        generated.contains("use route_todos::module;"),
        "{generated}"
    );
    // success tests:
    for expected in [
        "async fn list_todos_returns_200",
        "async fn create_todo_returns_201",
        "async fn show_todo_returns_200",
        "async fn delete_todo_returns_204",
        "async fn list_comments_returns_200",
        "async fn create_comment_returns_201",
    ] {
        assert!(
            generated.contains(expected),
            "missing {expected}\n{generated}"
        );
    }
    // listed 404s:
    assert!(
        generated.contains("async fn show_todo_missing_id_is_404"),
        "{generated}"
    );
    assert!(generated.contains("/todos/999999"), "{generated}");
    // seed-then-request flow uses the creator:
    assert!(generated.contains("post_json(\"/todos/\""), "{generated}");
    // memory preamble — no db:
    assert!(!generated.contains("jerrycan::db"), "{generated}");
    assert_eq!(
        testgen::test_count(&generated),
        8,
        "6 success + 2 listed 404s"
    );
}

#[test]
fn db_mode_preamble_migrates_an_in_memory_database() {
    let design = golden(true);
    let module = &design.modules[0];
    let generated = testgen::acceptance_rs(&design, module);
    assert!(
        generated.contains("Db::connect(\"sqlite::memory:\")"),
        "{generated}"
    );
    assert!(
        generated.contains("include_str!(\"../migrations/sqlite/0001_create_tables.sql\")"),
        "{generated}"
    );
    assert!(generated.contains(".extend(db)"), "{generated}");
}

/// A module's TestApp migrates the FULL workspace schema (issue #14), not just
/// its own tables — so a handler that legitimately writes ANOTHER module's table
/// no longer 500s with "no such table" under the module TestApp. The `orders`
/// TestApp must include BOTH its own migration (relative) AND the `products`
/// module's migration (cross-crate `../../products/...`).
#[test]
fn module_testapp_migrates_the_full_workspace_schema() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "shop-api",
        "contract_version": 1,
        "dependencies": ["db"],
        "modules": [
            { "name": "products",
              "entities": [{ "name": "Product", "fields": [
                  { "name": "sku", "type": "string" } ]}],
              "endpoints": [{ "operation_id": "list_products", "method": "GET", "path": "/",
                  "success": { "status": 200, "entity": "Product", "list": true } }] },
            { "name": "orders",
              "entities": [{ "name": "Order", "fields": [
                  { "name": "total", "type": "integer" } ]}],
              "endpoints": [{ "operation_id": "list_orders", "method": "GET", "path": "/",
                  "success": { "status": 200, "entity": "Order", "list": true } }] }
        ]
    }))
    .unwrap();
    let orders = design.modules.iter().find(|m| m.name == "orders").unwrap();
    let generated = testgen::acceptance_rs(&design, orders);
    // Its own tables (relative include).
    assert!(
        generated.contains("include_str!(\"../migrations/sqlite/0001_create_tables.sql\")"),
        "orders TestApp migrates its own tables: {generated}"
    );
    // AND the products module's tables (cross-crate include) — the whole point:
    // an orders handler may write the products table.
    assert!(
        generated
            .contains("include_str!(\"../../products/migrations/sqlite/0001_create_tables.sql\")"),
        "orders TestApp must also migrate the products module's tables: {generated}"
    );
}

#[test]
fn unsupported_error_cases_become_an_agent_todo_comment() {
    let mut design = golden(false);
    design.modules[0].endpoints[1]
        .errors
        // `platform::design` config structs are `#[non_exhaustive]` (#145): a
        // downstream crate (an integration test is a separate crate) constructs
        // them via the design contract (serde), never a struct literal.
        .push(
            serde_json::from_value(serde_json::json!({
                "status": 409,
                "code": "JC0409",
                "when": "duplicate title",
            }))
            .unwrap(),
        );
    let generated = testgen::acceptance_rs(&design, &design.modules[0].clone());
    assert!(
        generated.contains("// AGENT TODO: design lists 409 (duplicate title)"),
        "{generated}"
    );
}

/// A PUBLIC endpoint in an auth design gets a success test but NO
/// `_without_auth_is_401` test, and its request carries no session cookie. WHY
/// (Rule 9): `public: true` marks a credential-issuing route (login/register)
/// that is unauthenticated BY DESIGN — generating a 401 test or threading a
/// cookie would assert the opposite of the contract (fix F1).
#[test]
fn public_endpoints_get_no_401_test_and_no_cookie() {
    // An auth design (so guarded endpoints would normally get cookies + 401
    // tests) with one PUBLIC register POST and one ordinary guarded POST.
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "auth-api",
        "contract_version": 1,
        "auth": { "model": "jwt", "roles": ["admin"] },
        "dependencies": ["auth"],
        "modules": [{
            "name": "accounts",
            "entities": [{ "name": "User", "fields": [
                { "name": "email", "type": "string" },
                { "name": "password", "type": "string" }
            ]}],
            "endpoints": [
                { "operation_id": "register", "method": "POST", "path": "/register",
                  "public": true,
                  "request_body": { "entity": "User" },
                  "success": { "status": 201, "entity": "User" } },
                { "operation_id": "create_account", "method": "POST", "path": "/",
                  "auth_required": true,
                  "request_body": { "entity": "User" },
                  "success": { "status": 201, "entity": "User" } }
            ]
        }]
    }))
    .unwrap();
    let module = &design.modules[0];
    let generated = testgen::acceptance_rs(&design, module);

    // The public register route still gets its success test...
    assert!(
        generated.contains("async fn register_returns_201"),
        "public route still gets a success test: {generated}"
    );
    // ...but NO 401 test (it is unauthenticated by design)...
    assert!(
        !generated.contains("register_without_auth_is_401"),
        "public route must NOT get a 401 test: {generated}"
    );
    // ...and its request uses the plain (cookie-less) verb.
    assert!(
        generated.contains("t.post_json(\"/accounts/register\""),
        "public route request must carry no cookie: {generated}"
    );

    // The ordinary guarded endpoint still gets BOTH a credentialed success request
    // and a 401 test — the carve-out is narrow to public routes.
    assert!(
        generated.contains("create_account_without_auth_is_401"),
        "a guarded route still gets its 401 test: {generated}"
    );
    assert!(
        generated.contains("t.post_json_with(\"/accounts/\""),
        "a guarded route still threads the credential: {generated}"
    );

    // JWT model (issue #29): the credential is a `Authorization: Bearer <jwt>`
    // header minted with `jwt::encode` + `Auth::jwt_key()`, NOT a session cookie —
    // this is what proves the generated tests exercise the REAL Bearer guard.
    assert!(
        generated.contains("(\"authorization\", &test_cookie())"),
        "jwt guarded request threads the Authorization header, not a cookie: {generated}"
    );
    assert!(
        generated.contains("jerrycan::auth::jwt::encode(&shared::SessionUser")
            && generated.contains("auth.jwt_key())")
            && generated.contains("format!(\"Bearer {token}\")"),
        "jwt preamble mints a Bearer token via jwt::encode + jwt_key: {generated}"
    );
    assert!(
        !generated.contains("jerrycan_session=") && !generated.contains("(\"cookie\","),
        "jwt model must not mint or thread a session cookie: {generated}"
    );
}

/// A tenant-owned module's guarded handlers take `Dep<Tenant>`; the generated
/// test app must register the `tenant` factory and SEED a membership row, or the
/// guard 403s every guarded request (a false stub-test failure). WHY this matters:
/// the seed is what keeps these acceptance tests failing for the RIGHT reason
/// (stub-500), not an unseeded-membership 403. It must (a) migrate the tenant
/// module's tables (the `{tenant}_members` table the guard queries lives there),
/// (b) insert a tenant row whose enum column uses a DECLARED value so the CHECK
/// passes, and (c) insert the membership row, then provide the `tenant` factory.
#[test]
fn tenancy_module_tests_seed_membership_and_provide_the_guard() {
    let s = include_str!("../../../conformance/designs/reference-slice.design.json");
    let design: Design = serde_json::from_str(s).unwrap();
    let leads = design
        .modules
        .iter()
        .find(|m| m.name == "leads")
        .expect("leads module");
    let generated = testgen::acceptance_rs(&design, leads);

    // The Tenant factory is registered app-wide for the guard to resolve.
    assert!(
        generated.contains(".provide_dep(shared::tenant)"),
        "{generated}"
    );
    // The tenant module's migration is pulled in (cross-crate) so the membership
    // table exists in this module's test database.
    assert!(
        generated.contains(
            "include_str!(\"../../workspaces/migrations/sqlite/0001_create_tables.sql\")"
        ),
        "tenant migration cross-included: {generated}"
    );
    // Seeds: a tenant row (enum `plan` uses a declared value, not 'test-value', so
    // the CHECK passes) and the membership row for user 1.
    assert!(
        generated.contains("INSERT INTO \\\"workspaces\\\"") && generated.contains("'trial'"),
        "tenant row seeded with a valid enum value: {generated}"
    );
    assert!(
        generated.contains(
            "INSERT INTO \\\"workspace_members\\\" (user_id, workspace_id, role) VALUES (1, 1, 'owner')"
        ),
        "membership row seeded for user 1: {generated}"
    );
    // The raw-SQL seed needs ConnectionTrait in scope.
    assert!(
        generated.contains("use jerrycan::db::sea_orm::ConnectionTrait;"),
        "{generated}"
    );

    // The tenant module ITSELF (workspaces) owns no tenant-owned entity, so its
    // REGULAR app() neither seeds nor provides the guard (no false coupling —
    // its create tests must see an empty tenant table so the id echo holds).
    // Its own reads (`list_workspaces`/`show_workspace`) are `public: true`
    // (public discovery, per the design), so no endpoint here takes `Dep<Tenant>`.
    // The #107 member tests bring their own SELF-CONTAINED member_app(); the
    // membership seeds + guard registration live there, never in app().
    let workspaces = design
        .modules
        .iter()
        .find(|m| m.name == "workspaces")
        .expect("workspaces module");
    let ws_gen = testgen::acceptance_rs(&design, workspaces);
    let app_fn = ws_gen
        .split("async fn app()")
        .nth(1)
        .expect("app() present")
        .split("#[tokio::test]")
        .next()
        .unwrap();
    assert!(
        !app_fn.contains(".provide_dep(shared::tenant)") && !app_fn.contains("workspace_members"),
        "the tenant module's regular app() must neither seed membership nor provide the guard: {app_fn}"
    );
    let member_fn = ws_gen
        .split("async fn member_app()")
        .nth(1)
        .expect("member_app() present (#107)")
        .split("#[tokio::test]")
        .next()
        .unwrap();
    assert!(
        member_fn.contains(".provide_dep(shared::tenant)")
            && member_fn.contains("INSERT INTO \\\"workspace_members\\\""),
        "member_app() seeds membership and provides the guard itself: {member_fn}"
    );
}

/// The generated JSON request BODY for an enum field must use a DECLARED value,
/// not the generic `"test-value"` placeholder. WHY: the generator's own
/// migration emits `CHECK ("role" IN ('admin','user'))`, so a body with
/// `"role": "test-value"` makes the happy-path acceptance test fail at run time
/// with an opaque `JC0510` even when the handler is correctly implemented — the
/// gen-test would contradict the gen-migration. The body must agree with the
/// SQL seed (`seed_sql_value`), which already uses the first declared value.
#[test]
fn generated_request_body_uses_a_declared_enum_value_not_the_placeholder() {
    let s = include_str!("../../../conformance/designs/reference-slice.design.json");
    let design: Design = serde_json::from_str(s).unwrap();
    let users = design
        .modules
        .iter()
        .find(|m| m.name == "users")
        .expect("users module");
    let generated = testgen::acceptance_rs(&design, users);
    // `register`'s body posts the `User` entity, whose `role` is an enum
    // `["admin","user"]` → the first declared value, NOT `"test-value"`.
    assert!(
        generated.contains("\"role\": \"admin\""),
        "enum field uses its first declared value: {generated}"
    );
    assert!(
        !generated.contains("\"role\": \"test-value\""),
        "enum field must NOT use the placeholder (trips the CHECK): {generated}"
    );
    // A plain (non-enum) string field still uses the placeholder.
    assert!(
        generated.contains("\"email\": \"test-value\""),
        "non-enum string keeps the placeholder: {generated}"
    );
}

/// A tenant-owned entity's create/update bodies must carry the fk column the
/// `belongs_to` derives, valued at the SEEDED tenant (workspace 1). WHY: without
/// it the generated request body is missing a NOT-NULL column, so the handler's
/// `Json<Lead>` deserialization rejects it 422 — the test fails before reaching
/// the stub, masking whether the handler is actually implemented. With the fk
/// present the request reaches the stub (500 on stubs → green when implemented).
#[test]
fn tenant_owned_fixtures_carry_the_foreign_key() {
    let s = include_str!("../../../conformance/designs/reference-slice.design.json");
    let design: Design = serde_json::from_str(s).unwrap();
    let leads = design
        .modules
        .iter()
        .find(|m| m.name == "leads")
        .expect("leads module");
    let generated = testgen::acceptance_rs(&design, leads);
    // create_lead (POST /) and update_lead (PUT /{id}) both send a Lead body;
    // each must include the workspace_id fk valued at the seeded tenant (1).
    assert!(
        generated.contains("\"workspace_id\": 1"),
        "Lead fixture bodies must carry workspace_id: 1: {generated}"
    );

    // A non-tenant-owned entity's body must NOT gain a phantom fk.
    let workspaces = design
        .modules
        .iter()
        .find(|m| m.name == "workspaces")
        .expect("workspaces module");
    let ws_gen = testgen::acceptance_rs(&design, workspaces);
    assert!(
        !ws_gen.contains("\"workspace_id\""),
        "Workspace (the tenant itself) must not carry a self fk: {ws_gen}"
    );
}

/// A tenant-owned module with a creator + GET /{id} gets a cross-tenant
/// isolation test: user 1 creates a row in workspace 1, user 2 (workspace 2)
/// must NOT be able to read it. This is the security contract — it fails on
/// stubs (500) and stays red if the agent uses unscoped repo methods (which
/// would return the foreign row), going green only with scoped get_for.
#[test]
fn tenant_owned_modules_get_isolation_tests() {
    let s = include_str!("../../../conformance/designs/reference-slice.design.json");
    let d: Design = serde_json::from_str(s).unwrap();
    let leads = d
        .modules
        .iter()
        .find(|m| m.name == "leads")
        .expect("leads module");
    let out = testgen::acceptance_rs(&d, leads);
    assert!(
        out.contains("async fn tenant_a_cannot_read_tenant_b_leads()"),
        "{out}"
    );
    assert!(out.contains("404"), "cross-tenant get must 404: {out}");
    // The isolation test seeds a SECOND tenant (workspace 2) + membership for
    // user 2, and mints user 2's cookie via the generalized helper.
    assert!(
        out.contains("fn seed_second_tenant(") && out.contains("test_cookie_for("),
        "isolation test needs a second-tenant seed + per-user cookie helper: {out}"
    );
    // test_cookie() stays back-compat (delegates to test_cookie_for(1)).
    assert!(
        out.contains("test_cookie_for(1)"),
        "test_cookie() must delegate to test_cookie_for(1): {out}"
    );
    // The DELETE leg is role-gated (owner); user 2's membership must seed the
    // owner role so the role check passes and the SCOPED remove_for 404s (proving
    // isolation, not a role rejection).
    assert!(
        out.contains("'owner'"),
        "second tenant membership seeds the owner role: {out}"
    );

    // The non-tenant-owned tenant module (workspaces) gets NO cross-tenant
    // isolation test — AND, because its list is `public: true` (public discovery,
    // per the design), no I1 test either (a public list can't be membership-scoped).
    let workspaces = d
        .modules
        .iter()
        .find(|m| m.name == "workspaces")
        .expect("workspaces module");
    let ws_gen = testgen::acceptance_rs(&d, workspaces);
    assert!(
        !ws_gen.contains("cannot_read_tenant_b"),
        "non-tenant-owned module gets no isolation test: {ws_gen}"
    );
    assert!(
        !ws_gen.contains("seeds_only_the_creators_membership"),
        "a public tenant list can't be membership-scoped, so no I1 test: {ws_gen}"
    );
}

/// #96/#97: a FLAT (MembershipSet) tenant-owned module with a guarded creator gets
/// the flat-WRITE isolation test — user 1 POSTs a create whose tenant fk is tenant 2
/// (foreign) and must get 403 (`create_for_memberships`'s WITH CHECK). This is the
/// write-side backstop that #97's make-impossible needs: the bare `insert` is gone,
/// so a create MUST scope to the caller's memberships. A path-scoped (nested) module
/// and the tenant ROOT do NOT get it (their writes are not body-fk scoped).
#[test]
fn flat_tenant_module_gets_the_write_403_isolation_test() {
    let s = include_str!("../../../conformance/designs/reference-slice.design.json");
    let d: Design = serde_json::from_str(s).unwrap();

    // leads (FLAT) — the write-403 test is emitted, aimed at tenant 2, asserting 403.
    let leads = d.modules.iter().find(|m| m.name == "leads").unwrap();
    let out = testgen::acceptance_rs(&d, leads);
    assert!(
        out.contains("async fn leads_flat_write_into_foreign_tenant_is_403()"),
        "the flat-write isolation test must be emitted for a flat tenant module: {out}"
    );
    // The body's tenant fk is aimed at tenant 2 (a tenant user 1 is not a member of).
    let iso = out
        .split("async fn leads_flat_write_into_foreign_tenant_is_403()")
        .nth(1)
        .expect("flat-write isolation fn present");
    assert!(
        iso.contains("\"workspace_id\": 2"),
        "the create body must aim its tenant fk at the foreign tenant 2: {iso}"
    );
    assert!(
        iso.contains("test_cookie_for(1)") && iso.contains("403"),
        "user 1 POSTs and must get 403 (create_for_memberships WITH CHECK): {iso}"
    );

    // api-keys (also FLAT) gets its own write-403 test.
    let api_keys = d.modules.iter().find(|m| m.name == "api-keys").unwrap();
    let ak = testgen::acceptance_rs(&d, api_keys);
    assert!(
        ak.contains("async fn api_keys_flat_write_into_foreign_tenant_is_403()"),
        "the flat-write isolation test must be emitted for api-keys too: {ak}"
    );

    // The tenant ROOT (workspaces) is NOT tenant-OWNED → no flat-write test.
    let workspaces = d.modules.iter().find(|m| m.name == "workspaces").unwrap();
    let ws = testgen::acceptance_rs(&d, workspaces);
    assert!(
        !ws.contains("flat_write_into_foreign_tenant_is_403"),
        "the tenant root gets no flat-write isolation test: {ws}"
    );

    // A PATH-SCOPED (nested) module is scoped by the verified path tenant, not a body
    // fk, so it gets the path-scoped read isolation test but NOT the flat-write test.
    const CLUBS: &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" } },
                  { "operation_id": "get_book", "method": "GET", "path": "/{id}", "auth_required": true,
                    "success": { "status": 200, "entity": "Book" } } ] }
        ]
    }"#;
    let nested: Design = serde_json::from_str(CLUBS).unwrap();
    let books = nested.modules.iter().find(|m| m.name == "books").unwrap();
    let books_gen = testgen::acceptance_rs(&nested, books);
    assert!(
        !books_gen.contains("flat_write_into_foreign_tenant_is_403"),
        "a path-scoped nested module gets no flat-write isolation test: {books_gen}"
    );
}

/// A per-user (identity-owned) module gets a #79 isolation test: user B cannot
/// read/list/delete user A's row. WHY (Rule 9): the identity shape JC0540 steers
/// toward had NO backstop; this is it. It passes only with the owner-scoped
/// accessors — the unscoped repo methods are not even generated.
#[test]
fn per_user_identity_owned_modules_get_isolation_tests() {
    const FITNESS: &str = r#"{
        "name": "fitness-api", "contract_version": 1,
        "auth": { "model": "session", "roles": ["user"] },
        "dependencies": ["db", "auth"],
        "modules": [
            { "name": "users",
              "entities": [{ "name": "User", "fields": [{ "name": "email", "type": "string" }] }],
              "endpoints": [] },
            { "name": "workouts",
              "entities": [{ "name": "Workout",
                  "belongs_to": [{ "entity": "User", "on_delete": "cascade" }],
                  "fields": [{ "name": "id", "type": "integer" },
                             { "name": "distance", "type": "float" }] }],
              "endpoints": [
                  { "operation_id": "create_workout", "method": "POST", "path": "/", "auth_required": true,
                    "request_body": { "entity": "Workout" },
                    "success": { "status": 201, "entity": "Workout" } },
                  { "operation_id": "list_workouts", "method": "GET", "path": "/", "auth_required": true,
                    "success": { "status": 200, "entity": "Workout", "list": true } },
                  { "operation_id": "get_workout", "method": "GET", "path": "/{id}", "auth_required": true,
                    "success": { "status": 200, "entity": "Workout" } },
                  { "operation_id": "delete_workout", "method": "DELETE", "path": "/{id}", "auth_required": true,
                    "success": { "status": 204 } } ] }
        ]
    }"#;
    let d: Design = serde_json::from_str(FITNESS).unwrap();
    let workouts = d.modules.iter().find(|m| m.name == "workouts").unwrap();
    let out = testgen::acceptance_rs(&d, workouts);
    assert!(
        out.contains("async fn user_a_cannot_read_user_b_workouts()"),
        "per-user isolation test emitted: {out}"
    );
    // Two distinct user sessions, NO tenant seeding.
    assert!(
        out.contains("test_cookie_for(1)") && out.contains("test_cookie_for(2)"),
        "acts as two distinct users: {out}"
    );
    assert!(
        !out.contains("seed_second_tenant"),
        "per-user isolation needs no tenant seed: {out}"
    );
    // Cross-user get + list + delete all assert 404/absent.
    assert!(
        out.contains("cross-user get must 404") && out.contains("cross-user delete must 404"),
        "get + delete legs present: {out}"
    );
    assert!(
        out.contains("cross-user list must NOT contain user 1's row"),
        "list leg present: {out}"
    );
}

/// #240 Part B: a per-user module with a creator + `PUT /{id}` ONLY (no list, no
/// `GET /{id}`, no delete) emits NO isolation test. WHY (Rule 9): a `PUT` is not a
/// read leg, so there is no way to READ another user's row to probe — the previous
/// setup-only body asserted NOTHING about isolation yet bound `row`/`cookie2`
/// unused, which `jerrycan check`'s `clippy -D warnings` rejects. A clean omission
/// is honest; a vacuous `*_cannot_read_*` body is not. The write's own success +
/// 401 probes still cover it, and genroute's owner-scoped repo is the enforcement.
#[test]
fn per_user_create_update_only_module_gets_no_isolation_test() {
    const NOTES: &str = r#"{
        "name": "notes-api", "contract_version": 1,
        "auth": { "model": "session", "roles": ["user"] },
        "dependencies": ["db", "auth"],
        "modules": [
            { "name": "users",
              "entities": [{ "name": "User", "fields": [{ "name": "email", "type": "string" }] }],
              "endpoints": [] },
            { "name": "notes",
              "entities": [{ "name": "Note",
                  "belongs_to": [{ "entity": "User", "on_delete": "cascade" }],
                  "fields": [{ "name": "id", "type": "integer" }, { "name": "body", "type": "string" }] }],
              "endpoints": [
                  { "operation_id": "create_note", "method": "POST", "path": "/", "auth_required": true,
                    "request_body": { "entity": "Note" }, "success": { "status": 201, "entity": "Note" } },
                  { "operation_id": "update_note", "method": "PUT", "path": "/{id}", "auth_required": true,
                    "request_body": { "entity": "Note" }, "success": { "status": 200, "entity": "Note" } } ] }
        ]
    }"#;
    let d: Design = serde_json::from_str(NOTES).unwrap();
    let notes = d.modules.iter().find(|m| m.name == "notes").unwrap();
    let out = testgen::acceptance_rs(&d, notes);
    // No isolation test at all — not even a vacuous setup-only negative control.
    assert!(
        !out.contains("cannot_read_user_b"),
        "a read-less per-user module must emit NO isolation test: {out}"
    );
    // And no orphaned `cookie2` (the tell of the old setup-only body).
    assert!(
        !out.contains("let cookie2 = test_cookie_for(2)"),
        "no orphaned user-2 credential without a probe to consume it: {out}"
    );
    // Sanity: the write endpoints still get their own probes (the suite isn't empty).
    assert!(
        out.contains("create_note") && out.contains("update_note"),
        "the write endpoints still get their success/401 probes: {out}"
    );
}

/// The public-read/owner-write feed design (#105): Post is per-user identity-owned
/// with `public_read: true`; `list_posts` is DECLARED `auth_required` (the entity
/// flag must override it — the exact shape the blessed fixture uses).
const FEED: &str = r#"{
    "name": "feedapp", "contract_version": 1,
    "auth": { "model": "session", "roles": ["user"] },
    "dependencies": ["db", "auth"],
    "modules": [
        { "name": "users",
          "entities": [{ "name": "User", "fields": [{ "name": "email", "type": "string" }] }],
          "endpoints": [] },
        { "name": "posts",
          "entities": [{ "name": "Post", "public_read": true,
              "belongs_to": [{ "entity": "User", "on_delete": "cascade" }],
              "fields": [{ "name": "title", "type": "string" }] }],
          "endpoints": [
              { "operation_id": "list_posts", "method": "GET", "path": "/", "auth_required": true,
                "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 } } ] }
    ]
}"#;

/// #105 gate-lie fix: genroute emits a `public_read` GET UNGUARDED (no
/// CurrentUser) even when the design declares it `auth_required` — so testgen
/// must NOT emit its `_without_auth_is_401` probe. WHY (Rule 9): before the
/// shared predicate, testgen keyed on the raw `is_guarded()` and asserted a
/// no-cookie `list_posts` 401s, while the correct generated handler 200s — a
/// valid design produced a PERMANENTLY-RED acceptance test (green-means-safe
/// broken in the worst direction). The success probe must also run WITHOUT a
/// credential (anonymous is the contract). Writes keep their 401 probes.
#[test]
fn public_read_gets_lose_the_401_probe_and_probe_anonymously() {
    let d: Design = serde_json::from_str(FEED).unwrap();
    let posts = d.modules.iter().find(|m| m.name == "posts").unwrap();
    let out = testgen::acceptance_rs(&d, posts);
    assert!(
        !out.contains("list_posts_without_auth_is_401")
            && !out.contains("get_post_without_auth_is_401"),
        "a public_read GET must not get a 401 probe (the handler is unguarded — the test would be red-when-correct): {out}"
    );
    let list_probe = out
        .split("async fn list_posts_returns_200")
        .nth(1)
        .expect("list success probe present")
        .split("async fn")
        .next()
        .unwrap();
    assert!(
        list_probe.contains("t.get(\"/posts/\")") && !list_probe.contains("test_cookie"),
        "the public list probes anonymously: {list_probe}"
    );
    // Writes stay guarded: probe with a credential AND keep the 401 test.
    for probe in [
        "create_post_without_auth_is_401",
        "update_post_without_auth_is_401",
        "delete_post_without_auth_is_401",
    ] {
        assert!(out.contains(probe), "{probe} must stay: {out}");
    }
}

/// The #105 isolation variant: a `public_read` module gets the public-read/
/// owner-write test — anon list contains ANOTHER user's row, anon detail 200s,
/// anon create 401s, a non-owner PUT/DELETE 404s with the row SURVIVING, the
/// owner's PUT succeeds — and does NOT get the #79 cross-user test (whose
/// read-denial legs would be red on a correct public feed).
#[test]
fn public_read_modules_get_the_owner_write_isolation_test() {
    let d: Design = serde_json::from_str(FEED).unwrap();
    let posts = d.modules.iter().find(|m| m.name == "posts").unwrap();
    let out = testgen::acceptance_rs(&d, posts);
    assert!(
        out.contains("async fn anon_reads_but_only_the_owner_writes_posts()"),
        "public_read isolation test emitted: {out}"
    );
    assert!(
        out.contains("SECURITY (#105)"),
        "carries the #105 security doc-comment: {out}"
    );
    assert!(
        !out.contains("async fn user_a_cannot_read_user_b_posts()"),
        "the #79 cross-user test must NOT be emitted for a public_read entity: {out}"
    );
    let body = out
        .split("async fn anon_reads_but_only_the_owner_writes_posts()")
        .nth(1)
        .unwrap()
        .split("#[tokio::test]")
        .next()
        .unwrap();
    for leg in [
        "anonymous list must 200 (public_read)",
        "must contain ANOTHER user's row",
        "anonymous detail must 200 (public_read)",
        "an anonymous create must 401",
        "a non-owner update must 404",
        "a non-owner delete must 404",
        "must SURVIVE a non-owner write attempt",
        "the OWNER's update must succeed",
    ] {
        assert!(body.contains(leg), "leg `{leg}` present: {body}");
    }
}

/// The `required_roles.is_empty()` conjunct in the shared predicate is
/// LOAD-BEARING: a role-gated GET on a `public_read` entity KEEPS its guard, so
/// it keeps its 401 probe and probes WITH a credential. Deleting the conjunct
/// (treating every GET on the entity as public) must turn this red — otherwise
/// an explicit role demand would be silently dropped.
#[test]
fn role_gated_get_on_a_public_read_entity_keeps_the_401_probe() {
    let mut d: Design = serde_json::from_str(FEED).unwrap();
    let posts_idx = d.modules.iter().position(|m| m.name == "posts").unwrap();
    d.modules[posts_idx]
        .endpoints
        .iter_mut()
        .find(|ep| ep.operation_id == "list_posts")
        .unwrap()
        .required_roles = vec!["user".to_string()];
    let posts = &d.modules[posts_idx];
    let out = testgen::acceptance_rs(&d, posts);
    assert!(
        out.contains("list_posts_without_auth_is_401"),
        "a role-gated GET keeps its guard and its 401 probe: {out}"
    );
    let list_probe = out
        .split("async fn list_posts_returns_200")
        .nth(1)
        .expect("list success probe present")
        .split("async fn")
        .next()
        .unwrap();
    assert!(
        list_probe.contains("test_cookie"),
        "a role-gated GET probes WITH a credential: {list_probe}"
    );
}

/// The strict-resolution pin (#105 whole-branch review): an ENTITY-LESS
/// `auth_required` GET (`GET /stats`, custom-JSON success, no body, no
/// `{param}`) in the `public_read` module KEEPS its `_without_auth_is_401`
/// probe. WHY (Rule 9): the lenient first-entity fallback classified it as a
/// public read of `Post` — an entity it never reads — so the
/// declared-authenticated endpoint shipped anonymous with NO 401 probe: a
/// silent guard drop under a green gate. The explicit public reads keep losing
/// their probes (they are genuinely public), and the probe suite stays green
/// on a correct app.
#[test]
fn entityless_authed_get_keeps_the_401_probe_beside_public_read() {
    let mut v: serde_json::Value = serde_json::from_str(FEED).unwrap();
    v["modules"][1]["endpoints"]
        .as_array_mut()
        .unwrap()
        .push(serde_json::json!({
            "operation_id": "get_stats", "method": "GET", "path": "/stats",
            "auth_required": true, "success": { "status": 200 }
        }));
    let d: Design = serde_json::from_value(v).unwrap();
    let posts = d.modules.iter().find(|m| m.name == "posts").unwrap();
    let out = testgen::acceptance_rs(&d, posts);
    assert!(
        out.contains("get_stats_without_auth_is_401"),
        "an entity-less auth_required GET keeps its 401 probe: {out}"
    );
    // The explicit public reads stay probe-free — the fix must not over-guard.
    assert!(
        !out.contains("list_posts_without_auth_is_401")
            && !out.contains("get_post_without_auth_is_401"),
        "the explicit public_read GETs stay 401-probe-free: {out}"
    );
}

/// A path-scoped NESTED tenant module (BookClubs `/clubs/{club_id}/books`) gets a
/// cross-tenant isolation test with the mount pinned to tenant 1 — the exact #78
/// nested-creator leak that had NO coverage before. A member of club 2 gets 404 on
/// club 1's book; the list leg is skipped (user 2 can't reach club 1's collection).
#[test]
fn nested_path_scoped_module_gets_isolation_test_with_pinned_tenant() {
    const CLUBS: &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" } },
                  { "operation_id": "list_clubs", "method": "GET", "path": "/", "auth_required": true,
                    "success": { "status": 200, "entity": "Club", "list": true } } ] },
            { "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" } },
                  { "operation_id": "get_book", "method": "GET", "path": "/{id}", "auth_required": true,
                    "success": { "status": 200, "entity": "Book" } } ] }
        ]
    }"#;
    let d: Design = serde_json::from_str(CLUBS).unwrap();
    let books = d.modules.iter().find(|m| m.name == "books").unwrap();
    let out = testgen::acceptance_rs(&d, books);
    assert!(
        out.contains("async fn tenant_a_cannot_read_tenant_b_books()"),
        "nested isolation test emitted: {out}"
    );
    // In the ISOLATION test the mount's tenant fk is pinned to tenant 1 (not the
    // literal `{club_id}`): user 1 creates club 1's book, user 2 (a member of club 2
    // only) reads it and 404s. (The per-endpoint success tests now pin the mount the
    // same way — issue #81, covered by `subroute_mount_param_is_substituted_in_per_endpoint_urls`.)
    let iso = out
        .split("async fn tenant_a_cannot_read_tenant_b_books()")
        .nth(1)
        .expect("isolation fn present");
    assert!(
        iso.contains("\"/clubs/1/\"") && iso.contains("/clubs/1/{id}"),
        "isolation probe URLs pin the tenant fk to 1: {iso}"
    );
    assert!(
        !iso.contains("{club_id}"),
        "the isolation test carries no unsubstituted tenant param: {iso}"
    );
    assert!(
        out.contains("cross-tenant get must 404"),
        "get leg 404s: {out}"
    );
    // The list leg is skipped for a nested route (user 2 can't reach club 1's list).
    assert!(
        !out.contains("user 2 lists their own"),
        "nested route emits no list leg: {out}"
    );

    // The tenant module (clubs) — guarded create AND guarded list — gets the I1 test.
    let clubs = d.modules.iter().find(|m| m.name == "clubs").unwrap();
    let clubs_out = testgen::acceptance_rs(&d, clubs);
    assert!(
        clubs_out.contains("async fn creating_a_club_seeds_only_the_creators_membership()"),
        "I1 tenant-collection-create test emitted: {clubs_out}"
    );
    assert!(
        clubs_out.contains("the creator's list MUST contain the new Club")
            && clubs_out.contains("a non-creator's list must NOT contain the new Club"),
        "I1 asserts creator-lists-own + second-user-empty: {clubs_out}"
    );
}

/// #245 (the #240 sibling): a tenant-owned entity mounted on a param whose name
/// DIFFERS from the canonical tenant fk (`/happenings/{org_id}` for tenancy
/// `Organization`, canonical fk `organization_id`) must still get a CONCRETE
/// isolation probe. Before the fix, `tenant_owned_isolation_test` pinned only the
/// canonical fk / join child_fk tokens, so the non-canonical `{org_id}` survived
/// verbatim into the URL — `/happenings/{org_id}/` — and the cross-tenant negative
/// control 400'd at setup (`Path<i64>` can't parse `{org_id}`), never greenable. The
/// fix routes the probe base through `concrete_mount_base`, pinning EVERY `{param}`
/// to the seeded id 1 (the same helper the per-endpoint tests already use). WHY
/// (Rule 9): a security negative control that can NEVER go green is worse than none —
/// the agent deletes it or wedges on it. This is the regression guard.
#[test]
fn tenant_isolation_probe_pins_a_noncanonical_mount_param() {
    const HAPPENINGS: &str = r#"{
        "name": "orgs-api", "contract_version": 1,
        "auth": { "model": "session", "roles": ["owner", "member"] },
        "dependencies": ["db", "auth"],
        "tenancy": { "entity": "Organization", "member_roles": ["owner", "member"] },
        "modules": [
            { "name": "organizations",
              "entities": [{ "name": "Organization", "fields": [
                  { "name": "id", "type": "integer" }, { "name": "name", "type": "string" } ]}],
              "endpoints": [
                  { "operation_id": "create_organization", "method": "POST", "path": "/", "auth_required": true,
                    "request_body": { "entity": "Organization" }, "success": { "status": 201, "entity": "Organization" } } ] },
            { "name": "events", "mount": "/happenings/{org_id}",
              "entities": [{ "name": "Event", "belongs_to": [{ "entity": "Organization" }],
                  "fields": [{ "name": "id", "type": "integer" }, { "name": "title", "type": "string" }] }],
              "endpoints": [
                  { "operation_id": "create_event", "method": "POST", "path": "/", "auth_required": true,
                    "request_body": { "entity": "Event" }, "success": { "status": 201, "entity": "Event" } },
                  { "operation_id": "list_events", "method": "GET", "path": "/", "auth_required": true,
                    "success": { "status": 200, "entity": "Event", "list": true } },
                  { "operation_id": "get_event", "method": "GET", "path": "/{id}", "auth_required": true,
                    "success": { "status": 200, "entity": "Event" } } ] }
        ]
    }"#;
    let d: Design = serde_json::from_str(HAPPENINGS).unwrap();
    let events = d.modules.iter().find(|m| m.name == "events").unwrap();
    let out = testgen::acceptance_rs(&d, events);
    let iso = out
        .split("async fn tenant_a_cannot_read_tenant_b_events()")
        .nth(1)
        .expect("isolation fn present")
        .split("#[tokio::test]")
        .next()
        .unwrap();
    // The mount param is pinned to the seeded id 1 in EVERY probe leg (create, get,
    // list) — `{org_id}` (the non-canonical mount param) is the regression signal:
    // pre-fix it survived verbatim; the get leg's `format!("/happenings/{org_id}/…")`
    // would not even compile (`org_id` is an undefined named arg).
    assert!(
        !iso.contains("{org_id}"),
        "the isolation probe must carry NO unsubstituted mount param (#245): {iso}"
    );
    assert!(
        iso.contains("t.post_json_with(\"/happenings/1/\"")
            && iso.contains("t.get_with(\"/happenings/1/\"")
            && iso.contains("/happenings/1/{id}"),
        "every isolation probe URL pins the non-canonical mount param to 1: {iso}"
    );
}

/// A NESTED tenant module whose isolation probe carries create + LIST but no
/// `GET /{id}` shared by the two #240 nested-tenant tests below.
const NESTED_TENANT_LIST_ONLY: &str = r#"{
    "name": "orgs-api", "contract_version": 1,
    "auth": { "model": "session", "roles": ["owner", "member"] },
    "dependencies": ["db", "auth"],
    "tenancy": { "entity": "Org", "member_roles": ["owner", "member"] },
    "modules": [
        { "name": "orgs",
          "entities": [{ "name": "Org", "fields": [
              { "name": "id", "type": "integer" }, { "name": "name", "type": "string" } ]}],
          "endpoints": [
              { "operation_id": "create_org", "method": "POST", "path": "/", "auth_required": true,
                "request_body": { "entity": "Org" }, "success": { "status": 201, "entity": "Org" } } ] },
        { "name": "events", "mount": "/orgs/{org_id}",
          "entities": [{ "name": "Event", "belongs_to": [{ "entity": "Org" }],
              "fields": [{ "name": "id", "type": "integer" }, { "name": "title", "type": "string" }] }],
          "endpoints": [
              { "operation_id": "create_event", "method": "POST", "path": "/", "auth_required": true,
                "request_body": { "entity": "Event" }, "success": { "status": 201, "entity": "Event" } },
              { "operation_id": "list_events", "method": "GET", "path": "/", "auth_required": true,
                "success": { "status": 200, "entity": "Event", "list": true } } ] }
    ]
}"#;

/// #240 Part A: a NESTED tenant module with a creator + LIST but NO `GET /{id}` gets
/// a REAL cross-tenant isolation test. The list leg — SUPPRESSED for nested mounts
/// before, leaving ZERO isolation coverage AND unused `row`/`cookie2` bindings that
/// broke `clippy -D warnings` — now asserts a 404: user 2, a non-member of tenant 1,
/// is denied the pinned collection by the `Dep<Tenant>` path guard (proven in
/// `shared::tenant`). WHY (Rule 9): the negative control must actually ASSERT
/// isolation, not merely seed a row and bind unused credentials.
#[test]
fn nested_tenant_list_only_module_gets_a_cross_tenant_list_404_probe() {
    let d: Design = serde_json::from_str(NESTED_TENANT_LIST_ONLY).unwrap();
    let events = d.modules.iter().find(|m| m.name == "events").unwrap();
    let out = testgen::acceptance_rs(&d, events);
    assert!(
        out.contains("async fn tenant_a_cannot_read_tenant_b_events()"),
        "the nested tenant isolation test is emitted: {out}"
    );
    let iso = out
        .split("async fn tenant_a_cannot_read_tenant_b_events()")
        .nth(1)
        .expect("isolation fn present")
        .split("#[tokio::test]")
        .next()
        .unwrap();
    // The nested list leg carries a REAL 404 assertion at the pinned tenant-1 path.
    assert!(
        iso.contains("cross-tenant list must 404") && iso.contains("t.get_with(\"/orgs/1/\""),
        "the nested list leg asserts 404 at the pinned tenant path: {iso}"
    );
    // It consumes user 2's credential (so `cookie2` is not an unused binding)...
    assert!(
        iso.contains("&cookie2"),
        "the probe consumes cookie2: {iso}"
    );
    // ...and does NOT bind an unused `row` (a nested-list 404 leg reads neither the
    // by-id `id` nor the flat-list `id_value` derived from `row`).
    assert!(
        !iso.contains("let row"),
        "a nested-list-only probe must not bind an unused `row`: {iso}"
    );
    // NOT the FLAT 200-absent shape — that would false-fail against the guard 404.
    assert!(
        !iso.contains("user 2 lists their own"),
        "the nested list must not use the flat 200-absent assertion: {iso}"
    );
}

/// #240 Part B (tenant): a NESTED tenant module with a creator ONLY (no list, no
/// `GET /{id}`, no delete) emits NO isolation test — there is nothing to probe, so a
/// setup-only body with unused `row`/`cookie2` is wrong. A clean omission is honest.
#[test]
fn nested_tenant_create_only_module_gets_no_isolation_test() {
    let mut v: serde_json::Value = serde_json::from_str(NESTED_TENANT_LIST_ONLY).unwrap();
    // Drop the events LIST, leaving events with a creator only.
    let events_eps = v["modules"][1]["endpoints"].as_array_mut().unwrap();
    events_eps.retain(|ep| ep["operation_id"] != "list_events");
    let d: Design = serde_json::from_value(v).unwrap();
    let events = d.modules.iter().find(|m| m.name == "events").unwrap();
    let out = testgen::acceptance_rs(&d, events);
    assert!(
        !out.contains("cannot_read_tenant_b"),
        "a read-less nested tenant module must emit NO isolation test: {out}"
    );
    assert!(
        !out.contains("let cookie2 = test_cookie_for(2)"),
        "no orphaned user-2 credential without a probe to consume it: {out}"
    );
}

/// #172: the tenant ROOT module whose own `GET /{id}` detail route is GUARDED gets
/// a cross-tenant non-member-404 probe (the collection test only covers the root's
/// LIST, and `tenant_owned_isolation_test` skips the root). A root whose detail
/// route is PUBLIC (public discovery) gets NO probe — asserting 404 against a route
/// that returns 200 to everyone would false-fail it.
#[test]
fn tenant_root_with_a_guarded_detail_route_gets_the_non_member_404_probe() {
    // Base shape: a Workspace tenant root with a guarded create + guarded detail.
    const GUARDED: &str = r#"{
        "name": "ws-api", "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": "id", "type": "integer" }, { "name": "name", "type": "string" } ]}],
              "endpoints": [
                  { "operation_id": "create_workspace", "method": "POST", "path": "/", "auth_required": true,
                    "request_body": { "entity": "Workspace" }, "success": { "status": 201, "entity": "Workspace" } },
                  { "operation_id": "list_workspaces", "method": "GET", "path": "/", "auth_required": true,
                    "success": { "status": 200, "entity": "Workspace", "list": true } },
                  { "operation_id": "show_workspace", "method": "GET", "path": "/{id}", "auth_required": true,
                    "success": { "status": 200, "entity": "Workspace" } } ] }
        ]
    }"#;
    let d: Design = serde_json::from_str(GUARDED).unwrap();
    let ws = d.modules.iter().find(|m| m.name == "workspaces").unwrap();
    let out = testgen::acceptance_rs(&d, ws);
    assert!(
        out.contains("async fn a_non_member_cannot_read_the_workspace_detail()"),
        "guarded root detail route must get the non-member-404 probe: {out}"
    );
    let probe = out
        .split("async fn a_non_member_cannot_read_the_workspace_detail()")
        .nth(1)
        .expect("root-detail probe fn present");
    // The probe seeds a tenant-1 row as user 1, then asserts user 2 (a member of
    // tenant 2 only) gets 404 on the root's own detail route.
    assert!(
        probe.contains("&test_cookie_for(1))]).await;") && probe.contains("\"/workspaces/\""),
        "user 1 seeds the tenant-1 root row via the create: {probe}"
    );
    assert!(
        probe.contains("&format!(\"/workspaces/{id}\"), &[(\"cookie\", &test_cookie_for(2))])")
            && probe.contains("cross-tenant get on the tenant root must 404"),
        "the probe asserts a non-member (test_cookie_for(2)) 404s on the root detail route: {probe}"
    );

    // A root whose detail route is PUBLIC (discovery) emits NO probe — a 404
    // assertion would false-fail a route that returns 200 to everyone.
    let public_detail = GUARDED.replace(
        r#"{ "operation_id": "show_workspace", "method": "GET", "path": "/{id}", "auth_required": true,
                    "success": { "status": 200, "entity": "Workspace" } }"#,
        r#"{ "operation_id": "show_workspace", "method": "GET", "path": "/{id}", "public": true,
                    "success": { "status": 200, "entity": "Workspace" } }"#,
    );
    let dp: Design = serde_json::from_str(&public_detail).unwrap();
    let wsp = dp.modules.iter().find(|m| m.name == "workspaces").unwrap();
    let outp = testgen::acceptance_rs(&dp, wsp);
    assert!(
        !outp.contains("a_non_member_cannot_read_the_workspace_detail"),
        "a PUBLIC root detail route must emit NO non-member-404 probe: {outp}"
    );
}

/// A GRANDCHILD entity — transitively tenant-owned (`Contact belongs_to Account
/// belongs_to Org`, mount `/accounts/{account_id}`) — gets a cross-tenant
/// isolation test (issue #102). Before the transitive fix the generator BAILED on
/// such entities (direct-`belongs_to` finder returned `""`), leaving the exact
/// deep-graph leak with NO runtime coverage. WHY (Rule 9): user 1 creates a
/// Contact under Account 1 (owned by Org 1); user 2 (an Org 2 member, NOT Org 1)
/// must 404 on GET and DELETE — GREEN only when the handler scopes through the
/// JOIN chain (`get_for_memberships`/`remove_for_memberships`), RED on the
/// unscoped accessor that would leak the foreign row. The intermediate Account is
/// seeded in tenant 1 so the nested create resolves, and the mount's parent fk is
/// pinned to the seeded id.
const ORG_ACCOUNT_CONTACT_NESTED: &str = r#"{
    "name": "crm-api", "contract_version": 1,
    "auth": { "model": "session", "roles": ["owner", "member"] },
    "dependencies": ["db", "auth"],
    "tenancy": { "entity": "Org", "member_roles": ["owner", "member"] },
    "modules": [
        { "name": "orgs",
          "entities": [{ "name": "Org", "fields": [
              { "name": "id", "type": "integer" }, { "name": "name", "type": "string" } ]}],
          "endpoints": [
              { "operation_id": "create_org", "method": "POST", "path": "/", "auth_required": true,
                "request_body": { "entity": "Org" }, "success": { "status": 201, "entity": "Org" } } ] },
        { "name": "accounts",
          "entities": [{ "name": "Account", "belongs_to": [{ "entity": "Org" }],
              "fields": [{ "name": "id", "type": "integer" }] }],
          "endpoints": [
              { "operation_id": "create_account", "method": "POST", "path": "/", "auth_required": true,
                "request_body": { "entity": "Account" }, "success": { "status": 201, "entity": "Account" } } ] },
        { "name": "contacts", "mount": "/accounts/{account_id}",
          "entities": [{ "name": "Contact", "belongs_to": [{ "entity": "Account" }],
              "fields": [{ "name": "id", "type": "integer" }, { "name": "title", "type": "string" }] }],
          "endpoints": [
              { "operation_id": "create_contact", "method": "POST", "path": "/", "auth_required": true,
                "request_body": { "entity": "Contact" }, "success": { "status": 201, "entity": "Contact" } },
              { "operation_id": "get_contact", "method": "GET", "path": "/{id}", "auth_required": true,
                "success": { "status": 200, "entity": "Contact" } },
              { "operation_id": "delete_contact", "method": "DELETE", "path": "/{id}", "auth_required": true,
                "success": { "status": 204 } } ] }
    ]
}"#;

#[test]
fn grandchild_gets_a_transitive_isolation_test() {
    let d: Design = serde_json::from_str(ORG_ACCOUNT_CONTACT_NESTED).unwrap();
    let contacts = d.modules.iter().find(|m| m.name == "contacts").unwrap();
    let out = testgen::acceptance_rs(&d, contacts);
    // The isolation test IS emitted for the transitively-owned grandchild.
    assert!(
        out.contains("async fn tenant_a_cannot_read_tenant_b_contacts()"),
        "grandchild isolation test emitted: {out}"
    );
    // The intermediate parent (Account) is seeded in tenant 1 (org_id = 1) so the
    // nested create resolves through the JOIN chain.
    assert!(
        out.contains("INSERT INTO \\\"accounts\\\" (id, org_id) VALUES (1, 1)"),
        "seeds the intermediate Account in tenant 1: {out}"
    );
    // The probe URLs thread the seeded parent id into the nested mount — no
    // unsubstituted `{account_id}` token survives.
    let iso = out
        .split("async fn tenant_a_cannot_read_tenant_b_contacts()")
        .nth(1)
        .expect("isolation fn present");
    assert!(
        iso.contains("\"/accounts/1/\"") && iso.contains("/accounts/1/{id}"),
        "probe URLs pin the parent fk to the seeded id 1: {iso}"
    );
    assert!(
        !iso.contains("{account_id}"),
        "no unsubstituted parent mount param in the isolation test: {iso}"
    );
    // user 2 (Org 2 member, NOT Org 1) is denied read AND delete.
    assert!(
        iso.contains("cross-tenant get must 404"),
        "get leg 404s for user 2: {iso}"
    );
    assert!(
        iso.contains("cross-tenant delete must 404"),
        "delete leg 404s for user 2: {iso}"
    );
    // A nested route's list is itself tenant-path-guarded — user 2 can't reach
    // tenant 1's collection — so the list leg is skipped.
    assert!(
        !out.contains("user 2 lists their own"),
        "nested grandchild route emits no list leg: {out}"
    );
    // The scaffolding a grandchild module needs is present (transitive
    // `module_needs_tenant`): tenant 1 (Org) + user 1 membership are seeded, and
    // the second tenant (Org 2) + user 2 membership for the isolation probe.
    assert!(
        out.contains("INSERT INTO \\\"orgs\\\" (id")
            && out.contains(
                "INSERT INTO \\\"org_members\\\" (user_id, org_id, role) VALUES (1, 1, 'owner')"
            ),
        "tenant 1 Org + user 1 membership seeded for the grandchild module: {out}"
    );
    assert!(
        out.contains("fn seed_second_tenant(") && out.contains("test_cookie_for("),
        "grandchild isolation needs a second tenant + per-user cookie helper: {out}"
    );
}

/// AUGMENT (issue #102 eval): a MULTI-PARENT entity — `Comment belongs_to
/// [Ticket, User]`, where `Ticket` reaches the tenant (`Ticket belongs_to Org`)
/// and `User` is the auth identity — must be classified TENANT-owned (scoped
/// through the Ticket chain), NOT per-user. The presence of the identity fk
/// `user_id` must NOT downgrade it to a per-user backstop when a genuine tenant
/// path exists. WHY: a per-user-only test would let a tenant member read ANOTHER
/// tenant's comment (the identity check passes if they authored it, but the
/// tenant boundary is what matters). So the tenant isolation test fires and the
/// per-user one does not.
const TICKET_COMMENT_MULTIPARENT: &str = r#"{
    "name": "helpdesk-api", "contract_version": 1,
    "auth": { "model": "session", "roles": ["owner", "member"] },
    "dependencies": ["db", "auth"],
    "tenancy": { "entity": "Org", "member_roles": ["owner", "member"] },
    "modules": [
        { "name": "orgs",
          "entities": [{ "name": "Org", "fields": [
              { "name": "id", "type": "integer" }, { "name": "name", "type": "string" } ]}],
          "endpoints": [
              { "operation_id": "create_org", "method": "POST", "path": "/", "auth_required": true,
                "request_body": { "entity": "Org" }, "success": { "status": 201, "entity": "Org" } } ] },
        { "name": "tickets",
          "entities": [{ "name": "Ticket", "belongs_to": [{ "entity": "Org" }],
              "fields": [{ "name": "id", "type": "integer" }] }],
          "endpoints": [
              { "operation_id": "create_ticket", "method": "POST", "path": "/", "auth_required": true,
                "request_body": { "entity": "Ticket" }, "success": { "status": 201, "entity": "Ticket" } } ] },
        { "name": "comments",
          "entities": [{ "name": "Comment",
              "belongs_to": [{ "entity": "Ticket" }, { "entity": "User" }],
              "fields": [{ "name": "id", "type": "integer" }, { "name": "body", "type": "string" }] }],
          "endpoints": [
              { "operation_id": "create_comment", "method": "POST", "path": "/", "auth_required": true,
                "request_body": { "entity": "Comment" }, "success": { "status": 201, "entity": "Comment" } },
              { "operation_id": "get_comment", "method": "GET", "path": "/{id}", "auth_required": true,
                "success": { "status": 200, "entity": "Comment" } } ] }
    ]
}"#;

#[test]
fn multi_parent_entity_reaching_tenant_is_tenant_owned_not_per_user() {
    let d: Design = serde_json::from_str(TICKET_COMMENT_MULTIPARENT).unwrap();
    let comments = d.modules.iter().find(|m| m.name == "comments").unwrap();
    let out = testgen::acceptance_rs(&d, comments);
    // Classified TENANT-owned (via the Ticket chain) → the cross-tenant isolation
    // test is emitted.
    assert!(
        out.contains("async fn tenant_a_cannot_read_tenant_b_comments()"),
        "multi-parent entity reaching the tenant gets the tenant isolation test: {out}"
    );
    // NOT classified per-user, despite carrying `user_id` — no #79 test.
    assert!(
        !out.contains("async fn user_a_cannot_read_user_b_comments()"),
        "a tenant-owned multi-parent entity must NOT also get a per-user test: {out}"
    );
    // The tenant-reaching parent (Ticket) is seeded in tenant 1 so the flat
    // create's `ticket_id` resolves through the chain.
    assert!(
        out.contains("INSERT INTO \\\"tickets\\\" (id, org_id) VALUES (1, 1)"),
        "seeds the intermediate Ticket in tenant 1: {out}"
    );
}

/// A credential/signature-gated endpoint's SUCCESS test would be UN-GREENABLE: the
/// generator can't supply the credential, so a minimal-body probe can never reach
/// the designed success status (a `public` login 401s bad creds; a signed webhook
/// 400/401s a bad signature). WHY (Rule 9): emitting a hard `_returns_<status>`
/// assertion for these would leave a generated test that NO correct implementation
/// can pass — `jerrycan check` could never go green. So the generator must emit an
/// `// AGENT TODO` instead, and the agent writes the credentialed test by hand.
/// This locks BOTH gated shapes: (a) a public POST declaring 401 and (b) a
/// signature-authenticated webhook (declares a 4xx whose `when` names "signature").
#[test]
fn credential_gated_endpoints_get_an_agent_todo_not_a_success_test() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "gated-api",
        "contract_version": 1,
        "auth": { "model": "jwt", "roles": ["admin"] },
        "dependencies": ["auth"],
        "modules": [{
            "name": "accounts",
            "endpoints": [
                // (a) a public login: declares 401 on bad creds, no body.
                { "operation_id": "login", "method": "POST", "path": "/login",
                  "public": true,
                  "success": { "status": 200 },
                  "errors": [{ "status": 401, "when": "invalid email or password" }] },
                // (b) a signature-authenticated webhook: declares a 400 whose
                // `when` names a signature check (Stripe-style).
                { "operation_id": "stripe_webhook", "method": "POST", "path": "/webhook",
                  "success": { "status": 200 },
                  "errors": [{ "status": 400, "when": "Stripe signature is missing or invalid" }] }
            ]
        }]
    }))
    .unwrap();
    let generated = testgen::acceptance_rs(&design, &design.modules[0]);

    // Neither gated endpoint gets an un-greenable `_returns_` success assertion...
    assert!(
        !generated.contains("async fn login_returns_"),
        "credential-gated login must NOT get a success test: {generated}"
    );
    assert!(
        !generated.contains("async fn stripe_webhook_returns_"),
        "signature webhook must NOT get a success test: {generated}"
    );
    // ...each instead carries an AGENT TODO naming the credential it needs.
    assert!(
        generated.contains(
            "// AGENT TODO: login (POST /accounts/login) authenticates via a credential/signature"
        ),
        "login must get a credential AGENT TODO: {generated}"
    );
    assert!(
        generated.contains(
            "// AGENT TODO: stripe_webhook (POST /accounts/webhook) authenticates via a credential/signature"
        ),
        "webhook must get a credential AGENT TODO: {generated}"
    );
}

/// An explicit `probe: "skip"` hint (issue #11) makes the generator drop the
/// un-greenable 2xx probe even when the heuristic MISSES the endpoint — here a
/// `public` webhook that declares NO 401/403 error, so `endpoint_is_credential_gated`
/// wouldn't flag it. WHY (Rule 9): without the hint the generator would emit a
/// `_returns_200` probe that a correct signature-checking handler MUST reject,
/// so `jerrycan check` could never reach ok:true. With the hint it emits a TODO,
/// and an ordinary (auto) endpoint in the same module still gets its success probe.
#[test]
fn probe_skip_hint_drops_the_ungreenable_success_probe() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "ingest-api",
        "contract_version": 1,
        "dependencies": [],
        "modules": [{
            "name": "ingest",
            "endpoints": [
                // A public webhook the heuristic misses (no declared 401/403, no
                // "signature" in a `when`), marked probe: skip explicitly.
                { "operation_id": "receive_hook", "method": "POST", "path": "/hook",
                  "public": true, "probe": "skip",
                  "success": { "status": 202 } },
                // An ordinary endpoint (auto) still gets its happy-path probe.
                { "operation_id": "health_ping", "method": "GET", "path": "/ping",
                  "success": { "status": 200 } }
            ]
        }]
    }))
    .unwrap();
    let generated = testgen::acceptance_rs(&design, &design.modules[0]);
    assert!(
        !generated.contains("async fn receive_hook_returns_"),
        "probe: skip must drop the un-greenable success probe: {generated}"
    );
    assert!(
        generated
            .contains("// AGENT TODO: receive_hook (POST /ingest/hook) is marked `probe: skip`"),
        "probe: skip must emit an explanatory TODO: {generated}"
    );
    assert!(
        generated.contains("async fn health_ping_returns_200()"),
        "an ordinary (auto) endpoint still gets its success probe: {generated}"
    );
}

/// Issue #123(b): `probe: "skip"` on a GUARDED endpoint drops ONLY the
/// un-greenable success probe — the `_without_auth_is_401` guard test survives.
/// WHY (Rule 9): the 401 test is a GREENABLE security assertion (the generated
/// guard rejects a credential-less request before any handler logic, so it
/// needs no credential and no seed); before this fix `skip` silently deleted
/// it, so a hand-weakened guard stayed green. A param path pins its `{param}`
/// to a literal id — the guard 401s before the id is ever looked up.
#[test]
fn probe_skip_on_a_guarded_endpoint_keeps_the_401_guard_test() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "vault-api",
        "contract_version": 1,
        "auth": { "model": "session", "roles": ["admin"] },
        "dependencies": ["auth"],
        "modules": [{
            "name": "vault",
            "endpoints": [
                // Guarded, but its success needs a credential the generator
                // can't synthesize — marked probe: skip.
                { "operation_id": "rotate_key", "method": "POST", "path": "/rotate",
                  "auth_required": true, "probe": "skip",
                  "success": { "status": 202 } },
                // The same, on a parameterized path.
                { "operation_id": "reveal_secret", "method": "GET", "path": "/{id}/reveal",
                  "auth_required": true, "probe": "skip",
                  "success": { "status": 200 } }
            ]
        }]
    }))
    .unwrap();
    let generated = testgen::acceptance_rs(&design, &design.modules[0]);
    // The un-greenable success probes stay dropped...
    assert!(
        !generated.contains("async fn rotate_key_returns_"),
        "probe: skip still drops the un-greenable success probe: {generated}"
    );
    // ...but the 401 guard tests survive the skip.
    assert!(
        generated.contains("async fn rotate_key_without_auth_is_401"),
        "a guarded probe:skip endpoint keeps its 401 guard test: {generated}"
    );
    assert!(
        generated.contains("async fn reveal_secret_without_auth_is_401"),
        "a guarded param-path probe:skip endpoint keeps its 401 guard test: {generated}"
    );
    // The param path is pinned to a literal id — a 401 rejection needs no seed.
    assert!(
        generated.contains("\"/vault/1/reveal\""),
        "the 401 probe pins the path param to a literal id: {generated}"
    );
    // The TODO is retained, now asking for the success test ONLY (the rejection
    // test is generated, so the old "write the rejection test yourself" is gone).
    assert!(
        generated
            .contains("// AGENT TODO: rotate_key (POST /vault/rotate) is marked `probe: skip`"),
        "the probe:skip TODO is retained: {generated}"
    );
    assert!(
        !generated.contains("and its 401/403 rejection test"),
        "a guarded skip TODO must not ask for the generated rejection test: {generated}"
    );
    // expected_failing flows through push_401_test's count — no special-casing.
    let tmp = std::env::temp_dir().join(format!("jc123b-{}", std::process::id()));
    std::fs::create_dir_all(tmp.join("crates/routes/vault/tests")).unwrap();
    let (_rel, expected_failing) = testgen::write_acceptance(&tmp, &design, "vault").unwrap();
    assert_eq!(
        expected_failing, 2,
        "both 401 guard tests count toward expected_failing: {generated}"
    );
    std::fs::remove_dir_all(&tmp).ok();
}

/// Issue #153: a GUARDED `/{id}` endpoint with NO seed creator keeps its
/// `_without_auth_is_401` guard test — only the un-seedable success probe
/// becomes a TODO. WHY (Rule 9): the 401 assertion is GREENABLE without a seed
/// (the generated guard rejects a credential-less request before the id is
/// ever looked up, so a literal id stands in); before this fix the no-creator
/// branch silently dropped it, so a hand-weakened guard on such an endpoint
/// stayed green — the same hole #123b closed for `probe: skip`. An UNGUARDED
/// endpoint of the same shape must NOT gain a 401 test (asserting 401 on an
/// open endpoint would be permanently red on a correct app).
#[test]
fn guarded_id_endpoint_without_creator_keeps_the_401_guard_test() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "audit-api",
        "contract_version": 1,
        "auth": { "model": "session" },
        "dependencies": ["auth"],
        "modules": [{
            "name": "audits",
            "endpoints": [
                // Guarded detail route with no POST creator anywhere in the
                // module — the success probe cannot be seeded.
                { "operation_id": "show_audit", "method": "GET", "path": "/{id}",
                  "auth_required": true,
                  "success": { "status": 200 } },
                // The same shape UNGUARDED: no 401 test may be emitted.
                { "operation_id": "show_open_audit", "method": "GET", "path": "/open/{id}",
                  "success": { "status": 200 } }
            ]
        }]
    }))
    .unwrap();
    let generated = testgen::acceptance_rs(&design, &design.modules[0]);
    // The un-seedable success probes stay TODOs...
    assert!(
        !generated.contains("async fn show_audit_returns_"),
        "no creator still drops the un-seedable success probe: {generated}"
    );
    assert!(
        generated.contains("// AGENT TODO: show_audit (GET /audits/{id}) has no creator route"),
        "the no-creator TODO is retained: {generated}"
    );
    // ...but the guarded endpoint keeps its 401 guard test, on a literal id.
    assert!(
        generated.contains("async fn show_audit_without_auth_is_401"),
        "a guarded no-creator /{{id}} endpoint keeps its 401 guard test: {generated}"
    );
    assert!(
        generated.contains("\"/audits/1\""),
        "the 401 probe pins the id param to a literal id: {generated}"
    );
    // The unguarded control gains nothing.
    assert!(
        !generated.contains("show_open_audit_without_auth_is_401"),
        "an unguarded no-creator endpoint must NOT get a 401 test: {generated}"
    );
    // expected_failing flows through push_401_test's count — no special-casing.
    let tmp = std::env::temp_dir().join(format!("jc153a-{}", std::process::id()));
    std::fs::create_dir_all(tmp.join("crates/routes/audits/tests")).unwrap();
    let (_rel, expected_failing) = testgen::write_acceptance(&tmp, &design, "audits").unwrap();
    assert_eq!(
        expected_failing, 1,
        "the 401 guard test counts toward expected_failing: {generated}"
    );
    std::fs::remove_dir_all(&tmp).ok();
}

/// Issue #153: a GUARDED 2+-param endpoint keeps its `_without_auth_is_401`
/// guard test with EVERY `{param}` pinned to a literal id — only the seeded
/// success probe stays a TODO (the generator can't seed a multi-param path).
/// WHY (Rule 9): same silently-dropped-401 as the no-creator branch — a 401
/// rejection precedes any id lookup, so no seed is needed and dropping the
/// test un-tested a real guard. The UNGUARDED control of the same shape must
/// NOT gain a false 401 assertion.
#[test]
fn guarded_multi_param_endpoint_keeps_the_401_guard_test() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "grid-api",
        "contract_version": 1,
        "auth": { "model": "session" },
        "dependencies": ["auth"],
        "modules": [{
            "name": "grids",
            "endpoints": [
                { "operation_id": "get_cell", "method": "GET",
                  "path": "/{row}/cells/{col}",
                  "auth_required": true,
                  "success": { "status": 200 } },
                { "operation_id": "get_open_cell", "method": "GET",
                  "path": "/{row}/open/{col}",
                  "success": { "status": 200 } }
            ]
        }]
    }))
    .unwrap();
    let generated = testgen::acceptance_rs(&design, &design.modules[0]);
    assert!(
        !generated.contains("async fn get_cell_returns_"),
        "a multi-param endpoint still gets no auto-seeded success probe: {generated}"
    );
    assert!(
        generated
            .contains("// AGENT TODO: get_cell (GET /grids/{row}/cells/{col}) needs a creator"),
        "the multi-param TODO is retained: {generated}"
    );
    assert!(
        generated.contains("async fn get_cell_without_auth_is_401"),
        "a guarded multi-param endpoint keeps its 401 guard test: {generated}"
    );
    assert!(
        generated.contains("\"/grids/1/cells/1\""),
        "the 401 probe pins EVERY param to a literal id: {generated}"
    );
    assert!(
        !generated.contains("get_open_cell_without_auth_is_401"),
        "an unguarded multi-param endpoint must NOT get a 401 test: {generated}"
    );
}

/// A db-mode module whose EVERY endpoint is a TODO (e.g. a billing module whose
/// only route is a signature-gated webhook) emits ZERO `#[tokio::test]` functions.
/// The generated file must then carry NO `app()` helper and NO `use` imports —
/// they would be dead code and trip the generated workspace's `-D warnings`,
/// blocking `jerrycan check` from ever going green. WHY (Rule 9): this is the
/// exact regression Fix 1 first introduced (billing's webhook became a TODO,
/// leaving `app()` unused); the file must degrade to banner + TODOs only.
#[test]
fn module_with_only_todos_emits_no_dead_app_helper() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "webhook-only-api",
        "contract_version": 1,
        "dependencies": ["db"],
        "modules": [{
            "name": "billing",
            "endpoints": [
                { "operation_id": "stripe_webhook", "method": "POST", "path": "/webhook",
                  "success": { "status": 200 },
                  "errors": [{ "status": 400, "when": "Stripe signature is missing or invalid" }] }
            ]
        }]
    }))
    .unwrap();
    let generated = testgen::acceptance_rs(&design, &design.modules[0]);
    // The webhook becomes a TODO, so there are no tests at all.
    assert_eq!(
        testgen::test_count(&generated),
        0,
        "a signature-only billing module emits no tests: {generated}"
    );
    // The TODO is still present (the agent must hand-write the webhook test)...
    assert!(
        generated.contains("// AGENT TODO: stripe_webhook"),
        "the webhook TODO must be emitted: {generated}"
    );
    // ...but the dead `app()` helper and the `use` imports must be GONE, or the
    // generated crate fails to build under `-D warnings`.
    assert!(
        !generated.contains("async fn app()"),
        "a tests-less module must NOT emit a dead app() helper: {generated}"
    );
    assert!(
        !generated.contains("use jerrycan::prelude::*;") && !generated.contains("::module;"),
        "a tests-less module must NOT emit dead imports: {generated}"
    );
    // The banner stays (it identifies the tool-owned file).
    assert!(
        generated.contains("GENERATED by jerrycan gen-tests"),
        "the tool banner must remain: {generated}"
    );
}

/// A public POST that declares NO 401/403 (e.g. register: 409/422) is NOT
/// credential-gated — a minimal body CAN reach success — so it keeps its
/// `_returns_` test. WHY: the gate is narrow; widening it to every public route
/// would drop greenable success coverage for register/create-style endpoints.
#[test]
fn public_post_without_401_keeps_its_success_test() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "reg-api",
        "contract_version": 1,
        "auth": { "model": "jwt", "roles": ["admin"] },
        "dependencies": ["auth"],
        "modules": [{
            "name": "accounts",
            "entities": [{ "name": "User", "fields": [
                { "name": "email", "type": "string" }
            ]}],
            "endpoints": [
                { "operation_id": "register", "method": "POST", "path": "/register",
                  "public": true,
                  "request_body": { "entity": "User" },
                  "success": { "status": 201, "entity": "User" },
                  "errors": [
                    { "status": 409, "when": "email already registered" },
                    { "status": 422, "when": "request body fails validation" }
                  ] }
            ]
        }]
    }))
    .unwrap();
    let generated = testgen::acceptance_rs(&design, &design.modules[0]);
    assert!(
        generated.contains("async fn register_returns_201"),
        "a public POST with no 401/403 keeps its success test: {generated}"
    );
}

/// A POST-only `/{id}` action that declares a 404 must get a 404 probe built with
/// the endpoint's REAL method (POST), not a hardcoded GET. WHY (Rule 9): the router
/// returns 405 for a GET against a POST-only route, so a GET probe would assert 404
/// against an observed 405 and fail forever — an un-greenable generated test. The
/// fix routes the missing-id probe through `request_expr` (the success builder), so
/// it POSTs and the handler's real 404-on-missing path is exercised.
#[test]
fn post_only_id_action_404_probe_uses_post_not_get() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "tickets-api",
        "contract_version": 1,
        "modules": [{
            "name": "tickets",
            "endpoints": [
                { "operation_id": "close_ticket", "method": "POST", "path": "/{id}/close",
                  "success": { "status": 200 },
                  "errors": [{ "status": 404, "when": "unknown id" }] }
            ]
        }]
    }))
    .unwrap();
    let generated = testgen::acceptance_rs(&design, &design.modules[0]);
    assert!(
        generated.contains("async fn close_ticket_missing_id_is_404"),
        "POST-only /{{id}} action with a 404 gets a 404 test: {generated}"
    );
    // The probe must POST to the missing id (use the endpoint's method), NOT GET —
    // a GET would 405 and the 404 assertion could never pass.
    assert!(
        generated.contains("t.post_json(\"/tickets/999999/close\""),
        "404 probe must POST (the endpoint's method), not GET: {generated}"
    );
    assert!(
        !generated.contains("t.get(\"/tickets/999999/close\")"),
        "404 probe must NOT be a hardcoded GET: {generated}"
    );
}

/// A tenant entity with a `unique` non-PK column must seed tenant 1 and tenant 2
/// with DISTINCT values for that column, or the second-tenant seed the isolation
/// test depends on crashes every test at setup with a UNIQUE-constraint violation.
/// WHY (Rule 9): tenant 1 and tenant 2 previously shared `'test-value'` for every
/// string column; a `unique` column then collides. Tenant 1 seeds a value distinct
/// from BOTH tenant 2 (`'test-value-2'`) AND the create-probe body (`'test-value'`,
/// `fixture_value`) — the latter is the #85 D3 fix: without it a create probe on the
/// tenant entity 409s on the pre-seeded row.
#[test]
fn two_tenant_seed_uses_distinct_values_for_a_unique_field() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "slug-api",
        "contract_version": 1,
        "auth": { "model": "jwt", "roles": ["owner", "member"] },
        "dependencies": ["db", "auth"],
        "tenancy": { "entity": "Org", "member_roles": ["owner", "member"] },
        "modules": [
            {
                "name": "orgs",
                "entities": [{ "name": "Org", "fields": [
                    { "name": "id", "type": "integer" },
                    { "name": "slug", "type": "string", "unique": true }
                ]}],
                "endpoints": []
            },
            {
                "name": "projects",
                "entities": [{ "name": "Project",
                    "belongs_to": [{ "entity": "Org" }],
                    "fields": [
                        { "name": "id", "type": "integer" },
                        { "name": "title", "type": "string" }
                    ]}],
                "endpoints": [
                    { "operation_id": "list_projects", "method": "GET", "path": "/",
                      "auth_required": true,
                      "success": { "status": 200, "entity": "Project", "list": true } },
                    { "operation_id": "create_project", "method": "POST", "path": "/",
                      "auth_required": true,
                      "request_body": { "entity": "Project" },
                      "success": { "status": 201, "entity": "Project" } },
                    { "operation_id": "show_project", "method": "GET", "path": "/{id}",
                      "auth_required": true,
                      "success": { "status": 200, "entity": "Project" },
                      "errors": [{ "status": 404, "when": "unknown id" }] }
                ]
            }
        ]
    }))
    .unwrap();
    let projects = design
        .modules
        .iter()
        .find(|m| m.name == "projects")
        .expect("projects module");
    let generated = testgen::acceptance_rs(&design, projects);

    // Tenant 1's seed uses a value DISTINCT from the create-probe body (#85 D3), so
    // it collides with neither tenant 2 nor a create probe on the tenant entity.
    assert!(
        generated.contains("VALUES (1, 'seed-test-value')"),
        "tenant 1 seeds a unique slug distinct from the probe fixture: {generated}"
    );
    // Tenant 2's seed (in seed_second_tenant) must NOT reuse the SAME slug literal —
    // it carries a distinct value so the UNIQUE constraint holds.
    assert!(
        generated.contains("VALUES (2, 'test-value-2')"),
        "tenant 2 seeds a DISTINCT slug so the unique column doesn't collide: {generated}"
    );
    // Belt-and-suspenders: the two org INSERTs must not share the same slug literal.
    let org_inserts: Vec<&str> = generated
        .lines()
        .filter(|l| l.contains("INSERT INTO \\\"orgs\\\""))
        .collect();
    assert_eq!(org_inserts.len(), 2, "two org rows seeded: {generated}");
    assert_ne!(
        org_inserts[0], org_inserts[1],
        "the two tenant org INSERTs must differ on the unique slug: {generated}"
    );
}

/// The server-owned-FK rule (issue #34): a GUARDED endpoint whose body entity
/// `belongs_to` the auth identity entity (fk column `user_id`) gets probe
/// bodies WITHOUT `user_id` — the handler injects the session user's id, so a
/// clean client that omits it must reach the designed success (the agent-eval
/// 422 scenario). Non-identity FKs stay in the body; an UNGUARDED endpoint on
/// the same entity keeps `user_id` (no session to inject). WHY: the generated
/// probes ARE the wire contract — if they still carried user_id, the contract
/// would keep lying about a field the server overwrites anyway.
#[test]
fn guarded_identity_fk_is_omitted_from_probe_bodies() {
    let s = r#"{
        "name": "linkvault",
        "contract_version": 1,
        "auth": { "model": "session", "roles": ["admin"] },
        "dependencies": ["db", "auth"],
        "modules": [
            { "name": "users",
              "entities": [{ "name": "User", "fields": [
                  { "name": "email", "type": "string" } ]}],
              "endpoints": [
                  { "operation_id": "list_users", "method": "GET", "path": "/",
                    "auth_required": true,
                    "success": { "status": 200, "entity": "User", "list": true } }
              ] },
            { "name": "collections",
              "entities": [
                  { "name": "Collection",
                    "belongs_to": [{ "entity": "User", "on_delete": "cascade" }],
                    "fields": [{ "name": "title", "type": "string" }] },
                  { "name": "Bookmark",
                    "belongs_to": [
                        { "entity": "User", "on_delete": "cascade" },
                        { "entity": "Collection", "on_delete": "cascade" }
                    ],
                    "fields": [{ "name": "url", "type": "string" }] }
              ],
              "endpoints": [
                  { "operation_id": "create_collection", "method": "POST", "path": "/",
                    "auth_required": true,
                    "request_body": { "entity": "Collection" },
                    "success": { "status": 201, "entity": "Collection" } },
                  { "operation_id": "create_bookmark", "method": "POST", "path": "/bookmarks",
                    "auth_required": true,
                    "request_body": { "entity": "Bookmark" },
                    "success": { "status": 201, "entity": "Bookmark" } },
                  { "operation_id": "import_collection", "method": "POST", "path": "/import",
                    "request_body": { "entity": "Collection" },
                    "success": { "status": 201, "entity": "Collection" } }
              ] }
        ]
    }"#;
    let design: Design = serde_json::from_str(s).unwrap();
    let collections = design
        .modules
        .iter()
        .find(|m| m.name == "collections")
        .expect("collections module");
    let generated = testgen::acceptance_rs(&design, collections);

    // (a) guarded + identity FK: the create probe body omits user_id entirely.
    assert!(
        generated.contains(
            "t.post_json_with(\"/collections/\", &serde_json::json!({\"title\": \"test-value\"})"
        ),
        "guarded create body must omit user_id: {generated}"
    );
    // (c) guarded + non-identity FK: collection_id stays required client input.
    assert!(
        generated.contains("serde_json::json!({\"collection_id\": 1, \"url\": \"test-value\"})"),
        "non-identity fk stays in the body: {generated}"
    );
    // (b) unguarded + identity FK: user_id stays (no session to inject).
    assert!(
        generated.contains(
            "t.post_json(\"/collections/import\", &serde_json::json!({\"user_id\": 1, \"title\": \"test-value\"}))"
        ),
        "unguarded body keeps user_id: {generated}"
    );
}

/// Issue #47: an endpoint whose request body carries an enum `values` field gets a
/// generated acceptance test proving an OUT-OF-RANGE value is rejected with 422 at
/// the request boundary (before the DB), on BOTH the create (POST /) and update
/// (PUT /{id}) paths. WHY (Rule 9): the docs promise enum inputs are validated;
/// this pins that an out-of-range value 422s (JC0422), never dies as a 500 DB CHECK.
#[test]
fn enum_request_body_gets_out_of_range_reject_test() {
    let s = include_str!("../../../conformance/designs/reference-slice.design.json");
    let design: Design = serde_json::from_str(s).unwrap();
    let leads = design
        .modules
        .iter()
        .find(|m| m.name == "leads")
        .expect("leads module");
    let generated = testgen::acceptance_rs(&design, leads);
    // create path (POST /) and update path (PUT /{id}) both reject out-of-range.
    assert!(
        generated.contains("async fn create_lead_rejects_out_of_range_status"),
        "create reject test: {generated}"
    );
    assert!(
        generated.contains("async fn update_lead_rejects_out_of_range_status"),
        "update reject test: {generated}"
    );
    // the reject body carries an out-of-range sentinel and asserts 422.
    assert!(
        generated.contains("\"status\": \"__invalid_enum_value__\""),
        "reject body uses an out-of-range sentinel: {generated}"
    );
    assert!(
        generated.contains("as_u16(), 422"),
        "reject test asserts 422: {generated}"
    );
    // guarded endpoints thread the credential so the guard doesn't 401 first.
    assert!(
        generated.contains("_rejects_out_of_range_status() {\n    let t = app().await;\n    let res = t.post_json_with"),
        "guarded create reject threads the cookie: {generated}"
    );
}

/// The enum reject tests PASS on stubs (extraction 422s before the handler runs),
/// so gen-tests must NOT count them toward `expected_failing` — mirrors the storage
/// acceptance-test convention. Otherwise the RED-on-stubs invariant (`failed ==
/// expected_failing`) would over-count.
#[test]
fn enum_reject_tests_are_excluded_from_expected_failing() {
    let s = include_str!("../../../conformance/designs/reference-slice.design.json");
    let design: Design = serde_json::from_str(s).unwrap();
    let leads = design
        .modules
        .iter()
        .find(|m| m.name == "leads")
        .expect("leads module");
    let generated = testgen::acceptance_rs(&design, leads);
    let total = testgen::test_count(&generated);
    let rejects = generated.matches("_rejects_out_of_range_").count();
    assert!(
        rejects >= 2,
        "at least create + update reject tests: {rejects}"
    );

    let tmp = tempfile::tempdir().unwrap();
    let (_rel, expected_failing) =
        testgen::write_acceptance(tmp.path(), &design, "leads").expect("write acceptance");
    assert_eq!(
        expected_failing,
        total - rejects,
        "expected_failing must exclude exactly the reject tests (total {total}, rejects {rejects})"
    );
}

/// Slice one generated `#[tokio::test]` function body out of the acceptance file
/// (from its `async fn NAME(` to the next test), so a seeding assertion can be
/// scoped to the probe under test rather than the whole file.
fn test_body<'a>(generated: &'a str, fn_name: &str) -> &'a str {
    let start = generated
        .find(&format!("async fn {fn_name}("))
        .unwrap_or_else(|| panic!("no `async fn {fn_name}` in:\n{generated}"));
    let rest = &generated[start..];
    match rest[1..].find("#[tokio::test]") {
        Some(i) => &rest[..=i],
        None => rest,
    }
}

/// The design behind the J3 face-off failure (issue #51): ONE module holding a
/// root entity (Project at `/`) AND a second entity (Task) with its OWN creator
/// (`POST /tasks`) and its own `/{id}` routes. `contract_version` 1, db mode, no
/// auth — the minimal reproduction.
fn j3_two_entity_module() -> Design {
    serde_json::from_value(serde_json::json!({
        "name": "j3-api",
        "contract_version": 1,
        "dependencies": ["db"],
        "modules": [{
            "name": "projects",
            "entities": [
                { "name": "Task", "fields": [{ "name": "title", "type": "string" }] },
                { "name": "Project", "fields": [{ "name": "name", "type": "string" }] }
            ],
            "endpoints": [
                { "operation_id": "list_projects", "method": "GET", "path": "/",
                  "success": { "status": 200, "entity": "Project", "list": true } },
                { "operation_id": "create_project", "method": "POST", "path": "/",
                  "request_body": { "entity": "Project" },
                  "success": { "status": 201, "entity": "Project" } },
                { "operation_id": "list_tasks", "method": "GET", "path": "/tasks",
                  "success": { "status": 200, "entity": "Task", "list": true } },
                { "operation_id": "create_task", "method": "POST", "path": "/tasks",
                  "request_body": { "entity": "Task" },
                  "success": { "status": 201, "entity": "Task" } },
                { "operation_id": "update_task", "method": "PUT", "path": "/tasks/{id}",
                  "request_body": { "entity": "Task" },
                  "success": { "status": 200, "entity": "Task" },
                  "errors": [{ "status": 404, "when": "unknown id" }] },
                { "operation_id": "delete_task", "method": "DELETE", "path": "/tasks/{id}",
                  "success": { "status": 204 },
                  "errors": [{ "status": 404, "when": "unknown id" }] }
            ]
        }]
    }))
    .unwrap()
}

/// Issue #51: a `/{id}` probe for a NON-root entity must seed a row of THAT
/// entity via its own creator (`POST /tasks`), not reuse the module-root creator
/// (`POST /`, which makes a Project). Before the fix, `update_task`/`delete_task`
/// seeded a Project and then hit `/tasks/1` — 404 on a CORRECT handler.
#[test]
fn second_entity_id_probe_seeds_via_its_own_creator() {
    let design = j3_two_entity_module();
    let module = &design.modules[0];
    let generated = testgen::acceptance_rs(&design, module);

    for probe in ["update_task_returns_200", "delete_task_returns_204"] {
        let body = test_body(&generated, probe);
        assert!(
            body.contains("post_json(\"/projects/tasks\""),
            "{probe} must seed a Task via its own creator POST /projects/tasks:\n{body}"
        );
        // The probe addresses the seeded Task id, under the /tasks collection.
        assert!(
            body.contains("/projects/tasks/1"),
            "{probe} must address the seeded Task:\n{body}"
        );
        // ...and it must NOT reuse the root Project creator for an independent
        // entity (that seed row is the wrong table entirely).
        assert!(
            !body.contains("post_json(\"/projects/\""),
            "{probe} must not seed a Project for a Task probe:\n{body}"
        );
    }
}

/// Issue #51: when the target entity `belongs_to` another entity that has its own
/// creator in the module, the probe seeds the PARENT first (so the enforced
/// intra-module FK resolves), THEN the entity.
#[test]
fn id_probe_seeds_belongs_to_parents_before_the_entity() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "j3-fk-api",
        "contract_version": 1,
        "dependencies": ["db"],
        "modules": [{
            "name": "projects",
            "entities": [
                { "name": "Task",
                  "belongs_to": [{ "entity": "Project" }],
                  "fields": [{ "name": "title", "type": "string" }] },
                { "name": "Project", "fields": [{ "name": "name", "type": "string" }] }
            ],
            "endpoints": [
                { "operation_id": "create_project", "method": "POST", "path": "/",
                  "request_body": { "entity": "Project" },
                  "success": { "status": 201, "entity": "Project" } },
                { "operation_id": "create_task", "method": "POST", "path": "/tasks",
                  "request_body": { "entity": "Task" },
                  "success": { "status": 201, "entity": "Task" } },
                { "operation_id": "update_task", "method": "PUT", "path": "/tasks/{id}",
                  "request_body": { "entity": "Task" },
                  "success": { "status": 200, "entity": "Task" } }
            ]
        }]
    }))
    .unwrap();
    let module = &design.modules[0];
    let generated = testgen::acceptance_rs(&design, module);
    let body = test_body(&generated, "update_task_returns_200");
    let parent = body
        .find("post_json(\"/projects/\"")
        .expect("parent Project must be seeded (POST /projects/)");
    let child = body
        .find("post_json(\"/projects/tasks\"")
        .expect("Task must be seeded (POST /projects/tasks)");
    assert!(
        parent < child,
        "the parent Project must be seeded before the Task:\n{body}"
    );
    assert!(
        body.contains("\"project_id\": 1"),
        "the Task fixture must carry the fk pointing at the seeded parent:\n{body}"
    );
}

/// Issue #51: a `/{id}` endpoint whose entity has NO creator route can't be
/// seeded — degrade to an AGENT TODO instead of emitting a guaranteed-red probe.
#[test]
fn id_probe_without_a_creator_becomes_agent_todo() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "j3-nocreate-api",
        "contract_version": 1,
        "dependencies": ["db"],
        "modules": [{
            "name": "projects",
            "entities": [
                { "name": "Project", "fields": [{ "name": "name", "type": "string" }] },
                { "name": "Task", "fields": [{ "name": "title", "type": "string" }] }
            ],
            "endpoints": [
                { "operation_id": "create_project", "method": "POST", "path": "/",
                  "request_body": { "entity": "Project" },
                  "success": { "status": 201, "entity": "Project" } },
                { "operation_id": "update_task", "method": "PUT", "path": "/tasks/{id}",
                  "request_body": { "entity": "Task" },
                  "success": { "status": 200, "entity": "Task" } }
            ]
        }]
    }))
    .unwrap();
    let module = &design.modules[0];
    let generated = testgen::acceptance_rs(&design, module);
    assert!(
        !generated.contains("async fn update_task_returns_200"),
        "no un-greenable success probe when the entity can't be seeded:\n{generated}"
    );
    assert!(
        generated.contains("// AGENT TODO: update_task")
            && generated.contains("no creator route to seed"),
        "must emit an AGENT TODO naming the missing creator:\n{generated}"
    );
}

/// Issue #48a: a design-declared format type must yield a FORMAT-VALID fixture, so
/// the endpoint's own happy-path probe is greenable against a handler that
/// validates it. `uuid` used the NIL uuid (a valid string but NOT a valid v4 — a
/// v4 validator rejects it); `datetime` was already valid RFC3339.
#[test]
fn format_typed_fields_use_valid_fixtures_not_placeholders() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "fmt-api",
        "contract_version": 1,
        "dependencies": ["db"],
        "modules": [{
            "name": "events",
            "entities": [{ "name": "Event", "fields": [
                { "name": "ref_id", "type": "uuid" },
                { "name": "at", "type": "datetime" }
            ]}],
            "endpoints": [{ "operation_id": "create_event", "method": "POST", "path": "/",
                "request_body": { "entity": "Event" },
                "success": { "status": 201, "entity": "Event" } }]
        }]
    }))
    .unwrap();
    let module = &design.modules[0];
    let generated = testgen::acceptance_rs(&design, module);

    const V4: &str = "f47ac10b-58cc-4372-a567-0e02b2c3d479";
    assert!(
        generated.contains(V4),
        "uuid fixture must be a valid v4:\n{generated}"
    );
    assert!(
        !generated.contains("00000000-0000-0000-0000-000000000000"),
        "the nil uuid is not a valid v4 — un-greenable against a v4 validator:\n{generated}"
    );
    assert!(
        generated.contains("2026-01-01T00:00:00Z"),
        "datetime fixture stays valid RFC3339:\n{generated}"
    );
    // WHY (Rule 9): a v4-validating handler requires the version nibble = 4 and the
    // variant nibble in 8..=b. The generated literal must satisfy both or the
    // endpoint's own 2xx probe can never pass.
    let b = V4.as_bytes();
    assert_eq!(b[14], b'4', "uuid v4 version nibble");
    assert!(
        matches!(b[19], b'8' | b'9' | b'a' | b'b'),
        "uuid v4 variant nibble"
    );
}

/// Issue #53a (defaulted fields): the happy-path probe body OMITS every field
/// with a server-owned `default`, so `POST /subscribers/ {"email": ...}` proves a
/// minimal client body reaches 201 (the server applies confirmed=false /
/// status="active"). A defaulted ENUM field gets no reject probe — it is not on
/// the wire, so a bad value would be ignored, not 422'd.
#[test]
fn defaulted_fields_are_omitted_from_the_probe_body() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "news",
        "contract_version": 0,
        "dependencies": ["db"],
        "modules": [{ "name": "subscribers",
            "entities": [{ "name": "Subscriber", "fields": [
                { "name": "email", "type": "string" },
                { "name": "confirmed", "type": "boolean", "default": false },
                { "name": "status", "type": "string", "values": ["active", "expired"], "default": "active" } ] }],
            "endpoints": [{ "operation_id": "create_subscriber", "method": "POST", "path": "/",
                "request_body": { "entity": "Subscriber" },
                "success": { "status": 201, "entity": "Subscriber" } }] }]
    }))
    .unwrap();
    let generated = testgen::acceptance_rs(&design, &design.modules[0]);
    assert!(
        generated.contains("async fn create_subscriber_returns_201"),
        "{generated}"
    );
    // The probe body carries email but NOT the defaulted fields.
    assert!(generated.contains("\"email\""), "{generated}");
    assert!(
        !generated.contains("\"confirmed\"") && !generated.contains("\"status\""),
        "defaulted fields must not appear in any probe body: {generated}"
    );
    // A defaulted enum field is off the wire — no reject probe.
    assert!(
        !generated.contains("rejects_out_of_range_status"),
        "a defaulted enum field gets no boundary-reject probe: {generated}"
    );
}

/// Issue #53b (nested parent fk): a checkin created under `POST /{habit_id}/checkins`
/// seeds a parent Habit, addresses `/habits/1/checkins`, and OMITS `habit_id` from
/// the body — the handler injects it from the path, so the row attaches to the
/// path's habit.
#[test]
fn nested_parent_fk_is_omitted_from_the_probe_body_and_taken_from_the_path() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "habits",
        "contract_version": 0,
        "dependencies": ["db"],
        "modules": [{ "name": "habits",
            "entities": [
                { "name": "Habit", "fields": [{ "name": "name", "type": "string" }] },
                { "name": "Checkin", "belongs_to": [{ "entity": "Habit" }],
                  "fields": [{ "name": "note", "type": "string" }] } ],
            "endpoints": [
                { "operation_id": "create_habit", "method": "POST", "path": "/",
                  "request_body": { "entity": "Habit" },
                  "success": { "status": 201, "entity": "Habit" } },
                { "operation_id": "create_checkin", "method": "POST", "path": "/{habit_id}/checkins",
                  "request_body": { "entity": "Checkin" },
                  "success": { "status": 201, "entity": "Checkin" } }] }]
    }))
    .unwrap();
    let generated = testgen::acceptance_rs(&design, &design.modules[0]);
    assert!(
        generated.contains("async fn create_checkin_returns_201"),
        "{generated}"
    );
    // Seeds a Habit, then posts the checkin under the seeded habit's id.
    assert!(
        generated.contains("post_json(\"/habits/\""),
        "seed habit: {generated}"
    );
    assert!(
        generated.contains("post_json(\"/habits/1/checkins\""),
        "checkin addressed under the path's habit: {generated}"
    );
    // The checkin body carries `note` but NOT the path-redundant `habit_id`.
    assert!(generated.contains("\"note\""), "{generated}");
    assert!(
        !generated.contains("\"habit_id\""),
        "path-redundant fk must not appear in the body: {generated}"
    );
}

/// Issue #67: the minted test credential's `SessionUser.role` must satisfy the
/// design's role gate. A HelpDesk-shaped design (roles agent/customer, an
/// `agent`-gated endpoint) must mint role `"agent"` — a hardcoded `"admin"`
/// (never a declared role) makes a CORRECT `require_role("agent")` handler 403 the
/// happy-path probe, un-greenable by construction. WHY (Rule 9): the credential
/// role is the difference between a green and a 403 on a role-gated endpoint.
#[test]
fn credential_role_is_drawn_from_the_designs_role_gate() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "helpdesk",
        "contract_version": 1,
        "dependencies": ["db", "auth"],
        "auth": { "model": "jwt", "roles": ["agent", "customer"] },
        "modules": [{
            "name": "tickets",
            "entities": [{ "name": "Ticket", "fields": [{ "name": "subject", "type": "string" }] }],
            "endpoints": [
                { "operation_id": "resolve_ticket", "method": "POST", "path": "/resolve",
                  "auth_required": true, "required_roles": ["agent"],
                  "request_body": { "entity": "Ticket" },
                  "success": { "status": 200, "entity": "Ticket" } }
            ]
        }]
    }))
    .unwrap();
    let generated = testgen::acceptance_rs(&design, &design.modules[0]);
    assert!(
        generated.contains("role: \"agent\".into()"),
        "the minted credential must carry the gate's role `agent`, not a hardcoded `admin`: {generated}"
    );
    assert!(
        !generated.contains("role: \"admin\""),
        "no hardcoded admin role when the design declares none: {generated}"
    );
}

/// Issue #67: a design that declares roles but gates no endpoint mints the
/// design's FIRST declared role; only a design that declares NO roles at all
/// falls back to `"admin"`. Guards the derivation's two lower rungs.
#[test]
fn credential_role_falls_back_to_first_declared_then_admin() {
    // Declares roles, gates nothing -> first declared role ("owner").
    let roled: Design = serde_json::from_value(serde_json::json!({
        "name": "roled", "contract_version": 1, "dependencies": ["db", "auth"],
        "auth": { "model": "session", "roles": ["owner", "member"] },
        "modules": [{ "name": "notes",
            "entities": [{ "name": "Note", "fields": [{ "name": "body", "type": "string" }] }],
            "endpoints": [{ "operation_id": "create_note", "method": "POST", "path": "/",
                "auth_required": true, "request_body": { "entity": "Note" },
                "success": { "status": 201, "entity": "Note" } }] }]
    }))
    .unwrap();
    let g = testgen::acceptance_rs(&roled, &roled.modules[0]);
    assert!(
        g.contains("role: \"owner\".into()"),
        "first declared role: {g}"
    );

    // Declares no roles -> "admin" fallback (byte-identical to the pre-#67 output).
    let roleless: Design = serde_json::from_value(serde_json::json!({
        "name": "roleless", "contract_version": 1, "dependencies": ["db", "auth"],
        "auth": { "model": "session" },
        "modules": [{ "name": "notes",
            "entities": [{ "name": "Note", "fields": [{ "name": "body", "type": "string" }] }],
            "endpoints": [{ "operation_id": "create_note", "method": "POST", "path": "/",
                "auth_required": true, "request_body": { "entity": "Note" },
                "success": { "status": 201, "entity": "Note" } }] }]
    }))
    .unwrap();
    let g2 = testgen::acceptance_rs(&roleless, &roleless.modules[0]);
    assert!(
        g2.contains("role: \"admin\".into()"),
        "no roles -> admin fallback: {g2}"
    );
}

/// Issue #66: the TestApp harness must wire the design's declared extensions
/// (mirroring mounting.rs) so the generated probes exercise the SAME app main.rs
/// builds. Without the realtime extension a handler's `Dep<RealtimeHandle>` fails
/// to resolve → JC1001 500 → the happy-path probe is un-greenable until the agent
/// hand-patches the harness. WHY (Rule 9): a probe that 500s on a MISSING
/// extension is testing the harness, not the contract.
#[test]
fn testapp_wires_declared_realtime_and_jobs_extensions() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "live",
        "contract_version": 1,
        "dependencies": ["db", "auth"],
        "auth": { "model": "jwt", "roles": ["admin"] },
        "realtime": {
            "broadcast": [{ "name": "feed", "scope": "auth" }],
            "presence": [{ "name": "cursors", "scope": "auth" }]
        },
        "jobs": [{ "name": "sweep", "schedule": "0 * * * *", "queue": "default" }],
        "modules": [{
            "name": "posts",
            "entities": [{ "name": "Post", "fields": [{ "name": "title", "type": "string" }] }],
            "endpoints": [
                { "operation_id": "create_post", "method": "POST", "path": "/",
                  "auth_required": true, "request_body": { "entity": "Post" },
                  "success": { "status": 201, "entity": "Post" } }
            ]
        }]
    }))
    .unwrap();
    let generated = testgen::acceptance_rs(&design, &design.modules[0]);
    assert!(
        generated.contains(".extend(jerrycan::realtime::Realtime::new(db.clone())"),
        "realtime design's TestApp must wire the realtime extension (else JC1001): {generated}"
    );
    // Issue #84: the realtime extension must also DECLARE the app's topics, so a
    // handler that publishes to one resolves instead of failing JC0404 (undeclared
    // topic) on a bare `Realtime::new`. WHY (Rule 9): a probe that 404s on a MISSING
    // topic tests the harness, not the contract.
    assert!(
        generated.contains(".broadcast(\"feed\", jerrycan::realtime::TopicScope::Auth)"),
        "realtime TestApp must declare the app's broadcast topics (issue #84): {generated}"
    );
    assert!(
        generated.contains(".presence(\"cursors\", jerrycan::realtime::TopicScope::Auth)"),
        "realtime TestApp must declare the app's presence topics (issue #84): {generated}"
    );
    assert!(
        generated.contains(".extend(jerrycan::jobs::Jobs::postgres(db.clone()))"),
        "jobs design's TestApp must wire the jobs extension: {generated}"
    );
    // The extensions take db.clone() and precede `.extend(db)` (which moves db),
    // matching mounting.rs's order. Scope the check to the builder line so the doc
    // comment (which mentions `.extend(db)` in prose) doesn't confuse the search.
    let builder = generated
        .lines()
        .find(|l| l.contains("App::new()"))
        .expect("app() builder line");
    let realtime_at = builder.find(".extend(jerrycan::realtime").unwrap();
    let db_at = builder.find(".extend(db)").unwrap();
    assert!(
        realtime_at < db_at,
        "extensions must precede .extend(db): {builder}"
    );
    // The deliberately EXCLUDED extensions are documented in the harness comment.
    assert!(
        generated.contains("issue #66")
            && generated.contains("observe")
            && generated.contains("validate"),
        "the harness must document which extensions it excludes and why: {generated}"
    );
}

/// Issue #66: a storage design's TestApp wires the storage extension with a
/// test-env-safe in-memory store (no `from_env`/secrets), mirroring storagegen.
#[test]
fn testapp_wires_declared_storage_extension() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "files",
        "contract_version": 2,
        "dependencies": ["db", "auth"],
        "auth": { "model": "session", "roles": ["admin"] },
        "storage": { "buckets": [{ "name": "avatars", "visibility": "public" }] },
        "modules": [{
            "name": "profiles",
            "entities": [{ "name": "Profile", "fields": [{ "name": "handle", "type": "string" }] }],
            "endpoints": [
                { "operation_id": "create_profile", "method": "POST", "path": "/",
                  "auth_required": true, "request_body": { "entity": "Profile" },
                  "success": { "status": 201, "entity": "Profile" } }
            ]
        }]
    }))
    .unwrap();
    let generated = testgen::acceptance_rs(&design, &design.modules[0]);
    assert!(
        generated.contains(".extend(jerrycan::storage::Storage::memory().with_sign_secret("),
        "storage design's TestApp must wire an in-memory Storage extension: {generated}"
    );
}

/// Issue #66: a plain db(+validate) design declares none of storage/jobs/realtime,
/// so the harness stays byte-for-byte as before — no new extension extends, no
/// exclusion comment. This is the no-drift guard for todo-api's generated bytes.
#[test]
fn plain_db_design_harness_is_unchanged_by_extension_wiring() {
    let design = golden(true); // todo-api, db mode, no extensions
    let generated = testgen::acceptance_rs(&design, &design.modules[0]);
    assert!(
        !generated.contains("issue #66"),
        "no extension-wiring comment for a design that declares no extensions: {generated}"
    );
    assert!(
        !generated.contains("jerrycan::jobs::")
            && !generated.contains("jerrycan::realtime::")
            && !generated.contains("jerrycan::storage::"),
        "no extension extends for a plain db design: {generated}"
    );
}

/// Issue #68: when the creator that seeds a sibling `/{id}` probe is marked
/// `probe: "skip"` (a hand-written validator rejects the generated fixture), the
/// seed POST would 404 every downstream probe. The generator must NOT emit those
/// guaranteed-red sibling probes — it emits an AGENT TODO instead, and the doomed
/// probes are excluded from `expected_failing`. This is JR4's exact shape.
#[test]
fn skipped_creator_suppresses_sibling_id_probes() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "sitemonitor",
        "contract_version": 1,
        "dependencies": ["db"],
        "modules": [{
            "name": "monitors",
            "entities": [{ "name": "Monitor",
                "fields": [{ "name": "url", "type": "string" }] }],
            "endpoints": [
                // The creator rejects the generated fixture (url must be http/https),
                // so it is marked probe: skip. It must not seed sibling /{id} probes.
                { "operation_id": "create_monitor", "method": "POST", "path": "/",
                  "probe": "skip", "request_body": { "entity": "Monitor" },
                  "success": { "status": 201, "entity": "Monitor" } },
                { "operation_id": "get_monitor", "method": "GET", "path": "/{id}",
                  "success": { "status": 200, "entity": "Monitor" },
                  "errors": [{ "status": 404, "when": "unknown id" }] },
                { "operation_id": "delete_monitor", "method": "DELETE", "path": "/{id}",
                  "success": { "status": 204 } }
            ]
        }]
    }))
    .unwrap();
    let module = &design.modules[0];
    let generated = testgen::acceptance_rs(&design, module);
    // No guaranteed-red sibling success probes seeded through the skipped creator.
    assert!(
        !generated.contains("async fn get_monitor_returns_200"),
        "a probe:skip creator must not seed a sibling GET /{{id}} success probe: {generated}"
    );
    assert!(
        !generated.contains("async fn delete_monitor_returns_204"),
        "a probe:skip creator must not seed a sibling DELETE /{{id}} success probe: {generated}"
    );
    // It emits an AGENT TODO naming the skipped-creator reason instead.
    assert!(
        generated.contains("// AGENT TODO: get_monitor") && generated.contains("probe: skip"),
        "must emit an AGENT TODO explaining the skipped seed creator: {generated}"
    );
    // The 404 missing-id probe does NOT need a seed (it hits a missing id), so it
    // stays — the creator's validator never touches the getter.
    assert!(
        generated.contains("async fn get_monitor_missing_id_is_404"),
        "the missing-id 404 probe needs no seed and must remain greenable: {generated}"
    );

    // expected_failing counts only the emitted, greenable tests. The doomed sibling
    // success probes are NOT counted.
    let tmp = std::env::temp_dir().join(format!("jc68-{}", std::process::id()));
    std::fs::create_dir_all(tmp.join("crates/routes/monitors/tests")).unwrap();
    let (_rel, expected_failing) = testgen::write_acceptance(&tmp, &design, "monitors").unwrap();
    // Only the create_monitor probe:skip TODO + the get/delete sibling TODOs remain;
    // the sole greenable RED-on-stubs test is get_monitor_missing_id_is_404.
    assert_eq!(
        expected_failing, 1,
        "only the 404 missing-id probe is a counted RED-on-stubs test: {generated}"
    );
    std::fs::remove_dir_all(&tmp).ok();
}

/// Issue #123(b): a GUARDED `/{id}` sibling of a `probe: "skip"` creator loses
/// its seeded success probe (issue #68 — the skipped creator can't seed it) but
/// KEEPS its `_without_auth_is_401` guard test. WHY (Rule 9): the guard rejects
/// a credential-less request before the id lookup, so a literal id stands in
/// and no seed is needed — dropping the test would silently un-test a real guard.
#[test]
fn skipped_creator_guarded_sibling_keeps_the_401_guard_test() {
    let design: Design = serde_json::from_value(serde_json::json!({
        "name": "sitemonitor",
        "contract_version": 1,
        "auth": { "model": "session", "roles": ["admin"] },
        "dependencies": ["db", "auth"],
        "modules": [{
            "name": "monitors",
            "entities": [{ "name": "Monitor",
                "fields": [{ "name": "url", "type": "string" }] }],
            "endpoints": [
                { "operation_id": "create_monitor", "method": "POST", "path": "/",
                  "auth_required": true, "probe": "skip",
                  "request_body": { "entity": "Monitor" },
                  "success": { "status": 201, "entity": "Monitor" } },
                { "operation_id": "get_monitor", "method": "GET", "path": "/{id}",
                  "auth_required": true,
                  "success": { "status": 200, "entity": "Monitor" } }
            ]
        }]
    }))
    .unwrap();
    let generated = testgen::acceptance_rs(&design, &design.modules[0]);
    // The seeded success probe stays suppressed (issue #68)...
    assert!(
        !generated.contains("async fn get_monitor_returns_200"),
        "a probe:skip creator still suppresses the sibling success probe: {generated}"
    );
    // ...but the guarded sibling keeps its 401 guard test, on a literal id.
    assert!(
        generated.contains("async fn get_monitor_without_auth_is_401"),
        "a guarded sibling of a skipped creator keeps its 401 guard test: {generated}"
    );
    assert!(
        generated.contains("\"/monitors/1\""),
        "the sibling 401 probe pins {{id}} to a literal — no seed needed: {generated}"
    );
    // The guarded skipped creator itself keeps its own 401 guard test too.
    assert!(
        generated.contains("async fn create_monitor_without_auth_is_401"),
        "the guarded skipped creator keeps its own 401 guard test: {generated}"
    );
}

/// A subroute-mounted, tenant-owned module: `channels` mounts at
/// `/workspaces/{workspace_id}/channels` (the tenant fk rides in the MOUNT prefix,
/// not `ep.path`), and each Channel `belongs_to` the tenant Workspace.
const WORKSPACE_CHANNELS_NESTED: &str = r#"{
    "name": "chat-api", "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": "id", "type": "integer" }, { "name": "name", "type": "string" } ]}],
          "endpoints": [
              { "operation_id": "create_workspace", "method": "POST", "path": "/", "auth_required": true,
                "request_body": { "entity": "Workspace" }, "success": { "status": 201, "entity": "Workspace" } },
              { "operation_id": "list_workspaces", "method": "GET", "path": "/", "auth_required": true,
                "success": { "status": 200, "entity": "Workspace", "list": true } } ] },
        { "name": "channels", "mount": "/workspaces/{workspace_id}/channels",
          "entities": [{ "name": "Channel", "belongs_to": [{ "entity": "Workspace" }],
              "fields": [{ "name": "id", "type": "integer" }, { "name": "name", "type": "string" }] }],
          "endpoints": [
              { "operation_id": "create_channel", "method": "POST", "path": "/", "auth_required": true,
                "request_body": { "entity": "Channel" }, "success": { "status": 201, "entity": "Channel" } },
              { "operation_id": "get_channel", "method": "GET", "path": "/{id}", "auth_required": true,
                "success": { "status": 200, "entity": "Channel" },
                "errors": [{ "status": 404, "when": "unknown id" }] } ] }
    ]
}"#;

/// Issue #81: a subroute-mounted module's per-endpoint acceptance URLs must
/// substitute the mount-inherited path param with the seeded parent id (1), not
/// leave the literal `{workspace_id}` token. WHY (Rule 9): `channels` inherits
/// `{workspace_id}` in its MOUNT (not `ep.path`); left literal, the router
/// 400/404s the whole test group, so a correct app's tests are red BY CONSTRUCTION
/// and the builder re-scaffolds (the round-5 eval's biggest token sink). The mount
/// param is the tenant fk, seeded at id 1 by app()'s tenant chain, so pinning it to
/// `1` makes every probe URL concrete AND resolvable.
#[test]
fn subroute_mount_param_is_substituted_in_per_endpoint_urls() {
    let d: Design = serde_json::from_str(WORKSPACE_CHANNELS_NESTED).unwrap();
    let channels = d.modules.iter().find(|m| m.name == "channels").unwrap();
    let out = testgen::acceptance_rs(&d, channels);

    // No REQUEST url (`t.<verb>(...)`) may carry the literal mount param. The router
    // registration line (`.mount("/workspaces/{workspace_id}/channels", ...)`) keeps
    // the param PATTERN by design, so it is excluded from this check.
    for line in out
        .lines()
        .filter(|l| l.contains("    t.") || l.contains("= t."))
    {
        assert!(
            !line.contains("{workspace_id}"),
            "a request URL carries the literal mount param:\n{line}\n---\n{out}"
        );
    }
    // The create success test posts to the concrete, seeded-parent collection URL.
    let create = test_body(&out, "create_channel_returns_201");
    assert!(
        create.contains("t.post_json_with(\"/workspaces/1/channels/\""),
        "create URL pins the mount param to the seeded id 1:\n{create}"
    );
    // The by-id GET success test seeds via the concrete collection URL, then probes
    // the seeded row under the concrete mount (own `{id}` -> seeded id 1 as well).
    let get = test_body(&out, "get_channel_returns_200");
    assert!(
        get.contains("post_json_with(\"/workspaces/1/channels/\"")
            && get.contains("/workspaces/1/channels/1"),
        "get URL seeds + probes under the concrete mount:\n{get}"
    );
    // The missing-id 404 probe substitutes the mount param and probes a missing id.
    let missing = test_body(&out, "get_channel_missing_id_is_404");
    assert!(
        missing.contains("/workspaces/1/channels/999999"),
        "404 probe substitutes the mount param:\n{missing}"
    );
}

/// A FLAT module (no mount param) with a standalone `/{id}` route.
const FLAT_CUSTOMERS: &str = r#"{
    "name": "shop", "contract_version": 1, "dependencies": ["db"],
    "modules": [{
        "name": "customers",
        "entities": [{ "name": "Customer", "fields": [
            { "name": "id", "type": "integer" }, { "name": "email", "type": "string" } ]}],
        "endpoints": [
            { "operation_id": "create_customer", "method": "POST", "path": "/",
              "request_body": { "entity": "Customer" },
              "success": { "status": 201, "entity": "Customer" } },
            { "operation_id": "show_customer", "method": "GET", "path": "/{id}",
              "success": { "status": 200, "entity": "Customer" },
              "errors": [{ "status": 404, "when": "unknown id" }] }
        ]
    }]
}"#;

/// Issue #81 (byte-identity guard): a FLAT module (no mount param) must be
/// UNCHANGED by the mount-substitution fix — its accumulated mount carries no
/// `{param}` to substitute, so the substitution is the identity. WHY (Rule 9): the
/// fix is test-generation-only and must touch ONLY nested-mount modules; a
/// regression that rewrote flat URLs would silently change every non-nested app's
/// generated tests.
#[test]
fn flat_module_urls_are_unchanged_by_mount_substitution() {
    let d: Design = serde_json::from_str(FLAT_CUSTOMERS).unwrap();
    let customers = d.modules.iter().find(|m| m.name == "customers").unwrap();
    let out = testgen::acceptance_rs(&d, customers);
    // The flat create posts to the plain collection URL (no cookie: no auth)...
    assert!(
        out.contains("t.post_json(\"/customers/\""),
        "flat create URL is the plain collection path: {out}"
    );
    // ...the by-id probe addresses the seeded row directly under it, and the 404
    // probe hits a missing id — both plain, no nested segment.
    let show = test_body(&out, "show_customer_returns_200");
    assert!(
        show.contains("/customers/1"),
        "flat by-id URL is the plain path:\n{show}"
    );
    assert!(
        out.contains("/customers/999999"),
        "flat 404 URL is the plain path: {out}"
    );
    // No substitution artifact leaks into a flat file (no nested `/customers/<id>/…`).
    assert!(
        !out.contains("/customers/1/"),
        "a flat module must not gain a nested mount segment: {out}"
    );
}

/// Issue #85 (D3): a `unique` field on the tenant entity must seed a value
/// DISTINCT from the create-probe body, or the create probe 409s on the
/// pre-seeded tenant row. This tenant module owns a child (`Project`), so `app()`
/// pre-seeds the `Org` tenant row — and `create_org`'s probe body must not reuse
/// that row's unique `slug`. WHY (Rule 9): the round-4 `index` workaround did NOT
/// prevent the collision; only a distinct seed value keeps the create probe green.
#[test]
fn unique_tenant_field_seed_does_not_collide_with_the_create_probe() {
    const UNIQUE_TENANT: &str = r#"{
        "name": "orgs", "contract_version": 0,
        "auth": { "model": "session" },
        "dependencies": ["db", "auth"],
        "tenancy": { "entity": "Org", "member_roles": ["owner"] },
        "modules": [{ "name": "orgs",
            "entities": [
                { "name": "Org", "fields": [
                    { "name": "id", "type": "integer" },
                    { "name": "slug", "type": "string", "unique": true } ] },
                { "name": "Project", "belongs_to": [{ "entity": "Org" }],
                  "fields": [
                    { "name": "id", "type": "integer" },
                    { "name": "title", "type": "string" } ] } ],
            "endpoints": [
                { "operation_id": "list_orgs", "method": "GET", "path": "/", "auth_required": true,
                  "success": { "status": 200, "entity": "Org", "list": true } },
                { "operation_id": "create_org", "method": "POST", "path": "/", "auth_required": true,
                  "request_body": { "entity": "Org" },
                  "success": { "status": 201, "entity": "Org" } } ] }]
    }"#;
    let design: Design = serde_json::from_str(UNIQUE_TENANT).unwrap();
    let module = &design.modules[0];
    let generated = testgen::acceptance_rs(&design, module);
    // The create probe carries the ordinary string fixture for the unique slug.
    assert!(
        generated.contains("\"slug\": \"test-value\""),
        "create probe posts the string fixture for slug:\n{generated}"
    );
    // The pre-seeded tenant-1 row must NOT reuse that same unique value, else the
    // create probe 409s on the seeded row.
    assert!(
        !generated.contains("VALUES (1, 'test-value')"),
        "tenant-1 seed must not reuse the probe's unique slug value (would 409):\n{generated}"
    );
}

/// #107 (0.6.0 §D): the TENANT module's acceptance file carries the generated
/// member-surface tests — list, add (201), non-admin add (403), set-role (204,
/// persisted), remove (204, persisted), last-admin 409 on BOTH demote and
/// remove, self-removal without the admin role (204), and out-of-set role
/// (422). WHY (Rule 9): these routes are tool-owned real handlers, and these
/// tests are the runtime backstop that keeps the #107 security rules (admin
/// gate, last-admin lockout, role allow-list) from silently regressing in any
/// scaffolded app. They run under `jerrycan check` like every generated test.
#[test]
fn tenant_module_gets_member_surface_tests() {
    let s = include_str!("../../../conformance/designs/reference-slice.design.json");
    let d: Design = serde_json::from_str(s).unwrap();
    let workspaces = d
        .modules
        .iter()
        .find(|m| m.name == "workspaces")
        .expect("workspaces module");
    let out = testgen::acceptance_rs(&d, workspaces);

    // All nine tests, named after the member-route operation ids.
    for expected in [
        "async fn list_workspace_members_returns_200",
        "async fn add_workspace_member_returns_201",
        "async fn add_workspace_member_without_the_admin_role_is_403",
        "async fn set_workspace_member_role_returns_204",
        "async fn remove_workspace_member_returns_204",
        "async fn set_workspace_member_role_last_admin_demotion_is_409",
        "async fn remove_workspace_member_last_admin_is_409",
        "async fn remove_workspace_member_self_leave_returns_204",
        "async fn add_workspace_member_rejects_out_of_range_role",
    ] {
        assert!(out.contains(expected), "missing {expected}\n{out}");
    }
    // member_app() seeds the setup via RAW SQL (never the stubbed creator):
    // tenant 1, user 1 as the admin (member_roles[0] = owner), user 2 as the
    // non-admin member the 403/self-leave probes act as.
    let member_fn = out
        .split("async fn member_app()")
        .nth(1)
        .expect("member_app() helper")
        .split("#[tokio::test]")
        .next()
        .unwrap();
    assert!(
        member_fn.contains(
            "INSERT INTO \\\"workspace_members\\\" (user_id, workspace_id, role) VALUES (1, 1, 'owner')"
        ) && member_fn.contains(
            "INSERT INTO \\\"workspace_members\\\" (user_id, workspace_id, role) VALUES (2, 1, 'member')"
        ),
        "member_app seeds the admin (user 1) and a non-admin member (user 2) in tenant 1: {member_fn}"
    );
    assert!(
        member_fn.contains("INSERT INTO \\\"workspaces\\\"") && member_fn.contains("'trial'"),
        "member_app seeds the tenant row with a CHECK-valid enum value: {member_fn}"
    );
    assert!(
        member_fn.contains(".provide_dep(shared::tenant)"),
        "member_app registers the Tenant factory the member handlers resolve: {member_fn}"
    );
    // The probe URLs are path-scoped under the seeded tenant fk, and the jwt
    // credential is threaded per the auth model.
    assert!(
        out.contains("t.get_with(\"/workspaces/1/members\"")
            && out.contains("/workspaces/1/members/2")
            && out.contains("(\"authorization\", &test_cookie_for(2))"),
        "member probes hit the path-scoped member routes as distinct users: {out}"
    );
    // The 403 probe acts as the NON-admin (user 2); the last-admin probes act
    // on the SOLE admin (user 1).
    let forbidden = test_body(&out, "add_workspace_member_without_the_admin_role_is_403");
    assert!(
        forbidden.contains("test_cookie_for(2)") && forbidden.contains("403"),
        "the 403 probe must act as the non-admin member:\n{forbidden}"
    );
    let last_admin = test_body(&out, "remove_workspace_member_last_admin_is_409");
    assert!(
        last_admin.contains("/workspaces/1/members/1") && last_admin.contains("409"),
        "the last-admin probe removes the sole admin (user 1) and expects 409:\n{last_admin}"
    );
    // Self-leave: user 2 deletes their OWN membership — 204 without the admin role.
    let leave = test_body(&out, "remove_workspace_member_self_leave_returns_204");
    assert!(
        leave.contains("/workspaces/1/members/2") && leave.contains("test_cookie_for(2)"),
        "self-leave acts as user 2 on their own membership:\n{leave}"
    );

    // Confinement: a NON-tenant module of the same design gains nothing…
    let leads = d.modules.iter().find(|m| m.name == "leads").unwrap();
    let leads_out = testgen::acceptance_rs(&d, leads);
    assert!(
        !leads_out.contains("member_app") && !leads_out.contains("_members_returns_"),
        "non-tenant modules must not gain member tests: {leads_out}"
    );
    // …and a non-tenancy design stays byte-free of the surface.
    let plain = golden(true);
    let plain_out = testgen::acceptance_rs(&plain, &plain.modules[0]);
    assert!(
        !plain_out.contains("member_app"),
        "a non-tenancy design must not gain member tests: {plain_out}"
    );
}

/// #107: the member-surface tests PASS on a fresh scaffold (tool-owned real
/// handlers, raw-SQL seeds), so they must be EXCLUDED from the RED-on-stubs
/// `expected_failing` baseline — exactly like the enum reject probes. WHY
/// (Rule 9): `jerrycan check` compares observed failures against this count; if
/// the 9 green member tests were counted, every tenancy app's check would
/// report a broken baseline forever.
#[test]
fn member_surface_tests_are_excluded_from_expected_failing() {
    let s = include_str!("../../../conformance/designs/reference-slice.design.json");
    let d: Design = serde_json::from_str(s).unwrap();
    let tmp = std::env::temp_dir().join(format!("jc107-{}", std::process::id()));
    std::fs::create_dir_all(tmp.join("crates/routes/workspaces/tests")).unwrap();
    let (_rel, expected_failing) = testgen::write_acceptance(&tmp, &d, "workspaces").unwrap();
    let generated =
        std::fs::read_to_string(tmp.join("crates/routes/workspaces/tests/acceptance.rs")).unwrap();
    std::fs::remove_dir_all(&tmp).ok();
    // workspaces emits 15 tests. Its reads are `public: true` (public discovery),
    // so no read 401 probe and no I1 test. Counted toward expected_failing: list(1)
    // + create(1) + create-401(1) + show(1) + show-404(1) = 5 (the long-standing
    // baseline). Excluded: the create enum-reject probe (1) and the member
    // surface (9) — both pass on stubs.
    assert_eq!(
        testgen::test_count(&generated),
        15,
        "5 endpoint probes + 1 enum reject + 9 member tests: {generated}"
    );
    assert_eq!(
        expected_failing, 5,
        "the enum reject probe and the 9 member tests must be excluded: {generated}"
    );
}

/// #107: a SINGLE-role tenancy design (member_roles = ["owner"]) keeps only the
/// member tests that need no second, non-admin role: list, add (another admin),
/// last-admin remove 409, and the 422 role probe. The 403/re-role/remove/
/// demote/self-leave probes all REQUIRE a seeded non-admin member, which a
/// one-role design cannot express — emitting them would produce un-greenable
/// tests (user 2 would be an admin, so the 403 could never fire).
#[test]
fn single_role_tenancy_keeps_only_the_roleless_member_tests() {
    let d: Design = serde_json::from_value(serde_json::json!({
        "name": "solo-api",
        "contract_version": 1,
        "auth": { "model": "session", "roles": ["owner"] },
        "dependencies": ["db", "auth"],
        "tenancy": { "entity": "Org", "member_roles": ["owner"] },
        "modules": [{
            "name": "orgs",
            "entities": [{ "name": "Org", "fields": [
                { "name": "id", "type": "integer" },
                { "name": "name", "type": "string" } ]}],
            "endpoints": [
                { "operation_id": "create_org", "method": "POST", "path": "/", "auth_required": true,
                  "request_body": { "entity": "Org" },
                  "success": { "status": 201, "entity": "Org" } }
            ]
        }]
    }))
    .unwrap();
    let out = testgen::acceptance_rs(&d, &d.modules[0]);
    for expected in [
        "async fn list_org_members_returns_200",
        "async fn add_org_member_returns_201",
        "async fn remove_org_member_last_admin_is_409",
        "async fn add_org_member_rejects_out_of_range_role",
    ] {
        assert!(out.contains(expected), "missing {expected}\n{out}");
    }
    for absent in [
        "without_the_admin_role_is_403",
        "set_org_member_role_returns_204",
        "async fn remove_org_member_returns_204",
        "last_admin_demotion_is_409",
        "self_leave_returns_204",
    ] {
        assert!(
            !out.contains(absent),
            "a one-role design must not emit `{absent}` (needs a non-admin member):\n{out}"
        );
    }
    // No second membership is seeded — there is no second role to hold.
    assert!(
        !out.contains("VALUES (2, 1,"),
        "single-role member_app seeds no user-2 membership: {out}"
    );
    // The single add test adds another admin (the only declared role).
    let add = test_body(&out, "add_org_member_returns_201");
    assert!(
        add.contains("\"role\": \"owner\""),
        "single-role add uses the only declared role:\n{add}"
    );
}

// ---- #80: constraint-aware fixtures/seeds + the out-of-range 422 probe ----

/// One module, one entity with the given fields, a POST "/" creator and a
/// PUT "/{id}" updater — the minimal design the #80 testgen changes act on.
fn constrained_design(fields: serde_json::Value) -> Design {
    serde_json::from_value(serde_json::json!({
        "name": "shop-api",
        "contract_version": 1,
        "dependencies": ["db"],
        "modules": [{
            "name": "items",
            "entities": [{ "name": "Item", "fields": fields }],
            "endpoints": [
                { "operation_id": "create_item", "method": "POST", "path": "/",
                  "request_body": { "entity": "Item" },
                  "success": { "status": 201, "entity": "Item" } },
                { "operation_id": "update_item", "method": "PUT", "path": "/{id}",
                  "request_body": { "entity": "Item" },
                  "success": { "status": 200, "entity": "Item" } }
            ]
        }]
    }))
    .unwrap()
}

/// #80: a constrained field's happy-path fixture must be IN-RANGE — the design
/// declares the bound precisely so the generator can derive a fixture that
/// clears the deserialize validator and the migration CHECK (the whole point
/// of #80: no more hand-written `Valid` impls rejecting `"test-value"`/`1`).
#[test]
fn constrained_fixtures_are_derived_in_range() {
    let d = constrained_design(serde_json::json!([
        { "name": "quantity", "type": "integer", "min": 5, "max": 600 },
        { "name": "code", "type": "string", "max_len": 5 },
        { "name": "body", "type": "string", "min_len": 12 }
    ]));
    let generated = testgen::acceptance_rs(&d, &d.modules[0]);
    // Integer: the default 1 clamps up to min (5).
    assert!(
        generated.contains("\"quantity\": 5"),
        "int fixture must clamp into [5, 600]: {generated}"
    );
    // String over max_len: "test-value" truncates to 5 code points.
    assert!(
        generated.contains("\"code\": \"test-\""),
        "string fixture must truncate to max_len: {generated}"
    );
    // String under min_len: a synthesized minimum-length value.
    assert!(
        generated.contains("\"body\": \"aaaaaaaaaaaa\""),
        "string fixture must satisfy min_len (12): {generated}"
    );
}

/// #80: a constrained request body gets an out-of-range 422 reject probe on
/// BOTH the create and update paths (mirroring the #47 enum probes). WHY
/// (Rule 9): the docs promise a declared bound is enforced at the request
/// boundary; this pins that an out-of-range value 422s (JC0422), never dies
/// as a 500 at the DB CHECK.
#[test]
fn constrained_body_gets_out_of_range_reject_probe_on_create_and_update() {
    let d = constrained_design(serde_json::json!([
        { "name": "quantity", "type": "integer", "min": 1, "max": 600 }
    ]));
    let generated = testgen::acceptance_rs(&d, &d.modules[0]);
    assert!(
        generated.contains("async fn create_item_rejects_out_of_range_quantity"),
        "create reject probe: {generated}"
    );
    assert!(
        generated.contains("async fn update_item_rejects_out_of_range_quantity"),
        "update reject probe: {generated}"
    );
    // The probe corrupts ONLY the constrained field, to max + 1.
    assert!(
        generated.contains("\"quantity\": 601"),
        "reject body carries max + 1: {generated}"
    );
    let probe = test_body(&generated, "create_item_rejects_out_of_range_quantity");
    assert!(probe.contains("as_u16(), 422"), "asserts 422:\n{probe}");
    // The happy-path fixture stays in-range (1 is inside [1, 600]).
    let happy = test_body(&generated, "create_item_returns_201");
    assert!(
        happy.contains("\"quantity\": 1"),
        "in-range fixture:\n{happy}"
    );
}

/// #80 (0.6.5 final review, Critical): `serde_json::json!` types a bare
/// numeric literal as `i32`, so a constrained-integer fixture or reject value
/// OUTSIDE i32 range must be emitted `i64`-suffixed — a plain `3000000000`
/// inside a probe body is a HARD compile error in the generated suite
/// (deny-by-default `overflowing_literals`), failing `cargo test` on a
/// JC0552-clean design. Values inside i32 range stay unsuffixed, keeping
/// every existing design's output byte-identical.
#[test]
fn out_of_i32_range_bounds_emit_i64_suffixed_literals() {
    let d = constrained_design(serde_json::json!([
        { "name": "starts_at", "type": "integer", "min": 0, "max": 4102444800i64 },
        { "name": "seq", "type": "integer", "min": 3000000000i64 }
    ]));
    let generated = testgen::acceptance_rs(&d, &d.modules[0]);
    // Happy-path fixture: clamp(1) up to min 3000000000 — beyond i32, suffixed.
    assert!(
        generated.contains("\"seq\": 3000000000i64"),
        "out-of-i32-range fixture must be i64-suffixed: {generated}"
    );
    // Reject literal: max + 1 = 4102444801 — beyond i32, suffixed.
    assert!(
        generated.contains("\"starts_at\": 4102444801i64"),
        "out-of-i32-range reject literal must be i64-suffixed: {generated}"
    );
    // A constrained value INSIDE i32 range stays a plain literal (the
    // byte-identity guarantee for every existing design).
    assert!(
        generated.contains("\"starts_at\": 1,"),
        "in-i32-range fixture stays unsuffixed: {generated}"
    );

    // The negative direction: a bound below i32::MIN suffixes too.
    let d = constrained_design(serde_json::json!([
        { "name": "depth", "type": "integer", "max": -3000000000i64 }
    ]));
    let generated = testgen::acceptance_rs(&d, &d.modules[0]);
    assert!(
        generated.contains("\"depth\": -3000000000i64"),
        "below-i32::MIN fixture must be i64-suffixed: {generated}"
    );
}

/// #80: the constraint reject probes PASS on stubs (the 422 precedes the
/// handler), so `expected_failing` must exclude them — exactly like the #47
/// enum rejects. Otherwise the RED-on-stubs invariant over-counts.
#[test]
fn constraint_reject_probes_are_excluded_from_expected_failing() {
    let d = constrained_design(serde_json::json!([
        { "name": "quantity", "type": "integer", "min": 1, "max": 600 },
        { "name": "code", "type": "string", "max_len": 5 }
    ]));
    let generated = testgen::acceptance_rs(&d, &d.modules[0]);
    let total = testgen::test_count(&generated);
    let rejects = generated
        .matches("async fn create_item_rejects_out_of_range_")
        .count()
        + generated
            .matches("async fn update_item_rejects_out_of_range_")
            .count();
    assert!(rejects >= 2, "create + update reject probes: {generated}");

    let tmp = tempfile::tempdir().unwrap();
    let (_rel, expected_failing) =
        testgen::write_acceptance(tmp.path(), &d, "items").expect("write acceptance");
    assert_eq!(
        expected_failing,
        total - rejects,
        "expected_failing must exclude exactly the reject probes (total {total}, rejects {rejects})"
    );
}

/// #80: a string bound's reject literal is emitted as a `"a".repeat(n)`
/// EXPRESSION (serde_json::json! accepts expressions), so the generated file
/// never embeds a giant literal; over-max is preferred, under-min is the
/// fallback.
#[test]
fn string_reject_probe_uses_a_repeat_expression() {
    let d = constrained_design(serde_json::json!([
        { "name": "code", "type": "string", "max_len": 5 }
    ]));
    let generated = testgen::acceptance_rs(&d, &d.modules[0]);
    assert!(
        generated.contains("\"code\": \"a\".repeat(6)"),
        "over-max reject sends max_len + 1 code points: {generated}"
    );

    // min_len-only: the under-min direction (min_len - 1).
    let d = constrained_design(serde_json::json!([
        { "name": "body", "type": "string", "min_len": 3 }
    ]));
    let generated = testgen::acceptance_rs(&d, &d.modules[0]);
    assert!(
        generated.contains("\"body\": \"a\".repeat(2)"),
        "under-min reject sends min_len - 1 code points: {generated}"
    );
}

/// #80 (T1 review, Important-b): a very large `max_len` must NOT materialize a
/// multi-megabyte over-max string at test run time — above the 4096 fixture
/// cap the probe falls back to the under-`min_len` direction, or (no usable
/// min_len) emits no probe at all.
#[test]
fn huge_max_len_never_materializes_an_over_max_reject_string() {
    // No min_len: nothing rejectable below, over-max too large — no probe.
    let d = constrained_design(serde_json::json!([
        { "name": "body", "type": "string", "max_len": 100000 }
    ]));
    let generated = testgen::acceptance_rs(&d, &d.modules[0]);
    assert!(
        !generated.contains("_rejects_out_of_range_"),
        "an over-cap max_len with no min_len emits no probe: {generated}"
    );
    // The happy fixture still fits (10 <= 100000) and stays the plain literal.
    assert!(
        generated.contains("\"body\": \"test-value\""),
        "{generated}"
    );

    // With a usable min_len the probe flips to the under-min direction.
    let d = constrained_design(serde_json::json!([
        { "name": "body", "type": "string", "min_len": 3, "max_len": 100000 }
    ]));
    let generated = testgen::acceptance_rs(&d, &d.modules[0]);
    assert!(
        generated.contains("\"body\": \"a\".repeat(2)"),
        "over-cap max_len falls back to under-min: {generated}"
    );
    assert!(
        !generated.contains("repeat(100001)"),
        "never materialize an over-cap string: {generated}"
    );
}

/// #80: a bound at the i64 extreme is vacuous — the generated validator gates
/// it out (`bounds_rules`), so the probe must not target it: `max: i64::MAX`
/// falls back to `min - 1`; with BOTH extremes gated nothing is rejectable and
/// no probe is emitted.
#[test]
fn i64_extreme_bounds_fall_back_or_skip_the_probe() {
    let d = constrained_design(serde_json::json!([
        { "name": "views", "type": "integer", "min": 1, "max": i64::MAX }
    ]));
    let generated = testgen::acceptance_rs(&d, &d.modules[0]);
    assert!(
        generated.contains("\"views\": 0"),
        "max at i64::MAX falls back to min - 1: {generated}"
    );

    let d = constrained_design(serde_json::json!([
        { "name": "views", "type": "integer", "min": i64::MIN, "max": i64::MAX }
    ]));
    let generated = testgen::acceptance_rs(&d, &d.modules[0]);
    assert!(
        !generated.contains("_rejects_out_of_range_"),
        "both extremes gated: nothing rejectable, no probe: {generated}"
    );
}

/// #80: a defaulted constrained field is omitted from the create request DTO
/// (issue #53a), so a bad value would be dropped, not 422'd — no reject probe
/// (the same rule `first_enum_field` applies to defaulted enum fields).
#[test]
fn defaulted_constrained_field_gets_no_reject_probe() {
    let d = constrained_design(serde_json::json!([
        { "name": "quantity", "type": "integer", "min": 1, "max": 600, "default": 1 }
    ]));
    let generated = testgen::acceptance_rs(&d, &d.modules[0]);
    assert!(
        !generated.contains("_rejects_out_of_range_"),
        "a defaulted field cannot be rejected at the boundary: {generated}"
    );
}

/// #80: the SQL tenant seeds stay IN-RANGE and (for `unique` fields) DISTINCT
/// from each other and from the HTTP probe fixture — a constrained unique
/// field must survive the migration CHECK on tenant 1 AND tenant 2 without
/// colliding with the create probe's body (#85's invariant, now under bounds).
#[test]
fn tenant_seeds_for_constrained_unique_fields_stay_in_range_and_distinct() {
    let d: Design = serde_json::from_value(serde_json::json!({
        "name": "crm-api",
        "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": "id", "type": "integer" },
                  { "name": "slots", "type": "integer", "unique": true, "min": 5, "max": 600 },
                  { "name": "slug", "type": "string", "unique": true, "max_len": 8 }
              ]}],
              "endpoints": [] },
            { "name": "leads",
              "entities": [{ "name": "Lead",
                  "belongs_to": [{ "entity": "Workspace", "on_delete": "cascade" }],
                  "fields": [{ "name": "name", "type": "string" }] }],
              "endpoints": [
                  { "operation_id": "create_lead", "method": "POST", "path": "/", "auth_required": true,
                    "request_body": { "entity": "Lead" },
                    "success": { "status": 201, "entity": "Lead" } }
              ] }
        ]
    }))
    .unwrap();
    let leads = d.modules.iter().find(|m| m.name == "leads").unwrap();
    let generated = testgen::acceptance_rs(&d, leads);
    // Tenant 1: slots = the 1st distinct in-range value after the fixture
    // anchor (5) → 6; slug = 'seed-test-value' fitted to max_len 8.
    assert!(
        generated.contains("VALUES (1, 6, 'seed-tes')"),
        "tenant-1 seed must be in-range and distinct from the fixture: {generated}"
    );
    // Tenant 2: slots = the 2nd distinct value (7); slug keeps its
    // discriminator through the fit (front-loaded '2').
    assert!(
        generated.contains("VALUES (2, 7, '2-test-v')"),
        "tenant-2 seed must be in-range and distinct from tenant 1: {generated}"
    );
}

/// #115 composite / multi-column UNIQUE: an entity with `unique: [["user_id",
/// "post_id"]]` gets a `{entity}_composite_unique_{ordinal}_is_409` test — seed the
/// parents, create a row, then POST a body that agrees on the group → assert 409
/// (the DB unique index makes the duplicate a conflict). Byte-identity twin: an
/// entity with no composite `unique` emits no such test.
#[test]
fn composite_unique_emits_a_409_conflict_test() {
    const LIKES: &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_user", "method": "POST", "path": "/users",
                  "request_body": { "entity": "User" },
                  "success": { "status": 201, "entity": "User" } },
                { "operation_id": "create_post", "method": "POST", "path": "/posts",
                  "request_body": { "entity": "Post" },
                  "success": { "status": 201, "entity": "Post" } },
                { "operation_id": "create_like", "method": "POST", "path": "/likes",
                  "request_body": { "entity": "Like" },
                  "success": { "status": 201, "entity": "Like" } }
            ]
        }]
    }"#;
    let d: Design = serde_json::from_str(LIKES).unwrap();
    let module = &d.modules[0];
    let generated = testgen::acceptance_rs(&d, module);
    // The named test exists, keyed on the entity snake + the group ordinal.
    assert!(
        generated.contains("async fn like_composite_unique_0_is_409()"),
        "the composite-unique 409 test must be emitted:\n{generated}"
    );
    // It seeds both belongs_to parents (an enforced intra-module fk must resolve).
    assert!(
        generated.contains("/engagement/users") && generated.contains("/engagement/posts"),
        "the 409 test must seed the User and Post parents:\n{generated}"
    );
    // It posts the create body twice and asserts the second is a 409.
    let body = generated
        .split("async fn like_composite_unique_0_is_409()")
        .nth(1)
        .unwrap();
    let body = body.split("\n}\n").next().unwrap();
    assert_eq!(
        body.matches("/engagement/likes").count(),
        2,
        "two POSTs to the likes collection (first + duplicate):\n{body}"
    );
    assert!(
        body.contains("assert_eq!(dup.status().as_u16(), 409"),
        "the duplicate insert must assert 409:\n{body}"
    );

    // Byte-identity twin: drop the composite unique → no such test.
    let plain = d.clone();
    let mut v: serde_json::Value = serde_json::to_value(&plain).unwrap();
    v["modules"][0]["entities"][2]
        .as_object_mut()
        .unwrap()
        .remove("unique");
    let plain: Design = serde_json::from_value(v).unwrap();
    let plain_gen = testgen::acceptance_rs(&plain, &plain.modules[0]);
    assert!(
        !plain_gen.contains("_composite_unique_"),
        "an entity with no composite unique emits no 409 conflict test:\n{plain_gen}"
    );
}

/// #115 review — isolation: the composite-unique 409 test must trip ONLY on the
/// composite index, so its two create bodies AGREE on the group columns
/// (`user_id`, `course_id`) and DIFFER on every OTHER unique key — a `unique`
/// field `code` and the explicit string pk `id`. Without this the dup would 409 on
/// `code` (or on the constant pk) and pass GREEN even if the composite index were
/// missing — a green-means-safe erosion (spec §D).
#[test]
fn composite_unique_dup_bumps_competing_unique_columns_and_pk() {
    const ENROLL: &str = r#"{
        "name": "enroll-api", "contract_version": 1,
        "dependencies": ["db"],
        "modules": [{
            "name": "enrollments",
            "entities": [
                { "name": "User", "fields": [{ "name": "email", "type": "string" }] },
                { "name": "Course", "fields": [{ "name": "title", "type": "string" }] },
                { "name": "Enrollment",
                  "belongs_to": [{ "entity": "User" }, { "entity": "Course" }],
                  "unique": [["user_id", "course_id"]],
                  "fields": [
                      { "name": "id", "type": "string" },
                      { "name": "code", "type": "string", "unique": true }
                  ] }
            ],
            "endpoints": [
                { "operation_id": "create_user", "method": "POST", "path": "/users",
                  "request_body": { "entity": "User" },
                  "success": { "status": 201, "entity": "User" } },
                { "operation_id": "create_course", "method": "POST", "path": "/courses",
                  "request_body": { "entity": "Course" },
                  "success": { "status": 201, "entity": "Course" } },
                { "operation_id": "create_enrollment", "method": "POST", "path": "/enrollments",
                  "request_body": { "entity": "Enrollment" },
                  "success": { "status": 201, "entity": "Enrollment" } }
            ]
        }]
    }"#;
    let d: Design = serde_json::from_str(ENROLL).unwrap();
    let generated = testgen::acceptance_rs(&d, &d.modules[0]);
    // Isolate the 409 test body (first POST + dup POST).
    let body = generated
        .split("async fn enrollment_composite_unique_0_is_409()")
        .nth(1)
        .expect("the composite-unique 409 test must be emitted");
    let body = body.split("\n}\n").next().unwrap();
    // Two POSTs to the enrollments collection: the first + the duplicate.
    let first = body.split("let dup =").next().unwrap();
    let dup = &body[body.find("let dup =").unwrap()..];

    // The GROUP columns are held constant: both bodies carry the SAME fk values
    // (fk_fixture_value → 1 for both user_id and course_id).
    assert!(
        first.contains("\"user_id\": 1") && first.contains("\"course_id\": 1"),
        "the first body must carry the seeded group fks:\n{first}"
    );
    assert!(
        dup.contains("\"user_id\": 1") && dup.contains("\"course_id\": 1"),
        "the dup must AGREE with the first on the group columns:\n{dup}"
    );
    // The competing `unique` field `code` is bumped: the first uses the fixture
    // value, the dup a DISTINCT one, so the dup can't 409 on the `code` unique.
    assert!(
        first.contains("\"code\": \"test-value\""),
        "the first body uses the `code` fixture value:\n{first}"
    );
    assert!(
        dup.contains("\"code\": \"test-value-2\"") && !dup.contains("\"code\": \"test-value\""),
        "the dup must bump the competing `code` unique to a DISTINCT value:\n{dup}"
    );
    // The explicit string pk `id` is bumped too (else a constant pk would 409).
    assert!(
        first.contains("\"id\": \"test-value\""),
        "the first body carries the constant fixture pk:\n{first}"
    );
    assert!(
        dup.contains("\"id\": \"test-value-2\"") && !dup.contains("\"id\": \"test-value\""),
        "the dup must bump the explicit pk to a DISTINCT value:\n{dup}"
    );
    assert!(
        dup.contains("assert_eq!(dup.status().as_u16(), 409"),
        "the duplicate insert must assert 409:\n{dup}"
    );
}

/// #115 review — isolation escape hatch: with `>1` composite group and no
/// single-column `unique`/pk to bump, a second fk-only group is held fully constant
/// by the dup and would 409 on ITS index — so neither group's 409 can be attributed
/// to one index. The generator emits an AGENT TODO instead of a false-green probe.
#[test]
fn composite_unique_skips_with_agent_todo_when_a_competing_group_masks() {
    const TWO_GROUPS: &str = r#"{
        "name": "pairs-api", "contract_version": 1,
        "dependencies": ["db"],
        "modules": [{
            "name": "pairs",
            "entities": [
                { "name": "A", "fields": [{ "name": "label", "type": "string" }] },
                { "name": "B", "fields": [{ "name": "label", "type": "string" }] },
                { "name": "C", "fields": [{ "name": "label", "type": "string" }] },
                { "name": "Pair",
                  "belongs_to": [{ "entity": "A" }, { "entity": "B" }, { "entity": "C" }],
                  "unique": [["a_id", "b_id"], ["a_id", "c_id"]],
                  "fields": [{ "name": "note", "type": "string" }] }
            ],
            "endpoints": [
                { "operation_id": "create_a", "method": "POST", "path": "/as",
                  "request_body": { "entity": "A" },
                  "success": { "status": 201, "entity": "A" } },
                { "operation_id": "create_b", "method": "POST", "path": "/bs",
                  "request_body": { "entity": "B" },
                  "success": { "status": 201, "entity": "B" } },
                { "operation_id": "create_c", "method": "POST", "path": "/cs",
                  "request_body": { "entity": "C" },
                  "success": { "status": 201, "entity": "C" } },
                { "operation_id": "create_pair", "method": "POST", "path": "/pairs",
                  "request_body": { "entity": "Pair" },
                  "success": { "status": 201, "entity": "Pair" } }
            ]
        }]
    }"#;
    // Two DISTINCT fk-only groups (JC0559-valid): the dup for group 0 holds c_id
    // constant too, so group 1 (a_id, c_id) also trips — un-isolable → both TODO.
    let d: Design = serde_json::from_str(TWO_GROUPS).unwrap();
    let generated = testgen::acceptance_rs(&d, &d.modules[0]);
    assert!(
        !generated.contains("_composite_unique_0_is_409()")
            && !generated.contains("_composite_unique_1_is_409()"),
        "a masked composite group must NOT emit a false-green probe:\n{generated}"
    );
    assert!(
        generated.contains("AGENT TODO: pair composite UNIQUE(a_id, b_id) (group #0)")
            && generated.contains("AGENT TODO: pair composite UNIQUE(a_id, c_id) (group #1)"),
        "each masked composite group must emit an AGENT TODO:\n{generated}"
    );
}