1use crate::error::FetchiumError;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
18#[serde(rename_all = "snake_case")]
19pub enum Severity {
20 Low,
21 Medium,
22 High,
23 Critical,
24}
25
26#[derive(Debug, Clone)]
28pub struct CrpContradiction {
29 pub claim_a: String,
30 pub source_a_domain: String,
31 pub source_a_trust: f64,
32 pub source_a_date: Option<String>,
34 pub claim_b: String,
35 pub source_b_domain: String,
36 pub source_b_trust: f64,
37 pub source_b_date: Option<String>,
38 pub severity: Severity,
39}
40
41#[derive(Debug, Clone, PartialEq, serde::Serialize)]
43#[serde(rename_all = "snake_case")]
44pub enum ResolutionType {
45 TemporalPrecedence,
47 AuthorityPrecedence,
49 ScopeDependent,
51 InvestigationResolvedIt,
53 Unresolved,
55}
56
57#[derive(Debug, Clone, serde::Serialize)]
59pub struct ResolutionStep {
60 pub name: String,
61 pub conclusion: String,
62 pub confidence: f64,
63 pub conclusive: bool,
64}
65
66#[derive(Debug, Clone, serde::Serialize)]
68pub struct Resolution {
69 pub claim_a: String,
70 pub claim_b: String,
71 pub steps_taken: Vec<ResolutionStep>,
72 pub synthesis: String,
73 pub confidence: f64,
74 pub resolution_type: ResolutionType,
75}
76
77pub fn resolve<F>(
84 contradiction: &CrpContradiction,
85 stm_trust_fn: F,
86) -> Result<Resolution, FetchiumError>
87where
88 F: Fn(&str) -> f64,
89{
90 let mut steps = Vec::new();
91
92 let date_step = step_date_check(contradiction);
94 let conclusive = date_step.conclusive;
95 steps.push(date_step);
96 if conclusive {
97 return Ok(finalize(
98 contradiction,
99 steps,
100 ResolutionType::TemporalPrecedence,
101 ));
102 }
103
104 let auth_step = step_authority_check(contradiction, &stm_trust_fn);
106 let conclusive = auth_step.conclusive;
107 steps.push(auth_step);
108 if conclusive {
109 return Ok(finalize(
110 contradiction,
111 steps,
112 ResolutionType::AuthorityPrecedence,
113 ));
114 }
115
116 let ctx_step = step_context_check(contradiction);
118 let conclusive = ctx_step.conclusive;
119 steps.push(ctx_step);
120 if conclusive {
121 return Ok(finalize(
122 contradiction,
123 steps,
124 ResolutionType::ScopeDependent,
125 ));
126 }
127
128 let inv_step = step_investigation(contradiction);
130 let inv_conclusive = inv_step.conclusive;
131 steps.push(inv_step);
132
133 let synth_step = step_weighted_synthesis(contradiction, &steps);
135 steps.push(synth_step);
136
137 let resolution_type = if inv_conclusive {
138 ResolutionType::InvestigationResolvedIt
139 } else {
140 ResolutionType::Unresolved
141 };
142
143 Ok(finalize(contradiction, steps, resolution_type))
144}
145
146fn finalize(
148 c: &CrpContradiction,
149 steps: Vec<ResolutionStep>,
150 resolution_type: ResolutionType,
151) -> Resolution {
152 let synthesis = steps
153 .last()
154 .map(|s| s.conclusion.clone())
155 .unwrap_or_default();
156 let confidence = if steps.is_empty() {
157 0.5
158 } else {
159 steps.iter().map(|s| s.confidence).sum::<f64>() / steps.len() as f64
160 };
161 Resolution {
162 claim_a: c.claim_a.clone(),
163 claim_b: c.claim_b.clone(),
164 steps_taken: steps,
165 synthesis,
166 confidence,
167 resolution_type,
168 }
169}
170
171fn step_date_check(c: &CrpContradiction) -> ResolutionStep {
174 match (&c.source_a_date, &c.source_b_date) {
175 (Some(da), Some(db)) => {
176 if da == db {
178 return ResolutionStep {
179 name: "Date Check".into(),
180 conclusion: "Sources are from the same date; date alone is inconclusive."
181 .into(),
182 confidence: 0.3,
183 conclusive: false,
184 };
185 }
186 let (newer_domain, newer_claim) = if db > da {
187 (&c.source_b_domain, &c.claim_b)
188 } else {
189 (&c.source_a_domain, &c.claim_a)
190 };
191 ResolutionStep {
192 name: "Date Check".into(),
193 conclusion: format!(
194 "Newer source ({newer_domain}) supersedes older source. \
195 Adopting: \"{newer_claim}\""
196 ),
197 confidence: 0.7,
198 conclusive: true,
199 }
200 }
201 _ => ResolutionStep {
202 name: "Date Check".into(),
203 conclusion: "Publication dates unavailable; cannot determine temporal precedence."
204 .into(),
205 confidence: 0.2,
206 conclusive: false,
207 },
208 }
209}
210
211fn step_authority_check<F>(c: &CrpContradiction, trust_fn: &F) -> ResolutionStep
212where
213 F: Fn(&str) -> f64,
214{
215 let trust_a = c.source_a_trust.max(trust_fn(&c.source_a_domain));
216 let trust_b = c.source_b_trust.max(trust_fn(&c.source_b_domain));
217
218 let diff = (trust_a - trust_b).abs();
219 if diff < 0.2 {
220 return ResolutionStep {
221 name: "Authority Check".into(),
222 conclusion: format!(
223 "Sources have similar trust levels ({:.2} vs {:.2}); authority inconclusive.",
224 trust_a, trust_b
225 ),
226 confidence: 0.3,
227 conclusive: false,
228 };
229 }
230
231 let (winner_domain, winner_claim, winner_trust) = if trust_a > trust_b {
232 (&c.source_a_domain, &c.claim_a, trust_a)
233 } else {
234 (&c.source_b_domain, &c.claim_b, trust_b)
235 };
236
237 ResolutionStep {
238 name: "Authority Check".into(),
239 conclusion: format!(
240 "Higher-trust source ({winner_domain}, trust={winner_trust:.2}) preferred. \
241 Adopting: \"{winner_claim}\""
242 ),
243 confidence: 0.65 + diff * 0.2,
244 conclusive: true,
245 }
246}
247
248fn step_context_check(c: &CrpContradiction) -> ResolutionStep {
249 let shared = shared_word_ratio(&c.claim_a, &c.claim_b);
252 if shared < 0.20 {
253 ResolutionStep {
254 name: "Context Check".into(),
255 conclusion: format!(
256 "Claims share only {:.0}% vocabulary — they may refer to different contexts. \
257 Both claims can coexist without contradiction.",
258 shared * 100.0
259 ),
260 confidence: 0.55,
261 conclusive: true,
262 }
263 } else {
264 ResolutionStep {
265 name: "Context Check".into(),
266 conclusion: format!(
267 "Claims share {:.0}% vocabulary — they appear to discuss the same topic. \
268 The contradiction is genuine.",
269 shared * 100.0
270 ),
271 confidence: 0.35,
272 conclusive: false,
273 }
274 }
275}
276
277fn step_investigation(c: &CrpContradiction) -> ResolutionStep {
278 let severity_hint = match c.severity {
281 Severity::Critical | Severity::High => {
282 "⚠ High-severity contradiction — manual verification strongly recommended."
283 }
284 Severity::Medium => {
285 "Consider running `fetchium research` with both claims to gather more evidence."
286 }
287 Severity::Low => "Low-severity contradiction — likely a minor phrasing difference.",
288 };
289
290 ResolutionStep {
291 name: "Investigation".into(),
292 conclusion: format!(
293 "Suggested additional queries: \"{} evidence\", \"{} evidence\". {severity_hint}",
294 keywords_from_claim(&c.claim_a),
295 keywords_from_claim(&c.claim_b),
296 ),
297 confidence: 0.4,
298 conclusive: false,
299 }
300}
301
302fn step_weighted_synthesis(c: &CrpContradiction, prior_steps: &[ResolutionStep]) -> ResolutionStep {
303 let avg_conf: f64 = if prior_steps.is_empty() {
304 0.5
305 } else {
306 prior_steps.iter().map(|s| s.confidence).sum::<f64>() / prior_steps.len() as f64
307 };
308
309 let synthesis = format!(
310 "Sources disagree: \"{}\" ({}, trust={:.2}) vs \"{}\" ({}, trust={:.2}). \
311 Both perspectives are presented; final determination requires domain expertise. \
312 Overall confidence: {:.0}%.",
313 c.claim_a,
314 c.source_a_domain,
315 c.source_a_trust,
316 c.claim_b,
317 c.source_b_domain,
318 c.source_b_trust,
319 avg_conf * 100.0,
320 );
321
322 ResolutionStep {
323 name: "Weighted Synthesis".into(),
324 conclusion: synthesis,
325 confidence: avg_conf,
326 conclusive: false,
327 }
328}
329
330pub fn shared_word_ratio(a: &str, b: &str) -> f64 {
333 let stop_words: std::collections::HashSet<&str> = [
334 "the", "a", "an", "is", "was", "are", "were", "of", "in", "to", "and", "or",
335 ]
336 .iter()
337 .cloned()
338 .collect();
339
340 let words_a: std::collections::HashSet<String> = a
341 .split_whitespace()
342 .map(|w| {
343 w.to_lowercase()
344 .trim_matches(|c: char| !c.is_alphabetic())
345 .to_string()
346 })
347 .filter(|w| w.len() >= 3 && !stop_words.contains(w.as_str()))
348 .collect();
349
350 let words_b: std::collections::HashSet<String> = b
351 .split_whitespace()
352 .map(|w| {
353 w.to_lowercase()
354 .trim_matches(|c: char| !c.is_alphabetic())
355 .to_string()
356 })
357 .filter(|w| w.len() >= 3 && !stop_words.contains(w.as_str()))
358 .collect();
359
360 if words_a.is_empty() || words_b.is_empty() {
361 return 0.0;
362 }
363
364 let intersection: usize = words_a.intersection(&words_b).count();
365 let union: usize = words_a.union(&words_b).count();
366 intersection as f64 / union.max(1) as f64
367}
368
369fn keywords_from_claim(claim: &str) -> String {
370 claim
371 .split_whitespace()
372 .filter(|w| w.len() >= 4)
373 .take(4)
374 .collect::<Vec<_>>()
375 .join(" ")
376}
377
378#[cfg(test)]
379mod tests {
380 use super::*;
381
382 fn make_contradiction(
383 claim_a: &str,
384 claim_b: &str,
385 date_a: Option<&str>,
386 date_b: Option<&str>,
387 trust_a: f64,
388 trust_b: f64,
389 ) -> CrpContradiction {
390 CrpContradiction {
391 claim_a: claim_a.into(),
392 source_a_domain: "source-a.com".into(),
393 source_a_trust: trust_a,
394 source_a_date: date_a.map(String::from),
395 claim_b: claim_b.into(),
396 source_b_domain: "source-b.com".into(),
397 source_b_trust: trust_b,
398 source_b_date: date_b.map(String::from),
399 severity: Severity::Medium,
400 }
401 }
402
403 #[test]
404 fn newer_date_wins() {
405 let c = make_contradiction(
406 "X is true",
407 "X is false",
408 Some("2023-01-01"),
409 Some("2024-06-01"),
410 0.5,
411 0.5,
412 );
413 let res = resolve(&c, |_| 0.5).unwrap();
414 assert_eq!(res.resolution_type, ResolutionType::TemporalPrecedence);
415 }
416
417 #[test]
418 fn higher_trust_wins() {
419 let c = make_contradiction("Y is true", "Y is false", None, None, 0.9, 0.3);
420 let res = resolve(&c, |_| 0.5).unwrap();
421 assert_eq!(res.resolution_type, ResolutionType::AuthorityPrecedence);
422 }
423
424 #[test]
425 fn unrelated_claims_are_scope_dependent() {
426 let c = make_contradiction(
427 "quantum computing breaks RSA encryption",
428 "coffee is the most consumed beverage in the world",
429 None,
430 None,
431 0.6,
432 0.6,
433 );
434 let res = resolve(&c, |_| 0.5).unwrap();
435 assert_eq!(res.resolution_type, ResolutionType::ScopeDependent);
436 }
437
438 #[test]
439 fn resolution_has_all_steps_taken() {
440 let c = make_contradiction("Rust is fast", "Rust is slow", None, None, 0.5, 0.5);
441 let res = resolve(&c, |_| 0.5).unwrap();
442 assert!(!res.steps_taken.is_empty());
443 assert!(!res.synthesis.is_empty());
444 }
445}