brygge-ir 0.10.0

brygge's intermediate representation: the faithfulness-with-provenance model, its canonical content-addressed artifact, and the honesty machinery. The light core that links no source-decoder dependency.
Documentation
//! The honesty machinery: the recoverable fidelity report (RFC 002 D-3/D-6, `HO-4/FS-02`, report v2 per
//! RFC 011 §3).
//!
//! [`summary`] is a **pure function of the [`Ir`]**, so a later reader reproduces the exact end-of-run
//! summary from the artifact alone — the external proof that honesty travels with the import and cannot
//! be lost with a log. The report is **always complete**: there is no flag that drops the derived,
//! dropped, or flagged sections (`HO-5/CF-02`); verbosity affects rendering, never presence.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::rc::Rc;

use crate::model::{AtomId, Content, FlagKind, Ir, LossClass};
use crate::status::EpistemicStatus;

/// The machine-report contract version (RFC 002 D-3), independent of the IR contract and the tool.
/// Bumped to 2 by RFC 011 (`refused` replaced with `flagged`), and to 3 by the machine-output cleanup:
/// keys that embed a label are `snake_case`, and `skipped_non_critical_fields` is always printed.
pub const REPORT_VERSION: u32 = 3;

/// The submodule sentence's own machine-key version (RFC 021 D-4, batch G), independent of
/// `REPORT_VERSION`: shown by both `decode` and `inspect`, since both render one [`FidelityReport`].
pub const SUBMODULES_REPORT_VERSION: u32 = 1;

/// The `dropped` label for [`LossClass::Representation`] (matches [`class_label`]), used by
/// [`FidelityReport::render_human`] to split the representation-class count onto its own "not history"
/// line (handoff `cli-and-verify-handoff-v2.md` §3.4).
const REPRESENTATION_LABEL: &str = "representation";

/// What an import preserved, derived, dropped, and flagged. Grouped counts are in sorted-key order for
/// deterministic rendering.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FidelityReport {
    /// The machine-report contract version.
    pub report_version: u32,
    /// Number of atoms.
    pub atoms: u64,
    /// Number of refs.
    pub refs: u64,
    /// Number of distinct blobs.
    pub blobs: u64,
    /// Total content bytes.
    pub content_bytes: u64,
    /// Derived assertions, grouped by taxonomy-kind label → count (RFC 002 D-1).
    pub derived: BTreeMap<String, u64>,
    /// Dropped data, grouped by loss-class label → count (RFC 002 D-2).
    pub dropped: BTreeMap<String, u64>,
    /// Flagged conditions, grouped by flag-kind label → summed count (RFC 011 D-8).
    pub flagged: BTreeMap<String, u64>,
    /// How many fields from a newer contract minor the reader skipped while decoding the artifact
    /// (always non-critical, so none can change what it claims). This describes the *reading*, not the
    /// [`Ir`], so [`summary`] leaves it at `0`; a reader that decoded an artifact sets it with
    /// [`FidelityReport::with_skipped_non_critical_fields`].
    pub skipped_non_critical_fields: u64,
    /// Atoms a transform marked `Transformed`, grouped by step → count (RFC 018 D-5); empty for an
    /// import with no transform chain.
    pub transformed_atoms: BTreeMap<u64, u64>,
    /// Refs a transform marked `Transformed`, grouped by step → count.
    pub transformed_refs: BTreeMap<u64, u64>,
    /// `Transform`-class drops, grouped by step → count.
    pub transformed_drops: BTreeMap<u64, u64>,
    /// Distinct paths that ever held a submodule anywhere in the history (RFC 021 D-4's `P`).
    pub submodule_paths: u64,
    /// Distinct paths holding a submodule at any ref's own target (RFC 021 D-4's `T`).
    pub submodule_at_tips: u64,
}

/// Walk a status's own `Transformed`/`prior` chain, incrementing `counts[step]` once for every
/// `Transformed` layer found (iteratively, not recursively — RFC 018 D-5: a chain nests no deeper than
/// 64, already bounded at decode time, but this walk makes no assumption of its own about that bound).
fn count_transformed_layers(status: &EpistemicStatus, counts: &mut BTreeMap<u64, u64>) {
    let mut current = status;
    while let EpistemicStatus::Transformed { step, prior, .. } = current {
        *counts.entry(*step).or_insert(0) += 1;
        current = prior;
    }
}

