jerrycan 0.7.6

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
//! Heavy conformance tests (#[ignore]): real cargo builds of generated apps.
//! Run with: cargo test -p jerrycan --test conformance -- --include-ignored

use std::io::{Read, Write as IoWrite};
use std::path::{Path, PathBuf};
use std::process::Command;

mod common;

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

/// The v2 north-star eval slice: a tenant-scoped, JWT-guarded, db-backed
/// sales-engagement backend (workspaces/leads/api-keys/billing). This is the
/// heavy gate proving the full SeaORM stack scaffolds, builds, and behaves.
const REFERENCE: &str = include_str!("../../../conformance/designs/reference-slice.design.json");

/// Issue #218 guard fixture: db-backed QUEUE jobs (no schedule) with realistic,
/// NON-alphabetical names spanning every rustfmt wrap regime of the registry payload
/// bind + the acceptance-call line, plus two multi-field route modules. reference-slice's
/// two jobs are both CRON, so it never exercised the queue-job emitters this locks.
const QUEUE_JOBS_FIXPOINT: &str =
    include_str!("../../../conformance/designs/queue-jobs-fixpoint.design.json");

/// Issue #221 guard fixtures (residuals D/E/F): three design SHAPES the #218 guards
/// never scaffolded, each of which a fresh scaffold failed `cargo fmt --check` on.
/// D — a SINGLE-route-module jobs design: the jobs (and route) `tests/acceptance.rs`
/// emit a one-element `db.migrate(&[…])` array, which rustfmt HUGS onto one line.
const SINGLE_MODULE_JOBS_FIXPOINT: &str =
    include_str!("../../../conformance/designs/single-module-jobs-fixpoint.design.json");
/// E — an ID-ONLY (single-field, string pk) entity: the repo emits single-field
/// `ActiveModel { id: Set(…) }` literals in `insert`/`update`, which rustfmt collapses.
const ID_ONLY_ENTITY_FIXPOINT: &str =
    include_str!("../../../conformance/designs/id-only-entity-fixpoint.design.json");
/// F (registry) — CRON names spanning rustfmt's NON-MONOTONIC wrap of the closure body
/// `Box::pin({name}::{name}(ctx))` AND the `fn_call_width` break of `.cron(…)`. All names
/// are ≤ 36 cols so rustfmt actually reformats the chain (a ≥ 37 name would make it bail).
const CRON_NAME_WRAP_FIXPOINT: &str =
    include_str!("../../../conformance/designs/cron-name-wrap-fixpoint.design.json");
/// F (task stub) — a CRON name ≥ 39 cols whose agent-owned task-module stub signature
/// `pub async fn {name}(mut _ctx: TaskContext) -> …` wraps one param per line (the #218
/// fix wrapped the QUEUE stub but missed the cron stub).
const CRON_LONGNAME_STUB_FIXPOINT: &str =
    include_str!("../../../conformance/designs/cron-longname-stub-fixpoint.design.json");

fn repo_root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .ancestors()
        .nth(2)
        .unwrap()
        .to_path_buf()
}

/// Scaffold the golden app wired to the LOCAL framework (path dep).
fn scaffold_golden(tmp: &Path) -> PathBuf {
    let design = tmp.join("design.json");
    std::fs::write(&design, GOLDEN).unwrap();
    let app = tmp.join("todo-api");
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .env("JERRYCAN_FRAMEWORK_DEP", &dep)
        .arg("new")
        .arg(&app)
        .arg("--design")
        .arg(&design)
        .status()
        .unwrap();
    assert!(st.success());
    app
}

/// Scaffold the golden app in DB+validate mode against the LOCAL framework.
fn scaffold_golden_db(tmp: &Path) -> PathBuf {
    let mut design: serde_json::Value = serde_json::from_str(GOLDEN).unwrap();
    design["dependencies"] = serde_json::json!(["db", "validate"]);
    let design_path = tmp.join("design.json");
    std::fs::write(&design_path, serde_json::to_string_pretty(&design).unwrap()).unwrap();
    let app = tmp.join("todo-api");
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .env("JERRYCAN_FRAMEWORK_DEP", &dep)
        .arg("new")
        .arg(&app)
        .arg("--design")
        .arg(&design_path)
        .status()
        .unwrap();
    assert!(st.success());
    app
}

/// Reset the target Postgres to a clean slate before a DB-backed heavy test
/// migrates into it. The heavy suite runs `--test-threads=1`, so there is never a
/// concurrent user of this database; dropping and recreating `public` BEFORE the
/// run (no teardown to race, unlike DROP DATABASE) fully isolates each
/// Postgres-backed test from whatever ran before. Requires `psql` — `heavy.yml`
/// installs `postgresql-client`.
fn reset_pg_public_schema(pg_url: &str) {
    let st = Command::new("psql")
        .arg(pg_url)
        .args(["-v", "ON_ERROR_STOP=1"])
        .args([
            "-c",
            "DROP SCHEMA IF EXISTS public CASCADE; CREATE SCHEMA public;",
        ])
        .status()
        .unwrap_or_else(|e| {
            panic!(
                "psql is required to reset the Postgres schema for the DB-backed \
                 heavy test (install postgresql-client): {e}"
            )
        });
    assert!(
        st.success(),
        "failed to reset public schema on the test database"
    );
}

/// Recursively collect every `.rs` file under `dir`.
fn collect_rs(dir: &Path, out: &mut Vec<PathBuf>) {
    for entry in std::fs::read_dir(dir).unwrap() {
        let path = entry.unwrap().path();
        if path.is_dir() {
            collect_rs(&path, out);
        } else if path.extension().is_some_and(|e| e == "rs") {
            out.push(path);
        }
    }
}

/// Issue #218 (make-impossible guard): a fresh jobs+realtime scaffold
/// (reference-slice) must be a `rustfmt` fixpoint — EVERY generated `.rs`
/// (tool-owned AND agent-owned stubs) formats to itself, so `jerrycan new` never
/// emits code `cargo fmt` would rewrite. The emitters produce
/// byte-identical-to-rustfmt output by construction (#128/#165/#201/#218); this
/// locks it so a future emitter that drifts turns RED. FAST (scaffold + `rustfmt
/// --check` per file — no cargo build), so it runs in the per-PR gate and is NOT
/// `#[ignore]`d. It needs only `rustfmt`, which CI already has.
#[test]
fn scaffold_is_a_rustfmt_fixpoint() {
    // reference-slice: jobs+realtime, but its two jobs are CRON. Locks the cron
    // registry closure + the whole tenant/realtime SeaORM surface.
    assert_scaffold_is_fixpoint(REFERENCE, "reference-slice");
    // queue-jobs-fixpoint: db-backed QUEUE jobs with realistic, non-alphabetical names
    // spanning every wrap regime of the queue emitters (payload bind + acceptance call)
    // AND the `pub mod` reorder. reference-slice never reaches these (cron-only), so
    // this second design is what actually guards the #218 queue-job fixes. Its two
    // multi-field route modules keep the migration/db arrays multi-line, clear of the
    // single-element collapses tracked separately.
    assert_scaffold_is_fixpoint(QUEUE_JOBS_FIXPOINT, "queue-jobs-fixpoint");

    // Issue #221 residuals D/E/F — SHAPES the #218 designs never scaffolded, each kept
    // distinct so a regression in one cannot be masked by another (a D design with
    // multi-field entities; an E design with ≥ 2 route modules; F designs with
    // multi-field entities and ≥ 2 modules). Each was RED before its emitter fix
    // (verified by reverting the hunk and re-scaffolding).
    // D: ONE route module ⇒ single-element jobs/route migration array (rustfmt HUGS it).
    assert_scaffold_is_fixpoint(SINGLE_MODULE_JOBS_FIXPOINT, "single-module-jobs-fixpoint");
    // E: ID-ONLY entity ⇒ single-field `ActiveModel { id: Set(…) }` (rustfmt collapses it).
    assert_scaffold_is_fixpoint(ID_ONLY_ENTITY_FIXPOINT, "id-only-entity-fixpoint");
    // F (registry): CRON names ≤ 36 across every regime of the non-monotonic `Box::pin`
    // closure-body wrap + the `.cron(…)` fn_call_width break.
    assert_scaffold_is_fixpoint(CRON_NAME_WRAP_FIXPOINT, "cron-name-wrap-fixpoint");
    // F (task stub): a CRON name ≥ 39 whose task-module stub signature wraps.
    assert_scaffold_is_fixpoint(CRON_LONGNAME_STUB_FIXPOINT, "cron-longname-stub-fixpoint");
}

/// Scaffold `design_json` (wired to the LOCAL framework) into a fresh temp app named
/// `app_name`, then assert EVERY generated `.rs` is a `rustfmt` fixpoint — `rustfmt
/// --check` reports no rewrite. FAST (no cargo build), so it stays in the per-PR gate.
fn assert_scaffold_is_fixpoint(design_json: &str, app_name: &str) {
    let tmp = tempfile::tempdir().unwrap();
    let design = tmp.path().join("design.json");
    std::fs::write(&design, design_json).unwrap();
    let app = tmp.path().join(app_name);
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .env("JERRYCAN_FRAMEWORK_DEP", &dep)
        .arg("new")
        .arg(&app)
        .arg("--design")
        .arg(&design)
        .status()
        .unwrap();
    assert!(st.success(), "jerrycan new must scaffold {app_name}");

    let mut files = Vec::new();
    collect_rs(&app, &mut files);
    files.sort();
    assert!(
        !files.is_empty(),
        "the {app_name} scaffold must contain .rs files"
    );

    let mut drift = Vec::new();
    for f in &files {
        let out = Command::new("rustfmt")
            .args(["--edition", "2024", "--check"])
            .arg(f)
            .output()
            .unwrap();
        if !out.status.success() {
            drift.push(format!(
                "--- {} ---\n{}{}",
                f.strip_prefix(&app).unwrap().display(),
                String::from_utf8_lossy(&out.stdout),
                String::from_utf8_lossy(&out.stderr),
            ));
        }
    }
    assert!(
        drift.is_empty(),
        "every generated .rs must be a rustfmt fixpoint (issue #218); {app_name}: {} file(s) drifted:\n{}",
        drift.len(),
        drift.join("\n")
    );
}

#[test]
#[ignore = "heavy: db-mode golden app must build and pass the full gate"]
fn db_mode_scaffold_passes_jerrycan_check() {
    let tmp = tempfile::tempdir().unwrap();
    let app = scaffold_golden_db(tmp.path());
    common::isolate_app_bin(&app);
    // The documented workflow, in order: gen-tests → implement → check. Since
    // #123a a never-gen-tested scaffold is refused with JC0551, and the gate's
    // tests step then runs the generated acceptance suite — so the db fixtures
    // must be in place for the full gate to be green.
    for module in ["todos", "users"] {
        let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
            .current_dir(&app)
            .env("CARGO_TARGET_DIR", common::shared_app_target())
            .args(["gen-tests", "--module", module])
            .status()
            .unwrap();
        assert!(st.success(), "gen-tests {module} must succeed");
    }
    for (fixture, target) in [
        (
            "db/todos_handlers.rs",
            "crates/routes/todos/src/handlers.rs",
        ),
        (
            "db/comments_handlers.rs",
            "crates/routes/todos/src/subroutes/comments/handlers.rs",
        ),
        (
            "db/users_handlers.rs",
            "crates/routes/users/src/handlers.rs",
        ),
    ] {
        std::fs::copy(
            repo_root().join("conformance/fixtures").join(fixture),
            app.join(target),
        )
        .unwrap();
    }
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "check"])
        .output()
        .unwrap();
    let payload: serde_json::Value = serde_json::from_slice(&out.stdout).expect("one JSON doc");
    assert_eq!(
        payload["ok"], true,
        "diagnostics: {}",
        payload["diagnostics"]
    );
    assert!(out.status.success());
}

/// Scaffold the golden app in DB+validate mode PLUS a `rate_limit` block, against
/// the LOCAL framework (path dep). The block adds only app-level middleware wiring,
/// so the existing db handler fixtures still drive a green check.
fn scaffold_golden_db_rate_limited(tmp: &Path) -> PathBuf {
    let mut design: serde_json::Value = serde_json::from_str(GOLDEN).unwrap();
    design["dependencies"] = serde_json::json!(["db", "validate"]);
    design["rate_limit"] = serde_json::json!({ "limit": 100, "window": "1m" });
    let design_path = tmp.join("design.json");
    std::fs::write(&design_path, serde_json::to_string_pretty(&design).unwrap()).unwrap();
    let app = tmp.join("todo-api");
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .env("JERRYCAN_FRAMEWORK_DEP", &dep)
        .arg("new")
        .arg(&app)
        .arg("--design")
        .arg(&design_path)
        .status()
        .unwrap();
    assert!(st.success());
    app
}

/// The #83 acceptance: a design carrying `rate_limit: { limit: 100, window: "1m" }`
/// scaffolds a `main.rs` that WIRES the limiter (`.extend(RateLimit::per_window(
/// 100, Duration::from_secs(60)))`) with the `rate-limit` facade feature on, passes
/// the full `jerrycan check` gate, and — the whole point of #83 — does so WITHOUT
/// tripping JL0003. Rate limiting used to be reachable only by hand-editing the
/// tool-owned main.rs, which permanently drifted it from the generator (JL0003).
/// Now the wiring is GENERATED from the design, so main.rs equals the generator's
/// output byte-for-byte and stays a `cargo fmt` fixpoint (no drift, ever).
#[test]
#[ignore = "heavy: rate-limited db golden app must build, fmt-clean, and pass the gate w/o JL0003"]
fn rate_limited_db_scaffold_checks_green_without_tripping_jl0003() {
    let tmp = tempfile::tempdir().unwrap();
    let app = scaffold_golden_db_rate_limited(tmp.path());
    common::isolate_app_bin(&app);

    // The generated main.rs wires the limiter (no-builder regime: rustfmt breaks
    // per_window's two args). Asserting the exact bytes proves what `check`'s
    // JL0003 lint compares main.rs against.
    let main = std::fs::read_to_string(app.join("crates/app/src/main.rs")).unwrap();
    assert!(
        main.contains(
            "        .extend(jerrycan::ratelimit::RateLimit::per_window(\n            100,\n            std::time::Duration::from_secs(60),\n        ))\n"
        ),
        "main.rs must wire the generated rate limiter:\n{main}"
    );
    // The `rate-limit` facade feature is enabled on the workspace jerrycan dep, so
    // `jerrycan::ratelimit::RateLimit` resolves.
    let ws_cargo = std::fs::read_to_string(app.join("Cargo.toml")).unwrap();
    assert!(
        ws_cargo.contains("\"rate-limit\""),
        "the rate-limit facade feature must be enabled:\n{ws_cargo}"
    );

    // The TOOL-OWNED main.rs must be a `rustfmt` fixpoint: running fmt must not
    // rewrite the generated `.extend(RateLimit..)` line — a rewrite is exactly what
    // would drift main.rs from the generator and trip JL0003 on the NEXT check.
    // (Only the tool-owned files are held to this; agent-owned stubs are theirs to
    // format, and JL0003 never inspects them.)
    let fmt = Command::new("rustfmt")
        .args(["--edition", "2024", "--check"])
        .arg(app.join("crates/app/src/main.rs"))
        .output()
        .unwrap();
    assert!(
        fmt.status.success(),
        "the generated main.rs must be a rustfmt fixpoint (no drift → no JL0003):\n{}\n{}",
        String::from_utf8_lossy(&fmt.stdout),
        String::from_utf8_lossy(&fmt.stderr)
    );

    // The documented workflow: gen-tests → implement → check (#123a refuses a
    // never-gen-tested module with JC0551). Reuse the golden db handler fixtures.
    for module in ["todos", "users"] {
        let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
            .current_dir(&app)
            .env("CARGO_TARGET_DIR", common::shared_app_target())
            .args(["gen-tests", "--module", module])
            .status()
            .unwrap();
        assert!(st.success(), "gen-tests {module} must succeed");
    }
    for (fixture, target) in [
        (
            "db/todos_handlers.rs",
            "crates/routes/todos/src/handlers.rs",
        ),
        (
            "db/comments_handlers.rs",
            "crates/routes/todos/src/subroutes/comments/handlers.rs",
        ),
        (
            "db/users_handlers.rs",
            "crates/routes/users/src/handlers.rs",
        ),
    ] {
        std::fs::copy(
            repo_root().join("conformance/fixtures").join(fixture),
            app.join(target),
        )
        .unwrap();
    }

    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "check"])
        .output()
        .unwrap();
    let payload: serde_json::Value = serde_json::from_slice(&out.stdout).expect("one JSON doc");
    assert_eq!(
        payload["ok"], true,
        "the rate-limited app must pass the full gate; diagnostics: {}",
        payload["diagnostics"]
    );
    // The crux of #83: the generated wiring must NOT trip JL0003 (generated-file
    // drift). Assert it explicitly — a green `ok` alone could mask a lint that was
    // never evaluated.
    assert!(
        !payload["diagnostics"].to_string().contains("JL0003"),
        "generated rate-limit wiring must not trip JL0003: {}",
        payload["diagnostics"]
    );
    assert!(out.status.success());
}

