guibiao 0.9.0

圭表 (Guibiao) — Tianheng's dependency-light static observation core (derived from modou). Declare crate, module, and dependency-source boundaries in Rust — dependencies by name, module imports, and each dependency's declared source kind (git/registry/path) for manifest hygiene — observed from cargo metadata and source use-scans, reacted in CI. No AST: the syn-free gnomon of the family.
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
use super::helpers::*;
use crate::module_scan::EvaluationScans;
use std::collections::{BTreeSet, HashMap};
use std::path::PathBuf;

/// Judge one constitution through both scan forms: shared (each root's scan built once — the
/// production reading) and independent (a scan rebuilt at every lookup, none reused).
fn shared_and_independent(constitution: &Constitution, metadata: &Value) -> (Outcome, Outcome) {
    (
        crate::evaluate_with_scans(constitution, metadata, &EvaluationScans::shared()),
        crate::evaluate_with_scans(constitution, metadata, &EvaluationScans::independent()),
    )
}

/// Assemble `boundaries` into a constitution, in the order given.
fn constitution_of(boundaries: Vec<ModuleBoundary>) -> Constitution {
    let mut constitution = Constitution::new("corpus");
    for boundary in boundaries {
        constitution = constitution.boundary(boundary);
    }
    constitution
}

/// Two workspaces built from one label hold separate roots, so the second does not remove what the first
/// wrote.
///
/// The corpus builders below share a label across tests, and a root named from the label alone had the
/// second test's construction delete the first test's files mid-run. The direction builds both in one
/// thread, in the order that lost the first's files, and reads the first back; it needs no parallel schedule.
#[test]
fn two_workspaces_built_from_one_label_hold_separate_roots() {
    let first = TempWorkspace::new("eq-same-label");
    let written = first.write("lib.rs", "pub fn first() {}\n");
    let second = TempWorkspace::new("eq-same-label");
    assert!(
        written.is_file(),
        "building a second workspace of the same label removed the first workspace's file"
    );
    assert_ne!(first.dir(), second.dir());
}

/// A constitution of several module boundaries over one root builds the root's scan once, and a
/// package of two compiled roots builds each of theirs once — the work is counted where a scan is
/// built, never where a lookup finds one already built.
#[test]
pub(super) fn many_boundaries_over_one_root_build_its_scan_once() {
    let ws = TempWorkspace::new("root-scan-once");
    ws.write(
        "lib.rs",
        "pub mod kernel;\npub mod projection;\npub mod types;\n",
    );
    ws.write("kernel.rs", "use crate::projection::P;\npub struct K;\n");
    ws.write("projection.rs", "pub struct P;\n");
    ws.write("types.rs", "pub struct T;\n");
    let metadata = ws.metadata("x");
    let constitution = Constitution::new("t")
        .boundary(
            ModuleBoundary::in_crate("x")
                .module("crate::kernel")
                .must_not_import("crate::projection")
                .because("the kernel does not reach the projection"),
        )
        .boundary(
            ModuleBoundary::in_crate("x")
                .module("crate::kernel")
                .restrict_imports_to(vec!["crate::types"])
                .because("the kernel imports only the types"),
        )
        .boundary(
            ModuleBoundary::in_crate("x")
                .module("crate::projection")
                .must_not_import("crate::kernel")
                .because("the projection does not reach back"),
        )
        .boundary(
            ModuleBoundary::in_crate("x")
                .module("crate::kernel")
                .must_not_call_inline("std::process")
                .because("the kernel spawns no process"),
        );
    let scans = EvaluationScans::shared();
    let outcome = crate::evaluate_with_scans(&constitution, &metadata, &scans);
    assert_eq!(
        outcome.exit_code(),
        1,
        "the forbidden import reacts: {outcome:?}"
    );
    assert_eq!(
        scans.roots_built(),
        1,
        "four boundaries over one root build its scan once, not once per boundary"
    );

    let ws = TempWorkspace::new("root-scan-per-root");
    ws.write("lib.rs", "pub mod kernel;\npub mod types;\n");
    ws.write("kernel.rs", "pub struct K;\n");
    ws.write("types.rs", "pub struct T;\n");
    ws.write("bin/tool.rs", "fn main() {}\n");
    let metadata = serde_json::json!({
        "packages": [{
            "name": "x",
            "targets": [
                { "kind": ["lib"], "src_path": ws.src().join("lib.rs").to_string_lossy() },
                { "kind": ["bin"], "src_path": ws.src().join("bin/tool.rs").to_string_lossy() },
            ],
        }],
    });
    let constitution = Constitution::new("t")
        .boundary(
            ModuleBoundary::in_crate("x")
                .module("crate::kernel")
                .must_not_import("crate::types")
                .because("the kernel does not reach the types"),
        )
        .boundary(
            ModuleBoundary::in_crate("x")
                .module("crate::types")
                .must_not_import("crate::kernel")
                .because("the types do not reach back"),
        );
    let scans = EvaluationScans::shared();
    let outcome = crate::evaluate_with_scans(&constitution, &metadata, &scans);
    assert_eq!(outcome.exit_code(), 0, "{outcome:?}");
    assert_eq!(
        scans.roots_built(),
        2,
        "a package of a lib and a bin builds each root once across both boundaries"
    );
}

