jerrycan 0.6.11

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
//! design module → tests/acceptance.rs (TOOL-owned). One success test per
//! endpoint, one test per generatable error case (404 on parameterized paths),
//! an AGENT TODO comment for the rest. Stubs fail everything (expected_failing
//! = test_count) — green = the design contract is implemented.

use super::design::*;

/// The JSON request-body fixture literal for a field. Enum fields (those with a
/// declared `values` set) use their FIRST declared value, so the generated
/// happy-path body satisfies the migration's `CHECK (... IN (...))` constraint
/// instead of tripping it with `"test-value"` (an opaque `JC0510` at run time).
/// A range/length-constrained field (#80) derives an IN-RANGE value the same
/// way, so the happy-path body clears the deserialize validator AND the CHECK.
/// Mirrors `seed_sql_value` on the SQL seed side — the two must agree.
fn fixture_value(f: &Field) -> String {
    if let Some(first) = f.values.as_ref().and_then(|v| v.first()) {
        return format!("\"{first}\"");
    }
    // #80: both branches gate on a constraint being PRESENT — an unconstrained
    // field keeps the exact literals below (byte-identity for every existing
    // design).
    if has_int_range(f) {
        return int_literal(clamp_int(1, f));
    }
    if has_len_range(f) {
        return format!("\"{}\"", constrained_fixture_string(f));
    }
    match f.field_type {
        FieldType::String => "\"test-value\"",
        FieldType::Integer => "1",
        FieldType::Float => "1.0",
        FieldType::Boolean => "false",
        FieldType::Datetime => "\"2026-01-01T00:00:00Z\"",
        // A FIXED valid v4 (issue #48a): the design's declared format types must
        // yield format-VALID fixtures so the endpoint's own happy-path probe is
        // greenable against a handler that validates the format. The nil uuid
        // (`0000…`) is a valid string but NOT a valid v4 — a v4 validator would
        // reject it, making the 2xx probe un-greenable. datetime above is already
        // valid RFC3339. (email/url are NOT design-contract format types — they
        // ride on `string` via a hand-written `Valid` impl the generator can't
        // see; that case is `probe:"skip"`, see docs/ai/00-designing.md.)
        FieldType::Uuid => "\"f47ac10b-58cc-4372-a567-0e02b2c3d479\"",
        FieldType::Json => "{}",
    }
    .to_string()
}

/// True when the field declares an integer range constraint (#80) — the gate
/// every constraint-aware fixture/seed branch keys on, so an unconstrained
/// field's output stays byte-identical.
fn has_int_range(f: &Field) -> bool {
    matches!(f.field_type, FieldType::Integer) && (f.min.is_some() || f.max.is_some())
}

/// True when the field declares a string length constraint (#80). A `values`
/// field never carries one (JC0552 refuses the combination) and takes the enum
/// branch first anyway.
fn has_len_range(f: &Field) -> bool {
    matches!(f.field_type, FieldType::String) && (f.min_len.is_some() || f.max_len.is_some())
}

/// Render a constrained-integer value for embedding inside a
/// `serde_json::json!` probe body (#80): `json!` types a bare numeric literal
/// as `i32`, so a value outside i32 range (a bound like `max: 4102444800`)
/// would be a HARD compile error in the generated suite under rustc's
/// deny-by-default `overflowing_literals`. Suffix `i64` exactly when the
/// value is outside i32 range; everything in-range stays an unsuffixed
/// literal (byte-identity for every existing design). The `id` fixture never
/// routes through here — JC0552 refuses constraints on the pk — so a suffixed
/// value can never leak into a URL path.
fn int_literal(v: i64) -> String {
    if v < i64::from(i32::MIN) || v > i64::from(i32::MAX) {
        format!("{v}i64")
    } else {
        v.to_string()
    }
}

/// Clamp `v` into the field's declared `[min, max]` (#80): below-min snaps to
/// min, above-max to max — the NEAREST in-range value. Identity for an
/// unconstrained field.
fn clamp_int(v: i64, f: &Field) -> i64 {
    let v = match f.min {
        Some(mn) if v < mn => mn,
        _ => v,
    };
    match f.max {
        Some(mx) if v > mx => mx,
        _ => v,
    }
}

/// The k-th distinct in-range value for a `unique` range-constrained integer
/// field (#80): k = 0 is the fixture anchor (`clamp(1)`), higher k walks up
/// toward `max` and continues DOWNWARD from the anchor once the top of the
/// range is exhausted. JC0552 refuses a unique field whose cardinality is
/// below 3, so k <= 2 (the probe fixture + the tenant-1 and tenant-2 seeds)
/// always yields three distinct in-range values here; the saturating
/// arithmetic + final clamp keep even an unvalidated design's output in-range.
fn kth_in_range(f: &Field, k: i64) -> i64 {
    let anchor = clamp_int(1, f);
    let headroom = f.max.unwrap_or(i64::MAX).saturating_sub(anchor);
    let v = if k <= headroom {
        anchor.saturating_add(k)
    } else {
        anchor.saturating_sub(k - headroom)
    };
    clamp_int(v, f)
}

/// Fit `base` into `[min_len, max_len]` (#80): truncate to `max_len` CODE
/// POINTS (`.chars()`, the same semantics the generated validator and the
/// OpenAPI minLength/maxLength use — never `.len()` bytes) when too long, pad
/// with 'a' up to `min_len` when too short. JC0552's 4096 `min_len` ceiling
/// bounds the padding.
fn fit_string(base: &str, min_len: Option<u64>, max_len: Option<u64>) -> String {
    let len = base.chars().count() as u64;
    if let Some(mx) = max_len
        && len > mx
    {
        return base.chars().take(mx as usize).collect();
    }
    if let Some(mn) = min_len
        && len < mn
    {
        return format!("{base}{}", "a".repeat((mn - len) as usize));
    }
    base.to_string()
}

/// The in-range plain-string value for a length-constrained field (#80):
/// `test-value` when it fits `[min_len, max_len]`, `"a".repeat(min_len)` when
/// too short, a truncation to `max_len` code points when too long. Shared by
/// `fixture_value` and the non-unique seed literals so the HTTP fixture and
/// the SQL seed stay in agreement (the invariant on `fixture_value`).
fn constrained_fixture_string(f: &Field) -> String {
    const BASE: &str = "test-value";
    if let Some(mn) = f.min_len
        && (BASE.chars().count() as u64) < mn
    {
        return "a".repeat(mn as usize);
    }
    fit_string(BASE, f.min_len, f.max_len)
}

/// The Nth tenant's seed string for a length-constrained field (#80), derived
/// so the fixture (`test-value`…), the tenant-1 unique seed (`seed-…`) and the
/// tenant-2 seed stay DISTINCT after fitting: when truncation would cut the
/// trailing `-{n}` discriminator off the shared "test-value" prefix (colliding
/// with the fixture), the discriminator is front-loaded instead. The distinct
/// leading characters ('t' / 's' / a digit) survive any `max_len >= 1`; a
/// `unique` field with `max_len: 0` is refused at design time (JC0552).
fn constrained_seed_string_n(f: &Field, n: u32) -> String {
    let natural = format!("test-value-{n}");
    let base = if f
        .max_len
        .is_some_and(|mx| (natural.chars().count() as u64) > mx)
    {
        format!("{n}-test-value")
    } else {
        natural
    };
    fit_string(&base, f.min_len, f.max_len)
}

/// The fixture literal for a belongs_to fk column, valued at the SEEDED tenant
/// (id 1): "1" for an integer/synthetic key, the string fixture for a text key.
/// Mirrors the seed in `tenant_seed` so the generated body points at a row the
/// guard can actually resolve.
fn fk_fixture_value(design: &Design, target: &str) -> &'static str {
    match design.target_key_rust_type(target) {
        "String" => "\"1\"",
        _ => "1",
    }
}

/// The server-owned-FK omission (issue #34), db-gated (issue #43) so all three
/// surfaces agree: genroute only emits the `{Entity}Request` DTO in db mode (a
/// memory-mode struct carries no fk columns), so a memory-mode probe must NOT drop
/// `user_id` either — otherwise the probe body and the OpenAPI request schema would
/// diverge from the entity genroute actually deserializes. The fk it carries in
/// memory mode is serde-ignored (the struct has no such field), matching pre-#34
/// behavior; the omission is a db-mode contract only.
fn omits_identity_fk(design: &Design, unit: &ModuleDesign, ep: &Endpoint) -> bool {
    design.wants_db() && design.endpoint_omits_identity_fk(unit, ep)
}

/// `omit_identity_fk` is the server-owned-FK rule (issue #34): true for a
/// GUARDED endpoint's body in an auth design — its `user_id` fk is dropped
/// because the handler injects the session user's id, and the probe must prove
/// a clean client that OMITS it reaches the designed success (not a 422).
fn fixture_json(
    design: &Design,
    m: &ModuleDesign,
    entity: &str,
    omit_identity_fk: bool,
    bad: Option<(&str, &str)>,
    keep_defaults: bool,
) -> String {
    let Some(e) = m.entities.iter().find(|e| e.name == entity) else {
        return "{}".to_string();
    };
    // belongs_to fk columns first: a tenant-owned entity's body must carry the
    // fk (NOT NULL) so the handler's Json<Entity> deserializes (else 422 before
    // the stub), valued at the seeded tenant so a scoped query can resolve it.
    // The identity fk (`user_id`) is dropped on guarded bodies (issue #34); a
    // path-redundant parent fk (`habit_id` under `/{habit_id}/checkins`) is
    // dropped because the probe carries it in the URL, not the body (issue #53b).
    let path_fks = design.entity_path_fk_columns(entity);
    let fks = e
        .belongs_to
        .iter()
        .filter(|b| !(omit_identity_fk && Design::is_identity_fk(b)))
        .filter(|b| !path_fks.contains(&Design::fk_column(&b.entity)))
        .map(|b| {
            format!(
                "\"{}\": {}",
                Design::fk_column(&b.entity),
                fk_fixture_value(design, &b.entity)
            )
        });
    // A STATIC `default` field (issue #53a) is server-owned on CREATE: the probe
    // omits it so the minimal client body proves the server applies the default (not
    // a 422). On UPDATE the field is client-settable (issue #85 D1), so an update
    // probe KEEPS it — the body must match `{Entity}UpdateRequest`, which requires
    // it. A `now`-default timestamp (#110) is dropped from BOTH DTOs (server-owned,
    // immutable), so both probes omit it — inert for designs without the sentinel.
    let cols = e
        .fields
        .iter()
        .filter(|f| (keep_defaults || f.default.is_none()) && !Design::field_is_now_default(f))
        .map(|f| {
            // The reject probe corrupts ONE field to an out-of-range literal —
            // the enum sentinel (issue #47) or a #80 constraint violation;
            // every other field keeps its valid fixture value so the ONLY
            // reason for a 422 is that field.
            let value = match bad {
                Some((name, literal)) if name == f.name => literal.to_string(),
                _ => fixture_value(f),
            };
            format!("\"{}\": {}", f.name, value)
        });
    let fields = fks.chain(cols).collect::<Vec<_>>().join(", ");
    format!("{{{fields}}}")
}

/// The POST creator (with a body) mounted at a bare collection `path` — the route
/// that seeds a row addressable under `path/{id}`. `creator_at(m, "/")` is the
/// module-root creator; `creator_at(m, "/tasks")` seeds the second entity (#51).
fn creator_at<'a>(m: &'a ModuleDesign, path: &str) -> Option<&'a Endpoint> {
    m.endpoints
        .iter()
        .find(|ep| ep.method == HttpMethod::POST && ep.path == path && ep.request_body.is_some())
}

/// The POST creator (with a body) whose request body is `entity`, at a bare
/// collection path — used to seed a belongs_to PARENT before its dependent (#51).
fn creator_for_entity<'a>(m: &'a ModuleDesign, entity: &str) -> Option<&'a Endpoint> {
    m.endpoints.iter().find(|ep| {
        ep.method == HttpMethod::POST
            && param_count(ep) == 0
            && ep
                .request_body
                .as_ref()
                .is_some_and(|rb| rb.entity == entity)
    })
}

fn param_count(ep: &Endpoint) -> usize {
    ep.path.matches('{').count()
}

/// The collection path a `/{id}` endpoint acts under: its path with the trailing
/// `/{param}` segment removed (`/tasks/{id}` → `/tasks`, `/{id}` → `/`). The POST
/// creator at THIS path seeds the row the probe addresses (#51).
fn collection_path(ep: &Endpoint) -> String {
    let p = &ep.path;
    let brace = p.rfind('{').expect("parameterized path");
    let cut = p[..brace].rfind('/').unwrap_or(0);
    if cut == 0 {
        "/".to_string()
    } else {
        p[..cut].to_string()
    }
}

/// The fully-qualified collection URL a creator posts to. For the root collection
/// (`"/"`) this is byte-identical to the pre-#51 module-root seed (`{base}/`), so
/// a one-entity module's output is unchanged (conformance no-drift).
fn collection_url(base: &str, coll: &str) -> String {
    if coll == "/" {
        format!("{base}/")
    } else {
        format!("{}{}", base.trim_end_matches('/'), coll)
    }
}

/// One creator POST that seeds a row, threading the credential in auth mode for a
/// guarded creator. Byte-identical to the pre-#51 module-root seed line for the
/// root-collection case.
fn seed_line(
    design: &Design,
    unit: &ModuleDesign,
    url: &str,
    creator: &Endpoint,
    auth: bool,
    comment: &str,
) -> String {
    let body = fixture_json(
        design,
        unit,
        &creator
            .request_body
            .as_ref()
            .expect("creator has body")
            .entity,
        omits_identity_fk(design, unit, creator),
        None,
        false, // seed via the creator (POST) — a create body omits defaults
    );
    if auth && creator.is_guarded() {
        let hk = design.test_auth_header();
        format!(
            "    t.post_json_with(\"{url}\", &serde_json::json!({body}), &[(\"{hk}\", &test_cookie())]).await; {comment}\n"
        )
    } else {
        format!("    t.post_json(\"{url}\", &serde_json::json!({body})).await; {comment}\n")
    }
}

