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
//! Dimension-owned observed facts and their shared reaction projection.

use xuanji::{Finding, StructuredFactIdentity};

use crate::{DependencyKind, SourceKind};

/// One offending manifest declaration a crate boundary observed.
pub(crate) enum CrateFact {
    /// A dependency the rule does not permit.
    Dependency {
        /// The dependency's package name, never its local rename.
        package: String,
        /// The dependency table it is declared in.
        kind: DependencyKind,
    },
    /// A feature a dependency declaration requests on a crate whose features the rule restricts or
    /// forbids.
    Feature {
        /// The crate the rule names, whose feature it is.
        package: String,
        /// The feature's name.
        feature: String,
        /// The dependency table the declaration is in.
        kind: DependencyKind,
    },
    /// A dependency declared from a source kind the rule does not permit.
    Source {
        /// The dependency's package name, never its local rename.
        package: String,
        /// The source the declaration names.
        source: SourceKind,
        /// The dependency table it is declared in.
        kind: DependencyKind,
    },
}

impl CrateFact {
    /// A [`CrateFact::Dependency`].
    pub(crate) fn dependency(package: String, kind: DependencyKind) -> Self {
        Self::Dependency { package, kind }
    }

    /// A [`CrateFact::Feature`].
    pub(crate) fn feature(package: String, feature: String, kind: DependencyKind) -> Self {
        Self::Feature {
            package,
            feature,
            kind,
        }
    }

    /// A [`CrateFact::Source`].
    pub(crate) fn source(package: String, source: SourceKind, kind: DependencyKind) -> Self {
        Self::Source {
            package,
            source,
            kind,
        }
    }

    /// Project the fact into its finding: the text names the package (with `/feature` for a feature),
    /// suffixed ` (dev)` or ` (build)` outside the normal table, and the identity keys every field.
    pub(crate) fn into_finding(self) -> Finding {
        match self {
            CrateFact::Dependency { package, kind } => Finding::new(
                format!("{package}{}", kind.finding_suffix()),
                fact(
                    "dependency",
                    "dependency-edge",
                    [("kind", kind.key_label()), ("package", package.as_str())],
                ),
            ),
            CrateFact::Feature {
                package,
                feature,
                kind,
            } => Finding::new(
                format!("{package}/{feature}{}", kind.finding_suffix()),
                fact(
                    "dependency-feature",
                    "declared-feature",
                    [
                        ("feature", feature.as_str()),
                        ("kind", kind.key_label()),
                        ("package", package.as_str()),
                    ],
                ),
            ),
            CrateFact::Source {
                package,
                source,
                kind,
            } => Finding::new(
                format!("{package}{}", kind.finding_suffix()),
                fact(
                    "dependency-source",
                    "declared-source",
                    [
                        ("kind", kind.key_label()),
                        ("package", package.as_str()),
                        ("source", source.label()),
                    ],
                ),
            ),
        }
    }
}

/// One offence a module boundary observed in a compilation unit, before it is keyed by the governing
/// package and the unit.
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum ModuleFact {
    /// An outbound-rule offence: a `use` inside the governed module that the rule forbids.
    ImportedPath {
        /// The `crate::`-rooted path the `use` names.
        path: String,
        /// The module lexically declaring the `use`.
        importer: String,
    },
    /// An inbound-rule offence: the module outside the governed one that imports it.
    ImporterModule(String),
    /// An external-crate-confinement offence: the module outside the permitted subtree that imports
    /// the confined crate.
    ExternalImporter(String),
    /// An inline-confinement offence: a resolved path under the confined prefix, named in `module`.
    InlinePath {
        /// The canonical path the occurrence resolved to.
        path: String,
        /// The module whose file the occurrence stands in.
        module: String,
    },
    /// An inline-confinement offence by a glob import whose reach covers the confined prefix, rather
    /// than by a named path.
    InlineGlob {
        /// The glob's own resolved path.
        path: String,
        /// The module whose file the glob stands in.
        module: String,
    },
}

