jerrycan 0.5.0

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
//! 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)

use super::checkpipe::Diagnostic;
use super::design::{Design, HttpMethod, ModuleDesign};
use super::mounting;
use std::collections::{BTreeMap, 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 belongs_to the tenancy entity) → 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.
///
/// `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.
///
/// The scoped accessors (`all_for`/`get_for`/`remove_for`) are excluded by the `(`
/// anchor (e.g. `repo.get_for(` has `_` not `(` after `get`). A line ending in
/// `// jerrycan:allow JL0006` 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.
fn lint_unscoped_tenant_queries(root: &Path, design: &Design, out: &mut Vec<Diagnostic>) {
    // Tenant-owned modules leak ACROSS TENANTS; a per-user identity-owned module
    // (#79) leaks ACROSS USERS. An entity is one or the other, so scan the tenant
    // set first and skip any module it already covered. A tenant module is FLAT when
    // it owns a membership-set entity — only there is a bare `repo.insert` a create
    // leak (#94: the flat create reads the tenant fk from the BODY). A path-scoped
    // create pins the fk to the verified tenant, so its insert is not flagged.
    let mut tenant_modules: BTreeMap<&str, bool> = BTreeMap::new();
    for (module, entity) in design.tenant_owned() {
        let is_flat = design
            .modules
            .iter()
            .find(|m| m.name == module)
            .and_then(|m| m.entities.iter().find(|e| e.name == entity))
            .is_some_and(|e| super::genroute::entity_is_flat_tenant_owned(e, design));
        let flat = tenant_modules.entry(module).or_insert(false);
        *flat = *flat || is_flat;
    }
    for (&module, &is_flat) in &tenant_modules {
        scan_unscoped(
            root,
            module,
            "a tenant-owned",
            "another tenant's rows",
            // One message, both route shapes (issue #94): a FLAT handler cannot call
            // the path-scoped `*_for` accessors (there is no tenant-id arg), so the
            // membership-set methods are named too.
            "call a scoped accessor instead — path-scoped routes: all_for/get_for/remove_for with the tenant id; flat (membership-set) routes: all_for_memberships/get_for_memberships/update_for_memberships/remove_for_memberships (and create_for_memberships) with the session user's id (_user.0.id)",
            is_flat,
            out,
        );
    }
    for module in identity_owned_modules(design) {
        if tenant_modules.contains_key(module) {
            continue;
        }
        scan_unscoped(
            root,
            module,
            "an identity-owned",
            "another user's rows",
            "call the owner-scoped accessor (all_for/get_for/remove_for) with the session user's id (_user.0.id)",
            false,
            out,
        );
    }
}

/// Scan one top-level module's `handlers.rs` for the unscoped repo patterns,
/// pushing a JL0006 per hit with the caller-supplied ownership wording.
fn scan_unscoped(
    root: &Path,
    module: &str,
    owned_desc: &str,
    leak_desc: &str,
    suggestion: &str,
    flag_insert: bool,
    out: &mut Vec<Diagnostic>,
) {
    // `repo.all()` takes no args; the others anchor on `(` so `*_for(` is excluded.
    // `repo.insert(` is a CREATE leak only on a FLAT tenant module (#94: the flat
    // create takes the tenant fk from the BODY, so a bare insert trusts it) — 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 it is flagged only when
    // `flag_insert`.
    const BASE: [&str; 4] = ["repo.all()", "repo.get(", "repo.remove(", "repo.update("];
    const ALLOW: &str = "// jerrycan:allow JL0006";
    let rel = format!("crates/routes/{module}/src/handlers.rs");
    let Ok(content) = std::fs::read_to_string(root.join(&rel)) else {
        return;
    };
    for (i, line) in content.lines().enumerate() {
        let hit = BASE
            .iter()
            .copied()
            .find(|&p| line.contains(p))
            .or_else(|| (flag_insert && line.contains("repo.insert(")).then_some("repo.insert("));
        let Some(hit) = hit else {
            continue;
        };
        // A line-scoped, explicit opt-out — e.g. a create that pins the tenant fk to a
        // membership-verified value before inserting is safe despite the bare call.
        // Mirrors JL0007's allow-hatch.
        if line.trim_end().ends_with(ALLOW) {
            continue;
        }
        out.push(d(
            "JL0006",
            Some(rel.clone()),
            Some(i as u64 + 1),
            format!(
                "handler in module `{module}` calls the unscoped `{hit}` on {owned_desc} repo — it can read, write, or delete {leak_desc}"
            ),
            suggestion,
            "jerrycan docs database",
        ));
    }
}

/// 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. Mirrors genroute's `entity_is_per_user_owned` 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();
    if !design.wants_auth() {
        return out;
    }
    for m in &design.modules {
        let has_per_user = m.entities.iter().any(|e| {
            e.belongs_to.iter().any(Design::is_identity_fk)
                && !design
                    .tenancy
                    .as_ref()
                    .is_some_and(|t| e.belongs_to.iter().any(|b| b.entity == t.entity))
        });
        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"
        );
    }

    /// 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]);
    }
}