/// One corpus entry's fixture and constitution parts, built fresh per run.
type CorpusEntry = (TempWorkspace, Value, Vec<ModuleBoundary>);

/// One corpus entry: its name and the builder of its fixture and boundaries.
struct Corpus {
    name: &'static str,
    build: fn() -> CorpusEntry,
}

/// The outbound family: a forbid and a restrict over one governed module, both breached.
fn outbound() -> CorpusEntry {
    let ws = TempWorkspace::new("eq-outbound");
    ws.write(
        "lib.rs",
        "pub mod kernel;\npub mod projection;\npub mod types;\n",
    );
    ws.write("kernel.rs", "use crate::projection::P;\npub struct K;\n");
    ws.write("projection.rs", "pub struct P;\n");
    ws.write("types.rs", "pub struct T;\n");
    let metadata = ws.metadata("x");
    let boundaries = vec![
        ModuleBoundary::in_crate("x")
            .module("crate::kernel")
            .must_not_import("crate::projection")
            .because("the kernel does not reach the projection"),
        ModuleBoundary::in_crate("x")
            .module("crate::kernel")
            .restrict_imports_to(vec!["crate::types"])
            .because("the kernel imports only the types"),
    ];
    (ws, metadata, boundaries)
}

/// The inbound family: `crate::internal` binds `foo` in both namespaces (`mod foo` and `fn foo`),
/// so the shallow rule reacts through the value-namespace reading of `use crate::internal::foo;`.
/// `internal.rs` is not the unit's first file, and a block of it declares an inline module holding a
/// `fn`, so the value-namespace inventory is read from a table whose number is not `0` and holds a
/// block-declared module's item.
fn inbound() -> CorpusEntry {
    let ws = TempWorkspace::new("eq-inbound");
    ws.write(
        "lib.rs",
        "pub mod internal;\npub mod api;\npub mod kernel;\n",
    );
    ws.write("internal.rs", INBOUND_INTERNAL);
    ws.write("api.rs", "use crate::internal::foo;\npub fn a() {}\n");
    ws.write(
        "kernel.rs",
        "use crate::internal::foo as f;\npub fn k() {}\n",
    );
    let metadata = ws.metadata("x");
    let boundaries = vec![
        ModuleBoundary::in_crate("x")
            .module("crate::internal")
            .must_not_be_imported_by("crate::api")
            .depth(ScanDepth::Shallow)
            .because("internal is private to the crate"),
        ModuleBoundary::in_crate("x")
            .module("crate::internal")
            .must_only_be_imported_by(vec!["crate::kernel"])
            .because("only the kernel reaches internal"),
    ];
    (ws, metadata, boundaries)
}