#[test]
#[ignore = "heavy: full cargo build of a generated workspace"]
fn scaffolded_app_builds_with_zero_warnings() {
    let tmp = tempfile::tempdir().unwrap();
    let app = scaffold_golden(tmp.path());
    common::isolate_app_bin(&app);
    let out = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .env("RUSTFLAGS", "-D warnings")
        .args(["build", "--workspace"])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "generated app must build warning-free:\n{}",
        String::from_utf8_lossy(&out.stderr)
    );
}

/// Issue #116 — the compile proof. A transitively-owned grandchild (`Card`
/// belongs_to `Board` belongs_to the tenant `Org`) whose flat write lives in an
/// entity-hosting SUBROUTE (`/cards`, no tenant fk in the path → MembershipSet)
/// has its generated stub STEERED to `CardRepo::create_for_memberships(...)`.
/// Before the emission-gate fix, `entity_is_flat_tenant_owned` only scanned the
/// declaring top-level module's own endpoints — never a subroute — so it returned
/// false, the repo OMITTED the `*_for_memberships` methods, and a handler that
/// FOLLOWED its own steer failed to compile (`method not found`) behind a green
/// `check`. This scaffolds the shape, implements the create by following the steer
/// verbatim, and requires the workspace to build warning-free: the acceptance
/// criterion for #116 IS that the framework's own guidance compiles.
#[test]
#[ignore = "heavy: scaffolds the #116 grandchild-in-subroute shape and builds it"]
fn flat_grandchild_steer_following_handler_compiles() {
    const REPRO_116: &str = r#"{
        "name": "boards-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": "list_orgs", "method": "GET", "path": "/",
                  "auth_required": true,
                  "success": { "status": 200, "entity": "Org", "list": true } }] },
            { "name": "boards",
              "entities": [{ "name": "Board",
                  "belongs_to": [{ "entity": "Org" }],
                  "fields": [{ "name": "id", "type": "integer" },
                             { "name": "name", "type": "string" }] }],
              "endpoints": [{ "operation_id": "list_boards", "method": "GET", "path": "/",
                  "auth_required": true,
                  "success": { "status": 200, "entity": "Board", "list": true } }],
              "subroutes": [{
                  "name": "cards", "mount": "/cards",
                  "entities": [{ "name": "Card",
                      "belongs_to": [{ "entity": "Board" }],
                      "fields": [{ "name": "id", "type": "integer" },
                                 { "name": "title", "type": "string" }] }],
                  "endpoints": [{ "operation_id": "create_card", "method": "POST", "path": "/",
                      "auth_required": true,
                      "request_body": { "entity": "Card" },
                      "success": { "status": 201, "entity": "Card" } }]
              }] }
        ]
    }"#;

    let tmp = tempfile::tempdir().unwrap();
    let design = tmp.path().join("design.json");
    std::fs::write(&design, REPRO_116).unwrap();
    let app = tmp.path().join("boards-api");
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .env("JERRYCAN_FRAMEWORK_DEP", &dep)
        .arg("new")
        .arg(&app)
        .arg("--design")
        .arg(&design)
        .status()
        .unwrap();
    assert!(st.success(), "jerrycan new must scaffold the #116 shape");
    common::isolate_app_bin(&app);

    // The grandchild's flat write lives in the `cards` subroute of `boards`.
    let handlers_path = app.join("crates/routes/boards/src/subroutes/cards/handlers.rs");
    let handlers = std::fs::read_to_string(&handlers_path).unwrap();
    // The steer names the membership-checked create (fires regardless of the gate).
    assert!(
        handlers.contains("CardRepo::create_for_memberships(_user.0.id, card)"),
        "the subroute stub must steer to create_for_memberships:\n{handlers}"
    );
    // The gate must now EMIT that method, or following the steer is method-not-found.
    let repo =
        std::fs::read_to_string(app.join("crates/routes/boards/src/subroutes/cards/repo.rs"))
            .unwrap();
    assert!(
        repo.contains("pub async fn create_for_memberships("),
        "the emission gate must emit create_for_memberships for the grandchild-in-subroute (#116):\n{repo}"
    );

    // Follow the steer verbatim: call the membership-checked create. Keep the stub's
    // Err return (the create returns the new id; the point is that it type-checks). The
    // stub body wraps (op_len 11 ⇒ inner call past rustfmt's fn_call_width, issue #165).
    let stub = "    Err(Error::internal(\n        \"create_card not implemented — replace this stub\",\n    ))";
    assert!(handlers.contains(stub), "unexpected stub body:\n{handlers}");
    let implemented = handlers.replace(
        stub,
        "    let _id = _repo.create_for_memberships(_user.0.id, _body).await?;\n    Err(Error::internal(\"create_card membership-checked create wired\"))",
    );
    std::fs::write(&handlers_path, &implemented).unwrap();

    // The proof: the workspace builds warning-free with a steer-following handler.
    let out = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .env("RUSTFLAGS", "-D warnings")
        .args(["build", "--workspace"])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "a handler following its own #116 steer must compile (was method-not-found):\n{}",
        String::from_utf8_lossy(&out.stderr)
    );
}

/// #123a: the full pipeline on a freshly-scaffolded, NEVER-gen-tested app must
/// not read green — the pre-fix `check` folded a zero-test `cargo test` (exit
/// 0) into ok:true, so a scaffold nobody ever tested shipped a green verdict.
/// The pipeline is fail-fast per class, so JC0551 being the failing class is
/// itself the proof that build/clippy/audit/deny/tests are all green on a
/// fresh scaffold; the verdict then flips on the acceptance step, naming each
/// endpoint-bearing module and the exact gen-tests command that fixes it.
#[test]
#[ignore = "heavy: full verification pipeline incl. cargo-audit/cargo-deny"]
fn fresh_scaffold_check_refuses_hollow_green_with_jc0551() {
    let tmp = tempfile::tempdir().unwrap();
    let app = scaffold_golden(tmp.path());
    common::isolate_app_bin(&app);
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "check"])
        .output()
        .unwrap();
    let payload: serde_json::Value =
        serde_json::from_slice(&out.stdout).expect("check --json emits one JSON document");
    assert_eq!(
        payload["ok"], false,
        "a never-gen-tested scaffold must NOT read green: {payload}"
    );
    let diags = payload["diagnostics"].as_array().unwrap();
    assert!(
        !diags.is_empty() && diags.iter().all(|d| d["code"] == "JC0551"),
        "every diagnostic is JC0551 — the acceptance step is the failing class, \
         proving each earlier class (build/clippy/audit/deny/tests) was green: {diags:?}"
    );
    for m in ["todos", "users"] {
        assert!(
            diags.iter().any(|d| {
                let msg = d["message"].as_str().unwrap();
                msg.contains(&format!("module `{m}`"))
                    && msg.contains(&format!("jerrycan gen-tests --module {m}"))
            }),
            "JC0551 names `{m}` and its gen-tests command: {diags:?}"
        );
    }
    assert!(
        !out.status.success(),
        "a red check verdict must exit non-zero"
    );
}

/// Scaffold the golden app in auth+observe mode (in-memory repos) against the
/// LOCAL framework with auth+observe features.
#[cfg(feature = "auth")]
fn scaffold_golden_auth(tmp: &Path) -> PathBuf {
    let mut design: serde_json::Value = serde_json::from_str(GOLDEN).unwrap();
    design["dependencies"] = serde_json::json!(["auth", "observe"]);
    design["auth"] = serde_json::json!({ "model": "session", "roles": ["admin"] });
    for ep in design["modules"][0]["endpoints"].as_array_mut().unwrap() {
        if ep["operation_id"] == "create_todo" {
            ep["auth_required"] = serde_json::json!(true);
        }
        if ep["operation_id"] == "delete_todo" {
            ep["required_roles"] = serde_json::json!(["admin"]);
        }
    }
    // The comments subroute's create is mutating too: JL0004 demands every
    // mutating route in an auth design be guarded, so mark it auth_required.
    for ep in design["modules"][0]["subroutes"][0]["endpoints"]
        .as_array_mut()
        .unwrap()
    {
        if ep["operation_id"] == "create_comment" {
            ep["auth_required"] = serde_json::json!(true);
        }
    }
    for ep in design["modules"][1]["endpoints"].as_array_mut().unwrap() {
        if ep["operation_id"] == "create_user" {
            ep["auth_required"] = serde_json::json!(true);
        }
    }
    let design_path = tmp.join("design.json");
    std::fs::write(&design_path, serde_json::to_string_pretty(&design).unwrap()).unwrap();
    let app = tmp.join("todo-api");
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .env("JERRYCAN_FRAMEWORK_DEP", &dep)
        .arg("new")
        .arg(&app)
        .arg("--design")
        .arg(&design_path)
        .status()
        .unwrap();
    assert!(st.success());
    app
}

/// Spec §4 Phase 3: an agent builds an AUTH-guarded, OBSERVED API. The generated
/// app must build, pass the full gate (JL0004 satisfied — every mutation guarded),
/// reject credential-less mutations with 401, accept admin-cookied ones, and
/// expose observe's /healthz and /metrics.
#[cfg(feature = "auth")]
#[test]
#[ignore = "heavy: auth+observe golden app builds, checks, and serves guarded routes"]
fn auth_observe_app_builds_checks_and_guards() {
    let tmp = tempfile::tempdir().unwrap();
    let app = scaffold_golden_auth(tmp.path());
    common::isolate_app_bin(&app);
    for (fixture, target) in [
        (
            "auth/todos_handlers.rs",
            "crates/routes/todos/src/handlers.rs",
        ),
        (
            "auth/comments_handlers.rs",
            "crates/routes/todos/src/subroutes/comments/handlers.rs",
        ),
        (
            "auth/users_handlers.rs",
            "crates/routes/users/src/handlers.rs",
        ),
    ] {
        std::fs::copy(
            repo_root().join("conformance/fixtures").join(fixture),
            app.join(target),
        )
        .unwrap();
    }

    // #123a: gen-tests before check — the honest gate refuses a never-gen-tested
    // module with JC0551, and the acceptance suite it now runs (incl. the 401
    // guard probes) must be green on the implemented auth handlers.
    for module in ["todos", "users"] {
        let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
            .current_dir(&app)
            .env("CARGO_TARGET_DIR", common::shared_app_target())
            .args(["gen-tests", "--module", module])
            .status()
            .unwrap();
        assert!(st.success(), "gen-tests {module} must succeed");
    }

    // Full gate green (JL0004 must be satisfied — guarded mutations).
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "check"])
        .output()
        .unwrap();
    let payload: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(
        payload["ok"], true,
        "diagnostics: {}",
        payload["diagnostics"]
    );

    // Serve and exercise guard behavior over real HTTP.
    let port = {
        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        l.local_addr().unwrap().port()
    };
    let addr = format!("127.0.0.1:{port}");
    let mut server = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .env("JERRYCAN_ADDR", &addr)
        .env("JERRYCAN_SECRET", "a-very-long-development-secret-string!!")
        .args(["run", "-p", "app"])
        .spawn()
        .unwrap();
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(180);
    while std::time::Instant::now() < deadline {
        if std::net::TcpStream::connect(&addr).is_ok() {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(400));
    }
    let http = |req: String| -> String {
        let mut s = std::net::TcpStream::connect(&addr).unwrap();
        s.write_all(req.as_bytes()).unwrap();
        let mut buf = Vec::new();
        s.read_to_end(&mut buf).unwrap();
        String::from_utf8_lossy(&buf).into_owned()
    };

    // Public list works without auth.
    assert!(
        http("GET /todos/ HTTP/1.1\r\nHost: l\r\nConnection: close\r\n\r\n".into())
            .starts_with("HTTP/1.1 200")
    );
    // Guarded create without a cookie → 401.
    let body = r#"{"title":"x","done":false}"#;
    let create = |cookie: &str| {
        format!(
            "POST /todos/ HTTP/1.1\r\nHost: l\r\nContent-Type: application/json\r\nContent-Length: {}\r\n{}Connection: close\r\n\r\n{body}",
            body.len(),
            cookie
        )
    };
    assert!(
        http(create("")).starts_with("HTTP/1.1 401"),
        "no cookie → 401"
    );
    // Mint an admin cookie with the same secret and create successfully. The app
    // has no /login route, so build the session cookie via jerrycan-auth in-test.
    let cookie = {
        let auth = jerrycan::auth::Auth::with_secret("a-very-long-development-secret-string!!");
        let token = auth
            .sessions()
            // SessionUser.id is a String (the stringified user pk), so the
            // minted cookie must use a string id or the app's session decode
            // rejects it as a 401.
            .encode(&serde_json::json!({ "id": "1", "role": "admin" }))
            .unwrap();
        format!("Cookie: jerrycan_session={token}\r\n")
    };
    assert!(
        http(create(&cookie)).starts_with("HTTP/1.1 201"),
        "admin cookie → 201"
    );
    // Observe endpoints live.
    assert_eq!(
        http("GET /healthz HTTP/1.1\r\nHost: l\r\nConnection: close\r\n\r\n".into())
            .lines()
            .next()
            .unwrap(),
        "HTTP/1.1 200 OK"
    );
    assert!(
        http("GET /metrics HTTP/1.1\r\nHost: l\r\nConnection: close\r\n\r\n".into())
            .contains("jerrycan_requests_total")
    );

    let _ = server.kill();
    let _ = server.wait();
}

