jerrycan 0.7.20

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
//! jerrycan-specific lints (spec §5.3 ring 3). v0 set:
//! JL0001 route-crate lib.rs exports more than `module()`
//! JL0002 handler names don't match design operation_ids
//! JL0003 a generated (tool-owned) file was hand-edited
//! JL0004 an auth design leaves a mutating route unguarded
//! JL0006 a tenant-owned handler calls an UNSCOPED repo method (cross-tenant read)
//! JL0007 agent-owned module code reaches outside the request boundary (process/fs/net)
//! JL0008 a tenant-owned handler could not be read/parsed, so its scoping is unverified

use super::checkpipe::Diagnostic;
use super::design::{Design, HandlerRef, HttpMethod, ModuleDesign};
use super::mounting;
use std::collections::BTreeSet;
use std::path::Path;

fn d(
    code: &str,
    file: Option<String>,
    line: Option<u64>,
    message: String,
    suggestion: &str,
    doc: &str,
) -> Diagnostic {
    Diagnostic {
        code: code.into(),
        file,
        line,
        message,
        suggestion: Some(suggestion.into()),
        doc_url: Some(doc.into()),
    }
}

pub fn run(root: &Path, design: &Design) -> Vec<Diagnostic> {
    let mut out = Vec::new();
    for m in &design.modules {
        lint_public_surface(root, m, &mut out);
        lint_handlers(root, m, &format!("crates/routes/{}/src", m.name), &mut out);
    }
    lint_generated_drift(root, design, &mut out);
    lint_unguarded_mutations(design, &mut out);
    lint_unscoped_tenant_queries(root, design, &mut out);
    lint_boundary_escapes(root, design, &mut out);
    out
}

/// JL0007: agent-owned module code that reaches outside the request boundary —
/// process spawning, filesystem, or raw network. Handler code is agent-authored
/// untrusted input (see the threat model); the framework's contract is that I/O
/// goes through its extensions, not direct std::/tokio:: process/fs/net calls.
///
/// We scan the whole agent-owned file set of every module and subroute
/// (handlers.rs, repo.rs, deps.rs, model.rs) for the needles below. A line whose
/// trimmed start is `//` is prose, not code, and is skipped; a line ending in the
/// allow-hatch suffix is an explicit, line-scoped opt-out and is not flagged.
fn lint_boundary_escapes(root: &Path, design: &Design, out: &mut Vec<Diagnostic>) {
    const NEEDLES: [&str; 6] = [
        "std::process::",
        "std::fs::",
        "std::net::",
        "tokio::process::",
        "tokio::fs::",
        "tokio::net::",
    ];
    const ALLOW: &str = "// jerrycan:allow JL0007";
    const FILES: [&str; 4] = ["handlers.rs", "repo.rs", "deps.rs", "model.rs"];

    // Every agent-owned file, relative to root, across modules and subroutes.
    let mut rels: Vec<String> = Vec::new();
    fn collect(src_rel: &str, m: &ModuleDesign, files: &[&str], rels: &mut Vec<String>) {
        for f in files {
            rels.push(format!("{src_rel}/{f}"));
        }
        for sub in &m.subroutes {
            collect(
                &format!("{src_rel}/subroutes/{}", sub.name.replace('-', "_")),
                sub,
                files,
                rels,
            );
        }
    }
    for m in &design.modules {
        collect(
            &format!("crates/routes/{}/src", m.name),
            m,
            &FILES,
            &mut rels,
        );
    }

    for rel in rels {
        let Ok(content) = std::fs::read_to_string(root.join(&rel)) else {
            continue; // model.rs/repo.rs are absent in memory mode; that's fine
        };
        for (i, line) in content.lines().enumerate() {
            // A whole-line comment is prose, not code.
            if line.trim_start().starts_with("//") {
                continue;
            }
            if !NEEDLES.iter().any(|n| line.contains(n)) {
                continue;
            }
            // Line-scoped escape hatch.
            if line.trim_end().ends_with(ALLOW) {
                continue;
            }
            out.push(d(
                "JL0007",
                Some(rel.clone()),
                Some(i as u64 + 1),
                "handler code reaches outside the request boundary (process/fs/net)".into(),
                "use framework extensions for I/O; if this is genuinely intended, append `// jerrycan:allow JL0007` to the line",
                "jerrycan docs errors",
            ));
        }
    }
}

/// JL0006: a handler in an OWNER-SCOPED module calls an UNSCOPED repo method
/// (`repo.all()`, `repo.get(…)`, `repo.remove(…)`, `repo.update(…)`, and — on a
/// FLAT tenant module only — `repo.insert(…)`). Those read/write/delete across ALL
/// owners, leaking rows:
///   - a TENANT-owned module — an entity that resolves to a tenant path directly OR
///     transitively (#102: a grandchild through a parent chain) → another tenant's
///     rows;
///   - a per-user IDENTITY-owned module (#79 — an entity belongs_to the auth
///     identity, not tenant-scoped) → another user's rows. For these the unscoped
///     methods are additionally NOT generated (genroute make-impossible), so this
///     lint is belt-and-suspenders: it gives a precise, actionable fix instead of a
///     raw `no method all` compile error.
///
/// Detection is AST-based (`syn::parse_file` + a `Visit` walk), not a substring
/// scan (issue #103): the substring scan missed a call split across lines
/// (`repo\n  .all()`) and could be fooled by a rename/alias, and — worse — it built
/// a FLAT path (`crates/routes/{module}/src/handlers.rs`) for every module, so a
/// NESTED or transitively-owned handler resolved to a nonexistent file and was
/// silently skipped (the hole that let the #102 leak ship). The path now comes from
/// [`Design::tenant_owned_handlers`], which nests `subroutes/{seg}` exactly as the
/// scaffold writes them. A mention of `repo.all()` in a COMMENT is not a call, so
/// the AST never flags it; the `*_for`/`*_for_memberships` scoped accessors are
/// excluded for free (they are different method idents). `syn::visit` does not
/// descend into MACRO token streams, so the walk additionally scans each macro's
/// raw tokens for those same needles (`UnscopedVisitor::scan_macro`) — otherwise an
/// unscoped call wrapped in `json!`/`format!`/… would evade the lint (the pre-branch
/// substring scanner caught single-line macro-wrapped calls; this restores that).
///
/// `repo.insert(…)` is flagged ONLY on a FLAT (membership-set) tenant module (#94):
/// there the create reads the tenant fk from the request BODY, so a bare insert
/// trusts it (the create leak); the fix is `create_for_memberships`. A path-scoped
/// create pins the fk to the verified tenant, and a per-user create gets the
/// server-injected identity fk — both safe — so insert is not flagged there.
///
/// A line ending in `// jerrycan:allow JL0006` (the call's own source line) is an
/// explicit, line-scoped opt-out (e.g. a create that pins the fk to a
/// membership-verified value) — same hatch JL0007 offers.
///
/// We scan ONLY the agent-owned handlers.rs (where the call happens), never
/// repo.rs: the generated repo's own scoped methods call `Entity::...` directly,
/// not `self.all()`, so repo.rs never legitimately matches — and scanning it
/// would flag the unscoped methods the scoped ones are meant to replace.
///
/// FAIL LOUD: a tenant-owned handler that is missing, unreadable, or does NOT parse
/// becomes a [`JL0008`](scan_unscoped) diagnostic — never a silent skip, which is
/// exactly how #103 hid a leak. Per-user identity handlers are not part of that
/// hole and are skipped quietly when absent (memory-mode designs have no files).
fn lint_unscoped_tenant_queries(root: &Path, design: &Design, out: &mut Vec<Diagnostic>) {
    // Tenant-owned handlers (transitive #102, nested-path-aware #103) scan LOUD.
    let tenant = design.tenant_owned_handlers();
    let covered: BTreeSet<&str> = tenant.iter().map(|h| h.rel_path.as_str()).collect();
    for h in &tenant {
        scan_unscoped(root, h, true, true, out);
    }
    // Per-user IDENTITY-owned modules (#79) leak ACROSS USERS. Top-level only, flat
    // path, NOT fail-loud (not part of the #103 tenant hole). Skip any module a
    // tenant handler already covers at the same path.
    for module in identity_owned_modules(design) {
        let rel = format!("crates/routes/{module}/src/handlers.rs");
        if covered.contains(rel.as_str()) {
            continue;
        }
        // public_read (#105): when EVERY per-user entity this module owns is
        // public_read, its unscoped `repo.all()`/`get(` READS are legitimate (the
        // repo emits them for the public GETs) — restrict the needles to the
        // writes. A MIXED module (any non-public per-user entity) keeps the read
        // needles: the scan can't tell which repo an unscoped call targets, so it
        // stays conservative (the line-scoped allow-hatch covers the false
        // positive; a missed real read leak would have nothing).
        let reads_public = design
            .modules
            .iter()
            .find(|m| m.name == module)
            .is_some_and(|m| {
                m.entities
                    .iter()
                    .filter(|e| design.entity_is_per_user_owned(e))
                    .all(|e| design.entity_is_public_read(&e.name))
            });
        let h = HandlerRef {
            rel_path: rel,
            is_flat: false,
            owned_desc: "an identity-owned",
            leak_desc: "another user's rows",
            suggestion: if reads_public {
                "route the write through the owner-scoped accessors (update_for/remove_for) with the session user's id (_user.0.id); reads are public on this public_read module".to_string()
            } else {
                "call the owner-scoped accessor (all_for/get_for/remove_for) with the session user's id (_user.0.id)".to_string()
            },
            // The #124 exemption is tenant-only (a path-verified Dep<Tenant>
            // guard); per-user refs never exempt anything, so the #147 signature
            // markers are unused here (empty exempt_fns → never consulted).
            exempt_fns: BTreeSet::new(),
            tenant_repo_type: String::new(),
            tenant_guard_type: String::new(),
        };
        scan_unscoped(root, &h, false, !reads_public, out);
    }
}

