Skip to main content

vela_protocol/analysis/
credit.rs

1//! Derived credit view (CRediT-style): a pure projection over the event log plus
2//! finding provenance. It answers "who is accountable, and who produced what"
3//! from data that already exists — signatures, `contributions[]`, `extraction`,
4//! and the drafting actor. Never signed, never authoritative, always
5//! recomputable, and it never invents an author.
6//!
7//! The anti-crumple-zone property: `author_of_record` is computed from valid
8//! human signatures on accepting events, not from proximity. A machine holds no
9//! key and can never be accountable, so a model appears only under
10//! `contributors` / `originating_agents`, never as an author. If no human
11//! signature exists, the author set is empty and the view says so.
12
13use serde::Serialize;
14
15use crate::project::Project;
16
17/// One disclosed producer of a finding (or a unit of it), machine or human.
18#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
19pub struct Contributor {
20    pub agent_id: String,
21    /// `human | agent | model`.
22    pub agent_kind: String,
23    /// `originated | derived | formalized | extracted | reviewed | vouched | drafted`.
24    pub role: String,
25    /// The sub-claim this applies to, or `whole`.
26    pub unit: String,
27}
28
29/// The credit view for one finding. A projection, never signed.
30#[derive(Debug, Clone, Serialize)]
31pub struct CreditView {
32    pub finding: String,
33    /// Accountable humans: exactly the actors carrying a valid human signature on
34    /// an accepting event. Empty means "no accountable author yet" — never
35    /// invented.
36    pub author_of_record: Vec<String>,
37    /// Producers disclosed, machines included, from `contributions[]`,
38    /// `extraction`, and the drafting actor.
39    pub contributors: Vec<Contributor>,
40    /// Contributions whose role is `originated` — may be a model, disclosed, and
41    /// explicitly NOT an author.
42    pub originating_agents: Vec<Contributor>,
43    /// A one-line, methods-style rendering.
44    pub statement: String,
45}
46
47/// Compute the credit view for a finding. Pure and deterministic.
48#[must_use]
49pub fn credit(project: &Project, finding_id: &str) -> Option<CreditView> {
50    let finding = project.findings.iter().find(|f| f.id == finding_id)?;
51
52    // author_of_record: humans carrying a VALID human Ed25519 signature on an
53    // accepting event for this finding (`finding.asserted`, or `finding.reviewed`
54    // with an accept). Validity is cryptographic, not nominal — the actor must be
55    // registered, its key not revoked at the event timestamp, and the signature
56    // must verify against that key. A present-but-unverifiable signature confers
57    // no authorship; this is the anti-crumple-zone property, enforced here rather
58    // than assumed from a prior verify pass.
59    let mut author_of_record: Vec<String> = Vec::new();
60    for e in &project.events {
61        if e.target.id != finding_id || e.actor.r#type != "human" {
62            continue;
63        }
64        let accepting = match e.kind.as_str() {
65            "finding.asserted" => true,
66            "finding.reviewed" => {
67                e.payload.get("status").and_then(|v| v.as_str()) == Some("accepted")
68            }
69            _ => false,
70        };
71        if !accepting || author_of_record.contains(&e.actor.id) {
72            continue;
73        }
74        let Some(actor) = project.actors.iter().find(|a| a.id == e.actor.id) else {
75            continue; // unregistered signer — no accountable key
76        };
77        if actor.is_revoked_at(e.timestamp.as_str()) {
78            continue; // key revoked at-or-before this event
79        }
80        if matches!(
81            crate::sign::verify_event_signature(e, &actor.public_key),
82            Ok(true)
83        ) {
84            author_of_record.push(e.actor.id.clone());
85        }
86    }
87
88    // contributors: the recorded claim-granularity attributions, then the
89    // extraction model, then the drafting actor if it was an agent.
90    let mut contributors: Vec<Contributor> = Vec::new();
91    for c in &finding.provenance.contributions {
92        contributors.push(Contributor {
93            agent_id: c.agent_id.clone(),
94            agent_kind: c.agent_kind.as_str().to_string(),
95            role: c.role.as_str().to_string(),
96            unit: c.unit.clone(),
97        });
98    }
99    if let Some(model) = finding
100        .provenance
101        .extraction
102        .model
103        .as_deref()
104        .filter(|m| !m.trim().is_empty())
105    {
106        push_unique(
107            &mut contributors,
108            Contributor {
109                agent_id: model.to_string(),
110                agent_kind: "model".to_string(),
111                role: "extracted".to_string(),
112                unit: "whole".to_string(),
113            },
114        );
115    }
116    for e in &project.events {
117        if e.target.id == finding_id
118            && e.kind.as_str() == "finding.asserted"
119            && e.actor.r#type == "agent"
120        {
121            push_unique(
122                &mut contributors,
123                Contributor {
124                    agent_id: e.actor.id.clone(),
125                    agent_kind: "agent".to_string(),
126                    role: "drafted".to_string(),
127                    unit: "whole".to_string(),
128                },
129            );
130        }
131    }
132
133    let originating_agents: Vec<Contributor> = contributors
134        .iter()
135        .filter(|c| c.role == "originated")
136        .cloned()
137        .collect();
138
139    let statement = render_statement(&author_of_record, &contributors);
140
141    Some(CreditView {
142        finding: finding_id.to_string(),
143        author_of_record,
144        contributors,
145        originating_agents,
146        statement,
147    })
148}
149
150fn push_unique(v: &mut Vec<Contributor>, c: Contributor) {
151    if !v.contains(&c) {
152        v.push(c);
153    }
154}
155
156/// Methods-style: "Authored by <humans>. Contributions: <who> <role> <unit>; …"
157fn render_statement(authors: &[String], contributors: &[Contributor]) -> String {
158    let authored = if authors.is_empty() {
159        "No accountable author yet".to_string()
160    } else {
161        format!("Authored by {}", authors.join(", "))
162    };
163    if contributors.is_empty() {
164        return format!("{authored}.");
165    }
166    let parts: Vec<String> = contributors
167        .iter()
168        .map(|c| format!("{} {} {}", c.agent_id, c.role, c.unit))
169        .collect();
170    format!("{authored}. Contributions: {}.", parts.join("; "))
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use crate::bundle::{AgentKind, Contribution, ContributionRole, ContributionUnitType};
177    use crate::events::{FindingEventInput, StateEvent, compute_event_id, new_finding_event};
178    use crate::project::assemble;
179    use crate::project::reverse_dep_index_tests::synth_finding;
180    use crate::sign::ActorRecord;
181    use ed25519_dalek::SigningKey;
182
183    /// A deterministic keypair; returns the signing key and its hex pubkey.
184    fn keypair(seed: u8) -> (SigningKey, String) {
185        let sk = SigningKey::from_bytes(&[seed; 32]);
186        let pubkey = hex::encode(sk.verifying_key().to_bytes());
187        (sk, pubkey)
188    }
189
190    fn actor(id: &str, pubkey: &str) -> ActorRecord {
191        ActorRecord {
192            id: id.to_string(),
193            public_key: pubkey.to_string(),
194            algorithm: "ed25519".to_string(),
195            created_at: "2025-01-01T00:00:00Z".to_string(),
196            tier: None,
197            orcid: None,
198            access_clearance: None,
199            revoked_at: None,
200            revoked_reason: None,
201        }
202    }
203
204    /// An accepting review event, signed by `key` (id computed before signing so
205    /// the signature verifies against the canonical preimage).
206    fn signed_human_review(finding: &str, human: &str, key: &SigningKey) -> StateEvent {
207        let mut e = new_finding_event(FindingEventInput {
208            kind: "finding.reviewed",
209            finding_id: finding,
210            actor_id: human,
211            actor_type: "human",
212            reason: "accept",
213            before_hash: "",
214            after_hash: "",
215            payload: serde_json::json!({ "status": "accepted" }),
216            caveats: vec![],
217            timestamp: Some("2026-01-01T00:00:00Z"),
218        });
219        e.id = compute_event_id(&e);
220        e.signature = Some(crate::sign::sign_event(&e, key).unwrap());
221        e
222    }
223
224    #[test]
225    fn credit_names_human_signer_and_discloses_model_originator() {
226        let mut f = synth_finding(0, vec![]);
227        f.provenance.contributions = vec![Contribution {
228            unit: "number-field-towers lemma".into(),
229            unit_type: ContributionUnitType::Step,
230            agent_kind: AgentKind::Model,
231            agent_id: "openai/o5".into(),
232            model: Some("openai/o5".into()),
233            model_version: None,
234            role: ContributionRole::Originated,
235            basis: String::new(),
236        }];
237        let fid = f.id.clone();
238        let mut project = assemble("credit", vec![f], 0, 0, "test");
239        let (key, pubkey) = keypair(7);
240        project.actors.push(actor("reviewer:will-blair", &pubkey));
241        project
242            .events
243            .push(signed_human_review(&fid, "reviewer:will-blair", &key));
244
245        let view = credit(&project, &fid).expect("finding exists");
246        // The accountable author is the human signer, never the model.
247        assert_eq!(
248            view.author_of_record,
249            vec!["reviewer:will-blair".to_string()]
250        );
251        assert!(!view.author_of_record.iter().any(|a| a.contains("openai")));
252        // The model is disclosed as the originator, not as an author.
253        assert!(
254            view.originating_agents
255                .iter()
256                .any(|c| c.agent_id == "openai/o5" && c.agent_kind == "model"),
257            "model must appear as an originating agent: {view:?}"
258        );
259        assert!(view.statement.contains("Authored by reviewer:will-blair"));
260    }
261
262    #[test]
263    fn credit_invents_no_author_without_a_signature() {
264        // A review event with NO signature must not confer authorship.
265        let f = synth_finding(1, vec![]);
266        let fid = f.id.clone();
267        let mut project = assemble("credit", vec![f], 0, 0, "test");
268        let (key, pubkey) = keypair(9);
269        project.actors.push(actor("reviewer:x", &pubkey));
270        let mut unsigned = signed_human_review(&fid, "reviewer:x", &key);
271        unsigned.signature = None;
272        project.events.push(unsigned);
273
274        let view = credit(&project, &fid).expect("finding exists");
275        assert!(view.author_of_record.is_empty());
276        assert!(view.statement.contains("No accountable author yet"));
277    }
278
279    #[test]
280    fn credit_rejects_a_forged_signature_from_an_unregistered_actor() {
281        // A present, well-formed signature whose actor is not registered (no
282        // accountable key) must not confer authorship — validity is cryptographic.
283        let f = synth_finding(2, vec![]);
284        let fid = f.id.clone();
285        let mut project = assemble("credit", vec![f], 0, 0, "test");
286        let (key, _pubkey) = keypair(11);
287        // Signed by a real key, but the actor is never registered in project.actors.
288        project
289            .events
290            .push(signed_human_review(&fid, "reviewer:ghost", &key));
291
292        let view = credit(&project, &fid).expect("finding exists");
293        assert!(
294            view.author_of_record.is_empty(),
295            "an unregistered signer is not an accountable author: {view:?}"
296        );
297    }
298
299    #[test]
300    fn credit_rejects_a_signature_that_does_not_verify() {
301        // Actor registered, but the event's signature is from a different key.
302        let f = synth_finding(3, vec![]);
303        let fid = f.id.clone();
304        let mut project = assemble("credit", vec![f], 0, 0, "test");
305        let (wrong_key, _) = keypair(13);
306        let (_right_key, registered_pubkey) = keypair(14);
307        project.actors.push(actor("reviewer:y", &registered_pubkey));
308        // Signed with wrong_key, but the registry holds registered_pubkey.
309        project
310            .events
311            .push(signed_human_review(&fid, "reviewer:y", &wrong_key));
312
313        let view = credit(&project, &fid).expect("finding exists");
314        assert!(
315            view.author_of_record.is_empty(),
316            "a signature that does not verify against the registered key confers no authorship"
317        );
318    }
319}