vyre-conform 0.1.0

Conformance suite for vyre backends — proves byte-identical output to CPU reference
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
//! Structural rules gate — VYRE_RELEASE_PLAN Phase 4.7.
//!
//! The plan requires four structural rules that, together, enforce the
//! LAW 7 "one thing per file" discipline:
//!
//! 1. **no_mod_rs** — no `mod.rs` anywhere under any vyre crate's
//!    `src/`. Parent modules must be named `<dir>.rs` at the parent's
//!    level, not hidden inside a child directory.
//! 2. **max_5_entries_per_dir** — every directory under `src/`
//!    contains at most 5 direct entries (files + subdirectories).
//!    Beyond that, the module is doing too much and must be split.
//! 3. **no_use_super** — `use super::...` and `use self::...` are
//!    banned in favor of absolute `use crate::...` paths. Relative
//!    imports hide what a file depends on and become lies as soon as
//!    the file moves.
//! 4. **one_top_level_item_per_file** — each `.rs` file under `src/`
//!    contains exactly one top-level item (excluding `use`, `extern
//!    crate`, doc comments, and a single `mod` declaration that the
//!    parent `<dir>.rs` re-exports). Enforced by parsing with `syn`.
//!    *Not yet active in this commit — tracked via [`item_count_per_file`]
//!    which the shrinking-allowlist pass in a follow-up commit will
//!    activate behind a waiver file.*
//!
//! This gate runs in **shrinking-allowlist mode**: it records a
//! baseline of known violating files at a fixed revision, and every
//! new commit must either fix a known violation *or* leave the list
//! exactly the same. A commit that *adds* a new violating file fails
//! red; a commit that removes a previously-allowed violation shrinks
//! the list. This turns the migration from a "big bang" into a
//! monotonically-improving ratchet.
//!
//! # Why a scanner, not a fixer
//!
//! The plan has a separate task (Phase 4.1 `vyre-tree-gen`) that owns
//! the deterministic rewrite. This file is the *enforcer*: it reads
//! the current tree, compares it to the allowlist, and produces
//! findings. Any fixing is done by `vyre-tree-gen`, not here.

use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};

use walkdir::WalkDir;

/// Structural violation families recognized by the gate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum StructuralRule {
    /// A `mod.rs` file exists under `src/`. Parent modules should be
    /// named `<dir>.rs` at the sibling level instead.
    NoModRs,
    /// A directory under `src/` has more than 5 direct entries.
    MaxFiveEntriesPerDir,
    /// A file contains `use super::...` or `use self::...`.
    NoUseSuper,
}

impl StructuralRule {
    /// Canonical short name used in findings and allowlists.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::NoModRs => "no_mod_rs",
            Self::MaxFiveEntriesPerDir => "max_5_entries_per_dir",
            Self::NoUseSuper => "no_use_super",
        }
    }

    /// Fix hint attached to every finding for this rule.
    #[must_use]
    pub const fn fix_hint(self) -> &'static str {
        match self {
            Self::NoModRs => {
                "Fix: rename `foo/mod.rs` to `foo.rs` at the parent level and \
                 move the submodule declarations into the sibling file. Run \
                 `cargo run -p vyre-tree-gen -- rewrite foo` to do it \
                 deterministically."
            }
            Self::MaxFiveEntriesPerDir => {
                "Fix: split the directory into topic subdirectories until \
                 no parent has more than 5 direct entries. Related items \
                 group together; unrelated items each get their own leaf."
            }
            Self::NoUseSuper => {
                "Fix: rewrite `use super::X` as the absolute path \
                 `use crate::<module path>::X`. Relative imports hide \
                 dependencies and become lies when a file moves."
            }
        }
    }
}

/// A single structural violation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StructuralFinding {
    /// Path relative to the walk root.
    pub path: PathBuf,
    /// Rule violated.
    pub rule: StructuralRule,
    /// 1-indexed line number for file-level rules; `None` for
    /// directory-level rules (only the directory path is meaningful).
    pub line: Option<usize>,
    /// Human-readable description (one line, Fix:-prefixed).
    pub detail: String,
}