/// Seed statements + the id literal for a `/{id}` probe (#51): create the entity
/// THIS endpoint operates on — via the POST creator at the endpoint's collection
/// path — preceded by each belongs_to PARENT (via its own creator) so an enforced
/// intra-module FK resolves. Returns None when the target entity has no creator
/// route (the caller emits an AGENT TODO rather than a guaranteed-red probe).
/// The identity fk (handler-injected) and the tenancy entity (seeded by
/// `tenant_seed`) are never re-created here. Byte-identical to the pre-#51 single
/// module-root seed for a one-entity module (collection `"/"`, no such parents).
fn seed_for_id_probe(
    design: &Design,
    unit: &ModuleDesign,
    base: &str,
    ep: &Endpoint,
    auth: bool,
) -> Option<(String, String)> {
    let coll = collection_path(ep);
    let creator = creator_at(unit, &coll)?;
    let entity_name = &creator
        .request_body
        .as_ref()
        .expect("creator has body")
        .entity;
    let entity = unit.entities.iter().find(|e| &e.name == entity_name)?;

    let mut seed = String::new();
    let mut seen = vec![entity.name.clone()];
    seed_parents(design, unit, base, entity, auth, &mut seed, &mut seen);
    seed.push_str(&seed_line(
        design,
        unit,
        &collection_url(base, &coll),
        creator,
        auth,
        "// seed id 1",
    ));

    let seed_id = entity
        .fields
        .iter()
        .find(|f| f.name == "id")
        .map(|f| fixture_value(f).trim_matches('"').to_string())
        .unwrap_or_else(|| "1".to_string());
    Some((seed, seed_id))
}

/// True when the POST creator that would seed this `/{id}` endpoint's row is
/// marked `probe: skip` (issue #68). A hand-written validator on that creator
/// rejects the generated seed fixture, so seeding a sibling `/{id}` probe through
/// it would 404 on a CORRECT handler. Only valid for a parameterized path (the
/// caller gates on `param_count(ep) == 1`). Mirrors `seed_for_id_probe`'s creator
/// lookup so the two never disagree about which creator seeds the probe.
fn seed_creator_is_skipped(unit: &ModuleDesign, ep: &Endpoint) -> bool {
    creator_at(unit, &collection_path(ep)).is_some_and(|c| c.probe == ProbePolicy::Skip)
}

/// Append seed lines for `entity`'s belongs_to PARENTS (grandparents first), so a
/// dependent row's fk points at a real parent row. Skips the identity fk (the
/// handler injects it), the tenancy entity (already seeded), a parent with no
/// creator in this module (a cross-module target is an UNENFORCED relation — the
/// fk fixture's `1` needs no row), and already-seeded entities (cycle guard).
fn seed_parents(
    design: &Design,
    unit: &ModuleDesign,
    base: &str,
    entity: &Entity,
    auth: bool,
    seed: &mut String,
    seen: &mut Vec<String>,
) {
    let tenancy = design.tenancy.as_ref().map(|t| t.entity.as_str());
    for b in &entity.belongs_to {
        if Design::is_identity_fk(b)
            || Some(b.entity.as_str()) == tenancy
            || seen.contains(&b.entity)
        {
            continue;
        }
        let (Some(parent_creator), Some(parent)) = (
            creator_for_entity(unit, &b.entity),
            unit.entities.iter().find(|e| e.name == b.entity),
        ) else {
            continue;
        };
        seen.push(b.entity.clone());
        seed_parents(design, unit, base, parent, auth, seed, seen);
        seed.push_str(&seed_line(
            design,
            unit,
            &collection_url(base, &parent_creator.path),
            parent_creator,
            auth,
            &format!("// seed parent {} id 1", parent.name),
        ));
    }
}

/// True when this endpoint's SUCCESS requires a credential/signature the generator
/// cannot synthesize, so a minimal-body probe can never reach the designed success
/// status. Two shapes: (a) a signature-authenticated webhook (Stripe-style — a bad
/// or missing signature 400/401s), and (b) a NON-session endpoint that declares a
/// 401/403 (a `public` login 401s bad creds; an api-key route 401/403s a missing
/// key). A session-GUARDED endpoint is excluded: the generator threads its cookie,
/// so its success test IS greenable. For these gated endpoints we emit an AGENT
/// TODO instead of an un-greenable `_returns_<status>` assertion.
fn endpoint_is_credential_gated(ep: &Endpoint) -> bool {
    ep.declares_signature_auth()
        || (!ep.is_guarded() && ep.errors.iter().any(|e| e.status == 401 || e.status == 403))
}

struct TestOut {
    code: String,
    todos: Vec<String>,
    count: usize,
    /// Issue #47: enum "reject" tests PASS on stubs (an out-of-range value 422s at
    /// deserialization, before the handler runs), so they are subtracted from
    /// `expected_failing` — they are not part of the RED-on-stubs baseline.
    reject: usize,
    /// Auth mode: success tests on guarded endpoints carry a session cookie and
    /// every guarded endpoint also gets a no-cookie 401 test.
    auth: bool,
}

/// A value guaranteed to be OUT-OF-RANGE for any declared enum `values` set — the
/// reject probe sends it in an enum field to prove the request boundary answers
/// 422 (JC0422) before the DB (issue #47).
const ENUM_REJECT_SENTINEL: &str = "__invalid_enum_value__";

/// The first enum (`values`) field of an endpoint's request-body entity that is
/// present on the wire — the field the reject probe corrupts to an out-of-range
/// value. A defaulted enum field (issue #53a) is omitted from the request DTO, so
/// a bad value would be ignored, not 422'd — skip it (there is nothing to reject
/// at the boundary).
fn first_enum_field<'a>(unit: &'a ModuleDesign, entity: &str) -> Option<&'a str> {
    unit.entities
        .iter()
        .find(|e| e.name == entity)
        .and_then(|e| {
            e.fields
                .iter()
                .find(|f| f.values.is_some() && f.default.is_none())
        })
        .map(|f| f.name.as_str())
}

/// The largest `max_len` for which the reject probe materializes an over-max
/// string at test run time (`"a".repeat(max_len + 1)`) — matches JC0552's 4096
/// `min_len` fixture ceiling, so a generated suite never allocates beyond
/// ~4KB per probe. Above it the probe falls back to the under-`min_len`
/// direction, or (min_len absent/0) emits nothing — a bound too large to
/// violate cheaply goes unprobed (0.6.5 T1 review, Important-b).
const REJECT_LEN_CAP: u64 = 4096;

/// The out-of-range literal the #80 reject probe sends for a constrained
/// field, or None when NO rejectable direction exists. Directions mirror
/// exactly the bounds the generated validator enforces (genroute's
/// `bounds_rules` gates the vacuous spellings `min: i64::MIN`,
/// `max: i64::MAX`, `min_len: 0`, `max_len: u64::MAX` out of the runtime
/// check — and here the checked arithmetic fails on precisely those, so the
/// probe never asserts a 422 the validator won't produce):
/// - integer: `max + 1` (checked), falling back to `min - 1` (checked),
///   rendered via [`int_literal`] so an out-of-i32-range value compiles
///   inside `serde_json::json!`;
/// - string: `"a".repeat(max_len + 1)` — an EXPRESSION, valid inside
///   `serde_json::json!`, so the generated file never embeds a giant literal —
///   capped by [`REJECT_LEN_CAP`], falling back to `"a".repeat(min_len - 1)`.
fn constraint_reject_literal(f: &Field) -> Option<String> {
    match f.field_type {
        FieldType::Integer => f
            .max
            .and_then(|mx| mx.checked_add(1))
            .or_else(|| f.min.and_then(|mn| mn.checked_sub(1)))
            .map(int_literal),
        // A `values` field rides the enum reject probe instead (and a
        // values+length combination is refused at design time, JC0552).
        FieldType::String if f.values.is_none() => {
            if let Some(mx) = f.max_len
                && mx <= REJECT_LEN_CAP
            {
                return Some(format!("\"a\".repeat({})", mx + 1));
            }
            f.min_len
                .filter(|&mn| mn >= 1)
                .map(|mn| format!("\"a\".repeat({})", mn - 1))
        }
        _ => None,
    }
}

/// The first request-body field carrying a #80 range/length constraint with a
/// derivable out-of-range literal — the field the constraint reject probe
/// corrupts. A defaulted field is skipped for the same reason as
/// [`first_enum_field`]: it is omitted from the create request DTO, so a bad
/// value would be dropped, not 422'd. A constrained field with no rejectable
/// direction (both extremes vacuous) is passed over — nothing violates its
/// bound, so there is nothing to probe.
fn first_constraint_reject<'a>(unit: &'a ModuleDesign, entity: &str) -> Option<(&'a str, String)> {
    unit.entities
        .iter()
        .find(|e| e.name == entity)
        .and_then(|e| {
            e.fields
                .iter()
                .filter(|f| f.default.is_none() && (has_int_range(f) || has_len_range(f)))
                .find_map(|f| constraint_reject_literal(f).map(|lit| (f.name.as_str(), lit)))
        })
}

/// A request expression `t.<verb>(...)`. In auth mode a guarded endpoint threads
/// the test cookie via the `_with` helper variants; otherwise the plain verb.
fn request_expr(
    design: &Design,
    unit: &ModuleDesign,
    ep: &Endpoint,
    path: &str,
    guarded_and_auth: bool,
    bad: Option<(&str, &str)>,
) -> String {
    let body = || {
        ep.request_body
            .as_ref()
            // The omission keys on the ENDPOINT being guarded (the design-level
            // rule), not on whether THIS request threads a cookie — a guarded
            // endpoint's 401 probe still sends the guarded body shape.
            .map(|rb| {
                fixture_json(
                    design,
                    unit,
                    &rb.entity,
                    omits_identity_fk(design, unit, ep),
                    bad,
                    // An UPDATE (PUT/PATCH) probe keeps `default` fields so the body
                    // matches `{Entity}UpdateRequest` (issue #85 D1); a create omits them.
                    ep.method.is_update(),
                )
            })
            .unwrap_or_else(|| "{}".to_string())
    };
    if guarded_and_auth {
        // The test credential header follows the auth model: `cookie` (session)
        // or `authorization` (jwt Bearer) — issue #29. `test_cookie()` returns the
        // matching header value.
        let cookie = format!("&[(\"{}\", &test_cookie())]", design.test_auth_header());
        match ep.method {
            HttpMethod::GET => format!("t.get_with(\"{path}\", {cookie}).await"),
            HttpMethod::DELETE => format!("t.delete_with(\"{path}\", {cookie}).await"),
            HttpMethod::POST => format!(
                "t.post_json_with(\"{path}\", &serde_json::json!({}), {cookie}).await",
                body()
            ),
            HttpMethod::PUT => format!(
                "t.put_json_with(\"{path}\", &serde_json::json!({}), {cookie}).await",
                body()
            ),
            HttpMethod::PATCH => format!(
                "t.patch_json_with(\"{path}\", &serde_json::json!({}), {cookie}).await",
                body()
            ),
        }
    } else {
        match ep.method {
            HttpMethod::GET => format!("t.get(\"{path}\").await"),
            HttpMethod::DELETE => format!("t.delete(\"{path}\").await"),
            HttpMethod::POST => {
                format!(
                    "t.post_json(\"{path}\", &serde_json::json!({})).await",
                    body()
                )
            }
            HttpMethod::PUT => {
                format!(
                    "t.put_json(\"{path}\", &serde_json::json!({})).await",
                    body()
                )
            }
            HttpMethod::PATCH => {
                format!(
                    "t.patch_json(\"{path}\", &serde_json::json!({})).await",
                    body()
                )
            }
        }
    }
}

/// The accumulated mount `base` with every mount-INHERITED path param substituted
/// by the seeded parent id `1` (issue #81). A subroute-mounted module carries its
/// ancestor's param in the MOUNT prefix (`/workspaces/{workspace_id}/channels`),
/// not in `ep.path`; left literal, the router 400/404s the whole group and a
/// correct app's tests are red by construction. Every `{param}` in `base` is a
/// mount-inherited ancestor fk (or parent pk) whose row app()'s tenant chain seeds
/// at id 1 (`tenant_seed`/`seed_tenant1_chain` — the same rows the isolation test's
/// `cbase` pins), so substituting each to `1` makes the probe URL concrete AND
/// resolvable. The endpoint's OWN `/{id}` param lives in `ep.path` (appended AFTER
/// `base`, so never touched here) and is substituted separately by the seeded row
/// id. A FLAT mount carries no `{param}`, so this is the identity — every
/// non-nested design stays byte-identical. Also reused on a FULL path to pin an
/// endpoint's own `{param}`s for the seedless 401 guard probes (issue #123b) —
/// the guard rejects before any id is looked up, so a literal `1` suffices.
fn concrete_mount_base(base: &str) -> String {
    let mut out = String::with_capacity(base.len());
    let mut rest = base;
    while let Some(open) = rest.find('{') {
        out.push_str(&rest[..open]);
        match rest[open..].find('}') {
            Some(rel_close) => {
                out.push('1');
                rest = &rest[open + rel_close + 1..];
            }
            // Unbalanced brace (never valid in a mount): emit the remainder verbatim.
            None => {
                out.push_str(&rest[open..]);
                return out;
            }
        }
    }
    out.push_str(rest);
    out
}

