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