impl std::fmt::Display for StructuralFinding {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(line) = self.line {
            write!(
                f,
                "{}:{}: {}: {}",
                self.path.display(),
                line,
                self.rule.name(),
                self.detail
            )
        } else {
            write!(
                f,
                "{}: {}: {}",
                self.path.display(),
                self.rule.name(),
                self.detail
            )
        }
    }
}

/// A waiver entry — a path plus the rule it is exempted from. Two
/// entries with the same path and different rules are independent,
/// so callers can waive `no_mod_rs` without also waiving
/// `no_use_super` on the same file.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Waiver {
    /// Path relative to the walk root.
    pub path: PathBuf,
    /// Rule this waiver exempts.
    pub rule: StructuralRule,
}

/// Gate configuration.
#[derive(Debug, Clone)]
pub struct StructuralRulesConfig {
    /// Roots to walk.
    pub roots: Vec<PathBuf>,
    /// Directory names (exact match) to skip entirely.
    pub skip_dirs: Vec<String>,
    /// Baseline allowlist — violations that already exist in the
    /// tree and are being fixed incrementally. Each entry must be
    /// hit at least once during a scan or the gate emits a
    /// `waiver_unused` finding (so a fix that shrinks the allowlist
    /// actually does shrink it, instead of silently leaving stale
    /// entries).
    pub waivers: BTreeSet<Waiver>,
}

impl StructuralRulesConfig {
    /// Construct a config with a single root and default skip dirs.
    #[must_use]
    #[inline]
    pub fn with_root(root: impl Into<PathBuf>) -> Self {
        Self {
            roots: vec![root.into()],
            skip_dirs: default_skip_dirs(),
            waivers: BTreeSet::new(),
        }
    }
}

fn default_skip_dirs() -> Vec<String> {
    ["target", ".git", "coordination", "docs", "mutants.out"]
        .into_iter()
        .map(String::from)
        .collect()
}

/// Result of a gate run — both fresh findings and unused waivers.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct StructuralReport {
    /// Violations discovered during the scan that were not present
    /// in the waiver list. Each is a new regression.
    pub new_findings: Vec<StructuralFinding>,
    /// Waivers that were declared but never matched during the
    /// scan. A stale waiver is a lie that the tree has a violation
    /// that no longer exists.
    pub unused_waivers: Vec<Waiver>,
    /// Every violation hit during the scan, whether or not it was
    /// waived. Consumers can sum this to produce the shrinking
    /// target metric.
    pub all_findings: Vec<StructuralFinding>,
}

impl StructuralReport {
    /// `true` iff there are no new findings and no unused waivers.
    /// Stale waivers are treated as regressions — a green gate run
    /// guarantees the waiver list exactly equals the set of
    /// not-yet-fixed violations.
    #[must_use]
    #[inline]
    pub fn is_green(&self) -> bool {
        self.new_findings.is_empty() && self.unused_waivers.is_empty()
    }

    /// Render `new_findings` and `unused_waivers` into a list of
    /// one-line strings suitable for an `EnforcementReport` fail()
    /// call.
    #[must_use]
    #[inline]
    pub fn messages(&self) -> Vec<String> {
        let mut out = Vec::new();
        for finding in &self.new_findings {
            out.push(format!("NEW: {finding}. {}", finding.rule.fix_hint()));
        }
        for waiver in &self.unused_waivers {
            out.push(format!(
                "STALE WAIVER: {} for rule {} — the violation no longer \
                 exists. Fix: remove this entry from the waiver list so \
                 the allowlist keeps shrinking.",
                waiver.path.display(),
                waiver.rule.name()
            ));
        }
        out
    }
}