/// Compute the fidelity report from an [`Ir`] (pure — `FS-02`).
#[must_use]
pub fn summary(ir: &Ir) -> FidelityReport {
    let mut derived: BTreeMap<String, u64> = BTreeMap::new();
    let note = |s: &EpistemicStatus, d: &mut BTreeMap<String, u64>| {
        if let EpistemicStatus::Derived(der) = s {
            *d.entry(der.kind.label().to_string()).or_insert(0) += 1;
        }
    };
    let mut transformed_atoms: BTreeMap<u64, u64> = BTreeMap::new();
    let mut transformed_refs: BTreeMap<u64, u64> = BTreeMap::new();
    for atom in &ir.atoms {
        note(&atom.status, &mut derived);
        count_transformed_layers(&atom.status, &mut transformed_atoms);
        for op in &atom.ops {
            note(op.status(), &mut derived);
        }
        for copy in &atom.copies {
            note(&copy.status, &mut derived);
        }
    }
    for rf in &ir.refs {
        note(&rf.status, &mut derived);
        count_transformed_layers(&rf.status, &mut transformed_refs);
    }

    let mut dropped: BTreeMap<String, u64> = BTreeMap::new();
    let mut transformed_drops: BTreeMap<u64, u64> = BTreeMap::new();
    for drop in &ir.loss.dropped {
        *dropped
            .entry(class_label(drop.class).to_string())
            .or_insert(0) += 1;
        if let Some(step) = drop.step {
            *transformed_drops.entry(step).or_insert(0) += 1;
        }
    }

    let mut flagged: BTreeMap<String, u64> = BTreeMap::new();
    for flag in &ir.flags {
        *flagged
            .entry(flag_label(flag.kind).to_string())
            .or_insert(0) += flag.count;
    }

    let mut submodule_paths_ever: BTreeSet<&str> = BTreeSet::new();
    for atom in &ir.atoms {
        for op in &atom.ops {
            if matches!(op.content(), Some(Content::Submodule { .. })) {
                submodule_paths_ever.insert(op.path());
            }
        }
    }

    FidelityReport {
        report_version: REPORT_VERSION,
        atoms: ir.atoms.len() as u64,
        refs: ir.refs.len() as u64,
        blobs: ir.content.len() as u64,
        content_bytes: ir.content.total_bytes(),
        derived,
        dropped,
        flagged,
        skipped_non_critical_fields: 0,
        transformed_atoms,
        transformed_refs,
        transformed_drops,
        submodule_paths: submodule_paths_ever.len() as u64,
        submodule_at_tips: submodules_at_tips(ir).len() as u64,
    }
}

/// Every path holding a submodule at any ref's own target commit (RFC 021 D-4's `T`): each atom's own
/// submodule-path set is built incrementally from its first parent's set (mirroring
/// `encode_git::check`'s tree-state walk, but tracking only submodule paths, since that is all `T`
/// needs), assuming atoms are already in canonical, parents-before-children order — the same assumption
/// `encode_git::write_stream` already makes. An atom's retained set is dropped once no later atom still
/// needs it as a first-parent basis, so this never holds the whole history's states at once.
fn submodules_at_tips(ir: &Ir) -> BTreeSet<String> {
    let mut remaining: HashMap<AtomId, u32> = HashMap::new();
    for atom in &ir.atoms {
        if let Some(first) = atom.parents.first() {
            *remaining.entry(*first).or_insert(0) += 1;
        }
    }
    let targets: HashSet<AtomId> = ir.refs.iter().map(|rf| rf.target).collect();

    let mut state_of: HashMap<AtomId, Rc<BTreeSet<String>>> = HashMap::new();
    let mut tips: BTreeSet<String> = BTreeSet::new();
    for atom in &ir.atoms {
        let mut set: BTreeSet<String> = match atom.parents.first() {
            Some(p) => state_of.get(p).map(|rc| (**rc).clone()).unwrap_or_default(),
            None => BTreeSet::new(),
        };
        for op in &atom.ops {
            match op.content() {
                Some(Content::Submodule { .. }) => {
                    set.insert(op.path().to_string());
                }
                Some(Content::Blob { .. }) | None => {
                    set.remove(op.path());
                }
            }
        }
        if targets.contains(&atom.id) {
            tips.extend(set.iter().cloned());
        }
        if let Some(first) = atom.parents.first() {
            if let Some(c) = remaining.get_mut(first) {
                *c = c.saturating_sub(1);
                if *c == 0 {
                    state_of.remove(first);
                }
            }
        }
        if remaining.get(&atom.id).copied().unwrap_or(0) > 0 {
            state_of.insert(atom.id, Rc::new(set));
        }
    }
    tips
}

