source-mesh-core 1.1.1

Rust dependency graph analysis, diagrams, and cycle reports
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
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;

use anyhow::Context as _;
use anyhow::Result;
use anyhow::ensure;
use derive_new::new;
use getset::CopyGetters;
use getset::Getters;

use crate::SourcePath;

/**

```compile_fail
use std::path::PathBuf;
use source_mesh_core::model::FileNode;

let node = FileNode::new(PathBuf::from("source.rs"));
```
*/
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)]
#[getset(get = "pub")]
pub struct FileNode {
    path: PathBuf,
}

impl FileNode {
    #[must_use]
    pub fn new(path: SourcePath) -> Self {
        Self { path: path.into_path() }
    }

    #[must_use]
    fn directory(&self) -> &Path {
        let Some(directory) = self.path.parent() else {
            unreachable!("A validated source file path always has a parent directory");
        };
        directory
    }
}

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Getters, new)]
#[getset(get = "pub")]
pub struct FolderNode {
    label: String,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum DependencyKind {
    Production,
    Test,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, CopyGetters, Getters, new)]
pub struct Edge<Node> {
    #[getset(get = "pub")]
    source: Node,
    #[getset(get = "pub")]
    target: Node,
    #[getset(get_copy = "pub")]
    kind: DependencyKind,
}

pub type FileEdge = Edge<FileNode>;
pub type FolderEdge = Edge<FolderNode>;

/** Counts distinct directed file pairs of the same dependency kind.

```compile_fail
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use source_mesh_core::model::DependencyKind;
use source_mesh_core::model::FolderEdge;
use source_mesh_core::model::FolderGraph;
use source_mesh_core::model::FolderNode;

let folder = FolderNode::new("src".into());
let edge = FolderEdge::new(folder.clone(), folder.clone(), DependencyKind::Production);
let depth = 2_usize;
let graph = FolderGraph::new(BTreeSet::from([folder]), BTreeMap::from([(edge, depth)]));
```
*/
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, CopyGetters, new)]
#[getset(get_copy = "pub")]
pub struct DependencyCount {
    value: usize,
}

impl DependencyCount {
    const fn increment(&mut self) {
        assert!(self.value < usize::MAX, "Dependency counts are bounded by the number of input edges");
        self.value += 1;
    }
}

#[derive(Default, PartialEq, Getters)]
#[getset(get = "pub")]
pub struct FolderGraph {
    nodes: BTreeSet<FolderNode>,
    edges: BTreeMap<FolderEdge, DependencyCount>,
}

impl FolderGraph {
    pub fn new(nodes: BTreeSet<FolderNode>, edges: BTreeMap<FolderEdge, DependencyCount>) -> Result<Self> {
        ensure!(
            edges.keys().all(|edge| nodes.contains(edge.source()) && nodes.contains(edge.target())),
            "Folder graph has an unknown dependency endpoint"
        );
        Ok(Self { nodes, edges })
    }
}

/**


```compile_fail
use std::collections::BTreeSet;
use std::path::PathBuf;
use source_mesh_core::model::FileGraph;

let files = BTreeSet::from([PathBuf::from("lib.rs")]);
let graph = FileGraph::new(files, BTreeSet::new());
```
*/
#[derive(PartialEq, Getters)]
#[getset(get = "pub")]
pub struct FileGraph {
    files: BTreeSet<FileNode>,
    edges: BTreeSet<FileEdge>,
}

impl FileGraph {
    pub fn new(files: BTreeSet<FileNode>, edges: BTreeSet<FileEdge>) -> Result<Self> {
        ensure!(
            edges.iter().all(|edge| files.contains(edge.source()) && files.contains(edge.target())),
            "File graph has an unknown dependency endpoint"
        );
        Ok(Self { files, edges })
    }

    #[must_use]
    pub(crate) const fn from_files(files: BTreeSet<FileNode>) -> Self {
        Self { files, edges: BTreeSet::new() }
    }