fn unit_tests(design: &Design, unit: &ModuleDesign, base: &str, out: &mut TestOut) {
    let auth = out.auth;
    // Resolve the FULL path per endpoint against a mount base whose inherited params
    // are pinned to the seeded parent id 1 (issue #81). The RAW `base` still threads
    // through the subroute recursion below so the accumulation stays intact.
    let cbase = concrete_mount_base(base);

    for ep in &unit.endpoints {
        let full_path = format!("{}{}", cbase.trim_end_matches('/'), ep.path);
        let fn_base = &ep.operation_id;
        let status = ep.success.status;
        // A public_read GET (#105) is emitted UNGUARDED regardless of its declared
        // `auth_required` (the shared `Design::endpoint_is_public_read_get` — the
        // same predicate genroute keys the handler on), so it must probe WITHOUT a
        // credential and must NOT get a 401 test: a no-cookie request to the public
        // feed correctly 200s, and asserting 401 would generate a permanently-RED
        // test on a correct app. A role-gated GET keeps its guard and its 401 probe.
        let guarded = auth && ep.is_guarded() && !design.endpoint_is_public_read_get(unit, ep);
        // Endpoints whose success needs a credential/signature the generator can't
        // supply (login, signed webhook, api-key route): no un-greenable success
        // probe — emit a TODO instead. Detected by heuristic OR declared
        // explicitly with `probe: skip` (issue #11) so a design the heuristic
        // misses can still reach `ok:true`. Heuristic shape (b) (a non-session
        // 401/403 route) is unguarded by definition, so it gets no 401 test;
        // heuristic shape (a) (a signature webhook) and a `probe: skip` endpoint
        // CAN be guarded — their 401 guard test still emits below (issue #123b).
        let probe_skip = ep.probe == ProbePolicy::Skip;
        let gated = endpoint_is_credential_gated(ep) || probe_skip;

        if gated {
            let reason = if probe_skip {
                "is marked `probe: skip` — the generator can't synthesize a credential for its success"
            } else {
                "authenticates via a credential/signature the generator can't supply"
            };
            // Issue #123b: dropping the un-greenable success probe must NOT also
            // drop the `_without_auth_is_401` guard test — that assertion is
            // GREENABLE (the generated guard rejects a credential-less request
            // before any handler logic) and deleting it silently un-tests a real
            // security guard. Any `{param}` is pinned to a literal id: a 401
            // rejection happens before the id is ever looked up, so no seed is
            // needed. The TODO then asks for the success test only; an UNGUARDED
            // gated endpoint (login, signed webhook) keeps the old ask — its
            // rejection is handler logic, not a generated guard.
            let ask = if guarded {
                "write its success test (with a valid credential) in your own test file; its `_without_auth_is_401` guard test is already generated"
            } else {
                "write its success test (with a valid credential) and its 401/403 rejection test in your own test file"
            };
            out.todos.push(format!(
                "// AGENT TODO: {fn_base} ({:?} {full_path}) {reason} — {ask}.",
                ep.method
            ));
            if guarded {
                push_401_test(
                    design,
                    out,
                    unit,
                    ep,
                    &concrete_mount_base(&full_path),
                    false,
                );
            }
        } else if param_count(ep) == 0 {
            let request = request_expr(design, unit, ep, &full_path, guarded, None);
            // A creator that echoes its entity must echo the id it was given —
            // catches inserts that return a backend default (0) instead.
            let id_echo = (ep.method == HttpMethod::POST)
                .then_some(ep.request_body.as_ref())
                .flatten()
                .filter(|rb| ep.success.entity.as_deref() == Some(rb.entity.as_str()))
                .and_then(|rb| unit.entities.iter().find(|e| e.name == rb.entity))
                .and_then(|e| e.fields.iter().find(|f| f.name == "id"))
                .map(|f| format!(
                    "    let body: serde_json::Value = serde_json::from_str(&res.text()).expect(\"json body\");\n    assert_eq!(body[\"id\"], serde_json::json!({}), \"design: created {} echoes its id\");\n",
                    fixture_value(f), ep.success.entity.as_deref().unwrap_or("entity")
                ))
                .unwrap_or_default();
            out.code.push_str(&format!(
                "#[tokio::test]\nasync fn {fn_base}_returns_{status}() {{\n    let t = app().await;\n    let res = {request};\n    assert_eq!(res.status().as_u16(), {status}, \"design: {fn_base} -> {status}; body: {{}}\", res.text());\n{id_echo}}}\n\n"
            ));
            out.count += 1;
            if guarded {
                push_401_test(design, out, unit, ep, &full_path, false);
            }
            // Issue #47: an enum request body gets an out-of-range reject probe.
            if let Some(field) = ep
                .request_body
                .as_ref()
                .and_then(|rb| first_enum_field(unit, &rb.entity))
            {
                push_enum_reject_test(design, out, unit, ep, &full_path, guarded, field);
            }
            // #80: a range/length-constrained request body gets one too.
            if let Some((field, literal)) = ep
                .request_body
                .as_ref()
                .and_then(|rb| first_constraint_reject(unit, &rb.entity))
            {
                push_constraint_reject_test(
                    design, out, unit, ep, &full_path, guarded, field, &literal,
                );
            }
        } else if param_count(ep) == 1 && seed_creator_is_skipped(unit, ep) {
            // Issue #68: the creator that would seed this `/{id}` probe is marked
            // `probe: skip` — a hand-written validator on it rejects the generated
            // fixture (JR4: url must start http/https), so the seed POST would fail
            // and every downstream sibling probe would 404 on a CORRECT handler.
            // Emit an AGENT TODO instead of a guaranteed-red probe (excluded from
            // expected_failing). The missing-id 404 probe below needs no seed, so it
            // still emits — the creator's validator never touches the getter.
            out.todos.push(format!(
                "// AGENT TODO: {fn_base} ({:?} {full_path}) — its seed creator is `probe: skip` (a hand-written validator rejects the generated fixture), so an auto-seeded {{id}} would 404. Seed a valid row and encode its success case in your own test file.",
                ep.method
            ));
            // Issue #123b: the guard test survives the skipped seed — the guard
            // rejects a credential-less request before the id lookup, so a
            // literal id stands in and no seeded row is needed.
            if guarded {
                push_401_test(
                    design,
                    out,
                    unit,
                    ep,
                    &concrete_mount_base(&full_path),
                    false,
                );
            }
        } else if param_count(ep) == 1 {
            // Issue #51: seed the row THIS `/{id}` endpoint addresses via ITS OWN
            // entity's creator (`POST /tasks` for `/tasks/{id}`), walking belongs_to
            // parents first — not the module-root creator, which would seed the
            // wrong entity and make the probe 404 on a CORRECT handler. Seeds/probes
            // resolve against the mount-substituted `cbase` (issue #81) so a nested
            // module's seed POST + `/{id}` probe both hit the concrete parent URL.
            if let Some((seed, seed_id)) = seed_for_id_probe(design, unit, &cbase, ep, auth) {
                let seeded_path = full_path.replacen(&regex_free_param(&ep.path), &seed_id, 1);
                let request = request_expr(design, unit, ep, &seeded_path, guarded, None);
                out.code.push_str(&format!(
                    "#[tokio::test]\nasync fn {fn_base}_returns_{status}() {{\n    let t = app().await;\n{seed}    let res = {request};\n    assert_eq!(res.status().as_u16(), {status}, \"design: {fn_base} -> {status}; body: {{}}\", res.text());\n}}\n\n"
                ));
                out.count += 1;
                if guarded {
                    push_401_test(design, out, unit, ep, &seeded_path, true);
                }
                // Issue #47: update path (PUT/PATCH /{id}) rejects out-of-range too.
                if let Some(field) = ep
                    .request_body
                    .as_ref()
                    .and_then(|rb| first_enum_field(unit, &rb.entity))
                {
                    push_enum_reject_test(design, out, unit, ep, &seeded_path, guarded, field);
                }
                // #80: the update path rejects a constraint violation too.
                if let Some((field, literal)) = ep
                    .request_body
                    .as_ref()
                    .and_then(|rb| first_constraint_reject(unit, &rb.entity))
                {
                    push_constraint_reject_test(
                        design,
                        out,
                        unit,
                        ep,
                        &seeded_path,
                        guarded,
                        field,
                        &literal,
                    );
                }
            } else {
                out.todos.push(format!(
                    "// AGENT TODO: {fn_base} ({:?} {full_path}) has no creator route to seed its {{id}} — encode its success case in your own test file.",
                    ep.method
                ));
                // Issue #153: no creator drops only the un-seedable success
                // probe — the guard test survives (the guard rejects a
                // credential-less request before the id lookup, so a literal
                // id stands in and no seeded row is needed; same as #123b).
                if guarded {
                    push_401_test(
                        design,
                        out,
                        unit,
                        ep,
                        &concrete_mount_base(&full_path),
                        false,
                    );
                }
            }
        } else if param_count(ep) >= 1 {
            out.todos.push(format!(
                "// AGENT TODO: {fn_base} ({:?} {full_path}) needs a creator at \"/\" to seed ids — encode its success case in your own test file.",
                ep.method
            ));
            // Issue #153: a multi-param path blocks only the seeded success
            // probe — the guard test survives with every `{param}` pinned to a
            // literal id (a 401 rejection precedes any id lookup; same as #123b).
            if guarded {
                push_401_test(
                    design,
                    out,
                    unit,
                    ep,
                    &concrete_mount_base(&full_path),
                    false,
                );
            }
        }

        for ec in &ep.errors {
            if ec.status == 404 && param_count(ep) == 1 && !gated {
                let missing_path = full_path.replacen(&regex_free_param(&ep.path), "999999", 1);
                // Build the probe with the endpoint's REAL method (and body/cookie)
                // via the same builder the success test uses — a GET probe at a
                // POST-only `/{id}` action would hit 405, not the 404 we assert.
                // Guarded endpoints run the auth guard before not-found logic, so
                // `request_expr` threads the cookie when guarded.
                let request = request_expr(design, unit, ep, &missing_path, guarded, None);
                out.code.push_str(&format!(
                    "#[tokio::test]\nasync fn {fn_base}_missing_id_is_404() {{\n    let t = app().await;\n    let res = {request};\n    assert_eq!(res.status().as_u16(), 404, \"design: {fn_base} lists 404 ({when}); body: {{}}\", res.text());\n}}\n\n",
                    when = ec.when
                ));
                out.count += 1;
            } else {
                out.todos.push(format!(
                    "// AGENT TODO: design lists {} ({}) for {fn_base} — encode it in your own test file.",
                    ec.status, ec.when
                ));
            }
        }
    }

    for sub in &unit.subroutes {
        let sub_base = format!("{}{}", base, sub.effective_mount());
        unit_tests(design, sub, &sub_base, out);
    }
}

/// A `{op}_without_auth_is_401` test: the guard extractor runs first, so a
/// credential-less request is rejected before any handler logic — no seed needed.
fn push_401_test(
    design: &Design,
    out: &mut TestOut,
    unit: &ModuleDesign,
    ep: &Endpoint,
    path: &str,
    _seeded: bool,
) {
    let fn_base = &ep.operation_id;
    let request = request_expr(design, unit, ep, path, false, None); // no cookie
    out.code.push_str(&format!(
        "#[tokio::test]\nasync fn {fn_base}_without_auth_is_401() {{\n    let t = app().await;\n    let res = {request};\n    assert_eq!(res.status().as_u16(), 401, \"design: {fn_base} is guarded — no cookie must 401; body: {{}}\", res.text());\n}}\n\n"
    ));
    out.count += 1;
}

/// An enum "reject" probe (issue #47): sends the endpoint's fixture body with ONE
/// enum field corrupted to an out-of-range value, and asserts the request boundary
/// answers 422 (JC0422) — the generated `deserialize_with` validator refuses it at
/// deserialization, before the handler and the DB. It PASSES on stubs (the 422
/// precedes the stub), so it is NOT part of the RED-on-stubs baseline: `out.reject`
/// tracks it so gen-tests can exclude it from `expected_failing`. Guarded endpoints
/// thread the credential (via `request_expr`) so the guard doesn't 401 first.
fn push_enum_reject_test(
    design: &Design,
    out: &mut TestOut,
    unit: &ModuleDesign,
    ep: &Endpoint,
    path: &str,
    guarded: bool,
    field: &str,
) {
    let fn_base = &ep.operation_id;
    let sentinel = format!("\"{ENUM_REJECT_SENTINEL}\"");
    let request = request_expr(design, unit, ep, path, guarded, Some((field, &sentinel)));
    out.code.push_str(&format!(
        "#[tokio::test]\nasync fn {fn_base}_rejects_out_of_range_{field}() {{\n    let t = app().await;\n    let res = {request};\n    assert_eq!(res.status().as_u16(), 422, \"design: out-of-range `{field}` enum must 422 at the request boundary, not 500 at the DB CHECK; body: {{}}\", res.text());\n}}\n\n"
    ));
    out.count += 1;
    out.reject += 1;
}

/// The #80 constraint twin of [`push_enum_reject_test`]: sends the endpoint's
/// fixture body with ONE constrained field set to an out-of-range literal and
/// asserts the request boundary answers 422 (JC0422) — the generated
/// `deserialize_with` validator refuses it before the handler and the DB
/// CHECK. Like the enum probe it PASSES on stubs, so it increments
/// `out.reject` and is excluded from the RED-on-stubs `expected_failing`
/// baseline.
#[allow(clippy::too_many_arguments)]
fn push_constraint_reject_test(
    design: &Design,
    out: &mut TestOut,
    unit: &ModuleDesign,
    ep: &Endpoint,
    path: &str,
    guarded: bool,
    field: &str,
    literal: &str,
) {
    let fn_base = &ep.operation_id;
    let request = request_expr(design, unit, ep, path, guarded, Some((field, literal)));
    out.code.push_str(&format!(
        "#[tokio::test]\nasync fn {fn_base}_rejects_out_of_range_{field}() {{\n    let t = app().await;\n    let res = {request};\n    assert_eq!(res.status().as_u16(), 422, \"design: out-of-range `{field}` must 422 at the request boundary (the declared min/max/min_len/max_len), not 500 at the DB CHECK; body: {{}}\", res.text());\n}}\n\n"
    ));
    out.count += 1;
    out.reject += 1;
}

/// "{id}" as it appears inside the full path (the literal brace token).
fn regex_free_param(path: &str) -> String {
    let start = path.find('{').expect("parameterized path");
    let end = path[start..].find('}').expect("balanced braces") + start;
    path[start..=end].to_string()
}

/// The fixed dev secret the test app and `test_cookie()` share so the minted
/// session cookie decrypts against the app's `Auth` extension.
const TEST_SECRET: &str = "a-very-long-development-secret-string!!";

/// In auth mode: a test-only login shim that mints the guard credential directly
/// via the `Auth` extension (no app `/login` route needed), plus the
/// `.extend(Auth)` the app() helper adds so the SAME secret validates it.
/// `test_cookie_for` mints for any user id (isolation tests act as a second
/// user); `test_cookie()` keeps minting user 1's for back-compat.
///
/// The credential shape follows the auth model (issue #29): the `session` model
/// mints a `jerrycan_session=` cookie via the session store; the `jwt` model
/// mints a signed `Bearer <jwt>` over the SAME `SessionUser` payload with
/// `Auth::jwt_key()`, matching the generated `Bearer<SessionUser>` guard. The
/// helpers keep the `test_cookie` names in both models so the isolation seed and
/// probes stay untouched and the session/none output stays byte-identical.
///
/// No-`exp` (issue #45): the jwt token is minted deliberately WITHOUT an `exp`
/// claim. These are test-only, in-process credentials and must NOT be
/// time-dependent — a "helpfully" added `exp` would make the isolation tests expire
/// and flake. Keep it exp-free.
fn auth_preamble_login(design: &Design) -> String {
    // The minted `SessionUser.role` is drawn from the design (issue #67): a
    // `require_role`-guarded handler 403s a credential whose role doesn't satisfy
    // the gate, so a hardcoded "admin" left role-gated probes un-greenable for any
    // design whose roles exclude it. `test_credential_role` picks the gate's role.
    let role = design.test_credential_role();
    let mint = if design.auth_model() == AuthModel::Jwt {
        format!(
            "let token = jerrycan::auth::jwt::encode(&shared::SessionUser {{ id: user_id.to_string(), role: \"{role}\".into() }}, auth.jwt_key()).expect(\"encode\");\n    format!(\"Bearer {{token}}\")"
        )
    } else {
        format!(
            "let token = auth.sessions().encode(&shared::SessionUser {{ id: user_id.to_string(), role: \"{role}\".into() }}).expect(\"encode\");\n    format!(\"jerrycan_session={{token}}\")"
        )
    };
    format!(
        "fn test_cookie_for(user_id: i64) -> String {{\n    let auth = jerrycan::auth::Auth::with_secret(\"{TEST_SECRET}\");\n    {mint}\n}}\n\nfn test_cookie() -> String {{\n    test_cookie_for(1)\n}}\n\n"
    )
}

