1use std::collections::{BTreeMap, BTreeSet};
8
9use chrono::{DateTime, Utc};
10use serde::{Deserialize, Serialize};
11use serde_json::{Value, json};
12use sha2::{Digest, Sha256};
13
14use crate::bundle::FindingBundle;
15use crate::canonical;
16use crate::project::Project;
17
18pub const EVENT_SCHEMA: &str = "vela.event.v0.1";
19pub const NULL_HASH: &str = "sha256:null";
20
21pub const EVENT_KIND_KEY_REVOKE: &str = "key.revoke";
34
35pub const EVENT_KIND_ARTIFACT_ASSERTED: &str = "artifact.asserted";
39pub const EVENT_KIND_ARTIFACT_REVIEWED: &str = "artifact.reviewed";
40pub const EVENT_KIND_ARTIFACT_RETRACTED: &str = "artifact.retracted";
41
42pub const EVENT_KIND_VERIFIER_ATTACHMENT_ADDED: &str = "verifier_attachment.added";
46
47pub const EVENT_KIND_TIER_SET: &str = "tier.set";
53
54pub const EVENT_KIND_EVIDENCE_ATOM_LOCATOR_REPAIRED: &str = "evidence_atom.locator_repaired";
68
69pub const EVENT_KIND_FINDING_SPAN_REPAIRED: &str = "finding.span_repaired";
75
76pub const EVENT_KIND_ATTESTATION_RECORDED: &str = "attestation.recorded";
94
95pub const EVENT_KIND_FRONTIER_OBSERVATION_REVIEWED: &str = "frontier.observation_reviewed";
99
100pub const EVENT_KIND_CONTRADICTION_RESOLVED: &str = "contradiction.resolved";
109
110pub const EVENT_KIND_ATTEMPT_DEPOSITED: &str = "attempt.deposited";
114
115pub const EVENT_KIND_TRANSFER_DEPOSITED: &str = "transfer.deposited";
120
121pub const EVENT_KIND_ENDORSEMENT_DEPOSITED: &str = "endorsement.deposited";
126
127pub const EVENT_KIND_ATTEMPT_RESOLVED: &str = "attempt.resolved";
132
133pub const EVENT_KIND_STATEMENT_ATTESTED: &str = "statement.attested";
136
137pub const EVENT_KIND_ATTEMPT_CLAIMED: &str = "attempt.claimed";
143
144pub const EVENT_KIND_STATEMENT_REGISTERED: &str = "statement.registered";
149
150pub const EVENT_KIND_REVIEW_ACCEPTED: &str = "review.accepted";
164pub const EVENT_KIND_REVIEW_REJECTED: &str = "review.rejected";
165pub const EVENT_KIND_REVIEW_REVISION_REQUESTED: &str = "review.revision_requested";
166
167pub const EVENT_KIND_PROPOSAL_WITHDRAWN: &str = "proposal.withdrawn";
172pub const PROPOSAL_WITHDRAWAL_PAYLOAD_SCHEMA: &str = "vela.proposal-withdrawal.v1";
173
174pub const EVENT_KIND_ACTOR_REGISTRATION_ACTIVATED: &str = "actor.registration_activated";
178
179pub const EVENT_KIND_POLICY_AUTO_ADMITTED: &str = "policy.auto_admitted";
190
191pub const KNOWN_EVENT_KINDS: &[&str] = &[
198 "frontier.created",
199 "finding.asserted",
200 "finding.reviewed",
201 "finding.noted",
202 "finding.caveated",
203 "finding.confidence_revised",
204 "finding.rejected",
205 "finding.retracted",
206 "finding.contribution.recorded",
207 "finding.superseded",
208 "finding.dependency_invalidated",
209 "finding.span_repaired",
210 "assertion.reinterpreted_causal",
211 "source_text.reviewed",
212 "artifact.asserted",
213 "artifact.reviewed",
214 "artifact.retracted",
215 "verifier_attachment.added",
216 "tier.set",
217 "evidence_atom.locator_repaired",
218 "attestation.recorded",
219 "frontier.observation_reviewed",
220 "diff_pack.released",
221 "diff_pack.reviewed",
222 "verdict_conflict.resolved",
223 "contradiction.resolved",
224 "attempt.deposited",
225 "attempt.resolved",
226 "transfer.deposited",
227 "endorsement.deposited",
228 "statement.attested",
229 "attempt.claimed",
230 "statement.registered",
231 "anchor.attached",
232 "anchor.retracted",
233 "proposal.recommended",
234 "correction_return.review",
235 "research_trace.review",
236 "key.revoke",
237 "review.accepted",
238 "review.rejected",
239 "review.revision_requested",
240 "proposal.withdrawn",
241 "actor.registration_activated",
242 "policy.auto_admitted",
243];
244
245#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
246pub struct StateTarget {
247 pub r#type: String,
248 pub id: String,
249}
250
251#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
252pub struct StateActor {
253 pub id: String,
254 pub r#type: String,
255}
256
257pub fn actor_kind(id: &str) -> &'static str {
263 let id = id.trim();
264 let handle = id.split(':').next_back().unwrap_or(id);
265 if id.starts_with("agent:")
266 || id.starts_with("sim:")
267 || id.starts_with("ci:")
268 || id.starts_with("policy:")
269 || handle.ends_with("-bot")
270 || handle.ends_with("-sim")
271 {
272 "agent"
273 } else {
274 "human"
275 }
276}
277
278macro_rules! event_kinds {
290 ($($variant:ident => $wire:literal),+ $(,)?) => {
291 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
292 pub enum EventKind {
293 $($variant,)+
294 Other(String),
296 }
297
298 impl EventKind {
299 pub fn as_str(&self) -> &str {
301 match self {
302 $(EventKind::$variant => $wire,)+
303 EventKind::Other(s) => s.as_str(),
304 }
305 }
306 }
307
308 impl From<&str> for EventKind {
309 fn from(s: &str) -> Self {
310 match s {
311 $($wire => EventKind::$variant,)+
312 other => EventKind::Other(other.to_string()),
313 }
314 }
315 }
316 };
317}
318
319event_kinds! {
320 FrontierCreated => "frontier.created",
321 FindingAsserted => "finding.asserted",
322 FindingReviewed => "finding.reviewed",
323 FindingNoted => "finding.noted",
324 FindingCaveated => "finding.caveated",
325 SourceTextReviewed => "source_text.reviewed",
326 FindingConfidenceRevised => "finding.confidence_revised",
327 FindingRejected => "finding.rejected",
328 FindingRetracted => "finding.retracted",
329 FindingContributionRecorded => "finding.contribution.recorded",
330 FindingDependencyInvalidated => "finding.dependency_invalidated",
331 ArtifactAsserted => "artifact.asserted",
332 VerifierAttachmentAdded => "verifier_attachment.added",
333 ArtifactReviewed => "artifact.reviewed",
334 ArtifactRetracted => "artifact.retracted",
335 TierSet => "tier.set",
336 EvidenceAtomLocatorRepaired => "evidence_atom.locator_repaired",
337 FindingSpanRepaired => "finding.span_repaired",
338 AttestationRecorded => "attestation.recorded",
339 DiffPackReleased => "diff_pack.released",
340 DiffPackReviewed => "diff_pack.reviewed",
341 VerdictConflictResolved => "verdict_conflict.resolved",
342 ContradictionResolved => "contradiction.resolved",
343 AttemptDeposited => "attempt.deposited",
344 TransferDeposited => "transfer.deposited",
345 EndorsementDeposited => "endorsement.deposited",
346 AttemptResolved => "attempt.resolved",
347 StatementAttested => "statement.attested",
348 AnchorAttached => "anchor.attached",
349 AnchorRetracted => "anchor.retracted",
350 AttemptClaimed => "attempt.claimed",
351 StatementRegistered => "statement.registered",
352 FindingSuperseded => "finding.superseded",
353 AssertionReinterpretedCausal => "assertion.reinterpreted_causal",
354 ProposalRecommended => "proposal.recommended",
355 FrontierObservationReviewed => "frontier.observation_reviewed",
356 CorrectionReturnReview => "correction_return.review",
357 ResearchTraceReview => "research_trace.review",
358 KeyRevoke => "key.revoke",
359 ReviewAccepted => "review.accepted",
360 ReviewRejected => "review.rejected",
361 ReviewRevisionRequested => "review.revision_requested",
362 ProposalWithdrawn => "proposal.withdrawn",
363 ActorRegistrationActivated => "actor.registration_activated",
364 PolicyAutoAdmitted => "policy.auto_admitted",
365}
366
367impl From<String> for EventKind {
368 fn from(s: String) -> Self {
369 EventKind::from(s.as_str())
370 }
371}
372
373impl std::fmt::Display for EventKind {
374 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
375 f.write_str(self.as_str())
376 }
377}
378
379impl PartialEq<str> for EventKind {
382 fn eq(&self, other: &str) -> bool {
383 self.as_str() == other
384 }
385}
386impl PartialEq<&str> for EventKind {
387 fn eq(&self, other: &&str) -> bool {
388 self.as_str() == *other
389 }
390}
391
392impl Serialize for EventKind {
395 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
396 serializer.serialize_str(self.as_str())
397 }
398}
399impl<'de> Deserialize<'de> for EventKind {
400 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
401 let s = String::deserialize(deserializer)?;
402 Ok(EventKind::from(s.as_str()))
403 }
404}
405
406#[derive(Debug, Clone, Serialize, Deserialize)]
407pub struct StateEvent {
408 #[serde(default = "default_schema")]
409 pub schema: String,
410 pub id: String,
411 pub kind: EventKind,
412 pub target: StateTarget,
413 pub actor: StateActor,
414 pub timestamp: String,
415 pub reason: String,
416 pub before_hash: String,
417 pub after_hash: String,
418 #[serde(default)]
419 pub payload: Value,
420 #[serde(default)]
421 pub caveats: Vec<String>,
422 #[serde(default, skip_serializing_if = "Option::is_none")]
423 pub signature: Option<String>,
424}
425
426pub struct FindingEventInput<'a> {
427 pub kind: &'a str,
428 pub finding_id: &'a str,
429 pub actor_id: &'a str,
430 pub actor_type: &'a str,
431 pub reason: &'a str,
432 pub before_hash: &'a str,
433 pub after_hash: &'a str,
434 pub payload: Value,
435 pub caveats: Vec<String>,
436 pub timestamp: Option<&'a str>,
443}
444
445#[derive(Debug, Clone, Serialize, Deserialize)]
446pub struct EventLogSummary {
447 pub count: usize,
448 pub kinds: BTreeMap<String, usize>,
449 pub first_timestamp: Option<String>,
450 pub last_timestamp: Option<String>,
451 pub duplicate_ids: Vec<String>,
452 pub orphan_targets: Vec<String>,
453}
454
455#[derive(Debug, Clone, Serialize, Deserialize)]
456pub struct ReplayReport {
457 pub ok: bool,
458 pub status: String,
459 pub event_log: EventLogSummary,
460 pub source_hash: String,
461 pub event_log_hash: String,
462 pub replayed_hash: String,
463 pub current_hash: String,
464 pub conflicts: Vec<String>,
465}
466
467fn default_schema() -> String {
468 EVENT_SCHEMA.to_string()
469}
470
471pub fn new_finding_event(input: FindingEventInput<'_>) -> StateEvent {
472 let timestamp = input
473 .timestamp
474 .map(|t| t.to_string())
475 .unwrap_or_else(|| Utc::now().to_rfc3339());
476 let mut event = StateEvent {
477 schema: EVENT_SCHEMA.to_string(),
478 id: String::new(),
479 kind: input.kind.into(),
480 target: StateTarget {
481 r#type: "finding".to_string(),
482 id: input.finding_id.to_string(),
483 },
484 actor: StateActor {
485 id: input.actor_id.to_string(),
486 r#type: input.actor_type.to_string(),
487 },
488 timestamp,
489 reason: input.reason.to_string(),
490 before_hash: input.before_hash.to_string(),
491 after_hash: input.after_hash.to_string(),
492 payload: input.payload,
493 caveats: input.caveats,
494 signature: None,
495 };
496 event.id = event_id(&event);
497 event
498}
499
500#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
509pub struct RevocationPayload {
510 pub revoked_pubkey: String,
512 pub revoked_at: String,
516 #[serde(default, skip_serializing_if = "String::is_empty")]
520 pub replacement_pubkey: String,
521 #[serde(default, skip_serializing_if = "String::is_empty")]
525 pub reason: String,
526}
527
528pub fn new_revocation_event(
534 actor_id: &str,
535 actor_type: &str,
536 payload: RevocationPayload,
537 reason: &str,
538 before_hash: &str,
539 after_hash: &str,
540) -> StateEvent {
541 let timestamp = Utc::now().to_rfc3339();
542 let payload_value =
543 serde_json::to_value(&payload).expect("RevocationPayload serializes to a JSON object");
544 let mut event = StateEvent {
545 schema: EVENT_SCHEMA.to_string(),
546 id: String::new(),
547 kind: EVENT_KIND_KEY_REVOKE.into(),
548 target: StateTarget {
549 r#type: "actor".to_string(),
550 id: actor_id.to_string(),
551 },
552 actor: StateActor {
553 id: actor_id.to_string(),
554 r#type: actor_type.to_string(),
555 },
556 timestamp,
557 reason: reason.to_string(),
558 before_hash: before_hash.to_string(),
559 after_hash: after_hash.to_string(),
560 payload: payload_value,
561 caveats: Vec::new(),
562 signature: None,
563 };
564 event.id = event_id(&event);
565 event
566}
567
568#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
577pub struct ReviewDecisionPayload {
578 pub proposal_id: String,
580 pub proposal_kind: String,
583 pub verdict: String,
587 #[serde(default, skip_serializing_if = "Option::is_none")]
589 pub applied_event_id: Option<String>,
590}
591
592#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
594#[serde(deny_unknown_fields)]
595pub struct ProposalWithdrawalPayload {
596 pub schema: String,
597 pub proposal_id: String,
598 pub proposal_root: String,
599 pub receipt_root: String,
600 pub identity_binding_id: String,
601}
602
603pub fn new_proposal_withdrawal_event(
606 payload: ProposalWithdrawalPayload,
607 actor_id: &str,
608 reason: &str,
609 timestamp: Option<&str>,
610) -> Result<StateEvent, String> {
611 if payload.schema != PROPOSAL_WITHDRAWAL_PAYLOAD_SCHEMA {
612 return Err(format!(
613 "proposal withdrawal payload schema must be {PROPOSAL_WITHDRAWAL_PAYLOAD_SCHEMA}"
614 ));
615 }
616 if !payload.proposal_id.starts_with("vpr_") {
617 return Err("proposal withdrawal requires a vpr_ proposal id".to_string());
618 }
619 for (name, root) in [
620 ("proposal_root", payload.proposal_root.as_str()),
621 ("receipt_root", payload.receipt_root.as_str()),
622 ] {
623 if !root.strip_prefix("sha256:").is_some_and(|hex| {
624 hex.len() == 64
625 && hex
626 .bytes()
627 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
628 }) {
629 return Err(format!(
630 "proposal withdrawal {name} must be a full sha256 root"
631 ));
632 }
633 }
634 if !payload
635 .identity_binding_id
636 .strip_prefix("vib_")
637 .is_some_and(|hex| {
638 hex.len() == 16
639 && hex
640 .bytes()
641 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
642 })
643 {
644 return Err(
645 "proposal withdrawal identity_binding_id must be vib_<16 lowercase hex>".to_string(),
646 );
647 }
648 if actor_kind(actor_id) != "agent" {
649 return Err("only an agent or ci producer may withdraw its proposal".to_string());
650 }
651 if reason.trim().is_empty() {
652 return Err("proposal withdrawal reason must be non-empty".to_string());
653 }
654 let timestamp = timestamp
655 .map(str::to_string)
656 .unwrap_or_else(|| Utc::now().to_rfc3339());
657 let mut event = StateEvent {
658 schema: EVENT_SCHEMA.to_string(),
659 id: String::new(),
660 kind: EVENT_KIND_PROPOSAL_WITHDRAWN.into(),
661 target: StateTarget {
662 r#type: "proposal".to_string(),
663 id: payload.proposal_id.clone(),
664 },
665 actor: StateActor {
666 id: actor_id.to_string(),
667 r#type: "agent".to_string(),
668 },
669 timestamp,
670 reason: reason.to_string(),
671 before_hash: NULL_HASH.to_string(),
672 after_hash: NULL_HASH.to_string(),
673 payload: serde_json::to_value(payload)
674 .map_err(|error| format!("serialize proposal withdrawal payload: {error}"))?,
675 caveats: Vec::new(),
676 signature: None,
677 };
678 event.id = event_id(&event);
679 Ok(event)
680}
681
682pub fn new_review_decision_event(
690 proposal_id: &str,
691 proposal_kind: &str,
692 verdict: &str,
693 applied_event_id: Option<String>,
694 reviewer_id: &str,
695 reason: &str,
696 timestamp: Option<&str>,
697) -> Result<StateEvent, String> {
698 let kind = match verdict {
699 "accepted" => EVENT_KIND_REVIEW_ACCEPTED,
700 "rejected" => EVENT_KIND_REVIEW_REJECTED,
701 "revision_requested" => EVENT_KIND_REVIEW_REVISION_REQUESTED,
702 other => return Err(format!("unknown review verdict '{other}'")),
703 };
704 let payload = ReviewDecisionPayload {
705 proposal_id: proposal_id.to_string(),
706 proposal_kind: proposal_kind.to_string(),
707 verdict: verdict.to_string(),
708 applied_event_id,
709 };
710 let payload_value =
711 serde_json::to_value(&payload).expect("ReviewDecisionPayload serializes to a JSON object");
712 let timestamp = timestamp
713 .map(|t| t.to_string())
714 .unwrap_or_else(|| Utc::now().to_rfc3339());
715 let mut event = StateEvent {
716 schema: EVENT_SCHEMA.to_string(),
717 id: String::new(),
718 kind: kind.into(),
719 target: StateTarget {
720 r#type: "proposal".to_string(),
721 id: proposal_id.to_string(),
722 },
723 actor: StateActor {
724 id: reviewer_id.to_string(),
725 r#type: actor_kind(reviewer_id).to_string(),
726 },
727 timestamp,
728 reason: reason.to_string(),
729 before_hash: NULL_HASH.to_string(),
730 after_hash: NULL_HASH.to_string(),
731 payload: payload_value,
732 caveats: Vec::new(),
733 signature: None,
734 };
735 event.id = event_id(&event);
736 Ok(event)
737}
738
739pub fn new_evidence_atom_locator_repair_event(
745 atom_id: &str,
746 actor_id: &str,
747 actor_type: &str,
748 reason: &str,
749 before_hash: &str,
750 after_hash: &str,
751 payload: Value,
752 caveats: Vec<String>,
753) -> StateEvent {
754 let timestamp = Utc::now().to_rfc3339();
755 let mut event = StateEvent {
756 schema: EVENT_SCHEMA.to_string(),
757 id: String::new(),
758 kind: EVENT_KIND_EVIDENCE_ATOM_LOCATOR_REPAIRED.into(),
759 target: StateTarget {
760 r#type: "evidence_atom".to_string(),
761 id: atom_id.to_string(),
762 },
763 actor: StateActor {
764 id: actor_id.to_string(),
765 r#type: actor_type.to_string(),
766 },
767 timestamp,
768 reason: reason.to_string(),
769 before_hash: before_hash.to_string(),
770 after_hash: after_hash.to_string(),
771 payload,
772 caveats,
773 signature: None,
774 };
775 event.id = event_id(&event);
776 event
777}
778
779pub fn new_contradiction_resolved_event(
784 contradiction_id: &str,
785 actor_id: &str,
786 actor_type: &str,
787 reason: &str,
788 payload: Value,
789 caveats: Vec<String>,
790) -> StateEvent {
791 let timestamp = Utc::now().to_rfc3339();
792 let mut event = StateEvent {
793 schema: EVENT_SCHEMA.to_string(),
794 id: String::new(),
795 kind: EVENT_KIND_CONTRADICTION_RESOLVED.into(),
796 target: StateTarget {
797 r#type: "contradiction".to_string(),
798 id: contradiction_id.to_string(),
799 },
800 actor: StateActor {
801 id: actor_id.to_string(),
802 r#type: actor_type.to_string(),
803 },
804 timestamp,
805 reason: reason.to_string(),
806 before_hash: NULL_HASH.to_string(),
807 after_hash: NULL_HASH.to_string(),
808 payload,
809 caveats,
810 signature: None,
811 };
812 event.id = event_id(&event);
813 event
814}
815
816fn new_attempt_event(
820 kind: &str,
821 attempt_id: &str,
822 actor_id: &str,
823 actor_type: &str,
824 reason: &str,
825 payload: Value,
826 caveats: Vec<String>,
827) -> StateEvent {
828 let mut event = StateEvent {
829 schema: EVENT_SCHEMA.to_string(),
830 id: String::new(),
831 kind: kind.into(),
832 target: StateTarget {
833 r#type: "attempt".to_string(),
834 id: attempt_id.to_string(),
835 },
836 actor: StateActor {
837 id: actor_id.to_string(),
838 r#type: actor_type.to_string(),
839 },
840 timestamp: Utc::now().to_rfc3339(),
841 reason: reason.to_string(),
842 before_hash: NULL_HASH.to_string(),
843 after_hash: NULL_HASH.to_string(),
844 payload,
845 caveats,
846 signature: None,
847 };
848 event.id = event_id(&event);
849 event
850}
851
852pub fn new_attempt_deposited_event(
856 attempt_id: &str,
857 actor_id: &str,
858 actor_type: &str,
859 reason: &str,
860 payload: Value,
861 caveats: Vec<String>,
862) -> StateEvent {
863 new_attempt_event(
864 EVENT_KIND_ATTEMPT_DEPOSITED,
865 attempt_id,
866 actor_id,
867 actor_type,
868 reason,
869 payload,
870 caveats,
871 )
872}
873
874pub fn new_transfer_deposited_event(
878 transfer_id: &str,
879 actor_id: &str,
880 actor_type: &str,
881 reason: &str,
882 payload: Value,
883 caveats: Vec<String>,
884) -> StateEvent {
885 let mut event = StateEvent {
886 schema: EVENT_SCHEMA.to_string(),
887 id: String::new(),
888 kind: EVENT_KIND_TRANSFER_DEPOSITED.into(),
889 target: StateTarget {
890 r#type: "transfer".to_string(),
891 id: transfer_id.to_string(),
892 },
893 actor: StateActor {
894 id: actor_id.to_string(),
895 r#type: actor_type.to_string(),
896 },
897 timestamp: Utc::now().to_rfc3339(),
898 reason: reason.to_string(),
899 before_hash: NULL_HASH.to_string(),
900 after_hash: NULL_HASH.to_string(),
901 payload,
902 caveats,
903 signature: None,
904 };
905 event.id = event_id(&event);
906 event
907}
908
909pub fn new_endorsement_deposited_event(
913 endorsement_id: &str,
914 actor_id: &str,
915 actor_type: &str,
916 reason: &str,
917 payload: Value,
918 caveats: Vec<String>,
919) -> StateEvent {
920 let mut event = StateEvent {
921 schema: EVENT_SCHEMA.to_string(),
922 id: String::new(),
923 kind: EVENT_KIND_ENDORSEMENT_DEPOSITED.into(),
924 target: StateTarget {
925 r#type: "endorsement".to_string(),
926 id: endorsement_id.to_string(),
927 },
928 actor: StateActor {
929 id: actor_id.to_string(),
930 r#type: actor_type.to_string(),
931 },
932 timestamp: Utc::now().to_rfc3339(),
933 reason: reason.to_string(),
934 before_hash: NULL_HASH.to_string(),
935 after_hash: NULL_HASH.to_string(),
936 payload,
937 caveats,
938 signature: None,
939 };
940 event.id = event_id(&event);
941 event
942}
943
944pub fn new_attempt_resolved_event(
948 attempt_id: &str,
949 actor_id: &str,
950 actor_type: &str,
951 reason: &str,
952 payload: Value,
953 caveats: Vec<String>,
954) -> StateEvent {
955 new_attempt_event(
956 EVENT_KIND_ATTEMPT_RESOLVED,
957 attempt_id,
958 actor_id,
959 actor_type,
960 reason,
961 payload,
962 caveats,
963 )
964}
965
966pub fn evidence_atom_hash(atom: &crate::sources::EvidenceAtom) -> String {
971 let bytes = canonical::to_canonical_bytes(atom).unwrap_or_default();
972 format!("sha256:{}", hex::encode(Sha256::digest(bytes)))
973}
974pub fn finding_hash(finding: &FindingBundle) -> String {
975 let mut hashable = finding.clone();
986 hashable.links.clear();
987 let bytes = canonical::to_canonical_bytes(&hashable).unwrap_or_default();
988 format!("sha256:{}", hex::encode(Sha256::digest(bytes)))
989}
990
991pub fn finding_hash_by_id(frontier: &Project, finding_id: &str) -> String {
992 frontier
993 .findings
994 .iter()
995 .find(|finding| finding.id == finding_id)
996 .map(finding_hash)
997 .unwrap_or_else(|| NULL_HASH.to_string())
998}
999
1000pub fn event_log_hash(events: &[StateEvent]) -> String {
1014 let mut sorted: Vec<&StateEvent> = events.iter().collect();
1015 sorted.sort_by(|a, b| a.id.cmp(&b.id));
1016 let stripped: Vec<serde_json::Value> = sorted
1023 .iter()
1024 .map(|event| {
1025 let mut value = serde_json::to_value(event).unwrap_or(serde_json::Value::Null);
1026 if let serde_json::Value::Object(map) = &mut value {
1027 map.remove("signature");
1028 }
1029 value
1030 })
1031 .collect();
1032 let bytes = canonical::to_canonical_bytes(&stripped).unwrap_or_default();
1033 hex::encode(Sha256::digest(bytes))
1034}
1035
1036pub fn nonlease_event_log_hash(events: &[StateEvent]) -> String {
1045 let nonlease = events
1046 .iter()
1047 .filter(|event| event.kind != EVENT_KIND_ATTEMPT_CLAIMED)
1048 .cloned()
1049 .collect::<Vec<_>>();
1050 event_log_hash(&nonlease)
1051}
1052
1053pub fn snapshot_hash(frontier: &Project) -> String {
1054 let value = serde_json::to_value(frontier).unwrap_or(Value::Null);
1055 let mut value = value;
1056 if let Value::Object(map) = &mut value {
1057 map.remove("events");
1058 map.remove("signatures");
1059 map.remove("proof_state");
1060 }
1061 let bytes = canonical::to_canonical_bytes(&value).unwrap_or_default();
1062 hex::encode(Sha256::digest(bytes))
1063}
1064
1065pub fn events_for_finding<'a>(frontier: &'a Project, finding_id: &str) -> Vec<&'a StateEvent> {
1066 frontier
1067 .events
1068 .iter()
1069 .filter(|event| event.target.r#type == "finding" && event.target.id == finding_id)
1070 .collect()
1071}
1072
1073pub fn replay_report(frontier: &Project) -> ReplayReport {
1074 let event_log = summarize(frontier);
1075 let mut conflicts = Vec::new();
1076
1077 if frontier.events.is_empty() {
1078 let current_hash = snapshot_hash(frontier);
1079 return ReplayReport {
1080 ok: true,
1081 status: "no_events".to_string(),
1082 event_log,
1083 source_hash: current_hash.clone(),
1084 event_log_hash: event_log_hash(&frontier.events),
1085 replayed_hash: current_hash.clone(),
1086 current_hash,
1087 conflicts,
1088 };
1089 }
1090
1091 for duplicate in &event_log.duplicate_ids {
1092 conflicts.push(format!("duplicate event id: {duplicate}"));
1093 }
1094 for orphan in &event_log.orphan_targets {
1095 conflicts.push(format!("orphan event target: {orphan}"));
1096 }
1097
1098 let mut chains = BTreeMap::<String, Vec<&StateEvent>>::new();
1099 for event in &frontier.events {
1100 if event.schema != EVENT_SCHEMA {
1101 conflicts.push(format!(
1102 "unsupported event schema for {}: {}",
1103 event.id, event.schema
1104 ));
1105 }
1106 if event.reason.trim().is_empty() {
1107 conflicts.push(format!("event {} has empty reason", event.id));
1108 }
1109 if event.before_hash.trim().is_empty() || event.after_hash.trim().is_empty() {
1110 conflicts.push(format!("event {} has empty hash boundary", event.id));
1111 }
1112 if let Err(err) = validate_event_payload(event.kind.as_str(), &event.payload) {
1117 conflicts.push(format!("event {} payload invalid: {err}", event.id));
1118 }
1119 if event.before_hash == NULL_HASH && event.after_hash == NULL_HASH {
1126 continue;
1127 }
1128 chains
1129 .entry(format!("{}:{}", event.target.r#type, event.target.id))
1130 .or_default()
1131 .push(event);
1132 }
1133
1134 for (target, events) in chains {
1135 let mut sorted = events;
1136 sorted.sort_by(|a, b| a.timestamp.cmp(&b.timestamp).then(a.id.cmp(&b.id)));
1137 for pair in sorted.windows(2) {
1138 let previous = pair[0];
1139 let next = pair[1];
1140 if previous.after_hash != next.before_hash {
1141 conflicts.push(format!(
1142 "event chain break for {target}: {} after_hash does not match {} before_hash",
1143 previous.id, next.id
1144 ));
1145 }
1146 }
1147 if let Some(last) = sorted.last()
1148 && last.target.r#type == "finding"
1149 {
1150 let current = finding_hash_by_id(frontier, &last.target.id);
1151 if current != last.after_hash {
1152 conflicts.push(format!(
1153 "materialized finding {} hash does not match last event {}",
1154 last.target.id, last.id
1155 ));
1156 }
1157 }
1158 }
1159
1160 let current_hash = snapshot_hash(frontier);
1161 let ok = conflicts.is_empty();
1162 ReplayReport {
1163 ok,
1164 status: if ok { "ok" } else { "conflict" }.to_string(),
1165 event_log,
1166 source_hash: current_hash.clone(),
1167 event_log_hash: event_log_hash(&frontier.events),
1168 replayed_hash: if ok {
1169 current_hash.clone()
1170 } else {
1171 "unavailable".to_string()
1172 },
1173 current_hash,
1174 conflicts,
1175 }
1176}
1177pub fn summarize(frontier: &Project) -> EventLogSummary {
1178 let mut kinds = BTreeMap::<String, usize>::new();
1179 let mut seen = BTreeSet::<String>::new();
1180 let mut duplicate_ids = BTreeSet::<String>::new();
1181 let finding_ids = frontier
1182 .findings
1183 .iter()
1184 .map(|finding| finding.id.as_str())
1185 .collect::<BTreeSet<_>>();
1186 let mut orphan_targets = BTreeSet::<String>::new();
1187 let mut timestamps = Vec::<String>::new();
1188
1189 for event in &frontier.events {
1190 *kinds.entry(event.kind.to_string()).or_default() += 1;
1191 if !seen.insert(event.id.clone()) {
1192 duplicate_ids.insert(event.id.clone());
1193 }
1194 let external_obligation = event.kind == "attempt.claimed"
1198 && event.target.id.contains(':')
1199 && !event.target.id.starts_with("vf_");
1200 if event.target.r#type == "finding"
1201 && !finding_ids.contains(event.target.id.as_str())
1202 && event.kind != "finding.retracted"
1203 && !external_obligation
1204 {
1205 orphan_targets.insert(event.target.id.clone());
1206 }
1207 timestamps.push(event.timestamp.clone());
1208 }
1209 timestamps.sort();
1210
1211 EventLogSummary {
1212 count: frontier.events.len(),
1213 kinds,
1214 first_timestamp: timestamps.first().cloned(),
1215 last_timestamp: timestamps.last().cloned(),
1216 duplicate_ids: duplicate_ids.into_iter().collect(),
1217 orphan_targets: orphan_targets.into_iter().collect(),
1218 }
1219}
1220
1221fn validate_sha256_commitment(field: &str, value: &str) -> Result<(), String> {
1232 let hex = value.strip_prefix("sha256:").unwrap_or(value);
1233 if hex.len() != 64 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
1234 return Err(format!("{field} must be sha256:<64hex>"));
1235 }
1236 Ok(())
1237}
1238
1239pub fn validate_event_payload(kind: &str, payload: &Value) -> Result<(), String> {
1240 let object = payload.as_object().ok_or_else(|| {
1241 if matches!(payload, Value::Null) {
1242 "payload must be a JSON object (got null)".to_string()
1243 } else {
1244 "payload must be a JSON object".to_string()
1245 }
1246 })?;
1247 let require_str = |key: &str| -> Result<&str, String> {
1248 object
1249 .get(key)
1250 .and_then(Value::as_str)
1251 .ok_or_else(|| format!("missing required string field '{key}'"))
1252 };
1253 let require_f64 = |key: &str| -> Result<f64, String> {
1254 object
1255 .get(key)
1256 .and_then(Value::as_f64)
1257 .ok_or_else(|| format!("missing required number field '{key}'"))
1258 };
1259 match kind {
1260 "finding.asserted" => {
1261 require_str("proposal_id")?;
1264 }
1265 "finding.reviewed" => {
1266 require_str("proposal_id")?;
1267 let status = require_str("status")?;
1268 if !matches!(
1269 status,
1270 "accepted" | "approved" | "contested" | "needs_revision" | "rejected"
1271 ) {
1272 return Err(format!("invalid review status '{status}'"));
1273 }
1274 }
1275 "diff_pack.released" => {
1276 let pack_id = require_str("pack_id")?;
1277 if !pack_id.starts_with("vsd_") {
1278 return Err(format!(
1279 "payload.pack_id must start with 'vsd_', got '{pack_id}'"
1280 ));
1281 }
1282 let frontier_id = require_str("frontier_id")?;
1283 if !frontier_id.starts_with("vfr_") {
1284 return Err(format!(
1285 "payload.frontier_id must start with 'vfr_', got '{frontier_id}'"
1286 ));
1287 }
1288 let summary = require_str("summary")?;
1289 if summary.trim().is_empty() {
1290 return Err("payload.summary must be non-empty".to_string());
1291 }
1292 let aggregate_kind = require_str("aggregate_kind")?;
1293 if aggregate_kind.trim().is_empty() {
1294 return Err("payload.aggregate_kind must be non-empty".to_string());
1295 }
1296 }
1297 "diff_pack.reviewed" => {
1298 let pack_id = require_str("pack_id")?;
1299 if !pack_id.starts_with("vsd_") {
1300 return Err(format!(
1301 "payload.pack_id must start with 'vsd_', got '{pack_id}'"
1302 ));
1303 }
1304 let verdict = require_str("verdict")?;
1305 if !matches!(verdict, "accept" | "reject" | "revise") {
1306 return Err(format!(
1307 "payload.verdict must be accept|reject|revise, got '{verdict}'"
1308 ));
1309 }
1310 let reviewer = require_str("reviewer_actor")?;
1311 if reviewer.trim().is_empty() {
1312 return Err("payload.reviewer_actor must be non-empty".to_string());
1313 }
1314 let reason = require_str("reason")?;
1315 if reason.trim().is_empty() {
1316 return Err("payload.reason must be non-empty".to_string());
1317 }
1318 if let Some(applied) = object.get("applied_members") {
1319 applied
1320 .as_array()
1321 .ok_or("payload.applied_members must be an array when present")?;
1322 }
1323 if let Some(sdk_only) = object.get("sdk_only_members") {
1324 sdk_only
1325 .as_array()
1326 .ok_or("payload.sdk_only_members must be an array when present")?;
1327 }
1328 }
1329 "finding.contribution.recorded" => {
1330 let contribution = object
1331 .get("contribution")
1332 .and_then(Value::as_object)
1333 .ok_or("payload.contribution must be a JSON object")?;
1334 for field in ["unit", "unit_type", "agent_kind", "agent_id", "role"] {
1335 let v = contribution
1336 .get(field)
1337 .and_then(Value::as_str)
1338 .ok_or_else(|| format!("payload.contribution.{field} must be a string"))?;
1339 if v.trim().is_empty() {
1340 return Err(format!("payload.contribution.{field} must be non-empty"));
1341 }
1342 }
1343 if contribution.get("role").and_then(Value::as_str) == Some("vouched")
1346 && contribution.get("agent_kind").and_then(Value::as_str) != Some("human")
1347 {
1348 return Err(
1349 "payload.contribution: role `vouched` requires agent_kind `human`".to_string(),
1350 );
1351 }
1352 }
1353 "finding.noted" | "finding.caveated" => {
1354 require_str("proposal_id")?;
1355 require_str("annotation_id")?;
1356 let text = require_str("text")?;
1357 if text.trim().is_empty() {
1358 return Err("payload.text must be non-empty".to_string());
1359 }
1360 if let Some(prov) = object.get("provenance") {
1366 let prov_obj = prov
1367 .as_object()
1368 .ok_or("payload.provenance must be a JSON object when present")?;
1369 let has_id = prov_obj
1370 .get("doi")
1371 .and_then(Value::as_str)
1372 .is_some_and(|s| !s.trim().is_empty())
1373 || prov_obj
1374 .get("pmid")
1375 .and_then(Value::as_str)
1376 .is_some_and(|s| !s.trim().is_empty())
1377 || prov_obj
1378 .get("title")
1379 .and_then(Value::as_str)
1380 .is_some_and(|s| !s.trim().is_empty());
1381 if !has_id {
1382 return Err(
1383 "payload.provenance must include at least one of doi/pmid/title"
1384 .to_string(),
1385 );
1386 }
1387 }
1388 }
1389 "source_text.reviewed" => {
1390 require_str("proposal_id")?;
1391 let status = require_str("status")?;
1392 if !matches!(status, "accepted" | "approved") {
1393 return Err(format!("invalid source text review status '{status}'"));
1394 }
1395 let promotion_id = require_str("source_text_promotion_id")?;
1396 if !promotion_id.starts_with("vslaketxtprom_") {
1397 return Err(format!(
1398 "payload.source_text_promotion_id must start with 'vslaketxtprom_', got '{promotion_id}'"
1399 ));
1400 }
1401 let source_lake_record_id = require_str("source_lake_record_id")?;
1402 if !source_lake_record_id.starts_with("vslake_") {
1403 return Err(format!(
1404 "payload.source_lake_record_id must start with 'vslake_', got '{source_lake_record_id}'"
1405 ));
1406 }
1407 require_str("lane_id")?;
1408 require_str("locator")?;
1409 require_str("materialized_from")?;
1410 }
1411 "finding.confidence_revised" => {
1412 require_str("proposal_id")?;
1413 let new_score = require_f64("new_score")?;
1414 if !(0.0..=1.0).contains(&new_score) {
1415 return Err(format!("new_score {new_score} out of [0.0, 1.0]"));
1416 }
1417 let _ = require_f64("previous_score")?;
1418 }
1419 "finding.rejected" => {
1420 require_str("proposal_id")?;
1421 }
1422 "finding.superseded" => {
1423 require_str("proposal_id")?;
1424 require_str("new_finding_id")?;
1425 }
1426 "finding.retracted" => {
1427 require_str("proposal_id")?;
1428 if let Some(affected) = object.get("affected") {
1431 let _ = affected
1432 .as_u64()
1433 .ok_or("affected must be a non-negative integer")?;
1434 }
1435 }
1436 "finding.dependency_invalidated" => {
1441 require_str("upstream_finding_id")?;
1442 require_str("upstream_event_id")?;
1443 let depth = object
1444 .get("depth")
1445 .and_then(Value::as_u64)
1446 .ok_or("missing required positive integer 'depth'")?;
1447 if depth == 0 {
1448 return Err("depth must be >= 1 (genesis is the source retraction)".to_string());
1449 }
1450 require_str("proposal_id")?;
1452 }
1453 "frontier.created" => {
1456 require_str("name")?;
1457 require_str("creator")?;
1458 }
1459 "frontier.observation_reviewed" => {
1460 require_str("proposal_id")?;
1461 let proposal_kind = require_str("proposal_kind")?;
1462 if !matches!(
1463 proposal_kind,
1464 "research_trace.review" | "correction_return.review"
1465 ) {
1466 return Err(format!(
1467 "payload.proposal_kind must be research_trace.review or correction_return.review, got '{proposal_kind}'"
1468 ));
1469 }
1470 let status = require_str("status")?;
1471 if status != "accepted" {
1472 return Err(format!("payload.status must be 'accepted', got '{status}'"));
1473 }
1474 if let Some(value) = object.get("decision_reason")
1475 && value.as_str().is_none_or(|reason| reason.trim().is_empty())
1476 {
1477 return Err(
1478 "payload.decision_reason must be a non-empty string when present".to_string(),
1479 );
1480 }
1481 }
1482 "assertion.reinterpreted_causal" => {
1491 require_str("proposal_id")?;
1492 let check_block = |block_name: &str| -> Result<(), String> {
1493 let block = object
1494 .get(block_name)
1495 .and_then(Value::as_object)
1496 .ok_or_else(|| format!("payload.{block_name} must be an object"))?;
1497 if let Some(claim) = block.get("claim").and_then(Value::as_str)
1498 && !crate::bundle::VALID_CAUSAL_CLAIMS.contains(&claim)
1499 {
1500 return Err(format!(
1501 "{block_name}.claim '{claim}' not in {:?}",
1502 crate::bundle::VALID_CAUSAL_CLAIMS
1503 ));
1504 }
1505 if let Some(grade) = block.get("grade").and_then(Value::as_str)
1506 && !crate::bundle::VALID_CAUSAL_EVIDENCE_GRADES.contains(&grade)
1507 {
1508 return Err(format!(
1509 "{block_name}.grade '{grade}' not in {:?}",
1510 crate::bundle::VALID_CAUSAL_EVIDENCE_GRADES
1511 ));
1512 }
1513 Ok(())
1514 };
1515 check_block("before")?;
1516 check_block("after")?;
1517 }
1518 EVENT_KIND_KEY_REVOKE => {
1526 let revoked = require_str("revoked_pubkey")?;
1527 if revoked.len() != 64 || !revoked.chars().all(|c| c.is_ascii_hexdigit()) {
1528 return Err(format!(
1529 "revoked_pubkey must be 64 hex chars (Ed25519 pubkey), got {} chars",
1530 revoked.len()
1531 ));
1532 }
1533 let revoked_at = require_str("revoked_at")?;
1534 if revoked_at.trim().is_empty() {
1535 return Err("revoked_at must be a non-empty ISO-8601 timestamp".to_string());
1536 }
1537 if DateTime::parse_from_rfc3339(revoked_at).is_err() {
1542 return Err(format!(
1543 "revoked_at must parse as RFC-3339/ISO-8601, got {revoked_at:?}"
1544 ));
1545 }
1546 if let Some(replacement) = object.get("replacement_pubkey")
1550 && let Some(rep_str) = replacement.as_str()
1551 && !rep_str.is_empty()
1552 && (rep_str.len() != 64 || !rep_str.chars().all(|c| c.is_ascii_hexdigit()))
1553 {
1554 return Err(format!(
1555 "replacement_pubkey must be 64 hex chars when present, got {} chars",
1556 rep_str.len()
1557 ));
1558 }
1559 if let Some(replacement) = object.get("replacement_pubkey").and_then(Value::as_str)
1562 && !replacement.is_empty()
1563 && replacement.eq_ignore_ascii_case(revoked)
1564 {
1565 return Err("replacement_pubkey must differ from revoked_pubkey".to_string());
1566 }
1567 }
1568 EVENT_KIND_REVIEW_ACCEPTED
1572 | EVENT_KIND_REVIEW_REJECTED
1573 | EVENT_KIND_REVIEW_REVISION_REQUESTED => {
1574 let proposal_id = require_str("proposal_id")?;
1575 if !proposal_id.starts_with("vpr_") {
1576 return Err(format!(
1577 "payload.proposal_id must start with 'vpr_', got '{proposal_id}'"
1578 ));
1579 }
1580 require_str("proposal_kind")?;
1581 let verdict = require_str("verdict")?;
1582 let expected = match kind {
1583 EVENT_KIND_REVIEW_ACCEPTED => "accepted",
1584 EVENT_KIND_REVIEW_REJECTED => "rejected",
1585 _ => "revision_requested",
1586 };
1587 if verdict != expected {
1588 return Err(format!(
1589 "review event kind '{kind}' requires verdict '{expected}', got '{verdict}'"
1590 ));
1591 }
1592 if let Some(ev) = object.get("applied_event_id").and_then(Value::as_str) {
1595 if kind != EVENT_KIND_REVIEW_ACCEPTED {
1596 return Err(format!(
1597 "applied_event_id is only valid on '{EVENT_KIND_REVIEW_ACCEPTED}'"
1598 ));
1599 }
1600 if !ev.starts_with("vev_") {
1601 return Err(format!(
1602 "payload.applied_event_id must start with 'vev_', got '{ev}'"
1603 ));
1604 }
1605 }
1606 }
1607 EVENT_KIND_PROPOSAL_WITHDRAWN => {
1608 let parsed: ProposalWithdrawalPayload = serde_json::from_value(payload.clone())
1609 .map_err(|error| format!("invalid proposal-withdrawal payload: {error}"))?;
1610 new_proposal_withdrawal_event(
1613 parsed,
1614 "agent:payload-validator",
1615 "validate proposal withdrawal payload",
1616 Some("1970-01-01T00:00:00Z"),
1617 )?;
1618 }
1619 EVENT_KIND_ACTOR_REGISTRATION_ACTIVATED => {
1620 let parsed: crate::actor_registration::ActorRegistrationBoundaryPayload =
1621 serde_json::from_value(payload.clone())
1622 .map_err(|error| format!("invalid actor-registration payload: {error}"))?;
1623 parsed.validate()?;
1624 }
1625 EVENT_KIND_ARTIFACT_ASSERTED => {
1626 require_str("proposal_id")?;
1627 let artifact = object
1628 .get("artifact")
1629 .and_then(Value::as_object)
1630 .ok_or("payload.artifact must be a JSON object")?;
1631 let id = artifact
1632 .get("id")
1633 .and_then(Value::as_str)
1634 .ok_or("payload.artifact.id must be a va_<hex>")?;
1635 if !id.starts_with("va_") {
1636 return Err(format!(
1637 "payload.artifact.id must start with 'va_', got '{id}'"
1638 ));
1639 }
1640 let id_hex = id.trim_start_matches("va_");
1641 if id_hex.len() != 16 || !id_hex.chars().all(|c| c.is_ascii_hexdigit()) {
1642 return Err("payload.artifact.id must be va_<16hex>".to_string());
1643 }
1644 let kind = artifact
1645 .get("kind")
1646 .and_then(Value::as_str)
1647 .ok_or("payload.artifact.kind must be a string")?;
1648 if !crate::bundle::valid_artifact_kind(kind) {
1649 return Err(format!("payload.artifact.kind '{kind}' is not supported"));
1650 }
1651 for key in ["name", "content_hash", "storage_mode"] {
1652 let value = artifact
1653 .get(key)
1654 .and_then(Value::as_str)
1655 .ok_or_else(|| format!("payload.artifact.{key} must be a string"))?;
1656 if value.trim().is_empty() {
1657 return Err(format!("payload.artifact.{key} must be non-empty"));
1658 }
1659 }
1660 let content_hash = artifact
1661 .get("content_hash")
1662 .and_then(Value::as_str)
1663 .expect("content_hash checked above");
1664 validate_sha256_commitment("payload.artifact.content_hash", content_hash)?;
1665 }
1666 EVENT_KIND_ARTIFACT_REVIEWED => {
1667 require_str("proposal_id")?;
1668 let status = require_str("status")?;
1669 if !matches!(
1670 status,
1671 "accepted" | "approved" | "contested" | "needs_revision" | "rejected"
1672 ) {
1673 return Err(format!("invalid review status '{status}'"));
1674 }
1675 }
1676 EVENT_KIND_ARTIFACT_RETRACTED => {
1677 require_str("proposal_id")?;
1678 }
1679 EVENT_KIND_TIER_SET => {
1685 require_str("proposal_id")?;
1686 let object_type = require_str("object_type")?;
1687 if !matches!(object_type, "finding" | "artifact") {
1688 return Err(format!(
1689 "tier.set object_type '{object_type}' must be one of finding, artifact"
1690 ));
1691 }
1692 require_str("object_id")?;
1693 let new_tier = require_str("new_tier")?;
1694 crate::access_tier::AccessTier::parse(new_tier)?;
1695 if let Some(prev) = object.get("previous_tier").and_then(Value::as_str) {
1700 crate::access_tier::AccessTier::parse(prev)?;
1701 }
1702 }
1703 EVENT_KIND_EVIDENCE_ATOM_LOCATOR_REPAIRED => {
1709 require_str("proposal_id")?;
1710 let source_id = require_str("source_id")?;
1711 if source_id.trim().is_empty() {
1712 return Err("payload.source_id must be non-empty".to_string());
1713 }
1714 let locator = require_str("locator")?;
1715 if locator.trim().is_empty() {
1716 return Err("payload.locator must be non-empty".to_string());
1717 }
1718 }
1719 EVENT_KIND_FINDING_SPAN_REPAIRED => {
1722 require_str("proposal_id")?;
1723 let section = require_str("section")?;
1724 if section.trim().is_empty() {
1725 return Err("payload.section must be non-empty".to_string());
1726 }
1727 let text = require_str("text")?;
1728 if text.trim().is_empty() {
1729 return Err("payload.text must be non-empty".to_string());
1730 }
1731 }
1732 EVENT_KIND_ATTESTATION_RECORDED => {
1738 let target_id = require_str("target_event_id")?;
1739 if !target_id.starts_with("vev_") {
1740 return Err(format!(
1741 "payload.target_event_id must start with 'vev_', got '{target_id}'"
1742 ));
1743 }
1744 let attester = require_str("attester_id")?;
1745 if attester.trim().is_empty() {
1746 return Err("payload.attester_id must be non-empty".to_string());
1747 }
1748 let scope = require_str("scope_note")?;
1749 if scope.trim().is_empty() {
1750 return Err("payload.scope_note must be non-empty".to_string());
1751 }
1752 if let Some(sig) = object.get("signature")
1754 && !sig.is_null()
1755 && !sig.is_string()
1756 {
1757 return Err("payload.signature must be a string when present".to_string());
1758 }
1759 if let Some(scopes) = object.get("scopes") {
1760 let Some(items) = scopes.as_array() else {
1761 return Err("payload.scopes must be an array when present".to_string());
1762 };
1763 for scope in items {
1764 let Some(scope) = scope.as_str() else {
1765 return Err("payload.scopes entries must be strings".to_string());
1766 };
1767 match scope {
1768 "source_extraction"
1769 | "method_review"
1770 | "statistical_review"
1771 | "domain_relevance"
1772 | "translation_clarity"
1773 | "policy_approval" => {}
1774 other => {
1775 return Err(format!("payload.scopes contains unknown scope `{other}`"));
1776 }
1777 }
1778 }
1779 }
1780 for field in [
1781 "reviewer_role",
1782 "orcid",
1783 "ror",
1784 "attestation_id",
1785 "signed_at",
1786 ] {
1787 if let Some(value) = object.get(field)
1788 && !value.is_null()
1789 && !value.is_string()
1790 {
1791 return Err(format!("payload.{field} must be a string when present"));
1792 }
1793 }
1794 if let Some(proof) = object.get("proof_id")
1795 && !proof.is_null()
1796 && let Some(s) = proof.as_str()
1797 && !s.starts_with("vpf_")
1798 {
1799 return Err(format!(
1800 "payload.proof_id must start with 'vpf_' when present, got '{s}'"
1801 ));
1802 }
1803 }
1804 "verifier_attachment.added" => {
1805 if let Some(v) = object.get("proposal_id")
1812 && !v.is_string()
1813 {
1814 return Err(
1815 "verifier_attachment.added payload.proposal_id must be a string when present"
1816 .to_string(),
1817 );
1818 }
1819 if !object.get("attachment").is_some_and(|v| v.is_object()) {
1820 return Err(
1821 "verifier_attachment.added payload.attachment must be an object".to_string(),
1822 );
1823 }
1824 }
1825 "verdict_conflict.resolved" => {
1831 if !object.get("conflict").is_some_and(|v| v.is_object()) {
1832 return Err(
1833 "verdict_conflict.resolved payload.conflict must be an object".to_string(),
1834 );
1835 }
1836 }
1837 "contradiction.resolved" => {
1838 if !object.get("contradiction").is_some_and(|v| v.is_object()) {
1839 return Err(
1840 "contradiction.resolved payload.contradiction must be an object".to_string(),
1841 );
1842 }
1843 }
1844 EVENT_KIND_ATTEMPT_DEPOSITED => {
1845 if !object.get("attempt").is_some_and(|v| v.is_object()) {
1846 return Err("attempt.deposited payload.attempt must be an object".to_string());
1847 }
1848 }
1849 EVENT_KIND_TRANSFER_DEPOSITED => {
1850 if !object.get("transfer").is_some_and(|v| v.is_object()) {
1851 return Err("transfer.deposited payload.transfer must be an object".to_string());
1852 }
1853 }
1854 EVENT_KIND_ENDORSEMENT_DEPOSITED => {
1855 if !object.get("endorsement").is_some_and(|v| v.is_object()) {
1856 return Err(
1857 "endorsement.deposited payload.endorsement must be an object".to_string(),
1858 );
1859 }
1860 }
1861 EVENT_KIND_ATTEMPT_RESOLVED => {
1862 if !object.get("resolution").is_some_and(|v| v.is_object()) {
1863 return Err("attempt.resolved payload.resolution must be an object".to_string());
1864 }
1865 }
1866 EVENT_KIND_STATEMENT_ATTESTED => {
1867 if !object.get("attestation").is_some_and(|v| v.is_object()) {
1868 return Err("statement.attested payload.attestation must be an object".to_string());
1869 }
1870 }
1871 EVENT_KIND_ATTEMPT_CLAIMED => {
1872 let obligation_id = require_str("obligation_id")?;
1873 if obligation_id.trim().is_empty() {
1874 return Err("payload.obligation_id must be non-empty".to_string());
1875 }
1876 let ttl = object
1877 .get("lease_ttl_seconds")
1878 .and_then(Value::as_u64)
1879 .ok_or_else(|| {
1880 "attempt.claimed payload.lease_ttl_seconds must be a non-negative integer"
1881 .to_string()
1882 })?;
1883 for field in ["claimant_actor", "claimant_pubkey", "prior_claim_event_id"] {
1884 if let Some(value) = object.get(field)
1885 && !value.is_string()
1886 {
1887 return Err(format!(
1888 "attempt.claimed payload.{field} must be a string when present"
1889 ));
1890 }
1891 }
1892 if let Some(value) = object.get("release_reason")
1893 && !value.is_string()
1894 {
1895 return Err(
1896 "attempt.claimed payload.release_reason must be a string when present"
1897 .to_string(),
1898 );
1899 }
1900 if ttl == 0 {
1901 let prior = require_str("prior_claim_event_id")?;
1902 if !prior.strip_prefix("vev_").is_some_and(|hex| {
1903 hex.len() == 16
1904 && hex
1905 .bytes()
1906 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1907 }) {
1908 return Err(
1909 "zero-TTL attempt.claimed payload.prior_claim_event_id must be a vev_ event id"
1910 .to_string(),
1911 );
1912 }
1913 if require_str("release_reason")?.trim().is_empty() {
1914 return Err(
1915 "zero-TTL attempt.claimed payload.release_reason must be non-empty"
1916 .to_string(),
1917 );
1918 }
1919 }
1920 }
1921 EVENT_KIND_STATEMENT_REGISTERED => {
1922 let hash = require_str("statement_hash")?;
1923 if hash.len() != 64 || hex::decode(hash).is_err() {
1924 return Err(
1925 "payload.statement_hash must be 32 bytes of hex (64 hex chars)".to_string(),
1926 );
1927 }
1928 if let Some(finding) = object.get("finding_id")
1929 && !finding.is_null()
1930 && !finding.is_string()
1931 {
1932 return Err("payload.finding_id must be a string when present".to_string());
1933 }
1934 }
1935 "proposal.recommended" => {
1936 require_str("proposal_id")?;
1937 }
1938 "anchor.attached" => {
1939 if !payload.get("anchor_link").is_some_and(Value::is_object) {
1940 return Err("anchor.attached payload.anchor_link must be an object".to_string());
1941 }
1942 }
1943 "anchor.retracted" => {
1944 if !payload
1945 .get("anchor_link_id")
1946 .and_then(Value::as_str)
1947 .is_some_and(|s| !s.trim().is_empty())
1948 {
1949 return Err("anchor.retracted payload.anchor_link_id must be non-empty".to_string());
1950 }
1951 }
1952 "correction_return.review" | "research_trace.review" => {}
1956
1957 "policy.auto_admitted" => {
1968 require_str("proposal_id")?;
1969 require_str("claim_digest")?;
1970 require_str("policy_version")?;
1971 require_str("verifier_env_hash")?;
1972 match payload.get("attachment_ids") {
1973 Some(serde_json::Value::Array(ids)) => {
1974 if !ids.iter().all(|v| v.is_string()) {
1975 return Err(
1976 "policy.auto_admitted: attachment_ids must be strings".to_string()
1977 );
1978 }
1979 }
1980 _ => {
1981 return Err("policy.auto_admitted: attachment_ids must be an array".to_string());
1982 }
1983 }
1984 }
1985
1986 other => return Err(format!("unknown event kind '{other}'")),
1987 }
1988 Ok(())
1989}
1990
1991pub fn compute_event_id(event: &StateEvent) -> String {
1996 event_id(event)
1997}
1998
1999pub fn event_content_preimage_bytes(event: &StateEvent) -> Vec<u8> {
2007 let content = json!({
2008 "schema": event.schema,
2009 "kind": event.kind,
2010 "target": event.target,
2011 "actor": event.actor,
2012 "timestamp": event.timestamp,
2013 "reason": event.reason,
2014 "before_hash": event.before_hash,
2015 "after_hash": event.after_hash,
2016 "payload": event.payload,
2017 "caveats": event.caveats,
2018 });
2019 canonical::to_canonical_bytes(&content).unwrap_or_default()
2020}
2021
2022pub fn event_id(event: &StateEvent) -> String {
2023 format!(
2024 "vev_{}",
2025 &hex::encode(Sha256::digest(event_content_preimage_bytes(event)))[..16]
2026 )
2027}
2028
2029#[cfg(test)]
2030mod tests {
2031 use super::*;
2032 use crate::bundle::{
2033 Assertion, Conditions, Confidence, Evidence, Extraction, FindingBundle, Flags, Provenance,
2034 };
2035 use crate::project;
2036
2037 #[test]
2038 fn snapshot_hash_exclusion_keys_exist_on_project() {
2039 let project = project::assemble("guard", vec![finding()], 0, 0, "guard");
2046 let value = serde_json::to_value(&project).expect("serialize Project");
2047 let map = value.as_object().expect("Project serializes as an object");
2048 for key in ["events", "signatures", "proof_state"] {
2049 assert!(
2050 map.contains_key(key),
2051 "snapshot_hash excludes `{key}` by string key, but it is absent from \
2052 serde_json::to_value(Project) — the exclusion would silently no-op"
2053 );
2054 }
2055 }
2056
2057 fn finding() -> FindingBundle {
2058 FindingBundle::new(
2059 Assertion {
2060 text: "LRP1 clears amyloid beta at the BBB".to_string(),
2061 assertion_type: "mechanism".to_string(),
2062 entities: Vec::new(),
2063 relation: None,
2064 direction: None,
2065 causal_claim: None,
2066 causal_evidence_grade: None,
2067 },
2068 Evidence {
2069 evidence_type: "experimental".to_string(),
2070 model_system: "mouse".to_string(),
2071 method: "assay".to_string(),
2072 replicated: false,
2073 replication_count: None,
2074 evidence_spans: Vec::new(),
2075 },
2076 Conditions {
2077 text: "mouse model".to_string(),
2078 duration: None,
2079 },
2080 Confidence::raw(0.6, "test", 0.8),
2081 Provenance {
2082 source_type: "published_paper".to_string(),
2083 doi: None,
2084 url: None,
2085 title: "Test source".to_string(),
2086 authors: Vec::new(),
2087 year: Some(2026),
2088 license: None,
2089 publisher: None,
2090 funders: Vec::new(),
2091 extraction: Extraction::default(),
2092 review: None,
2093 contributions: Vec::new(),
2094 },
2095 Flags {
2096 gap: false,
2097 negative_space: false,
2098 contested: false,
2099 retracted: false,
2100 declining: false,
2101 gravity_well: false,
2102 review_state: None,
2103 superseded: false,
2104 signature_threshold: None,
2105 jointly_accepted: false,
2106 },
2107 )
2108 }
2109
2110 #[test]
2111 fn event_id_is_deterministic_for_content() {
2112 let event = new_finding_event(FindingEventInput {
2113 kind: "finding.reviewed",
2114 finding_id: "vf_test",
2115 actor_id: "reviewer",
2116 actor_type: "human",
2117 reason: "checked",
2118 before_hash: NULL_HASH,
2119 after_hash: "sha256:abc",
2120 payload: json!({"status": "accepted", "proposal_id": "vpr_test"}),
2121 caveats: vec![],
2122 timestamp: None,
2123 });
2124 let mut same = event.clone();
2125 same.id = String::new();
2126 same.id = super::event_id(&same);
2127 assert_eq!(event.id, same.id);
2128 }
2129
2130 #[test]
2131 fn genesis_only_event_log_replays_ok() {
2132 let frontier = project::assemble("test", Vec::new(), 0, 0, "test");
2137 let report = replay_report(&frontier);
2138 assert!(report.ok, "{:?}", report.conflicts);
2139 assert_eq!(report.event_log.count, 1);
2140 assert_eq!(report.event_log.kinds.get("frontier.created"), Some(&1));
2141 }
2142
2143 #[test]
2144 fn replay_detects_duplicate_event_ids() {
2145 let finding = finding();
2146 let after_hash = finding_hash(&finding);
2147 let event = new_finding_event(FindingEventInput {
2148 kind: "finding.reviewed",
2149 finding_id: &finding.id,
2150 actor_id: "reviewer",
2151 actor_type: "human",
2152 reason: "checked",
2153 before_hash: &after_hash,
2154 after_hash: &after_hash,
2155 payload: json!({"status": "accepted", "proposal_id": "vpr_test"}),
2156 caveats: vec![],
2157 timestamp: None,
2158 });
2159 let mut frontier = project::assemble("test", vec![finding], 0, 0, "test");
2160 frontier.events = vec![event.clone(), event];
2161
2162 let report = replay_report(&frontier);
2163 assert!(!report.ok);
2164 assert_eq!(report.status, "conflict");
2165 assert!(!report.event_log.duplicate_ids.is_empty());
2166 }
2167
2168 #[test]
2169 fn replay_detects_orphan_targets() {
2170 let mut frontier = project::assemble("test", Vec::new(), 0, 0, "test");
2171 frontier.events.push(new_finding_event(FindingEventInput {
2172 kind: "finding.reviewed",
2173 finding_id: "vf_missing",
2174 actor_id: "reviewer",
2175 actor_type: "human",
2176 reason: "checked",
2177 before_hash: NULL_HASH,
2178 after_hash: "sha256:abc",
2179 payload: json!({"status": "accepted", "proposal_id": "vpr_test"}),
2180 caveats: vec![],
2181 timestamp: None,
2182 }));
2183
2184 let report = replay_report(&frontier);
2185 assert!(!report.ok);
2186 assert_eq!(report.event_log.orphan_targets, vec!["vf_missing"]);
2187 }
2188
2189 #[test]
2190 fn external_obligation_lease_is_not_an_orphan() {
2191 let mut frontier = project::assemble("test", Vec::new(), 0, 0, "test");
2196 let mut event = new_finding_event(FindingEventInput {
2197 kind: "attempt.claimed",
2198 finding_id: "erdos:443",
2199 actor_id: "agent:swarm-443",
2200 actor_type: "agent",
2201 reason: "obligation lease",
2202 before_hash: "sha256:null",
2203 after_hash: "sha256:null",
2204 payload: serde_json::json!({
2205 "obligation_id": "erdos:443",
2206 "lease_ttl_seconds": 3600,
2207 "claimant_actor": "agent:swarm-443",
2208 "claimant_pubkey": "00",
2209 }),
2210 caveats: Vec::new(),
2211 timestamp: None,
2212 });
2213 event.id = compute_event_id(&event);
2214 frontier.events.push(event);
2215 let report = replay_report(&frontier);
2216 assert!(
2217 report.event_log.orphan_targets.is_empty(),
2218 "external obligation lease misread as orphan: {:?}",
2219 report.event_log.orphan_targets
2220 );
2221 }
2222
2223 #[test]
2224 fn replay_accepts_current_hash_boundary() {
2225 let finding = finding();
2226 let hash = finding_hash(&finding);
2227 let event = new_finding_event(FindingEventInput {
2228 kind: "finding.reviewed",
2229 finding_id: &finding.id,
2230 actor_id: "reviewer",
2231 actor_type: "human",
2232 reason: "checked",
2233 before_hash: &hash,
2234 after_hash: &hash,
2235 payload: json!({"status": "accepted", "proposal_id": "vpr_test"}),
2236 caveats: vec![],
2237 timestamp: None,
2238 });
2239 let mut frontier = project::assemble("test", vec![finding], 0, 0, "test");
2240 frontier.events.push(event);
2241
2242 let report = replay_report(&frontier);
2243 assert!(report.ok, "{:?}", report.conflicts);
2244 assert_eq!(report.status, "ok");
2245 }
2246
2247 #[test]
2248 fn validates_diff_pack_lifecycle_payloads() {
2249 assert!(
2250 validate_event_payload(
2251 "diff_pack.released",
2252 &json!({
2253 "pack_id": "vsd_1234567890abcdef",
2254 "frontier_id": "vfr_1234567890abcdef",
2255 "summary": "Review bounded proposed changes.",
2256 "aggregate_kind": "clinical_translation.review_set",
2257 }),
2258 )
2259 .is_ok()
2260 );
2261 assert!(
2262 validate_event_payload(
2263 "diff_pack.reviewed",
2264 &json!({
2265 "pack_id": "vsd_1234567890abcdef",
2266 "verdict": "revise",
2267 "reviewer_actor": "reviewer:test",
2268 "reason": "Needs source locator repair before acceptance.",
2269 "applied_members": [],
2270 "sdk_only_members": ["vpr_sdk_only"],
2271 }),
2272 )
2273 .is_ok()
2274 );
2275 assert!(
2276 validate_event_payload(
2277 "diff_pack.released",
2278 &json!({
2279 "pack_id": "bad",
2280 "frontier_id": "vfr_1234567890abcdef",
2281 "summary": "Review bounded proposed changes.",
2282 "aggregate_kind": "clinical_translation.review_set",
2283 }),
2284 )
2285 .is_err()
2286 );
2287 assert!(
2288 validate_event_payload(
2289 "diff_pack.reviewed",
2290 &json!({
2291 "pack_id": "vsd_1234567890abcdef",
2292 "verdict": "maybe",
2293 "reviewer_actor": "reviewer:test",
2294 "reason": "Needs source locator repair before acceptance.",
2295 }),
2296 )
2297 .is_err()
2298 );
2299 }
2300
2301 #[test]
2302 fn validates_artifact_asserted_payload() {
2303 let good_hash = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
2304 assert!(
2305 validate_event_payload(
2306 EVENT_KIND_ARTIFACT_ASSERTED,
2307 &json!({
2308 "proposal_id": "vpr_test",
2309 "artifact": {
2310 "id": "va_1234567890abcdef",
2311 "kind": "clinical_trial_record",
2312 "name": "NCT test record",
2313 "content_hash": good_hash,
2314 "storage_mode": "embedded",
2315 },
2316 }),
2317 )
2318 .is_ok()
2319 );
2320 assert!(
2321 validate_event_payload(
2322 EVENT_KIND_ARTIFACT_ASSERTED,
2323 &json!({
2324 "proposal_id": "vpr_test",
2325 "artifact": {
2326 "id": "va_123",
2327 "kind": "clinical_trial_record",
2328 "name": "NCT test record",
2329 "content_hash": good_hash,
2330 "storage_mode": "embedded",
2331 },
2332 }),
2333 )
2334 .is_err()
2335 );
2336 assert!(
2337 validate_event_payload(
2338 EVENT_KIND_ARTIFACT_ASSERTED,
2339 &json!({
2340 "proposal_id": "vpr_test",
2341 "artifact": {
2342 "id": "va_1234567890abcdef",
2343 "kind": "clinical_trial_record",
2344 "name": "NCT test record",
2345 "content_hash": "sha256:not-a-real-hash",
2346 "storage_mode": "embedded",
2347 },
2348 }),
2349 )
2350 .is_err()
2351 );
2352 }
2353
2354 #[test]
2356 fn validates_reinterpreted_causal_payload() {
2357 assert!(
2359 validate_event_payload(
2360 "assertion.reinterpreted_causal",
2361 &json!({
2362 "proposal_id": "vpr_test",
2363 "before": {},
2364 "after": { "claim": "intervention", "grade": "rct" },
2365 }),
2366 )
2367 .is_ok()
2368 );
2369 assert!(
2371 validate_event_payload(
2372 "assertion.reinterpreted_causal",
2373 &json!({
2374 "proposal_id": "vpr_test",
2375 "before": { "claim": "correlation" },
2376 "after": { "claim": "mediation" },
2377 }),
2378 )
2379 .is_ok()
2380 );
2381 assert!(
2383 validate_event_payload(
2384 "assertion.reinterpreted_causal",
2385 &json!({
2386 "proposal_id": "vpr_test",
2387 "before": {},
2388 "after": { "claim": "magic" },
2389 }),
2390 )
2391 .is_err()
2392 );
2393 assert!(
2395 validate_event_payload(
2396 "assertion.reinterpreted_causal",
2397 &json!({
2398 "proposal_id": "vpr_test",
2399 "before": {},
2400 "after": { "claim": "intervention", "grade": "vibes" },
2401 }),
2402 )
2403 .is_err()
2404 );
2405 assert!(
2407 validate_event_payload(
2408 "assertion.reinterpreted_causal",
2409 &json!({
2410 "before": {},
2411 "after": { "claim": "intervention" },
2412 }),
2413 )
2414 .is_err()
2415 );
2416 }
2417
2418 #[test]
2423 fn revocation_event_canonical_shape() {
2424 use crate::canonical;
2425 let payload = RevocationPayload {
2426 revoked_pubkey: "4892f93877e637b5f59af31d9ec6704814842fb278cacb0eb94704baef99455e"
2427 .to_string(),
2428 revoked_at: "2026-05-01T17:00:00Z".to_string(),
2429 replacement_pubkey: "8891a2ab35ca2ed2182ed4e46b6567ce8dacc9985eb496d895578201272a1cd9"
2430 .to_string(),
2431 reason: "key file leaked from CI cache".to_string(),
2432 };
2433 let event = new_revocation_event(
2434 "reviewer:will-blair",
2435 "human",
2436 payload,
2437 "rotating compromised key",
2438 NULL_HASH,
2439 NULL_HASH,
2440 );
2441 assert_eq!(event.kind, EVENT_KIND_KEY_REVOKE);
2442 assert_eq!(event.target.r#type, "actor");
2443 assert!(event.id.starts_with("vev_"));
2444 let bytes = canonical::to_canonical_bytes(&event).unwrap();
2445 let s = std::str::from_utf8(&bytes).unwrap();
2446 assert!(
2447 s.contains("\"revoked_pubkey\""),
2448 "canonical bytes missing revoked_pubkey: {s}"
2449 );
2450 assert!(
2451 s.contains("\"revoked_at\""),
2452 "canonical bytes missing revoked_at: {s}"
2453 );
2454 assert!(
2455 s.contains("\"replacement_pubkey\""),
2456 "canonical bytes missing replacement_pubkey: {s}"
2457 );
2458
2459 let payload_minimal = RevocationPayload {
2461 revoked_pubkey: "a".repeat(64),
2462 revoked_at: "2026-05-01T17:00:00Z".to_string(),
2463 replacement_pubkey: String::new(),
2464 reason: String::new(),
2465 };
2466 let minimal_event = new_revocation_event(
2467 "reviewer:will-blair",
2468 "human",
2469 payload_minimal,
2470 "scheduled rotation",
2471 NULL_HASH,
2472 NULL_HASH,
2473 );
2474 let minimal_bytes = canonical::to_canonical_bytes(&minimal_event).unwrap();
2475 let minimal_s = std::str::from_utf8(&minimal_bytes).unwrap();
2476 assert!(
2477 !minimal_s.contains("\"replacement_pubkey\""),
2478 "empty replacement_pubkey leaked into canonical JSON: {minimal_s}"
2479 );
2480 assert!(
2481 !minimal_s.contains("\"reason\":\"\""),
2482 "empty payload reason leaked into canonical JSON: {minimal_s}"
2483 );
2484 }
2485
2486 #[test]
2489 fn revocation_payload_validation() {
2490 let good_pubkey = "4892f93877e637b5f59af31d9ec6704814842fb278cacb0eb94704baef99455e";
2491 let other_pubkey = "8891a2ab35ca2ed2182ed4e46b6567ce8dacc9985eb496d895578201272a1cd9";
2492
2493 assert!(
2495 validate_event_payload(
2496 EVENT_KIND_KEY_REVOKE,
2497 &json!({
2498 "revoked_pubkey": good_pubkey,
2499 "revoked_at": "2026-05-01T17:00:00Z",
2500 }),
2501 )
2502 .is_ok()
2503 );
2504
2505 assert!(
2507 validate_event_payload(
2508 EVENT_KIND_KEY_REVOKE,
2509 &json!({
2510 "revoked_pubkey": good_pubkey,
2511 "revoked_at": "2026-05-01T17:00:00Z",
2512 "replacement_pubkey": other_pubkey,
2513 "reason": "key file leaked",
2514 }),
2515 )
2516 .is_ok()
2517 );
2518
2519 assert!(
2521 validate_event_payload(
2522 EVENT_KIND_KEY_REVOKE,
2523 &json!({
2524 "revoked_pubkey": "abc123",
2525 "revoked_at": "2026-05-01T17:00:00Z",
2526 }),
2527 )
2528 .is_err()
2529 );
2530
2531 assert!(
2533 validate_event_payload(
2534 EVENT_KIND_KEY_REVOKE,
2535 &json!({
2536 "revoked_pubkey": "ZZ".repeat(32),
2537 "revoked_at": "2026-05-01T17:00:00Z",
2538 }),
2539 )
2540 .is_err()
2541 );
2542
2543 assert!(
2545 validate_event_payload(
2546 EVENT_KIND_KEY_REVOKE,
2547 &json!({
2548 "revoked_pubkey": good_pubkey,
2549 }),
2550 )
2551 .is_err()
2552 );
2553
2554 assert!(
2556 validate_event_payload(
2557 EVENT_KIND_KEY_REVOKE,
2558 &json!({
2559 "revoked_pubkey": good_pubkey,
2560 "revoked_at": "2026-05-01T17:00:00Z",
2561 "replacement_pubkey": "deadbeef",
2562 }),
2563 )
2564 .is_err()
2565 );
2566
2567 assert!(
2569 validate_event_payload(
2570 EVENT_KIND_KEY_REVOKE,
2571 &json!({
2572 "revoked_pubkey": good_pubkey,
2573 "revoked_at": "2026-05-01T17:00:00Z",
2574 "replacement_pubkey": good_pubkey,
2575 }),
2576 )
2577 .is_err()
2578 );
2579
2580 for bad in [
2588 "yesterday",
2589 "2026-13-01T00:00:00Z", "2026-05-01", "x",
2592 ] {
2593 assert!(
2594 validate_event_payload(
2595 EVENT_KIND_KEY_REVOKE,
2596 &json!({
2597 "revoked_pubkey": good_pubkey,
2598 "revoked_at": bad,
2599 }),
2600 )
2601 .is_err(),
2602 "expected revoked_at {bad:?} to fail validation"
2603 );
2604 }
2605 }
2606
2607 #[test]
2612 fn attestation_recorded_validator() {
2613 let good = json!({
2615 "target_event_id": "vev_abc",
2616 "attester_id": "reviewer:will-blair",
2617 "scope_note": "Independent re-verification of the Stupp protocol finding."
2618 });
2619 assert!(validate_event_payload(EVENT_KIND_ATTESTATION_RECORDED, &good).is_ok());
2620 }
2621
2622 #[test]
2623 fn validates_policy_auto_admitted_payload() {
2624 let good = json!({
2626 "proposal_id": "vpr_abc",
2627 "claim_digest": "deadbeefdeadbeef",
2628 "attachment_ids": ["vva_a", "vva_b"],
2629 "policy_version": "exact-lane.v1",
2630 "verifier_env_hash": "sha256:cafe"
2631 });
2632 assert!(validate_event_payload(EVENT_KIND_POLICY_AUTO_ADMITTED, &good).is_ok());
2633
2634 let minimal = json!({ "proposal_id": "vpr_abc" });
2636 assert!(validate_event_payload(EVENT_KIND_POLICY_AUTO_ADMITTED, &minimal).is_err());
2637
2638 let floor_admit = json!({
2642 "proposal_id": "vpr_abc",
2643 "claim_digest": "deadbeef",
2644 "attachment_ids": [],
2645 "policy_version": "exact-lane.v1",
2646 "verifier_env_hash": "sha256:cafe"
2647 });
2648 assert!(validate_event_payload(EVENT_KIND_POLICY_AUTO_ADMITTED, &floor_admit).is_ok());
2649
2650 let no_digest = json!({
2652 "proposal_id": "vpr_abc",
2653 "attachment_ids": [],
2654 "policy_version": "exact-lane.v1",
2655 "verifier_env_hash": "sha256:cafe"
2656 });
2657 assert!(validate_event_payload(EVENT_KIND_POLICY_AUTO_ADMITTED, &no_digest).is_err());
2658
2659 let with_proof = json!({
2661 "target_event_id": "vev_abc",
2662 "attester_id": "reviewer:will-blair",
2663 "scope_note": "Lean-formalized.",
2664 "scopes": ["domain_relevance", "method_review"],
2665 "reviewer_role": "domain_reviewer",
2666 "orcid": "https://orcid.org/0000-0000-0000-000X",
2667 "ror": "https://ror.org/03yrm5c26",
2668 "attestation_id": "vatt_demo",
2669 "signature": "ed25519:cafebabe",
2670 "proof_id": "vpf_demo"
2671 });
2672 assert!(validate_event_payload(EVENT_KIND_ATTESTATION_RECORDED, &with_proof).is_ok());
2673
2674 let bad_target = json!({
2676 "target_event_id": "something_else",
2677 "attester_id": "reviewer:x",
2678 "scope_note": "x"
2679 });
2680 assert!(validate_event_payload(EVENT_KIND_ATTESTATION_RECORDED, &bad_target).is_err());
2681
2682 let no_attester = json!({
2684 "target_event_id": "vev_abc",
2685 "attester_id": "",
2686 "scope_note": "x"
2687 });
2688 assert!(validate_event_payload(EVENT_KIND_ATTESTATION_RECORDED, &no_attester).is_err());
2689
2690 let bad_proof = json!({
2692 "target_event_id": "vev_abc",
2693 "attester_id": "reviewer:x",
2694 "scope_note": "x",
2695 "proof_id": "not_a_vpf"
2696 });
2697 assert!(validate_event_payload(EVENT_KIND_ATTESTATION_RECORDED, &bad_proof).is_err());
2698 }
2699
2700 #[test]
2701 fn event_log_hash_is_independent_of_input_order() {
2702 let mk = |id: &str, ts: &str| StateEvent {
2708 schema: EVENT_SCHEMA.to_string(),
2709 id: id.to_string(),
2710 kind: "note.added".into(),
2711 target: StateTarget {
2712 r#type: "finding".to_string(),
2713 id: "vf_x".to_string(),
2714 },
2715 actor: StateActor {
2716 id: "reviewer:t".to_string(),
2717 r#type: "human".to_string(),
2718 },
2719 timestamp: ts.to_string(),
2720 reason: "t".to_string(),
2721 before_hash: String::new(),
2722 after_hash: String::new(),
2723 payload: Value::Null,
2724 caveats: vec![],
2725 signature: None,
2726 };
2727 let a = mk("vev_c", "2026-01-01T00:00:03Z");
2730 let b = mk("vev_a", "2026-01-01T00:00:01Z");
2731 let c = mk("vev_b", "2026-01-01T00:00:02Z");
2732 let forward = vec![a.clone(), b.clone(), c.clone()];
2733 let shuffled = vec![c, a.clone(), b];
2734 assert_eq!(
2735 event_log_hash(&forward),
2736 event_log_hash(&shuffled),
2737 "event_log_hash must be independent of input order"
2738 );
2739 let mut reversed = forward.clone();
2740 reversed.reverse();
2741 assert_eq!(event_log_hash(&forward), event_log_hash(&reversed));
2742 assert_ne!(event_log_hash(&forward), event_log_hash(&[]));
2744 }
2745}