1use serde::Serialize;
14
15use crate::project::Project;
16
17#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
19pub struct Contributor {
20 pub agent_id: String,
21 pub agent_kind: String,
23 pub role: String,
25 pub unit: String,
27}
28
29#[derive(Debug, Clone, Serialize)]
31pub struct CreditView {
32 pub finding: String,
33 pub author_of_record: Vec<String>,
37 pub contributors: Vec<Contributor>,
40 pub originating_agents: Vec<Contributor>,
43 pub statement: String,
45}
46
47#[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 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; };
77 if actor.is_revoked_at(e.timestamp.as_str()) {
78 continue; }
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 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
156fn 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 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 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 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 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 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 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 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 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", ®istered_pubkey));
308 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}