/// The module owning the design's tenancy entity (the `{tenant}_members` table
/// lives in its migration). None when the design has no tenancy.
fn tenant_module(design: &Design) -> Option<&ModuleDesign> {
    let tenancy = design.tenancy.as_ref()?;
    design
        .modules
        .iter()
        .find(|m| m.entities.iter().any(|e| e.name == tenancy.entity))
}

/// True when this module holds an entity that belongs_to the tenancy entity —
/// so its guarded handlers take `Dep<Tenant>` and the test app must register the
/// `tenant` factory + seed a membership row.
fn module_needs_tenant(design: &Design, module: &ModuleDesign) -> bool {
    if design.tenancy.is_none() {
        return false;
    }
    // Ownership is TRANSITIVE (issue #102): a grandchild (`Contact belongs_to
    // Account belongs_to Org`) is tenant-owned too, so its module also needs the
    // tenant/membership seed + second-tenant scaffolding its isolation test acts
    // on. `tenant_path(..).is_some()` subsumes the old direct-`belongs_to` check
    // (a direct child resolves to an empty-`joins` path), so direct designs stay
    // byte-identical; only grandchild modules gain the scaffolding.
    fn walk(design: &Design, m: &ModuleDesign) -> bool {
        m.entities
            .iter()
            .any(|e| design.tenant_path(&e.name).is_some())
            || m.subroutes.iter().any(|s| walk(design, s))
    }
    walk(design, module)
}

/// True when this module's test app must REGISTER the `tenant` DI factory so a
/// `Dep<Tenant>` handler resolves. This is broader than [`module_needs_tenant`]:
/// besides a tenant-owned child (whose guarded handlers take `Dep<Tenant>`), the
/// tenant module ITSELF needs the factory when its own detail route is a GUARDED
/// path-scoped route (normalized `/{tenant_fk}`, issue #78) — its `get`/`delete`
/// handler takes `Dep<Tenant>`. Kept SEPARATE from the membership-SEED gate
/// (`module_needs_tenant`): the tenant module creates its own rows in-test, so it
/// must not be pre-seeded (that would collide with the created id). An UNGUARDED
/// detail route (no `Dep<Tenant>`) is excluded, so a design whose tenant module
/// exposes only public reads stays byte-identical.
fn module_provides_tenant_dep(design: &Design, module: &ModuleDesign) -> bool {
    fn has_guarded_pathscoped(design: &Design, m: &ModuleDesign) -> bool {
        m.endpoints.iter().any(|ep| {
            ep.is_guarded()
                && matches!(
                    design.endpoint_tenant_shape(m, ep),
                    TenantShape::PathScoped { .. }
                )
        }) || m
            .subroutes
            .iter()
            .any(|s| has_guarded_pathscoped(design, s))
    }
    module_needs_tenant(design, module) || has_guarded_pathscoped(design, module)
}

/// A `migrate` entry for the tenant module's tables, referenced from THIS test
/// crate (cross-crate relative include) so the `{tenant}_members` table the
/// `tenant` guard queries exists. Empty if the tenant module IS this module
/// (its own migration is already included) or there is no tenancy.
/// Every module's create-tables migration for the FULL workspace schema, so a
/// module's TestApp can touch ANY module's table (issue #14): a handler that
/// legitimately writes another module's table no longer 500s with "no such
/// table". The CURRENT module includes its own files by the relative
/// `../migrations/...` path; every OTHER module by the cross-crate
/// `../../{module}/migrations/...` path (the same shape the old tenant
/// cross-include used). sqlite-memory schema is cheap, so migrating everything
/// is the simplest correct default. Deterministic: document order, skipping
/// entity-less modules (which have no migration file).
fn collect_workspace_migration_items(design: &Design, current: &ModuleDesign, out: &mut String) {
    // The current module reaches its own files by `..` (from its own tests dir);
    // every other module by the cross-crate `../../{module}` path.
    migration_items(
        design,
        |name| {
            if name == current.name {
                "..".to_string()
            } else {
                format!("../../{name}")
            }
        },
        out,
    );
}

/// Emit a `jerrycan::db::Migration { … include_str!(…) }` item for every route
/// module (and subroute) create-tables migration in the design, into `out` (design
/// order; entity-less modules skipped — they have no migration file). This is the
/// FULL workspace schema `App::build` applies (mounting.rs aggregates the same set
/// into `migrations::MIGRATIONS`). `prefix_for(module_name)` yields the
/// `include_str!` path prefix to that module's `migrations/` dir — it differs by
/// caller because their harness files sit at different depths: the route TestApp
/// (testgen) is at `crates/routes/<m>/tests/` (own module `..`, others `../../<m>`),
/// while the jobs harness (jobsgen) is at `crates/jobs/tests/` (every module
/// `../../routes/<m>`). Shared so both harnesses migrate the same tables (issue #84).
pub(crate) fn migration_items(
    design: &Design,
    prefix_for: impl Fn(&str) -> String,
    out: &mut String,
) {
    for m in &design.modules {
        let prefix = prefix_for(&m.name);
        let m_snake = m.name.replace('-', "_");
        if !m.entities.is_empty() {
            out.push_str(&format!(
                "        jerrycan::db::Migration {{\n            name: \"{m_snake}_0001_create_tables\",\n            sqlite: include_str!(\"{prefix}/migrations/sqlite/0001_create_tables.sql\"),\n            postgres: include_str!(\"{prefix}/migrations/postgres/0001_create_tables.sql\"),\n        }},\n"
            ));
        }
        collect_subroute_migration_items(m, &m_snake, &prefix, out);
    }
}

/// Subroute create-tables migrations for one top-level module (recursive). A
/// subroute's file lives in its TOP module's migrations dir as
/// `0001_create_tables_{sub}.sql`; its name is namespaced by the top module so
/// two modules' like-named subroutes never collide in the workspace list.
fn collect_subroute_migration_items(
    module: &ModuleDesign,
    top_snake: &str,
    prefix: &str,
    out: &mut String,
) {
    for sub in &module.subroutes {
        if !sub.entities.is_empty() {
            let s = sub.name.replace('-', "_");
            out.push_str(&format!(
                "        jerrycan::db::Migration {{\n            name: \"{top_snake}_0001_create_tables_{s}\",\n            sqlite: include_str!(\"{prefix}/migrations/sqlite/0001_create_tables_{s}.sql\"),\n            postgres: include_str!(\"{prefix}/migrations/postgres/0001_create_tables_{s}.sql\"),\n        }},\n"
            ));
        }
        collect_subroute_migration_items(sub, top_snake, prefix, out);
    }
}

/// The seed statements that put the test user (id 1) into a tenant: insert one
/// tenant row (id 1, required fields = fixtures, enum fields = first allowed
/// value so CHECKs pass) then one membership row (user_id 1, fk 1, first member
/// role). Run on the raw connection before `.into_test()` so the `tenant` guard
/// resolves a membership for every guarded request. Empty when not needed.
fn tenant_seed(design: &Design, module: &ModuleDesign) -> String {
    if !module_needs_tenant(design, module) {
        return String::new();
    }
    let Some(tenancy) = design.tenancy.as_ref() else {
        return String::new();
    };
    let Some(t) = tenant_module(design) else {
        return String::new();
    };
    let Some(entity) = t.entities.iter().find(|e| e.name == tenancy.entity) else {
        return String::new();
    };
    let table = design.table_name(&tenancy.entity);
    let members = format!("{}_members", Design::to_snake(&tenancy.entity));
    let fk = Design::fk_column(&tenancy.entity);
    // The seed role is member_roles[0]; JC0548 guarantees a non-empty list at
    // design time, so the fallback is dead code — `"member"` to match genroute's
    // (equally dead) seed-role fallback byte-for-byte.
    let role = tenancy
        .member_roles
        .first()
        .map(String::as_str)
        .unwrap_or("member");

    // Columns + values for the tenant row: id = 1 (so the fk resolves), then each
    // declared non-id field with a seed-safe fixture (enum fields use a declared
    // value to satisfy the CHECK constraint). Column identifiers are double-quoted
    // in the SQL; since the whole statement is a Rust string literal, those quotes
    // are escaped (`\\\"`) so the generated source stays valid.
    let (cols, vals) = tenant_row_cols_vals(entity, "1", 1);
    let mut seed = format!(
        "    db.conn()\n        .execute_unprepared(\"INSERT INTO \\\"{table}\\\" ({cols}) VALUES ({vals})\")\n        .await\n        .expect(\"seed tenant row\");\n    db.conn()\n        .execute_unprepared(\"INSERT INTO \\\"{members}\\\" (user_id, {fk}, role) VALUES (1, 1, '{role}')\")\n        .await\n        .expect(\"seed membership\");\n"
    );
    // Seed the TRANSITIVE parent chain in tenant 1 (issue #102): a grandchild's
    // create resolves its parent fk through the JOIN chain, so each intermediate
    // parent (from the anchor down to the immediate parent) must exist and be
    // linked to tenant 1. Empty for a direct child (no joins) — byte-identical.
    if let Some(path) = module
        .entities
        .iter()
        .find_map(|e| design.tenant_path(&e.name))
    {
        seed.push_str(&seed_tenant1_chain(design, &path));
    }
    seed
}

/// Seed the transitive parent chain in tenant 1 (issue #102) so a grandchild's
/// create resolves its parent fk through the JOIN chain. Emits one INSERT per
/// intermediate parent, ANCHOR FIRST (parents before children): the anchor (the
/// table that directly `belongs_to` the tenant) carries the tenant fk = 1; each
/// lower parent carries its own parent fk = 1 (the id of the row just seeded).
/// Every table is seeded at the fixed id 1. Required (NOT NULL) non-id fields are
/// seeded with a type-shaped literal so a parent with e.g. a required `name` still
/// inserts; nullable fields are omitted. Empty for a direct child (no joins).
fn seed_tenant1_chain(design: &Design, path: &TenantPath) -> String {
    let n = path.joins.len();
    let mut out = String::new();
    for i in (0..n).rev() {
        let table = &path.joins[i].parent_table;
        // The fk linking this parent upward: the anchor (top join) carries the
        // tenant fk; a lower parent carries its fk to ITS parent — the next join's
        // child fk — whose row we also seed at id 1.
        let link_fk = if i == n - 1 {
            path.tenant_fk.as_str()
        } else {
            path.joins[i + 1].child_fk.as_str()
        };
        let mut cols = vec!["id".to_string(), link_fk.to_string()];
        let mut vals = vec!["1".to_string(), "1".to_string()];
        // A parent may declare its own required columns (NOT NULL, no DB default);
        // seed them too so the INSERT satisfies the schema. Nullable columns are
        // left NULL. `id` is the fixed 1 above; the upward fk is `link_fk`.
        if let Some(e) = entity_by_table(design, table) {
            for f in e.fields.iter().filter(|f| f.name != "id" && f.required) {
                cols.push(format!("\\\"{}\\\"", f.name));
                vals.push(seed_sql_value(f));
            }
        }
        out.push_str(&format!(
            "    db.conn()\n        .execute_unprepared(\"INSERT INTO \\\"{table}\\\" ({cols}) VALUES ({vals})\")\n        .await\n        .expect(\"seed tenant 1 {table} row\");\n",
            cols = cols.join(", "),
            vals = vals.join(", "),
        ));
    }
    out
}

/// The entity whose table is `table` — the reverse of `Design::table_name`. Table
/// names are unique per entity, so this resolves the parent `Entity` a
/// `TenantPath` join references (the join stores only table names), needed to seed
/// that parent's required columns.
fn entity_by_table<'a>(design: &'a Design, table: &str) -> Option<&'a Entity> {
    fn collect<'a>(m: &'a ModuleDesign, out: &mut Vec<&'a Entity>) {
        out.extend(m.entities.iter());
        for s in &m.subroutes {
            collect(s, out);
        }
    }
    let mut all = Vec::new();
    for m in &design.modules {
        collect(m, &mut all);
    }
    all.into_iter()
        .find(|e| design.table_name(&e.name) == table)
}

/// The membership role to seed for the second tenant's user: the role a
/// role-gated DELETE on this module requires (so the isolation DELETE leg clears
/// the role check and exercises the SCOPED `remove_for` — proving cross-tenant
/// isolation, not a 403 role rejection), falling back to the first member role.
/// The final fallback is dead code under JC0548 (member_roles is non-empty at
/// design time) — `"member"` to match genroute's equally dead seed-role fallback.
fn isolation_member_role<'a>(design: &'a Design, module: &'a ModuleDesign) -> &'a str {
    module
        .endpoints
        .iter()
        .find(|ep| ep.method == HttpMethod::DELETE && !ep.required_roles.is_empty())
        .and_then(|ep| ep.required_roles.first())
        .map(String::as_str)
        .or_else(|| {
            design
                .tenancy
                .as_ref()
                .and_then(|t| t.member_roles.first())
                .map(String::as_str)
        })
        .unwrap_or("member")
}

/// The columns + values for a tenant row seeded at the given pk: id = the pk
/// literal, then each declared non-id field with a seed-safe fixture (enum
/// fields use a declared value to satisfy the CHECK). Returns (cols, vals) as
/// the comma-joined SQL fragments. The tenant pk is an integer in practice (the
/// reference-slice Workspace), so the literal is numeric.
pub(crate) fn tenant_row_cols_vals(entity: &Entity, pk: &str, n: u32) -> (String, String) {
    let mut cols = vec!["id".to_string()];
    let mut vals = vec![pk.to_string()];
    for f in entity.fields.iter().filter(|f| f.name != "id") {
        cols.push(format!("\\\"{}\\\"", f.name));
        vals.push(seed_sql_value_n(f, n));
    }
    (cols.join(", "), vals.join(", "))
}

/// The `seed_second_tenant` helper for a tenant-owned module: inserts a SECOND
/// tenant (id 2) and a membership for user 2 (fk 2, role from
/// `isolation_member_role`). The isolation test acts as this user to prove a
/// tenant cannot reach another tenant's rows. Empty for non-tenant-owned modules.
fn seed_second_tenant_fn(design: &Design, module: &ModuleDesign) -> String {
    if !module_needs_tenant(design, module) {
        return String::new();
    }
    let Some(tenancy) = design.tenancy.as_ref() else {
        return String::new();
    };
    let Some(t) = tenant_module(design) else {
        return String::new();
    };
    let Some(entity) = t.entities.iter().find(|e| e.name == tenancy.entity) else {
        return String::new();
    };
    let table = design.table_name(&tenancy.entity);
    let members = format!("{}_members", Design::to_snake(&tenancy.entity));
    let fk = Design::fk_column(&tenancy.entity);
    let role = isolation_member_role(design, module);
    let (cols, vals) = tenant_row_cols_vals(entity, "2", 2);
    format!(
        "async fn seed_second_tenant(db: &jerrycan::db::Db) {{\n    db.conn()\n        .execute_unprepared(\"INSERT INTO \\\"{table}\\\" ({cols}) VALUES ({vals})\")\n        .await\n        .expect(\"seed tenant 2 row\");\n    db.conn()\n        .execute_unprepared(\"INSERT INTO \\\"{members}\\\" (user_id, {fk}, role) VALUES (2, 2, '{role}')\")\n        .await\n        .expect(\"seed tenant 2 membership\");\n}}\n\n"
    )
}