/// Read one handler file and flag every unscoped repo call in it. `fail_loud`
/// (tenant-owned handlers) turns a missing, unreadable, or unparseable file into a
/// LOUD JL0008 instead of a silent skip (issue #103) — a handler whose scoping
/// cannot be checked is exactly where an unscoped cross-tenant call would hide.
/// `flag_reads` is false ONLY for a public_read per-user module (#105), where the
/// unscoped `repo.all()`/`get(` reads are the generated public surface — the
/// write needles always stay armed.
fn scan_unscoped(
    root: &Path,
    h: &HandlerRef,
    fail_loud: bool,
    flag_reads: bool,
    out: &mut Vec<Diagnostic>,
) {
    let content = match std::fs::read_to_string(root.join(&h.rel_path)) {
        Ok(c) => c,
        Err(_) => {
            if fail_loud {
                out.push(jl0008(&h.rel_path));
            }
            return;
        }
    };
    let ast = match syn::parse_file(&content) {
        Ok(f) => f,
        Err(_) => {
            if fail_loud {
                out.push(jl0008(&h.rel_path));
            }
            return;
        }
    };
    let src: Vec<&str> = content.lines().collect();
    let mut v = UnscopedVisitor {
        hits: Vec::new(),
        flag_insert: h.is_flat,
        flag_reads,
        exempt_fns: &h.exempt_fns,
        expected_repo_type: &h.tenant_repo_type,
        guard_marker: &h.tenant_guard_type,
        fn_stack: Vec::new(),
        src: &src,
    };
    syn::visit::Visit::visit_file(&mut v, &ast);
    for (line, call) in v.hits {
        out.push(d(
            "JL0006",
            Some(h.rel_path.clone()),
            Some(line as u64),
            format!(
                "handler calls the unscoped `repo.{call}` on {} repo — it can read, write, or delete {}",
                h.owned_desc, h.leak_desc
            ),
            &h.suggestion,
            "jerrycan docs database",
        ));
    }
}

/// JL0008: a tenant-owned handler could not be read/parsed, so its scoping is
/// UNVERIFIED. Loud on purpose — the #103 regression was a silent skip in exactly
/// this spot.
fn jl0008(rel: &str) -> Diagnostic {
    d(
        "JL0008",
        Some(rel.to_string()),
        None,
        format!(
            "tenant-owned handler `{rel}` could not be scanned for scoping — it is missing, unreadable, or not valid Rust, so an unscoped cross-tenant call could pass unseen"
        ),
        "ensure the handler file exists and compiles (run `cargo check`); a scaffold is generated parseable — if you hand-edited it, fix the syntax so `jerrycan check` can verify tenant scoping",
        "jerrycan docs database",
    )
}

/// Issue #147: if `ty` is `Dep<T>` (outer type `Dep`, exactly one generic type
/// arg), the inner type's LAST path segment ident — else `None`. Lenient on the
/// leading path on both levels (`jerrycan::Dep<shared::Tenant>` → `Tenant`), exact
/// on the final ident, so the signature check compares against `Tenant` /
/// `{Tenant}Repo` the same way the generated `Dep<…>` params are written.
fn dep_inner_last_segment(ty: &syn::Type) -> Option<String> {
    let syn::Type::Path(tp) = ty else { return None };
    let seg = tp.path.segments.last()?;
    if seg.ident != "Dep" {
        return None;
    }
    let syn::PathArguments::AngleBracketed(args) = &seg.arguments else {
        return None;
    };
    if args.args.len() != 1 {
        return None;
    }
    let syn::GenericArgument::Type(syn::Type::Path(inner)) = args.args.first()? else {
        return None;
    };
    Some(inner.path.segments.last()?.ident.to_string())
}

/// True when a param pattern is exactly the ident `name` (e.g. `repo` or
/// `mut repo`) — issue #147's tenant-own-repo binding check.
fn pat_is_ident(pat: &syn::Pat, name: &str) -> bool {
    matches!(pat, syn::Pat::Ident(pi) if pi.ident == name)
}

/// True when `expr` is (syntactically) the `repo` binding — a bare `repo` path,
/// possibly wrapped in parens/refs/groups. A genuinely aliased binding falls
/// through to no-hit (acceptable: the steering trains `repo.` usage).
fn receiver_is_repo(expr: &syn::Expr) -> bool {
    match expr {
        syn::Expr::Path(p) => p.path.is_ident("repo"),
        syn::Expr::Paren(p) => receiver_is_repo(&p.expr),
        syn::Expr::Group(g) => receiver_is_repo(&g.expr),
        syn::Expr::Reference(r) => receiver_is_repo(&r.expr),
        _ => false,
    }
}

/// Walks a parsed handler file for `repo.<unscoped>(…)` calls. Exact method-name
/// matching excludes every `*_for`/`*_for_memberships` scoped accessor for free
/// (they are different idents). `insert` is flagged only on a FLAT tenant module
/// (#94). Each hit records the call's real source line (via `span-locations`), and
/// a `// jerrycan:allow JL0006` on that line is an explicit, line-scoped opt-out.
///
/// `syn::visit` does NOT descend into MACRO token streams, so an unscoped call
/// wrapped in a macro (e.g. `Json(serde_json::json!({ "items": repo.all().await? }))`
/// — a tenant-owned handler that returns every tenant's rows) is invisible to the
/// method-call walk. The `visit_*_macro` arms below close that gap by scanning each
/// macro's raw tokens for the same needles the pre-branch substring scanner caught.
struct UnscopedVisitor<'a> {
    hits: Vec<(usize, &'static str)>,
    flag_insert: bool,
    /// False only on a public_read per-user module (#105): the unscoped
    /// `all`/`get` reads are the legitimate public surface there, so only the
    /// write needles stay armed.
    flag_reads: bool,
    /// Fn names (operation_ids) whose `get`/`update`/`remove`/`insert` hits are
    /// exempt (#124): the tenant's own PathScoped detail handlers. `all()` is
    /// NEVER exempt — see [`HandlerRef::exempt_fns`]. The exemption is honored
    /// only when the fn's SIGNATURE also qualifies (#147, see `fn_stack`).
    exempt_fns: &'a BTreeSet<String>,
    /// The tenant's own repo type `{Tenant}Repo` (#147): an exempt-named fn is
    /// honored only if it binds a param `repo` of type `Dep<{Tenant}Repo>`.
    expected_repo_type: &'a str,
    /// The membership-guard marker `Tenant` (#147): an exempt-named fn is honored
    /// only if it ALSO binds a `Dep<…Tenant>`-typed param (the guard, any name).
    guard_marker: &'a str,
    /// Enclosing-`fn` frames, innermost last (#124/#147): `(name, exempt_qualified)`
    /// where `exempt_qualified` is the #147 signature check (both the `Dep<Tenant>`
    /// guard AND a `repo: Dep<{Tenant}Repo>` param are present). Each hit attributes
    /// to its handler. A stack, not a slot: a nested named fn attributes to
    /// ITSELF, and a helper is never an operation_id → it stays armed
    /// (under-suppress, never over-suppress).
    fn_stack: Vec<(String, bool)>,
    src: &'a [&'a str],
}

impl<'ast> syn::visit::Visit<'ast> for UnscopedVisitor<'_> {
    // #124: frame every named fn (free or impl method) so a hit attributes to
    // the innermost one. Closures keep their enclosing frame — inline closure
    // code is part of the handler body.
    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
        let qualified = self.signature_qualifies_for_exempt(&node.sig.inputs);
        self.fn_stack.push((node.sig.ident.to_string(), qualified));
        syn::visit::visit_item_fn(self, node);
        self.fn_stack.pop();
    }
    fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
        let qualified = self.signature_qualifies_for_exempt(&node.sig.inputs);
        self.fn_stack.push((node.sig.ident.to_string(), qualified));
        syn::visit::visit_impl_item_fn(self, node);
        self.fn_stack.pop();
    }

    fn visit_expr_method_call(&mut self, c: &'ast syn::ExprMethodCall) {
        let name = c.method.to_string();
        // `all` takes no args (the scoped accessors carry the owner id); the others
        // match on the exact ident, so `all_for`/`get_for`/… never match.
        let display = match name.as_str() {
            "all" if c.args.is_empty() && self.flag_reads => Some("all()"),
            "get" if self.flag_reads => Some("get(...)"),
            "remove" => Some("remove(...)"),
            "update" => Some("update(...)"),
            "insert" if self.flag_insert => Some("insert(...)"),
            _ => None,
        };
        if let Some(display) = display
            && receiver_is_repo(&c.receiver)
            && self.armed_in_current_fn(display)
        {
            let line = c.method.span().start().line;
            let allowed = self
                .src
                .get(line.saturating_sub(1))
                .is_some_and(|l| l.trim_end().ends_with("// jerrycan:allow JL0006"));
            if !allowed {
                self.hits.push((line, display));
            }
        }
        // Recurse so a chain (`repo.foo().all()`) and nested calls are all visited.
        syn::visit::visit_expr_method_call(self, c);
    }

    // syn::visit stops at a macro boundary, so an unscoped `repo.<method>` call
    // inside a macro body is not reached by `visit_expr_method_call`. Scan the
    // macro's tokens for the same needles, then recurse (a macro node can itself
    // contain further exprs/stmts in non-token positions we still want to walk).
    fn visit_expr_macro(&mut self, node: &'ast syn::ExprMacro) {
        self.scan_macro(&node.mac);
        syn::visit::visit_expr_macro(self, node);
    }
    fn visit_stmt_macro(&mut self, node: &'ast syn::StmtMacro) {
        self.scan_macro(&node.mac);
        syn::visit::visit_stmt_macro(self, node);
    }
    fn visit_item_macro(&mut self, node: &'ast syn::ItemMacro) {
        self.scan_macro(&node.mac);
        syn::visit::visit_item_macro(self, node);
    }
}