/// The governed module of the inbound family: `foo` in both namespaces, a block declaring an inline
/// module whose `fn` is a value of that block-declared module, never of `crate::internal`, and a
/// macro's group holding a block-declared module, whose path segment names its table's number.
const INBOUND_INTERNAL: &str = "pub mod foo { pub const INSIDE: u8 = 0; }\npub fn foo() {}\n\
     pub fn host() { mod nested { pub fn foo() {} } nested::foo(); }\n\
     m! { fn g() { mod k { pub fn foo() {} } } }\n";

/// An inbound boundary whose value-namespace reading of its governed module decides a violation
/// builds each file's table once, as the module the unit reads it as, and the inventory builds none
/// of its own.
#[test]
pub(super) fn a_governed_modules_value_items_are_read_from_the_units_tables() {
    let (_ws, metadata, boundaries) = inbound();
    let constitution = constitution_of(boundaries);
    crate::module_scan::take_table_builds();
    let outcome = crate::evaluate_with_scans(&constitution, &metadata, &EvaluationScans::shared());
    let builds = crate::module_scan::take_table_builds();
    let importers: BTreeSet<String> = match &outcome {
        Outcome::Violations(report) => report
            .violations
            .iter()
            .map(|violation| violation.finding.clone())
            .collect(),
        other => panic!("the value-namespace reading reacts: {other:?}"),
    };
    assert!(
        importers
            .iter()
            .any(|finding| finding.contains("crate::api")),
        "the shallow rule reacts on `crate::api` only through the governed module's value items: {importers:?}"
    );
    let mut per_module: HashMap<&str, usize> = HashMap::new();
    for ((module, _table), count) in &builds {
        *per_module.entry(module.as_str()).or_default() += count;
    }
    assert_eq!(
        per_module,
        HashMap::from([
            ("crate", 1),
            ("crate::internal", 1),
            ("crate::api", 1),
            ("crate::kernel", 1),
        ]),
        "each file's table is built once, as its module, and the inventory builds none: {builds:?}"
    );
    let package = &metadata["packages"][0];
    let lib = PathBuf::from(package["targets"][0]["src_path"].as_str().unwrap());
    let root = EvaluationScans::shared()
        .root_scan(package, "x", Some(&lib), None)
        .unwrap();
    let items: BTreeSet<String> = root
        .governed_module_value_items("crate::internal")
        .unwrap()
        .into_iter()
        .collect();
    assert_eq!(
        items,
        BTreeSet::from([
            "crate::internal::foo".to_string(),
            "crate::internal::foo::INSIDE".to_string(),
            "crate::internal::host".to_string(),
            "crate::internal::{block}::nested::foo".to_string(),
        ]),
        "the inventory holds the values of the governed module and of each inline module it declares, a \
         block-declared module's among them, keyed by their true module, and no segment \
         naming a table's number, which a macro's group alone would carry"
    );
}

/// External-crate confinement beside an outbound rule over the same root, one of them clean.
fn external_confinement() -> CorpusEntry {
    let ws = TempWorkspace::new("eq-external");
    ws.write("lib.rs", "pub mod ffi;\npub mod service;\npub mod extra;\n");
    ws.write("ffi.rs", "\n");
    ws.write("service.rs", "use libc::c_int;\n");
    ws.write("extra.rs", "use serde::Deserialize;\n");
    let metadata = ws.metadata("x");
    let boundaries = vec![
        ModuleBoundary::in_crate("x")
            .module("crate::ffi")
            .confine_external_crate("libc")
            .because("the raw libc surface stays behind the ffi module"),
        ModuleBoundary::in_crate("x")
            .module("crate::service")
            .must_not_import("crate::ffi")
            .because("service does not reach the ffi module"),
    ];
    (ws, metadata, boundaries)
}