    pub(crate) fn insert_dependency(&mut self, dependency: FileEdge) {
        assert!(
            self.files.contains(dependency.source()) && self.files.contains(dependency.target()),
            "File dependency endpoints must belong to the graph"
        );
        self.edges.insert(dependency);
    }

    #[must_use]
    pub fn without_test_dependencies(mut self) -> Self {
        self.edges.retain(|edge| edge.kind() == DependencyKind::Production);
        self
    }

    pub fn within_root(mut self, root: &Path) -> Result<Self> {
        let root = relative_directory_root(root)?;
        self.files.retain(|file| file.directory().starts_with(&root));
        self.edges.retain(|edge| self.files.contains(edge.source()) && self.files.contains(edge.target()));
        Ok(self)
    }

    pub fn folders(&self, root: &Path, depth: Option<usize>, include_self: bool) -> Result<FolderGraph> {
        let root = relative_directory_root(root)?;
        let mut folder_graph = FolderGraph::default();
        let mut file_folders = BTreeMap::new();
        for file in &self.files {
            let Ok(relative) = file.directory().strip_prefix(&root) else {
                continue;
            };
            let directory_components = relative.components().take(depth.unwrap_or(usize::MAX));
            let parts = directory_components.map(|part| part.as_os_str().to_str().context("Folder path is not UTF-8"));
            let parts = parts.collect::<Result<Vec<_>>>()?;
            let label = if parts.is_empty() { ".".into() } else { parts.join("/") };
            let folder = FolderNode::new(label);
            folder_graph.nodes.insert(folder.clone());
            file_folders.insert(file, folder);
        }
        let mut folder_edges: BTreeMap<_, DependencyCount> = BTreeMap::new();
        for edge in &self.edges {
            let (source, target) = (edge.source(), edge.target());
            if source == target {
                continue;
            }
            if let (Some(source_folder), Some(target_folder)) = (file_folders.get(source), file_folders.get(target))
                && (include_self || source_folder != target_folder)
            {
                folder_edges.entry((source_folder, target_folder, edge.kind())).or_default().increment();
            }
        }
        folder_graph.edges = folder_edges.into_iter().map(|((source, target, kind), count)| {
            (FolderEdge::new(source.clone(), target.clone(), kind), count)
        }).collect();
        Ok(folder_graph)
    }
}

