Skip to main content

vela_protocol/computed/
state.rs

1//! Read-only frontier state projections plus the Receipt v1 finding-proposal
2//! builder and the explicitly chartered draft artifact-retirement exception.
3
4use std::path::Path;
5
6use serde::Serialize;
7use serde_json::{Value, json};
8use sha2::{Digest, Sha256};
9
10use crate::bundle::{
11    Assertion, Author, Conditions, Confidence, ConfidenceKind, ConfidenceMethod, Evidence,
12    Extraction, FindingBundle, Flags, Provenance, Review,
13};
14use crate::events;
15use crate::project::{self, Project};
16use crate::proposals::{self, StateProposal};
17use crate::repo;
18
19#[derive(Debug, Clone, Serialize)]
20pub struct ArtifactLifecycleReport {
21    pub ok: bool,
22    pub command: String,
23    #[serde(skip)]
24    pub frontier: String,
25    pub artifact_id: String,
26    pub proposal_id: String,
27    pub status: String,
28    pub route: String,
29}
30
31#[derive(Debug, Clone)]
32pub struct FindingDraftOptions {
33    pub text: String,
34    pub assertion_type: String,
35    pub source: String,
36    pub source_type: String,
37    pub author: String,
38    pub confidence: f64,
39    pub evidence_type: String,
40    /// v0.11: structured provenance — populates the existing `Provenance`
41    /// fields instead of jamming everything into `title`. Each is optional
42    /// so Receipt producers do not have to know all of them up front.
43    pub doi: Option<String>,
44    pub year: Option<i32>,
45    pub url: Option<String>,
46    /// Authors of the source artifact (the paper/preprint/etc).
47    /// Distinct from `author` above, which is the Vela actor doing the curation.
48    pub source_authors: Vec<String>,
49    /// External source references that justify this proposal. These are
50    /// proposal provenance only; they never confer acceptance authority.
51    pub source_refs: Vec<String>,
52    /// v0.11: structured conditions — replaces the placeholder
53    /// "Manually added finding; requires evidence review…" that was on
54    /// every manually-added finding in v0.10. Each field independently optional.
55    pub conditions_text: Option<String>,
56    pub evidence_spans: Vec<Value>,
57    pub gap: bool,
58    pub negative_space: bool,
59    /// Optional replication evidence for a circuit-claim proposal. It remains
60    /// review material only: recording an attestation never grants its author
61    /// acceptance authority or bypasses the Decision Plan.
62    pub replication_attestation: Option<Value>,
63}
64
65pub fn retract_artifact(
66    path: &Path,
67    artifact_id: &str,
68    actor: &str,
69    reason: &str,
70) -> Result<ArtifactLifecycleReport, String> {
71    let frontier = repo::load_from_path(path)?;
72    if reason.trim().is_empty() {
73        return Err("artifact retirement reason must be non-empty".to_string());
74    }
75    let artifact = frontier
76        .artifacts
77        .iter()
78        .find(|artifact| artifact.id == artifact_id)
79        .ok_or_else(|| format!("Artifact not found: {artifact_id}"))?;
80    if artifact.retracted {
81        return Err(format!("Artifact {artifact_id} is already retracted"));
82    }
83    let actor_type = events::actor_kind(actor);
84    let proposal = proposals::new_proposal(
85        "artifact.retract",
86        events::StateTarget {
87            r#type: "artifact".to_string(),
88            id: artifact_id.to_string(),
89        },
90        actor,
91        actor_type,
92        reason,
93        json!({}),
94        Vec::new(),
95        vec![
96            "Retirement changes proof readiness, not the truth or quality of any linked finding."
97                .to_string(),
98        ],
99    );
100    let result = proposals::insert_pending_at_path(path, proposal)?;
101    Ok(ArtifactLifecycleReport {
102        ok: true,
103        command: "artifact retract".to_string(),
104        frontier: frontier.project.name,
105        artifact_id: artifact_id.to_string(),
106        proposal_id: result.proposal_id,
107        status: result.status,
108        route: "deferred".to_string(),
109    })
110}
111
112pub fn history(path: &Path, finding_id: &str) -> Result<Value, String> {
113    history_as_of(path, finding_id, None)
114}
115
116/// v0.55: time-travel replay. When `as_of` is `Some(ts)`, the returned
117/// `events` / `review_events` / `confidence_updates` are filtered to
118/// records whose timestamp is `<= ts` (RFC3339 lexicographic compare),
119/// the `confidence` field reports the **score at that time** (last
120/// confidence update at-or-before cutoff, or genesis if none), and a
121/// `replayed_at_score` field surfaces it explicitly so a caller doesn't
122/// need to walk the updates array.
123pub fn history_as_of(path: &Path, finding_id: &str, as_of: Option<&str>) -> Result<Value, String> {
124    let frontier = repo::load_from_path(path)?;
125    let context = finding_context(&frontier, finding_id)?;
126    let finding = context
127        .get("finding")
128        .ok_or_else(|| format!("Finding not found: {finding_id}"))?;
129
130    let cutoff = as_of.map(|s| s.to_string());
131    let filter_by_ts = |arr: Option<&Value>, ts_field: &str| -> Value {
132        let Some(v) = arr else {
133            return Value::Array(Vec::new());
134        };
135        let Some(items) = v.as_array() else {
136            return Value::Array(Vec::new());
137        };
138        match &cutoff {
139            None => Value::Array(items.clone()),
140            Some(c) => Value::Array(
141                items
142                    .iter()
143                    .filter(|item| {
144                        item.get(ts_field)
145                            .and_then(Value::as_str)
146                            .map(|t| t <= c.as_str())
147                            .unwrap_or(true)
148                    })
149                    .cloned()
150                    .collect(),
151            ),
152        }
153    };
154
155    let events_filtered = filter_by_ts(context.get("events"), "timestamp");
156    let review_events_filtered = filter_by_ts(context.get("review_events"), "reviewed_at");
157    let confidence_updates_filtered = filter_by_ts(context.get("confidence_updates"), "updated_at");
158
159    // Score at cutoff: last confidence update at-or-before cutoff. If the
160    // finding is at its genesis confidence, fall back to the current score
161    // from the bundle (it never changed).
162    let score_at = if let Some(arr) = confidence_updates_filtered.as_array() {
163        let mut sorted: Vec<&Value> = arr.iter().collect();
164        sorted.sort_by(|a, b| {
165            let ta = a.get("updated_at").and_then(Value::as_str).unwrap_or("");
166            let tb = b.get("updated_at").and_then(Value::as_str).unwrap_or("");
167            ta.cmp(tb)
168        });
169        sorted
170            .last()
171            .and_then(|u| u.get("new_score"))
172            .cloned()
173            .unwrap_or_else(|| {
174                finding
175                    .pointer("/confidence/score")
176                    .cloned()
177                    .unwrap_or(Value::Null)
178            })
179    } else {
180        finding
181            .pointer("/confidence/score")
182            .cloned()
183            .unwrap_or(Value::Null)
184    };
185
186    Ok(json!({
187        "ok": true,
188        "command": "history",
189        "frontier": frontier.project.name,
190        "as_of": cutoff,
191        "finding": {
192            "id": finding.get("id"),
193            "assertion": finding.pointer("/assertion/text"),
194            "confidence": finding.pointer("/confidence/score"),
195            "flags": finding.get("flags"),
196            "annotations": finding.get("annotations"),
197        },
198        "replayed_at_score": score_at,
199        "confidence_score": context.get("confidence_score"),
200        "confidence_basis": context.get("confidence_basis"),
201        "reviewed": context.get("reviewed"),
202        "reviewed_by_kind": context.get("reviewed_by_kind"),
203        "review_events": review_events_filtered,
204        "confidence_updates": confidence_updates_filtered,
205        "sources": context.get("sources"),
206        "evidence_atoms": context.get("evidence_atoms"),
207        "condition_records": context.get("condition_records"),
208        "proposals": context.get("proposals"),
209        "events": events_filtered,
210        "proof_state": frontier.proof_state,
211    }))
212}
213
214pub fn finding_context(frontier: &Project, finding_id: &str) -> Result<Value, String> {
215    let finding = frontier
216        .findings
217        .iter()
218        .find(|finding| finding.id == finding_id)
219        .ok_or_else(|| format!("Finding not found: {finding_id}"))?;
220    // Legacy `.vela/reviews/` records. The canonical reviewer verdicts
221    // live in the `.vela/events/` log (exposed as `events` below); this
222    // collection is deliberately the legacy side and stays separate.
223    let reviews = frontier
224        .review_events
225        .iter()
226        .filter(|event| event.finding_id == finding_id)
227        .collect::<Vec<_>>();
228    let confidence_updates = frontier
229        .confidence_updates
230        .iter()
231        .filter(|update| update.finding_id == finding_id)
232        .collect::<Vec<_>>();
233    let source_records = frontier
234        .sources
235        .iter()
236        .filter(|source| source.finding_ids.iter().any(|id| id == finding_id))
237        .collect::<Vec<_>>();
238    let evidence_atoms = frontier
239        .evidence_atoms
240        .iter()
241        .filter(|atom| atom.finding_id == finding_id)
242        .collect::<Vec<_>>();
243    let condition_records = frontier
244        .condition_records
245        .iter()
246        .filter(|record| record.finding_id == finding_id)
247        .collect::<Vec<_>>();
248    // v0.326: `Confidence` serializes as a bare score, so a consumer
249    // of the finding payload cannot see the basis or reviewed-state. A
250    // confidence number must never stand alone — surface the basis and
251    // the (actor-classified) review state explicitly.
252    let review = finding.provenance.review.as_ref();
253    let reviewed = review.map(|r| r.reviewed).unwrap_or(false);
254    let reviewed_by_kind = review
255        .and_then(|r| r.reviewer.as_deref())
256        .map(crate::events::actor_kind);
257    Ok(json!({
258        "finding": finding,
259        "review_events": reviews,
260        "confidence_updates": confidence_updates,
261        "confidence_score": finding.confidence.score,
262        "confidence_basis": finding.confidence.basis,
263        "reviewed": reviewed,
264        "reviewed_by_kind": reviewed_by_kind,
265        "sources": source_records,
266        "evidence_atoms": evidence_atoms,
267        "condition_records": condition_records,
268        "proposals": proposals::proposals_for_finding(frontier, finding_id),
269        "events": events::events_for_finding(frontier, finding_id),
270        "proof_state": frontier.proof_state,
271        // Phase 1A: the verification trust tier (candidate / schema_checked /
272        // machine_verified / accepted). A read-only projection; machine_verified
273        // is the deterministic exact-lane admission and is DISTINCT from a human
274        // `accepted` (canonical-state landing via key custody). Every surface
275        // that renders this must keep the two visually + semantically separate.
276        "trust_tier": proposals::derive_trust_tier(frontier, finding_id).as_str(),
277    }))
278}
279
280pub fn state_transitions(frontier: &Project) -> Value {
281    let mut transitions = Vec::new();
282    if !frontier.events.is_empty() {
283        for event in &frontier.events {
284            transitions.push(json!({
285                "kind": event.kind,
286                "id": event.id,
287                "target": event.target,
288                "actor": event.actor,
289                "timestamp": event.timestamp,
290                "reason": event.reason,
291                "before_hash": event.before_hash,
292                "after_hash": event.after_hash,
293                "payload": event.payload,
294                "caveats": event.caveats,
295            }));
296        }
297        transitions.sort_by(|a, b| {
298            a.get("timestamp")
299                .and_then(Value::as_str)
300                .cmp(&b.get("timestamp").and_then(Value::as_str))
301        });
302        return json!({
303            "schema": "vela.state-transitions.v1",
304            "frontier": frontier.project.name,
305            "source": "canonical_events",
306            "transitions": transitions,
307        });
308    }
309    for event in &frontier.review_events {
310        transitions.push(json!({
311            "kind": "review_event",
312            "id": event.id,
313            "target": {"type": "finding", "id": event.finding_id},
314            "actor": event.reviewer,
315            "timestamp": event.reviewed_at,
316            "action": event.action,
317            "reason": event.reason,
318            "state_change": event.state_change,
319        }));
320    }
321    for update in &frontier.confidence_updates {
322        transitions.push(json!({
323            "kind": "confidence_update",
324            "id": confidence_update_id(update),
325            "target": {"type": "finding", "id": update.finding_id},
326            "actor": update.updated_by,
327            "timestamp": update.updated_at,
328            "action": "confidence_revised",
329            "reason": update.basis,
330            "state_change": {
331                "previous_score": update.previous_score,
332                "new_score": update.new_score,
333            },
334        }));
335    }
336    transitions.sort_by(|a, b| {
337        a.get("timestamp")
338            .and_then(Value::as_str)
339            .cmp(&b.get("timestamp").and_then(Value::as_str))
340    });
341    json!({
342        "schema": "vela.state-transitions.v0",
343        "frontier": frontier.project.name,
344        "transitions": transitions,
345    })
346}
347
348pub fn build_add_finding_proposal_at(
349    options: FindingDraftOptions,
350    now: &str,
351) -> Result<StateProposal, String> {
352    validate_score(options.confidence)?;
353    chrono::DateTime::parse_from_rfc3339(now)
354        .map_err(|e| format!("finding proposal timestamp must be RFC3339: {e}"))?;
355    let assertion = Assertion {
356        text: options.text.clone(),
357        assertion_type: options.assertion_type.clone(),
358        entities: vec![],
359        relation: None,
360        direction: None,
361        causal_claim: None,
362        causal_evidence_grade: None,
363    };
364    let evidence = Evidence {
365        evidence_type: options.evidence_type.clone(),
366        model_system: String::new(),
367        method: if options.evidence_type == "experimental" {
368            "manual state transition; control details require source inspection".to_string()
369        } else {
370            "manual state transition".to_string()
371        },
372        replicated: false,
373        replication_count: None,
374        evidence_spans: options.evidence_spans.clone(),
375    };
376    // v0.11: conditions text falls back to the v0.10 placeholder only when
377    // the caller didn't supply --conditions-text. The placeholder is a
378    // signal to a reviewer that scope needs to be added; once a real
379    // conditions string is provided, the placeholder isn't useful.
380    let conditions = Conditions {
381        text: options.conditions_text.clone().unwrap_or_else(|| {
382            "Manually added finding; requires evidence review before scientific use.".to_string()
383        }),
384        duration: None,
385    };
386    let confidence = Confidence {
387        kind: ConfidenceKind::FrontierEpistemic,
388        score: options.confidence,
389        basis: "operator-supplied frontier prior; review required".to_string(),
390        method: ConfidenceMethod::ExpertJudgment,
391        extraction_confidence: 1.0,
392    };
393    // v0.11: structured provenance. Source authors (the paper's authors)
394    // are distinct from the Vela actor that curated the finding. When
395    // --authors is omitted, fall back to the curator-as-author shape used
396    // pre-v0.11 so existing scripts keep working.
397    let source_authors = if options.source_authors.is_empty() {
398        vec![Author {
399            name: options.author.clone(),
400            orcid: None,
401        }]
402    } else {
403        options
404            .source_authors
405            .iter()
406            .map(|name| Author {
407                name: name.clone(),
408                orcid: None,
409            })
410            .collect()
411    };
412    let provenance = Provenance {
413        source_type: options.source_type.clone(),
414        doi: options.doi.clone(),
415        url: options.url.clone(),
416        title: options.source.clone(),
417        authors: source_authors,
418        year: options.year,
419        license: None,
420        publisher: None,
421        funders: Vec::new(),
422        extraction: Extraction {
423            method: "manual_curation".to_string(),
424            model: None,
425            model_version: None,
426            extracted_at: now.to_string(),
427            extractor_version: project::VELA_COMPILER_VERSION.to_string(),
428        },
429        review: Some(Review {
430            reviewed: false,
431            reviewer: None,
432            reviewed_at: None,
433            corrections: Vec::new(),
434        }),
435        contributions: Vec::new(),
436    };
437    let flags = Flags {
438        gap: options.gap,
439        negative_space: options.negative_space,
440        ..Default::default()
441    };
442    let finding = FindingBundle::new(
443        assertion, evidence, conditions, confidence, provenance, flags,
444    );
445    let finding_id = finding.id.clone();
446    // An agent author remains visibly typed as an agent proposal originator;
447    // proposal authorship never grants decision authority.
448    let actor_type = if options.author.starts_with("agent:") {
449        "agent"
450    } else {
451        "human"
452    };
453    // Replication evidence rides beside `finding` without changing its frozen
454    // shape. Reviewers may inspect it, but it cannot authorize acceptance.
455    let payload = match options.replication_attestation {
456        Some(att) => json!({"finding": finding, "replication_attestation": att}),
457        None => json!({"finding": finding}),
458    };
459    Ok(proposals::new_proposal_at(
460        "finding.add",
461        events::StateTarget {
462            r#type: "finding".to_string(),
463            id: finding_id,
464        },
465        options.author,
466        actor_type,
467        "Manual finding added to frontier state",
468        payload,
469        options.source_refs,
470        vec!["Manual findings require evidence review before scientific use.".to_string()],
471        now,
472    ))
473}
474
475fn confidence_update_id(update: &crate::bundle::ConfidenceUpdate) -> String {
476    let hash = Sha256::digest(
477        format!(
478            "{}|{}|{}|{}|{}",
479            update.finding_id,
480            update.previous_score,
481            update.new_score,
482            update.updated_by,
483            update.updated_at
484        )
485        .as_bytes(),
486    );
487    format!("cu_{}", &hex::encode(hash)[..16])
488}
489
490fn validate_score(score: f64) -> Result<(), String> {
491    if (0.0..=1.0).contains(&score) {
492        Ok(())
493    } else {
494        Err("--confidence must be between 0.0 and 1.0".to_string())
495    }
496}
497
498#[cfg(test)]
499mod v0_11_finding_tests {
500    use super::*;
501    use crate::bundle;
502
503    fn base_options() -> FindingDraftOptions {
504        FindingDraftOptions {
505            text: "Test claim".to_string(),
506            assertion_type: "mechanism".to_string(),
507            source: "Test 2024".to_string(),
508            source_type: "published_paper".to_string(),
509            author: "reviewer:test".to_string(),
510            confidence: 0.5,
511            evidence_type: "experimental".to_string(),
512            doi: None,
513            year: None,
514            url: None,
515            source_authors: Vec::new(),
516            source_refs: Vec::new(),
517            conditions_text: None,
518            evidence_spans: Vec::new(),
519            gap: false,
520            negative_space: false,
521            replication_attestation: None,
522        }
523    }
524
525    #[test]
526    fn provenance_flags_populate_structured_fields() {
527        let mut opts = base_options();
528        opts.doi = Some("10.1056/NEJMoa2212948".to_string());
529        opts.year = Some(2023);
530        opts.url = Some("https://nejm.org/...".to_string());
531        opts.source_authors = vec!["van Dyck CH".to_string(), "Swanson CJ".to_string()];
532        let proposal = build_add_finding_proposal_at(opts, "2026-07-15T00:00:00Z").unwrap();
533        let finding: bundle::FindingBundle =
534            serde_json::from_value(proposal.payload["finding"].clone()).unwrap();
535        assert_eq!(
536            finding.provenance.doi.as_deref(),
537            Some("10.1056/NEJMoa2212948")
538        );
539        assert_eq!(finding.provenance.year, Some(2023));
540        assert_eq!(
541            finding.provenance.url.as_deref(),
542            Some("https://nejm.org/...")
543        );
544        assert_eq!(
545            finding
546                .provenance
547                .authors
548                .iter()
549                .map(|a| a.name.as_str())
550                .collect::<Vec<_>>(),
551            vec!["van Dyck CH", "Swanson CJ"],
552        );
553    }
554
555    #[test]
556    fn conditions_flags_populate_structured_fields() {
557        let mut opts = base_options();
558        opts.conditions_text = Some("Phase 3 RCT, 18 mo".to_string());
559        let proposal = build_add_finding_proposal_at(opts, "2026-07-15T00:00:00Z").unwrap();
560        let finding: bundle::FindingBundle =
561            serde_json::from_value(proposal.payload["finding"].clone()).unwrap();
562        assert_eq!(finding.conditions.text, "Phase 3 RCT, 18 mo");
563    }
564
565    #[test]
566    fn reviewed_entities_spans_and_gap_flags_populate_structured_fields() {
567        let mut opts = base_options();
568        opts.evidence_spans = vec![json!({
569            "section": "abstract",
570            "text": "Lecanemab slowed decline under early symptomatic AD trial conditions."
571        })];
572        opts.gap = true;
573        opts.negative_space = true;
574
575        let proposal = build_add_finding_proposal_at(opts, "2026-07-15T00:00:00Z").unwrap();
576        let finding: bundle::FindingBundle =
577            serde_json::from_value(proposal.payload["finding"].clone()).unwrap();
578
579        assert_eq!(finding.evidence.evidence_spans.len(), 1);
580        assert_eq!(
581            finding.evidence.evidence_spans[0]["section"].as_str(),
582            Some("abstract")
583        );
584        assert!(finding.flags.gap);
585        assert!(finding.flags.negative_space);
586    }
587
588    #[test]
589    fn omitted_flags_fall_back_to_pre_v011_shape() {
590        let proposal =
591            build_add_finding_proposal_at(base_options(), "2026-07-15T00:00:00Z").unwrap();
592        let finding: bundle::FindingBundle =
593            serde_json::from_value(proposal.payload["finding"].clone()).unwrap();
594        // Pre-v0.11 placeholder remains when --conditions-text is omitted.
595        assert!(
596            finding
597                .conditions
598                .text
599                .starts_with("Manually added finding")
600        );
601        // No --source-authors → curator fills the authors slot, as in v0.10.
602        assert_eq!(finding.provenance.authors.len(), 1);
603        assert_eq!(finding.provenance.authors[0].name, "reviewer:test");
604        // None of the new optional provenance fields populated.
605        assert!(finding.provenance.doi.is_none());
606        assert!(finding.provenance.year.is_none());
607        assert!(finding.provenance.url.is_none());
608    }
609}