impl ModuleFact {
    /// `governing_package` is the crate the violated boundary was declared against
    /// (`boundary.crate_package`) — an identity-bearing field distinct from `CrateFact`'s
    /// `"package"` above, which names the *observed dependency*, not the declaring crate. Without
    /// it, two crates declaring the identical boundary against the identical module path produce
    /// identical identities and silently collapse (see `intent/structured-violation-identity.md`).
    /// `unit` is the **compilation unit** the observation came from: the root's source path relative to
    /// the package's manifest directory (`src/lib.rs`, `src/main.rs`, `tools/x.rs`). A package builds more
    /// than one root — a library beside a `bin` — and every root denotes the module path `crate` and
    /// shares the package name, so without this role the same violation in two roots carries ONE identity
    /// and a baseline accepting it in one silently masks it appearing in the other.
    ///
    /// It is not the target's NAME: a package may build a library and a `bin` of the same name (this
    /// repository does), so a name is not unique within a package. It is not an index or metadata order
    /// either — `semantic-signature-coupling`'s prohibition on positional identity applies here too. The
    /// root path is declaration-derived, unique per unit, and moves with neither the checkout nor the
    /// member set. A root **outside** the manifest directory has no checkout-independent label at all
    /// and is a constitution error rather than a fallback — see [`xingbiao::compilation_unit_label`],
    /// whose `None` has exactly that one cause.
    ///
    /// This is deliberately NOT the rule 漏刻 applies to a file reached through an absolute `#[path]`
    /// literal, and the difference is the whole reason: that literal is **committed text**, identical in
    /// every checkout, so keeping it verbatim is what makes it stable. A root path outside the manifest
    /// directory is the clone's own location, so keeping it verbatim is what makes it unstable. Same
    /// shape, opposite consequence.
    pub(crate) fn into_finding(self, governing_package: &str, unit: &str) -> Finding {
        match self {
            ModuleFact::ImportedPath { path, importer } => {
                let key = fact(
                    "imported-path",
                    "module-path",
                    [
                        ("governing_package", governing_package),
                        ("unit", unit),
                        ("importer", importer.as_str()),
                        ("path", path.as_str()),
                    ],
                );
                Finding::new(path, key)
            }
            ModuleFact::ImporterModule(module) => {
                let key = fact(
                    "importer-module",
                    "module-path",
                    [
                        ("governing_package", governing_package),
                        ("unit", unit),
                        ("module", module.as_str()),
                    ],
                );
                Finding::new(module, key)
            }
            ModuleFact::ExternalImporter(module) => {
                let key = fact(
                    "external-importer",
                    "module-path",
                    [
                        ("governing_package", governing_package),
                        ("unit", unit),
                        ("module", module.as_str()),
                    ],
                );
                Finding::new(module, key)
            }
            ModuleFact::InlinePath { path, module } => Finding::new(
                format!("{path} in {module}"),
                fact(
                    "inline-path",
                    "path-in-module",
                    [
                        ("governing_package", governing_package),
                        ("unit", unit),
                        ("module", module.as_str()),
                        ("path", path.as_str()),
                    ],
                ),
            ),
            ModuleFact::InlineGlob { path, module } => Finding::new(
                format!("glob {path} in {module}"),
                fact(
                    "inline-glob",
                    "path-in-module",
                    [
                        ("governing_package", governing_package),
                        ("unit", unit),
                        ("module", module.as_str()),
                        ("path", path.as_str()),
                    ],
                ),
            ),
        }
    }
}

