fallow-core 3.31.0

Internal detector backend for fallow-engine and fallow-api
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
use rustc_hash::{FxHashMap, FxHashSet};

use fallow_config::ResolvedConfig;
use fallow_types::extract::ImportedName;

use crate::discover::FileId;
use crate::graph::{
    EffectiveExportBinding, EffectiveExportResolution, ExportNamespace, ImportedSymbol,
    ModuleGraph, ModuleNode,
};
use crate::suppress::{IssueKind, SuppressionContext};
use fallow_types::results::BoundaryViolation;

use super::{LineOffsetsMap, byte_offset_to_line_col};

/// Detect imports that cross architecture boundary zones without permission.
///
/// For each analyzed module, classifies it into a zone and checks all its
/// import targets. If the target is in a different zone that the source zone
/// is not allowed to import from, a `BoundaryViolation` is emitted.
///
/// Reachability does not gate the check. A file that no entry point reaches
/// can still run (for example from a task runner that fallow does not read),
/// so its imports get the same rules as a reachable file (issue #2937).
pub fn find_boundary_violations(
    graph: &ModuleGraph,
    config: &ResolvedConfig,
    suppressions: &SuppressionContext<'_>,
    line_offsets_by_file: &LineOffsetsMap<'_>,
) -> Vec<BoundaryViolation> {
    let mut violations = Vec::new();
    let mut zone_cache: FxHashMap<FileId, Option<String>> = FxHashMap::default();
    let ctx = BoundaryContext {
        graph,
        config,
        suppressions,
        line_offsets_by_file,
    };

    for node in &graph.modules {
        collect_node_boundary_violations(&mut violations, node, &mut zone_cache, &ctx);
    }

    warn_unmatched_boundary_zones(config, &zone_cache);
    violations
}

struct BoundaryContext<'a> {
    graph: &'a ModuleGraph,
    config: &'a ResolvedConfig,
    suppressions: &'a SuppressionContext<'a>,
    line_offsets_by_file: &'a LineOffsetsMap<'a>,
}

fn classify_boundary_zone(
    file_id: FileId,
    cache: &mut FxHashMap<FileId, Option<String>>,
    ctx: &BoundaryContext<'_>,
) -> Option<String> {
    if let Some(cached) = cache.get(&file_id) {
        return cached.clone();
    }
    let node = &ctx.graph.modules[file_id.0 as usize];
    let rel_path = node
        .path
        .strip_prefix(&ctx.config.root)
        .ok()
        .map(|p| p.to_string_lossy().replace('\\', "/"));
    let zone = rel_path.and_then(|p| ctx.config.boundaries.classify_zone(&p).map(str::to_owned));
    cache.insert(file_id, zone.clone());
    zone
}

fn collect_node_boundary_violations(
    violations: &mut Vec<BoundaryViolation>,
    node: &ModuleNode,
    zone_cache: &mut FxHashMap<FileId, Option<String>>,
    ctx: &BoundaryContext<'_>,
) {
    let Some(from_zone) = classify_boundary_zone(node.file_id, zone_cache, ctx) else {
        return;
    };
    if !ctx
        .config
        .boundaries
        .rules
        .iter()
        .any(|r| r.from_zone == from_zone)
    {
        return;
    }
    if ctx
        .suppressions
        .is_file_suppressed(node.file_id, IssueKind::BoundaryViolation)
    {
        return;
    }

    let mut judged_targets: FxHashSet<FileId> = FxHashSet::default();
    let mut barrel_edges: Vec<(FileId, &[ImportedSymbol])> = Vec::new();
    // Only edges that run their target cross a boundary. A
    // `require.resolve('./x')` path or an asset loader request loads nothing.
    for summary in ctx.graph.outgoing_edge_summaries(node.file_id) {
        let edge = BoundaryEdge {
            target_id: summary.target,
            all_type_only: summary.all_type_only,
            span_start: summary.span_start,
            via: None,
        };
        if is_edge_violation(node.file_id, edge, zone_cache, ctx) {
            judged_targets.insert(summary.target);
            push_boundary_violation(violations, node, edge, &from_zone, zone_cache, ctx);
        } else {
            barrel_edges.push((summary.target, summary.symbols));
        }
    }

    for edge in chain_origin_edges(&barrel_edges, zone_cache, ctx) {
        if !judged_targets.insert(edge.target_id) {
            continue;
        }
        if is_edge_violation(node.file_id, edge, zone_cache, ctx) {
            push_boundary_violation(violations, node, edge, &from_zone, zone_cache, ctx);
        }
    }
}

