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