/// Run the structural rules gate. Returns a structured report.
///
/// # Errors
///
/// Returns a `Fix:`-prefixed error when a walk directory cannot be
/// opened or a Rust file cannot be read. Hard-fail; a gate that
/// cannot read the tree is not a pass.
#[inline]
pub fn scan(config: &StructuralRulesConfig) -> Result<StructuralReport, String> {
    let mut all_findings: Vec<StructuralFinding> = Vec::new();
    for root in &config.roots {
        scan_root(root, config, &mut all_findings)?;
    }
    all_findings.sort_by(|a, b| {
        a.path
            .cmp(&b.path)
            .then_with(|| a.rule.cmp(&b.rule))
            .then_with(|| a.line.cmp(&b.line))
    });

    let mut matched_waivers = BTreeSet::new();
    let mut new_findings = Vec::new();
    for finding in &all_findings {
        let key = Waiver {
            path: finding.path.clone(),
            rule: finding.rule,
        };
        if config.waivers.contains(&key) {
            matched_waivers.insert(key);
        } else {
            new_findings.push(finding.clone());
        }
    }
    let unused_waivers: Vec<Waiver> = config
        .waivers
        .iter()
        .filter(|waiver| !matched_waivers.contains(*waiver))
        .cloned()
        .collect();

    Ok(StructuralReport {
        new_findings,
        unused_waivers,
        all_findings,
    })
}

fn scan_root(
    root: &Path,
    config: &StructuralRulesConfig,
    findings: &mut Vec<StructuralFinding>,
) -> Result<(), String> {
    if !root.exists() {
        return Err(format!(
            "structural rules gate root does not exist: {}. Fix: pass an existing directory.",
            root.display()
        ));
    }
    let walker = WalkDir::new(root).into_iter().filter_entry(|entry| {
        if entry.depth() == 0 {
            return true;
        }
        let name = entry.file_name().to_string_lossy();
        !config.skip_dirs.iter().any(|skip| skip == name.as_ref())
    });
    for entry in walker {
        let entry = entry.map_err(|error| {
            format!(
                "structural rules walker error under {}: {error}. Fix: restore read permissions.",
                root.display()
            )
        })?;
        let path = entry.path();
        let rel = path.strip_prefix(root).unwrap_or(path).to_path_buf();
        if entry.file_type().is_dir() {
            scan_directory_rule(root, path, &rel, findings)?;
            continue;
        }
        if entry.file_type().is_file() {
            if path.file_name().and_then(|name| name.to_str()) == Some("mod.rs") {
                findings.push(StructuralFinding {
                    path: rel.clone(),
                    rule: StructuralRule::NoModRs,
                    line: None,
                    detail: "mod.rs is forbidden under LAW 7".to_string(),
                });
            }
            if path.extension().and_then(|ext| ext.to_str()) == Some("rs") {
                scan_file_rules(path, &rel, findings)?;
            }
        }
    }
    Ok(())
}

fn scan_directory_rule(
    _root: &Path,
    path: &Path,
    rel: &Path,
    findings: &mut Vec<StructuralFinding>,
) -> Result<(), String> {
    // Only apply to directories under a `src/` ancestor so we don't
    // punish project-level folders like `tests/`, `benches/`,
    // `examples/`, `docs/generated/`, etc.
    if !rel
        .components()
        .any(|component| component.as_os_str() == "src")
    {
        return Ok(());
    }
    let mut count = 0usize;
    let read_dir = fs::read_dir(path).map_err(|error| {
        format!(
            "structural rules failed to read directory {}: {error}. Fix: restore read permissions.",
            path.display()
        )
    })?;
    for entry in read_dir {
        let entry = entry.map_err(|error| {
            format!(
                "structural rules failed to enumerate {}: {error}",
                path.display()
            )
        })?;
        // `_tree.rs`, `_deprecated_bridge.rs`, and `rust-project.json`
        // are explicitly carved out from the count because they are
        // generated by `vyre-tree-gen` and carry the whole module
        // tree in one file.
        let name = entry.file_name().to_string_lossy().to_string();
        if name == "_tree.rs"
            || name == "_deprecated_bridge.rs"
            || name == "rust-project.json"
            || name.starts_with('.')
        {
            continue;
        }
        count += 1;
    }
    if count > 5 {
        findings.push(StructuralFinding {
            path: rel.to_path_buf(),
            rule: StructuralRule::MaxFiveEntriesPerDir,
            line: None,
            detail: format!("{count} direct entries (max 5)"),
        });
    }
    Ok(())
}