/// One import judged against the boundary rules. `target_id` is the module
/// that the import reaches; `via` is the barrel that the importer names when
/// the target was found through a re-export chain.
#[derive(Clone, Copy)]
struct BoundaryEdge {
    target_id: FileId,
    all_type_only: bool,
    span_start: Option<u32>,
    via: Option<FileId>,
}

/// Group the named and default symbols of barrel edges by the module that
/// declares them (issue #2939).
///
/// Namespace and side-effect imports stay judged by their direct target. A
/// symbol whose chain holds a hop that is itself a boundary violation is
/// dropped, because that hop already gets its own finding.
fn chain_origin_edges(
    barrel_edges: &[(FileId, &[ImportedSymbol])],
    zone_cache: &mut FxHashMap<FileId, Option<String>>,
    ctx: &BoundaryContext<'_>,
) -> Vec<BoundaryEdge> {
    let mut origins: Vec<BoundaryEdge> = Vec::new();
    for &(barrel_id, symbols) in barrel_edges {
        for symbol in symbols.iter().filter(|symbol| symbol.loads_target()) {
            let name = match &symbol.imported_name {
                ImportedName::Named(name) => name.as_str(),
                ImportedName::Default => "default",
                ImportedName::Namespace | ImportedName::SideEffect => continue,
            };
            let Some(origin) =
                resolve_chain_origin(barrel_id, name, symbol.is_type_only, zone_cache, ctx)
            else {
                continue;
            };
            if origin.file_id == barrel_id {
                continue;
            }
            let span_start = Some(symbol.import_span.start);
            if let Some(existing) = origins.iter_mut().find(|e| e.target_id == origin.file_id) {
                if existing.all_type_only && !origin.type_only {
                    existing.span_start = span_start;
                    existing.via = Some(barrel_id);
                }
                existing.all_type_only &= origin.type_only;
                continue;
            }
            origins.push(BoundaryEdge {
                target_id: origin.file_id,
                all_type_only: origin.type_only,
                span_start,
                via: Some(barrel_id),
            });
        }
    }
    origins
}

struct ChainOrigin {
    file_id: FileId,
    type_only: bool,
}

/// Follow one imported name from a barrel to the module that declares it.
///
/// Returns `None` when the name does not resolve to one declaration, when the
/// chain has a cycle, or when a hop in the chain breaks the rules of the
/// zone that owns the re-exporting file.
fn resolve_chain_origin(
    barrel_id: FileId,
    name: &str,
    import_type_only: bool,
    zone_cache: &mut FxHashMap<FileId, Option<String>>,
    ctx: &BoundaryContext<'_>,
) -> Option<ChainOrigin> {
    let lanes = if import_type_only {
        [ExportNamespace::Type, ExportNamespace::Value]
    } else {
        [ExportNamespace::Value, ExportNamespace::Type]
    };
    let (namespace, binding) = lanes.into_iter().find_map(|namespace| {
        match ctx.graph.resolve_export(barrel_id, name, namespace) {
            EffectiveExportResolution::Unique(binding) => Some((namespace, binding)),
            EffectiveExportResolution::Missing | EffectiveExportResolution::Ambiguous => None,
        }
    })?;

    let mut current = barrel_id;
    let mut current_name = name.to_owned();
    let mut type_only = import_type_only;
    let mut visited: FxHashSet<(FileId, String)> = FxHashSet::default();
    loop {
        if !visited.insert((current, current_name.clone())) {
            return None;
        }
        if binding.origin_file() == current {
            let Some(source) = binding.namespace_source() else {
                return Some(ChainOrigin {
                    file_id: current,
                    type_only,
                });
            };
            type_only |= ctx.graph.modules[current.0 as usize]
                .re_exports
                .iter()
                .any(|re| {
                    re.exported_name == current_name
                        && re.imported_name == "*"
                        && re.source_file == source
                        && re.is_type_only
                });
            return (!is_hop_violation(current, source, type_only, zone_cache, ctx)).then_some(
                ChainOrigin {
                    file_id: source,
                    type_only,
                },
            );
        }
        let hop = next_chain_hop(current, &current_name, namespace, binding, ctx)?;
        type_only |= hop.type_only;
        if is_hop_violation(current, hop.file_id, type_only, zone_cache, ctx) {
            return None;
        }
        current = hop.file_id;
        current_name = hop.name;
    }
}

