1use serde::{Deserialize, Serialize};
24use serde_json::Value;
25
26pub const DECISION_ROOT_INPUT_REF_PREFIX: &str = "urn:vela:decision-root:";
34
35pub 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
59pub struct Provenance {
60 #[serde(default, skip_serializing_if = "Option::is_none")]
63 pub activity: Option<Activity>,
64 #[serde(default, skip_serializing_if = "Vec::is_empty")]
67 pub machine_contributions: Vec<MachineContribution>,
68 #[serde(default, skip_serializing_if = "Vec::is_empty")]
72 pub evidence_refs: Vec<EvidenceRef>,
73 #[serde(default, skip_serializing_if = "Vec::is_empty")]
75 pub input_refs: Vec<String>,
76 #[serde(default, skip_serializing_if = "Vec::is_empty")]
78 pub output_refs: Vec<String>,
79}
80
81#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
83pub struct Activity {
84 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
98pub struct MachineContribution {
99 pub id: String,
102 #[serde(default, skip_serializing_if = "String::is_empty")]
105 pub class: String,
106 #[serde(default, skip_serializing_if = "String::is_empty")]
108 pub role: String,
109 #[serde(default, skip_serializing_if = "String::is_empty")]
111 pub tool: String,
112 #[serde(default, skip_serializing_if = "String::is_empty")]
116 pub generated_by: String,
117 #[serde(default = "authority_none")]
122 pub authority: String,
123}
124
125#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
127pub struct EvidenceRef {
128 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 #[serde(default, skip_serializing_if = "Vec::is_empty")]
137 pub attachment_ids: Vec<String>,
138}
139
140impl Provenance {
141 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 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 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
197pub 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 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 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 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 assert!(payload.get("provenance").is_none());
333 }
334
335 #[test]
336 fn empty_block_serializes_to_empty_object() {
337 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}