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
//! 圭表 (Guībiǎo) — the gnomon: Tianheng's static observation core. It reads the cast
//! shadow — a crate's imports and dependencies.
//!
//! The dependency-light **functional core**, derived from `modou`: declare a
//! [`Constitution`] in Rust, observe the real shape from `cargo metadata` and source
//! `use` scans, and [`check`] for drift, returning an [`Outcome`]. This crate is pure
//! observation + comparison — it carries **no** command-line, filesystem, or
//! stdout/stderr shell. The imperative shell lives in the sibling `tianheng` crate,
//! which must depend on this core and never the reverse — a crate-level invariant
//! Tianheng enforces on itself (`crates/shengmo/src/law.rs`).
//!
//! Two reaction kinds, each with its own observation source: [`CrateBoundary`] over
//! `cargo metadata`, and [`ModuleBoundary`] over the crate's own source `use`
//! declarations. Each carries a [`Severity`]; violations gate against a [`Baseline`].
//!
//! Govern by reaction, not instruction.

#![forbid(unsafe_code)]
#![deny(missing_docs)]
#![deny(clippy::missing_docs_in_private_items)]

use std::path::{Path, PathBuf};

use serde_json::Value;

mod bounds;
pub use bounds::observation_bounds;

mod observer;
pub use observer::StaticObserver;

mod module_scan;
use module_scan::EvaluationScans;
mod projection;
pub use projection::{
    StalePolicy, constitution_json, constitution_text, report_json, report_json_with_stale_policy,
    stale_policy,
};
/// Reading `cargo metadata`: workspace membership, dependency edges, and how each crate root is read.
mod cargo_metadata;
pub(crate) use cargo_metadata::*;
/// Checking one crate boundary against the dependency graph `cargo metadata` reports.
mod crate_check;
use crate_check::check_crate_boundary;
/// Which workspace members no boundary targets — an observation that never changes the exit code.
mod coverage;
pub use coverage::Coverage;
use coverage::coverage_from;
/// Messages for the constitution and scan refusals shared across the checks.
mod errors;
mod finding;
use errors::unreadable_workspace_error;
#[cfg(test)]
use errors::{
    confine_external_crate_on_crate_error, inline_empty_prefix_error, inline_empty_verbs_error,
    inline_module_target_error, inline_narrow_and_strict_error,
    must_not_be_imported_by_on_crate_error, must_only_be_imported_by_on_crate_error,
    restrict_imports_to_on_crate_error, unknown_module_error,
};
/// Checking one module boundary against the source of the crate it governs.
mod module_check;
use module_check::check_module_boundary;
mod model;
pub use model::*;

pub use xuanji::{
    Baseline, BaselineEntry, BoundDecl, BoundId, BoundaryKind, Defence, Demonstrates, Extent,
    FactGranularity, Finding, Observer, Outcome, Owner, Polarity, Reached, Report, RuleKey,
    ScanDepth, Severity, StructuredFactIdentity, Subject, Violation, ViolationId, apply_baseline,
};

/// Run the constitution's boundaries against the Cargo workspace at `manifest_path`.
///
/// The spine is **resolve -> observe -> compare -> react**: resolve each target to
/// a workspace package, observe (its dependencies, or its source imports), compare
/// against the rule, and return the outcome. An unresolvable target (or an
/// unreadable workspace) is a constitution error, never a silent pass.
pub fn check(constitution: &Constitution, manifest_path: &Path) -> Outcome {
    match cargo_metadata(manifest_path) {
        Ok(metadata) => evaluate(constitution, &metadata),
        Err(err) => Outcome::ConstitutionError(unreadable_workspace_error(manifest_path, &err)),
    }
}

/// Evaluate the constitution's boundaries against already-observed `cargo metadata` —
/// the compare -> react half of the spine, with the metadata read (the one IO step)
/// left to the caller so a single read can feed both evaluation and coverage (see
/// [`check_and_cover`]). An unresolvable target or a scan error is a constitution
/// error, never a silent pass.
///
/// Deduplicates violations by structured identity; when duplicates differ in severity,
/// `Enforce` dominates `Warn`. A clean verdict states a [`Subject`] of declared boundaries
/// and reached workspace members.
fn evaluate(constitution: &Constitution, metadata: &Value) -> Outcome {
    evaluate_with_scans(constitution, metadata, &EvaluationScans::shared())
}