/// The inline family: a call confinement, its permitting dual, a strict confinement, and a
/// strict-external confinement against a declared dependency.
fn inline() -> CorpusEntry {
    let ws = TempWorkspace::new("eq-inline");
    ws.write("lib.rs", "pub mod core;\npub mod exec;\n");
    ws.write(
        "core.rs",
        "pub fn stamp() { let _ = std::process::id(); }\npub fn tick() { let _ = chrono::Utc::now(); }\n",
    );
    ws.write("exec.rs", "pub fn run() { std::process::exit(0); }\n");
    let metadata = ws.metadata_with_deps("x", &[("chrono", None)]);
    let boundaries = vec![
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::process")
            .because("core spawns no process"),
        ModuleBoundary::in_crate("x")
            .module("crate::exec")
            .confine_inline_call("std::process")
            .because("only exec spawns a process"),
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::process")
            .strict_prefix_only()
            .because("core does not even name a process"),
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("chrono::Utc")
            .strict_external()
            .because("core reads no wall clock — time is injected"),
    ];
    (ws, metadata, boundaries)
}

/// A package of two compiled roots: a rule breached only in the bin root, a rule whose governed
/// module the bin root lacks, and a whole-root rule judged in the bin root with an empty permitted
/// region.
fn several_roots() -> CorpusEntry {
    let ws = TempWorkspace::new("eq-roots");
    ws.write(
        "lib.rs",
        "pub mod kernel;\npub mod shared;\npub mod internal;\n",
    );
    ws.write("kernel.rs", "pub struct K;\n");
    ws.write("shared.rs", "use crate::kernel::K;\n");
    ws.write("internal.rs", "\n");
    ws.write("bin/tool.rs", "mod tooling;\nmod shared;\nfn main() {}\n");
    ws.write("bin/tooling.rs", "use libc::c_int;\n");
    ws.write("bin/shared.rs", "use crate::tooling;\nuse libc::c_void;\n");
    let metadata = serde_json::json!({
        "packages": [{
            "name": "x",
            "targets": [
                { "kind": ["lib"], "src_path": ws.src().join("lib.rs").to_string_lossy() },
                { "kind": ["bin"], "src_path": ws.src().join("bin/tool.rs").to_string_lossy() },
            ],
        }],
    });
    let boundaries = vec![
        ModuleBoundary::in_crate("x")
            .module("crate::shared")
            .must_not_import("crate::tooling")
            .because("shared must not reach the tooling"),
        ModuleBoundary::in_crate("x")
            .module("crate::kernel")
            .must_not_import("crate::tooling")
            .because("the kernel must not reach the tooling"),
        ModuleBoundary::in_crate("x")
            .module("crate::internal")
            .confine_external_crate("libc")
            .because("the raw libc surface stays behind internal"),
    ];
    (ws, metadata, boundaries)
}

/// A constitution refused two ways: a rule's named module no root declares, and a governed module
/// no root declares.
fn refused_unknown_module() -> CorpusEntry {
    let ws = TempWorkspace::new("eq-refused-named");
    ws.write("lib.rs", "pub mod real;\n");
    ws.write("real.rs", "\n");
    let metadata = ws.metadata("x");
    let boundaries = vec![
        ModuleBoundary::in_crate("x")
            .module("crate::real")
            .must_not_import("crate::io")
            .because("real does not reach the io"),
        ModuleBoundary::in_crate("x")
            .module("crate::ghost")
            .must_not_import("crate::real")
            .because("a ghost does not reach the real"),
    ];
    (ws, metadata, boundaries)
}

/// A constitution refused by an inline module as a governed target.
fn refused_inline_target() -> CorpusEntry {
    let ws = TempWorkspace::new("eq-refused-inline");
    ws.write("lib.rs", "pub mod wrapper;\npub mod real;\n");
    ws.write("wrapper.rs", "pub mod inline {}\n");
    ws.write("real.rs", "\n");
    let metadata = ws.metadata("x");
    let boundaries = vec![
        ModuleBoundary::in_crate("x")
            .module("crate::wrapper::inline")
            .must_not_import("crate::real")
            .because("an inline module cannot be governed"),
        ModuleBoundary::in_crate("x")
            .module("crate::real")
            .must_not_import("crate::wrapper")
            .because("real does not reach the wrapper"),
    ];
    (ws, metadata, boundaries)
}

