Skip to main content

vela_protocol/objects/
provenance.rs

1//! Co-authorship provenance, shaped on W3C PROV (entity / activity / agent).
2//!
3//! A state transition records WHO contributed to it as signed-over ATTRIBUTION.
4//! The accountable party is the event (or attestation) signer, a durable human
5//! key for any judgment. Everyone named here is a contribution, never an
6//! authority: an AI that drafted the proposal, the CI that produced evidence.
7//! Because the block lives inside the signed bytes it is tamper-evident and
8//! auditable, yet it carries zero signing authority.
9//!
10//! Three planes are kept distinct and never collapsed: scientific authorship
11//! (claims, releases), cryptographic accountability (the event signer), and
12//! machine contribution (this block). The UI may render "Co-authored with
13//! Claude"; the schema says `machine_contributions`, so it never implies an AI
14//! is a scientific or accountable author.
15//!
16//! The no-signer property is STRUCTURAL. [`Provenance::validate`] refuses any id
17//! that classifies as human (via [`crate::events::actor_kind`]) and any machine
18//! contribution claiming authority, so a human key can never hide here to dodge
19//! the accountable signature, and a verification path that consults only
20//! `actor.id` can never treat a contribution as a signer. See
21//! `docs/TRUST_MODEL_REDESIGN.md` sections 5 and 13.
22
23use serde::{Deserialize, Serialize};
24use serde_json::Value;
25
26/// Typed reference prefix for the decision digest consumed by a human review.
27///
28/// The reference deliberately uses the existing generic `input_refs` lane. It
29/// is not a new object, manifest, or source of authority: the enclosing event
30/// and its human signature remain authoritative. The prefix only lets a
31/// verifier identify and zero this audit-reference slot when reconstructing a
32/// decision preimage without confusing it with other `sha256:` inputs.
33pub const DECISION_ROOT_INPUT_REF_PREFIX: &str = "urn:vela:decision-root:";
34
35/// Validate and type a canonical decision root for `Provenance.input_refs`.
36///
37/// Decision roots use the protocol's ordinary `sha256:<64 lowercase hex>`
38/// spelling. Returning the complete typed reference in one place prevents
39/// callers from inventing ambiguous or differently-cased aliases.
40pub fn decision_root_input_ref(decision_root: &str) -> Result<String, String> {
41    let Some(digest) = decision_root.strip_prefix("sha256:") else {
42        return Err("decision_root must be sha256:<64 lowercase hex>".to_string());
43    };
44    if digest.len() != 64
45        || !digest
46            .as_bytes()
47            .iter()
48            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(byte))
49    {
50        return Err("decision_root must be sha256:<64 lowercase hex>".to_string());
51    }
52    Ok(format!("{DECISION_ROOT_INPUT_REF_PREFIX}{decision_root}"))
53}
54
55/// Co-authorship attribution attached to an event payload or a `vsa_`
56/// statement attestation. Every named id is NON-HUMAN; the accountable human is
57/// the outer signer.
58#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
59pub struct Provenance {
60    /// What happened (PROV activity): drafted, formalized, verified, reviewed,
61    /// accepted.
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub activity: Option<Activity>,
64    /// Non-human actors that contributed (the `Co-authored-by` analogue). Never
65    /// authoritative.
66    #[serde(default, skip_serializing_if = "Vec::is_empty")]
67    pub machine_contributions: Vec<MachineContribution>,
68    /// Verifier / CI actors whose self-signed evidence this transition relied
69    /// on. Each entry points at the `vva_` ids that carry their own signatures,
70    /// so the decision CITES evidence without absorbing its authority.
71    #[serde(default, skip_serializing_if = "Vec::is_empty")]
72    pub evidence_refs: Vec<EvidenceRef>,
73    /// Inputs consumed (claim / proposal / object ids).
74    #[serde(default, skip_serializing_if = "Vec::is_empty")]
75    pub input_refs: Vec<String>,
76    /// Outputs produced (event / attestation / release ids).
77    #[serde(default, skip_serializing_if = "Vec::is_empty")]
78    pub output_refs: Vec<String>,
79}
80
81/// The PROV activity a transition performed.
82#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
83pub struct Activity {
84    /// `drafted` | `formalized` | `verified` | `reviewed` | `accepted`.
85    pub kind: String,
86    #[serde(default, skip_serializing_if = "String::is_empty")]
87    pub started_at: String,
88    #[serde(default, skip_serializing_if = "String::is_empty")]
89    pub ended_at: String,
90}
91
92fn authority_none() -> String {
93    "none".to_string()
94}
95
96/// A non-human actor that contributed to producing a transition.
97#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
98pub struct MachineContribution {
99    /// A non-human actor id, e.g. `agent:claude`. Refused by
100    /// [`Provenance::validate`] if it classifies as human.
101    pub id: String,
102    /// Declared actor class (`agent`, `ci`). Decorative: the load-bearing class
103    /// comes from `id` via [`crate::events::actor_kind`].
104    #[serde(default, skip_serializing_if = "String::is_empty")]
105    pub class: String,
106    /// What the contributor did, e.g. `drafted`.
107    #[serde(default, skip_serializing_if = "String::is_empty")]
108    pub role: String,
109    /// The tool surface, e.g. `claude-code`.
110    #[serde(default, skip_serializing_if = "String::is_empty")]
111    pub tool: String,
112    /// UNVERIFIED free-text model/version provenance, e.g.
113    /// `model: claude-opus-4-8`. Never resolved to a key, never an attestation
114    /// ABOUT the model.
115    #[serde(default, skip_serializing_if = "String::is_empty")]
116    pub generated_by: String,
117    /// Always `none`. A machine contribution cannot assert authority;
118    /// [`Provenance::validate`] refuses any other value. Present on the wire so
119    /// the non-authoritative status is explicit, matching PROV's agent-role
120    /// separation.
121    #[serde(default = "authority_none")]
122    pub authority: String,
123}
124
125/// A verifier / CI actor whose self-signed evidence a transition relied on.
126#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
127pub struct EvidenceRef {
128    /// A verifier / CI actor id, e.g. `ci:vela-verify`. Refused by
129    /// [`Provenance::validate`] if it classifies as human.
130    pub id: String,
131    #[serde(default, skip_serializing_if = "String::is_empty")]
132    pub class: String,
133    #[serde(default, skip_serializing_if = "String::is_empty")]
134    pub role: String,
135    /// The self-signed `vva_` evidence ids this decision cites.
136    #[serde(default, skip_serializing_if = "Vec::is_empty")]
137    pub attachment_ids: Vec<String>,
138}
139
140impl Provenance {
141    /// No attribution to record. An empty block is never serialized, so an event
142    /// without provenance stays byte-identical to the pre-redesign shape.
143    pub fn is_empty(&self) -> bool {
144        self.activity.is_none()
145            && self.machine_contributions.is_empty()
146            && self.evidence_refs.is_empty()
147            && self.input_refs.is_empty()
148            && self.output_refs.is_empty()
149    }
150
151    /// Structural no-signer guard: every named id MUST be non-human, and no
152    /// machine contribution may claim authority. A human id, or an asserted
153    /// authority, would be a name standing in for the accountable signature, the
154    /// exact anti-pattern the trust thesis forbids, so each is a hard error.
155    pub fn validate(&self) -> Result<(), String> {
156        for mc in &self.machine_contributions {
157            if crate::events::actor_kind(&mc.id) == "human" {
158                return Err(format!(
159                    "provenance.machine_contributions may not name a human id ('{}'): the accountable human is the signer, never a contribution",
160                    mc.id
161                ));
162            }
163            if !mc.authority.is_empty() && mc.authority != "none" {
164                return Err(format!(
165                    "provenance.machine_contributions['{}'].authority must be 'none': a machine contribution cannot assert authority",
166                    mc.id
167                ));
168            }
169        }
170        for er in &self.evidence_refs {
171            if crate::events::actor_kind(&er.id) == "human" {
172                return Err(format!(
173                    "provenance.evidence_refs may not name a human id ('{}'): evidence is signed by machine verifiers, not humans",
174                    er.id
175                ));
176            }
177        }
178        Ok(())
179    }
180
181    /// Bind exactly one decision root through the ordinary signed input-ref
182    /// lane. Rebinding replaces the previous decision-root slot while
183    /// preserving every unrelated input in its original order.
184    ///
185    /// Call this before deriving the event id or signature. The event signing
186    /// preimage covers `payload.provenance.input_refs`, so changing this root
187    /// changes the event id and invalidates an existing signature.
188    pub fn bind_decision_root(&mut self, decision_root: &str) -> Result<(), String> {
189        let reference = decision_root_input_ref(decision_root)?;
190        self.input_refs
191            .retain(|item| !item.starts_with(DECISION_ROOT_INPUT_REF_PREFIX));
192        self.input_refs.push(reference);
193        Ok(())
194    }
195}
196
197/// Insert a validated provenance block into an event payload under the
198/// `provenance` key. An empty block is a no-op, so the event stays
199/// byte-identical (preserving its `vev_` and `event_log_hash`). A populated
200/// block is validated first, so a human id can never enter a signed payload as a
201/// non-signer.
202pub fn attach_to_payload(payload: &mut Value, prov: &Provenance) -> Result<(), String> {
203    if prov.is_empty() {
204        return Ok(());
205    }
206    prov.validate()?;
207    let obj = payload
208        .as_object_mut()
209        .ok_or("provenance: event payload must be a JSON object to carry a provenance block")?;
210    obj.insert(
211        "provenance".to_string(),
212        serde_json::to_value(prov).map_err(|e| format!("provenance: serialize: {e}"))?,
213    );
214    Ok(())
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220    use serde_json::json;
221
222    fn agent_contribution() -> MachineContribution {
223        MachineContribution {
224            id: "agent:claude".to_string(),
225            class: "agent".to_string(),
226            role: "drafted".to_string(),
227            tool: "claude-code".to_string(),
228            generated_by: "model: claude-opus-4-8".to_string(),
229            authority: "none".to_string(),
230        }
231    }
232
233    #[test]
234    fn validate_accepts_non_human_ids() {
235        let p = Provenance {
236            activity: Some(Activity {
237                kind: "accepted".to_string(),
238                ..Default::default()
239            }),
240            machine_contributions: vec![agent_contribution()],
241            evidence_refs: vec![EvidenceRef {
242                id: "ci:vela-verify".to_string(),
243                class: "ci".to_string(),
244                role: "verified".to_string(),
245                attachment_ids: vec!["vva_abc".to_string()],
246            }],
247            ..Default::default()
248        };
249        assert!(p.validate().is_ok());
250    }
251
252    #[test]
253    fn validate_refuses_human_contribution() {
254        let p = Provenance {
255            machine_contributions: vec![MachineContribution {
256                id: "reviewer:will-blair".to_string(),
257                ..Default::default()
258            }],
259            ..Default::default()
260        };
261        // A human id smuggled in as a contribution must be a hard error: the
262        // accountable human signs, they are never merely attributed.
263        assert!(p.validate().is_err());
264    }
265
266    #[test]
267    fn validate_refuses_human_evidence_ref() {
268        let p = Provenance {
269            evidence_refs: vec![EvidenceRef {
270                id: "reviewer:will-blair".to_string(),
271                ..Default::default()
272            }],
273            ..Default::default()
274        };
275        assert!(p.validate().is_err());
276    }
277
278    #[test]
279    fn validate_refuses_machine_claiming_authority() {
280        let mut mc = agent_contribution();
281        mc.authority = "signer".to_string();
282        let p = Provenance {
283            machine_contributions: vec![mc],
284            ..Default::default()
285        };
286        // A machine contribution that asserts authority is rejected: authority
287        // is always the signer path, never a provenance entry.
288        assert!(p.validate().is_err());
289    }
290
291    #[test]
292    fn attach_empty_is_a_noop_byte_identical() {
293        let mut payload = json!({ "proposal_id": "vpr_x", "verdict": "accepted" });
294        let before = payload.clone();
295        attach_to_payload(&mut payload, &Provenance::default()).unwrap();
296        // An absent block must never perturb the payload, so the event's vev_
297        // and event_log_hash are unchanged for every pre-redesign event.
298        assert_eq!(payload, before);
299        assert!(payload.get("provenance").is_none());
300    }
301
302    #[test]
303    fn attach_populated_inserts_block() {
304        let mut payload = json!({ "proposal_id": "vpr_x" });
305        let p = Provenance {
306            machine_contributions: vec![agent_contribution()],
307            ..Default::default()
308        };
309        attach_to_payload(&mut payload, &p).unwrap();
310        assert_eq!(
311            payload["provenance"]["machine_contributions"][0]["id"],
312            "agent:claude"
313        );
314        assert_eq!(
315            payload["provenance"]["machine_contributions"][0]["authority"],
316            "none"
317        );
318    }
319
320    #[test]
321    fn attach_refuses_human_before_writing() {
322        let mut payload = json!({ "proposal_id": "vpr_x" });
323        let p = Provenance {
324            machine_contributions: vec![MachineContribution {
325                id: "reviewer:will-blair".to_string(),
326                ..Default::default()
327            }],
328            ..Default::default()
329        };
330        assert!(attach_to_payload(&mut payload, &p).is_err());
331        // The guard fires before mutation: a rejected block leaves no trace.
332        assert!(payload.get("provenance").is_none());
333    }
334
335    #[test]
336    fn empty_block_serializes_to_empty_object() {
337        // skip_serializing_if keeps every field out of the JSON when empty, so a
338        // defaulted Provenance is the empty object and adds nothing to a body.
339        let v = serde_json::to_value(Provenance::default()).unwrap();
340        assert_eq!(v, json!({}));
341    }
342
343    #[test]
344    fn decision_root_binding_is_typed_validated_and_replaceable() {
345        let first = format!("sha256:{}", "a".repeat(64));
346        let second = format!("sha256:{}", "b".repeat(64));
347        let mut p = Provenance {
348            input_refs: vec!["sha256:ordinary-input".to_string()],
349            ..Default::default()
350        };
351
352        p.bind_decision_root(&first).unwrap();
353        p.bind_decision_root(&second).unwrap();
354
355        assert_eq!(
356            p.input_refs,
357            vec![
358                "sha256:ordinary-input".to_string(),
359                format!("{DECISION_ROOT_INPUT_REF_PREFIX}{second}"),
360            ]
361        );
362        assert!(
363            p.bind_decision_root(&format!("sha256:{}", "A".repeat(64)))
364                .is_err()
365        );
366        assert!(p.bind_decision_root("sha256:short").is_err());
367    }
368}