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