/// The cross-tenant isolation test for a tenant-owned module: user 1 (tenant 1)
/// creates a row; user 2 (tenant 2, seeded by app()) must not be able to read,
/// list, or delete it. WHY this matters (Rule 9): it encodes the SECURITY
/// contract — it fails on stubs (500), goes green only when the handler uses the
/// SCOPED accessors (get_for/all_for/remove_for), and stays RED if the agent
/// reaches for the unscoped all/get/remove (which would leak the foreign row).
///
/// Emitted only for a top-level tenant-owned entity that has a guarded creator
/// (POST "/" with a body). With a GET "/{id}" it runs the full get/list/delete
/// legs; without one it degrades to a list-only variant asserting the foreign row
/// is absent from user 2's list. Empty when there's no usable creator.
/// Every applicable isolation test for a module, concatenated (issue #78/#79,
/// spec §F). One design shape ⇒ one emitter fires; each returns "" when N/A, so
/// composing is safe. The four shapes:
///   - tenant-owned (flat MembershipSet, and nested path-scoped) — a member of
///     tenant A cannot reach tenant B's rows;
///   - per-user identity-owned — user B cannot reach user A's rows (#79);
///   - tenant-collection-create (I1) — the creator's list-own returns the new
///     tenant; a second user's list is empty (the backstop for an agent who calls
///     the bare `insert` instead of `create_with_membership`).
fn isolation_test(design: &Design, module: &ModuleDesign) -> String {
    let mut out = String::new();
    out.push_str(&tenant_owned_isolation_test(design, module));
    out.push_str(&per_user_isolation_test(design, module));
    out.push_str(&public_read_isolation_test(design, module));
    out.push_str(&tenant_collection_isolation_test(design, module));
    out
}

/// The cross-tenant isolation test for a tenant-owned module: user 1 (tenant 1)
/// creates a row; user 2 (tenant 2, seeded by app()) must not be able to read,
/// list, or delete it. WHY this matters (Rule 9): it encodes the SECURITY
/// contract — it fails on stubs (500), goes green only when the handler uses the
/// SCOPED accessors (get_for/all_for/remove_for), and stays RED if the agent
/// reaches for the unscoped all/get/remove (which would leak the foreign row).
///
/// Handles BOTH route shapes:
///   - FLAT (MembershipSet, `/leads`): user 2 can list their own (empty) rows, so
///     the list leg asserts the foreign row is absent — byte-identical to before;
///   - NESTED path-scoped (`/clubs/{club_id}/books`, the #78 leak with no coverage
///     today): the tenant fk in the mount is pinned to tenant 1, and user 2 (a
///     member of tenant 2, NOT tenant 1) gets 404 on tenant 1's row. The list leg
///     is SKIPPED — user 2 can't even reach tenant 1's collection (the guard 404s
///     the whole path), so a "list 200, absent" assertion would false-fail.
fn tenant_owned_isolation_test(design: &Design, module: &ModuleDesign) -> String {
    let Some(tenancy) = design.tenancy.as_ref() else {
        return String::new();
    };
    // The tenant-owned entity on this module — directly OR TRANSITIVELY (issue
    // #102). `tenant_path` resolves the unique `belongs_to` chain that reaches the
    // tenant: a DIRECT child yields an empty-`joins` path (byte-identical to the
    // old direct-`belongs_to` finder); a GRANDCHILD (`Contact belongs_to Account
    // belongs_to Org`) yields the JOIN chain we seed (`seed_tenant1_chain`) and
    // pin into the mount below. (Subroute-nested tenant entities remain out of
    // scope — only top-level module entities, as before.)
    let Some((entity, path)) = module
        .entities
        .iter()
        .find_map(|e| design.tenant_path(&e.name).map(|p| (e, p)))
    else {
        return String::new();
    };
    // A guarded creator at "/" with a body for this entity is required to seed a
    // tenant-1 row to probe; without it there's nothing to isolate.
    let Some(create) = module.endpoints.iter().find(|ep| {
        ep.method == HttpMethod::POST
            && ep.path == "/"
            && ep
                .request_body
                .as_ref()
                .is_some_and(|rb| rb.entity == entity.name)
    }) else {
        return String::new();
    };
    let base = module.effective_mount();
    let base = base.trim_end_matches('/');
    // A NESTED mount carries an ancestor fk token: pin every one to the seeded id 1
    // so the probe URLs are concrete, and remember we're nested so the list leg
    // (user 2 can't reach tenant 1's collection at all) is skipped. A DIRECT child
    // carries the TENANT fk (`/clubs/{club_id}/…`); a GRANDCHILD carries a PARENT
    // fk instead (`/accounts/{account_id}/…` — issue #102), pinned to the
    // intermediate parent seeded in tenant 1. The `joins` loop is empty for a
    // direct child, so `cbase`/`is_nested` stay byte-identical to before. For a
    // FLAT mount no token is present, so `cbase == base` and every URL is unchanged.
    let fk_token = format!("{{{}}}", Design::fk_column(&tenancy.entity));
    let parent_tokens: Vec<String> = path
        .joins
        .iter()
        .map(|j| format!("{{{}}}", j.child_fk))
        .collect();
    let is_nested = base.contains(&fk_token) || parent_tokens.iter().any(|t| base.contains(t));
    let mut cbase = base.replace(&fk_token, "1");
    for tok in &parent_tokens {
        cbase = cbase.replace(tok, "1");
    }
    let plural = module.name.replace('-', "_");
    let body = fixture_json(
        design,
        module,
        &entity.name,
        omits_identity_fk(design, module, create),
        None,
        false, // isolation seeds a row via create — a create body omits defaults
    );
    let create_path = format!("{cbase}/");

    // A GET "/{id}" lets us assert the foreign row 404s for user 2 and survives
    // for user 1; a DELETE "/{id}" (role-gated → user 2's membership carries the
    // role) must also 404 without destroying user 1's row. Computed first so the
    // id bindings below are only emitted when a probe consumes them (never an
    // unused-variable warning under -D warnings).
    let get_one = module
        .endpoints
        .iter()
        .find(|ep| ep.method == HttpMethod::GET && param_count(ep) == 1);
    let delete_one = module
        .endpoints
        .iter()
        .find(|ep| ep.method == HttpMethod::DELETE && param_count(ep) == 1);
    // The list leg only applies to a FLAT (MembershipSet) route. A nested route's
    // list is scoped by construction — membership on the parent chain filters the
    // rows, not a path guard (a grandchild's parent fk is never pinned in the path)
    // — so there is no cross-tenant list leg to negative-test here.
    let list = module
        .endpoints
        .iter()
        .find(|ep| ep.method == HttpMethod::GET && param_count(ep) == 0)
        .filter(|_| !is_nested);

    // The credential header follows the auth model (cookie/session, Bearer/jwt —
    // issue #29); `test_cookie_for(n)` returns the matching header value.
    let hk = design.test_auth_header();
    // user 1 (cred 1) creates a row in tenant 1, then we read the id it echoes.
    let mut t = String::new();
    t.push_str(&format!(
        "/// SECURITY: a tenant must not reach another tenant's {entity} rows. User 1\n/// creates a row in tenant 1; user 2 (tenant 2) must be denied read/list/delete.\n/// Passes only with the SCOPED repo accessors (get_for/all_for/remove_for).\n#[tokio::test]\nasync fn tenant_a_cannot_read_tenant_b_{plural}() {{\n    let t = app().await;\n",
        entity = entity.name,
    ));
    t.push_str(&format!(
        "    let created = t.post_json_with(\"{create_path}\", &serde_json::json!({body}), &[(\"{hk}\", &test_cookie_for(1))]).await;\n    assert_eq!(created.status().as_u16(), {status}, \"setup: user 1 creates a {entity}; body: {{}}\", created.text());\n    let row: serde_json::Value = serde_json::from_str(&created.text()).expect(\"created json\");\n    let cookie2 = test_cookie_for(2);\n",
        status = create.success.status,
        entity = entity.name,
    ));
    // The list negative-control compares the created id as a JSON Value.
    if list.is_some() {
        t.push_str("    let id_value = row[\"id\"].clone();\n");
    }
    // A by-id URL must carry the RAW id: a string PK's `Value::String` Display
    // includes JSON quotes (`\"uuid\"`), so a `format!(\"…/{id}\")` would 404 every
    // by-id request. Interpolate the unquoted string (a numeric PK is identical).
    if get_one.is_some() || delete_one.is_some() {
        t.push_str(
            "    let id = row[\"id\"].as_str().map(str::to_string).unwrap_or_else(|| row[\"id\"].to_string());\n",
        );
    }

    if let Some(_get) = get_one {
        t.push_str(&format!(
            "    let foreign = t.get_with(&format!(\"{cbase}/{{id}}\"), &[(\"{hk}\", &cookie2)]).await;\n    assert_eq!(foreign.status().as_u16(), 404, \"cross-tenant get must 404 (use get_for, not get); body: {{}}\", foreign.text());\n",
        ));
    }
    if list.is_some() {
        // Always cookied: even an unguarded list is safe to call with a cookie,
        // and a guarded one needs it. user 2 sees only tenant 2's (empty) rows.
        t.push_str(&format!(
            "    let listed = t.get_with(\"{cbase}/\", &[(\"{hk}\", &cookie2)]).await;\n    assert_eq!(listed.status().as_u16(), 200, \"user 2 lists their own {plural}; body: {{}}\", listed.text());\n    let rows: serde_json::Value = serde_json::from_str(&listed.text()).expect(\"list json\");\n    let absent = rows.as_array().map(|a| a.iter().all(|r| r[\"id\"] != id_value)).unwrap_or(true);\n    assert!(absent, \"cross-tenant list must NOT contain tenant 1's row (use all_for); body: {{}}\", listed.text());\n",
        ));
    }
    if let Some(_del) = delete_one {
        t.push_str(&format!(
            "    let del = t.delete_with(&format!(\"{cbase}/{{id}}\"), &[(\"{hk}\", &cookie2)]).await;\n    assert_eq!(del.status().as_u16(), 404, \"cross-tenant delete must 404 (use remove_for, not remove); body: {{}}\", del.text());\n",
        ));
        if get_one.is_some() {
            t.push_str(&format!(
                "    let survives = t.get_with(&format!(\"{cbase}/{{id}}\"), &[(\"{hk}\", &test_cookie_for(1))]).await;\n    assert_eq!(survives.status().as_u16(), 200, \"tenant 1's row must survive a cross-tenant delete; body: {{}}\", survives.text());\n",
            ));
        }
    }
    t.push_str("}\n\n");
    t
}

/// The per-user (#79) isolation test: user 1 creates a row (the server injects
/// user 1's id); user 2 must not be able to read, list, or delete it. WHY (Rule 9):
/// the identity-owned shape JC0540 steers agents toward had NO backstop — an
/// unscoped `repo.all()` leaked every user's rows with `check` green. This test is
/// that backstop; it passes ONLY when the handler scopes via the owner accessors
/// (`all_for`/`get_for`/`remove_for`), which are now the ONLY methods generated
/// (genroute suppresses the unscoped ones). No tenant seeding — two distinct user
/// sessions (`test_cookie_for(1)`/`(2)`) are all it needs. db+auth only.
fn per_user_isolation_test(design: &Design, module: &ModuleDesign) -> String {
    if !(design.wants_db() && design.wants_auth()) {
        return String::new();
    }
    // Per-user classification is `Design::entity_is_per_user_owned` — the ONE
    // shared predicate (#105 §F): genroute suppresses the unscoped methods for
    // exactly the entities this test covers (TENANT ownership wins and is
    // TRANSITIVE, #102 — such entities get the cross-tenant test instead). A
    // `public_read` entity is EXCLUDED: its reads legitimately serve every
    // owner's rows, so this test's cross-user read-denial legs would be RED on a
    // correct app — it gets `public_read_isolation_test` (#105) instead.
    let Some(entity) = module
        .entities
        .iter()
        .find(|e| design.entity_is_per_user_owned(e) && !design.entity_is_public_read(&e.name))
    else {
        return String::new();
    };
    // A GUARDED creator at "/" with a body — the server injects the owner id from
    // the session, so the created row is owned by user 1.
    let Some(create) = module.endpoints.iter().find(|ep| {
        ep.method == HttpMethod::POST
            && ep.path == "/"
            && ep.is_guarded()
            && ep
                .request_body
                .as_ref()
                .is_some_and(|rb| rb.entity == entity.name)
    }) else {
        return String::new();
    };
    let base = module.effective_mount();
    let base = base.trim_end_matches('/');
    let plural = module.name.replace('-', "_");
    let body = fixture_json(
        design,
        module,
        &entity.name,
        omits_identity_fk(design, module, create),
        None,
        false, // isolation seeds a row via create — a create body omits defaults
    );
    let create_path = format!("{base}/");
    // Only GUARDED reads carry the owner scope — an unguarded read has no session to
    // scope by, so it can't prove isolation. Gate every probe leg on a guard.
    let guarded1 = |ep: &&Endpoint| ep.is_guarded();
    let get_one = module
        .endpoints
        .iter()
        .find(|ep| ep.method == HttpMethod::GET && param_count(ep) == 1 && guarded1(ep));
    let delete_one = module
        .endpoints
        .iter()
        .find(|ep| ep.method == HttpMethod::DELETE && param_count(ep) == 1 && guarded1(ep));
    let list = module
        .endpoints
        .iter()
        .find(|ep| ep.method == HttpMethod::GET && param_count(ep) == 0 && guarded1(ep));

    let hk = design.test_auth_header();
    let mut t = String::new();
    t.push_str(&format!(
        "/// SECURITY (#79): a user must not reach another user's {entity} rows. User 1\n/// creates a row (the server injects user 1's id); user 2 must be denied read/\n/// list/delete. Passes only with the owner-scoped accessors (all_for/get_for/\n/// remove_for) — the unscoped methods are NOT generated (genroute, #79).\n#[tokio::test]\nasync fn user_a_cannot_read_user_b_{plural}() {{\n    let t = app().await;\n",
        entity = entity.name,
    ));
    t.push_str(&format!(
        "    let created = t.post_json_with(\"{create_path}\", &serde_json::json!({body}), &[(\"{hk}\", &test_cookie_for(1))]).await;\n    assert_eq!(created.status().as_u16(), {status}, \"setup: user 1 creates a {entity}; body: {{}}\", created.text());\n    let row: serde_json::Value = serde_json::from_str(&created.text()).expect(\"created json\");\n    let cookie2 = test_cookie_for(2);\n",
        status = create.success.status,
        entity = entity.name,
    ));
    if list.is_some() {
        t.push_str("    let id_value = row[\"id\"].clone();\n");
    }
    if get_one.is_some() || delete_one.is_some() {
        t.push_str(
            "    let id = row[\"id\"].as_str().map(str::to_string).unwrap_or_else(|| row[\"id\"].to_string());\n",
        );
    }
    if get_one.is_some() {
        t.push_str(&format!(
            "    let foreign = t.get_with(&format!(\"{base}/{{id}}\"), &[(\"{hk}\", &cookie2)]).await;\n    assert_eq!(foreign.status().as_u16(), 404, \"cross-user get must 404 (use get_for(_user.0.id), not get); body: {{}}\", foreign.text());\n",
        ));
    }
    if list.is_some() {
        t.push_str(&format!(
            "    let listed = t.get_with(\"{base}/\", &[(\"{hk}\", &cookie2)]).await;\n    assert_eq!(listed.status().as_u16(), 200, \"user 2 lists their own {plural}; body: {{}}\", listed.text());\n    let rows: serde_json::Value = serde_json::from_str(&listed.text()).expect(\"list json\");\n    let absent = rows.as_array().map(|a| a.iter().all(|r| r[\"id\"] != id_value)).unwrap_or(true);\n    assert!(absent, \"cross-user list must NOT contain user 1's row (use all_for(_user.0.id)); body: {{}}\", listed.text());\n",
        ));
    }
    if delete_one.is_some() {
        t.push_str(&format!(
            "    let del = t.delete_with(&format!(\"{base}/{{id}}\"), &[(\"{hk}\", &cookie2)]).await;\n    assert_eq!(del.status().as_u16(), 404, \"cross-user delete must 404 (use remove_for(_user.0.id), not remove); body: {{}}\", del.text());\n",
        ));
        if get_one.is_some() {
            t.push_str(&format!(
                "    let survives = t.get_with(&format!(\"{base}/{{id}}\"), &[(\"{hk}\", &test_cookie_for(1))]).await;\n    assert_eq!(survives.status().as_u16(), 200, \"user 1's row must survive a cross-user delete; body: {{}}\", survives.text());\n",
            ));
        }
    }
    t.push_str("}\n\n");
    t
}