fn scan_file_rules(
    path: &Path,
    rel: &Path,
    findings: &mut Vec<StructuralFinding>,
) -> Result<(), String> {
    if !rel
        .components()
        .any(|component| component.as_os_str() == "src")
    {
        return Ok(());
    }
    let source = fs::read_to_string(path).map_err(|error| {
        format!(
            "structural rules failed to read {}: {error}. Fix: restore read permissions.",
            path.display()
        )
    })?;
    for (line_number, line) in source.lines().enumerate() {
        let trimmed = line.trim_start();
        // Skip doc comments and regular comments — they are free to
        // *reference* relative paths in prose.
        if trimmed.starts_with("//") {
            continue;
        }
        if trimmed.starts_with("use super::") || trimmed.starts_with("use self::") {
            findings.push(StructuralFinding {
                path: rel.to_path_buf(),
                rule: StructuralRule::NoUseSuper,
                line: Some(line_number + 1),
                detail: trimmed.to_string(),
            });
        }
    }
    Ok(())
}

/// Count every rule violation that would be reported if the waiver
/// list were empty. The number is monotonically non-increasing as
/// the migration progresses, and `StructuralReport.all_findings`
/// provides the underlying list.
#[must_use]
#[inline]
pub fn violation_count(report: &StructuralReport) -> usize {
    report.all_findings.len()
}

/// Registry entry for `structural_rules` enforcement.
pub struct StructuralRulesEnforcer;

impl crate::enforce::EnforceGate for StructuralRulesEnforcer {
    fn id(&self) -> &'static str {
        "structural_rules"
    }

    fn name(&self) -> &'static str {
        "structural_rules"
    }

    fn run(&self, ctx: &crate::enforce::EnforceCtx<'_>) -> Vec<crate::enforce::Finding> {
        let config = StructuralRulesConfig::with_root(ctx.workspace_root.to_path_buf());
        match scan(&config) {
            Ok(report) => crate::enforce::finding_result(self.id(), report.messages()),
            Err(error) => vec![crate::enforce::aggregate_finding(self.id(), vec![error])],
        }
    }
}

