1use std::collections::BTreeMap;
4
5use chrono::Utc;
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use sha2::{Digest, Sha256};
9
10pub const VALID_ASSERTION_TYPES: &[&str] = &[
16 "mechanism",
17 "observational",
18 "computational",
19 "theoretical",
20 "negative",
21 "measurement",
23 "exclusion",
24 "tension",
34 "open_question",
35 "hypothesis",
36 "candidate_finding",
37];
38
39pub const VALID_ARTIFACT_KINDS: &[&str] = &[
45 "dataset",
46 "clinical_trial_record",
47 "protocol",
48 "supplement",
49 "notebook",
50 "code",
51 "model_output",
52 "table",
53 "figure",
54 "registry_record",
55 "lab_file",
56 "source_file",
57 "other",
58];
59
60pub fn valid_artifact_kind(kind: &str) -> bool {
61 VALID_ARTIFACT_KINDS.contains(&kind)
62}
63
64pub const VALID_EVIDENCE_TYPES: &[&str] = &[
66 "experimental",
67 "observational",
68 "computational",
69 "theoretical",
70 "extracted_from_notes",
74];
75
76pub const VALID_PROVENANCE_SOURCE_TYPES: &[&str] = &[
83 "published_paper",
84 "preprint",
85 "model_output",
86 "expert_assertion",
87 "database_record",
88 "data_release",
90 "researcher_notes",
95 "vela_submission",
100];
101
102pub const VALID_LINK_TYPES: &[&str] = &[
114 "supports",
115 "contradicts",
116 "extends",
117 "depends",
118 "replicates",
119 "supersedes",
120 "synthesized_from",
121 "improves",
123 "generalizes",
124 "specializes",
125 "discharges",
127];
128
129#[must_use]
134pub fn bare_finding_id(target: &str) -> &str {
135 target.split('@').next().unwrap_or(target)
136}
137
138#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct ResolvedId {
141 pub source: String,
143 pub id: String,
145 pub confidence: f64,
147 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub matched_name: Option<String>,
150}
151
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154#[serde(rename_all = "snake_case")]
155pub enum ResolutionMethod {
156 ExactMatch,
157 FuzzyMatch,
158 LlmInference,
159 Manual,
160}
161
162impl std::fmt::Display for ResolutionMethod {
163 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
164 match self {
165 ResolutionMethod::ExactMatch => write!(f, "exact_match"),
166 ResolutionMethod::FuzzyMatch => write!(f, "fuzzy_match"),
167 ResolutionMethod::LlmInference => write!(f, "llm_inference"),
168 ResolutionMethod::Manual => write!(f, "manual"),
169 }
170 }
171}
172
173#[derive(Debug, Clone, Serialize, Deserialize)]
174pub struct Entity {
175 pub name: String,
176 #[serde(rename = "type")]
177 pub entity_type: String,
178 #[serde(default)]
181 pub identifiers: serde_json::Map<String, serde_json::Value>,
182 #[serde(default, skip_serializing_if = "Option::is_none")]
184 pub canonical_id: Option<ResolvedId>,
185 #[serde(default)]
187 pub candidates: Vec<ResolvedId>,
188 #[serde(default)]
190 pub aliases: Vec<String>,
191 #[serde(default, skip_serializing_if = "Option::is_none")]
193 pub resolution_provenance: Option<String>,
194 #[serde(default = "default_one")]
195 pub resolution_confidence: f64,
196 #[serde(default, skip_serializing_if = "Option::is_none")]
198 pub resolution_method: Option<ResolutionMethod>,
199 #[serde(default, skip_serializing_if = "Option::is_none")]
201 pub species_context: Option<String>,
202 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
204 pub needs_review: bool,
205}
206
207fn default_one() -> f64 {
208 1.0
209}
210
211#[derive(Debug, Clone, Serialize, Deserialize)]
212pub struct Evidence {
213 #[serde(rename = "type")]
214 pub evidence_type: String,
215 #[serde(default)]
216 pub model_system: String,
217 #[serde(default)]
218 pub method: String,
219 #[serde(default)]
223 pub replicated: bool,
224 pub replication_count: Option<u32>,
225 #[serde(default)]
226 pub evidence_spans: Vec<serde_json::Value>,
227}
228
229#[derive(Debug, Clone, Serialize, Deserialize)]
244pub struct Dataset {
245 pub id: String,
247 pub name: String,
249 pub version: Option<String>,
252 #[serde(default)]
255 pub schema: Vec<(String, String)>,
256 pub row_count: Option<u64>,
258 pub content_hash: String,
263 pub url: Option<String>,
265 pub license: Option<String>,
267 pub provenance: Provenance,
271 pub created: String,
273}
274
275impl Dataset {
276 pub fn content_address(
280 name: &str,
281 version: Option<&str>,
282 content_hash: &str,
283 url: Option<&str>,
284 ) -> String {
285 let preimage = format!(
286 "{}|{}|{}|{}",
287 name,
288 version.unwrap_or(""),
289 content_hash,
290 url.unwrap_or("")
291 );
292 let hash = Sha256::digest(preimage.as_bytes());
293 format!("vd_{}", &hex::encode(hash)[..16])
294 }
295
296 pub fn new(
299 name: impl Into<String>,
300 version: Option<String>,
301 content_hash: impl Into<String>,
302 url: Option<String>,
303 license: Option<String>,
304 provenance: Provenance,
305 ) -> Self {
306 let n = name.into();
307 let h = content_hash.into();
308 let id = Self::content_address(&n, version.as_deref(), &h, url.as_deref());
309 Self {
310 id,
311 name: n,
312 version,
313 schema: Vec::new(),
314 row_count: None,
315 content_hash: h,
316 url,
317 license,
318 provenance,
319 created: Utc::now().to_rfc3339(),
320 }
321 }
322}
323
324#[derive(Debug, Clone, Serialize, Deserialize)]
339pub struct CodeArtifact {
340 pub id: String,
342 pub language: String,
346 pub repo_url: Option<String>,
348 pub git_commit: Option<String>,
352 pub path: String,
354 pub line_range: Option<(u32, u32)>,
356 pub content_hash: String,
360 pub entry_point: Option<String>,
363 pub created: String,
365}
366
367impl CodeArtifact {
368 pub fn content_address(
372 repo_url: Option<&str>,
373 git_commit: Option<&str>,
374 path: &str,
375 line_range: Option<(u32, u32)>,
376 content_hash: &str,
377 ) -> String {
378 let lr = line_range
379 .map(|(a, b)| format!("{a}-{b}"))
380 .unwrap_or_default();
381 let preimage = format!(
382 "{}|{}|{}|{}|{}",
383 repo_url.unwrap_or(""),
384 git_commit.unwrap_or(""),
385 path,
386 lr,
387 content_hash
388 );
389 let hash = Sha256::digest(preimage.as_bytes());
390 format!("vc_{}", &hex::encode(hash)[..16])
391 }
392
393 pub fn new(
396 language: impl Into<String>,
397 repo_url: Option<String>,
398 git_commit: Option<String>,
399 path: impl Into<String>,
400 line_range: Option<(u32, u32)>,
401 content_hash: impl Into<String>,
402 entry_point: Option<String>,
403 ) -> Self {
404 let p = path.into();
405 let h = content_hash.into();
406 let id = Self::content_address(
407 repo_url.as_deref(),
408 git_commit.as_deref(),
409 &p,
410 line_range,
411 &h,
412 );
413 Self {
414 id,
415 language: language.into(),
416 repo_url,
417 git_commit,
418 path: p,
419 line_range,
420 content_hash: h,
421 entry_point,
422 created: Utc::now().to_rfc3339(),
423 }
424 }
425}
426
427#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
436#[serde(rename_all = "snake_case")]
437pub enum ArtifactDisclosure {
438 Public,
439 Restricted,
440 #[default]
441 Unknown,
442}
443
444impl ArtifactDisclosure {
445 pub(crate) fn is_unknown(value: &Self) -> bool {
446 *value == Self::Unknown
447 }
448}
449
450#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
451#[serde(rename_all = "snake_case")]
452pub enum LocatorIntegrity {
453 Immutable,
454 Mutable,
455 #[default]
456 Unknown,
457}
458
459impl LocatorIntegrity {
460 pub(crate) fn is_unknown(value: &Self) -> bool {
461 *value == Self::Unknown
462 }
463}
464
465#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
466#[serde(rename_all = "snake_case")]
467pub enum ArtifactAvailability {
468 Available,
469 Unavailable,
470 #[default]
471 Unknown,
472}
473
474impl ArtifactAvailability {
475 pub(crate) fn is_unknown(value: &Self) -> bool {
476 *value == Self::Unknown
477 }
478}
479
480#[derive(Debug, Clone, Serialize, Deserialize)]
481pub struct Artifact {
482 pub id: String,
485 pub kind: String,
487 pub name: String,
489 pub content_hash: String,
491 #[serde(default, skip_serializing_if = "Option::is_none")]
493 pub size_bytes: Option<u64>,
494 #[serde(default, skip_serializing_if = "Option::is_none")]
496 pub media_type: Option<String>,
497 pub storage_mode: String,
499 #[serde(default, skip_serializing_if = "ArtifactDisclosure::is_unknown")]
502 pub disclosure: ArtifactDisclosure,
503 #[serde(default, skip_serializing_if = "LocatorIntegrity::is_unknown")]
505 pub locator_integrity: LocatorIntegrity,
506 #[serde(default, skip_serializing_if = "ArtifactAvailability::is_unknown")]
508 pub availability: ArtifactAvailability,
509 #[serde(default, skip_serializing_if = "Option::is_none")]
511 pub locator: Option<String>,
512 #[serde(default, skip_serializing_if = "Option::is_none")]
514 pub source_url: Option<String>,
515 #[serde(default, skip_serializing_if = "Option::is_none")]
517 pub license: Option<String>,
518 #[serde(default, skip_serializing_if = "Vec::is_empty")]
520 pub target_findings: Vec<String>,
521 #[serde(default, skip_serializing_if = "Option::is_none")]
524 pub source_id: Option<String>,
525 pub provenance: Provenance,
528 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
531 pub metadata: BTreeMap<String, Value>,
532 #[serde(default, skip_serializing_if = "Option::is_none")]
534 pub review_state: Option<ReviewState>,
535 #[serde(default)]
536 pub retracted: bool,
537 #[serde(default)]
538 pub access_tier: crate::access_tier::AccessTier,
539 pub created: String,
541}
542
543impl Artifact {
544 pub fn content_address(
545 kind: &str,
546 name: &str,
547 content_hash: &str,
548 source_url: Option<&str>,
549 locator: Option<&str>,
550 ) -> String {
551 let preimage = format!(
552 "{}|{}|{}|{}|{}",
553 kind,
554 name,
555 content_hash,
556 source_url.unwrap_or(""),
557 locator.unwrap_or("")
558 );
559 let hash = Sha256::digest(preimage.as_bytes());
560 format!("va_{}", &hex::encode(hash)[..16])
561 }
562
563 #[allow(clippy::too_many_arguments)]
567 pub fn content_address_with_axes(
568 kind: &str,
569 name: &str,
570 content_hash: &str,
571 source_url: Option<&str>,
572 locator: Option<&str>,
573 disclosure: ArtifactDisclosure,
574 locator_integrity: LocatorIntegrity,
575 availability: ArtifactAvailability,
576 ) -> String {
577 if disclosure == ArtifactDisclosure::Unknown
578 && locator_integrity == LocatorIntegrity::Unknown
579 && availability == ArtifactAvailability::Unknown
580 {
581 return Self::content_address(kind, name, content_hash, source_url, locator);
582 }
583 let preimage = crate::canonical::to_canonical_bytes(&serde_json::json!({
584 "schema": "vela.artifact-reference-axes.v1",
585 "kind": kind,
586 "name": name,
587 "content_hash": content_hash,
588 "source_url": source_url,
589 "locator": locator,
590 "disclosure": disclosure,
591 "locator_integrity": locator_integrity,
592 "availability": availability,
593 }))
594 .unwrap_or_default();
595 let hash = Sha256::digest(preimage);
596 format!("va_{}", &hex::encode(hash)[..16])
597 }
598
599 pub fn validate_reference_axes(&self) -> Result<(), String> {
604 match self.disclosure {
605 ArtifactDisclosure::Public => {
606 let digest = self.content_hash.strip_prefix("sha256:").ok_or_else(|| {
607 "public artifact content_hash must be sha256:<64 lowercase hex>".to_string()
608 })?;
609 if digest.len() != 64
610 || !digest
611 .bytes()
612 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
613 {
614 return Err(
615 "public artifact content_hash must be sha256:<64 lowercase hex>"
616 .to_string(),
617 );
618 }
619 }
620 ArtifactDisclosure::Restricted => {
621 if !self.content_hash.is_empty() {
622 return Err(
623 "restricted artifact must use an opaque custodian reference; public digest disclosure requires a separately reviewed commitment scheme"
624 .to_string(),
625 );
626 }
627 let locator = self.locator.as_deref().unwrap_or_default();
628 if locator.trim().is_empty()
629 || !(locator.starts_with("custodian:") || locator.starts_with("opaque:"))
630 {
631 return Err(
632 "restricted artifact requires an opaque custodian: or opaque: locator"
633 .to_string(),
634 );
635 }
636 }
637 ArtifactDisclosure::Unknown => {}
638 }
639 if self.storage_mode == "local_blob"
640 && self.availability == ArtifactAvailability::Unavailable
641 {
642 return Err("local_blob artifact cannot be declared unavailable".to_string());
643 }
644 Ok(())
645 }
646
647 #[allow(clippy::too_many_arguments)]
648 pub fn new(
649 kind: impl Into<String>,
650 name: impl Into<String>,
651 content_hash: impl Into<String>,
652 size_bytes: Option<u64>,
653 media_type: Option<String>,
654 storage_mode: impl Into<String>,
655 locator: Option<String>,
656 source_url: Option<String>,
657 license: Option<String>,
658 target_findings: Vec<String>,
659 provenance: Provenance,
660 metadata: BTreeMap<String, Value>,
661 access_tier: crate::access_tier::AccessTier,
662 ) -> Result<Self, String> {
663 let kind = kind.into();
664 if !valid_artifact_kind(&kind) {
665 return Err(format!(
666 "artifact kind '{kind}' is not supported; valid: {}",
667 VALID_ARTIFACT_KINDS.join(", ")
668 ));
669 }
670 let name = name.into();
671 if name.trim().is_empty() {
672 return Err("artifact name must be non-empty".to_string());
673 }
674 let content_hash = normalize_sha256(content_hash.into())?;
675 let storage_mode = storage_mode.into();
676 if !matches!(
677 storage_mode.as_str(),
678 "local_blob" | "local_file" | "remote" | "pointer"
679 ) {
680 return Err(format!(
681 "artifact storage_mode '{storage_mode}' is not supported; valid: local_blob, local_file, remote, pointer"
682 ));
683 }
684 let id = Self::content_address(
685 &kind,
686 &name,
687 &content_hash,
688 source_url.as_deref(),
689 locator.as_deref(),
690 );
691 Ok(Self {
692 id,
693 kind,
694 name,
695 content_hash,
696 size_bytes,
697 media_type,
698 storage_mode,
699 disclosure: ArtifactDisclosure::Unknown,
700 locator_integrity: LocatorIntegrity::Unknown,
701 availability: ArtifactAvailability::Unknown,
702 locator,
703 source_url,
704 license,
705 target_findings,
706 source_id: None,
707 provenance,
708 metadata,
709 review_state: None,
710 retracted: false,
711 access_tier,
712 created: Utc::now().to_rfc3339(),
713 })
714 }
715}
716
717fn normalize_sha256(value: String) -> Result<String, String> {
718 let trimmed = value.trim();
719 let hex = trimmed.strip_prefix("sha256:").unwrap_or(trimmed);
720 if hex.len() != 64 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
721 return Err(format!(
722 "content_hash must be sha256:<64hex> or 64 hex chars, got {trimmed:?}"
723 ));
724 }
725 Ok(format!("sha256:{}", hex.to_ascii_lowercase()))
726}
727
728#[derive(Debug, Clone, Serialize, Deserialize)]
729pub struct Conditions {
730 #[serde(default)]
731 pub text: String,
732 pub duration: Option<String>,
738}
739
740#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
742#[serde(rename_all = "snake_case")]
743#[derive(Default)]
744pub enum ConfidenceMethod {
745 Computed,
747 ExpertJudgment,
749 #[default]
751 LlmInitial,
752}
753
754#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
756#[serde(rename_all = "snake_case")]
757pub enum ConfidenceKind {
758 #[default]
760 FrontierEpistemic,
761}
762
763#[derive(Debug, Clone, Serialize, Deserialize)]
764pub struct Confidence {
765 #[serde(default)]
767 pub kind: ConfidenceKind,
768 pub score: f64,
769 pub basis: String,
770 #[serde(default)]
772 pub method: ConfidenceMethod,
773 #[serde(default = "default_extraction_conf")]
775 pub extraction_confidence: f64,
776}
777
778fn default_extraction_conf() -> f64 {
779 0.85
780}
781
782impl Confidence {
783 pub fn raw(score: f64, basis: impl Into<String>, extraction_confidence: f64) -> Self {
792 Self {
793 kind: ConfidenceKind::FrontierEpistemic,
794 score,
795 basis: basis.into(),
796 method: ConfidenceMethod::LlmInitial,
797 extraction_confidence,
798 }
799 }
800}
801
802#[derive(Debug, Clone, Default, Serialize, Deserialize)]
803pub struct Extraction {
804 #[serde(default = "default_extraction_method")]
805 pub method: String,
806 pub model: Option<String>,
807 pub model_version: Option<String>,
808 #[serde(default)]
809 pub extracted_at: String,
810 #[serde(default = "default_extractor_version")]
811 pub extractor_version: String,
812}
813
814fn default_extraction_method() -> String {
815 "llm_extraction".into()
816}
817fn default_extractor_version() -> String {
818 "vela/0.2.0".into()
819}
820
821#[derive(Debug, Clone, Serialize, Deserialize)]
822pub struct Review {
823 #[serde(default)]
824 pub reviewed: bool,
825 pub reviewer: Option<String>,
826 pub reviewed_at: Option<String>,
827 #[serde(default)]
828 pub corrections: Vec<serde_json::Value>,
829}
830
831#[derive(Debug, Clone, Serialize, Deserialize)]
832pub struct Author {
833 pub name: String,
834 pub orcid: Option<String>,
835}
836
837#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
839#[serde(rename_all = "snake_case")]
840pub enum ContributionUnitType {
841 EvidenceSpan,
843 LeanDecl,
845 Step,
847 Whole,
849}
850
851#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
854#[serde(rename_all = "snake_case")]
855pub enum AgentKind {
856 Human,
857 Agent,
858 Model,
859}
860
861#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
864#[serde(rename_all = "snake_case")]
865pub enum ContributionRole {
866 Originated,
867 Derived,
868 Formalized,
869 Extracted,
870 Reviewed,
871 Vouched,
872}
873
874#[derive(Debug, Clone, Serialize, Deserialize)]
879pub struct Contribution {
880 pub unit: String,
883 pub unit_type: ContributionUnitType,
884 pub agent_kind: AgentKind,
885 pub agent_id: String,
887 #[serde(default, skip_serializing_if = "Option::is_none")]
888 pub model: Option<String>,
889 #[serde(default, skip_serializing_if = "Option::is_none")]
890 pub model_version: Option<String>,
891 pub role: ContributionRole,
892 #[serde(default, skip_serializing_if = "String::is_empty")]
894 pub basis: String,
895}
896
897impl AgentKind {
898 #[must_use]
899 pub fn as_str(&self) -> &'static str {
900 match self {
901 Self::Human => "human",
902 Self::Agent => "agent",
903 Self::Model => "model",
904 }
905 }
906}
907
908impl ContributionRole {
909 #[must_use]
910 pub fn as_str(&self) -> &'static str {
911 match self {
912 Self::Originated => "originated",
913 Self::Derived => "derived",
914 Self::Formalized => "formalized",
915 Self::Extracted => "extracted",
916 Self::Reviewed => "reviewed",
917 Self::Vouched => "vouched",
918 }
919 }
920}
921
922impl Contribution {
923 pub fn validate(&self) -> Result<(), String> {
926 if self.role == ContributionRole::Vouched && self.agent_kind != AgentKind::Human {
927 return Err(
928 "a contribution with role `vouched` must be a human (agents and models hold no key)"
929 .to_string(),
930 );
931 }
932 if self.unit.trim().is_empty() {
933 return Err("contribution `unit` must be non-empty".to_string());
934 }
935 if self.agent_id.trim().is_empty() {
936 return Err("contribution `agent_id` must be non-empty".to_string());
937 }
938 Ok(())
939 }
940}
941
942#[derive(Debug, Clone, Serialize, Deserialize)]
943pub struct Provenance {
944 #[serde(default = "default_source_type")]
945 pub source_type: String,
946 pub doi: Option<String>,
947 #[serde(default, skip_serializing_if = "Option::is_none")]
956 pub url: Option<String>,
957 #[serde(default)]
958 pub title: String,
959 #[serde(default)]
960 pub authors: Vec<Author>,
961 pub year: Option<i32>,
962 #[serde(default, skip_serializing_if = "Option::is_none")]
964 pub license: Option<String>,
965 #[serde(default, skip_serializing_if = "Option::is_none")]
967 pub publisher: Option<String>,
968 #[serde(default, skip_serializing_if = "Vec::is_empty")]
970 pub funders: Vec<String>,
971 #[serde(default)]
972 pub extraction: Extraction,
973 pub review: Option<Review>,
974 #[serde(default, skip_serializing_if = "Vec::is_empty")]
980 pub contributions: Vec<Contribution>,
981}
982
983fn default_source_type() -> String {
984 "published_paper".into()
985}
986
987#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
991#[serde(rename_all = "snake_case")]
992pub enum ReviewState {
993 Accepted,
995 Contested,
997 NeedsRevision,
1000 Rejected,
1003}
1004
1005impl ReviewState {
1006 #[must_use]
1009 pub fn implies_contested(&self) -> bool {
1010 matches!(
1011 self,
1012 ReviewState::Contested | ReviewState::NeedsRevision | ReviewState::Rejected
1013 )
1014 }
1015}
1016
1017#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1018pub struct Flags {
1019 #[serde(default)]
1020 pub gap: bool,
1021 #[serde(default)]
1022 pub negative_space: bool,
1023 #[serde(default)]
1027 pub contested: bool,
1028 #[serde(default)]
1029 pub retracted: bool,
1030 #[serde(default)]
1031 pub declining: bool,
1032 #[serde(default)]
1033 pub gravity_well: bool,
1034 #[serde(default, skip_serializing_if = "Option::is_none")]
1038 pub review_state: Option<ReviewState>,
1039 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1044 pub superseded: bool,
1045 #[serde(default, skip_serializing_if = "Option::is_none")]
1054 pub signature_threshold: Option<u32>,
1055 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1060 pub jointly_accepted: bool,
1061}
1062
1063#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1077#[serde(rename_all = "snake_case")]
1078pub enum CausalClaim {
1079 Correlation,
1081 Mediation,
1083 Intervention,
1085}
1086
1087#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1093#[serde(rename_all = "snake_case")]
1094pub enum CausalEvidenceGrade {
1095 Rct,
1097 QuasiExperimental,
1100 Observational,
1103 Theoretical,
1105}
1106
1107pub const VALID_CAUSAL_CLAIMS: &[&str] = &["correlation", "mediation", "intervention"];
1110
1111pub const VALID_CAUSAL_EVIDENCE_GRADES: &[&str] =
1113 &["rct", "quasi_experimental", "observational", "theoretical"];
1114
1115#[derive(Debug, Clone, Serialize, Deserialize)]
1116pub struct Assertion {
1117 pub text: String,
1118 #[serde(rename = "type")]
1119 pub assertion_type: String,
1120 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1125 pub entities: Vec<Entity>,
1126 pub relation: Option<String>,
1127 pub direction: Option<String>,
1128 #[serde(default, skip_serializing_if = "Option::is_none")]
1133 pub causal_claim: Option<CausalClaim>,
1134 #[serde(default, skip_serializing_if = "Option::is_none")]
1138 pub causal_evidence_grade: Option<CausalEvidenceGrade>,
1139}
1140
1141#[derive(Debug, Clone, Serialize, Deserialize)]
1142pub struct Link {
1143 pub target: String,
1144 #[serde(rename = "type")]
1145 pub link_type: String,
1146 #[serde(default)]
1147 pub note: String,
1148 #[serde(default = "default_compiler")]
1149 pub inferred_by: String,
1150 #[serde(default)]
1152 pub created_at: String,
1153 #[serde(default, skip_serializing_if = "Option::is_none")]
1160 pub mechanism: Option<Mechanism>,
1161}
1162
1163fn default_compiler() -> String {
1164 "compiler".into()
1165}
1166
1167#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
1193#[serde(tag = "kind", rename_all = "snake_case")]
1194pub enum Mechanism {
1195 Linear {
1196 sign: MechanismSign,
1197 slope: f64,
1199 },
1200 Monotonic {
1201 sign: MechanismSign,
1202 },
1203 Threshold {
1204 sign: MechanismSign,
1205 threshold: f64,
1206 },
1207 Saturating {
1208 sign: MechanismSign,
1209 half_max: f64,
1210 },
1211 Unknown,
1212}
1213
1214#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1219#[serde(rename_all = "lowercase")]
1220pub enum MechanismSign {
1221 Positive,
1222 Negative,
1223}
1224
1225impl MechanismSign {
1226 #[must_use]
1227 pub fn as_f64(self) -> f64 {
1228 match self {
1229 Self::Positive => 1.0,
1230 Self::Negative => -1.0,
1231 }
1232 }
1233}
1234
1235impl Mechanism {
1236 #[must_use]
1240 pub fn apply(&self, delta_x: f64) -> Option<f64> {
1241 match *self {
1242 Self::Linear { sign, slope } => Some(sign.as_f64() * slope * delta_x),
1243 Self::Monotonic { sign } => {
1244 Some(sign.as_f64() * delta_x.signum() * delta_x.abs().min(1.0))
1245 }
1246 Self::Threshold { sign, threshold } => {
1247 if delta_x.abs() >= threshold {
1248 Some(sign.as_f64() * delta_x.signum())
1249 } else {
1250 Some(0.0)
1251 }
1252 }
1253 Self::Saturating { sign, half_max } => {
1254 let denom = delta_x.abs() + half_max.max(1e-9);
1256 Some(sign.as_f64() * delta_x / denom)
1257 }
1258 Self::Unknown => None,
1259 }
1260 }
1261}
1262
1263#[derive(Debug, Clone, PartialEq, Eq)]
1271pub enum LinkRef {
1272 Local { vf_id: String },
1274 Cross { vf_id: String, vfr_id: String },
1278}
1279
1280#[derive(Debug, Clone, PartialEq, Eq)]
1281pub enum LinkParseError {
1282 Empty,
1283 BadVfPrefix,
1284 BadVfrPrefix,
1285 EmptyVfId,
1286 EmptyVfrId,
1287 TooManyAtSigns,
1288}
1289
1290impl std::fmt::Display for LinkParseError {
1291 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1292 match self {
1293 LinkParseError::Empty => write!(f, "empty link target"),
1294 LinkParseError::BadVfPrefix => write!(f, "link target must start with 'vf_'"),
1295 LinkParseError::BadVfrPrefix => {
1296 write!(f, "cross-frontier suffix must start with 'vfr_'")
1297 }
1298 LinkParseError::EmptyVfId => write!(f, "link target's vf_ id is empty"),
1299 LinkParseError::EmptyVfrId => write!(f, "cross-frontier vfr_ id is empty"),
1300 LinkParseError::TooManyAtSigns => {
1301 write!(f, "link target has more than one '@' separator")
1302 }
1303 }
1304 }
1305}
1306
1307impl std::error::Error for LinkParseError {}
1308
1309impl LinkRef {
1310 pub fn parse(s: &str) -> Result<Self, LinkParseError> {
1315 if s.is_empty() {
1316 return Err(LinkParseError::Empty);
1317 }
1318 let mut parts = s.split('@');
1319 let local = parts.next().ok_or(LinkParseError::Empty)?;
1320 let remote = parts.next();
1321 if parts.next().is_some() {
1322 return Err(LinkParseError::TooManyAtSigns);
1323 }
1324 let vf_id = local
1325 .strip_prefix("vf_")
1326 .ok_or(LinkParseError::BadVfPrefix)?;
1327 if vf_id.is_empty() {
1328 return Err(LinkParseError::EmptyVfId);
1329 }
1330 match remote {
1331 None => Ok(LinkRef::Local {
1332 vf_id: local.to_string(),
1333 }),
1334 Some(r) => {
1335 let vfr_id = r.strip_prefix("vfr_").ok_or(LinkParseError::BadVfrPrefix)?;
1336 if vfr_id.is_empty() {
1337 return Err(LinkParseError::EmptyVfrId);
1338 }
1339 Ok(LinkRef::Cross {
1340 vf_id: local.to_string(),
1341 vfr_id: r.to_string(),
1342 })
1343 }
1344 }
1345 }
1346
1347 pub fn format(&self) -> String {
1349 match self {
1350 LinkRef::Local { vf_id } => vf_id.clone(),
1351 LinkRef::Cross { vf_id, vfr_id } => format!("{vf_id}@{vfr_id}"),
1352 }
1353 }
1354
1355 pub fn is_cross_frontier(&self) -> bool {
1357 matches!(self, LinkRef::Cross { .. })
1358 }
1359}
1360
1361#[cfg(test)]
1362mod link_ref_tests {
1363 use super::*;
1364
1365 #[test]
1366 fn parses_local_vf_id() {
1367 let r = LinkRef::parse("vf_abc123").unwrap();
1368 assert_eq!(
1369 r,
1370 LinkRef::Local {
1371 vf_id: "vf_abc123".into()
1372 }
1373 );
1374 assert_eq!(r.format(), "vf_abc123");
1375 assert!(!r.is_cross_frontier());
1376 }
1377
1378 #[test]
1379 fn parses_cross_frontier_target() {
1380 let r = LinkRef::parse("vf_abc@vfr_def").unwrap();
1381 assert_eq!(
1382 r,
1383 LinkRef::Cross {
1384 vf_id: "vf_abc".into(),
1385 vfr_id: "vfr_def".into(),
1386 }
1387 );
1388 assert_eq!(r.format(), "vf_abc@vfr_def");
1389 assert!(r.is_cross_frontier());
1390 }
1391
1392 #[test]
1393 fn rejects_empty() {
1394 assert_eq!(LinkRef::parse(""), Err(LinkParseError::Empty));
1395 }
1396
1397 #[test]
1398 fn rejects_missing_vf_prefix() {
1399 assert_eq!(LinkRef::parse("xx_abc"), Err(LinkParseError::BadVfPrefix));
1400 }
1401
1402 #[test]
1403 fn rejects_empty_vf_id() {
1404 assert_eq!(LinkRef::parse("vf_"), Err(LinkParseError::EmptyVfId));
1405 }
1406
1407 #[test]
1408 fn rejects_missing_vfr_prefix_after_at() {
1409 assert_eq!(
1410 LinkRef::parse("vf_abc@xxx_def"),
1411 Err(LinkParseError::BadVfrPrefix)
1412 );
1413 }
1414
1415 #[test]
1416 fn rejects_empty_vfr_id() {
1417 assert_eq!(
1418 LinkRef::parse("vf_abc@vfr_"),
1419 Err(LinkParseError::EmptyVfrId)
1420 );
1421 }
1422
1423 #[test]
1424 fn rejects_double_at() {
1425 assert_eq!(
1426 LinkRef::parse("vf_abc@vfr_def@x"),
1427 Err(LinkParseError::TooManyAtSigns)
1428 );
1429 }
1430
1431 #[test]
1432 fn round_trips_real_ids() {
1433 for s in [
1434 "vf_d0a962d3251133dd",
1435 "vf_d0a962d3251133dd@vfr_7344e96c0f2669d5",
1436 ] {
1437 assert_eq!(LinkRef::parse(s).unwrap().format(), s);
1438 }
1439 }
1440}
1441
1442#[derive(Debug, Clone, Serialize, Deserialize)]
1444pub struct Annotation {
1445 pub id: String,
1447 pub text: String,
1449 pub author: String,
1451 pub timestamp: String,
1453 #[serde(default, skip_serializing_if = "Option::is_none")]
1459 pub provenance: Option<ProvenanceRef>,
1460}
1461
1462#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1468pub struct ProvenanceRef {
1469 #[serde(default, skip_serializing_if = "Option::is_none")]
1470 pub doi: Option<String>,
1471 #[serde(default, skip_serializing_if = "Option::is_none")]
1472 pub pmid: Option<String>,
1473 #[serde(default, skip_serializing_if = "Option::is_none")]
1474 pub title: Option<String>,
1475 #[serde(default, skip_serializing_if = "Option::is_none")]
1477 pub span: Option<String>,
1478}
1479
1480impl ProvenanceRef {
1481 #[must_use]
1484 pub fn has_identifier(&self) -> bool {
1485 self.doi.is_some() || self.pmid.is_some() || self.title.is_some()
1486 }
1487}
1488
1489#[derive(Debug, Clone, Serialize, Deserialize)]
1491pub struct Attachment {
1492 pub filename: String,
1493 pub label: Option<String>,
1494 pub path: String,
1495 pub size_bytes: u64,
1496 pub mime_type: Option<String>,
1497 pub attached_at: String,
1498 pub attached_by: Option<String>,
1499}
1500
1501#[derive(Debug, Clone, Serialize, Deserialize)]
1506pub struct ReviewEvent {
1507 pub id: String,
1509 #[serde(default, skip_serializing_if = "Option::is_none")]
1511 pub workspace: Option<String>,
1512 pub finding_id: String,
1514 pub reviewer: String,
1516 pub reviewed_at: String,
1518 #[serde(default, skip_serializing_if = "Option::is_none")]
1520 pub scope: Option<String>,
1521 #[serde(default, skip_serializing_if = "Option::is_none")]
1523 pub status: Option<String>,
1524 pub action: ReviewAction,
1526 #[serde(default)]
1528 pub reason: String,
1529 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1531 pub evidence_considered: Vec<ReviewEvidence>,
1532 #[serde(default, skip_serializing_if = "Option::is_none")]
1534 pub state_change: Option<serde_json::Value>,
1535}
1536
1537#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1538pub struct ReviewEvidence {
1539 pub finding_id: String,
1540 #[serde(default, skip_serializing_if = "Option::is_none")]
1541 pub role: Option<String>,
1542 #[serde(default, skip_serializing_if = "Option::is_none")]
1543 pub note: Option<String>,
1544}
1545
1546#[derive(Debug, Clone, Serialize, Deserialize)]
1548#[serde(tag = "type", rename_all = "snake_case")]
1549pub enum ReviewAction {
1550 Approved,
1552 Qualified { target: String },
1554 Corrected {
1556 field: String,
1557 original: String,
1558 corrected: String,
1559 },
1560 Flagged { flag_type: String },
1562 Disputed {
1564 counter_evidence: String,
1565 #[serde(default, skip_serializing_if = "Option::is_none")]
1566 counter_doi: Option<String>,
1567 },
1568}
1569
1570#[derive(Debug, Clone, Serialize, Deserialize)]
1575pub struct ConfidenceUpdate {
1576 pub finding_id: String,
1577 pub previous_score: f64,
1578 pub new_score: f64,
1579 pub basis: String,
1580 pub updated_by: String,
1582 pub updated_at: String,
1584}
1585
1586#[derive(Debug, Clone, Serialize, Deserialize)]
1587pub struct FindingBundle {
1588 pub id: String,
1589 #[serde(default = "default_version")]
1590 pub version: u32,
1591 pub previous_version: Option<String>,
1592 pub assertion: Assertion,
1593 pub evidence: Evidence,
1594 pub conditions: Conditions,
1595 pub confidence: Confidence,
1596 pub provenance: Provenance,
1597 pub flags: Flags,
1598 #[serde(default)]
1599 pub links: Vec<Link>,
1600 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1601 pub annotations: Vec<Annotation>,
1602 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1603 pub attachments: Vec<Attachment>,
1604 pub created: String,
1605 pub updated: Option<String>,
1606 #[serde(default, skip_serializing_if = "is_public_tier")]
1613 pub access_tier: crate::access_tier::AccessTier,
1614}
1615
1616fn is_public_tier(tier: &crate::access_tier::AccessTier) -> bool {
1617 matches!(tier, crate::access_tier::AccessTier::Public)
1618}
1619
1620fn default_version() -> u32 {
1621 1
1622}
1623
1624impl FindingBundle {
1625 pub fn normalize_text(s: &str) -> String {
1631 let lower = s.to_lowercase();
1632 let collapsed: String = lower.split_whitespace().collect::<Vec<_>>().join(" ");
1634 collapsed
1636 .trim_end_matches(['.', ';', ':', '!', '?'])
1637 .to_string()
1638 }
1639
1640 pub fn content_address(assertion: &Assertion, provenance: &Provenance) -> String {
1644 let norm_text = Self::normalize_text(&assertion.text);
1645 let prov_id = provenance.doi.as_deref().unwrap_or(&provenance.title);
1648 let preimage = format!("{}|{}|{}", norm_text, assertion.assertion_type, prov_id);
1649 let hash = Sha256::digest(preimage.as_bytes());
1650 format!("vf_{}", &hex::encode(hash)[..16])
1651 }
1652
1653 pub fn new(
1654 assertion: Assertion,
1655 evidence: Evidence,
1656 conditions: Conditions,
1657 confidence: Confidence,
1658 provenance: Provenance,
1659 flags: Flags,
1660 ) -> Self {
1661 let now = Utc::now().to_rfc3339();
1662 let id = Self::content_address(&assertion, &provenance);
1663
1664 Self {
1665 id,
1666 version: 1,
1667 previous_version: None,
1668 assertion,
1669 evidence,
1670 conditions,
1671 confidence,
1672 provenance,
1673 flags,
1674 links: Vec::new(),
1675 annotations: Vec::new(),
1676 attachments: Vec::new(),
1677 created: now,
1678 updated: None,
1679 access_tier: crate::access_tier::AccessTier::Public,
1680 }
1681 }
1682
1683 pub fn add_link(&mut self, target_id: &str, link_type: &str, note: &str) {
1684 self.links.push(Link {
1685 target: target_id.to_string(),
1686 link_type: link_type.to_string(),
1687 note: note.to_string(),
1688 inferred_by: "compiler".to_string(),
1689 created_at: Utc::now().to_rfc3339(),
1690 mechanism: None,
1691 });
1692 }
1693
1694 pub fn add_link_with_source(
1695 &mut self,
1696 target_id: &str,
1697 link_type: &str,
1698 note: &str,
1699 inferred_by: &str,
1700 ) {
1701 self.links.push(Link {
1702 target: target_id.to_string(),
1703 link_type: link_type.to_string(),
1704 note: note.to_string(),
1705 inferred_by: inferred_by.to_string(),
1706 created_at: Utc::now().to_rfc3339(),
1707 mechanism: None,
1708 });
1709 }
1710}
1711
1712#[cfg(test)]
1713mod tests {
1714 use super::*;
1715
1716 fn sample_assertion() -> Assertion {
1717 Assertion {
1718 text: "NLRP3 activates IL-1B".into(),
1719 assertion_type: "mechanism".into(),
1720 entities: vec![Entity {
1721 name: "NLRP3".into(),
1722 entity_type: "protein".into(),
1723 identifiers: serde_json::Map::new(),
1724 canonical_id: None,
1725 candidates: vec![],
1726 aliases: vec![],
1727 resolution_provenance: None,
1728 resolution_confidence: 1.0,
1729 resolution_method: None,
1730 species_context: None,
1731 needs_review: false,
1732 }],
1733 relation: Some("activates".into()),
1734 direction: Some("positive".into()),
1735 causal_claim: None,
1736 causal_evidence_grade: None,
1737 }
1738 }
1739
1740 fn sample_evidence() -> Evidence {
1741 Evidence {
1742 evidence_type: "experimental".into(),
1743 model_system: "mouse".into(),
1744 method: "Western blot".into(),
1745 replicated: true,
1746 replication_count: Some(3),
1747 evidence_spans: vec![],
1748 }
1749 }
1750
1751 fn sample_conditions() -> Conditions {
1752 Conditions {
1753 text: "In vitro, mouse microglia".into(),
1754 duration: None,
1755 }
1756 }
1757
1758 fn sample_confidence() -> Confidence {
1759 Confidence {
1760 kind: ConfidenceKind::FrontierEpistemic,
1761 score: 0.85,
1762 basis: "Experimental with replication".into(),
1763 method: ConfidenceMethod::LlmInitial,
1764 extraction_confidence: 0.9,
1765 }
1766 }
1767
1768 fn sample_provenance() -> Provenance {
1769 Provenance {
1770 source_type: "published_paper".into(),
1771 doi: Some("10.1234/test".into()),
1772 url: None,
1773 title: "Test Paper".into(),
1774 authors: vec![Author {
1775 name: "Smith J".into(),
1776 orcid: None,
1777 }],
1778 year: Some(2024),
1779 license: None,
1780 publisher: None,
1781 funders: vec![],
1782 extraction: Extraction::default(),
1783 review: None,
1784 contributions: Vec::new(),
1785 }
1786 }
1787
1788 fn sample_flags() -> Flags {
1789 Flags {
1790 gap: false,
1791 negative_space: false,
1792 contested: false,
1793 retracted: false,
1794 declining: false,
1795 gravity_well: false,
1796 review_state: None,
1797 superseded: false,
1798 signature_threshold: None,
1799 jointly_accepted: false,
1800 }
1801 }
1802
1803 #[test]
1806 fn same_content_same_id() {
1807 let b1 = FindingBundle::new(
1808 sample_assertion(),
1809 sample_evidence(),
1810 sample_conditions(),
1811 sample_confidence(),
1812 sample_provenance(),
1813 sample_flags(),
1814 );
1815 let b2 = FindingBundle::new(
1816 sample_assertion(),
1817 sample_evidence(),
1818 sample_conditions(),
1819 sample_confidence(),
1820 sample_provenance(),
1821 sample_flags(),
1822 );
1823 assert_eq!(b1.id, b2.id);
1824 }
1825
1826 #[test]
1827 fn different_content_different_id() {
1828 let b1 = FindingBundle::new(
1829 sample_assertion(),
1830 sample_evidence(),
1831 sample_conditions(),
1832 sample_confidence(),
1833 sample_provenance(),
1834 sample_flags(),
1835 );
1836 let mut different_assertion = sample_assertion();
1837 different_assertion.text = "Completely different claim".into();
1838 let b2 = FindingBundle::new(
1839 different_assertion,
1840 sample_evidence(),
1841 sample_conditions(),
1842 sample_confidence(),
1843 sample_provenance(),
1844 sample_flags(),
1845 );
1846 assert_ne!(b1.id, b2.id);
1847 }
1848
1849 #[test]
1850 fn id_starts_with_vf_prefix() {
1851 let b = FindingBundle::new(
1852 sample_assertion(),
1853 sample_evidence(),
1854 sample_conditions(),
1855 sample_confidence(),
1856 sample_provenance(),
1857 sample_flags(),
1858 );
1859 assert!(b.id.starts_with("vf_"));
1860 assert_eq!(b.id.len(), 3 + 16); }
1862
1863 #[test]
1864 fn new_bundle_version_is_one() {
1865 let b = FindingBundle::new(
1866 sample_assertion(),
1867 sample_evidence(),
1868 sample_conditions(),
1869 sample_confidence(),
1870 sample_provenance(),
1871 sample_flags(),
1872 );
1873 assert_eq!(b.version, 1);
1874 assert!(b.previous_version.is_none());
1875 }
1876
1877 #[test]
1878 fn new_bundle_has_no_links() {
1879 let b = FindingBundle::new(
1880 sample_assertion(),
1881 sample_evidence(),
1882 sample_conditions(),
1883 sample_confidence(),
1884 sample_provenance(),
1885 sample_flags(),
1886 );
1887 assert!(b.links.is_empty());
1888 }
1889
1890 #[test]
1891 fn new_bundle_has_created_timestamp() {
1892 let b = FindingBundle::new(
1893 sample_assertion(),
1894 sample_evidence(),
1895 sample_conditions(),
1896 sample_confidence(),
1897 sample_provenance(),
1898 sample_flags(),
1899 );
1900 assert!(!b.created.is_empty());
1901 assert!(b.updated.is_none());
1902 }
1903
1904 #[test]
1907 fn add_link_works() {
1908 let mut b = FindingBundle::new(
1909 sample_assertion(),
1910 sample_evidence(),
1911 sample_conditions(),
1912 sample_confidence(),
1913 sample_provenance(),
1914 sample_flags(),
1915 );
1916 b.add_link("target_id", "extends", "shared entity");
1917 assert_eq!(b.links.len(), 1);
1918 assert_eq!(b.links[0].target, "target_id");
1919 assert_eq!(b.links[0].link_type, "extends");
1920 assert_eq!(b.links[0].note, "shared entity");
1921 assert_eq!(b.links[0].inferred_by, "compiler");
1922 }
1923
1924 #[test]
1925 fn add_link_with_source_works() {
1926 let mut b = FindingBundle::new(
1927 sample_assertion(),
1928 sample_evidence(),
1929 sample_conditions(),
1930 sample_confidence(),
1931 sample_provenance(),
1932 sample_flags(),
1933 );
1934 b.add_link_with_source(
1935 "target_id",
1936 "contradicts",
1937 "opposite direction",
1938 "entity_overlap",
1939 );
1940 assert_eq!(b.links.len(), 1);
1941 assert_eq!(b.links[0].inferred_by, "entity_overlap");
1942 }
1943
1944 #[test]
1945 fn multiple_links_accumulate() {
1946 let mut b = FindingBundle::new(
1947 sample_assertion(),
1948 sample_evidence(),
1949 sample_conditions(),
1950 sample_confidence(),
1951 sample_provenance(),
1952 sample_flags(),
1953 );
1954 b.add_link("t1", "extends", "note1");
1955 b.add_link("t2", "contradicts", "note2");
1956 b.add_link("t3", "supports", "note3");
1957 assert_eq!(b.links.len(), 3);
1958 }
1959
1960 #[test]
1963 fn review_event_creation() {
1964 let event = ReviewEvent {
1965 id: "rev_abc123".into(),
1966 workspace: None,
1967 finding_id: "vf_abc".into(),
1968 reviewer: "0000-0001-2345-6789".into(),
1969 reviewed_at: "2024-01-01T00:00:00Z".into(),
1970 scope: None,
1971 status: None,
1972 action: ReviewAction::Approved,
1973 reason: "Looks correct".into(),
1974 evidence_considered: vec![],
1975 state_change: None,
1976 };
1977 assert_eq!(event.finding_id, "vf_abc");
1978 assert_eq!(event.reviewer, "0000-0001-2345-6789");
1979 }
1980
1981 #[test]
1982 fn review_action_corrected() {
1983 let action = ReviewAction::Corrected {
1984 field: "direction".into(),
1985 original: "positive".into(),
1986 corrected: "negative".into(),
1987 };
1988 if let ReviewAction::Corrected {
1989 field,
1990 original,
1991 corrected,
1992 } = action
1993 {
1994 assert_eq!(field, "direction");
1995 assert_eq!(original, "positive");
1996 assert_eq!(corrected, "negative");
1997 } else {
1998 panic!("Expected Corrected variant");
1999 }
2000 }
2001
2002 #[test]
2003 fn review_action_disputed() {
2004 let action = ReviewAction::Disputed {
2005 counter_evidence: "Later study contradicts".into(),
2006 counter_doi: Some("10.1234/counter".into()),
2007 };
2008 if let ReviewAction::Disputed {
2009 counter_evidence,
2010 counter_doi,
2011 } = action
2012 {
2013 assert_eq!(counter_evidence, "Later study contradicts");
2014 assert_eq!(counter_doi, Some("10.1234/counter".into()));
2015 } else {
2016 panic!("Expected Disputed variant");
2017 }
2018 }
2019
2020 #[test]
2023 fn confidence_update_creation() {
2024 let update = ConfidenceUpdate {
2025 finding_id: "vf_abc".into(),
2026 previous_score: 0.7,
2027 new_score: 0.85,
2028 basis: "grounded".into(),
2029 updated_by: "grounding_pass".into(),
2030 updated_at: "2024-01-01T00:00:00Z".into(),
2031 };
2032 assert_eq!(update.previous_score, 0.7);
2033 assert_eq!(update.new_score, 0.85);
2034 assert_eq!(update.updated_by, "grounding_pass");
2035 }
2036
2037 #[test]
2040 fn finding_serializes_and_deserializes() {
2041 let b = FindingBundle::new(
2042 sample_assertion(),
2043 sample_evidence(),
2044 sample_conditions(),
2045 sample_confidence(),
2046 sample_provenance(),
2047 sample_flags(),
2048 );
2049 let json = serde_json::to_string(&b).unwrap();
2050 let b2: FindingBundle = serde_json::from_str(&json).unwrap();
2051 assert_eq!(b.id, b2.id);
2052 assert_eq!(b.assertion.text, b2.assertion.text);
2053 assert_eq!(b.confidence.score, b2.confidence.score);
2054 }
2055
2056 #[test]
2057 fn v0_10_assertion_and_source_extensions() {
2058 assert!(VALID_ASSERTION_TYPES.contains(&"measurement"));
2059 assert!(VALID_ASSERTION_TYPES.contains(&"exclusion"));
2060 assert!(VALID_PROVENANCE_SOURCE_TYPES.contains(&"data_release"));
2061 assert!(VALID_PROVENANCE_SOURCE_TYPES.contains(&"vela_submission"));
2062 }
2063
2064 #[test]
2067 fn confidence_does_not_affect_id() {
2068 let b1 = FindingBundle::new(
2070 sample_assertion(),
2071 sample_evidence(),
2072 sample_conditions(),
2073 sample_confidence(),
2074 sample_provenance(),
2075 sample_flags(),
2076 );
2077 let mut conf2 = sample_confidence();
2078 conf2.score = 0.5;
2079 let b2 = FindingBundle::new(
2080 sample_assertion(),
2081 sample_evidence(),
2082 sample_conditions(),
2083 conf2,
2084 sample_provenance(),
2085 sample_flags(),
2086 );
2087 assert_eq!(b1.id, b2.id);
2088 }
2089
2090 #[test]
2091 fn flags_do_not_affect_id() {
2092 let b1 = FindingBundle::new(
2093 sample_assertion(),
2094 sample_evidence(),
2095 sample_conditions(),
2096 sample_confidence(),
2097 sample_provenance(),
2098 sample_flags(),
2099 );
2100 let mut flags2 = sample_flags();
2101 flags2.gap = true;
2102 flags2.contested = true;
2103 let b2 = FindingBundle::new(
2104 sample_assertion(),
2105 sample_evidence(),
2106 sample_conditions(),
2107 sample_confidence(),
2108 sample_provenance(),
2109 flags2,
2110 );
2111 assert_eq!(b1.id, b2.id);
2113 }
2114
2115 #[test]
2116 fn different_assertion_text_different_id() {
2117 let b1 = FindingBundle::new(
2118 sample_assertion(),
2119 sample_evidence(),
2120 sample_conditions(),
2121 sample_confidence(),
2122 sample_provenance(),
2123 sample_flags(),
2124 );
2125 let mut assertion2 = sample_assertion();
2126 assertion2.assertion_type = "therapeutic".into();
2127 let b2 = FindingBundle::new(
2128 assertion2,
2129 sample_evidence(),
2130 sample_conditions(),
2131 sample_confidence(),
2132 sample_provenance(),
2133 sample_flags(),
2134 );
2135 assert_ne!(b1.id, b2.id);
2136 }
2137
2138 #[test]
2139 fn different_doi_different_id() {
2140 let b1 = FindingBundle::new(
2141 sample_assertion(),
2142 sample_evidence(),
2143 sample_conditions(),
2144 sample_confidence(),
2145 sample_provenance(),
2146 sample_flags(),
2147 );
2148 let mut prov2 = sample_provenance();
2149 prov2.doi = Some("10.5678/other".into());
2150 let b2 = FindingBundle::new(
2151 sample_assertion(),
2152 sample_evidence(),
2153 sample_conditions(),
2154 sample_confidence(),
2155 prov2,
2156 sample_flags(),
2157 );
2158 assert_ne!(b1.id, b2.id);
2159 }
2160
2161 #[test]
2164 fn content_address_is_deterministic_across_runs() {
2165 let assertion1 = Assertion {
2168 text: "Mitochondrial dysfunction precedes amyloid plaque formation.".into(),
2169 assertion_type: "mechanism".into(),
2170 entities: vec![],
2171 relation: None,
2172 direction: None,
2173 causal_claim: None,
2174 causal_evidence_grade: None,
2175 };
2176 let prov1 = Provenance {
2177 source_type: "published_paper".into(),
2178 doi: Some("10.1038/s41586-023-06789-1".into()),
2179 url: None,
2180 title: "Mitochondria in AD".into(),
2181 authors: vec![],
2182 year: Some(2023),
2183 license: None,
2184 publisher: None,
2185 funders: vec![],
2186 extraction: Extraction::default(),
2187 review: None,
2188 contributions: Vec::new(),
2189 };
2190
2191 let assertion2 = Assertion {
2193 text: "Mitochondrial dysfunction precedes amyloid plaque formation.".into(),
2194 assertion_type: "mechanism".into(),
2195 entities: vec![Entity {
2196 name: "mitochondria".into(),
2197 entity_type: "anatomical_structure".into(),
2198 identifiers: serde_json::Map::new(),
2199 canonical_id: None,
2200 candidates: vec![],
2201 aliases: vec![],
2202 resolution_provenance: None,
2203 resolution_confidence: 1.0,
2204 resolution_method: None,
2205 species_context: None,
2206 needs_review: false,
2207 }],
2208 relation: Some("precedes".into()),
2209 direction: Some("positive".into()),
2210 causal_claim: None,
2211 causal_evidence_grade: None,
2212 };
2213 let prov2 = Provenance {
2214 source_type: "published_paper".into(),
2215 doi: Some("10.1038/s41586-023-06789-1".into()),
2216 url: None,
2217 title: "Different title".into(),
2218 authors: vec![Author {
2219 name: "Jones A".into(),
2220 orcid: None,
2221 }],
2222 year: Some(2023),
2223 license: None,
2224 publisher: None,
2225 funders: vec![],
2226 extraction: Extraction::default(),
2227 review: None,
2228 contributions: Vec::new(),
2229 };
2230
2231 let id1 = FindingBundle::content_address(&assertion1, &prov1);
2232 let id2 = FindingBundle::content_address(&assertion2, &prov2);
2233 assert_eq!(
2234 id1, id2,
2235 "Same assertion text + type + DOI must produce same ID"
2236 );
2237 }
2238
2239 #[test]
2240 fn content_address_normalizes_whitespace_and_punctuation() {
2241 let assertion1 = Assertion {
2242 text: " NLRP3 activates IL-1B. ".into(),
2243 assertion_type: "mechanism".into(),
2244 entities: vec![],
2245 relation: None,
2246 direction: None,
2247 causal_claim: None,
2248 causal_evidence_grade: None,
2249 };
2250 let assertion2 = Assertion {
2251 text: "NLRP3 activates IL-1B".into(),
2252 assertion_type: "mechanism".into(),
2253 entities: vec![],
2254 relation: None,
2255 direction: None,
2256 causal_claim: None,
2257 causal_evidence_grade: None,
2258 };
2259 let prov = sample_provenance();
2260 let id1 = FindingBundle::content_address(&assertion1, &prov);
2261 let id2 = FindingBundle::content_address(&assertion2, &prov);
2262 assert_eq!(
2263 id1, id2,
2264 "Whitespace and trailing punctuation should be normalized away"
2265 );
2266 }
2267
2268 #[test]
2269 fn content_address_falls_back_to_title_when_no_doi() {
2270 let assertion = sample_assertion();
2271 let mut prov = sample_provenance();
2272 prov.doi = None;
2273 prov.title = "Fallback Title".into();
2274 let id = FindingBundle::content_address(&assertion, &prov);
2275 assert!(id.starts_with("vf_"));
2276 assert_eq!(id.len(), 19); let mut prov2 = sample_provenance();
2280 prov2.doi = None;
2281 prov2.title = "Fallback Title".into();
2282 let id2 = FindingBundle::content_address(&assertion, &prov2);
2283 assert_eq!(id, id2);
2284 }
2285
2286 #[test]
2287 fn content_address_prefers_doi_over_title() {
2288 let assertion = sample_assertion();
2289
2290 let mut prov_doi = sample_provenance();
2291 prov_doi.doi = Some("10.1234/test".into());
2292 prov_doi.title = "Title".into();
2293
2294 let mut prov_title = sample_provenance();
2295 prov_title.doi = None;
2296 prov_title.title = "Title".into();
2297
2298 let id_doi = FindingBundle::content_address(&assertion, &prov_doi);
2299 let id_title = FindingBundle::content_address(&assertion, &prov_title);
2300
2301 assert_ne!(id_doi, id_title, "DOI vs title should differ");
2302 }
2303
2304 #[test]
2305 fn parses_bbb_review_event_with_richer_schema() {
2306 let raw = include_str!("../../embedded/tests/fixtures/legacy/rev_001_bbb_correction.json");
2307 let review: ReviewEvent = serde_json::from_str(raw).unwrap();
2308
2309 assert_eq!(review.id, "rev_001_bbb_correction");
2310 assert_eq!(review.workspace.as_deref(), Some("projects/bbb-flagship"));
2311 assert_eq!(review.scope.as_deref(), Some("bbb_opening_trusted_subset"));
2312 assert_eq!(review.status.as_deref(), Some("accepted"));
2313 assert!(matches!(
2314 review.action,
2315 ReviewAction::Qualified { ref target } if target == "trusted_interpretation"
2316 ));
2317 assert_eq!(review.evidence_considered.len(), 3);
2318 assert_eq!(
2319 review.evidence_considered[0].role.as_deref(),
2320 Some("qualifier")
2321 );
2322 assert_eq!(
2323 review
2324 .state_change
2325 .as_ref()
2326 .and_then(|value| value.get("assumption_retired"))
2327 .and_then(|value| value.as_str()),
2328 Some("safe opening implies therapeutic efficacy")
2329 );
2330 }
2331
2332 #[test]
2333 fn artifact_requires_sha256_and_stable_kind() {
2334 let artifact = Artifact::new(
2335 "clinical_trial_record",
2336 "AHEAD 3-45",
2337 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
2338 Some(42),
2339 Some("application/json".into()),
2340 "local_blob",
2341 Some(".vela/artifact-blobs/sha256/aaaaaaaa".into()),
2342 Some("https://clinicaltrials.gov/study/NCT04468659".into()),
2343 Some("ClinicalTrials.gov public record".into()),
2344 vec!["vf_demo".into()],
2345 sample_provenance(),
2346 BTreeMap::new(),
2347 crate::access_tier::AccessTier::Public,
2348 )
2349 .unwrap();
2350
2351 assert!(artifact.id.starts_with("va_"));
2352 assert_eq!(
2353 artifact.content_hash,
2354 "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
2355 );
2356 assert_eq!(artifact.kind, "clinical_trial_record");
2357 }
2358
2359 #[test]
2360 fn artifact_reference_axes_are_independent_and_content_bound() {
2361 let hash = format!("sha256:{}", "a".repeat(64));
2362 let legacy = Artifact::content_address(
2363 "dataset",
2364 "public data",
2365 &hash,
2366 None,
2367 Some("https://example.test/data"),
2368 );
2369 let all_unknown = Artifact::content_address_with_axes(
2370 "dataset",
2371 "public data",
2372 &hash,
2373 None,
2374 Some("https://example.test/data"),
2375 ArtifactDisclosure::Unknown,
2376 LocatorIntegrity::Unknown,
2377 ArtifactAvailability::Unknown,
2378 );
2379 assert_eq!(legacy, all_unknown);
2380
2381 let immutable = Artifact::content_address_with_axes(
2382 "dataset",
2383 "public data",
2384 &hash,
2385 None,
2386 Some("https://example.test/data"),
2387 ArtifactDisclosure::Public,
2388 LocatorIntegrity::Immutable,
2389 ArtifactAvailability::Available,
2390 );
2391 let mutable = Artifact::content_address_with_axes(
2392 "dataset",
2393 "public data",
2394 &hash,
2395 None,
2396 Some("https://example.test/data"),
2397 ArtifactDisclosure::Public,
2398 LocatorIntegrity::Mutable,
2399 ArtifactAvailability::Available,
2400 );
2401 assert_ne!(immutable, mutable);
2402 }
2403
2404 #[test]
2405 fn restricted_reference_refuses_public_equality_digest() {
2406 let mut artifact = Artifact::new(
2407 "dataset",
2408 "restricted data",
2409 "a".repeat(64),
2410 None,
2411 None,
2412 "pointer",
2413 Some("custodian:lab-vault/item-7".to_string()),
2414 None,
2415 None,
2416 vec![],
2417 sample_provenance(),
2418 BTreeMap::new(),
2419 crate::access_tier::AccessTier::Restricted,
2420 )
2421 .unwrap();
2422 artifact.disclosure = ArtifactDisclosure::Restricted;
2423 artifact.locator_integrity = LocatorIntegrity::Immutable;
2424 artifact.availability = ArtifactAvailability::Unknown;
2425 assert!(artifact.validate_reference_axes().is_err());
2426
2427 artifact.content_hash.clear();
2428 assert!(artifact.validate_reference_axes().is_ok());
2429 }
2430}