use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::rc::Rc;
use crate::model::{AtomId, Content, FlagKind, Ir, LossClass};
use crate::status::EpistemicStatus;
pub const REPORT_VERSION: u32 = 3;
pub const SUBMODULES_REPORT_VERSION: u32 = 1;
const REPRESENTATION_LABEL: &str = "representation";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FidelityReport {
pub report_version: u32,
pub atoms: u64,
pub refs: u64,
pub blobs: u64,
pub content_bytes: u64,
pub derived: BTreeMap<String, u64>,
pub dropped: BTreeMap<String, u64>,
pub flagged: BTreeMap<String, u64>,
pub skipped_non_critical_fields: u64,
pub transformed_atoms: BTreeMap<u64, u64>,
pub transformed_refs: BTreeMap<u64, u64>,
pub transformed_drops: BTreeMap<u64, u64>,
pub submodule_paths: u64,
pub submodule_at_tips: u64,
}
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;
}
}
#[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(©.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,
}
}
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
}
fn key_segment(label: &str) -> String {
label.replace('-', "_")
}
impl FidelityReport {
#[must_use]
pub fn with_skipped_non_critical_fields(mut self, skipped: u64) -> Self {
self.skipped_non_critical_fields = skipped;
self
}
#[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));
}
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}");
}
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
}
#[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}");
}
}
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)");
}
}
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;