impl UnscopedVisitor<'_> {
    /// Whether the `display` needle still fires inside the CURRENT fn frame
    /// (#124): inside one of the tenant's own PathScoped detail handlers
    /// (`exempt_fns`) the guard already verified membership in the path tenant,
    /// so `get`/`update`/`remove`/`insert` on the tenant repo are legitimate —
    /// but `all()` stays armed even there (fn-level suppression cannot see
    /// which repo the `repo` binding holds; a correct detail handler calls
    /// `get`, not `all`). Attribution is to the INNERMOST frame, and no frame
    /// (top-level macro/item code) is never exempt.
    ///
    /// Issue #147: the name-keyed exemption is honored ONLY when the innermost
    /// frame's SIGNATURE also qualifies (`exempt_qualified`) — it binds both the
    /// `Dep<Tenant>` guard and the tenant's own `repo`. Dropping the guard, or
    /// binding a child repo as `repo`, drops the exemption so the needle fires.
    /// The signature check only ever REMOVES exemptions (moves toward flagging),
    /// so it stays on the safe side of the under-exempt-never-over-exempt rule.
    fn armed_in_current_fn(&self, display: &str) -> bool {
        display == "all()"
            || !self
                .fn_stack
                .last()
                .is_some_and(|(name, qualified)| *qualified && self.exempt_fns.contains(name))
    }

    /// Issue #147: whether a fn's signature qualifies it for the tenant-detail
    /// exemption — it must bind BOTH a `Dep<…Tenant>`-typed param (the membership
    /// guard, any binding name) AND a param whose pattern is the ident `repo` of
    /// type `Dep<{Tenant}Repo>` (the tenant's OWN repo, the receiver the exempt
    /// unscoped calls target). Only these two together justify the exemption; an
    /// exempt-named fn that qualifies on neither is flagged like any other.
    fn signature_qualifies_for_exempt(
        &self,
        inputs: &syn::punctuated::Punctuated<syn::FnArg, syn::token::Comma>,
    ) -> bool {
        let mut has_guard = false;
        let mut has_own_repo = false;
        for arg in inputs {
            let syn::FnArg::Typed(pt) = arg else { continue };
            let Some(inner) = dep_inner_last_segment(&pt.ty) else {
                continue;
            };
            if inner == self.guard_marker {
                has_guard = true;
            }
            if inner == self.expected_repo_type && pat_is_ident(&pt.pat, "repo") {
                has_own_repo = true;
            }
        }
        has_guard && has_own_repo
    }

    /// Scan a macro's raw token stream for the unscoped `repo.<method>(` calls the
    /// AST walk cannot see. `TokenStream::to_string()` inserts spacing between tokens
    /// (`repo . all ()`), so we strip whitespace first and then substring-match the
    /// SAME method set the method-call visitor flags — the trailing `(`/`()` excludes
    /// the `*_for`/`*_for_memberships` accessors exactly as the AST idents do, and
    /// `insert` is a leak only on a FLAT tenant module (#94). The macro's own source
    /// line carries the `// jerrycan:allow JL0006` hatch, same as the non-macro path.
    fn scan_macro(&mut self, mac: &syn::Macro) {
        let tokens: String = mac.tokens.to_string().split_whitespace().collect();
        // (needle, display) — mirrors the match arms of `visit_expr_method_call`,
        // including the flag_reads/flag_insert config (needle order preserved so
        // multi-hit diagnostics keep their order).
        let mut needles: Vec<(&str, &'static str)> = Vec::new();
        if self.flag_reads {
            needles.push(("repo.all()", "all()"));
            needles.push(("repo.get(", "get(...)"));
        }
        needles.push(("repo.remove(", "remove(...)"));
        needles.push(("repo.update(", "update(...)"));
        if self.flag_insert {
            needles.push(("repo.insert(", "insert(...)"));
        }
        let matched: Vec<&'static str> = needles
            .iter()
            .filter(|(needle, _)| tokens.contains(needle))
            .map(|(_, display)| *display)
            // #124: the fn frame is live here too (scan_macro runs inside the
            // same walk), so the exempt suppression mirrors the AST arm exactly
            // — otherwise wrapping a call in `json!` would flip the verdict.
            .filter(|display| self.armed_in_current_fn(display))
            .collect();
        if matched.is_empty() {
            return;
        }
        // The macro's span line: where the invocation (`serde_json::json!`) sits.
        let line = mac
            .path
            .segments
            .last()
            .map_or(1, |s| s.ident.span().start().line);
        let allowed = self
            .src
            .get(line.saturating_sub(1))
            .is_some_and(|l| l.trim_end().ends_with("// jerrycan:allow JL0006"));
        if allowed {
            return;
        }
        for display in matched {
            self.hits.push((line, display));
        }
    }
}

/// Top-level modules that own a per-user IDENTITY-owned entity (#79): an entity
/// that belongs_to the auth identity (`user_id`) and is NOT tenant-owned. Empty
/// unless the design wants auth. Classification is [`Design::entity_is_per_user_owned`]
/// — the ONE shared per-user predicate (#105 §F) — so the lint and the
/// method-suppression agree on which modules are owner-scoped.
fn identity_owned_modules(design: &Design) -> BTreeSet<&str> {
    let mut out = BTreeSet::new();
    for m in &design.modules {
        let has_per_user = m
            .entities
            .iter()
            .any(|e| design.entity_is_per_user_owned(e));
        if has_per_user {
            out.insert(m.name.as_str());
        }
    }
    out
}

/// JL0004: in an auth design, a mutating route (POST/PUT/PATCH/DELETE) whose
/// design endpoint is NOT guarded (no auth_required, no required_roles), is not
/// marked `public` (the credential-issuing carve-out — login/register can't hold
/// a session yet), AND does not carry its own signature authentication (the
/// webhook exemption — see `Endpoint::declares_signature_auth`).
fn lint_unguarded_mutations(design: &Design, out: &mut Vec<Diagnostic>) {
    if !design.wants_auth() {
        return;
    }
    fn walk(m: &ModuleDesign, out: &mut Vec<Diagnostic>) {
        for ep in &m.endpoints {
            let mutating = matches!(
                ep.method,
                HttpMethod::POST | HttpMethod::PUT | HttpMethod::PATCH | HttpMethod::DELETE
            );
            if mutating && !ep.is_guarded() && !ep.public && !ep.declares_signature_auth() {
                out.push(d(
                    "JL0004",
                    Some("design.json".into()),
                    None,
                    format!(
                        "mutating route `{}` in module `{}` has no auth guard (design declares auth)",
                        ep.operation_id, m.name
                    ),
                    "set auth_required: true or required_roles in design.json",
                    "jerrycan docs auth",
                ));
            }
        }
        for sub in &m.subroutes {
            walk(sub, out);
        }
    }
    for m in &design.modules {
        walk(m, out);
    }
}

/// JL0001: scan a route crate's lib.rs for public items besides `pub fn module()`.
fn lint_public_surface(root: &Path, m: &ModuleDesign, out: &mut Vec<Diagnostic>) {
    let rel = format!("crates/routes/{}/src/lib.rs", m.name);
    let Ok(content) = std::fs::read_to_string(root.join(&rel)) else {
        return;
    };
    for (i, line) in content.lines().enumerate() {
        let t = line.trim_start();
        if !t.starts_with("pub ") || t.starts_with("pub(") {
            continue;
        }
        if t.starts_with("pub fn module(") {
            continue;
        }
        out.push(d(
            "JL0001",
            Some(rel.clone()),
            Some(i as u64 + 1),
            format!(
                "route crate `{}` exports more than `module()`: `{}`",
                m.name,
                t.trim_end()
            ),
            "make it pub(crate), move shared types to the shared crate, or expose via module(); to reach another module's TABLE, declare a narrow second entity in your own module (jerrycan docs database)",
            "jerrycan docs modules#anti-patterns",
        ));
    }
}

/// JL0002: every design endpoint needs `async fn <operation_id>(` in its unit's handlers.rs.
fn lint_handlers(root: &Path, m: &ModuleDesign, src_rel: &str, out: &mut Vec<Diagnostic>) {
    let rel = format!("{src_rel}/handlers.rs");
    let content = std::fs::read_to_string(root.join(&rel)).unwrap_or_default();
    for ep in &m.endpoints {
        // Substring match can be fooled by commented-out handlers; the build class is the real guarantee (lib.rs references handlers::<op>).
        if !content.contains(&format!("async fn {}(", ep.operation_id)) {
            out.push(d(
                "JL0002",
                Some(rel.clone()),
                None,
                format!(
                    "handler `{}` (from design.json) is missing in {rel}",
                    ep.operation_id
                ),
                "add the handler with that exact name, or fix the design's operation_id",
                "jerrycan docs modules",
            ));
        }
    }
    for sub in &m.subroutes {
        lint_handlers(
            root,
            sub,
            &format!("{src_rel}/subroutes/{}", sub.name.replace('-', "_")),
            out,
        );
    }
}