fn relative_directory_root(root: &Path) -> Result<PathBuf> {
    ensure!(
        root.components().all(|component| matches!(component, Component::Normal(_) | Component::CurDir)),
        "--root must be a relative directory inside the indexed project (no '..')"
    );
    Ok(root.components().filter(|component| !matches!(component, Component::CurDir)).collect())
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::collections::BTreeSet;
    use std::panic::AssertUnwindSafe;
    use std::panic::catch_unwind;
    use std::path::Path;
    use std::path::PathBuf;

    use anyhow::Result;
    use claims::assert_ok;
    use pretty_assertions::assert_eq;
    use rstest::rstest;

    use super::DependencyCount;
    use super::DependencyKind;
    use super::FileEdge;
    use super::FileGraph;
    use super::FileNode;
    use super::FolderEdge;
    use super::FolderGraph;
    use super::FolderNode;
    use crate::SourcePath;

    #[rstest]
    #[case(0, 1)]
    #[case(7, 8)]
    #[case(usize::MAX - 1, usize::MAX)]
    fn test_dependency_count_increment(#[case] initial: usize, #[case] expected: usize) {
        let mut system_under_test = DependencyCount::new(initial);

        system_under_test.increment();

        assert_eq!(expected, system_under_test.value(), "Dependency count did not increase by one");
    }

    #[test]
    fn test_dependency_count_overflow() {
        let mut system_under_test = DependencyCount::new(usize::MAX);

        let result = catch_unwind(AssertUnwindSafe(|| system_under_test.increment()));

        assert!(result.is_err(), "Dependency count overflow must violate the input-edge bound");
        assert_eq!(usize::MAX, system_under_test.value(), "Overflow changed the dependency count");
    }

    fn file_graph_fixture() -> Result<(BTreeSet<FileNode>, BTreeSet<FileEdge>)> {
        let source_directory = Path::new("src");
        let service_module = FileNode::new(SourcePath::new(source_directory.join("api").join("service.rs"))?);
        let http_module = FileNode::new(SourcePath::new(source_directory.join("api").join("http.rs"))?);
        let routes_module = FileNode::new(SourcePath::new(source_directory.join("api").join("v1").join("routes.rs"))?);
        let request_module = FileNode::new(SourcePath::new(source_directory.join("domain").join("request.rs"))?);
        let rules_module = FileNode::new(SourcePath::new(source_directory.join("domain").join("rules.rs"))?);
        let database_module = FileNode::new(SourcePath::new(source_directory.join("storage").join("db.rs"))?);
        let calls_module = FileNode::new(SourcePath::new(source_directory.join("body_only").join("calls.rs"))?);
        let files = BTreeSet::from([
            FileNode::new(SourcePath::new(source_directory.join("lib.rs"))?),
            FileNode::new(SourcePath::new(source_directory.join("api").join("mod.rs"))?),
            service_module.clone(),
            http_module.clone(),
            FileNode::new(SourcePath::new(source_directory.join("api").join("v1").join("mod.rs"))?),
            routes_module.clone(),
            FileNode::new(SourcePath::new(source_directory.join("domain").join("mod.rs"))?),
            request_module.clone(),
            rules_module.clone(),
            database_module.clone(),
            FileNode::new(SourcePath::new(source_directory.join("body_only").join("mod.rs"))?),
            calls_module.clone(),
            FileNode::new(SourcePath::new(source_directory.join("isolated").join("mod.rs"))?),
            FileNode::new(SourcePath::new(source_directory.join("isolated").join("sample.rs"))?),
        ]);
        let dependencies = BTreeSet::from([
            FileEdge::new(service_module.clone(), http_module.clone(), DependencyKind::Production),
            FileEdge::new(service_module, routes_module.clone(), DependencyKind::Production),
            FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Production),
            FileEdge::new(http_module, database_module.clone(), DependencyKind::Production),
            FileEdge::new(routes_module.clone(), request_module.clone(), DependencyKind::Production),
            FileEdge::new(routes_module, database_module.clone(), DependencyKind::Production),
            FileEdge::new(request_module, rules_module.clone(), DependencyKind::Production),
            FileEdge::new(rules_module, database_module.clone(), DependencyKind::Production),
            FileEdge::new(calls_module, database_module, DependencyKind::Production),
        ]);
        Ok((files, dependencies))
    }

    #[must_use]
    fn folder_edges(values: &[(&str, &str, usize)], kind: DependencyKind) -> BTreeMap<FolderEdge, DependencyCount> {
        values.iter().map(|&(source, destination, weight)| {
            let edge = FolderEdge::new(FolderNode::new(source.into()), FolderNode::new(destination.into()), kind);
            (edge, DependencyCount::new(weight))
        }).collect()
    }

    #[must_use]
    fn folder_nodes(values: &[&str]) -> BTreeSet<FolderNode> {
        values.iter().map(|&label| FolderNode::new(label.into())).collect()
    }

    fn mixed_dependency_fixture() -> Result<(BTreeSet<FileNode>, BTreeSet<FileEdge>)> {
        let source_directory = Path::new("src");
        let http_module = FileNode::new(SourcePath::new(source_directory.join("api").join("http.rs"))?);
        let routes_module = FileNode::new(SourcePath::new(source_directory.join("api").join("v1").join("routes.rs"))?);
        let request_module = FileNode::new(SourcePath::new(source_directory.join("domain").join("request.rs"))?);
        let checks_module = FileNode::new(SourcePath::new(source_directory.join("tests").join("checks.rs"))?);
        let files = BTreeSet::from([
            http_module.clone(),
            routes_module.clone(),
            request_module.clone(),
            checks_module.clone(),
            FileNode::new(SourcePath::new(source_directory.join("isolated").join("sample.rs"))?),
        ]);
        let dependencies = BTreeSet::from([
            FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Production),
            FileEdge::new(routes_module.clone(), request_module.clone(), DependencyKind::Production),
            FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Test),
            FileEdge::new(http_module.clone(), request_module.clone(), DependencyKind::Test),
            FileEdge::new(routes_module, request_module.clone(), DependencyKind::Test),
            FileEdge::new(request_module.clone(), http_module, DependencyKind::Test),
            FileEdge::new(checks_module, request_module, DependencyKind::Test),
        ]);
        Ok((files, dependencies))
    }

    #[test]
    fn test_physical_directories_and_isolated_files() {
        let fixture = file_graph_fixture();
        let (files, dependencies) = assert_ok!(fixture, "Physical-directory fixture paths must be valid");
        let system_under_test = FileGraph::new(files, dependencies);
        let system_under_test = assert_ok!(system_under_test, "Physical-directory fixture must form a valid file graph");
        let expected_nodes = folder_nodes(&[".", "api", "api/v1", "body_only", "domain", "isolated", "storage"]);
        let expected_edges = folder_edges(
            &[
                ("api", "api/v1", 1),
                ("api", "domain", 1),
                ("api", "storage", 1),
                ("api/v1", "domain", 1),
                ("api/v1", "storage", 1),
                ("body_only", "storage", 1),
                ("domain", "storage", 1),
            ],
            DependencyKind::Production,
        );

        let graph = system_under_test.folders(Path::new("src"), None, false);
        let graph = assert_ok!(graph, "Physical directories must aggregate under the source root");

        assert_eq!(&expected_nodes, graph.nodes(), "Physical directory nodes differ");
        assert_eq!(&expected_edges, graph.edges(), "Physical directory dependencies differ");
        assert!(!graph.nodes().contains(&FolderNode::new("persistence".into())), "Module name replaced physical folder");
    }

    #[rstest]
    #[case(None)]
    #[case(Some(2))]
    #[case(Some(10))]
    fn test_depth_beyond_existing_folders(#[case] depth: Option<usize>) {
        let fixture = file_graph_fixture();
        let (files, dependencies) = assert_ok!(fixture, "Depth fixture paths must be valid");
        let system_under_test = FileGraph::new(files, dependencies);
        let system_under_test = assert_ok!(system_under_test, "Depth fixture must form a valid file graph");
        let complete_graph = system_under_test.folders(Path::new("src"), None, false);
        let complete_graph = assert_ok!(complete_graph, "Unbounded folder aggregation must succeed");

        let graph = system_under_test.folders(Path::new("src"), depth, false);
        let graph = assert_ok!(graph, "Folder aggregation must succeed at depth {depth:?}");

        assert_eq!(complete_graph.nodes(), graph.nodes(), "Depth {depth:?} changed nodes in a shallower graph");
        assert_eq!(complete_graph.edges(), graph.edges(), "Depth {depth:?} changed dependencies in a shallower graph");
    }

    #[rstest]
    #[case(0, &["."], &[])]
    #[case(1, &[".", "api", "body_only", "domain", "isolated", "storage"], &[
        ("api", "domain", 2), ("api", "storage", 2),
        ("body_only", "storage", 1), ("domain", "storage", 1),
    ])]
    fn test_depth_grouping_and_distinct_file_pair_weights(
        #[case] depth: usize,
        #[case] expected_nodes: &[&str],
        #[case] expected_edges: &[(&str, &str, usize)],
    ) {
        let fixture = file_graph_fixture();
        let (files, dependencies) = assert_ok!(fixture, "Depth-grouping fixture paths must be valid");
        let system_under_test = FileGraph::new(files, dependencies);
        let system_under_test = assert_ok!(system_under_test, "Depth-grouping fixture must form a valid file graph");

        let graph = system_under_test.folders(Path::new("src"), Some(depth), false);
        let graph = assert_ok!(graph, "Folder grouping must succeed at depth {depth}");

        assert_eq!(&folder_nodes(expected_nodes), graph.nodes(), "Depth {depth} grouped nodes incorrectly");
        assert_eq!(&folder_edges(expected_edges, DependencyKind::Production), graph.edges(), "Depth {depth}: misgrouped edges");
    }

    #[rstest]
    #[case(None, &[
        ("api", "api", 1), ("api", "api/v1", 1),
        ("api", "domain", 1), ("api", "storage", 1),
        ("api/v1", "domain", 1), ("api/v1", "storage", 1),
        ("body_only", "storage", 1), ("domain", "domain", 1),
        ("domain", "storage", 1),
    ])]
    #[case(Some(0), &[(".", ".", 9)])]
    #[case(Some(1), &[
        ("api", "api", 2), ("api", "domain", 2),
        ("api", "storage", 2), ("body_only", "storage", 1),
        ("domain", "domain", 1), ("domain", "storage", 1),
    ])]
    fn test_self_edges_between_distinct_files(#[case] depth: Option<usize>, #[case] expected_edges: &[(&str, &str, usize)]) {
        let fixture = file_graph_fixture();
        let (files, mut dependencies) = assert_ok!(fixture, "Self-edge fixture paths must be valid");
        let request_path = SourcePath::new(Path::new("src").join("domain").join("request.rs"));
        let request_path = assert_ok!(request_path, "Self-dependent request module must have a valid source path");
        let request_module = FileNode::new(request_path);
        dependencies.insert(FileEdge::new(request_module.clone(), request_module, DependencyKind::Production));
        let system_under_test = FileGraph::new(files, dependencies);
        let system_under_test = assert_ok!(system_under_test, "Self-edge fixture must form a valid file graph");

        let graph = system_under_test.folders(Path::new("src"), depth, true);
        let graph = assert_ok!(graph, "Folder aggregation with self-edges must succeed at depth {depth:?}");

        assert_eq!(
            &folder_edges(expected_edges, DependencyKind::Production),
            graph.edges(),
            "Self-edge handling at depth {depth:?} differs"
        );
    }

    #[test]
    fn test_scope_boundaries_use_path_components() {
        let fixture = file_graph_fixture();
        let (mut files, mut dependencies) = assert_ok!(fixture, "Scope-boundary fixture paths must be valid");
        let outside_path = SourcePath::new(Path::new("src2").join("outside.rs"));
        let outside_path = assert_ok!(outside_path, "Outside module must have a valid project-relative source path");
        let outside_module = FileNode::new(outside_path);
        files.insert(outside_module.clone());
        let service_path = SourcePath::new(Path::new("src").join("api").join("service.rs"));
        let service_path = assert_ok!(service_path, "Service module must have a valid source path");
        dependencies.insert(FileEdge::new(outside_module, FileNode::new(service_path), DependencyKind::Production));
        let system_under_test = FileGraph::new(files, dependencies);
        let system_under_test = assert_ok!(system_under_test, "Cross-scope dependencies must form a valid file graph");

        let api_graph = system_under_test.folders(&Path::new("src").join("api"), None, false);
        let api_graph = assert_ok!(api_graph, "API folder scope must aggregate successfully");
        let source_graph = system_under_test.folders(Path::new("src"), None, false);
        let source_graph = assert_ok!(source_graph, "Source folder scope must aggregate successfully");

        assert_eq!(&folder_nodes(&[".", "v1"]), api_graph.nodes(), "API scope contains unexpected folders");
        assert_eq!(&folder_edges(&[(".", "v1", 1)], DependencyKind::Production), api_graph.edges(), "API scope edges differ");
        assert!(!source_graph.nodes().contains(&FolderNode::new("src2".into())), "Scope included a shared-prefix sibling");
        assert_eq!(7, source_graph.edges().len(), "Scope changed the seven dependencies internal to the source tree");
    }

    #[rstest]
    #[case(1, &["src"], &[])]
    #[case(2, &["src", "src/api", "src/body_only", "src/domain", "src/isolated", "src/storage"], &[
        ("src/api", "src/domain", 2), ("src/api", "src/storage", 2),
        ("src/body_only", "src/storage", 1), ("src/domain", "src/storage", 1),
    ])]
    fn test_default_depth_origin(
        #[case] depth: usize,
        #[case] expected_nodes: &[&str],
        #[case] expected_edges: &[(&str, &str, usize)],
    ) {
        let fixture = file_graph_fixture();
        let (files, dependencies) = assert_ok!(fixture, "Default-root fixture paths must be valid");
        let system_under_test = FileGraph::new(files, dependencies);
        let system_under_test = assert_ok!(system_under_test, "Default-root fixture must form a valid file graph");

        let graph = system_under_test.folders(Path::new(""), Some(depth), false);
        let graph = assert_ok!(graph, "Default-root aggregation must succeed at depth {depth}");

        assert_eq!(&folder_nodes(expected_nodes), graph.nodes(), "Default root produced incorrect nodes at depth {depth}");
        assert_eq!(
            &folder_edges(expected_edges, DependencyKind::Production),
            graph.edges(),
            "Default root produced incorrect dependencies at depth {depth}"
        );
    }

    #[test]
    fn test_isolated_folder_scope() {
        let fixture = file_graph_fixture();
        let (files, dependencies) = assert_ok!(fixture, "Isolated-folder fixture paths must be valid");
        let system_under_test = FileGraph::new(files, dependencies);
        let system_under_test = assert_ok!(system_under_test, "Isolated-folder fixture must form a valid file graph");

        let graph = system_under_test.folders(&Path::new("src").join("isolated"), None, true);
        let graph = assert_ok!(graph, "An isolated folder must be a valid aggregation scope");

        assert_eq!(&folder_nodes(&["."]), graph.nodes(), "Isolated scope contains unexpected folders");
        assert!(graph.edges().is_empty(), "An isolated folder acquired dependencies");
    }

    #[rstest]
    #[case(None, &[("api", "domain", 1), ("api/v1", "domain", 1)], &[
        ("api", "domain", 1), ("api/v1", "domain", 1), ("domain", "api", 1), ("tests", "domain", 1),
    ])]
    #[case(Some(1), &[("api", "domain", 2)], &[("api", "domain", 2), ("domain", "api", 1), ("tests", "domain", 1)])]
    #[case(Some(0), &[(".", ".", 2)], &[(".", ".", 4)])]
    fn test_dependency_kinds_deduplication_and_depth_aggregation(
        #[case] depth: Option<usize>,
        #[case] expected_production: &[(&str, &str, usize)],
        #[case] expected_tests: &[(&str, &str, usize)],
    ) {
        let fixture = mixed_dependency_fixture();
        let (files, dependencies) = assert_ok!(fixture, "Mixed-dependency fixture paths must be valid");
        let system_under_test = FileGraph::new(files, dependencies);
        let system_under_test = assert_ok!(system_under_test, "Mixed dependency kinds must form a valid file graph");
        let mut expected_edges = folder_edges(expected_production, DependencyKind::Production);
        expected_edges.extend(folder_edges(expected_tests, DependencyKind::Test));

        let graph = system_under_test.folders(Path::new("src"), depth, true);
        let graph = assert_ok!(graph, "Mixed dependency kinds must aggregate at depth {depth:?}");

        assert_eq!(6, system_under_test.edges().len(), "Duplicate occurrences retained or dependency kinds merged");
        assert_eq!(&expected_edges, graph.edges(), "Depth {depth:?} changed dependency kinds or distinct file-pair counts");
    }

    #[test]
    fn test_many_file_pairs_aggregate_by_folder_and_dependency_kind() {
        let mut files = BTreeSet::new();
        let mut dependencies = BTreeSet::new();
        for index in 0..16 {
            let source_path = SourcePath::new(Path::new("src").join("api").join(format!("source_{index}.rs")));
            let source_path = assert_ok!(source_path, "Repeated-edge source path must be valid");
            let target_path = SourcePath::new(Path::new("src").join("domain").join(format!("target_{index}.rs")));
            let target_path = assert_ok!(target_path, "Repeated-edge target path must be valid");
            let source = FileNode::new(source_path);
            let target = FileNode::new(target_path);
            files.insert(source.clone());
            files.insert(target.clone());
            dependencies.insert(FileEdge::new(source.clone(), target.clone(), DependencyKind::Production));
            if index < 8 {
                dependencies.insert(FileEdge::new(source, target, DependencyKind::Test));
            }
        }
        let system_under_test = FileGraph::new(files, dependencies);
        let system_under_test = assert_ok!(system_under_test, "Repeated folder edges must form a valid file graph");
        let mut expected_edges = folder_edges(&[("api", "domain", 16)], DependencyKind::Production);
        expected_edges.extend(folder_edges(&[("api", "domain", 8)], DependencyKind::Test));

        let graph = system_under_test.folders(Path::new("src"), Some(1), false);
        let graph = assert_ok!(graph, "Repeated mixed-kind file dependencies must aggregate successfully");

        assert_eq!(&folder_nodes(&["api", "domain"]), graph.nodes(), "Repeated endpoints changed folder membership");
        assert_eq!(&expected_edges, graph.edges(), "Repeated endpoints lost weights or merged dependency kinds");
    }

    #[test]
    fn test_dependency_kind_filtering() {
        let fixture = mixed_dependency_fixture();
        let (files, dependencies) = assert_ok!(fixture, "Dependency-filtering fixture paths must be valid");
        let expected_files = files.clone();
        let system_under_test = FileGraph::new(files, dependencies);
        let system_under_test = assert_ok!(system_under_test, "Dependency-filtering fixture must form a valid file graph");
        let expected_edges = folder_edges(&[("api", "domain", 1), ("api/v1", "domain", 1)], DependencyKind::Production);

        let graph = system_under_test.without_test_dependencies();
        let folders = graph.folders(Path::new("src"), None, false);
        let folders = assert_ok!(folders, "Production-only dependencies must support folder aggregation");

        assert_eq!(&expected_files, graph.files(), "Excluding test dependencies removed source files");
        assert_eq!(2, graph.edges().len(), "Excluding test dependencies lost production edges or retained test edges");
        assert_eq!(&expected_edges, folders.edges(), "Excluding test dependencies changed production dependencies or counts");
        assert_eq!(
            &folder_nodes(&["api", "api/v1", "domain", "isolated", "tests"]),
            folders.nodes(),
            "Excluding test dependencies removed isolated or test-only source folders"
        );
    }

    #[rstest]
    #[case(PathBuf::from("source.rs"), PathBuf::new())]
    #[case(Path::new("src").join("source.rs"), PathBuf::from("src"))]
    #[case(PathBuf::from("src//source.rs/"), PathBuf::from("src"))]
    #[case(PathBuf::from("src/./source.rs"), PathBuf::from("src"))]
    fn test_file_node_source_path(#[case] path: PathBuf, #[case] directory: PathBuf) {
        let source_path = SourcePath::new(path.clone());
        let source_path = assert_ok!(source_path, "File-node fixture path must be lexically valid: {path:?}");

        let system_under_test = FileNode::new(source_path);

        assert_eq!(path.as_os_str(), system_under_test.path().as_os_str(), "File node changed its source path");
        assert_eq!(directory, system_under_test.directory(), "File node has the wrong parent directory");
    }

    #[rstest]
    #[case("", true)]
    #[case(".", true)]
    #[case("source.rs", false)]
    #[case("src", false)]
    fn test_project_root_file_scope(#[case] root: &str, #[case] included: bool) {
        let source_path = SourcePath::new(PathBuf::from("source.rs"));
        let source_path = assert_ok!(source_path, "Root-level file must have a valid source path");
        let file = FileNode::new(source_path);
        let system_under_test = FileGraph::new(BTreeSet::from([file.clone()]), BTreeSet::new());
        let system_under_test = assert_ok!(system_under_test, "A root-level file must form a valid graph");
        let expected_folders = if included { folder_nodes(&["."]) } else { BTreeSet::new() };

        let folders = system_under_test.folders(Path::new(root), None, false);
        let folders = assert_ok!(folders, "Root-level folder aggregation must accept scope {root:?}");
        let scoped_files = system_under_test.within_root(Path::new(root));
        let scoped_files = assert_ok!(scoped_files, "File scoping must accept root {root:?}");

        assert_eq!(included, scoped_files.files().contains(&file), "Root filtering changed root-level file membership");
        assert_eq!(&expected_folders, folders.nodes(), "Folder aggregation changed root-level file membership");
    }

    #[rstest]
    #[case("..")]
    #[case("../src")]
    #[case("/src")]
    fn test_folder_scope_preconditions(#[case] root: &str) {
        let fixture = file_graph_fixture();
        let (files, dependencies) = assert_ok!(fixture, "Scope-precondition fixture paths must be valid");
        let system_under_test = FileGraph::new(files, dependencies);
        let system_under_test = assert_ok!(system_under_test, "Scope-precondition fixture must form a valid file graph");

        let graph = system_under_test.folders(Path::new(root), None, false);

        assert!(graph.is_err(), "Invalid folder scope was accepted: {root}");
    }

    #[rstest]
    #[case("known.rs", "missing.rs")]
    #[case("missing.rs", "known.rs")]
    fn test_file_graph_endpoint_membership(#[case] source: &str, #[case] destination: &str) {
        let known_path = SourcePath::new(PathBuf::from("known.rs"));
        let known_path = assert_ok!(known_path, "Known graph file must have a valid source path");
        let files = BTreeSet::from([FileNode::new(known_path)]);
        let source_path = SourcePath::new(PathBuf::from(source));
        let source_path = assert_ok!(source_path, "Dependency source path must be valid: {source}");
        let destination_path = SourcePath::new(PathBuf::from(destination));
        let destination_path = assert_ok!(destination_path, "Dependency destination path must be valid: {destination}");
        let dependencies = BTreeSet::from([FileEdge::new(
            FileNode::new(source_path), FileNode::new(destination_path), DependencyKind::Production,
        )]);

        let system_under_test = FileGraph::new(files, dependencies);

        assert!(system_under_test.is_err(), "File graph accepted an unknown dependency endpoint");
    }

    #[rstest]
    #[case("known.rs", "missing.rs")]
    #[case("missing.rs", "known.rs")]
    fn test_file_dependency_insertion_membership(#[case] source: &str, #[case] target: &str) {
        let known_path = SourcePath::new(PathBuf::from("known.rs"));
        let known_path = assert_ok!(known_path, "Known insertion-fixture file must have a valid source path");
        let files = BTreeSet::from([FileNode::new(known_path)]);
        let source_path = SourcePath::new(PathBuf::from(source));
        let source_path = assert_ok!(source_path, "Inserted dependency source path must be valid: {source}");
        let target_path = SourcePath::new(PathBuf::from(target));
        let target_path = assert_ok!(target_path, "Inserted dependency target path must be valid: {target}");
        let dependency = FileEdge::new(FileNode::new(source_path), FileNode::new(target_path), DependencyKind::Production);
        let mut system_under_test = FileGraph::from_files(files.clone());

        let result = catch_unwind(AssertUnwindSafe(|| system_under_test.insert_dependency(dependency)));

        assert!(result.is_err(), "Inserting an unknown dependency endpoint must violate the graph invariant");
        assert_eq!(&files, system_under_test.files(), "Invalid dependency insertion changed graph files");
        assert!(system_under_test.edges().is_empty(), "Invalid dependency insertion changed graph edges");
    }

    #[rstest]
    #[case("known", "missing")]
    #[case("missing", "known")]
    fn test_folder_graph_endpoint_membership(#[case] source: &str, #[case] destination: &str) {
        let nodes = folder_nodes(&["known"]);
        let dependencies = folder_edges(&[(source, destination, 1)], DependencyKind::Production);

        let system_under_test = FolderGraph::new(nodes, dependencies);

        assert!(system_under_test.is_err(), "Folder graph accepted an unknown dependency endpoint");
    }
}