1use std::collections::BTreeSet;
26
27use serde::{Deserialize, Serialize};
28use sha2::{Digest, Sha256};
29
30pub const ACTIVITY_ENVELOPE_SCHEMA: &str = "vela.activity-envelope.v1";
31pub const RETRIEVAL_RECEIPT_SCHEMA: &str = "vela.retrieval-receipt.v1";
32
33pub const ACTIVITY_PREFIXES: [&str; 2] = ["vac_", "vrr_"];
36
37pub fn is_activity_id(id: &str) -> bool {
40 ACTIVITY_PREFIXES.iter().any(|p| id.starts_with(p))
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45pub struct ActivityEnvelope {
46 pub schema: String,
47 pub activity_id: String,
50 pub actor_id: String,
51 pub actor_type: String,
52 pub kind: String,
55 pub base_root: String,
57 #[serde(default, skip_serializing_if = "Vec::is_empty")]
58 pub input_roots: Vec<String>,
59 #[serde(default, skip_serializing_if = "Vec::is_empty")]
60 pub output_roots: Vec<String>,
61 #[serde(default, skip_serializing_if = "Vec::is_empty")]
62 pub tool_digests: Vec<String>,
63 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub trace_root: Option<String>,
67 #[serde(default, skip_serializing_if = "Vec::is_empty")]
68 pub risk_tags: Vec<String>,
69 #[serde(default, skip_serializing_if = "String::is_empty")]
72 pub claimed_relation: String,
73 pub created_at: String,
74 #[serde(default, skip_serializing_if = "String::is_empty")]
75 pub signature: String,
76 #[serde(default, skip_serializing_if = "String::is_empty")]
77 pub signer_pubkey_hex: String,
78}
79
80#[derive(Debug, Clone, Default)]
82pub struct ActivityDraft {
83 pub actor_id: String,
84 pub actor_type: String,
85 pub kind: String,
86 pub base_root: String,
87 pub input_roots: Vec<String>,
88 pub output_roots: Vec<String>,
89 pub tool_digests: Vec<String>,
90 pub trace_root: Option<String>,
91 pub risk_tags: Vec<String>,
92 pub claimed_relation: String,
93 pub created_at: String,
94}
95
96impl ActivityEnvelope {
97 pub fn new(draft: ActivityDraft) -> Result<Self, String> {
100 if draft.base_root.trim().is_empty() {
101 return Err("activity.base_root cannot be empty (root it ran against)".to_string());
102 }
103 if draft.kind.trim().is_empty() {
104 return Err("activity.kind cannot be empty".to_string());
105 }
106 let mut env = ActivityEnvelope {
107 schema: ACTIVITY_ENVELOPE_SCHEMA.to_string(),
108 activity_id: String::new(),
109 actor_id: draft.actor_id,
110 actor_type: draft.actor_type,
111 kind: draft.kind,
112 base_root: draft.base_root,
113 input_roots: draft.input_roots,
114 output_roots: draft.output_roots,
115 tool_digests: draft.tool_digests,
116 trace_root: draft.trace_root,
117 risk_tags: draft.risk_tags,
118 claimed_relation: draft.claimed_relation,
119 created_at: draft.created_at,
120 signature: String::new(),
121 signer_pubkey_hex: String::new(),
122 };
123 env.activity_id = env.derive_id()?;
124 Ok(env)
125 }
126
127 fn id_preimage_bytes(&self) -> Result<Vec<u8>, String> {
128 let mut p = self.clone();
129 p.activity_id = String::new();
130 p.signature = String::new();
131 p.signer_pubkey_hex = String::new();
132 crate::canonical::to_canonical_bytes(&p)
133 .map_err(|e| format!("canonicalize activity preimage: {e}"))
134 }
135
136 pub fn derive_id(&self) -> Result<String, String> {
138 let bytes = self.id_preimage_bytes()?;
139 Ok(format!(
140 "vac_{}",
141 &hex::encode(Sha256::digest(&bytes))[..16]
142 ))
143 }
144
145 pub fn sign(&mut self, key: &ed25519_dalek::SigningKey) -> Result<(), String> {
147 let preimage = self.id_preimage_bytes()?;
148 self.signature = hex::encode(crate::sign::sign_bytes(key, &preimage));
149 self.signer_pubkey_hex = hex::encode(key.verifying_key().to_bytes());
150 Ok(())
151 }
152
153 pub fn is_authoritative(&self) -> bool {
156 false
157 }
158
159 pub fn verify(&self) -> Result<(), String> {
162 if self.schema != ACTIVITY_ENVELOPE_SCHEMA {
163 return Err(format!(
164 "activity.schema must be `{ACTIVITY_ENVELOPE_SCHEMA}`"
165 ));
166 }
167 if self.activity_id != self.derive_id()? {
168 return Err("activity_id is not the content address of the body".to_string());
169 }
170 if !self.signature.is_empty() {
171 let preimage = self.id_preimage_bytes()?;
172 if !crate::sign::verify_action_signature(
173 &preimage,
174 &self.signature,
175 &self.signer_pubkey_hex,
176 )? {
177 return Err(
178 "activity signature does not verify under the declared pubkey".to_string(),
179 );
180 }
181 }
182 Ok(())
183 }
184}
185
186#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
189pub struct RetrievalReceipt {
190 pub schema: String,
191 pub receipt_id: String,
193 pub dataset_root: String,
194 pub query: String,
196 pub tool_digest: String,
197 pub result_root: String,
198 #[serde(default, skip_serializing_if = "Vec::is_empty")]
199 pub completeness_warnings: Vec<String>,
200 #[serde(default, skip_serializing_if = "String::is_empty")]
201 pub replay_command: String,
202 pub created_at: String,
203}
204
205impl RetrievalReceipt {
206 pub fn new(
207 dataset_root: &str,
208 query: &str,
209 tool_digest: &str,
210 result_root: &str,
211 completeness_warnings: Vec<String>,
212 replay_command: &str,
213 created_at: &str,
214 ) -> Result<Self, String> {
215 if dataset_root.trim().is_empty() || result_root.trim().is_empty() {
216 return Err("retrieval receipt needs dataset_root and result_root".to_string());
217 }
218 let mut r = RetrievalReceipt {
219 schema: RETRIEVAL_RECEIPT_SCHEMA.to_string(),
220 receipt_id: String::new(),
221 dataset_root: dataset_root.to_string(),
222 query: query.to_string(),
223 tool_digest: tool_digest.to_string(),
224 result_root: result_root.to_string(),
225 completeness_warnings,
226 replay_command: replay_command.to_string(),
227 created_at: created_at.to_string(),
228 };
229 r.receipt_id = r.derive_id()?;
230 Ok(r)
231 }
232
233 pub fn derive_id(&self) -> Result<String, String> {
234 let mut p = self.clone();
235 p.receipt_id = String::new();
236 let bytes = crate::canonical::to_canonical_bytes(&p)
237 .map_err(|e| format!("canonicalize retrieval receipt: {e}"))?;
238 Ok(format!(
239 "vrr_{}",
240 &hex::encode(Sha256::digest(&bytes))[..16]
241 ))
242 }
243
244 pub fn is_authoritative(&self) -> bool {
245 false
246 }
247
248 pub fn verify(&self) -> Result<(), String> {
249 if self.schema != RETRIEVAL_RECEIPT_SCHEMA {
250 return Err(format!(
251 "retrieval.schema must be `{RETRIEVAL_RECEIPT_SCHEMA}`"
252 ));
253 }
254 if self.receipt_id != self.derive_id()? {
255 return Err("receipt_id is not the content address of the body".to_string());
256 }
257 Ok(())
258 }
259}
260
261pub fn assert_not_in_lineage(accepted_atoms: &BTreeSet<String>) -> Result<(), String> {
266 let leaked: Vec<&String> = accepted_atoms
267 .iter()
268 .filter(|a| is_activity_id(a))
269 .collect();
270 if leaked.is_empty() {
271 Ok(())
272 } else {
273 Err(format!(
274 "activity-plane ids leaked into accepted lineage (activity is not state): {leaked:?}"
275 ))
276 }
277}
278
279pub fn activity_ids_in_lineage(
288 findings: &[crate::bundle::FindingBundle],
289 attachments: &[crate::verifier_attachment::VerifierAttachment],
290) -> Vec<(String, String)> {
291 let mut leaks = Vec::new();
292 for f in findings
293 .iter()
294 .filter(|f| !f.flags.superseded && !f.flags.retracted)
295 {
296 for l in f.links.iter().filter(|l| is_activity_id(&l.target)) {
297 leaks.push((f.id.clone(), l.target.clone()));
298 }
299 }
300 for a in attachments {
301 if is_activity_id(&a.target) {
302 leaks.push((a.id.clone(), a.target.clone()));
303 }
304 for indep in a.independent_of.iter().filter(|i| is_activity_id(i)) {
305 leaks.push((a.id.clone(), indep.clone()));
306 }
307 }
308 leaks
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314
315 fn draft() -> ActivityDraft {
316 ActivityDraft {
317 actor_id: "agent:canopus".into(),
318 actor_type: "agent".into(),
319 kind: "model.candidate".into(),
320 base_root: "vpr_root_r".into(),
321 claimed_relation: "improves A309370(13)".into(),
322 created_at: "2026-06-18T00:00:00Z".into(),
323 ..Default::default()
324 }
325 }
326
327 #[test]
328 fn envelope_is_content_addressed_and_nonauthoritative() {
329 let e = ActivityEnvelope::new(draft()).unwrap();
330 assert!(e.activity_id.starts_with("vac_"));
331 assert!(!e.is_authoritative());
332 e.verify().unwrap();
333 }
334
335 #[test]
336 fn tamper_breaks_the_id() {
337 let mut e = ActivityEnvelope::new(draft()).unwrap();
338 e.claimed_relation = "improves A309370(99)".into(); assert!(e.verify().is_err());
340 }
341
342 #[test]
343 fn optional_signature_round_trips() {
344 let mut e = ActivityEnvelope::new(draft()).unwrap();
345 let key = ed25519_dalek::SigningKey::from_bytes(&[3u8; 32]);
346 e.sign(&key).unwrap();
347 e.verify().unwrap();
348 assert!(!e.signature.is_empty());
349 }
350
351 #[test]
352 fn retrieval_receipt_round_trips() {
353 let r = RetrievalReceipt::new(
354 "sha256:dataset",
355 "A309370 where n<=24",
356 "sha256:tool",
357 "sha256:result",
358 vec!["paginated; 2 pages not fetched".into()],
359 "vela retrieve ...",
360 "2026-06-18T00:00:00Z",
361 )
362 .unwrap();
363 assert!(r.receipt_id.starts_with("vrr_"));
364 assert!(!r.is_authoritative());
365 r.verify().unwrap();
366 }
367
368 #[test]
369 fn the_law_catches_a_leaked_activity_id() {
370 let mut atoms = BTreeSet::new();
371 atoms.insert("verifier:vela-verify.sidon".to_string());
372 assert!(assert_not_in_lineage(&atoms).is_ok());
373 atoms.insert("vac_deadbeefdeadbeef".to_string()); assert!(assert_not_in_lineage(&atoms).is_err());
375 }
376
377 #[test]
378 fn lineage_scan_flags_activity_link_targets() {
379 let mut f = crate::test_support::make_finding("vf_a", 1.0, "computational");
380 assert!(activity_ids_in_lineage(std::slice::from_ref(&f), &[]).is_empty());
382 f.links.push(crate::bundle::Link {
384 target: "vac_deadbeefdeadbeef".to_string(),
385 link_type: "depends".to_string(),
386 note: String::new(),
387 inferred_by: "agent:test".to_string(),
388 created_at: "2026-06-18T00:00:00Z".to_string(),
389 mechanism: None,
390 });
391 let leaks = activity_ids_in_lineage(std::slice::from_ref(&f), &[]);
392 assert_eq!(leaks.len(), 1);
393 assert_eq!(leaks[0].1, "vac_deadbeefdeadbeef");
394 }
395
396 fn attachment_to(
400 target: &str,
401 independent_of: Vec<String>,
402 ) -> crate::verifier_attachment::VerifierAttachment {
403 use crate::verifier_attachment::{
404 AttachmentDraft, AttachmentOutcome, MatchToClaim, VerifierAttachment, VerifierMethod,
405 };
406 let mut att = VerifierAttachment::build(AttachmentDraft {
407 target: "vf_0123456789abcdef".to_string(),
408 claim_digest: "sha256:claim".to_string(),
409 verifier_method: VerifierMethod::ComputationalSearch,
410 solver_id: "cp-sat".to_string(),
411 independent_of,
412 match_to_claim: MatchToClaim {
413 matches: true,
414 checker_actor: "checker".to_string(),
415 },
416 adversarial_probes: vec![],
417 outcome: AttachmentOutcome::Passed,
418 verifier_actor: "Opus 4.8".to_string(),
419 note: String::new(),
420 })
421 .unwrap();
422 att.target = target.to_string();
423 att
424 }
425
426 #[test]
427 fn lineage_scan_flags_attachment_target_and_independence() {
428 let att = attachment_to("vac_deadbeefdeadbeef", vec![]);
430 let leaks = activity_ids_in_lineage(&[], std::slice::from_ref(&att));
431 assert_eq!(leaks.len(), 1);
432 assert_eq!(leaks[0].1, "vac_deadbeefdeadbeef");
433
434 let att = attachment_to(
436 "vf_0123456789abcdef",
437 vec!["vrr_cafebabecafebabe".to_string()],
438 );
439 let leaks = activity_ids_in_lineage(&[], std::slice::from_ref(&att));
440 assert_eq!(leaks.len(), 1);
441 assert_eq!(leaks[0].1, "vrr_cafebabecafebabe");
442
443 let att = attachment_to("vf_0123456789abcdef", vec![]);
445 assert!(activity_ids_in_lineage(&[], std::slice::from_ref(&att)).is_empty());
446 }
447
448 #[test]
449 fn lineage_scan_skips_superseded_and_retracted_findings() {
450 let mut f = crate::test_support::make_finding("vf_a", 1.0, "computational");
451 f.links.push(crate::bundle::Link {
452 target: "vac_deadbeefdeadbeef".to_string(),
453 link_type: "depends".to_string(),
454 note: String::new(),
455 inferred_by: "agent:test".to_string(),
456 created_at: "2026-06-18T00:00:00Z".to_string(),
457 mechanism: None,
458 });
459 assert_eq!(
461 activity_ids_in_lineage(std::slice::from_ref(&f), &[]).len(),
462 1
463 );
464 f.flags.superseded = true;
466 assert!(activity_ids_in_lineage(std::slice::from_ref(&f), &[]).is_empty());
467 f.flags.superseded = false;
469 f.flags.retracted = true;
470 assert!(activity_ids_in_lineage(std::slice::from_ref(&f), &[]).is_empty());
471 }
472}