/// The public-read/owner-write isolation test (#105) — the `public_read` sibling
/// of [`per_user_isolation_test`]. WHY (Rule 9): the flag splits the ownership
/// contract in two, and each half needs a backstop or it silently rots into the
/// other. The READ half — anyone, even anonymous, sees EVERY owner's rows (the
/// feed intent) — fails if an agent leaves the read owner-scoped (all_for) or
/// guarded. The WRITE half — creates need a session, updates/deletes 404 for a
/// non-owner with the row SURVIVING — fails if "public read" bleeds into "public
/// write" (an anon POST landing, or a foreign PUT/DELETE touching the row).
/// Emitted only for a module owning a `public_read` entity (the shared
/// `Design::entity_is_public_read` classifier) with a guarded creator; every
/// other design stays byte-identical. db+auth only.
fn public_read_isolation_test(design: &Design, module: &ModuleDesign) -> String {
    if !(design.wants_db() && design.wants_auth()) {
        return String::new();
    }
    let Some(entity) = module
        .entities
        .iter()
        .find(|e| design.entity_is_public_read(&e.name))
    else {
        return String::new();
    };
    // A GUARDED creator at "/" with a body — the server injects the owner id from
    // the session, so the created row is owned by user 1 (and the anon-POST-401
    // leg has a guard to prove).
    let Some(create) = module.endpoints.iter().find(|ep| {
        ep.method == HttpMethod::POST
            && ep.path == "/"
            && ep.is_guarded()
            && ep
                .request_body
                .as_ref()
                .is_some_and(|rb| rb.entity == entity.name)
    }) else {
        return String::new();
    };
    let base = module.effective_mount();
    let base = base.trim_end_matches('/');
    let plural = module.name.replace('-', "_");
    let body = fixture_json(
        design,
        module,
        &entity.name,
        omits_identity_fk(design, module, create),
        None,
        false, // isolation seeds a row via create — a create body omits defaults
    );
    let create_path = format!("{base}/");
    // The read legs use the endpoints genroute actually UNGUARDS — the shared
    // `Design::endpoint_is_public_read_get` (a role-gated GET keeps its guard and
    // is not probed anonymously). The write legs bind this entity's guarded
    // PUT/DELETE at "/{id}".
    let this_entity =
        |ep: &&Endpoint| endpoint_repo_entity(module, ep) == Some(entity.name.as_str());
    let list = module
        .endpoints
        .iter()
        .find(|ep| {
            ep.method == HttpMethod::GET
                && param_count(ep) == 0
                && this_entity(ep)
                && design.endpoint_is_public_read_get(module, ep)
        })
        .map(|ep| ep.path.clone());
    let get_one = module.endpoints.iter().find(|ep| {
        ep.method == HttpMethod::GET
            && param_count(ep) == 1
            && this_entity(ep)
            && design.endpoint_is_public_read_get(module, ep)
    });
    let put_one = module.endpoints.iter().find(|ep| {
        ep.method == HttpMethod::PUT && param_count(ep) == 1 && this_entity(ep) && ep.is_guarded()
    });
    let delete_one = module.endpoints.iter().find(|ep| {
        ep.method == HttpMethod::DELETE
            && param_count(ep) == 1
            && this_entity(ep)
            && ep.is_guarded()
    });

    let hk = design.test_auth_header();
    let mut t = String::new();
    t.push_str(&format!(
        "/// SECURITY (#105): {entity} is public_read — reads are PUBLIC (anyone, even\n/// anonymous, sees every owner's rows), writes stay OWNER-scoped. User 1 creates a\n/// row; an anonymous reader must see it; an anonymous create must 401; user 2's\n/// update/delete must 404 with the row surviving; user 1's update succeeds.\n#[tokio::test]\nasync fn anon_reads_but_only_the_owner_writes_{plural}() {{\n    let t = app().await;\n",
        entity = entity.name,
    ));
    t.push_str(&format!(
        "    let created = t.post_json_with(\"{create_path}\", &serde_json::json!({body}), &[(\"{hk}\", &test_cookie_for(1))]).await;\n    assert_eq!(created.status().as_u16(), {status}, \"setup: user 1 creates a {entity}; body: {{}}\", created.text());\n    let row: serde_json::Value = serde_json::from_str(&created.text()).expect(\"created json\");\n",
        status = create.success.status,
        entity = entity.name,
    ));
    if list.is_some() {
        t.push_str("    let id_value = row[\"id\"].clone();\n");
    }
    if get_one.is_some() || put_one.is_some() || delete_one.is_some() {
        t.push_str(
            "    let id = row[\"id\"].as_str().map(str::to_string).unwrap_or_else(|| row[\"id\"].to_string());\n",
        );
    }
    // PUBLIC READ: an anonymous list returns 200 AND contains user 1's row — the
    // whole collection, not the caller's slice (there is no caller).
    if let Some(list_path) = &list {
        t.push_str(&format!(
            "    let listed = t.get(\"{base}{list_path}\").await;\n    assert_eq!(listed.status().as_u16(), 200, \"anonymous list must 200 (public_read); body: {{}}\", listed.text());\n    let rows: serde_json::Value = serde_json::from_str(&listed.text()).expect(\"list json\");\n    let present = rows.as_array().map(|a| a.iter().any(|r| r[\"id\"] == id_value)).unwrap_or(false);\n    assert!(present, \"the anonymous list must contain ANOTHER user's row (public read serves the whole collection); body: {{}}\", listed.text());\n",
        ));
    }
    if get_one.is_some() {
        t.push_str(&format!(
            "    let detail = t.get(&format!(\"{base}/{{id}}\")).await;\n    assert_eq!(detail.status().as_u16(), 200, \"anonymous detail must 200 (public_read); body: {{}}\", detail.text());\n",
        ));
    }
    // OWNER WRITE: an anonymous create is rejected by the guard.
    t.push_str(&format!(
        "    let anon_create = t.post_json(\"{create_path}\", &serde_json::json!({body})).await;\n    assert_eq!(anon_create.status().as_u16(), 401, \"public_read never opens WRITES — an anonymous create must 401; body: {{}}\", anon_create.text());\n",
    ));
    if let Some(put) = put_one {
        let put_body = fixture_json(
            design,
            module,
            &entity.name,
            omits_identity_fk(design, module, put),
            None,
            true, // an UPDATE body keeps `default` fields ({Entity}UpdateRequest)
        );
        t.push_str(&format!(
            "    let foreign_put = t.put_json_with(&format!(\"{base}/{{id}}\"), &serde_json::json!({put_body}), &[(\"{hk}\", &test_cookie_for(2))]).await;\n    assert_eq!(foreign_put.status().as_u16(), 404, \"a non-owner update must 404 (use update_for, not update); body: {{}}\", foreign_put.text());\n",
        ));
    }
    if delete_one.is_some() {
        t.push_str(&format!(
            "    let foreign_del = t.delete_with(&format!(\"{base}/{{id}}\"), &[(\"{hk}\", &test_cookie_for(2))]).await;\n    assert_eq!(foreign_del.status().as_u16(), 404, \"a non-owner delete must 404 (use remove_for, not remove); body: {{}}\", foreign_del.text());\n",
        ));
    }
    if get_one.is_some() && (put_one.is_some() || delete_one.is_some()) {
        t.push_str(&format!(
            "    let survives = t.get(&format!(\"{base}/{{id}}\")).await;\n    assert_eq!(survives.status().as_u16(), 200, \"the row must SURVIVE a non-owner write attempt; body: {{}}\", survives.text());\n",
        ));
    }
    if let Some(put) = put_one {
        let put_body = fixture_json(
            design,
            module,
            &entity.name,
            omits_identity_fk(design, module, put),
            None,
            true,
        );
        t.push_str(&format!(
            "    let owner_put = t.put_json_with(&format!(\"{base}/{{id}}\"), &serde_json::json!({put_body}), &[(\"{hk}\", &test_cookie_for(1))]).await;\n    assert_eq!(owner_put.status().as_u16(), {status}, \"the OWNER's update must succeed; body: {{}}\", owner_put.text());\n",
            status = put.success.status,
        ));
    }
    t.push_str("}\n\n");
    t
}

/// The tenant-collection-create isolation/lifecycle test (REVIEWER I1): user 1
/// creates a tenant; user 1's immediate list-own returns it; user 2's list is
/// EMPTY of it. WHY (Rule 9): T3 left the bare `insert` reachable next to
/// `create_with_membership`; an agent who calls `insert` (skipping the membership
/// seed) leaves the tenant memberless — the creator is locked out and, worse, a
/// membership-filtered list can silently diverge. This test makes that failure
/// LOUD: it passes only when create seeds the creator's membership AND list scopes
/// to `all_for_member`. Emitted only when the tenant module has BOTH a guarded
/// `POST "/"` create and a guarded `GET "/"` list for the tenant entity — an
/// unguarded list (e.g. reference-slice `list_workspaces`) can't be membership-
/// scoped, so the test would be un-passable and is skipped.
fn tenant_collection_isolation_test(design: &Design, module: &ModuleDesign) -> String {
    let Some(tenancy) = design.tenancy.as_ref() else {
        return String::new();
    };
    // This module must DECLARE the tenant entity (be the tenant module).
    let Some(entity) = module.entities.iter().find(|e| e.name == tenancy.entity) else {
        return String::new();
    };
    let Some(create) = module.endpoints.iter().find(|ep| {
        ep.method == HttpMethod::POST
            && ep.path == "/"
            && ep.is_guarded()
            && ep
                .request_body
                .as_ref()
                .is_some_and(|rb| rb.entity == entity.name)
    }) else {
        return String::new();
    };
    // A GUARDED list at "/" — an unguarded list has no session to membership-scope
    // by, so it can't prove the second-user-empty contract; skip it there.
    if !module.endpoints.iter().any(|ep| {
        ep.method == HttpMethod::GET && ep.path == "/" && ep.is_guarded() && ep.success.list
    }) {
        return String::new();
    }
    let base = module.effective_mount();
    let base = base.trim_end_matches('/');
    let plural = module.name.replace('-', "_");
    let body = fixture_json(
        design,
        module,
        &entity.name,
        omits_identity_fk(design, module, create),
        None,
        false, // isolation seeds a row via create — a create body omits defaults
    );
    let hk = design.test_auth_header();
    format!(
        "/// SECURITY (#78, I1): creating a {entity} seeds ONLY the creator's membership.\n/// User 1 creates a {entity}; user 1's own list returns it; user 2's list is empty.\n/// Passes only when create uses `create_with_membership` (NOT the bare `insert`,\n/// which leaves the tenant memberless) and list uses `all_for_member`.\n#[tokio::test]\nasync fn creating_a_{plural2}_seeds_only_the_creators_membership() {{\n    let t = app().await;\n    let created = t.post_json_with(\"{base}/\", &serde_json::json!({body}), &[(\"{hk}\", &test_cookie_for(1))]).await;\n    assert_eq!(created.status().as_u16(), {status}, \"setup: user 1 creates a {entity}; body: {{}}\", created.text());\n    let row: serde_json::Value = serde_json::from_str(&created.text()).expect(\"created json\");\n    let id_value = row[\"id\"].clone();\n    let own = t.get_with(\"{base}/\", &[(\"{hk}\", &test_cookie_for(1))]).await;\n    assert_eq!(own.status().as_u16(), 200, \"user 1 lists their own {plural}; body: {{}}\", own.text());\n    let own_rows: serde_json::Value = serde_json::from_str(&own.text()).expect(\"own list json\");\n    let present = own_rows.as_array().map(|a| a.iter().any(|r| r[\"id\"] == id_value)).unwrap_or(false);\n    assert!(present, \"the creator's list MUST contain the new {entity} (create_with_membership seeds membership); body: {{}}\", own.text());\n    let other = t.get_with(\"{base}/\", &[(\"{hk}\", &test_cookie_for(2))]).await;\n    assert_eq!(other.status().as_u16(), 200, \"user 2 lists their own {plural}; body: {{}}\", other.text());\n    let other_rows: serde_json::Value = serde_json::from_str(&other.text()).expect(\"other list json\");\n    let absent = other_rows.as_array().map(|a| a.iter().all(|r| r[\"id\"] != id_value)).unwrap_or(true);\n    assert!(absent, \"a non-creator's list must NOT contain the new {entity} (use all_for_member); body: {{}}\", other.text());\n}}\n\n",
        entity = entity.name,
        plural2 = Design::to_snake(&entity.name),
        status = create.success.status,
    )
}

/// True when this module's acceptance file carries the #107 member-surface
/// tests: db+auth+tenancy and the module DECLARES the tenancy entity — the same
/// gate genroute's `emits_member_surface` uses, so the tests exist exactly where
/// the generated member routes do and every other module (and every non-tenancy
/// design) stays byte-identical.
fn emits_member_surface_tests(design: &Design, module: &ModuleDesign) -> bool {
    design.wants_db()
        && design.wants_auth()
        && design
            .tenancy
            .as_ref()
            .is_some_and(|t| module.entities.iter().any(|e| e.name == t.entity))
}