/// The structured identity of one guibiao fact: fact type `tianheng.fact/guibiao/<family>`, with
/// `shape` and `fields` passed through unchanged.
fn fact<const N: usize>(
    family: &str,
    shape: &str,
    fields: [(&str, &str); N],
) -> StructuredFactIdentity {
    StructuredFactIdentity::of(format!("tianheng.fact/guibiao/{family}"), shape, fields)
}

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

    fn assert_dependency_kind_is_cataloged(kind: DependencyKind) {
        match kind {
            DependencyKind::Normal | DependencyKind::Dev | DependencyKind::Build => {}
        }
    }

    fn assert_source_kind_is_cataloged(source: SourceKind) {
        match source {
            SourceKind::Registry | SourceKind::Git | SourceKind::Path => {}
        }
    }

    fn assert_crate_fact_is_cataloged(fact: &CrateFact) {
        match fact {
            CrateFact::Dependency { package: _, kind }
            | CrateFact::Feature {
                package: _,
                feature: _,
                kind,
            } => assert_dependency_kind_is_cataloged(*kind),
            CrateFact::Source {
                package: _,
                source,
                kind,
            } => {
                assert_dependency_kind_is_cataloged(*kind);
                assert_source_kind_is_cataloged(*source);
            }
        }
    }

    fn assert_module_fact_is_cataloged(fact: &ModuleFact) {
        match fact {
            ModuleFact::ImportedPath { .. }
            | ModuleFact::ImporterModule(_)
            | ModuleFact::ExternalImporter(_)
            | ModuleFact::InlinePath { path: _, module: _ }
            | ModuleFact::InlineGlob { path: _, module: _ } => {}
        }
    }

    fn assert_key(fact: impl IntoFinding, family: &str, shape: &str, fields: &[(&str, &str)]) {
        let finding = fact.into_finding();
        assert_eq!(
            finding.key().fact_type(),
            format!("tianheng.fact/guibiao/{family}")
        );
        assert_eq!(finding.key().shape(), shape);
        assert_eq!(finding.key().fields().collect::<Vec<_>>(), fields);
    }

    trait IntoFinding {
        fn into_finding(self) -> Finding;
    }

    impl IntoFinding for CrateFact {
        fn into_finding(self) -> Finding {
            CrateFact::into_finding(self)
        }
    }

    impl IntoFinding for ModuleFact {
        fn into_finding(self) -> Finding {
            ModuleFact::into_finding(self, "app", "src/lib.rs")
        }
    }

    #[test]
    fn published_crate_fact_identity_schema_is_exact_and_exhaustive() {
        let dependency_cases = [
            (DependencyKind::Normal, "normal"),
            (DependencyKind::Dev, "dev"),
            (DependencyKind::Build, "build"),
        ];
        for (kind, label) in dependency_cases {
            let fact = CrateFact::dependency("serde".to_string(), kind);
            assert_crate_fact_is_cataloged(&fact);
            assert_key(
                fact,
                "dependency",
                "dependency-edge",
                &[("kind", label), ("package", "serde")],
            );

            let fact = CrateFact::feature("serde".to_string(), "derive".to_string(), kind);
            assert_crate_fact_is_cataloged(&fact);
            assert_key(
                fact,
                "dependency-feature",
                "declared-feature",
                &[("feature", "derive"), ("kind", label), ("package", "serde")],
            );
        }

        let source_cases = [
            (SourceKind::Registry, "registry"),
            (SourceKind::Git, "git"),
            (SourceKind::Path, "path"),
        ];
        for (source, label) in source_cases {
            let fact = CrateFact::source("serde".to_string(), source, DependencyKind::Normal);
            assert_crate_fact_is_cataloged(&fact);
            assert_key(
                fact,
                "dependency-source",
                "declared-source",
                &[("kind", "normal"), ("package", "serde"), ("source", label)],
            );
        }
    }

    /// Every module fact is observed from source, so governing_package and unit coordinates
    /// must always be present in the identity key.
    #[test]
    fn published_module_fact_identity_schema_is_exact_and_exhaustive() {
        struct ModuleKeyCase {
            fact: ModuleFact,
            fields: Vec<(&'static str, &'static str)>,
            family: &'static str,
            shape: &'static str,
        }

        let cases = vec![
            ModuleKeyCase {
                fact: ModuleFact::ImportedPath {
                    path: "crate::ports".to_string(),
                    importer: "crate::core".to_string(),
                },
                fields: vec![
                    ("governing_package", "app"),
                    ("importer", "crate::core"),
                    ("path", "crate::ports"),
                    ("unit", "src/lib.rs"),
                ],
                family: "imported-path",
                shape: "module-path",
            },
            ModuleKeyCase {
                fact: ModuleFact::ImporterModule("crate::api".to_string()),
                fields: vec![
                    ("governing_package", "app"),
                    ("module", "crate::api"),
                    ("unit", "src/lib.rs"),
                ],
                family: "importer-module",
                shape: "module-path",
            },
            ModuleKeyCase {
                fact: ModuleFact::ExternalImporter("crate::ffi".to_string()),
                fields: vec![
                    ("governing_package", "app"),
                    ("module", "crate::ffi"),
                    ("unit", "src/lib.rs"),
                ],
                family: "external-importer",
                shape: "module-path",
            },
            ModuleKeyCase {
                fact: ModuleFact::InlinePath {
                    path: "std::time::SystemTime::now".to_string(),
                    module: "crate::kernel".to_string(),
                },
                fields: vec![
                    ("governing_package", "app"),
                    ("module", "crate::kernel"),
                    ("path", "std::time::SystemTime::now"),
                    ("unit", "src/lib.rs"),
                ],
                family: "inline-path",
                shape: "path-in-module",
            },
            ModuleKeyCase {
                fact: ModuleFact::InlineGlob {
                    path: "std::time::*".to_string(),
                    module: "crate::kernel".to_string(),
                },
                fields: vec![
                    ("governing_package", "app"),
                    ("module", "crate::kernel"),
                    ("path", "std::time::*"),
                    ("unit", "src/lib.rs"),
                ],
                family: "inline-glob",
                shape: "path-in-module",
            },
        ];
        for case in cases {
            assert_module_fact_is_cataloged(&case.fact);
            for required in ["governing_package", "unit"] {
                assert!(
                    case.fields.iter().any(|(name, _)| *name == required),
                    "{}: a source-observed fact must carry the '{required}' coordinate — see \
                     `structured-violation-identity`'s coordinate derivation",
                    case.family
                );
            }
            assert_key(case.fact, case.family, case.shape, &case.fields);
        }
    }

    #[test]
    fn distinct_governing_packages_produce_distinct_module_fact_identity() {
        let alpha = ModuleFact::ImporterModule("crate::app".to_string())
            .into_finding("alpha", "src/lib.rs")
            .key()
            .clone();
        let beta = ModuleFact::ImporterModule("crate::app".to_string())
            .into_finding("beta", "src/lib.rs")
            .key()
            .clone();
        assert_ne!(
            alpha, beta,
            "two crates declaring the identical module path must not share one fact identity"
        );
    }

    #[test]
    fn identity_bearing_values_and_fact_shapes_stay_distinct() {
        let normal = CrateFact::dependency("serde".to_string(), DependencyKind::Normal)
            .into_finding()
            .key()
            .clone();
        let dev = CrateFact::dependency("serde".to_string(), DependencyKind::Dev)
            .into_finding()
            .key()
            .clone();
        let feature = CrateFact::feature(
            "serde".to_string(),
            "derive".to_string(),
            DependencyKind::Normal,
        )
        .into_finding()
        .key()
        .clone();
        assert_ne!(normal, dev);
        assert_ne!(normal, feature);

        let import = ModuleFact::ImportedPath {
            path: "crate::ports".to_string(),
            importer: "crate::core".to_string(),
        }
        .into_finding("app", "src/lib.rs")
        .key()
        .clone();
        let importer = ModuleFact::ImporterModule("crate::ports".to_string())
            .into_finding("app", "src/lib.rs")
            .key()
            .clone();
        assert_ne!(import, importer);
    }

    #[test]
    fn unrelated_construction_order_does_not_change_fact_identity() {
        let before = ModuleFact::ImportedPath {
            path: "crate::ports".to_string(),
            importer: "crate::core".to_string(),
        }
        .into_finding("app", "src/lib.rs")
        .key()
        .clone();
        let _unrelated = ModuleFact::InlinePath {
            path: "std::time::SystemTime::now".to_string(),
            module: "crate::adapter".to_string(),
        }
        .into_finding("app", "src/lib.rs");
        let after = ModuleFact::ImportedPath {
            path: "crate::ports".to_string(),
            importer: "crate::core".to_string(),
        }
        .into_finding("app", "src/lib.rs")
        .key()
        .clone();
        assert_eq!(before, after);
    }
}