/// THE Phase 1 exit criterion: an agent builds a working multi-module CRUD
/// service via MCP only (design → scaffold → implement → check → serve).
#[test]
#[ignore = "heavy: MCP loop + cargo build + live HTTP round-trips"]
fn agent_generates_working_crud_service_via_mcp_only() {
    let tmp = tempfile::tempdir().unwrap();
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let shared_target = common::shared_app_target();
    let mut c = common::McpClient::start_in_with_env(
        tmp.path(),
        &[
            ("JERRYCAN_FRAMEWORK_DEP", &dep),
            ("CARGO_TARGET_DIR", shared_target.to_str().unwrap()),
        ],
    );

    // 1. design: draft in, validated design.json out.
    let draft: serde_json::Value = serde_json::from_str(GOLDEN).unwrap();
    let (err, payload) = c.call_tool(
        "jerrycan_design",
        serde_json::json!({"requirements": "multi-module todo backend", "draft": draft}),
    );
    assert!(!err, "{payload}");
    assert_eq!(payload["status"], "complete");
    let design_path = payload["design_path"].as_str().unwrap().to_string();

    // 2. scaffold.
    let app = tmp.path().join("todo-api");
    let (err, payload) = c.call_tool(
        "jerrycan_scaffold",
        serde_json::json!({"design_path": design_path, "directory": app.to_str().unwrap()}),
    );
    assert!(!err, "{payload}");

    // 3. gen-tests via MCP (#123a: the check tool refuses a never-gen-tested
    // module with JC0551, so the agent loop runs gen-tests before check —
    // exactly the workflow the scaffold's next_step orders).
    for module in ["todos", "users"] {
        let (err, payload) = c.call_tool(
            "jerrycan_gen_tests",
            serde_json::json!({"directory": app.to_str().unwrap(), "module": module}),
        );
        assert!(!err, "{payload}");
    }

    // 4. the "agent" implements the handlers (canned fixtures).
    for (fixture, target) in [
        ("todos_handlers.rs", "crates/routes/todos/src/handlers.rs"),
        (
            "comments_handlers.rs",
            "crates/routes/todos/src/subroutes/comments/handlers.rs",
        ),
        ("users_handlers.rs", "crates/routes/users/src/handlers.rs"),
    ] {
        std::fs::copy(
            repo_root().join("conformance/fixtures").join(fixture),
            app.join(target),
        )
        .unwrap();
    }

    // 5. verify: the full gate must be green (incl. the generated acceptance
    // suite, which the canned implementations satisfy).
    let (err, payload) = c.call_tool(
        "jerrycan_check",
        serde_json::json!({"directory": app.to_str().unwrap()}),
    );
    assert!(!err, "{payload}");
    assert_eq!(
        payload["ok"], true,
        "diagnostics: {}",
        payload["diagnostics"]
    );
    c.shutdown();

    // 6. serve and exercise the CRUD loop over real HTTP.
    let port = {
        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        l.local_addr().unwrap().port()
    };
    let addr = format!("127.0.0.1:{port}");
    let mut server = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .env("JERRYCAN_ADDR", &addr)
        .args(["run", "-p", "app"])
        .spawn()
        .unwrap();

    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
    let mut connected = None;
    while std::time::Instant::now() < deadline {
        if let Ok(s) = std::net::TcpStream::connect(&addr) {
            connected = Some(s);
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(300));
    }
    let http = |req: String| -> String {
        let mut s = std::net::TcpStream::connect(&addr).unwrap();
        s.write_all(req.as_bytes()).unwrap();
        let mut buf = Vec::new();
        s.read_to_end(&mut buf).unwrap();
        String::from_utf8_lossy(&buf).into_owned()
    };
    drop(connected.expect("generated app started serving within 120s"));

    let res = http("GET /todos/ HTTP/1.1\r\nHost: l\r\nConnection: close\r\n\r\n".into());
    assert!(res.starts_with("HTTP/1.1 200"), "{res}");
    assert!(res.ends_with("[]"), "empty store first: {res}");

    let body = r#"{"title":"ship phase 1"}"#;
    let res = http(format!(
        "POST /todos/ HTTP/1.1\r\nHost: l\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
        body.len()
    ));
    assert!(res.starts_with("HTTP/1.1 201"), "{res}");

    let res = http("GET /todos/1 HTTP/1.1\r\nHost: l\r\nConnection: close\r\n\r\n".into());
    assert!(
        res.starts_with("HTTP/1.1 200") && res.contains("ship phase 1"),
        "{res}"
    );

    let res = http("GET /users/ HTTP/1.1\r\nHost: l\r\nConnection: close\r\n\r\n".into());
    assert!(res.starts_with("HTTP/1.1 200"), "multi-module proof: {res}");

    let res = http("DELETE /todos/1 HTTP/1.1\r\nHost: l\r\nConnection: close\r\n\r\n".into());
    assert!(res.starts_with("HTTP/1.1 204"), "{res}");

    let res = http("GET /todos/1 HTTP/1.1\r\nHost: l\r\nConnection: close\r\n\r\n".into());
    assert!(res.starts_with("HTTP/1.1 404"), "{res}");

    let _ = server.kill();
    let _ = server.wait();
}

/// The J3 face-off failure (issue #51): ONE module with a root entity (Project at
/// `/`) AND a second entity (Task) that has its own creator (`POST /tasks`) and
/// its own `/{id}` routes. The generated `update_task`/`delete_task` probes must
/// seed a TASK (via `POST /tasks`) — not reuse the module-root Project creator —
/// so they are GREEN on a CORRECT handler. Before the fix they seeded a Project
/// and hit `/tasks/1`, a guaranteed 404 on correct code.
const J3_TWO_ENTITY: &str = r#"{
  "name": "j3",
  "contract_version": 1,
  "auth": { "model": "none" },
  "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" }] }
    ]
  }]
}"#;

/// The correct `projects` handlers: `update_task`/`delete_task` operate on the
/// TASK repo. They only pass if the generated probe seeded a real Task row.
const J3_HANDLERS: &str = r#"//! Correct J3 handlers.
use jerrycan::prelude::*;
use super::model::*;
use super::repo::*;

pub(crate) async fn list_projects(repo: Dep<ProjectRepo>) -> Result<Json<Vec<Project>>> {
    Ok(Json(repo.all().await?))
}
pub(crate) async fn create_project(repo: Dep<ProjectRepo>, Json(body): Json<Project>) -> Result<Created<Project>> {
    repo.insert(body.clone()).await?;
    Ok(Created(body))
}
pub(crate) async fn list_tasks(repo: Dep<TaskRepo>) -> Result<Json<Vec<Task>>> {
    Ok(Json(repo.all().await?))
}
pub(crate) async fn create_task(repo: Dep<TaskRepo>, Json(body): Json<Task>) -> Result<Created<Task>> {
    repo.insert(body.clone()).await?;
    Ok(Created(body))
}
pub(crate) async fn update_task(repo: Dep<TaskRepo>, Path(id): Path<i64>, Json(body): Json<Task>) -> Result<Json<Task>> {
    if repo.update(id, body.clone()).await? { Ok(Json(body)) } else { Err(Error::not_found()) }
}
pub(crate) async fn delete_task(repo: Dep<TaskRepo>, Path(id): Path<i64>) -> Result<NoContent> {
    if repo.remove(id).await? { Ok(NoContent) } else { Err(Error::not_found()) }
}
"#;

/// Issue #51 end-to-end: a two-entity module's `/{id}` probes seed the RIGHT
/// entity and go GREEN on a correct scaffold. Scaffold → gen-tests (RED on stubs)
/// → implement the correct handlers → the SAME probes pass. Mirrors
/// `tdd_loop_goes_red_then_green_on_sqlite` for the J3 shape.
#[test]
#[ignore = "heavy: scaffold + gen-tests + red run + implement + green run (J3 seeding)"]
fn second_entity_id_probes_go_green_on_a_correct_scaffold() {
    let tmp = tempfile::tempdir().unwrap();
    let design = tmp.path().join("design.json");
    std::fs::write(&design, J3_TWO_ENTITY).unwrap();
    let app = tmp.path().join("j3");
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .env("JERRYCAN_FRAMEWORK_DEP", &dep)
        .args(["new"])
        .arg(&app)
        .arg("--design")
        .arg(&design)
        .status()
        .unwrap();
    assert!(st.success(), "J3 must scaffold");
    common::isolate_app_bin(&app);

    // gen-tests: the two /{id} probes seed a Task via its OWN creator.
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "gen-tests", "--module", "projects"])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let acceptance = app.join("crates/routes/projects/tests/acceptance.rs");
    let generated = std::fs::read_to_string(&acceptance).unwrap();
    // The Task probes seed the /tasks collection, not the root Project creator.
    for probe in ["update_task_returns_200", "delete_task_returns_204"] {
        let body = &generated[generated.find(probe).expect(probe)..];
        assert!(
            body[..body.find("assert_eq!").unwrap()].contains("post_json(\"/projects/tasks\""),
            "{probe} must seed a Task via POST /projects/tasks:\n{generated}"
        );
    }

    // RED: stubs (500) fail the suite.
    let red = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["test", "--workspace", "--no-fail-fast"])
        .output()
        .unwrap();
    assert!(!red.status.success(), "stub handlers must fail the suite");

    // Implement the correct handlers.
    let dest = app.join("crates/routes/projects/src/handlers.rs");
    std::fs::write(&dest, J3_HANDLERS).unwrap();
    let future = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
    std::fs::File::options()
        .write(true)
        .open(&dest)
        .unwrap()
        .set_modified(future)
        .unwrap();

    // GREEN: the same probes pass — proving the update/delete probes addressed a
    // seeded Task row, not a phantom id.
    let green = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["test", "--workspace"])
        .status()
        .unwrap();
    assert!(
        green.success(),
        "the second-entity /{{id}} probes must go green on a correct handler"
    );
}

/// The public-read/owner-write conformance fixture (#105): Post is per-user
/// identity-owned with `public_read: true`; `list_posts` is DECLARED
/// `auth_required` (the entity flag must override it — correct-by-construction).
/// User lives in its OWN module so the identity fk is cross-module (no DB FK —
/// the isolation test's session users need no seeded rows).
const FEED_PUBLIC_READ: &str = r#"{
  "name": "feed-api",
  "contract_version": 1,
  "auth": { "model": "session", "roles": ["user"] },
  "dependencies": ["db", "auth"],
  "modules": [
    {
      "name": "users",
      "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" } }
      ]
    },
    {
      "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" },
          "errors": [{ "status": 404, "when": "unknown id" }] },
        { "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" },
          "errors": [{ "status": 404, "when": "unknown id or not the owner" }] },
        { "operation_id": "delete_post", "method": "DELETE", "path": "/{id}",
          "auth_required": true,
          "success": { "status": 204 },
          "errors": [{ "status": 404, "when": "unknown id or not the owner" }] }
      ]
    }
  ]
}"#;

/// The correct public-read/owner-write posts handlers (#105): PUBLIC reads via
/// the unscoped `all()`/`get()` (no session), owner-scoped writes via the
/// server-injected session user id + `update_for`/`remove_for`.
const FEED_POSTS_HANDLERS: &str = r#"//! Correct #105 posts handlers: public reads, owner-scoped writes.
use super::model::*;
use super::repo::*;
use jerrycan::prelude::*;
use shared::CurrentUser;

pub(crate) async fn list_posts(repo: Dep<PostRepo>) -> Result<Json<Vec<Post>>> {
    Ok(Json(repo.all().await?))
}

pub(crate) async fn get_post(repo: Dep<PostRepo>, Path(id): Path<i64>) -> Result<Json<Post>> {
    repo.get(id).await?.map(Json).ok_or_else(Error::not_found)
}

pub(crate) async fn create_post(repo: Dep<PostRepo>, user: CurrentUser, Json(body): Json<PostRequest>) -> Result<Created<Post>> {
    let user_id: i64 = user.0.id.parse().map_err(|_| Error::unauthorized())?;
    let mut post = Post { id: 0, user_id, title: body.title };
    post.id = repo.insert(post.clone()).await?;
    Ok(Created(post))
}

pub(crate) async fn update_post(repo: Dep<PostRepo>, user: CurrentUser, Path(id): Path<i64>, Json(body): Json<PostRequest>) -> Result<Json<Post>> {
    let user_id: i64 = user.0.id.parse().map_err(|_| Error::unauthorized())?;
    let post = Post { id, user_id, title: body.title };
    if repo.update_for(user_id, id, post.clone()).await? {
        Ok(Json(post))
    } else {
        Err(Error::not_found())
    }
}

pub(crate) async fn delete_post(repo: Dep<PostRepo>, user: CurrentUser, Path(id): Path<i64>) -> Result<NoContent> {
    let user_id: i64 = user.0.id.parse().map_err(|_| Error::unauthorized())?;
    if repo.remove_for(user_id, id).await? {
        Ok(NoContent)
    } else {
        Err(Error::not_found())
    }
}
"#;

/// The trivial users handler for the feed fixture.
const FEED_USERS_HANDLERS: &str = r#"//! Correct users handlers for the #105 feed fixture.
use super::model::*;
use super::repo::*;
use jerrycan::prelude::*;

pub(crate) async fn register(repo: Dep<UserRepo>, Json(body): Json<User>) -> Result<Created<User>> {
    let mut user = body.clone();
    user.id = repo.insert(body).await?;
    Ok(Created(user))
}
"#;

/// Issue #105 end-to-end: the public-read/owner-write shape proves out on a real
/// scaffold. Scaffold → gen-tests (the acceptance suite carries the #105
/// isolation test and NO 401 probe for the public reads) → RED on stubs →
/// implement the correct handlers → the SAME suite goes GREEN — proving anon
/// list serves another user's row (200), anon detail 200s, anon create 401s, a
/// non-owner PUT/DELETE 404s with the row surviving, and the owner's PUT 200s.
/// Then the full `jerrycan check` gate passes on the implemented app — JL0006
/// stays silent on the module's unscoped public reads while the write needles
/// stay armed.
#[test]
#[ignore = "heavy: scaffold + gen-tests + red run + implement + green run + check (#105 public_read)"]
fn public_read_feed_goes_green_on_a_correct_scaffold() {
    let tmp = tempfile::tempdir().unwrap();
    let design = tmp.path().join("design.json");
    std::fs::write(&design, FEED_PUBLIC_READ).unwrap();
    let app = tmp.path().join("feed-api");
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .env("JERRYCAN_FRAMEWORK_DEP", &dep)
        .args(["new"])
        .arg(&app)
        .arg("--design")
        .arg(&design)
        .status()
        .unwrap();
    assert!(st.success(), "the public_read design must scaffold");
    common::isolate_app_bin(&app);

    // The generated posts handlers: public GETs take no CurrentUser (despite the
    // declared auth_required on list_posts), writes keep the guard.
    let stubs = std::fs::read_to_string(app.join("crates/routes/posts/src/handlers.rs")).unwrap();
    assert!(
        stubs.contains("async fn list_posts(_repo: Dep<PostRepo>)"),
        "the public list stub must take no CurrentUser:\n{stubs}"
    );
    // The signature wraps one param per line (issue #165 — its one-line width exceeds
    // rustfmt's max_width), so the guard param appears on its own line.
    assert!(
        stubs.contains(
            "pub(crate) async fn create_post(\n    _repo: Dep<PostRepo>,\n    _user: CurrentUser,"
        ),
        "writes keep the guard:\n{stubs}"
    );

    // gen-tests: the suite carries the #105 isolation test; the public reads get
    // no 401 probe (the pre-fix gate-lie generated a permanently-red one).
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "gen-tests", "--module", "posts"])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "gen-tests posts: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let acceptance =
        std::fs::read_to_string(app.join("crates/routes/posts/tests/acceptance.rs")).unwrap();
    assert!(
        acceptance.contains("async fn anon_reads_but_only_the_owner_writes_posts()"),
        "the #105 isolation test must be generated:\n{acceptance}"
    );
    assert!(
        !acceptance.contains("list_posts_without_auth_is_401")
            && !acceptance.contains("get_post_without_auth_is_401"),
        "no 401 probe for the public reads (red-when-correct otherwise):\n{acceptance}"
    );
    assert!(
        acceptance.contains("create_post_without_auth_is_401"),
        "writes keep their 401 probes:\n{acceptance}"
    );

    // #123a: the users module needs its acceptance file too, or the final
    // `jerrycan check` refuses the app with JC0551 (never-gen-tested module).
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "gen-tests", "--module", "users"])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "gen-tests users: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    // RED: stubs (500) fail the generated suite.
    let red = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["test", "--workspace", "--no-fail-fast"])
        .output()
        .unwrap();
    assert!(!red.status.success(), "stub handlers must fail the suite");

    // Implement the correct handlers.
    install_handler(
        &app,
        "crates/routes/posts/src/handlers.rs",
        FEED_POSTS_HANDLERS,
    );
    install_handler(
        &app,
        "crates/routes/users/src/handlers.rs",
        FEED_USERS_HANDLERS,
    );

    // GREEN: the same probes pass — the four-way #105 contract holds on a real
    // app: anon read 200 (another user's row), anon write 401, non-owner write
    // 404 (row survives), owner write 200.
    let green = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["test", "--workspace"])
        .status()
        .unwrap();
    assert!(
        green.success(),
        "the correct public-read/owner-write handlers must satisfy the generated suite"
    );

    // And the full gate holds on the implemented app: JL0006 must stay silent on
    // the unscoped public reads (`repo.all()`/`repo.get(`) in this public_read
    // module while the owner-scoped writes pass untouched.
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "check"])
        .output()
        .unwrap();
    let payload: serde_json::Value = serde_json::from_slice(&out.stdout).expect("one JSON doc");
    assert_eq!(
        payload["ok"], true,
        "diagnostics: {}",
        payload["diagnostics"]
    );
}

