Skip to main content

vela_protocol/analysis/
evidence_diff.rs

1//! Evidence Diff: the before/after lens over a claim's state.
2//!
3//! Two derived projections, both read-only over the accepted event log —
4//! they never write, never store, and mint no new event kinds:
5//!
6//!   - [`state_cell`] — the Claim-State Cell (STATE_PLANE_MEMO §7.1):
7//!     claim, context, Belnap-style status, status provenance
8//!     (support/refute id sets), supersession, dependencies, open
9//!     obligations, priority. This is the pure core relocated out of the
10//!     CLI so the hub can compute the identical cell.
11//!   - [`claim_state_delta`] — applies one pending proposal in-memory
12//!     (the same `apply_proposal` the preview uses, never saved) and
13//!     reports the target claim's state *before* and *after*, plus the
14//!     downstream claims whose status letter flips as a result. This is
15//!     the integrating lens behind the Evidence Diff page: "what changed,
16//!     what broke, what should be reviewed next."
17//!
18//! The Engine verdict ("what would CI say if accepted?") is deliberately
19//! NOT computed here: `evidence_ci::run_project` needs a frontier path
20//! (policy docs, artifact files), which the hub's Postgres-materialized
21//! project does not have. The CLI caller, which holds the path, merges in
22//! `proposals::preview_engine_verdict`; the hub renders engine as absent
23//! (the real strict gate runs at accept time and returns 422 on refusal).
24
25use std::collections::BTreeSet;
26
27use serde_json::{Value, json};
28
29use crate::bundle::{FindingBundle, ReviewState};
30use crate::contradiction::ContradictionStatus;
31use crate::events::StateEvent;
32use crate::project::{Project, StatementRegistration};
33use crate::status_provenance::{BelnapStatus, StatusProvenance};
34use crate::verifier_attachment::{
35    AttachmentOutcome, GateStatus, MethodIntegrity, VerifierAttachment, claim_digest,
36    derive_gate_status,
37};
38
39/// A passed, claim-matched attachment whose method integrity is not
40/// `Compromised` — artifact-level support. Replicates the gate's private
41/// `is_passing_match` over public fields (the projection is read-only and
42/// must not depend on gate internals).
43fn is_passing_match(a: &VerifierAttachment, digest: &str) -> bool {
44    a.id.starts_with("vva_")
45        && a.outcome == AttachmentOutcome::Passed
46        && a.claim_digest == digest
47        && a.match_to_claim.matches
48        && a.method_integrity != MethodIntegrity::Compromised
49}
50
51/// The verifier attachments bound to this finding's CURRENT claim.
52/// Cloned (owned) to match `derive_gate_status`'s `&[VerifierAttachment]`.
53pub fn matched_attachments(project: &Project, finding: &FindingBundle) -> Vec<VerifierAttachment> {
54    project
55        .verifier_attachments
56        .iter()
57        .filter(|a| a.target == finding.id)
58        .cloned()
59        .collect()
60}
61
62/// Adjudicated (human-confirmed/resolved) contradictions naming this
63/// finding — a refute signal. Candidates are NOT counted (doctrine:
64/// contradictions are never auto-adjudicated).
65fn adjudicated_contradiction(project: &Project, id: &str) -> bool {
66    project.contradictions.iter().any(|c| {
67        (c.finding_a == id || c.finding_b == id)
68            && matches!(
69                c.status,
70                ContradictionStatus::ExpertConfirmed { .. } | ContradictionStatus::Resolved { .. }
71            )
72    })
73}
74
75/// The priority registration for a finding (gap 5). Prefers the exact
76/// finding-to-registration edge (`payload.finding_id`, stored on
77/// `StatementRegistration.finding_id`); falls back to the original
78/// heuristic (statement hash equals the claim digest, or the
79/// informal_ref names the finding id) for registrations that predate
80/// the edge. Returns the registration plus how it matched.
81pub fn find_priority_registration<'a>(
82    project: &'a Project,
83    id: &str,
84    digest: &str,
85) -> Option<(&'a StatementRegistration, &'static str)> {
86    project
87        .statement_registrations
88        .iter()
89        .find(|r| r.finding_id.as_deref() == Some(id))
90        .map(|r| (r, "finding_edge"))
91        .or_else(|| {
92            project
93                .statement_registrations
94                .iter()
95                .find(|r| r.statement_hash == digest || r.informal_ref.contains(id))
96                .map(|r| (r, "heuristic"))
97        })
98}
99
100/// Gap 2: derive the support/refute provenance sets for a finding from
101/// its event history — a READ-SIDE projection, computed at projection
102/// time and never stored. Zero reducer or state changes.
103///
104/// Contribution rules over the canonical log (in log order):
105///   - `finding.asserted` and accept events (`finding.reviewed` with
106///     status accepted/approved) add support ids — the event ids
107///     themselves.
108///   - `finding.superseded` and `finding.retracted` retract every
109///     support id accumulated so far, so all supporting evidence dies
110///     (Theorem 2/3: no zombie findings — superseded implies the
111///     support set is empty, hence the status cannot be T).
112///   - `finding.dependency_invalidated` adds a refute id.
113pub fn derive_status_provenance(events: &[StateEvent], id: &str) -> StatusProvenance {
114    derive_status_provenance_tiered(events, id, crate::access_tier::AccessTier::Public)
115}
116
117/// Visibility-aware [`derive_status_provenance`]: every support/refute variable
118/// is tagged with `tier` (the access tier of the finding whose status this is),
119/// so `StatusProvenance::derive_public_support(clearance)` can later project out
120/// the private derivations. `tier = Public` leaves variables bare and is
121/// byte-identical to the untagged path (so the canonical finding-effects digest
122/// and every cross-impl fixture are unaffected — visibility lives only in the
123/// derived projection, never in stored state). This is how "private memory is
124/// not public truth" becomes enforced rather than assumed.
125pub fn derive_status_provenance_tiered(
126    events: &[StateEvent],
127    id: &str,
128    tier: crate::access_tier::AccessTier,
129) -> StatusProvenance {
130    use crate::status_provenance::tag_visibility;
131    let mut sp = StatusProvenance::empty();
132    let var = |e: &StateEvent| tag_visibility(e.id.as_str(), tier);
133    for e in events.iter().filter(|e| e.target.id == id) {
134        match e.kind.as_str() {
135            "finding.asserted" => sp.add_support(var(e)),
136            "finding.reviewed" => {
137                if matches!(
138                    e.payload.get("status").and_then(Value::as_str),
139                    Some("accepted") | Some("approved")
140                ) {
141                    sp.add_support(var(e));
142                }
143            }
144            "finding.dependency_invalidated" => {
145                sp.add_refute(var(e));
146            }
147            "finding.superseded" | "finding.retracted" => {
148                let retracted: BTreeSet<String> = sp.support.clone();
149                sp = sp.retract(&retracted);
150            }
151            _ => {}
152        }
153    }
154    sp
155}
156
157fn belnap_meaning(status: BelnapStatus) -> &'static str {
158    match status {
159        BelnapStatus::True => "supported",
160        BelnapStatus::False => "refuted",
161        BelnapStatus::Both => "both supported and refuted (contested)",
162        BelnapStatus::None => "neither supported nor refuted",
163    }
164}
165
166/// Derive the Claim-State Cell — a projection over the event log, never
167/// a stored object. (STATE_PLANE_MEMO §7.1.)
168///
169/// Relocated verbatim from `vela-cli::cli_state::derive_state_cell` so
170/// both the CLI projection and the hub Evidence-Diff endpoint compute
171/// the identical cell from one source of truth.
172pub fn state_cell(project: &Project, finding: &FindingBundle) -> Value {
173    let id = finding.id.as_str();
174    let digest = claim_digest(&finding.assertion.text);
175    let atts = matched_attachments(project, finding);
176    let gate = derive_gate_status(&digest, &atts);
177
178    // Evidence-polarity signals (Belnap). Support and refute are
179    // independent bits over EXISTING objects; status is their join.
180    let mut support_signals: Vec<&str> = Vec::new();
181    let mut refute_signals: Vec<&str> = Vec::new();
182
183    if matches!(finding.flags.review_state, Some(ReviewState::Accepted)) {
184        support_signals.push("review_state=accepted");
185    }
186    if gate.status == GateStatus::Verified {
187        support_signals.push("verifier_gate=verified");
188    }
189    // A passing, claim-matched attachment is artifact-level support even
190    // when the full G1–G4 gate is not yet satisfied (the §7.1 example:
191    // "contested flag + passing attachment" → B).
192    if atts.iter().any(|a| is_passing_match(a, &digest)) {
193        support_signals.push("verifier_attachment=passed");
194    }
195
196    if finding.flags.retracted {
197        refute_signals.push("retracted");
198    }
199    match finding.flags.review_state {
200        Some(ReviewState::Rejected) => refute_signals.push("review_state=rejected"),
201        Some(ReviewState::Contested) => refute_signals.push("review_state=contested"),
202        Some(ReviewState::NeedsRevision) => refute_signals.push("review_state=needs_revision"),
203        _ => {}
204    }
205    if finding.flags.contested {
206        refute_signals.push("flags.contested");
207    }
208    if gate.status == GateStatus::Refuted {
209        refute_signals.push("verifier_gate=refuted");
210    }
211    if adjudicated_contradiction(project, id) {
212        refute_signals.push("contradiction=adjudicated");
213    }
214
215    let has_support = !support_signals.is_empty();
216    let has_refute = !refute_signals.is_empty();
217    let status = match (has_support, has_refute) {
218        (true, true) => "B",
219        (true, false) => "T",
220        (false, true) => "F",
221        (false, false) => "N",
222    };
223    let status_meaning = match status {
224        "T" => "supported",
225        "F" => "refuted",
226        "B" => "both supported and refuted (contested)",
227        _ => "neither supported nor refuted",
228    };
229
230    // Supersession: the OLD finding carries flags.superseded; the
231    // replacement id (if any) is in the thin finding.superseded event.
232    let superseding_id = project
233        .events
234        .iter()
235        .filter(|e| e.kind == "finding.superseded" && e.target.id == id)
236        .max_by(|a, b| a.timestamp.cmp(&b.timestamp))
237        .and_then(|e| {
238            e.payload
239                .get("new_finding_id")
240                .and_then(Value::as_str)
241                .map(str::to_string)
242        });
243    let supersession = json!({
244        "superseded": finding.flags.superseded,
245        "superseded_by": superseding_id,
246    });
247
248    // Dependencies: this finding's outbound typed links.
249    let dependencies: Vec<Value> = finding
250        .links
251        .iter()
252        .map(|l| {
253            json!({
254                "target": l.target,
255                "type": l.link_type,
256                "note": l.note,
257            })
258        })
259        .collect();
260
261    // Open obligations: gap-flagged findings linked to this finding in
262    // either direction (mirrors the task_packet derivation).
263    let open_obligations: Vec<Value> = project
264        .findings
265        .iter()
266        .filter(|f| f.flags.gap && f.id != id)
267        .filter(|f| {
268            f.links.iter().any(|l| l.target == id) || finding.links.iter().any(|l| l.target == f.id)
269        })
270        .map(|f| {
271            json!({
272                "id": f.id,
273                "statement": f.assertion.text,
274                "review_state": f.flags.review_state.as_ref().map(|s| format!("{s:?}")),
275            })
276        })
277        .collect();
278
279    // Priority registration: the exact finding-to-registration edge
280    // when present (gap 5), else the original heuristic (statement
281    // hash equals the claim digest, or informal_ref names the id).
282    // Rendered `null` (absent) when nothing matches — never invented.
283    let priority = find_priority_registration(project, id, &digest).map(|(r, matched_by)| {
284        json!({
285            "statement_hash": r.statement_hash,
286            "informal_ref": r.informal_ref,
287            "registered_by": r.registered_by,
288            "registered_at": r.registered_at,
289            "finding_id": r.finding_id,
290            "matched_by": matched_by,
291        })
292    });
293
294    // Gap 2: the support/refute provenance view of the same status — derived
295    // from the event history at read time, never stored. Printed NEXT TO the
296    // signal-derived status with an explicit divergence flag: measurement, not
297    // silent replacement. The Belnap status depends only on whether the two
298    // support sets are non-empty (`docs/THEORY.md` Section 7, Theorem 3).
299    let sp = derive_status_provenance(&project.events, id);
300    let prov_status = sp.derive_status();
301    let prov_letter = prov_status.letter().to_string();
302    let status_provenance = json!({
303        "support": sp.support,
304        "refute": sp.refute,
305        "letter": prov_letter,
306        "meaning": belnap_meaning(prov_status),
307        "divergence": prov_letter != status,
308        "note": "read-side projection over the event log (asserted/accept -> support ids, supersession/retraction -> drop accumulated support, dependency_invalidated -> refute); never stored. The Belnap letter is deriveStatus(support nonempty, refute nonempty).",
309    });
310
311    json!({
312        "projection": "claim_state_cell",
313        "frontier_id": project.frontier_id(),
314        "claim": finding.assertion.text,
315        "context": {
316            "conditions": finding.conditions.text,
317        },
318        "id": id,
319        "status": {
320            "letter": status,
321            "meaning": status_meaning,
322            "support_signals": support_signals,
323            "refute_signals": refute_signals,
324        },
325        "status_provenance": status_provenance,
326        "supersession": supersession,
327        "dependencies": dependencies,
328        "open_obligations": open_obligations,
329        "priority_registration": priority,
330    })
331}
332
333/// The headline Belnap letter of a finding's current state cell.
334fn status_letter(project: &Project, finding: &FindingBundle) -> String {
335    state_cell(project, finding)["status"]["letter"]
336        .as_str()
337        .unwrap_or("N")
338        .to_string()
339}
340
341/// Whether `dependent` depends on `target_id` through any outbound link.
342fn depends_on(dependent: &FindingBundle, target_id: &str) -> bool {
343    dependent.links.iter().any(|l| l.target == target_id)
344}
345
346/// Classify a downstream letter transition into a human-readable reason.
347fn downstream_reason(before: &str, after: &str) -> &'static str {
348    match (before, after) {
349        // Lost its only support path (T/B -> F/N with no support left).
350        ("T", "F") | ("T", "N") | ("B", "F") => "support_path_lost",
351        // Gained a refute signal (a dependency_invalidated cascade), or
352        // landed in B (both) — contested either way.
353        (_, "B") | ("N", "F") => "now_contested",
354        // Gained support without conflict.
355        ("N", "T") | ("F", "T") => "strengthened",
356        _ => "changed",
357    }
358}
359
360/// The integrating Evidence-Diff lens: apply one pending proposal
361/// in-memory (never saved) and report the target claim's state cell
362/// before and after, plus the downstream claims whose status letter
363/// flips as a result.
364///
365/// `reviewer` is the synthetic actor under which the in-memory apply
366/// runs (e.g. `reviewer:evidence-diff-preview`); nothing is persisted,
367/// so it never confers authority. The Engine verdict is NOT included —
368/// see the module docs; callers with a frontier path merge it in.
369pub fn claim_state_delta(
370    project: &Project,
371    proposal_id: &str,
372    reviewer: &str,
373) -> Result<Value, String> {
374    let proposal = project
375        .proposals
376        .iter()
377        .find(|p| p.id == proposal_id)
378        .ok_or_else(|| format!("Proposal not found: {proposal_id}"))?
379        .clone();
380    let target_id = proposal.target.id.clone();
381
382    // before: the target's current cell (null if the proposal introduces
383    // a new finding that does not exist yet).
384    let before = project
385        .findings
386        .iter()
387        .find(|f| f.id == target_id)
388        .map(|f| state_cell(project, f));
389    let before_letter = before
390        .as_ref()
391        .and_then(|c| c["status"]["letter"].as_str())
392        .unwrap_or("N")
393        .to_string();
394
395    // after: clone, apply the proposal in-memory under the synthetic
396    // reviewer, recompute the target cell. Reuses the same
397    // `apply_proposal` the diff preview uses, so before/after agree.
398    let mut after_state: Project = serde_json::from_value(
399        serde_json::to_value(project).map_err(|e| format!("serialize project: {e}"))?,
400    )
401    .map_err(|e| format!("clone project: {e}"))?;
402    crate::proposals::apply_proposal(
403        &mut after_state,
404        &proposal,
405        reviewer,
406        "Evidence Diff preview application",
407        None,
408    )?;
409    let after = after_state
410        .findings
411        .iter()
412        .find(|f| f.id == target_id)
413        .map(|f| state_cell(&after_state, f));
414    let after_letter = after
415        .as_ref()
416        .and_then(|c| c["status"]["letter"].as_str())
417        .unwrap_or("N")
418        .to_string();
419
420    // downstream: every finding that depends on the target and whose
421    // status letter flips between before and after.
422    let mut downstream: Vec<Value> = Vec::new();
423    for dep in project
424        .findings
425        .iter()
426        .filter(|f| depends_on(f, &target_id))
427    {
428        let before_d = status_letter(project, dep);
429        let after_d = after_state
430            .findings
431            .iter()
432            .find(|f| f.id == dep.id)
433            .map(|f| status_letter(&after_state, f))
434            .unwrap_or_else(|| "N".to_string());
435        if before_d != after_d {
436            downstream.push(json!({
437                "id": dep.id,
438                "statement": dep.assertion.text,
439                "before": before_d,
440                "after": after_d,
441                "reason": downstream_reason(&before_d, &after_d),
442            }));
443        }
444    }
445
446    Ok(json!({
447        "projection": "claim_state_delta",
448        "frontier_id": project.frontier_id(),
449        "proposal_id": proposal.id,
450        "kind": proposal.kind,
451        "target": target_id,
452        "status_change": {
453            "before": before_letter,
454            "after": after_letter,
455            "changed": before_letter != after_letter,
456        },
457        "before": before,
458        "after": after,
459        "downstream": downstream,
460        "downstream_count": downstream.len(),
461        // Filled by callers that hold a frontier path (the CLI); the hub
462        // leaves it absent because the strict gate runs at accept time.
463        "engine": { "available": false, "note": "Engine verdict (new_blocking/new_warnings) requires a frontier path; run `vela check . --strict --json` locally and inspect the pending proposal with `vela diff <vpr_> --json`." },
464    }))
465}
466
467#[cfg(test)]
468mod tests {
469    use super::*;
470    use crate::events::{NULL_HASH, StateActor, StateTarget};
471
472    fn ev(idx: usize, kind: &str, target: &str, payload: Value) -> StateEvent {
473        StateEvent {
474            schema: crate::events::EVENT_SCHEMA.to_string(),
475            id: format!("vev_synthetic_{idx:04}"),
476            kind: kind.into(),
477            target: StateTarget {
478                r#type: "finding".to_string(),
479                id: target.to_string(),
480            },
481            actor: StateActor {
482                id: "reviewer:synthetic".to_string(),
483                r#type: "human".to_string(),
484            },
485            timestamp: format!("2026-06-12T00:00:{:02}Z", idx % 60),
486            reason: "synthetic provenance test".to_string(),
487            before_hash: NULL_HASH.to_string(),
488            after_hash: NULL_HASH.to_string(),
489            payload,
490            caveats: vec![],
491            signature: None,
492        }
493    }
494
495    #[test]
496    fn asserted_plus_accept_derives_t() {
497        let log = vec![
498            ev(0, "finding.asserted", "vf_a", json!({})),
499            ev(1, "finding.reviewed", "vf_a", json!({"status": "accepted"})),
500        ];
501        let sp = derive_status_provenance(&log, "vf_a");
502        assert_eq!(sp.derive_status(), BelnapStatus::True);
503        assert_eq!(sp.support.len(), 2);
504        assert!(sp.refute.is_empty());
505    }
506
507    /// No-zombie (Theorem 3 at the projection layer): supersession
508    /// retracts every accumulated support id, so the support set is empty
509    /// and the derived status cannot remain T.
510    #[test]
511    fn no_zombie_superseded_support_is_empty_not_t() {
512        let log = vec![
513            ev(0, "finding.asserted", "vf_a", json!({})),
514            ev(1, "finding.reviewed", "vf_a", json!({"status": "accepted"})),
515            ev(
516                2,
517                "finding.superseded",
518                "vf_a",
519                json!({"new_finding_id": "vf_b"}),
520            ),
521        ];
522        let sp = derive_status_provenance(&log, "vf_a");
523        assert!(sp.support.is_empty());
524        assert_ne!(sp.derive_status(), BelnapStatus::True);
525        assert_eq!(sp.derive_status(), BelnapStatus::None);
526    }
527
528    #[test]
529    fn retraction_also_zeroes_support() {
530        let log = vec![
531            ev(0, "finding.asserted", "vf_a", json!({})),
532            ev(1, "finding.retracted", "vf_a", json!({})),
533        ];
534        let sp = derive_status_provenance(&log, "vf_a");
535        assert!(sp.support.is_empty());
536        assert_eq!(sp.derive_status(), BelnapStatus::None);
537    }
538
539    #[test]
540    fn dependency_invalidated_contributes_refute() {
541        let log = vec![
542            ev(0, "finding.asserted", "vf_b", json!({})),
543            ev(
544                1,
545                "finding.dependency_invalidated",
546                "vf_b",
547                json!({"upstream_finding_id": "vf_a", "depth": 1}),
548            ),
549        ];
550        let sp = derive_status_provenance(&log, "vf_b");
551        assert_eq!(sp.derive_status(), BelnapStatus::Both);
552        let mut log2 = log;
553        log2.push(ev(
554            2,
555            "finding.superseded",
556            "vf_b",
557            json!({"new_finding_id": "vf_c"}),
558        ));
559        let sp2 = derive_status_provenance(&log2, "vf_b");
560        assert!(sp2.support.is_empty());
561        assert_eq!(sp2.derive_status(), BelnapStatus::False);
562    }
563
564    #[test]
565    fn support_after_supersession_revives_via_new_event_only() {
566        let log = vec![
567            ev(0, "finding.asserted", "vf_a", json!({})),
568            ev(1, "finding.superseded", "vf_a", json!({})),
569            ev(2, "finding.reviewed", "vf_a", json!({"status": "accepted"})),
570        ];
571        let sp = derive_status_provenance(&log, "vf_a");
572        assert_eq!(sp.derive_status(), BelnapStatus::True);
573        assert_eq!(sp.support.len(), 1);
574    }
575
576    #[test]
577    fn non_accept_reviews_contribute_nothing() {
578        let log = vec![
579            ev(0, "finding.asserted", "vf_a", json!({})),
580            ev(
581                1,
582                "finding.reviewed",
583                "vf_a",
584                json!({"status": "contested"}),
585            ),
586        ];
587        let sp = derive_status_provenance(&log, "vf_a");
588        assert_eq!(sp.support.len(), 1);
589        assert!(sp.refute.is_empty());
590        assert_eq!(sp.derive_status(), BelnapStatus::True);
591    }
592
593    #[test]
594    fn events_for_other_findings_are_ignored() {
595        let log = vec![
596            ev(0, "finding.asserted", "vf_a", json!({})),
597            ev(1, "finding.asserted", "vf_b", json!({})),
598            ev(2, "finding.retracted", "vf_b", json!({})),
599        ];
600        let sp = derive_status_provenance(&log, "vf_a");
601        assert_eq!(sp.derive_status(), BelnapStatus::True);
602        assert_eq!(sp.support.len(), 1);
603    }
604
605    #[test]
606    fn downstream_reason_classifies_transitions() {
607        assert_eq!(downstream_reason("T", "F"), "support_path_lost");
608        assert_eq!(downstream_reason("T", "B"), "now_contested");
609        assert_eq!(downstream_reason("N", "T"), "strengthened");
610        assert_eq!(downstream_reason("T", "T"), "changed");
611    }
612
613    /// End-to-end: a retract proposal on a supported claim flips it
614    /// T -> F, and the dependent that `depends` on it is reported in
615    /// `downstream` as now-contested (the cascade marks it `contested`,
616    /// so its accepted support meets a new refute signal -> B).
617    #[test]
618    fn claim_state_delta_retract_cascades_to_dependents() {
619        use crate::bundle::{Link, ReviewState};
620        use crate::events::StateTarget;
621        use crate::proposals::new_proposal;
622        use crate::test_support::{make_finding, make_project};
623
624        let mut target = make_finding("vf_target", 0.9, "result");
625        target.flags.review_state = Some(ReviewState::Accepted);
626
627        let mut dep = make_finding("vf_dep", 0.8, "result");
628        dep.flags.review_state = Some(ReviewState::Accepted);
629        dep.links.push(Link {
630            target: "vf_target".into(),
631            link_type: "depends".into(),
632            note: "dep depends on target".into(),
633            inferred_by: "test".into(),
634            created_at: String::new(),
635            mechanism: None,
636        });
637
638        let mut project = make_project("cascade", vec![target, dep]);
639        let proposal = new_proposal(
640            "finding.retract",
641            StateTarget {
642                r#type: "finding".into(),
643                id: "vf_target".into(),
644            },
645            "reviewer:test",
646            "human",
647            "retracting target",
648            json!({}),
649            vec![],
650            vec![],
651        );
652        let proposal_id = proposal.id.clone();
653        project.proposals.push(proposal);
654
655        let delta = claim_state_delta(&project, &proposal_id, "reviewer:test").unwrap();
656
657        // Target: accepted (T) -> retracted. The prior accept signal
658        // lingers as support while `retracted` adds a refute signal, so
659        // the signal-derived headline lands at B (both). The status
660        // PROVENANCE poly, in contrast, zeroes support under rho_Y — both
661        // views travel together in the cell, by design.
662        assert_eq!(delta["status_change"]["before"], "T");
663        assert_eq!(delta["status_change"]["after"], "B");
664        assert_eq!(delta["status_change"]["changed"], true);
665        assert_eq!(
666            delta["after"]["status_provenance"]["letter"], "N",
667            "provenance support is zeroed by the retraction homomorphism"
668        );
669
670        // The dependent flips and is reported with a reason code:
671        // accepted support + the new contested refute = B (both).
672        let downstream = delta["downstream"].as_array().unwrap();
673        assert_eq!(downstream.len(), 1, "exactly one dependent should flip");
674        assert_eq!(downstream[0]["id"], "vf_dep");
675        assert_eq!(downstream[0]["before"], "T");
676        assert_eq!(downstream[0]["after"], "B");
677        assert_eq!(downstream[0]["reason"], "now_contested");
678    }
679}