Skip to main content

vela_protocol/kernel/
events.rs

1//! Canonical replayable frontier events.
2//!
3//! Events are the authoritative record for user-visible state transitions in
4//! the finding-centered v0 kernel. Frontier snapshots remain the convenient
5//! materialized state, but checks and proof packets can validate the event log.
6
7use 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
21/// v0.49: explicit event kind for actor-key revocation. Coalition
22/// governance promises that key compromise is handled by a signed
23/// `RevocationEvent` that names the key, the moment of compromise,
24/// and the recommended replacement. This constant pairs with
25/// `RevocationPayload` and `new_revocation_event` below.
26///
27/// Existing signed history stays valid as a record of what was
28/// signed when; clients that re-verify against a governed actor
29/// registry may flag signatures whose `signed_at` is after the
30/// `revoked_at` moment. This historical event is audit-only in the
31/// repository reducer: it does not itself mutate `.vela/actors.json`.
32/// Profile v1 therefore freezes the actor registry until a separate,
33/// repository-local rotation and recovery contract is accepted.
34pub const EVENT_KIND_KEY_REVOKE: &str = "key.revoke";
35
36/// Generic artifact lifecycle. Carries the full `Artifact` inline on
37/// `payload.artifact` so protocol snapshots can be replayed without
38/// resolving a sidecar file first.
39pub const EVENT_KIND_ARTIFACT_ASSERTED: &str = "artifact.asserted";
40pub const EVENT_KIND_ARTIFACT_REVIEWED: &str = "artifact.reviewed";
41pub const EVENT_KIND_ARTIFACT_RETRACTED: &str = "artifact.retracted";
42
43/// A verifier attachment was bound to a finding (target = vf_…). The attachment
44/// travels in payload.attachment; the reducer appends it to the sidecar
45/// verifier_attachments collection. Per-finding trust status is derived on read.
46pub const EVENT_KIND_VERIFIER_ATTACHMENT_ADDED: &str = "verifier_attachment.added";
47
48/// v0.51: Re-classify a finding or artifact's read-side
49/// access tier. Audit-trail event for the dual-use channel: the
50/// fact that an object's tier changed (and who changed it, when, with
51/// what reason) is itself part of the substrate's accountability
52/// surface and must replay deterministically.
53pub const EVENT_KIND_TIER_SET: &str = "tier.set";
54
55/// v0.56: Mechanical evidence-atom locator repair. Targets a single
56/// evidence atom by id and sets its `locator` field to the value
57/// resolved from the parent source's locator. Carries the resolved
58/// locator string and the source id it was derived from on the event
59/// payload so a fresh replay reconstructs the atom's locator without
60/// needing to re-resolve the source.
61///
62/// This event mutates `state.evidence_atoms[i].locator` and clears the
63/// "missing evidence locator" caveat on the same atom. It does not
64/// touch `state.findings`, so cross-impl reducer fixtures whose
65/// post-replay digest covers `findings[]` only treat this event as a
66/// no-op on finding state. The Rust reducer still has an explicit arm
67/// to avoid silently dropping the repair from a fresh replay.
68pub const EVENT_KIND_EVIDENCE_ATOM_LOCATOR_REPAIRED: &str = "evidence_atom.locator_repaired";
69
70/// v0.57: Mechanical evidence-span repair on a finding. Appends one
71/// `{section, text}` span to `state.findings[i].evidence.evidence_spans`.
72/// Required payload: `{proposal_id, section, text}`. The reducer arm
73/// is idempotent under identical re-application (refuses to append an
74/// equal span twice on the same finding).
75pub const EVENT_KIND_FINDING_SPAN_REPAIRED: &str = "finding.span_repaired";
76
77/// Per-event attestation. Frontier-level review and decision records are too
78/// coarse to bind one exact event. Per-event attestation lets a reviewer or
79/// external verifier
80/// attest one specific canonical event (`vev_*`) by emitting a
81/// new `attestation.recorded` event that points at it.
82///
83/// Required payload: `{target_event_id, attester_id, scope_note}`.
84/// Optional: `scopes`, `reviewer_role`, `orcid`, `ror`,
85/// `attestation_id`, `signature` (Ed25519 over the target event's
86/// preimage), `proof_id` (`vpf_*` from the v0.75 Vela proof
87/// primitive when the attestation is backed by a proof-assistant
88/// verification), `signed_at` (RFC3339).
89///
90/// Reducer arm: no-op on findings. Attestations live as
91/// append-only canonical events; consumers (Workbench, audit
92/// scripts, hub mirrors) project them per-event by reading the
93/// log.
94pub const EVENT_KIND_ATTESTATION_RECORDED: &str = "attestation.recorded";
95
96/// Review verdict over non-mutating frontier observation material,
97/// such as research traces and correction returns. This records what
98/// entered the review ledger without asserting a finding by itself.
99pub const EVENT_KIND_FRONTIER_OBSERVATION_REVIEWED: &str = "frontier.observation_reviewed";
100
101/// T7: a reviewer's decision on a Contradiction object (`vcx_`). The
102/// event carries the full resolved `Contradiction` in
103/// `payload.contradiction`; the reducer upserts it into
104/// `Project.contradictions` (latest resolution per id wins). This is
105/// the only canonical state a contradiction accrues — candidates are
106/// derived from the graph and never written. Honest by construction:
107/// the stored object's status records a *named reviewer's* judgment,
108/// never platform-adjudicated truth.
109pub const EVENT_KIND_CONTRADICTION_RESOLVED: &str = "contradiction.resolved";
110
111/// A signed banked attempt (`vat_`) is deposited into the frontier. The full
112/// [`crate::attempt::Attempt`] travels in `payload.attempt`; the reducer
113/// verifies its id + signature and upserts it into `Project.attempts`.
114pub const EVENT_KIND_ATTEMPT_DEPOSITED: &str = "attempt.deposited";
115
116/// A signed cross-domain [`crate::transfer::Transfer`] is deposited. The full
117/// object travels in `payload.transfer`; the reducer verifies its id +
118/// signature and upserts it into `Project.transfers`. Admission (whether the
119/// link is sound) is derived on read, never stored.
120pub const EVENT_KIND_TRANSFER_DEPOSITED: &str = "transfer.deposited";
121
122/// A signed significance [`crate::endorsement::Endorsement`] is deposited. The
123/// object travels in `payload.endorsement`; the reducer verifies and upserts
124/// into `Project.endorsements`. Endorsements are stored individually and NEVER
125/// aggregated into a score.
126pub const EVENT_KIND_ENDORSEMENT_DEPOSITED: &str = "endorsement.deposited";
127
128/// An append-only lifecycle transition on an attempt. The
129/// [`crate::attempt::ResolutionEvent`] travels in `payload.resolution`; the
130/// reducer upserts it into `Project.attempt_resolutions` (idempotent by
131/// `vre_` id; the head per attempt is the latest by `at`).
132pub const EVENT_KIND_ATTEMPT_RESOLVED: &str = "attempt.resolved";
133
134/// A signed statement-faithfulness attestation rides in
135/// `payload.attestation`; the reducer upserts it (idempotent by vsa_ id).
136pub const EVENT_KIND_STATEMENT_ATTESTED: &str = "statement.attested";
137
138/// A TTL lease on an open obligation: fleet coordination so producers
139/// route around in-flight work (the ETP ran 22M-implication crowd+AI
140/// coordination on GitHub-issue leases; this is that primitive, signed).
141/// Expiry is computed at READ time from event timestamp + ttl — the
142/// reducer never reads a clock.
143pub const EVENT_KIND_ATTEMPT_CLAIMED: &str = "attempt.claimed";
144/// Maximum duration of one coordination lease: 365 days.
145///
146/// A lease is temporary operational coordination, not scientific authority.
147/// Bounding its wire value prevents integer/date overflow and makes every
148/// implementation agree on whether a lease can be live. A zero value remains
149/// reserved for the compare-and-swap release form.
150pub const MAX_ATTEMPT_LEASE_TTL_SECONDS: u64 = 31_536_000;
151
152/// Parse and safely add one protocol-bounded coordination lease duration.
153///
154/// Callers must not reproduce date arithmetic with integer casts: malformed
155/// historical input is an error, never a perpetually live lease or a panic.
156pub fn attempt_lease_expiry(
157    claimed_at: &str,
158    ttl_seconds: u64,
159) -> Result<chrono::DateTime<chrono::FixedOffset>, String> {
160    if ttl_seconds > MAX_ATTEMPT_LEASE_TTL_SECONDS {
161        return Err(format!(
162            "lease_ttl_seconds must be at most {MAX_ATTEMPT_LEASE_TTL_SECONDS}"
163        ));
164    }
165    let claimed = chrono::DateTime::parse_from_rfc3339(claimed_at)
166        .map_err(|error| format!("invalid lease timestamp: {error}"))?;
167    let seconds = i64::try_from(ttl_seconds)
168        .map_err(|_| "lease_ttl_seconds cannot be represented safely".to_string())?;
169    let duration = chrono::Duration::try_seconds(seconds)
170        .ok_or_else(|| "lease_ttl_seconds exceeds the supported duration".to_string())?;
171    claimed
172        .checked_add_signed(duration)
173        .ok_or_else(|| "lease expiry exceeds the supported timestamp range".to_string())
174}
175
176/// Priority registration: a content-addressed statement hash with a hub
177/// receipt timestamp. External anchoring rides the release-archive
178/// chain (every Zenodo/GH bundle embeds the event log), so the time
179/// claim does not depend on trusting the hub.
180pub const EVENT_KIND_STATEMENT_REGISTERED: &str = "statement.registered";
181
182/// A reviewer's decision on a proposal, recorded as a first-class,
183/// signed, append-only event. Before these existed, an accept graduated
184/// into a signed domain event (`finding.asserted`, …) but a REJECT
185/// mutated only the proposal file's `status` field — leaving no
186/// tamper-evident, replayable trace of the decision. That asymmetry was
187/// the silent-drop vector (THREAT_MODEL A11): a maintainer could suppress
188/// an outside producer's proposal with no signed record. These three
189/// kinds close it: every decision a key-registered reviewer makes is now
190/// a side-table event (`before_hash == after_hash == NULL_HASH`, so it is
191/// transparent to the per-finding hash chain) targeting the proposal,
192/// signed by the reviewer key. Proposal `status` becomes a projection of
193/// these events, verified against the stored field by the parity gate
194/// (`verify_proposal_decision_parity`).
195pub const EVENT_KIND_REVIEW_ACCEPTED: &str = "review.accepted";
196pub const EVENT_KIND_REVIEW_REJECTED: &str = "review.rejected";
197pub const EVENT_KIND_REVIEW_REVISION_REQUESTED: &str = "review.revision_requested";
198
199/// A producer closes its own still-pending proposal. This is an audit-only
200/// lifecycle event: it cannot mutate accepted scientific state and is
201/// authorized by the self-signed producer identity embedded in the exact
202/// Receipt v1 already bound by the proposal.
203pub const EVENT_KIND_PROPOSAL_WITHDRAWN: &str = "proposal.withdrawn";
204pub const PROPOSAL_WITHDRAWAL_PAYLOAD_SCHEMA_V1: &str = "vela.proposal-withdrawal.v1";
205pub const PROPOSAL_WITHDRAWAL_PAYLOAD_SCHEMA: &str = "vela.proposal-withdrawal.v2";
206
207/// Signed temporal activation of an actor registration. The event is an
208/// audit-only boundary over exact Git/Vela history; it neither authenticates
209/// unsigned legacy events nor mutates scientific state.
210pub const EVENT_KIND_ACTOR_REGISTRATION_ACTIVATED: &str = "actor.registration_activated";
211
212/// Signed, non-scientific binding between one exact Frontier repository
213/// history, its stable identity, and its exact dependency list.
214pub const EVENT_KIND_FRONTIER_REPOSITORY_BOUND: &str = "frontier.repository_bound";
215
216pub const FRONTIER_CREATED_SCHEMA_V1: &str = "vela.frontier-created.v1";
217
218/// Deterministic machine-verified admission (Phase 1A). Emitted, UNSIGNED, when a
219/// proposal clears the exact-lane auto-admission predicate (kernel-clean, >=2
220/// independent attachments derive `Verified`, a present-and-Survived
221/// FormalismFidelity probe, Sound method integrity, no synthetic-source block, no
222/// frontier contradiction). The trust is the frozen verifier + the audited
223/// deterministic predicate, never a model and never a human rubber stamp; this
224/// materializes the `machine_verified` tier, distinct from `review.accepted`
225/// (human, signed, = significance/release). `before_hash == after_hash` (no
226/// finding mutation): it is an audit record of the admission decision, binding
227/// (proposal_id, attachment_ids, signal_status, policy_version).
228pub const EVENT_KIND_POLICY_AUTO_ADMITTED: &str = "policy.auto_admitted";
229
230/// The complete registry of event kinds the protocol can emit or store.
231/// This is the writer-side universe; the reducer must handle every kind
232/// here (a real arm or an explicit no-op) — `reducer::every_known_kind_reduces`
233/// pins that invariant, so a new kind added to a writer without a reducer
234/// arm fails CI instead of erroring on the next replay. If you add a kind
235/// anywhere, add it here.
236pub const KNOWN_EVENT_KINDS: &[&str] = &[
237    "frontier.created",
238    "finding.asserted",
239    "finding.reviewed",
240    "finding.noted",
241    "finding.caveated",
242    "finding.confidence_revised",
243    "finding.rejected",
244    "finding.retracted",
245    "finding.contribution.recorded",
246    "finding.superseded",
247    "finding.dependency_invalidated",
248    "finding.span_repaired",
249    "assertion.reinterpreted_causal",
250    "source_text.reviewed",
251    "artifact.asserted",
252    "artifact.reviewed",
253    "artifact.retracted",
254    "verifier_attachment.added",
255    "tier.set",
256    "evidence_atom.locator_repaired",
257    "attestation.recorded",
258    "frontier.observation_reviewed",
259    "diff_pack.released",
260    "diff_pack.reviewed",
261    "verdict_conflict.resolved",
262    "contradiction.resolved",
263    "attempt.deposited",
264    "attempt.resolved",
265    "transfer.deposited",
266    "endorsement.deposited",
267    "statement.attested",
268    "attempt.claimed",
269    "statement.registered",
270    "anchor.attached",
271    "anchor.retracted",
272    "proposal.recommended",
273    "correction_return.review",
274    "research_trace.review",
275    "key.revoke",
276    "review.accepted",
277    "review.rejected",
278    "review.revision_requested",
279    "proposal.withdrawn",
280    "actor.registration_activated",
281    "frontier.repository_bound",
282    "policy.auto_admitted",
283];
284
285#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
286pub struct StateTarget {
287    pub r#type: String,
288    pub id: String,
289}
290
291#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
292pub struct StateActor {
293    pub id: String,
294    pub r#type: String,
295}
296
297/// Canonical actor classification. Provenance must never claim more
298/// than is true: an `agent:`-prefixed id, or one whose handle ends in
299/// `-bot` / `-sim`, is a machine actor, never `human`. This is the one
300/// classifier used at event construction and in review-count stats so
301/// an agent or bot is never recorded or counted as human review.
302pub fn actor_kind(id: &str) -> &'static str {
303    let id = id.trim();
304    let handle = id.split(':').next_back().unwrap_or(id);
305    if id.starts_with("agent:")
306        || id.starts_with("sim:")
307        || id.starts_with("ci:")
308        || id.starts_with("verifier:")
309        || id.starts_with("policy:")
310        || handle.ends_with("-bot")
311        || handle.ends_with("-sim")
312    {
313        "agent"
314    } else {
315        "human"
316    }
317}
318
319/// The kind of a canonical state event: a typed enum over the wire strings.
320///
321/// It serializes to, and deserializes from, the exact `"domain.verb"` string the
322/// log has always used, so canonical bytes and event ids are unchanged. The
323/// difference is upstream: the reducer dispatches on this enum, so a removed or
324/// mistyped handler is a compile error rather than a silent fall-through (the old
325/// `match event.kind.as_str()` over bare string literals could drop a typo'd kind
326/// into the default arm). `Other` round-trips any kind a future build does not
327/// know, keeping the log forward-compatible. Single source of truth: the
328/// `event_kinds!` table below generates `as_str` and `From<&str>` together, so
329/// they cannot drift.
330macro_rules! event_kinds {
331    ($($variant:ident => $wire:literal),+ $(,)?) => {
332        #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
333        pub enum EventKind {
334            $($variant,)+
335            /// A kind not known to this build; holds its original wire string.
336            Other(String),
337        }
338
339        impl EventKind {
340            /// The canonical wire string (what serializes into the log).
341            pub fn as_str(&self) -> &str {
342                match self {
343                    $(EventKind::$variant => $wire,)+
344                    EventKind::Other(s) => s.as_str(),
345                }
346            }
347        }
348
349        impl From<&str> for EventKind {
350            fn from(s: &str) -> Self {
351                match s {
352                    $($wire => EventKind::$variant,)+
353                    other => EventKind::Other(other.to_string()),
354                }
355            }
356        }
357    };
358}
359
360event_kinds! {
361    FrontierCreated => "frontier.created",
362    FindingAsserted => "finding.asserted",
363    FindingReviewed => "finding.reviewed",
364    FindingNoted => "finding.noted",
365    FindingCaveated => "finding.caveated",
366    SourceTextReviewed => "source_text.reviewed",
367    FindingConfidenceRevised => "finding.confidence_revised",
368    FindingRejected => "finding.rejected",
369    FindingRetracted => "finding.retracted",
370    FindingContributionRecorded => "finding.contribution.recorded",
371    FindingDependencyInvalidated => "finding.dependency_invalidated",
372    ArtifactAsserted => "artifact.asserted",
373    VerifierAttachmentAdded => "verifier_attachment.added",
374    ArtifactReviewed => "artifact.reviewed",
375    ArtifactRetracted => "artifact.retracted",
376    TierSet => "tier.set",
377    EvidenceAtomLocatorRepaired => "evidence_atom.locator_repaired",
378    FindingSpanRepaired => "finding.span_repaired",
379    AttestationRecorded => "attestation.recorded",
380    DiffPackReleased => "diff_pack.released",
381    DiffPackReviewed => "diff_pack.reviewed",
382    VerdictConflictResolved => "verdict_conflict.resolved",
383    ContradictionResolved => "contradiction.resolved",
384    AttemptDeposited => "attempt.deposited",
385    TransferDeposited => "transfer.deposited",
386    EndorsementDeposited => "endorsement.deposited",
387    AttemptResolved => "attempt.resolved",
388    StatementAttested => "statement.attested",
389    AnchorAttached => "anchor.attached",
390    AnchorRetracted => "anchor.retracted",
391    AttemptClaimed => "attempt.claimed",
392    StatementRegistered => "statement.registered",
393    FindingSuperseded => "finding.superseded",
394    AssertionReinterpretedCausal => "assertion.reinterpreted_causal",
395    ProposalRecommended => "proposal.recommended",
396    FrontierObservationReviewed => "frontier.observation_reviewed",
397    CorrectionReturnReview => "correction_return.review",
398    ResearchTraceReview => "research_trace.review",
399    KeyRevoke => "key.revoke",
400    ReviewAccepted => "review.accepted",
401    ReviewRejected => "review.rejected",
402    ReviewRevisionRequested => "review.revision_requested",
403    ProposalWithdrawn => "proposal.withdrawn",
404    ActorRegistrationActivated => "actor.registration_activated",
405    FrontierRepositoryBound => "frontier.repository_bound",
406    PolicyAutoAdmitted => "policy.auto_admitted",
407}
408
409impl From<String> for EventKind {
410    fn from(s: String) -> Self {
411        EventKind::from(s.as_str())
412    }
413}
414
415impl std::fmt::Display for EventKind {
416    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
417        f.write_str(self.as_str())
418    }
419}
420
421// Ergonomic comparisons so the many `event.kind == "domain.verb"` and
422// `event.kind == EVENT_KIND_X` (a `&str`) call sites keep compiling unchanged.
423impl PartialEq<str> for EventKind {
424    fn eq(&self, other: &str) -> bool {
425        self.as_str() == other
426    }
427}
428impl PartialEq<&str> for EventKind {
429    fn eq(&self, other: &&str) -> bool {
430        self.as_str() == *other
431    }
432}
433
434// Wire form is the bare string: `"kind":"finding.asserted"`, byte-identical to
435// the pre-migration `String` field, so event ids and canonical hashes are stable.
436impl Serialize for EventKind {
437    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
438        serializer.serialize_str(self.as_str())
439    }
440}
441impl<'de> Deserialize<'de> for EventKind {
442    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
443        let s = String::deserialize(deserializer)?;
444        Ok(EventKind::from(s.as_str()))
445    }
446}
447
448#[derive(Debug, Clone, Serialize, Deserialize)]
449pub struct StateEvent {
450    #[serde(default = "default_schema")]
451    pub schema: String,
452    pub id: String,
453    pub kind: EventKind,
454    pub target: StateTarget,
455    pub actor: StateActor,
456    pub timestamp: String,
457    pub reason: String,
458    pub before_hash: String,
459    pub after_hash: String,
460    #[serde(default)]
461    pub payload: Value,
462    #[serde(default)]
463    pub caveats: Vec<String>,
464    #[serde(default, skip_serializing_if = "Option::is_none")]
465    pub signature: Option<String>,
466}
467
468pub struct FindingEventInput<'a> {
469    pub kind: &'a str,
470    pub finding_id: &'a str,
471    pub actor_id: &'a str,
472    pub actor_type: &'a str,
473    pub reason: &'a str,
474    pub before_hash: &'a str,
475    pub after_hash: &'a str,
476    pub payload: Value,
477    pub caveats: Vec<String>,
478    /// When the writer has already stamped a clock into the FINDING
479    /// (annotation timestamp, confidence updated_at), it MUST pass that
480    /// same instant here — the reducer reconstructs those fields from
481    /// `event.timestamp`, and two clock reads diverge the replay hash
482    /// by microseconds (caught live by verify_replay on the first
483    /// replayed finding.noted events). None = stamp now.
484    pub timestamp: Option<&'a str>,
485}
486
487#[derive(Debug, Clone, Serialize, Deserialize)]
488pub struct EventLogSummary {
489    pub count: usize,
490    pub kinds: BTreeMap<String, usize>,
491    pub first_timestamp: Option<String>,
492    pub last_timestamp: Option<String>,
493    pub duplicate_ids: Vec<String>,
494    pub orphan_targets: Vec<String>,
495}
496
497#[derive(Debug, Clone, Serialize, Deserialize)]
498pub struct ReplayReport {
499    pub ok: bool,
500    pub status: String,
501    pub event_log: EventLogSummary,
502    pub source_hash: String,
503    pub event_log_hash: String,
504    pub replayed_hash: String,
505    pub current_hash: String,
506    pub conflicts: Vec<String>,
507}
508
509fn default_schema() -> String {
510    EVENT_SCHEMA.to_string()
511}
512
513pub fn new_finding_event(input: FindingEventInput<'_>) -> StateEvent {
514    let timestamp = input
515        .timestamp
516        .map(|t| t.to_string())
517        .unwrap_or_else(|| Utc::now().to_rfc3339());
518    let mut event = StateEvent {
519        schema: EVENT_SCHEMA.to_string(),
520        id: String::new(),
521        kind: input.kind.into(),
522        target: StateTarget {
523            r#type: "finding".to_string(),
524            id: input.finding_id.to_string(),
525        },
526        actor: StateActor {
527            id: input.actor_id.to_string(),
528            r#type: input.actor_type.to_string(),
529        },
530        timestamp,
531        reason: input.reason.to_string(),
532        before_hash: input.before_hash.to_string(),
533        after_hash: input.after_hash.to_string(),
534        payload: input.payload,
535        caveats: input.caveats,
536        signature: None,
537    };
538    event.id = event_id(&event);
539    event
540}
541
542/// Payload of an `EVENT_KIND_KEY_REVOKE` event. Carries the
543/// revoked Ed25519 pubkey (hex-encoded), the moment compromise was
544/// detected (ISO-8601), an optional replacement pubkey the actor is
545/// migrating to, and a free-form reason string. Stored on the event's
546/// `payload` field; the event's `actor` is the actor whose key is
547/// being revoked, and the event itself must be signed by a key that
548/// was authoritative *before* the revocation (typically a co-signer
549/// or the actor's prior key — never the revoked key itself).
550#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
551pub struct RevocationPayload {
552    /// The Ed25519 pubkey being revoked, hex-encoded (64 chars).
553    pub revoked_pubkey: String,
554    /// ISO-8601 moment when compromise was detected. Signatures
555    /// whose `signed_at` falls after this should be flagged on
556    /// re-verification.
557    pub revoked_at: String,
558    /// Optional replacement pubkey the actor is now signing with,
559    /// hex-encoded. Reviewers re-verifying signed history use this
560    /// to walk forward to the new key.
561    #[serde(default, skip_serializing_if = "String::is_empty")]
562    pub replacement_pubkey: String,
563    /// Free-form reason — "key file leaked", "stolen device",
564    /// "scheduled rotation", etc. Reviewer-facing only; the
565    /// substrate doesn't enumerate.
566    #[serde(default, skip_serializing_if = "String::is_empty")]
567    pub reason: String,
568}
569
570/// Construct a signed-shape `key.revoke` event for the given actor.
571/// Mirrors `new_finding_event` in shape but targets an actor and
572/// carries a `RevocationPayload` in `payload`. The returned event is
573/// unsigned (caller signs it); `event.id` is the canonical content
574/// address of the unsigned shape.
575pub fn new_revocation_event(
576    actor_id: &str,
577    actor_type: &str,
578    payload: RevocationPayload,
579    reason: &str,
580    before_hash: &str,
581    after_hash: &str,
582) -> StateEvent {
583    let timestamp = Utc::now().to_rfc3339();
584    let payload_value =
585        serde_json::to_value(&payload).expect("RevocationPayload serializes to a JSON object");
586    let mut event = StateEvent {
587        schema: EVENT_SCHEMA.to_string(),
588        id: String::new(),
589        kind: EVENT_KIND_KEY_REVOKE.into(),
590        target: StateTarget {
591            r#type: "actor".to_string(),
592            id: actor_id.to_string(),
593        },
594        actor: StateActor {
595            id: actor_id.to_string(),
596            r#type: actor_type.to_string(),
597        },
598        timestamp,
599        reason: reason.to_string(),
600        before_hash: before_hash.to_string(),
601        after_hash: after_hash.to_string(),
602        payload: payload_value,
603        caveats: Vec::new(),
604        signature: None,
605    };
606    event.id = event_id(&event);
607    event
608}
609
610/// Payload of a `review.accepted` / `review.rejected` /
611/// `review.revision_requested` event. Records WHICH proposal was decided
612/// and HOW, binding the decision to the exact proposal by its
613/// content-addressed id (`vpr_…`). The event's `actor` is the deciding
614/// reviewer; the event's `signature` (set by the caller) is the
615/// non-repudiable proof the key holder made the call. `applied_event_id`
616/// is set only for accepts and points at the domain event the accept
617/// graduated into.
618#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
619pub struct ReviewDecisionPayload {
620    /// The proposal this decision applies to (`vpr_…`, content-addressed).
621    pub proposal_id: String,
622    /// The proposal's kind (e.g. `finding.add`), copied for legibility so
623    /// a reviewer reading the log need not cross-reference the proposal.
624    pub proposal_kind: String,
625    /// `accepted` | `rejected` | `revision_requested`. Redundant with the
626    /// event kind but explicit in the payload so consumers that index by
627    /// payload need not parse the kind string.
628    pub verdict: String,
629    /// For accepts: the domain event id (`vev_…`) the accept produced.
630    #[serde(default, skip_serializing_if = "Option::is_none")]
631    pub applied_event_id: Option<String>,
632}
633
634/// Exact authorization material carried by `proposal.withdrawn`.
635#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
636#[serde(deny_unknown_fields)]
637pub struct ProposalWithdrawalPayload {
638    pub schema: String,
639    pub proposal_id: String,
640    pub proposal_root: String,
641    #[serde(default, skip_serializing_if = "Option::is_none")]
642    pub submission_root: Option<String>,
643    #[serde(default, skip_serializing_if = "Option::is_none")]
644    pub receipt_root: Option<String>,
645    pub identity_binding_id: String,
646}
647
648/// Construct an unsigned producer-withdrawal event. The caller verifies the
649/// Submission-bound producer identity and applies the ordinary event signature.
650pub fn new_proposal_withdrawal_event(
651    payload: ProposalWithdrawalPayload,
652    actor_id: &str,
653    reason: &str,
654    timestamp: Option<&str>,
655) -> Result<StateEvent, String> {
656    if !matches!(
657        payload.schema.as_str(),
658        PROPOSAL_WITHDRAWAL_PAYLOAD_SCHEMA | PROPOSAL_WITHDRAWAL_PAYLOAD_SCHEMA_V1
659    ) {
660        return Err(format!(
661            "proposal withdrawal payload schema must be {PROPOSAL_WITHDRAWAL_PAYLOAD_SCHEMA} or {PROPOSAL_WITHDRAWAL_PAYLOAD_SCHEMA_V1}"
662        ));
663    }
664    if !payload.proposal_id.starts_with("vpr_") {
665        return Err("proposal withdrawal requires a vpr_ proposal id".to_string());
666    }
667    let producer_root = match payload.schema.as_str() {
668        PROPOSAL_WITHDRAWAL_PAYLOAD_SCHEMA => match (
669            payload.submission_root.as_deref(),
670            payload.receipt_root.as_deref(),
671        ) {
672            (Some(root), None) => ("submission_root", root),
673            _ => {
674                return Err(
675                    "proposal withdrawal v2 requires submission_root and forbids receipt_root"
676                        .to_string(),
677                );
678            }
679        },
680        PROPOSAL_WITHDRAWAL_PAYLOAD_SCHEMA_V1 => match (
681            payload.receipt_root.as_deref(),
682            payload.submission_root.as_deref(),
683        ) {
684            (Some(root), None) => ("receipt_root", root),
685            _ => {
686                return Err(
687                    "proposal withdrawal v1 requires receipt_root and forbids submission_root"
688                        .to_string(),
689                );
690            }
691        },
692        _ => unreachable!("schema was closed above"),
693    };
694    for (name, root) in [
695        ("proposal_root", payload.proposal_root.as_str()),
696        producer_root,
697    ] {
698        if !root.strip_prefix("sha256:").is_some_and(|hex| {
699            hex.len() == 64
700                && hex
701                    .bytes()
702                    .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
703        }) {
704            return Err(format!(
705                "proposal withdrawal {name} must be a full sha256 root"
706            ));
707        }
708    }
709    if !payload
710        .identity_binding_id
711        .strip_prefix("vib_")
712        .is_some_and(|hex| {
713            hex.len() == 16
714                && hex
715                    .bytes()
716                    .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
717        })
718    {
719        return Err(
720            "proposal withdrawal identity_binding_id must be vib_<16 lowercase hex>".to_string(),
721        );
722    }
723    if actor_kind(actor_id) != "agent" {
724        return Err("only an agent or ci producer may withdraw its proposal".to_string());
725    }
726    if reason.trim().is_empty() {
727        return Err("proposal withdrawal reason must be non-empty".to_string());
728    }
729    let timestamp = timestamp
730        .map(str::to_string)
731        .unwrap_or_else(|| Utc::now().to_rfc3339());
732    let mut event = StateEvent {
733        schema: EVENT_SCHEMA.to_string(),
734        id: String::new(),
735        kind: EVENT_KIND_PROPOSAL_WITHDRAWN.into(),
736        target: StateTarget {
737            r#type: "proposal".to_string(),
738            id: payload.proposal_id.clone(),
739        },
740        actor: StateActor {
741            id: actor_id.to_string(),
742            r#type: "agent".to_string(),
743        },
744        timestamp,
745        reason: reason.to_string(),
746        before_hash: NULL_HASH.to_string(),
747        after_hash: NULL_HASH.to_string(),
748        payload: serde_json::to_value(payload)
749            .map_err(|error| format!("serialize proposal withdrawal payload: {error}"))?,
750        caveats: Vec::new(),
751        signature: None,
752    };
753    event.id = event_id(&event);
754    Ok(event)
755}
756
757/// Construct an unsigned `review.*` event for a proposal decision. The
758/// event is a side-table record (`before_hash == after_hash ==
759/// NULL_HASH`), so it is transparent to the per-finding hash chain. The
760/// caller signs it (under the reviewer key) before persisting; `event.id`
761/// is the content address of the unsigned shape, so signing never changes
762/// the id. `verdict` must be one of `accepted` / `rejected` /
763/// `revision_requested` and selects the event kind.
764pub fn new_review_decision_event(
765    proposal_id: &str,
766    proposal_kind: &str,
767    verdict: &str,
768    applied_event_id: Option<String>,
769    reviewer_id: &str,
770    reason: &str,
771    timestamp: Option<&str>,
772) -> Result<StateEvent, String> {
773    let kind = match verdict {
774        "accepted" => EVENT_KIND_REVIEW_ACCEPTED,
775        "rejected" => EVENT_KIND_REVIEW_REJECTED,
776        "revision_requested" => EVENT_KIND_REVIEW_REVISION_REQUESTED,
777        other => return Err(format!("unknown review verdict '{other}'")),
778    };
779    let payload = ReviewDecisionPayload {
780        proposal_id: proposal_id.to_string(),
781        proposal_kind: proposal_kind.to_string(),
782        verdict: verdict.to_string(),
783        applied_event_id,
784    };
785    let payload_value =
786        serde_json::to_value(&payload).expect("ReviewDecisionPayload serializes to a JSON object");
787    let timestamp = timestamp
788        .map(|t| t.to_string())
789        .unwrap_or_else(|| Utc::now().to_rfc3339());
790    let mut event = StateEvent {
791        schema: EVENT_SCHEMA.to_string(),
792        id: String::new(),
793        kind: kind.into(),
794        target: StateTarget {
795            r#type: "proposal".to_string(),
796            id: proposal_id.to_string(),
797        },
798        actor: StateActor {
799            id: reviewer_id.to_string(),
800            r#type: actor_kind(reviewer_id).to_string(),
801        },
802        timestamp,
803        reason: reason.to_string(),
804        before_hash: NULL_HASH.to_string(),
805        after_hash: NULL_HASH.to_string(),
806        payload: payload_value,
807        caveats: Vec::new(),
808        signature: None,
809    };
810    event.id = event_id(&event);
811    Ok(event)
812}
813
814/// Construct an `evidence_atom.locator_repaired` event targeting an
815/// evidence atom by id. The payload carries the resolved locator and
816/// the parent source id so a fresh replay can both apply the repair
817/// and reconstruct its derivation. Returned event is unsigned; the
818/// caller signs it before persisting.
819pub fn new_evidence_atom_locator_repair_event(
820    atom_id: &str,
821    actor_id: &str,
822    actor_type: &str,
823    reason: &str,
824    before_hash: &str,
825    after_hash: &str,
826    payload: Value,
827    caveats: Vec<String>,
828) -> StateEvent {
829    let timestamp = Utc::now().to_rfc3339();
830    let mut event = StateEvent {
831        schema: EVENT_SCHEMA.to_string(),
832        id: String::new(),
833        kind: EVENT_KIND_EVIDENCE_ATOM_LOCATOR_REPAIRED.into(),
834        target: StateTarget {
835            r#type: "evidence_atom".to_string(),
836            id: atom_id.to_string(),
837        },
838        actor: StateActor {
839            id: actor_id.to_string(),
840            r#type: actor_type.to_string(),
841        },
842        timestamp,
843        reason: reason.to_string(),
844        before_hash: before_hash.to_string(),
845        after_hash: after_hash.to_string(),
846        payload,
847        caveats,
848        signature: None,
849    };
850    event.id = event_id(&event);
851    event
852}
853
854/// T7: build a `contradiction.resolved` event. Target is the
855/// contradiction's content-addressed id (`vcx_*`); the full resolved
856/// object travels in `payload.contradiction`. The reducer arm upserts
857/// it into `Project.contradictions`.
858pub fn new_contradiction_resolved_event(
859    contradiction_id: &str,
860    actor_id: &str,
861    actor_type: &str,
862    reason: &str,
863    payload: Value,
864    caveats: Vec<String>,
865) -> StateEvent {
866    let timestamp = Utc::now().to_rfc3339();
867    let mut event = StateEvent {
868        schema: EVENT_SCHEMA.to_string(),
869        id: String::new(),
870        kind: EVENT_KIND_CONTRADICTION_RESOLVED.into(),
871        target: StateTarget {
872            r#type: "contradiction".to_string(),
873            id: contradiction_id.to_string(),
874        },
875        actor: StateActor {
876            id: actor_id.to_string(),
877            r#type: actor_type.to_string(),
878        },
879        timestamp,
880        reason: reason.to_string(),
881        before_hash: NULL_HASH.to_string(),
882        after_hash: NULL_HASH.to_string(),
883        payload,
884        caveats,
885        signature: None,
886    };
887    event.id = event_id(&event);
888    event
889}
890
891/// Shared builder for the attempt-lifecycle events (`attempt.deposited` /
892/// `attempt.resolved`): both target an attempt's `vat_` id and differ only in
893/// `kind` and the payload they carry.
894fn new_attempt_event(
895    kind: &str,
896    attempt_id: &str,
897    actor_id: &str,
898    actor_type: &str,
899    reason: &str,
900    payload: Value,
901    caveats: Vec<String>,
902) -> StateEvent {
903    let mut event = StateEvent {
904        schema: EVENT_SCHEMA.to_string(),
905        id: String::new(),
906        kind: kind.into(),
907        target: StateTarget {
908            r#type: "attempt".to_string(),
909            id: attempt_id.to_string(),
910        },
911        actor: StateActor {
912            id: actor_id.to_string(),
913            r#type: actor_type.to_string(),
914        },
915        timestamp: Utc::now().to_rfc3339(),
916        reason: reason.to_string(),
917        before_hash: NULL_HASH.to_string(),
918        after_hash: NULL_HASH.to_string(),
919        payload,
920        caveats,
921        signature: None,
922    };
923    event.id = event_id(&event);
924    event
925}
926
927/// Build an `attempt.deposited` event. The full signed object travels in
928/// `payload.attempt`; the reducer verifies it and upserts into
929/// `Project.attempts`.
930pub fn new_attempt_deposited_event(
931    attempt_id: &str,
932    actor_id: &str,
933    actor_type: &str,
934    reason: &str,
935    payload: Value,
936    caveats: Vec<String>,
937) -> StateEvent {
938    new_attempt_event(
939        EVENT_KIND_ATTEMPT_DEPOSITED,
940        attempt_id,
941        actor_id,
942        actor_type,
943        reason,
944        payload,
945        caveats,
946    )
947}
948
949/// Build a `transfer.deposited` event. The full signed [`crate::transfer::Transfer`]
950/// travels in `payload.transfer`; the reducer verifies it and upserts into
951/// `Project.transfers`.
952pub fn new_transfer_deposited_event(
953    transfer_id: &str,
954    actor_id: &str,
955    actor_type: &str,
956    reason: &str,
957    payload: Value,
958    caveats: Vec<String>,
959) -> StateEvent {
960    let mut event = StateEvent {
961        schema: EVENT_SCHEMA.to_string(),
962        id: String::new(),
963        kind: EVENT_KIND_TRANSFER_DEPOSITED.into(),
964        target: StateTarget {
965            r#type: "transfer".to_string(),
966            id: transfer_id.to_string(),
967        },
968        actor: StateActor {
969            id: actor_id.to_string(),
970            r#type: actor_type.to_string(),
971        },
972        timestamp: Utc::now().to_rfc3339(),
973        reason: reason.to_string(),
974        before_hash: NULL_HASH.to_string(),
975        after_hash: NULL_HASH.to_string(),
976        payload,
977        caveats,
978        signature: None,
979    };
980    event.id = event_id(&event);
981    event
982}
983
984/// Build an `endorsement.deposited` event. The signed
985/// [`crate::endorsement::Endorsement`] travels in `payload.endorsement`; the
986/// reducer verifies it and upserts into `Project.endorsements`.
987pub fn new_endorsement_deposited_event(
988    endorsement_id: &str,
989    actor_id: &str,
990    actor_type: &str,
991    reason: &str,
992    payload: Value,
993    caveats: Vec<String>,
994) -> StateEvent {
995    let mut event = StateEvent {
996        schema: EVENT_SCHEMA.to_string(),
997        id: String::new(),
998        kind: EVENT_KIND_ENDORSEMENT_DEPOSITED.into(),
999        target: StateTarget {
1000            r#type: "endorsement".to_string(),
1001            id: endorsement_id.to_string(),
1002        },
1003        actor: StateActor {
1004            id: actor_id.to_string(),
1005            r#type: actor_type.to_string(),
1006        },
1007        timestamp: Utc::now().to_rfc3339(),
1008        reason: reason.to_string(),
1009        before_hash: NULL_HASH.to_string(),
1010        after_hash: NULL_HASH.to_string(),
1011        payload,
1012        caveats,
1013        signature: None,
1014    };
1015    event.id = event_id(&event);
1016    event
1017}
1018
1019/// Build an `attempt.resolved` event. The [`crate::attempt::ResolutionEvent`]
1020/// travels in `payload.resolution`; the reducer upserts it into
1021/// `Project.attempt_resolutions` (idempotent by `vre_` id).
1022pub fn new_attempt_resolved_event(
1023    attempt_id: &str,
1024    actor_id: &str,
1025    actor_type: &str,
1026    reason: &str,
1027    payload: Value,
1028    caveats: Vec<String>,
1029) -> StateEvent {
1030    new_attempt_event(
1031        EVENT_KIND_ATTEMPT_RESOLVED,
1032        attempt_id,
1033        actor_id,
1034        actor_type,
1035        reason,
1036        payload,
1037        caveats,
1038    )
1039}
1040
1041/// Canonical hash of one evidence atom. Mirrors `finding_hash` for the
1042/// before/after pair on locator-repair events so a chain validator can
1043/// confirm that exactly the named atom changed and exactly the named
1044/// repair was applied.
1045pub fn evidence_atom_hash(atom: &crate::sources::EvidenceAtom) -> String {
1046    let bytes = canonical::to_canonical_bytes(atom).unwrap_or_default();
1047    format!("sha256:{}", hex::encode(Sha256::digest(bytes)))
1048}
1049pub fn finding_hash(finding: &FindingBundle) -> String {
1050    // Per Protocol §5, links are "review surfaces" — typed relationships
1051    // between findings inferred at compile or review time, NOT part of the
1052    // finding's content commitment. They are mutable: `vela link add`
1053    // appends links without emitting a state-event (links don't change
1054    // what the finding asserts; they change which findings know about
1055    // each other). For event-replay validity the finding hash must therefore
1056    // exclude `links`, otherwise any CLI-added link breaks the asserted-event
1057    // chain. v0.12: hash a links-cleared copy. State-changing events
1058    // (caveat/note/review/revise/retract) still mutate annotations/flags/
1059    // confidence — those remain in the hash and chain through events properly.
1060    let mut hashable = finding.clone();
1061    hashable.links.clear();
1062    let bytes = canonical::to_canonical_bytes(&hashable).unwrap_or_default();
1063    format!("sha256:{}", hex::encode(Sha256::digest(bytes)))
1064}
1065
1066pub fn finding_hash_by_id(frontier: &Project, finding_id: &str) -> String {
1067    frontier
1068        .findings
1069        .iter()
1070        .find(|finding| finding.id == finding_id)
1071        .map(finding_hash)
1072        .unwrap_or_else(|| NULL_HASH.to_string())
1073}
1074
1075/// The integrity commitment over an event log.
1076///
1077/// Canonical order is the content-addressed event `id`, so the hash is
1078/// INDEPENDENT of how the events were loaded: the packet path (authored
1079/// array order), the `.vela/events/` directory path (filename
1080/// `vev_<id>.json`, i.e. id order), and a future one-file-per-event git
1081/// layout all canonicalize to the same sequence. This is the property the
1082/// git-backed migration needs (ADR 0001): committing events as individual
1083/// files must not redefine the hash. Sorting by `id` (rather than the
1084/// causal `(timestamp, id)` replay order) is also what keeps existing
1085/// signed locks byte-stable, because the directory loader already yields
1086/// id order. Causal REPLAY order is enforced separately in
1087/// `reducer::sorted_for_replay`; this function is only the commitment.
1088pub fn event_log_hash(events: &[StateEvent]) -> String {
1089    let mut sorted: Vec<&StateEvent> = events.iter().collect();
1090    sorted.sort_by(|a, b| a.id.cmp(&b.id));
1091    // Content-only: the log hash binds what the events SAY, not who signed them.
1092    // The `signature` field is stripped before hashing, so re-signing (the v0->v1
1093    // flip, a key rotation) never perturbs `event_log_hash`. Signing is therefore
1094    // orthogonal to content-addressing, the same discipline `snapshot_hash`
1095    // already follows (it removes the top-level `signatures` key). The signatures
1096    // still live on the events on disk; they are simply not part of this digest.
1097    let stripped: Vec<serde_json::Value> = sorted
1098        .iter()
1099        .map(|event| {
1100            let mut value = serde_json::to_value(event).unwrap_or(serde_json::Value::Null);
1101            if let serde_json::Value::Object(map) = &mut value {
1102                map.remove("signature");
1103            }
1104            value
1105        })
1106        .collect();
1107    let bytes = canonical::to_canonical_bytes(&stripped).unwrap_or_default();
1108    hex::encode(Sha256::digest(bytes))
1109}
1110
1111/// Commit to every canonical event except the signed coordination leases used
1112/// by `vela start`.
1113///
1114/// Proof exports describe scientific and authority state. A later
1115/// `attempt.claimed` event changes who is coordinating work, but it does not
1116/// change that proof subject. Keep this exclusion closed to the one named
1117/// event kind: every scientific, provenance, authority, and unknown future
1118/// event remains in the commitment and therefore stales the proof.
1119pub fn nonlease_event_log_hash(events: &[StateEvent]) -> String {
1120    let nonlease = events
1121        .iter()
1122        .filter(|event| event.kind != EVENT_KIND_ATTEMPT_CLAIMED)
1123        .cloned()
1124        .collect::<Vec<_>>();
1125    event_log_hash(&nonlease)
1126}
1127
1128pub fn snapshot_hash(frontier: &Project) -> String {
1129    let value = serde_json::to_value(frontier).unwrap_or(Value::Null);
1130    let mut value = value;
1131    if let Value::Object(map) = &mut value {
1132        map.remove("events");
1133        map.remove("signatures");
1134        map.remove("proof_state");
1135    }
1136    let bytes = canonical::to_canonical_bytes(&value).unwrap_or_default();
1137    hex::encode(Sha256::digest(bytes))
1138}
1139
1140pub fn events_for_finding<'a>(frontier: &'a Project, finding_id: &str) -> Vec<&'a StateEvent> {
1141    frontier
1142        .events
1143        .iter()
1144        .filter(|event| event.target.r#type == "finding" && event.target.id == finding_id)
1145        .collect()
1146}
1147
1148pub fn replay_report(frontier: &Project) -> ReplayReport {
1149    let event_log = summarize(frontier);
1150    let mut conflicts = Vec::new();
1151
1152    if frontier.events.is_empty() {
1153        let current_hash = snapshot_hash(frontier);
1154        return ReplayReport {
1155            ok: true,
1156            status: "no_events".to_string(),
1157            event_log,
1158            source_hash: current_hash.clone(),
1159            event_log_hash: event_log_hash(&frontier.events),
1160            replayed_hash: current_hash.clone(),
1161            current_hash,
1162            conflicts,
1163        };
1164    }
1165
1166    for duplicate in &event_log.duplicate_ids {
1167        conflicts.push(format!("duplicate event id: {duplicate}"));
1168    }
1169    for orphan in &event_log.orphan_targets {
1170        conflicts.push(format!("orphan event target: {orphan}"));
1171    }
1172    conflicts.extend(
1173        crate::frontier_repository::validate_repository_boundary_event_set(&frontier.events),
1174    );
1175
1176    let mut chains = BTreeMap::<String, Vec<&StateEvent>>::new();
1177    for event in &frontier.events {
1178        if event.schema != EVENT_SCHEMA {
1179            conflicts.push(format!(
1180                "unsupported event schema for {}: {}",
1181                event.id, event.schema
1182            ));
1183        }
1184        if event.reason.trim().is_empty() {
1185            conflicts.push(format!("event {} has empty reason", event.id));
1186        }
1187        if event.before_hash.trim().is_empty() || event.after_hash.trim().is_empty() {
1188            conflicts.push(format!("event {} has empty hash boundary", event.id));
1189        }
1190        // Phase E: per-kind payload schema validation. Each event kind has
1191        // a normative payload shape documented in `docs/PROTOCOL.md` §6;
1192        // payloads that don't match are conformance failures, not just
1193        // "weird optional content."
1194        if let Err(err) = validate_event_payload(event.kind.as_str(), &event.payload) {
1195            conflicts.push(format!("event {} payload invalid: {err}", event.id));
1196        }
1197        // Side-table events (statement.registered, attempt.deposited, …)
1198        // are minted with before_hash == after_hash == NULL_HASH: they
1199        // record activity against a finding without transitioning its
1200        // state, so they are transparent to the per-finding hash chain.
1201        // Including them would break the chain between the real
1202        // transitions on either side.
1203        if event.before_hash == NULL_HASH && event.after_hash == NULL_HASH {
1204            continue;
1205        }
1206        chains
1207            .entry(format!("{}:{}", event.target.r#type, event.target.id))
1208            .or_default()
1209            .push(event);
1210    }
1211
1212    for (target, events) in chains {
1213        let mut sorted = events;
1214        sorted.sort_by(|a, b| a.timestamp.cmp(&b.timestamp).then(a.id.cmp(&b.id)));
1215        for pair in sorted.windows(2) {
1216            let previous = pair[0];
1217            let next = pair[1];
1218            if previous.after_hash != next.before_hash {
1219                conflicts.push(format!(
1220                    "event chain break for {target}: {} after_hash does not match {} before_hash",
1221                    previous.id, next.id
1222                ));
1223            }
1224        }
1225        if let Some(last) = sorted.last()
1226            && last.target.r#type == "finding"
1227        {
1228            let current = finding_hash_by_id(frontier, &last.target.id);
1229            if current != last.after_hash {
1230                conflicts.push(format!(
1231                    "materialized finding {} hash does not match last event {}",
1232                    last.target.id, last.id
1233                ));
1234            }
1235        }
1236    }
1237
1238    let current_hash = snapshot_hash(frontier);
1239    let ok = conflicts.is_empty();
1240    ReplayReport {
1241        ok,
1242        status: if ok { "ok" } else { "conflict" }.to_string(),
1243        event_log,
1244        source_hash: current_hash.clone(),
1245        event_log_hash: event_log_hash(&frontier.events),
1246        replayed_hash: if ok {
1247            current_hash.clone()
1248        } else {
1249            "unavailable".to_string()
1250        },
1251        current_hash,
1252        conflicts,
1253    }
1254}
1255pub fn summarize(frontier: &Project) -> EventLogSummary {
1256    let mut kinds = BTreeMap::<String, usize>::new();
1257    let mut seen = BTreeSet::<String>::new();
1258    let mut duplicate_ids = BTreeSet::<String>::new();
1259    let finding_ids = frontier
1260        .findings
1261        .iter()
1262        .map(|finding| finding.id.as_str())
1263        .collect::<BTreeSet<_>>();
1264    let mut orphan_targets = BTreeSet::<String>::new();
1265    let mut timestamps = Vec::<String>::new();
1266
1267    for event in &frontier.events {
1268        *kinds.entry(event.kind.to_string()).or_default() += 1;
1269        if !seen.insert(event.id.clone()) {
1270            duplicate_ids.insert(event.id.clone());
1271        }
1272        // An `attempt.claimed` lease may target a namespaced EXTERNAL
1273        // obligation (e.g. `erdos:443` — work on a problem that has no
1274        // finding yet). Coordination, not truth: not an orphan.
1275        let external_obligation = event.kind == "attempt.claimed"
1276            && event.target.id.contains(':')
1277            && !event.target.id.starts_with("vf_");
1278        let pending_proposal_evidence = event.kind == EVENT_KIND_VERIFIER_ATTACHMENT_ADDED
1279            && event
1280                .payload
1281                .get("proposal_id")
1282                .and_then(Value::as_str)
1283                .is_some_and(|proposal_id| {
1284                    frontier.proposals.iter().any(|proposal| {
1285                        proposal.id == proposal_id
1286                            && proposal.status == "pending_review"
1287                            && proposal.target.id == event.target.id
1288                    })
1289                });
1290        if event.target.r#type == "finding"
1291            && !finding_ids.contains(event.target.id.as_str())
1292            && event.kind != "finding.retracted"
1293            && !external_obligation
1294            && !pending_proposal_evidence
1295        {
1296            orphan_targets.insert(event.target.id.clone());
1297        }
1298        timestamps.push(event.timestamp.clone());
1299    }
1300    timestamps.sort();
1301
1302    EventLogSummary {
1303        count: frontier.events.len(),
1304        kinds,
1305        first_timestamp: timestamps.first().cloned(),
1306        last_timestamp: timestamps.last().cloned(),
1307        duplicate_ids: duplicate_ids.into_iter().collect(),
1308        orphan_targets: orphan_targets.into_iter().collect(),
1309    }
1310}
1311
1312/// Validate a canonical event's payload against its per-kind schema.
1313///
1314/// Each event kind has a normative payload shape. Phase E pins those
1315/// shapes so a second implementation can reject malformed events
1316/// without per-kind ad-hoc parsing. The schemas are documented in
1317/// `docs/PROTOCOL.md` §6 and conformance-checked at the v0.3 level.
1318///
1319/// Unknown kinds are rejected so future-event-kind reads from older
1320/// implementations fail fast rather than silently accepting opaque
1321/// content.
1322fn validate_sha256_commitment(field: &str, value: &str) -> Result<(), String> {
1323    let hex = value.strip_prefix("sha256:").unwrap_or(value);
1324    if hex.len() != 64 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
1325        return Err(format!("{field} must be sha256:<64hex>"));
1326    }
1327    Ok(())
1328}
1329
1330pub fn validate_event_payload(kind: &str, payload: &Value) -> Result<(), String> {
1331    let object = payload.as_object().ok_or_else(|| {
1332        if matches!(payload, Value::Null) {
1333            "payload must be a JSON object (got null)".to_string()
1334        } else {
1335            "payload must be a JSON object".to_string()
1336        }
1337    })?;
1338    let require_str = |key: &str| -> Result<&str, String> {
1339        object
1340            .get(key)
1341            .and_then(Value::as_str)
1342            .ok_or_else(|| format!("missing required string field '{key}'"))
1343    };
1344    let require_f64 = |key: &str| -> Result<f64, String> {
1345        object
1346            .get(key)
1347            .and_then(Value::as_f64)
1348            .ok_or_else(|| format!("missing required number field '{key}'"))
1349    };
1350    match kind {
1351        "finding.asserted" => {
1352            // proposal_id required; optional `finding` for v0.3 genesis
1353            // events that carry the bootstrap finding inline.
1354            require_str("proposal_id")?;
1355        }
1356        "finding.reviewed" => {
1357            require_str("proposal_id")?;
1358            let status = require_str("status")?;
1359            if !matches!(
1360                status,
1361                "accepted" | "approved" | "contested" | "needs_revision" | "rejected"
1362            ) {
1363                return Err(format!("invalid review status '{status}'"));
1364            }
1365        }
1366        "diff_pack.released" => {
1367            let pack_id = require_str("pack_id")?;
1368            if !pack_id.starts_with("vsd_") {
1369                return Err(format!(
1370                    "payload.pack_id must start with 'vsd_', got '{pack_id}'"
1371                ));
1372            }
1373            let frontier_id = require_str("frontier_id")?;
1374            if !frontier_id.starts_with("vfr_") {
1375                return Err(format!(
1376                    "payload.frontier_id must start with 'vfr_', got '{frontier_id}'"
1377                ));
1378            }
1379            let summary = require_str("summary")?;
1380            if summary.trim().is_empty() {
1381                return Err("payload.summary must be non-empty".to_string());
1382            }
1383            let aggregate_kind = require_str("aggregate_kind")?;
1384            if aggregate_kind.trim().is_empty() {
1385                return Err("payload.aggregate_kind must be non-empty".to_string());
1386            }
1387        }
1388        "diff_pack.reviewed" => {
1389            let pack_id = require_str("pack_id")?;
1390            if !pack_id.starts_with("vsd_") {
1391                return Err(format!(
1392                    "payload.pack_id must start with 'vsd_', got '{pack_id}'"
1393                ));
1394            }
1395            let verdict = require_str("verdict")?;
1396            if !matches!(verdict, "accept" | "reject" | "revise") {
1397                return Err(format!(
1398                    "payload.verdict must be accept|reject|revise, got '{verdict}'"
1399                ));
1400            }
1401            let reviewer = require_str("reviewer_actor")?;
1402            if reviewer.trim().is_empty() {
1403                return Err("payload.reviewer_actor must be non-empty".to_string());
1404            }
1405            let reason = require_str("reason")?;
1406            if reason.trim().is_empty() {
1407                return Err("payload.reason must be non-empty".to_string());
1408            }
1409            if let Some(applied) = object.get("applied_members") {
1410                applied
1411                    .as_array()
1412                    .ok_or("payload.applied_members must be an array when present")?;
1413            }
1414            if let Some(sdk_only) = object.get("sdk_only_members") {
1415                sdk_only
1416                    .as_array()
1417                    .ok_or("payload.sdk_only_members must be an array when present")?;
1418            }
1419        }
1420        "finding.contribution.recorded" => {
1421            let contribution = object
1422                .get("contribution")
1423                .and_then(Value::as_object)
1424                .ok_or("payload.contribution must be a JSON object")?;
1425            for field in ["unit", "unit_type", "agent_kind", "agent_id", "role"] {
1426                let v = contribution
1427                    .get(field)
1428                    .and_then(Value::as_str)
1429                    .ok_or_else(|| format!("payload.contribution.{field} must be a string"))?;
1430                if v.trim().is_empty() {
1431                    return Err(format!("payload.contribution.{field} must be non-empty"));
1432                }
1433            }
1434            // The trust invariant, enforced at the wire boundary: `vouched` is a
1435            // human role. A model or agent can never vouch.
1436            if contribution.get("role").and_then(Value::as_str) == Some("vouched")
1437                && contribution.get("agent_kind").and_then(Value::as_str) != Some("human")
1438            {
1439                return Err(
1440                    "payload.contribution: role `vouched` requires agent_kind `human`".to_string(),
1441                );
1442            }
1443        }
1444        "finding.noted" | "finding.caveated" => {
1445            require_str("proposal_id")?;
1446            require_str("annotation_id")?;
1447            let text = require_str("text")?;
1448            if text.trim().is_empty() {
1449                return Err("payload.text must be non-empty".to_string());
1450            }
1451            // Phase β (v0.6): optional structured `provenance` block.
1452            // When present, MUST be an object and MUST carry at least one
1453            // identifying field (doi/pmid/title). An all-empty
1454            // `provenance: {}` is a contract violation, not a tolerable
1455            // default — agents that pass the field are expected to mean it.
1456            if let Some(prov) = object.get("provenance") {
1457                let prov_obj = prov
1458                    .as_object()
1459                    .ok_or("payload.provenance must be a JSON object when present")?;
1460                let has_id = prov_obj
1461                    .get("doi")
1462                    .and_then(Value::as_str)
1463                    .is_some_and(|s| !s.trim().is_empty())
1464                    || prov_obj
1465                        .get("pmid")
1466                        .and_then(Value::as_str)
1467                        .is_some_and(|s| !s.trim().is_empty())
1468                    || prov_obj
1469                        .get("title")
1470                        .and_then(Value::as_str)
1471                        .is_some_and(|s| !s.trim().is_empty());
1472                if !has_id {
1473                    return Err(
1474                        "payload.provenance must include at least one of doi/pmid/title"
1475                            .to_string(),
1476                    );
1477                }
1478            }
1479        }
1480        "source_text.reviewed" => {
1481            require_str("proposal_id")?;
1482            let status = require_str("status")?;
1483            if !matches!(status, "accepted" | "approved") {
1484                return Err(format!("invalid source text review status '{status}'"));
1485            }
1486            let promotion_id = require_str("source_text_promotion_id")?;
1487            if !promotion_id.starts_with("vslaketxtprom_") {
1488                return Err(format!(
1489                    "payload.source_text_promotion_id must start with 'vslaketxtprom_', got '{promotion_id}'"
1490                ));
1491            }
1492            let source_lake_record_id = require_str("source_lake_record_id")?;
1493            if !source_lake_record_id.starts_with("vslake_") {
1494                return Err(format!(
1495                    "payload.source_lake_record_id must start with 'vslake_', got '{source_lake_record_id}'"
1496                ));
1497            }
1498            require_str("lane_id")?;
1499            require_str("locator")?;
1500            require_str("materialized_from")?;
1501        }
1502        "finding.confidence_revised" => {
1503            require_str("proposal_id")?;
1504            let new_score = require_f64("new_score")?;
1505            if !(0.0..=1.0).contains(&new_score) {
1506                return Err(format!("new_score {new_score} out of [0.0, 1.0]"));
1507            }
1508            let _ = require_f64("previous_score")?;
1509        }
1510        "finding.rejected" => {
1511            require_str("proposal_id")?;
1512        }
1513        "finding.superseded" => {
1514            require_str("proposal_id")?;
1515            require_str("new_finding_id")?;
1516        }
1517        "finding.retracted" => {
1518            require_str("proposal_id")?;
1519            // affected and cascade are summary fields; optional but if
1520            // present, affected must be a non-negative integer.
1521            if let Some(affected) = object.get("affected") {
1522                let _ = affected
1523                    .as_u64()
1524                    .ok_or("affected must be a non-negative integer")?;
1525            }
1526        }
1527        // Phase L: per-dependent cascade events. Each one names the
1528        // upstream retraction it descends from, the cascade depth, and
1529        // the canonical event ID of the source retraction so a replay
1530        // can reconstruct the cascade without trusting summary fields.
1531        "finding.dependency_invalidated" => {
1532            require_str("upstream_finding_id")?;
1533            require_str("upstream_event_id")?;
1534            let depth = object
1535                .get("depth")
1536                .and_then(Value::as_u64)
1537                .ok_or("missing required positive integer 'depth'")?;
1538            if depth == 0 {
1539                return Err("depth must be >= 1 (genesis is the source retraction)".to_string());
1540            }
1541            // proposal_id present for cascade-source traceability.
1542            require_str("proposal_id")?;
1543        }
1544        "frontier.created" => {
1545            if object.get("schema").and_then(Value::as_str) == Some(FRONTIER_CREATED_SCHEMA_V1) {
1546                const FIELDS: &[&str] = &[
1547                    "schema",
1548                    "name_at_creation",
1549                    "creator",
1550                    "profile_schema",
1551                    "dependency_root",
1552                    "created_at",
1553                ];
1554                if object.len() != FIELDS.len()
1555                    || object.keys().any(|key| !FIELDS.contains(&key.as_str()))
1556                {
1557                    return Err(format!(
1558                        "{FRONTIER_CREATED_SCHEMA_V1} payload is closed; expected exactly {}",
1559                        FIELDS.join(", ")
1560                    ));
1561                }
1562                require_str("name_at_creation")?;
1563                require_str("creator")?;
1564                if require_str("profile_schema")? != "vela.frontier-profile.v1" {
1565                    return Err(
1566                        "payload.profile_schema must be vela.frontier-profile.v1".to_string()
1567                    );
1568                }
1569                let dependency_root = require_str("dependency_root")?;
1570                if !crate::receipt_v1::is_full_sha256_root(dependency_root) {
1571                    return Err(
1572                        "payload.dependency_root must use sha256:<64 lowercase hex>".to_string()
1573                    );
1574                }
1575                chrono::DateTime::parse_from_rfc3339(require_str("created_at")?).map_err(
1576                    |error| format!("payload.created_at must be an RFC3339 timestamp: {error}"),
1577                )?;
1578            } else {
1579                // Historical structural genesis events predate the closed v1
1580                // payload. They remain replayable, but only the v1 shape may
1581                // establish a Profile v1 repository identity.
1582                require_str("name")?;
1583                require_str("creator")?;
1584            }
1585        }
1586        "frontier.observation_reviewed" => {
1587            require_str("proposal_id")?;
1588            let proposal_kind = require_str("proposal_kind")?;
1589            if !matches!(
1590                proposal_kind,
1591                "research_trace.review" | "correction_return.review"
1592            ) {
1593                return Err(format!(
1594                    "payload.proposal_kind must be research_trace.review or correction_return.review, got '{proposal_kind}'"
1595                ));
1596            }
1597            let status = require_str("status")?;
1598            if status != "accepted" {
1599                return Err(format!("payload.status must be 'accepted', got '{status}'"));
1600            }
1601            if let Some(value) = object.get("decision_reason")
1602                && value.as_str().is_none_or(|reason| reason.trim().is_empty())
1603            {
1604                return Err(
1605                    "payload.decision_reason must be a non-empty string when present".to_string(),
1606                );
1607            }
1608        }
1609        // v0.38: causal-typing reinterpretation. The substrate doesn't
1610        // erase the prior reading; it appends a new event recording who
1611        // re-graded the claim and why. `before` and `after` payloads
1612        // each carry `claim` (correlation|mediation|intervention) and
1613        // optionally `grade` (rct|quasi_experimental|observational|
1614        // theoretical). Pre-v0.38 findings carried neither, so a
1615        // reinterpretation may originate from a block with both fields
1616        // absent or null.
1617        "assertion.reinterpreted_causal" => {
1618            require_str("proposal_id")?;
1619            let check_block = |block_name: &str| -> Result<(), String> {
1620                let block = object
1621                    .get(block_name)
1622                    .and_then(Value::as_object)
1623                    .ok_or_else(|| format!("payload.{block_name} must be an object"))?;
1624                if let Some(claim) = block.get("claim").and_then(Value::as_str)
1625                    && !crate::bundle::VALID_CAUSAL_CLAIMS.contains(&claim)
1626                {
1627                    return Err(format!(
1628                        "{block_name}.claim '{claim}' not in {:?}",
1629                        crate::bundle::VALID_CAUSAL_CLAIMS
1630                    ));
1631                }
1632                if let Some(grade) = block.get("grade").and_then(Value::as_str)
1633                    && !crate::bundle::VALID_CAUSAL_EVIDENCE_GRADES.contains(&grade)
1634                {
1635                    return Err(format!(
1636                        "{block_name}.grade '{grade}' not in {:?}",
1637                        crate::bundle::VALID_CAUSAL_EVIDENCE_GRADES
1638                    ));
1639                }
1640                Ok(())
1641            };
1642            check_block("before")?;
1643            check_block("after")?;
1644        }
1645        // v0.49: key revocation event. Carries the revoked Ed25519
1646        // pubkey (hex-encoded 64 chars), the ISO-8601 moment compromise
1647        // was detected, and an optional replacement pubkey + reason.
1648        // Validating here keeps a hand-emitted or peer-fetched
1649        // revocation honest at the event-pipeline boundary so a
1650        // malformed revocation can't slip through replay and silently
1651        // re-trust the compromised key.
1652        EVENT_KIND_KEY_REVOKE => {
1653            let revoked = require_str("revoked_pubkey")?;
1654            if revoked.len() != 64 || !revoked.chars().all(|c| c.is_ascii_hexdigit()) {
1655                return Err(format!(
1656                    "revoked_pubkey must be 64 hex chars (Ed25519 pubkey), got {} chars",
1657                    revoked.len()
1658                ));
1659            }
1660            let revoked_at = require_str("revoked_at")?;
1661            if revoked_at.trim().is_empty() {
1662                return Err("revoked_at must be a non-empty ISO-8601 timestamp".to_string());
1663            }
1664            // v0.49.1: parse as RFC-3339 / ISO-8601 so a typo'd value
1665            // ("yesterday", "x", "2026-13-99T...") fails at the
1666            // validator boundary rather than poisoning re-verification
1667            // of post-revocation signatures further downstream.
1668            if DateTime::parse_from_rfc3339(revoked_at).is_err() {
1669                return Err(format!(
1670                    "revoked_at must parse as RFC-3339/ISO-8601, got {revoked_at:?}"
1671                ));
1672            }
1673            // replacement_pubkey is optional but if present must be a
1674            // valid hex pubkey of the same shape — a typo here would
1675            // strand the actor's identity at the wrong forward key.
1676            if let Some(replacement) = object.get("replacement_pubkey")
1677                && let Some(rep_str) = replacement.as_str()
1678                && !rep_str.is_empty()
1679                && (rep_str.len() != 64 || !rep_str.chars().all(|c| c.is_ascii_hexdigit()))
1680            {
1681                return Err(format!(
1682                    "replacement_pubkey must be 64 hex chars when present, got {} chars",
1683                    rep_str.len()
1684                ));
1685            }
1686            // The revoked key cannot also be the replacement; that
1687            // would be a self-rotation that revokes nothing.
1688            if let Some(replacement) = object.get("replacement_pubkey").and_then(Value::as_str)
1689                && !replacement.is_empty()
1690                && replacement.eq_ignore_ascii_case(revoked)
1691            {
1692                return Err("replacement_pubkey must differ from revoked_pubkey".to_string());
1693            }
1694        }
1695        // Reviewer decision events. The proposal id binds the decision to
1696        // content (it is content-addressed); verdict must agree with the
1697        // kind so a consumer indexing by either field reads the same call.
1698        EVENT_KIND_REVIEW_ACCEPTED
1699        | EVENT_KIND_REVIEW_REJECTED
1700        | EVENT_KIND_REVIEW_REVISION_REQUESTED => {
1701            let proposal_id = require_str("proposal_id")?;
1702            if !proposal_id.starts_with("vpr_") {
1703                return Err(format!(
1704                    "payload.proposal_id must start with 'vpr_', got '{proposal_id}'"
1705                ));
1706            }
1707            require_str("proposal_kind")?;
1708            let verdict = require_str("verdict")?;
1709            let expected = match kind {
1710                EVENT_KIND_REVIEW_ACCEPTED => "accepted",
1711                EVENT_KIND_REVIEW_REJECTED => "rejected",
1712                _ => "revision_requested",
1713            };
1714            if verdict != expected {
1715                return Err(format!(
1716                    "review event kind '{kind}' requires verdict '{expected}', got '{verdict}'"
1717                ));
1718            }
1719            // applied_event_id only makes sense on an accept, and must be a
1720            // vev_ when present.
1721            if let Some(ev) = object.get("applied_event_id").and_then(Value::as_str) {
1722                if kind != EVENT_KIND_REVIEW_ACCEPTED {
1723                    return Err(format!(
1724                        "applied_event_id is only valid on '{EVENT_KIND_REVIEW_ACCEPTED}'"
1725                    ));
1726                }
1727                if !ev.starts_with("vev_") {
1728                    return Err(format!(
1729                        "payload.applied_event_id must start with 'vev_', got '{ev}'"
1730                    ));
1731                }
1732            }
1733        }
1734        EVENT_KIND_PROPOSAL_WITHDRAWN => {
1735            let parsed: ProposalWithdrawalPayload = serde_json::from_value(payload.clone())
1736                .map_err(|error| format!("invalid proposal-withdrawal payload: {error}"))?;
1737            // Reuse the constructor's closed shape and exact identifier/root
1738            // validation without admitting the resulting unsigned event.
1739            new_proposal_withdrawal_event(
1740                parsed,
1741                "agent:payload-validator",
1742                "validate proposal withdrawal payload",
1743                Some("1970-01-01T00:00:00Z"),
1744            )?;
1745        }
1746        EVENT_KIND_ACTOR_REGISTRATION_ACTIVATED => {
1747            let parsed: crate::actor_registration::ActorRegistrationBoundaryPayload =
1748                serde_json::from_value(payload.clone())
1749                    .map_err(|error| format!("invalid actor-registration payload: {error}"))?;
1750            parsed.validate()?;
1751        }
1752        EVENT_KIND_FRONTIER_REPOSITORY_BOUND => {
1753            let parsed: crate::frontier_repository::FrontierRepositoryBoundaryPayloadV1 =
1754                serde_json::from_value(payload.clone())
1755                    .map_err(|error| format!("invalid repository-boundary payload: {error}"))?;
1756            parsed.validate()?;
1757        }
1758        EVENT_KIND_ARTIFACT_ASSERTED => {
1759            require_str("proposal_id")?;
1760            let artifact = object
1761                .get("artifact")
1762                .and_then(Value::as_object)
1763                .ok_or("payload.artifact must be a JSON object")?;
1764            let id = artifact
1765                .get("id")
1766                .and_then(Value::as_str)
1767                .ok_or("payload.artifact.id must be a va_<hex>")?;
1768            if !id.starts_with("va_") {
1769                return Err(format!(
1770                    "payload.artifact.id must start with 'va_', got '{id}'"
1771                ));
1772            }
1773            let id_hex = id.trim_start_matches("va_");
1774            if id_hex.len() != 16 || !id_hex.chars().all(|c| c.is_ascii_hexdigit()) {
1775                return Err("payload.artifact.id must be va_<16hex>".to_string());
1776            }
1777            let kind = artifact
1778                .get("kind")
1779                .and_then(Value::as_str)
1780                .ok_or("payload.artifact.kind must be a string")?;
1781            if !crate::bundle::valid_artifact_kind(kind) {
1782                return Err(format!("payload.artifact.kind '{kind}' is not supported"));
1783            }
1784            for key in ["name", "content_hash", "storage_mode"] {
1785                let value = artifact
1786                    .get(key)
1787                    .and_then(Value::as_str)
1788                    .ok_or_else(|| format!("payload.artifact.{key} must be a string"))?;
1789                if value.trim().is_empty() {
1790                    return Err(format!("payload.artifact.{key} must be non-empty"));
1791                }
1792            }
1793            let content_hash = artifact
1794                .get("content_hash")
1795                .and_then(Value::as_str)
1796                .expect("content_hash checked above");
1797            validate_sha256_commitment("payload.artifact.content_hash", content_hash)?;
1798        }
1799        EVENT_KIND_ARTIFACT_REVIEWED => {
1800            require_str("proposal_id")?;
1801            let status = require_str("status")?;
1802            if !matches!(
1803                status,
1804                "accepted" | "approved" | "contested" | "needs_revision" | "rejected"
1805            ) {
1806                return Err(format!("invalid review status '{status}'"));
1807            }
1808        }
1809        EVENT_KIND_ARTIFACT_RETRACTED => {
1810            require_str("proposal_id")?;
1811        }
1812        // v0.51: Re-classify an object's read-side access tier.
1813        // Validates target.r#type up front so a `tier.set` event for
1814        // a non-tiered kernel object (dataset, source, etc.)
1815        // fails at the validator boundary rather than silently
1816        // succeeding under the reducer's match-or-noop.
1817        EVENT_KIND_TIER_SET => {
1818            require_str("proposal_id")?;
1819            let object_type = require_str("object_type")?;
1820            if !matches!(object_type, "finding" | "artifact") {
1821                return Err(format!(
1822                    "tier.set object_type '{object_type}' must be one of finding, artifact"
1823                ));
1824            }
1825            require_str("object_id")?;
1826            let new_tier = require_str("new_tier")?;
1827            crate::access_tier::AccessTier::parse(new_tier)?;
1828            // previous_tier is optional but if present must parse to
1829            // a valid tier so a stale or hand-edited event log can't
1830            // smuggle in `"prev"` strings the reducer would later
1831            // reject.
1832            if let Some(prev) = object.get("previous_tier").and_then(Value::as_str) {
1833                crate::access_tier::AccessTier::parse(prev)?;
1834            }
1835        }
1836        // v0.56: Mechanical evidence-atom locator repair. Required
1837        // payload shape: {proposal_id, source_id, locator}. The locator
1838        // string lands on the atom's `locator` field and the source_id
1839        // is recorded for traceability so a reader can reconstruct the
1840        // derivation without re-resolving the source registry.
1841        EVENT_KIND_EVIDENCE_ATOM_LOCATOR_REPAIRED => {
1842            require_str("proposal_id")?;
1843            let source_id = require_str("source_id")?;
1844            if source_id.trim().is_empty() {
1845                return Err("payload.source_id must be non-empty".to_string());
1846            }
1847            let locator = require_str("locator")?;
1848            if locator.trim().is_empty() {
1849                return Err("payload.locator must be non-empty".to_string());
1850            }
1851        }
1852        // v0.57: Append a `{section, text}` span to a finding's
1853        // evidence_spans. Required payload: {proposal_id, section, text}.
1854        EVENT_KIND_FINDING_SPAN_REPAIRED => {
1855            require_str("proposal_id")?;
1856            let section = require_str("section")?;
1857            if section.trim().is_empty() {
1858                return Err("payload.section must be non-empty".to_string());
1859            }
1860            let text = require_str("text")?;
1861            if text.trim().is_empty() {
1862                return Err("payload.text must be non-empty".to_string());
1863            }
1864        }
1865        // v0.79.4: Per-event attestation. Required payload:
1866        // `{target_event_id, attester_id, scope_note}`. Optional:
1867        // `scopes`, `reviewer_role`, `orcid`, `ror`,
1868        // `attestation_id`, `signature`, `proof_id` (vpf_*),
1869        // `signed_at`.
1870        EVENT_KIND_ATTESTATION_RECORDED => {
1871            let target_id = require_str("target_event_id")?;
1872            if !target_id.starts_with("vev_") {
1873                return Err(format!(
1874                    "payload.target_event_id must start with 'vev_', got '{target_id}'"
1875                ));
1876            }
1877            let attester = require_str("attester_id")?;
1878            if attester.trim().is_empty() {
1879                return Err("payload.attester_id must be non-empty".to_string());
1880            }
1881            let scope = require_str("scope_note")?;
1882            if scope.trim().is_empty() {
1883                return Err("payload.scope_note must be non-empty".to_string());
1884            }
1885            // Optional fields: type-check when present.
1886            if let Some(sig) = object.get("signature")
1887                && !sig.is_null()
1888                && !sig.is_string()
1889            {
1890                return Err("payload.signature must be a string when present".to_string());
1891            }
1892            if let Some(scopes) = object.get("scopes") {
1893                let Some(items) = scopes.as_array() else {
1894                    return Err("payload.scopes must be an array when present".to_string());
1895                };
1896                for scope in items {
1897                    let Some(scope) = scope.as_str() else {
1898                        return Err("payload.scopes entries must be strings".to_string());
1899                    };
1900                    match scope {
1901                        "source_extraction"
1902                        | "method_review"
1903                        | "statistical_review"
1904                        | "domain_relevance"
1905                        | "translation_clarity"
1906                        | "policy_approval" => {}
1907                        other => {
1908                            return Err(format!("payload.scopes contains unknown scope `{other}`"));
1909                        }
1910                    }
1911                }
1912            }
1913            for field in [
1914                "reviewer_role",
1915                "orcid",
1916                "ror",
1917                "attestation_id",
1918                "signed_at",
1919            ] {
1920                if let Some(value) = object.get(field)
1921                    && !value.is_null()
1922                    && !value.is_string()
1923                {
1924                    return Err(format!("payload.{field} must be a string when present"));
1925                }
1926            }
1927            if let Some(proof) = object.get("proof_id")
1928                && !proof.is_null()
1929                && let Some(s) = proof.as_str()
1930                && !s.starts_with("vpf_")
1931            {
1932                return Err(format!(
1933                    "payload.proof_id must start with 'vpf_' when present, got '{s}'"
1934                ));
1935            }
1936        }
1937        "verifier_attachment.added" => {
1938            // `proposal_id` is present when the attachment came through the
1939            // propose/accept flow, and absent when a verifier (e.g. CI) directly
1940            // signs its own evidence event. Evidence carries no signer-authority
1941            // claim, so it needs no human accept. Either way the embedded
1942            // attachment object is the load-bearing payload, and the reducer
1943            // re-verifies its content-addressed id on apply.
1944            if let Some(v) = object.get("proposal_id") {
1945                let Some(proposal_id) = v.as_str() else {
1946                    return Err(
1947                        "verifier_attachment.added payload.proposal_id must be a string when present"
1948                            .to_string(),
1949                    );
1950                };
1951                if !proposal_id.starts_with("vpr_") {
1952                    return Err(
1953                        "verifier_attachment.added payload.proposal_id must start with vpr_"
1954                            .to_string(),
1955                    );
1956                }
1957            }
1958            if !object.get("attachment").is_some_and(|v| v.is_object()) {
1959                return Err(
1960                    "verifier_attachment.added payload.attachment must be an object".to_string(),
1961                );
1962            }
1963        }
1964        // Loader=reducer parity: every kind the reducer replays must
1965        // also pass payload validation, or `vela check`'s event-replay
1966        // verdict reports valid history as conflict. These arms are
1967        // signature-pure shape checks; the reducer arms re-verify the
1968        // embedded objects' own ids/signatures on apply.
1969        "verdict_conflict.resolved" => {
1970            if !object.get("conflict").is_some_and(|v| v.is_object()) {
1971                return Err(
1972                    "verdict_conflict.resolved payload.conflict must be an object".to_string(),
1973                );
1974            }
1975        }
1976        "contradiction.resolved" => {
1977            if !object.get("contradiction").is_some_and(|v| v.is_object()) {
1978                return Err(
1979                    "contradiction.resolved payload.contradiction must be an object".to_string(),
1980                );
1981            }
1982        }
1983        EVENT_KIND_ATTEMPT_DEPOSITED => {
1984            if !object.get("attempt").is_some_and(|v| v.is_object()) {
1985                return Err("attempt.deposited payload.attempt must be an object".to_string());
1986            }
1987        }
1988        EVENT_KIND_TRANSFER_DEPOSITED => {
1989            if !object.get("transfer").is_some_and(|v| v.is_object()) {
1990                return Err("transfer.deposited payload.transfer must be an object".to_string());
1991            }
1992        }
1993        EVENT_KIND_ENDORSEMENT_DEPOSITED => {
1994            if !object.get("endorsement").is_some_and(|v| v.is_object()) {
1995                return Err(
1996                    "endorsement.deposited payload.endorsement must be an object".to_string(),
1997                );
1998            }
1999        }
2000        EVENT_KIND_ATTEMPT_RESOLVED => {
2001            if !object.get("resolution").is_some_and(|v| v.is_object()) {
2002                return Err("attempt.resolved payload.resolution must be an object".to_string());
2003            }
2004        }
2005        EVENT_KIND_STATEMENT_ATTESTED => {
2006            if !object.get("attestation").is_some_and(|v| v.is_object()) {
2007                return Err("statement.attested payload.attestation must be an object".to_string());
2008            }
2009        }
2010        EVENT_KIND_ATTEMPT_CLAIMED => {
2011            let obligation_id = require_str("obligation_id")?;
2012            if obligation_id.trim().is_empty() {
2013                return Err("payload.obligation_id must be non-empty".to_string());
2014            }
2015            let ttl = object
2016                .get("lease_ttl_seconds")
2017                .and_then(Value::as_u64)
2018                .ok_or_else(|| {
2019                    "attempt.claimed payload.lease_ttl_seconds must be a non-negative integer"
2020                        .to_string()
2021                })?;
2022            if ttl > MAX_ATTEMPT_LEASE_TTL_SECONDS {
2023                return Err(format!(
2024                    "attempt.claimed payload.lease_ttl_seconds must be at most {MAX_ATTEMPT_LEASE_TTL_SECONDS}"
2025                ));
2026            }
2027            for field in ["claimant_actor", "claimant_pubkey", "prior_claim_event_id"] {
2028                if let Some(value) = object.get(field)
2029                    && !value.is_string()
2030                {
2031                    return Err(format!(
2032                        "attempt.claimed payload.{field} must be a string when present"
2033                    ));
2034                }
2035            }
2036            if let Some(value) = object.get("release_reason")
2037                && !value.is_string()
2038            {
2039                return Err(
2040                    "attempt.claimed payload.release_reason must be a string when present"
2041                        .to_string(),
2042                );
2043            }
2044            if ttl == 0 {
2045                let prior = require_str("prior_claim_event_id")?;
2046                if !prior.strip_prefix("vev_").is_some_and(|hex| {
2047                    hex.len() == 16
2048                        && hex
2049                            .bytes()
2050                            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
2051                }) {
2052                    return Err(
2053                        "zero-TTL attempt.claimed payload.prior_claim_event_id must be a vev_ event id"
2054                            .to_string(),
2055                    );
2056                }
2057                if require_str("release_reason")?.trim().is_empty() {
2058                    return Err(
2059                        "zero-TTL attempt.claimed payload.release_reason must be non-empty"
2060                            .to_string(),
2061                    );
2062                }
2063            }
2064        }
2065        EVENT_KIND_STATEMENT_REGISTERED => {
2066            let hash = require_str("statement_hash")?;
2067            if hash.len() != 64 || hex::decode(hash).is_err() {
2068                return Err(
2069                    "payload.statement_hash must be 32 bytes of hex (64 hex chars)".to_string(),
2070                );
2071            }
2072            if let Some(finding) = object.get("finding_id")
2073                && !finding.is_null()
2074                && !finding.is_string()
2075            {
2076                return Err("payload.finding_id must be a string when present".to_string());
2077            }
2078        }
2079        "proposal.recommended" => {
2080            require_str("proposal_id")?;
2081        }
2082        "anchor.attached" => {
2083            if !payload.get("anchor_link").is_some_and(Value::is_object) {
2084                return Err("anchor.attached payload.anchor_link must be an object".to_string());
2085            }
2086        }
2087        "anchor.retracted" => {
2088            if !payload
2089                .get("anchor_link_id")
2090                .and_then(Value::as_str)
2091                .is_some_and(|s| !s.trim().is_empty())
2092            {
2093                return Err("anchor.retracted payload.anchor_link_id must be non-empty".to_string());
2094            }
2095        }
2096        // Historical audit-record kinds: the reducer replays them as
2097        // no-ops; the payload shape is whatever the retired surface
2098        // minted. Object-ness is already enforced above.
2099        "correction_return.review" | "research_trace.review" => {}
2100
2101        // policy.auto_admitted (Phase 1A): deterministic machine-verified admission
2102        // audit record. The audit record is the only accountability artifact for
2103        // a human-free admit (checklist #10), so the binding fields are mandatory
2104        // and well-formed: the proposal it admitted, the claim digest the gate
2105        // matched, the frozen policy version, and the frozen verifier-env hash —
2106        // these let an auditor re-derive a FLOOR admission (reproduce the witness
2107        // under `verifier_env_hash` + check `claim_digest` against the assertion)
2108        // independently of attachments. `attachment_ids` lists the corroborating
2109        // attachments and MAY be empty: a floor-sufficient exact-lane admit has
2110        // none — the frozen verifier + faithful binding is itself the proof.
2111        "policy.auto_admitted" => {
2112            require_str("proposal_id")?;
2113            require_str("claim_digest")?;
2114            require_str("policy_version")?;
2115            require_str("verifier_env_hash")?;
2116            match payload.get("attachment_ids") {
2117                Some(serde_json::Value::Array(ids)) => {
2118                    if !ids.iter().all(|v| v.is_string()) {
2119                        return Err(
2120                            "policy.auto_admitted: attachment_ids must be strings".to_string()
2121                        );
2122                    }
2123                }
2124                _ => {
2125                    return Err("policy.auto_admitted: attachment_ids must be an array".to_string());
2126                }
2127            }
2128        }
2129
2130        other => return Err(format!("unknown event kind '{other}'")),
2131    }
2132    Ok(())
2133}
2134
2135/// Public form of `event_id` so callers building non-finding events
2136/// (e.g. the `frontier.created` genesis event in `project::assemble`)
2137/// can compute the canonical event ID with the same canonical-JSON
2138/// preimage shape as `new_finding_event`.
2139pub fn compute_event_id(event: &StateEvent) -> String {
2140    event_id(event)
2141}
2142
2143/// The canonical content-address preimage bytes of an event — the exact bytes
2144/// hashed to form its `vev_` id. Deliberately EXCLUDES the event's own `id`,
2145/// and `signature`, so the preimage is stable under legitimate
2146/// re-signing/co-signing. Shared by `event_id` and the Merkle transparency log
2147/// (`crate::merkle`) so a log leaf is exactly the event's content address —
2148/// immune to re-signing and reproducible by any independent implementation.
2149/// Changing this shape is a protocol break.
2150pub fn event_content_preimage_bytes(event: &StateEvent) -> Vec<u8> {
2151    let content = json!({
2152        "schema": event.schema,
2153        "kind": event.kind,
2154        "target": event.target,
2155        "actor": event.actor,
2156        "timestamp": event.timestamp,
2157        "reason": event.reason,
2158        "before_hash": event.before_hash,
2159        "after_hash": event.after_hash,
2160        "payload": event.payload,
2161        "caveats": event.caveats,
2162    });
2163    canonical::to_canonical_bytes(&content).unwrap_or_default()
2164}
2165
2166pub fn event_id(event: &StateEvent) -> String {
2167    format!(
2168        "vev_{}",
2169        &hex::encode(Sha256::digest(event_content_preimage_bytes(event)))[..16]
2170    )
2171}
2172
2173#[cfg(test)]
2174mod tests {
2175    use super::*;
2176    use crate::bundle::{
2177        Assertion, Conditions, Confidence, Evidence, Extraction, FindingBundle, Flags, Provenance,
2178    };
2179    use crate::project;
2180
2181    #[test]
2182    fn snapshot_hash_exclusion_keys_exist_on_project() {
2183        // snapshot_hash removes "events"/"signatures"/"proof_state" by string
2184        // key from the serialized Project so the derived/mutable plane is
2185        // excluded from the hash. If a future serde rename or field rename made
2186        // one of these keys stop existing, the remove() would silently no-op and
2187        // snapshot_hash would begin covering the event log — a global byte-parity
2188        // break with NO compiler error. This pins the contract cheaply.
2189        let project = project::assemble("guard", vec![finding()], 0, 0, "guard");
2190        let value = serde_json::to_value(&project).expect("serialize Project");
2191        let map = value.as_object().expect("Project serializes as an object");
2192        for key in ["events", "signatures", "proof_state"] {
2193            assert!(
2194                map.contains_key(key),
2195                "snapshot_hash excludes `{key}` by string key, but it is absent from \
2196                 serde_json::to_value(Project) — the exclusion would silently no-op"
2197            );
2198        }
2199    }
2200
2201    fn finding() -> FindingBundle {
2202        FindingBundle::new(
2203            Assertion {
2204                text: "LRP1 clears amyloid beta at the BBB".to_string(),
2205                assertion_type: "mechanism".to_string(),
2206                entities: Vec::new(),
2207                relation: None,
2208                direction: None,
2209                causal_claim: None,
2210                causal_evidence_grade: None,
2211            },
2212            Evidence {
2213                evidence_type: "experimental".to_string(),
2214                model_system: "mouse".to_string(),
2215                method: "assay".to_string(),
2216                replicated: false,
2217                replication_count: None,
2218                evidence_spans: Vec::new(),
2219            },
2220            Conditions {
2221                text: "mouse model".to_string(),
2222                duration: None,
2223            },
2224            Confidence::raw(0.6, "test", 0.8),
2225            Provenance {
2226                source_type: "published_paper".to_string(),
2227                doi: None,
2228                url: None,
2229                title: "Test source".to_string(),
2230                authors: Vec::new(),
2231                year: Some(2026),
2232                license: None,
2233                publisher: None,
2234                funders: Vec::new(),
2235                extraction: Extraction::default(),
2236                review: None,
2237                contributions: Vec::new(),
2238            },
2239            Flags {
2240                gap: false,
2241                negative_space: false,
2242                contested: false,
2243                retracted: false,
2244                declining: false,
2245                gravity_well: false,
2246                review_state: None,
2247                superseded: false,
2248                signature_threshold: None,
2249                jointly_accepted: false,
2250            },
2251        )
2252    }
2253
2254    #[test]
2255    fn event_id_is_deterministic_for_content() {
2256        let event = new_finding_event(FindingEventInput {
2257            kind: "finding.reviewed",
2258            finding_id: "vf_test",
2259            actor_id: "reviewer",
2260            actor_type: "human",
2261            reason: "checked",
2262            before_hash: NULL_HASH,
2263            after_hash: "sha256:abc",
2264            payload: json!({"status": "accepted", "proposal_id": "vpr_test"}),
2265            caveats: vec![],
2266            timestamp: None,
2267        });
2268        let mut same = event.clone();
2269        same.id = String::new();
2270        same.id = super::event_id(&same);
2271        assert_eq!(event.id, same.id);
2272    }
2273
2274    #[test]
2275    fn genesis_only_event_log_replays_ok() {
2276        // Phase J: assemble() emits a `frontier.created` genesis event,
2277        // so a freshly compiled frontier never has an empty event log.
2278        // Replay over genesis-only must succeed with status "ok" and the
2279        // single event accounted for.
2280        let frontier = project::assemble("test", Vec::new(), 0, 0, "test");
2281        let report = replay_report(&frontier);
2282        assert!(report.ok, "{:?}", report.conflicts);
2283        assert_eq!(report.event_log.count, 1);
2284        assert_eq!(report.event_log.kinds.get("frontier.created"), Some(&1));
2285    }
2286
2287    #[test]
2288    fn replay_detects_duplicate_event_ids() {
2289        let finding = finding();
2290        let after_hash = finding_hash(&finding);
2291        let event = new_finding_event(FindingEventInput {
2292            kind: "finding.reviewed",
2293            finding_id: &finding.id,
2294            actor_id: "reviewer",
2295            actor_type: "human",
2296            reason: "checked",
2297            before_hash: &after_hash,
2298            after_hash: &after_hash,
2299            payload: json!({"status": "accepted", "proposal_id": "vpr_test"}),
2300            caveats: vec![],
2301            timestamp: None,
2302        });
2303        let mut frontier = project::assemble("test", vec![finding], 0, 0, "test");
2304        frontier.events = vec![event.clone(), event];
2305
2306        let report = replay_report(&frontier);
2307        assert!(!report.ok);
2308        assert_eq!(report.status, "conflict");
2309        assert!(!report.event_log.duplicate_ids.is_empty());
2310    }
2311
2312    #[test]
2313    fn replay_detects_orphan_targets() {
2314        let mut frontier = project::assemble("test", Vec::new(), 0, 0, "test");
2315        frontier.events.push(new_finding_event(FindingEventInput {
2316            kind: "finding.reviewed",
2317            finding_id: "vf_missing",
2318            actor_id: "reviewer",
2319            actor_type: "human",
2320            reason: "checked",
2321            before_hash: NULL_HASH,
2322            after_hash: "sha256:abc",
2323            payload: json!({"status": "accepted", "proposal_id": "vpr_test"}),
2324            caveats: vec![],
2325            timestamp: None,
2326        }));
2327
2328        let report = replay_report(&frontier);
2329        assert!(!report.ok);
2330        assert_eq!(report.event_log.orphan_targets, vec!["vf_missing"]);
2331    }
2332
2333    #[test]
2334    fn external_obligation_lease_is_not_an_orphan() {
2335        // Swarm regression (2026-07-02): an `attempt.claimed` lease on a
2336        // namespaced external target (erdos:443 — a problem with no
2337        // finding yet) must not read as an orphan event; ten of them
2338        // turned a green frontier red.
2339        let mut frontier = project::assemble("test", Vec::new(), 0, 0, "test");
2340        let mut event = new_finding_event(FindingEventInput {
2341            kind: "attempt.claimed",
2342            finding_id: "erdos:443",
2343            actor_id: "agent:swarm-443",
2344            actor_type: "agent",
2345            reason: "obligation lease",
2346            before_hash: "sha256:null",
2347            after_hash: "sha256:null",
2348            payload: serde_json::json!({
2349                "obligation_id": "erdos:443",
2350                "lease_ttl_seconds": 3600,
2351                "claimant_actor": "agent:swarm-443",
2352                "claimant_pubkey": "00",
2353            }),
2354            caveats: Vec::new(),
2355            timestamp: None,
2356        });
2357        event.id = compute_event_id(&event);
2358        frontier.events.push(event);
2359        let report = replay_report(&frontier);
2360        assert!(
2361            report.event_log.orphan_targets.is_empty(),
2362            "external obligation lease misread as orphan: {:?}",
2363            report.event_log.orphan_targets
2364        );
2365    }
2366
2367    #[test]
2368    fn attempt_claimed_rejects_unbounded_lease_ttl() {
2369        let payload = serde_json::json!({
2370            "obligation_id": "erdos:1056",
2371            "lease_ttl_seconds": u64::MAX,
2372            "claimant_actor": "agent:fixture",
2373            "claimant_pubkey": "00",
2374        });
2375        let error = validate_event_payload(EVENT_KIND_ATTEMPT_CLAIMED, &payload).unwrap_err();
2376        assert!(error.contains("must be at most"), "{error}");
2377    }
2378
2379    #[test]
2380    fn replay_accepts_current_hash_boundary() {
2381        let finding = finding();
2382        let hash = finding_hash(&finding);
2383        let event = new_finding_event(FindingEventInput {
2384            kind: "finding.reviewed",
2385            finding_id: &finding.id,
2386            actor_id: "reviewer",
2387            actor_type: "human",
2388            reason: "checked",
2389            before_hash: &hash,
2390            after_hash: &hash,
2391            payload: json!({"status": "accepted", "proposal_id": "vpr_test"}),
2392            caveats: vec![],
2393            timestamp: None,
2394        });
2395        let mut frontier = project::assemble("test", vec![finding], 0, 0, "test");
2396        frontier.events.push(event);
2397
2398        let report = replay_report(&frontier);
2399        assert!(report.ok, "{:?}", report.conflicts);
2400        assert_eq!(report.status, "ok");
2401    }
2402
2403    #[test]
2404    fn validates_diff_pack_lifecycle_payloads() {
2405        assert!(
2406            validate_event_payload(
2407                "diff_pack.released",
2408                &json!({
2409                    "pack_id": "vsd_1234567890abcdef",
2410                    "frontier_id": "vfr_1234567890abcdef",
2411                    "summary": "Review bounded proposed changes.",
2412                    "aggregate_kind": "clinical_translation.review_set",
2413                }),
2414            )
2415            .is_ok()
2416        );
2417        assert!(
2418            validate_event_payload(
2419                "diff_pack.reviewed",
2420                &json!({
2421                    "pack_id": "vsd_1234567890abcdef",
2422                    "verdict": "revise",
2423                    "reviewer_actor": "reviewer:test",
2424                    "reason": "Needs source locator repair before acceptance.",
2425                    "applied_members": [],
2426                    "sdk_only_members": ["vpr_sdk_only"],
2427                }),
2428            )
2429            .is_ok()
2430        );
2431        assert!(
2432            validate_event_payload(
2433                "diff_pack.released",
2434                &json!({
2435                    "pack_id": "bad",
2436                    "frontier_id": "vfr_1234567890abcdef",
2437                    "summary": "Review bounded proposed changes.",
2438                    "aggregate_kind": "clinical_translation.review_set",
2439                }),
2440            )
2441            .is_err()
2442        );
2443        assert!(
2444            validate_event_payload(
2445                "diff_pack.reviewed",
2446                &json!({
2447                    "pack_id": "vsd_1234567890abcdef",
2448                    "verdict": "maybe",
2449                    "reviewer_actor": "reviewer:test",
2450                    "reason": "Needs source locator repair before acceptance.",
2451                }),
2452            )
2453            .is_err()
2454        );
2455    }
2456
2457    #[test]
2458    fn validates_artifact_asserted_payload() {
2459        let good_hash = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
2460        assert!(
2461            validate_event_payload(
2462                EVENT_KIND_ARTIFACT_ASSERTED,
2463                &json!({
2464                    "proposal_id": "vpr_test",
2465                    "artifact": {
2466                        "id": "va_1234567890abcdef",
2467                        "kind": "clinical_trial_record",
2468                        "name": "NCT test record",
2469                        "content_hash": good_hash,
2470                        "storage_mode": "embedded",
2471                    },
2472                }),
2473            )
2474            .is_ok()
2475        );
2476        assert!(
2477            validate_event_payload(
2478                EVENT_KIND_ARTIFACT_ASSERTED,
2479                &json!({
2480                    "proposal_id": "vpr_test",
2481                    "artifact": {
2482                        "id": "va_123",
2483                        "kind": "clinical_trial_record",
2484                        "name": "NCT test record",
2485                        "content_hash": good_hash,
2486                        "storage_mode": "embedded",
2487                    },
2488                }),
2489            )
2490            .is_err()
2491        );
2492        assert!(
2493            validate_event_payload(
2494                EVENT_KIND_ARTIFACT_ASSERTED,
2495                &json!({
2496                    "proposal_id": "vpr_test",
2497                    "artifact": {
2498                        "id": "va_1234567890abcdef",
2499                        "kind": "clinical_trial_record",
2500                        "name": "NCT test record",
2501                        "content_hash": "sha256:not-a-real-hash",
2502                        "storage_mode": "embedded",
2503                    },
2504                }),
2505            )
2506            .is_err()
2507        );
2508    }
2509
2510    // v0.38 — causal-typing event validation
2511    #[test]
2512    fn validates_reinterpreted_causal_payload() {
2513        // OK: missing claim/grade is fine (None means no prior reading).
2514        assert!(
2515            validate_event_payload(
2516                "assertion.reinterpreted_causal",
2517                &json!({
2518                    "proposal_id": "vpr_test",
2519                    "before": {},
2520                    "after": { "claim": "intervention", "grade": "rct" },
2521                }),
2522            )
2523            .is_ok()
2524        );
2525        // OK: pure claim revision, no grade.
2526        assert!(
2527            validate_event_payload(
2528                "assertion.reinterpreted_causal",
2529                &json!({
2530                    "proposal_id": "vpr_test",
2531                    "before": { "claim": "correlation" },
2532                    "after": { "claim": "mediation" },
2533                }),
2534            )
2535            .is_ok()
2536        );
2537        // FAIL: invalid claim.
2538        assert!(
2539            validate_event_payload(
2540                "assertion.reinterpreted_causal",
2541                &json!({
2542                    "proposal_id": "vpr_test",
2543                    "before": {},
2544                    "after": { "claim": "magic" },
2545                }),
2546            )
2547            .is_err()
2548        );
2549        // FAIL: invalid grade.
2550        assert!(
2551            validate_event_payload(
2552                "assertion.reinterpreted_causal",
2553                &json!({
2554                    "proposal_id": "vpr_test",
2555                    "before": {},
2556                    "after": { "claim": "intervention", "grade": "vibes" },
2557                }),
2558            )
2559            .is_err()
2560        );
2561        // FAIL: missing proposal_id.
2562        assert!(
2563            validate_event_payload(
2564                "assertion.reinterpreted_causal",
2565                &json!({
2566                    "before": {},
2567                    "after": { "claim": "intervention" },
2568                }),
2569            )
2570            .is_err()
2571        );
2572    }
2573
2574    /// v0.49: a `key.revoke` event names the revoked pubkey, the
2575    /// moment of compromise, and (optionally) the replacement key.
2576    /// Empty optional fields skip canonical-JSON serialization so
2577    /// existing event logs round-trip byte-identically.
2578    #[test]
2579    fn revocation_event_canonical_shape() {
2580        use crate::canonical;
2581        let payload = RevocationPayload {
2582            revoked_pubkey: "4892f93877e637b5f59af31d9ec6704814842fb278cacb0eb94704baef99455e"
2583                .to_string(),
2584            revoked_at: "2026-05-01T17:00:00Z".to_string(),
2585            replacement_pubkey: "8891a2ab35ca2ed2182ed4e46b6567ce8dacc9985eb496d895578201272a1cd9"
2586                .to_string(),
2587            reason: "key file leaked from CI cache".to_string(),
2588        };
2589        let event = new_revocation_event(
2590            "reviewer:will-blair",
2591            "human",
2592            payload,
2593            "rotating compromised key",
2594            NULL_HASH,
2595            NULL_HASH,
2596        );
2597        assert_eq!(event.kind, EVENT_KIND_KEY_REVOKE);
2598        assert_eq!(event.target.r#type, "actor");
2599        assert!(event.id.starts_with("vev_"));
2600        let bytes = canonical::to_canonical_bytes(&event).unwrap();
2601        let s = std::str::from_utf8(&bytes).unwrap();
2602        assert!(
2603            s.contains("\"revoked_pubkey\""),
2604            "canonical bytes missing revoked_pubkey: {s}"
2605        );
2606        assert!(
2607            s.contains("\"revoked_at\""),
2608            "canonical bytes missing revoked_at: {s}"
2609        );
2610        assert!(
2611            s.contains("\"replacement_pubkey\""),
2612            "canonical bytes missing replacement_pubkey: {s}"
2613        );
2614
2615        // Empty replacement_pubkey skips serialization.
2616        let payload_minimal = RevocationPayload {
2617            revoked_pubkey: "a".repeat(64),
2618            revoked_at: "2026-05-01T17:00:00Z".to_string(),
2619            replacement_pubkey: String::new(),
2620            reason: String::new(),
2621        };
2622        let minimal_event = new_revocation_event(
2623            "reviewer:will-blair",
2624            "human",
2625            payload_minimal,
2626            "scheduled rotation",
2627            NULL_HASH,
2628            NULL_HASH,
2629        );
2630        let minimal_bytes = canonical::to_canonical_bytes(&minimal_event).unwrap();
2631        let minimal_s = std::str::from_utf8(&minimal_bytes).unwrap();
2632        assert!(
2633            !minimal_s.contains("\"replacement_pubkey\""),
2634            "empty replacement_pubkey leaked into canonical JSON: {minimal_s}"
2635        );
2636        assert!(
2637            !minimal_s.contains("\"reason\":\"\""),
2638            "empty payload reason leaked into canonical JSON: {minimal_s}"
2639        );
2640    }
2641
2642    /// v0.49: validate_event_payload now recognises `key.revoke`.
2643    /// Tests cover the four real failure modes plus the happy path.
2644    #[test]
2645    fn revocation_payload_validation() {
2646        let good_pubkey = "4892f93877e637b5f59af31d9ec6704814842fb278cacb0eb94704baef99455e";
2647        let other_pubkey = "8891a2ab35ca2ed2182ed4e46b6567ce8dacc9985eb496d895578201272a1cd9";
2648
2649        // OK: minimal valid payload.
2650        assert!(
2651            validate_event_payload(
2652                EVENT_KIND_KEY_REVOKE,
2653                &json!({
2654                    "revoked_pubkey": good_pubkey,
2655                    "revoked_at": "2026-05-01T17:00:00Z",
2656                }),
2657            )
2658            .is_ok()
2659        );
2660
2661        // OK: full payload with replacement and reason.
2662        assert!(
2663            validate_event_payload(
2664                EVENT_KIND_KEY_REVOKE,
2665                &json!({
2666                    "revoked_pubkey": good_pubkey,
2667                    "revoked_at": "2026-05-01T17:00:00Z",
2668                    "replacement_pubkey": other_pubkey,
2669                    "reason": "key file leaked",
2670                }),
2671            )
2672            .is_ok()
2673        );
2674
2675        // FAIL: revoked_pubkey wrong length (32 bytes ASCII, not 64 hex).
2676        assert!(
2677            validate_event_payload(
2678                EVENT_KIND_KEY_REVOKE,
2679                &json!({
2680                    "revoked_pubkey": "abc123",
2681                    "revoked_at": "2026-05-01T17:00:00Z",
2682                }),
2683            )
2684            .is_err()
2685        );
2686
2687        // FAIL: revoked_pubkey contains non-hex chars.
2688        assert!(
2689            validate_event_payload(
2690                EVENT_KIND_KEY_REVOKE,
2691                &json!({
2692                    "revoked_pubkey": "ZZ".repeat(32),
2693                    "revoked_at": "2026-05-01T17:00:00Z",
2694                }),
2695            )
2696            .is_err()
2697        );
2698
2699        // FAIL: missing revoked_at.
2700        assert!(
2701            validate_event_payload(
2702                EVENT_KIND_KEY_REVOKE,
2703                &json!({
2704                    "revoked_pubkey": good_pubkey,
2705                }),
2706            )
2707            .is_err()
2708        );
2709
2710        // FAIL: replacement_pubkey wrong length.
2711        assert!(
2712            validate_event_payload(
2713                EVENT_KIND_KEY_REVOKE,
2714                &json!({
2715                    "revoked_pubkey": good_pubkey,
2716                    "revoked_at": "2026-05-01T17:00:00Z",
2717                    "replacement_pubkey": "deadbeef",
2718                }),
2719            )
2720            .is_err()
2721        );
2722
2723        // FAIL: replacement equals revoked (no-op rotation).
2724        assert!(
2725            validate_event_payload(
2726                EVENT_KIND_KEY_REVOKE,
2727                &json!({
2728                    "revoked_pubkey": good_pubkey,
2729                    "revoked_at": "2026-05-01T17:00:00Z",
2730                    "replacement_pubkey": good_pubkey,
2731                }),
2732            )
2733            .is_err()
2734        );
2735
2736        // FAIL: revoked_at is non-empty but not a valid ISO-8601 stamp.
2737        // The v0.49.1 validator parses it as RFC-3339 so typos can't
2738        // reach replay verification.
2739        // chrono's parse_from_rfc3339 is intentionally lenient on the
2740        // `T` vs space separator (RFC-3339 §5.6), so we don't include
2741        // that case here — chronologically nonsensical strings still
2742        // fail, which is the bar we care about.
2743        for bad in [
2744            "yesterday",
2745            "2026-13-01T00:00:00Z", // month 13
2746            "2026-05-01",           // date only, no time
2747            "x",
2748        ] {
2749            assert!(
2750                validate_event_payload(
2751                    EVENT_KIND_KEY_REVOKE,
2752                    &json!({
2753                        "revoked_pubkey": good_pubkey,
2754                        "revoked_at": bad,
2755                    }),
2756                )
2757                .is_err(),
2758                "expected revoked_at {bad:?} to fail validation"
2759            );
2760        }
2761    }
2762
2763    /// v0.79.4: per-event attestation validator. Required
2764    /// payload: target_event_id (must start with vev_),
2765    /// attester_id (non-empty), scope_note (non-empty). Optional
2766    /// signature (string), proof_id (vpf_*).
2767    #[test]
2768    fn attestation_recorded_validator() {
2769        // PASS: minimal good payload.
2770        let good = json!({
2771            "target_event_id": "vev_abc",
2772            "attester_id": "reviewer:will-blair",
2773            "scope_note": "Independent re-verification of the Stupp protocol finding."
2774        });
2775        assert!(validate_event_payload(EVENT_KIND_ATTESTATION_RECORDED, &good).is_ok());
2776    }
2777
2778    #[test]
2779    fn validates_policy_auto_admitted_payload() {
2780        // PASS: all binding fields present + well-formed.
2781        let good = json!({
2782            "proposal_id": "vpr_abc",
2783            "claim_digest": "deadbeefdeadbeef",
2784            "attachment_ids": ["vva_a", "vva_b"],
2785            "policy_version": "exact-lane.v1",
2786            "verifier_env_hash": "sha256:cafe"
2787        });
2788        assert!(validate_event_payload(EVENT_KIND_POLICY_AUTO_ADMITTED, &good).is_ok());
2789
2790        // FAIL: the pre-hardening minimal payload (proposal_id only) is now rejected.
2791        let minimal = json!({ "proposal_id": "vpr_abc" });
2792        assert!(validate_event_payload(EVENT_KIND_POLICY_AUTO_ADMITTED, &minimal).is_err());
2793
2794        // PASS: empty attachment_ids — a floor-sufficient admit has no
2795        // attachments; the frozen verifier + faithful binding is the proof, and
2796        // claim_digest + verifier_env_hash are the accountability.
2797        let floor_admit = json!({
2798            "proposal_id": "vpr_abc",
2799            "claim_digest": "deadbeef",
2800            "attachment_ids": [],
2801            "policy_version": "exact-lane.v1",
2802            "verifier_env_hash": "sha256:cafe"
2803        });
2804        assert!(validate_event_payload(EVENT_KIND_POLICY_AUTO_ADMITTED, &floor_admit).is_ok());
2805
2806        // FAIL: a missing claim_digest (the floor accountability) still rejects.
2807        let no_digest = json!({
2808            "proposal_id": "vpr_abc",
2809            "attachment_ids": [],
2810            "policy_version": "exact-lane.v1",
2811            "verifier_env_hash": "sha256:cafe"
2812        });
2813        assert!(validate_event_payload(EVENT_KIND_POLICY_AUTO_ADMITTED, &no_digest).is_err());
2814
2815        // PASS: with optional signature + proof_id.
2816        let with_proof = json!({
2817            "target_event_id": "vev_abc",
2818            "attester_id": "reviewer:will-blair",
2819            "scope_note": "Lean-formalized.",
2820            "scopes": ["domain_relevance", "method_review"],
2821            "reviewer_role": "domain_reviewer",
2822            "orcid": "https://orcid.org/0000-0000-0000-000X",
2823            "ror": "https://ror.org/03yrm5c26",
2824            "attestation_id": "vatt_demo",
2825            "signature": "ed25519:cafebabe",
2826            "proof_id": "vpf_demo"
2827        });
2828        assert!(validate_event_payload(EVENT_KIND_ATTESTATION_RECORDED, &with_proof).is_ok());
2829
2830        // FAIL: target_event_id without vev_ prefix.
2831        let bad_target = json!({
2832            "target_event_id": "something_else",
2833            "attester_id": "reviewer:x",
2834            "scope_note": "x"
2835        });
2836        assert!(validate_event_payload(EVENT_KIND_ATTESTATION_RECORDED, &bad_target).is_err());
2837
2838        // FAIL: empty attester_id.
2839        let no_attester = json!({
2840            "target_event_id": "vev_abc",
2841            "attester_id": "",
2842            "scope_note": "x"
2843        });
2844        assert!(validate_event_payload(EVENT_KIND_ATTESTATION_RECORDED, &no_attester).is_err());
2845
2846        // FAIL: proof_id without vpf_ prefix.
2847        let bad_proof = json!({
2848            "target_event_id": "vev_abc",
2849            "attester_id": "reviewer:x",
2850            "scope_note": "x",
2851            "proof_id": "not_a_vpf"
2852        });
2853        assert!(validate_event_payload(EVENT_KIND_ATTESTATION_RECORDED, &bad_proof).is_err());
2854    }
2855
2856    #[test]
2857    fn event_log_hash_is_independent_of_input_order() {
2858        // ADR 0001 Phase 0a: the integrity commitment must not depend on how
2859        // the events were loaded (packet authored-order vs `.vela/events/`
2860        // filename-order vs a future git per-file layout). event_log_hash
2861        // canonicalizes on the content-addressed event id, so any permutation
2862        // of the same events hashes identically.
2863        let mk = |id: &str, ts: &str| StateEvent {
2864            schema: EVENT_SCHEMA.to_string(),
2865            id: id.to_string(),
2866            kind: "note.added".into(),
2867            target: StateTarget {
2868                r#type: "finding".to_string(),
2869                id: "vf_x".to_string(),
2870            },
2871            actor: StateActor {
2872                id: "reviewer:t".to_string(),
2873                r#type: "human".to_string(),
2874            },
2875            timestamp: ts.to_string(),
2876            reason: "t".to_string(),
2877            before_hash: String::new(),
2878            after_hash: String::new(),
2879            payload: Value::Null,
2880            caveats: vec![],
2881            signature: None,
2882        };
2883        // ids deliberately NOT in timestamp order: proves the canonical order
2884        // is id-sort (load-path stable), not (timestamp, id) replay order.
2885        let a = mk("vev_c", "2026-01-01T00:00:03Z");
2886        let b = mk("vev_a", "2026-01-01T00:00:01Z");
2887        let c = mk("vev_b", "2026-01-01T00:00:02Z");
2888        let forward = vec![a.clone(), b.clone(), c.clone()];
2889        let shuffled = vec![c, a.clone(), b];
2890        assert_eq!(
2891            event_log_hash(&forward),
2892            event_log_hash(&shuffled),
2893            "event_log_hash must be independent of input order"
2894        );
2895        let mut reversed = forward.clone();
2896        reversed.reverse();
2897        assert_eq!(event_log_hash(&forward), event_log_hash(&reversed));
2898        // sanity: it is NOT the trivial empty hash
2899        assert_ne!(event_log_hash(&forward), event_log_hash(&[]));
2900    }
2901}