/// The #124 conformance fixture: a tenant module (`clubs`) that HOSTS a
/// tenant-owned child (Book belongs_to Club in the SAME module), so the
/// JL0006 scan reads the tenant's OWN handlers alongside the child's.
const CLUB_HOSTED_CHILD: &str = r#"{
  "name": "club-api",
  "contract_version": 1,
  "auth": { "model": "session", "roles": ["owner", "member"] },
  "dependencies": ["db", "auth"],
  "tenancy": { "entity": "Club", "member_roles": ["owner", "member"] },
  "modules": [
    {
      "name": "users",
      "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" } }
      ]
    },
    {
      "name": "clubs",
      "entities": [
        { "name": "Club", "fields": [{ "name": "name", "type": "string" }] },
        { "name": "Book", "belongs_to": [{ "entity": "Club", "on_delete": "cascade" }],
          "fields": [{ "name": "title", "type": "string" }] }
      ],
      "endpoints": [
        { "operation_id": "list_clubs", "method": "GET", "path": "/",
          "auth_required": true,
          "success": { "status": 200, "entity": "Club", "list": true } },
        { "operation_id": "create_club", "method": "POST", "path": "/",
          "auth_required": true,
          "request_body": { "entity": "Club" },
          "success": { "status": 201, "entity": "Club" } },
        { "operation_id": "get_club", "method": "GET", "path": "/{id}",
          "auth_required": true,
          "success": { "status": 200, "entity": "Club" },
          "errors": [{ "status": 404, "when": "unknown id or not a member" }] },
        { "operation_id": "list_books", "method": "GET", "path": "/{club_id}/books",
          "auth_required": true,
          "success": { "status": 200, "entity": "Book", "list": true } },
        { "operation_id": "create_book", "method": "POST", "path": "/{club_id}/books",
          "auth_required": true,
          "request_body": { "entity": "Book" },
          "success": { "status": 201, "entity": "Book" } }
      ]
    }
  ]
}"#;

/// The CORRECT #124 clubs handlers: the tenant's own PathScoped detail route
/// (`get_club`) calls the unscoped `repo.get` on the TENANT repo — legitimate,
/// because the `Dep<Tenant>` guard already verified membership in the path
/// club — while the hosted child stays on the scoped accessors.
const CLUB_HANDLERS_CORRECT: &str = r#"//! Correct #124 clubs handlers: unscoped tenant detail read, scoped child.
use jerrycan::prelude::*;
use super::model::*;
use super::repo::*;
use shared::Tenant;
use shared::CurrentUser;

pub(crate) async fn list_clubs(repo: Dep<ClubRepo>, user: CurrentUser) -> Result<Json<Vec<Club>>> {
    Ok(Json(repo.all_for_member(user.0.id.clone()).await?))
}

pub(crate) async fn create_club(repo: Dep<ClubRepo>, user: CurrentUser, Json(body): Json<Club>) -> Result<Created<Club>> {
    let mut club = body;
    club.id = repo.create_with_membership(user.0.id.clone(), club.clone()).await?;
    Ok(Created(club))
}

pub(crate) async fn get_club(repo: Dep<ClubRepo>, _tenant: Dep<Tenant>, Path(club_id): Path<i64>) -> Result<Json<Club>> {
    // Membership in the path club was already verified by the Dep<Tenant> guard;
    // the unscoped get on the TENANT repo is the correct call here (#124).
    repo.get(club_id).await?.map(Json).ok_or_else(Error::not_found)
}

pub(crate) async fn list_books(repo: Dep<BookRepo>, _tenant: Dep<Tenant>, Path(_club_id): Path<i64>) -> Result<Json<Vec<Book>>> {
    Ok(Json(repo.all_for(_tenant.id()).await?))
}

pub(crate) async fn create_book(repo: Dep<BookRepo>, _tenant: Dep<Tenant>, Path(club_id): Path<i64>, Json(body): Json<BookRequest>) -> Result<Created<Book>> {
    let mut book = Book { id: 0, club_id, title: body.title };
    book.id = repo.insert(book.clone()).await?;
    Ok(Created(book))
}
"#;

/// The trivial users handler for the #124 fixture.
const CLUB_USERS_HANDLERS: &str = r#"//! Correct users handlers for the #124 fixture.
use jerrycan::prelude::*;
use super::model::*;
use super::repo::*;

pub(crate) async fn register(repo: Dep<UserRepo>, Json(body): Json<User>) -> Result<Created<User>> {
    let mut user = body.clone();
    user.id = repo.insert(body).await?;
    Ok(Created(user))
}
"#;

/// Issue #124 end-to-end: a child-hosting tenant app with CORRECT handlers
/// passes the full `jerrycan check` gate — JL0006 stays silent on the tenant's
/// own path-verified detail read (`repo.get` in `get_club`, the pre-fix false
/// positive) — while a REAL leak (the child's `list_books` swapped to the
/// unscoped `repo.all()`) still fails the same gate with JL0006 pointing at
/// that line. WHY (Rule 9): the exemption must be surgical — green on correct
/// code, red on the exact leak class the lint exists for.
#[test]
#[ignore = "heavy: scaffold + implement + check green, then leak + check red (#124 tenant-detail exemption)"]
fn child_hosting_tenant_app_goes_green_on_correct_handlers() {
    let tmp = tempfile::tempdir().unwrap();
    let design = tmp.path().join("design.json");
    std::fs::write(&design, CLUB_HOSTED_CHILD).unwrap();
    let app = tmp.path().join("club-api");
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .env("JERRYCAN_FRAMEWORK_DEP", &dep)
        .args(["new"])
        .arg(&app)
        .arg("--design")
        .arg(&design)
        .status()
        .unwrap();
    assert!(
        st.success(),
        "the child-hosting tenant design must scaffold"
    );
    common::isolate_app_bin(&app);

    // Implement the correct handlers: get_club reads the guard-verified tenant
    // via the unscoped `repo.get`, the child stays on the scoped accessors.
    install_handler(
        &app,
        "crates/routes/clubs/src/handlers.rs",
        CLUB_HANDLERS_CORRECT,
    );
    install_handler(
        &app,
        "crates/routes/users/src/handlers.rs",
        CLUB_USERS_HANDLERS,
    );

    // #123a: gen-tests before check — the honest gate refuses a never-gen-tested
    // module with JC0551, and the generated suite (incl. the member-surface and
    // isolation tests) must be green on the correct handlers.
    for module in ["users", "clubs"] {
        let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
            .current_dir(&app)
            .env("CARGO_TARGET_DIR", common::shared_app_target())
            .args(["gen-tests", "--module", module])
            .status()
            .unwrap();
        assert!(st.success(), "gen-tests {module} must succeed");
    }

    // GREEN: the full gate passes — pre-#124 this was a false JL0006 on
    // `get_club`'s legitimate `repo.get(club_id)`.
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "check"])
        .output()
        .unwrap();
    let payload: serde_json::Value = serde_json::from_slice(&out.stdout).expect("one JSON doc");
    assert_eq!(
        payload["ok"], true,
        "correct child-hosting tenant handlers must pass the gate (JL0006 silent \
         on the tenant's own detail read): {}",
        payload["diagnostics"]
    );

    // RED: a real unscoped call in the CHILD's handler still fails the gate —
    // the exemption never reaches the child (the actual JL0006 target).
    install_handler(
        &app,
        "crates/routes/clubs/src/handlers.rs",
        &CLUB_HANDLERS_CORRECT.replace("repo.all_for(_tenant.id())", "repo.all()"),
    );
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "check"])
        .output()
        .unwrap();
    let payload: serde_json::Value = serde_json::from_slice(&out.stdout).expect("one JSON doc");
    assert_eq!(
        payload["ok"], false,
        "the child's unscoped repo.all() must still fail the gate"
    );
    let diags = payload["diagnostics"].as_array().unwrap();
    assert!(
        diags.iter().any(|d| d["code"] == "JL0006"
            && d["file"] == "crates/routes/clubs/src/handlers.rs"
            && d["message"].as_str().unwrap().contains("all()")),
        "JL0006 must name the child's unscoped all(): {diags:?}"
    );
}

/// Issue #53 end-to-end: body-omittable server-owned fields. J4's shape (a public
/// `POST /subscribers` whose `confirmed`/`status` default server-side) AND J2's
/// shape (a nested `POST /habits/{habit_id}/checkins` whose parent fk comes from
/// the path). Both are UN-buildable before #53 (the minimal body 422s / the fk is
/// body-required); here the generated probe omits those fields and a correct
/// handler goes GREEN.
const OMITTABLE_DESIGN: &str = r#"{
  "name": "body-omittables",
  "contract_version": 0,
  "auth": { "model": "none" },
  "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": "list_subscribers", "method": "GET", "path": "/",
          "success": { "status": 200, "entity": "Subscriber", "list": true } },
        { "operation_id": "create_subscriber", "method": "POST", "path": "/",
          "request_body": { "entity": "Subscriber" },
          "success": { "status": 201, "entity": "Subscriber" } }
      ]
    },
    {
      "name": "habits",
      "entities": [
        { "name": "Habit", "fields": [{ "name": "name", "type": "string" }] },
        { "name": "Checkin", "belongs_to": [{ "entity": "Habit" }],
          "fields": [{ "name": "note", "type": "string" }] }
      ],
      "endpoints": [
        { "operation_id": "list_habits", "method": "GET", "path": "/",
          "success": { "status": 200, "entity": "Habit", "list": true } },
        { "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" } }
      ]
    }
  ]
}"#;

/// Correct subscribers handlers: `SubscriberRequest` has NO `confirmed`/`status`,
/// so the handler MUST supply the server defaults (it can't even name them from
/// the body — a compile-time forcing function).
const OMITTABLE_SUBSCRIBERS_HANDLERS: &str = r#"//! Correct subscribers handlers.
use super::model::*;
use super::repo::*;
use jerrycan::prelude::*;

pub(crate) async fn list_subscribers(repo: Dep<SubscriberRepo>) -> Result<Json<Vec<Subscriber>>> {
    Ok(Json(repo.all().await?))
}

pub(crate) async fn create_subscriber(repo: Dep<SubscriberRepo>, Json(body): Json<SubscriberRequest>) -> Result<Created<Subscriber>> {
    let mut sub = Subscriber { id: 0, email: body.email, confirmed: false, status: "active".into() };
    sub.id = repo.insert(sub.clone()).await?;
    Ok(Created(sub))
}
"#;

/// Correct habits handlers: `create_checkin` injects the `habit_id` PATH param
/// (the DTO omits it), so the checkin attaches to the path's habit.
const OMITTABLE_HABITS_HANDLERS: &str = r#"//! Correct habits handlers.
use super::model::*;
use super::repo::*;
use jerrycan::prelude::*;

pub(crate) async fn list_habits(repo: Dep<HabitRepo>) -> Result<Json<Vec<Habit>>> {
    Ok(Json(repo.all().await?))
}

pub(crate) async fn create_habit(repo: Dep<HabitRepo>, Json(body): Json<Habit>) -> Result<Created<Habit>> {
    let mut habit = body.clone();
    habit.id = repo.insert(body).await?;
    Ok(Created(habit))
}

pub(crate) async fn create_checkin(repo: Dep<CheckinRepo>, Path(habit_id): Path<i64>, Json(body): Json<CheckinRequest>) -> Result<Created<Checkin>> {
    let mut checkin = Checkin { id: 0, habit_id, note: body.note };
    checkin.id = repo.insert(checkin.clone()).await?;
    Ok(Created(checkin))
}
"#;

/// Overwrite a handler file and bump its mtime so cargo's mtime fingerprint
/// recompiles it (RED's `cargo test` and this write share a wall-clock second).
fn install_handler(app: &Path, rel: &str, contents: &str) {
    let dest = app.join(rel);
    std::fs::write(&dest, contents).unwrap();
    let future = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
    std::fs::File::options()
        .write(true)
        .open(&dest)
        .unwrap()
        .set_modified(future)
        .unwrap();
}

#[test]
#[ignore = "heavy: scaffold + gen-tests + red run + implement + green run (#53 body-omittables)"]
fn body_omittable_fields_go_green_on_a_correct_scaffold() {
    let tmp = tempfile::tempdir().unwrap();
    let design = tmp.path().join("design.json");
    std::fs::write(&design, OMITTABLE_DESIGN).unwrap();
    let app = tmp.path().join("body-omittables");
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .env("JERRYCAN_FRAMEWORK_DEP", &dep)
        .args(["new"])
        .arg(&app)
        .arg("--design")
        .arg(&design)
        .status()
        .unwrap();
    assert!(st.success(), "design must scaffold");
    common::isolate_app_bin(&app);

    // gen-tests both modules; capture the generated probe bodies.
    for module in ["subscribers", "habits"] {
        let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
            .current_dir(&app)
            .env("CARGO_TARGET_DIR", common::shared_app_target())
            .args(["--json", "gen-tests", "--module", module])
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "gen-tests {module}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    // The generated probe bodies OMIT the server-owned fields (contract on the wire).
    let subs =
        std::fs::read_to_string(app.join("crates/routes/subscribers/tests/acceptance.rs")).unwrap();
    assert!(
        subs.contains("create_subscriber_returns_201")
            && !subs.contains("\"confirmed\"")
            && !subs.contains("\"status\""),
        "subscriber probe must omit defaulted fields:\n{subs}"
    );
    let habits =
        std::fs::read_to_string(app.join("crates/routes/habits/tests/acceptance.rs")).unwrap();
    assert!(
        habits.contains("post_json(\"/habits/1/checkins\"") && !habits.contains("\"habit_id\""),
        "checkin probe must post under the path habit and omit habit_id:\n{habits}"
    );

    // RED: stubs (500) fail the generated suite.
    let red = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["test", "--workspace", "--no-fail-fast"])
        .output()
        .unwrap();
    assert!(!red.status.success(), "stub handlers must fail the suite");

    // Implement the correct handlers.
    install_handler(
        &app,
        "crates/routes/subscribers/src/handlers.rs",
        OMITTABLE_SUBSCRIBERS_HANDLERS,
    );
    install_handler(
        &app,
        "crates/routes/habits/src/handlers.rs",
        OMITTABLE_HABITS_HANDLERS,
    );

    // Append value assertions that reuse each module's tool-owned `app()` helper:
    // the minimal body 201s AND the server-owned values are readable server-side.
    let subs_test = "\n#[tokio::test]\nasync fn create_subscriber_applies_server_defaults() {\n    let t = app().await;\n    let res = t.post_json(\"/subscribers/\", &serde_json::json!({\"email\": \"a@b.c\"})).await;\n    assert_eq!(res.status().as_u16(), 201, \"minimal body must 201; body: {}\", res.text());\n    let body: serde_json::Value = serde_json::from_str(&res.text()).expect(\"json\");\n    assert_eq!(body[\"confirmed\"], serde_json::json!(false), \"server default confirmed=false; body: {}\", res.text());\n    assert_eq!(body[\"status\"], serde_json::json!(\"active\"), \"server default status=active; body: {}\", res.text());\n}\n";
    let habits_test = "\n#[tokio::test]\nasync fn create_checkin_attaches_to_path_habit() {\n    let t = app().await;\n    let h = t.post_json(\"/habits/\", &serde_json::json!({\"name\": \"run\"})).await;\n    assert_eq!(h.status().as_u16(), 201, \"seed habit; body: {}\", h.text());\n    let res = t.post_json(\"/habits/1/checkins\", &serde_json::json!({\"note\": \"did it\"})).await;\n    assert_eq!(res.status().as_u16(), 201, \"checkin without habit_id must 201; body: {}\", res.text());\n    let body: serde_json::Value = serde_json::from_str(&res.text()).expect(\"json\");\n    assert_eq!(body[\"habit_id\"], serde_json::json!(1), \"checkin attaches to the path's habit; body: {}\", res.text());\n}\n";
    for (rel, extra) in [
        ("crates/routes/subscribers/tests/acceptance.rs", subs_test),
        ("crates/routes/habits/tests/acceptance.rs", habits_test),
    ] {
        let path = app.join(rel);
        let mut content = std::fs::read_to_string(&path).unwrap();
        content.push_str(extra);
        std::fs::write(&path, &content).unwrap();
        let future = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
        std::fs::File::options()
            .write(true)
            .open(&path)
            .unwrap()
            .set_modified(future)
            .unwrap();
    }

    // GREEN: the generated probes AND the value assertions pass.
    let green = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["test", "--workspace"])
        .status()
        .unwrap();
    assert!(
        green.success(),
        "correct handlers must satisfy the body-omittable contract (defaults applied, path fk injected)"
    );
}