/// The member-management surface tests (issue #107, spec §D): list/add/re-role/
/// remove plus the SECURITY rules — the admin (`member_roles[0]`) gate (403), the
/// last-admin lockout (409 on demote AND remove), self-removal without the admin
/// role (204), and the role allow-list (422). WHY (Rule 9): the member routes are
/// TOOL-OWNED with REAL generated handlers (members.rs), so unlike the stub
/// probes these PASS on a fresh scaffold and turn RED only when the generated
/// surface itself breaks — they are the runtime backstop for the #107 rules, and
/// (like the enum reject probes) they are EXCLUDED from `expected_failing`.
///
/// `member_app()` seeds the tenant + memberships via RAW SQL (the same shape as
/// `tenant_seed`), never through the module's own creator: the creator is an
/// AGENT STUB on a fresh scaffold, so an HTTP-seeded setup would 500 before the
/// member surface was ever reached. User 1 holds the admin role; user 2 (when a
/// second role is declared) is the non-admin member the 403/self-removal probes
/// act as. The tests that NEED that non-admin second role (403, re-role, remove,
/// demote-409, self-leave) are emitted only for a multi-role design; a
/// single-role design keeps list/add/last-admin-409/422.
fn member_surface_tests(design: &Design, module: &ModuleDesign) -> String {
    if !emits_member_surface_tests(design, module) {
        return String::new();
    }
    let tenancy = design.tenancy.as_ref().expect("gated on tenancy");
    let Some(entity) = module.entities.iter().find(|e| e.name == tenancy.entity) else {
        return String::new();
    };
    let mount = module.effective_mount();
    let base = mount.trim_end_matches('/').to_string();
    let snake = Design::to_snake(&tenancy.entity);
    let table = design.table_name(&tenancy.entity);
    let members = format!("{snake}_members");
    let fk = Design::fk_column(&tenancy.entity);
    // The admin role is member_roles[0] by convention (JC0548 guarantees a
    // non-empty list at design time; the dead fallback matches genroute's).
    let admin = tenancy
        .member_roles
        .first()
        .map(String::as_str)
        .unwrap_or("member");
    let second = tenancy.member_roles.get(1).map(String::as_str);
    // A single-role design can only add another admin; a multi-role design adds
    // a NON-admin member (the spec's "non-admin role" add).
    let add_role = second.unwrap_or(admin);
    let hk = design.test_auth_header();
    let (cols, vals) = tenant_row_cols_vals(entity, "1", 1);
    let mut migration_items = String::new();
    collect_workspace_migration_items(design, module, &mut migration_items);
    let auth_extend = format!(".extend(jerrycan::auth::Auth::with_secret(\"{TEST_SECRET}\"))");
    let (_, ext_extends) = extension_wiring(design);
    let second_seed = second
        .map(|role| {
            format!(
                "    db.conn()\n        .execute_unprepared(\"INSERT INTO \\\"{members}\\\" (user_id, {fk}, role) VALUES (2, 1, '{role}')\")\n        .await\n        .expect(\"seed non-admin membership\");\n"
            )
        })
        .unwrap_or_default();

    let mut t = format!(
        "/// #107 member surface: TOOL-OWNED routes with REAL generated handlers, so\n/// these tests pass on a fresh scaffold and turn RED only if the generated\n/// surface (admin gate, last-admin lockout, self-removal, role allow-list)\n/// breaks. Seeded via raw SQL — the HTTP surface under test is exactly what\n/// removes that need from application code.\nasync fn member_app() -> TestApp {{\n    let db = jerrycan::db::Db::connect(\"sqlite::memory:\").await.expect(\"test db\");\n    db.migrate(&[\n{migration_items}    ])\n    .await\n    .expect(\"migrations\");\n    db.conn()\n        .execute_unprepared(\"INSERT INTO \\\"{table}\\\" ({cols}) VALUES ({vals})\")\n        .await\n        .expect(\"seed tenant row\");\n    db.conn()\n        .execute_unprepared(\"INSERT INTO \\\"{members}\\\" (user_id, {fk}, role) VALUES (1, 1, '{admin}')\")\n        .await\n        .expect(\"seed admin membership\");\n{second_seed}    App::new(){auth_extend}{ext_extends}.extend(db).provide_dep(shared::tenant).mount(\"{mount}\", module()).into_test()\n}}\n\n"
    );

    // list: any member sees the roster (the membership guard is the whole gate).
    t.push_str(&format!(
        "#[tokio::test]\nasync fn list_{snake}_members_returns_200() {{\n    let t = member_app().await;\n    let res = t.get_with(\"{base}/1/members\", &[(\"{hk}\", &test_cookie_for(1))]).await;\n    assert_eq!(res.status().as_u16(), 200, \"design: any member lists the roster; body: {{}}\", res.text());\n    let rows: serde_json::Value = serde_json::from_str(&res.text()).expect(\"roster json\");\n    let has_admin = rows.as_array().map(|a| a.iter().any(|m| m[\"user_id\"] == serde_json::json!(\"1\") && m[\"role\"] == serde_json::json!(\"{admin}\"))).unwrap_or(false);\n    assert!(has_admin, \"the roster must list the seeded {admin} (user 1); body: {{}}\", res.text());\n}}\n\n"
    ));
    // add: an admin adds a member (non-admin role when one is declared) → 201.
    t.push_str(&format!(
        "#[tokio::test]\nasync fn add_{snake}_member_returns_201() {{\n    let t = member_app().await;\n    let res = t.post_json_with(\"{base}/1/members\", &serde_json::json!({{\"user_id\": \"9\", \"role\": \"{add_role}\"}}), &[(\"{hk}\", &test_cookie_for(1))]).await;\n    assert_eq!(res.status().as_u16(), 201, \"design: an {admin} adds a member -> 201; body: {{}}\", res.text());\n}}\n\n"
    ));
    if let Some(role2) = second {
        // SECURITY: member management is admin-gated — a non-admin add is 403.
        t.push_str(&format!(
            "/// SECURITY (#107): member management is gated on the {admin} role — a\n/// {role2} may read the roster but must NOT be able to add members.\n#[tokio::test]\nasync fn add_{snake}_member_without_the_admin_role_is_403() {{\n    let t = member_app().await;\n    let res = t.post_json_with(\"{base}/1/members\", &serde_json::json!({{\"user_id\": \"9\", \"role\": \"{role2}\"}}), &[(\"{hk}\", &test_cookie_for(2))]).await;\n    assert_eq!(res.status().as_u16(), 403, \"design: member add requires the {admin} role — a {role2} must 403; body: {{}}\", res.text());\n}}\n\n"
        ));
        // set-role: the write must PERSIST (roster reflects it), not just 204.
        t.push_str(&format!(
            "#[tokio::test]\nasync fn set_{snake}_member_role_returns_204() {{\n    let t = member_app().await;\n    let res = t.patch_json_with(\"{base}/1/members/2\", &serde_json::json!({{\"role\": \"{admin}\"}}), &[(\"{hk}\", &test_cookie_for(1))]).await;\n    assert_eq!(res.status().as_u16(), 204, \"design: an {admin} re-roles a member -> 204; body: {{}}\", res.text());\n    let roster = t.get_with(\"{base}/1/members\", &[(\"{hk}\", &test_cookie_for(1))]).await;\n    let rows: serde_json::Value = serde_json::from_str(&roster.text()).expect(\"roster json\");\n    let promoted = rows.as_array().map(|a| a.iter().any(|m| m[\"user_id\"] == serde_json::json!(\"2\") && m[\"role\"] == serde_json::json!(\"{admin}\"))).unwrap_or(false);\n    assert!(promoted, \"the roster must reflect the new role (the PATCH must persist, not just 204); body: {{}}\", roster.text());\n}}\n\n"
        ));
        // remove: the delete must PERSIST (the member leaves the roster).
        // Fail-closed: the roster read-back must be 200 and an ARRAY without
        // user 2 — `unwrap_or(true)` would pass vacuously if the list route
        // broke (non-array body), like the set-role twin's `unwrap_or(false)`.
        t.push_str(&format!(
            "#[tokio::test]\nasync fn remove_{snake}_member_returns_204() {{\n    let t = member_app().await;\n    let res = t.delete_with(\"{base}/1/members/2\", &[(\"{hk}\", &test_cookie_for(1))]).await;\n    assert_eq!(res.status().as_u16(), 204, \"design: an {admin} removes a member -> 204; body: {{}}\", res.text());\n    let roster = t.get_with(\"{base}/1/members\", &[(\"{hk}\", &test_cookie_for(1))]).await;\n    assert_eq!(roster.status().as_u16(), 200, \"the roster read-back must succeed (the removal is verified against it); body: {{}}\", roster.text());\n    let rows: serde_json::Value = serde_json::from_str(&roster.text()).expect(\"roster json\");\n    let gone = rows.as_array().map(|a| a.iter().all(|m| m[\"user_id\"] != serde_json::json!(\"2\"))).unwrap_or(false);\n    assert!(gone, \"the removed member must leave the roster (the DELETE must persist); body: {{}}\", roster.text());\n}}\n\n"
        ));
        // SECURITY: demoting the sole admin would lock the tenant out of member
        // management (the write gate is admin-only) — 409, never applied.
        t.push_str(&format!(
            "/// SECURITY (#107): demoting the SOLE {admin} would leave nobody able to\n/// manage members (the write gate is {admin}-only) — the repo must refuse with 409.\n#[tokio::test]\nasync fn set_{snake}_member_role_last_admin_demotion_is_409() {{\n    let t = member_app().await;\n    let res = t.patch_json_with(\"{base}/1/members/1\", &serde_json::json!({{\"role\": \"{role2}\"}}), &[(\"{hk}\", &test_cookie_for(1))]).await;\n    assert_eq!(res.status().as_u16(), 409, \"design: demoting the sole {admin} must 409 (last-admin lockout); body: {{}}\", res.text());\n}}\n\n"
        ));
        // self-removal: any member may LEAVE without the admin role.
        t.push_str(&format!(
            "/// #107: self-removal (\"leave\") needs NO admin role — the guard already\n/// proved the caller's membership; only removing OTHERS is admin-gated.\n#[tokio::test]\nasync fn remove_{snake}_member_self_leave_returns_204() {{\n    let t = member_app().await;\n    let res = t.delete_with(\"{base}/1/members/2\", &[(\"{hk}\", &test_cookie_for(2))]).await;\n    assert_eq!(res.status().as_u16(), 204, \"design: a member removes their OWN membership without the {admin} role; body: {{}}\", res.text());\n}}\n\n"
        ));
    }
    // SECURITY: removing the sole admin is refused even as self-removal.
    t.push_str(&format!(
        "/// SECURITY (#107): removing the SOLE {admin} — even by themselves — would\n/// leave the tenant admin-less forever; the repo must refuse with 409.\n#[tokio::test]\nasync fn remove_{snake}_member_last_admin_is_409() {{\n    let t = member_app().await;\n    let res = t.delete_with(\"{base}/1/members/1\", &[(\"{hk}\", &test_cookie_for(1))]).await;\n    assert_eq!(res.status().as_u16(), 409, \"design: removing the sole {admin} must 409 (last-admin lockout); body: {{}}\", res.text());\n}}\n\n"
    ));
    // An out-of-set role must 422 (no DB CHECK backs the role column).
    t.push_str(&format!(
        "#[tokio::test]\nasync fn add_{snake}_member_rejects_out_of_range_role() {{\n    let t = member_app().await;\n    let res = t.post_json_with(\"{base}/1/members\", &serde_json::json!({{\"user_id\": \"9\", \"role\": \"{ENUM_REJECT_SENTINEL}\"}}), &[(\"{hk}\", &test_cookie_for(1))]).await;\n    assert_eq!(res.status().as_u16(), 422, \"design: a role outside member_roles must 422 (no DB CHECK backs the column); body: {{}}\", res.text());\n}}\n\n"
    ));
    t
}

/// A SQL literal for seeding a tenant-row column. Enum fields use their first
/// declared value (so a CHECK constraint passes); other fields use a type-shaped
/// literal. String/text literals are single-quoted for inline DDL execution.
fn seed_sql_value(f: &Field) -> String {
    if let Some(values) = &f.values
        && let Some(first) = values.first()
    {
        return format!("'{first}'");
    }
    // #80: a constrained field seeds an IN-RANGE literal (the row must clear
    // the migration CHECK and any later validated read), a `unique` one a
    // value DISTINCT from the probe fixture — the next value after the
    // fixture anchor / the 'seed-…' base fitted to the length bounds — so a
    // create probe on a pre-seeded row still can't 409 (#85). Both branches
    // gate on a constraint being present (byte-identity).
    if has_int_range(f) {
        return if f.unique {
            kth_in_range(f, 1)
        } else {
            clamp_int(1, f)
        }
        .to_string();
    }
    if has_len_range(f) {
        let s = if f.unique {
            fit_string("seed-test-value", f.min_len, f.max_len)
        } else {
            constrained_fixture_string(f)
        };
        return format!("'{s}'");
    }
    match f.field_type {
        // A `unique` String/Integer/Float shares its literal with the create-probe
        // body (`fixture_value`), so a create probe on a pre-seeded tenant row 409s
        // (#85). Seed a DISTINCT value for those. datetime/uuid seeds ('test-value')
        // already differ from their probe fixtures (a real timestamp / v4 uuid), so
        // they stay unchanged; boolean/json are never realistic unique keys.
        FieldType::String if f.unique => "'seed-test-value'".to_string(),
        FieldType::Integer if f.unique => "1000".to_string(),
        FieldType::Float if f.unique => "1000.0".to_string(),
        FieldType::String | FieldType::Datetime | FieldType::Uuid => "'test-value'".to_string(),
        FieldType::Integer => "1".to_string(),
        FieldType::Float => "1.0".to_string(),
        FieldType::Boolean => "false".to_string(),
        FieldType::Json => "'{}'".to_string(),
    }
}

