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];
96
97pub const VALID_LINK_TYPES: &[&str] = &[
109 "supports",
110 "contradicts",
111 "extends",
112 "depends",
113 "replicates",
114 "supersedes",
115 "synthesized_from",
116 "improves",
118 "generalizes",
119 "specializes",
120 "discharges",
122];
123
124#[must_use]
129pub fn bare_finding_id(target: &str) -> &str {
130 target.split('@').next().unwrap_or(target)
131}
132
133#[derive(Debug, Clone, Serialize, Deserialize)]
135pub struct ResolvedId {
136 pub source: String,
138 pub id: String,
140 pub confidence: f64,
142 #[serde(default, skip_serializing_if = "Option::is_none")]
144 pub matched_name: Option<String>,
145}
146
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
149#[serde(rename_all = "snake_case")]
150pub enum ResolutionMethod {
151 ExactMatch,
152 FuzzyMatch,
153 LlmInference,
154 Manual,
155}
156
157impl std::fmt::Display for ResolutionMethod {
158 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
159 match self {
160 ResolutionMethod::ExactMatch => write!(f, "exact_match"),
161 ResolutionMethod::FuzzyMatch => write!(f, "fuzzy_match"),
162 ResolutionMethod::LlmInference => write!(f, "llm_inference"),
163 ResolutionMethod::Manual => write!(f, "manual"),
164 }
165 }
166}
167
168#[derive(Debug, Clone, Serialize, Deserialize)]
169pub struct Entity {
170 pub name: String,
171 #[serde(rename = "type")]
172 pub entity_type: String,
173 #[serde(default)]
176 pub identifiers: serde_json::Map<String, serde_json::Value>,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub canonical_id: Option<ResolvedId>,
180 #[serde(default)]
182 pub candidates: Vec<ResolvedId>,
183 #[serde(default)]
185 pub aliases: Vec<String>,
186 #[serde(default, skip_serializing_if = "Option::is_none")]
188 pub resolution_provenance: Option<String>,
189 #[serde(default = "default_one")]
190 pub resolution_confidence: f64,
191 #[serde(default, skip_serializing_if = "Option::is_none")]
193 pub resolution_method: Option<ResolutionMethod>,
194 #[serde(default, skip_serializing_if = "Option::is_none")]
196 pub species_context: Option<String>,
197 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
199 pub needs_review: bool,
200}
201
202fn default_one() -> f64 {
203 1.0
204}
205
206#[derive(Debug, Clone, Serialize, Deserialize)]
207pub struct Evidence {
208 #[serde(rename = "type")]
209 pub evidence_type: String,
210 #[serde(default)]
211 pub model_system: String,
212 #[serde(default)]
213 pub method: String,
214 #[serde(default)]
218 pub replicated: bool,
219 pub replication_count: Option<u32>,
220 #[serde(default)]
221 pub evidence_spans: Vec<serde_json::Value>,
222}
223
224#[derive(Debug, Clone, Serialize, Deserialize)]
239pub struct Dataset {
240 pub id: String,
242 pub name: String,
244 pub version: Option<String>,
247 #[serde(default)]
250 pub schema: Vec<(String, String)>,
251 pub row_count: Option<u64>,
253 pub content_hash: String,
258 pub url: Option<String>,
260 pub license: Option<String>,
262 pub provenance: Provenance,
266 pub created: String,
268}
269
270impl Dataset {
271 pub fn content_address(
275 name: &str,
276 version: Option<&str>,
277 content_hash: &str,
278 url: Option<&str>,
279 ) -> String {
280 let preimage = format!(
281 "{}|{}|{}|{}",
282 name,
283 version.unwrap_or(""),
284 content_hash,
285 url.unwrap_or("")
286 );
287 let hash = Sha256::digest(preimage.as_bytes());
288 format!("vd_{}", &hex::encode(hash)[..16])
289 }
290
291 pub fn new(
294 name: impl Into<String>,
295 version: Option<String>,
296 content_hash: impl Into<String>,
297 url: Option<String>,
298 license: Option<String>,
299 provenance: Provenance,
300 ) -> Self {
301 let n = name.into();
302 let h = content_hash.into();
303 let id = Self::content_address(&n, version.as_deref(), &h, url.as_deref());
304 Self {
305 id,
306 name: n,
307 version,
308 schema: Vec::new(),
309 row_count: None,
310 content_hash: h,
311 url,
312 license,
313 provenance,
314 created: Utc::now().to_rfc3339(),
315 }
316 }
317}
318
319#[derive(Debug, Clone, Serialize, Deserialize)]
334pub struct CodeArtifact {
335 pub id: String,
337 pub language: String,
341 pub repo_url: Option<String>,
343 pub git_commit: Option<String>,
347 pub path: String,
349 pub line_range: Option<(u32, u32)>,
351 pub content_hash: String,
355 pub entry_point: Option<String>,
358 pub created: String,
360}
361
362impl CodeArtifact {
363 pub fn content_address(
367 repo_url: Option<&str>,
368 git_commit: Option<&str>,
369 path: &str,
370 line_range: Option<(u32, u32)>,
371 content_hash: &str,
372 ) -> String {
373 let lr = line_range
374 .map(|(a, b)| format!("{a}-{b}"))
375 .unwrap_or_default();
376 let preimage = format!(
377 "{}|{}|{}|{}|{}",
378 repo_url.unwrap_or(""),
379 git_commit.unwrap_or(""),
380 path,
381 lr,
382 content_hash
383 );
384 let hash = Sha256::digest(preimage.as_bytes());
385 format!("vc_{}", &hex::encode(hash)[..16])
386 }
387
388 pub fn new(
391 language: impl Into<String>,
392 repo_url: Option<String>,
393 git_commit: Option<String>,
394 path: impl Into<String>,
395 line_range: Option<(u32, u32)>,
396 content_hash: impl Into<String>,
397 entry_point: Option<String>,
398 ) -> Self {
399 let p = path.into();
400 let h = content_hash.into();
401 let id = Self::content_address(
402 repo_url.as_deref(),
403 git_commit.as_deref(),
404 &p,
405 line_range,
406 &h,
407 );
408 Self {
409 id,
410 language: language.into(),
411 repo_url,
412 git_commit,
413 path: p,
414 line_range,
415 content_hash: h,
416 entry_point,
417 created: Utc::now().to_rfc3339(),
418 }
419 }
420}
421
422#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
431#[serde(rename_all = "snake_case")]
432pub enum ArtifactDisclosure {
433 Public,
434 Restricted,
435 #[default]
436 Unknown,
437}
438
439impl ArtifactDisclosure {
440 pub(crate) fn is_unknown(value: &Self) -> bool {
441 *value == Self::Unknown
442 }
443}
444
445#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
446#[serde(rename_all = "snake_case")]
447pub enum LocatorIntegrity {
448 Immutable,
449 Mutable,
450 #[default]
451 Unknown,
452}
453
454impl LocatorIntegrity {
455 pub(crate) fn is_unknown(value: &Self) -> bool {
456 *value == Self::Unknown
457 }
458}
459
460#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
461#[serde(rename_all = "snake_case")]
462pub enum ArtifactAvailability {
463 Available,
464 Unavailable,
465 #[default]
466 Unknown,
467}
468
469impl ArtifactAvailability {
470 pub(crate) fn is_unknown(value: &Self) -> bool {
471 *value == Self::Unknown
472 }
473}
474
475#[derive(Debug, Clone, Serialize, Deserialize)]
476pub struct Artifact {
477 pub id: String,
480 pub kind: String,
482 pub name: String,
484 pub content_hash: String,
486 #[serde(default, skip_serializing_if = "Option::is_none")]
488 pub size_bytes: Option<u64>,
489 #[serde(default, skip_serializing_if = "Option::is_none")]
491 pub media_type: Option<String>,
492 pub storage_mode: String,
494 #[serde(default, skip_serializing_if = "ArtifactDisclosure::is_unknown")]
497 pub disclosure: ArtifactDisclosure,
498 #[serde(default, skip_serializing_if = "LocatorIntegrity::is_unknown")]
500 pub locator_integrity: LocatorIntegrity,
501 #[serde(default, skip_serializing_if = "ArtifactAvailability::is_unknown")]
503 pub availability: ArtifactAvailability,
504 #[serde(default, skip_serializing_if = "Option::is_none")]
506 pub locator: Option<String>,
507 #[serde(default, skip_serializing_if = "Option::is_none")]
509 pub source_url: Option<String>,
510 #[serde(default, skip_serializing_if = "Option::is_none")]
512 pub license: Option<String>,
513 #[serde(default, skip_serializing_if = "Vec::is_empty")]
515 pub target_findings: Vec<String>,
516 #[serde(default, skip_serializing_if = "Option::is_none")]
519 pub source_id: Option<String>,
520 pub provenance: Provenance,
523 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
526 pub metadata: BTreeMap<String, Value>,
527 #[serde(default, skip_serializing_if = "Option::is_none")]
529 pub review_state: Option<ReviewState>,
530 #[serde(default)]
531 pub retracted: bool,
532 #[serde(default)]
533 pub access_tier: crate::access_tier::AccessTier,
534 pub created: String,
536}
537
538impl Artifact {
539 pub fn content_address(
540 kind: &str,
541 name: &str,
542 content_hash: &str,
543 source_url: Option<&str>,
544 locator: Option<&str>,
545 ) -> String {
546 let preimage = format!(
547 "{}|{}|{}|{}|{}",
548 kind,
549 name,
550 content_hash,
551 source_url.unwrap_or(""),
552 locator.unwrap_or("")
553 );
554 let hash = Sha256::digest(preimage.as_bytes());
555 format!("va_{}", &hex::encode(hash)[..16])
556 }
557
558 #[allow(clippy::too_many_arguments)]
562 pub fn content_address_with_axes(
563 kind: &str,
564 name: &str,
565 content_hash: &str,
566 source_url: Option<&str>,
567 locator: Option<&str>,
568 disclosure: ArtifactDisclosure,
569 locator_integrity: LocatorIntegrity,
570 availability: ArtifactAvailability,
571 ) -> String {
572 if disclosure == ArtifactDisclosure::Unknown
573 && locator_integrity == LocatorIntegrity::Unknown
574 && availability == ArtifactAvailability::Unknown
575 {
576 return Self::content_address(kind, name, content_hash, source_url, locator);
577 }
578 let preimage = crate::canonical::to_canonical_bytes(&serde_json::json!({
579 "schema": "vela.artifact-reference-axes.v1",
580 "kind": kind,
581 "name": name,
582 "content_hash": content_hash,
583 "source_url": source_url,
584 "locator": locator,
585 "disclosure": disclosure,
586 "locator_integrity": locator_integrity,
587 "availability": availability,
588 }))
589 .unwrap_or_default();
590 let hash = Sha256::digest(preimage);
591 format!("va_{}", &hex::encode(hash)[..16])
592 }
593
594 pub fn validate_reference_axes(&self) -> Result<(), String> {
599 match self.disclosure {
600 ArtifactDisclosure::Public => {
601 let digest = self.content_hash.strip_prefix("sha256:").ok_or_else(|| {
602 "public artifact content_hash must be sha256:<64 lowercase hex>".to_string()
603 })?;
604 if digest.len() != 64
605 || !digest
606 .bytes()
607 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
608 {
609 return Err(
610 "public artifact content_hash must be sha256:<64 lowercase hex>"
611 .to_string(),
612 );
613 }
614 }
615 ArtifactDisclosure::Restricted => {
616 if !self.content_hash.is_empty() {
617 return Err(
618 "restricted artifact must use an opaque custodian reference; public digest disclosure requires a separately reviewed commitment scheme"
619 .to_string(),
620 );
621 }
622 let locator = self.locator.as_deref().unwrap_or_default();
623 if locator.trim().is_empty()
624 || !(locator.starts_with("custodian:") || locator.starts_with("opaque:"))
625 {
626 return Err(
627 "restricted artifact requires an opaque custodian: or opaque: locator"
628 .to_string(),
629 );
630 }
631 }
632 ArtifactDisclosure::Unknown => {}
633 }
634 if self.storage_mode == "local_blob"
635 && self.availability == ArtifactAvailability::Unavailable
636 {
637 return Err("local_blob artifact cannot be declared unavailable".to_string());
638 }
639 Ok(())
640 }
641
642 #[allow(clippy::too_many_arguments)]
643 pub fn new(
644 kind: impl Into<String>,
645 name: impl Into<String>,
646 content_hash: impl Into<String>,
647 size_bytes: Option<u64>,
648 media_type: Option<String>,
649 storage_mode: impl Into<String>,
650 locator: Option<String>,
651 source_url: Option<String>,
652 license: Option<String>,
653 target_findings: Vec<String>,
654 provenance: Provenance,
655 metadata: BTreeMap<String, Value>,
656 access_tier: crate::access_tier::AccessTier,
657 ) -> Result<Self, String> {
658 let kind = kind.into();
659 if !valid_artifact_kind(&kind) {
660 return Err(format!(
661 "artifact kind '{kind}' is not supported; valid: {}",
662 VALID_ARTIFACT_KINDS.join(", ")
663 ));
664 }
665 let name = name.into();
666 if name.trim().is_empty() {
667 return Err("artifact name must be non-empty".to_string());
668 }
669 let content_hash = normalize_sha256(content_hash.into())?;
670 let storage_mode = storage_mode.into();
671 if !matches!(
672 storage_mode.as_str(),
673 "local_blob" | "local_file" | "remote" | "pointer"
674 ) {
675 return Err(format!(
676 "artifact storage_mode '{storage_mode}' is not supported; valid: local_blob, local_file, remote, pointer"
677 ));
678 }
679 let id = Self::content_address(
680 &kind,
681 &name,
682 &content_hash,
683 source_url.as_deref(),
684 locator.as_deref(),
685 );
686 Ok(Self {
687 id,
688 kind,
689 name,
690 content_hash,
691 size_bytes,
692 media_type,
693 storage_mode,
694 disclosure: ArtifactDisclosure::Unknown,
695 locator_integrity: LocatorIntegrity::Unknown,
696 availability: ArtifactAvailability::Unknown,
697 locator,
698 source_url,
699 license,
700 target_findings,
701 source_id: None,
702 provenance,
703 metadata,
704 review_state: None,
705 retracted: false,
706 access_tier,
707 created: Utc::now().to_rfc3339(),
708 })
709 }
710}
711
712fn normalize_sha256(value: String) -> Result<String, String> {
713 let trimmed = value.trim();
714 let hex = trimmed.strip_prefix("sha256:").unwrap_or(trimmed);
715 if hex.len() != 64 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
716 return Err(format!(
717 "content_hash must be sha256:<64hex> or 64 hex chars, got {trimmed:?}"
718 ));
719 }
720 Ok(format!("sha256:{}", hex.to_ascii_lowercase()))
721}
722
723#[derive(Debug, Clone, Serialize, Deserialize)]
724pub struct Conditions {
725 #[serde(default)]
726 pub text: String,
727 pub duration: Option<String>,
733}
734
735#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
737#[serde(rename_all = "snake_case")]
738#[derive(Default)]
739pub enum ConfidenceMethod {
740 Computed,
742 ExpertJudgment,
744 #[default]
746 LlmInitial,
747}
748
749#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
751#[serde(rename_all = "snake_case")]
752pub enum ConfidenceKind {
753 #[default]
755 FrontierEpistemic,
756}
757
758#[derive(Debug, Clone, Serialize, Deserialize)]
759pub struct Confidence {
760 #[serde(default)]
762 pub kind: ConfidenceKind,
763 pub score: f64,
764 pub basis: String,
765 #[serde(default)]
767 pub method: ConfidenceMethod,
768 #[serde(default = "default_extraction_conf")]
770 pub extraction_confidence: f64,
771}
772
773fn default_extraction_conf() -> f64 {
774 0.85
775}
776
777impl Confidence {
778 pub fn raw(score: f64, basis: impl Into<String>, extraction_confidence: f64) -> Self {
787 Self {
788 kind: ConfidenceKind::FrontierEpistemic,
789 score,
790 basis: basis.into(),
791 method: ConfidenceMethod::LlmInitial,
792 extraction_confidence,
793 }
794 }
795}
796
797#[derive(Debug, Clone, Default, Serialize, Deserialize)]
798pub struct Extraction {
799 #[serde(default = "default_extraction_method")]
800 pub method: String,
801 pub model: Option<String>,
802 pub model_version: Option<String>,
803 #[serde(default)]
804 pub extracted_at: String,
805 #[serde(default = "default_extractor_version")]
806 pub extractor_version: String,
807}
808
809fn default_extraction_method() -> String {
810 "llm_extraction".into()
811}
812fn default_extractor_version() -> String {
813 "vela/0.2.0".into()
814}
815
816#[derive(Debug, Clone, Serialize, Deserialize)]
817pub struct Review {
818 #[serde(default)]
819 pub reviewed: bool,
820 pub reviewer: Option<String>,
821 pub reviewed_at: Option<String>,
822 #[serde(default)]
823 pub corrections: Vec<serde_json::Value>,
824}
825
826#[derive(Debug, Clone, Serialize, Deserialize)]
827pub struct Author {
828 pub name: String,
829 pub orcid: Option<String>,
830}
831
832#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
834#[serde(rename_all = "snake_case")]
835pub enum ContributionUnitType {
836 EvidenceSpan,
838 LeanDecl,
840 Step,
842 Whole,
844}
845
846#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
849#[serde(rename_all = "snake_case")]
850pub enum AgentKind {
851 Human,
852 Agent,
853 Model,
854}
855
856#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
859#[serde(rename_all = "snake_case")]
860pub enum ContributionRole {
861 Originated,
862 Derived,
863 Formalized,
864 Extracted,
865 Reviewed,
866 Vouched,
867}
868
869#[derive(Debug, Clone, Serialize, Deserialize)]
874pub struct Contribution {
875 pub unit: String,
878 pub unit_type: ContributionUnitType,
879 pub agent_kind: AgentKind,
880 pub agent_id: String,
882 #[serde(default, skip_serializing_if = "Option::is_none")]
883 pub model: Option<String>,
884 #[serde(default, skip_serializing_if = "Option::is_none")]
885 pub model_version: Option<String>,
886 pub role: ContributionRole,
887 #[serde(default, skip_serializing_if = "String::is_empty")]
889 pub basis: String,
890}
891
892impl AgentKind {
893 #[must_use]
894 pub fn as_str(&self) -> &'static str {
895 match self {
896 Self::Human => "human",
897 Self::Agent => "agent",
898 Self::Model => "model",
899 }
900 }
901}
902
903impl ContributionRole {
904 #[must_use]
905 pub fn as_str(&self) -> &'static str {
906 match self {
907 Self::Originated => "originated",
908 Self::Derived => "derived",
909 Self::Formalized => "formalized",
910 Self::Extracted => "extracted",
911 Self::Reviewed => "reviewed",
912 Self::Vouched => "vouched",
913 }
914 }
915}
916
917impl Contribution {
918 pub fn validate(&self) -> Result<(), String> {
921 if self.role == ContributionRole::Vouched && self.agent_kind != AgentKind::Human {
922 return Err(
923 "a contribution with role `vouched` must be a human (agents and models hold no key)"
924 .to_string(),
925 );
926 }
927 if self.unit.trim().is_empty() {
928 return Err("contribution `unit` must be non-empty".to_string());
929 }
930 if self.agent_id.trim().is_empty() {
931 return Err("contribution `agent_id` must be non-empty".to_string());
932 }
933 Ok(())
934 }
935}
936
937#[derive(Debug, Clone, Serialize, Deserialize)]
938pub struct Provenance {
939 #[serde(default = "default_source_type")]
940 pub source_type: String,
941 pub doi: Option<String>,
942 #[serde(default, skip_serializing_if = "Option::is_none")]
951 pub url: Option<String>,
952 #[serde(default)]
953 pub title: String,
954 #[serde(default)]
955 pub authors: Vec<Author>,
956 pub year: Option<i32>,
957 #[serde(default, skip_serializing_if = "Option::is_none")]
959 pub license: Option<String>,
960 #[serde(default, skip_serializing_if = "Option::is_none")]
962 pub publisher: Option<String>,
963 #[serde(default, skip_serializing_if = "Vec::is_empty")]
965 pub funders: Vec<String>,
966 #[serde(default)]
967 pub extraction: Extraction,
968 pub review: Option<Review>,
969 #[serde(default, skip_serializing_if = "Vec::is_empty")]
975 pub contributions: Vec<Contribution>,
976}
977
978fn default_source_type() -> String {
979 "published_paper".into()
980}
981
982#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
986#[serde(rename_all = "snake_case")]
987pub enum ReviewState {
988 Accepted,
990 Contested,
992 NeedsRevision,
995 Rejected,
998}
999
1000impl ReviewState {
1001 #[must_use]
1004 pub fn implies_contested(&self) -> bool {
1005 matches!(
1006 self,
1007 ReviewState::Contested | ReviewState::NeedsRevision | ReviewState::Rejected
1008 )
1009 }
1010}
1011
1012#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1013pub struct Flags {
1014 #[serde(default)]
1015 pub gap: bool,
1016 #[serde(default)]
1017 pub negative_space: bool,
1018 #[serde(default)]
1022 pub contested: bool,
1023 #[serde(default)]
1024 pub retracted: bool,
1025 #[serde(default)]
1026 pub declining: bool,
1027 #[serde(default)]
1028 pub gravity_well: bool,
1029 #[serde(default, skip_serializing_if = "Option::is_none")]
1033 pub review_state: Option<ReviewState>,
1034 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1039 pub superseded: bool,
1040 #[serde(default, skip_serializing_if = "Option::is_none")]
1049 pub signature_threshold: Option<u32>,
1050 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1055 pub jointly_accepted: bool,
1056}
1057
1058#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1072#[serde(rename_all = "snake_case")]
1073pub enum CausalClaim {
1074 Correlation,
1076 Mediation,
1078 Intervention,
1080}
1081
1082#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1088#[serde(rename_all = "snake_case")]
1089pub enum CausalEvidenceGrade {
1090 Rct,
1092 QuasiExperimental,
1095 Observational,
1098 Theoretical,
1100}
1101
1102pub const VALID_CAUSAL_CLAIMS: &[&str] = &["correlation", "mediation", "intervention"];
1105
1106pub const VALID_CAUSAL_EVIDENCE_GRADES: &[&str] =
1108 &["rct", "quasi_experimental", "observational", "theoretical"];
1109
1110#[derive(Debug, Clone, Serialize, Deserialize)]
1111pub struct Assertion {
1112 pub text: String,
1113 #[serde(rename = "type")]
1114 pub assertion_type: String,
1115 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1120 pub entities: Vec<Entity>,
1121 pub relation: Option<String>,
1122 pub direction: Option<String>,
1123 #[serde(default, skip_serializing_if = "Option::is_none")]
1128 pub causal_claim: Option<CausalClaim>,
1129 #[serde(default, skip_serializing_if = "Option::is_none")]
1133 pub causal_evidence_grade: Option<CausalEvidenceGrade>,
1134}
1135
1136#[derive(Debug, Clone, Serialize, Deserialize)]
1137pub struct Link {
1138 pub target: String,
1139 #[serde(rename = "type")]
1140 pub link_type: String,
1141 #[serde(default)]
1142 pub note: String,
1143 #[serde(default = "default_compiler")]
1144 pub inferred_by: String,
1145 #[serde(default)]
1147 pub created_at: String,
1148 #[serde(default, skip_serializing_if = "Option::is_none")]
1155 pub mechanism: Option<Mechanism>,
1156}
1157
1158fn default_compiler() -> String {
1159 "compiler".into()
1160}
1161
1162#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
1188#[serde(tag = "kind", rename_all = "snake_case")]
1189pub enum Mechanism {
1190 Linear {
1191 sign: MechanismSign,
1192 slope: f64,
1194 },
1195 Monotonic {
1196 sign: MechanismSign,
1197 },
1198 Threshold {
1199 sign: MechanismSign,
1200 threshold: f64,
1201 },
1202 Saturating {
1203 sign: MechanismSign,
1204 half_max: f64,
1205 },
1206 Unknown,
1207}
1208
1209#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1214#[serde(rename_all = "lowercase")]
1215pub enum MechanismSign {
1216 Positive,
1217 Negative,
1218}
1219
1220impl MechanismSign {
1221 #[must_use]
1222 pub fn as_f64(self) -> f64 {
1223 match self {
1224 Self::Positive => 1.0,
1225 Self::Negative => -1.0,
1226 }
1227 }
1228}
1229
1230impl Mechanism {
1231 #[must_use]
1235 pub fn apply(&self, delta_x: f64) -> Option<f64> {
1236 match *self {
1237 Self::Linear { sign, slope } => Some(sign.as_f64() * slope * delta_x),
1238 Self::Monotonic { sign } => {
1239 Some(sign.as_f64() * delta_x.signum() * delta_x.abs().min(1.0))
1240 }
1241 Self::Threshold { sign, threshold } => {
1242 if delta_x.abs() >= threshold {
1243 Some(sign.as_f64() * delta_x.signum())
1244 } else {
1245 Some(0.0)
1246 }
1247 }
1248 Self::Saturating { sign, half_max } => {
1249 let denom = delta_x.abs() + half_max.max(1e-9);
1251 Some(sign.as_f64() * delta_x / denom)
1252 }
1253 Self::Unknown => None,
1254 }
1255 }
1256}
1257
1258#[derive(Debug, Clone, PartialEq, Eq)]
1266pub enum LinkRef {
1267 Local { vf_id: String },
1269 Cross { vf_id: String, vfr_id: String },
1273}
1274
1275#[derive(Debug, Clone, PartialEq, Eq)]
1276pub enum LinkParseError {
1277 Empty,
1278 BadVfPrefix,
1279 BadVfrPrefix,
1280 EmptyVfId,
1281 EmptyVfrId,
1282 TooManyAtSigns,
1283}
1284
1285impl std::fmt::Display for LinkParseError {
1286 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1287 match self {
1288 LinkParseError::Empty => write!(f, "empty link target"),
1289 LinkParseError::BadVfPrefix => write!(f, "link target must start with 'vf_'"),
1290 LinkParseError::BadVfrPrefix => {
1291 write!(f, "cross-frontier suffix must start with 'vfr_'")
1292 }
1293 LinkParseError::EmptyVfId => write!(f, "link target's vf_ id is empty"),
1294 LinkParseError::EmptyVfrId => write!(f, "cross-frontier vfr_ id is empty"),
1295 LinkParseError::TooManyAtSigns => {
1296 write!(f, "link target has more than one '@' separator")
1297 }
1298 }
1299 }
1300}
1301
1302impl std::error::Error for LinkParseError {}
1303
1304impl LinkRef {
1305 pub fn parse(s: &str) -> Result<Self, LinkParseError> {
1310 if s.is_empty() {
1311 return Err(LinkParseError::Empty);
1312 }
1313 let mut parts = s.split('@');
1314 let local = parts.next().ok_or(LinkParseError::Empty)?;
1315 let remote = parts.next();
1316 if parts.next().is_some() {
1317 return Err(LinkParseError::TooManyAtSigns);
1318 }
1319 let vf_id = local
1320 .strip_prefix("vf_")
1321 .ok_or(LinkParseError::BadVfPrefix)?;
1322 if vf_id.is_empty() {
1323 return Err(LinkParseError::EmptyVfId);
1324 }
1325 match remote {
1326 None => Ok(LinkRef::Local {
1327 vf_id: local.to_string(),
1328 }),
1329 Some(r) => {
1330 let vfr_id = r.strip_prefix("vfr_").ok_or(LinkParseError::BadVfrPrefix)?;
1331 if vfr_id.is_empty() {
1332 return Err(LinkParseError::EmptyVfrId);
1333 }
1334 Ok(LinkRef::Cross {
1335 vf_id: local.to_string(),
1336 vfr_id: r.to_string(),
1337 })
1338 }
1339 }
1340 }
1341
1342 pub fn format(&self) -> String {
1344 match self {
1345 LinkRef::Local { vf_id } => vf_id.clone(),
1346 LinkRef::Cross { vf_id, vfr_id } => format!("{vf_id}@{vfr_id}"),
1347 }
1348 }
1349
1350 pub fn is_cross_frontier(&self) -> bool {
1352 matches!(self, LinkRef::Cross { .. })
1353 }
1354}
1355
1356#[cfg(test)]
1357mod link_ref_tests {
1358 use super::*;
1359
1360 #[test]
1361 fn parses_local_vf_id() {
1362 let r = LinkRef::parse("vf_abc123").unwrap();
1363 assert_eq!(
1364 r,
1365 LinkRef::Local {
1366 vf_id: "vf_abc123".into()
1367 }
1368 );
1369 assert_eq!(r.format(), "vf_abc123");
1370 assert!(!r.is_cross_frontier());
1371 }
1372
1373 #[test]
1374 fn parses_cross_frontier_target() {
1375 let r = LinkRef::parse("vf_abc@vfr_def").unwrap();
1376 assert_eq!(
1377 r,
1378 LinkRef::Cross {
1379 vf_id: "vf_abc".into(),
1380 vfr_id: "vfr_def".into(),
1381 }
1382 );
1383 assert_eq!(r.format(), "vf_abc@vfr_def");
1384 assert!(r.is_cross_frontier());
1385 }
1386
1387 #[test]
1388 fn rejects_empty() {
1389 assert_eq!(LinkRef::parse(""), Err(LinkParseError::Empty));
1390 }
1391
1392 #[test]
1393 fn rejects_missing_vf_prefix() {
1394 assert_eq!(LinkRef::parse("xx_abc"), Err(LinkParseError::BadVfPrefix));
1395 }
1396
1397 #[test]
1398 fn rejects_empty_vf_id() {
1399 assert_eq!(LinkRef::parse("vf_"), Err(LinkParseError::EmptyVfId));
1400 }
1401
1402 #[test]
1403 fn rejects_missing_vfr_prefix_after_at() {
1404 assert_eq!(
1405 LinkRef::parse("vf_abc@xxx_def"),
1406 Err(LinkParseError::BadVfrPrefix)
1407 );
1408 }
1409
1410 #[test]
1411 fn rejects_empty_vfr_id() {
1412 assert_eq!(
1413 LinkRef::parse("vf_abc@vfr_"),
1414 Err(LinkParseError::EmptyVfrId)
1415 );
1416 }
1417
1418 #[test]
1419 fn rejects_double_at() {
1420 assert_eq!(
1421 LinkRef::parse("vf_abc@vfr_def@x"),
1422 Err(LinkParseError::TooManyAtSigns)
1423 );
1424 }
1425
1426 #[test]
1427 fn round_trips_real_ids() {
1428 for s in [
1429 "vf_d0a962d3251133dd",
1430 "vf_d0a962d3251133dd@vfr_7344e96c0f2669d5",
1431 ] {
1432 assert_eq!(LinkRef::parse(s).unwrap().format(), s);
1433 }
1434 }
1435}
1436
1437#[derive(Debug, Clone, Serialize, Deserialize)]
1439pub struct Annotation {
1440 pub id: String,
1442 pub text: String,
1444 pub author: String,
1446 pub timestamp: String,
1448 #[serde(default, skip_serializing_if = "Option::is_none")]
1454 pub provenance: Option<ProvenanceRef>,
1455}
1456
1457#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1463pub struct ProvenanceRef {
1464 #[serde(default, skip_serializing_if = "Option::is_none")]
1465 pub doi: Option<String>,
1466 #[serde(default, skip_serializing_if = "Option::is_none")]
1467 pub pmid: Option<String>,
1468 #[serde(default, skip_serializing_if = "Option::is_none")]
1469 pub title: Option<String>,
1470 #[serde(default, skip_serializing_if = "Option::is_none")]
1472 pub span: Option<String>,
1473}
1474
1475impl ProvenanceRef {
1476 #[must_use]
1479 pub fn has_identifier(&self) -> bool {
1480 self.doi.is_some() || self.pmid.is_some() || self.title.is_some()
1481 }
1482}
1483
1484#[derive(Debug, Clone, Serialize, Deserialize)]
1486pub struct Attachment {
1487 pub filename: String,
1488 pub label: Option<String>,
1489 pub path: String,
1490 pub size_bytes: u64,
1491 pub mime_type: Option<String>,
1492 pub attached_at: String,
1493 pub attached_by: Option<String>,
1494}
1495
1496#[derive(Debug, Clone, Serialize, Deserialize)]
1501pub struct ReviewEvent {
1502 pub id: String,
1504 #[serde(default, skip_serializing_if = "Option::is_none")]
1506 pub workspace: Option<String>,
1507 pub finding_id: String,
1509 pub reviewer: String,
1511 pub reviewed_at: String,
1513 #[serde(default, skip_serializing_if = "Option::is_none")]
1515 pub scope: Option<String>,
1516 #[serde(default, skip_serializing_if = "Option::is_none")]
1518 pub status: Option<String>,
1519 pub action: ReviewAction,
1521 #[serde(default)]
1523 pub reason: String,
1524 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1526 pub evidence_considered: Vec<ReviewEvidence>,
1527 #[serde(default, skip_serializing_if = "Option::is_none")]
1529 pub state_change: Option<serde_json::Value>,
1530}
1531
1532#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1533pub struct ReviewEvidence {
1534 pub finding_id: String,
1535 #[serde(default, skip_serializing_if = "Option::is_none")]
1536 pub role: Option<String>,
1537 #[serde(default, skip_serializing_if = "Option::is_none")]
1538 pub note: Option<String>,
1539}
1540
1541#[derive(Debug, Clone, Serialize, Deserialize)]
1543#[serde(tag = "type", rename_all = "snake_case")]
1544pub enum ReviewAction {
1545 Approved,
1547 Qualified { target: String },
1549 Corrected {
1551 field: String,
1552 original: String,
1553 corrected: String,
1554 },
1555 Flagged { flag_type: String },
1557 Disputed {
1559 counter_evidence: String,
1560 #[serde(default, skip_serializing_if = "Option::is_none")]
1561 counter_doi: Option<String>,
1562 },
1563}
1564
1565#[derive(Debug, Clone, Serialize, Deserialize)]
1570pub struct ConfidenceUpdate {
1571 pub finding_id: String,
1572 pub previous_score: f64,
1573 pub new_score: f64,
1574 pub basis: String,
1575 pub updated_by: String,
1577 pub updated_at: String,
1579}
1580
1581#[derive(Debug, Clone, Serialize, Deserialize)]
1582pub struct FindingBundle {
1583 pub id: String,
1584 #[serde(default = "default_version")]
1585 pub version: u32,
1586 pub previous_version: Option<String>,
1587 pub assertion: Assertion,
1588 pub evidence: Evidence,
1589 pub conditions: Conditions,
1590 pub confidence: Confidence,
1591 pub provenance: Provenance,
1592 pub flags: Flags,
1593 #[serde(default)]
1594 pub links: Vec<Link>,
1595 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1596 pub annotations: Vec<Annotation>,
1597 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1598 pub attachments: Vec<Attachment>,
1599 pub created: String,
1600 pub updated: Option<String>,
1601 #[serde(default, skip_serializing_if = "is_public_tier")]
1608 pub access_tier: crate::access_tier::AccessTier,
1609}
1610
1611fn is_public_tier(tier: &crate::access_tier::AccessTier) -> bool {
1612 matches!(tier, crate::access_tier::AccessTier::Public)
1613}
1614
1615fn default_version() -> u32 {
1616 1
1617}
1618
1619impl FindingBundle {
1620 pub fn normalize_text(s: &str) -> String {
1626 let lower = s.to_lowercase();
1627 let collapsed: String = lower.split_whitespace().collect::<Vec<_>>().join(" ");
1629 collapsed
1631 .trim_end_matches(['.', ';', ':', '!', '?'])
1632 .to_string()
1633 }
1634
1635 pub fn content_address(assertion: &Assertion, provenance: &Provenance) -> String {
1639 let norm_text = Self::normalize_text(&assertion.text);
1640 let prov_id = provenance.doi.as_deref().unwrap_or(&provenance.title);
1643 let preimage = format!("{}|{}|{}", norm_text, assertion.assertion_type, prov_id);
1644 let hash = Sha256::digest(preimage.as_bytes());
1645 format!("vf_{}", &hex::encode(hash)[..16])
1646 }
1647
1648 pub fn new(
1649 assertion: Assertion,
1650 evidence: Evidence,
1651 conditions: Conditions,
1652 confidence: Confidence,
1653 provenance: Provenance,
1654 flags: Flags,
1655 ) -> Self {
1656 let now = Utc::now().to_rfc3339();
1657 let id = Self::content_address(&assertion, &provenance);
1658
1659 Self {
1660 id,
1661 version: 1,
1662 previous_version: None,
1663 assertion,
1664 evidence,
1665 conditions,
1666 confidence,
1667 provenance,
1668 flags,
1669 links: Vec::new(),
1670 annotations: Vec::new(),
1671 attachments: Vec::new(),
1672 created: now,
1673 updated: None,
1674 access_tier: crate::access_tier::AccessTier::Public,
1675 }
1676 }
1677
1678 pub fn add_link(&mut self, target_id: &str, link_type: &str, note: &str) {
1679 self.links.push(Link {
1680 target: target_id.to_string(),
1681 link_type: link_type.to_string(),
1682 note: note.to_string(),
1683 inferred_by: "compiler".to_string(),
1684 created_at: Utc::now().to_rfc3339(),
1685 mechanism: None,
1686 });
1687 }
1688
1689 pub fn add_link_with_source(
1690 &mut self,
1691 target_id: &str,
1692 link_type: &str,
1693 note: &str,
1694 inferred_by: &str,
1695 ) {
1696 self.links.push(Link {
1697 target: target_id.to_string(),
1698 link_type: link_type.to_string(),
1699 note: note.to_string(),
1700 inferred_by: inferred_by.to_string(),
1701 created_at: Utc::now().to_rfc3339(),
1702 mechanism: None,
1703 });
1704 }
1705}
1706
1707#[cfg(test)]
1708mod tests {
1709 use super::*;
1710
1711 fn sample_assertion() -> Assertion {
1712 Assertion {
1713 text: "NLRP3 activates IL-1B".into(),
1714 assertion_type: "mechanism".into(),
1715 entities: vec![Entity {
1716 name: "NLRP3".into(),
1717 entity_type: "protein".into(),
1718 identifiers: serde_json::Map::new(),
1719 canonical_id: None,
1720 candidates: vec![],
1721 aliases: vec![],
1722 resolution_provenance: None,
1723 resolution_confidence: 1.0,
1724 resolution_method: None,
1725 species_context: None,
1726 needs_review: false,
1727 }],
1728 relation: Some("activates".into()),
1729 direction: Some("positive".into()),
1730 causal_claim: None,
1731 causal_evidence_grade: None,
1732 }
1733 }
1734
1735 fn sample_evidence() -> Evidence {
1736 Evidence {
1737 evidence_type: "experimental".into(),
1738 model_system: "mouse".into(),
1739 method: "Western blot".into(),
1740 replicated: true,
1741 replication_count: Some(3),
1742 evidence_spans: vec![],
1743 }
1744 }
1745
1746 fn sample_conditions() -> Conditions {
1747 Conditions {
1748 text: "In vitro, mouse microglia".into(),
1749 duration: None,
1750 }
1751 }
1752
1753 fn sample_confidence() -> Confidence {
1754 Confidence {
1755 kind: ConfidenceKind::FrontierEpistemic,
1756 score: 0.85,
1757 basis: "Experimental with replication".into(),
1758 method: ConfidenceMethod::LlmInitial,
1759 extraction_confidence: 0.9,
1760 }
1761 }
1762
1763 fn sample_provenance() -> Provenance {
1764 Provenance {
1765 source_type: "published_paper".into(),
1766 doi: Some("10.1234/test".into()),
1767 url: None,
1768 title: "Test Paper".into(),
1769 authors: vec![Author {
1770 name: "Smith J".into(),
1771 orcid: None,
1772 }],
1773 year: Some(2024),
1774 license: None,
1775 publisher: None,
1776 funders: vec![],
1777 extraction: Extraction::default(),
1778 review: None,
1779 contributions: Vec::new(),
1780 }
1781 }
1782
1783 fn sample_flags() -> Flags {
1784 Flags {
1785 gap: false,
1786 negative_space: false,
1787 contested: false,
1788 retracted: false,
1789 declining: false,
1790 gravity_well: false,
1791 review_state: None,
1792 superseded: false,
1793 signature_threshold: None,
1794 jointly_accepted: false,
1795 }
1796 }
1797
1798 #[test]
1801 fn same_content_same_id() {
1802 let b1 = FindingBundle::new(
1803 sample_assertion(),
1804 sample_evidence(),
1805 sample_conditions(),
1806 sample_confidence(),
1807 sample_provenance(),
1808 sample_flags(),
1809 );
1810 let b2 = FindingBundle::new(
1811 sample_assertion(),
1812 sample_evidence(),
1813 sample_conditions(),
1814 sample_confidence(),
1815 sample_provenance(),
1816 sample_flags(),
1817 );
1818 assert_eq!(b1.id, b2.id);
1819 }
1820
1821 #[test]
1822 fn different_content_different_id() {
1823 let b1 = FindingBundle::new(
1824 sample_assertion(),
1825 sample_evidence(),
1826 sample_conditions(),
1827 sample_confidence(),
1828 sample_provenance(),
1829 sample_flags(),
1830 );
1831 let mut different_assertion = sample_assertion();
1832 different_assertion.text = "Completely different claim".into();
1833 let b2 = FindingBundle::new(
1834 different_assertion,
1835 sample_evidence(),
1836 sample_conditions(),
1837 sample_confidence(),
1838 sample_provenance(),
1839 sample_flags(),
1840 );
1841 assert_ne!(b1.id, b2.id);
1842 }
1843
1844 #[test]
1845 fn id_starts_with_vf_prefix() {
1846 let b = FindingBundle::new(
1847 sample_assertion(),
1848 sample_evidence(),
1849 sample_conditions(),
1850 sample_confidence(),
1851 sample_provenance(),
1852 sample_flags(),
1853 );
1854 assert!(b.id.starts_with("vf_"));
1855 assert_eq!(b.id.len(), 3 + 16); }
1857
1858 #[test]
1859 fn new_bundle_version_is_one() {
1860 let b = FindingBundle::new(
1861 sample_assertion(),
1862 sample_evidence(),
1863 sample_conditions(),
1864 sample_confidence(),
1865 sample_provenance(),
1866 sample_flags(),
1867 );
1868 assert_eq!(b.version, 1);
1869 assert!(b.previous_version.is_none());
1870 }
1871
1872 #[test]
1873 fn new_bundle_has_no_links() {
1874 let b = FindingBundle::new(
1875 sample_assertion(),
1876 sample_evidence(),
1877 sample_conditions(),
1878 sample_confidence(),
1879 sample_provenance(),
1880 sample_flags(),
1881 );
1882 assert!(b.links.is_empty());
1883 }
1884
1885 #[test]
1886 fn new_bundle_has_created_timestamp() {
1887 let b = FindingBundle::new(
1888 sample_assertion(),
1889 sample_evidence(),
1890 sample_conditions(),
1891 sample_confidence(),
1892 sample_provenance(),
1893 sample_flags(),
1894 );
1895 assert!(!b.created.is_empty());
1896 assert!(b.updated.is_none());
1897 }
1898
1899 #[test]
1902 fn add_link_works() {
1903 let mut b = FindingBundle::new(
1904 sample_assertion(),
1905 sample_evidence(),
1906 sample_conditions(),
1907 sample_confidence(),
1908 sample_provenance(),
1909 sample_flags(),
1910 );
1911 b.add_link("target_id", "extends", "shared entity");
1912 assert_eq!(b.links.len(), 1);
1913 assert_eq!(b.links[0].target, "target_id");
1914 assert_eq!(b.links[0].link_type, "extends");
1915 assert_eq!(b.links[0].note, "shared entity");
1916 assert_eq!(b.links[0].inferred_by, "compiler");
1917 }
1918
1919 #[test]
1920 fn add_link_with_source_works() {
1921 let mut b = FindingBundle::new(
1922 sample_assertion(),
1923 sample_evidence(),
1924 sample_conditions(),
1925 sample_confidence(),
1926 sample_provenance(),
1927 sample_flags(),
1928 );
1929 b.add_link_with_source(
1930 "target_id",
1931 "contradicts",
1932 "opposite direction",
1933 "entity_overlap",
1934 );
1935 assert_eq!(b.links.len(), 1);
1936 assert_eq!(b.links[0].inferred_by, "entity_overlap");
1937 }
1938
1939 #[test]
1940 fn multiple_links_accumulate() {
1941 let mut b = FindingBundle::new(
1942 sample_assertion(),
1943 sample_evidence(),
1944 sample_conditions(),
1945 sample_confidence(),
1946 sample_provenance(),
1947 sample_flags(),
1948 );
1949 b.add_link("t1", "extends", "note1");
1950 b.add_link("t2", "contradicts", "note2");
1951 b.add_link("t3", "supports", "note3");
1952 assert_eq!(b.links.len(), 3);
1953 }
1954
1955 #[test]
1958 fn review_event_creation() {
1959 let event = ReviewEvent {
1960 id: "rev_abc123".into(),
1961 workspace: None,
1962 finding_id: "vf_abc".into(),
1963 reviewer: "0000-0001-2345-6789".into(),
1964 reviewed_at: "2024-01-01T00:00:00Z".into(),
1965 scope: None,
1966 status: None,
1967 action: ReviewAction::Approved,
1968 reason: "Looks correct".into(),
1969 evidence_considered: vec![],
1970 state_change: None,
1971 };
1972 assert_eq!(event.finding_id, "vf_abc");
1973 assert_eq!(event.reviewer, "0000-0001-2345-6789");
1974 }
1975
1976 #[test]
1977 fn review_action_corrected() {
1978 let action = ReviewAction::Corrected {
1979 field: "direction".into(),
1980 original: "positive".into(),
1981 corrected: "negative".into(),
1982 };
1983 if let ReviewAction::Corrected {
1984 field,
1985 original,
1986 corrected,
1987 } = action
1988 {
1989 assert_eq!(field, "direction");
1990 assert_eq!(original, "positive");
1991 assert_eq!(corrected, "negative");
1992 } else {
1993 panic!("Expected Corrected variant");
1994 }
1995 }
1996
1997 #[test]
1998 fn review_action_disputed() {
1999 let action = ReviewAction::Disputed {
2000 counter_evidence: "Later study contradicts".into(),
2001 counter_doi: Some("10.1234/counter".into()),
2002 };
2003 if let ReviewAction::Disputed {
2004 counter_evidence,
2005 counter_doi,
2006 } = action
2007 {
2008 assert_eq!(counter_evidence, "Later study contradicts");
2009 assert_eq!(counter_doi, Some("10.1234/counter".into()));
2010 } else {
2011 panic!("Expected Disputed variant");
2012 }
2013 }
2014
2015 #[test]
2018 fn confidence_update_creation() {
2019 let update = ConfidenceUpdate {
2020 finding_id: "vf_abc".into(),
2021 previous_score: 0.7,
2022 new_score: 0.85,
2023 basis: "grounded".into(),
2024 updated_by: "grounding_pass".into(),
2025 updated_at: "2024-01-01T00:00:00Z".into(),
2026 };
2027 assert_eq!(update.previous_score, 0.7);
2028 assert_eq!(update.new_score, 0.85);
2029 assert_eq!(update.updated_by, "grounding_pass");
2030 }
2031
2032 #[test]
2035 fn finding_serializes_and_deserializes() {
2036 let b = FindingBundle::new(
2037 sample_assertion(),
2038 sample_evidence(),
2039 sample_conditions(),
2040 sample_confidence(),
2041 sample_provenance(),
2042 sample_flags(),
2043 );
2044 let json = serde_json::to_string(&b).unwrap();
2045 let b2: FindingBundle = serde_json::from_str(&json).unwrap();
2046 assert_eq!(b.id, b2.id);
2047 assert_eq!(b.assertion.text, b2.assertion.text);
2048 assert_eq!(b.confidence.score, b2.confidence.score);
2049 }
2050
2051 #[test]
2052 fn v0_10_assertion_and_source_extensions() {
2053 assert!(VALID_ASSERTION_TYPES.contains(&"measurement"));
2054 assert!(VALID_ASSERTION_TYPES.contains(&"exclusion"));
2055 assert!(VALID_PROVENANCE_SOURCE_TYPES.contains(&"data_release"));
2056 }
2057
2058 #[test]
2061 fn confidence_does_not_affect_id() {
2062 let b1 = FindingBundle::new(
2064 sample_assertion(),
2065 sample_evidence(),
2066 sample_conditions(),
2067 sample_confidence(),
2068 sample_provenance(),
2069 sample_flags(),
2070 );
2071 let mut conf2 = sample_confidence();
2072 conf2.score = 0.5;
2073 let b2 = FindingBundle::new(
2074 sample_assertion(),
2075 sample_evidence(),
2076 sample_conditions(),
2077 conf2,
2078 sample_provenance(),
2079 sample_flags(),
2080 );
2081 assert_eq!(b1.id, b2.id);
2082 }
2083
2084 #[test]
2085 fn flags_do_not_affect_id() {
2086 let b1 = FindingBundle::new(
2087 sample_assertion(),
2088 sample_evidence(),
2089 sample_conditions(),
2090 sample_confidence(),
2091 sample_provenance(),
2092 sample_flags(),
2093 );
2094 let mut flags2 = sample_flags();
2095 flags2.gap = true;
2096 flags2.contested = true;
2097 let b2 = FindingBundle::new(
2098 sample_assertion(),
2099 sample_evidence(),
2100 sample_conditions(),
2101 sample_confidence(),
2102 sample_provenance(),
2103 flags2,
2104 );
2105 assert_eq!(b1.id, b2.id);
2107 }
2108
2109 #[test]
2110 fn different_assertion_text_different_id() {
2111 let b1 = FindingBundle::new(
2112 sample_assertion(),
2113 sample_evidence(),
2114 sample_conditions(),
2115 sample_confidence(),
2116 sample_provenance(),
2117 sample_flags(),
2118 );
2119 let mut assertion2 = sample_assertion();
2120 assertion2.assertion_type = "therapeutic".into();
2121 let b2 = FindingBundle::new(
2122 assertion2,
2123 sample_evidence(),
2124 sample_conditions(),
2125 sample_confidence(),
2126 sample_provenance(),
2127 sample_flags(),
2128 );
2129 assert_ne!(b1.id, b2.id);
2130 }
2131
2132 #[test]
2133 fn different_doi_different_id() {
2134 let b1 = FindingBundle::new(
2135 sample_assertion(),
2136 sample_evidence(),
2137 sample_conditions(),
2138 sample_confidence(),
2139 sample_provenance(),
2140 sample_flags(),
2141 );
2142 let mut prov2 = sample_provenance();
2143 prov2.doi = Some("10.5678/other".into());
2144 let b2 = FindingBundle::new(
2145 sample_assertion(),
2146 sample_evidence(),
2147 sample_conditions(),
2148 sample_confidence(),
2149 prov2,
2150 sample_flags(),
2151 );
2152 assert_ne!(b1.id, b2.id);
2153 }
2154
2155 #[test]
2158 fn content_address_is_deterministic_across_runs() {
2159 let assertion1 = Assertion {
2162 text: "Mitochondrial dysfunction precedes amyloid plaque formation.".into(),
2163 assertion_type: "mechanism".into(),
2164 entities: vec![],
2165 relation: None,
2166 direction: None,
2167 causal_claim: None,
2168 causal_evidence_grade: None,
2169 };
2170 let prov1 = Provenance {
2171 source_type: "published_paper".into(),
2172 doi: Some("10.1038/s41586-023-06789-1".into()),
2173 url: None,
2174 title: "Mitochondria in AD".into(),
2175 authors: vec![],
2176 year: Some(2023),
2177 license: None,
2178 publisher: None,
2179 funders: vec![],
2180 extraction: Extraction::default(),
2181 review: None,
2182 contributions: Vec::new(),
2183 };
2184
2185 let assertion2 = Assertion {
2187 text: "Mitochondrial dysfunction precedes amyloid plaque formation.".into(),
2188 assertion_type: "mechanism".into(),
2189 entities: vec![Entity {
2190 name: "mitochondria".into(),
2191 entity_type: "anatomical_structure".into(),
2192 identifiers: serde_json::Map::new(),
2193 canonical_id: None,
2194 candidates: vec![],
2195 aliases: vec![],
2196 resolution_provenance: None,
2197 resolution_confidence: 1.0,
2198 resolution_method: None,
2199 species_context: None,
2200 needs_review: false,
2201 }],
2202 relation: Some("precedes".into()),
2203 direction: Some("positive".into()),
2204 causal_claim: None,
2205 causal_evidence_grade: None,
2206 };
2207 let prov2 = Provenance {
2208 source_type: "published_paper".into(),
2209 doi: Some("10.1038/s41586-023-06789-1".into()),
2210 url: None,
2211 title: "Different title".into(),
2212 authors: vec![Author {
2213 name: "Jones A".into(),
2214 orcid: None,
2215 }],
2216 year: Some(2023),
2217 license: None,
2218 publisher: None,
2219 funders: vec![],
2220 extraction: Extraction::default(),
2221 review: None,
2222 contributions: Vec::new(),
2223 };
2224
2225 let id1 = FindingBundle::content_address(&assertion1, &prov1);
2226 let id2 = FindingBundle::content_address(&assertion2, &prov2);
2227 assert_eq!(
2228 id1, id2,
2229 "Same assertion text + type + DOI must produce same ID"
2230 );
2231 }
2232
2233 #[test]
2234 fn content_address_normalizes_whitespace_and_punctuation() {
2235 let assertion1 = Assertion {
2236 text: " NLRP3 activates IL-1B. ".into(),
2237 assertion_type: "mechanism".into(),
2238 entities: vec![],
2239 relation: None,
2240 direction: None,
2241 causal_claim: None,
2242 causal_evidence_grade: None,
2243 };
2244 let assertion2 = Assertion {
2245 text: "NLRP3 activates IL-1B".into(),
2246 assertion_type: "mechanism".into(),
2247 entities: vec![],
2248 relation: None,
2249 direction: None,
2250 causal_claim: None,
2251 causal_evidence_grade: None,
2252 };
2253 let prov = sample_provenance();
2254 let id1 = FindingBundle::content_address(&assertion1, &prov);
2255 let id2 = FindingBundle::content_address(&assertion2, &prov);
2256 assert_eq!(
2257 id1, id2,
2258 "Whitespace and trailing punctuation should be normalized away"
2259 );
2260 }
2261
2262 #[test]
2263 fn content_address_falls_back_to_title_when_no_doi() {
2264 let assertion = sample_assertion();
2265 let mut prov = sample_provenance();
2266 prov.doi = None;
2267 prov.title = "Fallback Title".into();
2268 let id = FindingBundle::content_address(&assertion, &prov);
2269 assert!(id.starts_with("vf_"));
2270 assert_eq!(id.len(), 19); let mut prov2 = sample_provenance();
2274 prov2.doi = None;
2275 prov2.title = "Fallback Title".into();
2276 let id2 = FindingBundle::content_address(&assertion, &prov2);
2277 assert_eq!(id, id2);
2278 }
2279
2280 #[test]
2281 fn content_address_prefers_doi_over_title() {
2282 let assertion = sample_assertion();
2283
2284 let mut prov_doi = sample_provenance();
2285 prov_doi.doi = Some("10.1234/test".into());
2286 prov_doi.title = "Title".into();
2287
2288 let mut prov_title = sample_provenance();
2289 prov_title.doi = None;
2290 prov_title.title = "Title".into();
2291
2292 let id_doi = FindingBundle::content_address(&assertion, &prov_doi);
2293 let id_title = FindingBundle::content_address(&assertion, &prov_title);
2294
2295 assert_ne!(id_doi, id_title, "DOI vs title should differ");
2296 }
2297
2298 #[test]
2299 fn parses_bbb_review_event_with_richer_schema() {
2300 let raw = include_str!("../../embedded/tests/fixtures/legacy/rev_001_bbb_correction.json");
2301 let review: ReviewEvent = serde_json::from_str(raw).unwrap();
2302
2303 assert_eq!(review.id, "rev_001_bbb_correction");
2304 assert_eq!(review.workspace.as_deref(), Some("projects/bbb-flagship"));
2305 assert_eq!(review.scope.as_deref(), Some("bbb_opening_trusted_subset"));
2306 assert_eq!(review.status.as_deref(), Some("accepted"));
2307 assert!(matches!(
2308 review.action,
2309 ReviewAction::Qualified { ref target } if target == "trusted_interpretation"
2310 ));
2311 assert_eq!(review.evidence_considered.len(), 3);
2312 assert_eq!(
2313 review.evidence_considered[0].role.as_deref(),
2314 Some("qualifier")
2315 );
2316 assert_eq!(
2317 review
2318 .state_change
2319 .as_ref()
2320 .and_then(|value| value.get("assumption_retired"))
2321 .and_then(|value| value.as_str()),
2322 Some("safe opening implies therapeutic efficacy")
2323 );
2324 }
2325
2326 #[test]
2327 fn artifact_requires_sha256_and_stable_kind() {
2328 let artifact = Artifact::new(
2329 "clinical_trial_record",
2330 "AHEAD 3-45",
2331 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
2332 Some(42),
2333 Some("application/json".into()),
2334 "local_blob",
2335 Some(".vela/artifact-blobs/sha256/aaaaaaaa".into()),
2336 Some("https://clinicaltrials.gov/study/NCT04468659".into()),
2337 Some("ClinicalTrials.gov public record".into()),
2338 vec!["vf_demo".into()],
2339 sample_provenance(),
2340 BTreeMap::new(),
2341 crate::access_tier::AccessTier::Public,
2342 )
2343 .unwrap();
2344
2345 assert!(artifact.id.starts_with("va_"));
2346 assert_eq!(
2347 artifact.content_hash,
2348 "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
2349 );
2350 assert_eq!(artifact.kind, "clinical_trial_record");
2351 }
2352
2353 #[test]
2354 fn artifact_reference_axes_are_independent_and_content_bound() {
2355 let hash = format!("sha256:{}", "a".repeat(64));
2356 let legacy = Artifact::content_address(
2357 "dataset",
2358 "public data",
2359 &hash,
2360 None,
2361 Some("https://example.test/data"),
2362 );
2363 let all_unknown = Artifact::content_address_with_axes(
2364 "dataset",
2365 "public data",
2366 &hash,
2367 None,
2368 Some("https://example.test/data"),
2369 ArtifactDisclosure::Unknown,
2370 LocatorIntegrity::Unknown,
2371 ArtifactAvailability::Unknown,
2372 );
2373 assert_eq!(legacy, all_unknown);
2374
2375 let immutable = Artifact::content_address_with_axes(
2376 "dataset",
2377 "public data",
2378 &hash,
2379 None,
2380 Some("https://example.test/data"),
2381 ArtifactDisclosure::Public,
2382 LocatorIntegrity::Immutable,
2383 ArtifactAvailability::Available,
2384 );
2385 let mutable = Artifact::content_address_with_axes(
2386 "dataset",
2387 "public data",
2388 &hash,
2389 None,
2390 Some("https://example.test/data"),
2391 ArtifactDisclosure::Public,
2392 LocatorIntegrity::Mutable,
2393 ArtifactAvailability::Available,
2394 );
2395 assert_ne!(immutable, mutable);
2396 }
2397
2398 #[test]
2399 fn restricted_reference_refuses_public_equality_digest() {
2400 let mut artifact = Artifact::new(
2401 "dataset",
2402 "restricted data",
2403 "a".repeat(64),
2404 None,
2405 None,
2406 "pointer",
2407 Some("custodian:lab-vault/item-7".to_string()),
2408 None,
2409 None,
2410 vec![],
2411 sample_provenance(),
2412 BTreeMap::new(),
2413 crate::access_tier::AccessTier::Restricted,
2414 )
2415 .unwrap();
2416 artifact.disclosure = ArtifactDisclosure::Restricted;
2417 artifact.locator_integrity = LocatorIntegrity::Immutable;
2418 artifact.availability = ArtifactAvailability::Unknown;
2419 assert!(artifact.validate_reference_axes().is_err());
2420
2421 artifact.content_hash.clear();
2422 assert!(artifact.validate_reference_axes().is_ok());
2423 }
2424}