/// Issue #110 end-to-end: a `datetime` field defaulting to `"now"` is a dynamic
/// server-set, set-once timestamp. `created_at` is dropped from BOTH request DTOs
/// (create + update) and their OpenAPI schemas, stays in the response entity
/// schema, and the create stub steers the handler to `now_rfc3339()`. A correct
/// app — create sets `created_at = now_rfc3339()`, update PRESERVES it — passes the
/// full `jerrycan check` gate.
const NOW_DESIGN: &str = r#"{
  "name": "notes-now",
  "contract_version": 0,
  "auth": { "model": "none" },
  "dependencies": ["db"],
  "modules": [
    {
      "name": "notes",
      "entities": [
        { "name": "Note", "fields": [
          { "name": "body", "type": "string" },
          { "name": "created_at", "type": "datetime", "default": "now" }
        ]}
      ],
      "endpoints": [
        { "operation_id": "list_notes", "method": "GET", "path": "/",
          "success": { "status": 200, "entity": "Note", "list": true } },
        { "operation_id": "create_note", "method": "POST", "path": "/",
          "request_body": { "entity": "Note" },
          "success": { "status": 201, "entity": "Note" } },
        { "operation_id": "update_note", "method": "PUT", "path": "/{id}",
          "request_body": { "entity": "Note" },
          "success": { "status": 200, "entity": "Note" } }
      ]
    }
  ]
}"#;

/// Correct notes handlers: `NoteRequest`/`NoteUpdateRequest` have NO `created_at`,
/// so the create handler MUST set it via `now_rfc3339()` (a compile-time forcing
/// function) and the update handler PRESERVES the stored value — a client can never
/// rewrite the timestamp.
const NOW_HANDLERS: &str = r#"//! Correct notes handlers (#110 now-default).
use super::model::*;
use super::repo::*;
use jerrycan::prelude::*;

pub(crate) async fn list_notes(repo: Dep<NoteRepo>) -> Result<Json<Vec<Note>>> {
    Ok(Json(repo.all().await?))
}

pub(crate) async fn create_note(repo: Dep<NoteRepo>, Json(body): Json<NoteRequest>) -> Result<Created<Note>> {
    let mut note = Note { id: 0, body: body.body, created_at: now_rfc3339() };
    note.id = repo.insert(note.clone()).await?;
    Ok(Created(note))
}

pub(crate) async fn update_note(repo: Dep<NoteRepo>, Path(id): Path<i64>, Json(body): Json<NoteUpdateRequest>) -> Result<Json<Note>> {
    let existing = repo.get(id).await?.ok_or_else(Error::not_found)?;
    let updated = Note { id, body: body.body, created_at: existing.created_at };
    if repo.update(id, updated.clone()).await? {
        Ok(Json(updated))
    } else {
        Err(Error::not_found())
    }
}
"#;

#[test]
#[ignore = "heavy: scaffold + gen-tests + implement + full check gate (#110 now-default)"]
fn now_default_timestamp_goes_green_on_a_correct_scaffold() {
    let tmp = tempfile::tempdir().unwrap();
    let design = tmp.path().join("design.json");
    std::fs::write(&design, NOW_DESIGN).unwrap();
    let app = tmp.path().join("notes-now");
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .env("JERRYCAN_FRAMEWORK_DEP", &dep)
        .args(["new"])
        .arg(&app)
        .arg("--design")
        .arg(&design)
        .status()
        .unwrap();
    assert!(st.success(), "the now-default design must scaffold");
    common::isolate_app_bin(&app);

    // BOTH request DTOs drop `created_at` (server-owned on create, immutable on
    // update); the entity Model KEEPS it (present in every response).
    let model = std::fs::read_to_string(app.join("crates/routes/notes/src/model.rs")).unwrap();
    for dto in ["pub struct NoteRequest {", "pub struct NoteUpdateRequest {"] {
        let body = model
            .split(dto)
            .nth(1)
            .unwrap_or_else(|| panic!("{dto} must be emitted:\n{model}"))
            .split('}')
            .next()
            .unwrap();
        assert!(
            !body.contains("created_at"),
            "{dto} must omit created_at (the divergence: dropped on both):\n{body}"
        );
        assert!(
            body.contains("body"),
            "{dto} keeps the client field:\n{body}"
        );
    }
    assert!(
        model.contains("pub created_at: String,"),
        "the entity Model KEEPS created_at (present in responses):\n{model}"
    );

    // The create stub steers the handler at now_rfc3339().
    let handlers =
        std::fs::read_to_string(app.join("crates/routes/notes/src/handlers.rs")).unwrap();
    assert!(
        handlers.contains("now_rfc3339()") && handlers.contains("server-set timestamp"),
        "the create stub must steer created_at at now_rfc3339():\n{handlers}"
    );

    // OpenAPI: the response schema (Note) includes created_at; both request schemas
    // omit it.
    let openapi: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(app.join("openapi.json")).unwrap()).unwrap();
    let schemas = &openapi["components"]["schemas"];
    assert!(
        !schemas["Note"]["properties"]["created_at"].is_null(),
        "the response entity schema must include created_at: {}",
        schemas["Note"]
    );
    for req in ["NoteRequest", "NoteUpdateRequest"] {
        assert!(
            schemas[req]["properties"]["created_at"].is_null(),
            "{req} schema must omit created_at: {}",
            schemas[req]
        );
    }

    // gen-tests the module, implement the correct handlers, then the FULL gate is
    // green (JC0551 cleared, the generated acceptance suite passes on real handlers).
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "gen-tests", "--module", "notes"])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "gen-tests notes: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    install_handler(&app, "crates/routes/notes/src/handlers.rs", NOW_HANDLERS);

    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "check"])
        .output()
        .unwrap();
    let payload: serde_json::Value = serde_json::from_slice(&out.stdout).expect("one JSON doc");
    assert_eq!(
        payload["ok"], true,
        "correct now-default handlers must pass the full gate; diagnostics: {}",
        payload["diagnostics"]
    );
    assert!(out.status.success());
}

/// The #80 conformance fixture: a db-mode design whose fields declare
/// range/length constraints. `body` (min_len 2 / max_len 30) is the FIRST
/// rejectable field of the Note body, so the generated string reject probe
/// carries the `"a".repeat(31)` over-max EXPRESSION; `priority`/`points`
/// (integer min/max, both minimums above the default fixture `1`) force the
/// in-range clamp — a broken derivation would send `1`, trip the migration
/// CHECK, and turn the 201 probes red. `seq` (min 3000000000 / max
/// 4102444800, both `> i32::MAX`) forces the `i64`-suffixed fixture literal
/// (0.6.5 final review, Critical): a bare `3000000000` inside
/// `serde_json::json!` is typed i32 and the whole suite is a HARD compile
/// error — this test COMPILES AND RUNS the generated probes, so a regression
/// can't scaffold-and-pass again.
const LIMITS: &str = include_str!("../../../conformance/designs/limits-api.design.json");

/// The correct limits-api handlers: plain store + echo. Deliberately ZERO
/// hand-written validation — the generated `de_*` deserialize-validators own
/// the declared bounds, which is the whole #80 payoff.
const LIMITS_HANDLERS: &str = r#"//! Correct #80 handlers: store + echo; the generated de_* validators own the bounds.
use jerrycan::prelude::*;
use super::model::*;
use super::repo::*;

pub(crate) async fn create_note(repo: Dep<NoteRepo>, Json(body): Json<Note>) -> Result<Created<Note>> {
    let mut note = body;
    note.id = repo.insert(note.clone()).await?;
    Ok(Created(note))
}

pub(crate) async fn update_note(repo: Dep<NoteRepo>, Path(id): Path<i64>, Json(body): Json<Note>) -> Result<Json<Note>> {
    if repo.update(id, body.clone()).await? { Ok(Json(body)) } else { Err(Error::not_found()) }
}

pub(crate) async fn create_score(repo: Dep<ScoreRepo>, Json(body): Json<Score>) -> Result<Created<Score>> {
    let mut score = body;
    score.id = repo.insert(score.clone()).await?;
    Ok(Created(score))
}
"#;

/// Issue #80 end-to-end: a range/length-constrained design is greenable with
/// ZERO hand-written `Valid` impls. Scaffold (migration CHECKs emitted) →
/// gen-tests (the three 422 reject probes are reject-counted OUT of
/// expected_failing) → RED on stubs (exactly the four success/404 probes) →
/// trivial store+echo handlers → the SAME suite goes GREEN — the in-range
/// happy path 201/200s through the de_* validator AND the DB CHECK, and the
/// `_rejects_out_of_range_{field}` probes (incl. the compiled-and-run
/// `"a".repeat(31)` over-max string) assert 422 — → full `jerrycan check` ok.
#[test]
#[ignore = "heavy: scaffold + gen-tests + red run + implement + green run + check (#80 constraints)"]
fn constrained_design_goes_green_on_a_correct_scaffold() {
    let tmp = tempfile::tempdir().unwrap();
    let design = tmp.path().join("design.json");
    std::fs::write(&design, LIMITS).unwrap();
    let app = tmp.path().join("limits-api");
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .env("JERRYCAN_FRAMEWORK_DEP", &dep)
        .args(["new"])
        .arg(&app)
        .arg("--design")
        .arg(&design)
        .status()
        .unwrap();
    assert!(st.success(), "the constrained design must scaffold");
    common::isolate_app_bin(&app);

    // Defense-in-depth: every constrained column carries its migration CHECK,
    // so the in-range fixtures below are proven against the DB too.
    let ddl = std::fs::read_to_string(
        app.join("crates/routes/notes/migrations/sqlite/0001_create_tables.sql"),
    )
    .unwrap();
    for check in [
        "CHECK (length(\"body\") BETWEEN 2 AND 30)",
        "CHECK (\"priority\" BETWEEN 2 AND 5)",
        "CHECK (\"points\" BETWEEN 10 AND 100)",
        "CHECK (\"seq\" BETWEEN 3000000000 AND 4102444800)",
    ] {
        assert!(
            ddl.contains(check),
            "missing `{check}` in migration:\n{ddl}"
        );
    }

    // gen-tests: 7 tests, of which the three 422 reject probes pass on stubs
    // (the boundary rejects before the handler) — expected_failing counts only
    // the four success/404 probes (the T3 reject math, proven end-to-end).
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "gen-tests", "--module", "notes"])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "gen-tests notes: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let payload: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(
        payload["expected_failing"], 4,
        "the three reject probes must be excluded from expected_failing: {payload}"
    );

    let acceptance =
        std::fs::read_to_string(app.join("crates/routes/notes/tests/acceptance.rs")).unwrap();
    // Each constrained body gets its out-of-range 422 probe, corrupting the
    // FIRST rejectable field: the string one carries the `"a".repeat(31)`
    // over-max EXPRESSION (compiled and executed below, not just pinned as
    // text), the integer one sends max + 1.
    for (probe, needle) in [
        (
            "async fn create_note_rejects_out_of_range_body()",
            "\"body\": \"a\".repeat(31)",
        ),
        (
            "async fn update_note_rejects_out_of_range_body()",
            "\"body\": \"a\".repeat(31)",
        ),
        (
            "async fn create_score_rejects_out_of_range_points()",
            "\"points\": 101",
        ),
    ] {
        let at = acceptance
            .find(probe)
            .unwrap_or_else(|| panic!("{probe} missing:\n{acceptance}"));
        let fn_body = &acceptance[at..acceptance[at..].find("\n}").unwrap() + at];
        assert!(
            fn_body.contains(needle) && fn_body.contains(", 422,"),
            "{probe} must send {needle} and assert 422:\n{fn_body}"
        );
    }
    // The happy-path fixtures are derived IN-RANGE: the default integer
    // fixture `1` is clamped up to each declared minimum (2 and 10) — a raw
    // `1` would violate the CHECKs above and redden the 201 probes on a
    // CORRECT handler.
    assert!(
        acceptance.contains("\"priority\": 2") && acceptance.contains("\"points\": 10"),
        "integer fixtures must clamp into the declared range:\n{acceptance}"
    );
    // A `> i32::MAX` bound emits an `i64`-suffixed fixture literal — a bare
    // `3000000000` inside `serde_json::json!` is typed i32 and the generated
    // suite would not COMPILE (deny-by-default `overflowing_literals`); the
    // red/green runs below execute it, so this can't regress silently.
    assert!(
        acceptance.contains("\"seq\": 3000000000i64"),
        "out-of-i32-range fixtures must be i64-suffixed:\n{acceptance}"
    );

    // RED: stubs (500) fail exactly the four success/404 probes — the three
    // reject probes PASS on stubs (the 422 precedes the handler), proving the
    // out-of-range bodies are refused by the GENERATED validators alone.
    let red = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["test", "--workspace", "--no-fail-fast"])
        .output()
        .unwrap();
    assert!(!red.status.success(), "stub handlers must fail the suite");
    let red_out = format!(
        "{}{}",
        String::from_utf8_lossy(&red.stdout),
        String::from_utf8_lossy(&red.stderr)
    );
    let failed: usize = red_out
        .lines()
        .filter_map(|l| {
            l.strip_prefix("test result: FAILED. ")?
                .split("; ")
                .nth(1)?
                .strip_suffix(" failed")
                .map(|n| n.parse::<usize>().unwrap_or(0))
        })
        .sum();
    assert_eq!(
        failed, 4,
        "the 422 reject probes must already pass on stubs:\n{red_out}"
    );

    // Implement the correct handlers: store + echo, ZERO hand-written
    // validation — the #80 contract is enforced entirely by generated code.
    install_handler(&app, "crates/routes/notes/src/handlers.rs", LIMITS_HANDLERS);

    // GREEN: the same suite passes — in-range bodies clear the de_* validator
    // AND the migration CHECK (201/200), out-of-range bodies 422 at the
    // boundary, on the create AND update paths.
    let green = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["test", "--workspace"])
        .status()
        .unwrap();
    assert!(
        green.success(),
        "a constrained design must be greenable with zero hand-written Valid impls"
    );

    // And the full gate holds on the implemented app.
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "check"])
        .output()
        .unwrap();
    let payload: serde_json::Value = serde_json::from_slice(&out.stdout).expect("one JSON doc");
    assert_eq!(
        payload["ok"], true,
        "diagnostics: {}",
        payload["diagnostics"]
    );
}