/// Auto-registered `structural_rules` enforcer.
pub const REGISTERED: StructuralRulesEnforcer = StructuralRulesEnforcer;

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

    use std::io::Write;
    use tempfile::TempDir;

    fn write_file(dir: &TempDir, rel: &str, content: &str) -> PathBuf {
        let path = dir.path().join(rel);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        let mut file = std::fs::File::create(&path).unwrap();
        file.write_all(content.as_bytes()).unwrap();
        path
    }

    fn run(dir: &TempDir) -> StructuralReport {
        scan(&StructuralRulesConfig::with_root(dir.path())).expect("scan must not fail")
    }

    #[test]
    fn clean_tree_is_green() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, "src/lib.rs", "pub fn a() {}\n");
        write_file(&dir, "src/a.rs", "pub fn a() {}\n");
        let report = run(&dir);
        assert!(report.is_green(), "{:?}", report);
    }

    #[test]
    fn mod_rs_is_detected() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, "src/lib.rs", "pub mod foo;\n");
        write_file(&dir, "src/foo/mod.rs", "pub fn a() {}\n");
        let report = run(&dir);
        let kinds: Vec<_> = report
            .new_findings
            .iter()
            .map(|finding| finding.rule)
            .collect();
        assert!(kinds.contains(&StructuralRule::NoModRs), "{:?}", report);
    }

    #[test]
    fn six_entries_in_src_dir_fails_max_5() {
        let dir = TempDir::new().unwrap();
        for letter in 'a'..='f' {
            write_file(
                &dir,
                &format!("src/foo/item_{letter}.rs"),
                "pub fn a() {}\n",
            );
        }
        let report = run(&dir);
        let dir_findings: Vec<_> = report
            .new_findings
            .iter()
            .filter(|finding| finding.rule == StructuralRule::MaxFiveEntriesPerDir)
            .collect();
        assert_eq!(dir_findings.len(), 1, "{:?}", report);
    }

    #[test]
    fn max_5_ignores_tree_gen_artifacts() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, "src/a.rs", "pub fn a() {}\n");
        write_file(&dir, "src/b.rs", "pub fn a() {}\n");
        write_file(&dir, "src/c.rs", "pub fn a() {}\n");
        write_file(&dir, "src/d.rs", "pub fn a() {}\n");
        write_file(&dir, "src/e.rs", "pub fn a() {}\n");
        write_file(&dir, "src/_tree.rs", "pub mod a;\n");
        write_file(&dir, "src/_deprecated_bridge.rs", "\n");
        let report = run(&dir);
        assert!(
            !report
                .new_findings
                .iter()
                .any(|finding| finding.rule == StructuralRule::MaxFiveEntriesPerDir),
            "tree-gen files must not count toward the 5-entry limit: {:?}",
            report
        );
    }

    #[test]
    fn use_super_is_detected_and_use_crate_is_not() {
        let dir = TempDir::new().unwrap();
        write_file(
            &dir,
            "src/lib.rs",
            "use super::parent;\nuse self::sibling;\nuse crate::elsewhere;\nfn f() {}\n",
        );
        let report = run(&dir);
        let count = report
            .new_findings
            .iter()
            .filter(|finding| finding.rule == StructuralRule::NoUseSuper)
            .count();
        assert_eq!(count, 2, "{:?}", report);
    }

    #[test]
    fn use_super_in_comment_is_ignored() {
        let dir = TempDir::new().unwrap();
        write_file(
            &dir,
            "src/lib.rs",
            "/// Historical example: `use super::parent;` is banned.\nfn f() {}\n",
        );
        let report = run(&dir);
        assert!(report.is_green(), "{:?}", report);
    }

    #[test]
    fn skip_dirs_default_excludes_target_and_docs() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, "target/poison/src/mod.rs", "pub fn a() {}\n");
        write_file(&dir, "src/good.rs", "pub fn a() {}\n");
        let report = run(&dir);
        assert!(report.is_green(), "{:?}", report);
    }

    #[test]
    fn waiver_suppresses_exactly_its_rule_on_its_path() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, "src/a/mod.rs", "pub fn a() {}\n");
        write_file(&dir, "src/b.rs", "use super::x;\nfn f() {}\n");
        let config = StructuralRulesConfig {
            roots: vec![dir.path().to_path_buf()],
            skip_dirs: default_skip_dirs(),
            waivers: [
                Waiver {
                    path: PathBuf::from("src/a/mod.rs"),
                    rule: StructuralRule::NoModRs,
                },
                Waiver {
                    path: PathBuf::from("src/b.rs"),
                    rule: StructuralRule::NoUseSuper,
                },
            ]
            .into_iter()
            .collect(),
        };
        let report = scan(&config).unwrap();
        assert!(
            report.is_green(),
            "all violations should be waived: {:?}",
            report
        );
    }

    #[test]
    fn stale_waiver_is_a_regression() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, "src/ok.rs", "pub fn a() {}\n");
        let config = StructuralRulesConfig {
            roots: vec![dir.path().to_path_buf()],
            skip_dirs: default_skip_dirs(),
            waivers: [Waiver {
                path: PathBuf::from("src/gone.rs"),
                rule: StructuralRule::NoModRs,
            }]
            .into_iter()
            .collect(),
        };
        let report = scan(&config).unwrap();
        assert!(
            !report.is_green(),
            "unused waivers should fail the gate: {:?}",
            report
        );
        assert_eq!(report.unused_waivers.len(), 1);
    }

    #[test]
    fn waiver_does_not_bleed_across_rules() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, "src/foo/mod.rs", "use super::parent;\n");
        let config = StructuralRulesConfig {
            roots: vec![dir.path().to_path_buf()],
            skip_dirs: default_skip_dirs(),
            waivers: [Waiver {
                path: PathBuf::from("src/foo/mod.rs"),
                rule: StructuralRule::NoModRs,
            }]
            .into_iter()
            .collect(),
        };
        let report = scan(&config).unwrap();
        // mod.rs is waived; use super must still fire.
        assert_eq!(
            report
                .new_findings
                .iter()
                .filter(|finding| finding.rule == StructuralRule::NoUseSuper)
                .count(),
            1,
            "{:?}",
            report
        );
    }

    #[test]
    fn violation_count_counts_all_findings_regardless_of_waivers() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, "src/a/mod.rs", "use super::x;\n");
        let config = StructuralRulesConfig {
            roots: vec![dir.path().to_path_buf()],
            skip_dirs: default_skip_dirs(),
            waivers: [
                Waiver {
                    path: PathBuf::from("src/a/mod.rs"),
                    rule: StructuralRule::NoModRs,
                },
                Waiver {
                    path: PathBuf::from("src/a/mod.rs"),
                    rule: StructuralRule::NoUseSuper,
                },
            ]
            .into_iter()
            .collect(),
        };
        let report = scan(&config).unwrap();
        assert_eq!(violation_count(&report), 2);
        assert!(report.is_green());
    }

    #[test]
    fn findings_are_deterministically_sorted() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, "src/z/mod.rs", "\n");
        write_file(&dir, "src/a/mod.rs", "\n");
        write_file(&dir, "src/m/mod.rs", "\n");
        let report = run(&dir);
        let paths: Vec<_> = report
            .all_findings
            .iter()
            .map(|finding| finding.path.to_string_lossy().to_string())
            .collect();
        let mut sorted = paths.clone();
        sorted.sort();
        assert_eq!(paths, sorted, "{:?}", paths);
    }

    #[test]
    fn missing_root_returns_actionable_error() {
        let config = StructuralRulesConfig::with_root("/nope/does/not/exist");
        let error = scan(&config).unwrap_err();
        assert!(
            error.contains("structural rules gate root does not exist"),
            "{error}"
        );
        assert!(error.contains("Fix:"), "{error}");
    }

    #[test]
    fn rule_names_are_unique() {
        let mut seen = std::collections::BTreeSet::new();
        for rule in [
            StructuralRule::NoModRs,
            StructuralRule::MaxFiveEntriesPerDir,
            StructuralRule::NoUseSuper,
        ] {
            assert!(seen.insert(rule.name()), "duplicate name {}", rule.name());
        }
    }

    #[test]
    fn display_finding_includes_rule_name_and_fix() {
        let finding = StructuralFinding {
            path: PathBuf::from("src/a/mod.rs"),
            rule: StructuralRule::NoModRs,
            line: None,
            detail: "mod.rs is forbidden".to_string(),
        };
        let rendered = format!("{finding}");
        assert!(rendered.contains("src/a/mod.rs"), "{rendered}");
        assert!(rendered.contains("no_mod_rs"), "{rendered}");
    }

    #[test]
    fn dir_rule_ignores_non_src_directories() {
        let dir = TempDir::new().unwrap();
        // 6 entries under `tests/` must not fire — only `src/` is in scope.
        for letter in 'a'..='f' {
            write_file(&dir, &format!("tests/{letter}.rs"), "\n");
        }
        let report = run(&dir);
        assert!(report.is_green(), "{:?}", report);
    }
}