use crate::intelligence::string_similarity;
#[derive(Debug, Clone, serde::Serialize)]
pub struct GenealogyNode {
pub url: String,
pub title: String,
pub claim_text: String,
pub trust_score: f64,
pub depth: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MutationSeverity {
Low,
Medium,
High,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct Mutation {
pub from_depth: usize,
pub to_depth: usize,
pub original_claim: String,
pub mutated_claim: String,
pub similarity: f64,
pub severity: MutationSeverity,
pub description: String,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct CitationChain {
pub nodes: Vec<GenealogyNode>,
pub mutations: Vec<Mutation>,
pub trust_cascade: Vec<f64>,
pub primary_source: Option<GenealogyNode>,
}
pub fn build_chain(hops: Vec<(String, String, String)>) -> CitationChain {
let nodes: Vec<GenealogyNode> = hops
.into_iter()
.enumerate()
.map(|(depth, (url, title, claim_text))| GenealogyNode {
url,
title,
claim_text,
trust_score: (1.0 - depth as f64 * 0.15).clamp(0.1, 1.0),
depth,
})
.collect();
let mutations = detect_mutations(&nodes);
let trust_cascade: Vec<f64> = nodes.iter().map(|n| n.trust_score).collect();
let primary_source = nodes.last().cloned();
CitationChain {
nodes,
mutations,
trust_cascade,
primary_source,
}
}
pub fn detect_mutations(nodes: &[GenealogyNode]) -> Vec<Mutation> {
let mut mutations = Vec::new();
for i in 0..nodes.len().saturating_sub(1) {
let from = &nodes[i];
let to = &nodes[i + 1];
let similarity = string_similarity(
&from.claim_text.to_lowercase(),
&to.claim_text.to_lowercase(),
);
if similarity < 0.95 {
let severity = if similarity < 0.5 {
MutationSeverity::High
} else if similarity < 0.8 {
MutationSeverity::Medium
} else {
MutationSeverity::Low
};
let description = describe_mutation(similarity, &severity);
mutations.push(Mutation {
from_depth: from.depth,
to_depth: to.depth,
original_claim: from.claim_text.clone(),
mutated_claim: to.claim_text.clone(),
similarity,
severity,
description,
});
}
}
mutations
}
fn describe_mutation(similarity: f64, severity: &MutationSeverity) -> String {
match severity {
MutationSeverity::Low => format!(
"Minor phrasing change ({:.0}% similar) — meaning likely preserved.",
similarity * 100.0
),
MutationSeverity::Medium => format!(
"Significant rewording ({:.0}% similar) — verify meaning is unchanged.",
similarity * 100.0
),
MutationSeverity::High => format!(
"Claim substantially altered ({:.0}% similar) — original meaning may be lost.",
similarity * 100.0
),
}
}
impl CitationChain {
pub fn to_markdown(&self) -> String {
let mut out = String::new();
out.push_str("## Citation Chain\n\n");
for node in &self.nodes {
out.push_str(&format!(
"{}. **{}** (trust: {:.0}%)\n - URL: {}\n - Claim: \"{}\"\n\n",
node.depth + 1,
node.title,
node.trust_score * 100.0,
node.url,
node.claim_text,
));
}
if !self.mutations.is_empty() {
out.push_str("### Mutations Detected\n\n");
for m in &self.mutations {
out.push_str(&format!(
"- **{:?}** mutation (depth {} → {}): {}\n",
m.severity, m.from_depth, m.to_depth, m.description
));
}
}
if let Some(primary) = &self.primary_source {
out.push_str(&format!(
"\n**Primary Source**: {} ({})\n",
primary.title, primary.url
));
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn make_chain(hops: &[(&str, &str, &str)]) -> CitationChain {
build_chain(
hops.iter()
.map(|(u, t, c)| (u.to_string(), t.to_string(), c.to_string()))
.collect(),
)
}
#[test]
fn trust_degrades_per_hop() {
let chain = make_chain(&[
("https://original.com", "Original", "Rust is memory safe"),
("https://blog.com", "Blog", "Rust is memory safe"),
("https://tweet.com", "Tweet", "Rust is memory safe"),
]);
assert!(chain.trust_cascade[0] > chain.trust_cascade[1]);
assert!(chain.trust_cascade[1] > chain.trust_cascade[2]);
}
#[test]
fn identical_claims_have_no_mutations() {
let chain = make_chain(&[
("https://a.com", "A", "Rust is fast"),
("https://b.com", "B", "Rust is fast"),
]);
assert!(chain.mutations.is_empty());
}
#[test]
fn substantially_different_claims_are_high_severity() {
let chain = make_chain(&[
(
"https://a.com",
"A",
"Rust provides memory safety without garbage collection",
),
(
"https://b.com",
"B",
"Python is an interpreted scripting language for data science",
),
]);
let high = chain
.mutations
.iter()
.any(|m| m.severity == MutationSeverity::High);
assert!(high, "expected high-severity mutation");
}
#[test]
fn primary_source_is_last_node() {
let chain = make_chain(&[
("https://origin.com", "Origin", "claim"),
("https://cite.com", "Cite", "claim slightly modified"),
]);
let ps = chain.primary_source.as_ref().unwrap();
assert_eq!(ps.url, "https://cite.com");
}
#[test]
fn markdown_output_not_empty() {
let chain = make_chain(&[
("https://a.com", "A", "test claim"),
("https://b.com", "B", "slightly changed claim"),
]);
let md = chain.to_markdown();
assert!(md.contains("Citation Chain"), "md={md}");
}
}