/// The Phase 2 TDD loop: gen-tests makes the design executable and FAILING,
/// the agent implements, the same tests go green, the gate stays green.
#[test]
#[ignore = "heavy: scaffold + gen-tests + red run + implement + green run"]
fn tdd_loop_goes_red_then_green_on_sqlite() {
    let tmp = tempfile::tempdir().unwrap();
    let app = scaffold_golden_db(tmp.path());
    common::isolate_app_bin(&app);

    // 1. Generate acceptance tests for both top-level modules.
    let mut expected_failing = 0usize;
    for module in ["todos", "users"] {
        let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
            .current_dir(&app)
            .env("CARGO_TARGET_DIR", common::shared_app_target())
            .args(["--json", "gen-tests", "--module", module])
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "stderr: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        let payload: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
        expected_failing += payload["expected_failing"].as_u64().unwrap() as usize;
    }
    assert_eq!(expected_failing, 10, "todos 8 + users 2");

    // 2. RED: stubs must fail every acceptance test. `--no-fail-fast` so cargo
    // runs EVERY test binary (it otherwise halts at the first failing one, and
    // only the todos binary's `test result: FAILED.` line would be emitted).
    let out = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["test", "--workspace", "--no-fail-fast"])
        .output()
        .unwrap();
    assert!(
        !out.status.success(),
        "stub handlers must fail the acceptance suite"
    );
    let test_output = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    let failed: usize = test_output
        .lines()
        .filter_map(|l| {
            l.strip_prefix("test result: FAILED. ")?
                .split("; ")
                .nth(1)?
                .strip_suffix(" failed")
                .map(|n| n.parse::<usize>().unwrap_or(0))
        })
        .sum();
    assert_eq!(
        failed, expected_failing,
        "every generated test red:\n{test_output}"
    );

    // 3. The agent implements (db fixtures).
    for (fixture, target) in [
        (
            "db/todos_handlers.rs",
            "crates/routes/todos/src/handlers.rs",
        ),
        (
            "db/comments_handlers.rs",
            "crates/routes/todos/src/subroutes/comments/handlers.rs",
        ),
        (
            "db/users_handlers.rs",
            "crates/routes/users/src/handlers.rs",
        ),
    ] {
        let dest = app.join(target);
        std::fs::copy(
            repo_root().join("conformance/fixtures").join(fixture),
            &dest,
        )
        .unwrap();
        // RED's `cargo test` and this copy land in the same wall-clock second, so
        // bump the mtime forward — cargo's fingerprint is mtime-based and would
        // otherwise skip recompiling the changed handler and re-run the stubs.
        let future = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
        std::fs::File::options()
            .write(true)
            .open(&dest)
            .unwrap()
            .set_modified(future)
            .unwrap();
    }

    // 4. GREEN: the same acceptance tests pass.
    let st = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["test", "--workspace"])
        .status()
        .unwrap();
    assert!(
        st.success(),
        "implemented handlers must satisfy the design contract"
    );

    // 5. And the full gate holds.
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "check"])
        .output()
        .unwrap();
    let payload: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(
        payload["ok"], true,
        "diagnostics: {}",
        payload["diagnostics"]
    );
}

/// Spec §11 Phase 2 exit: an agent builds a POSTGRES-backed API test-first,
/// all green. Runs wherever JERRYCAN_TEST_PG_URL points at a live Postgres
/// (CI service container); skips loudly elsewhere.
#[test]
#[ignore = "heavy: full TDD loop against live Postgres (JERRYCAN_TEST_PG_URL)"]
fn agent_builds_postgres_backed_api_test_first() {
    let Ok(pg_url) = std::env::var("JERRYCAN_TEST_PG_URL") else {
        eprintln!("SKIP: JERRYCAN_TEST_PG_URL not set (CI provides a postgres service)");
        return;
    };
    let tmp = tempfile::tempdir().unwrap();
    let app = scaffold_golden_db(tmp.path());
    common::isolate_app_bin(&app);

    for module in ["todos", "users"] {
        let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
            .current_dir(&app)
            .env("CARGO_TARGET_DIR", common::shared_app_target())
            .args(["gen-tests", "--module", module])
            .status()
            .unwrap();
        assert!(st.success());
    }
    for (fixture, target) in [
        (
            "db/todos_handlers.rs",
            "crates/routes/todos/src/handlers.rs",
        ),
        (
            "db/comments_handlers.rs",
            "crates/routes/todos/src/subroutes/comments/handlers.rs",
        ),
        (
            "db/users_handlers.rs",
            "crates/routes/users/src/handlers.rs",
        ),
    ] {
        std::fs::copy(
            repo_root().join("conformance/fixtures").join(fixture),
            app.join(target),
        )
        .unwrap();
    }

    // Clean slate before migrating: isolate this test from any prior run's tables
    // (see reset_pg_public_schema). Safe because the heavy suite runs
    // single-threaded, so there is never a concurrent user of this database.
    reset_pg_public_schema(&pg_url);

    // Apply migrations to the real Postgres, then serve against it and drive CRUD.
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["db", "migrate", "--url", &pg_url])
        .status()
        .unwrap();
    assert!(st.success(), "migrations must apply to live Postgres");

    let port = {
        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        l.local_addr().unwrap().port()
    };
    let addr = format!("127.0.0.1:{port}");
    let mut server = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .env("JERRYCAN_ADDR", &addr)
        .env("JERRYCAN_DATABASE_URL", &pg_url)
        .args(["run", "-p", "app"])
        .spawn()
        .unwrap();

    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(180);
    while std::time::Instant::now() < deadline {
        if std::net::TcpStream::connect(&addr).is_ok() {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(400));
    }
    let http = |req: String| -> String {
        let mut s = std::net::TcpStream::connect(&addr).unwrap();
        s.write_all(req.as_bytes()).unwrap();
        let mut buf = Vec::new();
        s.read_to_end(&mut buf).unwrap();
        String::from_utf8_lossy(&buf).into_owned()
    };

    let body = r#"{"title":"pg ship","done":false}"#;
    let res = http(format!(
        "POST /todos/ HTTP/1.1\r\nHost: l\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
        body.len()
    ));
    assert!(res.starts_with("HTTP/1.1 201"), "{res}");
    let res = http("GET /todos/1 HTTP/1.1\r\nHost: l\r\nConnection: close\r\n\r\n".into());
    assert!(
        res.starts_with("HTTP/1.1 200") && res.contains("pg ship"),
        "{res}"
    );
    let res = http("GET /openapi.json HTTP/1.1\r\nHost: l\r\nConnection: close\r\n\r\n".into());
    assert!(
        res.starts_with("HTTP/1.1 200") && res.contains("3.1.0"),
        "validate extension live: {res}"
    );
    let res = http("DELETE /todos/1 HTTP/1.1\r\nHost: l\r\nConnection: close\r\n\r\n".into());
    assert!(res.starts_with("HTTP/1.1 204"), "{res}");

    // Test-first, all green, against Postgres:
    let st = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .env("JERRYCAN_DATABASE_URL", &pg_url)
        .args(["test", "--workspace"])
        .status()
        .unwrap();
    let _ = server.kill();
    let _ = server.wait();
    assert!(
        st.success(),
        "acceptance suite must be green against Postgres"
    );
}

/// Spec §11 Phase 3 exit: the golden app deploys to Docker + k8s + bare server
/// from one command. Each leg is gated on its tool; missing tools SKIP that leg
/// loudly. The binary (bare-server) leg is unconditional.
///
/// DOCKER leg — pre-publish reality: the EMITTED `deploy/Dockerfile` does an
/// in-container `cargo build` of the generated app, which depends on `jerrycan`.
/// Today jerrycan is UNPUBLISHED (crates.io has only 0.0.0 reservations) and the
/// conformance scaffold wires a host PATH dep via `JERRYCAN_FRAMEWORK_DEP` that
/// lives OUTSIDE the `COPY . .` build context — so `docker build -f
/// deploy/Dockerfile` cannot fetch the framework and FAILS. The emitted
/// Dockerfile is correct for the post-0.1.0 world and stays the default artifact.
/// To PROVE the deploy-anywhere intent TODAY (a containerized jerrycan app serves
/// over HTTP) we build a THIN runtime image from the host-built binary instead:
/// the `--binary` artifact is copied into a minimal image and run. This needs a
/// Linux-runnable binary; on a non-Linux host the host binary is the host OS's
/// format and cannot run in a Linux container, so the docker leg SKIPs loudly.
#[test]
#[ignore = "heavy: package the golden app and prove binary/docker/k8s deploy paths"]
fn golden_app_deploys_everywhere() {
    // The heart of this test — a static `x86_64-unknown-linux-musl` binary built
    // and served, plus a Linux container image — cannot be produced on a non-Linux
    // host: there is no musl cross-linker, so the link fails (Apple's ld rejects
    // the GNU `-Bstatic`/`--as-needed`/… flags). CI runs this on Linux; skip loudly
    // elsewhere so `cargo test --include-ignored` stays green for macOS/other
    // contributors. Package file-generation (Dockerfile/k8s/systemd/SBOM) is
    // covered on every host by tests/package.rs.
    if !cfg!(target_os = "linux") {
        eprintln!(
            "SKIP golden_app_deploys_everywhere: needs a Linux host for the musl \
             binary + container legs (host is {}); CI covers it.",
            std::env::consts::OS
        );
        return;
    }
    let tmp = tempfile::tempdir().unwrap();
    // Reuse the memory-mode golden app (deploy paths are storage-agnostic).
    let app = scaffold_golden(tmp.path());
    for (fixture, target) in [
        ("todos_handlers.rs", "crates/routes/todos/src/handlers.rs"),
        (
            "comments_handlers.rs",
            "crates/routes/todos/src/subroutes/comments/handlers.rs",
        ),
        ("users_handlers.rs", "crates/routes/users/src/handlers.rs"),
    ] {
        std::fs::copy(
            repo_root().join("conformance/fixtures").join(fixture),
            app.join(target),
        )
        .unwrap();
    }

    // #123a: `package` shares the check gate, which now refuses a
    // never-gen-tested module with JC0551 — gen-tests first, as the workflow
    // orders (the canned implementations satisfy the generated suite).
    for module in ["todos", "users"] {
        let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
            .current_dir(&app)
            .env("CARGO_TARGET_DIR", common::shared_app_target())
            .args(["gen-tests", "--module", module])
            .status()
            .unwrap();
        assert!(st.success(), "gen-tests {module} must succeed");
    }

    // ONE command emits every artifact (after a green check gate).
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args([
            "--json",
            "package",
            "--binary",
            "--docker",
            "--k8s",
            "--systemd",
        ])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "package failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let payload: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    let artifacts = payload["artifacts"].as_array().unwrap();
    for expected in [
        "deploy/Dockerfile",
        "deploy/k8s.yaml",
        "deploy/todo-api.service",
        "deploy/todo-api",
        "deploy/sbom.json",
    ] {
        assert!(
            artifacts.iter().any(|a| a == expected) || app.join(expected).exists(),
            "missing {expected}"
        );
    }
    // SBOM is valid CycloneDX.
    let sbom: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(app.join("deploy/sbom.json")).unwrap())
            .unwrap();
    assert_eq!(sbom["bomFormat"], "CycloneDX");
    assert!(
        sbom["components"]
            .as_array()
            .unwrap()
            .iter()
            .any(|c| c["name"] == "tokio")
    );

    // BARE SERVER leg: run the built binary directly, curl it.
    let port = pick_port();
    let addr = format!("127.0.0.1:{port}");
    let mut bin = Command::new(app.join("deploy/todo-api"))
        .env("JERRYCAN_ADDR", &addr)
        .spawn()
        .expect("packaged binary runs");
    await_listen(&addr, 60);
    assert!(
        http_get(&addr, "/todos/").starts_with("HTTP/1.1 200"),
        "bare binary serves"
    );
    let _ = bin.kill();
    let _ = bin.wait();

    // DOCKER leg (gated): build a THIN runtime image from the host-built binary
    // and run it (see the function doc for why we don't use the emitted, publish-
    // gated, in-container-build Dockerfile here). Needs docker AND a Linux host
    // (the host binary must be executable inside a Linux container).
    if !tool_present("docker") {
        eprintln!("SKIP docker leg: docker not present");
    } else if std::env::consts::OS != "linux" {
        eprintln!(
            "SKIP docker leg: host is {} — the host-built binary is not a Linux \
             executable and cannot run in a Linux container (CI proves this leg on Linux)",
            std::env::consts::OS
        );
    } else {
        // distroless/static needs a fully static (musl) binary; a dynamically
        // linked gnu binary needs a glibc base. Pick the base to match.
        let base = if musl_built(&app) {
            "gcr.io/distroless/static:nonroot"
        } else {
            "debian:stable-slim"
        };
        let test_dockerfile = format!(
            "FROM {base}\nCOPY deploy/todo-api /usr/local/bin/todo-api\n\
             EXPOSE 8000\nENV JERRYCAN_ADDR=0.0.0.0:8000\n\
             ENTRYPOINT [\"/usr/local/bin/todo-api\"]\n"
        );
        std::fs::write(app.join("Dockerfile.thin"), &test_dockerfile).unwrap();
        let tag = "jerrycan-conformance:test";
        let build = Command::new("docker")
            .current_dir(&app)
            .env("CARGO_TARGET_DIR", common::shared_app_target())
            .args(["build", "-f", "Dockerfile.thin", "-t", tag, "."])
            .status()
            .unwrap();
        assert!(build.success(), "thin-image docker build");
        let port = pick_port();
        let run = Command::new("docker")
            .args([
                "run",
                "-d",
                "--rm",
                "-p",
                &format!("{port}:8000"),
                "--name",
                "jerrycan-conformance",
                tag,
            ])
            .output()
            .unwrap();
        assert!(
            run.status.success(),
            "docker run: {}",
            String::from_utf8_lossy(&run.stderr)
        );
        let addr = format!("127.0.0.1:{port}");
        await_listen(&addr, 60);
        let body = http_get(&addr, "/todos/");
        let _ = Command::new("docker")
            .args(["stop", "jerrycan-conformance"])
            .status();
        let _ = Command::new("docker").args(["rmi", "-f", tag]).status();
        assert!(
            body.starts_with("HTTP/1.1 200"),
            "containerized app serves: {body}"
        );
    }

    // K8S leg (gated): validate the manifests parse + are structurally appl-able.
    // `kubectl apply --dry-run=client` still performs API-resource discovery
    // against the cluster (it queries `/api` to map kinds), so it needs a
    // reachable cluster — `--dry-run=client` is NOT cluster-free. We therefore
    // gate on cluster reachability, not merely on kubectl being installed
    // (`kubectl --version` is also not a valid flag — probe `version --client`).
    if kubectl_present() && cluster_reachable() {
        let out = Command::new("kubectl")
            .current_dir(&app)
            .env("CARGO_TARGET_DIR", common::shared_app_target())
            .args(["apply", "--dry-run=client", "-f", "deploy/k8s.yaml"])
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "kubectl dry-run: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    } else {
        // Structural fallback: every YAML doc parses and has kind+apiVersion.
        let y = std::fs::read_to_string(app.join("deploy/k8s.yaml")).unwrap();
        let docs: Vec<&str> = y.split("\n---\n").collect();
        assert_eq!(docs.len(), 3, "Deployment + Service + NetworkPolicy");
        for d in docs {
            assert!(
                d.contains("apiVersion:") && d.contains("kind:"),
                "valid manifest doc"
            );
        }
        eprintln!(
            "SKIP kubectl dry-run: no reachable cluster — used structural manifest validation"
        );
    }
}