/// A ring of imports inside one module, read from two of its bindings: `x` and `y` each name a terminal of their own
/// under `cfg(unix)` and each other otherwise, and `z` names `y`. A reading entering at `x` reads `y` one binding deep
/// and cuts the ring where `y` comes back to `x`, so what it finds for `y` there lacks `x`'s terminal; a reading
/// entering at `z` reads `y` at that same depth, from that same module, and its answer holds both terminals. Two inline
/// boundaries enter at the two bindings, from two child modules, under different prefixes and strictness, so a cut
/// answer the first kept for `y` would hide from the second the terminal its prefix names.
fn import_ring() -> CorpusEntry {
    let ws = TempWorkspace::new("eq-ring");
    ws.write("lib.rs", "pub mod t0;\npub mod t1;\npub mod r;\n");
    ws.write("t0.rs", "pub fn f() {}\n");
    ws.write("t1.rs", "pub fn f() {}\n");
    ws.write(
        "r.rs",
        "#[cfg(unix)]\npub use crate::t0 as x;\n#[cfg(not(unix))]\npub use y as x;\n\
         #[cfg(unix)]\npub use crate::t1 as y;\n#[cfg(not(unix))]\npub use x as y;\n\
         pub use y as z;\npub mod ra;\npub mod rb;\n",
    );
    ws.write("r/ra.rs", "pub fn run() { super::x::f(); }\n");
    ws.write("r/rb.rs", "pub fn run() { super::z::f(); }\n");
    let metadata = ws.metadata("x");
    let boundaries = vec![
        ModuleBoundary::in_crate("x")
            .module("crate::r::ra")
            .must_not_call_inline("crate::t1")
            .because("ra does not reach the second terminal"),
        ModuleBoundary::in_crate("x")
            .module("crate::r::rb")
            .must_not_call_inline("crate::t0")
            .strict_prefix_only()
            .because("rb does not even name the first terminal"),
    ];
    (ws, metadata, boundaries)
}

/// Every constitution
/// of the corpus — outbound, inbound with the value-namespace form, external confinement, the
/// inline family with strict and strict-external, a ring of imports read from two of its bindings
/// under different prefixes and strictness, a two-root package, and two refused
/// constitutions — is judged through both scan forms, in each of two boundary orders, and the two
/// readings of one order yield the same outcome: the same violations with the same identities and
/// severities, or the same refusal. Nothing is claimed across orders: the first error an
/// evaluation returns may be a different boundary's.
#[test]
pub(super) fn shared_and_independent_scans_yield_one_outcome() {
    let corpus = [
        Corpus {
            name: "outbound",
            build: outbound,
        },
        Corpus {
            name: "inbound",
            build: inbound,
        },
        Corpus {
            name: "external-confinement",
            build: external_confinement,
        },
        Corpus {
            name: "inline",
            build: inline,
        },
        Corpus {
            name: "import-ring",
            build: import_ring,
        },
        Corpus {
            name: "several-roots",
            build: several_roots,
        },
        Corpus {
            name: "refused-unknown-module",
            build: refused_unknown_module,
        },
        Corpus {
            name: "refused-inline-target",
            build: refused_inline_target,
        },
    ];
    let mut saw_violations = false;
    let mut saw_refusal = false;
    for Corpus { name, build } in corpus {
        let (_ws, metadata, boundaries) = build();
        for reversed in [false, true] {
            let mut ordered = boundaries.clone();
            if reversed {
                ordered.reverse();
            }
            let constitution = constitution_of(ordered);
            let (shared, independent) = shared_and_independent(&constitution, &metadata);
            match &shared {
                Outcome::Violations(_) => saw_violations = true,
                Outcome::ConstitutionError(_) => saw_refusal = true,
                _ => {}
            }
            assert_eq!(
                shared, independent,
                "{name} (reversed: {reversed}): a shared scan per root and a scan per boundary \
                 yield one outcome"
            );
        }
    }
    assert!(
        saw_violations,
        "the corpus judges violations — without one, the equivalence shown is vacuous"
    );
    assert!(
        saw_refusal,
        "the corpus is refused — without one, the equivalence shown is vacuous"
    );
}

