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];
96
97/// Valid link types per protocol §5.
98///
99/// T7 (FrontierGraph substrate) extends the vocabulary with the
100/// relation kinds the typed-edge layer reasons over. The conceptual
101/// T7 set is SUPPORTS / CONTRADICTS / DEPENDS_ON / DERIVED_FROM /
102/// IMPROVES / GENERALIZES / SPECIALIZES / SUPERSEDES; the existing
103/// lowercase strings already cover DEPENDS_ON (`depends`) and
104/// DERIVED_FROM (`synthesized_from`), so only the three genuinely new
105/// concepts are added here. `extends` and `replicates` predate T7 and
106/// stay. No redundant aliases — the FrontierGraph EdgeKind layer maps
107/// strings to the canonical T7 vocabulary.
108pub const VALID_LINK_TYPES: &[&str] = &[
109    "supports",
110    "contradicts",
111    "extends",
112    "depends",
113    "replicates",
114    "supersedes",
115    "synthesized_from",
116    // T7 additions:
117    "improves",
118    "generalizes",
119    "specializes",
120    // cross-domain transfer (vtr_):
121    "discharges",
122];
123
124/// The local finding id of a link target, stripping any cross-frontier
125/// `@vfr_…` suffix. A `vf_X@vfr_Y` target resolves to `vf_X`; a plain
126/// `vf_X` is returned unchanged. Single source of truth for the
127/// resolution the graph builders and read tools all rely on.
128#[must_use]
129pub fn bare_finding_id(target: &str) -> &str {
130    target.split('@').next().unwrap_or(target)
131}
132
133/// A resolved identifier from a scientific database.
134#[derive(Debug, Clone, Serialize, Deserialize)]
135pub struct ResolvedId {
136    /// The database source (mesh, uniprot, pubchem, chebi, go, ncbi_gene).
137    pub source: String,
138    /// The identifier value (e.g., "D000544", "Q6ZSS7", "24752728").
139    pub id: String,
140    /// Confidence in this resolution (0.0-1.0).
141    pub confidence: f64,
142    /// The matched name in the source database.
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub matched_name: Option<String>,
145}
146
147/// How an entity was resolved to its canonical form (v0.2.0 schema).
148#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
149#[serde(rename_all = "snake_case")]
150pub enum ResolutionMethod {
151    ExactMatch,
152    FuzzyMatch,
153    LlmInference,
154    Manual,
155}
156
157impl std::fmt::Display for ResolutionMethod {
158    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
159        match self {
160            ResolutionMethod::ExactMatch => write!(f, "exact_match"),
161            ResolutionMethod::FuzzyMatch => write!(f, "fuzzy_match"),
162            ResolutionMethod::LlmInference => write!(f, "llm_inference"),
163            ResolutionMethod::Manual => write!(f, "manual"),
164        }
165    }
166}
167
168#[derive(Debug, Clone, Serialize, Deserialize)]
169pub struct Entity {
170    pub name: String,
171    #[serde(rename = "type")]
172    pub entity_type: String,
173    /// Deprecated: flat identifiers map. Retained for backward compatibility with
174    /// older frontier JSON files. New code should use `canonical_id` and `candidates`.
175    #[serde(default)]
176    pub identifiers: serde_json::Map<String, serde_json::Value>,
177    /// The primary resolved identifier (if resolved).
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    pub canonical_id: Option<ResolvedId>,
180    /// Alternative resolution candidates with scores.
181    #[serde(default)]
182    pub candidates: Vec<ResolvedId>,
183    /// Known aliases for this entity (e.g., NLRP3 = cryopyrin = NALP3).
184    #[serde(default)]
185    pub aliases: Vec<String>,
186    /// How this resolution was performed.
187    #[serde(default, skip_serializing_if = "Option::is_none")]
188    pub resolution_provenance: Option<String>,
189    #[serde(default = "default_one")]
190    pub resolution_confidence: f64,
191    /// How the entity was resolved: exact_match, fuzzy_match, llm_inference, manual.
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub resolution_method: Option<ResolutionMethod>,
194    /// Species context for orthologs (e.g., "Homo sapiens" vs "Mus musculus" for APP).
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    pub species_context: Option<String>,
197    /// True when resolution_confidence < 0.8 and the match needs human review.
198    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
199    pub needs_review: bool,
200}
201
202fn default_one() -> f64 {
203    1.0
204}
205
206#[derive(Debug, Clone, Serialize, Deserialize)]
207pub struct Evidence {
208    #[serde(rename = "type")]
209    pub evidence_type: String,
210    #[serde(default)]
211    pub model_system: String,
212    #[serde(default)]
213    pub method: String,
214    // v0.700: the empirical-measurement slots (species/sample_size/effect_size/
215    // p_value) were removed — unused in the math wedge, stripped from every live
216    // finding by the re-genesis, byte-identical to their skip-guarded form.
217    #[serde(default)]
218    pub replicated: bool,
219    pub replication_count: Option<u32>,
220    #[serde(default)]
221    pub evidence_spans: Vec<serde_json::Value>,
222}
223
224/// v0.33: Dataset as a first-class kernel object.
225///
226/// A `Dataset` is a versioned, content-addressed reference to data
227/// that anchors empirical claims. Before v0.33, datasets were strings
228/// in `Provenance.title` or entity-typed mentions in assertions —
229/// a claim could say "we used ADNI" without anchoring which release
230/// of ADNI the analysis ran against, and re-running the same code on
231/// a refreshed cohort silently produced a "different" claim.
232///
233/// `vd_<id>` is content-addressed over `name + version + content_hash
234/// + url`. Two dataset records with the same name but different
235/// versions get distinct ids; two records pointing at the same
236/// snapshot collapse to the same id. Claims can reference the exact
237/// bytes they rest on, not only a dataset name in prose.
238#[derive(Debug, Clone, Serialize, Deserialize)]
239pub struct Dataset {
240    /// `vd_<16hex>`, content-addressed; see `Dataset::content_address`.
241    pub id: String,
242    /// Human-readable name (e.g. "ADNI", "TRAILBLAZER-ALZ", "MIMIC-IV").
243    pub name: String,
244    /// Semantic version or release tag (e.g. "ADNI-3", "v2.2", "SR0").
245    /// Two entries differing only in version are distinct kernel objects.
246    pub version: Option<String>,
247    /// Optional column-level schema as `(name, type)` pairs. For
248    /// non-tabular datasets, leave empty.
249    #[serde(default)]
250    pub schema: Vec<(String, String)>,
251    /// Number of rows / observations / records, when known.
252    pub row_count: Option<u64>,
253    /// SHA-256 of the canonical contents, when computable. For
254    /// large datasets stored remotely, this is the publisher's
255    /// declared content hash; integrity verification is the puller's
256    /// job (same pattern as `vfr_*` snapshots).
257    pub content_hash: String,
258    /// Where the dataset is reachable (https URL, file://, s3://, etc.).
259    pub url: Option<String>,
260    /// License identifier or URL (e.g. "CC-BY-4.0", a Crossref license).
261    pub license: Option<String>,
262    /// Provenance of the dataset itself — typically the paper or release
263    /// that publishes it. Reuses `Provenance` for shape parity with
264    /// findings.
265    pub provenance: Provenance,
266    /// RFC 3339 creation timestamp.
267    pub created: String,
268}
269
270impl Dataset {
271    /// Compute the content-addressed ID per v0.33 spec:
272    /// `SHA-256(name | version | content_hash | url)`.
273    /// Returns first 16 hex chars prefixed with "vd_".
274    pub fn content_address(
275        name: &str,
276        version: Option<&str>,
277        content_hash: &str,
278        url: Option<&str>,
279    ) -> String {
280        let preimage = format!(
281            "{}|{}|{}|{}",
282            name,
283            version.unwrap_or(""),
284            content_hash,
285            url.unwrap_or("")
286        );
287        let hash = Sha256::digest(preimage.as_bytes());
288        format!("vd_{}", &hex::encode(hash)[..16])
289    }
290
291    /// Construct a new Dataset with a freshly-derived id and `created`
292    /// timestamp set to now.
293    pub fn new(
294        name: impl Into<String>,
295        version: Option<String>,
296        content_hash: impl Into<String>,
297        url: Option<String>,
298        license: Option<String>,
299        provenance: Provenance,
300    ) -> Self {
301        let n = name.into();
302        let h = content_hash.into();
303        let id = Self::content_address(&n, version.as_deref(), &h, url.as_deref());
304        Self {
305            id,
306            name: n,
307            version,
308            schema: Vec::new(),
309            row_count: None,
310            content_hash: h,
311            url,
312            license,
313            provenance,
314            created: Utc::now().to_rfc3339(),
315        }
316    }
317}
318
319/// v0.33: CodeArtifact as a first-class kernel object.
320///
321/// A `CodeArtifact` is a content-addressed pointer at a specific
322/// region of source code (a function, a notebook cell, a script, a
323/// pipeline step) at a specific git commit. Before v0.33, code was
324/// captured as a string in `Evidence.method` — "we ran a logistic
325/// regression" — with no way for a reader to verify which code
326/// produced the result, or to re-run it.
327///
328/// `vc_<id>` is content-addressed over `repo_url + git_commit + path
329/// + line_range + content_hash`. The same code at two commits gets
330/// two records (the relevant historical fact); the same code in two
331/// paths in the same repo also gets two records (location matters
332/// for re-execution).
333#[derive(Debug, Clone, Serialize, Deserialize)]
334pub struct CodeArtifact {
335    /// `vc_<16hex>`, content-addressed; see `CodeArtifact::content_address`.
336    pub id: String,
337    /// Source language: `python` / `r` / `julia` / `rust` / `bash`,
338    /// etc. Not validated against a closed allow-list — code provenance
339    /// should accept whatever language the analysis was actually in.
340    pub language: String,
341    /// Repository URL (e.g. `https://github.com/vela-science/vela`).
342    pub repo_url: Option<String>,
343    /// Specific git commit (40-char SHA preferred). Required for
344    /// reproducibility; `None` means "unpinned" and weakens the
345    /// substrate claim.
346    pub git_commit: Option<String>,
347    /// Path within the repository (e.g. `crates/producer/src/notes.rs`).
348    pub path: String,
349    /// Optional line range as `(start, end)`, both inclusive.
350    pub line_range: Option<(u32, u32)>,
351    /// SHA-256 of the snippet body. Decouples the artifact from the
352    /// repository's external state — even if a repo is deleted, the
353    /// content_hash remains anchored.
354    pub content_hash: String,
355    /// Optional entry point: function name, notebook cell id, or
356    /// `__main__`. Used by re-execution tooling.
357    pub entry_point: Option<String>,
358    /// RFC 3339 creation timestamp.
359    pub created: String,
360}
361
362impl CodeArtifact {
363    /// Compute the content-addressed ID per v0.33 spec:
364    /// `SHA-256(repo_url | git_commit | path | line_range | content_hash)`.
365    /// Returns first 16 hex chars prefixed with "vc_".
366    pub fn content_address(
367        repo_url: Option<&str>,
368        git_commit: Option<&str>,
369        path: &str,
370        line_range: Option<(u32, u32)>,
371        content_hash: &str,
372    ) -> String {
373        let lr = line_range
374            .map(|(a, b)| format!("{a}-{b}"))
375            .unwrap_or_default();
376        let preimage = format!(
377            "{}|{}|{}|{}|{}",
378            repo_url.unwrap_or(""),
379            git_commit.unwrap_or(""),
380            path,
381            lr,
382            content_hash
383        );
384        let hash = Sha256::digest(preimage.as_bytes());
385        format!("vc_{}", &hex::encode(hash)[..16])
386    }
387
388    /// Construct a new CodeArtifact with a freshly-derived id and
389    /// `created` timestamp.
390    pub fn new(
391        language: impl Into<String>,
392        repo_url: Option<String>,
393        git_commit: Option<String>,
394        path: impl Into<String>,
395        line_range: Option<(u32, u32)>,
396        content_hash: impl Into<String>,
397        entry_point: Option<String>,
398    ) -> Self {
399        let p = path.into();
400        let h = content_hash.into();
401        let id = Self::content_address(
402            repo_url.as_deref(),
403            git_commit.as_deref(),
404            &p,
405            line_range,
406            &h,
407        );
408        Self {
409            id,
410            language: language.into(),
411            repo_url,
412            git_commit,
413            path: p,
414            line_range,
415            content_hash: h,
416            entry_point,
417            created: Utc::now().to_rfc3339(),
418        }
419    }
420}
421
422/// Generic content-addressed artifact.
423///
424/// This is the common substrate object for records and files that are not
425/// only papers: trial registry snapshots, protocols, supplements, notebooks,
426/// tables, figures, model outputs, lab files, and dataset manifests. Typed
427/// objects such as `Dataset` and `CodeArtifact` still exist because they
428/// carry stronger domain-specific fields. `Artifact` gives every byte or
429/// pointer the same minimum durability contract.
430#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
431#[serde(rename_all = "snake_case")]
432pub enum ArtifactDisclosure {
433    Public,
434    Restricted,
435    #[default]
436    Unknown,
437}
438
439impl ArtifactDisclosure {
440    pub(crate) fn is_unknown(value: &Self) -> bool {
441        *value == Self::Unknown
442    }
443}
444
445#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
446#[serde(rename_all = "snake_case")]
447pub enum LocatorIntegrity {
448    Immutable,
449    Mutable,
450    #[default]
451    Unknown,
452}
453
454impl LocatorIntegrity {
455    pub(crate) fn is_unknown(value: &Self) -> bool {
456        *value == Self::Unknown
457    }
458}
459
460#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
461#[serde(rename_all = "snake_case")]
462pub enum ArtifactAvailability {
463    Available,
464    Unavailable,
465    #[default]
466    Unknown,
467}
468
469impl ArtifactAvailability {
470    pub(crate) fn is_unknown(value: &Self) -> bool {
471        *value == Self::Unknown
472    }
473}
474
475#[derive(Debug, Clone, Serialize, Deserialize)]
476pub struct Artifact {
477    /// `va_<16hex>`, content-addressed over kind, name, hash, source, and
478    /// locator.
479    pub id: String,
480    /// One of `VALID_ARTIFACT_KINDS`.
481    pub kind: String,
482    /// Human-readable label.
483    pub name: String,
484    /// SHA-256 commitment. Convention: `sha256:<64hex>`.
485    pub content_hash: String,
486    /// Byte count when known.
487    #[serde(default, skip_serializing_if = "Option::is_none")]
488    pub size_bytes: Option<u64>,
489    /// MIME type or close equivalent.
490    #[serde(default, skip_serializing_if = "Option::is_none")]
491    pub media_type: Option<String>,
492    /// `local_blob`, `local_file`, `remote`, or `pointer`.
493    pub storage_mode: String,
494    /// Independent disclosure axis. Missing on legacy artifacts means
495    /// `unknown`, never silently `public`.
496    #[serde(default, skip_serializing_if = "ArtifactDisclosure::is_unknown")]
497    pub disclosure: ArtifactDisclosure,
498    /// Locator mutability is independent from storage and disclosure.
499    #[serde(default, skip_serializing_if = "LocatorIntegrity::is_unknown")]
500    pub locator_integrity: LocatorIntegrity,
501    /// Observed availability is independent from locator integrity.
502    #[serde(default, skip_serializing_if = "ArtifactAvailability::is_unknown")]
503    pub availability: ArtifactAvailability,
504    /// Local relative path, file path, HTTPS URL, S3 URL, or registry locator.
505    #[serde(default, skip_serializing_if = "Option::is_none")]
506    pub locator: Option<String>,
507    /// Original upstream URL or accession, distinct from a mirrored blob path.
508    #[serde(default, skip_serializing_if = "Option::is_none")]
509    pub source_url: Option<String>,
510    /// License identifier, URL, or access terms note.
511    #[serde(default, skip_serializing_if = "Option::is_none")]
512    pub license: Option<String>,
513    /// Findings this artifact directly bears on.
514    #[serde(default, skip_serializing_if = "Vec::is_empty")]
515    pub target_findings: Vec<String>,
516    /// Pointer to the source record that described this artifact, if one
517    /// already exists in `sources`.
518    #[serde(default, skip_serializing_if = "Option::is_none")]
519    pub source_id: Option<String>,
520    /// Artifact-level provenance. The source record may be a registry,
521    /// repository, dataset portal, protocol page, or paper.
522    pub provenance: Provenance,
523    /// Structured adapter metadata such as NCT id, outcomes, accession ids,
524    /// version tags, or retrieval timestamps.
525    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
526    pub metadata: BTreeMap<String, Value>,
527    /// Review lifecycle for the artifact itself.
528    #[serde(default, skip_serializing_if = "Option::is_none")]
529    pub review_state: Option<ReviewState>,
530    #[serde(default)]
531    pub retracted: bool,
532    #[serde(default)]
533    pub access_tier: crate::access_tier::AccessTier,
534    /// RFC 3339 creation timestamp.
535    pub created: String,
536}
537
538impl Artifact {
539    pub fn content_address(
540        kind: &str,
541        name: &str,
542        content_hash: &str,
543        source_url: Option<&str>,
544        locator: Option<&str>,
545    ) -> String {
546        let preimage = format!(
547            "{}|{}|{}|{}|{}",
548            kind,
549            name,
550            content_hash,
551            source_url.unwrap_or(""),
552            locator.unwrap_or("")
553        );
554        let hash = Sha256::digest(preimage.as_bytes());
555        format!("va_{}", &hex::encode(hash)[..16])
556    }
557
558    /// Content-address a descriptor that opts into the independent reference
559    /// axes. The all-unknown shape deliberately delegates to the legacy
560    /// preimage so existing artifact IDs remain stable.
561    #[allow(clippy::too_many_arguments)]
562    pub fn content_address_with_axes(
563        kind: &str,
564        name: &str,
565        content_hash: &str,
566        source_url: Option<&str>,
567        locator: Option<&str>,
568        disclosure: ArtifactDisclosure,
569        locator_integrity: LocatorIntegrity,
570        availability: ArtifactAvailability,
571    ) -> String {
572        if disclosure == ArtifactDisclosure::Unknown
573            && locator_integrity == LocatorIntegrity::Unknown
574            && availability == ArtifactAvailability::Unknown
575        {
576            return Self::content_address(kind, name, content_hash, source_url, locator);
577        }
578        let preimage = crate::canonical::to_canonical_bytes(&serde_json::json!({
579            "schema": "vela.artifact-reference-axes.v1",
580            "kind": kind,
581            "name": name,
582            "content_hash": content_hash,
583            "source_url": source_url,
584            "locator": locator,
585            "disclosure": disclosure,
586            "locator_integrity": locator_integrity,
587            "availability": availability,
588        }))
589        .unwrap_or_default();
590        let hash = Sha256::digest(preimage);
591        format!("va_{}", &hex::encode(hash)[..16])
592    }
593
594    /// Fail-closed validation for descriptors crossing the receipt write edge.
595    /// Restricted bytes use an opaque custodian locator in the first safe
596    /// implementation; no public equality digest is emitted until a separately
597    /// reviewed sealed-commitment scheme exists.
598    pub fn validate_reference_axes(&self) -> Result<(), String> {
599        match self.disclosure {
600            ArtifactDisclosure::Public => {
601                let digest = self.content_hash.strip_prefix("sha256:").ok_or_else(|| {
602                    "public artifact content_hash must be sha256:<64 lowercase hex>".to_string()
603                })?;
604                if digest.len() != 64
605                    || !digest
606                        .bytes()
607                        .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
608                {
609                    return Err(
610                        "public artifact content_hash must be sha256:<64 lowercase hex>"
611                            .to_string(),
612                    );
613                }
614            }
615            ArtifactDisclosure::Restricted => {
616                if !self.content_hash.is_empty() {
617                    return Err(
618                        "restricted artifact must use an opaque custodian reference; public digest disclosure requires a separately reviewed commitment scheme"
619                            .to_string(),
620                    );
621                }
622                let locator = self.locator.as_deref().unwrap_or_default();
623                if locator.trim().is_empty()
624                    || !(locator.starts_with("custodian:") || locator.starts_with("opaque:"))
625                {
626                    return Err(
627                        "restricted artifact requires an opaque custodian: or opaque: locator"
628                            .to_string(),
629                    );
630                }
631            }
632            ArtifactDisclosure::Unknown => {}
633        }
634        if self.storage_mode == "local_blob"
635            && self.availability == ArtifactAvailability::Unavailable
636        {
637            return Err("local_blob artifact cannot be declared unavailable".to_string());
638        }
639        Ok(())
640    }
641
642    #[allow(clippy::too_many_arguments)]
643    pub fn new(
644        kind: impl Into<String>,
645        name: impl Into<String>,
646        content_hash: impl Into<String>,
647        size_bytes: Option<u64>,
648        media_type: Option<String>,
649        storage_mode: impl Into<String>,
650        locator: Option<String>,
651        source_url: Option<String>,
652        license: Option<String>,
653        target_findings: Vec<String>,
654        provenance: Provenance,
655        metadata: BTreeMap<String, Value>,
656        access_tier: crate::access_tier::AccessTier,
657    ) -> Result<Self, String> {
658        let kind = kind.into();
659        if !valid_artifact_kind(&kind) {
660            return Err(format!(
661                "artifact kind '{kind}' is not supported; valid: {}",
662                VALID_ARTIFACT_KINDS.join(", ")
663            ));
664        }
665        let name = name.into();
666        if name.trim().is_empty() {
667            return Err("artifact name must be non-empty".to_string());
668        }
669        let content_hash = normalize_sha256(content_hash.into())?;
670        let storage_mode = storage_mode.into();
671        if !matches!(
672            storage_mode.as_str(),
673            "local_blob" | "local_file" | "remote" | "pointer"
674        ) {
675            return Err(format!(
676                "artifact storage_mode '{storage_mode}' is not supported; valid: local_blob, local_file, remote, pointer"
677            ));
678        }
679        let id = Self::content_address(
680            &kind,
681            &name,
682            &content_hash,
683            source_url.as_deref(),
684            locator.as_deref(),
685        );
686        Ok(Self {
687            id,
688            kind,
689            name,
690            content_hash,
691            size_bytes,
692            media_type,
693            storage_mode,
694            disclosure: ArtifactDisclosure::Unknown,
695            locator_integrity: LocatorIntegrity::Unknown,
696            availability: ArtifactAvailability::Unknown,
697            locator,
698            source_url,
699            license,
700            target_findings,
701            source_id: None,
702            provenance,
703            metadata,
704            review_state: None,
705            retracted: false,
706            access_tier,
707            created: Utc::now().to_rfc3339(),
708        })
709    }
710}
711
712fn normalize_sha256(value: String) -> Result<String, String> {
713    let trimmed = value.trim();
714    let hex = trimmed.strip_prefix("sha256:").unwrap_or(trimmed);
715    if hex.len() != 64 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
716        return Err(format!(
717            "content_hash must be sha256:<64hex> or 64 hex chars, got {trimmed:?}"
718        ));
719    }
720    Ok(format!("sha256:{}", hex.to_ascii_lowercase()))
721}
722
723#[derive(Debug, Clone, Serialize, Deserialize)]
724pub struct Conditions {
725    #[serde(default)]
726    pub text: String,
727    // v0.700: the empirical-context slots (species_verified/species_unverified/
728    // in_vitro/in_vivo/human_data/clinical_trial/concentration_range/age_group/
729    // cell_type) were removed. The cheap-verifier math wedge never populated them,
730    // the re-genesis stripped them from every live finding, and dropping the struct
731    // fields is byte-identical to their skip-guarded (always-omitted) form.
732    pub duration: Option<String>,
733}
734
735/// Confidence method: how the score was determined.
736#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
737#[serde(rename_all = "snake_case")]
738#[derive(Default)]
739pub enum ConfidenceMethod {
740    /// Computed from structured frontier support components (v0.2.0).
741    Computed,
742    /// A human expert assigned it.
743    ExpertJudgment,
744    /// Legacy import path for confidence seeded before component breakdown existed.
745    #[default]
746    LlmInitial,
747}
748
749/// Semantic category of the confidence score stored on the frontier.
750#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
751#[serde(rename_all = "snake_case")]
752pub enum ConfidenceKind {
753    /// Bounded epistemic support for the finding as currently represented in frontier state.
754    #[default]
755    FrontierEpistemic,
756}
757
758#[derive(Debug, Clone, Serialize, Deserialize)]
759pub struct Confidence {
760    /// Semantic meaning of `score`. v0 emits `frontier_epistemic`.
761    #[serde(default)]
762    pub kind: ConfidenceKind,
763    pub score: f64,
764    pub basis: String,
765    /// How this score was determined.
766    #[serde(default)]
767    pub method: ConfidenceMethod,
768    /// Confidence in the extraction itself (separate from scientific confidence).
769    #[serde(default = "default_extraction_conf")]
770    pub extraction_confidence: f64,
771}
772
773fn default_extraction_conf() -> f64 {
774    0.85
775}
776
777impl Confidence {
778    /// Construct a `Confidence` with a raw score and basis string. The
779    /// agent and verifier layers use this directly: a frozen verifier
780    /// assigns `score = 1.0`, while an LLM extraction supplies a single
781    /// confidence value.
782    ///
783    /// Renamed from `legacy()` in v0.36; the previous name was a
784    /// historical accident (the constructor was never actually
785    /// deprecated, just misnamed).
786    pub fn raw(score: f64, basis: impl Into<String>, extraction_confidence: f64) -> Self {
787        Self {
788            kind: ConfidenceKind::FrontierEpistemic,
789            score,
790            basis: basis.into(),
791            method: ConfidenceMethod::LlmInitial,
792            extraction_confidence,
793        }
794    }
795}
796
797#[derive(Debug, Clone, Default, Serialize, Deserialize)]
798pub struct Extraction {
799    #[serde(default = "default_extraction_method")]
800    pub method: String,
801    pub model: Option<String>,
802    pub model_version: Option<String>,
803    #[serde(default)]
804    pub extracted_at: String,
805    #[serde(default = "default_extractor_version")]
806    pub extractor_version: String,
807}
808
809fn default_extraction_method() -> String {
810    "llm_extraction".into()
811}
812fn default_extractor_version() -> String {
813    "vela/0.2.0".into()
814}
815
816#[derive(Debug, Clone, Serialize, Deserialize)]
817pub struct Review {
818    #[serde(default)]
819    pub reviewed: bool,
820    pub reviewer: Option<String>,
821    pub reviewed_at: Option<String>,
822    #[serde(default)]
823    pub corrections: Vec<serde_json::Value>,
824}
825
826#[derive(Debug, Clone, Serialize, Deserialize)]
827pub struct Author {
828    pub name: String,
829    pub orcid: Option<String>,
830}
831
832/// What sub-part of a finding a contribution applies to.
833#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
834#[serde(rename_all = "snake_case")]
835pub enum ContributionUnitType {
836    /// An evidence span within a paper finding.
837    EvidenceSpan,
838    /// A Lean declaration name (FC / formal findings).
839    LeanDecl,
840    /// A single step of an argument.
841    Step,
842    /// The whole bundle (the finding-level default).
843    Whole,
844}
845
846/// The kind of actor behind a contribution. A `model` holds no key and can never
847/// be accountable; only a `human` can carry a signature.
848#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
849#[serde(rename_all = "snake_case")]
850pub enum AgentKind {
851    Human,
852    Agent,
853    Model,
854}
855
856/// The kind of contribution. Only `vouched` carries trust weight, and it maps to
857/// a human signature — a `model` or `agent` can never be `vouched`.
858#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
859#[serde(rename_all = "snake_case")]
860pub enum ContributionRole {
861    Originated,
862    Derived,
863    Formalized,
864    Extracted,
865    Reviewed,
866    Vouched,
867}
868
869/// One attribution record at claim granularity: which actor contributed which
870/// unit of a finding, and in what role. Descriptive provenance only — the
871/// reducer never reads it as state, the gate never reads it as evidence, and it
872/// is outside the `vf_` id preimage (adding it does not change the finding id).
873#[derive(Debug, Clone, Serialize, Deserialize)]
874pub struct Contribution {
875    /// The sub-claim reference: an evidence-span ref, a Lean decl name, or the
876    /// literal `whole` (the current finding-level behaviour).
877    pub unit: String,
878    pub unit_type: ContributionUnitType,
879    pub agent_kind: AgentKind,
880    /// ORCID, agent handle, or model id.
881    pub agent_id: String,
882    #[serde(default, skip_serializing_if = "Option::is_none")]
883    pub model: Option<String>,
884    #[serde(default, skip_serializing_if = "Option::is_none")]
885    pub model_version: Option<String>,
886    pub role: ContributionRole,
887    /// Free text or an evidence-span reference backing the claim.
888    #[serde(default, skip_serializing_if = "String::is_empty")]
889    pub basis: String,
890}
891
892impl AgentKind {
893    #[must_use]
894    pub fn as_str(&self) -> &'static str {
895        match self {
896            Self::Human => "human",
897            Self::Agent => "agent",
898            Self::Model => "model",
899        }
900    }
901}
902
903impl ContributionRole {
904    #[must_use]
905    pub fn as_str(&self) -> &'static str {
906        match self {
907            Self::Originated => "originated",
908            Self::Derived => "derived",
909            Self::Formalized => "formalized",
910            Self::Extracted => "extracted",
911            Self::Reviewed => "reviewed",
912            Self::Vouched => "vouched",
913        }
914    }
915}
916
917impl Contribution {
918    /// The one trust invariant: `vouched` is a human-signature role, so a
919    /// `model` or `agent` can never carry it. Structural, not a verdict.
920    pub fn validate(&self) -> Result<(), String> {
921        if self.role == ContributionRole::Vouched && self.agent_kind != AgentKind::Human {
922            return Err(
923                "a contribution with role `vouched` must be a human (agents and models hold no key)"
924                    .to_string(),
925            );
926        }
927        if self.unit.trim().is_empty() {
928            return Err("contribution `unit` must be non-empty".to_string());
929        }
930        if self.agent_id.trim().is_empty() {
931            return Err("contribution `agent_id` must be non-empty".to_string());
932        }
933        Ok(())
934    }
935}
936
937#[derive(Debug, Clone, Serialize, Deserialize)]
938pub struct Provenance {
939    #[serde(default = "default_source_type")]
940    pub source_type: String,
941    pub doi: Option<String>,
942    // v0.700: the bibliometric slots (pmid/pmc/openalex_id/journal/citation_count)
943    // were removed. The math wedge cites by DOI/title, never PubMed/OpenAlex; the
944    // re-genesis stripped them from every live finding (0 were pmid-addressed, so
945    // content_address now uses doi||title with no id change). Byte-identical to the
946    // skip-guarded form.
947    /// v0.11: generic source URL when none of the structured identifiers
948    /// fit (preprint server URL, dataset landing page, talk recording, etc.).
949    /// Skipped when None so pre-v0.11 frontiers serialise byte-identically.
950    #[serde(default, skip_serializing_if = "Option::is_none")]
951    pub url: Option<String>,
952    #[serde(default)]
953    pub title: String,
954    #[serde(default)]
955    pub authors: Vec<Author>,
956    pub year: Option<i32>,
957    /// License URL (e.g., Creative Commons), typically from Crossref.
958    #[serde(default, skip_serializing_if = "Option::is_none")]
959    pub license: Option<String>,
960    /// Publisher name, typically from Crossref.
961    #[serde(default, skip_serializing_if = "Option::is_none")]
962    pub publisher: Option<String>,
963    /// Funding sources, typically from Crossref.
964    #[serde(default, skip_serializing_if = "Vec::is_empty")]
965    pub funders: Vec<String>,
966    #[serde(default)]
967    pub extraction: Extraction,
968    pub review: Option<Review>,
969    /// Claim-granularity attribution: which actor originated / derived /
970    /// formalized which unit of this finding. Descriptive provenance, distinct
971    /// from `extraction` (who extracted the whole bundle) and `authors` (the
972    /// source paper's humans). Skipped when empty so pre-existing bundles
973    /// serialise byte-identically, and outside the `vf_` id preimage.
974    #[serde(default, skip_serializing_if = "Vec::is_empty")]
975    pub contributions: Vec<Contribution>,
976}
977
978fn default_source_type() -> String {
979    "published_paper".into()
980}
981
982/// Typed review state. Replaces the v0.2 `flags.contested: bool` collapse
983/// of three semantically distinct review judgments. Doctrine line 6:
984/// "scientific disagreement should remain live state."
985#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
986#[serde(rename_all = "snake_case")]
987pub enum ReviewState {
988    /// Review verdict was "accepted" or "approved" — finding stands.
989    Accepted,
990    /// Review verdict was "contested" — disagreement preserved as live state.
991    Contested,
992    /// Review verdict was "needs_revision" — finding stays but flagged for
993    /// confidence revision or condition refinement.
994    NeedsRevision,
995    /// Review verdict was "rejected" — finding kept for replay history but
996    /// not treated as active state.
997    Rejected,
998}
999
1000impl ReviewState {
1001    /// Whether `flags.contested` should be true given this review_state.
1002    /// Backwards-compat shim: contested is the v0.2 derived bit.
1003    #[must_use]
1004    pub fn implies_contested(&self) -> bool {
1005        matches!(
1006            self,
1007            ReviewState::Contested | ReviewState::NeedsRevision | ReviewState::Rejected
1008        )
1009    }
1010}
1011
1012#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1013pub struct Flags {
1014    #[serde(default)]
1015    pub gap: bool,
1016    #[serde(default)]
1017    pub negative_space: bool,
1018    /// Derived from `review_state` for backward compatibility. Code that
1019    /// reads `flags.contested` still works; new code should read
1020    /// `review_state` for the typed verdict.
1021    #[serde(default)]
1022    pub contested: bool,
1023    #[serde(default)]
1024    pub retracted: bool,
1025    #[serde(default)]
1026    pub declining: bool,
1027    #[serde(default)]
1028    pub gravity_well: bool,
1029    /// Typed review verdict (v0.3+). When set, drives `flags.contested`
1030    /// for backward compatibility. `None` means no review verdict has
1031    /// been recorded.
1032    #[serde(default, skip_serializing_if = "Option::is_none")]
1033    pub review_state: Option<ReviewState>,
1034    /// v0.14: true once a newer content-addressed finding supersedes
1035    /// this one via the `finding.supersede` proposal kind. The newer
1036    /// finding carries a `supersedes` link back to this finding's id.
1037    /// Skipped when false so pre-v0.14 frontiers serialize byte-identically.
1038    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1039    pub superseded: bool,
1040    /// v0.37: minimum number of unique valid signatures required for
1041    /// this finding to qualify as `jointly_accepted`. `None` (the
1042    /// default) preserves single-sig semantics — any one valid
1043    /// signature is accepted. When `Some(k)`, the finding only counts
1044    /// as joint-accepted once `k` distinct registered actors have
1045    /// each contributed a valid Ed25519 signature over the canonical
1046    /// finding bytes. Pre-v0.37 frontiers omit the field; loading is
1047    /// backward-compatible.
1048    #[serde(default, skip_serializing_if = "Option::is_none")]
1049    pub signature_threshold: Option<u32>,
1050    /// v0.37: true once at least `signature_threshold` unique actors
1051    /// have signed this finding. Set by the verify pass; not written
1052    /// directly by any other code path. Skipped when false so pre-v0.37
1053    /// frontiers serialize byte-identically.
1054    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1055    pub jointly_accepted: bool,
1056}
1057
1058/// v0.38: Pearlian causal typing for an assertion. The kernel's
1059/// pre-v0.38 record carried only `direction: Some("positive" |
1060/// "negative")` — enough to know that "X covaries with Y" but not
1061/// whether the speaker meant correlation, mediation, or intervention.
1062/// In real review work those are different epistemic claims with
1063/// different evidence requirements; conflating them produced silent
1064/// over-claiming.
1065///
1066/// This release lands the schema layer. The reasoning surface
1067/// (do-calculus, identifiability, derived bridges that propagate
1068/// causal vs correlational claims separately) ships in a follow-up.
1069/// The same staging used v0.32 (Replication as object) → v0.36.1
1070/// (Project.replications becomes the source of truth for confidence).
1071#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1072#[serde(rename_all = "snake_case")]
1073pub enum CausalClaim {
1074    /// "X covaries with Y" — no claim about generative direction.
1075    Correlation,
1076    /// "X mediates Y → Z" — pathway claim, weaker than intervention.
1077    Mediation,
1078    /// "Setting X=x changes Y" — Pearl's `do(X=x)`.
1079    Intervention,
1080}
1081
1082/// v0.38: study-design grade backing a causal claim.
1083/// The grade is what makes the difference between "the data is
1084/// consistent with X causing Y" (Observational) and "X causes Y"
1085/// (Rct). The kernel carries the design label so reviewers can
1086/// re-grade without re-extracting.
1087#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1088#[serde(rename_all = "snake_case")]
1089pub enum CausalEvidenceGrade {
1090    /// Randomized controlled trial. Strongest grade for intervention claims.
1091    Rct,
1092    /// Mendelian randomization, instrumental variables, regression
1093    /// discontinuity, natural experiments, etc.
1094    QuasiExperimental,
1095    /// Cohort, case-control, cross-sectional. Identifies association
1096    /// only without further design assumptions.
1097    Observational,
1098    /// Computational simulation, theoretical model, mathematical proof.
1099    Theoretical,
1100}
1101
1102/// Valid string forms for serialized `CausalClaim`. The kernel
1103/// validates against this on load.
1104pub const VALID_CAUSAL_CLAIMS: &[&str] = &["correlation", "mediation", "intervention"];
1105
1106/// Valid string forms for serialized `CausalEvidenceGrade`.
1107pub const VALID_CAUSAL_EVIDENCE_GRADES: &[&str] =
1108    &["rct", "quasi_experimental", "observational", "theoretical"];
1109
1110#[derive(Debug, Clone, Serialize, Deserialize)]
1111pub struct Assertion {
1112    pub text: String,
1113    #[serde(rename = "type")]
1114    pub assertion_type: String,
1115    // v0.700: typed entities are an empirical-domain affordance (gene/protein/
1116    // dataset mentions). The math wedge encodes its objects in the assertion
1117    // text and OEIS/Lean anchors, never here, so the array stays empty and is
1118    // skip-guarded out of the serialised finding (see Conditions).
1119    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1120    pub entities: Vec<Entity>,
1121    pub relation: Option<String>,
1122    pub direction: Option<String>,
1123    /// v0.38: the kind of causal claim this assertion makes. `None`
1124    /// means the kernel hasn't been told yet — the legacy default for
1125    /// pre-v0.38 findings. `Some(Correlation)` is the safe minimum
1126    /// claim; `Some(Intervention)` is the strongest.
1127    #[serde(default, skip_serializing_if = "Option::is_none")]
1128    pub causal_claim: Option<CausalClaim>,
1129    /// v0.38: study-design grade backing the causal claim. Drives the
1130    /// reasoning layer's identifiability checks (deferred). Pre-v0.38
1131    /// findings omit the field; loading is backward-compatible.
1132    #[serde(default, skip_serializing_if = "Option::is_none")]
1133    pub causal_evidence_grade: Option<CausalEvidenceGrade>,
1134}
1135
1136#[derive(Debug, Clone, Serialize, Deserialize)]
1137pub struct Link {
1138    pub target: String,
1139    #[serde(rename = "type")]
1140    pub link_type: String,
1141    #[serde(default)]
1142    pub note: String,
1143    #[serde(default = "default_compiler")]
1144    pub inferred_by: String,
1145    /// When this link was created (immutable timestamp). Uses serde default for backward compat.
1146    #[serde(default)]
1147    pub created_at: String,
1148    /// v0.45: optional structural causal mechanism on a `depends` /
1149    /// `supports` edge. When present, the edge participates in
1150    /// counterfactual (Pearl level 3) queries via twin-network
1151    /// construction. Edges without a mechanism still participate in
1152    /// level 2 (back-door / front-door identification); they simply
1153    /// can't answer twin-network counterfactuals.
1154    #[serde(default, skip_serializing_if = "Option::is_none")]
1155    pub mechanism: Option<Mechanism>,
1156}
1157
1158fn default_compiler() -> String {
1159    "compiler".into()
1160}
1161
1162/// v0.45: structural causal mechanism on a directed edge.
1163///
1164/// A `Mechanism` captures *how* a parent finding determines a child's
1165/// value, not just that a dependency exists. With mechanisms in place,
1166/// the kernel can answer counterfactual (Pearl level 3) queries: "given
1167/// that we observed X under parent=p, what would X have been under
1168/// parent=p'?" via twin-network construction.
1169///
1170/// Doctrine: mechanisms are deliberately coarse. Science rarely warrants
1171/// precise functional forms; what we need is enough algebraic structure
1172/// to propagate counterfactual perturbations sign-and-magnitude. Five
1173/// shapes cover the empirical distribution of biology / clinical claims:
1174///
1175/// - `Linear { sign, slope }`: dY = slope * dX (with sign packing the
1176///   direction; slope is a unitless effect-size on the [0,1] confidence
1177///   scale).
1178/// - `Monotonic { sign }`: dY agrees with sign(dX) but magnitude is
1179///   ungraded (used when direction is known but effect-size isn't).
1180/// - `Threshold { sign, threshold }`: parent must cross `threshold` for
1181///   any child response (binary above/below).
1182/// - `Saturating { sign, half_max }`: hyperbolic / Hill-style; large dX
1183///   above `half_max` produces vanishing dY.
1184/// - `Unknown`: explicitly annotated as causally connected but
1185///   mechanism unspecified. Twin-network treats this as opaque (the
1186///   counterfactual is reported as `MechanismUnspecified`).
1187#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
1188#[serde(tag = "kind", rename_all = "snake_case")]
1189pub enum Mechanism {
1190    Linear {
1191        sign: MechanismSign,
1192        /// Effect-size on [0, 1] confidence scale.
1193        slope: f64,
1194    },
1195    Monotonic {
1196        sign: MechanismSign,
1197    },
1198    Threshold {
1199        sign: MechanismSign,
1200        threshold: f64,
1201    },
1202    Saturating {
1203        sign: MechanismSign,
1204        half_max: f64,
1205    },
1206    Unknown,
1207}
1208
1209/// v0.45: causal direction on a `Mechanism`.
1210///
1211/// `Positive`: parent confidence ↑ ⇒ child confidence ↑.
1212/// `Negative`: parent confidence ↑ ⇒ child confidence ↓.
1213#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1214#[serde(rename_all = "lowercase")]
1215pub enum MechanismSign {
1216    Positive,
1217    Negative,
1218}
1219
1220impl MechanismSign {
1221    #[must_use]
1222    pub fn as_f64(self) -> f64 {
1223        match self {
1224            Self::Positive => 1.0,
1225            Self::Negative => -1.0,
1226        }
1227    }
1228}
1229
1230impl Mechanism {
1231    /// Apply this mechanism to a parent perturbation `delta_x`,
1232    /// returning the implied child perturbation `delta_y` on the
1233    /// confidence scale. Returns `None` for `Unknown`.
1234    #[must_use]
1235    pub fn apply(&self, delta_x: f64) -> Option<f64> {
1236        match *self {
1237            Self::Linear { sign, slope } => Some(sign.as_f64() * slope * delta_x),
1238            Self::Monotonic { sign } => {
1239                Some(sign.as_f64() * delta_x.signum() * delta_x.abs().min(1.0))
1240            }
1241            Self::Threshold { sign, threshold } => {
1242                if delta_x.abs() >= threshold {
1243                    Some(sign.as_f64() * delta_x.signum())
1244                } else {
1245                    Some(0.0)
1246                }
1247            }
1248            Self::Saturating { sign, half_max } => {
1249                // Hill-style: delta_y = sign * dx / (|dx| + half_max), bounded to [-1,1]
1250                let denom = delta_x.abs() + half_max.max(1e-9);
1251                Some(sign.as_f64() * delta_x / denom)
1252            }
1253            Self::Unknown => None,
1254        }
1255    }
1256}
1257
1258/// v0.8: typed reference resolved from `Link.target`.
1259///
1260/// Targets stay opaque `String` on the wire (canonical-JSON stable). At
1261/// validation/render time callers parse via `LinkRef::parse`. The
1262/// `Local` variant is the v0–v0.7 shape; `Cross` is new in v0.8 and
1263/// requires the dependent frontier to declare a matching `vfr_id` in
1264/// `frontier.dependencies`.
1265#[derive(Debug, Clone, PartialEq, Eq)]
1266pub enum LinkRef {
1267    /// `vf_<16hex>` — the target finding lives in this same frontier.
1268    Local { vf_id: String },
1269    /// `vf_<16hex>@vfr_<16hex>` — the target finding lives in a
1270    /// different frontier. Strict validation requires the `vfr_id` to
1271    /// appear in `Project.frontier.dependencies`.
1272    Cross { vf_id: String, vfr_id: String },
1273}
1274
1275#[derive(Debug, Clone, PartialEq, Eq)]
1276pub enum LinkParseError {
1277    Empty,
1278    BadVfPrefix,
1279    BadVfrPrefix,
1280    EmptyVfId,
1281    EmptyVfrId,
1282    TooManyAtSigns,
1283}
1284
1285impl std::fmt::Display for LinkParseError {
1286    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1287        match self {
1288            LinkParseError::Empty => write!(f, "empty link target"),
1289            LinkParseError::BadVfPrefix => write!(f, "link target must start with 'vf_'"),
1290            LinkParseError::BadVfrPrefix => {
1291                write!(f, "cross-frontier suffix must start with 'vfr_'")
1292            }
1293            LinkParseError::EmptyVfId => write!(f, "link target's vf_ id is empty"),
1294            LinkParseError::EmptyVfrId => write!(f, "cross-frontier vfr_ id is empty"),
1295            LinkParseError::TooManyAtSigns => {
1296                write!(f, "link target has more than one '@' separator")
1297            }
1298        }
1299    }
1300}
1301
1302impl std::error::Error for LinkParseError {}
1303
1304impl LinkRef {
1305    /// Parse `vf_<id>` or `vf_<id>@vfr_<id>` into a typed reference.
1306    /// Treats inputs as opaque hex-ish blobs — does not validate hex
1307    /// length or character set, since the substrate's content-address
1308    /// derivation already handles that.
1309    pub fn parse(s: &str) -> Result<Self, LinkParseError> {
1310        if s.is_empty() {
1311            return Err(LinkParseError::Empty);
1312        }
1313        let mut parts = s.split('@');
1314        let local = parts.next().ok_or(LinkParseError::Empty)?;
1315        let remote = parts.next();
1316        if parts.next().is_some() {
1317            return Err(LinkParseError::TooManyAtSigns);
1318        }
1319        let vf_id = local
1320            .strip_prefix("vf_")
1321            .ok_or(LinkParseError::BadVfPrefix)?;
1322        if vf_id.is_empty() {
1323            return Err(LinkParseError::EmptyVfId);
1324        }
1325        match remote {
1326            None => Ok(LinkRef::Local {
1327                vf_id: local.to_string(),
1328            }),
1329            Some(r) => {
1330                let vfr_id = r.strip_prefix("vfr_").ok_or(LinkParseError::BadVfrPrefix)?;
1331                if vfr_id.is_empty() {
1332                    return Err(LinkParseError::EmptyVfrId);
1333                }
1334                Ok(LinkRef::Cross {
1335                    vf_id: local.to_string(),
1336                    vfr_id: r.to_string(),
1337                })
1338            }
1339        }
1340    }
1341
1342    /// Round-trip: format back to the canonical wire string.
1343    pub fn format(&self) -> String {
1344        match self {
1345            LinkRef::Local { vf_id } => vf_id.clone(),
1346            LinkRef::Cross { vf_id, vfr_id } => format!("{vf_id}@{vfr_id}"),
1347        }
1348    }
1349
1350    /// True if this reference points outside the current frontier.
1351    pub fn is_cross_frontier(&self) -> bool {
1352        matches!(self, LinkRef::Cross { .. })
1353    }
1354}
1355
1356#[cfg(test)]
1357mod link_ref_tests {
1358    use super::*;
1359
1360    #[test]
1361    fn parses_local_vf_id() {
1362        let r = LinkRef::parse("vf_abc123").unwrap();
1363        assert_eq!(
1364            r,
1365            LinkRef::Local {
1366                vf_id: "vf_abc123".into()
1367            }
1368        );
1369        assert_eq!(r.format(), "vf_abc123");
1370        assert!(!r.is_cross_frontier());
1371    }
1372
1373    #[test]
1374    fn parses_cross_frontier_target() {
1375        let r = LinkRef::parse("vf_abc@vfr_def").unwrap();
1376        assert_eq!(
1377            r,
1378            LinkRef::Cross {
1379                vf_id: "vf_abc".into(),
1380                vfr_id: "vfr_def".into(),
1381            }
1382        );
1383        assert_eq!(r.format(), "vf_abc@vfr_def");
1384        assert!(r.is_cross_frontier());
1385    }
1386
1387    #[test]
1388    fn rejects_empty() {
1389        assert_eq!(LinkRef::parse(""), Err(LinkParseError::Empty));
1390    }
1391
1392    #[test]
1393    fn rejects_missing_vf_prefix() {
1394        assert_eq!(LinkRef::parse("xx_abc"), Err(LinkParseError::BadVfPrefix));
1395    }
1396
1397    #[test]
1398    fn rejects_empty_vf_id() {
1399        assert_eq!(LinkRef::parse("vf_"), Err(LinkParseError::EmptyVfId));
1400    }
1401
1402    #[test]
1403    fn rejects_missing_vfr_prefix_after_at() {
1404        assert_eq!(
1405            LinkRef::parse("vf_abc@xxx_def"),
1406            Err(LinkParseError::BadVfrPrefix)
1407        );
1408    }
1409
1410    #[test]
1411    fn rejects_empty_vfr_id() {
1412        assert_eq!(
1413            LinkRef::parse("vf_abc@vfr_"),
1414            Err(LinkParseError::EmptyVfrId)
1415        );
1416    }
1417
1418    #[test]
1419    fn rejects_double_at() {
1420        assert_eq!(
1421            LinkRef::parse("vf_abc@vfr_def@x"),
1422            Err(LinkParseError::TooManyAtSigns)
1423        );
1424    }
1425
1426    #[test]
1427    fn round_trips_real_ids() {
1428        for s in [
1429            "vf_d0a962d3251133dd",
1430            "vf_d0a962d3251133dd@vfr_7344e96c0f2669d5",
1431        ] {
1432            assert_eq!(LinkRef::parse(s).unwrap().format(), s);
1433        }
1434    }
1435}
1436
1437/// A lightweight annotation on a finding — like a comment on a line of code.
1438#[derive(Debug, Clone, Serialize, Deserialize)]
1439pub struct Annotation {
1440    /// Content-addressed ID (ann_{hash}).
1441    pub id: String,
1442    /// The annotation text.
1443    pub text: String,
1444    /// Who wrote it (ORCID preferred).
1445    pub author: String,
1446    /// When it was created (RFC 3339).
1447    pub timestamp: String,
1448    /// Phase β (v0.6): structured provenance for the annotation.
1449    /// Optional. When present, encodes which paper / preprint / extract
1450    /// span produced this note. Reviewers query by these fields:
1451    /// "show every annotation from PMID 25378646" works because the
1452    /// identifier is structure, not prose.
1453    #[serde(default, skip_serializing_if = "Option::is_none")]
1454    pub provenance: Option<ProvenanceRef>,
1455}
1456
1457/// Phase β (v0.6): structured provenance reference attached to an
1458/// annotation (or any future note-shaped object). At least one
1459/// identifying field (`doi`, `pmid`, `title`) must be set when the
1460/// provenance is present; an all-empty `ProvenanceRef` is rejected by
1461/// `validate_event_payload`.
1462#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1463pub struct ProvenanceRef {
1464    #[serde(default, skip_serializing_if = "Option::is_none")]
1465    pub doi: Option<String>,
1466    #[serde(default, skip_serializing_if = "Option::is_none")]
1467    pub pmid: Option<String>,
1468    #[serde(default, skip_serializing_if = "Option::is_none")]
1469    pub title: Option<String>,
1470    /// Verbatim quote / extraction span from the source.
1471    #[serde(default, skip_serializing_if = "Option::is_none")]
1472    pub span: Option<String>,
1473}
1474
1475impl ProvenanceRef {
1476    /// True iff at least one identifying field is set. Used by
1477    /// `validate_event_payload` to reject all-empty `provenance: {}` objects.
1478    #[must_use]
1479    pub fn has_identifier(&self) -> bool {
1480        self.doi.is_some() || self.pmid.is_some() || self.title.is_some()
1481    }
1482}
1483
1484/// A file attached to a finding (dataset, figure, supplementary material).
1485#[derive(Debug, Clone, Serialize, Deserialize)]
1486pub struct Attachment {
1487    pub filename: String,
1488    pub label: Option<String>,
1489    pub path: String,
1490    pub size_bytes: u64,
1491    pub mime_type: Option<String>,
1492    pub attached_at: String,
1493    pub attached_by: Option<String>,
1494}
1495
1496// ── REVIEW layer: content-addressed review events ──────────────────────────
1497
1498/// A review event is a content-addressed record of human judgment on a finding.
1499/// Like a Git commit, it records who, when, what changed, and why.
1500#[derive(Debug, Clone, Serialize, Deserialize)]
1501pub struct ReviewEvent {
1502    /// Content-addressed ID of this review event.
1503    pub id: String,
1504    /// Optional workspace-relative origin for repo-scoped reviews.
1505    #[serde(default, skip_serializing_if = "Option::is_none")]
1506    pub workspace: Option<String>,
1507    /// ID of the finding being reviewed.
1508    pub finding_id: String,
1509    /// The reviewer (ORCID preferred).
1510    pub reviewer: String,
1511    /// When the review happened (RFC 3339).
1512    pub reviewed_at: String,
1513    /// Optional review scope for richer curation workflows.
1514    #[serde(default, skip_serializing_if = "Option::is_none")]
1515    pub scope: Option<String>,
1516    /// Optional status for the review event (for example: accepted).
1517    #[serde(default, skip_serializing_if = "Option::is_none")]
1518    pub status: Option<String>,
1519    /// What action was taken.
1520    pub action: ReviewAction,
1521    /// Human-readable reason.
1522    #[serde(default)]
1523    pub reason: String,
1524    /// Supporting findings or artifacts considered during review.
1525    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1526    pub evidence_considered: Vec<ReviewEvidence>,
1527    /// Optional structured interpretation update payload.
1528    #[serde(default, skip_serializing_if = "Option::is_none")]
1529    pub state_change: Option<serde_json::Value>,
1530}
1531
1532#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1533pub struct ReviewEvidence {
1534    pub finding_id: String,
1535    #[serde(default, skip_serializing_if = "Option::is_none")]
1536    pub role: Option<String>,
1537    #[serde(default, skip_serializing_if = "Option::is_none")]
1538    pub note: Option<String>,
1539}
1540
1541/// The action taken in a review event.
1542#[derive(Debug, Clone, Serialize, Deserialize)]
1543#[serde(tag = "type", rename_all = "snake_case")]
1544pub enum ReviewAction {
1545    /// Finding approved as correct.
1546    Approved,
1547    /// Finding interpretation was qualified to narrow or constrain the claim.
1548    Qualified { target: String },
1549    /// Finding corrected — a specific field was changed.
1550    Corrected {
1551        field: String,
1552        original: String,
1553        corrected: String,
1554    },
1555    /// Finding flagged with a specific flag type.
1556    Flagged { flag_type: String },
1557    /// Finding disputed — reviewer disagrees with the claim.
1558    Disputed {
1559        counter_evidence: String,
1560        #[serde(default, skip_serializing_if = "Option::is_none")]
1561        counter_doi: Option<String>,
1562    },
1563}
1564
1565// ── Interpretation layer: mutable confidence updates ───────────────────────
1566
1567/// A confidence update is a mutable interpretation layer event.
1568/// The finding's evidence is immutable; the confidence assessment can evolve.
1569#[derive(Debug, Clone, Serialize, Deserialize)]
1570pub struct ConfidenceUpdate {
1571    pub finding_id: String,
1572    pub previous_score: f64,
1573    pub new_score: f64,
1574    pub basis: String,
1575    /// Who or what produced this update (e.g., "grounding_pass", "reviewer:0000-0001-2345-6789").
1576    pub updated_by: String,
1577    /// When this update was produced (RFC 3339).
1578    pub updated_at: String,
1579}
1580
1581#[derive(Debug, Clone, Serialize, Deserialize)]
1582pub struct FindingBundle {
1583    pub id: String,
1584    #[serde(default = "default_version")]
1585    pub version: u32,
1586    pub previous_version: Option<String>,
1587    pub assertion: Assertion,
1588    pub evidence: Evidence,
1589    pub conditions: Conditions,
1590    pub confidence: Confidence,
1591    pub provenance: Provenance,
1592    pub flags: Flags,
1593    #[serde(default)]
1594    pub links: Vec<Link>,
1595    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1596    pub annotations: Vec<Annotation>,
1597    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1598    pub attachments: Vec<Attachment>,
1599    pub created: String,
1600    pub updated: Option<String>,
1601    /// v0.51: Read-side access tier. Default `Public` — pre-v0.51
1602    /// findings load with `Public` and serialize byte-identically
1603    /// (skip-if-public). Mutated through `tier.set` events; gated in
1604    /// MCP/HTTP read paths via `access_tier::redact_for_actor`. NOT
1605    /// part of the content-address preimage — re-classifying a
1606    /// finding does not mint a new id.
1607    #[serde(default, skip_serializing_if = "is_public_tier")]
1608    pub access_tier: crate::access_tier::AccessTier,
1609}
1610
1611fn is_public_tier(tier: &crate::access_tier::AccessTier) -> bool {
1612    matches!(tier, crate::access_tier::AccessTier::Public)
1613}
1614
1615fn default_version() -> u32 {
1616    1
1617}
1618
1619impl FindingBundle {
1620    /// Create a new finding bundle with a content-addressed ID.
1621    /// Normalize text for content-addressing: lowercase, collapse whitespace,
1622    /// strip trailing punctuation. Matches the v0.2.0 schema specification.
1623    /// Public since v0.32 so `Replication::content_address` can reuse the
1624    /// same canonicalization rule for its conditions preimage.
1625    pub fn normalize_text(s: &str) -> String {
1626        let lower = s.to_lowercase();
1627        // Collapse all runs of whitespace into a single space
1628        let collapsed: String = lower.split_whitespace().collect::<Vec<_>>().join(" ");
1629        // Strip trailing punctuation (., ;, :, !, ?)
1630        collapsed
1631            .trim_end_matches(['.', ';', ':', '!', '?'])
1632            .to_string()
1633    }
1634
1635    /// Compute the content-addressed ID per v0.2.0 spec:
1636    /// SHA-256(normalize(assertion.text) + "|" + assertion.type + "|" + (provenance.doi || provenance.pmid || provenance.title))
1637    /// Returns first 16 hex chars prefixed with "vf_".
1638    pub fn content_address(assertion: &Assertion, provenance: &Provenance) -> String {
1639        let norm_text = Self::normalize_text(&assertion.text);
1640        // v0.700: pmid removed. doi || title (no live finding was pmid-addressed,
1641        // so every existing vf_ id is unchanged).
1642        let prov_id = provenance.doi.as_deref().unwrap_or(&provenance.title);
1643        let preimage = format!("{}|{}|{}", norm_text, assertion.assertion_type, prov_id);
1644        let hash = Sha256::digest(preimage.as_bytes());
1645        format!("vf_{}", &hex::encode(hash)[..16])
1646    }
1647
1648    pub fn new(
1649        assertion: Assertion,
1650        evidence: Evidence,
1651        conditions: Conditions,
1652        confidence: Confidence,
1653        provenance: Provenance,
1654        flags: Flags,
1655    ) -> Self {
1656        let now = Utc::now().to_rfc3339();
1657        let id = Self::content_address(&assertion, &provenance);
1658
1659        Self {
1660            id,
1661            version: 1,
1662            previous_version: None,
1663            assertion,
1664            evidence,
1665            conditions,
1666            confidence,
1667            provenance,
1668            flags,
1669            links: Vec::new(),
1670            annotations: Vec::new(),
1671            attachments: Vec::new(),
1672            created: now,
1673            updated: None,
1674            access_tier: crate::access_tier::AccessTier::Public,
1675        }
1676    }
1677
1678    pub fn add_link(&mut self, target_id: &str, link_type: &str, note: &str) {
1679        self.links.push(Link {
1680            target: target_id.to_string(),
1681            link_type: link_type.to_string(),
1682            note: note.to_string(),
1683            inferred_by: "compiler".to_string(),
1684            created_at: Utc::now().to_rfc3339(),
1685            mechanism: None,
1686        });
1687    }
1688
1689    pub fn add_link_with_source(
1690        &mut self,
1691        target_id: &str,
1692        link_type: &str,
1693        note: &str,
1694        inferred_by: &str,
1695    ) {
1696        self.links.push(Link {
1697            target: target_id.to_string(),
1698            link_type: link_type.to_string(),
1699            note: note.to_string(),
1700            inferred_by: inferred_by.to_string(),
1701            created_at: Utc::now().to_rfc3339(),
1702            mechanism: None,
1703        });
1704    }
1705}
1706
1707#[cfg(test)]
1708mod tests {
1709    use super::*;
1710
1711    fn sample_assertion() -> Assertion {
1712        Assertion {
1713            text: "NLRP3 activates IL-1B".into(),
1714            assertion_type: "mechanism".into(),
1715            entities: vec![Entity {
1716                name: "NLRP3".into(),
1717                entity_type: "protein".into(),
1718                identifiers: serde_json::Map::new(),
1719                canonical_id: None,
1720                candidates: vec![],
1721                aliases: vec![],
1722                resolution_provenance: None,
1723                resolution_confidence: 1.0,
1724                resolution_method: None,
1725                species_context: None,
1726                needs_review: false,
1727            }],
1728            relation: Some("activates".into()),
1729            direction: Some("positive".into()),
1730            causal_claim: None,
1731            causal_evidence_grade: None,
1732        }
1733    }
1734
1735    fn sample_evidence() -> Evidence {
1736        Evidence {
1737            evidence_type: "experimental".into(),
1738            model_system: "mouse".into(),
1739            method: "Western blot".into(),
1740            replicated: true,
1741            replication_count: Some(3),
1742            evidence_spans: vec![],
1743        }
1744    }
1745
1746    fn sample_conditions() -> Conditions {
1747        Conditions {
1748            text: "In vitro, mouse microglia".into(),
1749            duration: None,
1750        }
1751    }
1752
1753    fn sample_confidence() -> Confidence {
1754        Confidence {
1755            kind: ConfidenceKind::FrontierEpistemic,
1756            score: 0.85,
1757            basis: "Experimental with replication".into(),
1758            method: ConfidenceMethod::LlmInitial,
1759            extraction_confidence: 0.9,
1760        }
1761    }
1762
1763    fn sample_provenance() -> Provenance {
1764        Provenance {
1765            source_type: "published_paper".into(),
1766            doi: Some("10.1234/test".into()),
1767            url: None,
1768            title: "Test Paper".into(),
1769            authors: vec![Author {
1770                name: "Smith J".into(),
1771                orcid: None,
1772            }],
1773            year: Some(2024),
1774            license: None,
1775            publisher: None,
1776            funders: vec![],
1777            extraction: Extraction::default(),
1778            review: None,
1779            contributions: Vec::new(),
1780        }
1781    }
1782
1783    fn sample_flags() -> Flags {
1784        Flags {
1785            gap: false,
1786            negative_space: false,
1787            contested: false,
1788            retracted: false,
1789            declining: false,
1790            gravity_well: false,
1791            review_state: None,
1792            superseded: false,
1793            signature_threshold: None,
1794            jointly_accepted: false,
1795        }
1796    }
1797
1798    // ── Content-addressed ID tests ───────────────────────────────────
1799
1800    #[test]
1801    fn same_content_same_id() {
1802        let b1 = FindingBundle::new(
1803            sample_assertion(),
1804            sample_evidence(),
1805            sample_conditions(),
1806            sample_confidence(),
1807            sample_provenance(),
1808            sample_flags(),
1809        );
1810        let b2 = FindingBundle::new(
1811            sample_assertion(),
1812            sample_evidence(),
1813            sample_conditions(),
1814            sample_confidence(),
1815            sample_provenance(),
1816            sample_flags(),
1817        );
1818        assert_eq!(b1.id, b2.id);
1819    }
1820
1821    #[test]
1822    fn different_content_different_id() {
1823        let b1 = FindingBundle::new(
1824            sample_assertion(),
1825            sample_evidence(),
1826            sample_conditions(),
1827            sample_confidence(),
1828            sample_provenance(),
1829            sample_flags(),
1830        );
1831        let mut different_assertion = sample_assertion();
1832        different_assertion.text = "Completely different claim".into();
1833        let b2 = FindingBundle::new(
1834            different_assertion,
1835            sample_evidence(),
1836            sample_conditions(),
1837            sample_confidence(),
1838            sample_provenance(),
1839            sample_flags(),
1840        );
1841        assert_ne!(b1.id, b2.id);
1842    }
1843
1844    #[test]
1845    fn id_starts_with_vf_prefix() {
1846        let b = FindingBundle::new(
1847            sample_assertion(),
1848            sample_evidence(),
1849            sample_conditions(),
1850            sample_confidence(),
1851            sample_provenance(),
1852            sample_flags(),
1853        );
1854        assert!(b.id.starts_with("vf_"));
1855        assert_eq!(b.id.len(), 3 + 16); // "vf_" + 16 hex chars
1856    }
1857
1858    #[test]
1859    fn new_bundle_version_is_one() {
1860        let b = FindingBundle::new(
1861            sample_assertion(),
1862            sample_evidence(),
1863            sample_conditions(),
1864            sample_confidence(),
1865            sample_provenance(),
1866            sample_flags(),
1867        );
1868        assert_eq!(b.version, 1);
1869        assert!(b.previous_version.is_none());
1870    }
1871
1872    #[test]
1873    fn new_bundle_has_no_links() {
1874        let b = FindingBundle::new(
1875            sample_assertion(),
1876            sample_evidence(),
1877            sample_conditions(),
1878            sample_confidence(),
1879            sample_provenance(),
1880            sample_flags(),
1881        );
1882        assert!(b.links.is_empty());
1883    }
1884
1885    #[test]
1886    fn new_bundle_has_created_timestamp() {
1887        let b = FindingBundle::new(
1888            sample_assertion(),
1889            sample_evidence(),
1890            sample_conditions(),
1891            sample_confidence(),
1892            sample_provenance(),
1893            sample_flags(),
1894        );
1895        assert!(!b.created.is_empty());
1896        assert!(b.updated.is_none());
1897    }
1898
1899    // ── add_link tests ───────────────────────────────────────────────
1900
1901    #[test]
1902    fn add_link_works() {
1903        let mut b = FindingBundle::new(
1904            sample_assertion(),
1905            sample_evidence(),
1906            sample_conditions(),
1907            sample_confidence(),
1908            sample_provenance(),
1909            sample_flags(),
1910        );
1911        b.add_link("target_id", "extends", "shared entity");
1912        assert_eq!(b.links.len(), 1);
1913        assert_eq!(b.links[0].target, "target_id");
1914        assert_eq!(b.links[0].link_type, "extends");
1915        assert_eq!(b.links[0].note, "shared entity");
1916        assert_eq!(b.links[0].inferred_by, "compiler");
1917    }
1918
1919    #[test]
1920    fn add_link_with_source_works() {
1921        let mut b = FindingBundle::new(
1922            sample_assertion(),
1923            sample_evidence(),
1924            sample_conditions(),
1925            sample_confidence(),
1926            sample_provenance(),
1927            sample_flags(),
1928        );
1929        b.add_link_with_source(
1930            "target_id",
1931            "contradicts",
1932            "opposite direction",
1933            "entity_overlap",
1934        );
1935        assert_eq!(b.links.len(), 1);
1936        assert_eq!(b.links[0].inferred_by, "entity_overlap");
1937    }
1938
1939    #[test]
1940    fn multiple_links_accumulate() {
1941        let mut b = FindingBundle::new(
1942            sample_assertion(),
1943            sample_evidence(),
1944            sample_conditions(),
1945            sample_confidence(),
1946            sample_provenance(),
1947            sample_flags(),
1948        );
1949        b.add_link("t1", "extends", "note1");
1950        b.add_link("t2", "contradicts", "note2");
1951        b.add_link("t3", "supports", "note3");
1952        assert_eq!(b.links.len(), 3);
1953    }
1954
1955    // ── ReviewEvent creation test ────────────────────────────────────
1956
1957    #[test]
1958    fn review_event_creation() {
1959        let event = ReviewEvent {
1960            id: "rev_abc123".into(),
1961            workspace: None,
1962            finding_id: "vf_abc".into(),
1963            reviewer: "0000-0001-2345-6789".into(),
1964            reviewed_at: "2024-01-01T00:00:00Z".into(),
1965            scope: None,
1966            status: None,
1967            action: ReviewAction::Approved,
1968            reason: "Looks correct".into(),
1969            evidence_considered: vec![],
1970            state_change: None,
1971        };
1972        assert_eq!(event.finding_id, "vf_abc");
1973        assert_eq!(event.reviewer, "0000-0001-2345-6789");
1974    }
1975
1976    #[test]
1977    fn review_action_corrected() {
1978        let action = ReviewAction::Corrected {
1979            field: "direction".into(),
1980            original: "positive".into(),
1981            corrected: "negative".into(),
1982        };
1983        if let ReviewAction::Corrected {
1984            field,
1985            original,
1986            corrected,
1987        } = action
1988        {
1989            assert_eq!(field, "direction");
1990            assert_eq!(original, "positive");
1991            assert_eq!(corrected, "negative");
1992        } else {
1993            panic!("Expected Corrected variant");
1994        }
1995    }
1996
1997    #[test]
1998    fn review_action_disputed() {
1999        let action = ReviewAction::Disputed {
2000            counter_evidence: "Later study contradicts".into(),
2001            counter_doi: Some("10.1234/counter".into()),
2002        };
2003        if let ReviewAction::Disputed {
2004            counter_evidence,
2005            counter_doi,
2006        } = action
2007        {
2008            assert_eq!(counter_evidence, "Later study contradicts");
2009            assert_eq!(counter_doi, Some("10.1234/counter".into()));
2010        } else {
2011            panic!("Expected Disputed variant");
2012        }
2013    }
2014
2015    // ── ConfidenceUpdate creation test ───────────────────────────────
2016
2017    #[test]
2018    fn confidence_update_creation() {
2019        let update = ConfidenceUpdate {
2020            finding_id: "vf_abc".into(),
2021            previous_score: 0.7,
2022            new_score: 0.85,
2023            basis: "grounded".into(),
2024            updated_by: "grounding_pass".into(),
2025            updated_at: "2024-01-01T00:00:00Z".into(),
2026        };
2027        assert_eq!(update.previous_score, 0.7);
2028        assert_eq!(update.new_score, 0.85);
2029        assert_eq!(update.updated_by, "grounding_pass");
2030    }
2031
2032    // ── Serialization round-trip test ────────────────────────────────
2033
2034    #[test]
2035    fn finding_serializes_and_deserializes() {
2036        let b = FindingBundle::new(
2037            sample_assertion(),
2038            sample_evidence(),
2039            sample_conditions(),
2040            sample_confidence(),
2041            sample_provenance(),
2042            sample_flags(),
2043        );
2044        let json = serde_json::to_string(&b).unwrap();
2045        let b2: FindingBundle = serde_json::from_str(&json).unwrap();
2046        assert_eq!(b.id, b2.id);
2047        assert_eq!(b.assertion.text, b2.assertion.text);
2048        assert_eq!(b.confidence.score, b2.confidence.score);
2049    }
2050
2051    #[test]
2052    fn v0_10_assertion_and_source_extensions() {
2053        assert!(VALID_ASSERTION_TYPES.contains(&"measurement"));
2054        assert!(VALID_ASSERTION_TYPES.contains(&"exclusion"));
2055        assert!(VALID_PROVENANCE_SOURCE_TYPES.contains(&"data_release"));
2056    }
2057
2058    // ── Different fields change the ID ───────────────────────────────
2059
2060    #[test]
2061    fn confidence_does_not_affect_id() {
2062        // v0.2.0: confidence is the mutable interpretation layer, not part of content address
2063        let b1 = FindingBundle::new(
2064            sample_assertion(),
2065            sample_evidence(),
2066            sample_conditions(),
2067            sample_confidence(),
2068            sample_provenance(),
2069            sample_flags(),
2070        );
2071        let mut conf2 = sample_confidence();
2072        conf2.score = 0.5;
2073        let b2 = FindingBundle::new(
2074            sample_assertion(),
2075            sample_evidence(),
2076            sample_conditions(),
2077            conf2,
2078            sample_provenance(),
2079            sample_flags(),
2080        );
2081        assert_eq!(b1.id, b2.id);
2082    }
2083
2084    #[test]
2085    fn flags_do_not_affect_id() {
2086        let b1 = FindingBundle::new(
2087            sample_assertion(),
2088            sample_evidence(),
2089            sample_conditions(),
2090            sample_confidence(),
2091            sample_provenance(),
2092            sample_flags(),
2093        );
2094        let mut flags2 = sample_flags();
2095        flags2.gap = true;
2096        flags2.contested = true;
2097        let b2 = FindingBundle::new(
2098            sample_assertion(),
2099            sample_evidence(),
2100            sample_conditions(),
2101            sample_confidence(),
2102            sample_provenance(),
2103            flags2,
2104        );
2105        // Flags are NOT in the content hash, so IDs should be the same
2106        assert_eq!(b1.id, b2.id);
2107    }
2108
2109    #[test]
2110    fn different_assertion_text_different_id() {
2111        let b1 = FindingBundle::new(
2112            sample_assertion(),
2113            sample_evidence(),
2114            sample_conditions(),
2115            sample_confidence(),
2116            sample_provenance(),
2117            sample_flags(),
2118        );
2119        let mut assertion2 = sample_assertion();
2120        assertion2.assertion_type = "therapeutic".into();
2121        let b2 = FindingBundle::new(
2122            assertion2,
2123            sample_evidence(),
2124            sample_conditions(),
2125            sample_confidence(),
2126            sample_provenance(),
2127            sample_flags(),
2128        );
2129        assert_ne!(b1.id, b2.id);
2130    }
2131
2132    #[test]
2133    fn different_doi_different_id() {
2134        let b1 = FindingBundle::new(
2135            sample_assertion(),
2136            sample_evidence(),
2137            sample_conditions(),
2138            sample_confidence(),
2139            sample_provenance(),
2140            sample_flags(),
2141        );
2142        let mut prov2 = sample_provenance();
2143        prov2.doi = Some("10.5678/other".into());
2144        let b2 = FindingBundle::new(
2145            sample_assertion(),
2146            sample_evidence(),
2147            sample_conditions(),
2148            sample_confidence(),
2149            prov2,
2150            sample_flags(),
2151        );
2152        assert_ne!(b1.id, b2.id);
2153    }
2154
2155    // ── v0.2.0 content-addressing determinism ───────────────────────
2156
2157    #[test]
2158    fn content_address_is_deterministic_across_runs() {
2159        // Two independent extraction runs with the same assertion text,
2160        // assertion type, and DOI must produce the same finding ID.
2161        let assertion1 = Assertion {
2162            text: "Mitochondrial dysfunction precedes amyloid plaque formation.".into(),
2163            assertion_type: "mechanism".into(),
2164            entities: vec![],
2165            relation: None,
2166            direction: None,
2167            causal_claim: None,
2168            causal_evidence_grade: None,
2169        };
2170        let prov1 = Provenance {
2171            source_type: "published_paper".into(),
2172            doi: Some("10.1038/s41586-023-06789-1".into()),
2173            url: None,
2174            title: "Mitochondria in AD".into(),
2175            authors: vec![],
2176            year: Some(2023),
2177            license: None,
2178            publisher: None,
2179            funders: vec![],
2180            extraction: Extraction::default(),
2181            review: None,
2182            contributions: Vec::new(),
2183        };
2184
2185        // Different entities, evidence, conditions, confidence -- should NOT matter
2186        let assertion2 = Assertion {
2187            text: "Mitochondrial dysfunction precedes amyloid plaque formation.".into(),
2188            assertion_type: "mechanism".into(),
2189            entities: vec![Entity {
2190                name: "mitochondria".into(),
2191                entity_type: "anatomical_structure".into(),
2192                identifiers: serde_json::Map::new(),
2193                canonical_id: None,
2194                candidates: vec![],
2195                aliases: vec![],
2196                resolution_provenance: None,
2197                resolution_confidence: 1.0,
2198                resolution_method: None,
2199                species_context: None,
2200                needs_review: false,
2201            }],
2202            relation: Some("precedes".into()),
2203            direction: Some("positive".into()),
2204            causal_claim: None,
2205            causal_evidence_grade: None,
2206        };
2207        let prov2 = Provenance {
2208            source_type: "published_paper".into(),
2209            doi: Some("10.1038/s41586-023-06789-1".into()),
2210            url: None,
2211            title: "Different title".into(),
2212            authors: vec![Author {
2213                name: "Jones A".into(),
2214                orcid: None,
2215            }],
2216            year: Some(2023),
2217            license: None,
2218            publisher: None,
2219            funders: vec![],
2220            extraction: Extraction::default(),
2221            review: None,
2222            contributions: Vec::new(),
2223        };
2224
2225        let id1 = FindingBundle::content_address(&assertion1, &prov1);
2226        let id2 = FindingBundle::content_address(&assertion2, &prov2);
2227        assert_eq!(
2228            id1, id2,
2229            "Same assertion text + type + DOI must produce same ID"
2230        );
2231    }
2232
2233    #[test]
2234    fn content_address_normalizes_whitespace_and_punctuation() {
2235        let assertion1 = Assertion {
2236            text: "  NLRP3  activates   IL-1B.  ".into(),
2237            assertion_type: "mechanism".into(),
2238            entities: vec![],
2239            relation: None,
2240            direction: None,
2241            causal_claim: None,
2242            causal_evidence_grade: None,
2243        };
2244        let assertion2 = Assertion {
2245            text: "NLRP3 activates IL-1B".into(),
2246            assertion_type: "mechanism".into(),
2247            entities: vec![],
2248            relation: None,
2249            direction: None,
2250            causal_claim: None,
2251            causal_evidence_grade: None,
2252        };
2253        let prov = sample_provenance();
2254        let id1 = FindingBundle::content_address(&assertion1, &prov);
2255        let id2 = FindingBundle::content_address(&assertion2, &prov);
2256        assert_eq!(
2257            id1, id2,
2258            "Whitespace and trailing punctuation should be normalized away"
2259        );
2260    }
2261
2262    #[test]
2263    fn content_address_falls_back_to_title_when_no_doi() {
2264        let assertion = sample_assertion();
2265        let mut prov = sample_provenance();
2266        prov.doi = None;
2267        prov.title = "Fallback Title".into();
2268        let id = FindingBundle::content_address(&assertion, &prov);
2269        assert!(id.starts_with("vf_"));
2270        assert_eq!(id.len(), 19); // "vf_" + 16 hex chars
2271
2272        // Same title -> same ID
2273        let mut prov2 = sample_provenance();
2274        prov2.doi = None;
2275        prov2.title = "Fallback Title".into();
2276        let id2 = FindingBundle::content_address(&assertion, &prov2);
2277        assert_eq!(id, id2);
2278    }
2279
2280    #[test]
2281    fn content_address_prefers_doi_over_title() {
2282        let assertion = sample_assertion();
2283
2284        let mut prov_doi = sample_provenance();
2285        prov_doi.doi = Some("10.1234/test".into());
2286        prov_doi.title = "Title".into();
2287
2288        let mut prov_title = sample_provenance();
2289        prov_title.doi = None;
2290        prov_title.title = "Title".into();
2291
2292        let id_doi = FindingBundle::content_address(&assertion, &prov_doi);
2293        let id_title = FindingBundle::content_address(&assertion, &prov_title);
2294
2295        assert_ne!(id_doi, id_title, "DOI vs title should differ");
2296    }
2297
2298    #[test]
2299    fn parses_bbb_review_event_with_richer_schema() {
2300        let raw = include_str!("../../embedded/tests/fixtures/legacy/rev_001_bbb_correction.json");
2301        let review: ReviewEvent = serde_json::from_str(raw).unwrap();
2302
2303        assert_eq!(review.id, "rev_001_bbb_correction");
2304        assert_eq!(review.workspace.as_deref(), Some("projects/bbb-flagship"));
2305        assert_eq!(review.scope.as_deref(), Some("bbb_opening_trusted_subset"));
2306        assert_eq!(review.status.as_deref(), Some("accepted"));
2307        assert!(matches!(
2308            review.action,
2309            ReviewAction::Qualified { ref target } if target == "trusted_interpretation"
2310        ));
2311        assert_eq!(review.evidence_considered.len(), 3);
2312        assert_eq!(
2313            review.evidence_considered[0].role.as_deref(),
2314            Some("qualifier")
2315        );
2316        assert_eq!(
2317            review
2318                .state_change
2319                .as_ref()
2320                .and_then(|value| value.get("assumption_retired"))
2321                .and_then(|value| value.as_str()),
2322            Some("safe opening implies therapeutic efficacy")
2323        );
2324    }
2325
2326    #[test]
2327    fn artifact_requires_sha256_and_stable_kind() {
2328        let artifact = Artifact::new(
2329            "clinical_trial_record",
2330            "AHEAD 3-45",
2331            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
2332            Some(42),
2333            Some("application/json".into()),
2334            "local_blob",
2335            Some(".vela/artifact-blobs/sha256/aaaaaaaa".into()),
2336            Some("https://clinicaltrials.gov/study/NCT04468659".into()),
2337            Some("ClinicalTrials.gov public record".into()),
2338            vec!["vf_demo".into()],
2339            sample_provenance(),
2340            BTreeMap::new(),
2341            crate::access_tier::AccessTier::Public,
2342        )
2343        .unwrap();
2344
2345        assert!(artifact.id.starts_with("va_"));
2346        assert_eq!(
2347            artifact.content_hash,
2348            "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
2349        );
2350        assert_eq!(artifact.kind, "clinical_trial_record");
2351    }
2352
2353    #[test]
2354    fn artifact_reference_axes_are_independent_and_content_bound() {
2355        let hash = format!("sha256:{}", "a".repeat(64));
2356        let legacy = Artifact::content_address(
2357            "dataset",
2358            "public data",
2359            &hash,
2360            None,
2361            Some("https://example.test/data"),
2362        );
2363        let all_unknown = Artifact::content_address_with_axes(
2364            "dataset",
2365            "public data",
2366            &hash,
2367            None,
2368            Some("https://example.test/data"),
2369            ArtifactDisclosure::Unknown,
2370            LocatorIntegrity::Unknown,
2371            ArtifactAvailability::Unknown,
2372        );
2373        assert_eq!(legacy, all_unknown);
2374
2375        let immutable = Artifact::content_address_with_axes(
2376            "dataset",
2377            "public data",
2378            &hash,
2379            None,
2380            Some("https://example.test/data"),
2381            ArtifactDisclosure::Public,
2382            LocatorIntegrity::Immutable,
2383            ArtifactAvailability::Available,
2384        );
2385        let mutable = Artifact::content_address_with_axes(
2386            "dataset",
2387            "public data",
2388            &hash,
2389            None,
2390            Some("https://example.test/data"),
2391            ArtifactDisclosure::Public,
2392            LocatorIntegrity::Mutable,
2393            ArtifactAvailability::Available,
2394        );
2395        assert_ne!(immutable, mutable);
2396    }
2397
2398    #[test]
2399    fn restricted_reference_refuses_public_equality_digest() {
2400        let mut artifact = Artifact::new(
2401            "dataset",
2402            "restricted data",
2403            "a".repeat(64),
2404            None,
2405            None,
2406            "pointer",
2407            Some("custodian:lab-vault/item-7".to_string()),
2408            None,
2409            None,
2410            vec![],
2411            sample_provenance(),
2412            BTreeMap::new(),
2413            crate::access_tier::AccessTier::Restricted,
2414        )
2415        .unwrap();
2416        artifact.disclosure = ArtifactDisclosure::Restricted;
2417        artifact.locator_integrity = LocatorIntegrity::Immutable;
2418        artifact.availability = ArtifactAvailability::Unknown;
2419        assert!(artifact.validate_reference_axes().is_err());
2420
2421        artifact.content_hash.clear();
2422        assert!(artifact.validate_reference_axes().is_ok());
2423    }
2424}