/// A label as a machine-output key segment: keys are `snake_case`, values (labels) stay `kebab-case`.
fn key_segment(label: &str) -> String {
    label.replace('-', "_")
}

impl FidelityReport {
    /// Record how many non-critical fields the reader skipped while decoding the artifact this report
    /// describes. [`summary`] stays a pure function of the [`Ir`]; this is the one reading-time fact that is
    /// not in it.
    #[must_use]
    pub fn with_skipped_non_critical_fields(mut self, skipped: u64) -> Self {
        self.skipped_non_critical_fields = skipped;
        self
    }

    /// A stable, deterministic machine rendering (versioned — a CI gate can pin it, `CL-07/CT-04`). Keys
    /// are dot-separated `snake_case` segments; a label embedded in a key (`derived.inferred_rename`) is
    /// written in `snake_case` too, while values stay `kebab-case`.
    #[must_use]
    pub fn render_machine(&self) -> String {
        use std::fmt::Write as _;
        let mut s = String::new();
        let _ = writeln!(s, "report_version={}", self.report_version);
        let _ = writeln!(s, "atoms={}", self.atoms);
        let _ = writeln!(s, "refs={}", self.refs);
        let _ = writeln!(s, "blobs={}", self.blobs);
        let _ = writeln!(s, "content_bytes={}", self.content_bytes);
        let _ = writeln!(
            s,
            "skipped_non_critical_fields={}",
            self.skipped_non_critical_fields
        );
        for (kind, n) in &self.derived {
            let _ = writeln!(s, "derived.{}={n}", key_segment(kind));
        }
        for (class, n) in &self.dropped {
            let _ = writeln!(s, "dropped.{}={n}", key_segment(class));
        }
        for (kind, n) in &self.flagged {
            let _ = writeln!(s, "flagged.{}={n}", key_segment(kind));
        }
        // Shown only when the import has a transform chain (RFC 018 D-5) — a decoder's own report,
        // with no chain, is byte-identical to before this field existed.
        for (step, n) in &self.transformed_atoms {
            let _ = writeln!(s, "transformed_atoms.{step}={n}");
        }
        for (step, n) in &self.transformed_refs {
            let _ = writeln!(s, "transformed_refs.{step}={n}");
        }
        for (step, n) in &self.transformed_drops {
            let _ = writeln!(s, "transformed_drops.{step}={n}");
        }
        // RFC 021 D-4 (batch G): absent entirely when the history never held a submodule, so a decode
        // or inspect of an ordinary repository's report is byte-for-byte unchanged by this RFC.
        if self.submodule_paths > 0 {
            let _ = writeln!(s, "decode_submodules_version={SUBMODULES_REPORT_VERSION}");
            let _ = writeln!(s, "decode.submodules.paths={}", self.submodule_paths);
            let _ = writeln!(s, "decode.submodules.at_tips={}", self.submodule_at_tips);
        }
        s
    }