/// Each path in `paths`, read once: what an evaluation that reads every source it meets once, and
/// no other, has read.
fn read_once(paths: &[PathBuf]) -> HashMap<PathBuf, usize> {
    paths.iter().map(|path| (path.clone(), 1)).collect()
}

/// Several boundaries over
/// one root — import rules with an inbound rule's value-namespace reading of the governed module,
/// and the inline family with a strict confinement — read each source they reach once, among them a
/// source outside the root's file list that a `#[path]` reaches; the set read is exactly the set
/// reached, held both ways.
#[test]
pub(super) fn each_source_path_is_read_once_on_demand() {
    let ws = TempWorkspace::new("read-once");
    ws.write(
        "lib.rs",
        "pub mod internal;\npub mod api;\npub mod core;\n#[path = \"../outside.rs\"]\npub mod outside;\n",
    );
    ws.write(
        "internal.rs",
        "pub mod foo { pub const INSIDE: u8 = 0; }\npub fn foo() {}\n",
    );
    ws.write("api.rs", "use crate::internal::foo;\npub fn a() {}\n");
    ws.write(
        "core.rs",
        "use crate::internal::foo as f;\npub fn stamp() { let _ = std::process::id(); }\n",
    );
    ws.write_at("outside.rs", "pub fn o() { std::process::exit(0); }\n");
    let metadata = ws.metadata("x");
    let constitution = constitution_of(vec![
        ModuleBoundary::in_crate("x")
            .module("crate::internal")
            .must_not_be_imported_by("crate::api")
            .depth(ScanDepth::Shallow)
            .because("internal is private to the crate"),
        ModuleBoundary::in_crate("x")
            .module("crate::internal")
            .must_only_be_imported_by(vec!["crate::core"])
            .because("only core reaches internal"),
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::process")
            .because("core spawns no process"),
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::process")
            .strict_prefix_only()
            .because("core does not even name a process"),
        ModuleBoundary::in_crate("x")
            .module("crate::outside")
            .must_not_call_inline("std::process")
            .because("the outside module spawns no process"),
    ]);
    let scans = EvaluationScans::shared();
    let outcome = crate::evaluate_with_scans(&constitution, &metadata, &scans);
    assert_eq!(outcome.exit_code(), 1, "the boundaries react: {outcome:?}");
    let src = ws.src();
    assert_eq!(
        scans.source_reads(),
        read_once(&[
            src.join("lib.rs"),
            src.join("internal.rs"),
            src.join("api.rs"),
            src.join("core.rs"),
            src.join("../outside.rs"),
        ]),
        "every source the boundaries reach is read once, by the path it was opened at, and no other is read"
    );
}

