use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use crate::canonical;
pub const EVENT_SCHEMA: &str = "vela.event.v0.1";
pub const NULL_HASH: &str = "sha256:null";
pub const MAX_ATTEMPT_LEASE_TTL_SECONDS: u64 = 31_536_000;
pub fn attempt_lease_expiry(
claimed_at: &str,
ttl_seconds: u64,
) -> Result<chrono::DateTime<chrono::FixedOffset>, String> {
if ttl_seconds > MAX_ATTEMPT_LEASE_TTL_SECONDS {
return Err(format!(
"lease_ttl_seconds must be at most {MAX_ATTEMPT_LEASE_TTL_SECONDS}"
));
}
let claimed = chrono::DateTime::parse_from_rfc3339(claimed_at)
.map_err(|error| format!("invalid lease timestamp: {error}"))?;
let seconds = i64::try_from(ttl_seconds)
.map_err(|_| "lease_ttl_seconds cannot be represented safely".to_string())?;
let duration = chrono::Duration::try_seconds(seconds)
.ok_or_else(|| "lease_ttl_seconds exceeds the supported duration".to_string())?;
claimed
.checked_add_signed(duration)
.ok_or_else(|| "lease expiry exceeds the supported timestamp range".to_string())
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct StateTarget {
pub r#type: String,
pub id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct StateActor {
pub id: String,
pub r#type: String,
}
pub fn actor_kind(id: &str) -> &'static str {
let id = id.trim();
let handle = id.split(':').next_back().unwrap_or(id);
if id.starts_with("agent:")
|| id.starts_with("sim:")
|| id.starts_with("ci:")
|| id.starts_with("verifier:")
|| id.starts_with("policy:")
|| handle.ends_with("-bot")
|| handle.ends_with("-sim")
{
"agent"
} else {
"human"
}
}
macro_rules! event_kinds {
($($variant:ident => $wire:literal),+ $(,)?) => {
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum EventKind {
$($variant,)+
Other(String),
}
impl EventKind {
pub fn as_str(&self) -> &str {
match self {
$(Self::$variant => $wire,)+
Self::Other(value) => value,
}
}
}
impl From<&str> for EventKind {
fn from(value: &str) -> Self {
match value {
$($wire => Self::$variant,)+
other => Self::Other(other.to_string()),
}
}
}
};
}
event_kinds! {
FrontierCreated => "frontier.created",
FindingAsserted => "finding.asserted",
FindingNoted => "finding.noted",
FindingRetracted => "finding.retracted",
AttemptClaimed => "attempt.claimed",
FindingSuperseded => "finding.superseded",
ReviewAccepted => "review.accepted",
ReviewRejected => "review.rejected",
ReviewRevisionRequested => "review.revision_requested",
}
impl From<String> for EventKind {
fn from(value: String) -> Self {
Self::from(value.as_str())
}
}
impl std::fmt::Display for EventKind {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(self.as_str())
}
}
impl PartialEq<str> for EventKind {
fn eq(&self, other: &str) -> bool {
self.as_str() == other
}
}
impl PartialEq<&str> for EventKind {
fn eq(&self, other: &&str) -> bool {
self.as_str() == *other
}
}
impl Serialize for EventKind {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for EventKind {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = String::deserialize(deserializer)?;
Ok(Self::from(value))
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateEvent {
#[serde(default = "default_schema")]
pub schema: String,
pub id: String,
pub kind: EventKind,
pub target: StateTarget,
pub actor: StateActor,
pub timestamp: String,
pub reason: String,
pub before_hash: String,
pub after_hash: String,
#[serde(default)]
pub payload: Value,
#[serde(default)]
pub caveats: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signature: Option<String>,
}
fn default_schema() -> String {
EVENT_SCHEMA.to_string()
}
pub fn event_log_hash(events: &[StateEvent]) -> String {
let mut sorted = events.iter().collect::<Vec<_>>();
sorted.sort_by(|left, right| left.id.cmp(&right.id));
let stripped = sorted
.into_iter()
.map(|event| {
let mut value = serde_json::to_value(event).unwrap_or(Value::Null);
if let Value::Object(object) = &mut value {
object.remove("signature");
}
value
})
.collect::<Vec<_>>();
let bytes = canonical::to_canonical_bytes(&stripped).unwrap_or_default();
hex::encode(Sha256::digest(bytes))
}
pub fn compute_event_id(event: &StateEvent) -> String {
event_id(event)
}
pub fn event_content_preimage_bytes(event: &StateEvent) -> Vec<u8> {
canonical::to_canonical_bytes(&json!({
"schema": event.schema,
"kind": event.kind,
"target": event.target,
"actor": event.actor,
"timestamp": event.timestamp,
"reason": event.reason,
"before_hash": event.before_hash,
"after_hash": event.after_hash,
"payload": event.payload,
"caveats": event.caveats,
}))
.unwrap_or_default()
}
pub fn event_id(event: &StateEvent) -> String {
format!(
"vev_{}",
&hex::encode(Sha256::digest(event_content_preimage_bytes(event)))[..16]
)
}
#[cfg(test)]
mod tests {
use super::*;
fn event(kind: EventKind, label: &str) -> StateEvent {
let mut value = StateEvent {
schema: EVENT_SCHEMA.into(),
id: String::new(),
kind,
target: StateTarget {
r#type: "claim".into(),
id: format!("vcl_{label}"),
},
actor: StateActor {
id: "agent:test".into(),
r#type: "agent".into(),
},
timestamp: "2026-07-28T00:00:00Z".into(),
reason: "Exact bounded transition.".into(),
before_hash: NULL_HASH.into(),
after_hash: format!("sha256:{label}"),
payload: json!({"label": label}),
caveats: Vec::new(),
signature: None,
};
value.id = compute_event_id(&value);
value
}
#[test]
fn signatures_do_not_change_event_identity_or_log_root() {
let mut value = event(EventKind::FindingAsserted, "a");
let id = value.id.clone();
let root = event_log_hash(&[value.clone()]);
value.signature = Some("detached".into());
assert_eq!(compute_event_id(&value), id);
assert_eq!(event_log_hash(&[value]), root);
}
#[test]
fn event_log_order_is_canonical() {
let left = event(EventKind::FindingAsserted, "a");
let right = event(EventKind::ReviewAccepted, "b");
assert_eq!(
event_log_hash(&[left.clone(), right.clone()]),
event_log_hash(&[right, left])
);
}
}