/// JL0003: tool-owned app/src/main.rs (and, in db mode, app/src/migrations.rs)
/// must equal the regenerator's output exactly.
fn lint_generated_drift(root: &Path, design: &Design, out: &mut Vec<Diagnostic>) {
    let drift = d(
        "JL0003",
        Some("crates/app/src/main.rs".into()),
        None,
        "generated file drifted from the design (hand-edited, or design.json changed without regenerating)".into(),
        "run `jerrycan generate route <module>` to regenerate mounting; never hand-edit GENERATED files",
        "jerrycan docs app#anti-patterns",
    );
    let main_rel = "crates/app/src/main.rs";
    let on_disk = std::fs::read_to_string(root.join(main_rel)).unwrap_or_default();
    if on_disk != mounting::expected_main(design) {
        out.push(drift);
    }

    if design.wants_db()
        && let Ok(Some(expected)) = mounting::expected_migrations_rs(root, design)
    {
        let mig_rel = "crates/app/src/migrations.rs";
        let on_disk = std::fs::read_to_string(root.join(mig_rel)).unwrap_or_default();
        if on_disk != expected {
            out.push(d(
                "JL0003",
                Some(mig_rel.into()),
                None,
                "generated file drifted from the design (hand-edited, or migrations changed without regenerating)".into(),
                "run `jerrycan generate route <module>` to regenerate the migration aggregate; never hand-edit GENERATED files",
                "jerrycan docs app#anti-patterns",
            ));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A design with tenancy whose `leads` module owns a tenant-owned entity, so
    /// JL0006 scans crates/routes/leads/src/handlers.rs. (Reuses the design.rs
    /// V1_FULL fixture, where Lead belongs_to the Workspace tenancy.)
    fn tenant_design() -> Design {
        serde_json::from_str(super::super::design::tests::V1_FULL).unwrap()
    }

    /// JL0006 flags the UNSCOPED `repo.get(` call on a tenant-owned module's
    /// handler, and only that line — the clean `repo.get_for(...)` accessor (which
    /// the `(` anchor distinguishes from `get(`) must NOT be flagged. WHY: this is
    /// the cross-tenant-read guard; a false positive on the scoped call would make
    /// the correct fix un-passable.
    #[test]
    fn jl0006_flags_unscoped_repo_call_not_the_scoped_one() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/leads/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        // Line 3 is the offender; line 5 is the clean scoped accessor.
        let content = "\
use super::repo::*;
async fn show_lead(repo: Dep<LeadRepo>) -> Result<()> {
    let leaked = repo.get(id).await?;
    let _ = leaked;
    let scoped = repo.get_for(tenant.id(), id).await?;
    Ok(())
}
";
        std::fs::write(&handlers, content).unwrap();

        let design = tenant_design();
        let hits = jl0006_only(root, &design);
        assert_eq!(
            hits.len(),
            1,
            "exactly one unscoped call, the scoped one is clean: {hits:?}"
        );
        let only = &hits[0];
        assert_eq!(only.code, "JL0006");
        assert_eq!(only.line, Some(3), "must point at the `repo.get(` line");
        assert!(
            only.file
                .as_deref()
                .unwrap()
                .contains("leads/src/handlers.rs"),
            "{only:?}"
        );
        assert!(
            only.suggestion
                .as_deref()
                .unwrap()
                .contains("all_for/get_for/remove_for"),
            "carries the registered fix text: {only:?}"
        );
    }

    /// A module with no unscoped calls (only scoped accessors) produces no JL0006.
    #[test]
    fn jl0006_silent_when_handlers_use_scoped_accessors() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/leads/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn list_leads(repo: Dep<LeadRepo>) -> Result<()> {\n    let _ = repo.all_for(tenant.id()).await?;\n    Ok(())\n}\n",
        )
        .unwrap();
        let design = tenant_design();
        assert!(
            jl0006_only(root, &design).is_empty(),
            "scoped-only handlers are clean"
        );
    }

    /// Run the full lint pass and keep only JL0006 (the other lints fire on the
    /// absent lib.rs/main.rs in this bare fixture — irrelevant to this check).
    fn jl0006_only(root: &Path, design: &Design) -> Vec<Diagnostic> {
        run(root, design)
            .into_iter()
            .filter(|d| d.code == "JL0006")
            .collect()
    }

    /// A per-user (identity-owned, no tenancy) auth design: Workout belongs_to the
    /// auth identity (User → `user_id`), so its module is owner-scoped (#79).
    fn per_user_design() -> Design {
        serde_json::from_value(serde_json::json!({
            "name": "fitness-api",
            "contract_version": 1,
            "auth": { "model": "session", "roles": ["user"] },
            "dependencies": ["db", "auth"],
            "modules": [{
                "name": "workouts",
                "entities": [{
                    "name": "Workout",
                    "belongs_to": [{ "entity": "User", "on_delete": "cascade" }],
                    "fields": [{ "name": "distance", "type": "float" }]
                }],
                "endpoints": [{
                    "operation_id": "list_workouts", "method": "GET", "path": "/",
                    "auth_required": true,
                    "success": { "status": 200, "entity": "Workout", "list": true }
                }]
            }]
        }))
        .unwrap()
    }

    /// JL0006 also flags the unscoped `repo.all()` on a per-user IDENTITY-owned
    /// module (#79), naming a CROSS-USER (not cross-tenant) leak and the owner-
    /// scoped fix. WHY (Rule 9): genroute already suppresses the unscoped method
    /// (a compile error), but this belt-and-suspenders lint gives the agent a
    /// precise, actionable diagnostic; the scoped `all_for(...)` stays clean.
    #[test]
    fn jl0006_flags_unscoped_call_on_a_per_user_identity_module() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/workouts/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn list_workouts(repo: Dep<WorkoutRepo>) -> Result<()> {\n    let _ = repo.all().await?;\n    Ok(())\n}\n",
        )
        .unwrap();
        let hits = jl0006_only(root, &per_user_design());
        assert_eq!(
            hits.len(),
            1,
            "one unscoped call on a per-user repo: {hits:?}"
        );
        assert_eq!(hits[0].line, Some(2), "points at the `repo.all()` line");
        assert!(
            hits[0].message.contains("another user's rows"),
            "names the cross-USER leak, not cross-tenant: {:?}",
            hits[0]
        );
        assert!(
            hits[0]
                .suggestion
                .as_deref()
                .unwrap()
                .contains("_user.0.id"),
            "carries the owner-scoped fix: {:?}",
            hits[0]
        );
    }

    /// The owner-scoped accessor on a per-user module is clean — no false positive
    /// (the `(` anchor distinguishes `all_for(` from `all()`).
    #[test]
    fn jl0006_silent_on_owner_scoped_per_user_handler() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/workouts/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn list_workouts(repo: Dep<WorkoutRepo>, _user: CurrentUser) -> Result<()> {\n    let _ = repo.all_for(_user.0.id).await?;\n    Ok(())\n}\n",
        )
        .unwrap();
        assert!(
            jl0006_only(root, &per_user_design()).is_empty(),
            "owner-scoped per-user handler is clean"
        );
    }

    /// JL0006 flags a bare `repo.insert(` on a FLAT tenant module (#94): the flat create
    /// takes the tenant fk from the BODY, so an unchecked insert is a cross-tenant WRITE
    /// leak. WHY (Rule 9): this backstops the create steer the same way the lint already
    /// backstops read/update/delete — the fix is `create_for_memberships`. `leads` in
    /// V1_FULL is flat tenant-owned (no tenant fk in its path).
    #[test]
    fn jl0006_flags_bare_insert_on_a_flat_tenant_module() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/leads/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn create_lead(repo: Dep<LeadRepo>, Json(body): Json<Lead>) -> Result<()> {\n    let _ = repo.insert(body).await?;\n    Ok(())\n}\n",
        )
        .unwrap();
        let hits = jl0006_only(root, &tenant_design());
        assert_eq!(
            hits.len(),
            1,
            "bare insert on a flat tenant module: {hits:?}"
        );
        assert_eq!(hits[0].line, Some(2), "points at the `repo.insert(` line");
        assert!(
            hits[0]
                .suggestion
                .as_deref()
                .unwrap()
                .contains("create_for_memberships"),
            "names the membership-checked create as the fix: {:?}",
            hits[0]
        );
    }

    /// The line-scoped `// jerrycan:allow JL0006` hatch is an explicit opt-out (e.g. a
    /// create that pins the tenant fk to a membership-verified value before inserting).
    /// WHY: the reference `leads`/`api-keys` create handlers do exactly that; the hatch
    /// keeps them lint-clean without suppressing the backstop for genuinely-leaky calls.
    #[test]
    fn jl0006_insert_allow_hatch_suppresses_the_flag() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/leads/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn create_lead(repo: Dep<LeadRepo>, tenant: Dep<Tenant>) -> Result<()> {\n    let _ = repo.insert(row).await?; // jerrycan:allow JL0006\n    Ok(())\n}\n",
        )
        .unwrap();
        assert!(
            jl0006_only(root, &tenant_design()).is_empty(),
            "an explicit allow-hatch suppresses the JL0006 insert flag"
        );
    }

    /// JL0006 does NOT flag a bare `repo.insert(` on a per-user IDENTITY-owned module:
    /// a per-user create is scoped by the SERVER-injected identity fk (the DTO drops it),
    /// so the insert is safe. Flagging it would be a false positive — insert is a leak
    /// only on a FLAT tenant module, where the fk comes from the body.
    #[test]
    fn jl0006_does_not_flag_insert_on_a_per_user_module() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/workouts/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn create_workout(repo: Dep<WorkoutRepo>, Json(body): Json<Workout>) -> Result<()> {\n    let _ = repo.insert(body).await?;\n    Ok(())\n}\n",
        )
        .unwrap();
        assert!(
            jl0006_only(root, &per_user_design()).is_empty(),
            "a per-user create insert is server-scoped — not a JL0006 leak"
        );
    }

    /// The per-user design with `public_read: true` on Workout (#105): reads are
    /// public (the repo emits the unscoped `all`/`get`), writes stay owner-scoped.
    fn public_read_design() -> Design {
        let mut d = per_user_design();
        d.modules[0].entities[0].public_read = true;
        d
    }

    /// Issue #105: on a module whose per-user entities are ALL `public_read`, the
    /// unscoped `repo.all()`/`repo.get(` READS are legitimate (the repo emits them
    /// for the public GETs) — JL0006 must NOT flag them, in plain calls or macro
    /// token streams. The WRITE needles keep firing: `public_read` never exempts
    /// `repo.update(`/`repo.remove(` (#79's owner-write contract). WHY (Rule 9):
    /// without the needle split the lint would false-positive every public feed
    /// handler, training agents to scatter allow-hatches — which would ALSO mute
    /// real write leaks on those same lines.
    #[test]
    fn jl0006_public_read_module_skips_reads_but_flags_writes() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/workouts/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn list_workouts(repo: Dep<WorkoutRepo>) -> Result<()> {\n    let _ = repo.all().await?;\n    let _ = repo.get(7).await?;\n    let _ = serde_json::json!({ \"rows\": repo.all().await? });\n    Ok(())\n}\nasync fn update_workout(repo: Dep<WorkoutRepo>) -> Result<()> {\n    let _ = repo.update(7, item).await?;\n    let _ = repo.remove(7).await?;\n    Ok(())\n}\n",
        )
        .unwrap();
        let hits = jl0006_only(root, &public_read_design());
        assert_eq!(
            hits.len(),
            2,
            "only the WRITE needles fire on a public_read module: {hits:?}"
        );
        assert_eq!(hits[0].line, Some(8), "the `repo.update(` line: {hits:?}");
        assert_eq!(hits[1].line, Some(9), "the `repo.remove(` line: {hits:?}");
        assert!(
            hits.iter().all(|h| h
                .suggestion
                .as_deref()
                .unwrap()
                .contains("update_for/remove_for")),
            "steers writes to the owner-scoped write accessors: {hits:?}"
        );
    }

    /// The MACRO token scanner keeps its WRITE needles under the public_read
    /// needle split (`flag_reads=false`): an unscoped `repo.remove(`/`repo.update(`
    /// wrapped in a macro body — invisible to the AST method-call walk — must
    /// still be flagged on a public_read module. WHY (Rule 9): the read needles
    /// are disarmed there, and if the macro scanner's needle list drifted from the
    /// AST visitor's (they are built independently), a macro-wrapped cross-user
    /// WRITE would sail through exactly where the lint's guard is thinnest.
    #[test]
    fn jl0006_macro_scanner_keeps_write_needles_on_a_public_read_module() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/workouts/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn delete_workout(repo: Dep<WorkoutRepo>) -> Result<()> {\n    let _ = serde_json::json!({ \"gone\": repo.remove(7).await? });\n    Ok(())\n}\n",
        )
        .unwrap();
        let hits = jl0006_only(root, &public_read_design());
        assert_eq!(
            hits.len(),
            1,
            "the macro-wrapped unscoped write must be flagged even with the read \
             needles disarmed: {hits:?}"
        );
        assert_eq!(hits[0].line, Some(2), "points at the macro line: {hits:?}");
        assert!(
            hits[0].message.contains("remove(...)"),
            "names the write needle: {:?}",
            hits[0]
        );
    }

    /// A MIXED module — one `public_read` entity plus one plain per-user entity —
    /// KEEPS the read needles: the lint cannot tell which repo an unscoped
    /// `repo.all()` targets, so it stays conservative (the false positive has the
    /// line-scoped allow-hatch; a missed real read leak would have nothing).
    #[test]
    fn jl0006_mixed_module_keeps_the_read_needles() {
        let mut design = public_read_design();
        design.modules[0].entities.push(
            serde_json::from_value(serde_json::json!({
                "name": "Meal",
                "belongs_to": [{ "entity": "User", "on_delete": "cascade" }],
                "fields": [{ "name": "calories", "type": "integer" }]
            }))
            .unwrap(),
        );
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/workouts/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn list_meals(repo: Dep<MealRepo>) -> Result<()> {\n    let _ = repo.all().await?;\n    Ok(())\n}\n",
        )
        .unwrap();
        let hits = jl0006_only(root, &design);
        assert_eq!(
            hits.len(),
            1,
            "a mixed module keeps flagging unscoped reads: {hits:?}"
        );
    }

    /// The `public_read` flag NEVER exempts a write: an unguarded POST in a
    /// public_read design still trips JL0004 — the #105 contract is public READ,
    /// owner WRITE, so reads-public must never bleed into writes-public.
    #[test]
    fn jl0004_still_fires_on_an_unguarded_write_in_a_public_read_design() {
        let mut design = public_read_design();
        design.modules[0].endpoints.push(
            serde_json::from_value(serde_json::json!({
                "operation_id": "create_workout", "method": "POST", "path": "/",
                "request_body": { "entity": "Workout" },
                "success": { "status": 201, "entity": "Workout" }
            }))
            .unwrap(),
        );
        let hits = jl0004_only(&design);
        assert_eq!(
            hits.len(),
            1,
            "public_read never exempts an unguarded write: {hits:?}"
        );
    }

    // ---- JL0006 AST rewrite + nested paths + JL0008 (issue #103) ---------

    /// Org (tenant) → Account (belongs_to Org) as the top-level `accounts` module,
    /// with Contact (belongs_to Account) as a SUBROUTE of accounts. Contact is thus
    /// transitively tenant-owned (#102) and its handler nests on disk at
    /// `crates/routes/accounts/src/subroutes/contacts/handlers.rs` — the path the old
    /// flat-path scan never built (it looked at `crates/routes/contacts/src/…`, a
    /// nonexistent file) and so silently skipped (the #103 hole).
    fn nested_grandchild_design() -> Design {
        serde_json::from_value(serde_json::json!({
            "name": "org-api",
            "contract_version": 1,
            "auth": { "model": "session", "roles": ["owner", "member"] },
            "dependencies": ["db", "auth"],
            "tenancy": { "entity": "Org", "member_roles": ["owner", "member"] },
            "modules": [
                { "name": "orgs",
                  "entities": [{ "name": "Org", "fields": [{ "name": "id", "type": "integer" }] }],
                  "endpoints": [{ "operation_id": "list_orgs", "method": "GET", "path": "/",
                      "success": { "status": 200, "entity": "Org", "list": true } }] },
                { "name": "accounts",
                  "entities": [{ "name": "Account",
                      "belongs_to": [{ "entity": "Org" }],
                      "fields": [{ "name": "id", "type": "integer" }] }],
                  "endpoints": [{ "operation_id": "list_accounts", "method": "GET", "path": "/",
                      "success": { "status": 200, "entity": "Account", "list": true } }],
                  "subroutes": [
                    { "name": "contacts",
                      "entities": [{ "name": "Contact",
                          "belongs_to": [{ "entity": "Account" }],
                          "fields": [{ "name": "id", "type": "integer" }] }],
                      "endpoints": [{ "operation_id": "show_contact", "method": "GET", "path": "/{id}",
                          "success": { "status": 200, "entity": "Contact" } }] }
                  ] }
            ]
        }))
        .unwrap()
    }

    /// JL0006 reaches a bare unscoped `repo.get(id)` in a NESTED (grandchild)
    /// handler at its REAL on-disk path. WHY (Rule 9, #103): the old scan built a
    /// FLAT `crates/routes/{module}/src/handlers.rs` for every module, so a nested
    /// or transitively-owned handler resolved to a missing file and was skipped in
    /// silence — the exact gap that let the #102 transitive leak ship undetected.
    #[test]
    fn jl0006_fires_on_unscoped_call_in_nested_handler() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let rel = "crates/routes/accounts/src/subroutes/contacts/handlers.rs";
        let handlers = root.join(rel);
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn show_contact(repo: Dep<ContactRepo>) -> Result<()> {\n    let _ = repo.get(id).await?;\n    Ok(())\n}\n",
        )
        .unwrap();
        // The parent `accounts` handler is present and scoped, so its own scan is
        // clean (and no JL0008 for a missing file muddies the result).
        std::fs::write(
            root.join("crates/routes/accounts/src/handlers.rs"),
            "async fn list_accounts(repo: Dep<AccountRepo>) -> Result<()> {\n    let _ = repo.all_for(_tenant.id()).await?;\n    Ok(())\n}\n",
        )
        .unwrap();

        let diags = run(root, &nested_grandchild_design());
        assert!(
            diags
                .iter()
                .any(|d| d.code == "JL0006" && d.file.as_deref() == Some(rel) && d.line == Some(2)),
            "JL0006 must reach the NESTED grandchild handler (was silently skipped, #103): {diags:?}"
        );
    }

    /// JL0006 reaches an unscoped `repo.all()` wrapped in a `json!` MACRO inside a
    /// NESTED tenant-owned (grandchild) handler. WHY (Rule 9, security regression):
    /// the AST `Visit` walk does NOT descend into macro token streams, so a
    /// tenant-owned handler returning `Json(json!({ "items": repo.all().await? }))`
    /// leaks every tenant's rows while JL0006 stays silent — the coverage the
    /// pre-branch substring scanner had for single-line macro-wrapped calls. RED
    /// before the macro-token scan, GREEN after.
    #[test]
    fn jl0006_fires_on_unscoped_call_inside_a_macro_in_nested_handler() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let rel = "crates/routes/accounts/src/subroutes/contacts/handlers.rs";
        let handlers = root.join(rel);
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        // The unscoped call lives inside the json! token stream — invisible to the
        // AST method-call walk, visible only to the macro-token scan.
        std::fs::write(
            &handlers,
            "async fn show_contact(repo: Dep<ContactRepo>) -> Result<()> {\n    Ok(Json(serde_json::json!({ \"items\": repo.all().await? })))\n}\n",
        )
        .unwrap();
        // Parent `accounts` handler present + scoped, so its own scan is clean.
        std::fs::write(
            root.join("crates/routes/accounts/src/handlers.rs"),
            "async fn list_accounts(repo: Dep<AccountRepo>) -> Result<()> {\n    let _ = repo.all_for(_tenant.id()).await?;\n    Ok(())\n}\n",
        )
        .unwrap();

        let diags = run(root, &nested_grandchild_design());
        assert!(
            diags
                .iter()
                .any(|d| d.code == "JL0006" && d.file.as_deref() == Some(rel) && d.line == Some(2)),
            "JL0006 must reach the unscoped repo.all() inside the json! macro — syn::visit does not descend into macro tokens: {diags:?}"
        );
    }

    /// A SCOPED `repo.all_for_memberships(...)` inside the same macro does NOT fire:
    /// the trailing-paren needles exclude the `*_for_memberships` accessor exactly as
    /// the AST idents do. WHY (Rule 9): a false positive on the scoped call inside a
    /// macro would make the correct fix un-passable.
    #[test]
    fn jl0006_silent_on_scoped_call_inside_a_macro() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let rel = "crates/routes/accounts/src/subroutes/contacts/handlers.rs";
        let handlers = root.join(rel);
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn show_contact(repo: Dep<ContactRepo>, u: CurrentUser) -> Result<()> {\n    Ok(Json(serde_json::json!({ \"items\": repo.all_for_memberships(u).await? })))\n}\n",
        )
        .unwrap();
        std::fs::write(
            root.join("crates/routes/accounts/src/handlers.rs"),
            "async fn list_accounts(repo: Dep<AccountRepo>) -> Result<()> {\n    let _ = repo.all_for(_tenant.id()).await?;\n    Ok(())\n}\n",
        )
        .unwrap();

        let diags = run(root, &nested_grandchild_design());
        assert!(
            !diags.iter().any(|d| d.code == "JL0006"),
            "a scoped all_for_memberships inside a macro must not fire JL0006: {diags:?}"
        );
    }

    // ---- JL0006 fn attribution + tenant-detail exemption (issue #124) ----

    /// A tenant module that HOSTS a tenant-owned child (#124): Club is the
    /// tenancy entity and Book (belongs_to Club) lives in the SAME `clubs`
    /// module, so `collect_owned_handlers` drags the tenant's OWN handlers into
    /// the JL0006 scan alongside the child's. `get_club` is GUARDED
    /// (`auth_required: true`) — the exemption exists BECAUSE the `Dep<Tenant>`
    /// guard verified membership, and genroute emits that guard only for
    /// guarded endpoints, so only a guarded detail route may be exempt (the
    /// unguarded variants are pinned below). `export_club` is an ENTITY-LESS
    /// custom detail endpoint (custom-JSON success, no body) — PathScoped by
    /// its `{id}` path, but the strict resolver binds it to NO entity, so it
    /// must never enter the exemption set (pinned below).
    fn child_hosting_tenant_design() -> Design {
        serde_json::from_value(serde_json::json!({
            "name": "club-api",
            "contract_version": 1,
            "auth": { "model": "session", "roles": ["owner", "member"] },
            "dependencies": ["db", "auth"],
            "tenancy": { "entity": "Club", "member_roles": ["owner", "member"] },
            "modules": [{
                "name": "clubs",
                "entities": [
                    { "name": "Club", "fields": [{ "name": "name", "type": "string" }] },
                    { "name": "Book",
                      "belongs_to": [{ "entity": "Club" }],
                      "fields": [{ "name": "title", "type": "string" }] }
                ],
                "endpoints": [
                    { "operation_id": "list_clubs", "method": "GET", "path": "/",
                      "success": { "status": 200, "entity": "Club", "list": true } },
                    { "operation_id": "get_club", "method": "GET", "path": "/{id}",
                      "auth_required": true,
                      "success": { "status": 200, "entity": "Club" } },
                    { "operation_id": "export_club", "method": "GET", "path": "/{id}/export",
                      "success": { "status": 200 } },
                    { "operation_id": "list_books", "method": "GET", "path": "/{club_id}/books",
                      "success": { "status": 200, "entity": "Book", "list": true } }
                ]
            }]
        }))
        .unwrap()
    }

    /// Issue #124: in a child-hosting tenant module, the tenant's own PathScoped
    /// detail handler (`get_club`) legitimately calls the unscoped
    /// `repo.get/update/remove` on the TENANT repo — membership in the path
    /// tenant was already verified by the `Dep<Tenant>` guard — so JL0006 must
    /// be SILENT there, while the same needles stay ARMED in the tenant's
    /// Collection handler (`list_clubs` must steer to `all_for_member`) and in
    /// the child's handlers (the real JL0006 target). WHY (Rule 9): without fn
    /// attribution the lint false-positives on correct code, training agents to
    /// scatter allow-hatches that ALSO mute real leaks on those lines.
    #[test]
    fn jl0006_exempts_the_tenants_own_path_scoped_detail_handler() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/clubs/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        // Lines 2 and 12 are ARMED (`all()` in the Collection handler; the
        // child's unscoped `all()`); lines 6-8 are the exempt detail calls.
        std::fs::write(
            &handlers,
            "\
async fn list_clubs(repo: Dep<ClubRepo>) -> Result<()> {
    let _ = repo.all().await?;
    Ok(())
}
async fn get_club(repo: Dep<ClubRepo>, _tenant: Dep<Tenant>) -> Result<()> {
    let _ = repo.get(id).await?;
    let _ = repo.update(id, item).await?;
    let _ = repo.remove(id).await?;
    Ok(())
}
async fn list_books(repo: Dep<BookRepo>) -> Result<()> {
    let _ = repo.all().await?;
    Ok(())
}
",
        )
        .unwrap();
        let hits = jl0006_only(root, &child_hosting_tenant_design());
        let lines: Vec<Option<u64>> = hits.iter().map(|h| h.line).collect();
        assert_eq!(
            lines,
            vec![Some(2), Some(12)],
            "silent on the tenant's own PathScoped detail calls (lines 6-8), \
             armed on the Collection `all()` and the child's `all()`: {hits:?}"
        );
    }

    /// Issue #124: `repo.all()` stays armed EVEN INSIDE the exempt detail
    /// handler. WHY: fn-level suppression cannot see which repo the `repo`
    /// binding holds — a correct tenant detail handler calls `get`, not `all` —
    /// so keeping `all()` armed cheaply bounds the "agent bound the CHILD repo
    /// as `repo` in the tenant's detail handler" residual. The `get_club`
    /// signature is fully-qualified (#147: `Dep<Tenant>` guard + `repo:
    /// Dep<ClubRepo>`) so the fn IS genuinely exempt — this pins that `all()`
    /// stays armed even then, not merely because the fn failed to qualify.
    #[test]
    fn jl0006_keeps_all_armed_inside_an_exempt_detail_handler() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/clubs/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn get_club(repo: Dep<ClubRepo>, _tenant: Dep<Tenant>) -> Result<()> {\n    let _ = repo.all().await?;\n    Ok(())\n}\n",
        )
        .unwrap();
        let hits = jl0006_only(root, &child_hosting_tenant_design());
        assert_eq!(
            hits.len(),
            1,
            "`all()` is never exempted, even in the tenant's own detail fn: {hits:?}"
        );
        assert_eq!(hits[0].line, Some(2), "points at the `repo.all()` line");
        assert!(
            hits[0].message.contains("all()"),
            "names the `all()` needle: {:?}",
            hits[0]
        );
    }

    /// Issue #124: the MACRO token scanner attributes to the enclosing fn too —
    /// scan_macro runs inside the same walk, so the fn frame is live. A
    /// macro-wrapped `repo.get(` inside the exempt detail handler is suppressed
    /// exactly like the plain call, while a macro-wrapped `repo.all()` in the
    /// SAME fn stays armed. WHY (Rule 9): if the macro arm's suppression drifted
    /// from the AST visitor's, the exemption would be spelling-dependent —
    /// wrapping a call in `json!` would flip the verdict on identical code. The
    /// `get_club` signature is fully-qualified (#147: `Dep<Tenant>` guard +
    /// `repo: Dep<ClubRepo>`) so the fn IS genuinely exempt and the macro-wrapped
    /// `get(` is legitimately suppressed there.
    #[test]
    fn jl0006_macro_scan_attributes_to_the_enclosing_fn() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/clubs/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn get_club(repo: Dep<ClubRepo>, _tenant: Dep<Tenant>) -> Result<()> {\n    let _ = serde_json::json!({ \"club\": repo.get(id).await? });\n    let _ = serde_json::json!({ \"rows\": repo.all().await? });\n    Ok(())\n}\n",
        )
        .unwrap();
        let hits = jl0006_only(root, &child_hosting_tenant_design());
        assert_eq!(
            hits.len(),
            1,
            "the macro-wrapped `get(` is exempt in the detail fn, the macro-wrapped \
             `all()` stays armed: {hits:?}"
        );
        assert_eq!(hits[0].line, Some(3), "points at the `all()` macro line");
        assert!(
            hits[0].message.contains("all()"),
            "names the `all()` needle: {:?}",
            hits[0]
        );
    }

    /// Issue #124 hardening: the exemption requires the PathScoped detail
    /// SHAPE, not just "resolves to the tenant repo". The tenant's Collection
    /// handler (`list_clubs`, `GET /`) also resolves strictly to Club, but no
    /// path tenant was guard-verified there — an unscoped `repo.update(` in it
    /// is a cross-tenant WRITE leak and must stay flagged. WHY (Rule 9):
    /// dropping the `TenantShape::PathScoped` conjunct in
    /// `collect_owned_handlers` survived the whole suite before this test —
    /// the existing Collection-handler probe uses `repo.all()`, which is never
    /// exempted and so cannot pin this conjunct.
    #[test]
    fn jl0006_keeps_the_tenants_collection_handler_armed_for_writes() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/clubs/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn list_clubs(repo: Dep<ClubRepo>) -> Result<()> {\n    let _ = repo.update(id, item).await?;\n    Ok(())\n}\n",
        )
        .unwrap();
        let hits = jl0006_only(root, &child_hosting_tenant_design());
        assert_eq!(
            hits.len(),
            1,
            "a Collection handler is NOT PathScoped — its unscoped write stays armed: {hits:?}"
        );
        assert_eq!(hits[0].line, Some(2), "points at the `repo.update(` line");
        assert!(
            hits[0].message.contains("update(...)"),
            "names the `update` needle: {:?}",
            hits[0]
        );
    }

    /// Issue #124 hardening: the exemption resolves the endpoint's repo entity
    /// with the STRICT resolver on purpose. `export_club` (`GET /{id}/export`,
    /// custom-JSON success — no success.entity, no request_body) IS PathScoped,
    /// and the lenient resolver's first-entity fallback would mis-bind it to
    /// Club and exempt its whole fn — fail-OPEN, since an entity-less handler
    /// may bind ANY repo (here the child's BookRepo): its unscoped `repo.get(`
    /// is a real cross-tenant read. Strict resolves it to NO entity, so the fn
    /// never enters the exemption set. WHY (Rule 9): swapping
    /// `endpoint_repo_entity_strict` for `endpoint_repo_entity` in
    /// `collect_owned_handlers` survived the whole suite before this test.
    #[test]
    fn jl0006_does_not_exempt_an_entity_less_custom_tenant_endpoint() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/clubs/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn export_club(repo: Dep<BookRepo>, _tenant: Dep<Tenant>) -> Result<()> {\n    let _ = repo.get(id).await?;\n    Ok(())\n}\n",
        )
        .unwrap();
        let hits = jl0006_only(root, &child_hosting_tenant_design());
        assert_eq!(
            hits.len(),
            1,
            "an entity-less custom endpoint resolves to no entity under the strict \
             resolver — its fn is never exempt: {hits:?}"
        );
        assert_eq!(hits[0].line, Some(2), "points at the `repo.get(` line");
        assert!(
            hits[0].message.contains("get(...)"),
            "names the `get` needle: {:?}",
            hits[0]
        );
    }

    /// The green-gate anonymous-read hole (0.6.2 final review): the #124
    /// exemption's whole justification is the guard-verified path membership,
    /// but genroute emits the `Dep<Tenant>` guard only when `ep.is_guarded()`.
    /// An UNGUARDED `get_club` (`GET /{id}`, no `auth_required` — serde
    /// default false) is still PathScoped and strict-resolves to the tenant,
    /// so WITHOUT the `is_guarded()` conjunct it enters the exemption set and
    /// its `repo.get(club_id)` — a real ANONYMOUS tenant read — ships with a
    /// green `jerrycan check`. WHY (Rule 9): dropping the `is_guarded()`
    /// conjunct in `collect_owned_handlers` must fail THIS test — the
    /// guarded-fixture tests above cannot pin it (their `get_club` is exempt
    /// either way).
    #[test]
    fn jl0006_keeps_an_unguarded_tenant_detail_handler_armed() {
        let mut design = child_hosting_tenant_design();
        let ep = design.modules[0]
            .endpoints
            .iter_mut()
            .find(|e| e.operation_id == "get_club")
            .unwrap();
        assert!(
            ep.auth_required,
            "fixture precondition: get_club is guarded"
        );
        ep.auth_required = false;
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/clubs/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn get_club(repo: Dep<ClubRepo>) -> Result<()> {\n    let _ = repo.get(club_id).await?;\n    Ok(())\n}\n",
        )
        .unwrap();
        let hits = jl0006_only(root, &design);
        assert_eq!(
            hits.len(),
            1,
            "an UNGUARDED tenant detail route has no Dep<Tenant> guard — its \
             unscoped `repo.get(` is an anonymous tenant read and must stay armed: {hits:?}"
        );
        assert_eq!(hits[0].line, Some(2), "points at the `repo.get(` line");
        assert!(
            hits[0].message.contains("get(...)"),
            "names the `get` needle: {:?}",
            hits[0]
        );
    }

    /// The write variant of the green-gate hole: a `public: true` mutating
    /// tenant detail route (`DELETE /{id}`, success = tenant) is unguarded by
    /// construction (validation forbids `public` + `auth_required`), so no
    /// `Dep<Tenant>` guard is emitted — its unscoped `repo.remove(` is an
    /// ANONYMOUS tenant delete and must stay armed. WHY (Rule 9): `public`
    /// reaches `is_guarded() == false` through a different design field than
    /// the missing-`auth_required` read variant, so this pins the conjunct
    /// against a rewrite keyed on `auth_required` alone.
    #[test]
    fn jl0006_keeps_a_public_tenant_detail_write_armed() {
        let mut design = child_hosting_tenant_design();
        design.modules[0].endpoints.push(
            serde_json::from_value(serde_json::json!({
                "operation_id": "delete_club", "method": "DELETE", "path": "/{id}",
                "public": true,
                "success": { "status": 200, "entity": "Club" }
            }))
            .unwrap(),
        );
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/clubs/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            "async fn delete_club(repo: Dep<ClubRepo>) -> Result<()> {\n    repo.remove(club_id).await?;\n    Ok(())\n}\n",
        )
        .unwrap();
        let hits = jl0006_only(root, &design);
        assert_eq!(
            hits.len(),
            1,
            "a `public: true` tenant detail write has no guard — its unscoped \
             `repo.remove(` is an anonymous tenant delete and must stay armed: {hits:?}"
        );
        assert_eq!(hits[0].line, Some(2), "points at the `repo.remove(` line");
        assert!(
            hits[0].message.contains("remove(...)"),
            "names the `remove` needle: {:?}",
            hits[0]
        );
    }

    // ---- JL0006 tenant-detail exemption is signature-aware (issue #147) ----

    /// A Workspace tenancy whose `workspaces` module HOSTS a tenant-owned child
    /// (Member) — so `collect_owned_handlers` drags the tenant's OWN handlers
    /// into the JL0006 scan and `get_workspace` (the guarded PathScoped `/{id}`
    /// detail) enters the exemption set, with signature markers `WorkspaceRepo`
    /// (the tenant's own repo) + `Tenant` (the `Dep<Tenant>` guard). Mirrors the
    /// #124 `child_hosting_tenant_design` shape with Workspace-named entities.
    fn child_hosting_workspace_design() -> Design {
        serde_json::from_value(serde_json::json!({
            "name": "workspace-api",
            "contract_version": 1,
            "auth": { "model": "session", "roles": ["owner", "member"] },
            "dependencies": ["db", "auth"],
            "tenancy": { "entity": "Workspace", "member_roles": ["owner", "member"] },
            "modules": [{
                "name": "workspaces",
                "entities": [
                    { "name": "Workspace", "fields": [{ "name": "name", "type": "string" }] },
                    { "name": "Member",
                      "belongs_to": [{ "entity": "Workspace" }],
                      "fields": [{ "name": "role", "type": "string" }] }
                ],
                "endpoints": [
                    { "operation_id": "list_workspaces", "method": "GET", "path": "/",
                      "success": { "status": 200, "entity": "Workspace", "list": true } },
                    { "operation_id": "get_workspace", "method": "GET", "path": "/{id}",
                      "auth_required": true,
                      "success": { "status": 200, "entity": "Workspace" } },
                    { "operation_id": "list_members", "method": "GET", "path": "/{workspace_id}/members",
                      "success": { "status": 200, "entity": "Member", "list": true } }
                ]
            }]
        }))
        .unwrap()
    }

    /// Write `source` as the `workspaces` module's handlers.rs and return only
    /// its JL0006 diagnostics (the module is the sole tenant-owned handler).
    fn workspace_jl0006(source: &str) -> Vec<Diagnostic> {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/workspaces/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(&handlers, source).unwrap();
        jl0006_only(root, &child_hosting_workspace_design())
    }

    /// Issue #147, the legitimate case (unchanged): a fully-qualified tenant
    /// detail handler — it binds BOTH the `Dep<Tenant>` guard (membership was
    /// verified) AND `repo: Dep<WorkspaceRepo>` (the tenant's own repo) — stays
    /// EXEMPT, so its `repo.get(id)` is silent. This must match the #124
    /// expectation exactly: the signature check only tightens the name-key.
    #[test]
    fn jl0006_147_qualified_exempt_detail_handler_stays_exempt() {
        let hits = workspace_jl0006(
            "async fn get_workspace(_tenant: Dep<Tenant>, repo: Dep<WorkspaceRepo>, Path(id): Path<i64>) -> Result<()> {\n    let _ = repo.get(id).await?;\n    Ok(())\n}\n",
        );
        assert!(
            hits.is_empty(),
            "a fully-qualified tenant detail handler (Dep<Tenant> guard + repo: \
             Dep<WorkspaceRepo>) stays exempt: {hits:?}"
        );
    }

    /// Issue #147 residual 1: an agent DROPS the `_tenant: Dep<Tenant>` guard from
    /// the exempt-named `get_workspace` and calls `repo.get(id)` — with no guard
    /// there is nothing verifying path membership, so the exemption is withdrawn
    /// and JL0006 FIRES (was silently green under the pure name-key). WHY (Rule 9):
    /// the name-keyed exemption trusted the operation_id alone; a hand-edit that
    /// removes the guard is exactly the anonymous-tenant-read this lint must catch.
    #[test]
    fn jl0006_147_exempt_fn_without_tenant_guard_fires() {
        let hits = workspace_jl0006(
            "async fn get_workspace(repo: Dep<WorkspaceRepo>, Path(id): Path<i64>) -> Result<()> {\n    let _ = repo.get(id).await?;\n    Ok(())\n}\n",
        );
        assert_eq!(
            hits.len(),
            1,
            "dropping the Dep<Tenant> guard withdraws the exemption — the unscoped \
             get fires: {hits:?}"
        );
        assert_eq!(hits[0].line, Some(2), "points at the `repo.get(` line");
        assert!(
            hits[0].message.contains("get(...)"),
            "names the `get` needle: {:?}",
            hits[0]
        );
    }

    /// Issue #147 residual 2: the exempt-named `get_workspace` keeps its
    /// `Dep<Tenant>` guard but binds a DIFFERENT repo as `repo` — a child's
    /// `Dep<MemberRepo>`, not the tenant's `Dep<WorkspaceRepo>` — then calls
    /// `repo.get(id)`. That reads the CHILD table unscoped (a cross-tenant child
    /// read), so the exemption (which only justifies the tenant's OWN repo) is
    /// withdrawn and JL0006 FIRES. WHY (Rule 9): the guard verifies the path
    /// tenant, not arbitrary access to a mis-bound child repo.
    #[test]
    fn jl0006_147_exempt_fn_binding_a_child_repo_fires() {
        let hits = workspace_jl0006(
            "async fn get_workspace(_tenant: Dep<Tenant>, repo: Dep<MemberRepo>, Path(id): Path<i64>) -> Result<()> {\n    let _ = repo.get(id).await?;\n    Ok(())\n}\n",
        );
        assert_eq!(
            hits.len(),
            1,
            "`repo` bound to a NON-tenant repo (MemberRepo) withdraws the exemption \
             — the unscoped get fires: {hits:?}"
        );
        assert_eq!(hits[0].line, Some(2), "points at the `repo.get(` line");
        assert!(
            hits[0].message.contains("get(...)"),
            "names the `get` needle: {:?}",
            hits[0]
        );
    }

    /// Issue #147: `all()` is NEVER exempt, even inside a fully-qualified exempt
    /// detail handler (unchanged #124 invariant) — a correct detail handler calls
    /// `get`, not `all`, so an `all()` in one is a cross-tenant read regardless of
    /// signature. The signature check does not loosen this.
    #[test]
    fn jl0006_147_all_stays_armed_in_a_qualified_exempt_fn() {
        let hits = workspace_jl0006(
            "async fn get_workspace(_tenant: Dep<Tenant>, repo: Dep<WorkspaceRepo>) -> Result<()> {\n    let _ = repo.all().await?;\n    Ok(())\n}\n",
        );
        assert_eq!(
            hits.len(),
            1,
            "all() is never exempt, even in a fully-qualified detail fn: {hits:?}"
        );
        assert_eq!(hits[0].line, Some(2), "points at the `repo.all()` line");
        assert!(
            hits[0].message.contains("all()"),
            "names the `all()` needle: {:?}",
            hits[0]
        );
    }

    /// Issue #147 baseline: a NON-exempt child handler (`show_member`, not the
    /// tenant's `get_workspace`) calling `repo.get(id)` still fires — the
    /// signature check only ever REMOVES exemptions, never grants one to a name
    /// that was never exempt. The child's real fix is the scoped accessor.
    #[test]
    fn jl0006_147_non_exempt_child_handler_still_fires() {
        let hits = workspace_jl0006(
            "async fn show_member(repo: Dep<MemberRepo>, Path(id): Path<i64>) -> Result<()> {\n    let _ = repo.get(id).await?;\n    Ok(())\n}\n",
        );
        assert_eq!(
            hits.len(),
            1,
            "a non-exempt child handler's unscoped get still fires (baseline): {hits:?}"
        );
        assert_eq!(hits[0].line, Some(2), "points at the `repo.get(` line");
    }

    /// Run the full lint pass over a V1_FULL `leads` (FLAT tenant-owned) handler
    /// whose body is `body` wrapped in a handler fn. Reuses the tenant fixture so
    /// the tenant-owned scan (and its fail-loud JL0008) is exercised.
    fn lints_for_leads_body(body: &str) -> Vec<Diagnostic> {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let handlers = root.join("crates/routes/leads/src/handlers.rs");
        std::fs::create_dir_all(handlers.parent().unwrap()).unwrap();
        std::fs::write(
            &handlers,
            format!(
                "async fn h(repo: Dep<LeadRepo>) -> Result<()> {{\n    {body}\n    Ok(())\n}}\n"
            ),
        )
        .unwrap();
        run(root, &tenant_design())
    }

    /// A mention of `repo.all()` in a COMMENT is not a call — the AST walk never
    /// flags it, and the real call on the next line (`all_for_memberships`, a scoped
    /// accessor) is clean. WHY (Rule 9): the old substring scan would have flagged
    /// the comment; AST detection is what closes that false-positive class.
    #[test]
    fn jl0006_ast_ignores_repo_all_in_a_comment() {
        let diags = lints_for_leads_body(
            "// repo.all() is the unscoped call we must avoid\n    let _x = repo.all_for_memberships(u).await?;",
        );
        assert!(
            !diags.iter().any(|d| d.code == "JL0006"),
            "a mention in a comment is not a call: {diags:?}"
        );
    }

    /// A call split across lines (`repo\n .all()`) is caught — the substring scan
    /// missed it because `repo.all()` never appeared contiguously on one line. WHY
    /// (Rule 9, #103): multi-line chains are idiomatic Rust, so a scan that only
    /// matched one-line spellings left a real evasion path open.
    #[test]
    fn jl0006_ast_catches_multiline_chain() {
        let diags = lints_for_leads_body("let _x = repo\n        .all()\n        .await?;");
        assert!(
            diags.iter().any(|d| d.code == "JL0006"),
            "multi-line chain must be caught (substring scan missed it): {diags:?}"
        );
    }

    /// A tenant-owned handler that does NOT parse becomes a LOUD JL0008 — never a
    /// silent skip. WHY (Rule 9/12, #103): a handler whose scoping cannot be checked
    /// is exactly where an unscoped cross-tenant call would hide; failing loud makes
    /// `jerrycan check` surface it instead of passing over it.
    #[test]
    fn jl0008_when_tenant_owned_handler_unparseable() {
        let diags = lints_for_leads_body("fn broken( {{{ this does not parse");
        assert!(
            diags.iter().any(|d| d.code == "JL0008"
                && d.file.as_deref() == Some("crates/routes/leads/src/handlers.rs")),
            "unparseable tenant-owned handler → loud JL0008, never a silent skip: {diags:?}"
        );
    }

    /// A minimal auth design with one mutating module endpoint; the test mutates
    /// just that endpoint's guard/error shape to probe JL0004 in isolation.
    fn auth_design_with_endpoint(endpoint: serde_json::Value) -> Design {
        serde_json::from_value(serde_json::json!({
            "name": "billing-api",
            "contract_version": 1,
            "auth": { "model": "jwt", "roles": ["owner"] },
            "dependencies": ["auth"],
            "modules": [{
                "name": "billing",
                "endpoints": [endpoint]
            }]
        }))
        .unwrap()
    }

    /// Only JL0004 diagnostics from a full pass (other lints fire on the absent
    /// crate files in these bare in-memory designs).
    fn jl0004_only(design: &Design) -> Vec<Diagnostic> {
        let tmp = tempfile::tempdir().unwrap();
        run(tmp.path(), design)
            .into_iter()
            .filter(|d| d.code == "JL0004")
            .collect()
    }

    /// JL0004 must NOT flag a signature-authenticated webhook: a POST with no JWT
    /// guard but a declared `4xx … signature …` error carries its own auth, so the
    /// lint treats it as guarded. WHY (Rule 9): this is the Stripe-webhook contract
    /// — a third party signs the payload because it can't hold the app's session;
    /// flagging it would force a JWT guard that makes the webhook unreachable.
    #[test]
    fn jl0004_exempts_a_signature_authenticated_webhook() {
        let design = auth_design_with_endpoint(serde_json::json!({
            "operation_id": "stripe_webhook",
            "method": "POST",
            "path": "/webhook",
            "success": { "status": 200 },
            "errors": [{ "status": 400, "when": "Stripe signature is missing or invalid" }]
        }));
        assert!(
            jl0004_only(&design).is_empty(),
            "a signature-authed webhook is intentionally not JWT-guarded"
        );
    }

    /// JL0004 must NOT flag a PUBLIC mutating route: a credential-issuing login/
    /// register POST is genuinely unauthenticated (it has no session yet to guard
    /// by), so `public: true` is its carve-out. WHY (Rule 9): this is fix F1 — an
    /// auth design could not declare its own login/register without JL0004 firing
    /// with no escape; the flag lets a public route declare itself unguarded ON
    /// PURPOSE while the lint stays sharp on everything else.
    #[test]
    fn jl0004_exempts_a_public_credential_issuing_route() {
        let design = auth_design_with_endpoint(serde_json::json!({
            "operation_id": "register",
            "method": "POST",
            "path": "/register",
            "public": true,
            "success": { "status": 201 },
            "errors": [{ "status": 422, "when": "request body fails validation" }]
        }));
        assert!(
            jl0004_only(&design).is_empty(),
            "a public credential-issuing route is intentionally unguarded"
        );
    }

    /// The same endpoint WITHOUT `public` trips JL0004 — the exemption is the flag,
    /// nothing else (pairs with the public test above, like the signature-auth pair).
    #[test]
    fn jl0004_flags_the_same_route_without_public() {
        let design = auth_design_with_endpoint(serde_json::json!({
            "operation_id": "register",
            "method": "POST",
            "path": "/register",
            "success": { "status": 201 },
            "errors": [{ "status": 422, "when": "request body fails validation" }]
        }));
        let hits = jl0004_only(&design);
        assert_eq!(
            hits.len(),
            1,
            "without public, an unguarded mutation still trips JL0004: {hits:?}"
        );
        assert!(hits[0].message.contains("register"), "{:?}", hits[0]);
    }

    // ---- JL0007: handler code escaping the request boundary --------------

    /// A bare design with a `leads` module that has one `audit` subroute, so the
    /// JL0007 scan walks both `crates/routes/leads/src/{...}.rs` and
    /// `crates/routes/leads/src/subroutes/audit/{...}.rs`.
    fn boundary_design() -> Design {
        serde_json::from_value(serde_json::json!({
            "name": "leads-api",
            "contract_version": 1,
            "modules": [{
                "name": "leads",
                "endpoints": [{
                    "operation_id": "list_leads", "method": "GET", "path": "/",
                    "success": { "status": 200 }
                }],
                "subroutes": [{
                    "name": "audit",
                    "endpoints": [{
                        "operation_id": "list_audit", "method": "GET", "path": "/",
                        "success": { "status": 200 }
                    }]
                }]
            }]
        }))
        .unwrap()
    }

    /// Only JL0007 diagnostics from a full pass (the other lints fire on the
    /// absent lib.rs/main.rs in these bare fixtures — irrelevant here).
    fn jl0007_only(root: &Path, design: &Design) -> Vec<Diagnostic> {
        run(root, design)
            .into_iter()
            .filter(|d| d.code == "JL0007")
            .collect()
    }

    /// Write a file under root, creating parent dirs.
    fn write_at(root: &Path, rel: &str, content: &str) {
        let p = root.join(rel);
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(&p, content).unwrap();
    }

    /// JL0007 flags `std::process::Command` in a module's handlers.rs, with the
    /// exact file:line. WHY (Rule 9): handler code is agent-authored untrusted
    /// input; reaching process/fs/net escapes the framework's request boundary
    /// and the threat model — the lint is the mechanical guard for that class.
    #[test]
    fn jl0007_flags_process_in_handlers() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        write_at(
            root,
            "crates/routes/leads/src/handlers.rs",
            "async fn run_it() {\n    let _ = std::process::Command::new(\"curl\");\n}\n",
        );
        let hits = jl0007_only(root, &boundary_design());
        assert_eq!(hits.len(), 1, "exactly one boundary escape: {hits:?}");
        assert_eq!(hits[0].code, "JL0007");
        assert_eq!(hits[0].line, Some(2), "points at the std::process:: line");
        assert!(
            hits[0]
                .file
                .as_deref()
                .unwrap()
                .contains("leads/src/handlers.rs"),
            "{:?}",
            hits[0]
        );
    }

    /// The scan covers the whole agent-owned set (repo.rs, deps.rs) and the
    /// tokio:: needles too, not just handlers.rs/std::. A subroute's files are
    /// scanned at their nested path.
    #[test]
    fn jl0007_flags_fs_net_across_the_agent_owned_set() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        write_at(
            root,
            "crates/routes/leads/src/repo.rs",
            "fn load() {\n    let _ = std::fs::read_to_string(\"/etc/passwd\");\n}\n",
        );
        write_at(
            root,
            "crates/routes/leads/src/deps.rs",
            "fn dial() {\n    let _ = std::net::TcpStream::connect(\"10.0.0.1:80\");\n}\n",
        );
        write_at(
            root,
            "crates/routes/leads/src/subroutes/audit/handlers.rs",
            "async fn beam() {\n    let _ = tokio::fs::read(\"x\").await;\n}\n",
        );
        let hits = jl0007_only(root, &boundary_design());
        assert_eq!(hits.len(), 3, "fs + net + tokio::fs: {hits:?}");
        let files: BTreeSet<&str> = hits.iter().map(|h| h.file.as_deref().unwrap()).collect();
        assert!(files.iter().any(|f| f.contains("repo.rs")), "{files:?}");
        assert!(files.iter().any(|f| f.contains("deps.rs")), "{files:?}");
        assert!(
            files
                .iter()
                .any(|f| f.contains("subroutes/audit/handlers.rs")),
            "subroute files are scanned: {files:?}"
        );
    }

    /// The escape hatch: a line ending with `// jerrycan:allow JL0007` is NOT
    /// flagged, but the hatch is line-scoped — the very next offending line still
    /// flags. WHY (Rule 9): a blanket file/module suppression would let one
    /// `allow` silence the whole file; line scope keeps every other escape sharp.
    #[test]
    fn jl0007_allow_hatch_is_line_scoped() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        write_at(
            root,
            "crates/routes/leads/src/handlers.rs",
            "async fn x() {\n    let _ = std::process::Command::new(\"ok\"); // jerrycan:allow JL0007\n    let _ = std::process::Command::new(\"bad\");\n}\n",
        );
        let hits = jl0007_only(root, &boundary_design());
        assert_eq!(hits.len(), 1, "only the un-allowed line flags: {hits:?}");
        assert_eq!(hits[0].line, Some(3), "the next line still flags");
    }

    /// Legitimate code is never flagged: jerrycan::/sea_orm:: calls, `use std::fmt`,
    /// `std::collections::HashMap`, and a comment that merely mentions std::process
    /// in prose. The needle is `std::process::` (etc.), and a line whose trimmed
    /// start is `//` is skipped entirely.
    #[test]
    fn jl0007_silent_on_legitimate_code() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        write_at(
            root,
            "crates/routes/leads/src/handlers.rs",
            "use std::fmt;\nuse std::collections::HashMap;\n// we never call std::process::Command here\nasync fn x() {\n    let _ = jerrycan::prelude::Json::default();\n    let _: HashMap<u8, u8> = HashMap::new();\n    let _ = sea_orm::EntityTrait::find();\n}\n",
        );
        assert!(
            jl0007_only(root, &boundary_design()).is_empty(),
            "no boundary escape in legitimate code"
        );
    }

    /// The exemption is narrow: a plain unguarded mutation (no guard, no signature
    /// error) still trips JL0004, so the lint stays sharp against forgotten guards.
    #[test]
    fn jl0004_still_flags_a_plain_unguarded_mutation() {
        let design = auth_design_with_endpoint(serde_json::json!({
            "operation_id": "create_charge",
            "method": "POST",
            "path": "/charges",
            "success": { "status": 201 },
            "errors": [{ "status": 400, "when": "request body is malformed" }]
        }));
        let hits = jl0004_only(&design);
        assert_eq!(
            hits.len(),
            1,
            "a non-signature 400 is no exemption: {hits:?}"
        );
        assert!(hits[0].message.contains("create_charge"), "{:?}", hits[0]);
    }
}