/// A source compiled
/// by two roots is read once across both, and each root retains its own findings.
#[test]
pub(super) fn a_source_two_roots_reach_is_read_once() {
    let ws = TempWorkspace::new("read-once-two-roots");
    ws.write("lib.rs", "pub mod kernel;\npub mod common;\n");
    ws.write("main.rs", "mod kernel;\nmod common;\nfn main() {}\n");
    ws.write("kernel.rs", "pub struct K;\n");
    ws.write("common.rs", "use crate::kernel::K;\n");
    let metadata = serde_json::json!({
        "packages": [{
            "name": "x",
            "targets": [
                { "kind": ["lib"], "src_path": ws.src().join("lib.rs").to_string_lossy() },
                { "kind": ["bin"], "src_path": ws.src().join("main.rs").to_string_lossy() },
            ],
        }],
    });
    let constitution = constitution_of(vec![
        ModuleBoundary::in_crate("x")
            .module("crate::common")
            .must_not_import("crate::kernel")
            .because("common does not reach the kernel"),
    ]);
    let scans = EvaluationScans::shared();
    let outcome = crate::evaluate_with_scans(&constitution, &metadata, &scans);
    let src = ws.src();
    assert_eq!(
        scans.source_reads(),
        read_once(&[
            src.join("lib.rs"),
            src.join("main.rs"),
            src.join("kernel.rs"),
            src.join("common.rs"),
        ]),
        "a file both roots compile is read once across them"
    );
    let units: BTreeSet<String> = match &outcome {
        Outcome::Violations(report) => report
            .violations
            .iter()
            .flat_map(|violation| violation.fact().fields())
            .filter(|(field, _)| *field == "unit")
            .map(|(_, unit)| unit.to_string())
            .collect(),
        other => panic!("each root's common module reacts: {other:?}"),
    };
    assert_eq!(
        units,
        BTreeSet::from(["lib.rs".to_string(), "main.rs".to_string()]),
        "each root judges its own position of the shared file: {outcome:?}"
    );
    assert_eq!(
        outcome,
        crate::evaluate_with_scans(&constitution, &metadata, &EvaluationScans::independent()),
        "the shared reading judges each root as a reading per boundary does"
    );
}

/// One source loaded
/// as two modules is read once, and both module positions retain their findings.
#[test]
pub(super) fn a_source_two_modules_reach_is_read_once() {
    let ws = TempWorkspace::new("read-once-two-modules");
    ws.write(
        "lib.rs",
        "#[path = \"twin.rs\"]\npub mod a;\n#[path = \"twin.rs\"]\npub mod b;\n",
    );
    ws.write("twin.rs", "pub fn t() { std::process::exit(0); }\n");
    let metadata = ws.metadata("x");
    let constitution = constitution_of(vec![
        ModuleBoundary::in_crate("x")
            .module("crate::a")
            .must_not_call_inline("std::process")
            .because("a spawns no process"),
        ModuleBoundary::in_crate("x")
            .module("crate::b")
            .must_not_call_inline("std::process")
            .strict_prefix_only()
            .because("b does not even name a process"),
    ]);
    let scans = EvaluationScans::shared();
    let outcome = crate::evaluate_with_scans(&constitution, &metadata, &scans);
    let src = ws.src();
    assert_eq!(
        scans.source_reads(),
        read_once(&[src.join("lib.rs"), src.join("twin.rs")]),
        "a file loaded as two modules is read once for both"
    );
    let findings: BTreeSet<String> = match &outcome {
        Outcome::Violations(report) => report
            .violations
            .iter()
            .map(|violation| violation.finding.clone())
            .collect(),
        other => panic!("each module the file is loaded as reacts: {other:?}"),
    };
    assert_eq!(
        findings,
        BTreeSet::from([
            "std::process::exit in crate::a".to_string(),
            "std::process::exit in crate::b".to_string(),
        ]),
        "each module position of the one file is judged: {outcome:?}"
    );
    assert_eq!(
        outcome,
        crate::evaluate_with_scans(&constitution, &metadata, &EvaluationScans::independent()),
        "the shared reading judges each module position as a reading per boundary does"
    );
}