struct ChainHop {
    file_id: FileId,
    name: String,
    type_only: bool,
}

/// The re-export on `current` that forwards `name` to the same declaration.
fn next_chain_hop(
    current: FileId,
    name: &str,
    namespace: ExportNamespace,
    binding: EffectiveExportBinding,
    ctx: &BoundaryContext<'_>,
) -> Option<ChainHop> {
    let expected = EffectiveExportResolution::Unique(binding);
    ctx.graph.modules[current.0 as usize]
        .re_exports
        .iter()
        .filter(|re| namespace == ExportNamespace::Type || !re.is_type_only)
        .find_map(|re| {
            let source_name = if re.exported_name == "*" {
                (name != "default").then_some(name)?
            } else if re.exported_name == name && re.imported_name != "*" {
                re.imported_name.as_str()
            } else {
                return None;
            };
            (ctx.graph
                .resolve_export(re.source_file, source_name, namespace)
                == expected)
                .then(|| ChainHop {
                    file_id: re.source_file,
                    name: source_name.to_owned(),
                    type_only: re.is_type_only,
                })
        })
}

/// Whether the re-export hop `from -> to` breaks the rules of the zone that
/// owns `from`. That hop is reported on `from` itself, so the files that
/// consume the barrel do not get a second finding for it.
fn is_hop_violation(
    from: FileId,
    to: FileId,
    type_only: bool,
    zone_cache: &mut FxHashMap<FileId, Option<String>>,
    ctx: &BoundaryContext<'_>,
) -> bool {
    let edge = BoundaryEdge {
        target_id: to,
        all_type_only: type_only,
        span_start: None,
        via: None,
    };
    is_edge_violation(from, edge, zone_cache, ctx)
}

fn is_edge_violation(
    from: FileId,
    edge: BoundaryEdge,
    zone_cache: &mut FxHashMap<FileId, Option<String>>,
    ctx: &BoundaryContext<'_>,
) -> bool {
    let Some(from_zone) = classify_boundary_zone(from, zone_cache, ctx) else {
        return false;
    };
    let Some(to_zone) = classify_boundary_zone(edge.target_id, zone_cache, ctx) else {
        return false;
    };
    !is_boundary_import_allowed(
        from,
        edge.target_id,
        edge.all_type_only,
        &from_zone,
        &to_zone,
        ctx,
    )
}

fn push_boundary_violation(
    violations: &mut Vec<BoundaryViolation>,
    node: &ModuleNode,
    edge: BoundaryEdge,
    from_zone: &str,
    zone_cache: &mut FxHashMap<FileId, Option<String>>,
    ctx: &BoundaryContext<'_>,
) {
    let Some(to_zone) = classify_boundary_zone(edge.target_id, zone_cache, ctx) else {
        return;
    };
    let (line, col) = edge.span_start.map_or((1, 0), |s| {
        byte_offset_to_line_col(ctx.line_offsets_by_file, node.file_id, s)
    });
    if ctx
        .suppressions
        .is_suppressed(node.file_id, line, IssueKind::BoundaryViolation)
    {
        return;
    }

    let target_node = &ctx.graph.modules[edge.target_id.0 as usize];
    violations.push(BoundaryViolation {
        from_path: node.path.clone(),
        to_path: target_node.path.clone(),
        from_zone: from_zone.to_string(),
        to_zone,
        import_specifier: boundary_import_specifier(target_node, ctx.config),
        line,
        col,
        via_path: edge
            .via
            .map(|via| ctx.graph.modules[via.0 as usize].path.clone()),
    });
}

fn is_boundary_import_allowed(
    from: FileId,
    target_id: FileId,
    all_type_only: bool,
    from_zone: &str,
    to_zone: &str,
    ctx: &BoundaryContext<'_>,
) -> bool {
    if ctx.config.boundaries.is_import_allowed(from_zone, to_zone) {
        return true;
    }
    if all_type_only
        && ctx
            .config
            .boundaries
            .is_type_only_allowed(from_zone, to_zone)
    {
        tracing::debug!(
            "boundary type-only allowed: '{}' -> '{}' ({} -> {})",
            from_zone,
            to_zone,
            ctx.graph.modules[from.0 as usize].path.display(),
            ctx.graph.modules[target_id.0 as usize].path.display()
        );
        return true;
    }
    false
}

