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