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