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    verify_replay_events(state, state.events.clone())
545}
546
547/// Verify the materialized scientific projection against the union of the
548/// immutable Era-0 event log and an already-verified Era-1 authority log.
549///
550/// Authority verification deliberately remains outside the reducer. Each
551/// supplied event is converted to its transaction-independent semantic event
552/// identity before ordinary replay. Duplicate semantic identities across or
553/// within eras fail closed.
554pub fn verify_replay_with_authority(
555    state: &Project,
556    authority_events: &[crate::authority::AuthorityEventV1],
557) -> ReplayVerification {
558    let events = match semantic_event_union(state, authority_events) {
559        Ok(events) => events,
560        Err(error) => {
561            return ReplayVerification {
562                ok: false,
563                replayed_snapshot_hash: String::new(),
564                materialized_snapshot_hash: findings_digest(&state.findings),
565                diffs: vec![error],
566                note: "dual-log event history does not replay through the reducer".to_string(),
567            };
568        }
569    };
570    verify_replay_events(state, events)
571}
572
573/// Return the transaction-independent semantic event union of the retained
574/// Era-0 log and an already verified repository-authority log.
575///
576/// Authority verification remains the caller's responsibility. This helper is
577/// for read/check projections that need the same event identities as the
578/// reducer without mutating or relabeling either retained log.
579pub fn semantic_event_union(
580    state: &Project,
581    authority_events: &[crate::authority::AuthorityEventV1],
582) -> Result<Vec<StateEvent>, String> {
583    let mut events = state.events.clone();
584    let mut ids = events
585        .iter()
586        .map(|event| event.id.clone())
587        .collect::<std::collections::BTreeSet<_>>();
588    for authority_event in authority_events {
589        // Era-1 `Other` records are authority/workflow audit events such as
590        // policy rotation and Receipt landing. The scientific reducer
591        // deliberately rejects `Other`; these records are replayed by the
592        // authority-history verifier and their own projections instead.
593        if matches!(authority_event.content.kind, EventKind::Other(_)) {
594            continue;
595        }
596        let mut event = match authority_event.semantic_state_event() {
597            Ok(event) => event,
598            Err(error) => {
599                return Err(format!(
600                    "repository-authority event {} has no valid semantic replay form: {error}",
601                    authority_event.id
602                ));
603            }
604        };
605        // Lease release/refresh payloads name the stored authority-event ID of
606        // the prior claim. Coordination replay therefore retains that ID.
607        // Scientific domain links use the semantic ID above.
608        if authority_event.content.kind == EventKind::AttemptClaimed {
609            event.id = authority_event.id.clone();
610        }
611        if !ids.insert(event.id.clone()) {
612            return Err(format!(
613                "semantic event {} occurs more than once across the dual log",
614                event.id
615            ));
616        }
617        events.push(event);
618    }
619    // Split-repository objects load in filename order, and visible Profile v1
620    // materialization uses the same content-ID ordering. The virtual dual-log
621    // projection must therefore use semantic event-ID order too; otherwise an
622    // exact clean clone can replay correctly while deriving a different
623    // legacy snapshot solely from in-memory append order.
624    events.sort_by(|left, right| left.id.cmp(&right.id));
625    Ok(events)
626}
627
628fn verify_replay_events(state: &Project, events: Vec<StateEvent>) -> ReplayVerification {
629    if events.is_empty() {
630        let d = findings_digest(&state.findings);
631        return ReplayVerification {
632            ok: true,
633            replayed_snapshot_hash: d.clone(),
634            materialized_snapshot_hash: d,
635            diffs: Vec::new(),
636            note: "no events; replay is identity".to_string(),
637        };
638    }
639    let sorted = sorted_for_replay(&events);
640    let (genesis, mut diffs, remnants) = seed_genesis_with_remnants(state, &sorted);
641    let replayed = match replay_from_genesis(
642        genesis,
643        sorted,
644        &state.project.name,
645        &state.project.description,
646        &state.project.compiled_at,
647        &state.project.compiler,
648    ) {
649        Ok(p) => p,
650        Err(e) => {
651            return ReplayVerification {
652                ok: false,
653                replayed_snapshot_hash: String::new(),
654                materialized_snapshot_hash: findings_digest(&state.findings),
655                diffs: vec![format!("replay failed: {e}")],
656                note: "event log does not replay through the reducer".to_string(),
657            };
658        }
659    };
660    let replayed_by_id: HashMap<&str, &crate::bundle::FindingBundle> = replayed
661        .findings
662        .iter()
663        .map(|f| (f.id.as_str(), f))
664        .collect();
665    for cached in &state.findings {
666        match replayed_by_id.get(cached.id.as_str()) {
667            None => diffs.push(format!(
668                "finding {} is materialized but absent from replay (no assert event hydrates it)",
669                cached.id
670            )),
671            Some(rep) => {
672                let ch = events::finding_hash(cached);
673                let rh = events::finding_hash(rep);
674                if ch != rh {
675                    diffs.push(format!(
676                        "finding {} diverges: materialized {ch} vs replayed {rh}",
677                        cached.id
678                    ));
679                }
680            }
681        }
682    }
683    for rep in &replayed.findings {
684        if !state.findings.iter().any(|c| c.id == rep.id) {
685            diffs.push(format!(
686                "finding {} is replayable from the log but absent from the materialized state",
687                rep.id
688            ));
689        }
690    }
691    let ok = diffs.is_empty();
692    ReplayVerification {
693        ok,
694        replayed_snapshot_hash: findings_digest(&replayed.findings),
695        materialized_snapshot_hash: findings_digest(&state.findings),
696        diffs,
697        note: if ok {
698            format!(
699                "replayed {} event(s) over {} seeded finding(s) ({} genesis remnant(s)); materialized state reproduced",
700                events.len(),
701                replayed.findings.len(),
702                remnants
703            )
704        } else {
705            "materialized state is NOT reproducible from the event log".to_string()
706        },
707    }
708}
709
710#[derive(Debug, Clone)]
711pub struct ReplayVerification {
712    pub ok: bool,
713    pub replayed_snapshot_hash: String,
714    pub materialized_snapshot_hash: String,
715    pub diffs: Vec<String>,
716    pub note: String,
717}
718
719/// v0.701: per-finding provenance classification for the event-sourcing
720/// migration. Where `verify_replay` *proves* the materialized findings are
721/// reducible, this reports *why* each one is reducible — exactly which
722/// on-disk derived view still pins a finding to git — so a migration can
723/// target the gap and a decommit can be justified one bucket at a time.
724///
725/// Each finding lands in exactly one bucket (inline takes precedence, so a
726/// finding asserted-by-proposal then superseded-inline counts as inline —
727/// its current body is in the log):
728///
729/// - `inline`: an assert/supersede event carries the full body in its
730///   payload; reducible from `events/` alone.
731/// - `proposal_backed`: an assert event exists but hydrates its body from
732///   the signed proposal store; still needs `proposals/`.
733/// - `remnant`: no assert/supersede event targets it; seeded straight from
734///   the `findings/` cache. Predates the event-first discipline.
735///
736/// A frontier is *fully event-sourced* iff `proposal_backed` and `remnant`
737/// are both empty: then `events/` reduces to its whole finding set and the
738/// derived views are pure caches, safe to decommit. This is the explanatory
739/// companion to `verify_replay`, not a trust gate — `verify_replay` remains
740/// the exact, byte-parity invariant.
741#[derive(Debug, Clone, Default)]
742pub struct ProvenanceReport {
743    pub inline: Vec<String>,
744    pub proposal_backed: Vec<String>,
745    pub remnant: Vec<String>,
746    pub actors: usize,
747    pub proposals: usize,
748}
749
750impl ProvenanceReport {
751    /// True when every materialized finding is reducible from the event log
752    /// alone (no proposal-backed bodies, no pre-event remnants).
753    pub fn fully_event_sourced(&self) -> bool {
754        self.proposal_backed.is_empty() && self.remnant.is_empty()
755    }
756}
757
758/// Classify every materialized finding by how its body enters the log.
759/// Mirrors the `seed_genesis` dispatch: an inline body (`payload.finding`
760/// / `payload.new_finding`) vs a proposal reference (`payload.proposal_id`).
761pub fn classify_provenance(state: &Project) -> ProvenanceReport {
762    use std::collections::HashSet;
763    let mut inline: HashSet<&str> = HashSet::new();
764    let mut proposal_backed: HashSet<&str> = HashSet::new();
765    for ev in &state.events {
766        match ev.kind.as_str() {
767            "finding.asserted" => {
768                let id = ev.target.id.as_str();
769                if ev.payload.get("finding").is_some() {
770                    inline.insert(id);
771                } else if ev.payload.get("proposal_id").is_some() {
772                    proposal_backed.insert(id);
773                }
774            }
775            "finding.superseded" => {
776                if let Some(nid) = ev.payload.get("new_finding_id").and_then(Value::as_str) {
777                    if ev.payload.get("new_finding").is_some() {
778                        inline.insert(nid);
779                    } else if ev.payload.get("proposal_id").is_some() {
780                        proposal_backed.insert(nid);
781                    }
782                }
783            }
784            _ => {}
785        }
786    }
787    let mut report = ProvenanceReport {
788        actors: state.actors.len(),
789        proposals: state.proposals.len(),
790        ..Default::default()
791    };
792    for f in &state.findings {
793        let id = f.id.as_str();
794        if inline.contains(id) {
795            report.inline.push(f.id.clone());
796        } else if proposal_backed.contains(id) {
797            report.proposal_backed.push(f.id.clone());
798        } else {
799            report.remnant.push(f.id.clone());
800        }
801    }
802    report
803}
804
805// --- per-kind reducer rules ---------------------------------------------------
806
807fn apply_finding_asserted(
808    state: &mut Project,
809    event: &StateEvent,
810    idx: &mut FindingIndex,
811) -> Result<(), String> {
812    // For a v0.3 frontier emitting genesis events, finding.asserted carries
813    // the full finding in payload.finding; for legacy frontiers replay is
814    // a no-op (the finding was already materialized at genesis).
815    if let Some(finding_value) = event.payload.get("finding") {
816        let finding: crate::bundle::FindingBundle =
817            serde_json::from_value(finding_value.clone())
818                .map_err(|e| format!("reducer: invalid finding.asserted payload.finding: {e}"))?;
819        if idx.contains_key(&finding.id) {
820            return Ok(());
821        }
822        let position = state.findings.len();
823        idx.insert(finding.id.clone(), position);
824        state.findings.push(finding);
825    }
826    Ok(())
827}
828
829fn apply_finding_reviewed(
830    state: &mut Project,
831    event: &StateEvent,
832    index: &mut FindingIndex,
833) -> Result<(), String> {
834    let id = event.target.id.as_str();
835    let status = event
836        .payload
837        .get("status")
838        .and_then(Value::as_str)
839        .ok_or("reducer: finding.reviewed missing payload.status")?;
840    let idx = *index
841        .get(id)
842        .ok_or_else(|| format!("reducer: finding.reviewed targets unknown finding {id}"))?;
843    use crate::bundle::ReviewState;
844    let new_state = match status {
845        "accepted" | "approved" => ReviewState::Accepted,
846        "contested" => ReviewState::Contested,
847        "needs_revision" => ReviewState::NeedsRevision,
848        "rejected" => ReviewState::Rejected,
849        other => return Err(format!("reducer: unsupported review status '{other}'")),
850    };
851    state.findings[idx].flags.contested = new_state.implies_contested();
852    state.findings[idx].flags.review_state = Some(new_state);
853    Ok(())
854}
855
856fn apply_finding_annotation(
857    state: &mut Project,
858    event: &StateEvent,
859    _kind_label: &str,
860    index: &mut FindingIndex,
861) -> Result<(), String> {
862    let id = event.target.id.as_str();
863    let text = event
864        .payload
865        .get("text")
866        .and_then(Value::as_str)
867        .ok_or("reducer: annotation event missing payload.text")?;
868    let annotation_id = event
869        .payload
870        .get("annotation_id")
871        .and_then(Value::as_str)
872        .ok_or("reducer: annotation event missing payload.annotation_id")?;
873    let idx = *index
874        .get(id)
875        .ok_or_else(|| format!("reducer: annotation event targets unknown finding {id}"))?;
876    if state.findings[idx]
877        .annotations
878        .iter()
879        .any(|a| a.id == annotation_id)
880    {
881        return Ok(());
882    }
883    // Phase β (v0.6): pass through optional structured provenance from
884    // the event payload to the materialized annotation. The validator in
885    // `events::validate_event_payload` already rejected all-empty
886    // provenance objects, so deserialization here is best-effort —
887    // unknown shapes silently drop to None rather than failing the
888    // whole reduce.
889    let provenance = event
890        .payload
891        .get("provenance")
892        .and_then(|v| serde_json::from_value::<crate::bundle::ProvenanceRef>(v.clone()).ok());
893    state.findings[idx].annotations.push(Annotation {
894        id: annotation_id.to_string(),
895        text: text.to_string(),
896        author: event.actor.id.clone(),
897        timestamp: event.timestamp.clone(),
898        provenance,
899    });
900    Ok(())
901}
902
903fn apply_finding_confidence_revised(
904    state: &mut Project,
905    event: &StateEvent,
906    index: &mut FindingIndex,
907) -> Result<(), String> {
908    let id = event.target.id.as_str();
909    let new_score = event
910        .payload
911        .get("new_score")
912        .and_then(Value::as_f64)
913        .ok_or("reducer: finding.confidence_revised missing payload.new_score")?;
914    let previous = event
915        .payload
916        .get("previous_score")
917        .and_then(Value::as_f64)
918        .unwrap_or(0.0);
919    let idx = *index
920        .get(id)
921        .ok_or_else(|| format!("reducer: confidence_revised targets unknown finding {id}"))?;
922    let updated_at = event
923        .payload
924        .get("updated_at")
925        .and_then(Value::as_str)
926        .map(str::to_string)
927        .unwrap_or_else(|| event.timestamp.clone());
928    state.findings[idx].confidence.score = new_score;
929    state.findings[idx].confidence.basis = format!(
930        "expert revision from {:.3} to {:.3}: {}",
931        previous, new_score, event.reason
932    );
933    state.findings[idx].confidence.method = ConfidenceMethod::ExpertJudgment;
934    state.findings[idx].updated = Some(updated_at);
935    Ok(())
936}
937
938fn apply_finding_rejected(
939    state: &mut Project,
940    event: &StateEvent,
941    index: &mut FindingIndex,
942) -> Result<(), String> {
943    let id = event.target.id.as_str();
944    let idx = *index
945        .get(id)
946        .ok_or_else(|| format!("reducer: finding.rejected targets unknown finding {id}"))?;
947    state.findings[idx].flags.contested = true;
948    Ok(())
949}
950
951fn apply_finding_retracted(
952    state: &mut Project,
953    event: &StateEvent,
954    index: &mut FindingIndex,
955) -> Result<(), String> {
956    let id = event.target.id.as_str();
957    let idx = *index
958        .get(id)
959        .ok_or_else(|| format!("reducer: finding.retracted targets unknown finding {id}"))?;
960    state.findings[idx].flags.retracted = true;
961    Ok(())
962}
963
964/// Append a claim-granularity attribution to a finding's provenance. Purely
965/// descriptive: it touches no flag, no confidence, no review state, and the gate
966/// never reads `contributions[]` as evidence. Idempotent replay — a contribution
967/// already present (same unit + agent + role) is not duplicated.
968fn apply_finding_contribution_recorded(
969    state: &mut Project,
970    event: &StateEvent,
971    index: &mut FindingIndex,
972) -> Result<(), String> {
973    let id = event.target.id.as_str();
974    let idx = *index.get(id).ok_or_else(|| {
975        format!("reducer: finding.contribution.recorded targets unknown finding {id}")
976    })?;
977    let contribution: crate::bundle::Contribution = serde_json::from_value(
978        event
979            .payload
980            .get("contribution")
981            .cloned()
982            .ok_or("reducer: finding.contribution.recorded missing payload.contribution")?,
983    )
984    .map_err(|e| format!("reducer: malformed contribution: {e}"))?;
985    contribution.validate()?;
986    let existing = &mut state.findings[idx].provenance.contributions;
987    if !existing.iter().any(|c| {
988        c.unit == contribution.unit
989            && c.agent_id == contribution.agent_id
990            && c.role == contribution.role
991    }) {
992        existing.push(contribution);
993    }
994    Ok(())
995}
996
997/// `finding.superseded` targets the OLD finding and flips its
998/// `flags.superseded` (idempotent). The replacement finding is NOT
999/// applied here: the event payload is thin (`{proposal_id,
1000/// new_finding_id}`) and the replacement's body lives in the accepted
1001/// proposal's `payload.new_finding`, entering replay as a genesis seed.
1002/// Note: the writer (`proposals::apply_supersede`) also auto-injects a
1003/// `supersedes` link into the replacement; links are excluded from
1004/// `finding_hash`, so replay verification is unaffected by that
1005/// injection.
1006fn apply_finding_superseded(
1007    state: &mut Project,
1008    event: &StateEvent,
1009    index: &mut FindingIndex,
1010) -> Result<(), String> {
1011    let id = event.target.id.as_str();
1012    let idx = *index
1013        .get(id)
1014        .ok_or_else(|| format!("reducer: finding.superseded targets unknown finding {id}"))?;
1015    state.findings[idx].flags.superseded = true;
1016    Ok(())
1017}
1018
1019/// `assertion.reinterpreted_causal` replays the causal re-grading from
1020/// the event's `payload.after` (`{claim, grade}`), mirroring the writer
1021/// in `state::causal_set`. Invalid vocabulary is an error — the payload
1022/// was validated at emit time, so a mismatch here means a corrupted log.
1023fn apply_assertion_reinterpreted_causal(
1024    state: &mut Project,
1025    event: &StateEvent,
1026    index: &mut FindingIndex,
1027) -> Result<(), String> {
1028    use crate::bundle::{CausalClaim, CausalEvidenceGrade};
1029    let id = event.target.id.as_str();
1030    let idx = *index.get(id).ok_or_else(|| {
1031        format!("reducer: assertion.reinterpreted_causal targets unknown finding {id}")
1032    })?;
1033    let after = event
1034        .payload
1035        .get("after")
1036        .ok_or("reducer: assertion.reinterpreted_causal missing payload.after")?;
1037    let claim = after
1038        .get("claim")
1039        .and_then(Value::as_str)
1040        .ok_or("reducer: assertion.reinterpreted_causal missing payload.after.claim")?;
1041    let parsed_claim = match claim {
1042        "correlation" => CausalClaim::Correlation,
1043        "mediation" => CausalClaim::Mediation,
1044        "intervention" => CausalClaim::Intervention,
1045        other => return Err(format!("reducer: invalid causal claim '{other}'")),
1046    };
1047    let parsed_grade = match after.get("grade").and_then(Value::as_str) {
1048        None => None,
1049        Some("rct") => Some(CausalEvidenceGrade::Rct),
1050        Some("quasi_experimental") => Some(CausalEvidenceGrade::QuasiExperimental),
1051        Some("observational") => Some(CausalEvidenceGrade::Observational),
1052        Some("theoretical") => Some(CausalEvidenceGrade::Theoretical),
1053        Some(other) => return Err(format!("reducer: invalid causal evidence grade '{other}'")),
1054    };
1055    state.findings[idx].assertion.causal_claim = Some(parsed_claim);
1056    if let Some(g) = parsed_grade {
1057        state.findings[idx].assertion.causal_evidence_grade = Some(g);
1058    }
1059    Ok(())
1060}
1061
1062fn apply_finding_dependency_invalidated(
1063    state: &mut Project,
1064    event: &StateEvent,
1065    index: &mut FindingIndex,
1066) -> Result<(), String> {
1067    let id = event.target.id.as_str();
1068    let upstream = event
1069        .payload
1070        .get("upstream_finding_id")
1071        .and_then(Value::as_str)
1072        .unwrap_or("?");
1073    let depth = event
1074        .payload
1075        .get("depth")
1076        .and_then(Value::as_u64)
1077        .unwrap_or(1);
1078    let idx = *index.get(id).ok_or_else(|| {
1079        format!("reducer: finding.dependency_invalidated targets unknown finding {id}")
1080    })?;
1081    state.findings[idx].flags.contested = true;
1082    let annotation_id = format!("ann_dep_{}_{}", &event.id[4..], depth);
1083    if !state.findings[idx]
1084        .annotations
1085        .iter()
1086        .any(|a| a.id == annotation_id)
1087    {
1088        state.findings[idx].annotations.push(Annotation {
1089            id: annotation_id,
1090            text: format!("Upstream {upstream} retracted (cascade depth {depth})."),
1091            author: event.actor.id.clone(),
1092            timestamp: event.timestamp.clone(),
1093            provenance: None,
1094        });
1095    }
1096    Ok(())
1097}
1098
1099fn apply_artifact_asserted(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1100    let artifact_value = event
1101        .payload
1102        .get("artifact")
1103        .ok_or("reducer: artifact.asserted missing payload.artifact")?;
1104    let artifact: crate::bundle::Artifact = serde_json::from_value(artifact_value.clone())
1105        .map_err(|e| format!("reducer: invalid artifact.asserted payload: {e}"))?;
1106    if state.artifacts.iter().any(|a| a.id == artifact.id) {
1107        return Ok(());
1108    }
1109    state.artifacts.push(artifact);
1110    Ok(())
1111}
1112
1113/// Append a verifier attachment (target = `vf_…`) to the sidecar collection.
1114/// Idempotent on the content-addressed `vva_` id. The per-finding trust-gate
1115/// status is derived from these on read (export), never stored here.
1116fn apply_verifier_attachment_added(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1117    let value = event
1118        .payload
1119        .get("attachment")
1120        .ok_or("reducer: verifier_attachment.added missing payload.attachment")?;
1121    let att: crate::verifier_attachment::VerifierAttachment = serde_json::from_value(value.clone())
1122        .map_err(|e| format!("reducer: invalid verifier_attachment.added payload: {e}"))?;
1123    // Re-verify the embedded object's content-addressed id on apply, exactly as
1124    // every sibling object reducer does (this arm previously skipped it, leaving
1125    // a forged-id attachment landable). The gate's G4 id-integrity check is the
1126    // second line of defense; this is the first.
1127    att.verify()
1128        .map_err(|e| format!("reducer: verifier_attachment.added failed id-integrity: {e}"))?;
1129    if state.verifier_attachments.iter().any(|a| a.id == att.id) {
1130        return Ok(());
1131    }
1132    state.verifier_attachments.push(att);
1133    Ok(())
1134}
1135
1136fn apply_artifact_reviewed(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1137    let id = event.target.id.as_str();
1138    let status = event
1139        .payload
1140        .get("status")
1141        .and_then(Value::as_str)
1142        .ok_or("reducer: artifact.reviewed missing payload.status")?;
1143    use crate::bundle::ReviewState;
1144    let new_state = match status {
1145        "accepted" | "approved" => ReviewState::Accepted,
1146        "contested" => ReviewState::Contested,
1147        "needs_revision" => ReviewState::NeedsRevision,
1148        "rejected" => ReviewState::Rejected,
1149        other => return Err(format!("reducer: unsupported review status '{other}'")),
1150    };
1151    let idx = state
1152        .artifacts
1153        .iter()
1154        .position(|a| a.id == id)
1155        .ok_or_else(|| format!("reducer: artifact.reviewed targets unknown artifact {id}"))?;
1156    state.artifacts[idx].review_state = Some(new_state);
1157    Ok(())
1158}
1159
1160fn apply_artifact_retracted(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1161    let id = event.target.id.as_str();
1162    let idx = state
1163        .artifacts
1164        .iter()
1165        .position(|a| a.id == id)
1166        .ok_or_else(|| format!("reducer: artifact.retracted targets unknown artifact {id}"))?;
1167    state.artifacts[idx].retracted = true;
1168    Ok(())
1169}
1170
1171/// v0.51: Apply a `tier.set` event. Re-classifies the access_tier on
1172/// the matched finding / artifact. The validator
1173/// has already checked the object_type and tier strings; here we
1174/// just locate the object and mutate.
1175fn apply_tier_set(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1176    let object_type = event
1177        .payload
1178        .get("object_type")
1179        .and_then(Value::as_str)
1180        .ok_or("reducer: tier.set missing payload.object_type")?;
1181    let object_id = event
1182        .payload
1183        .get("object_id")
1184        .and_then(Value::as_str)
1185        .ok_or("reducer: tier.set missing payload.object_id")?;
1186    let new_tier_str = event
1187        .payload
1188        .get("new_tier")
1189        .and_then(Value::as_str)
1190        .ok_or("reducer: tier.set missing payload.new_tier")?;
1191    let new_tier = crate::access_tier::AccessTier::parse(new_tier_str)
1192        .map_err(|e| format!("reducer: tier.set {e}"))?;
1193    match object_type {
1194        "finding" => {
1195            let idx = state
1196                .findings
1197                .iter()
1198                .position(|f| f.id == object_id)
1199                .ok_or_else(|| format!("reducer: tier.set targets unknown finding {object_id}"))?;
1200            state.findings[idx].access_tier = new_tier;
1201        }
1202        "artifact" => {
1203            let idx = state
1204                .artifacts
1205                .iter()
1206                .position(|a| a.id == object_id)
1207                .ok_or_else(|| format!("reducer: tier.set targets unknown artifact {object_id}"))?;
1208            state.artifacts[idx].access_tier = new_tier;
1209        }
1210        other => {
1211            return Err(format!(
1212                "reducer: tier.set object_type '{other}' must be one of finding, artifact"
1213            ));
1214        }
1215    }
1216    Ok(())
1217}
1218
1219/// v0.213: append a ReleasedDiffPackRecord to
1220/// `state.released_diff_packs` when a `diff_pack.released` event
1221/// lands on the canonical log. Idempotent on pack_id — re-applying
1222/// the same released event is a no-op so hub re-sync stays
1223/// clean. Theorem 29 pins the accumulation algebra.
1224fn apply_diff_pack_released(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1225    use crate::released_diff_pack::ReleasedDiffPackRecord;
1226
1227    let pack_id = event
1228        .payload
1229        .get("pack_id")
1230        .and_then(Value::as_str)
1231        .ok_or("diff_pack.released event missing payload.pack_id")?;
1232    if !pack_id.starts_with("vsd_") {
1233        return Err(format!(
1234            "diff_pack.released event payload.pack_id must start with `vsd_`, got `{pack_id}`"
1235        ));
1236    }
1237    if state
1238        .released_diff_packs
1239        .iter()
1240        .any(|r| r.pack_id == pack_id)
1241    {
1242        return Ok(());
1243    }
1244    let frontier_id = event
1245        .payload
1246        .get("frontier_id")
1247        .and_then(Value::as_str)
1248        .unwrap_or("")
1249        .to_string();
1250    let summary = event
1251        .payload
1252        .get("summary")
1253        .and_then(Value::as_str)
1254        .unwrap_or("")
1255        .to_string();
1256    let aggregate_kind = event
1257        .payload
1258        .get("aggregate_kind")
1259        .and_then(Value::as_str)
1260        .unwrap_or("")
1261        .to_string();
1262    let member_proposals: Vec<String> = event
1263        .payload
1264        .get("members")
1265        .and_then(Value::as_array)
1266        .map(|a| {
1267            a.iter()
1268                .filter_map(Value::as_str)
1269                .map(String::from)
1270                .collect()
1271        })
1272        .unwrap_or_default();
1273    state
1274        .released_diff_packs
1275        .push(ReleasedDiffPackRecord::from_released_event(
1276            pack_id.to_string(),
1277            frontier_id,
1278            summary,
1279            aggregate_kind,
1280            event.timestamp.clone(),
1281            event.id.clone(),
1282            member_proposals,
1283        ));
1284    Ok(())
1285}
1286
1287/// v0.213: update the matching ReleasedDiffPackRecord when a
1288/// `diff_pack.reviewed` event lands. Sets verdict +
1289/// verdict_event_id + reviewer_actor + applied_members +
1290/// sdk_only_members from the payload. Idempotent under
1291/// re-application: re-applying the same verdict to the same
1292/// record produces no further change.
1293///
1294/// If no ReleasedDiffPackRecord exists for the pack_id yet (the
1295/// release event has not been replayed, or the pack was promoted
1296/// without first emitting `diff_pack.released`), the function
1297/// creates a record on the fly from the verdict event's payload
1298/// so the log stays self-sufficient.
1299fn apply_diff_pack_reviewed(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1300    use crate::released_diff_pack::{ReleasedDiffPackRecord, ReleasedVerdict};
1301
1302    let pack_id = event
1303        .payload
1304        .get("pack_id")
1305        .and_then(Value::as_str)
1306        .ok_or("diff_pack.reviewed event missing payload.pack_id")?
1307        .to_string();
1308    if !pack_id.starts_with("vsd_") {
1309        return Err(format!(
1310            "diff_pack.reviewed event payload.pack_id must start with `vsd_`, got `{pack_id}`"
1311        ));
1312    }
1313    let verdict_str = event
1314        .payload
1315        .get("verdict")
1316        .and_then(Value::as_str)
1317        .ok_or("diff_pack.reviewed event missing payload.verdict")?;
1318    let verdict = ReleasedVerdict::from_str_ci(verdict_str).ok_or_else(|| {
1319        format!(
1320            "diff_pack.reviewed event payload.verdict must be accept|reject|revise, got `{verdict_str}`"
1321        )
1322    })?;
1323    let reviewer_actor = event
1324        .payload
1325        .get("reviewer_actor")
1326        .and_then(Value::as_str)
1327        .unwrap_or(&event.actor.id)
1328        .to_string();
1329    let applied: Vec<String> = event
1330        .payload
1331        .get("applied_members")
1332        .and_then(Value::as_array)
1333        .map(|a| {
1334            a.iter()
1335                .filter_map(|v| v.as_str().map(String::from))
1336                .collect()
1337        })
1338        .unwrap_or_default();
1339    let sdk_only: Vec<String> = event
1340        .payload
1341        .get("sdk_only_members")
1342        .and_then(Value::as_array)
1343        .map(|a| {
1344            a.iter()
1345                .filter_map(|v| v.as_str().map(String::from))
1346                .collect()
1347        })
1348        .unwrap_or_default();
1349
1350    if let Some(rec) = state
1351        .released_diff_packs
1352        .iter_mut()
1353        .find(|r| r.pack_id == pack_id)
1354    {
1355        rec.verdict = Some(verdict);
1356        rec.verdict_event_id = Some(event.id.clone());
1357        rec.reviewer_actor = Some(reviewer_actor);
1358        rec.applied_members = applied;
1359        rec.sdk_only_members = sdk_only;
1360    } else {
1361        // No prior `diff_pack.released` event for this pack. Create
1362        // a record from the verdict event so the log stays self-
1363        // sufficient. The promoter typically emits the release event
1364        // before the verdict, but a hub that receives only the
1365        // verdict (e.g., a peer hub that missed the release)
1366        // can still reconstruct a sensible record.
1367        let mut rec = ReleasedDiffPackRecord::from_released_event(
1368            pack_id,
1369            event
1370                .payload
1371                .get("frontier_id")
1372                .and_then(Value::as_str)
1373                .unwrap_or("")
1374                .to_string(),
1375            String::new(),
1376            String::new(),
1377            event.timestamp.clone(),
1378            String::new(),
1379            Vec::new(),
1380        );
1381        rec.verdict = Some(verdict);
1382        rec.verdict_event_id = Some(event.id.clone());
1383        rec.reviewer_actor = Some(reviewer_actor);
1384        rec.applied_members = applied;
1385        rec.sdk_only_members = sdk_only;
1386        state.released_diff_packs.push(rec);
1387    }
1388    Ok(())
1389}
1390
1391/// v0.218: append a VerdictConflict record to
1392/// `state.verdict_conflicts` when a `verdict_conflict.resolved`
1393/// event lands. The full conflict body lives in the event payload
1394/// under `conflict`. Idempotent on conflict_id — re-applying the
1395/// same resolution is a no-op. T32 pins the bounded-length
1396/// accumulation algebra.
1397fn apply_verdict_conflict_resolved(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1398    use crate::verdict_conflict::VerdictConflict;
1399
1400    let conflict_value = event
1401        .payload
1402        .get("conflict")
1403        .ok_or("verdict_conflict.resolved event missing payload.conflict")?
1404        .clone();
1405    let conflict: VerdictConflict = serde_json::from_value(conflict_value)
1406        .map_err(|e| format!("verdict_conflict.resolved payload parse: {e}"))?;
1407    conflict
1408        .verify()
1409        .map_err(|e| format!("verdict_conflict.resolved body did not verify: {e}"))?;
1410    if state
1411        .verdict_conflicts
1412        .iter()
1413        .any(|c| c.conflict_id == conflict.conflict_id)
1414    {
1415        return Ok(());
1416    }
1417    state.verdict_conflicts.push(conflict);
1418    Ok(())
1419}
1420
1421/// T7: upsert a resolved Contradiction into `state.contradictions`
1422/// when a `contradiction.resolved` event lands. The full object lives
1423/// in the event payload under `contradiction`. Integrity check: the
1424/// object's `contradiction_id` must equal the content address of its
1425/// own (frontier_id, finding pair), so a forged or mismatched id is
1426/// rejected. Latest resolution per id wins — re-applying the same
1427/// event is a no-op; a later transition replaces the earlier record.
1428fn apply_contradiction_resolved(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1429    use crate::contradiction::Contradiction;
1430
1431    let value = event
1432        .payload
1433        .get("contradiction")
1434        .ok_or("contradiction.resolved event missing payload.contradiction")?
1435        .clone();
1436    let contradiction: Contradiction = serde_json::from_value(value)
1437        .map_err(|e| format!("contradiction.resolved payload parse: {e}"))?;
1438
1439    let expected = Contradiction::content_address(
1440        &contradiction.frontier_id,
1441        &contradiction.finding_a,
1442        &contradiction.finding_b,
1443    );
1444    if contradiction.contradiction_id != expected {
1445        return Err(format!(
1446            "contradiction.resolved id '{}' does not match its pair (expected '{expected}')",
1447            contradiction.contradiction_id
1448        ));
1449    }
1450
1451    if let Some(slot) = state
1452        .contradictions
1453        .iter_mut()
1454        .find(|c| c.contradiction_id == contradiction.contradiction_id)
1455    {
1456        *slot = contradiction;
1457    } else {
1458        state.contradictions.push(contradiction);
1459    }
1460    Ok(())
1461}
1462
1463/// Idempotent upsert into a content-addressed collection: replace the element
1464/// that matches `item` by `same`, or append it. The shared shape behind the
1465/// attempt/resolution reducer arms.
1466fn upsert_by<T>(vec: &mut Vec<T>, item: T, same: impl Fn(&T, &T) -> bool) {
1467    if let Some(slot) = vec.iter_mut().find(|x| same(x, &item)) {
1468        *slot = item;
1469    } else {
1470        vec.push(item);
1471    }
1472}
1473
1474/// Upsert a signed banked attempt into `state.attempts` when an
1475/// `attempt.deposited` event lands. The full object lives in
1476/// `payload.attempt`. Integrity: the object must `verify()` (id re-derives,
1477/// signature checks, claim_digest matches) — a forged or hand-edited deposit
1478/// is rejected. Idempotent by `vat_` id.
1479/// `statement.attested`: upsert the signed attestation from
1480/// `payload.attestation`. The record's own signature + content address
1481/// are re-verified on every apply — a tampered attestation cannot
1482/// re-enter through replay.
1483/// `attempt.claimed`: append/refresh an obligation lease. The
1484/// determinism rule: a prior lease is "expired" relative to THIS
1485/// event's timestamp (parse both RFC3339 instants; if claimed_at + ttl
1486/// <= new event's timestamp, the old lease is dead and the claim
1487/// succeeds). Same claimant refreshing their own live lease is allowed only
1488/// under the same key. A zero-TTL update is an immediate release and must
1489/// compare-and-swap the exact current claim event with the same actor and key.
1490fn apply_attempt_claimed(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1491    let p = &event.payload;
1492    let obligation_id = p
1493        .get("obligation_id")
1494        .and_then(Value::as_str)
1495        .ok_or("attempt.claimed missing payload.obligation_id")?;
1496    let ttl = p
1497        .get("lease_ttl_seconds")
1498        .and_then(Value::as_u64)
1499        .ok_or("attempt.claimed missing payload.lease_ttl_seconds")?;
1500    if ttl > crate::events::MAX_ATTEMPT_LEASE_TTL_SECONDS {
1501        return Err(format!(
1502            "attempt.claimed payload.lease_ttl_seconds must be at most {}",
1503            crate::events::MAX_ATTEMPT_LEASE_TTL_SECONDS
1504        ));
1505    }
1506    let claimant_actor = p
1507        .get("claimant_actor")
1508        .and_then(Value::as_str)
1509        .unwrap_or(&event.actor.id)
1510        .to_string();
1511    let claimant_pubkey = p
1512        .get("claimant_pubkey")
1513        .and_then(Value::as_str)
1514        .unwrap_or("")
1515        .to_string();
1516    if claimant_actor != event.actor.id {
1517        return Err(format!(
1518            "attempt.claimed payload claimant {claimant_actor} does not match event actor {}",
1519            event.actor.id
1520        ));
1521    }
1522    if event.target.id != obligation_id {
1523        return Err(format!(
1524            "attempt.claimed target {} does not match obligation {obligation_id}",
1525            event.target.id
1526        ));
1527    }
1528    let prior_claim_event_id = p.get("prior_claim_event_id").and_then(Value::as_str);
1529    let release_reason = p.get("release_reason").and_then(Value::as_str);
1530    let parse = chrono::DateTime::parse_from_rfc3339;
1531    let event_at = parse(&event.timestamp)
1532        .map_err(|e| format!("attempt.claimed: bad event timestamp: {e}"))?;
1533    let live_at_event = |claimed_at: &chrono::DateTime<chrono::FixedOffset>, lease_ttl: u64| {
1534        i64::try_from(lease_ttl)
1535            .ok()
1536            .and_then(chrono::Duration::try_seconds)
1537            .and_then(|duration| claimed_at.checked_add_signed(duration))
1538            .is_some_and(|expires_at| expires_at > event_at)
1539    };
1540    let existing = state
1541        .attempt_claims
1542        .iter()
1543        .find(|c| c.obligation_id == obligation_id)
1544        .cloned();
1545    if ttl == 0 {
1546        let existing = existing.as_ref().ok_or_else(|| {
1547            format!("cannot release obligation {obligation_id}: no current lease exists")
1548        })?;
1549        let claimed_at = parse(&existing.claimed_at)
1550            .map_err(|e| format!("attempt.claimed: bad prior claim timestamp: {e}"))?;
1551        if !live_at_event(&claimed_at, existing.lease_ttl_seconds) {
1552            return Err(format!(
1553                "cannot release obligation {obligation_id}: the current lease is not live"
1554            ));
1555        }
1556        if event_at < claimed_at {
1557            return Err(format!(
1558                "cannot release obligation {obligation_id}: release timestamp predates the prior claim"
1559            ));
1560        }
1561        if existing.claimant_actor != claimant_actor {
1562            return Err(format!(
1563                "cannot release obligation {obligation_id}: leased by {}, not {claimant_actor}",
1564                existing.claimant_actor
1565            ));
1566        }
1567        if existing.claimant_pubkey != claimant_pubkey {
1568            return Err(format!(
1569                "cannot release obligation {obligation_id}: claimant key does not match the current lease"
1570            ));
1571        }
1572        let expected_prior = existing.claim_event_id.as_deref().ok_or_else(|| {
1573            format!(
1574                "cannot release obligation {obligation_id}: prior lease identity is unavailable"
1575            )
1576        })?;
1577        if prior_claim_event_id != Some(expected_prior) {
1578            return Err(format!(
1579                "cannot release obligation {obligation_id}: prior lease identity does not match"
1580            ));
1581        }
1582        if release_reason.is_none_or(|reason| reason.trim().is_empty()) {
1583            return Err(format!(
1584                "cannot release obligation {obligation_id}: release reason is required"
1585            ));
1586        }
1587    } else if let Some(existing) = existing.as_ref() {
1588        let live = parse(&existing.claimed_at)
1589            .map(|claimed_at| live_at_event(&claimed_at, existing.lease_ttl_seconds))
1590            .unwrap_or(false);
1591        if live && existing.claimant_actor != claimant_actor {
1592            return Err(format!(
1593                "obligation {obligation_id} is leased by {} until +{}s; route around it or wait for expiry",
1594                existing.claimant_actor, existing.lease_ttl_seconds
1595            ));
1596        }
1597        if live && existing.claimant_pubkey != claimant_pubkey {
1598            return Err(format!(
1599                "obligation {obligation_id} is leased by {claimant_actor} under a different key; use the original session key or wait for expiry"
1600            ));
1601        }
1602        if live
1603            && prior_claim_event_id.is_some()
1604            && prior_claim_event_id != existing.claim_event_id.as_deref()
1605        {
1606            return Err(format!(
1607                "obligation {obligation_id} refresh names a stale prior lease"
1608            ));
1609        }
1610    }
1611    state
1612        .attempt_claims
1613        .retain(|c| c.obligation_id != obligation_id);
1614    state.attempt_claims.push(crate::project::AttemptClaim {
1615        obligation_id: obligation_id.to_string(),
1616        claimant_actor,
1617        claimant_pubkey,
1618        claimed_at: event.timestamp.clone(),
1619        lease_ttl_seconds: ttl,
1620        claim_event_id: Some(event.id.clone()),
1621    });
1622    Ok(())
1623}
1624
1625/// `statement.registered`: append a priority registration (idempotent
1626/// on statement_hash).
1627fn apply_statement_registered(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1628    let p = &event.payload;
1629    let hash = p
1630        .get("statement_hash")
1631        .and_then(Value::as_str)
1632        .ok_or("statement.registered missing payload.statement_hash")?;
1633    if hash.len() != 64 || hex::decode(hash).is_err() {
1634        return Err("statement_hash must be 32 bytes of hex".to_string());
1635    }
1636    if state
1637        .statement_registrations
1638        .iter()
1639        .any(|r| r.statement_hash == hash)
1640    {
1641        return Ok(());
1642    }
1643    state
1644        .statement_registrations
1645        .push(crate::project::StatementRegistration {
1646            statement_hash: hash.to_string(),
1647            informal_ref: p
1648                .get("informal_ref")
1649                .and_then(Value::as_str)
1650                .unwrap_or("")
1651                .to_string(),
1652            registered_by: event.actor.id.clone(),
1653            registered_at: event.timestamp.clone(),
1654            // Gap 5 (STATE_PLANE_MEMO appendix): the optional
1655            // finding-to-registration edge. Old events carry no
1656            // payload.finding_id and store None.
1657            finding_id: p
1658                .get("finding_id")
1659                .and_then(Value::as_str)
1660                .map(str::to_string),
1661        });
1662    Ok(())
1663}
1664
1665fn apply_statement_attested(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1666    use crate::statement_attestation::StatementAttestation;
1667    let value = event
1668        .payload
1669        .get("attestation")
1670        .ok_or("statement.attested event missing payload.attestation")?
1671        .clone();
1672    let att: StatementAttestation = serde_json::from_value(value)
1673        .map_err(|e| format!("statement.attested payload parse: {e}"))?;
1674    att.verify()
1675        .map_err(|e| format!("statement.attested rejected: {e}"))?;
1676    if let Some(existing) = state
1677        .statement_attestations
1678        .iter_mut()
1679        .find(|a| a.id == att.id)
1680    {
1681        *existing = att;
1682    } else {
1683        state.statement_attestations.push(att);
1684    }
1685    Ok(())
1686}
1687
1688/// `anchor.attached`: upsert a signed `val_` anchor link from
1689/// `payload.anchor_link`. The link's own signature + content address are
1690/// re-verified on every apply, so a tampered anchor cannot enter state.
1691fn apply_anchor_attached(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1692    use crate::anchor::AnchorLink;
1693    let value = event
1694        .payload
1695        .get("anchor_link")
1696        .ok_or("anchor.attached event missing payload.anchor_link")?
1697        .clone();
1698    let link: AnchorLink =
1699        serde_json::from_value(value).map_err(|e| format!("anchor.attached payload parse: {e}"))?;
1700    link.verify()
1701        .map_err(|e| format!("anchor.attached rejected: {e}"))?;
1702    if let Some(existing) = state.anchor_links.iter_mut().find(|a| a.id == link.id) {
1703        *existing = link;
1704    } else {
1705        state.anchor_links.push(link);
1706    }
1707    Ok(())
1708}
1709
1710/// `anchor.retracted`: remove the anchor link named by
1711/// `payload.anchor_link_id`. Anchor attachment is fallible and therefore
1712/// retractable (frontier-calculus Law 22). Retracting an absent id is a
1713/// no-op, so replay stays idempotent.
1714fn apply_anchor_retracted(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1715    let id = event
1716        .payload
1717        .get("anchor_link_id")
1718        .and_then(|v| v.as_str())
1719        .ok_or("anchor.retracted event missing payload.anchor_link_id")?;
1720    state.anchor_links.retain(|a| a.id != id);
1721    Ok(())
1722}
1723
1724fn apply_attempt_deposited(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1725    use crate::attempt::Attempt;
1726
1727    let value = event
1728        .payload
1729        .get("attempt")
1730        .ok_or("attempt.deposited event missing payload.attempt")?
1731        .clone();
1732    let attempt: Attempt = serde_json::from_value(value)
1733        .map_err(|e| format!("attempt.deposited payload parse: {e}"))?;
1734    attempt
1735        .verify()
1736        .map_err(|e| format!("attempt.deposited rejected: {e}"))?;
1737
1738    upsert_by(&mut state.attempts, attempt, |a, b| {
1739        a.attempt_id == b.attempt_id
1740    });
1741    Ok(())
1742}
1743
1744/// Upsert a signed cross-domain transfer into `state.transfers` when a
1745/// `transfer.deposited` event lands. The full object lives in
1746/// `payload.transfer`. Integrity: the object must `verify()` (id re-derives,
1747/// signature checks) — a forged or hand-edited transfer is rejected. Admission
1748/// (whether the link is sound) is NOT decided here; it is derived on read via
1749/// `transfer::derive_transfer_status`. Idempotent by `vtr_` id.
1750fn apply_transfer_deposited(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1751    use crate::transfer::Transfer;
1752
1753    let value = event
1754        .payload
1755        .get("transfer")
1756        .ok_or("transfer.deposited event missing payload.transfer")?
1757        .clone();
1758    let transfer: Transfer = serde_json::from_value(value)
1759        .map_err(|e| format!("transfer.deposited payload parse: {e}"))?;
1760    transfer
1761        .verify()
1762        .map_err(|e| format!("transfer.deposited rejected: {e}"))?;
1763
1764    upsert_by(&mut state.transfers, transfer, |a, b| {
1765        a.transfer_id == b.transfer_id
1766    });
1767    Ok(())
1768}
1769
1770/// Upsert a signed significance endorsement into `state.endorsements` when an
1771/// `endorsement.deposited` event lands. The object lives in
1772/// `payload.endorsement`. Integrity: it must `verify()` (id re-derives,
1773/// signature checks). Idempotent by `ven_` id. There is deliberately NO
1774/// aggregation here — endorsements accumulate as individual records and are
1775/// never folded into a significance score.
1776fn apply_endorsement_deposited(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1777    use crate::endorsement::Endorsement;
1778
1779    let value = event
1780        .payload
1781        .get("endorsement")
1782        .ok_or("endorsement.deposited event missing payload.endorsement")?
1783        .clone();
1784    let endorsement: Endorsement = serde_json::from_value(value)
1785        .map_err(|e| format!("endorsement.deposited payload parse: {e}"))?;
1786    endorsement
1787        .verify()
1788        .map_err(|e| format!("endorsement.deposited rejected: {e}"))?;
1789
1790    upsert_by(&mut state.endorsements, endorsement, |a, b| {
1791        a.endorsement_id == b.endorsement_id
1792    });
1793    Ok(())
1794}
1795
1796/// Append a lifecycle transition into `state.attempt_resolutions` when an
1797/// `attempt.resolved` event lands. The [`crate::attempt::ResolutionEvent`]
1798/// lives in `payload.resolution`. Integrity: the object must `verify()`
1799/// (`vre_` id re-derives). Idempotent by `vre_` id; the head per attempt is
1800/// the latest by `at`, computed on read (`Project::head_resolution`).
1801fn apply_attempt_resolved(state: &mut Project, event: &StateEvent) -> Result<(), String> {
1802    use crate::attempt::ResolutionEvent;
1803
1804    let value = event
1805        .payload
1806        .get("resolution")
1807        .ok_or("attempt.resolved event missing payload.resolution")?
1808        .clone();
1809    let resolution: ResolutionEvent = serde_json::from_value(value)
1810        .map_err(|e| format!("attempt.resolved payload parse: {e}"))?;
1811    resolution
1812        .verify()
1813        .map_err(|e| format!("attempt.resolved rejected: {e}"))?;
1814
1815    upsert_by(&mut state.attempt_resolutions, resolution, |a, b| {
1816        a.resolution_id == b.resolution_id
1817    });
1818    Ok(())
1819}
1820
1821/// v0.57: Apply a `finding.span_repaired` event. Appends a
1822/// `{section, text}` span object to
1823/// `state.findings[i].evidence.evidence_spans`. Idempotent:
1824/// applying twice with the same (section, text) pair is a no-op.
1825fn apply_finding_span_repaired(
1826    state: &mut Project,
1827    event: &StateEvent,
1828    index: &mut FindingIndex,
1829) -> Result<(), String> {
1830    if event.target.r#type != "finding" {
1831        return Err(format!(
1832            "reducer: finding.span_repaired target.type must be 'finding', got '{}'",
1833            event.target.r#type
1834        ));
1835    }
1836    let finding_id = event.target.id.as_str();
1837    let section = event
1838        .payload
1839        .get("section")
1840        .and_then(Value::as_str)
1841        .ok_or("reducer: finding.span_repaired missing payload.section")?;
1842    let text = event
1843        .payload
1844        .get("text")
1845        .and_then(Value::as_str)
1846        .ok_or("reducer: finding.span_repaired missing payload.text")?;
1847    let idx = *index.get(finding_id).ok_or_else(|| {
1848        format!("reducer: finding.span_repaired targets unknown finding {finding_id}")
1849    })?;
1850    let span_value = serde_json::json!({"section": section, "text": text});
1851    let already_present = state.findings[idx]
1852        .evidence
1853        .evidence_spans
1854        .iter()
1855        .any(|existing| {
1856            existing.get("section").and_then(Value::as_str) == Some(section)
1857                && existing.get("text").and_then(Value::as_str) == Some(text)
1858        });
1859    if !already_present {
1860        state.findings[idx].evidence.evidence_spans.push(span_value);
1861    }
1862    Ok(())
1863}
1864
1865/// v0.56: Apply an `evidence_atom.locator_repaired` event. Sets
1866/// `locator` on the named atom and removes the "missing evidence
1867/// locator" caveat if present. Idempotent: applying twice with the
1868/// same locator is a no-op. Mismatched locator values fail the reduce
1869/// rather than silently overwriting, since divergent locators on the
1870/// same atom are a chain-integrity issue, not a repair.
1871fn apply_evidence_atom_locator_repaired(
1872    state: &mut Project,
1873    event: &StateEvent,
1874) -> Result<(), String> {
1875    if event.target.r#type != "evidence_atom" {
1876        return Err(format!(
1877            "reducer: evidence_atom.locator_repaired target.type must be 'evidence_atom', got '{}'",
1878            event.target.r#type
1879        ));
1880    }
1881    let atom_id = event.target.id.as_str();
1882    let locator = event
1883        .payload
1884        .get("locator")
1885        .and_then(Value::as_str)
1886        .ok_or("reducer: evidence_atom.locator_repaired missing payload.locator")?;
1887    let idx = state
1888        .evidence_atoms
1889        .iter()
1890        .position(|atom| atom.id == atom_id)
1891        .ok_or_else(|| {
1892            format!("reducer: evidence_atom.locator_repaired targets unknown atom {atom_id}")
1893        })?;
1894    if let Some(existing) = &state.evidence_atoms[idx].locator
1895        && existing != locator
1896    {
1897        return Err(format!(
1898            "reducer: evidence_atom {atom_id} already has locator '{existing}', refusing to overwrite with '{locator}'"
1899        ));
1900    }
1901    state.evidence_atoms[idx].locator = Some(locator.to_string());
1902    state.evidence_atoms[idx]
1903        .caveats
1904        .retain(|c| c != "missing evidence locator");
1905    Ok(())
1906}
1907
1908#[cfg(test)]
1909mod tests {
1910    use super::*;
1911    use crate::bundle::{Assertion, Conditions, Confidence, Evidence, Flags, Provenance};
1912    use crate::events::{FindingEventInput, NULL_HASH, StateActor, StateTarget};
1913    use chrono::Utc;
1914    use serde_json::json;
1915
1916    fn lease_event(
1917        actor: &str,
1918        pubkey: &str,
1919        at: &str,
1920        ttl: u64,
1921        prior: Option<&str>,
1922        reason: Option<&str>,
1923    ) -> StateEvent {
1924        let mut payload = json!({
1925            "obligation_id": "scope:lease-cas",
1926            "lease_ttl_seconds": ttl,
1927            "claimant_actor": actor,
1928            "claimant_pubkey": pubkey,
1929        });
1930        if let Some(prior) = prior {
1931            payload["prior_claim_event_id"] = json!(prior);
1932        }
1933        if let Some(reason) = reason {
1934            payload["release_reason"] = json!(reason);
1935        }
1936        crate::events::new_finding_event(FindingEventInput {
1937            kind: crate::events::EVENT_KIND_ATTEMPT_CLAIMED,
1938            finding_id: "scope:lease-cas",
1939            actor_id: actor,
1940            actor_type: "agent",
1941            reason: reason.unwrap_or("claim fixture"),
1942            before_hash: NULL_HASH,
1943            after_hash: NULL_HASH,
1944            payload,
1945            caveats: Vec::new(),
1946            timestamp: Some(at),
1947        })
1948    }
1949
1950    fn state_with_claim(claim: &StateEvent) -> crate::project::Project {
1951        let mut state = crate::project::assemble("lease", Vec::new(), 0, 0, "test");
1952        apply_event(&mut state, claim).unwrap();
1953        state
1954    }
1955
1956    #[test]
1957    fn zero_ttl_lease_release_is_an_exact_same_owner_compare_and_swap() {
1958        let claim = lease_event(
1959            "agent:owner",
1960            &"11".repeat(32),
1961            "2026-07-14T12:00:00.500Z",
1962            3_600,
1963            None,
1964            None,
1965        );
1966        let initial = state_with_claim(&claim);
1967        assert_eq!(
1968            initial.attempt_claims[0].claim_event_id.as_deref(),
1969            Some(claim.id.as_str())
1970        );
1971
1972        for (label, release, expected) in [
1973            (
1974                "different actor",
1975                lease_event(
1976                    "agent:other",
1977                    &"11".repeat(32),
1978                    "2026-07-14T12:01:00Z",
1979                    0,
1980                    Some(&claim.id),
1981                    Some("not mine"),
1982                ),
1983                "leased by agent:owner",
1984            ),
1985            (
1986                "different key",
1987                lease_event(
1988                    "agent:owner",
1989                    &"22".repeat(32),
1990                    "2026-07-14T12:01:00Z",
1991                    0,
1992                    Some(&claim.id),
1993                    Some("wrong key"),
1994                ),
1995                "key does not match",
1996            ),
1997            (
1998                "stale predecessor",
1999                lease_event(
2000                    "agent:owner",
2001                    &"11".repeat(32),
2002                    "2026-07-14T12:01:00Z",
2003                    0,
2004                    Some("vev_0000000000000000"),
2005                    Some("stale"),
2006                ),
2007                "prior lease identity does not match",
2008            ),
2009            (
2010                "backdated",
2011                lease_event(
2012                    "agent:owner",
2013                    &"11".repeat(32),
2014                    "2026-07-14T12:00:00.499Z",
2015                    0,
2016                    Some(&claim.id),
2017                    Some("backdated"),
2018                ),
2019                "predates the prior claim",
2020            ),
2021        ] {
2022            let mut state = state_with_claim(&claim);
2023            let error = apply_event(&mut state, &release).unwrap_err();
2024            assert!(error.contains(expected), "{label}: {error}");
2025            assert_eq!(state.attempt_claims, initial.attempt_claims, "{label}");
2026        }
2027
2028        let mut state = initial;
2029        let release = lease_event(
2030            "agent:owner",
2031            &"11".repeat(32),
2032            "2026-07-14T12:01:00Z",
2033            0,
2034            Some(&claim.id),
2035            Some("switching approaches"),
2036        );
2037        apply_event(&mut state, &release).unwrap();
2038        assert_eq!(state.attempt_claims.len(), 1);
2039        assert_eq!(state.attempt_claims[0].lease_ttl_seconds, 0);
2040        assert_eq!(
2041            state.attempt_claims[0].claim_event_id.as_deref(),
2042            Some(release.id.as_str())
2043        );
2044    }
2045
2046    #[test]
2047    fn live_lease_refresh_requires_the_same_actor_key() {
2048        let mut state = crate::project::assemble("lease", Vec::new(), 0, 0, "test");
2049        let claim = lease_event(
2050            "agent:owner",
2051            &"11".repeat(32),
2052            "2026-07-14T12:00:00Z",
2053            3_600,
2054            None,
2055            None,
2056        );
2057        apply_event(&mut state, &claim).unwrap();
2058        let refresh = lease_event(
2059            "agent:owner",
2060            &"22".repeat(32),
2061            "2026-07-14T12:01:00Z",
2062            3_600,
2063            Some(&claim.id),
2064            None,
2065        );
2066        let error = apply_event(&mut state, &refresh).unwrap_err();
2067        assert!(error.contains("different key"), "{error}");
2068    }
2069
2070    fn finding(id: &str) -> crate::bundle::FindingBundle {
2071        crate::bundle::FindingBundle::new(
2072            Assertion {
2073                text: format!("test finding {id}"),
2074                assertion_type: "mechanism".to_string(),
2075                entities: Vec::new(),
2076                relation: None,
2077                direction: None,
2078                causal_claim: None,
2079                causal_evidence_grade: None,
2080            },
2081            Evidence {
2082                evidence_type: "experimental".to_string(),
2083                model_system: String::new(),
2084                method: "test".to_string(),
2085                replicated: false,
2086                replication_count: None,
2087                evidence_spans: Vec::new(),
2088            },
2089            Conditions {
2090                text: "test".to_string(),
2091                duration: None,
2092            },
2093            Confidence::raw(0.5, "test", 0.8),
2094            Provenance {
2095                source_type: "published_paper".to_string(),
2096                doi: Some(format!("10.1/test-{id}")),
2097                url: None,
2098                title: format!("Source for {id}"),
2099                authors: Vec::new(),
2100                year: Some(2026),
2101                license: None,
2102                publisher: None,
2103                funders: Vec::new(),
2104                extraction: crate::bundle::Extraction::default(),
2105                review: None,
2106                contributions: Vec::new(),
2107            },
2108            Flags {
2109                gap: false,
2110                negative_space: false,
2111                contested: false,
2112                retracted: false,
2113                declining: false,
2114                gravity_well: false,
2115                review_state: None,
2116                superseded: false,
2117                signature_threshold: None,
2118                jointly_accepted: false,
2119            },
2120        )
2121    }
2122
2123    #[test]
2124    fn replay_with_no_events_is_identity() {
2125        let state = project::assemble("test", vec![finding("a")], 0, 0, "test");
2126        let v = verify_replay(&state);
2127        assert!(v.ok, "diffs: {:?} note: {}", v.diffs, v.note);
2128        assert_eq!(v.replayed_snapshot_hash, v.materialized_snapshot_hash);
2129    }
2130
2131    #[test]
2132    fn reducer_marks_finding_contested() {
2133        let f = finding("a");
2134        let mut state = project::assemble("test", vec![f.clone()], 0, 0, "test");
2135        let event = events::new_finding_event(FindingEventInput {
2136            kind: "finding.reviewed",
2137            finding_id: &f.id,
2138            actor_id: "reviewer:test",
2139            actor_type: "human",
2140            reason: "test",
2141            before_hash: &events::finding_hash(&f),
2142            after_hash: NULL_HASH,
2143            payload: json!({"status": "contested"}),
2144            caveats: vec![],
2145            timestamp: None,
2146        });
2147        apply_event(&mut state, &event).unwrap();
2148        assert!(state.findings[0].flags.contested);
2149    }
2150
2151    #[test]
2152    fn classify_provenance_separates_inline_from_remnant() {
2153        // `inline` carries its body in a finding.asserted event; `rem` has
2154        // no event at all (a pre-event-sourcing remnant seeded from cache).
2155        let inline = finding("inline");
2156        let rem = finding("rem");
2157        let mut state = project::assemble("test", vec![inline.clone(), rem.clone()], 0, 0, "test");
2158        state.events.push(StateEvent {
2159            schema: events::EVENT_SCHEMA.to_string(),
2160            id: "vev_inline".to_string(),
2161            kind: "finding.asserted".into(),
2162            target: StateTarget {
2163                r#type: "finding".to_string(),
2164                id: inline.id.clone(),
2165            },
2166            actor: StateActor {
2167                id: "reviewer:test".to_string(),
2168                r#type: "human".to_string(),
2169            },
2170            timestamp: Utc::now().to_rfc3339(),
2171            reason: "assert".to_string(),
2172            before_hash: NULL_HASH.to_string(),
2173            after_hash: events::finding_hash(&inline),
2174            payload: json!({ "finding": inline }),
2175            caveats: vec![],
2176            signature: None,
2177        });
2178
2179        let report = classify_provenance(&state);
2180        assert_eq!(report.inline, vec![inline.id.clone()]);
2181        assert_eq!(report.remnant, vec![rem.id.clone()]);
2182        assert!(report.proposal_backed.is_empty());
2183        assert!(
2184            !report.fully_event_sourced(),
2185            "a frontier with a remnant is not fully event-sourced"
2186        );
2187
2188        // Removing the remnant leaves an all-inline frontier: fully reducible.
2189        state.findings.retain(|f| f.id != rem.id);
2190        assert!(classify_provenance(&state).fully_event_sourced());
2191    }
2192
2193    #[test]
2194    fn reducer_retracts_finding() {
2195        let f = finding("a");
2196        let mut state = project::assemble("test", vec![f.clone()], 0, 0, "test");
2197        let event = StateEvent {
2198            schema: events::EVENT_SCHEMA.to_string(),
2199            id: "vev_test".to_string(),
2200            kind: "finding.retracted".into(),
2201            target: StateTarget {
2202                r#type: "finding".to_string(),
2203                id: f.id.clone(),
2204            },
2205            actor: StateActor {
2206                id: "reviewer:test".to_string(),
2207                r#type: "human".to_string(),
2208            },
2209            timestamp: Utc::now().to_rfc3339(),
2210            reason: "test retraction".to_string(),
2211            before_hash: events::finding_hash(&f),
2212            after_hash: NULL_HASH.to_string(),
2213            payload: json!({"proposal_id": "vpr_x"}),
2214            caveats: vec![],
2215            signature: None,
2216        };
2217        apply_event(&mut state, &event).unwrap();
2218        assert!(state.findings[0].flags.retracted);
2219    }
2220
2221    #[test]
2222    fn confidence_revision_replay_uses_event_payload_timestamp() {
2223        let f = finding("a");
2224        let mut expected = f.clone();
2225        let updated_at = "2026-05-07T23:30:00Z";
2226        let reason = "lower confidence after review";
2227        expected.confidence.score = 0.42;
2228        expected.confidence.basis = format!(
2229            "expert revision from {:.3} to {:.3}: {}",
2230            f.confidence.score, 0.42, reason
2231        );
2232        expected.confidence.method = ConfidenceMethod::ExpertJudgment;
2233        expected.updated = Some(updated_at.to_string());
2234        let mut state = project::assemble("test", vec![f.clone()], 0, 0, "test");
2235        let event = StateEvent {
2236            schema: events::EVENT_SCHEMA.to_string(),
2237            id: "vev_confidence".to_string(),
2238            kind: "finding.confidence_revised".into(),
2239            target: StateTarget {
2240                r#type: "finding".to_string(),
2241                id: f.id.clone(),
2242            },
2243            actor: StateActor {
2244                id: "reviewer:test".to_string(),
2245                r#type: "human".to_string(),
2246            },
2247            timestamp: "2026-05-07T23:31:00Z".to_string(),
2248            reason: reason.to_string(),
2249            before_hash: events::finding_hash(&f),
2250            after_hash: events::finding_hash(&expected),
2251            payload: json!({
2252                "previous_score": f.confidence.score,
2253                "new_score": 0.42,
2254                "updated_at": updated_at,
2255            }),
2256            caveats: vec![],
2257            signature: None,
2258        };
2259
2260        apply_event(&mut state, &event).unwrap();
2261
2262        assert_eq!(state.findings[0].updated.as_deref(), Some(updated_at));
2263        assert_eq!(events::finding_hash(&state.findings[0]), event.after_hash);
2264    }
2265
2266    #[test]
2267    fn reducer_rejects_unknown_kind() {
2268        let mut state = project::assemble("test", vec![], 0, 0, "test");
2269        let event = StateEvent {
2270            schema: events::EVENT_SCHEMA.to_string(),
2271            id: "vev_test".to_string(),
2272            kind: "finding.unknown_kind".into(),
2273            target: StateTarget {
2274                r#type: "finding".to_string(),
2275                id: "vf_x".to_string(),
2276            },
2277            actor: StateActor {
2278                id: "x".to_string(),
2279                r#type: "human".to_string(),
2280            },
2281            timestamp: Utc::now().to_rfc3339(),
2282            reason: "x".to_string(),
2283            before_hash: NULL_HASH.to_string(),
2284            after_hash: NULL_HASH.to_string(),
2285            payload: Value::Null,
2286            caveats: vec![],
2287            signature: None,
2288        };
2289        let r = apply_event(&mut state, &event);
2290        assert!(r.is_err());
2291    }
2292
2293    /// v0.49.3: the dispatch table in `apply_event` and the
2294    /// `REDUCER_MUTATION_KINDS` constant must agree. Adding a new
2295    /// match arm without updating the constant (or vice versa) makes
2296    /// CI fail loudly here, which then makes the cross-impl fixture
2297    /// coverage assertion fail correctly downstream. This is the
2298    /// single source of truth that retires the hand-maintained mirror.
2299    #[test]
2300    fn dispatch_handles_every_declared_kind() {
2301        for kind in REDUCER_MUTATION_KINDS {
2302            let mut state = project::assemble("test", vec![], 0, 0, "test");
2303            // Dummy event with the declared kind. The handler may
2304            // reject the payload (it's empty), but it MUST NOT reject
2305            // the kind itself with "unsupported event kind" — that
2306            // would prove the dispatch table is missing an arm for
2307            // a kind the constant declares.
2308            let event = StateEvent {
2309                schema: events::EVENT_SCHEMA.to_string(),
2310                id: "vev_dispatch_check".to_string(),
2311                kind: (*kind).into(),
2312                target: StateTarget {
2313                    r#type: "finding".to_string(),
2314                    id: "vf_x".to_string(),
2315                },
2316                actor: StateActor {
2317                    id: "x".to_string(),
2318                    r#type: "human".to_string(),
2319                },
2320                timestamp: Utc::now().to_rfc3339(),
2321                reason: String::new(),
2322                before_hash: NULL_HASH.to_string(),
2323                after_hash: NULL_HASH.to_string(),
2324                payload: Value::Null,
2325                caveats: vec![],
2326                signature: None,
2327            };
2328            let r = apply_event(&mut state, &event);
2329            if let Err(e) = r {
2330                assert!(
2331                    !e.contains("unsupported event kind"),
2332                    "kind {kind:?} declared in REDUCER_MUTATION_KINDS \
2333                     but rejected by apply_event dispatch: {e}"
2334                );
2335            }
2336        }
2337    }
2338
2339    /// The writer/reducer seam invariant: every kind the protocol can
2340    /// emit or store (`events::KNOWN_EVENT_KINDS` — the writer-side
2341    /// universe) must be handled by the dispatch, either with a real arm
2342    /// or an explicit no-op. A new writer kind without a reducer arm
2343    /// fails here instead of erroring on the next replay of a live log.
2344    /// (This is the test that would have caught `finding.superseded`
2345    /// being emittable-but-unreplayable.)
2346    #[test]
2347    fn every_known_kind_reduces() {
2348        for kind in events::KNOWN_EVENT_KINDS {
2349            let mut state = project::assemble("test", vec![], 0, 0, "test");
2350            let event = StateEvent {
2351                schema: events::EVENT_SCHEMA.to_string(),
2352                id: "vev_known_kind_check".to_string(),
2353                kind: (*kind).into(),
2354                target: StateTarget {
2355                    r#type: "finding".to_string(),
2356                    id: "vf_x".to_string(),
2357                },
2358                actor: StateActor {
2359                    id: "x".to_string(),
2360                    r#type: "human".to_string(),
2361                },
2362                timestamp: Utc::now().to_rfc3339(),
2363                reason: String::new(),
2364                before_hash: NULL_HASH.to_string(),
2365                after_hash: NULL_HASH.to_string(),
2366                payload: Value::Null,
2367                caveats: vec![],
2368                signature: None,
2369            };
2370            if let Err(e) = apply_event(&mut state, &event) {
2371                assert!(
2372                    !e.contains("unsupported event kind"),
2373                    "kind {kind:?} is in events::KNOWN_EVENT_KINDS (a writer \
2374                     can emit it) but the reducer dispatch rejects it: {e}"
2375                );
2376            }
2377        }
2378    }
2379
2380    fn project_with_one_atom(missing_locator: bool) -> Project {
2381        // `project::assemble` calls `sources::materialize_project`,
2382        // which derives one evidence atom per finding. The hand-built
2383        // atom below is appended after materialization with a distinct
2384        // id (`vea_test_atom`), so it survives alongside the derived
2385        // atom. Tests look up atoms by id via `atom_by_id`.
2386        let mut state = project::assemble("test-locator", vec![finding("a")], 0, 0, "test");
2387        state.sources.push(crate::sources::SourceRecord {
2388            id: "vs_test_source".to_string(),
2389            source_type: "paper".to_string(),
2390            locator: "doi:10.1/test-source".to_string(),
2391            content_hash: None,
2392            title: "Test source".to_string(),
2393            authors: Vec::new(),
2394            year: Some(2026),
2395            doi: Some("10.1/test-source".to_string()),
2396            pmid: None,
2397            imported_at: "2026-01-01T00:00:00Z".to_string(),
2398            extraction_mode: "manual".to_string(),
2399            source_quality: "declared".to_string(),
2400            caveats: Vec::new(),
2401            finding_ids: vec![state.findings[0].id.clone()],
2402        });
2403        state.evidence_atoms.push(crate::sources::EvidenceAtom {
2404            id: "vea_test_atom".to_string(),
2405            source_id: "vs_test_source".to_string(),
2406            finding_id: state.findings[0].id.clone(),
2407            locator: if missing_locator {
2408                None
2409            } else {
2410                Some("doi:10.1/already-set".to_string())
2411            },
2412            evidence_type: "experimental".to_string(),
2413            measurement_or_claim: "test claim".to_string(),
2414            supports_or_challenges: "supports".to_string(),
2415            condition_refs: Vec::new(),
2416            extraction_method: "manual".to_string(),
2417            human_verified: false,
2418            caveats: if missing_locator {
2419                vec!["missing evidence locator".to_string()]
2420            } else {
2421                Vec::new()
2422            },
2423        });
2424        state
2425    }
2426
2427    fn atom_by_id<'a>(state: &'a Project, id: &str) -> &'a crate::sources::EvidenceAtom {
2428        state
2429            .evidence_atoms
2430            .iter()
2431            .find(|atom| atom.id == id)
2432            .expect("atom exists")
2433    }
2434
2435    #[test]
2436    fn evidence_atom_locator_repaired_sets_locator_and_clears_caveat() {
2437        let mut state = project_with_one_atom(true);
2438        assert!(state.evidence_atoms[0].locator.is_none());
2439        let event = StateEvent {
2440            schema: crate::events::EVENT_SCHEMA.to_string(),
2441            id: "vev_test".to_string(),
2442            kind: "evidence_atom.locator_repaired".into(),
2443            target: StateTarget {
2444                r#type: "evidence_atom".to_string(),
2445                id: "vea_test_atom".to_string(),
2446            },
2447            actor: StateActor {
2448                id: "agent:test".to_string(),
2449                r#type: "agent".to_string(),
2450            },
2451            timestamp: Utc::now().to_rfc3339(),
2452            reason: "Mechanical repair from parent source".to_string(),
2453            before_hash: NULL_HASH.to_string(),
2454            after_hash: NULL_HASH.to_string(),
2455            payload: json!({
2456                "proposal_id": "vpr_test",
2457                "source_id": "vs_test_source",
2458                "locator": "doi:10.1/test-source",
2459            }),
2460            caveats: vec![],
2461            signature: None,
2462        };
2463        apply_event(&mut state, &event).expect("apply locator_repaired");
2464        let atom = atom_by_id(&state, "vea_test_atom");
2465        assert_eq!(atom.locator.as_deref(), Some("doi:10.1/test-source"));
2466        assert!(atom.caveats.is_empty());
2467    }
2468
2469    #[test]
2470    fn evidence_atom_locator_repaired_is_idempotent() {
2471        let mut state = project_with_one_atom(true);
2472        let event = StateEvent {
2473            schema: crate::events::EVENT_SCHEMA.to_string(),
2474            id: "vev_test".to_string(),
2475            kind: "evidence_atom.locator_repaired".into(),
2476            target: StateTarget {
2477                r#type: "evidence_atom".to_string(),
2478                id: "vea_test_atom".to_string(),
2479            },
2480            actor: StateActor {
2481                id: "agent:test".to_string(),
2482                r#type: "agent".to_string(),
2483            },
2484            timestamp: Utc::now().to_rfc3339(),
2485            reason: "Mechanical repair from parent source".to_string(),
2486            before_hash: NULL_HASH.to_string(),
2487            after_hash: NULL_HASH.to_string(),
2488            payload: json!({
2489                "proposal_id": "vpr_test",
2490                "source_id": "vs_test_source",
2491                "locator": "doi:10.1/test-source",
2492            }),
2493            caveats: vec![],
2494            signature: None,
2495        };
2496        apply_event(&mut state, &event).expect("first apply");
2497        apply_event(&mut state, &event).expect("second apply is a no-op when locator matches");
2498        let atom = atom_by_id(&state, "vea_test_atom");
2499        assert_eq!(atom.locator.as_deref(), Some("doi:10.1/test-source"));
2500    }
2501
2502    #[test]
2503    fn evidence_atom_locator_repaired_refuses_divergent_overwrite() {
2504        let mut state = project_with_one_atom(false);
2505        let event = StateEvent {
2506            schema: crate::events::EVENT_SCHEMA.to_string(),
2507            id: "vev_test".to_string(),
2508            kind: "evidence_atom.locator_repaired".into(),
2509            target: StateTarget {
2510                r#type: "evidence_atom".to_string(),
2511                id: "vea_test_atom".to_string(),
2512            },
2513            actor: StateActor {
2514                id: "agent:test".to_string(),
2515                r#type: "agent".to_string(),
2516            },
2517            timestamp: Utc::now().to_rfc3339(),
2518            reason: "Different repair".to_string(),
2519            before_hash: NULL_HASH.to_string(),
2520            after_hash: NULL_HASH.to_string(),
2521            payload: json!({
2522                "proposal_id": "vpr_test",
2523                "source_id": "vs_test_source",
2524                "locator": "doi:10.1/different",
2525            }),
2526            caveats: vec![],
2527            signature: None,
2528        };
2529        let r = apply_event(&mut state, &event);
2530        assert!(r.is_err());
2531        assert!(r.unwrap_err().contains("already has locator"));
2532    }
2533
2534    #[test]
2535    fn evidence_atom_locator_repaired_does_not_mutate_findings() {
2536        // Cross-impl conformance: this event mutates evidence_atoms only.
2537        let mut state = project_with_one_atom(true);
2538        let hashes_before: Vec<String> = state
2539            .findings
2540            .iter()
2541            .map(crate::events::finding_hash)
2542            .collect();
2543        let event = StateEvent {
2544            schema: crate::events::EVENT_SCHEMA.to_string(),
2545            id: "vev_test".to_string(),
2546            kind: "evidence_atom.locator_repaired".into(),
2547            target: StateTarget {
2548                r#type: "evidence_atom".to_string(),
2549                id: "vea_test_atom".to_string(),
2550            },
2551            actor: StateActor {
2552                id: "agent:test".to_string(),
2553                r#type: "agent".to_string(),
2554            },
2555            timestamp: Utc::now().to_rfc3339(),
2556            reason: "Mechanical repair".to_string(),
2557            before_hash: NULL_HASH.to_string(),
2558            after_hash: NULL_HASH.to_string(),
2559            payload: json!({
2560                "proposal_id": "vpr_test",
2561                "source_id": "vs_test_source",
2562                "locator": "doi:10.1/test-source",
2563            }),
2564            caveats: vec![],
2565            signature: None,
2566        };
2567        apply_event(&mut state, &event).expect("apply ok");
2568        let hashes_after: Vec<String> = state
2569            .findings
2570            .iter()
2571            .map(crate::events::finding_hash)
2572            .collect();
2573        assert_eq!(hashes_before, hashes_after);
2574    }
2575
2576    #[test]
2577    fn attempt_deposit_and_resolution_roundtrip() {
2578        use crate::attempt::{Attempt, AttemptDraft, AttemptResolution, ResolutionEvent};
2579        use ed25519_dalek::SigningKey;
2580        let key = SigningKey::from_bytes(&[7u8; 32]);
2581        let mut state = project::assemble("test", vec![], 0, 0, "test");
2582
2583        let att = Attempt::build(
2584            AttemptDraft {
2585                problem: 309,
2586                kind: "lower_bound".into(),
2587                claim: "a(8) >= 33".to_string(),
2588                ..Default::default()
2589            },
2590            &key,
2591        )
2592        .unwrap();
2593        let dep = att.deposit_event("agent:opus", "agent", "bank attempt");
2594        apply_event(&mut state, &dep).unwrap();
2595        assert_eq!(state.attempts.len(), 1);
2596        assert_eq!(state.attempts[0].attempt_id, att.attempt_id);
2597        // Idempotent: re-applying the same deposit is a no-op.
2598        apply_event(&mut state, &dep).unwrap();
2599        assert_eq!(state.attempts.len(), 1);
2600        // No resolution yet -> still a candidate.
2601        assert!(state.head_resolution(&att.attempt_id).is_none());
2602
2603        let res = ResolutionEvent::new(
2604            &att.attempt_id,
2605            AttemptResolution::Verified {
2606                gate_ref: "gate@vva_x".to_string(),
2607            },
2608            "reviewer:will-blair",
2609            "2026-06-09T00:00:00Z",
2610            "two independent methods",
2611        )
2612        .unwrap();
2613        apply_event(&mut state, &res.to_state_event("reviewer", "verified")).unwrap();
2614        assert_eq!(
2615            state
2616                .head_resolution(&att.attempt_id)
2617                .unwrap()
2618                .resolution
2619                .as_str(),
2620            "verified"
2621        );
2622
2623        // A later refutation becomes the head (latest by `at`); history kept.
2624        let res2 = ResolutionEvent::new(
2625            &att.attempt_id,
2626            AttemptResolution::Refuted {
2627                by_probe: "case_b".to_string(),
2628            },
2629            "reviewer:skeptic",
2630            "2026-06-10T00:00:00Z",
2631            "Case B breaks it",
2632        )
2633        .unwrap();
2634        apply_event(&mut state, &res2.to_state_event("reviewer", "refuted")).unwrap();
2635        assert_eq!(
2636            state
2637                .head_resolution(&att.attempt_id)
2638                .unwrap()
2639                .resolution
2640                .as_str(),
2641            "refuted"
2642        );
2643        assert_eq!(state.attempt_resolutions.len(), 2);
2644    }
2645
2646    #[test]
2647    fn forged_attempt_deposit_is_rejected_by_reducer() {
2648        use crate::attempt::{Attempt, AttemptDraft};
2649        use ed25519_dalek::SigningKey;
2650        let key = SigningKey::from_bytes(&[9u8; 32]);
2651        let mut state = project::assemble("test", vec![], 0, 0, "test");
2652        let att = Attempt::build(
2653            AttemptDraft {
2654                problem: 1,
2655                kind: "k".into(),
2656                claim: "c".to_string(),
2657                ..Default::default()
2658            },
2659            &key,
2660        )
2661        .unwrap();
2662        let mut dep = att.deposit_event("agent:opus", "agent", "x");
2663        // Hand-edit the embedded attempt: the signature no longer verifies.
2664        dep.payload["attempt"]["claim"] = serde_json::json!("tampered");
2665        assert!(apply_event(&mut state, &dep).is_err());
2666        assert_eq!(state.attempts.len(), 0);
2667    }
2668}