/// A `.rs` file under the
/// source directory that no `mod` declaration reaches, and that cannot be read, is never asked for,
/// so the evaluation's exit code is the one its reachable sources decide. Unix only and
/// self-calibrating: it skips under a privileged user, where mode 0 is still readable.
#[cfg(unix)]
#[test]
pub(super) fn a_source_no_root_reaches_is_never_read() {
    let ws = TempWorkspace::new("read-never");
    ws.write("lib.rs", "pub mod kernel;\npub mod projection;\n");
    ws.write("kernel.rs", "use crate::projection::P;\npub struct K;\n");
    ws.write("projection.rs", "pub struct P;\n");
    let orphan = ws.write("orphan.rs", "use crate::kernel::K;\n");
    let Some(_unreadable) = xingbiao::Unreadable::try_new(&orphan) else {
        return;
    };
    let metadata = ws.metadata("x");
    let constitution = constitution_of(vec![
        ModuleBoundary::in_crate("x")
            .module("crate::kernel")
            .must_not_import("crate::projection")
            .because("the kernel does not reach the projection"),
    ]);
    let scans = EvaluationScans::shared();
    let outcome = crate::evaluate_with_scans(&constitution, &metadata, &scans);
    assert_eq!(
        outcome.exit_code(),
        1,
        "the reachable sources decide the exit code: {outcome:?}"
    );
    let src = ws.src();
    assert_eq!(
        scans.source_reads(),
        read_once(&[
            src.join("lib.rs"),
            src.join("kernel.rs"),
            src.join("projection.rs"),
        ]),
        "the unreachable, unreadable file is never read"
    );
}

/// Outbound, inbound and external rules share one classification per file and module across
/// boundaries. The exact key set includes every pair a rule reads and excludes the protected
/// subtree every rule skips.
#[test]
pub(super) fn a_files_uses_are_classified_once_across_rules_and_boundaries() {
    let ws = TempWorkspace::new("classify-once");
    ws.write(
        "lib.rs",
        "pub mod internal;\npub mod service;\npub mod ffi;\n",
    );
    ws.write("internal.rs", "pub mod detail;\npub struct Secret;\n");
    ws.write("internal/detail.rs", "use crate::internal::Secret;\n");
    ws.write(
        "service.rs",
        "use crate::internal::Secret;\nuse libc::c_int;\n",
    );
    ws.write(
        "ffi.rs",
        "use crate::internal::Secret;\nuse libc::c_void;\n",
    );
    let metadata = ws.metadata("x");
    let constitution = constitution_of(vec![
        ModuleBoundary::in_crate("x")
            .module("crate::service")
            .must_not_import("crate::internal")
            .because("service does not import internal"),
        ModuleBoundary::in_crate("x")
            .module("crate::service")
            .restrict_imports_to(["crate::ffi"])
            .because("service imports only ffi"),
        ModuleBoundary::in_crate("x")
            .module("crate::internal")
            .must_not_be_imported_by("crate::service")
            .because("service does not reach internal"),
        ModuleBoundary::in_crate("x")
            .module("crate::internal")
            .must_only_be_imported_by(["crate::ffi"])
            .because("only ffi reaches internal"),
        ModuleBoundary::in_crate("x")
            .module("crate::internal")
            .confine_external_crate("libc")
            .because("only internal imports libc"),
        ModuleBoundary::in_crate("x")
            .module("crate::internal")
            .confine_external_crate("serde")
            .because("only internal imports serde"),
    ]);
    for reversed in [false, true] {
        let constitution = if reversed {
            let mut boundaries = constitution.boundaries().to_vec();
            boundaries.reverse();
            let mut reversed = Constitution::new("reverse");
            for boundary in boundaries {
                reversed = reversed.boundary(boundary);
            }
            reversed
        } else {
            constitution.clone()
        };
        let scans = EvaluationScans::shared();
        let outcome = crate::evaluate_with_scans(&constitution, &metadata, &scans);
        assert_eq!(outcome.exit_code(), 1, "the rules react: {outcome:?}");
        let expected: HashMap<_, _> = [
            ("lib.rs", "crate"),
            ("service.rs", "crate::service"),
            ("ffi.rs", "crate::ffi"),
        ]
        .into_iter()
        .map(|(file, module)| ((ws.src().join(file), module.to_string()), 1))
        .collect();
        assert_eq!(
            scans.classifications(),
            expected,
            "each pair at least one rule reads is classified once and no other pair is classified (reversed: {reversed})"
        );
    }
}