Skip to main content

vela_protocol/objects/
activity.rs

1//! The activity plane: non-authoritative records of what agents, tools, and
2//! producers DID, kept strictly separate from accepted scientific state.
3//!
4//! "Activity is not state." An agent run, a retrieval, a model candidate, a
5//! simulation: these are inputs and proposals, never evidence, until an accepted
6//! transition admits a specific load-bearing atom. This module gives that
7//! boundary a TYPE and an executable LAW.
8//!
9//!   - [`ActivityEnvelope`] (`vac_`) is a content-addressed record of one action
10//!     against a named root, carrying its inputs/outputs, tool digests, a trace
11//!     root, risk tags, and a CLAIMED relation. The claim is a proposal, not a
12//!     finding.
13//!   - [`RetrievalReceipt`] (`vrr_`) is a deterministic retrieval record: the
14//!     dataset root, the query semantics, the tool digest, the result root, any
15//!     completeness warnings, and a replay command.
16//!   - [`assert_not_in_lineage`] is the law: no activity id may appear among the
17//!     accepted-lineage atoms. The activity plane can be enormous without scaling
18//!     false authority, because authority lives only in accepted transitions.
19//!
20//! These are intentionally NOT signed-or-rejected like accepted state: an
21//! envelope may be unsigned (activity is cheap and high-volume). The id is a pure
22//! content address; an optional signature binds an accountable actor. Mirrors the
23//! content-addressing of [`crate::attempt::Attempt`].
24
25use 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
33/// The id prefixes the activity plane owns. Anything with one of these prefixes
34/// is non-authoritative by construction.
35pub const ACTIVITY_PREFIXES: [&str; 2] = ["vac_", "vrr_"];
36
37/// True if `id` names an activity-plane artifact (and therefore can never be
38/// accepted support).
39pub fn is_activity_id(id: &str) -> bool {
40    ACTIVITY_PREFIXES.iter().any(|p| id.starts_with(p))
41}
42
43/// A non-authoritative record of one action against a named root.
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45pub struct ActivityEnvelope {
46    pub schema: String,
47    /// `vac_<16hex>`, content-addressed over the body with id/signature/signer
48    /// zeroed. Key-independent.
49    pub activity_id: String,
50    pub actor_id: String,
51    pub actor_type: String,
52    /// `agent.run` | `retrieval` | `model.candidate` | `simulation` |
53    /// `review.note` | other. Free-form, domain adapters refine it.
54    pub kind: String,
55    /// The frontier / presentation root this ran against.
56    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    /// Content hash of the full trace artifact (the raw transcript lives in
64    /// object storage; only its address is bound here).
65    #[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    /// What this activity CLAIMS (e.g. "improves A309370(13)"). A proposal, never
70    /// accepted from here.
71    #[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/// Fields a caller supplies; schema, id, and signature are derived.
81#[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    /// Content-address an envelope from a draft (unsigned). Activity is cheap and
98    /// high-volume; a signature is optional and added by [`Self::sign`].
99    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    /// `vac_<16hex>` over the canonical content preimage.
137    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    /// Optionally bind an accountable signer over the same content preimage.
146    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    /// `false`, always. Activity never carries authority; only an accepted
154    /// transition does. Present so the type makes the boundary explicit.
155    pub fn is_authoritative(&self) -> bool {
156        false
157    }
158
159    /// Re-derive the id and, if a signature is present, verify it over the
160    /// content preimage. Any hand-edit fails here.
161    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/// A deterministic retrieval record: what was fetched, under what query, with
187/// what completeness, and how to replay it.
188#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
189pub struct RetrievalReceipt {
190    pub schema: String,
191    /// `vrr_<16hex>`, content-addressed.
192    pub receipt_id: String,
193    pub dataset_root: String,
194    /// The exact query / filter semantics (not a prose summary).
195    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
261/// The activity/state boundary, made executable: NO activity-plane id may appear
262/// among the accepted-lineage atoms. If one has leaked into accepted state, that
263/// is a soundness break (activity was admitted as authority without a
264/// transition). Returns the offending ids.
265pub 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
279/// Activity-plane ids found in LINEAGE-BEARING positions of accepted records:
280/// the dependency-link targets of live findings, and the target / independence
281/// refs of verifier-gate attachments. These are the only positions a `vac_`/
282/// `vrr_` id could occupy to become load-bearing, since activity envelopes live
283/// in a separate store and never enter the event log. Returns `(holder_id,
284/// leaked_atom)` pairs; empty means the activity/state boundary holds on this
285/// record. This is [`assert_not_in_lineage`] applied to a live frontier: the
286/// accept path rejects these at write, and `vela check` fails on any that exist.
287pub 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(); // edit body, id stale
339        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()); // activity leaked into lineage
374        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        // a normal finding carries no activity-plane lineage
381        assert!(activity_ids_in_lineage(std::slice::from_ref(&f), &[]).is_empty());
382        // depending on an activity envelope is a boundary break
383        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    /// Build a structurally-valid attachment, then overwrite the lineage-bearing
397    /// fields the scan reads (`build` enforces a `vf_`/`vfr_` target, so the leak
398    /// has to be injected after construction).
399    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        // an attachment pointed AT an activity envelope is a boundary break
429        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        // declaring independence from a retrieval receipt (vrr_) is also a break
435        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        // a clean attachment trips nothing
444        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        // live: the leak is in force and visible
460        assert_eq!(
461            activity_ids_in_lineage(std::slice::from_ref(&f), &[]).len(),
462            1
463        );
464        // superseded findings are out of force, so out of scope for the scan
465        f.flags.superseded = true;
466        assert!(activity_ids_in_lineage(std::slice::from_ref(&f), &[]).is_empty());
467        // retracted likewise
468        f.flags.superseded = false;
469        f.flags.retracted = true;
470        assert!(activity_ids_in_lineage(std::slice::from_ref(&f), &[]).is_empty());
471    }
472}