1use aspero_core::matching::{self, PLAUSIBLE, VERIFIED};
5use aspero_core::publication::first_page;
6use aspero_core::{Agreement, Claim, Update, UpdateKind};
7
8use crate::resolve::{Candidate, ClaimExt, ResolveReport};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11#[non_exhaustive]
12pub enum Verdict {
13 Verified,
15 Plausible,
17 Mismatch,
20 NotFound,
22 Unverifiable,
24}
25
26impl Verdict {
27 pub fn as_str(self) -> &'static str {
28 match self {
29 Verdict::Verified => "verified",
30 Verdict::Plausible => "plausible",
31 Verdict::Mismatch => "mismatch",
32 Verdict::NotFound => "not_found",
33 Verdict::Unverifiable => "unverifiable",
34 }
35 }
36}
37
38#[derive(Debug, Clone)]
39#[non_exhaustive]
40pub struct Verification {
41 pub verdict: Verdict,
42 pub reason: String,
45 pub why: Reason,
47 pub notes: Vec<Update>,
50 pub best: Option<usize>,
54 pub report: ResolveReport,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
60#[non_exhaustive]
61pub enum Reason {
62 Matches,
64 PartlyMatches { differs: Vec<Difference> },
67 Unconfirmed,
71 Closest { differs: Vec<Difference> },
74 NoMatch,
76 IdExists,
79 IdAgrees,
81 IdPartlyMatches { differs: Vec<Difference> },
85 IdElsewhere { cited: usize },
88 IdDisagrees,
91 IdMissingElsewhere,
94 IdMissing,
97 ProvidersFailed,
99}
100
101impl Reason {
102 pub fn as_str(&self) -> &'static str {
104 match self {
105 Reason::Matches => "matches",
106 Reason::PartlyMatches { .. } => "partly_matches",
107 Reason::Unconfirmed => "unconfirmed",
108 Reason::Closest { .. } => "closest",
109 Reason::NoMatch => "no_match",
110 Reason::IdExists => "id_exists",
111 Reason::IdAgrees => "id_agrees",
112 Reason::IdPartlyMatches { .. } => "id_partly_matches",
113 Reason::IdElsewhere { .. } => "id_elsewhere",
114 Reason::IdDisagrees => "id_disagrees",
115 Reason::IdMissingElsewhere => "id_missing_elsewhere",
116 Reason::IdMissing => "id_missing",
117 Reason::ProvidersFailed => "providers_failed",
118 }
119 }
120
121 pub fn differs(&self) -> &[Difference] {
123 match self {
124 Reason::PartlyMatches { differs }
125 | Reason::Closest { differs }
126 | Reason::IdPartlyMatches { differs } => differs,
127 _ => &[],
128 }
129 }
130}
131
132#[derive(Debug, Clone, PartialEq, Eq)]
135#[non_exhaustive]
136pub struct Difference {
137 pub field: CitedField,
138 pub actual: Option<String>,
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142#[non_exhaustive]
143pub enum CitedField {
144 Title,
145 Authors,
146 Year,
147 Journal,
148 Volume,
149 FirstPage,
150 Kind,
153}
154
155impl CitedField {
156 pub fn as_str(self) -> &'static str {
157 match self {
158 CitedField::Title => "title",
159 CitedField::Authors => "authors",
160 CitedField::Year => "year",
161 CitedField::Journal => "journal",
162 CitedField::Volume => "volume",
163 CitedField::FirstPage => "first_page",
164 CitedField::Kind => "kind",
165 }
166 }
167}
168
169impl std::fmt::Display for Difference {
170 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171 f.write_str(&self.field.as_str().replace('_', " "))?;
172 match (&self.actual, self.field) {
173 (Some(v), CitedField::Journal) => write!(f, " (\"{v}\")"),
174 (Some(v), _) => write!(f, " ({v})"),
175 (None, _) => Ok(()),
176 }
177 }
178}
179
180fn near_miss(c: &Candidate) -> bool {
185 let a = &c.assessment;
186 a.title.agreement == Agreement::Match
187 && (a.authors.agreement == Agreement::Match || a.year.agreement == Agreement::Match)
188}
189
190fn differences(claim: &Claim, c: &Candidate, known_only: bool) -> Vec<Difference> {
194 let a = &c.assessment;
195 let w = &c.record.work;
196 let off = |check: &matching::FieldCheck| match known_only {
197 true => matches!(check.agreement, Agreement::Mismatch | Agreement::Partial),
198 false => check.agreement != Agreement::Match,
199 };
200 let diff = |field, actual: Option<String>| Difference { field, actual };
201 [
202 off(&a.title).then(|| diff(CitedField::Title, None)),
203 off(&a.authors).then(|| diff(CitedField::Authors, None)),
204 matches!(a.year.agreement, Agreement::Mismatch | Agreement::Partial)
205 .then(|| diff(CitedField::Year, w.issued.map(|d| d.year().to_string()))),
206 (a.container.agreement == Agreement::Mismatch)
207 .then(|| diff(CitedField::Journal, w.container_title.clone())),
208 (a.volume.agreement == Agreement::Mismatch)
209 .then(|| diff(CitedField::Volume, w.volume.clone())),
210 (a.page.agreement == Agreement::Mismatch).then(|| {
211 let first = w.page.as_deref().map(|p| first_page(p).to_owned());
212 diff(CitedField::FirstPage, first)
213 }),
214 w.title
215 .as_deref()
216 .and_then(matching::derivative_kind)
217 .filter(|_| !matching::claim_mentions_derivative(claim))
218 .map(|kind| diff(CitedField::Kind, Some(kind.to_owned()))),
219 ]
220 .into_iter()
221 .flatten()
222 .collect()
223}
224
225fn clause(differs: &[Difference]) -> Option<String> {
228 let fields: Vec<String> = differs.iter().map(ToString::to_string).collect();
229 match fields.len() {
230 0 => None,
231 1 => Some(format!("its {} differs", fields[0])),
232 _ => Some(format!("its {} differ", fields.join(" and "))),
233 }
234}
235
236fn describe(c: &Candidate) -> String {
237 let w = &c.record.work;
238 let title = w.title.as_deref().unwrap_or("(untitled)");
239 let year = w
240 .issued
241 .map(|d| format!(" ({})", d.year()))
242 .unwrap_or_default();
243 let id = c.ids.first().map(|i| format!(", {i}")).unwrap_or_default();
244 format!("\"{title}\"{year}{id}")
245}
246
247pub(crate) fn judge(claim: &Claim, report: ResolveReport) -> Verification {
249 let (verdict, why, best) = decide(claim, &report);
250 let notes: Vec<Update> = best
253 .map(|i| &report.candidates[i])
254 .into_iter()
255 .flat_map(|c| {
256 [
257 c.retraction(),
258 c.updates.iter().find(|u| u.kind == UpdateKind::NewVersion),
259 ]
260 })
261 .flatten()
262 .cloned()
263 .collect();
264 let mut reason = explain(claim, &report, &why, best);
265 if !notes.is_empty() {
266 let notes: Vec<String> = notes.iter().map(describe_update).collect();
267 reason = format!("{reason}; note: {}", notes.join("; "));
268 }
269 Verification {
270 verdict,
271 reason,
272 why,
273 notes,
274 best,
275 report,
276 }
277}
278
279fn decide(claim: &Claim, report: &ResolveReport) -> (Verdict, Reason, Option<usize>) {
283 match weigh(claim, report) {
284 (
285 verdict,
286 Reason::PartlyMatches { differs } | Reason::IdPartlyMatches { differs },
287 best,
288 ) if differs.is_empty() => (verdict, Reason::Unconfirmed, best),
289 (_, Reason::Closest { differs }, _) if differs.is_empty() => {
290 (Verdict::NotFound, Reason::NoMatch, None)
291 }
292 settled => settled,
293 }
294}
295
296fn weigh(claim: &Claim, report: &ResolveReport) -> (Verdict, Reason, Option<usize>) {
297 let best = report.candidates.first();
298 let best_conf = best.map_or(0.0, |c| c.assessment.confidence);
299 let failed = !report.errors.is_empty()
300 || report
301 .lookups
302 .iter()
303 .any(|l| l.record.is_none() && !l.is_not_found());
304
305 if claim.ids.is_empty() {
306 return match best {
307 Some(_) if best_conf >= VERIFIED => (Verdict::Verified, Reason::Matches, Some(0)),
308 Some(c) if best_conf >= PLAUSIBLE => (
309 Verdict::Plausible,
310 Reason::PartlyMatches {
311 differs: differences(claim, c, true),
312 },
313 Some(0),
314 ),
315 Some(c) if near_miss(c) => (
316 Verdict::Mismatch,
317 Reason::Closest {
318 differs: differences(claim, c, false),
319 },
320 Some(0),
321 ),
322 _ if failed => (Verdict::Unverifiable, Reason::ProvidersFailed, None),
323 _ => (Verdict::NotFound, Reason::NoMatch, None),
324 };
325 }
326 let by_id = report
327 .candidates
328 .iter()
329 .position(|c| c.assessment.ids == Agreement::Match);
330 let elsewhere = |skip: Option<usize>| {
331 report
332 .candidates
333 .iter()
334 .enumerate()
335 .position(|(i, c)| Some(i) != skip && c.assessment.confidence >= PLAUSIBLE)
336 };
337 match by_id.map(|i| (i, &report.candidates[i])) {
338 Some((i, _)) if !claim.is_descriptive() => (Verdict::Verified, Reason::IdExists, Some(i)),
339 Some((i, c)) if c.assessment.confidence >= VERIFIED => {
340 (Verdict::Verified, Reason::IdAgrees, Some(i))
341 }
342 Some((i, c)) if c.assessment.confidence >= PLAUSIBLE => (
343 Verdict::Plausible,
344 Reason::IdPartlyMatches {
345 differs: differences(claim, c, true),
346 },
347 Some(i),
348 ),
349 Some((i, c)) => match elsewhere(Some(i)) {
350 Some(j) => (Verdict::Mismatch, Reason::IdElsewhere { cited: i }, Some(j)),
351 None if near_miss(c) => (
354 Verdict::Plausible,
355 Reason::IdPartlyMatches {
356 differs: differences(claim, c, true),
357 },
358 Some(i),
359 ),
360 None => (Verdict::Mismatch, Reason::IdDisagrees, Some(i)),
361 },
362 None if failed => (Verdict::Unverifiable, Reason::ProvidersFailed, None),
363 None => match elsewhere(None) {
364 Some(j) => (Verdict::Mismatch, Reason::IdMissingElsewhere, Some(j)),
365 None => (Verdict::NotFound, Reason::IdMissing, None),
366 },
367 }
368}
369
370fn explain(claim: &Claim, report: &ResolveReport, why: &Reason, best: Option<usize>) -> String {
372 let claimed = claim
373 .ids
374 .iter()
375 .map(ToString::to_string)
376 .collect::<Vec<_>>()
377 .join(", ");
378 let work = || {
379 best.map(|i| describe(&report.candidates[i]))
380 .unwrap_or_default()
381 };
382 let details = || clause(why.differs());
383 match why {
384 Reason::Matches => format!("matches {}", work()),
385 Reason::PartlyMatches { .. } => format!(
386 "partly matches {}; {}",
387 work(),
388 details().unwrap_or_else(|| "check the details".into())
389 ),
390 Reason::Unconfirmed => format!(
391 "agrees with {} as far as it goes, but gives too little to confirm it",
392 work()
393 ),
394 Reason::Closest { .. } => format!(
395 "closest work is {}, but {}",
396 work(),
397 details().unwrap_or_else(|| "its details differ".into())
398 ),
399 Reason::NoMatch => "no matching work found".into(),
400 Reason::IdExists => format!("{claimed} exists: {}", work()),
401 Reason::IdAgrees => format!("{claimed} and the citation agree: {}", work()),
402 Reason::IdPartlyMatches { .. } => format!(
403 "{claimed} exists and partly matches the citation: {}{}",
404 work(),
405 details().map(|d| format!("; {d}")).unwrap_or_default()
406 ),
407 Reason::IdElsewhere { cited } => format!(
408 "{claimed} is {}, but the citation matches {}",
409 describe(&report.candidates[*cited]),
410 work()
411 ),
412 Reason::IdDisagrees => {
413 format!("{claimed} is {}, which does not match the citation", work())
414 }
415 Reason::IdMissingElsewhere => {
416 format!("{claimed} does not exist; the citation matches {}", work())
417 }
418 Reason::IdMissing => format!("{claimed} does not exist and no matching work was found"),
419 Reason::ProvidersFailed if claim.ids.is_empty() => {
420 "providers failed; nothing conclusive".into()
421 }
422 Reason::ProvidersFailed => format!("could not look up {claimed}: providers failed"),
423 }
424}
425
426pub fn describe_update(u: &Update) -> String {
428 if u.kind == UpdateKind::NewVersion {
430 let by = u
431 .notice
432 .as_ref()
433 .map(|n| format!(" by {n}"))
434 .unwrap_or_default();
435 let date = u.date.map(|d| format!(" ({d})")).unwrap_or_default();
436 return format!("superseded{by}{date}");
437 }
438 let what = match &u.kind {
439 UpdateKind::Retraction => "RETRACTED".to_owned(),
440 UpdateKind::Withdrawal => "WITHDRAWN".to_owned(),
441 UpdateKind::ExpressionOfConcern => "expression of concern".to_owned(),
442 UpdateKind::Correction => "corrected".to_owned(),
443 other => other.as_str().replace('_', " "),
444 };
445 let details: Vec<String> = [
446 u.date.map(|d| d.to_string()),
447 u.notice.as_ref().map(|n| format!("notice {n}")),
448 u.source.as_ref().map(|s| format!("via {s}")),
449 ]
450 .into_iter()
451 .flatten()
452 .collect();
453 if details.is_empty() {
454 what
455 } else {
456 format!("{what} ({})", details.join(", "))
457 }
458}