    /// A human-facing rendering. Authorship is always shown `Unverifiable` (`VF-4/HO-3`), and the report
    /// makes the stated-vs-derived distinction plain — a newcomer should be able to tell what the source
    /// recorded from what brygge judged, and see that nothing was silently lost (`HO-4`, SRC-C2). The
    /// dropped section is split (handoff `cli-and-verify-handoff-v2.md` §3.4) so a newcomer is not alarmed
    /// by ordinary storage-layout drops: representation-class drops (nothing lost — packfiles, working
    /// copy, reflogs and the like) are one line; everything else is genuine recorded loss.
    #[must_use]
    pub fn render_human(&self) -> String {
        use std::fmt::Write as _;
        let mut s = String::new();
        let _ = writeln!(
            s,
            "fidelity report (v{}) — what brygge imported, and how much is the source's own record",
            self.report_version
        );
        let _ = writeln!(
            s,
            "vs brygge's judgment. Authorship is Unverifiable (carried as the source claimed it; no \
             target can verify it)."
        );
        let _ = writeln!(s);
        let _ = writeln!(
            s,
            "  preserved: {} atom(s), {} ref(s), {} blob(s), {} content byte(s)",
            self.atoms, self.refs, self.blobs, self.content_bytes
        );
        if self.derived.is_empty() {
            let _ = writeln!(
                s,
                "  derived:   none — every assertion is source-stated (the source recorded it; \
                 brygge inferred nothing)"
            );
        } else {
            let _ = writeln!(
                s,
                "  derived:   brygge's judgment, not the source's fact — a later brygge version could \
                 differ; `inspect --atoms` shows where each is marked:"
            );
            for (kind, n) in &self.derived {
                let _ = writeln!(s, "    {kind}: {n}");
            }
        }
        let representation_n = self.dropped.get(REPRESENTATION_LABEL).copied().unwrap_or(0);
        let _ = writeln!(
            s,
            "  not history (no content or claim lost): {representation_n}"
        );
        let recorded_loss: Vec<(&String, &u64)> = self
            .dropped
            .iter()
            .filter(|(class, _)| class.as_str() != REPRESENTATION_LABEL)
            .collect();
        if recorded_loss.is_empty() {
            let _ = writeln!(s, "  dropped (recorded loss): nothing");
        } else {
            let _ = writeln!(s, "  dropped (recorded loss):");
            for (class, n) in recorded_loss {
                let _ = writeln!(s, "    {class}: {n}");
            }
        }
        if !self.flagged.is_empty() {
            let _ = writeln!(
                s,
                "  flagged:   recorded, and why this import needs your attention:"
            );
            for (kind, n) in &self.flagged {
                let _ = writeln!(s, "    {kind}: {n}");
            }
        }
        // Shown only when the import has a transform chain (RFC 018 D-5) — a decoder's own report,
        // with no chain, is byte-identical to before this section existed.
        if !self.transformed_atoms.is_empty()
            || !self.transformed_refs.is_empty()
            || !self.transformed_drops.is_empty()
        {
            let _ = writeln!(
                s,
                "  transformed, per step (see `inspect` for each step's own name/version):"
            );
            for (step, n) in &self.transformed_atoms {
                let _ = writeln!(s, "    step {step}: {n} atom(s)");
            }
            for (step, n) in &self.transformed_refs {
                let _ = writeln!(s, "    step {step}: {n} ref(s)");
            }
            for (step, n) in &self.transformed_drops {
                let _ = writeln!(s, "    step {step}: {n} drop(s)");
            }
        }
        // RFC 021 D-4 (batch G): condition A — wherever a submodule appears, say plainly what brygge
        // did not do. Absent entirely when the history never held one.
        if self.submodule_paths > 0 {
            let _ = writeln!(
                s,
                "submodules: {} path(s) in the history, {} at the branch and tag tips; their own \
                 repositories were not read, imported or verified",
                self.submodule_paths, self.submodule_at_tips
            );
        }
        s
    }
}

fn class_label(class: LossClass) -> &'static str {
    match class {
        LossClass::Representation => "representation",
        LossClass::AdvisoryUnreliable => "advisory-unreliable",
        LossClass::Other => "other",
        LossClass::Transform => "transform",
    }
}

fn flag_label(kind: FlagKind) -> &'static str {
    match kind {
        FlagKind::ConventionViolation => "convention-violation",
        FlagKind::BelowConfidenceFloor => "below-confidence-floor",
    }
}

#[cfg(test)]
mod tests;