1use serde::{Deserialize, Serialize};
24use sha2::{Digest, Sha256};
25
26use crate::bundle::{ArtifactAvailability, ArtifactDisclosure, LocatorIntegrity};
27use crate::receipt_v1::ReceiptLineage;
28
29pub const ACTIVITY_RECORD_SCHEMA: &str = "vela.activity-record.v0.1";
30
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
35pub struct RecordArtifact {
36 pub kind: String,
39 pub locator: String,
40 #[serde(default, skip_serializing_if = "String::is_empty")]
44 pub sha256: String,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
46 pub size_bytes: Option<u64>,
47 #[serde(default, skip_serializing_if = "Option::is_none")]
48 pub media_type: Option<String>,
49 #[serde(default, skip_serializing_if = "ArtifactDisclosure::is_unknown")]
50 pub disclosure: ArtifactDisclosure,
51 #[serde(default, skip_serializing_if = "LocatorIntegrity::is_unknown")]
52 pub locator_integrity: LocatorIntegrity,
53 #[serde(default, skip_serializing_if = "ArtifactAvailability::is_unknown")]
54 pub availability: ArtifactAvailability,
55 #[serde(default, skip_serializing_if = "String::is_empty")]
56 pub note: String,
57}
58
59#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
63pub struct RecordVerifierRun {
64 pub method: String,
65 pub outcome: String,
66 pub output_hash: String,
67 #[serde(default, skip_serializing_if = "String::is_empty")]
68 pub solver: String,
69}
70
71#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
75pub struct RecordSource {
76 #[serde(default, skip_serializing_if = "String::is_empty")]
77 pub name: String,
78 #[serde(default, skip_serializing_if = "String::is_empty")]
79 pub source_type: String,
80 #[serde(default, skip_serializing_if = "String::is_empty")]
81 pub uri: String,
82 #[serde(default, skip_serializing_if = "Vec::is_empty")]
83 pub authors: Vec<String>,
84}
85
86#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
87pub struct ActivityRecord {
88 pub schema: String,
89 pub id: String,
91 pub frontier_id: String,
93 #[serde(default, skip_serializing_if = "String::is_empty")]
95 pub against_head: String,
96 pub assertion: String,
98 pub assertion_type: String,
101 pub artifacts: Vec<RecordArtifact>,
102 #[serde(default, skip_serializing_if = "Vec::is_empty")]
103 pub verifier_runs: Vec<RecordVerifierRun>,
104 pub caveats: Vec<String>,
107 #[serde(default, skip_serializing_if = "Option::is_none")]
109 pub source: Option<RecordSource>,
110 #[serde(default, skip_serializing_if = "Vec::is_empty")]
113 pub source_refs: Vec<String>,
114 #[serde(default, skip_serializing_if = "String::is_empty")]
117 pub receipt_digest: String,
118 #[serde(default, skip_serializing_if = "String::is_empty")]
122 pub receipt_path: String,
123 #[serde(default, skip_serializing_if = "String::is_empty")]
126 pub operation_id: String,
127 #[serde(default, skip_serializing_if = "Option::is_none")]
130 pub lineage: Option<ReceiptLineage>,
131 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub supersedes: Option<String>,
140 pub emitted_by: String,
143 pub emitted_at: String,
144 #[serde(default, skip_serializing_if = "String::is_empty")]
148 pub signature: String,
149 #[serde(default, skip_serializing_if = "String::is_empty")]
150 pub signer_pubkey_hex: String,
151}
152
153pub struct ActivityRecordDraft {
154 pub frontier_id: String,
155 pub against_head: String,
156 pub assertion: String,
157 pub assertion_type: String,
158 pub artifacts: Vec<RecordArtifact>,
159 pub verifier_runs: Vec<RecordVerifierRun>,
160 pub caveats: Vec<String>,
161 pub source: Option<RecordSource>,
162 pub source_refs: Vec<String>,
163 pub receipt_digest: String,
164 pub receipt_path: String,
165 pub operation_id: String,
166 pub lineage: Option<ReceiptLineage>,
167 pub emitted_by: String,
168 pub emitted_at: String,
169}
170
171impl ActivityRecord {
172 pub fn build(
174 draft: ActivityRecordDraft,
175 key: Option<&ed25519_dalek::SigningKey>,
176 ) -> Result<Self, String> {
177 if draft.assertion.trim().is_empty() {
178 return Err("record assertion cannot be empty".to_string());
179 }
180 if !draft.frontier_id.starts_with("vfr_") {
181 return Err(format!(
182 "record frontier_id must be a vfr_… id, got '{}'",
183 draft.frontier_id
184 ));
185 }
186 if draft.artifacts.is_empty() {
187 return Err("a record with no artifacts is a slogan; attach at least one".to_string());
188 }
189 for atom in &draft.artifacts {
190 match atom.disclosure {
191 ArtifactDisclosure::Restricted => {
192 if !atom.sha256.is_empty() {
193 return Err(format!(
194 "restricted evidence '{}' must not expose a public equality digest",
195 atom.locator
196 ));
197 }
198 if !(atom.locator.starts_with("custodian:")
199 || atom.locator.starts_with("opaque:"))
200 {
201 return Err(format!(
202 "restricted evidence '{}' needs an opaque custodian: or opaque: locator",
203 atom.locator
204 ));
205 }
206 }
207 ArtifactDisclosure::Public | ArtifactDisclosure::Unknown => {
208 if atom.sha256.len() != 64
209 || !atom
210 .sha256
211 .bytes()
212 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
213 {
214 return Err(format!(
215 "evidence '{}' sha256 must be 32 bytes of lowercase hex",
216 atom.locator
217 ));
218 }
219 }
220 }
221 }
222 if draft.caveats.iter().all(|c| c.trim().is_empty()) {
223 return Err(
224 "a record must state at least one caveat (what this does NOT establish)"
225 .to_string(),
226 );
227 }
228 if draft.emitted_by.trim().is_empty() {
229 return Err("emitted_by is required (agent:…, ci:…, or reviewer:…)".to_string());
230 }
231 if !draft.receipt_digest.is_empty()
232 && !draft
233 .receipt_digest
234 .strip_prefix("sha256:")
235 .is_some_and(|digest| {
236 digest.len() == 64
237 && digest
238 .bytes()
239 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
240 })
241 {
242 return Err("receipt_digest must be sha256:<64 lowercase hex>".to_string());
243 }
244 if !draft.operation_id.is_empty()
245 && !draft
246 .operation_id
247 .strip_prefix("vop_")
248 .is_some_and(|digest| {
249 digest.len() == 64
250 && digest
251 .bytes()
252 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
253 })
254 {
255 return Err("operation_id must be vop_<64 lowercase hex>".to_string());
256 }
257 if !draft.receipt_path.is_empty() {
258 let path = std::path::Path::new(&draft.receipt_path);
259 if path.is_absolute()
260 || path.components().any(|component| {
261 matches!(
262 component,
263 std::path::Component::ParentDir
264 | std::path::Component::RootDir
265 | std::path::Component::Prefix(_)
266 )
267 })
268 {
269 return Err("receipt_path must be a normalized frontier-relative path".to_string());
270 }
271 }
272 let mut rc = ActivityRecord {
273 schema: ACTIVITY_RECORD_SCHEMA.to_string(),
274 id: String::new(),
275 frontier_id: draft.frontier_id,
276 against_head: draft.against_head,
277 assertion: draft.assertion,
278 assertion_type: draft.assertion_type,
279 artifacts: draft.artifacts,
280 verifier_runs: draft.verifier_runs,
281 caveats: draft.caveats,
282 source: draft.source,
283 source_refs: draft.source_refs,
284 receipt_digest: draft.receipt_digest,
285 receipt_path: draft.receipt_path,
286 operation_id: draft.operation_id,
287 lineage: draft.lineage,
288 supersedes: None,
289 emitted_by: draft.emitted_by,
290 emitted_at: draft.emitted_at,
291 signature: String::new(),
292 signer_pubkey_hex: key
293 .map(|k| hex::encode(k.verifying_key().to_bytes()))
294 .unwrap_or_default(),
295 };
296 rc.id = rc.derive_id()?;
297 if let Some(k) = key {
298 use ed25519_dalek::Signer;
299 rc.signature = hex::encode(k.sign(&rc.signing_bytes()?).to_bytes());
300 }
301 Ok(rc)
302 }
303
304 pub fn signing_bytes(&self) -> Result<Vec<u8>, String> {
307 let mut c = self.clone();
308 c.signature = String::new();
309 let body = crate::canonical::to_canonical_bytes(&c)?;
310 Ok(crate::signing_input::signing_input(
311 crate::signing_input::SigVersion::V0,
312 crate::signing_input::payload_type::ACTIVITY_RECORD,
313 &body,
314 ))
315 }
316
317 pub fn derive_id(&self) -> Result<String, String> {
318 let mut c = self.clone();
319 c.id = String::new();
320 c.signature = String::new();
321 let bytes = crate::canonical::to_canonical_bytes(&c)?;
322 Ok(format!("vrc_{}", &hex::encode(Sha256::digest(bytes))[..16]))
323 }
324
325 pub fn to_finding_draft(
329 &self,
330 staleness: &str,
331 signed: bool,
332 ) -> crate::state::FindingDraftOptions {
333 let conditions = format!(
334 "Record {} ({}; {}). Receipt: {}. Caveats: {}. Artifacts: {} hash-verified at propose.",
335 self.id,
336 if signed { "signed" } else { "unsigned" },
337 staleness,
338 if self.receipt_digest.is_empty() {
339 "legacy-unbound"
340 } else {
341 self.receipt_digest.as_str()
342 },
343 self.caveats.join(" | "),
344 self.artifacts.len(),
345 );
346 let source = self.source.as_ref();
347 let source_label = source
348 .and_then(|s| (!s.name.trim().is_empty()).then(|| s.name.clone()))
349 .unwrap_or_else(|| format!("record:{}", self.id));
350 let source_type = source
351 .and_then(|s| (!s.source_type.trim().is_empty()).then(|| s.source_type.clone()))
352 .unwrap_or_else(|| "model_output".to_string());
353 let url = source.and_then(|s| (!s.uri.trim().is_empty()).then(|| s.uri.clone()));
354 let source_authors = source
355 .map(|s| s.authors.clone())
356 .filter(|authors| !authors.is_empty())
357 .unwrap_or_else(|| vec![self.emitted_by.clone()]);
358 let mut source_refs = self.source_refs.clone();
359 source_refs.push(format!("record:{}", self.id));
360 if !self.receipt_digest.is_empty() {
361 source_refs.push(self.receipt_digest.clone());
362 }
363 if let Some(lineage) = &self.lineage {
364 source_refs.extend(
365 lineage
366 .parents
367 .iter()
368 .map(|parent| format!("parent:{parent}")),
369 );
370 source_refs.extend(lineage.source_refs.iter().cloned());
371 }
372 source_refs.sort();
373 source_refs.dedup();
374 let evidence_spans = self
381 .artifacts
382 .iter()
383 .enumerate()
384 .map(|(index, artifact)| {
385 let source = if !self.receipt_path.is_empty() {
386 self.receipt_path.as_str()
387 } else if !self.receipt_digest.is_empty() {
388 self.receipt_digest.as_str()
389 } else {
390 artifact.locator.as_str()
391 };
392 let mut span = serde_json::json!({
393 "source": source,
394 "section": format!("artifacts[{index}]"),
395 "text": self.assertion.as_str(),
396 "artifact_kind": artifact.kind.as_str(),
397 "artifact_locator": artifact.locator.as_str(),
398 });
399 if !artifact.sha256.is_empty() {
400 span["artifact_sha256"] = serde_json::json!(artifact.sha256.as_str());
401 }
402 span
403 })
404 .collect();
405 crate::state::FindingDraftOptions {
406 text: self.assertion.clone(),
407 assertion_type: self.assertion_type.clone(),
408 source: source_label,
409 source_type,
410 author: self.emitted_by.clone(),
411 confidence: 0.3,
412 evidence_type: self.assertion_type.clone(),
413 doi: None,
414 year: None,
415 url,
416 source_authors,
417 source_refs,
418 conditions_text: Some(conditions),
419 evidence_spans,
420 gap: false,
421 negative_space: false,
422 replication_attestation: None,
423 }
424 }
425
426 pub fn to_finding_proposal_at(
434 &self,
435 staleness: &str,
436 signed: bool,
437 at: &str,
438 ) -> Result<crate::proposals::StateProposal, String> {
439 let mut proposal = crate::state::build_add_finding_proposal_at(
440 self.to_finding_draft(staleness, signed),
441 at,
442 )?;
443 let payload = proposal
444 .payload
445 .as_object_mut()
446 .ok_or_else(|| "finding proposal payload must be an object".to_string())?;
447 payload.insert(
448 "vela_submission".to_string(),
449 serde_json::json!({
450 "schema": "vela.submission-links.internal.v1",
451 "receipt_root": self.receipt_digest,
452 "receipt_path": self.receipt_path,
453 "record_id": self.id,
454 "operation_id": self.operation_id,
455 }),
456 );
457 if !self.receipt_path.is_empty()
458 && !proposal
459 .source_refs
460 .iter()
461 .any(|item| item == &self.receipt_path)
462 {
463 proposal.source_refs.push(self.receipt_path.clone());
464 proposal.source_refs.sort();
465 proposal.source_refs.dedup();
466 }
467 proposal.id = crate::proposals::proposal_id(&proposal);
468 Ok(proposal)
469 }
470
471 pub fn verify(&self) -> Result<bool, String> {
475 if self.schema != ACTIVITY_RECORD_SCHEMA {
476 return Err(format!(
477 "record schema must be {ACTIVITY_RECORD_SCHEMA}, got {}",
478 self.schema
479 ));
480 }
481 let derived = self.derive_id()?;
482 if derived != self.id {
483 return Err(format!(
484 "record id does not re-derive: stored {}, derived {derived}",
485 self.id
486 ));
487 }
488 if self.signature.is_empty() {
489 return Ok(false);
490 }
491 use ed25519_dalek::Verifier;
492 let pk_bytes: [u8; 32] = hex::decode(&self.signer_pubkey_hex)
493 .map_err(|e| format!("pubkey hex: {e}"))?
494 .try_into()
495 .map_err(|_| "pubkey must be 32 bytes".to_string())?;
496 let vk = ed25519_dalek::VerifyingKey::from_bytes(&pk_bytes)
497 .map_err(|e| format!("pubkey: {e}"))?;
498 let sig_bytes: [u8; 64] = hex::decode(&self.signature)
499 .map_err(|e| format!("signature hex: {e}"))?
500 .try_into()
501 .map_err(|_| "signature must be 64 bytes".to_string())?;
502 let sig = ed25519_dalek::Signature::from_bytes(&sig_bytes);
503 vk.verify(&self.signing_bytes()?, &sig)
504 .map_err(|_| "record signature does not verify".to_string())?;
505 Ok(true)
506 }
507}
508
509#[cfg(test)]
510mod tests {
511 use super::*;
512
513 fn draft() -> ActivityRecordDraft {
514 ActivityRecordDraft {
515 frontier_id: "vfr_0123456789abcdef".into(),
516 against_head: "sha256:abc".into(),
517 assertion: "a(17) >= 292 for the Sidon frontier".into(),
518 assertion_type: "computational".into(),
519 artifacts: vec![RecordArtifact {
520 kind: "witness".into(),
521 locator: "witnesses/a17.json".into(),
522 sha256: "a".repeat(64),
523 size_bytes: None,
524 media_type: None,
525 disclosure: ArtifactDisclosure::Unknown,
526 locator_integrity: LocatorIntegrity::Unknown,
527 availability: ArtifactAvailability::Unknown,
528 note: String::new(),
529 }],
530 verifier_runs: vec![],
531 caveats: vec!["lower bound only; optimality not established".into()],
532 source: None,
533 source_refs: Vec::new(),
534 receipt_digest: String::new(),
535 receipt_path: String::new(),
536 operation_id: String::new(),
537 lineage: None,
538 emitted_by: "agent:claude".into(),
539 emitted_at: "2026-07-01T00:00:00Z".into(),
540 }
541 }
542
543 fn key() -> ed25519_dalek::SigningKey {
544 ed25519_dalek::SigningKey::from_bytes(&[7u8; 32])
545 }
546
547 #[test]
548 fn unsigned_record_builds_and_verifies_as_unsigned() {
549 let r = ActivityRecord::build(draft(), None).unwrap();
550 assert!(r.id.starts_with("vrc_"));
551 assert!(!r.verify().unwrap());
552 }
553
554 #[test]
555 fn receipt_pointer_and_operation_identity_are_bound_into_the_record() {
556 let mut input = draft();
557 input.receipt_digest = format!("sha256:{}", "b".repeat(64));
558 input.receipt_path = "records/receipts/sha256/b.json".to_string();
559 input.operation_id = format!("vop_{}", "c".repeat(64));
560 let record = ActivityRecord::build(input, None).unwrap();
561 assert_eq!(record.receipt_path, "records/receipts/sha256/b.json");
562 assert!(record.operation_id.starts_with("vop_"));
563
564 let mut tampered = record.clone();
565 tampered.operation_id = format!("vop_{}", "d".repeat(64));
566 assert!(tampered.verify().is_err());
567
568 let proposal = record
569 .to_finding_proposal_at("current head", false, "2026-07-13T00:00:00Z")
570 .unwrap();
571 let links = proposal.payload.get("vela_submission").unwrap();
572 assert_eq!(links["receipt_root"], record.receipt_digest);
573 assert_eq!(links["record_id"], record.id);
574 assert!(!proposal.payload.to_string().contains("verifier_runs"));
575 let span = &proposal.payload["finding"]["evidence"]["evidence_spans"][0];
576 assert_eq!(span["source"], record.receipt_path);
577 assert_eq!(span["section"], "artifacts[0]");
578 assert_eq!(span["artifact_kind"], "witness");
579 assert_eq!(span["artifact_locator"], "witnesses/a17.json");
580 assert_eq!(span["artifact_sha256"], "a".repeat(64));
581 }
582
583 #[test]
584 fn receipt_pointer_rejects_escape_and_untyped_operation_ids() {
585 let mut escaped = draft();
586 escaped.receipt_path = "../secret.json".to_string();
587 assert!(ActivityRecord::build(escaped, None).is_err());
588
589 let mut invalid_operation = draft();
590 invalid_operation.operation_id = "vop_request".to_string();
591 assert!(ActivityRecord::build(invalid_operation, None).is_err());
592 }
593
594 #[test]
595 fn signed_record_verifies_and_tamper_fails() {
596 let r = ActivityRecord::build(draft(), Some(&key())).unwrap();
597 assert!(r.verify().unwrap());
598 let mut bad = r.clone();
599 bad.assertion = "a(17) >= 300".into();
600 assert!(bad.verify().is_err()); }
602
603 #[test]
604 fn record_without_artifacts_or_caveats_refused() {
605 let mut d = draft();
606 d.artifacts.clear();
607 assert!(ActivityRecord::build(d, None).is_err());
608 let mut d = draft();
609 d.caveats = vec!["".into()];
610 assert!(ActivityRecord::build(d, None).is_err());
611 }
612
613 #[test]
614 fn receipt_binding_and_lineage_are_visible_to_review() {
615 let mut d = draft();
616 d.receipt_digest = format!("sha256:{}", "b".repeat(64));
617 d.lineage = Some(ReceiptLineage {
618 parents: vec!["vf_parent".into()],
619 source_refs: vec!["urn:sha256:source".into()],
620 ..ReceiptLineage::default()
621 });
622 let record = ActivityRecord::build(d, None).unwrap();
623 let finding = record.to_finding_draft("recorded against head", false);
624 assert!(finding.source_refs.contains(&record.receipt_digest));
625 assert!(
626 finding
627 .source_refs
628 .contains(&"parent:vf_parent".to_string())
629 );
630 assert!(
631 finding
632 .source_refs
633 .contains(&format!("record:{}", record.id))
634 );
635 }
636
637 #[test]
638 fn restricted_artifact_span_preserves_opaque_locator_without_equality_digest() {
639 let mut input = draft();
640 input.artifacts[0].locator = "custodian:restricted-evidence-01".to_string();
641 input.artifacts[0].sha256.clear();
642 input.artifacts[0].disclosure = ArtifactDisclosure::Restricted;
643 input.receipt_digest = format!("sha256:{}", "b".repeat(64));
644 input.receipt_path = "records/receipts/sha256/restricted.json".to_string();
645 let record = ActivityRecord::build(input, None).unwrap();
646
647 let finding = record.to_finding_draft("current head", false);
648 let span = &finding.evidence_spans[0];
649 assert_eq!(span["source"], record.receipt_path);
650 assert_eq!(span["artifact_locator"], "custodian:restricted-evidence-01");
651 assert!(span.get("artifact_sha256").is_none());
652 }
653}