/// A SQL literal for seeding the Nth tenant's row, made DISTINCT from earlier
/// tenants so a `unique` non-PK column (e.g. `Workspace.slug`) doesn't collide
/// when the isolation test seeds tenant 2. Tenant 1 (`n == 1`) is byte-identical
/// to `seed_sql_value` (keeps every existing seed unchanged). Enum fields stay
/// fixed at the first declared value — they can't vary without violating the
/// CHECK — which is safe because an enum column is not the unique key in practice.
fn seed_sql_value_n(f: &Field, n: u32) -> String {
    if n == 1 {
        return seed_sql_value(f);
    }
    if let Some(values) = &f.values
        && let Some(first) = values.first()
    {
        return format!("'{first}'");
    }
    // #80: the Nth tenant's constrained literals stay in-range; a `unique`
    // integer takes the Nth distinct in-range value (the fixture anchor is the
    // 0th, the tenant-1 seed the 1st), a string keeps its `-{n}` discriminator
    // through the length fit. Gated on a constraint being present.
    if has_int_range(f) {
        return if f.unique {
            kth_in_range(f, i64::from(n))
        } else {
            clamp_int(i64::from(n), f)
        }
        .to_string();
    }
    if has_len_range(f) {
        return format!("'{}'", constrained_seed_string_n(f, n));
    }
    match f.field_type {
        FieldType::String | FieldType::Datetime | FieldType::Uuid => format!("'test-value-{n}'"),
        FieldType::Integer => n.to_string(),
        FieldType::Float => format!("{n}.0"),
        FieldType::Boolean => "false".to_string(),
        FieldType::Json => "'{}'".to_string(),
    }
}

/// The mirrored-extension wiring for the db-mode `app()` harness (issue #66):
/// `(comment, extends)`. `extends` is the `.extend(...)` chain for the design's
/// declared storage/jobs/realtime extensions (in mounting.rs's order: storage,
/// jobs, realtime — all before `.extend(db)`), each test-env-safe. `comment` is a
/// documented header (only emitted when something is wired) recording the wired
/// set AND the deliberately-excluded extensions. Both are empty for a design that
/// declares none of these — that harness stays byte-identical (no-drift).
fn extension_wiring(design: &Design) -> (String, String) {
    let mut extends = String::new();
    if design.wants_storage() {
        // In-memory store + a fixed dev sign key: no `from_env`/secret env needed.
        extends.push_str(&format!(
            ".extend(jerrycan::storage::Storage::memory().with_sign_secret(\"{TEST_SECRET}\"))"
        ));
    }
    if design.wants_jobs() {
        // The worker/cron `on_serve` loops don't spawn under `into_test()`.
        extends.push_str(".extend(jerrycan::jobs::Jobs::postgres(db.clone()))");
    }
    if design.wants_realtime() {
        // Resolves `Dep<RealtimeHandle>` for realtime handlers (no JC1001) AND
        // declares the app's broadcast/presence topics on the extension — the SAME
        // topics the realtime crate wires (realtimegen::wiring_rs). Without them a
        // handler that publishes to a topic hits JC0404 (undeclared topic) on a bare
        // `Realtime::new`, so the probe is un-greenable (issue #84). Changes channels
        // are omitted: they need Postgres (never exercised by a sqlite TestApp) and
        // are not `RealtimeHandle::publish` targets.
        extends.push_str(&format!(
            ".extend(jerrycan::realtime::Realtime::new(db.clone()){})",
            super::realtimegen::topic_wiring_inline(design)
        ));
    }
    if extends.is_empty() {
        return (String::new(), String::new());
    }
    let comment =
        "// TestApp extension wiring (issue #66) mirrors main.rs so the generated probes\n\
        // exercise the SAME app the framework builds: the design's declared\n\
        // storage/jobs/realtime extensions are wired below (jobs/realtime take\n\
        // db.clone() before `.extend(db)` moves db; jobs' worker/cron loops are\n\
        // on_serve tasks that into_test() never spawns). EXCLUDED here: observe\n\
        // (no handler resolves it — only /healthz, /metrics, access-log middleware)\n\
        // and validate (its OpenApi extension include_str!s an absent openapi.json,\n\
        // and probes send valid fixtures). Cover any excluded surface yourself.\n"
            .to_string();
    (comment, extends)
}

/// `emit_app`: false when the module's only tests are the #107 member-surface
/// tests (every design endpoint is an AGENT TODO) — the regular `app()` helper
/// would then be dead code and trip the generated workspace's `-D warnings`, so
/// only the helpers the member tests use (imports, cookie mint) are emitted.
fn preamble(design: &Design, module: &ModuleDesign, uses_cookies: bool, emit_app: bool) -> String {
    let mount = module.effective_mount();
    // The cookie helpers (`test_cookie`/`test_cookie_for`) are only emitted when
    // the module's generated tests actually reference them — a module with no
    // guarded endpoint and no isolation test (e.g. a public webhook or OAuth
    // callback) would otherwise carry dead `test_cookie` fns that trip
    // `-D warnings`.
    let auth_login = if design.wants_auth() && uses_cookies {
        auth_preamble_login(design)
    } else {
        String::new()
    };
    // The auth extension must register before the guards resolve it; it leads the
    // App chain (and shares TEST_SECRET with test_cookie()).
    let auth_extend = if design.wants_auth() {
        format!(".extend(jerrycan::auth::Auth::with_secret(\"{TEST_SECRET}\"))")
    } else {
        String::new()
    };
    if design.wants_db() {
        // Migrate the FULL workspace schema (issue #14), not just this module's
        // tables: a handler may legitimately write another module's table, which
        // would 500 with "no such table" under a module-only TestApp. This also
        // subsumes the old tenant-module cross-include (the `{tenant}_members`
        // table the Tenant guard queries is now always present). Tenancy still
        // needs (b) a seeded membership row so the guard resolves a tenant (not
        // 403) and (c) the `tenant` factory registered so `Dep<Tenant>` resolves.
        let mut migration_items = String::new();
        collect_workspace_migration_items(design, module, &mut migration_items);
        let seed = tenant_seed(design, module);
        let tenant_dep = if module_provides_tenant_dep(design, module) {
            ".provide_dep(shared::tenant)"
        } else {
            ""
        };
        // The second-tenant seed helper exists only for tenant-owned modules (the
        // ones whose isolation test acts as a second user). app() always seeds it
        // so success tests (user 1, tenant 1) are unaffected and the isolation test
        // finds tenant 2 already present.
        let second_seed_fn = seed_second_tenant_fn(design, module);
        let second_seed_call = if second_seed_fn.is_empty() {
            String::new()
        } else {
            "    seed_second_tenant(&db).await;\n".to_string()
        };
        // The seed runs raw SQL on the connection, which needs `ConnectionTrait`
        // in scope; only import it when there's a seed OR the #107 member tests
        // (whose member_app() also seeds raw SQL) — else `-D warnings` trips.
        let seed_use = if seed.is_empty() && !emits_member_surface_tests(design, module) {
            String::new()
        } else {
            "use jerrycan::db::sea_orm::ConnectionTrait;\n\n".to_string()
        };
        if !emit_app {
            // Only the member-surface tests exist: no app(), no seeds, no
            // second-tenant helper — member_app() is self-contained.
            return format!("{seed_use}{auth_login}");
        }
        // Issue #66: the TestApp must wire the SAME design-declared extensions
        // main.rs does (mounting.rs's `extension_block`), so the generated probes
        // exercise the app the framework actually builds — a realtime handler's
        // `Dep<RealtimeHandle>` resolves (no JC1001 500) and a jobs design's app
        // constructs. Order + `db.clone()` mirror mounting.rs (extensions precede
        // `.extend(db)`, which moves `db`). Test-env realities: storage uses an
        // in-memory store (no `from_env`/secret env), and the jobs worker/cron
        // loops are `on_serve` tasks that `into_test()` never spawns, so wiring
        // Jobs starts no background loop. EXCLUDED, by design: `observe` (adds only
        // /healthz + /metrics + an access-log middleware — no handler resolves it,
        // so its absence never 500s a probe) and `validate` (its OpenApi extension
        // `include_str!`s app/openapi.json, which does not exist relative to a
        // route crate's test; and probes send valid fixtures, so wire-level
        // validation is not needed). See the harness comment emitted below.
        let (ext_comment, ext_extends) = extension_wiring(design);
        format!(
            "{seed_use}{auth_login}{second_seed_fn}{ext_comment}async fn app() -> TestApp {{\n    let db = jerrycan::db::Db::connect(\"sqlite::memory:\").await.expect(\"test db\");\n    db.migrate(&[\n{migration_items}    ])\n    .await\n    .expect(\"migrations\");\n{seed}{second_seed_call}    App::new(){auth_extend}{ext_extends}.extend(db){tenant_dep}.mount(\"{mount}\", module()).into_test()\n}}\n"
        )
    } else {
        format!(
            "{auth_login}async fn app() -> TestApp {{\n    App::new(){auth_extend}.mount(\"{mount}\", module()).into_test()\n}}\n"
        )
    }
}

/// The full tests/acceptance.rs for one top-level module.
pub fn acceptance_rs(design: &Design, module: &ModuleDesign) -> String {
    render_acceptance(design, module).0
}

/// Renders the acceptance file AND the count of generated tests that PASS on
/// stubs — the enum "reject" probes (issue #47) and the #107 member-surface
/// tests (tool-owned real handlers) — which `write_acceptance` subtracts from
/// `expected_failing` so the RED-on-stubs baseline stays exact.
fn render_acceptance(design: &Design, module: &ModuleDesign) -> (String, usize) {
    let mut out = TestOut {
        code: String::new(),
        todos: Vec::new(),
        count: 0,
        reject: 0,
        auth: design.wants_auth(),
    };
    unit_tests(design, module, &module.effective_mount(), &mut out);
    // Cross-tenant isolation: the security contract for tenant-owned modules.
    // Appended after the per-endpoint tests; counts toward expected_failing
    // (it fails on stubs like every other generated test).
    let isolation = isolation_test(design, module);
    out.count += isolation.matches("#[tokio::test]").count();
    out.code.push_str(&isolation);
    // #107: the member-surface tests run against TOOL-OWNED real handlers, so
    // they PASS on stubs — appended after the isolation tests and, like the
    // enum reject probes, EXCLUDED from the RED-on-stubs baseline. Whether the
    // regular app() helper is needed is decided BEFORE appending them (a
    // tenant module whose every endpoint is a TODO has member tests only).
    let emit_app = out.code.contains("#[tokio::test]");
    let member = member_surface_tests(design, module);
    let member_passing = member.matches("#[tokio::test]").count();
    out.code.push_str(&member);
    let todos = if out.todos.is_empty() {
        String::new()
    } else {
        format!("\n{}\n", out.todos.join("\n"))
    };
    let banner = "//! GENERATED by jerrycan gen-tests — TOOL-OWNED acceptance criteria from design.json.\n//! Regenerated on demand; add your own tests in sibling files, not here.\n";
    // A module whose every endpoint is a TODO (e.g. a billing module whose only
    // route is a signature-gated webhook) emits ZERO #[tokio::test] functions. The
    // preamble's `app()` helper and the `use` imports would then be dead code and
    // trip the generated workspace's `-D warnings`. Emit only the banner + the
    // TODOs in that case — there is nothing for the imports/app() to support.
    if !out.code.contains("#[tokio::test]") {
        return (format!("{banner}{todos}"), out.reject);
    }
    // Only emit the cookie helpers if the rendered tests reference them (a module
    // with no guarded endpoint and no isolation test uses neither).
    let uses_cookies = out.code.contains("test_cookie");
    let content = format!(
        "{banner}use jerrycan::prelude::*;\nuse {ident}::module;\n\n{preamble}\n{code}{todos}",
        ident = super::genroute::crate_ident(&module.name),
        preamble = preamble(design, module, uses_cookies, emit_app),
        code = out.code,
    );
    (content, out.reject + member_passing)
}

/// Write tests/acceptance.rs for a TOP-LEVEL module. Returns (rel_path, expected_failing).
pub fn write_acceptance(
    root: &std::path::Path,
    design: &Design,
    module_name: &str,
) -> Result<(String, usize), String> {
    let Some(module) = design.modules.iter().find(|m| m.name == module_name) else {
        return Err(format!(
            "module `{module_name}` not found in design.json (top-level modules only)"
        ));
    };
    let (content, reject) = render_acceptance(design, module);
    let rel = format!("crates/routes/{module_name}/tests/acceptance.rs");
    let path = root.join(&rel);
    std::fs::create_dir_all(path.parent().expect("parent")).map_err(|e| e.to_string())?;
    std::fs::write(&path, &content).map_err(|e| e.to_string())?;
    // Enum reject tests (issue #47) and the #107 member-surface tests pass on
    // stubs, so they are NOT part of the RED-on-stubs baseline: exclude them
    // from `expected_failing`.
    Ok((rel, test_count(&content) - reject))
}

/// The outcome of generating every module's acceptance suite plus the jobs
/// suite — the shared core of the "all modules" path used by both the CLI's
/// bare `gen-tests` and the MCP `jerrycan_gen_tests` with no `module` (#159).
/// Each caller formats its own `next_step`/human envelope from these pieces.
pub struct AllAcceptance {
    /// Written suite paths, in order: one per endpoint-bearing module, then jobs.
    pub tests_created: Vec<String>,
    /// Aggregate expected-failing count (the jobs suite counted exactly once).
    pub expected_failing: usize,
    /// The cargo packages the suites live in: `route-{module}` …, then `jobs`.
    pub packages: Vec<String>,
    /// Whether the design declared jobs (a jobs suite was written).
    pub has_jobs: bool,
}

/// Generate one acceptance suite per endpoint-bearing top-level module, plus the
/// jobs suite once — the all-modules path shared by the CLI's bare `gen-tests`
/// and the MCP `jerrycan_gen_tests` with no `module`. Module selection mirrors
/// the JC0551 step (`checkpipe::missing_acceptance_tests`): a subroute's
/// endpoints count toward its parent (their tests live in the parent's crate),
/// so this clears every JC0551 the check can raise — including the jobs one on a
/// jobs-only design, which has no module name to pass. Each file is byte-identical
/// to what `write_acceptance` produces per module.
pub fn write_all_acceptance(
    root: &std::path::Path,
    design: &Design,
) -> Result<AllAcceptance, String> {
    fn endpoint_count(m: &ModuleDesign) -> usize {
        m.endpoints.len() + m.subroutes.iter().map(endpoint_count).sum::<usize>()
    }
    let mut tests_created: Vec<String> = Vec::new();
    let mut expected_failing = 0usize;
    let mut packages: Vec<String> = Vec::new();
    for m in design.modules.iter().filter(|m| endpoint_count(m) > 0) {
        let (rel, c) = write_acceptance(root, design, &m.name)?;
        tests_created.push(rel);
        expected_failing += c;
        packages.push(format!("route-{}", m.name));
    }
    // Jobs are top-level (not per-module): their suite is written ONCE, so its
    // count is added to the aggregate exactly once.
    let jobs = super::jobsgen::write_jobs_acceptance(root, design)?;
    let has_jobs = jobs.is_some();
    if let Some((jobs_rel, jobs_count)) = jobs {
        tests_created.push(jobs_rel);
        expected_failing += jobs_count;
        packages.push("jobs".to_string());
    }
    Ok(AllAcceptance {
        tests_created,
        expected_failing,
        packages,
        has_jobs,
    })
}

/// How many #[tokio::test] functions a generated file contains.
pub fn test_count(generated: &str) -> usize {
    generated.matches("#[tokio::test]").count()
}