fn boundary_import_specifier(target_node: &ModuleNode, config: &ResolvedConfig) -> String {
    target_node.path.strip_prefix(&config.root).map_or_else(
        |_| target_node.path.to_string_lossy().replace('\\', "/"),
        |p| p.to_string_lossy().replace('\\', "/"),
    )
}

fn warn_unmatched_boundary_zones(
    config: &ResolvedConfig,
    zone_cache: &FxHashMap<FileId, Option<String>>,
) {
    if config.boundaries.is_empty() {
        return;
    }

    let classified_zones: rustc_hash::FxHashSet<&str> =
        zone_cache.values().filter_map(|z| z.as_deref()).collect();
    for zone in &config.boundaries.zones {
        if !classified_zones.contains(zone.name.as_str()) {
            tracing::warn!("{}", unmatched_zone_warning(&zone.name, config));
        }
    }
}

/// Message for a boundary zone that classified no analyzed file.
///
/// The `audit --base` pass analyzes the base revision, where a zone can be
/// legitimately empty while the working tree matches it. That pass is labelled
/// explicitly so the warning is not read as a defect in the current
/// configuration (issue #2013). The working-tree wording is unchanged.
fn unmatched_zone_warning(zone: &str, config: &ResolvedConfig) -> String {
    if config.analysis_snapshot.is_base() {
        return format!(
            "base revision snapshot (audit --base): boundary zone '{zone}' matched 0 files \
             in the base revision, this is about the base revision only and not about your \
             current configuration"
        );
    }
    format!(
        "boundary zone '{zone}' matched 0 files, check your directory structure \
         or pattern"
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::discover::{DiscoveredFile, EntryPoint, EntryPointSource};
    use crate::graph::ModuleGraph;
    use crate::resolve::ResolvedModule;
    use crate::suppress::Suppression;
    use fallow_config::{
        BoundaryCallsConfig, BoundaryConfig, BoundaryCoverageConfig, BoundaryRule, BoundaryZone,
        FallowConfig, OutputFormat, ResolvedConfig, RulesConfig, Severity,
    };
    use rustc_hash::FxHashSet;
    use std::path::PathBuf;

    fn make_config(root: PathBuf, boundaries: BoundaryConfig) -> ResolvedConfig {
        FallowConfig {
            rules: RulesConfig {
                boundary_violation: Severity::Error,
                ..RulesConfig::default()
            },
            boundaries,
            ..Default::default()
        }
        .resolve(root, OutputFormat::Human, 1, true, true, None)
    }

    fn resolved_module(file_id: FileId, path: PathBuf) -> ResolvedModule {
        ResolvedModule {
            file_id,
            path,
            exports: vec![].into(),
            re_exports: vec![],
            resolved_imports: vec![],
            resolved_dynamic_imports: vec![],
            resolved_dynamic_patterns: vec![],
            member_accesses: vec![].into(),
            semantic_facts: std::sync::Arc::default(),
            whole_object_uses: std::sync::Arc::default(),
            has_cjs_exports: false,
            has_angular_component_template_url: false,
            unused_import_bindings: FxHashSet::default(),
            type_referenced_import_bindings: vec![],
            value_referenced_import_bindings: vec![],
            namespace_object_aliases: vec![],
            exported_factory_returns: std::sync::Arc::default(),
            exported_factory_return_object_shapes: std::sync::Arc::default(),
            type_member_types: std::sync::Arc::default(),
        }
    }

    fn build_graph(
        root: &std::path::Path,
        file_names: &[&str],
        edges: &[(usize, usize, bool)],
    ) -> (Vec<DiscoveredFile>, ModuleGraph) {
        let files: Vec<DiscoveredFile> = file_names
            .iter()
            .enumerate()
            .map(|(i, name)| DiscoveredFile {
                id: FileId(i as u32),
                path: root.join(name),
                size_bytes: 100,
            })
            .collect();

        let entry_points = vec![EntryPoint {
            path: files[0].path.clone(),
            source: EntryPointSource::ManualEntry,
        }];

        let resolved: Vec<ResolvedModule> = files
            .iter()
            .map(|f| {
                let mut rm = resolved_module(f.id, f.path.clone());
                for &(from, to, is_type_only) in edges {
                    if from == f.id.0 as usize {
                        rm.resolved_imports.push(crate::resolve::ResolvedImport {
                            target: crate::resolve::ResolveResult::InternalModule(FileId(
                                to as u32,
                            )),
                            info: fallow_types::extract::ImportInfo {
                                source: format!("./{}", file_names[to]),
                                imported_name: fallow_types::extract::ImportedName::Default,
                                local_name: "x".to_string(),
                                is_type_only,
                                is_type_only_star: false,
                                from_style: false,
                                span: oxc_span::Span::new(0, 10),
                                source_span: oxc_span::Span::new(0, 10),
                            },
                        });
                    }
                }
                rm
            })
            .collect();

        let graph = ModuleGraph::build(&resolved, &entry_points, &files);
        (files, graph)
    }

    #[test]
    fn no_boundaries_returns_empty() {
        let root = PathBuf::from("/tmp/boundary-test");
        let config = make_config(root.clone(), BoundaryConfig::default());
        let (_, graph) = build_graph(
            &root,
            &["src/ui/Button.tsx", "src/db/query.ts"],
            &[(0, 1, false)],
        );
        let suppressions = SuppressionContext::empty();
        let line_offsets = FxHashMap::default();

        let violations = find_boundary_violations(&graph, &config, &suppressions, &line_offsets);
        assert!(violations.is_empty());
    }

    #[test]
    fn allowed_import_no_violation() {
        let root = PathBuf::from("/tmp/boundary-test");
        let boundaries = BoundaryConfig {
            coverage: BoundaryCoverageConfig::default(),
            calls: BoundaryCallsConfig::default(),
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "ui".to_string(),
                    patterns: vec!["src/ui/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "shared".to_string(),
                    patterns: vec!["src/shared/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
            ],
            rules: vec![BoundaryRule {
                from: "ui".to_string(),
                allow: vec!["shared".to_string()],
                allow_type_only: vec![],
            }],
        };
        let config = make_config(root.clone(), boundaries);
        let (_, graph) = build_graph(
            &root,
            &["src/ui/Button.tsx", "src/shared/utils.ts"],
            &[(0, 1, false)],
        );
        let suppressions = SuppressionContext::empty();
        let line_offsets = FxHashMap::default();

        let violations = find_boundary_violations(&graph, &config, &suppressions, &line_offsets);
        assert!(violations.is_empty());
    }

    #[test]
    fn disallowed_import_produces_violation() {
        let root = PathBuf::from("/tmp/boundary-test");
        let boundaries = BoundaryConfig {
            coverage: BoundaryCoverageConfig::default(),
            calls: BoundaryCallsConfig::default(),
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "ui".to_string(),
                    patterns: vec!["src/ui/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "db".to_string(),
                    patterns: vec!["src/db/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "shared".to_string(),
                    patterns: vec!["src/shared/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
            ],
            rules: vec![BoundaryRule {
                from: "ui".to_string(),
                allow: vec!["shared".to_string()],
                allow_type_only: vec![],
            }],
        };
        let config = make_config(root.clone(), boundaries);
        let (_, graph) = build_graph(
            &root,
            &["src/ui/Button.tsx", "src/db/query.ts"],
            &[(0, 1, false)],
        );
        let suppressions = SuppressionContext::empty();
        let line_offsets = FxHashMap::default();

        let violations = find_boundary_violations(&graph, &config, &suppressions, &line_offsets);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].from_zone, "ui");
        assert_eq!(violations[0].to_zone, "db");
    }

    #[test]
    fn self_import_always_allowed() {
        let root = PathBuf::from("/tmp/boundary-test");
        let boundaries = BoundaryConfig {
            coverage: BoundaryCoverageConfig::default(),
            calls: BoundaryCallsConfig::default(),
            preset: None,
            zones: vec![BoundaryZone {
                name: "ui".to_string(),
                patterns: vec!["src/ui/**".to_string()],
                auto_discover: vec![],
                root: None,
            }],
            rules: vec![BoundaryRule {
                from: "ui".to_string(),
                allow: vec![],
                allow_type_only: vec![],
            }],
        };
        let config = make_config(root.clone(), boundaries);
        let (_, graph) = build_graph(
            &root,
            &["src/ui/Button.tsx", "src/ui/helpers.ts"],
            &[(0, 1, false)],
        );
        let suppressions = SuppressionContext::empty();
        let line_offsets = FxHashMap::default();

        let violations = find_boundary_violations(&graph, &config, &suppressions, &line_offsets);
        assert!(violations.is_empty());
    }

    #[test]
    fn unzoned_files_unrestricted() {
        let root = PathBuf::from("/tmp/boundary-test");
        let boundaries = BoundaryConfig {
            coverage: BoundaryCoverageConfig::default(),
            calls: BoundaryCallsConfig::default(),
            preset: None,
            zones: vec![BoundaryZone {
                name: "ui".to_string(),
                patterns: vec!["src/ui/**".to_string()],
                auto_discover: vec![],
                root: None,
            }],
            rules: vec![BoundaryRule {
                from: "ui".to_string(),
                allow: vec![],
                allow_type_only: vec![],
            }],
        };
        let config = make_config(root.clone(), boundaries);
        let (_, graph) = build_graph(
            &root,
            &["src/ui/Button.tsx", "src/utils.ts"],
            &[(0, 1, false)],
        );
        let suppressions = SuppressionContext::empty();
        let line_offsets = FxHashMap::default();

        let violations = find_boundary_violations(&graph, &config, &suppressions, &line_offsets);
        assert!(violations.is_empty());
    }

    #[test]
    fn file_level_suppression_skips_file() {
        let root = PathBuf::from("/tmp/boundary-test");
        let boundaries = BoundaryConfig {
            coverage: BoundaryCoverageConfig::default(),
            calls: BoundaryCallsConfig::default(),
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "ui".to_string(),
                    patterns: vec!["src/ui/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "db".to_string(),
                    patterns: vec!["src/db/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
            ],
            rules: vec![BoundaryRule {
                from: "ui".to_string(),
                allow: vec![],
                allow_type_only: vec![],
            }],
        };
        let config = make_config(root.clone(), boundaries);
        let (_, graph) = build_graph(
            &root,
            &["src/ui/Button.tsx", "src/db/query.ts"],
            &[(0, 1, false)],
        );

        let supps = vec![Suppression::issue(0, 1, IssueKind::BoundaryViolation)];
        let mut supp_map = FxHashMap::default();
        supp_map.insert(FileId(0), supps.as_slice());
        let suppressions = SuppressionContext::from_map(supp_map);
        let line_offsets = FxHashMap::default();

        let violations = find_boundary_violations(&graph, &config, &suppressions, &line_offsets);
        assert!(violations.is_empty());
    }

    /// Build a ui->db restricted config with an optional `allowTypeOnly`
    /// list on the `ui` rule. Used by the type-only escape hatch tests.
    fn ui_db_boundaries(allow_type_only: Vec<String>) -> BoundaryConfig {
        BoundaryConfig {
            coverage: BoundaryCoverageConfig::default(),
            calls: BoundaryCallsConfig::default(),
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "ui".to_string(),
                    patterns: vec!["src/ui/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "db".to_string(),
                    patterns: vec!["src/db/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
            ],
            rules: vec![BoundaryRule {
                from: "ui".to_string(),
                allow: vec![],
                allow_type_only,
            }],
        }
    }

    #[test]
    fn type_only_import_allowed_when_zone_listed() {
        let root = PathBuf::from("/tmp/boundary-test");
        let config = make_config(root.clone(), ui_db_boundaries(vec!["db".to_string()]));
        let (_, graph) = build_graph(
            &root,
            &["src/ui/Button.tsx", "src/db/types.ts"],
            &[(0, 1, true)],
        );
        let suppressions = SuppressionContext::empty();
        let line_offsets = FxHashMap::default();

        let violations = find_boundary_violations(&graph, &config, &suppressions, &line_offsets);
        assert!(
            violations.is_empty(),
            "type-only import to a zone in allowTypeOnly should not fire"
        );
    }

    #[test]
    fn type_only_import_still_blocked_when_zone_not_listed() {
        let root = PathBuf::from("/tmp/boundary-test");
        let config = make_config(root.clone(), ui_db_boundaries(vec!["other".to_string()]));
        let (_, graph) = build_graph(
            &root,
            &["src/ui/Button.tsx", "src/db/types.ts"],
            &[(0, 1, true)],
        );
        let suppressions = SuppressionContext::empty();
        let line_offsets = FxHashMap::default();

        let violations = find_boundary_violations(&graph, &config, &suppressions, &line_offsets);
        assert_eq!(
            violations.len(),
            1,
            "type-only import to a zone NOT in allowTypeOnly must still fire"
        );
    }

    #[test]
    fn value_import_blocked_even_when_zone_in_allow_type_only() {
        let root = PathBuf::from("/tmp/boundary-test");
        let config = make_config(root.clone(), ui_db_boundaries(vec!["db".to_string()]));
        let (_, graph) = build_graph(
            &root,
            &["src/ui/Button.tsx", "src/db/query.ts"],
            &[(0, 1, false)],
        );
        let suppressions = SuppressionContext::empty();
        let line_offsets = FxHashMap::default();

        let violations = find_boundary_violations(&graph, &config, &suppressions, &line_offsets);
        assert_eq!(
            violations.len(),
            1,
            "value import must fire regardless of allowTypeOnly"
        );
    }

    #[test]
    fn empty_allow_type_only_preserves_baseline_behavior() {
        let root = PathBuf::from("/tmp/boundary-test");
        let config = make_config(root.clone(), ui_db_boundaries(vec![]));
        let (_, graph) = build_graph(
            &root,
            &["src/ui/Button.tsx", "src/db/types.ts"],
            &[(0, 1, true)],
        );
        let suppressions = SuppressionContext::empty();
        let line_offsets = FxHashMap::default();

        let violations = find_boundary_violations(&graph, &config, &suppressions, &line_offsets);
        assert_eq!(
            violations.len(),
            1,
            "default empty allowTypeOnly must preserve pre-feature behavior"
        );
    }

    #[test]
    fn allow_type_only_is_independent_of_allow() {
        let root = PathBuf::from("/tmp/boundary-test");
        let boundaries = BoundaryConfig {
            coverage: BoundaryCoverageConfig::default(),
            calls: BoundaryCallsConfig::default(),
            preset: None,
            zones: vec![
                BoundaryZone {
                    name: "ui".to_string(),
                    patterns: vec!["src/ui/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
                BoundaryZone {
                    name: "db".to_string(),
                    patterns: vec!["src/db/**".to_string()],
                    auto_discover: vec![],
                    root: None,
                },
            ],
            rules: vec![BoundaryRule {
                from: "ui".to_string(),
                allow: vec!["db".to_string()],
                allow_type_only: vec!["db".to_string()],
            }],
        };
        let config = make_config(root.clone(), boundaries);
        let (_, graph) = build_graph(
            &root,
            &["src/ui/Button.tsx", "src/db/query.ts"],
            &[(0, 1, false)],
        );
        let suppressions = SuppressionContext::empty();
        let line_offsets = FxHashMap::default();

        let violations = find_boundary_violations(&graph, &config, &suppressions, &line_offsets);
        assert!(
            violations.is_empty(),
            "import already in `allow` must not fire regardless of allowTypeOnly"
        );
    }

    #[test]
    fn unmatched_zone_warning_keeps_current_revision_wording() {
        let config = make_config(PathBuf::from("/project"), BoundaryConfig::default());

        assert_eq!(
            unmatched_zone_warning("ui", &config),
            "boundary zone 'ui' matched 0 files, check your directory structure or pattern"
        );
    }

    #[test]
    fn unmatched_zone_warning_labels_the_base_revision_snapshot() {
        let mut config = make_config(PathBuf::from("/project"), BoundaryConfig::default());
        config.analysis_snapshot = fallow_config::AnalysisSnapshot::Base;

        let message = unmatched_zone_warning("ui", &config);

        assert!(
            message.starts_with("base revision snapshot (audit --base): "),
            "base-revision warning must be labelled, got: {message}"
        );
        assert_ne!(
            message,
            unmatched_zone_warning(
                "ui",
                &make_config(PathBuf::from("/project"), BoundaryConfig::default())
            ),
            "base-revision warning must differ from the current-revision warning"
        );
    }
}