Skip to main content

vela_protocol/kernel/
reducer.rs

1//! Pure separable reducer over canonical events.
2//!
3//! `apply_event` is the deterministic state-transition function: given a
4//! `Project` and a `StateEvent`, it produces the next `Project`. It does
5//! not construct events, validate proposals, or call into network code.
6//! It is the inverse pole of `proposals::apply_proposal`, which prepares
7//! an event from a proposal and a current state.
8//!
9//! Why this matters: v0 doctrine says "proposal → canonical event →
10//! reducer → replayable frontier state." Until v0.3, the reducer step was
11//! implicit inside `apply_proposal` — replay was hash-walking, not
12//! reduction. Phase C of the v0.3 focusing run pulls the reducer out so a
13//! second implementation can independently reduce a canonical event log
14//! and produce byte-identical state.
15//!
16//! Replay verification (`replay_from_genesis` + `verify_replay`) is the
17//! check that turns "state was claimed to result from these events" into
18//! "state demonstrably results from these events when re-derived from
19//! scratch."
20
21use std::collections::HashMap;
22
23use serde_json::Value;
24
25use crate::bundle::{Annotation, ConfidenceMethod};
26use crate::events::{self, EventKind, StateEvent};
27use crate::project::{self, Project};
28
29/// v0.105: per-replay finding-id index. Keys are content-addressed
30/// finding ids; values are positions into `state.findings`. Replay
31/// builds this once from genesis state and updates it in lockstep
32/// with `finding.asserted` pushes. Per-kind apply functions look up
33/// their target via `idx.get(...)` instead of an O(N) linear scan.
34/// findings are append-only in the substrate (no removals), so the
35/// index never goes stale; positions remain valid for the life of
36/// a replay.
37pub type FindingIndex = HashMap<String, usize>;
38
39/// Build the finding-id index from the current state. O(N) once.
40#[must_use]
41pub fn build_finding_index(state: &Project) -> FindingIndex {
42    state
43        .findings
44        .iter()
45        .enumerate()
46        .map(|(i, f)| (f.id.clone(), i))
47        .collect()
48}
49
50/// Single source of truth for the event kinds whose mutations the
51/// reducer enforces. The no-op anchor `frontier.created` is excluded
52/// because it does not mutate state. Used by:
53///   - the dispatch table in `apply_event` (validated by
54///     `dispatch_handles_every_declared_kind` below)
55///   - the cross-implementation fixture coverage assertion in
56///     `crates/vela-protocol/tests/cross_impl_reducer_fixtures.rs`
57///
58/// If you add a new reducer arm, add it here too. CI will fail if the
59/// dispatch table and this constant disagree, and the cross-impl
60/// fixture coverage test will fail if the new kind isn't exercised by
61/// at least one fixture builder. The hand-maintained mirror is gone.
62pub const REDUCER_MUTATION_KINDS: &[&str] = &[
63    "finding.asserted",
64    "finding.reviewed",
65    "finding.noted",
66    "finding.caveated",
67    "finding.confidence_revised",
68    "finding.rejected",
69    "finding.retracted",
70    "finding.contribution.recorded",
71    "finding.dependency_invalidated",
72    // Generic artifacts: protocol files, trial registry records, source
73    // files, notebooks, and other byte or pointer commitments.
74    "artifact.asserted",
75    "artifact.reviewed",
76    "artifact.retracted",
77    // v0.51: tier.set re-classifies the access_tier on a finding
78    // or artifact. Mutates the matched object's
79    // access_tier field. Replay reproduces the current tier from the
80    // canonical event log alone, no out-of-band classification
81    // table.
82    "tier.set",
83    // v0.56: evidence_atom.locator_repaired sets `locator` on a single
84    // evidence atom and clears the "missing evidence locator" caveat.
85    // Mutates `state.evidence_atoms[i].locator` only. Cross-impl
86    // reducer fixtures whose post-replay digest covers `findings[]`
87    // only treat this as a no-op on finding state. The Rust reducer
88    // still has an explicit arm because skipping unknown kinds would
89    // silently drop the repair from a fresh replay.
90    "evidence_atom.locator_repaired",
91    // v0.57: finding.span_repaired appends one `{section, text}` span
92    // to `state.findings[i].evidence.evidence_spans`. Idempotent under
93    // identical re-application (refuses to append an equal span twice).
94    "finding.span_repaired",
95    // v0.213: Released Diff Pack tracking. Both arms mutate
96    // `state.released_diff_packs`:
97    //   * `diff_pack.released` appends a new ReleasedDiffPackRecord
98    //     (idempotent on pack_id).
99    //   * `diff_pack.reviewed` updates the matching record's verdict
100    //     + verdict_event_id + applied_members + sdk_only_members.
101    "diff_pack.released",
102    "diff_pack.reviewed",
103    // v0.218: Verdict Conflict Resolution. Appends a VerdictConflict
104    // to state.verdict_conflicts (idempotent on conflict_id). T32
105    // pins the accumulation algebra.
106    "verdict_conflict.resolved",
107    // T7: a reviewer's decision on a Contradiction object. Upserts the
108    // resolved Contradiction into state.contradictions (latest per id).
109    "contradiction.resolved",
110    // Supersession flips `flags.superseded` on the *old* finding (the
111    // replacement enters via genesis seeding from the accepted proposal's
112    // payload — the event itself is thin).
113    "finding.superseded",
114    // Causal re-grading replays `assertion.causal_claim` /
115    // `causal_evidence_grade` from the event's `payload.after`.
116    "assertion.reinterpreted_causal",
117    // Statement-faithfulness attestation: upserts a signed vsa_ record
118    // into state.statement_attestations (idempotent by id; the record's
119    // own Ed25519 signature is re-verified on apply).
120    "statement.attested",
121    // Obligation lease: one live lease per obligation; a second claim
122    // while a prior is unexpired is a reducer error. Expiry is computed
123    // against the NEW event's timestamp (the log's own clock), never
124    // wall time — replay stays deterministic.
125    "attempt.claimed",
126    // Priority registration: append a content-addressed statement hash
127    // (idempotent on hash).
128    "statement.registered",
129    // Math-atlas anchor link: upsert/remove a signed val_ record into
130    // state.anchor_links (idempotent by id; signature re-verified on apply).
131    "anchor.attached",
132    "anchor.retracted",
133];
134
135/// Apply one canonical event to `state`, mutating it in place.
136///
137/// The function dispatches on `event.kind` and performs the same
138/// mutations that `proposals::apply_*` performs when constructing the
139/// event. Two implementations of the reducer must therefore agree on the
140/// mutation rules per kind. Those rules are documented in
141/// `docs/PROTOCOL.md` §6 and pinned via canonical hashing.
142pub fn apply_event(state: &mut Project, event: &StateEvent) -> Result<(), String> {
143    let mut idx = build_finding_index(state);
144    apply_event_indexed(state, event, &mut idx)
145}
146
147/// v0.105: indexed dispatch. Used by `replay_from_genesis` so the
148/// finding-id index gets built once and reused across every event.
149/// `apply_event` builds the index lazily for one-off callers.
150pub fn apply_event_indexed(
151    state: &mut Project,
152    event: &StateEvent,
153    idx: &mut FindingIndex,
154) -> Result<(), String> {
155    match &event.kind {
156        // Phase J: `frontier.created` is the genesis event. It carries
157        // identity (its canonical hash IS the frontier_id) but does not
158        // mutate finding state. Replay treats it as a structural
159        // anchor — the chain begins here.
160        EventKind::FrontierCreated => Ok(()),
161        EventKind::FindingAsserted => apply_finding_asserted(state, event, idx),
162        EventKind::FindingReviewed => apply_finding_reviewed(state, event, idx),
163        EventKind::FindingNoted => apply_finding_annotation(state, event, "noted", idx),
164        EventKind::FindingCaveated => apply_finding_annotation(state, event, "caveated", idx),
165        EventKind::SourceTextReviewed => Ok(()),
166        EventKind::FindingConfidenceRevised => apply_finding_confidence_revised(state, event, idx),
167        EventKind::FindingRejected => apply_finding_rejected(state, event, idx),
168        EventKind::FindingRetracted => apply_finding_retracted(state, event, idx),
169        EventKind::FindingContributionRecorded => {
170            apply_finding_contribution_recorded(state, event, idx)
171        }
172        // Phase L: per-dependent cascade event. Replay marks the
173        // dependent as contested and records the upstream chain in an
174        // annotation so a fresh reduce reproduces the post-cascade
175        // state without re-running the propagator.
176        EventKind::FindingDependencyInvalidated => apply_finding_dependency_invalidated(state, event, idx),
177        EventKind::ArtifactAsserted => apply_artifact_asserted(state, event),
178        EventKind::VerifierAttachmentAdded => apply_verifier_attachment_added(state, event),
179        EventKind::ArtifactReviewed => apply_artifact_reviewed(state, event),
180        EventKind::ArtifactRetracted => apply_artifact_retracted(state, event),
181        // v0.51: tier re-classification.
182        EventKind::TierSet => apply_tier_set(state, event),
183        // v0.56: mechanical evidence-atom locator repair.
184        EventKind::EvidenceAtomLocatorRepaired => apply_evidence_atom_locator_repaired(state, event),
185        // v0.57: mechanical finding-level span repair.
186        EventKind::FindingSpanRepaired => apply_finding_span_repaired(state, event, idx),
187        // v0.79.4: per-event attestation. No-op on findings;
188        // attestations live as append-only canonical events
189        // pointing at a target event id.
190        EventKind::AttestationRecorded => Ok(()),
191        // v0.201: a `vsd_*` Scientific Diff Pack was signed, applied,
192        // and is now released. The event is a metadata-only handle —
193        // its payload references the pack id; replay does not mutate
194        // project state because the pack's member proposals already
195        // applied through their own `proposal.accepted` arms. The arm
196        // exists so the event is a first-class handle that
197        // hubs can index by `vsd_*`.
198        EventKind::DiffPackReleased => apply_diff_pack_released(state, event),
199        // v0.205: a reviewer issued a verdict on a `vsd_*` Diff Pack.
200        // The event payload carries (pack_id, verdict, reviewer_actor,
201        // reason). Like `diff_pack.released`, this arm is metadata-
202        // only — member proposals mutate state through their own
203        // existing acceptance paths (proposals.rs). The arm exists
204        // so the verdict is a first-class canonical event the log
205        // pins. Theorem 26 (Diff Pack verdict atomicity) pins the
206        // promoter-side guarantee that accept either applies every
207        // member or none.
208        EventKind::DiffPackReviewed => apply_diff_pack_reviewed(state, event),
209        // v0.218: a verdict-conflict resolution lands on the log.
210        // Append the VerdictConflict record to state.verdict_conflicts
211        // (idempotent on conflict_id).
212        EventKind::VerdictConflictResolved => apply_verdict_conflict_resolved(state, event),
213        // T7: a contradiction resolution lands on the log. Upsert the
214        // resolved Contradiction into state.contradictions by id.
215        EventKind::ContradictionResolved => apply_contradiction_resolved(state, event),
216        // Attempt lifecycle: a signed deposit, then append-only resolutions.
217        EventKind::AttemptDeposited => apply_attempt_deposited(state, event),
218        EventKind::TransferDeposited => apply_transfer_deposited(state, event),
219        EventKind::EndorsementDeposited => apply_endorsement_deposited(state, event),
220        EventKind::AttemptResolved => apply_attempt_resolved(state, event),
221        EventKind::StatementAttested => apply_statement_attested(state, event),
222        EventKind::AnchorAttached => apply_anchor_attached(state, event),
223        EventKind::AnchorRetracted => apply_anchor_retracted(state, event),
224        EventKind::AttemptClaimed => apply_attempt_claimed(state, event),
225        EventKind::StatementRegistered => apply_statement_registered(state, event),
226        // Supersession: the event targets the *old* finding and flips its
227        // `flags.superseded`. The replacement finding's body lives in the
228        // accepted proposal's `payload.new_finding` and enters replay via
229        // genesis seeding (`repo::seed_genesis`), not via this arm — the
230        // event payload is deliberately thin ({proposal_id, new_finding_id}).
231        EventKind::FindingSuperseded => apply_finding_superseded(state, event, idx),
232        // Causal re-grading (`vela finding causal-set`): replays the
233        // claim/grade mutation from the event's `payload.after`.
234        EventKind::AssertionReinterpretedCausal => apply_assertion_reinterpreted_causal(state, event, idx),
235        // Audit-only / writerless kinds. Each is validated at emit time and
236        // appended to the log, but mutates no projected state on replay:
237        // their consumers read the events directly. The threshold,
238        // correction-return, research-trace, and prediction-expiry kinds had
239        // their CLI writers removed in the v0.700 surface cut (zero such
240        // events exist in any live log); `frontier.observation_reviewed` and
241        // `key.revoke` are audit records. `key.revoke` does not mutate the
242        // repository actor registry; Profile v1 freezes that registry until
243        // a separate governed rotation and recovery contract exists. Explicit
244        // arms let historical logs containing either event replay.
245        // A reviewer-tier key's recommend-accept: audit record consumed by
246        // owner/maintainer keys; no projected-state mutation.
247        EventKind::ProposalRecommended
248        | EventKind::FrontierObservationReviewed
249        | EventKind::CorrectionReturnReview
250        | EventKind::ResearchTraceReview
251        | EventKind::KeyRevoke
252        // Reviewer decision records. Audit-only on the FINDING projection:
253        // the accept's effect on state is the domain event it produced
254        // (finding.asserted, …), already replayed by its own arm; the
255        // review.* event records WHO decided and HOW. Proposal `status` is
256        // a separate projection over these events, verified by
257        // `proposals::verify_proposal_decision_parity` — not reconstructed
258        // here, so verify_replay's finding hashes are untouched.
259        | EventKind::ReviewAccepted
260        | EventKind::ReviewRejected
261        | EventKind::ReviewRevisionRequested
262        | EventKind::ProposalWithdrawn
263        | EventKind::ActorRegistrationActivated
264        // policy.auto_admitted: deterministic machine-verified admission (Phase 1A).
265        // Like review.*, it records the decision (WHO/HOW: the frozen verifier + the
266        // audited predicate) without mutating findings — the verifier attachments
267        // already on the frontier define the gate status. No-op on finding hashes.
268        | EventKind::PolicyAutoAdmitted => Ok(()),
269        EventKind::FrontierRepositoryBound => apply_frontier_repository_bound(event),
270        EventKind::Other(other) => Err(format!("reducer: unsupported event kind '{other}'")),
271    }
272}
273
274/// Replay an entire event log from genesis state.
275///
276/// `genesis` is the bootstrap finding set (the state of the frontier at
277/// the moment of compile, before any reviewed transitions). `events` is
278/// the full canonical event log. Returns the materialized `Project` after
279/// applying every event in sequence.
280pub fn replay_from_genesis(
281    genesis: Vec<crate::bundle::FindingBundle>,
282    events: Vec<StateEvent>,
283    name: &str,
284    description: &str,
285    compiled_at: &str,
286    compiler: &str,
287) -> Result<Project, String> {
288    let boundary_errors =
289        crate::frontier_repository::validate_repository_boundary_event_set(&events);
290    if !boundary_errors.is_empty() {
291        return Err(format!(
292            "repository-boundary event set is invalid: {}",
293            boundary_errors.join("; ")
294        ));
295    }
296    let mut state = Project {
297        vela_version: project::VELA_SCHEMA_VERSION.to_string(),
298        schema: project::VELA_SCHEMA_URL.to_string(),
299        frontier_id: None,
300        project: project::ProjectMeta {
301            name: name.to_string(),
302            description: description.to_string(),
303            compiled_at: compiled_at.to_string(),
304            compiler: compiler.to_string(),
305            papers_processed: 0,
306            errors: 0,
307            dependencies: Vec::new(),
308        },
309        stats: project::ProjectStats::default(),
310        findings: genesis,
311        sources: Vec::new(),
312        evidence_atoms: Vec::new(),
313        condition_records: Vec::new(),
314        review_events: Vec::new(),
315        confidence_updates: Vec::new(),
316        events: Vec::new(),
317        proposals: Vec::new(),
318        proof_state: crate::proposals::ProofState::default(),
319        signatures: Vec::new(),
320        actors: Vec::new(),
321        artifacts: Vec::new(),
322        released_diff_packs: Vec::new(),
323        verdict_conflicts: Vec::new(),
324        contradictions: Vec::new(),
325        verifier_attachments: Vec::new(),
326        attempts: Vec::new(),
327        attempt_resolutions: Vec::new(),
328        transfers: Vec::new(),
329        endorsements: Vec::new(),
330        statement_attestations: Vec::new(),
331        anchor_links: Vec::new(),
332        attempt_claims: Vec::new(),
333        statement_registrations: Vec::new(),
334    };
335    crate::sources::materialize_project(&mut state);
336    // v0.105: build the finding-id index once, reuse across every
337    // event. Replay is the hot path and was previously O(N^2) (each
338    // per-kind apply linear-scanned state.findings); with the index
339    // it is O(N).
340    let mut idx = build_finding_index(&state);
341    // v0.106.6: take events by value and move each one into
342    // state.events instead of cloning. Pre-v0.106.6 the input was
343    // &[StateEvent] and the loop did event.clone() on every
344    // iteration, which walked the heap-allocated payload Value tree
345    // for each event. At N=20k events this was the next bottleneck
346    // after the v0.105 O(N^2) scan was removed.
347    for event in events {
348        apply_event_indexed(&mut state, &event, &mut idx)?;
349        state.events.push(event);
350    }
351    project::recompute_stats(&mut state);
352    Ok(state)
353}
354
355fn apply_frontier_repository_bound(event: &StateEvent) -> Result<(), String> {
356    let payload = crate::frontier_repository::repository_boundary_payload_from_event_shape(event)?;
357    crate::frontier_repository::verify_repository_boundary_signature_only(
358        event,
359        &payload.administrator_public_key,
360    )?;
361    Ok(())
362}
363
364/// Canonical replay order: (timestamp, id). This is the same order
365/// `events::replay_report` uses for chain verification. Timestamps are
366/// RFC3339 with microseconds; the content-addressed id is the
367/// deterministic tiebreak.
368pub fn sorted_for_replay(events: &[StateEvent]) -> Vec<StateEvent> {
369    let mut sorted: Vec<StateEvent> = events.to_vec();
370    sorted.sort_by(|a, b| a.timestamp.cmp(&b.timestamp).then_with(|| a.id.cmp(&b.id)));
371    sorted
372}
373
374/// Synthesize the genesis finding set from the event log plus the
375/// proposal payload store. The protocol's `finding.asserted` events are
376/// deliberately thin (`{proposal_id}`); the asserted body lives in the
377/// accepted proposal's `payload.finding` (or `payload.new_finding` for a
378/// supersession) and is cryptographically pinned: the assert event's
379/// `after_hash` is `finding_hash` of the body pushed at accept time.
380/// Every hydration is verified against that hash — a tampered or missing
381/// proposal becomes a diagnostic, never a silently wrong finding.
382///
383/// Events whose payload carries `finding` inline (v0.3 genesis form) are
384/// NOT seeded here: the reducer's `finding.asserted` arm applies them
385/// during replay.
386pub fn seed_genesis(
387    events_sorted: &[StateEvent],
388    proposals: &[crate::proposals::StateProposal],
389) -> (Vec<crate::bundle::FindingBundle>, Vec<String>) {
390    use crate::bundle::FindingBundle;
391    let by_id: HashMap<&str, &crate::proposals::StateProposal> =
392        proposals.iter().map(|p| (p.id.as_str(), p)).collect();
393    let mut genesis: Vec<FindingBundle> = Vec::new();
394    let mut diagnostics: Vec<String> = Vec::new();
395    for ev in events_sorted {
396        let (payload_key, is_supersede) = match ev.kind.as_str() {
397            "finding.asserted" => ("finding", false),
398            "finding.superseded" => ("new_finding", true),
399            _ => continue,
400        };
401        if !is_supersede && ev.payload.get("finding").is_some() {
402            // Inline (v0.3 genesis) form: the reducer arm applies it.
403            continue;
404        }
405        let Some(pid) = ev.payload.get("proposal_id").and_then(Value::as_str) else {
406            diagnostics.push(format!(
407                "{}: {} carries neither an inline body nor a proposal_id",
408                ev.id, ev.kind
409            ));
410            continue;
411        };
412        let Some(proposal) = by_id.get(pid) else {
413            diagnostics.push(format!(
414                "{}: {} references proposal {pid}, which is not in the proposal store",
415                ev.id, ev.kind
416            ));
417            continue;
418        };
419        let Some(body) = proposal.payload.get(payload_key) else {
420            diagnostics.push(format!(
421                "{}: proposal {pid} has no payload.{payload_key} to hydrate from",
422                ev.id
423            ));
424            continue;
425        };
426        let finding: FindingBundle = match serde_json::from_value(body.clone()) {
427            Ok(f) => f,
428            Err(e) => {
429                diagnostics.push(format!(
430                    "{}: proposal {pid} payload.{payload_key} does not deserialize: {e}",
431                    ev.id
432                ));
433                continue;
434            }
435        };
436        // The pin: the assert event's after_hash is finding_hash of the
437        // body as pushed (links excluded from the hash, so the writer's
438        // auto-injected supersedes link cannot break it). For
439        // finding.superseded the after_hash covers the OLD finding, so
440        // the new body is hydrated unverified-by-hash but is still
441        // confined to the signed, content-addressed proposal store.
442        if !is_supersede {
443            let h = events::finding_hash(&finding);
444            if h != ev.after_hash {
445                diagnostics.push(format!(
446                    "{}: hydrated body hash {h} != event after_hash {} (proposal {pid} tampered or stale)",
447                    ev.id, ev.after_hash
448                ));
449                continue;
450            }
451        }
452        if genesis.iter().any(|g| g.id == finding.id) {
453            continue; // idempotent under duplicate asserts
454        }
455        genesis.push(finding);
456    }
457    (genesis, diagnostics)
458}
459
460/// One full reducer replay of a loaded project's own event log: sort a
461/// copy of the events into canonical replay order, seed genesis from the
462/// proposal payload store, and run `replay_from_genesis`. The loader
463/// grafts every event-derived collection from the result — this is the
464/// single code path that makes "loader = reducer" true. Hydration
465/// diagnostics are not fatal here (a finding that fails to hydrate is
466/// simply absent from the replayed copy); `verify_replay` is where they
467/// become check failures.
468pub fn replayed_projection(state: &Project) -> Result<Project, String> {
469    let sorted = sorted_for_replay(&state.events);
470    let (genesis, _diagnostics, _remnants) = seed_genesis_with_remnants(state, &sorted);
471    replay_from_genesis(
472        genesis,
473        sorted,
474        &state.project.name,
475        &state.project.description,
476        &state.project.compiled_at,
477        &state.project.compiler,
478    )
479}
480
481/// Genesis = hydrated asserts (from the proposal payload store) plus
482/// *genesis remnants*: cached findings with no assert/supersede event
483/// anywhere in the log. Remnants predate the event-first discipline (or
484/// were assembled directly, as in tests); they cannot be replayed into
485/// existence, but later events may target them, so both the loader and
486/// the verifier must seed them or replay would reject their own log.
487/// Returns (genesis, hydration diagnostics, remnant count).
488pub fn seed_genesis_with_remnants(
489    state: &Project,
490    events_sorted: &[StateEvent],
491) -> (Vec<crate::bundle::FindingBundle>, Vec<String>, usize) {
492    let (mut genesis, diagnostics) = seed_genesis(events_sorted, &state.proposals);
493    let evented_ids: std::collections::HashSet<&str> = events_sorted
494        .iter()
495        .filter(|e| matches!(e.kind.as_str(), "finding.asserted" | "finding.superseded"))
496        .flat_map(|e| {
497            let mut ids = vec![e.target.id.as_str()];
498            if let Some(nid) = e.payload.get("new_finding_id").and_then(Value::as_str) {
499                ids.push(nid);
500            }
501            ids
502        })
503        .collect();
504    let mut remnants = 0usize;
505    for f in &state.findings {
506        if !evented_ids.contains(f.id.as_str()) && !genesis.iter().any(|g| g.id == f.id) {
507            genesis.push(f.clone());
508            remnants += 1;
509        }
510    }
511    (genesis, diagnostics, remnants)
512}
513
514/// Order-independent digest over a finding set (ids sorted, links
515/// excluded via `finding_hash`). This is the comparison surface of
516/// `verify_replay`: the full `snapshot_hash` covers loader-only state
517/// (proposals, actors, stats) that a pure replay can never reproduce,
518/// so replayed-vs-materialized equality is only meaningful over the
519/// findings themselves.
520fn findings_digest(findings: &[crate::bundle::FindingBundle]) -> String {
521    let mut pairs: Vec<(String, String)> = findings
522        .iter()
523        .map(|f| (f.id.clone(), events::finding_hash(f)))
524        .collect();
525    pairs.sort();
526    let joined = pairs
527        .iter()
528        .map(|(id, h)| format!("{id}:{h}"))
529        .collect::<Vec<_>>()
530        .join("\n");
531    use sha2::Digest;
532    hex::encode(sha2::Sha256::digest(joined.as_bytes()))
533}
534
535/// Verify that the materialized `state` is reproducible from its own
536/// event log: seed genesis from the proposal payload store, replay every
537/// event through the one reducer, and compare per-finding
538/// `finding_hash` between the replayed and materialized findings.
539///
540/// This is the load-bearing check that turns Vela's replay claim into a
541/// verifiable invariant — the loader and the reducer can no longer
542/// drift apart silently.
543pub fn verify_replay(state: &Project) -> ReplayVerification {
544    if state.events.is_empty() {
545        let d = findings_digest(&state.findings);
546        return ReplayVerification {
547            ok: true,
548            replayed_snapshot_hash: d.clone(),
549            materialized_snapshot_hash: d,
550            diffs: Vec::new(),
551            note: "no events; replay is identity".to_string(),
552        };
553    }
554    let sorted = sorted_for_replay(&state.events);
555    let (genesis, mut diffs, remnants) = seed_genesis_with_remnants(state, &sorted);
556    let replayed = match replay_from_genesis(
557        genesis,
558        sorted,
559        &state.project.name,
560        &state.project.description,
561        &state.project.compiled_at,
562        &state.project.compiler,
563    ) {
564        Ok(p) => p,
565        Err(e) => {
566            return ReplayVerification {
567                ok: false,
568                replayed_snapshot_hash: String::new(),
569                materialized_snapshot_hash: findings_digest(&state.findings),
570                diffs: vec![format!("replay failed: {e}")],
571                note: "event log does not replay through the reducer".to_string(),
572            };
573        }
574    };
575    let replayed_by_id: HashMap<&str, &crate::bundle::FindingBundle> = replayed
576        .findings
577        .iter()
578        .map(|f| (f.id.as_str(), f))
579        .collect();
580    for cached in &state.findings {
581        match replayed_by_id.get(cached.id.as_str()) {
582            None => diffs.push(format!(
583                "finding {} is materialized but absent from replay (no assert event hydrates it)",
584                cached.id
585            )),
586            Some(rep) => {
587                let ch = events::finding_hash(cached);
588                let rh = events::finding_hash(rep);
589                if ch != rh {
590                    diffs.push(format!(
591                        "finding {} diverges: materialized {ch} vs replayed {rh}",
592                        cached.id
593                    ));
594                }
595            }
596        }
597    }
598    for rep in &replayed.findings {
599        if !state.findings.iter().any(|c| c.id == rep.id) {
600            diffs.push(format!(
601                "finding {} is replayable from the log but absent from the materialized state",
602                rep.id
603            ));
604        }
605    }
606    let ok = diffs.is_empty();
607    ReplayVerification {
608        ok,
609        replayed_snapshot_hash: findings_digest(&replayed.findings),
610        materialized_snapshot_hash: findings_digest(&state.findings),
611        diffs,
612        note: if ok {
613            format!(
614                "replayed {} event(s) over {} seeded finding(s) ({} genesis remnant(s)); materialized state reproduced",
615                state.events.len(),
616                replayed.findings.len(),
617                remnants
618            )
619        } else {
620            "materialized state is NOT reproducible from the event log".to_string()
621        },
622    }
623}
624
625#[derive(Debug, Clone)]
626pub struct ReplayVerification {
627    pub ok: bool,
628    pub replayed_snapshot_hash: String,
629    pub materialized_snapshot_hash: String,
630    pub diffs: Vec<String>,
631    pub note: String,
632}
633
634/// v0.701: per-finding provenance classification for the event-sourcing
635/// migration. Where `verify_replay` *proves* the materialized findings are
636/// reducible, this reports *why* each one is reducible — exactly which
637/// on-disk derived view still pins a finding to git — so a migration can
638/// target the gap and a decommit can be justified one bucket at a time.
639///
640/// Each finding lands in exactly one bucket (inline takes precedence, so a
641/// finding asserted-by-proposal then superseded-inline counts as inline —
642/// its current body is in the log):
643///
644/// - `inline`: an assert/supersede event carries the full body in its
645///   payload; reducible from `events/` alone.
646/// - `proposal_backed`: an assert event exists but hydrates its body from
647///   the signed proposal store; still needs `proposals/`.
648/// - `remnant`: no assert/supersede event targets it; seeded straight from
649///   the `findings/` cache. Predates the event-first discipline.
650///
651/// A frontier is *fully event-sourced* iff `proposal_backed` and `remnant`
652/// are both empty: then `events/` reduces to its whole finding set and the
653/// derived views are pure caches, safe to decommit. This is the explanatory
654/// companion to `verify_replay`, not a trust gate — `verify_replay` remains
655/// the exact, byte-parity invariant.
656#[derive(Debug, Clone, Default)]
657pub struct ProvenanceReport {
658    pub inline: Vec<String>,
659    pub proposal_backed: Vec<String>,
660    pub remnant: Vec<String>,
661    pub actors: usize,
662    pub proposals: usize,
663}
664
665impl ProvenanceReport {
666    /// True when every materialized finding is reducible from the event log
667    /// alone (no proposal-backed bodies, no pre-event remnants).
668    pub fn fully_event_sourced(&self) -> bool {
669        self.proposal_backed.is_empty() && self.remnant.is_empty()
670    }
671}
672
673/// Classify every materialized finding by how its body enters the log.
674/// Mirrors the `seed_genesis` dispatch: an inline body (`payload.finding`
675/// / `payload.new_finding`) vs a proposal reference (`payload.proposal_id`).
676pub fn classify_provenance(state: &Project) -> ProvenanceReport {
677    use std::collections::HashSet;
678    let mut inline: HashSet<&str> = HashSet::new();
679    let mut proposal_backed: HashSet<&str> = HashSet::new();
680    for ev in &state.events {
681        match ev.kind.as_str() {
682            "finding.asserted" => {
683                let id = ev.target.id.as_str();
684                if ev.payload.get("finding").is_some() {
685                    inline.insert(id);
686                } else if ev.payload.get("proposal_id").is_some() {
687                    proposal_backed.insert(id);
688                }
689            }
690            "finding.superseded" => {
691                if let Some(nid) = ev.payload.get("new_finding_id").and_then(Value::as_str) {
692                    if ev.payload.get("new_finding").is_some() {
693                        inline.insert(nid);
694                    } else if ev.payload.get("proposal_id").is_some() {
695                        proposal_backed.insert(nid);
696                    }
697                }
698            }
699            _ => {}
700        }
701    }
702    let mut report = ProvenanceReport {
703        actors: state.actors.len(),
704        proposals: state.proposals.len(),
705        ..Default::default()
706    };
707    for f in &state.findings {
708        let id = f.id.as_str();
709        if inline.contains(id) {
710            report.inline.push(f.id.clone());
711        } else if proposal_backed.contains(id) {
712            report.proposal_backed.push(f.id.clone());
713        } else {
714            report.remnant.push(f.id.clone());
715        }
716    }
717    report
718}
719
720// --- per-kind reducer rules ---------------------------------------------------
721
722fn apply_finding_asserted(
723    state: &mut Project,
724    event: &StateEvent,
725    idx: &mut FindingIndex,
726) -> Result<(), String> {
727    // For a v0.3 frontier emitting genesis events, finding.asserted carries
728    // the full finding in payload.finding; for legacy frontiers replay is
729    // a no-op (the finding was already materialized at genesis).
730    if let Some(finding_value) = event.payload.get("finding") {
731        let finding: crate::bundle::FindingBundle =
732            serde_json::from_value(finding_value.clone())
733                .map_err(|e| format!("reducer: invalid finding.asserted payload.finding: {e}"))?;
734        if idx.contains_key(&finding.id) {
735            return Ok(());
736        }
737        let position = state.findings.len();
738        idx.insert(finding.id.clone(), position);
739        state.findings.push(finding);
740    }
741    Ok(())
742}
743
744fn apply_finding_reviewed(
745    state: &mut Project,
746    event: &StateEvent,
747    index: &mut FindingIndex,
748) -> Result<(), String> {
749    let id = event.target.id.as_str();
750    let status = event
751        .payload
752        .get("status")
753        .and_then(Value::as_str)
754        .ok_or("reducer: finding.reviewed missing payload.status")?;
755    let idx = *index
756        .get(id)
757        .ok_or_else(|| format!("reducer: finding.reviewed targets unknown finding {id}"))?;
758    use crate::bundle::ReviewState;
759    let new_state = match status {
760        "accepted" | "approved" => ReviewState::Accepted,
761        "contested" => ReviewState::Contested,
762        "needs_revision" => ReviewState::NeedsRevision,
763        "rejected" => ReviewState::Rejected,
764        other => return Err(format!("reducer: unsupported review status '{other}'")),
765    };
766    state.findings[idx].flags.contested = new_state.implies_contested();
767    state.findings[idx].flags.review_state = Some(new_state);
768    Ok(())
769}
770
771fn apply_finding_annotation(
772    state: &mut Project,
773    event: &StateEvent,
774    _kind_label: &str,
775    index: &mut FindingIndex,
776) -> Result<(), String> {
777    let id = event.target.id.as_str();
778    let text = event
779        .payload
780        .get("text")
781        .and_then(Value::as_str)
782        .ok_or("reducer: annotation event missing payload.text")?;
783    let annotation_id = event
784        .payload
785        .get("annotation_id")
786        .and_then(Value::as_str)
787        .ok_or("reducer: annotation event missing payload.annotation_id")?;
788    let idx = *index
789        .get(id)
790        .ok_or_else(|| format!("reducer: annotation event targets unknown finding {id}"))?;
791    if state.findings[idx]
792        .annotations
793        .iter()
794        .any(|a| a.id == annotation_id)
795    {
796        return Ok(());
797    }
798    // Phase β (v0.6): pass through optional structured provenance from
799    // the event payload to the materialized annotation. The validator in
800    // `events::validate_event_payload` already rejected all-empty
801    // provenance objects, so deserialization here is best-effort —
802    // unknown shapes silently drop to None rather than failing the
803    // whole reduce.
804    let provenance = event
805        .payload
806        .get("provenance")
807        .and_then(|v| serde_json::from_value::<crate::bundle::ProvenanceRef>(v.clone()).ok());
808    state.findings[idx].annotations.push(Annotation {
809        id: annotation_id.to_string(),
810        text: text.to_string(),
811        author: event.actor.id.clone(),
812        timestamp: event.timestamp.clone(),
813        provenance,
814    });
815    Ok(())
816}
817
818fn apply_finding_confidence_revised(
819    state: &mut Project,
820    event: &StateEvent,
821    index: &mut FindingIndex,
822) -> Result<(), String> {
823    let id = event.target.id.as_str();
824    let new_score = event
825        .payload
826        .get("new_score")
827        .and_then(Value::as_f64)
828        .ok_or("reducer: finding.confidence_revised missing payload.new_score")?;
829    let previous = event
830        .payload
831        .get("previous_score")
832        .and_then(Value::as_f64)
833        .unwrap_or(0.0);
834    let idx = *index
835        .get(id)
836        .ok_or_else(|| format!("reducer: confidence_revised targets unknown finding {id}"))?;
837    let updated_at = event
838        .payload
839        .get("updated_at")
840        .and_then(Value::as_str)
841        .map(str::to_string)
842        .unwrap_or_else(|| event.timestamp.clone());
843    state.findings[idx].confidence.score = new_score;
844    state.findings[idx].confidence.basis = format!(
845        "expert revision from {:.3} to {:.3}: {}",
846        previous, new_score, event.reason
847    );
848    state.findings[idx].confidence.method = ConfidenceMethod::ExpertJudgment;
849    state.findings[idx].updated = Some(updated_at);
850    Ok(())
851}
852
853fn apply_finding_rejected(
854    state: &mut Project,
855    event: &StateEvent,
856    index: &mut FindingIndex,
857) -> Result<(), String> {
858    let id = event.target.id.as_str();
859    let idx = *index
860        .get(id)
861        .ok_or_else(|| format!("reducer: finding.rejected targets unknown finding {id}"))?;
862    state.findings[idx].flags.contested = true;
863    Ok(())
864}
865
866fn apply_finding_retracted(
867    state: &mut Project,
868    event: &StateEvent,
869    index: &mut FindingIndex,
870) -> Result<(), String> {
871    let id = event.target.id.as_str();
872    let idx = *index
873        .get(id)
874        .ok_or_else(|| format!("reducer: finding.retracted targets unknown finding {id}"))?;
875    state.findings[idx].flags.retracted = true;
876    Ok(())
877}
878
879/// Append a claim-granularity attribution to a finding's provenance. Purely
880/// descriptive: it touches no flag, no confidence, no review state, and the gate
881/// never reads `contributions[]` as evidence. Idempotent replay — a contribution
882/// already present (same unit + agent + role) is not duplicated.
883fn apply_finding_contribution_recorded(
884    state: &mut Project,
885    event: &StateEvent,
886    index: &mut FindingIndex,
887) -> Result<(), String> {
888    let id = event.target.id.as_str();
889    let idx = *index.get(id).ok_or_else(|| {
890        format!("reducer: finding.contribution.recorded targets unknown finding {id}")
891    })?;
892    let contribution: crate::bundle::Contribution = serde_json::from_value(
893        event
894            .payload
895            .get("contribution")
896            .cloned()
897            .ok_or("reducer: finding.contribution.recorded missing payload.contribution")?,
898    )
899    .map_err(|e| format!("reducer: malformed contribution: {e}"))?;
900    contribution.validate()?;
901    let existing = &mut state.findings[idx].provenance.contributions;
902    if !existing.iter().any(|c| {
903        c.unit == contribution.unit
904            && c.agent_id == contribution.agent_id
905            && c.role == contribution.role
906    }) {
907        existing.push(contribution);
908    }
909    Ok(())
910}
911
912/// `finding.superseded` targets the OLD finding and flips its
913/// `flags.superseded` (idempotent). The replacement finding is NOT
914/// applied here: the event payload is thin (`{proposal_id,
915/// new_finding_id}`) and the replacement's body lives in the accepted
916/// proposal's `payload.new_finding`, entering replay as a genesis seed.
917/// Note: the writer (`proposals::apply_supersede`) also auto-injects a
918/// `supersedes` link into the replacement; links are excluded from
919/// `finding_hash`, so replay verification is unaffected by that
920/// injection.
921fn apply_finding_superseded(
922    state: &mut Project,
923    event: &StateEvent,
924    index: &mut FindingIndex,
925) -> Result<(), String> {
926    let id = event.target.id.as_str();
927    let idx = *index
928        .get(id)
929        .ok_or_else(|| format!("reducer: finding.superseded targets unknown finding {id}"))?;
930    state.findings[idx].flags.superseded = true;
931    Ok(())
932}
933
934/// `assertion.reinterpreted_causal` replays the causal re-grading from
935/// the event's `payload.after` (`{claim, grade}`), mirroring the writer
936/// in `state::causal_set`. Invalid vocabulary is an error — the payload
937/// was validated at emit time, so a mismatch here means a corrupted log.
938fn apply_assertion_reinterpreted_causal(
939    state: &mut Project,
940    event: &StateEvent,
941    index: &mut FindingIndex,
942) -> Result<(), String> {
943    use crate::bundle::{CausalClaim, CausalEvidenceGrade};
944    let id = event.target.id.as_str();
945    let idx = *index.get(id).ok_or_else(|| {
946        format!("reducer: assertion.reinterpreted_causal targets unknown finding {id}")
947    })?;
948    let after = event
949        .payload
950        .get("after")
951        .ok_or("reducer: assertion.reinterpreted_causal missing payload.after")?;
952    let claim = after
953        .get("claim")
954        .and_then(Value::as_str)
955        .ok_or("reducer: assertion.reinterpreted_causal missing payload.after.claim")?;
956    let parsed_claim = match claim {
957        "correlation" => CausalClaim::Correlation,
958        "mediation" => CausalClaim::Mediation,
959        "intervention" => CausalClaim::Intervention,
960        other => return Err(format!("reducer: invalid causal claim '{other}'")),
961    };
962    let parsed_grade = match after.get("grade").and_then(Value::as_str) {
963        None => None,
964        Some("rct") => Some(CausalEvidenceGrade::Rct),
965        Some("quasi_experimental") => Some(CausalEvidenceGrade::QuasiExperimental),
966        Some("observational") => Some(CausalEvidenceGrade::Observational),
967        Some("theoretical") => Some(CausalEvidenceGrade::Theoretical),
968        Some(other) => return Err(format!("reducer: invalid causal evidence grade '{other}'")),
969    };
970    state.findings[idx].assertion.causal_claim = Some(parsed_claim);
971    if let Some(g) = parsed_grade {
972        state.findings[idx].assertion.causal_evidence_grade = Some(g);
973    }
974    Ok(())
975}
976
977fn apply_finding_dependency_invalidated(
978    state: &mut Project,
979    event: &StateEvent,
980    index: &mut FindingIndex,
981) -> Result<(), String> {
982    let id = event.target.id.as_str();
983    let upstream = event
984        .payload
985        .get("upstream_finding_id")
986        .and_then(Value::as_str)
987        .unwrap_or("?");
988    let depth = event
989        .payload
990        .get("depth")
991        .and_then(Value::as_u64)
992        .unwrap_or(1);
993    let idx = *index.get(id).ok_or_else(|| {
994        format!("reducer: finding.dependency_invalidated targets unknown finding {id}")
995    })?;
996    state.findings[idx].flags.contested = true;
997    let annotation_id = format!("ann_dep_{}_{}", &event.id[4..], depth);
998    if !state.findings[idx]
999        .annotations
1000        .iter()
1001        .any(|a| a.id == annotation_id)
1002    {
1003        state.findings[idx].annotations.push(Annotation {
1004            id: annotation_id,
1005            text: format!("Upstream {upstream} retracted (cascade depth {depth})."),
1006            author: event.actor.id.clone(),
1007            timestamp: event.timestamp.clone(),
1008            provenance: None,
1009        });
1010    }
1011    Ok(())
1012}
1013
1014fn apply_artifact_asserted(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1015    let artifact_value = event
1016        .payload
1017        .get("artifact")
1018        .ok_or("reducer: artifact.asserted missing payload.artifact")?;
1019    let artifact: crate::bundle::Artifact = serde_json::from_value(artifact_value.clone())
1020        .map_err(|e| format!("reducer: invalid artifact.asserted payload: {e}"))?;
1021    if state.artifacts.iter().any(|a| a.id == artifact.id) {
1022        return Ok(());
1023    }
1024    state.artifacts.push(artifact);
1025    Ok(())
1026}
1027
1028/// Append a verifier attachment (target = `vf_…`) to the sidecar collection.
1029/// Idempotent on the content-addressed `vva_` id. The per-finding trust-gate
1030/// status is derived from these on read (export), never stored here.
1031fn apply_verifier_attachment_added(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1032    let value = event
1033        .payload
1034        .get("attachment")
1035        .ok_or("reducer: verifier_attachment.added missing payload.attachment")?;
1036    let att: crate::verifier_attachment::VerifierAttachment = serde_json::from_value(value.clone())
1037        .map_err(|e| format!("reducer: invalid verifier_attachment.added payload: {e}"))?;
1038    // Re-verify the embedded object's content-addressed id on apply, exactly as
1039    // every sibling object reducer does (this arm previously skipped it, leaving
1040    // a forged-id attachment landable). The gate's G4 id-integrity check is the
1041    // second line of defense; this is the first.
1042    att.verify()
1043        .map_err(|e| format!("reducer: verifier_attachment.added failed id-integrity: {e}"))?;
1044    if state.verifier_attachments.iter().any(|a| a.id == att.id) {
1045        return Ok(());
1046    }
1047    state.verifier_attachments.push(att);
1048    Ok(())
1049}
1050
1051fn apply_artifact_reviewed(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1052    let id = event.target.id.as_str();
1053    let status = event
1054        .payload
1055        .get("status")
1056        .and_then(Value::as_str)
1057        .ok_or("reducer: artifact.reviewed missing payload.status")?;
1058    use crate::bundle::ReviewState;
1059    let new_state = match status {
1060        "accepted" | "approved" => ReviewState::Accepted,
1061        "contested" => ReviewState::Contested,
1062        "needs_revision" => ReviewState::NeedsRevision,
1063        "rejected" => ReviewState::Rejected,
1064        other => return Err(format!("reducer: unsupported review status '{other}'")),
1065    };
1066    let idx = state
1067        .artifacts
1068        .iter()
1069        .position(|a| a.id == id)
1070        .ok_or_else(|| format!("reducer: artifact.reviewed targets unknown artifact {id}"))?;
1071    state.artifacts[idx].review_state = Some(new_state);
1072    Ok(())
1073}
1074
1075fn apply_artifact_retracted(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1076    let id = event.target.id.as_str();
1077    let idx = state
1078        .artifacts
1079        .iter()
1080        .position(|a| a.id == id)
1081        .ok_or_else(|| format!("reducer: artifact.retracted targets unknown artifact {id}"))?;
1082    state.artifacts[idx].retracted = true;
1083    Ok(())
1084}
1085
1086/// v0.51: Apply a `tier.set` event. Re-classifies the access_tier on
1087/// the matched finding / artifact. The validator
1088/// has already checked the object_type and tier strings; here we
1089/// just locate the object and mutate.
1090fn apply_tier_set(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1091    let object_type = event
1092        .payload
1093        .get("object_type")
1094        .and_then(Value::as_str)
1095        .ok_or("reducer: tier.set missing payload.object_type")?;
1096    let object_id = event
1097        .payload
1098        .get("object_id")
1099        .and_then(Value::as_str)
1100        .ok_or("reducer: tier.set missing payload.object_id")?;
1101    let new_tier_str = event
1102        .payload
1103        .get("new_tier")
1104        .and_then(Value::as_str)
1105        .ok_or("reducer: tier.set missing payload.new_tier")?;
1106    let new_tier = crate::access_tier::AccessTier::parse(new_tier_str)
1107        .map_err(|e| format!("reducer: tier.set {e}"))?;
1108    match object_type {
1109        "finding" => {
1110            let idx = state
1111                .findings
1112                .iter()
1113                .position(|f| f.id == object_id)
1114                .ok_or_else(|| format!("reducer: tier.set targets unknown finding {object_id}"))?;
1115            state.findings[idx].access_tier = new_tier;
1116        }
1117        "artifact" => {
1118            let idx = state
1119                .artifacts
1120                .iter()
1121                .position(|a| a.id == object_id)
1122                .ok_or_else(|| format!("reducer: tier.set targets unknown artifact {object_id}"))?;
1123            state.artifacts[idx].access_tier = new_tier;
1124        }
1125        other => {
1126            return Err(format!(
1127                "reducer: tier.set object_type '{other}' must be one of finding, artifact"
1128            ));
1129        }
1130    }
1131    Ok(())
1132}
1133
1134/// v0.213: append a ReleasedDiffPackRecord to
1135/// `state.released_diff_packs` when a `diff_pack.released` event
1136/// lands on the canonical log. Idempotent on pack_id — re-applying
1137/// the same released event is a no-op so hub re-sync stays
1138/// clean. Theorem 29 pins the accumulation algebra.
1139fn apply_diff_pack_released(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1140    use crate::released_diff_pack::ReleasedDiffPackRecord;
1141
1142    let pack_id = event
1143        .payload
1144        .get("pack_id")
1145        .and_then(Value::as_str)
1146        .ok_or("diff_pack.released event missing payload.pack_id")?;
1147    if !pack_id.starts_with("vsd_") {
1148        return Err(format!(
1149            "diff_pack.released event payload.pack_id must start with `vsd_`, got `{pack_id}`"
1150        ));
1151    }
1152    if state
1153        .released_diff_packs
1154        .iter()
1155        .any(|r| r.pack_id == pack_id)
1156    {
1157        return Ok(());
1158    }
1159    let frontier_id = event
1160        .payload
1161        .get("frontier_id")
1162        .and_then(Value::as_str)
1163        .unwrap_or("")
1164        .to_string();
1165    let summary = event
1166        .payload
1167        .get("summary")
1168        .and_then(Value::as_str)
1169        .unwrap_or("")
1170        .to_string();
1171    let aggregate_kind = event
1172        .payload
1173        .get("aggregate_kind")
1174        .and_then(Value::as_str)
1175        .unwrap_or("")
1176        .to_string();
1177    let member_proposals: Vec<String> = event
1178        .payload
1179        .get("members")
1180        .and_then(Value::as_array)
1181        .map(|a| {
1182            a.iter()
1183                .filter_map(Value::as_str)
1184                .map(String::from)
1185                .collect()
1186        })
1187        .unwrap_or_default();
1188    state
1189        .released_diff_packs
1190        .push(ReleasedDiffPackRecord::from_released_event(
1191            pack_id.to_string(),
1192            frontier_id,
1193            summary,
1194            aggregate_kind,
1195            event.timestamp.clone(),
1196            event.id.clone(),
1197            member_proposals,
1198        ));
1199    Ok(())
1200}
1201
1202/// v0.213: update the matching ReleasedDiffPackRecord when a
1203/// `diff_pack.reviewed` event lands. Sets verdict +
1204/// verdict_event_id + reviewer_actor + applied_members +
1205/// sdk_only_members from the payload. Idempotent under
1206/// re-application: re-applying the same verdict to the same
1207/// record produces no further change.
1208///
1209/// If no ReleasedDiffPackRecord exists for the pack_id yet (the
1210/// release event has not been replayed, or the pack was promoted
1211/// without first emitting `diff_pack.released`), the function
1212/// creates a record on the fly from the verdict event's payload
1213/// so the log stays self-sufficient.
1214fn apply_diff_pack_reviewed(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1215    use crate::released_diff_pack::{ReleasedDiffPackRecord, ReleasedVerdict};
1216
1217    let pack_id = event
1218        .payload
1219        .get("pack_id")
1220        .and_then(Value::as_str)
1221        .ok_or("diff_pack.reviewed event missing payload.pack_id")?
1222        .to_string();
1223    if !pack_id.starts_with("vsd_") {
1224        return Err(format!(
1225            "diff_pack.reviewed event payload.pack_id must start with `vsd_`, got `{pack_id}`"
1226        ));
1227    }
1228    let verdict_str = event
1229        .payload
1230        .get("verdict")
1231        .and_then(Value::as_str)
1232        .ok_or("diff_pack.reviewed event missing payload.verdict")?;
1233    let verdict = ReleasedVerdict::from_str_ci(verdict_str).ok_or_else(|| {
1234        format!(
1235            "diff_pack.reviewed event payload.verdict must be accept|reject|revise, got `{verdict_str}`"
1236        )
1237    })?;
1238    let reviewer_actor = event
1239        .payload
1240        .get("reviewer_actor")
1241        .and_then(Value::as_str)
1242        .unwrap_or(&event.actor.id)
1243        .to_string();
1244    let applied: Vec<String> = event
1245        .payload
1246        .get("applied_members")
1247        .and_then(Value::as_array)
1248        .map(|a| {
1249            a.iter()
1250                .filter_map(|v| v.as_str().map(String::from))
1251                .collect()
1252        })
1253        .unwrap_or_default();
1254    let sdk_only: Vec<String> = event
1255        .payload
1256        .get("sdk_only_members")
1257        .and_then(Value::as_array)
1258        .map(|a| {
1259            a.iter()
1260                .filter_map(|v| v.as_str().map(String::from))
1261                .collect()
1262        })
1263        .unwrap_or_default();
1264
1265    if let Some(rec) = state
1266        .released_diff_packs
1267        .iter_mut()
1268        .find(|r| r.pack_id == pack_id)
1269    {
1270        rec.verdict = Some(verdict);
1271        rec.verdict_event_id = Some(event.id.clone());
1272        rec.reviewer_actor = Some(reviewer_actor);
1273        rec.applied_members = applied;
1274        rec.sdk_only_members = sdk_only;
1275    } else {
1276        // No prior `diff_pack.released` event for this pack. Create
1277        // a record from the verdict event so the log stays self-
1278        // sufficient. The promoter typically emits the release event
1279        // before the verdict, but a hub that receives only the
1280        // verdict (e.g., a peer hub that missed the release)
1281        // can still reconstruct a sensible record.
1282        let mut rec = ReleasedDiffPackRecord::from_released_event(
1283            pack_id,
1284            event
1285                .payload
1286                .get("frontier_id")
1287                .and_then(Value::as_str)
1288                .unwrap_or("")
1289                .to_string(),
1290            String::new(),
1291            String::new(),
1292            event.timestamp.clone(),
1293            String::new(),
1294            Vec::new(),
1295        );
1296        rec.verdict = Some(verdict);
1297        rec.verdict_event_id = Some(event.id.clone());
1298        rec.reviewer_actor = Some(reviewer_actor);
1299        rec.applied_members = applied;
1300        rec.sdk_only_members = sdk_only;
1301        state.released_diff_packs.push(rec);
1302    }
1303    Ok(())
1304}
1305
1306/// v0.218: append a VerdictConflict record to
1307/// `state.verdict_conflicts` when a `verdict_conflict.resolved`
1308/// event lands. The full conflict body lives in the event payload
1309/// under `conflict`. Idempotent on conflict_id — re-applying the
1310/// same resolution is a no-op. T32 pins the bounded-length
1311/// accumulation algebra.
1312fn apply_verdict_conflict_resolved(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1313    use crate::verdict_conflict::VerdictConflict;
1314
1315    let conflict_value = event
1316        .payload
1317        .get("conflict")
1318        .ok_or("verdict_conflict.resolved event missing payload.conflict")?
1319        .clone();
1320    let conflict: VerdictConflict = serde_json::from_value(conflict_value)
1321        .map_err(|e| format!("verdict_conflict.resolved payload parse: {e}"))?;
1322    conflict
1323        .verify()
1324        .map_err(|e| format!("verdict_conflict.resolved body did not verify: {e}"))?;
1325    if state
1326        .verdict_conflicts
1327        .iter()
1328        .any(|c| c.conflict_id == conflict.conflict_id)
1329    {
1330        return Ok(());
1331    }
1332    state.verdict_conflicts.push(conflict);
1333    Ok(())
1334}
1335
1336/// T7: upsert a resolved Contradiction into `state.contradictions`
1337/// when a `contradiction.resolved` event lands. The full object lives
1338/// in the event payload under `contradiction`. Integrity check: the
1339/// object's `contradiction_id` must equal the content address of its
1340/// own (frontier_id, finding pair), so a forged or mismatched id is
1341/// rejected. Latest resolution per id wins — re-applying the same
1342/// event is a no-op; a later transition replaces the earlier record.
1343fn apply_contradiction_resolved(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1344    use crate::contradiction::Contradiction;
1345
1346    let value = event
1347        .payload
1348        .get("contradiction")
1349        .ok_or("contradiction.resolved event missing payload.contradiction")?
1350        .clone();
1351    let contradiction: Contradiction = serde_json::from_value(value)
1352        .map_err(|e| format!("contradiction.resolved payload parse: {e}"))?;
1353
1354    let expected = Contradiction::content_address(
1355        &contradiction.frontier_id,
1356        &contradiction.finding_a,
1357        &contradiction.finding_b,
1358    );
1359    if contradiction.contradiction_id != expected {
1360        return Err(format!(
1361            "contradiction.resolved id '{}' does not match its pair (expected '{expected}')",
1362            contradiction.contradiction_id
1363        ));
1364    }
1365
1366    if let Some(slot) = state
1367        .contradictions
1368        .iter_mut()
1369        .find(|c| c.contradiction_id == contradiction.contradiction_id)
1370    {
1371        *slot = contradiction;
1372    } else {
1373        state.contradictions.push(contradiction);
1374    }
1375    Ok(())
1376}
1377
1378/// Idempotent upsert into a content-addressed collection: replace the element
1379/// that matches `item` by `same`, or append it. The shared shape behind the
1380/// attempt/resolution reducer arms.
1381fn upsert_by<T>(vec: &mut Vec<T>, item: T, same: impl Fn(&T, &T) -> bool) {
1382    if let Some(slot) = vec.iter_mut().find(|x| same(x, &item)) {
1383        *slot = item;
1384    } else {
1385        vec.push(item);
1386    }
1387}
1388
1389/// Upsert a signed banked attempt into `state.attempts` when an
1390/// `attempt.deposited` event lands. The full object lives in
1391/// `payload.attempt`. Integrity: the object must `verify()` (id re-derives,
1392/// signature checks, claim_digest matches) — a forged or hand-edited deposit
1393/// is rejected. Idempotent by `vat_` id.
1394/// `statement.attested`: upsert the signed attestation from
1395/// `payload.attestation`. The record's own signature + content address
1396/// are re-verified on every apply — a tampered attestation cannot
1397/// re-enter through replay.
1398/// `attempt.claimed`: append/refresh an obligation lease. The
1399/// determinism rule: a prior lease is "expired" relative to THIS
1400/// event's timestamp (parse both RFC3339 instants; if claimed_at + ttl
1401/// <= new event's timestamp, the old lease is dead and the claim
1402/// succeeds). Same claimant refreshing their own live lease is allowed only
1403/// under the same key. A zero-TTL update is an immediate release and must
1404/// compare-and-swap the exact current claim event with the same actor and key.
1405fn apply_attempt_claimed(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1406    let p = &event.payload;
1407    let obligation_id = p
1408        .get("obligation_id")
1409        .and_then(Value::as_str)
1410        .ok_or("attempt.claimed missing payload.obligation_id")?;
1411    let ttl = p
1412        .get("lease_ttl_seconds")
1413        .and_then(Value::as_u64)
1414        .ok_or("attempt.claimed missing payload.lease_ttl_seconds")?;
1415    if ttl > crate::events::MAX_ATTEMPT_LEASE_TTL_SECONDS {
1416        return Err(format!(
1417            "attempt.claimed payload.lease_ttl_seconds must be at most {}",
1418            crate::events::MAX_ATTEMPT_LEASE_TTL_SECONDS
1419        ));
1420    }
1421    let claimant_actor = p
1422        .get("claimant_actor")
1423        .and_then(Value::as_str)
1424        .unwrap_or(&event.actor.id)
1425        .to_string();
1426    let claimant_pubkey = p
1427        .get("claimant_pubkey")
1428        .and_then(Value::as_str)
1429        .unwrap_or("")
1430        .to_string();
1431    if claimant_actor != event.actor.id {
1432        return Err(format!(
1433            "attempt.claimed payload claimant {claimant_actor} does not match event actor {}",
1434            event.actor.id
1435        ));
1436    }
1437    if event.target.id != obligation_id {
1438        return Err(format!(
1439            "attempt.claimed target {} does not match obligation {obligation_id}",
1440            event.target.id
1441        ));
1442    }
1443    let prior_claim_event_id = p.get("prior_claim_event_id").and_then(Value::as_str);
1444    let release_reason = p.get("release_reason").and_then(Value::as_str);
1445    let parse = chrono::DateTime::parse_from_rfc3339;
1446    let event_at = parse(&event.timestamp)
1447        .map_err(|e| format!("attempt.claimed: bad event timestamp: {e}"))?;
1448    let live_at_event = |claimed_at: &chrono::DateTime<chrono::FixedOffset>, lease_ttl: u64| {
1449        i64::try_from(lease_ttl)
1450            .ok()
1451            .and_then(chrono::Duration::try_seconds)
1452            .and_then(|duration| claimed_at.checked_add_signed(duration))
1453            .is_some_and(|expires_at| expires_at > event_at)
1454    };
1455    let existing = state
1456        .attempt_claims
1457        .iter()
1458        .find(|c| c.obligation_id == obligation_id)
1459        .cloned();
1460    if ttl == 0 {
1461        let existing = existing.as_ref().ok_or_else(|| {
1462            format!("cannot release obligation {obligation_id}: no current lease exists")
1463        })?;
1464        let claimed_at = parse(&existing.claimed_at)
1465            .map_err(|e| format!("attempt.claimed: bad prior claim timestamp: {e}"))?;
1466        if !live_at_event(&claimed_at, existing.lease_ttl_seconds) {
1467            return Err(format!(
1468                "cannot release obligation {obligation_id}: the current lease is not live"
1469            ));
1470        }
1471        if event_at < claimed_at {
1472            return Err(format!(
1473                "cannot release obligation {obligation_id}: release timestamp predates the prior claim"
1474            ));
1475        }
1476        if existing.claimant_actor != claimant_actor {
1477            return Err(format!(
1478                "cannot release obligation {obligation_id}: leased by {}, not {claimant_actor}",
1479                existing.claimant_actor
1480            ));
1481        }
1482        if existing.claimant_pubkey != claimant_pubkey {
1483            return Err(format!(
1484                "cannot release obligation {obligation_id}: claimant key does not match the current lease"
1485            ));
1486        }
1487        let expected_prior = existing.claim_event_id.as_deref().ok_or_else(|| {
1488            format!(
1489                "cannot release obligation {obligation_id}: prior lease identity is unavailable"
1490            )
1491        })?;
1492        if prior_claim_event_id != Some(expected_prior) {
1493            return Err(format!(
1494                "cannot release obligation {obligation_id}: prior lease identity does not match"
1495            ));
1496        }
1497        if release_reason.is_none_or(|reason| reason.trim().is_empty()) {
1498            return Err(format!(
1499                "cannot release obligation {obligation_id}: release reason is required"
1500            ));
1501        }
1502    } else if let Some(existing) = existing.as_ref() {
1503        let live = parse(&existing.claimed_at)
1504            .map(|claimed_at| live_at_event(&claimed_at, existing.lease_ttl_seconds))
1505            .unwrap_or(false);
1506        if live && existing.claimant_actor != claimant_actor {
1507            return Err(format!(
1508                "obligation {obligation_id} is leased by {} until +{}s; route around it or wait for expiry",
1509                existing.claimant_actor, existing.lease_ttl_seconds
1510            ));
1511        }
1512        if live && existing.claimant_pubkey != claimant_pubkey {
1513            return Err(format!(
1514                "obligation {obligation_id} is leased by {claimant_actor} under a different key; use the original session key or wait for expiry"
1515            ));
1516        }
1517        if live
1518            && prior_claim_event_id.is_some()
1519            && prior_claim_event_id != existing.claim_event_id.as_deref()
1520        {
1521            return Err(format!(
1522                "obligation {obligation_id} refresh names a stale prior lease"
1523            ));
1524        }
1525    }
1526    state
1527        .attempt_claims
1528        .retain(|c| c.obligation_id != obligation_id);
1529    state.attempt_claims.push(crate::project::AttemptClaim {
1530        obligation_id: obligation_id.to_string(),
1531        claimant_actor,
1532        claimant_pubkey,
1533        claimed_at: event.timestamp.clone(),
1534        lease_ttl_seconds: ttl,
1535        claim_event_id: Some(event.id.clone()),
1536    });
1537    Ok(())
1538}
1539
1540/// `statement.registered`: append a priority registration (idempotent
1541/// on statement_hash).
1542fn apply_statement_registered(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1543    let p = &event.payload;
1544    let hash = p
1545        .get("statement_hash")
1546        .and_then(Value::as_str)
1547        .ok_or("statement.registered missing payload.statement_hash")?;
1548    if hash.len() != 64 || hex::decode(hash).is_err() {
1549        return Err("statement_hash must be 32 bytes of hex".to_string());
1550    }
1551    if state
1552        .statement_registrations
1553        .iter()
1554        .any(|r| r.statement_hash == hash)
1555    {
1556        return Ok(());
1557    }
1558    state
1559        .statement_registrations
1560        .push(crate::project::StatementRegistration {
1561            statement_hash: hash.to_string(),
1562            informal_ref: p
1563                .get("informal_ref")
1564                .and_then(Value::as_str)
1565                .unwrap_or("")
1566                .to_string(),
1567            registered_by: event.actor.id.clone(),
1568            registered_at: event.timestamp.clone(),
1569            // Gap 5 (STATE_PLANE_MEMO appendix): the optional
1570            // finding-to-registration edge. Old events carry no
1571            // payload.finding_id and store None.
1572            finding_id: p
1573                .get("finding_id")
1574                .and_then(Value::as_str)
1575                .map(str::to_string),
1576        });
1577    Ok(())
1578}
1579
1580fn apply_statement_attested(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1581    use crate::statement_attestation::StatementAttestation;
1582    let value = event
1583        .payload
1584        .get("attestation")
1585        .ok_or("statement.attested event missing payload.attestation")?
1586        .clone();
1587    let att: StatementAttestation = serde_json::from_value(value)
1588        .map_err(|e| format!("statement.attested payload parse: {e}"))?;
1589    att.verify()
1590        .map_err(|e| format!("statement.attested rejected: {e}"))?;
1591    if let Some(existing) = state
1592        .statement_attestations
1593        .iter_mut()
1594        .find(|a| a.id == att.id)
1595    {
1596        *existing = att;
1597    } else {
1598        state.statement_attestations.push(att);
1599    }
1600    Ok(())
1601}
1602
1603/// `anchor.attached`: upsert a signed `val_` anchor link from
1604/// `payload.anchor_link`. The link's own signature + content address are
1605/// re-verified on every apply, so a tampered anchor cannot enter state.
1606fn apply_anchor_attached(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1607    use crate::anchor::AnchorLink;
1608    let value = event
1609        .payload
1610        .get("anchor_link")
1611        .ok_or("anchor.attached event missing payload.anchor_link")?
1612        .clone();
1613    let link: AnchorLink =
1614        serde_json::from_value(value).map_err(|e| format!("anchor.attached payload parse: {e}"))?;
1615    link.verify()
1616        .map_err(|e| format!("anchor.attached rejected: {e}"))?;
1617    if let Some(existing) = state.anchor_links.iter_mut().find(|a| a.id == link.id) {
1618        *existing = link;
1619    } else {
1620        state.anchor_links.push(link);
1621    }
1622    Ok(())
1623}
1624
1625/// `anchor.retracted`: remove the anchor link named by
1626/// `payload.anchor_link_id`. Anchor attachment is fallible and therefore
1627/// retractable (frontier-calculus Law 22). Retracting an absent id is a
1628/// no-op, so replay stays idempotent.
1629fn apply_anchor_retracted(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1630    let id = event
1631        .payload
1632        .get("anchor_link_id")
1633        .and_then(|v| v.as_str())
1634        .ok_or("anchor.retracted event missing payload.anchor_link_id")?;
1635    state.anchor_links.retain(|a| a.id != id);
1636    Ok(())
1637}
1638
1639fn apply_attempt_deposited(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1640    use crate::attempt::Attempt;
1641
1642    let value = event
1643        .payload
1644        .get("attempt")
1645        .ok_or("attempt.deposited event missing payload.attempt")?
1646        .clone();
1647    let attempt: Attempt = serde_json::from_value(value)
1648        .map_err(|e| format!("attempt.deposited payload parse: {e}"))?;
1649    attempt
1650        .verify()
1651        .map_err(|e| format!("attempt.deposited rejected: {e}"))?;
1652
1653    upsert_by(&mut state.attempts, attempt, |a, b| {
1654        a.attempt_id == b.attempt_id
1655    });
1656    Ok(())
1657}
1658
1659/// Upsert a signed cross-domain transfer into `state.transfers` when a
1660/// `transfer.deposited` event lands. The full object lives in
1661/// `payload.transfer`. Integrity: the object must `verify()` (id re-derives,
1662/// signature checks) — a forged or hand-edited transfer is rejected. Admission
1663/// (whether the link is sound) is NOT decided here; it is derived on read via
1664/// `transfer::derive_transfer_status`. Idempotent by `vtr_` id.
1665fn apply_transfer_deposited(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1666    use crate::transfer::Transfer;
1667
1668    let value = event
1669        .payload
1670        .get("transfer")
1671        .ok_or("transfer.deposited event missing payload.transfer")?
1672        .clone();
1673    let transfer: Transfer = serde_json::from_value(value)
1674        .map_err(|e| format!("transfer.deposited payload parse: {e}"))?;
1675    transfer
1676        .verify()
1677        .map_err(|e| format!("transfer.deposited rejected: {e}"))?;
1678
1679    upsert_by(&mut state.transfers, transfer, |a, b| {
1680        a.transfer_id == b.transfer_id
1681    });
1682    Ok(())
1683}
1684
1685/// Upsert a signed significance endorsement into `state.endorsements` when an
1686/// `endorsement.deposited` event lands. The object lives in
1687/// `payload.endorsement`. Integrity: it must `verify()` (id re-derives,
1688/// signature checks). Idempotent by `ven_` id. There is deliberately NO
1689/// aggregation here — endorsements accumulate as individual records and are
1690/// never folded into a significance score.
1691fn apply_endorsement_deposited(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1692    use crate::endorsement::Endorsement;
1693
1694    let value = event
1695        .payload
1696        .get("endorsement")
1697        .ok_or("endorsement.deposited event missing payload.endorsement")?
1698        .clone();
1699    let endorsement: Endorsement = serde_json::from_value(value)
1700        .map_err(|e| format!("endorsement.deposited payload parse: {e}"))?;
1701    endorsement
1702        .verify()
1703        .map_err(|e| format!("endorsement.deposited rejected: {e}"))?;
1704
1705    upsert_by(&mut state.endorsements, endorsement, |a, b| {
1706        a.endorsement_id == b.endorsement_id
1707    });
1708    Ok(())
1709}
1710
1711/// Append a lifecycle transition into `state.attempt_resolutions` when an
1712/// `attempt.resolved` event lands. The [`crate::attempt::ResolutionEvent`]
1713/// lives in `payload.resolution`. Integrity: the object must `verify()`
1714/// (`vre_` id re-derives). Idempotent by `vre_` id; the head per attempt is
1715/// the latest by `at`, computed on read (`Project::head_resolution`).
1716fn apply_attempt_resolved(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1717    use crate::attempt::ResolutionEvent;
1718
1719    let value = event
1720        .payload
1721        .get("resolution")
1722        .ok_or("attempt.resolved event missing payload.resolution")?
1723        .clone();
1724    let resolution: ResolutionEvent = serde_json::from_value(value)
1725        .map_err(|e| format!("attempt.resolved payload parse: {e}"))?;
1726    resolution
1727        .verify()
1728        .map_err(|e| format!("attempt.resolved rejected: {e}"))?;
1729
1730    upsert_by(&mut state.attempt_resolutions, resolution, |a, b| {
1731        a.resolution_id == b.resolution_id
1732    });
1733    Ok(())
1734}
1735
1736/// v0.57: Apply a `finding.span_repaired` event. Appends a
1737/// `{section, text}` span object to
1738/// `state.findings[i].evidence.evidence_spans`. Idempotent:
1739/// applying twice with the same (section, text) pair is a no-op.
1740fn apply_finding_span_repaired(
1741    state: &mut Project,
1742    event: &StateEvent,
1743    index: &mut FindingIndex,
1744) -> Result<(), String> {
1745    if event.target.r#type != "finding" {
1746        return Err(format!(
1747            "reducer: finding.span_repaired target.type must be 'finding', got '{}'",
1748            event.target.r#type
1749        ));
1750    }
1751    let finding_id = event.target.id.as_str();
1752    let section = event
1753        .payload
1754        .get("section")
1755        .and_then(Value::as_str)
1756        .ok_or("reducer: finding.span_repaired missing payload.section")?;
1757    let text = event
1758        .payload
1759        .get("text")
1760        .and_then(Value::as_str)
1761        .ok_or("reducer: finding.span_repaired missing payload.text")?;
1762    let idx = *index.get(finding_id).ok_or_else(|| {
1763        format!("reducer: finding.span_repaired targets unknown finding {finding_id}")
1764    })?;
1765    let span_value = serde_json::json!({"section": section, "text": text});
1766    let already_present = state.findings[idx]
1767        .evidence
1768        .evidence_spans
1769        .iter()
1770        .any(|existing| {
1771            existing.get("section").and_then(Value::as_str) == Some(section)
1772                && existing.get("text").and_then(Value::as_str) == Some(text)
1773        });
1774    if !already_present {
1775        state.findings[idx].evidence.evidence_spans.push(span_value);
1776    }
1777    Ok(())
1778}
1779
1780/// v0.56: Apply an `evidence_atom.locator_repaired` event. Sets
1781/// `locator` on the named atom and removes the "missing evidence
1782/// locator" caveat if present. Idempotent: applying twice with the
1783/// same locator is a no-op. Mismatched locator values fail the reduce
1784/// rather than silently overwriting, since divergent locators on the
1785/// same atom are a chain-integrity issue, not a repair.
1786fn apply_evidence_atom_locator_repaired(
1787    state: &mut Project,
1788    event: &StateEvent,
1789) -> Result<(), String> {
1790    if event.target.r#type != "evidence_atom" {
1791        return Err(format!(
1792            "reducer: evidence_atom.locator_repaired target.type must be 'evidence_atom', got '{}'",
1793            event.target.r#type
1794        ));
1795    }
1796    let atom_id = event.target.id.as_str();
1797    let locator = event
1798        .payload
1799        .get("locator")
1800        .and_then(Value::as_str)
1801        .ok_or("reducer: evidence_atom.locator_repaired missing payload.locator")?;
1802    let idx = state
1803        .evidence_atoms
1804        .iter()
1805        .position(|atom| atom.id == atom_id)
1806        .ok_or_else(|| {
1807            format!("reducer: evidence_atom.locator_repaired targets unknown atom {atom_id}")
1808        })?;
1809    if let Some(existing) = &state.evidence_atoms[idx].locator
1810        && existing != locator
1811    {
1812        return Err(format!(
1813            "reducer: evidence_atom {atom_id} already has locator '{existing}', refusing to overwrite with '{locator}'"
1814        ));
1815    }
1816    state.evidence_atoms[idx].locator = Some(locator.to_string());
1817    state.evidence_atoms[idx]
1818        .caveats
1819        .retain(|c| c != "missing evidence locator");
1820    Ok(())
1821}
1822
1823#[cfg(test)]
1824mod tests {
1825    use super::*;
1826    use crate::bundle::{Assertion, Conditions, Confidence, Evidence, Flags, Provenance};
1827    use crate::events::{FindingEventInput, NULL_HASH, StateActor, StateTarget};
1828    use chrono::Utc;
1829    use serde_json::json;
1830
1831    fn lease_event(
1832        actor: &str,
1833        pubkey: &str,
1834        at: &str,
1835        ttl: u64,
1836        prior: Option<&str>,
1837        reason: Option<&str>,
1838    ) -> StateEvent {
1839        let mut payload = json!({
1840            "obligation_id": "scope:lease-cas",
1841            "lease_ttl_seconds": ttl,
1842            "claimant_actor": actor,
1843            "claimant_pubkey": pubkey,
1844        });
1845        if let Some(prior) = prior {
1846            payload["prior_claim_event_id"] = json!(prior);
1847        }
1848        if let Some(reason) = reason {
1849            payload["release_reason"] = json!(reason);
1850        }
1851        crate::events::new_finding_event(FindingEventInput {
1852            kind: crate::events::EVENT_KIND_ATTEMPT_CLAIMED,
1853            finding_id: "scope:lease-cas",
1854            actor_id: actor,
1855            actor_type: "agent",
1856            reason: reason.unwrap_or("claim fixture"),
1857            before_hash: NULL_HASH,
1858            after_hash: NULL_HASH,
1859            payload,
1860            caveats: Vec::new(),
1861            timestamp: Some(at),
1862        })
1863    }
1864
1865    fn state_with_claim(claim: &StateEvent) -> crate::project::Project {
1866        let mut state = crate::project::assemble("lease", Vec::new(), 0, 0, "test");
1867        apply_event(&mut state, claim).unwrap();
1868        state
1869    }
1870
1871    #[test]
1872    fn zero_ttl_lease_release_is_an_exact_same_owner_compare_and_swap() {
1873        let claim = lease_event(
1874            "agent:owner",
1875            &"11".repeat(32),
1876            "2026-07-14T12:00:00.500Z",
1877            3_600,
1878            None,
1879            None,
1880        );
1881        let initial = state_with_claim(&claim);
1882        assert_eq!(
1883            initial.attempt_claims[0].claim_event_id.as_deref(),
1884            Some(claim.id.as_str())
1885        );
1886
1887        for (label, release, expected) in [
1888            (
1889                "different actor",
1890                lease_event(
1891                    "agent:other",
1892                    &"11".repeat(32),
1893                    "2026-07-14T12:01:00Z",
1894                    0,
1895                    Some(&claim.id),
1896                    Some("not mine"),
1897                ),
1898                "leased by agent:owner",
1899            ),
1900            (
1901                "different key",
1902                lease_event(
1903                    "agent:owner",
1904                    &"22".repeat(32),
1905                    "2026-07-14T12:01:00Z",
1906                    0,
1907                    Some(&claim.id),
1908                    Some("wrong key"),
1909                ),
1910                "key does not match",
1911            ),
1912            (
1913                "stale predecessor",
1914                lease_event(
1915                    "agent:owner",
1916                    &"11".repeat(32),
1917                    "2026-07-14T12:01:00Z",
1918                    0,
1919                    Some("vev_0000000000000000"),
1920                    Some("stale"),
1921                ),
1922                "prior lease identity does not match",
1923            ),
1924            (
1925                "backdated",
1926                lease_event(
1927                    "agent:owner",
1928                    &"11".repeat(32),
1929                    "2026-07-14T12:00:00.499Z",
1930                    0,
1931                    Some(&claim.id),
1932                    Some("backdated"),
1933                ),
1934                "predates the prior claim",
1935            ),
1936        ] {
1937            let mut state = state_with_claim(&claim);
1938            let error = apply_event(&mut state, &release).unwrap_err();
1939            assert!(error.contains(expected), "{label}: {error}");
1940            assert_eq!(state.attempt_claims, initial.attempt_claims, "{label}");
1941        }
1942
1943        let mut state = initial;
1944        let release = lease_event(
1945            "agent:owner",
1946            &"11".repeat(32),
1947            "2026-07-14T12:01:00Z",
1948            0,
1949            Some(&claim.id),
1950            Some("switching approaches"),
1951        );
1952        apply_event(&mut state, &release).unwrap();
1953        assert_eq!(state.attempt_claims.len(), 1);
1954        assert_eq!(state.attempt_claims[0].lease_ttl_seconds, 0);
1955        assert_eq!(
1956            state.attempt_claims[0].claim_event_id.as_deref(),
1957            Some(release.id.as_str())
1958        );
1959    }
1960
1961    #[test]
1962    fn live_lease_refresh_requires_the_same_actor_key() {
1963        let mut state = crate::project::assemble("lease", Vec::new(), 0, 0, "test");
1964        let claim = lease_event(
1965            "agent:owner",
1966            &"11".repeat(32),
1967            "2026-07-14T12:00:00Z",
1968            3_600,
1969            None,
1970            None,
1971        );
1972        apply_event(&mut state, &claim).unwrap();
1973        let refresh = lease_event(
1974            "agent:owner",
1975            &"22".repeat(32),
1976            "2026-07-14T12:01:00Z",
1977            3_600,
1978            Some(&claim.id),
1979            None,
1980        );
1981        let error = apply_event(&mut state, &refresh).unwrap_err();
1982        assert!(error.contains("different key"), "{error}");
1983    }
1984
1985    fn finding(id: &str) -> crate::bundle::FindingBundle {
1986        crate::bundle::FindingBundle::new(
1987            Assertion {
1988                text: format!("test finding {id}"),
1989                assertion_type: "mechanism".to_string(),
1990                entities: Vec::new(),
1991                relation: None,
1992                direction: None,
1993                causal_claim: None,
1994                causal_evidence_grade: None,
1995            },
1996            Evidence {
1997                evidence_type: "experimental".to_string(),
1998                model_system: String::new(),
1999                method: "test".to_string(),
2000                replicated: false,
2001                replication_count: None,
2002                evidence_spans: Vec::new(),
2003            },
2004            Conditions {
2005                text: "test".to_string(),
2006                duration: None,
2007            },
2008            Confidence::raw(0.5, "test", 0.8),
2009            Provenance {
2010                source_type: "published_paper".to_string(),
2011                doi: Some(format!("10.1/test-{id}")),
2012                url: None,
2013                title: format!("Source for {id}"),
2014                authors: Vec::new(),
2015                year: Some(2026),
2016                license: None,
2017                publisher: None,
2018                funders: Vec::new(),
2019                extraction: crate::bundle::Extraction::default(),
2020                review: None,
2021                contributions: Vec::new(),
2022            },
2023            Flags {
2024                gap: false,
2025                negative_space: false,
2026                contested: false,
2027                retracted: false,
2028                declining: false,
2029                gravity_well: false,
2030                review_state: None,
2031                superseded: false,
2032                signature_threshold: None,
2033                jointly_accepted: false,
2034            },
2035        )
2036    }
2037
2038    #[test]
2039    fn replay_with_no_events_is_identity() {
2040        let state = project::assemble("test", vec![finding("a")], 0, 0, "test");
2041        let v = verify_replay(&state);
2042        assert!(v.ok, "diffs: {:?} note: {}", v.diffs, v.note);
2043        assert_eq!(v.replayed_snapshot_hash, v.materialized_snapshot_hash);
2044    }
2045
2046    #[test]
2047    fn reducer_marks_finding_contested() {
2048        let f = finding("a");
2049        let mut state = project::assemble("test", vec![f.clone()], 0, 0, "test");
2050        let event = events::new_finding_event(FindingEventInput {
2051            kind: "finding.reviewed",
2052            finding_id: &f.id,
2053            actor_id: "reviewer:test",
2054            actor_type: "human",
2055            reason: "test",
2056            before_hash: &events::finding_hash(&f),
2057            after_hash: NULL_HASH,
2058            payload: json!({"status": "contested"}),
2059            caveats: vec![],
2060            timestamp: None,
2061        });
2062        apply_event(&mut state, &event).unwrap();
2063        assert!(state.findings[0].flags.contested);
2064    }
2065
2066    #[test]
2067    fn classify_provenance_separates_inline_from_remnant() {
2068        // `inline` carries its body in a finding.asserted event; `rem` has
2069        // no event at all (a pre-event-sourcing remnant seeded from cache).
2070        let inline = finding("inline");
2071        let rem = finding("rem");
2072        let mut state = project::assemble("test", vec![inline.clone(), rem.clone()], 0, 0, "test");
2073        state.events.push(StateEvent {
2074            schema: events::EVENT_SCHEMA.to_string(),
2075            id: "vev_inline".to_string(),
2076            kind: "finding.asserted".into(),
2077            target: StateTarget {
2078                r#type: "finding".to_string(),
2079                id: inline.id.clone(),
2080            },
2081            actor: StateActor {
2082                id: "reviewer:test".to_string(),
2083                r#type: "human".to_string(),
2084            },
2085            timestamp: Utc::now().to_rfc3339(),
2086            reason: "assert".to_string(),
2087            before_hash: NULL_HASH.to_string(),
2088            after_hash: events::finding_hash(&inline),
2089            payload: json!({ "finding": inline }),
2090            caveats: vec![],
2091            signature: None,
2092        });
2093
2094        let report = classify_provenance(&state);
2095        assert_eq!(report.inline, vec![inline.id.clone()]);
2096        assert_eq!(report.remnant, vec![rem.id.clone()]);
2097        assert!(report.proposal_backed.is_empty());
2098        assert!(
2099            !report.fully_event_sourced(),
2100            "a frontier with a remnant is not fully event-sourced"
2101        );
2102
2103        // Removing the remnant leaves an all-inline frontier: fully reducible.
2104        state.findings.retain(|f| f.id != rem.id);
2105        assert!(classify_provenance(&state).fully_event_sourced());
2106    }
2107
2108    #[test]
2109    fn reducer_retracts_finding() {
2110        let f = finding("a");
2111        let mut state = project::assemble("test", vec![f.clone()], 0, 0, "test");
2112        let event = StateEvent {
2113            schema: events::EVENT_SCHEMA.to_string(),
2114            id: "vev_test".to_string(),
2115            kind: "finding.retracted".into(),
2116            target: StateTarget {
2117                r#type: "finding".to_string(),
2118                id: f.id.clone(),
2119            },
2120            actor: StateActor {
2121                id: "reviewer:test".to_string(),
2122                r#type: "human".to_string(),
2123            },
2124            timestamp: Utc::now().to_rfc3339(),
2125            reason: "test retraction".to_string(),
2126            before_hash: events::finding_hash(&f),
2127            after_hash: NULL_HASH.to_string(),
2128            payload: json!({"proposal_id": "vpr_x"}),
2129            caveats: vec![],
2130            signature: None,
2131        };
2132        apply_event(&mut state, &event).unwrap();
2133        assert!(state.findings[0].flags.retracted);
2134    }
2135
2136    #[test]
2137    fn confidence_revision_replay_uses_event_payload_timestamp() {
2138        let f = finding("a");
2139        let mut expected = f.clone();
2140        let updated_at = "2026-05-07T23:30:00Z";
2141        let reason = "lower confidence after review";
2142        expected.confidence.score = 0.42;
2143        expected.confidence.basis = format!(
2144            "expert revision from {:.3} to {:.3}: {}",
2145            f.confidence.score, 0.42, reason
2146        );
2147        expected.confidence.method = ConfidenceMethod::ExpertJudgment;
2148        expected.updated = Some(updated_at.to_string());
2149        let mut state = project::assemble("test", vec![f.clone()], 0, 0, "test");
2150        let event = StateEvent {
2151            schema: events::EVENT_SCHEMA.to_string(),
2152            id: "vev_confidence".to_string(),
2153            kind: "finding.confidence_revised".into(),
2154            target: StateTarget {
2155                r#type: "finding".to_string(),
2156                id: f.id.clone(),
2157            },
2158            actor: StateActor {
2159                id: "reviewer:test".to_string(),
2160                r#type: "human".to_string(),
2161            },
2162            timestamp: "2026-05-07T23:31:00Z".to_string(),
2163            reason: reason.to_string(),
2164            before_hash: events::finding_hash(&f),
2165            after_hash: events::finding_hash(&expected),
2166            payload: json!({
2167                "previous_score": f.confidence.score,
2168                "new_score": 0.42,
2169                "updated_at": updated_at,
2170            }),
2171            caveats: vec![],
2172            signature: None,
2173        };
2174
2175        apply_event(&mut state, &event).unwrap();
2176
2177        assert_eq!(state.findings[0].updated.as_deref(), Some(updated_at));
2178        assert_eq!(events::finding_hash(&state.findings[0]), event.after_hash);
2179    }
2180
2181    #[test]
2182    fn reducer_rejects_unknown_kind() {
2183        let mut state = project::assemble("test", vec![], 0, 0, "test");
2184        let event = StateEvent {
2185            schema: events::EVENT_SCHEMA.to_string(),
2186            id: "vev_test".to_string(),
2187            kind: "finding.unknown_kind".into(),
2188            target: StateTarget {
2189                r#type: "finding".to_string(),
2190                id: "vf_x".to_string(),
2191            },
2192            actor: StateActor {
2193                id: "x".to_string(),
2194                r#type: "human".to_string(),
2195            },
2196            timestamp: Utc::now().to_rfc3339(),
2197            reason: "x".to_string(),
2198            before_hash: NULL_HASH.to_string(),
2199            after_hash: NULL_HASH.to_string(),
2200            payload: Value::Null,
2201            caveats: vec![],
2202            signature: None,
2203        };
2204        let r = apply_event(&mut state, &event);
2205        assert!(r.is_err());
2206    }
2207
2208    /// v0.49.3: the dispatch table in `apply_event` and the
2209    /// `REDUCER_MUTATION_KINDS` constant must agree. Adding a new
2210    /// match arm without updating the constant (or vice versa) makes
2211    /// CI fail loudly here, which then makes the cross-impl fixture
2212    /// coverage assertion fail correctly downstream. This is the
2213    /// single source of truth that retires the hand-maintained mirror.
2214    #[test]
2215    fn dispatch_handles_every_declared_kind() {
2216        for kind in REDUCER_MUTATION_KINDS {
2217            let mut state = project::assemble("test", vec![], 0, 0, "test");
2218            // Dummy event with the declared kind. The handler may
2219            // reject the payload (it's empty), but it MUST NOT reject
2220            // the kind itself with "unsupported event kind" — that
2221            // would prove the dispatch table is missing an arm for
2222            // a kind the constant declares.
2223            let event = StateEvent {
2224                schema: events::EVENT_SCHEMA.to_string(),
2225                id: "vev_dispatch_check".to_string(),
2226                kind: (*kind).into(),
2227                target: StateTarget {
2228                    r#type: "finding".to_string(),
2229                    id: "vf_x".to_string(),
2230                },
2231                actor: StateActor {
2232                    id: "x".to_string(),
2233                    r#type: "human".to_string(),
2234                },
2235                timestamp: Utc::now().to_rfc3339(),
2236                reason: String::new(),
2237                before_hash: NULL_HASH.to_string(),
2238                after_hash: NULL_HASH.to_string(),
2239                payload: Value::Null,
2240                caveats: vec![],
2241                signature: None,
2242            };
2243            let r = apply_event(&mut state, &event);
2244            if let Err(e) = r {
2245                assert!(
2246                    !e.contains("unsupported event kind"),
2247                    "kind {kind:?} declared in REDUCER_MUTATION_KINDS \
2248                     but rejected by apply_event dispatch: {e}"
2249                );
2250            }
2251        }
2252    }
2253
2254    /// The writer/reducer seam invariant: every kind the protocol can
2255    /// emit or store (`events::KNOWN_EVENT_KINDS` — the writer-side
2256    /// universe) must be handled by the dispatch, either with a real arm
2257    /// or an explicit no-op. A new writer kind without a reducer arm
2258    /// fails here instead of erroring on the next replay of a live log.
2259    /// (This is the test that would have caught `finding.superseded`
2260    /// being emittable-but-unreplayable.)
2261    #[test]
2262    fn every_known_kind_reduces() {
2263        for kind in events::KNOWN_EVENT_KINDS {
2264            let mut state = project::assemble("test", vec![], 0, 0, "test");
2265            let event = StateEvent {
2266                schema: events::EVENT_SCHEMA.to_string(),
2267                id: "vev_known_kind_check".to_string(),
2268                kind: (*kind).into(),
2269                target: StateTarget {
2270                    r#type: "finding".to_string(),
2271                    id: "vf_x".to_string(),
2272                },
2273                actor: StateActor {
2274                    id: "x".to_string(),
2275                    r#type: "human".to_string(),
2276                },
2277                timestamp: Utc::now().to_rfc3339(),
2278                reason: String::new(),
2279                before_hash: NULL_HASH.to_string(),
2280                after_hash: NULL_HASH.to_string(),
2281                payload: Value::Null,
2282                caveats: vec![],
2283                signature: None,
2284            };
2285            if let Err(e) = apply_event(&mut state, &event) {
2286                assert!(
2287                    !e.contains("unsupported event kind"),
2288                    "kind {kind:?} is in events::KNOWN_EVENT_KINDS (a writer \
2289                     can emit it) but the reducer dispatch rejects it: {e}"
2290                );
2291            }
2292        }
2293    }
2294
2295    fn project_with_one_atom(missing_locator: bool) -> Project {
2296        // `project::assemble` calls `sources::materialize_project`,
2297        // which derives one evidence atom per finding. The hand-built
2298        // atom below is appended after materialization with a distinct
2299        // id (`vea_test_atom`), so it survives alongside the derived
2300        // atom. Tests look up atoms by id via `atom_by_id`.
2301        let mut state = project::assemble("test-locator", vec![finding("a")], 0, 0, "test");
2302        state.sources.push(crate::sources::SourceRecord {
2303            id: "vs_test_source".to_string(),
2304            source_type: "paper".to_string(),
2305            locator: "doi:10.1/test-source".to_string(),
2306            content_hash: None,
2307            title: "Test source".to_string(),
2308            authors: Vec::new(),
2309            year: Some(2026),
2310            doi: Some("10.1/test-source".to_string()),
2311            pmid: None,
2312            imported_at: "2026-01-01T00:00:00Z".to_string(),
2313            extraction_mode: "manual".to_string(),
2314            source_quality: "declared".to_string(),
2315            caveats: Vec::new(),
2316            finding_ids: vec![state.findings[0].id.clone()],
2317        });
2318        state.evidence_atoms.push(crate::sources::EvidenceAtom {
2319            id: "vea_test_atom".to_string(),
2320            source_id: "vs_test_source".to_string(),
2321            finding_id: state.findings[0].id.clone(),
2322            locator: if missing_locator {
2323                None
2324            } else {
2325                Some("doi:10.1/already-set".to_string())
2326            },
2327            evidence_type: "experimental".to_string(),
2328            measurement_or_claim: "test claim".to_string(),
2329            supports_or_challenges: "supports".to_string(),
2330            condition_refs: Vec::new(),
2331            extraction_method: "manual".to_string(),
2332            human_verified: false,
2333            caveats: if missing_locator {
2334                vec!["missing evidence locator".to_string()]
2335            } else {
2336                Vec::new()
2337            },
2338        });
2339        state
2340    }
2341
2342    fn atom_by_id<'a>(state: &'a Project, id: &str) -> &'a crate::sources::EvidenceAtom {
2343        state
2344            .evidence_atoms
2345            .iter()
2346            .find(|atom| atom.id == id)
2347            .expect("atom exists")
2348    }
2349
2350    #[test]
2351    fn evidence_atom_locator_repaired_sets_locator_and_clears_caveat() {
2352        let mut state = project_with_one_atom(true);
2353        assert!(state.evidence_atoms[0].locator.is_none());
2354        let event = StateEvent {
2355            schema: crate::events::EVENT_SCHEMA.to_string(),
2356            id: "vev_test".to_string(),
2357            kind: "evidence_atom.locator_repaired".into(),
2358            target: StateTarget {
2359                r#type: "evidence_atom".to_string(),
2360                id: "vea_test_atom".to_string(),
2361            },
2362            actor: StateActor {
2363                id: "agent:test".to_string(),
2364                r#type: "agent".to_string(),
2365            },
2366            timestamp: Utc::now().to_rfc3339(),
2367            reason: "Mechanical repair from parent source".to_string(),
2368            before_hash: NULL_HASH.to_string(),
2369            after_hash: NULL_HASH.to_string(),
2370            payload: json!({
2371                "proposal_id": "vpr_test",
2372                "source_id": "vs_test_source",
2373                "locator": "doi:10.1/test-source",
2374            }),
2375            caveats: vec![],
2376            signature: None,
2377        };
2378        apply_event(&mut state, &event).expect("apply locator_repaired");
2379        let atom = atom_by_id(&state, "vea_test_atom");
2380        assert_eq!(atom.locator.as_deref(), Some("doi:10.1/test-source"));
2381        assert!(atom.caveats.is_empty());
2382    }
2383
2384    #[test]
2385    fn evidence_atom_locator_repaired_is_idempotent() {
2386        let mut state = project_with_one_atom(true);
2387        let event = StateEvent {
2388            schema: crate::events::EVENT_SCHEMA.to_string(),
2389            id: "vev_test".to_string(),
2390            kind: "evidence_atom.locator_repaired".into(),
2391            target: StateTarget {
2392                r#type: "evidence_atom".to_string(),
2393                id: "vea_test_atom".to_string(),
2394            },
2395            actor: StateActor {
2396                id: "agent:test".to_string(),
2397                r#type: "agent".to_string(),
2398            },
2399            timestamp: Utc::now().to_rfc3339(),
2400            reason: "Mechanical repair from parent source".to_string(),
2401            before_hash: NULL_HASH.to_string(),
2402            after_hash: NULL_HASH.to_string(),
2403            payload: json!({
2404                "proposal_id": "vpr_test",
2405                "source_id": "vs_test_source",
2406                "locator": "doi:10.1/test-source",
2407            }),
2408            caveats: vec![],
2409            signature: None,
2410        };
2411        apply_event(&mut state, &event).expect("first apply");
2412        apply_event(&mut state, &event).expect("second apply is a no-op when locator matches");
2413        let atom = atom_by_id(&state, "vea_test_atom");
2414        assert_eq!(atom.locator.as_deref(), Some("doi:10.1/test-source"));
2415    }
2416
2417    #[test]
2418    fn evidence_atom_locator_repaired_refuses_divergent_overwrite() {
2419        let mut state = project_with_one_atom(false);
2420        let event = StateEvent {
2421            schema: crate::events::EVENT_SCHEMA.to_string(),
2422            id: "vev_test".to_string(),
2423            kind: "evidence_atom.locator_repaired".into(),
2424            target: StateTarget {
2425                r#type: "evidence_atom".to_string(),
2426                id: "vea_test_atom".to_string(),
2427            },
2428            actor: StateActor {
2429                id: "agent:test".to_string(),
2430                r#type: "agent".to_string(),
2431            },
2432            timestamp: Utc::now().to_rfc3339(),
2433            reason: "Different repair".to_string(),
2434            before_hash: NULL_HASH.to_string(),
2435            after_hash: NULL_HASH.to_string(),
2436            payload: json!({
2437                "proposal_id": "vpr_test",
2438                "source_id": "vs_test_source",
2439                "locator": "doi:10.1/different",
2440            }),
2441            caveats: vec![],
2442            signature: None,
2443        };
2444        let r = apply_event(&mut state, &event);
2445        assert!(r.is_err());
2446        assert!(r.unwrap_err().contains("already has locator"));
2447    }
2448
2449    #[test]
2450    fn evidence_atom_locator_repaired_does_not_mutate_findings() {
2451        // Cross-impl conformance: this event mutates evidence_atoms only.
2452        let mut state = project_with_one_atom(true);
2453        let hashes_before: Vec<String> = state
2454            .findings
2455            .iter()
2456            .map(crate::events::finding_hash)
2457            .collect();
2458        let event = StateEvent {
2459            schema: crate::events::EVENT_SCHEMA.to_string(),
2460            id: "vev_test".to_string(),
2461            kind: "evidence_atom.locator_repaired".into(),
2462            target: StateTarget {
2463                r#type: "evidence_atom".to_string(),
2464                id: "vea_test_atom".to_string(),
2465            },
2466            actor: StateActor {
2467                id: "agent:test".to_string(),
2468                r#type: "agent".to_string(),
2469            },
2470            timestamp: Utc::now().to_rfc3339(),
2471            reason: "Mechanical repair".to_string(),
2472            before_hash: NULL_HASH.to_string(),
2473            after_hash: NULL_HASH.to_string(),
2474            payload: json!({
2475                "proposal_id": "vpr_test",
2476                "source_id": "vs_test_source",
2477                "locator": "doi:10.1/test-source",
2478            }),
2479            caveats: vec![],
2480            signature: None,
2481        };
2482        apply_event(&mut state, &event).expect("apply ok");
2483        let hashes_after: Vec<String> = state
2484            .findings
2485            .iter()
2486            .map(crate::events::finding_hash)
2487            .collect();
2488        assert_eq!(hashes_before, hashes_after);
2489    }
2490
2491    #[test]
2492    fn attempt_deposit_and_resolution_roundtrip() {
2493        use crate::attempt::{Attempt, AttemptDraft, AttemptResolution, ResolutionEvent};
2494        use ed25519_dalek::SigningKey;
2495        let key = SigningKey::from_bytes(&[7u8; 32]);
2496        let mut state = project::assemble("test", vec![], 0, 0, "test");
2497
2498        let att = Attempt::build(
2499            AttemptDraft {
2500                problem: 309,
2501                kind: "lower_bound".into(),
2502                claim: "a(8) >= 33".to_string(),
2503                ..Default::default()
2504            },
2505            &key,
2506        )
2507        .unwrap();
2508        let dep = att.deposit_event("agent:opus", "agent", "bank attempt");
2509        apply_event(&mut state, &dep).unwrap();
2510        assert_eq!(state.attempts.len(), 1);
2511        assert_eq!(state.attempts[0].attempt_id, att.attempt_id);
2512        // Idempotent: re-applying the same deposit is a no-op.
2513        apply_event(&mut state, &dep).unwrap();
2514        assert_eq!(state.attempts.len(), 1);
2515        // No resolution yet -> still a candidate.
2516        assert!(state.head_resolution(&att.attempt_id).is_none());
2517
2518        let res = ResolutionEvent::new(
2519            &att.attempt_id,
2520            AttemptResolution::Verified {
2521                gate_ref: "gate@vva_x".to_string(),
2522            },
2523            "reviewer:will-blair",
2524            "2026-06-09T00:00:00Z",
2525            "two independent methods",
2526        )
2527        .unwrap();
2528        apply_event(&mut state, &res.to_state_event("reviewer", "verified")).unwrap();
2529        assert_eq!(
2530            state
2531                .head_resolution(&att.attempt_id)
2532                .unwrap()
2533                .resolution
2534                .as_str(),
2535            "verified"
2536        );
2537
2538        // A later refutation becomes the head (latest by `at`); history kept.
2539        let res2 = ResolutionEvent::new(
2540            &att.attempt_id,
2541            AttemptResolution::Refuted {
2542                by_probe: "case_b".to_string(),
2543            },
2544            "reviewer:skeptic",
2545            "2026-06-10T00:00:00Z",
2546            "Case B breaks it",
2547        )
2548        .unwrap();
2549        apply_event(&mut state, &res2.to_state_event("reviewer", "refuted")).unwrap();
2550        assert_eq!(
2551            state
2552                .head_resolution(&att.attempt_id)
2553                .unwrap()
2554                .resolution
2555                .as_str(),
2556            "refuted"
2557        );
2558        assert_eq!(state.attempt_resolutions.len(), 2);
2559    }
2560
2561    #[test]
2562    fn forged_attempt_deposit_is_rejected_by_reducer() {
2563        use crate::attempt::{Attempt, AttemptDraft};
2564        use ed25519_dalek::SigningKey;
2565        let key = SigningKey::from_bytes(&[9u8; 32]);
2566        let mut state = project::assemble("test", vec![], 0, 0, "test");
2567        let att = Attempt::build(
2568            AttemptDraft {
2569                problem: 1,
2570                kind: "k".into(),
2571                claim: "c".to_string(),
2572                ..Default::default()
2573            },
2574            &key,
2575        )
2576        .unwrap();
2577        let mut dep = att.deposit_event("agent:opus", "agent", "x");
2578        // Hand-edit the embedded attempt: the signature no longer verifies.
2579        dep.payload["attempt"]["claim"] = serde_json::json!("tampered");
2580        assert!(apply_event(&mut state, &dep).is_err());
2581        assert_eq!(state.attempts.len(), 0);
2582    }
2583}