/// The whole of [`evaluate`] against caller-held scans. Evaluation itself always builds the shared
/// form — one scan per compiled root, shared by every module boundary judged over it; a direction
/// holds the scans itself to read the work they did, or to run the independent form the shared one
/// is held equal to.
fn evaluate_with_scans(
    constitution: &Constitution,
    metadata: &Value,
    scans: &EvaluationScans,
) -> Outcome {
    let workspace = match workspace_member_names(metadata) {
        Members::Read(names) => names,
        Members::Unreadable(why) => return Outcome::ConstitutionError(why),
    };
    let mut violations = Vec::new();
    for boundary in constitution.boundaries() {
        match boundary {
            Boundary::Crate(crate_boundary) => {
                if let Err(error) =
                    check_crate_boundary(metadata, &workspace, crate_boundary, &mut violations)
                {
                    return Outcome::ConstitutionError(error);
                }
            }
            Boundary::Module(module_boundary) => {
                if let Err(error) =
                    check_module_boundary(metadata, scans, module_boundary, &mut violations)
                {
                    return Outcome::ConstitutionError(error);
                }
            }
        }
    }

    let mut deduped: Vec<Violation> = Vec::new();
    for violation in std::mem::take(&mut violations) {
        match deduped.iter_mut().find(|kept| kept.id() == violation.id()) {
            Some(kept) => {
                if kept.severity == Severity::Warn && violation.severity == Severity::Enforce {
                    *kept = violation;
                }
            }
            None => deduped.push(violation),
        }
    }
    violations = deduped;

    if violations.is_empty() {
        match Subject::of(constitution.boundaries().len(), workspace.len()) {
            Some(subject) => Outcome::Clean(subject),
            None => Outcome::ConstitutionError(format!(
                "{} static boundary/boundaries are declared and this workspace has no member to observe \
                 them over, so nothing was judged — which is not a clean workspace",
                constitution.boundaries().len()
            )),
        }
    } else {
        Outcome::Violations(Report::new(violations))
    }
}

/// Read the target workspace once and return both the reaction outcome and workspace
/// coverage. Coverage is `Some` whenever the membership was read — including when the
/// outcome is a constitution error from a later boundary; the caller decides whether to
/// surface it. It is `None` for either of the two facts that make a membership unavailable:
/// the `cargo metadata` read itself failed, or the metadata was read and its workspace
/// membership could not be decoded from it. Both are reported as a constitution error in the
/// outcome, so `None` never travels alone. One `cargo metadata` spawn feeds both, where
/// `check` plus a separate coverage pass would have spawned twice.
pub fn check_and_cover(
    constitution: &Constitution,
    manifest_path: &Path,
) -> (Outcome, Option<Coverage>) {
    let metadata = match cargo_metadata(manifest_path) {
        Ok(metadata) => metadata,
        Err(err) => {
            return (
                Outcome::ConstitutionError(unreadable_workspace_error(manifest_path, &err)),
                None,
            );
        }
    };
    (
        evaluate(constitution, &metadata),
        coverage_of(&metadata, constitution),
    )
}

/// The workspace coverage the metadata supports, or `None` where it supports none.
///
/// **Named so that the two consumers of [`Members`] cannot reinterpret it apart.** Coverage over a
/// membership that could not be read is coverage over nothing: `total = 0` with an empty uncovered list
/// renders as complete. [`evaluate`] reports the same fact as a constitution error, so the advisory is
/// withheld rather than fabricated — and the two arms saying so live in one function each, reachable by a
/// direction, rather than inline in a function whose only entry point spawns `cargo metadata` and so cannot
/// be handed a membership to fail on.
fn coverage_of(metadata: &Value, constitution: &Constitution) -> Option<Coverage> {
    match workspace_member_names(metadata) {
        Members::Read(names) => Some(coverage_from(names, constitution)),
        Members::Unreadable(_) => None,
    }
}

/// Resolve every workspace member's source-root directory from the target workspace at
/// `manifest_path`, so a caller (the 天衡 shell, composing the 漏刻 runtime CI audit) can
/// hand resolved `&Path`s to a dimension that must stay std-only and never read `cargo
/// metadata` itself. Each root is the parent of the member's `lib` (else `proc-macro`, else `bin`)
/// target `src_path` — this preserves custom target layouts that a `manifest_dir/src` shortcut
/// would silently miss. An unreadable workspace is a constitution error, never a silent empty set.
pub fn workspace_member_src_dirs(manifest_path: &Path) -> Result<Vec<PathBuf>, String> {
    match cargo_metadata(manifest_path) {
        Ok(metadata) => Ok(member_src_dirs(&metadata)),
        Err(err) => Err(unreadable_workspace_error(manifest_path, &err)),
    }
}

#[cfg(test)]
mod tests;