Skip to main content

vela_protocol/computed/
sources.rs

1//! Source registry and evidence atom projections.
2//!
3//! Sources identify imported artifacts. Evidence atoms identify the exact
4//! source-grounded unit that bears on a finding. Both are safe to derive from
5//! legacy finding bundles when older frontiers do not persist them yet.
6
7use std::collections::{BTreeMap, BTreeSet};
8
9use serde::{Deserialize, Serialize};
10use serde_json::{Value, json};
11use sha2::{Digest, Sha256};
12
13use crate::bundle::{FindingBundle, Provenance};
14use crate::canonical;
15use crate::project::Project;
16
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
18pub struct SourceRecord {
19    pub id: String,
20    pub source_type: String,
21    pub locator: String,
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub content_hash: Option<String>,
24    #[serde(default)]
25    pub title: String,
26    #[serde(default)]
27    pub authors: Vec<String>,
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub year: Option<i32>,
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub doi: Option<String>,
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub pmid: Option<String>,
34    #[serde(default)]
35    pub imported_at: String,
36    #[serde(default)]
37    pub extraction_mode: String,
38    #[serde(default)]
39    pub source_quality: String,
40    #[serde(default)]
41    pub caveats: Vec<String>,
42    #[serde(default)]
43    pub finding_ids: Vec<String>,
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
47pub struct EvidenceAtom {
48    pub id: String,
49    pub source_id: String,
50    pub finding_id: String,
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub locator: Option<String>,
53    pub evidence_type: String,
54    pub measurement_or_claim: String,
55    pub supports_or_challenges: String,
56    pub condition_refs: Vec<String>,
57    pub extraction_method: String,
58    pub human_verified: bool,
59    pub caveats: Vec<String>,
60}
61
62#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
63pub struct ConditionRecord {
64    pub id: String,
65    pub finding_id: String,
66    pub text: String,
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    pub species: Option<String>,
69    pub model_system: String,
70    pub method: String,
71    pub exposure_or_efficacy: String,
72    pub comparator_status: String,
73    pub translation_scope: String,
74    pub caveats: Vec<String>,
75}
76
77#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
78pub struct SourceRegistrySummary {
79    pub count: usize,
80    pub source_types: BTreeMap<String, usize>,
81    pub low_quality_count: usize,
82    pub missing_hash_count: usize,
83}
84
85#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
86pub struct EvidenceAtomSummary {
87    pub count: usize,
88    pub missing_locator_count: usize,
89    pub unverified_count: usize,
90    pub synthetic_source_count: usize,
91}
92
93#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
94pub struct ConditionSummary {
95    pub count: usize,
96    pub missing_text_count: usize,
97    pub missing_comparator_count: usize,
98    pub exposure_efficacy_risk_count: usize,
99    pub translation_scopes: BTreeMap<String, usize>,
100}
101
102#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
103pub struct SourceEvidenceProjection {
104    pub sources: Vec<SourceRecord>,
105    pub evidence_atoms: Vec<EvidenceAtom>,
106    pub condition_records: Vec<ConditionRecord>,
107}
108
109/// Phase N: rewrite each finding's `provenance` (title, year, authors,
110/// journal, license, publisher, funders) from the canonical
111/// SourceRecord that matches by DOI / PMID / title. Returns the count
112/// of findings whose provenance changed.
113///
114/// Doctrine: `Project.sources` is canonical; `FindingBundle.provenance`
115/// is the denormalized cache. When they disagree, the source wins.
116pub fn resync_provenance_from_sources(project: &mut Project) -> usize {
117    use crate::bundle::Author;
118    let mut by_doi: BTreeMap<String, &SourceRecord> = BTreeMap::new();
119    let mut by_title: BTreeMap<String, &SourceRecord> = BTreeMap::new();
120    for source in &project.sources {
121        if let Some(doi) = source.doi.as_deref() {
122            by_doi.insert(doi.to_lowercase(), source);
123        }
124        if !source.title.trim().is_empty() {
125            by_title.insert(normalize_title_key(&source.title), source);
126        }
127    }
128
129    let mut updated = 0usize;
130    for finding in &mut project.findings {
131        let source: Option<&SourceRecord> = finding
132            .provenance
133            .doi
134            .as_deref()
135            .map(str::to_lowercase)
136            .and_then(|key| by_doi.get(&key).copied())
137            .or_else(|| {
138                if finding.provenance.title.trim().is_empty() {
139                    None
140                } else {
141                    by_title
142                        .get(&normalize_title_key(&finding.provenance.title))
143                        .copied()
144                }
145            });
146
147        let Some(source) = source else { continue };
148        let mut changed = false;
149
150        if !source.title.is_empty() && source.title != finding.provenance.title {
151            finding.provenance.title = source.title.clone();
152            changed = true;
153        }
154        if source.year.is_some() && source.year != finding.provenance.year {
155            finding.provenance.year = source.year;
156            changed = true;
157        }
158        if !source.authors.is_empty() {
159            let derived: Vec<Author> = source
160                .authors
161                .iter()
162                .map(|name| Author {
163                    name: name.clone(),
164                    orcid: None,
165                })
166                .collect();
167            let differs = derived.len() != finding.provenance.authors.len()
168                || derived
169                    .iter()
170                    .zip(finding.provenance.authors.iter())
171                    .any(|(a, b)| a.name != b.name);
172            if differs {
173                finding.provenance.authors = derived;
174                changed = true;
175            }
176        }
177        if changed {
178            updated += 1;
179        }
180    }
181    updated
182}
183
184fn normalize_title_key(title: &str) -> String {
185    title
186        .split_whitespace()
187        .collect::<Vec<_>>()
188        .join(" ")
189        .to_lowercase()
190}
191
192pub fn materialize_project(project: &mut Project) {
193    let projection = derive_projection(project);
194    project.sources = projection.sources;
195    project.evidence_atoms = projection.evidence_atoms;
196    project.condition_records = projection.condition_records;
197    crate::project::recompute_stats(project);
198}
199
200pub fn derive_projection(project: &Project) -> SourceEvidenceProjection {
201    let sources = derive_source_records(project);
202    let condition_records = derive_condition_records(project);
203    let evidence_atoms = derive_evidence_atoms(project, &sources, &condition_records);
204    SourceEvidenceProjection {
205        sources,
206        evidence_atoms,
207        condition_records,
208    }
209}
210
211pub fn source_summary(project: &Project) -> SourceRegistrySummary {
212    let sources = if project.sources.is_empty() {
213        derive_source_records(project)
214    } else {
215        project.sources.clone()
216    };
217    let mut source_types = BTreeMap::new();
218    let mut low_quality_count = 0usize;
219    let mut missing_hash_count = 0usize;
220    for source in &sources {
221        *source_types.entry(source.source_type.clone()).or_default() += 1;
222        if matches!(
223            source.source_quality.as_str(),
224            "low" | "rough" | "needs_review" | "synthetic"
225        ) {
226            low_quality_count += 1;
227        }
228        if source.content_hash.is_none() {
229            missing_hash_count += 1;
230        }
231    }
232    SourceRegistrySummary {
233        count: sources.len(),
234        source_types,
235        low_quality_count,
236        missing_hash_count,
237    }
238}
239
240pub fn evidence_summary(project: &Project) -> EvidenceAtomSummary {
241    let projection;
242    let (atoms, source_records): (&[EvidenceAtom], &[SourceRecord]) =
243        if project.evidence_atoms.is_empty() || project.sources.is_empty() {
244            projection = derive_projection(project);
245            (&projection.evidence_atoms, &projection.sources)
246        } else {
247            (&project.evidence_atoms, &project.sources)
248        };
249    let source_map = source_records
250        .iter()
251        .map(|source| (source.id.as_str(), source))
252        .collect::<BTreeMap<_, _>>();
253    let mut missing_locator_count = 0usize;
254    let mut unverified_count = 0usize;
255    let mut synthetic_source_count = 0usize;
256    for atom in atoms {
257        if atom.locator.as_deref().is_none_or(str::is_empty) {
258            missing_locator_count += 1;
259        }
260        if !atom.human_verified {
261            unverified_count += 1;
262        }
263        if source_map
264            .get(atom.source_id.as_str())
265            .is_some_and(|source| is_synthetic_source(source))
266        {
267            synthetic_source_count += 1;
268        }
269    }
270    EvidenceAtomSummary {
271        count: atoms.len(),
272        missing_locator_count,
273        unverified_count,
274        synthetic_source_count,
275    }
276}
277
278pub fn condition_summary(project: &Project) -> ConditionSummary {
279    let records = if project.condition_records.is_empty() {
280        derive_condition_records(project)
281    } else {
282        project.condition_records.clone()
283    };
284    let mut translation_scopes = BTreeMap::new();
285    let mut missing_text_count = 0usize;
286    let mut missing_comparator_count = 0usize;
287    let mut exposure_efficacy_risk_count = 0usize;
288    for record in &records {
289        *translation_scopes
290            .entry(record.translation_scope.clone())
291            .or_default() += 1;
292        if record.text.trim().is_empty() {
293            missing_text_count += 1;
294        }
295        if record.comparator_status == "missing_or_unclear" {
296            missing_comparator_count += 1;
297        }
298        if record.exposure_or_efficacy == "both" {
299            exposure_efficacy_risk_count += 1;
300        }
301    }
302    ConditionSummary {
303        count: records.len(),
304        missing_text_count,
305        missing_comparator_count,
306        exposure_efficacy_risk_count,
307        translation_scopes,
308    }
309}
310
311pub fn condition_records_for_finding<'a>(
312    project: &'a Project,
313    finding_id: &str,
314) -> Vec<&'a ConditionRecord> {
315    project
316        .condition_records
317        .iter()
318        .filter(|record| record.finding_id == finding_id)
319        .collect()
320}
321
322pub fn evidence_atoms_for_finding<'a>(
323    project: &'a Project,
324    finding_id: &str,
325) -> Vec<&'a EvidenceAtom> {
326    project
327        .evidence_atoms
328        .iter()
329        .filter(|atom| atom.finding_id == finding_id)
330        .collect()
331}
332
333pub fn sources_for_finding<'a>(project: &'a Project, finding_id: &str) -> Vec<&'a SourceRecord> {
334    let atoms = evidence_atoms_for_finding(project, finding_id);
335    let ids = atoms
336        .iter()
337        .map(|atom| atom.source_id.as_str())
338        .collect::<BTreeSet<_>>();
339    project
340        .sources
341        .iter()
342        .filter(|source| {
343            source.finding_ids.iter().any(|id| id == finding_id) || ids.contains(source.id.as_str())
344        })
345        .collect()
346}
347pub fn source_evidence_map_from_atoms(evidence_atoms: &[EvidenceAtom]) -> Value {
348    let mut by_source = BTreeMap::<String, Vec<Value>>::new();
349    for atom in evidence_atoms {
350        by_source
351            .entry(atom.source_id.clone())
352            .or_default()
353            .push(json!({
354                "evidence_atom_id": atom.id,
355                "finding_id": atom.finding_id,
356                "locator": atom.locator,
357                "supports_or_challenges": atom.supports_or_challenges,
358                "human_verified": atom.human_verified,
359                "caveats": atom.caveats,
360            }));
361    }
362    json!({
363        "schema": "vela.source-evidence-map.v0",
364        "sources": by_source,
365    })
366}
367
368pub fn condition_matrix(records: &[ConditionRecord]) -> Value {
369    let rows = records
370        .iter()
371        .map(|record| {
372            json!({
373                "condition_id": record.id,
374                "finding_id": record.finding_id,
375                "text": record.text,
376                "species": record.species,
377                "model_system": record.model_system,
378                "method": record.method,
379                "exposure_or_efficacy": record.exposure_or_efficacy,
380                "comparator_status": record.comparator_status,
381                "translation_scope": record.translation_scope,
382                "caveats": record.caveats,
383            })
384        })
385        .collect::<Vec<_>>();
386    json!({
387        "schema": "vela.condition-matrix.v0",
388        "conditions": rows,
389    })
390}
391pub fn source_record_for_finding(finding: &FindingBundle) -> SourceRecord {
392    let source_type = normalize_source_type(&finding.provenance.source_type);
393    let locator = source_locator(&finding.provenance, &finding.id);
394    let content_hash = derived_local_source_hash(finding, &source_type, &locator);
395    let id = source_id(
396        &source_type,
397        &locator,
398        content_hash.as_deref(),
399        finding.provenance.doi.as_deref(),
400        None,
401        &finding.provenance.title,
402    );
403    let mut caveats = Vec::new();
404    if source_type == "synthetic_report" || source_type == "agent_trace" {
405        caveats.push("source requires human review before being treated as evidence".to_string());
406    }
407    if finding.provenance.title.trim().is_empty() && finding.provenance.doi.is_none() {
408        caveats.push("weak source metadata; locator derived from finding id".to_string());
409    }
410    let source_quality = if caveats.is_empty()
411        && !finding.provenance.extraction.method.contains("fallback")
412        && !finding.provenance.extraction.method.contains("rough")
413    {
414        "declared".to_string()
415    } else if source_type == "synthetic_report" || source_type == "agent_trace" {
416        "synthetic".to_string()
417    } else {
418        "needs_review".to_string()
419    };
420    SourceRecord {
421        id,
422        source_type,
423        locator,
424        content_hash,
425        title: finding.provenance.title.clone(),
426        authors: finding
427            .provenance
428            .authors
429            .iter()
430            .map(|author| author.name.clone())
431            .collect(),
432        year: finding.provenance.year,
433        doi: finding.provenance.doi.clone(),
434        pmid: None,
435        imported_at: finding.provenance.extraction.extracted_at.clone(),
436        extraction_mode: finding.provenance.extraction.method.clone(),
437        source_quality,
438        caveats,
439        finding_ids: vec![finding.id.clone()],
440    }
441}
442
443fn derived_local_source_hash(
444    finding: &FindingBundle,
445    source_type: &str,
446    locator: &str,
447) -> Option<String> {
448    if !matches!(
449        source_type,
450        "csv"
451            | "text"
452            | "note"
453            | "agent_trace"
454            | "benchmark_output"
455            | "notebook_entry"
456            | "experiment_log"
457            | "synthetic_report"
458    ) {
459        return None;
460    }
461
462    let preimage = json!({
463        "schema": "vela.source.synthetic-commitment.v1",
464        "finding_id": finding.id,
465        "source_type": source_type,
466        "locator": locator,
467        "title": finding.provenance.title,
468        "url": finding.provenance.url,
469        "extraction_method": finding.provenance.extraction.method,
470        "extracted_at": finding.provenance.extraction.extracted_at,
471        "extractor_version": finding.provenance.extraction.extractor_version,
472    });
473    // Source commitments are protocol identities. Ordinary `serde_json`
474    // object bytes vary when another dependency enables its `preserve_order`
475    // feature, so the same finding could acquire a different source ID in the
476    // product CLI than in a reusable-library consumer. Canonical JSON makes
477    // the preimage independent of Cargo feature unification and map order.
478    let bytes = canonical::to_canonical_bytes(&preimage)
479        .expect("source commitment is canonically serializable");
480    Some(format!("sha256:{}", hex::encode(Sha256::digest(bytes))))
481}
482
483fn derive_source_records(project: &Project) -> Vec<SourceRecord> {
484    let mut by_id = BTreeMap::<String, SourceRecord>::new();
485
486    for finding in &project.findings {
487        let mut record = source_record_for_finding(finding);
488        if let Some(existing) = matching_existing_source(project, &record) {
489            record.source_type = existing.source_type.clone();
490            if existing.content_hash.is_some() {
491                record.content_hash = existing.content_hash.clone();
492            }
493            record.id = source_id(
494                &record.source_type,
495                &record.locator,
496                record.content_hash.as_deref(),
497                record.doi.as_deref(),
498                record.pmid.as_deref(),
499                &record.title,
500            );
501            for caveat in &existing.caveats {
502                push_unique(&mut record.caveats, caveat);
503            }
504        }
505        by_id
506            .entry(record.id.clone())
507            .and_modify(|existing| push_unique(&mut existing.finding_ids, &finding.id))
508            .or_insert(record);
509    }
510
511    for existing in &project.sources {
512        by_id
513            .entry(existing.id.clone())
514            .or_insert_with(|| existing.clone());
515    }
516
517    by_id.into_values().collect()
518}
519
520fn matching_existing_source<'a>(
521    project: &'a Project,
522    record: &SourceRecord,
523) -> Option<&'a SourceRecord> {
524    project.sources.iter().find(|existing| {
525        existing
526            .finding_ids
527            .iter()
528            .any(|id| record.finding_ids.iter().any(|record_id| record_id == id))
529            || (existing.locator == record.locator
530                && existing.title == record.title
531                && existing.doi == record.doi
532                && existing.pmid == record.pmid)
533    })
534}
535
536fn derive_evidence_atoms(
537    project: &Project,
538    sources: &[SourceRecord],
539    condition_records: &[ConditionRecord],
540) -> Vec<EvidenceAtom> {
541    let source_by_finding = sources
542        .iter()
543        .flat_map(|source| {
544            source
545                .finding_ids
546                .iter()
547                .map(move |finding_id| (finding_id.as_str(), source))
548        })
549        .collect::<BTreeMap<_, _>>();
550    let mut atoms = BTreeMap::<String, EvidenceAtom>::new();
551    for finding in &project.findings {
552        let source = source_by_finding
553            .get(finding.id.as_str())
554            .copied()
555            .cloned()
556            .unwrap_or_else(|| source_record_for_finding(finding));
557        let source_id = source.id.clone();
558        if finding.evidence.evidence_spans.is_empty() {
559            let atom = weak_atom(finding, &source_id, condition_records);
560            atoms.insert(atom.id.clone(), atom);
561            continue;
562        }
563        for (span_index, span) in finding.evidence.evidence_spans.iter().enumerate() {
564            let (locator, claim) = span_locator_and_claim(span, span_index);
565            let mut caveats = Vec::new();
566            if locator.is_none() {
567                caveats.push("missing evidence locator".to_string());
568            }
569            if finding.conditions.text.trim().is_empty() {
570                caveats.push("condition boundary missing on parent finding".to_string());
571            }
572            let atom = EvidenceAtom {
573                id: evidence_atom_id(
574                    &source_id,
575                    &finding.id,
576                    locator.as_deref(),
577                    &claim,
578                    &finding.evidence.evidence_type,
579                ),
580                source_id: source_id.clone(),
581                finding_id: finding.id.clone(),
582                locator,
583                evidence_type: finding.evidence.evidence_type.clone(),
584                measurement_or_claim: claim,
585                supports_or_challenges: "supports".to_string(),
586                condition_refs: condition_refs(finding, condition_records),
587                extraction_method: finding.provenance.extraction.method.clone(),
588                human_verified: finding
589                    .provenance
590                    .review
591                    .as_ref()
592                    .is_some_and(|review| review.reviewed),
593                caveats,
594            };
595            atoms.insert(atom.id.clone(), atom);
596        }
597    }
598    // v0.56: When a persisted atom shares an id with a derived one,
599    // merge field-by-field so reducer-applied repairs survive
600    // re-derivation. The derive pass produces weak atoms (locator
601    // None, "missing evidence locator" caveat) for findings whose
602    // evidence_spans are empty. After an `evidence_atom.locator_repaired`
603    // event lands, the persisted atom carries `locator: Some(...)`
604    // and no longer carries the missing-locator caveat. Without this
605    // merge step, re-derivation would silently overwrite the repair
606    // because the existing entry-or-insert pattern preferred the
607    // derived weak atom on id collision.
608    for existing in &project.evidence_atoms {
609        let id = existing.id.clone();
610        match atoms.get_mut(&id) {
611            None => {
612                atoms.insert(id, existing.clone());
613            }
614            Some(derived) => {
615                if existing.locator.is_some() && derived.locator.is_none() {
616                    derived.locator = existing.locator.clone();
617                    derived.caveats.retain(|c| c != "missing evidence locator");
618                }
619                if existing.human_verified && !derived.human_verified {
620                    derived.human_verified = true;
621                }
622            }
623        }
624    }
625    atoms.into_values().collect()
626}
627
628fn derive_condition_records(project: &Project) -> Vec<ConditionRecord> {
629    let mut records = BTreeMap::<String, ConditionRecord>::new();
630    for finding in &project.findings {
631        let record = condition_record_for_finding(finding);
632        records.insert(record.id.clone(), record);
633    }
634    for existing in &project.condition_records {
635        records
636            .entry(existing.id.clone())
637            .or_insert_with(|| existing.clone());
638    }
639    records.into_values().collect()
640}
641
642pub fn condition_record_for_finding(finding: &FindingBundle) -> ConditionRecord {
643    let text = finding.conditions.text.trim().to_string();
644    let species: Option<String> = None;
645    let combined = format!(
646        "{} {} {} {} {}",
647        finding.assertion.text,
648        finding.evidence.evidence_type,
649        finding.evidence.model_system,
650        finding.evidence.method,
651        text
652    );
653    let exposure_or_efficacy = exposure_or_efficacy(&combined);
654    let comparator_status = comparator_status(&combined, finding);
655    let translation_scope = translation_scope(finding, &combined);
656    let mut caveats = Vec::new();
657    if text.is_empty() {
658        caveats.push("condition boundary missing".to_string());
659    }
660    if comparator_status == "missing_or_unclear" {
661        caveats.push("comparator or baseline missing or unclear".to_string());
662    }
663    if exposure_or_efficacy == "both" {
664        caveats.push(
665            "exposure and efficacy language both present; review for overgeneralization"
666                .to_string(),
667        );
668    }
669    if translation_scope == "animal_model" && mentions_human_translation(&combined) {
670        caveats.push(
671            "animal-model evidence is being discussed near human translation language".to_string(),
672        );
673    }
674    ConditionRecord {
675        id: condition_record_id(finding),
676        finding_id: finding.id.clone(),
677        text,
678        species,
679        model_system: finding.evidence.model_system.clone(),
680        method: finding.evidence.method.clone(),
681        exposure_or_efficacy,
682        comparator_status,
683        translation_scope,
684        caveats,
685    }
686}
687
688fn weak_atom(
689    finding: &FindingBundle,
690    source_id: &str,
691    condition_records: &[ConditionRecord],
692) -> EvidenceAtom {
693    let claim = finding.assertion.text.clone();
694    EvidenceAtom {
695        id: evidence_atom_id(
696            source_id,
697            &finding.id,
698            None,
699            &claim,
700            &finding.evidence.evidence_type,
701        ),
702        source_id: source_id.to_string(),
703        finding_id: finding.id.clone(),
704        locator: None,
705        evidence_type: finding.evidence.evidence_type.clone(),
706        measurement_or_claim: claim,
707        supports_or_challenges: "unknown".to_string(),
708        condition_refs: condition_refs(finding, condition_records),
709        extraction_method: finding.provenance.extraction.method.clone(),
710        human_verified: false,
711        caveats: vec!["missing evidence locator".to_string()],
712    }
713}
714
715fn span_locator_and_claim(span: &Value, span_index: usize) -> (Option<String>, String) {
716    if let Some(text) = span.as_str() {
717        let trimmed = text.trim().to_string();
718        let locator = if trimmed.is_empty() {
719            None
720        } else {
721            Some(format!("span:{span_index}"))
722        };
723        return (locator, trimmed);
724    }
725    if let Some(object) = span.as_object() {
726        let claim = object
727            .get("text")
728            .or_else(|| object.get("quote"))
729            .or_else(|| object.get("claim"))
730            .and_then(Value::as_str)
731            .unwrap_or("")
732            .trim()
733            .to_string();
734        let mut parts = Vec::new();
735        for key in [
736            "source", "section", "page", "row", "table", "figure", "start", "end",
737        ] {
738            if let Some(value) = object.get(key) {
739                let rendered = value
740                    .as_str()
741                    .map(str::to_string)
742                    .unwrap_or_else(|| value.to_string());
743                if !rendered.trim().is_empty() {
744                    parts.push(format!("{key}:{rendered}"));
745                }
746            }
747        }
748        let locator = if parts.is_empty() {
749            Some(format!("span:{span_index}"))
750        } else {
751            Some(parts.join("|"))
752        };
753        let claim = if claim.is_empty() {
754            span.to_string()
755        } else {
756            claim
757        };
758        return (locator, claim);
759    }
760    (Some(format!("span:{span_index}")), span.to_string())
761}
762
763fn condition_refs(finding: &FindingBundle, condition_records: &[ConditionRecord]) -> Vec<String> {
764    if let Some(record) = condition_records
765        .iter()
766        .find(|record| record.finding_id == finding.id)
767    {
768        return vec![record.id.clone()];
769    }
770    let text = finding.conditions.text.trim();
771    if text.is_empty() {
772        vec![format!("finding:{}", finding.id)]
773    } else {
774        vec![condition_record_id(finding)]
775    }
776}
777
778pub fn condition_record_id(finding: &FindingBundle) -> String {
779    let input = format!(
780        "{}|{}|{}|{}|{}",
781        finding.id,
782        finding.conditions.text.trim(),
783        finding.evidence.model_system,
784        finding.evidence.method,
785        ""
786    );
787    format!("vcnd_{}", short_hash(input.as_bytes()))
788}
789
790fn exposure_or_efficacy(text: &str) -> String {
791    let lower = text.to_ascii_lowercase();
792    let exposure = [
793        "exposure",
794        "uptake",
795        "transport",
796        "delivery",
797        "penetration",
798        "brain level",
799        "biodistribution",
800        "concentration",
801    ]
802    .iter()
803    .any(|needle| lower.contains(needle));
804    let efficacy = [
805        "efficacy",
806        "therapeutic",
807        "functional",
808        "cognition",
809        "survival",
810        "clinical",
811        "symptom",
812        "outcome",
813    ]
814    .iter()
815    .any(|needle| lower.contains(needle));
816    match (exposure, efficacy) {
817        (true, true) => "both",
818        (true, false) => "exposure",
819        (false, true) => "efficacy",
820        (false, false) => "unknown",
821    }
822    .to_string()
823}
824
825fn comparator_status(text: &str, _finding: &FindingBundle) -> String {
826    let lower = text.to_ascii_lowercase();
827    if [
828        "control",
829        "comparator",
830        "compared",
831        "versus",
832        "relative to",
833        "baseline",
834        "vs ",
835    ]
836    .iter()
837    .any(|needle| lower.contains(needle))
838    {
839        "declared"
840    } else {
841        "missing_or_unclear"
842    }
843    .to_string()
844}
845
846fn translation_scope(_finding: &FindingBundle, text: &str) -> String {
847    let lower = text.to_ascii_lowercase();
848    if lower.contains("cell") || lower.contains("in vitro") || lower.contains("organoid") {
849        return "in_vitro".to_string();
850    }
851    if lower.contains("mice")
852        || lower.contains("mouse")
853        || lower.contains(" rat ")
854        || lower.contains("rats")
855        || lower.contains("rodent")
856        || lower.contains("zebrafish")
857        || lower.contains("monkey")
858        || lower.contains("primate")
859        || lower.contains("in vivo")
860        || lower.contains("animal model")
861    {
862        return "animal_model".to_string();
863    }
864    if lower.contains("benchmark")
865        || lower.contains("dataset")
866        || lower.contains("simulation")
867        || lower.contains("computational")
868    {
869        return "computational".to_string();
870    }
871    "unspecified".to_string()
872}
873
874fn mentions_human_translation(text: &str) -> bool {
875    let lower = text.to_ascii_lowercase();
876    ["human", "clinical", "patient", "therapeutic efficacy"]
877        .iter()
878        .any(|needle| lower.contains(needle))
879}
880
881fn normalize_source_type(source_type: &str) -> String {
882    match source_type {
883        "published_paper" | "paper" => "paper",
884        "database_record" | "curated_csv" | "csv" => "csv",
885        "pdf" => "pdf",
886        "jats" | "jats_xml" => "jats",
887        "text" | "markdown" => "text",
888        "note" => "note",
889        "doi" | "doi_list" => "doi",
890        "agent_trace" => "agent_trace",
891        "benchmark_output" => "benchmark_output",
892        "notebook_entry" => "notebook_entry",
893        "experiment_log" => "experiment_log",
894        "model_output" | "summary" | "synthesis" | "synthetic_report" => "synthetic_report",
895        _ => "paper",
896    }
897    .to_string()
898}
899
900fn source_locator(provenance: &Provenance, finding_id: &str) -> String {
901    provenance
902        .doi
903        .as_ref()
904        .map(|doi| format!("doi:{doi}"))
905        .or_else(|| {
906            (!provenance.title.trim().is_empty()).then(|| format!("title:{}", provenance.title))
907        })
908        .unwrap_or_else(|| format!("unknown-source:{finding_id}"))
909}
910
911pub fn source_id(
912    source_type: &str,
913    locator: &str,
914    content_hash: Option<&str>,
915    doi: Option<&str>,
916    pmid: Option<&str>,
917    title: &str,
918) -> String {
919    let mut input = String::new();
920    input.push_str(source_type);
921    input.push('|');
922    input.push_str(locator);
923    input.push('|');
924    input.push_str(content_hash.unwrap_or(""));
925    input.push('|');
926    input.push_str(doi.unwrap_or(""));
927    input.push('|');
928    input.push_str(pmid.unwrap_or(""));
929    input.push('|');
930    input.push_str(title);
931    format!("vs_{}", short_hash(input.as_bytes()))
932}
933
934pub fn evidence_atom_id(
935    source_id: &str,
936    finding_id: &str,
937    locator: Option<&str>,
938    measurement_or_claim: &str,
939    evidence_type: &str,
940) -> String {
941    let input = format!(
942        "{source_id}|{finding_id}|{}|{measurement_or_claim}|{evidence_type}",
943        locator.unwrap_or("")
944    );
945    format!("vea_{}", short_hash(input.as_bytes()))
946}
947
948pub fn is_synthetic_source(source: &SourceRecord) -> bool {
949    matches!(
950        source.source_type.as_str(),
951        "synthetic_report" | "agent_trace"
952    )
953}
954
955pub fn source_has_canonical_locator(source: &SourceRecord) -> bool {
956    let locator = source.locator.trim();
957    !locator.is_empty()
958        && !locator.starts_with("unknown-source:")
959        && (locator.starts_with("doi:")
960            || locator.starts_with("pmid:")
961            || locator.starts_with("pmc:")
962            || locator.starts_with("url:")
963            || locator.starts_with("title:")
964            || source.doi.is_some()
965            || source.pmid.is_some()
966            || source.content_hash.is_some())
967}
968fn push_unique(values: &mut Vec<String>, value: &str) {
969    if !values.iter().any(|existing| existing == value) {
970        values.push(value.to_string());
971        values.sort();
972    }
973}
974
975fn short_hash(bytes: &[u8]) -> String {
976    let mut hasher = Sha256::new();
977    hasher.update(bytes);
978    let digest = hasher.finalize();
979    hex::encode(&digest[..8])
980}
981
982#[cfg(test)]
983mod tests {
984    use super::*;
985    use crate::bundle::*;
986
987    fn finding_with_span(span: Value) -> FindingBundle {
988        FindingBundle {
989            id: "vf_test".to_string(),
990            version: 1,
991            previous_version: None,
992            assertion: Assertion {
993                text: "TfR targeting increases apparent brain exposure in mice.".to_string(),
994                assertion_type: "mechanism".to_string(),
995                entities: Vec::new(),
996                relation: None,
997                direction: None,
998                causal_claim: None,
999                causal_evidence_grade: None,
1000            },
1001            evidence: Evidence {
1002                evidence_type: "experimental".to_string(),
1003                model_system: "mouse".to_string(),
1004                method: "in vivo exposure assay".to_string(),
1005                replicated: false,
1006                replication_count: None,
1007                evidence_spans: vec![span],
1008            },
1009            conditions: Conditions {
1010                text: "Mouse exposure assay; not human therapeutic efficacy.".to_string(),
1011                duration: None,
1012            },
1013            confidence: Confidence::raw(0.6, "test", 0.8),
1014            provenance: Provenance {
1015                source_type: "published_paper".to_string(),
1016                doi: Some("10.0000/test".to_string()),
1017                url: None,
1018                title: "Test paper".to_string(),
1019                authors: vec![],
1020                year: Some(2026),
1021                license: None,
1022                publisher: None,
1023                funders: vec![],
1024                extraction: Extraction::default(),
1025                review: None,
1026                contributions: Vec::new(),
1027            },
1028            flags: Flags {
1029                gap: false,
1030                negative_space: false,
1031                contested: false,
1032                retracted: false,
1033                declining: false,
1034                gravity_well: false,
1035                review_state: None,
1036                superseded: false,
1037                signature_threshold: None,
1038                jointly_accepted: false,
1039            },
1040            links: Vec::new(),
1041            annotations: vec![],
1042            attachments: vec![],
1043            created: "2026-01-01T00:00:00Z".to_string(),
1044            updated: None,
1045
1046            access_tier: crate::access_tier::AccessTier::Public,
1047        }
1048    }
1049
1050    #[test]
1051    fn projection_distinguishes_sources_from_evidence_atoms() {
1052        let finding = finding_with_span(json!({
1053            "text": "Brain exposure increased in mice.",
1054            "section": "results",
1055            "page": 4
1056        }));
1057        let project = crate::project::assemble("test", vec![finding], 1, 0, "test");
1058        let projection = derive_projection(&project);
1059        assert_eq!(projection.sources.len(), 1);
1060        assert_eq!(projection.evidence_atoms.len(), 1);
1061        assert_eq!(projection.condition_records.len(), 1);
1062        assert!(projection.sources[0].id.starts_with("vs_"));
1063        assert!(projection.evidence_atoms[0].id.starts_with("vea_"));
1064        assert!(projection.condition_records[0].id.starts_with("vcnd_"));
1065        assert_eq!(
1066            projection.evidence_atoms[0].source_id,
1067            projection.sources[0].id
1068        );
1069        assert_eq!(
1070            projection.evidence_atoms[0].condition_refs,
1071            vec![projection.condition_records[0].id.clone()]
1072        );
1073        assert_eq!(
1074            projection.evidence_atoms[0].locator.as_deref(),
1075            Some("section:results|page:4")
1076        );
1077    }
1078
1079    #[test]
1080    fn missing_span_creates_weak_atom_with_caveat() {
1081        let mut finding = finding_with_span(json!({"text": "unused"}));
1082        finding.evidence.evidence_spans.clear();
1083        let project = crate::project::assemble("test", vec![finding], 1, 0, "test");
1084        let projection = derive_projection(&project);
1085        assert_eq!(projection.evidence_atoms.len(), 1);
1086        assert!(projection.evidence_atoms[0].locator.is_none());
1087        assert_eq!(
1088            projection.evidence_atoms[0].supports_or_challenges,
1089            "unknown"
1090        );
1091        assert!(
1092            projection.evidence_atoms[0]
1093                .caveats
1094                .iter()
1095                .any(|c| c == "missing evidence locator")
1096        );
1097    }
1098
1099    #[test]
1100    fn condition_record_flags_exposure_efficacy_boundary() {
1101        let finding = finding_with_span(json!({
1102            "text": "Brain exposure and therapeutic efficacy increased in mice.",
1103            "section": "results"
1104        }));
1105        let record = condition_record_for_finding(&finding);
1106        assert_eq!(record.exposure_or_efficacy, "both");
1107        assert_eq!(record.translation_scope, "animal_model");
1108        assert!(
1109            record
1110                .caveats
1111                .iter()
1112                .any(|caveat| caveat.contains("overgeneralization"))
1113        );
1114    }
1115
1116    #[test]
1117    fn generated_sources_receive_local_commitment_hashes() {
1118        let mut finding = finding_with_span(json!({
1119            "text": "Agent-derived synthesis should be review scoped.",
1120            "section": "summary"
1121        }));
1122        finding.provenance.source_type = "model_output".to_string();
1123        finding.provenance.title = "cap_demo - claim_001".to_string();
1124        finding.provenance.url = Some("artifact_packet:cap_demo".to_string());
1125        finding.provenance.extraction.method = "artifact_to_state_import".to_string();
1126        finding.provenance.extraction.extracted_at = "2026-05-06T00:00:00Z".to_string();
1127        finding.provenance.extraction.extractor_version = "vela/0.55.0".to_string();
1128
1129        let record = source_record_for_finding(&finding);
1130
1131        assert_eq!(record.source_type, "synthetic_report");
1132        assert_eq!(
1133            record.content_hash.as_deref(),
1134            Some("sha256:e19b1285f2e3757335079ff945e62f387b6edfa08b517b99402e9425eed97987")
1135        );
1136        assert_eq!(record.id, "vs_cf51972d2d6fe9d7");
1137    }
1138
1139    #[test]
1140    fn published_paper_sources_do_not_receive_synthetic_hashes() {
1141        let finding = finding_with_span(json!({
1142            "text": "Brain exposure increased in mice.",
1143            "section": "results"
1144        }));
1145
1146        let record = source_record_for_finding(&finding);
1147
1148        assert_eq!(record.source_type, "paper");
1149        assert!(record.content_hash.is_none());
1150    }
1151}