use sha2::{Digest, Sha256};
pub const REPORT_KIND: &str = "agentLaborAuditReport";
fn sha256_hex(bytes: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(bytes);
let digest = hasher.finalize();
let mut hex = String::with_capacity(64);
for b in digest {
use std::fmt::Write as _;
let _ = write!(hex, "{b:02x}");
}
hex
}
pub struct CapsuleNode {
pub name: String,
pub path: std::path::PathBuf,
pub value: serde_json::Value,
pub file_sha256: String,
}
pub fn collect(dir: &str) -> Result<Vec<CapsuleNode>, String> {
let mut out = Vec::new();
let entries =
std::fs::read_dir(dir).map_err(|e| format!("폴더를 읽을 수 없습니다 - {dir}: {e}"))?;
for entry in entries {
let entry = entry.map_err(|e| format!("폴더 항목 오류: {e}"))?;
let path = entry.path();
let name = path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.into_owned();
if !name.ends_with(".capsule.json") {
continue;
}
let bytes =
std::fs::read(&path).map_err(|e| format!("캡슐을 읽을 수 없습니다 - {name}: {e}"))?;
let value: serde_json::Value =
serde_json::from_slice(&bytes).map_err(|e| format!("{name}: 파싱 실패 - {e}"))?;
out.push(CapsuleNode {
file_sha256: sha256_hex(&bytes),
name,
path,
value,
});
}
out.sort_by(|a, b| a.name.cmp(&b.name));
Ok(out)
}
pub fn resolve_parent(capsule_path: &std::path::Path, parent: &str) -> std::path::PathBuf {
let pp = std::path::PathBuf::from(parent);
if pp.is_absolute() {
pp
} else {
capsule_path
.parent()
.unwrap_or(std::path::Path::new("."))
.join(pp)
}
}
pub struct Ancestry {
pub ancestors: Vec<(String, String)>,
pub broken_at: Option<String>,
}
pub fn walk_ancestry(node_path: &std::path::Path, node_value: &serde_json::Value) -> Ancestry {
let mut ancestors = Vec::new();
let mut current_path = node_path.to_path_buf();
let mut current = node_value.clone();
for _ in 0..1000 {
let parent = current["parent"].clone();
if parent.is_null() {
return Ancestry {
ancestors,
broken_at: None,
};
}
let (Some(pp), Some(psha)) = (parent["capsule"].as_str(), parent["sha256"].as_str()) else {
return Ancestry {
ancestors,
broken_at: Some(format!(
"{}: parent 형식 오류",
current_path
.file_name()
.unwrap_or_default()
.to_string_lossy()
)),
};
};
let parent_path = resolve_parent(¤t_path, pp);
let parent_name = parent_path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.into_owned();
let Ok(bytes) = std::fs::read(&parent_path) else {
return Ancestry {
ancestors,
broken_at: Some(format!("{parent_name}: 부모 파일 없음")),
};
};
let actual = sha256_hex(&bytes);
if actual != psha {
return Ancestry {
ancestors,
broken_at: Some(format!("{parent_name}: 부모 해시 불일치")),
};
}
let Ok(parent_value) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
return Ancestry {
ancestors,
broken_at: Some(format!("{parent_name}: 부모 파싱 실패")),
};
};
let parent_out = parent_value["receipt"]["outputSha256"]
.as_str()
.unwrap_or("");
let child_in = current["receipt"]["inputSha256"].as_str().unwrap_or("");
if !parent_out.is_empty() && !child_in.is_empty() && parent_out != child_in {
return Ancestry {
ancestors,
broken_at: Some(format!("{parent_name}: 계보 불변식 위반(산출≠입력)")),
};
}
ancestors.push((parent_name, actual));
current_path = parent_path;
current = parent_value;
}
Ancestry {
ancestors,
broken_at: Some("체인 길이 1000 초과 — 순환 의심".to_string()),
}
}
pub fn heads_and_roots(nodes: &[CapsuleNode]) -> (Vec<usize>, usize) {
let mut referenced: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
for node in nodes {
let parent = &node.value["parent"];
if let Some(psha) = parent["sha256"].as_str() {
referenced.insert(psha.to_string());
}
}
let heads: Vec<usize> = nodes
.iter()
.enumerate()
.filter(|(_, n)| !referenced.contains(&n.file_sha256))
.map(|(i, _)| i)
.collect();
let roots = nodes.iter().filter(|n| n.value["parent"].is_null()).count();
(heads, roots)
}