Skip to main content

vela_protocol/kernel/
bundle.rs

1//! Content-addressed finding bundles: the atomic object of the Vela protocol.
2
3use std::collections::BTreeMap;
4
5use chrono::Utc;
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use sha2::{Digest, Sha256};
9
10/// Valid assertion types per schema.
11///
12/// v0.10 added `measurement` and `exclusion` for measurement-heavy domains
13/// (physics, chemistry, climate, materials) where the substance of a
14/// finding is a numerical value or an exclusion limit at a confidence level.
15pub const VALID_ASSERTION_TYPES: &[&str] = &[
16    "mechanism",
17    "observational",
18    "computational",
19    "theoretical",
20    "negative",
21    // v0.10
22    "measurement",
23    "exclusion",
24    // v0.30: Notes Compiler emits these for proposals derived from
25    // researcher zettelkasten / Obsidian vaults. They become canonical
26    // findings on accept; rejecting them at the validator would force a
27    // post-hoc rewrite that breaks content-addressed ids. The semantic
28    // intent: `tension` = a theoretical claim about a field-level
29    // contradiction (paired claims that don't reconcile); `open_question`
30    // = an unresolved framing the agent surfaced; `hypothesis` = a
31    // provisional candidate claim awaiting evidence. The notes-compiler
32    // proposals doc covers how these are produced.
33    "tension",
34    "open_question",
35    "hypothesis",
36    "candidate_finding",
37];
38
39/// Valid artifact kinds for the generic `Artifact` kernel object.
40///
41/// `Dataset` and `CodeArtifact` remain as stronger, typed legacy objects.
42/// `Artifact` is the shared substrate path for files and records that need
43/// durable byte or pointer provenance before a domain-specific object exists.
44pub 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
64/// Valid evidence types per schema.
65pub const VALID_EVIDENCE_TYPES: &[&str] = &[
66    "experimental",
67    "observational",
68    "computational",
69    "theoretical",
70    // v0.30: Notes Compiler — the evidence span lives in the researcher's
71    // zettelkasten note rather than a primary literature passage.
72    // Treated as an `expert_assertion`-shaped evidence kind.
73    "extracted_from_notes",
74];
75
76/// Valid provenance source types per schema.
77///
78/// v0.10 added `data_release` for instrument runs, observation campaigns,
79/// and dataset versions that are themselves the substantive object — distinct
80/// from the paper that reports them (XENONnT SR0, Planck data releases,
81/// JWST observation runs, LHC analysis releases).
82pub const VALID_PROVENANCE_SOURCE_TYPES: &[&str] = &[
83    "published_paper",
84    "preprint",
85    "model_output",
86    "expert_assertion",
87    "database_record",
88    // v0.10
89    "data_release",
90    // v0.30: notes-compiler proposals cite the source markdown note
91    // by filename. Distinct from `lab_notebook` (which implies a
92    // dated lab workbook entry with primary observations) and
93    // `expert_assertion` (which implies a named expert's claim).
94    "researcher_notes",
95    // Current authenticated producer input. The retained Finding remains the
96    // accepted scientific object; this value records that its provenance is a
97    // content-addressed vela.submission.v1 rather than a paper or free-form
98    // model transcript.
99    "vela_submission",
100];
101
102/// Valid link types per protocol §5.
103///
104/// T7 (FrontierGraph substrate) extends the vocabulary with the
105/// relation kinds the typed-edge layer reasons over. The conceptual
106/// T7 set is SUPPORTS / CONTRADICTS / DEPENDS_ON / DERIVED_FROM /
107/// IMPROVES / GENERALIZES / SPECIALIZES / SUPERSEDES; the existing
108/// lowercase strings already cover DEPENDS_ON (`depends`) and
109/// DERIVED_FROM (`synthesized_from`), so only the three genuinely new
110/// concepts are added here. `extends` and `replicates` predate T7 and
111/// stay. No redundant aliases — the FrontierGraph EdgeKind layer maps
112/// strings to the canonical T7 vocabulary.
113pub const VALID_LINK_TYPES: &[&str] = &[
114    "supports",
115    "contradicts",
116    "extends",
117    "depends",
118    "replicates",
119    "supersedes",
120    "synthesized_from",
121    // T7 additions:
122    "improves",
123    "generalizes",
124    "specializes",
125    // cross-domain transfer (vtr_):
126    "discharges",
127];
128
129/// The local finding id of a link target, stripping any cross-frontier
130/// `@vfr_…` suffix. A `vf_X@vfr_Y` target resolves to `vf_X`; a plain
131/// `vf_X` is returned unchanged. Single source of truth for the
132/// resolution the graph builders and read tools all rely on.
133#[must_use]
134pub fn bare_finding_id(target: &str) -> &str {
135    target.split('@').next().unwrap_or(target)
136}
137
138/// A resolved identifier from a scientific database.
139#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct ResolvedId {
141    /// The database source (mesh, uniprot, pubchem, chebi, go, ncbi_gene).
142    pub source: String,
143    /// The identifier value (e.g., "D000544", "Q6ZSS7", "24752728").
144    pub id: String,
145    /// Confidence in this resolution (0.0-1.0).
146    pub confidence: f64,
147    /// The matched name in the source database.
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub matched_name: Option<String>,
150}
151
152/// How an entity was resolved to its canonical form (v0.2.0 schema).
153#[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    /// Deprecated: flat identifiers map. Retained for backward compatibility with
179    /// older frontier JSON files. New code should use `canonical_id` and `candidates`.
180    #[serde(default)]
181    pub identifiers: serde_json::Map<String, serde_json::Value>,
182    /// The primary resolved identifier (if resolved).
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub canonical_id: Option<ResolvedId>,
185    /// Alternative resolution candidates with scores.
186    #[serde(default)]
187    pub candidates: Vec<ResolvedId>,
188    /// Known aliases for this entity (e.g., NLRP3 = cryopyrin = NALP3).
189    #[serde(default)]
190    pub aliases: Vec<String>,
191    /// How this resolution was performed.
192    #[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    /// How the entity was resolved: exact_match, fuzzy_match, llm_inference, manual.
197    #[serde(default, skip_serializing_if = "Option::is_none")]
198    pub resolution_method: Option<ResolutionMethod>,
199    /// Species context for orthologs (e.g., "Homo sapiens" vs "Mus musculus" for APP).
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub species_context: Option<String>,
202    /// True when resolution_confidence < 0.8 and the match needs human review.
203    #[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    // v0.700: the empirical-measurement slots (species/sample_size/effect_size/
220    // p_value) were removed — unused in the math wedge, stripped from every live
221    // finding by the re-genesis, byte-identical to their skip-guarded form.
222    #[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/// v0.33: Dataset as a first-class kernel object.
230///
231/// A `Dataset` is a versioned, content-addressed reference to data
232/// that anchors empirical claims. Before v0.33, datasets were strings
233/// in `Provenance.title` or entity-typed mentions in assertions —
234/// a claim could say "we used ADNI" without anchoring which release
235/// of ADNI the analysis ran against, and re-running the same code on
236/// a refreshed cohort silently produced a "different" claim.
237///
238/// `vd_<id>` is content-addressed over `name + version + content_hash
239/// + url`. Two dataset records with the same name but different
240/// versions get distinct ids; two records pointing at the same
241/// snapshot collapse to the same id. Claims can reference the exact
242/// bytes they rest on, not only a dataset name in prose.
243#[derive(Debug, Clone, Serialize, Deserialize)]
244pub struct Dataset {
245    /// `vd_<16hex>`, content-addressed; see `Dataset::content_address`.
246    pub id: String,
247    /// Human-readable name (e.g. "ADNI", "TRAILBLAZER-ALZ", "MIMIC-IV").
248    pub name: String,
249    /// Semantic version or release tag (e.g. "ADNI-3", "v2.2", "SR0").
250    /// Two entries differing only in version are distinct kernel objects.
251    pub version: Option<String>,
252    /// Optional column-level schema as `(name, type)` pairs. For
253    /// non-tabular datasets, leave empty.
254    #[serde(default)]
255    pub schema: Vec<(String, String)>,
256    /// Number of rows / observations / records, when known.
257    pub row_count: Option<u64>,
258    /// SHA-256 of the canonical contents, when computable. For
259    /// large datasets stored remotely, this is the publisher's
260    /// declared content hash; integrity verification is the puller's
261    /// job (same pattern as `vfr_*` snapshots).
262    pub content_hash: String,
263    /// Where the dataset is reachable (https URL, file://, s3://, etc.).
264    pub url: Option<String>,
265    /// License identifier or URL (e.g. "CC-BY-4.0", a Crossref license).
266    pub license: Option<String>,
267    /// Provenance of the dataset itself — typically the paper or release
268    /// that publishes it. Reuses `Provenance` for shape parity with
269    /// findings.
270    pub provenance: Provenance,
271    /// RFC 3339 creation timestamp.
272    pub created: String,
273}
274
275impl Dataset {
276    /// Compute the content-addressed ID per v0.33 spec:
277    /// `SHA-256(name | version | content_hash | url)`.
278    /// Returns first 16 hex chars prefixed with "vd_".
279    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    /// Construct a new Dataset with a freshly-derived id and `created`
297    /// timestamp set to now.
298    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/// v0.33: CodeArtifact as a first-class kernel object.
325///
326/// A `CodeArtifact` is a content-addressed pointer at a specific
327/// region of source code (a function, a notebook cell, a script, a
328/// pipeline step) at a specific git commit. Before v0.33, code was
329/// captured as a string in `Evidence.method` — "we ran a logistic
330/// regression" — with no way for a reader to verify which code
331/// produced the result, or to re-run it.
332///
333/// `vc_<id>` is content-addressed over `repo_url + git_commit + path
334/// + line_range + content_hash`. The same code at two commits gets
335/// two records (the relevant historical fact); the same code in two
336/// paths in the same repo also gets two records (location matters
337/// for re-execution).
338#[derive(Debug, Clone, Serialize, Deserialize)]
339pub struct CodeArtifact {
340    /// `vc_<16hex>`, content-addressed; see `CodeArtifact::content_address`.
341    pub id: String,
342    /// Source language: `python` / `r` / `julia` / `rust` / `bash`,
343    /// etc. Not validated against a closed allow-list — code provenance
344    /// should accept whatever language the analysis was actually in.
345    pub language: String,
346    /// Repository URL (e.g. `https://github.com/vela-science/vela`).
347    pub repo_url: Option<String>,
348    /// Specific git commit (40-char SHA preferred). Required for
349    /// reproducibility; `None` means "unpinned" and weakens the
350    /// substrate claim.
351    pub git_commit: Option<String>,
352    /// Path within the repository (e.g. `crates/producer/src/notes.rs`).
353    pub path: String,
354    /// Optional line range as `(start, end)`, both inclusive.
355    pub line_range: Option<(u32, u32)>,
356    /// SHA-256 of the snippet body. Decouples the artifact from the
357    /// repository's external state — even if a repo is deleted, the
358    /// content_hash remains anchored.
359    pub content_hash: String,
360    /// Optional entry point: function name, notebook cell id, or
361    /// `__main__`. Used by re-execution tooling.
362    pub entry_point: Option<String>,
363    /// RFC 3339 creation timestamp.
364    pub created: String,
365}
366
367impl CodeArtifact {
368    /// Compute the content-addressed ID per v0.33 spec:
369    /// `SHA-256(repo_url | git_commit | path | line_range | content_hash)`.
370    /// Returns first 16 hex chars prefixed with "vc_".
371    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    /// Construct a new CodeArtifact with a freshly-derived id and
394    /// `created` timestamp.
395    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/// Generic content-addressed artifact.
428///
429/// This is the common substrate object for records and files that are not
430/// only papers: trial registry snapshots, protocols, supplements, notebooks,
431/// tables, figures, model outputs, lab files, and dataset manifests. Typed
432/// objects such as `Dataset` and `CodeArtifact` still exist because they
433/// carry stronger domain-specific fields. `Artifact` gives every byte or
434/// pointer the same minimum durability contract.
435#[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    /// `va_<16hex>`, content-addressed over kind, name, hash, source, and
483    /// locator.
484    pub id: String,
485    /// One of `VALID_ARTIFACT_KINDS`.
486    pub kind: String,
487    /// Human-readable label.
488    pub name: String,
489    /// SHA-256 commitment. Convention: `sha256:<64hex>`.
490    pub content_hash: String,
491    /// Byte count when known.
492    #[serde(default, skip_serializing_if = "Option::is_none")]
493    pub size_bytes: Option<u64>,
494    /// MIME type or close equivalent.
495    #[serde(default, skip_serializing_if = "Option::is_none")]
496    pub media_type: Option<String>,
497    /// `local_blob`, `local_file`, `remote`, or `pointer`.
498    pub storage_mode: String,
499    /// Independent disclosure axis. Missing on legacy artifacts means
500    /// `unknown`, never silently `public`.
501    #[serde(default, skip_serializing_if = "ArtifactDisclosure::is_unknown")]
502    pub disclosure: ArtifactDisclosure,
503    /// Locator mutability is independent from storage and disclosure.
504    #[serde(default, skip_serializing_if = "LocatorIntegrity::is_unknown")]
505    pub locator_integrity: LocatorIntegrity,
506    /// Observed availability is independent from locator integrity.
507    #[serde(default, skip_serializing_if = "ArtifactAvailability::is_unknown")]
508    pub availability: ArtifactAvailability,
509    /// Local relative path, file path, HTTPS URL, S3 URL, or registry locator.
510    #[serde(default, skip_serializing_if = "Option::is_none")]
511    pub locator: Option<String>,
512    /// Original upstream URL or accession, distinct from a mirrored blob path.
513    #[serde(default, skip_serializing_if = "Option::is_none")]
514    pub source_url: Option<String>,
515    /// License identifier, URL, or access terms note.
516    #[serde(default, skip_serializing_if = "Option::is_none")]
517    pub license: Option<String>,
518    /// Findings this artifact directly bears on.
519    #[serde(default, skip_serializing_if = "Vec::is_empty")]
520    pub target_findings: Vec<String>,
521    /// Pointer to the source record that described this artifact, if one
522    /// already exists in `sources`.
523    #[serde(default, skip_serializing_if = "Option::is_none")]
524    pub source_id: Option<String>,
525    /// Artifact-level provenance. The source record may be a registry,
526    /// repository, dataset portal, protocol page, or paper.
527    pub provenance: Provenance,
528    /// Structured adapter metadata such as NCT id, outcomes, accession ids,
529    /// version tags, or retrieval timestamps.
530    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
531    pub metadata: BTreeMap<String, Value>,
532    /// Review lifecycle for the artifact itself.
533    #[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    /// RFC 3339 creation timestamp.
540    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    /// Content-address a descriptor that opts into the independent reference
564    /// axes. The all-unknown shape deliberately delegates to the legacy
565    /// preimage so existing artifact IDs remain stable.
566    #[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    /// Fail-closed validation for descriptors crossing the receipt write edge.
600    /// Restricted bytes use an opaque custodian locator in the first safe
601    /// implementation; no public equality digest is emitted until a separately
602    /// reviewed sealed-commitment scheme exists.
603    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    // v0.700: the empirical-context slots (species_verified/species_unverified/
733    // in_vitro/in_vivo/human_data/clinical_trial/concentration_range/age_group/
734    // cell_type) were removed. The cheap-verifier math wedge never populated them,
735    // the re-genesis stripped them from every live finding, and dropping the struct
736    // fields is byte-identical to their skip-guarded (always-omitted) form.
737    pub duration: Option<String>,
738}
739
740/// Confidence method: how the score was determined.
741#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
742#[serde(rename_all = "snake_case")]
743#[derive(Default)]
744pub enum ConfidenceMethod {
745    /// Computed from structured frontier support components (v0.2.0).
746    Computed,
747    /// A human expert assigned it.
748    ExpertJudgment,
749    /// Legacy import path for confidence seeded before component breakdown existed.
750    #[default]
751    LlmInitial,
752}
753
754/// Semantic category of the confidence score stored on the frontier.
755#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
756#[serde(rename_all = "snake_case")]
757pub enum ConfidenceKind {
758    /// Bounded epistemic support for the finding as currently represented in frontier state.
759    #[default]
760    FrontierEpistemic,
761}
762
763#[derive(Debug, Clone, Serialize, Deserialize)]
764pub struct Confidence {
765    /// Semantic meaning of `score`. v0 emits `frontier_epistemic`.
766    #[serde(default)]
767    pub kind: ConfidenceKind,
768    pub score: f64,
769    pub basis: String,
770    /// How this score was determined.
771    #[serde(default)]
772    pub method: ConfidenceMethod,
773    /// Confidence in the extraction itself (separate from scientific confidence).
774    #[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    /// Construct a `Confidence` with a raw score and basis string. The
784    /// agent and verifier layers use this directly: a frozen verifier
785    /// assigns `score = 1.0`, while an LLM extraction supplies a single
786    /// confidence value.
787    ///
788    /// Renamed from `legacy()` in v0.36; the previous name was a
789    /// historical accident (the constructor was never actually
790    /// deprecated, just misnamed).
791    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/// What sub-part of a finding a contribution applies to.
838#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
839#[serde(rename_all = "snake_case")]
840pub enum ContributionUnitType {
841    /// An evidence span within a paper finding.
842    EvidenceSpan,
843    /// A Lean declaration name (FC / formal findings).
844    LeanDecl,
845    /// A single step of an argument.
846    Step,
847    /// The whole bundle (the finding-level default).
848    Whole,
849}
850
851/// The kind of actor behind a contribution. A `model` holds no key and can never
852/// be accountable; only a `human` can carry a signature.
853#[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/// The kind of contribution. Only `vouched` carries trust weight, and it maps to
862/// a human signature — a `model` or `agent` can never be `vouched`.
863#[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/// One attribution record at claim granularity: which actor contributed which
875/// unit of a finding, and in what role. Descriptive provenance only — the
876/// reducer never reads it as state, the gate never reads it as evidence, and it
877/// is outside the `vf_` id preimage (adding it does not change the finding id).
878#[derive(Debug, Clone, Serialize, Deserialize)]
879pub struct Contribution {
880    /// The sub-claim reference: an evidence-span ref, a Lean decl name, or the
881    /// literal `whole` (the current finding-level behaviour).
882    pub unit: String,
883    pub unit_type: ContributionUnitType,
884    pub agent_kind: AgentKind,
885    /// ORCID, agent handle, or model id.
886    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    /// Free text or an evidence-span reference backing the claim.
893    #[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    /// The one trust invariant: `vouched` is a human-signature role, so a
924    /// `model` or `agent` can never carry it. Structural, not a verdict.
925    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    // v0.700: the bibliometric slots (pmid/pmc/openalex_id/journal/citation_count)
948    // were removed. The math wedge cites by DOI/title, never PubMed/OpenAlex; the
949    // re-genesis stripped them from every live finding (0 were pmid-addressed, so
950    // content_address now uses doi||title with no id change). Byte-identical to the
951    // skip-guarded form.
952    /// v0.11: generic source URL when none of the structured identifiers
953    /// fit (preprint server URL, dataset landing page, talk recording, etc.).
954    /// Skipped when None so pre-v0.11 frontiers serialise byte-identically.
955    #[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    /// License URL (e.g., Creative Commons), typically from Crossref.
963    #[serde(default, skip_serializing_if = "Option::is_none")]
964    pub license: Option<String>,
965    /// Publisher name, typically from Crossref.
966    #[serde(default, skip_serializing_if = "Option::is_none")]
967    pub publisher: Option<String>,
968    /// Funding sources, typically from Crossref.
969    #[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    /// Claim-granularity attribution: which actor originated / derived /
975    /// formalized which unit of this finding. Descriptive provenance, distinct
976    /// from `extraction` (who extracted the whole bundle) and `authors` (the
977    /// source paper's humans). Skipped when empty so pre-existing bundles
978    /// serialise byte-identically, and outside the `vf_` id preimage.
979    #[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/// Typed review state. Replaces the v0.2 `flags.contested: bool` collapse
988/// of three semantically distinct review judgments. Doctrine line 6:
989/// "scientific disagreement should remain live state."
990#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
991#[serde(rename_all = "snake_case")]
992pub enum ReviewState {
993    /// Review verdict was "accepted" or "approved" — finding stands.
994    Accepted,
995    /// Review verdict was "contested" — disagreement preserved as live state.
996    Contested,
997    /// Review verdict was "needs_revision" — finding stays but flagged for
998    /// confidence revision or condition refinement.
999    NeedsRevision,
1000    /// Review verdict was "rejected" — finding kept for replay history but
1001    /// not treated as active state.
1002    Rejected,
1003}
1004
1005impl ReviewState {
1006    /// Whether `flags.contested` should be true given this review_state.
1007    /// Backwards-compat shim: contested is the v0.2 derived bit.
1008    #[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    /// Derived from `review_state` for backward compatibility. Code that
1024    /// reads `flags.contested` still works; new code should read
1025    /// `review_state` for the typed verdict.
1026    #[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    /// Typed review verdict (v0.3+). When set, drives `flags.contested`
1035    /// for backward compatibility. `None` means no review verdict has
1036    /// been recorded.
1037    #[serde(default, skip_serializing_if = "Option::is_none")]
1038    pub review_state: Option<ReviewState>,
1039    /// v0.14: true once a newer content-addressed finding supersedes
1040    /// this one via the `finding.supersede` proposal kind. The newer
1041    /// finding carries a `supersedes` link back to this finding's id.
1042    /// Skipped when false so pre-v0.14 frontiers serialize byte-identically.
1043    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1044    pub superseded: bool,
1045    /// v0.37: minimum number of unique valid signatures required for
1046    /// this finding to qualify as `jointly_accepted`. `None` (the
1047    /// default) preserves single-sig semantics — any one valid
1048    /// signature is accepted. When `Some(k)`, the finding only counts
1049    /// as joint-accepted once `k` distinct registered actors have
1050    /// each contributed a valid Ed25519 signature over the canonical
1051    /// finding bytes. Pre-v0.37 frontiers omit the field; loading is
1052    /// backward-compatible.
1053    #[serde(default, skip_serializing_if = "Option::is_none")]
1054    pub signature_threshold: Option<u32>,
1055    /// v0.37: true once at least `signature_threshold` unique actors
1056    /// have signed this finding. Set by the verify pass; not written
1057    /// directly by any other code path. Skipped when false so pre-v0.37
1058    /// frontiers serialize byte-identically.
1059    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1060    pub jointly_accepted: bool,
1061}
1062
1063/// v0.38: Pearlian causal typing for an assertion. The kernel's
1064/// pre-v0.38 record carried only `direction: Some("positive" |
1065/// "negative")` — enough to know that "X covaries with Y" but not
1066/// whether the speaker meant correlation, mediation, or intervention.
1067/// In real review work those are different epistemic claims with
1068/// different evidence requirements; conflating them produced silent
1069/// over-claiming.
1070///
1071/// This release lands the schema layer. The reasoning surface
1072/// (do-calculus, identifiability, derived bridges that propagate
1073/// causal vs correlational claims separately) ships in a follow-up.
1074/// The same staging used v0.32 (Replication as object) → v0.36.1
1075/// (Project.replications becomes the source of truth for confidence).
1076#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1077#[serde(rename_all = "snake_case")]
1078pub enum CausalClaim {
1079    /// "X covaries with Y" — no claim about generative direction.
1080    Correlation,
1081    /// "X mediates Y → Z" — pathway claim, weaker than intervention.
1082    Mediation,
1083    /// "Setting X=x changes Y" — Pearl's `do(X=x)`.
1084    Intervention,
1085}
1086
1087/// v0.38: study-design grade backing a causal claim.
1088/// The grade is what makes the difference between "the data is
1089/// consistent with X causing Y" (Observational) and "X causes Y"
1090/// (Rct). The kernel carries the design label so reviewers can
1091/// re-grade without re-extracting.
1092#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1093#[serde(rename_all = "snake_case")]
1094pub enum CausalEvidenceGrade {
1095    /// Randomized controlled trial. Strongest grade for intervention claims.
1096    Rct,
1097    /// Mendelian randomization, instrumental variables, regression
1098    /// discontinuity, natural experiments, etc.
1099    QuasiExperimental,
1100    /// Cohort, case-control, cross-sectional. Identifies association
1101    /// only without further design assumptions.
1102    Observational,
1103    /// Computational simulation, theoretical model, mathematical proof.
1104    Theoretical,
1105}
1106
1107/// Valid string forms for serialized `CausalClaim`. The kernel
1108/// validates against this on load.
1109pub const VALID_CAUSAL_CLAIMS: &[&str] = &["correlation", "mediation", "intervention"];
1110
1111/// Valid string forms for serialized `CausalEvidenceGrade`.
1112pub 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    // v0.700: typed entities are an empirical-domain affordance (gene/protein/
1121    // dataset mentions). The math wedge encodes its objects in the assertion
1122    // text and OEIS/Lean anchors, never here, so the array stays empty and is
1123    // skip-guarded out of the serialised finding (see Conditions).
1124    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1125    pub entities: Vec<Entity>,
1126    pub relation: Option<String>,
1127    pub direction: Option<String>,
1128    /// v0.38: the kind of causal claim this assertion makes. `None`
1129    /// means the kernel hasn't been told yet — the legacy default for
1130    /// pre-v0.38 findings. `Some(Correlation)` is the safe minimum
1131    /// claim; `Some(Intervention)` is the strongest.
1132    #[serde(default, skip_serializing_if = "Option::is_none")]
1133    pub causal_claim: Option<CausalClaim>,
1134    /// v0.38: study-design grade backing the causal claim. Drives the
1135    /// reasoning layer's identifiability checks (deferred). Pre-v0.38
1136    /// findings omit the field; loading is backward-compatible.
1137    #[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    /// When this link was created (immutable timestamp). Uses serde default for backward compat.
1151    #[serde(default)]
1152    pub created_at: String,
1153    /// v0.45: optional structural causal mechanism on a `depends` /
1154    /// `supports` edge. When present, the edge participates in
1155    /// counterfactual (Pearl level 3) queries via twin-network
1156    /// construction. Edges without a mechanism still participate in
1157    /// level 2 (back-door / front-door identification); they simply
1158    /// can't answer twin-network counterfactuals.
1159    #[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/// v0.45: structural causal mechanism on a directed edge.
1168///
1169/// A `Mechanism` captures *how* a parent finding determines a child's
1170/// value, not just that a dependency exists. With mechanisms in place,
1171/// the kernel can answer counterfactual (Pearl level 3) queries: "given
1172/// that we observed X under parent=p, what would X have been under
1173/// parent=p'?" via twin-network construction.
1174///
1175/// Doctrine: mechanisms are deliberately coarse. Science rarely warrants
1176/// precise functional forms; what we need is enough algebraic structure
1177/// to propagate counterfactual perturbations sign-and-magnitude. Five
1178/// shapes cover the empirical distribution of biology / clinical claims:
1179///
1180/// - `Linear { sign, slope }`: dY = slope * dX (with sign packing the
1181///   direction; slope is a unitless effect-size on the [0,1] confidence
1182///   scale).
1183/// - `Monotonic { sign }`: dY agrees with sign(dX) but magnitude is
1184///   ungraded (used when direction is known but effect-size isn't).
1185/// - `Threshold { sign, threshold }`: parent must cross `threshold` for
1186///   any child response (binary above/below).
1187/// - `Saturating { sign, half_max }`: hyperbolic / Hill-style; large dX
1188///   above `half_max` produces vanishing dY.
1189/// - `Unknown`: explicitly annotated as causally connected but
1190///   mechanism unspecified. Twin-network treats this as opaque (the
1191///   counterfactual is reported as `MechanismUnspecified`).
1192#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
1193#[serde(tag = "kind", rename_all = "snake_case")]
1194pub enum Mechanism {
1195    Linear {
1196        sign: MechanismSign,
1197        /// Effect-size on [0, 1] confidence scale.
1198        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/// v0.45: causal direction on a `Mechanism`.
1215///
1216/// `Positive`: parent confidence ↑ ⇒ child confidence ↑.
1217/// `Negative`: parent confidence ↑ ⇒ child confidence ↓.
1218#[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    /// Apply this mechanism to a parent perturbation `delta_x`,
1237    /// returning the implied child perturbation `delta_y` on the
1238    /// confidence scale. Returns `None` for `Unknown`.
1239    #[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                // Hill-style: delta_y = sign * dx / (|dx| + half_max), bounded to [-1,1]
1255                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/// v0.8: typed reference resolved from `Link.target`.
1264///
1265/// Targets stay opaque `String` on the wire (canonical-JSON stable). At
1266/// validation/render time callers parse via `LinkRef::parse`. The
1267/// `Local` variant is the v0–v0.7 shape; `Cross` is new in v0.8 and
1268/// requires the dependent frontier to declare a matching `vfr_id` in
1269/// `frontier.dependencies`.
1270#[derive(Debug, Clone, PartialEq, Eq)]
1271pub enum LinkRef {
1272    /// `vf_<16hex>` — the target finding lives in this same frontier.
1273    Local { vf_id: String },
1274    /// `vf_<16hex>@vfr_<16hex>` — the target finding lives in a
1275    /// different frontier. Strict validation requires the `vfr_id` to
1276    /// appear in `Project.frontier.dependencies`.
1277    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    /// Parse `vf_<id>` or `vf_<id>@vfr_<id>` into a typed reference.
1311    /// Treats inputs as opaque hex-ish blobs — does not validate hex
1312    /// length or character set, since the substrate's content-address
1313    /// derivation already handles that.
1314    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    /// Round-trip: format back to the canonical wire string.
1348    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    /// True if this reference points outside the current frontier.
1356    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/// A lightweight annotation on a finding — like a comment on a line of code.
1443#[derive(Debug, Clone, Serialize, Deserialize)]
1444pub struct Annotation {
1445    /// Content-addressed ID (ann_{hash}).
1446    pub id: String,
1447    /// The annotation text.
1448    pub text: String,
1449    /// Who wrote it (ORCID preferred).
1450    pub author: String,
1451    /// When it was created (RFC 3339).
1452    pub timestamp: String,
1453    /// Phase β (v0.6): structured provenance for the annotation.
1454    /// Optional. When present, encodes which paper / preprint / extract
1455    /// span produced this note. Reviewers query by these fields:
1456    /// "show every annotation from PMID 25378646" works because the
1457    /// identifier is structure, not prose.
1458    #[serde(default, skip_serializing_if = "Option::is_none")]
1459    pub provenance: Option<ProvenanceRef>,
1460}
1461
1462/// Phase β (v0.6): structured provenance reference attached to an
1463/// annotation (or any future note-shaped object). At least one
1464/// identifying field (`doi`, `pmid`, `title`) must be set when the
1465/// provenance is present; an all-empty `ProvenanceRef` is rejected by
1466/// `validate_event_payload`.
1467#[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    /// Verbatim quote / extraction span from the source.
1476    #[serde(default, skip_serializing_if = "Option::is_none")]
1477    pub span: Option<String>,
1478}
1479
1480impl ProvenanceRef {
1481    /// True iff at least one identifying field is set. Used by
1482    /// `validate_event_payload` to reject all-empty `provenance: {}` objects.
1483    #[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/// A file attached to a finding (dataset, figure, supplementary material).
1490#[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// ── REVIEW layer: content-addressed review events ──────────────────────────
1502
1503/// A review event is a content-addressed record of human judgment on a finding.
1504/// Like a Git commit, it records who, when, what changed, and why.
1505#[derive(Debug, Clone, Serialize, Deserialize)]
1506pub struct ReviewEvent {
1507    /// Content-addressed ID of this review event.
1508    pub id: String,
1509    /// Optional workspace-relative origin for repo-scoped reviews.
1510    #[serde(default, skip_serializing_if = "Option::is_none")]
1511    pub workspace: Option<String>,
1512    /// ID of the finding being reviewed.
1513    pub finding_id: String,
1514    /// The reviewer (ORCID preferred).
1515    pub reviewer: String,
1516    /// When the review happened (RFC 3339).
1517    pub reviewed_at: String,
1518    /// Optional review scope for richer curation workflows.
1519    #[serde(default, skip_serializing_if = "Option::is_none")]
1520    pub scope: Option<String>,
1521    /// Optional status for the review event (for example: accepted).
1522    #[serde(default, skip_serializing_if = "Option::is_none")]
1523    pub status: Option<String>,
1524    /// What action was taken.
1525    pub action: ReviewAction,
1526    /// Human-readable reason.
1527    #[serde(default)]
1528    pub reason: String,
1529    /// Supporting findings or artifacts considered during review.
1530    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1531    pub evidence_considered: Vec<ReviewEvidence>,
1532    /// Optional structured interpretation update payload.
1533    #[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/// The action taken in a review event.
1547#[derive(Debug, Clone, Serialize, Deserialize)]
1548#[serde(tag = "type", rename_all = "snake_case")]
1549pub enum ReviewAction {
1550    /// Finding approved as correct.
1551    Approved,
1552    /// Finding interpretation was qualified to narrow or constrain the claim.
1553    Qualified { target: String },
1554    /// Finding corrected — a specific field was changed.
1555    Corrected {
1556        field: String,
1557        original: String,
1558        corrected: String,
1559    },
1560    /// Finding flagged with a specific flag type.
1561    Flagged { flag_type: String },
1562    /// Finding disputed — reviewer disagrees with the claim.
1563    Disputed {
1564        counter_evidence: String,
1565        #[serde(default, skip_serializing_if = "Option::is_none")]
1566        counter_doi: Option<String>,
1567    },
1568}
1569
1570// ── Interpretation layer: mutable confidence updates ───────────────────────
1571
1572/// A confidence update is a mutable interpretation layer event.
1573/// The finding's evidence is immutable; the confidence assessment can evolve.
1574#[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    /// Who or what produced this update (e.g., "grounding_pass", "reviewer:0000-0001-2345-6789").
1581    pub updated_by: String,
1582    /// When this update was produced (RFC 3339).
1583    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    /// v0.51: Read-side access tier. Default `Public` — pre-v0.51
1607    /// findings load with `Public` and serialize byte-identically
1608    /// (skip-if-public). Mutated through `tier.set` events; gated in
1609    /// MCP/HTTP read paths via `access_tier::redact_for_actor`. NOT
1610    /// part of the content-address preimage — re-classifying a
1611    /// finding does not mint a new id.
1612    #[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    /// Create a new finding bundle with a content-addressed ID.
1626    /// Normalize text for content-addressing: lowercase, collapse whitespace,
1627    /// strip trailing punctuation. Matches the v0.2.0 schema specification.
1628    /// Public since v0.32 so `Replication::content_address` can reuse the
1629    /// same canonicalization rule for its conditions preimage.
1630    pub fn normalize_text(s: &str) -> String {
1631        let lower = s.to_lowercase();
1632        // Collapse all runs of whitespace into a single space
1633        let collapsed: String = lower.split_whitespace().collect::<Vec<_>>().join(" ");
1634        // Strip trailing punctuation (., ;, :, !, ?)
1635        collapsed
1636            .trim_end_matches(['.', ';', ':', '!', '?'])
1637            .to_string()
1638    }
1639
1640    /// Compute the content-addressed ID per v0.2.0 spec:
1641    /// SHA-256(normalize(assertion.text) + "|" + assertion.type + "|" + (provenance.doi || provenance.pmid || provenance.title))
1642    /// Returns first 16 hex chars prefixed with "vf_".
1643    pub fn content_address(assertion: &Assertion, provenance: &Provenance) -> String {
1644        let norm_text = Self::normalize_text(&assertion.text);
1645        // v0.700: pmid removed. doi || title (no live finding was pmid-addressed,
1646        // so every existing vf_ id is unchanged).
1647        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    // ── Content-addressed ID tests ───────────────────────────────────
1804
1805    #[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); // "vf_" + 16 hex chars
1861    }
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    // ── add_link tests ───────────────────────────────────────────────
1905
1906    #[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    // ── ReviewEvent creation test ────────────────────────────────────
1961
1962    #[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    // ── ConfidenceUpdate creation test ───────────────────────────────
2021
2022    #[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    // ── Serialization round-trip test ────────────────────────────────
2038
2039    #[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    // ── Different fields change the ID ───────────────────────────────
2065
2066    #[test]
2067    fn confidence_does_not_affect_id() {
2068        // v0.2.0: confidence is the mutable interpretation layer, not part of content address
2069        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        // Flags are NOT in the content hash, so IDs should be the same
2112        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    // ── v0.2.0 content-addressing determinism ───────────────────────
2162
2163    #[test]
2164    fn content_address_is_deterministic_across_runs() {
2165        // Two independent extraction runs with the same assertion text,
2166        // assertion type, and DOI must produce the same finding ID.
2167        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        // Different entities, evidence, conditions, confidence -- should NOT matter
2192        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); // "vf_" + 16 hex chars
2277
2278        // Same title -> same ID
2279        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}