1use serde::{Deserialize, Serialize};
9use serde_json::{Value, json};
10use sha2::{Digest, Sha256};
11
12use crate::canonical;
13
14pub const EVENT_SCHEMA: &str = "vela.event.v0.1";
15pub const NULL_HASH: &str = "sha256:null";
16pub const MAX_ATTEMPT_LEASE_TTL_SECONDS: u64 = 31_536_000;
17
18pub fn attempt_lease_expiry(
20 claimed_at: &str,
21 ttl_seconds: u64,
22) -> Result<chrono::DateTime<chrono::FixedOffset>, String> {
23 if ttl_seconds > MAX_ATTEMPT_LEASE_TTL_SECONDS {
24 return Err(format!(
25 "lease_ttl_seconds must be at most {MAX_ATTEMPT_LEASE_TTL_SECONDS}"
26 ));
27 }
28 let claimed = chrono::DateTime::parse_from_rfc3339(claimed_at)
29 .map_err(|error| format!("invalid lease timestamp: {error}"))?;
30 let seconds = i64::try_from(ttl_seconds)
31 .map_err(|_| "lease_ttl_seconds cannot be represented safely".to_string())?;
32 let duration = chrono::Duration::try_seconds(seconds)
33 .ok_or_else(|| "lease_ttl_seconds exceeds the supported duration".to_string())?;
34 claimed
35 .checked_add_signed(duration)
36 .ok_or_else(|| "lease expiry exceeds the supported timestamp range".to_string())
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
40pub struct StateTarget {
41 pub r#type: String,
42 pub id: String,
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
46pub struct StateActor {
47 pub id: String,
48 pub r#type: String,
49}
50
51pub fn actor_kind(id: &str) -> &'static str {
55 let id = id.trim();
56 let handle = id.split(':').next_back().unwrap_or(id);
57 if id.starts_with("agent:")
58 || id.starts_with("sim:")
59 || id.starts_with("ci:")
60 || id.starts_with("verifier:")
61 || id.starts_with("policy:")
62 || handle.ends_with("-bot")
63 || handle.ends_with("-sim")
64 {
65 "agent"
66 } else {
67 "human"
68 }
69}
70
71macro_rules! event_kinds {
72 ($($variant:ident => $wire:literal),+ $(,)?) => {
73 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
74 pub enum EventKind {
75 $($variant,)+
76 Other(String),
78 }
79
80 impl EventKind {
81 pub fn as_str(&self) -> &str {
82 match self {
83 $(Self::$variant => $wire,)+
84 Self::Other(value) => value,
85 }
86 }
87 }
88
89 impl From<&str> for EventKind {
90 fn from(value: &str) -> Self {
91 match value {
92 $($wire => Self::$variant,)+
93 other => Self::Other(other.to_string()),
94 }
95 }
96 }
97 };
98}
99
100event_kinds! {
104 FrontierCreated => "frontier.created",
105 FindingAsserted => "finding.asserted",
106 FindingNoted => "finding.noted",
107 FindingRetracted => "finding.retracted",
108 AttemptClaimed => "attempt.claimed",
109 FindingSuperseded => "finding.superseded",
110 ReviewAccepted => "review.accepted",
111 ReviewRejected => "review.rejected",
112 ReviewRevisionRequested => "review.revision_requested",
113}
114
115impl From<String> for EventKind {
116 fn from(value: String) -> Self {
117 Self::from(value.as_str())
118 }
119}
120
121impl std::fmt::Display for EventKind {
122 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123 formatter.write_str(self.as_str())
124 }
125}
126
127impl PartialEq<str> for EventKind {
128 fn eq(&self, other: &str) -> bool {
129 self.as_str() == other
130 }
131}
132
133impl PartialEq<&str> for EventKind {
134 fn eq(&self, other: &&str) -> bool {
135 self.as_str() == *other
136 }
137}
138
139impl Serialize for EventKind {
140 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
141 serializer.serialize_str(self.as_str())
142 }
143}
144
145impl<'de> Deserialize<'de> for EventKind {
146 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
147 let value = String::deserialize(deserializer)?;
148 Ok(Self::from(value))
149 }
150}
151
152#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct StateEvent {
154 #[serde(default = "default_schema")]
155 pub schema: String,
156 pub id: String,
157 pub kind: EventKind,
158 pub target: StateTarget,
159 pub actor: StateActor,
160 pub timestamp: String,
161 pub reason: String,
162 pub before_hash: String,
163 pub after_hash: String,
164 #[serde(default)]
165 pub payload: Value,
166 #[serde(default)]
167 pub caveats: Vec<String>,
168 #[serde(default, skip_serializing_if = "Option::is_none")]
169 pub signature: Option<String>,
170}
171
172fn default_schema() -> String {
173 EVENT_SCHEMA.to_string()
174}
175
176pub fn event_log_hash(events: &[StateEvent]) -> String {
178 let mut sorted = events.iter().collect::<Vec<_>>();
179 sorted.sort_by(|left, right| left.id.cmp(&right.id));
180 let stripped = sorted
181 .into_iter()
182 .map(|event| {
183 let mut value = serde_json::to_value(event).unwrap_or(Value::Null);
184 if let Value::Object(object) = &mut value {
185 object.remove("signature");
186 }
187 value
188 })
189 .collect::<Vec<_>>();
190 let bytes = canonical::to_canonical_bytes(&stripped).unwrap_or_default();
191 hex::encode(Sha256::digest(bytes))
192}
193
194pub fn compute_event_id(event: &StateEvent) -> String {
195 event_id(event)
196}
197
198pub fn event_content_preimage_bytes(event: &StateEvent) -> Vec<u8> {
200 canonical::to_canonical_bytes(&json!({
201 "schema": event.schema,
202 "kind": event.kind,
203 "target": event.target,
204 "actor": event.actor,
205 "timestamp": event.timestamp,
206 "reason": event.reason,
207 "before_hash": event.before_hash,
208 "after_hash": event.after_hash,
209 "payload": event.payload,
210 "caveats": event.caveats,
211 }))
212 .unwrap_or_default()
213}
214
215pub fn event_id(event: &StateEvent) -> String {
216 format!(
217 "vev_{}",
218 &hex::encode(Sha256::digest(event_content_preimage_bytes(event)))[..16]
219 )
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225
226 fn event(kind: EventKind, label: &str) -> StateEvent {
227 let mut value = StateEvent {
228 schema: EVENT_SCHEMA.into(),
229 id: String::new(),
230 kind,
231 target: StateTarget {
232 r#type: "claim".into(),
233 id: format!("vcl_{label}"),
234 },
235 actor: StateActor {
236 id: "agent:test".into(),
237 r#type: "agent".into(),
238 },
239 timestamp: "2026-07-28T00:00:00Z".into(),
240 reason: "Exact bounded transition.".into(),
241 before_hash: NULL_HASH.into(),
242 after_hash: format!("sha256:{label}"),
243 payload: json!({"label": label}),
244 caveats: Vec::new(),
245 signature: None,
246 };
247 value.id = compute_event_id(&value);
248 value
249 }
250
251 #[test]
252 fn signatures_do_not_change_event_identity_or_log_root() {
253 let mut value = event(EventKind::FindingAsserted, "a");
254 let id = value.id.clone();
255 let root = event_log_hash(&[value.clone()]);
256 value.signature = Some("detached".into());
257 assert_eq!(compute_event_id(&value), id);
258 assert_eq!(event_log_hash(&[value]), root);
259 }
260
261 #[test]
262 fn event_log_order_is_canonical() {
263 let left = event(EventKind::FindingAsserted, "a");
264 let right = event(EventKind::ReviewAccepted, "b");
265 assert_eq!(
266 event_log_hash(&[left.clone(), right.clone()]),
267 event_log_hash(&[right, left])
268 );
269 }
270}