Skip to main content

fetchium_core/citation/
evidence_graph.rs

1//! Evidence Graph Protocol (EGP) — graph-based claim provenance (PRD §8.7, §24).
2
3use chrono::Utc;
4use serde::{Deserialize, Serialize};
5use sha2::{Digest, Sha256};
6use std::collections::HashMap;
7
8/// The complete evidence graph for a research query.
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct EvidenceGraph {
11    pub nodes: Vec<EvidenceNode>,
12    pub edges: Vec<EvidenceEdge>,
13    pub root_claim: String,
14    pub overall_confidence: f64,
15    pub content_hashes: HashMap<String, String>,
16}
17
18/// A node in the evidence graph.
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct EvidenceNode {
21    pub id: String,
22    #[serde(rename = "type")]
23    pub node_type: NodeType,
24    pub content: String,
25    pub confidence: f64,
26    pub timestamp: String,
27    pub source_url: Option<String>,
28}
29
30/// Node type in the evidence graph.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(rename_all = "lowercase")]
33pub enum NodeType {
34    Claim,
35    Source,
36    Fact,
37    Inference,
38}
39
40/// An edge linking nodes in the evidence graph.
41#[derive(Debug, Clone, Serialize, Deserialize)]
42pub struct EvidenceEdge {
43    pub from: String,
44    pub to: String,
45    #[serde(rename = "type")]
46    pub edge_type: EdgeType,
47    pub quote: String,
48    pub quote_hash: String,
49}
50
51/// Type of evidence relationship.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(rename_all = "snake_case")]
54pub enum EdgeType {
55    Supports,
56    Contradicts,
57    PartiallySupports,
58    InferredFrom,
59}
60
61/// Incrementally builds an evidence graph.
62pub struct EvidenceGraphBuilder {
63    nodes: Vec<EvidenceNode>,
64    edges: Vec<EvidenceEdge>,
65    content_hashes: HashMap<String, String>,
66    root_claim: String,
67    node_counter: usize,
68}
69
70impl EvidenceGraphBuilder {
71    pub fn new(root_claim: &str) -> Self {
72        let mut builder = Self {
73            nodes: Vec::new(),
74            edges: Vec::new(),
75            content_hashes: HashMap::new(),
76            root_claim: root_claim.to_string(),
77            node_counter: 0,
78        };
79        // n1 is always the root claim node
80        builder.add_node(NodeType::Claim, root_claim, 0.0, None);
81        builder
82    }
83
84    /// Add a node and return its ID.
85    pub fn add_node(
86        &mut self,
87        node_type: NodeType,
88        content: &str,
89        confidence: f64,
90        source_url: Option<&str>,
91    ) -> String {
92        self.node_counter += 1;
93        let id = format!("n{}", self.node_counter);
94        self.nodes.push(EvidenceNode {
95            id: id.clone(),
96            node_type,
97            content: content.to_string(),
98            confidence,
99            timestamp: Utc::now().to_rfc3339(),
100            source_url: source_url.map(|s| s.to_string()),
101        });
102        id
103    }
104
105    /// Add a source node and register its content hash.
106    pub fn add_source(&mut self, url: &str, title: &str, content: &str, confidence: f64) -> String {
107        let hash = Self::sha256_hex(content);
108        self.content_hashes.insert(url.to_string(), hash);
109        self.add_node(NodeType::Source, title, confidence, Some(url))
110    }
111
112    /// Add an evidence edge with a supporting quote.
113    pub fn add_edge(&mut self, from: &str, to: &str, edge_type: EdgeType, quote: &str) {
114        let quote_hash = Self::sha256_hex(quote);
115        self.edges.push(EvidenceEdge {
116            from: from.to_string(),
117            to: to.to_string(),
118            edge_type,
119            quote: quote.to_string(),
120            quote_hash,
121        });
122    }
123
124    /// Add a fact extracted from a source and link it to that source.
125    pub fn add_fact_from_source(
126        &mut self,
127        source_id: &str,
128        fact_text: &str,
129        supporting_quote: &str,
130        confidence: f64,
131    ) -> String {
132        let fact_id = self.add_node(NodeType::Fact, fact_text, confidence, None);
133        self.add_edge(source_id, &fact_id, EdgeType::Supports, supporting_quote);
134        fact_id
135    }
136
137    /// Link a fact to the root claim (n1).
138    pub fn link_to_root(&mut self, fact_id: &str, edge_type: EdgeType, quote: &str) {
139        self.add_edge(fact_id, "n1", edge_type, quote);
140    }
141
142    /// Build the final evidence graph with computed overall confidence.
143    pub fn build(self) -> EvidenceGraph {
144        let confidence = Self::compute_overall_confidence(&self.edges);
145        EvidenceGraph {
146            nodes: self.nodes,
147            edges: self.edges,
148            root_claim: self.root_claim,
149            overall_confidence: confidence,
150            content_hashes: self.content_hashes,
151        }
152    }
153
154    fn compute_overall_confidence(edges: &[EvidenceEdge]) -> f64 {
155        let support_count = edges
156            .iter()
157            .filter(|e| e.edge_type == EdgeType::Supports)
158            .count();
159        let contradict_count = edges
160            .iter()
161            .filter(|e| e.edge_type == EdgeType::Contradicts)
162            .count();
163        let total = (support_count + contradict_count).max(1);
164        support_count as f64 / total as f64
165    }
166
167    fn sha256_hex(input: &str) -> String {
168        let mut h = Sha256::new();
169        h.update(input.as_bytes());
170        h.finalize().iter().map(|b| format!("{b:02x}")).collect()
171    }
172}
173
174impl EvidenceGraph {
175    /// Verify that a quote's hash matches the stored hash.
176    pub fn verify_quote(&self, edge_index: usize) -> bool {
177        if let Some(edge) = self.edges.get(edge_index) {
178            let computed = {
179                let mut h = Sha256::new();
180                h.update(edge.quote.as_bytes());
181                h.finalize()
182                    .iter()
183                    .map(|b| format!("{b:02x}"))
184                    .collect::<String>()
185            };
186            computed == edge.quote_hash
187        } else {
188            false
189        }
190    }
191
192    /// Verify a source's content hash against freshly fetched content.
193    pub fn verify_source(&self, url: &str, current_content: &str) -> bool {
194        if let Some(stored_hash) = self.content_hashes.get(url) {
195            let mut h = Sha256::new();
196            h.update(current_content.as_bytes());
197            let current: String = h.finalize().iter().map(|b| format!("{b:02x}")).collect();
198            &current == stored_hash
199        } else {
200            false
201        }
202    }
203
204    /// Return all source->fact->claim paths to the root (n1).
205    pub fn trace_root_evidence(&self) -> Vec<Vec<String>> {
206        let mut paths = Vec::new();
207        for edge in &self.edges {
208            if edge.to == "n1" {
209                let mut path = vec![edge.from.clone(), "n1".to_string()];
210                for inner_edge in &self.edges {
211                    if inner_edge.to == edge.from {
212                        path.insert(0, inner_edge.from.clone());
213                    }
214                }
215                paths.push(path);
216            }
217        }
218        paths
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    #[test]
227    fn build_and_verify_graph() {
228        let mut b = EvidenceGraphBuilder::new("Rust is memory-safe");
229        let s1 = b.add_source(
230            "https://rust-lang.org",
231            "Rust Lang",
232            "Rust guarantees memory safety without GC",
233            0.95,
234        );
235        let f1 = b.add_fact_from_source(
236            &s1,
237            "Rust uses ownership for memory safety",
238            "Rust guarantees memory safety without GC",
239            0.9,
240        );
241        b.link_to_root(&f1, EdgeType::Supports, "memory safety without GC");
242        let graph = b.build();
243        assert_eq!(graph.nodes.len(), 3);
244        assert_eq!(graph.edges.len(), 2);
245        assert!(graph.overall_confidence > 0.9);
246        assert!(graph.verify_quote(0));
247        assert!(graph.verify_source(
248            "https://rust-lang.org",
249            "Rust guarantees memory safety without GC"
250        ));
251        assert!(!graph.verify_source("https://rust-lang.org", "tampered content"));
252    }
253
254    #[test]
255    fn trace_evidence_chain() {
256        let mut b = EvidenceGraphBuilder::new("claim");
257        let s = b.add_source("https://a.com", "A", "content", 0.8);
258        let f = b.add_fact_from_source(&s, "fact", "content", 0.8);
259        b.link_to_root(&f, EdgeType::Supports, "evidence");
260        let graph = b.build();
261        let paths = graph.trace_root_evidence();
262        assert_eq!(paths.len(), 1);
263        assert_eq!(paths[0].len(), 3);
264    }
265
266    #[test]
267    fn serialization_roundtrip() {
268        let mut b = EvidenceGraphBuilder::new("test claim");
269        b.add_source("https://x.com", "X", "data", 0.7);
270        let graph = b.build();
271        let json = serde_json::to_string(&graph).unwrap();
272        let parsed: EvidenceGraph = serde_json::from_str(&json).unwrap();
273        assert_eq!(parsed.root_claim, "test claim");
274    }
275}