/// THE v2 north-star gate: the reference-slice design — a tenant-scoped, JWT-guarded,
/// db-backed multi-module backend (workspaces/leads/api-keys/billing) — scaffolds
/// onto the full SeaORM stack, the generated workspace BUILDS, its generated
/// acceptance + isolation tests run and fail ONLY on unimplemented stubs (JC0500),
/// and the lighter check gates (jerrycan lints + schema-contract freshness) are
/// clean. We deliberately skip the heaviest gates here (cargo-audit/cargo-deny are
/// exercised by the db-mode golden test); this gate's job is to pin the SeaORM
/// compile-tax baseline and the red-test shape on the real eval design.
///
/// WHY the stub-class assertion matters (Rule 9): a pre-implementation scaffold
/// MUST go red because the handlers are unimplemented — every red is a JC0500
/// "not implemented" stub. If a red were instead a 401/403/422, the *generator*
/// would be wiring the wrong status (a guard misfire or a validation false-reject)
/// onto a request the test intends to succeed — a real bug. So this gate fails
/// loudly if any acceptance failure carries a non-500 status, while the
/// `*_without_auth_is_401` guard tests are expected to PASS (the guard runs before
/// the stub, so a credential-less request is correctly rejected pre-implementation).
#[test]
#[ignore = "heavy: reference-slice (SeaORM) scaffolds, builds, reds-on-stubs; records cold-build baseline"]
fn reference_slice_scaffold_passes_check() {
    let tmp = tempfile::tempdir().unwrap();

    // Scaffold the reference-slice design wired to the LOCAL framework path dep, the
    // same way every other heavy test wires it (env passed to the child only).
    let design_path = tmp.path().join("design.json");
    std::fs::write(&design_path, REFERENCE).unwrap();
    let app = tmp.path().join("reference-slice");
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .env("JERRYCAN_FRAMEWORK_DEP", &dep)
        .arg("new")
        .arg(&app)
        .arg("--design")
        .arg(&design_path)
        .status()
        .unwrap();
    assert!(st.success(), "reference-slice must scaffold");
    common::isolate_app_bin(&app);

    // schema.json is written by the db-mode scaffold (derived from migrations).
    assert!(
        app.join("schema.json").exists(),
        "db-mode scaffold must emit schema.json"
    );

    // gen-tests for every top-level module — mirrors the binary invocation the
    // other heavy tests use. Each emits a failing acceptance suite (stubs).
    let mut expected_failing = 0usize;
    for module in [
        "users",
        "workspaces",
        "leads",
        "api-keys",
        "billing",
        "integrations",
    ] {
        let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
            .current_dir(&app)
            .env("CARGO_TARGET_DIR", common::shared_app_target())
            .args(["--json", "gen-tests", "--module", module])
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "gen-tests {module} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        let payload: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
        expected_failing += payload["expected_failing"].as_u64().unwrap() as usize;
    }
    assert!(
        expected_failing > 0,
        "the design must generate failing acceptance tests"
    );

    // COLD BUILD baseline: time the generated workspace's first build. The tempdir
    // is its own target root, so this is a genuine from-scratch SeaORM compile —
    // print it so CI logs carry the v2 compile-tax baseline.
    let t0 = std::time::Instant::now();
    let build = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["build", "--workspace"])
        .output()
        .unwrap();
    let cold_build = t0.elapsed();
    assert!(
        build.status.success(),
        "reference-slice (SeaORM) generated workspace must build:\n{}",
        String::from_utf8_lossy(&build.stderr)
    );
    eprintln!("reference-slice cold build: {cold_build:?}");

    // INCREMENTAL test-build baseline: build (don't run) the route-leads test
    // binary now that deps are warm — the tightest agent inner-loop signal. `cargo
    // test --no-run` compiles the test target without executing it.
    let t1 = std::time::Instant::now();
    let leads_build = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["test", "-p", "route-leads", "--no-run"])
        .output()
        .unwrap();
    let leads_test_build = t1.elapsed();
    assert!(
        leads_build.status.success(),
        "route-leads test binary must compile:\n{}",
        String::from_utf8_lossy(&leads_build.stderr)
    );
    eprintln!("reference-slice route-leads incremental test-build: {leads_test_build:?}");

    // RED on stubs: run every generated test. `--no-fail-fast` so cargo runs all
    // test binaries (it otherwise halts at the first failing crate).
    let out = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["test", "--workspace", "--no-fail-fast"])
        .output()
        .unwrap();
    assert!(
        !out.status.success(),
        "pre-implementation stubs must fail the acceptance suite"
    );
    let test_output = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );

    // Every red MUST be a JC0500 stub. A test failure prints the asserted-against
    // status as `  left: <code>` (the observed status) above a `right:` (the
    // designed status). Walk every observed status from a failed assertion and
    // require it to be 500 — a 401/403/422 here would mean the generator mis-wired
    // a guard or a validator onto a request the test means to succeed (a REAL bug).
    let observed: Vec<u16> = test_output
        .lines()
        .filter_map(|l| l.trim().strip_prefix("left: "))
        .filter_map(|n| n.trim().parse::<u16>().ok())
        .collect();
    assert!(
        !observed.is_empty(),
        "expected failed-assertion `left:` lines in:\n{test_output}"
    );
    let non_stub: Vec<u16> = observed.iter().copied().filter(|s| *s != 500).collect();
    assert!(
        non_stub.is_empty(),
        "acceptance failures must be ONLY JC0500 stubs (500); found non-stub \
         observed statuses {non_stub:?} — a guard/validation false-failure is a \
         generator bug:\n{test_output}"
    );
    // And the only JC#### code surfacing in any failure body is the stub code: a
    // JC0422 (validation) in a failure body would be a false-reject of a body the
    // generator itself built from the design fixtures.
    assert!(
        !test_output.contains("JC0422"),
        "no acceptance failure may carry JC0422 (validation false-reject):\n{test_output}"
    );
    // The guard tests must be PRESENT and PASSING — proof the JWT guard runs ahead
    // of the stub (a credential-less mutation is correctly 401 pre-implementation).
    assert!(
        test_output.contains("_without_auth_is_401 ... ok"),
        "guard tests must pass (guard precedes the stub):\n{test_output}"
    );
    assert!(
        !test_output.contains("_without_auth_is_401 ... FAILED"),
        "a guard test must never fail — the guard precedes the stub:\n{test_output}"
    );

    // The lighter check gates, run directly (audit/deny are too heavy here and are
    // covered by the db-mode golden test): jerrycan lints and schema-contract
    // freshness must both be clean on the fresh scaffold.
    let design: jerrycan::platform::design::Design = serde_json::from_str(REFERENCE).unwrap();
    let lints = jerrycan::platform::lints::run(&app, &design);
    assert!(
        lints.is_empty(),
        "jerrycan lints must be clean on a fresh scaffold: {lints:?}"
    );
    let schema_drift = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(jerrycan::platform::schema::verify_fresh(&app, &design))
        .expect("schema derivation must succeed");
    assert!(
        schema_drift.is_empty(),
        "scaffolded schema.json must match a fresh derivation: {schema_drift:?}"
    );
}

/// The #115 composite-unique conformance fixture: a `Like` per `(user, post)`.
/// User and Post live in their OWN modules, so the fk columns are cross-module
/// (unenforced — no seeded parent row needed for a flat create probe) while the
/// `unique: [["user_id","post_id"]]` composite index is emitted on the likes
/// table regardless. The generated suite carries the composite-unique 409 test.
const COMPOSITE_UNIQUE_LIKES: &str = r#"{
  "name": "likes-api",
  "contract_version": 1,
  "dependencies": ["db"],
  "modules": [
    { "name": "users",
      "entities": [{ "name": "User", "fields": [{ "name": "email", "type": "string" }] }],
      "endpoints": [{ "operation_id": "create_user", "method": "POST", "path": "/",
        "request_body": { "entity": "User" }, "success": { "status": 201, "entity": "User" } }] },
    { "name": "posts",
      "entities": [{ "name": "Post", "fields": [{ "name": "title", "type": "string" }] }],
      "endpoints": [{ "operation_id": "create_post", "method": "POST", "path": "/",
        "request_body": { "entity": "Post" }, "success": { "status": 201, "entity": "Post" } }] },
    { "name": "engagement",
      "entities": [{ "name": "Like",
        "belongs_to": [{ "entity": "User" }, { "entity": "Post" }],
        "unique": [["user_id", "post_id"]],
        "fields": [{ "name": "reaction", "type": "string" }] }],
      "endpoints": [{ "operation_id": "create_like", "method": "POST", "path": "/",
        "request_body": { "entity": "Like" }, "success": { "status": 201, "entity": "Like" } }] }
  ]
}"#;

const LIKES_USERS_HANDLERS: &str = r#"//! Correct users handler for the #115 fixture.
use jerrycan::prelude::*;
use super::model::*;
use super::repo::*;

pub(crate) async fn create_user(repo: Dep<UserRepo>, Json(body): Json<User>) -> Result<Created<User>> {
    repo.insert(body.clone()).await?;
    Ok(Created(body))
}
"#;

const LIKES_POSTS_HANDLERS: &str = r#"//! Correct posts handler for the #115 fixture.
use jerrycan::prelude::*;
use super::model::*;
use super::repo::*;

pub(crate) async fn create_post(repo: Dep<PostRepo>, Json(body): Json<Post>) -> Result<Created<Post>> {
    repo.insert(body.clone()).await?;
    Ok(Created(body))
}
"#;

/// The correct engagement handler: a plain `insert`. The SECOND create with the
/// same `(user_id, post_id)` hits the `CREATE UNIQUE INDEX` — `db_error` maps the
/// unique violation to `Error::conflict` → 409, no application-level check.
const LIKES_ENGAGEMENT_HANDLERS: &str = r#"//! Correct #115 engagement handler: insert; the composite UNIQUE index 409s a dup.
use jerrycan::prelude::*;
use super::model::*;
use super::repo::*;

pub(crate) async fn create_like(repo: Dep<LikeRepo>, Json(body): Json<Like>) -> Result<Created<Like>> {
    repo.insert(body.clone()).await?;
    Ok(Created(body))
}
"#;

/// Issue #115 end-to-end: the composite / multi-column UNIQUE proves out on a
/// real scaffold. Scaffold → gen-tests (the suite carries the composite-unique
/// 409 test) → RED on stubs → implement the plain-insert handlers → the SAME
/// suite goes GREEN, so a duplicate `(user_id, post_id)` insert is a 409 through
/// the DB index (no application-level SELECT-then-INSERT). Then the full
/// `jerrycan check` gate passes on the implemented app.
#[test]
#[ignore = "heavy: scaffold + gen-tests + red run + implement + green run + check (#115 composite unique)"]
fn composite_unique_conflict_goes_409_on_a_correct_scaffold() {
    let tmp = tempfile::tempdir().unwrap();
    let design = tmp.path().join("design.json");
    std::fs::write(&design, COMPOSITE_UNIQUE_LIKES).unwrap();
    let app = tmp.path().join("likes-api");
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .env("JERRYCAN_FRAMEWORK_DEP", &dep)
        .args(["new"])
        .arg(&app)
        .arg("--design")
        .arg(&design)
        .status()
        .unwrap();
    assert!(st.success(), "the composite-unique design must scaffold");
    common::isolate_app_bin(&app);

    // The migration carries the composite unique index on the likes table.
    for dialect in ["sqlite", "postgres"] {
        let sql = std::fs::read_to_string(app.join(format!(
            "crates/routes/engagement/migrations/{dialect}/0001_create_tables.sql"
        )))
        .unwrap();
        assert!(
            sql.contains(
                "CREATE UNIQUE INDEX \"idx_likes_uc0\" ON \"likes\" (\"user_id\", \"post_id\")"
            ),
            "{dialect}: the composite unique index must be scaffolded:\n{sql}"
        );
    }

    // gen-tests every module; the engagement suite carries the 409 conflict test.
    for module in ["users", "posts", "engagement"] {
        let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
            .current_dir(&app)
            .env("CARGO_TARGET_DIR", common::shared_app_target())
            .args(["--json", "gen-tests", "--module", module])
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "gen-tests {module}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }
    let acceptance =
        std::fs::read_to_string(app.join("crates/routes/engagement/tests/acceptance.rs")).unwrap();
    assert!(
        acceptance.contains("async fn like_composite_unique_0_is_409()"),
        "the composite-unique 409 test must be generated:\n{acceptance}"
    );

    // RED: stubs fail the generated suite (the first create never inserts).
    let red = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["test", "--workspace", "--no-fail-fast"])
        .output()
        .unwrap();
    assert!(!red.status.success(), "stub handlers must fail the suite");

    // Implement the correct plain-insert handlers.
    install_handler(
        &app,
        "crates/routes/users/src/handlers.rs",
        LIKES_USERS_HANDLERS,
    );
    install_handler(
        &app,
        "crates/routes/posts/src/handlers.rs",
        LIKES_POSTS_HANDLERS,
    );
    install_handler(
        &app,
        "crates/routes/engagement/src/handlers.rs",
        LIKES_ENGAGEMENT_HANDLERS,
    );

    // GREEN: the composite-unique 409 test passes — a duplicate (user_id,
    // post_id) is a 409 through the DB index, not a race.
    let green = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["test", "--workspace"])
        .status()
        .unwrap();
    assert!(
        green.success(),
        "the plain-insert handlers must satisfy the composite-unique 409 test"
    );

    // The full gate holds on the implemented app.
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "check"])
        .output()
        .unwrap();
    let payload: serde_json::Value = serde_json::from_slice(&out.stdout).expect("one JSON doc");
    assert_eq!(
        payload["ok"], true,
        "diagnostics: {}",
        payload["diagnostics"]
    );
}

/// The #119 fk-alias conformance fixture: a ledger `Transfer` with TWO aliased
/// references to `Account` (from_account/to_account) and a self-referential
/// `Comment` (parent), all in ONE module so the fk columns carry REAL DDL FOREIGN
/// KEY constraints — the case a single un-aliased `belongs_to` cannot express.
/// GET-only so the generated probes read (no create probe → no FK-seed needed).
const FK_ALIAS_LEDGER: &str = r#"{
  "name": "ledger-api",
  "contract_version": 1,
  "dependencies": ["db"],
  "modules": [
    { "name": "ledger",
      "entities": [
        { "name": "Account", "fields": [{ "name": "name", "type": "string" }] },
        { "name": "Transfer",
          "belongs_to": [
            { "entity": "Account", "as": "from_account" },
            { "entity": "Account", "as": "to_account" }
          ],
          "fields": [{ "name": "amount", "type": "integer" }] },
        { "name": "Comment",
          "belongs_to": [{ "entity": "Comment", "as": "parent", "on_delete": "cascade" }],
          "fields": [{ "name": "body", "type": "string" }] }
      ],
      "endpoints": [
        { "operation_id": "list_transfers", "method": "GET", "path": "/transfers",
          "success": { "status": 200, "entity": "Transfer", "list": true } },
        { "operation_id": "show_transfer", "method": "GET", "path": "/transfers/{id}",
          "success": { "status": 200, "entity": "Transfer" } },
        { "operation_id": "list_comments", "method": "GET", "path": "/comments",
          "success": { "status": 200, "entity": "Comment", "list": true } }
      ] }
  ]
}"#;

/// The correct GET-only handlers over the aliased-fk entities.
const FK_ALIAS_HANDLERS: &str = r#"//! Correct #119 handlers: GET-only reads over the aliased-fk entities.
use jerrycan::prelude::*;
use super::model::*;
use super::repo::*;

pub(crate) async fn list_transfers(repo: Dep<TransferRepo>) -> Result<Json<Vec<Transfer>>> {
    Ok(Json(repo.all().await?))
}

pub(crate) async fn show_transfer(repo: Dep<TransferRepo>, Path(id): Path<i64>) -> Result<Json<Transfer>> {
    repo.get(id).await?.map(Json).ok_or_else(Error::not_found)
}

pub(crate) async fn list_comments(repo: Dep<CommentRepo>) -> Result<Json<Vec<Comment>>> {
    Ok(Json(repo.all().await?))
}
"#;

/// Issue #119 end-to-end: the belongs_to fk alias proves out on a real scaffold.
/// The two-reference `Transfer` (from_account_id + to_account_id, two distinct
/// FKs to `accounts` with distinct constraint names) and the self-referential
/// `Comment` (parent_id → comments) scaffold, the generated SeaORM model
/// (distinct Relation variants + a single `Related` impl per target) COMPILES,
/// the generated suite goes GREEN on the correct handlers, and the full
/// `jerrycan check` gate passes. Un-aliased `belongs_to` stays byte-identical
/// (covered by determinism.rs); THIS proves the alias path is buildable end to
/// end — a single un-aliased belongs_to could never express two refs to one table.
#[test]
#[ignore = "heavy: scaffold + build + gen-tests + red run + implement + green run + check (#119 fk alias)"]
fn fk_alias_two_refs_and_self_ref_go_green_on_a_correct_scaffold() {
    let tmp = tempfile::tempdir().unwrap();
    let design = tmp.path().join("design.json");
    std::fs::write(&design, FK_ALIAS_LEDGER).unwrap();
    let app = tmp.path().join("ledger-api");
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .env("JERRYCAN_FRAMEWORK_DEP", &dep)
        .args(["new"])
        .arg(&app)
        .arg("--design")
        .arg(&design)
        .status()
        .unwrap();
    assert!(st.success(), "the fk-alias design must scaffold");
    common::isolate_app_bin(&app);

    // The migration carries the two aliased fk columns + the self-ref column, with
    // two distinct FKs to accounts (distinct constraint names on Postgres, where
    // two same-named table constraints would be rejected at apply).
    for dialect in ["sqlite", "postgres"] {
        let sql = std::fs::read_to_string(app.join(format!(
            "crates/routes/ledger/migrations/{dialect}/0001_create_tables.sql"
        )))
        .unwrap();
        assert!(
            sql.contains("\"from_account_id\"")
                && sql.contains("\"to_account_id\"")
                && !sql.contains("\"account_id\""),
            "{dialect}: both aliased fk columns replace the default account_id:\n{sql}"
        );
        assert_eq!(
            sql.matches("REFERENCES \"accounts\"").count(),
            2,
            "{dialect}: two distinct FKs must reference accounts:\n{sql}"
        );
        assert!(
            sql.contains("\"parent_id\"") && sql.contains("REFERENCES \"comments\""),
            "{dialect}: the self-reference must emit parent_id → comments:\n{sql}"
        );
    }
    let pg = std::fs::read_to_string(
        app.join("crates/routes/ledger/migrations/postgres/0001_create_tables.sql"),
    )
    .unwrap();
    assert!(
        pg.contains("\"fk_transfers_from_account_id\"")
            && pg.contains("\"fk_transfers_to_account_id\"")
            && pg.contains("\"fk_comments_parent_id\""),
        "postgres must name the three FK constraints distinctly:\n{pg}"
    );

    // gen-tests the module (the ledger suite carries the list/show read probes).
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "gen-tests", "--module", "ledger"])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "gen-tests ledger: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    // RED: the stub handlers (500) fail the generated read suite.
    let red = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["test", "--workspace", "--no-fail-fast"])
        .output()
        .unwrap();
    assert!(!red.status.success(), "stub handlers must fail the suite");

    // Implement the correct GET-only handlers.
    install_handler(
        &app,
        "crates/routes/ledger/src/handlers.rs",
        FK_ALIAS_HANDLERS,
    );

    // GREEN: the aliased-fk model compiles and the read suite passes.
    let green = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["test", "--workspace"])
        .status()
        .unwrap();
    assert!(
        green.success(),
        "the correct handlers must satisfy the generated read suite"
    );

    // The full gate holds on the implemented app.
    let out = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["--json", "check"])
        .output()
        .unwrap();
    let payload: serde_json::Value = serde_json::from_slice(&out.stdout).expect("one JSON doc");
    assert_eq!(
        payload["ok"], true,
        "diagnostics: {}",
        payload["diagnostics"]
    );
}

/// A create-surfaced sibling of `FK_ALIAS_LEDGER` (issue #179): the same
/// two-aliased-fk `Transfer belongs_to Account as from_account / as to_account`
/// pair, with `create_account` + `create_transfer` POST endpoints so the
/// two-aliased-fk INSERT can be driven live. Kept separate so the GET-only
/// `fk_alias_two_refs_and_self_ref_go_green_on_a_correct_scaffold` fixture stays
/// byte-identical; the self-referential `Comment` is dropped as irrelevant to
/// the INSERT proof.
const FK_ALIAS_LEDGER_CREATE: &str = r#"{
  "name": "ledger-api",
  "contract_version": 1,
  "dependencies": ["db"],
  "modules": [
    { "name": "ledger",
      "entities": [
        { "name": "Account", "fields": [{ "name": "name", "type": "string" }] },
        { "name": "Transfer",
          "belongs_to": [
            { "entity": "Account", "as": "from_account" },
            { "entity": "Account", "as": "to_account" }
          ],
          "fields": [{ "name": "amount", "type": "integer" }] }
      ],
      "endpoints": [
        { "operation_id": "create_account", "method": "POST", "path": "/accounts",
          "success": { "status": 201, "entity": "Account" } },
        { "operation_id": "show_account", "method": "GET", "path": "/accounts/{id}",
          "success": { "status": 200, "entity": "Account" } },
        { "operation_id": "create_transfer", "method": "POST", "path": "/transfers",
          "success": { "status": 201, "entity": "Transfer" } },
        { "operation_id": "show_transfer", "method": "GET", "path": "/transfers/{id}",
          "success": { "status": 200, "entity": "Transfer" } }
      ] }
  ]
}"#;

/// Correct create/read handlers: the two-aliased-fk INSERT reads BOTH aliased
/// fk columns straight off the request body and persists them distinctly.
const FK_ALIAS_CREATE_HANDLERS: &str = r#"//! Correct #119 create/read handlers: the two-aliased-fk INSERT run live.
use super::model::*;
use super::repo::*;
use jerrycan::prelude::*;

pub(crate) async fn create_account(
    repo: Dep<AccountRepo>,
    Json(body): Json<Account>,
) -> Result<Created<Account>> {
    let id = repo.insert(Account { id: body.id, name: body.name.clone() }).await?;
    Ok(Created(Account { id, name: body.name }))
}

pub(crate) async fn show_account(repo: Dep<AccountRepo>, Path(id): Path<i64>) -> Result<Json<Account>> {
    repo.get(id).await?.map(Json).ok_or_else(Error::not_found)
}

pub(crate) async fn create_transfer(
    repo: Dep<TransferRepo>,
    Json(body): Json<Transfer>,
) -> Result<Created<Transfer>> {
    let id = repo
        .insert(Transfer {
            id: body.id,
            from_account_id: body.from_account_id,
            to_account_id: body.to_account_id,
            amount: body.amount,
        })
        .await?;
    Ok(Created(Transfer {
        id,
        from_account_id: body.from_account_id,
        to_account_id: body.to_account_id,
        amount: body.amount,
    }))
}

pub(crate) async fn show_transfer(repo: Dep<TransferRepo>, Path(id): Path<i64>) -> Result<Json<Transfer>> {
    repo.get(id).await?.map(Json).ok_or_else(Error::not_found)
}
"#;

/// Issue #179: the two-aliased-fk INSERT (#119) proven END TO END, live over HTTP.
/// The GET-only sibling above only asserts the migration SQL; the INSERT path
/// (seeding a row under BOTH `from_account_id` and `to_account_id`) was never run.
/// Here the app scaffolds, the correct insert handlers COMPILE, and — served on a
/// real port over a fresh sqlite file — two `Account` rows are POSTed, then a
/// `Transfer` referencing BOTH via the two DISTINCT aliased fks: it must 201 and
/// the persisted row (GET round-trip) must carry the two distinct fk values.
///
/// The hand-driven POST (not the generated create probe) is deliberate: the
/// generated happy-path probe posts `{}`, which cannot express the two required
/// aliased fk values nor seed the referenced accounts — so it is an AGENT-TODO
/// stub for this shape, not a valid INSERT proof. Framework code is untouched;
/// this is coverage of already-shipped #119 behaviour.
#[test]
#[ignore = "heavy: scaffold + build + serve + live two-aliased-fk INSERT over HTTP (#119/#179)"]
fn fk_alias_two_refs_insert_persists_both_aliased_fks_live() {
    let tmp = tempfile::tempdir().unwrap();
    let design = tmp.path().join("design.json");
    std::fs::write(&design, FK_ALIAS_LEDGER_CREATE).unwrap();
    let app = tmp.path().join("ledger-api");
    let dep = format!(
        "jerrycan = {{ path = \"{}\", default-features = false }}",
        repo_root().join("crates/jerrycan").display()
    );
    let st = Command::new(env!("CARGO_BIN_EXE_jerrycan"))
        .env("JERRYCAN_FRAMEWORK_DEP", &dep)
        .args(["new"])
        .arg(&app)
        .arg("--design")
        .arg(&design)
        .status()
        .unwrap();
    assert!(st.success(), "the fk-alias create design must scaffold");
    common::isolate_app_bin(&app);

    install_handler(
        &app,
        "crates/routes/ledger/src/handlers.rs",
        FK_ALIAS_CREATE_HANDLERS,
    );

    // Compile the app binary (proves the two-aliased-fk insert handlers build
    // against the generated aliased Model/repo) before serving it.
    let build = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .args(["build", "-p", "app"])
        .status()
        .unwrap();
    assert!(build.success(), "the app with insert handlers must compile");

    // Serve live over a fresh sqlite file (so migrations run clean and account
    // ids start at 1); `mode=rwc` lets sqlx CREATE the file.
    let port = pick_port();
    let addr = format!("127.0.0.1:{port}");
    let db_file = app.join("live.db");
    let _ = std::fs::remove_file(&db_file);
    let db_url = format!("sqlite://{}?mode=rwc", db_file.display());
    let mut server = Command::new("cargo")
        .current_dir(&app)
        .env("CARGO_TARGET_DIR", common::shared_app_target())
        .env("JERRYCAN_ADDR", &addr)
        .env("JERRYCAN_SECRET", "a-very-long-development-secret-string!!")
        .env("JERRYCAN_DATABASE_URL", &db_url)
        .args(["run", "-p", "app"])
        .spawn()
        .unwrap();

    // Drive the battery; ALWAYS kill the server afterwards, even on a panic.
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        await_listen(&addr, 180);

        // Seed two DISTINCT accounts (ids assigned by the DB, read from the
        // responses so the proof never assumes the autoincrement values).
        let a1 = http_post_json(&addr, "/ledger/accounts", r#"{"name":"alice"}"#);
        assert_eq!(http_status(&a1), 201, "create account A must 201:\n{a1}");
        let from_id = http_json_body(&a1)["id"].as_i64().expect("account A id");
        let a2 = http_post_json(&addr, "/ledger/accounts", r#"{"name":"bob"}"#);
        assert_eq!(http_status(&a2), 201, "create account B must 201:\n{a2}");
        let to_id = http_json_body(&a2)["id"].as_i64().expect("account B id");
        assert_ne!(from_id, to_id, "the two accounts must be distinct rows");

        // The two-aliased-fk INSERT: a Transfer referencing BOTH accounts.
        let body =
            format!(r#"{{"from_account_id":{from_id},"to_account_id":{to_id},"amount":100}}"#);
        let created = http_post_json(&addr, "/ledger/transfers", &body);
        assert_eq!(
            http_status(&created),
            201,
            "the two-aliased-fk INSERT must 201:\n{created}"
        );
        let created = http_json_body(&created);
        assert_eq!(
            created["from_account_id"].as_i64(),
            Some(from_id),
            "created transfer echoes from_account_id"
        );
        assert_eq!(
            created["to_account_id"].as_i64(),
            Some(to_id),
            "created transfer echoes to_account_id"
        );

        // Round-trip: the PERSISTED row carries the two distinct aliased fks.
        let tid = created["id"].as_i64().expect("transfer id");
        let got = http_json_body(&http_get(&addr, &format!("/ledger/transfers/{tid}")));
        assert_eq!(
            got["from_account_id"].as_i64(),
            Some(from_id),
            "persisted from_account_id"
        );
        assert_eq!(
            got["to_account_id"].as_i64(),
            Some(to_id),
            "persisted to_account_id"
        );
        assert_ne!(
            got["from_account_id"], got["to_account_id"],
            "the two aliased fks persist as DISTINCT values: {got}"
        );
    }));
    let _ = server.kill();
    let _ = server.wait();
    if let Err(panic) = result {
        std::panic::resume_unwind(panic);
    }
}

// Small helpers for the deploy-anywhere test (no earlier-phase equivalents exist
// in this file; the auth_observe test inlines its own closures).
fn pick_port() -> u16 {
    std::net::TcpListener::bind("127.0.0.1:0")
        .unwrap()
        .local_addr()
        .unwrap()
        .port()
}
fn tool_present(tool: &str) -> bool {
    Command::new(tool)
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}
/// kubectl rejects `--version`; its client-only probe is `version --client`.
fn kubectl_present() -> bool {
    Command::new("kubectl")
        .args(["version", "--client"])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}
/// `kubectl apply --dry-run=client` still discovers API resources from the
/// cluster, so the dry-run leg only runs when a cluster is reachable.
fn cluster_reachable() -> bool {
    Command::new("kubectl")
        .args(["cluster-info"])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}
fn await_listen(addr: &str, secs: u64) {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(secs);
    while std::time::Instant::now() < deadline {
        if std::net::TcpStream::connect(addr).is_ok() {
            return;
        }
        std::thread::sleep(std::time::Duration::from_millis(400));
    }
    panic!("nothing listening on {addr} after {secs}s");
}
fn http_get(addr: &str, path: &str) -> String {
    let mut s = std::net::TcpStream::connect(addr).unwrap();
    s.write_all(format!("GET {path} HTTP/1.1\r\nHost: l\r\nConnection: close\r\n\r\n").as_bytes())
        .unwrap();
    let mut buf = Vec::new();
    let _ = s.read_to_end(&mut buf);
    String::from_utf8_lossy(&buf).into_owned()
}
/// POST a JSON body over raw HTTP and return the whole response (status line +
/// headers + body). No auth header — the fk-alias ledger design is unguarded.
fn http_post_json(addr: &str, path: &str, body: &str) -> String {
    let mut s = std::net::TcpStream::connect(addr).unwrap();
    let req = format!(
        "POST {path} HTTP/1.1\r\nHost: l\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
        body.len()
    );
    s.write_all(req.as_bytes()).unwrap();
    let mut buf = Vec::new();
    let _ = s.read_to_end(&mut buf);
    String::from_utf8_lossy(&buf).into_owned()
}
/// The numeric status of a raw HTTP response (`HTTP/1.1 201 Created` → 201).
fn http_status(raw: &str) -> u16 {
    raw.split_whitespace()
        .nth(1)
        .and_then(|s| s.parse().ok())
        .unwrap_or_else(|| panic!("no status in response:\n{raw}"))
}
/// Parse the JSON body (everything past the header terminator) of a raw response.
fn http_json_body(raw: &str) -> serde_json::Value {
    let body = raw.split_once("\r\n\r\n").map(|x| x.1).unwrap_or("");
    serde_json::from_str(body.trim()).unwrap_or_else(|e| panic!("body not JSON ({e}):\n{raw}"))
}
/// True when `jerrycan package --binary` produced a static musl binary (so a
/// distroless/static runtime base is appropriate); false ⇒ a gnu host binary.
fn musl_built(app: &Path) -> bool {
    app.join("target/x86_64-unknown-linux-musl/release/app")
        .exists()
}