Skip to main content

vela_protocol/analysis/
verifier_attachment.rs

1//! Verifier attachments (`vva_`) and the derived verification gate.
2//!
3//! ## The hole this closes
4//!
5//! Everywhere else the substrate is careful: a finding is content
6//! addressed, an event is signed, a proof verification carries a
7//! verifier's signature ([`crate::proof_verification`]). But the step
8//! from "the log says this finding is accepted" to "the *claim* is
9//! actually true" was never gated. A reviewer's `finding.reviewed →
10//! accepted` event records a *human verdict*; it says nothing about
11//! whether an independent verifier ever re-derived the result. The
12//! Erdős dogfooding made the cost concrete: 47 of 76 records marked
13//! "verified" carried an empty verification field, and the promote
14//! path trusted every one.
15//!
16//! ## The fix: a noun, then a derived gate
17//!
18//! A [`VerifierAttachment`] is the missing noun — a content-addressed,
19//! standalone object (the [`crate::bundle`] `Replication` precedent:
20//! first-class, targets a finding by id, never a mutable field on it).
21//! It binds *one* verifier's judgment to the *exact* claim it checked,
22//! by [`claim_digest`]. [`crate::proof_verification::ProofVerification`]
23//! and [`crate::lean_verification`] are two instances of one such
24//! method (`lean_kernel`); exact combinatorial recompute is another.
25//!
26//! The gate, [`derive_gate_status`], is a *function of the
27//! attachments*, exactly as [`crate::status_provenance`] derives Belnap
28//! status from provenance polynomials and never persists it. There is
29//! deliberately **no setter** on [`GateStatus`]: a finding cannot be
30//! stamped "verified", it can only *derive* as verified from
31//! attachments that satisfy four conditions:
32//!
33//! - **G1 independence** — ≥2 matched attachments by *different*
34//!   `(verifier_method, solver_id)`, with at least one naming another in
35//!   `independent_of`. The declaration is one-directional by necessity:
36//!   the `vva_` id content-addresses the whole body *including*
37//!   `independent_of`, so a mutual 2-cycle (A names B, B names A) is a
38//!   hash circularity and cannot be constructed. Independence is a
39//!   *declared, auditable* property, not a cryptographic one — a single
40//!   producer controls every field; the real diversity signal is
41//!   distinct `(method, solver)` here and distinct `implementation_id`
42//!   in the exact lane. One self-confirmed run never suffices.
43//! - **G2 claim-match** — every passing attachment is bound to the
44//!   *current* claim digest and declares `match_to_claim.matches`. A
45//!   proof that checks a *different* statement is `passed_but_unmatched`
46//!   and counts for nothing.
47//! - **G3 adversarial** — at least one adversarial probe present and
48//!   *none* refuted. A refuted probe drives the status to `Refuted`.
49//! - **G4 well-formed + id-integrity** — attachments are structurally
50//!   valid (`vva_` ids, parseable methods) AND their stored id
51//!   content-addresses their body (`derive_id() == id`). An attachment
52//!   whose id is forged or has drifted from its body is excluded from
53//!   the matched set: admission re-derives integrity from frozen
54//!   content, it never trusts a self-asserted id.
55//!
56//! Like Belnap status, the gate is orthogonal to the human review
57//! verdict ([`crate::bundle::ReviewState`]) and to Bayesian confidence
58//! ([`crate::confidence`]). A finding may be reviewer-`Accepted` and
59//! still gate `NeedsVerification` — that gap is the point, and the
60//! thing the substrate previously hid.
61
62use serde::{Deserialize, Serialize};
63use sha2::{Digest, Sha256};
64
65pub const ATTACHMENT_SCHEMA: &str = "vela.verifier_attachment.v0.1";
66
67/// The independent ways a claim can be checked. Two attachments by
68/// different methods are stronger evidence than two runs of the same
69/// method — G1 independence keys on this plus `solver_id`.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
71#[serde(rename_all = "snake_case")]
72pub enum VerifierMethod {
73    /// Re-run the combinatorial search / re-check a witness exactly.
74    ComputationalSearch,
75    /// Recompute an LP bound from its dual (a second solver).
76    LpDualRecompute,
77    /// A SAT/UNSAT certificate checked independently.
78    SatUnsatCert,
79    /// The Lean (or other proof-assistant) kernel accepts the term.
80    /// [`crate::proof_verification`] / [`crate::lean_verification`]
81    /// are instances of this method.
82    LeanKernel,
83    /// Re-derive a numeric result by exact arithmetic in a second tool.
84    ExactArithmeticRecompute,
85    /// Corroboration against an independent published source.
86    LiteratureCorroboration,
87    /// A human referee's structured judgment.
88    ManualReferee,
89    /// An evaluation-harness run (e.g. Inspect-AI): a task + scorer scored a
90    /// model's output. Distinct from a frozen exact verifier — the scorer may
91    /// be model-graded, so an `EvalHarness` attachment is evidence, never a
92    /// self-certifying `Sound` method. It defaults to
93    /// [`MethodIntegrity::Unattested`] and cannot auto-admit; a lone one fails
94    /// G1 like any other single attachment.
95    EvalHarness,
96}
97
98impl VerifierMethod {
99    #[must_use]
100    pub fn as_str(self) -> &'static str {
101        match self {
102            Self::ComputationalSearch => "computational_search",
103            Self::LpDualRecompute => "lp_dual_recompute",
104            Self::SatUnsatCert => "sat_unsat_cert",
105            Self::LeanKernel => "lean_kernel",
106            Self::ExactArithmeticRecompute => "exact_arithmetic_recompute",
107            Self::LiteratureCorroboration => "literature_corroboration",
108            Self::ManualReferee => "manual_referee",
109            Self::EvalHarness => "eval_harness",
110        }
111    }
112
113    #[must_use]
114    pub fn parse(s: &str) -> Option<Self> {
115        Some(match s {
116            "computational_search" => Self::ComputationalSearch,
117            "lp_dual_recompute" => Self::LpDualRecompute,
118            "sat_unsat_cert" => Self::SatUnsatCert,
119            "lean_kernel" => Self::LeanKernel,
120            "exact_arithmetic_recompute" => Self::ExactArithmeticRecompute,
121            "literature_corroboration" => Self::LiteratureCorroboration,
122            "manual_referee" => Self::ManualReferee,
123            "eval_harness" => Self::EvalHarness,
124            _ => return None,
125        })
126    }
127
128    pub const ALL: [VerifierMethod; 8] = [
129        Self::ComputationalSearch,
130        Self::LpDualRecompute,
131        Self::SatUnsatCert,
132        Self::LeanKernel,
133        Self::ExactArithmeticRecompute,
134        Self::LiteratureCorroboration,
135        Self::ManualReferee,
136        Self::EvalHarness,
137    ];
138}
139
140/// The kinds of adversarial probe a verifier can run against a claim.
141/// G3 requires at least one to be present and surviving.
142#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
143#[serde(rename_all = "snake_case")]
144pub enum ProbeKind {
145    /// Search directly for a counterexample to the claim.
146    CounterexampleSearch,
147    /// Exercise the adversarial "Case B" configuration that broke an
148    /// earlier over-claim.
149    CaseBConfig,
150    /// Check dual feasibility at the boundary of an LP bound.
151    BoundaryDualFeasibility,
152    /// Extrapolate a finite-size result and test it does not collapse.
153    FiniteSizeExtrapolation,
154    /// Re-implement the construction independently and compare.
155    IndependentReimplementation,
156    /// Statement-faithfulness: throw a prover at the formalized statement S
157    /// AND its negation ¬S. Both provable ⇒ the formalization is
158    /// vacuous/contradictory (misformalized). Also flags a statement that is
159    /// trivially provable, or a proof that uses no hypothesis. A `Refuted`
160    /// result here means the *verification claim* is unfaithful, not that the
161    /// underlying mathematics is false — and it drives the gate to Refuted so
162    /// a green kernel seal can never stand on a statement that does not mean
163    /// what it claims.
164    FormalismFidelity,
165}
166
167impl ProbeKind {
168    #[must_use]
169    pub fn as_str(self) -> &'static str {
170        match self {
171            Self::CounterexampleSearch => "counterexample_search",
172            Self::CaseBConfig => "case_b_config",
173            Self::BoundaryDualFeasibility => "boundary_dual_feasibility",
174            Self::FiniteSizeExtrapolation => "finite_size_extrapolation",
175            Self::IndependentReimplementation => "independent_reimplementation",
176            Self::FormalismFidelity => "formalism_fidelity",
177        }
178    }
179}
180
181/// The outcome of a single adversarial probe.
182#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
183#[serde(rename_all = "snake_case")]
184pub enum ProbeResult {
185    /// The claim survived the probe.
186    Survived,
187    /// The probe *refuted* the claim. A single refuting probe drives
188    /// the whole gate to [`GateStatus::Refuted`].
189    Refuted,
190}
191
192/// One adversarial probe run against the claim.
193#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
194pub struct AdversarialProbe {
195    pub kind: ProbeKind,
196    pub result: ProbeResult,
197    #[serde(default, skip_serializing_if = "String::is_empty")]
198    pub note: String,
199}
200
201/// Whether the verifier confirmed it checked the *exact* frozen claim.
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203pub struct MatchToClaim {
204    /// The verifier asserts its check is of the target claim verbatim,
205    /// not a weaker or different statement.
206    pub matches: bool,
207    /// Who performed the match check.
208    pub checker_actor: String,
209}
210
211/// The verifier's top-line outcome, before the gate's claim-match and
212/// independence reasoning. `Passed` means the method accepted; it does
213/// *not* by itself mean the claim is verified.
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
215#[serde(rename_all = "snake_case")]
216pub enum AttachmentOutcome {
217    Passed,
218    Failed,
219}
220
221/// A method-specific integrity claim layered on top of [`AttachmentOutcome`].
222///
223/// `Passed` says the method accepted; this says whether the method ran
224/// *soundly*. A Lean proof can pass `lake build` yet depend on
225/// `native_decide` (compiler trust) or `sorry` — sound elaboration, unsound
226/// kernel claim. The producer that mints a `lean_kernel` attachment sets this
227/// from the [`crate::tcb_policy::AxiomVerdict`] of the underlying
228/// verification, so the gate can refuse compromised methods without ever
229/// importing Lean specifics (G5).
230///
231/// Default is [`MethodIntegrity::Unattested`], serialized as *absent* so
232/// pre-existing `vva_` records re-derive their content-addressed id
233/// unchanged.
234#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
235#[serde(rename_all = "snake_case")]
236pub enum MethodIntegrity {
237    /// No method-specific integrity claim is made (legacy, or a method for
238    /// which integrity is not applicable). Neither trusted nor rejected.
239    #[default]
240    Unattested,
241    /// The method self-certifies clean (e.g. the Lean axiom set is
242    /// `KernelClean`, or an independent recompute matched).
243    Sound,
244    /// The method ran but its integrity check failed (a forbidden/unlisted
245    /// Lean axiom, a failed external kernel re-check, a solver in an
246    /// untrusted mode). Excluded from the matched set by the gate.
247    Compromised,
248}
249
250impl MethodIntegrity {
251    #[must_use]
252    pub fn as_str(self) -> &'static str {
253        match self {
254            Self::Unattested => "unattested",
255            Self::Sound => "sound",
256            Self::Compromised => "compromised",
257        }
258    }
259
260    /// Used by `skip_serializing_if` so the default serializes as absent,
261    /// keeping legacy `vva_` ids stable.
262    #[must_use]
263    pub fn is_unattested(&self) -> bool {
264        *self == Self::Unattested
265    }
266}
267
268/// A single verifier's judgment, content-addressed and bound to the
269/// exact claim it checked.
270#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
271pub struct VerifierAttachment {
272    pub schema: String,
273    /// `vva_<16hex>`, derived from the canonical body (id field empty).
274    pub id: String,
275    /// The finding (`vf_…`) or claim object this attaches to.
276    pub target: String,
277    /// [`claim_digest`] of the exact claim text checked. G2 compares
278    /// this to the current claim's digest.
279    pub claim_digest: String,
280    pub verifier_method: VerifierMethod,
281    /// Identifies the independent solver/tool that produced this check
282    /// (e.g. `cp-sat`, `pulp-cbc`, `lean4@4.29.1`). G1 independence
283    /// keys on `(verifier_method, solver_id)`.
284    pub solver_id: String,
285    /// Ids of *other* attachments this one declares itself independent
286    /// of. G1 requires the matched set to declare independence one-
287    /// directionally (>=1 declaration); a mutual 2-cycle is unconstructable
288    /// because the id content-addresses this field. Reference EARLIER-built
289    /// attachments only, so the referenced id is final before this one is built.
290    #[serde(default)]
291    pub independent_of: Vec<String>,
292    pub match_to_claim: MatchToClaim,
293    #[serde(default)]
294    pub adversarial_probes: Vec<AdversarialProbe>,
295    pub outcome: AttachmentOutcome,
296    /// Method-specific integrity (G5). Absent on legacy records; a
297    /// `Compromised` attachment is excluded from the matched set.
298    #[serde(default, skip_serializing_if = "MethodIntegrity::is_unattested")]
299    pub method_integrity: MethodIntegrity,
300    pub verifier_actor: String,
301    #[serde(default, skip_serializing_if = "String::is_empty")]
302    pub note: String,
303    /// Monoculture provenance (optional; absent on legacy records):
304    /// which IMPLEMENTATION produced this run. N runs of one frozen
305    /// binary are replication; N independent implementations are
306    /// diversity — the gate's reasons distinguish them.
307    #[serde(default, skip_serializing_if = "String::is_empty")]
308    pub implementation_id: String,
309    #[serde(default, skip_serializing_if = "String::is_empty")]
310    pub toolchain_hash: String,
311    /// Undischarged hypotheses the proof assumes (optional; absent on legacy
312    /// records, so their ids are byte-unchanged). For a `lean_kernel` attachment
313    /// these are the problem-defined named propositions the theorem takes as
314    /// parameters — e.g. a `(h : DensityHypothesis)` standing for an unproven
315    /// prime-gaps result, or `(h : DukeTheoremStatement)`. The proof is then
316    /// `sorry`-free and `#print axioms`-clean yet establishes the claim only
317    /// CONDITIONALLY: the hypothesis is a parameter, not an axiom, so the axiom
318    /// check cannot see it. A non-empty list demotes the gate (this attachment
319    /// cannot be an unconditional verification). Each entry is `"name : type"`.
320    #[serde(default, skip_serializing_if = "Vec::is_empty")]
321    pub undischarged_hypotheses: Vec<String>,
322    /// Lineage couplings this run declares (optional; absent on legacy
323    /// records, so their ids are byte-unchanged). Namespaced tags naming a
324    /// shared failure domain: `model:<id>`, `code:<swhid>`, `data:<dvc>`,
325    /// `run:<parent-run>`. Two matched attachments sharing any tag are one
326    /// failure domain regardless of method/solver diversity — the G1-L
327    /// clause demotes them. Declared honestly by the producer; a missing
328    /// declaration is invisible here, which is why G1's positive
329    /// requirements (distinct method/solver + `independent_of`) remain.
330    #[serde(default, skip_serializing_if = "Vec::is_empty")]
331    pub lineage_couplings: Vec<String>,
332    /// The `vva_` id of the attachment revision this one supersedes
333    /// (optional; absent on legacy records, so their ids are
334    /// byte-unchanged). Attachments are content-addressed — a revision
335    /// mints a new id — so continuity across revisions is a back-pointer
336    /// chain (`FindingBundle.previous_version` is the precedent). The
337    /// deliberate substitute for a stable-id + revision-digest pairing;
338    /// see docs/adr/0002.
339    #[serde(default, skip_serializing_if = "Option::is_none")]
340    pub supersedes: Option<String>,
341}
342
343/// Fields a caller supplies; the id and schema are derived.
344#[derive(Debug, Clone)]
345pub struct AttachmentDraft {
346    pub target: String,
347    pub claim_digest: String,
348    pub verifier_method: VerifierMethod,
349    pub solver_id: String,
350    pub independent_of: Vec<String>,
351    pub match_to_claim: MatchToClaim,
352    pub adversarial_probes: Vec<AdversarialProbe>,
353    pub outcome: AttachmentOutcome,
354    pub verifier_actor: String,
355    pub note: String,
356}
357
358/// The digest of a claim, binding an attachment to the exact text it
359/// checked. `sha256(trimmed claim)`, first 16 hex chars — the same
360/// rule as `verifier_gate_reference.py::claim_digest`, so digests match across
361/// the Rust and Python implementations.
362#[must_use]
363pub fn claim_digest(claim: &str) -> String {
364    let digest = Sha256::digest(claim.trim().as_bytes());
365    hex::encode(digest)[..16].to_string()
366}
367
368/// A deterministic, non-forgeable toolchain fingerprint for an attachment: the
369/// verifier-method class pinned to the attachment schema version. Two
370/// attachments from the same verifier TOOLCHAIN share it (replication of one
371/// checker); a Lean kernel and a frozen computational search differ (genuine
372/// toolchain diversity). Unlike `solver_id` — a free string the producing agent
373/// chooses — it is derived from the method, so a cosmetic rename cannot fake a
374/// "distinct" toolchain. The exact-lane independence reasoning surfaces it as
375/// corroborating evidence; the at-enable tightening can promote it from a
376/// reported signal to a hard distinctness requirement.
377#[must_use]
378pub fn derive_toolchain_hash(method: &VerifierMethod) -> String {
379    let tag = format!("{ATTACHMENT_SCHEMA}:{method:?}");
380    hex::encode(Sha256::digest(tag.as_bytes()))[..16].to_string()
381}
382
383impl VerifierAttachment {
384    /// Build an attachment, deriving its content-addressed id from the
385    /// canonical body. Mirrors the id-from-signed-body pattern in
386    /// [`crate::proof_verification`].
387    pub fn build(draft: AttachmentDraft) -> Result<Self, String> {
388        if !draft.target.starts_with("vf_") && !draft.target.starts_with("vfr_") {
389            return Err(format!(
390                "attachment target should be a finding (`vf_`) or frontier-claim (`vfr_`) id; got `{}`",
391                draft.target
392            ));
393        }
394        let mut att = VerifierAttachment {
395            schema: ATTACHMENT_SCHEMA.to_string(),
396            id: String::new(),
397            target: draft.target,
398            claim_digest: draft.claim_digest,
399            verifier_method: draft.verifier_method,
400            solver_id: draft.solver_id,
401            independent_of: draft.independent_of,
402            match_to_claim: draft.match_to_claim,
403            adversarial_probes: draft.adversarial_probes,
404            outcome: draft.outcome,
405            method_integrity: MethodIntegrity::Unattested,
406            verifier_actor: draft.verifier_actor,
407            note: draft.note,
408            implementation_id: String::new(),
409            lineage_couplings: Vec::new(),
410            supersedes: None,
411            toolchain_hash: derive_toolchain_hash(&draft.verifier_method),
412            undischarged_hypotheses: Vec::new(),
413        };
414        att.id = att.derive_id()?;
415        Ok(att)
416    }
417
418    /// Set the method integrity and re-derive the content-addressed id.
419    /// The Lean producer calls this with the [`crate::tcb_policy::AxiomVerdict`]
420    /// mapped through [`crate::lean_verification::LeanVerification::to_attachment_integrity`].
421    /// Because integrity is part of the canonical body, a `Sound`/`Compromised`
422    /// attachment necessarily has a different id than its `Unattested` form.
423    pub fn with_method_integrity(mut self, integrity: MethodIntegrity) -> Result<Self, String> {
424        self.method_integrity = integrity;
425        self.id = self.derive_id()?;
426        Ok(self)
427    }
428
429    /// Set the implementation id and re-derive the content-addressed id.
430    /// `implementation_id` is part of the canonical body, so a producer that
431    /// records which implementation ran (the exact-lane monoculture guard reads
432    /// it) must set it through this builder rather than by field assignment, or
433    /// the stored id would no longer content-address the body and the gate's G4
434    /// id-integrity check would exclude the attachment. Apply it AFTER
435    /// `with_method_integrity` (it is the last mutation) so the id is final.
436    pub fn with_implementation_id(mut self, implementation_id: &str) -> Result<Self, String> {
437        self.implementation_id = implementation_id.to_string();
438        self.id = self.derive_id()?;
439        Ok(self)
440    }
441
442    /// Record the undischarged hypotheses the proof assumes and re-derive the id.
443    /// Part of the canonical body (like `method_integrity`), so it must be set
444    /// through this builder, not by field assignment, or the gate's G4 id-integrity
445    /// check would exclude the attachment. A non-empty list makes the attachment
446    /// CONDITIONAL: `derive_gate_status` will not let it reach `Verified`.
447    pub fn with_undischarged_hypotheses(mut self, hyps: Vec<String>) -> Result<Self, String> {
448        self.undischarged_hypotheses = hyps;
449        self.id = self.derive_id()?;
450        Ok(self)
451    }
452
453    /// Record the lineage couplings this run declares and re-derive the id.
454    /// Part of the canonical body (like `method_integrity`), so it must be
455    /// set through this builder, not by field assignment, or the gate's G4
456    /// id-integrity check would exclude the attachment.
457    pub fn with_lineage_couplings(mut self, couplings: Vec<String>) -> Result<Self, String> {
458        self.lineage_couplings = couplings;
459        self.id = self.derive_id()?;
460        Ok(self)
461    }
462
463    /// Chain this attachment to the revision it supersedes and re-derive
464    /// the id. Part of the canonical body, so it must be set through this
465    /// builder, not by field assignment.
466    pub fn with_supersedes(mut self, prior: &str) -> Result<Self, String> {
467        if !prior.starts_with("vva_") {
468            return Err(format!("supersedes must name a vva_… id, got '{prior}'"));
469        }
470        self.supersedes = Some(prior.to_string());
471        self.id = self.derive_id()?;
472        Ok(self)
473    }
474
475    /// Re-derive the content-addressed id from the canonical body with
476    /// the id field zeroed.
477    pub fn derive_id(&self) -> Result<String, String> {
478        let mut preimage = self.clone();
479        preimage.id = String::new();
480        let bytes = crate::canonical::to_canonical_bytes(&preimage)
481            .map_err(|e| format!("canonicalize attachment preimage: {e}"))?;
482        let digest = Sha256::digest(&bytes);
483        Ok(format!("vva_{}", &hex::encode(digest)[..16]))
484    }
485
486    /// Structural validity (G4): schema, id prefix, and id integrity.
487    pub fn verify(&self) -> Result<(), String> {
488        if self.schema != ATTACHMENT_SCHEMA {
489            return Err(format!(
490                "attachment.schema must be `{ATTACHMENT_SCHEMA}`, got `{}`",
491                self.schema
492            ));
493        }
494        if !self.id.starts_with("vva_") {
495            return Err(format!(
496                "attachment id must start with `vva_`, got `{}`",
497                self.id
498            ));
499        }
500        let derived = self.derive_id()?;
501        if derived != self.id {
502            return Err(format!(
503                "attachment id mismatch: stored `{}`, derived `{}`",
504                self.id, derived
505            ));
506        }
507        Ok(())
508    }
509
510    /// Whether this attachment is well-formed *and* matches the given
511    /// claim digest with `outcome = passed`, `match_to_claim`, and an
512    /// integrity that is not `Compromised` (G5).
513    pub(crate) fn is_passing_match(&self, current_digest: &str) -> bool {
514        self.is_base_match(current_digest) && self.method_integrity != MethodIntegrity::Compromised
515    }
516
517    /// True iff the stored id content-addresses the body (`derive_id() == id`).
518    /// The gate re-derives this for every matched attachment so admission rests
519    /// on frozen content, never on a forgeable self-asserted id. (No production
520    /// path called `verify()` before; the gate now closes that hole itself.)
521    fn has_valid_id(&self) -> bool {
522        self.derive_id().is_ok_and(|d| d == self.id)
523    }
524
525    /// Passed, claim-matched, well-prefixed — the *claim binding*, before the
526    /// id-integrity (G4) and method-integrity (G5) checks. Used to surface a
527    /// forged-id or compromised attachment with a precise reason rather than
528    /// silently dropping it into `passed_but_unmatched` (G2).
529    fn is_claim_bound(&self, current_digest: &str) -> bool {
530        self.id.starts_with("vva_")
531            && self.outcome == AttachmentOutcome::Passed
532            && self.claim_digest == current_digest
533            && self.match_to_claim.matches
534    }
535
536    /// Well-formed, passed, claim-matched, AND id-integral (G4) — everything but
537    /// the method-integrity check. The integrity check is the only thing
538    /// distinguishing a passing match (G5 ok) from a compromised one (G5 excluded).
539    fn is_base_match(&self, current_digest: &str) -> bool {
540        self.is_claim_bound(current_digest) && self.has_valid_id()
541    }
542
543    /// Whether this attachment would have matched the claim but is excluded
544    /// solely because its method integrity is `Compromised` (G5 reason).
545    fn is_compromised_match(&self, current_digest: &str) -> bool {
546        self.is_base_match(current_digest) && self.method_integrity == MethodIntegrity::Compromised
547    }
548}
549
550/// The derived verification status of a finding. There is no
551/// constructor that sets this directly — it is only ever the return
552/// value of [`derive_gate_status`].
553#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
554#[serde(rename_all = "snake_case")]
555pub enum GateStatus {
556    /// The default. Not enough independent, matched, probed evidence.
557    NeedsVerification,
558    /// G1–G4 all satisfied.
559    Verified,
560    /// An adversarial probe refuted the claim. Terminal until the
561    /// claim is revised.
562    Refuted,
563}
564
565/// The full outcome of the gate: a status plus the reasons it is not
566/// [`GateStatus::Verified`] (empty exactly when verified).
567#[derive(Debug, Clone, PartialEq, Eq)]
568pub struct GateOutcome {
569    pub status: GateStatus,
570    pub reasons: Vec<String>,
571}
572
573impl GateOutcome {
574    #[must_use]
575    pub fn is_verified(&self) -> bool {
576        self.status == GateStatus::Verified
577    }
578}
579
580/// Derive the gate status of a claim from its verifier attachments.
581///
582/// This is the substrate's answer to "is this claim verified?" — a
583/// pure function of `(current_claim_digest, attachments)`, never a
584/// stored flag. Implements G1–G4. A finding with `payload.status =
585/// accepted` and **zero** attachments derives to `NeedsVerification`,
586/// not `Verified` — the exact bug class the gate exists to prevent.
587#[must_use]
588pub fn derive_gate_status(
589    current_claim_digest: &str,
590    attachments: &[VerifierAttachment],
591) -> GateOutcome {
592    let mut reasons = Vec::new();
593
594    let passed: Vec<&VerifierAttachment> = attachments
595        .iter()
596        .filter(|a| a.outcome == AttachmentOutcome::Passed)
597        .collect();
598
599    // G2 claim-match: a passing attachment bound to a different claim,
600    // or not declaring a match, is `passed_but_unmatched` and counts
601    // for nothing.
602    let matched: Vec<&VerifierAttachment> = attachments
603        .iter()
604        .filter(|a| a.is_passing_match(current_claim_digest))
605        .collect();
606
607    // Independence (G1 + monoculture demotion): derived in one place,
608    // `analysis::independence`, shared with the policy layer. NB: pushing a
609    // reason here DOES demote (status is Verified iff `reasons` is empty),
610    // so a single-implementation matched set derives `NeedsVerification`.
611    reasons.extend(
612        super::independence::independence_from_attachments(current_claim_digest, attachments)
613            .reasons,
614    );
615
616    // G5 method-integrity: an attachment that *would* match the claim but
617    // ran with a compromised method (e.g. a forbidden Lean axiom such as
618    // `native_decide`/`sorry`, or a failed external kernel re-check) is
619    // excluded from the matched set. A `lean_kernel` proof that trusts the
620    // compiler can therefore never push a finding to Verified.
621    let compromised = attachments
622        .iter()
623        .filter(|a| a.is_compromised_match(current_claim_digest))
624        .count();
625    if compromised > 0 {
626        reasons.push(format!(
627            "G5: {compromised} attachment(s) excluded — method integrity compromised \
628             (e.g. forbidden Lean axiom or failed kernel re-check)"
629        ));
630    }
631
632    // Conditional-proof guard: a matched attachment whose proof is conditional on
633    // undischarged hypotheses (a theorem parameter `(h : DensityHypothesis)`
634    // standing for an unproven result) establishes the claim only CONDITIONALLY.
635    // `#print axioms` cannot see this — the hypothesis is a parameter, not an
636    // axiom — so `method_integrity` may be `Sound` and the kernel clean while the
637    // proof still assumes a deep result. The gate refuses to call such an
638    // attachment an unconditional verification. (Empty on every legacy record, so
639    // this never changes a stored finding's status.)
640    let conditional: Vec<&str> = matched
641        .iter()
642        .filter(|a| !a.undischarged_hypotheses.is_empty())
643        .flat_map(|a| a.undischarged_hypotheses.iter().map(String::as_str))
644        .collect();
645    if !conditional.is_empty() {
646        reasons.push(format!(
647            "conditional: matched attachment(s) prove the claim only under undischarged \
648             hypotheses [{}] — `#print axioms`-clean but not an unconditional verification",
649            conditional.join("; ")
650        ));
651    }
652
653    // G4 id-integrity: an attachment that *would* match the claim but whose
654    // stored id does not content-address its body (forged or drifted) is
655    // excluded from the matched set. `verify()` was never called on the
656    // write path, so the gate re-derives integrity here — a self-asserted
657    // `vva_` id can never push a finding to Verified on its own say-so.
658    let id_invalid = attachments
659        .iter()
660        .filter(|a| a.is_claim_bound(current_claim_digest) && !a.has_valid_id())
661        .count();
662    if id_invalid > 0 {
663        reasons.push(format!(
664            "G4: {id_invalid} attachment(s) excluded — id does not content-address the body \
665             (forged or drifted; derive_id() != id)"
666        ));
667    }
668
669    // Genuine claim mismatch: passed, but neither matched, compromised, nor
670    // id-invalid (wrong claim digest, or match_to_claim=false).
671    if passed.len() > matched.len() + compromised + id_invalid {
672        reasons.push(
673            "G2: an attachment passed but is unmatched to the current claim (passed_but_unmatched)"
674                .to_string(),
675        );
676    }
677
678    // G3 adversarial: a refuted probe is terminal; otherwise need >=1
679    // surviving probe across the matched set.
680    let probes: Vec<&AdversarialProbe> = matched
681        .iter()
682        .flat_map(|a| a.adversarial_probes.iter())
683        .collect();
684    if probes.iter().any(|p| p.result == ProbeResult::Refuted) {
685        return GateOutcome {
686            status: GateStatus::Refuted,
687            reasons: vec![
688                "G3: an adversarial probe REFUTED the claim -> status is refuted".to_string(),
689            ],
690        };
691    }
692    if probes.is_empty() {
693        reasons.push("G3: no surviving adversarial probe attached (need >=1)".to_string());
694    }
695
696    // G4 well-formed: every matched attachment is structurally valid.
697    for a in &matched {
698        if !a.id.starts_with("vva_") {
699            reasons.push(format!("G4: malformed attachment id `{}`", a.id));
700        }
701    }
702
703    let status = if reasons.is_empty() {
704        GateStatus::Verified
705    } else {
706        GateStatus::NeedsVerification
707    };
708    GateOutcome { status, reasons }
709}
710
711/// The deterministic attachment-level decision for **exact-lane
712/// auto-admission** (Phase 1A, the de-human-gate). This is the trust
713/// predicate the `policy.auto_admitted` event materializes: it is frozen
714/// audited Rust, never a model, so "no AI in the trust path" stays literally
715/// true while the human is removed from the rote kernel-clean admit.
716///
717/// It is **strictly stronger** than [`derive_gate_status`] reaching
718/// `Verified` — it never admits anything the gate would not, and it adds the
719/// guards a human reviewer would otherwise apply. Each guard closes a concrete
720/// red-team attack the bare `Verified` check leaves open:
721///
722///   1. the gate must already be [`GateStatus::Verified`] (inherits G1-G5:
723///      >=2 matched independent attachments, claim-bound, no compromised
724///      method, no refuted probe).
725///   2. **every matched attachment is [`MethodIntegrity::Sound`]** — reject
726///      the legacy `Unattested` default the gate otherwise tolerates (the gate
727///      only *excludes* `Compromised`). Closes the smuggled-axiom /
728///      unaudited-legacy attack.
729///   3. **a [`ProbeKind::FormalismFidelity`] probe is PRESENT and Survived**
730///      on the matched set, and none is Refuted. The gate's G3 accepts *any*
731///      surviving probe, so a vacuous or misformalized statement with only a
732///      `CounterexampleSearch` probe passes it. Auto-admit demands the
733///      faithfulness probe explicitly (absent != safe).
734///   4. **declared independence**: at least one matched attachment names
735///      another matched attachment in `independent_of` (one-directional). This
736///      cannot be mutual: the `vva_` id content-addresses the body *including*
737///      `independent_of`, so a 2-cycle is a hash circularity (the prior "mutual"
738///      rule made this lane unreachable for every honestly-built pair). The
739///      declaration is a consistency/audit signal, not cryptographic
740///      independence — a single producer controls every field; the real
741///      diversity teeth are guards 5 (distinct implementations) and the gate's
742///      G1 (distinct method/solver). Do NOT re-tighten this to mutual.
743///   5. **not an implementation monoculture**: the matched set carries >=2
744///      distinct non-empty `implementation_id`s. N runs of one binary are
745///      replication, not independent verification; the gate only *warns*.
746///
747/// Every matched attachment is also id-integral (G4: `derive_id() == id`),
748/// inherited from the gate's `is_base_match`, so a forged-id attachment can
749/// never enter the matched set this predicate reasons over.
750///
751/// Proposal-level guards (synthetic-source signal, live frontier
752/// contradiction, proposal kind) are applied by the caller in `proposals.rs`,
753/// which has the `StateProposal`/`Project` context this primitive does not.
754/// Returns `(admit, reasons)`; `reasons` is non-empty exactly when refused.
755pub fn exact_lane_attachment_admit(
756    current_claim_digest: &str,
757    attachments: &[VerifierAttachment],
758) -> (bool, Vec<String>) {
759    let mut reasons = Vec::new();
760
761    // Guard 1: the existing frozen gate must reach Verified.
762    let gate = derive_gate_status(current_claim_digest, attachments);
763    if gate.status != GateStatus::Verified {
764        reasons.push(format!(
765            "exact-lane: gate not Verified ({:?}): {}",
766            gate.status,
767            gate.reasons.join("; ")
768        ));
769        return (false, reasons);
770    }
771
772    // The matched set is exactly the gate's notion of "counts toward Verified".
773    let matched: Vec<&VerifierAttachment> = attachments
774        .iter()
775        .filter(|a| a.is_passing_match(current_claim_digest))
776        .collect();
777    // Verified implies matched.len() >= 2, but never assume it.
778    if matched.len() < 2 {
779        reasons.push("exact-lane: fewer than 2 matched attachments".to_string());
780        return (false, reasons);
781    }
782
783    // Guard 2: reject the Unattested legacy default; require Sound on all.
784    if let Some(bad) = matched
785        .iter()
786        .find(|a| a.method_integrity != MethodIntegrity::Sound)
787    {
788        reasons.push(format!(
789            "exact-lane: attachment `{}` is not MethodIntegrity::Sound ({:?}); auto-admit requires Sound (a human must clear Unattested)",
790            bad.id, bad.method_integrity
791        ));
792        return (false, reasons);
793    }
794
795    // Guard 3: a FormalismFidelity probe must be PRESENT and Survived, and
796    // none may be Refuted (a Refuted one already forces the gate to Refuted,
797    // but assert it independently of gate internals).
798    let mut ff_survived = false;
799    for a in &matched {
800        for p in &a.adversarial_probes {
801            if p.kind == ProbeKind::FormalismFidelity {
802                match p.result {
803                    ProbeResult::Survived => ff_survived = true,
804                    ProbeResult::Refuted => {
805                        reasons
806                            .push("exact-lane: a FormalismFidelity probe is Refuted".to_string());
807                        return (false, reasons);
808                    }
809                }
810            }
811        }
812    }
813    if !ff_survived {
814        reasons.push(
815            "exact-lane: no present-and-Survived FormalismFidelity probe (faithfulness unproven; \
816             absent does not count as safe)"
817                .to_string(),
818        );
819        return (false, reasons);
820    }
821
822    // Guard 4: declared independence — at least one matched attachment names
823    // another matched attachment in `independent_of` (one-directional, the same
824    // form the gate's G1 accepts). Mutual is impossible: the vva_ id
825    // content-addresses the body INCLUDING independent_of, so a 2-cycle is a
826    // hash circularity; requiring it (as this guard once did) made the whole
827    // lane unreachable for every honestly-built pair. The teeth are guard 5
828    // (distinct implementations) and G1 (distinct method/solver), not this
829    // declaration. Re-derived from the same `matched` set the gate verified.
830    let ids: std::collections::BTreeSet<&str> = matched.iter().map(|a| a.id.as_str()).collect();
831    let declares_independence = matched.iter().any(|a| {
832        a.independent_of
833            .iter()
834            .any(|other| other != &a.id && ids.contains(other.as_str()))
835    });
836    if !declares_independence {
837        reasons.push(
838            "exact-lane: no matched attachment declares independent_of another (need >=1 \
839             one-directional declaration)"
840                .to_string(),
841        );
842        return (false, reasons);
843    }
844
845    // Guard 5: not an implementation monoculture.
846    let impls: std::collections::BTreeSet<&str> = matched
847        .iter()
848        .map(|a| a.implementation_id.as_str())
849        .filter(|s| !s.is_empty())
850        .collect();
851    if impls.len() < 2 {
852        reasons.push(
853            "exact-lane: implementation monoculture (need >=2 distinct implementation_id; N runs \
854             of one binary are replication, not independent verification)"
855                .to_string(),
856        );
857        return (false, reasons);
858    }
859
860    (true, reasons)
861}
862
863#[cfg(test)]
864mod tests {
865    use super::*;
866
867    fn match_to(actor: &str) -> MatchToClaim {
868        MatchToClaim {
869            matches: true,
870            checker_actor: actor.to_string(),
871        }
872    }
873
874    fn surviving_probe() -> AdversarialProbe {
875        AdversarialProbe {
876            kind: ProbeKind::CounterexampleSearch,
877            result: ProbeResult::Survived,
878            note: String::new(),
879        }
880    }
881
882    fn attach(
883        digest: &str,
884        method: VerifierMethod,
885        solver: &str,
886        independent_of: Vec<String>,
887        probes: Vec<AdversarialProbe>,
888    ) -> VerifierAttachment {
889        VerifierAttachment::build(AttachmentDraft {
890            target: "vf_0123456789abcdef".to_string(),
891            claim_digest: digest.to_string(),
892            verifier_method: method,
893            solver_id: solver.to_string(),
894            independent_of,
895            match_to_claim: match_to("checker"),
896            adversarial_probes: probes,
897            outcome: AttachmentOutcome::Passed,
898            verifier_actor: "Opus 4.8".to_string(),
899            note: String::new(),
900        })
901        .unwrap()
902    }
903
904    fn ff_survived() -> AdversarialProbe {
905        AdversarialProbe {
906            kind: ProbeKind::FormalismFidelity,
907            result: ProbeResult::Survived,
908            note: String::new(),
909        }
910    }
911
912    /// Build a fully-specified attachment with a GENUINELY VALID id: every
913    /// id-bearing field (integrity, implementation_id) is set through the
914    /// re-deriving builders, never by post-build mutation, so `verify()` holds.
915    /// `independent_of` is set at build time, so reference EARLIER-built ids.
916    #[allow(clippy::too_many_arguments)]
917    fn attach_full(
918        digest: &str,
919        method: VerifierMethod,
920        solver: &str,
921        independent_of: Vec<String>,
922        probes: Vec<AdversarialProbe>,
923        integrity: MethodIntegrity,
924        impl_id: &str,
925    ) -> VerifierAttachment {
926        let mut a = attach(digest, method, solver, independent_of, probes);
927        if integrity != MethodIntegrity::Unattested {
928            a = a.with_method_integrity(integrity).unwrap();
929        }
930        if !impl_id.is_empty() {
931            a = a.with_implementation_id(impl_id).unwrap();
932        }
933        a
934    }
935
936    /// A pair of attachments that SHOULD pass exact-lane auto-admit: two
937    /// matched, `Sound`, distinct-implementation runs, each carrying a Survived
938    /// FormalismFidelity probe, with ONE-DIRECTIONAL declared independence (a2
939    /// names a1 — mutual is a hash circularity, see Guard 4). Both ids are
940    /// genuinely content-valid. Each red-team test below degrades exactly one
941    /// property and asserts the predicate refuses while the bare gate often
942    /// still says Verified.
943    fn admit_pair(digest: &str) -> (VerifierAttachment, VerifierAttachment) {
944        // a1 is built first so its id is final before a2 references it.
945        let a1 = attach_full(
946            digest,
947            VerifierMethod::ComputationalSearch,
948            "cp-sat",
949            vec![],
950            vec![ff_survived()],
951            MethodIntegrity::Sound,
952            "impl-cp-sat",
953        );
954        let a2 = attach_full(
955            digest,
956            VerifierMethod::ExactArithmeticRecompute,
957            "pari-gp",
958            vec![a1.id.clone()],
959            vec![ff_survived()],
960            MethodIntegrity::Sound,
961            "impl-pari",
962        );
963        (a1, a2)
964    }
965
966    #[test]
967    fn exact_lane_happy_path_admits() {
968        let digest = claim_digest("claim X");
969        let (a1, a2) = admit_pair(&digest);
970        // The admitting pair is GENUINELY id-valid — built through build() +
971        // the re-deriving builders, not by mutating ids in memory.
972        a1.verify().expect("a1 content-addresses its body");
973        a2.verify().expect("a2 content-addresses its body");
974        assert_eq!(
975            derive_gate_status(&digest, &[a1.clone(), a2.clone()]).status,
976            GateStatus::Verified
977        );
978        let (admit, reasons) = exact_lane_attachment_admit(&digest, &[a1, a2]);
979        assert!(admit, "should auto-admit, refused for: {reasons:?}");
980        assert!(reasons.is_empty());
981    }
982
983    // The forged-id attack the relaxed Guard 4 must not open: a single actor
984    // hand-authors two attachments whose ids do NOT content-address their
985    // bodies (here, mutual independence declarations added without re-deriving,
986    // exactly the unconstructable-honestly 2-cycle). G4 id-integrity excludes
987    // them from the matched set, so the gate never reaches Verified and the
988    // exact lane refuses. Without the id-integrity check this pair would admit.
989    #[test]
990    fn exact_lane_refuses_forged_id_pair() {
991        let digest = claim_digest("claim X");
992        let (mut a1, mut a2) = admit_pair(&digest);
993        // Hand-author a mutual 2-cycle with arbitrary `vva_` ids — the form an
994        // attacker writes directly as JSON, which build() can never mint (the id
995        // content-addresses independent_of). Neither id matches its body.
996        a1.id = "vva_forged00000a1".to_string();
997        a2.id = "vva_forged00000a2".to_string();
998        a1.independent_of = vec![a2.id.clone()];
999        a2.independent_of = vec![a1.id.clone()];
1000        assert!(a1.verify().is_err(), "forged a1 must fail id-integrity");
1001        assert!(a2.verify().is_err(), "forged a2 must fail id-integrity");
1002        assert_eq!(
1003            derive_gate_status(&digest, &[a1.clone(), a2.clone()]).status,
1004            GateStatus::NeedsVerification,
1005            "forged-id attachments must not reach Verified"
1006        );
1007        let (admit, reasons) = exact_lane_attachment_admit(&digest, &[a1, a2]);
1008        assert!(!admit, "forged-id pair must never auto-admit");
1009        assert!(reasons.iter().any(|r| r.contains("G4")
1010            || r.contains("content-address")
1011            || r.contains("not Verified")));
1012    }
1013
1014    // Attack 1: a vacuous / misformalized statement whose only probe is a
1015    // CounterexampleSearch. The gate's G3 accepts any survived probe, so it
1016    // says Verified; auto-admit demands the FormalismFidelity probe.
1017    #[test]
1018    fn exact_lane_refuses_without_formalism_fidelity_probe() {
1019        let digest = claim_digest("claim X");
1020        // A vacuous/misformalized statement whose only probe is a
1021        // CounterexampleSearch — built id-valid, no FormalismFidelity probe.
1022        let a1 = attach_full(
1023            &digest,
1024            VerifierMethod::ComputationalSearch,
1025            "cp-sat",
1026            vec![],
1027            vec![surviving_probe()],
1028            MethodIntegrity::Sound,
1029            "impl-cp-sat",
1030        );
1031        let a2 = attach_full(
1032            &digest,
1033            VerifierMethod::ExactArithmeticRecompute,
1034            "pari-gp",
1035            vec![a1.id.clone()],
1036            vec![surviving_probe()],
1037            MethodIntegrity::Sound,
1038            "impl-pari",
1039        );
1040        assert_eq!(
1041            derive_gate_status(&digest, &[a1.clone(), a2.clone()]).status,
1042            GateStatus::Verified,
1043            "the bare gate tolerates a missing fidelity probe"
1044        );
1045        let (admit, reasons) = exact_lane_attachment_admit(&digest, &[a1, a2]);
1046        assert!(!admit);
1047        assert!(reasons.iter().any(|r| r.contains("FormalismFidelity")));
1048    }
1049
1050    // Attack 2: a Refuted fidelity probe must never auto-admit (it also drives
1051    // the gate itself to Refuted).
1052    #[test]
1053    fn exact_lane_refuses_refuted_formalism_fidelity() {
1054        let digest = claim_digest("claim X");
1055        let a1 = attach_full(
1056            &digest,
1057            VerifierMethod::ComputationalSearch,
1058            "cp-sat",
1059            vec![],
1060            vec![AdversarialProbe {
1061                kind: ProbeKind::FormalismFidelity,
1062                result: ProbeResult::Refuted,
1063                note: String::new(),
1064            }],
1065            MethodIntegrity::Sound,
1066            "impl-cp-sat",
1067        );
1068        let a2 = attach_full(
1069            &digest,
1070            VerifierMethod::ExactArithmeticRecompute,
1071            "pari-gp",
1072            vec![a1.id.clone()],
1073            vec![ff_survived()],
1074            MethodIntegrity::Sound,
1075            "impl-pari",
1076        );
1077        let (admit, reasons) = exact_lane_attachment_admit(&digest, &[a1, a2]);
1078        assert!(!admit);
1079        assert!(
1080            reasons
1081                .iter()
1082                .any(|r| r.contains("Refuted") || r.contains("not Verified"))
1083        );
1084    }
1085
1086    // Attack 3: the legacy Unattested integrity default. The gate's G5 only
1087    // excludes Compromised, so Unattested still drives Verified; auto-admit
1088    // demands Sound on every matched attachment.
1089    #[test]
1090    fn exact_lane_refuses_unattested_integrity() {
1091        let digest = claim_digest("claim X");
1092        let a1 = attach_full(
1093            &digest,
1094            VerifierMethod::ComputationalSearch,
1095            "cp-sat",
1096            vec![],
1097            vec![ff_survived()],
1098            MethodIntegrity::Unattested,
1099            "impl-cp-sat",
1100        );
1101        let a2 = attach_full(
1102            &digest,
1103            VerifierMethod::ExactArithmeticRecompute,
1104            "pari-gp",
1105            vec![a1.id.clone()],
1106            vec![ff_survived()],
1107            MethodIntegrity::Sound,
1108            "impl-pari",
1109        );
1110        assert_eq!(
1111            derive_gate_status(&digest, &[a1.clone(), a2.clone()]).status,
1112            GateStatus::Verified,
1113            "the bare gate tolerates Unattested integrity"
1114        );
1115        let (admit, reasons) = exact_lane_attachment_admit(&digest, &[a1, a2]);
1116        assert!(!admit);
1117        assert!(reasons.iter().any(|r| r.contains("Sound")));
1118    }
1119
1120    // Attack 4: a Compromised method (gate excludes it, dropping below 2).
1121    #[test]
1122    fn exact_lane_refuses_compromised_method() {
1123        let digest = claim_digest("claim X");
1124        let a1 = attach_full(
1125            &digest,
1126            VerifierMethod::ComputationalSearch,
1127            "cp-sat",
1128            vec![],
1129            vec![ff_survived()],
1130            MethodIntegrity::Compromised,
1131            "impl-cp-sat",
1132        );
1133        let a2 = attach_full(
1134            &digest,
1135            VerifierMethod::ExactArithmeticRecompute,
1136            "pari-gp",
1137            vec![a1.id.clone()],
1138            vec![ff_survived()],
1139            MethodIntegrity::Sound,
1140            "impl-pari",
1141        );
1142        let (admit, _r) = exact_lane_attachment_admit(&digest, &[a1, a2]);
1143        assert!(!admit);
1144    }
1145
1146    // Attack 5: NO declared independence at all. One-directional is now the
1147    // accepted (and only constructable) form, so the refusal case is the
1148    // absence of any declaration — caught by the gate's G1, inherited via
1149    // Guard 1. (Mutual independence is a hash circularity; see Guard 4.)
1150    #[test]
1151    fn exact_lane_refuses_when_no_independence_declared() {
1152        let digest = claim_digest("claim X");
1153        let a1 = attach_full(
1154            &digest,
1155            VerifierMethod::ComputationalSearch,
1156            "cp-sat",
1157            vec![],
1158            vec![ff_survived()],
1159            MethodIntegrity::Sound,
1160            "impl-cp-sat",
1161        );
1162        let a2 = attach_full(
1163            &digest,
1164            VerifierMethod::ExactArithmeticRecompute,
1165            "pari-gp",
1166            vec![], // neither names the other
1167            vec![ff_survived()],
1168            MethodIntegrity::Sound,
1169            "impl-pari",
1170        );
1171        assert_eq!(
1172            derive_gate_status(&digest, &[a1.clone(), a2.clone()]).status,
1173            GateStatus::NeedsVerification,
1174            "no declaration fails the gate's G1"
1175        );
1176        let (admit, reasons) = exact_lane_attachment_admit(&digest, &[a1, a2]);
1177        assert!(!admit);
1178        assert!(reasons.iter().any(|r| r.contains("independ")));
1179    }
1180
1181    // Attack 6: implementation monoculture (N runs of one binary). With
1182    // genuinely id-valid attachments, a single shared implementation_id trips
1183    // the gate's own monoculture observation, which (any reason => not Verified)
1184    // demotes to NeedsVerification — so the refusal arrives via Guard 1 (gate
1185    // not Verified) carrying the "monoculture" reason, before exact-lane Guard 5
1186    // is reached. Guard 5 remains as defense-in-depth for any future gate that
1187    // stops demoting on monoculture.
1188    #[test]
1189    fn exact_lane_refuses_implementation_monoculture() {
1190        let digest = claim_digest("claim X");
1191        let a1 = attach_full(
1192            &digest,
1193            VerifierMethod::ComputationalSearch,
1194            "cp-sat",
1195            vec![],
1196            vec![ff_survived()],
1197            MethodIntegrity::Sound,
1198            "same-binary",
1199        );
1200        let a2 = attach_full(
1201            &digest,
1202            VerifierMethod::ExactArithmeticRecompute,
1203            "pari-gp",
1204            vec![a1.id.clone()],
1205            vec![ff_survived()],
1206            MethodIntegrity::Sound,
1207            "same-binary",
1208        );
1209        let (admit, reasons) = exact_lane_attachment_admit(&digest, &[a1, a2]);
1210        assert!(!admit);
1211        assert!(reasons.iter().any(|r| r.contains("monoculture")));
1212    }
1213
1214    // Attack 7: a lone attachment (no independence at all).
1215    #[test]
1216    fn exact_lane_refuses_single_attachment() {
1217        let digest = claim_digest("claim X");
1218        let (a1, _a2) = admit_pair(&digest);
1219        let (admit, _r) = exact_lane_attachment_admit(&digest, &[a1]);
1220        assert!(!admit);
1221    }
1222
1223    // Attack 8: claim-digest drift. Attachments bound to a superseded claim
1224    // must not auto-admit a revised statement.
1225    #[test]
1226    fn exact_lane_refuses_on_claim_digest_drift() {
1227        let digest = claim_digest("claim X");
1228        let (a1, a2) = admit_pair(&digest);
1229        let revised = claim_digest("claim X, revised");
1230        let (admit, _r) = exact_lane_attachment_admit(&revised, &[a1, a2]);
1231        assert!(
1232            !admit,
1233            "attachments bound to the old digest must not admit the revised claim"
1234        );
1235    }
1236
1237    #[test]
1238    fn accepted_finding_with_zero_attachments_is_needs_verification() {
1239        // The headline bug class: the reducer may mark a finding
1240        // `accepted` from a self-reported payload, but with no verifier
1241        // attachments the GATE derives NeedsVerification, never Verified.
1242        let digest = claim_digest("a Sidon set of size 33 in [0,256]");
1243        let outcome = derive_gate_status(&digest, &[]);
1244        assert_eq!(outcome.status, GateStatus::NeedsVerification);
1245        assert!(!outcome.is_verified());
1246    }
1247
1248    #[test]
1249    fn single_attachment_fails_g1() {
1250        let digest = claim_digest("claim X");
1251        let a = attach(
1252            &digest,
1253            VerifierMethod::ComputationalSearch,
1254            "cp-sat",
1255            vec![],
1256            vec![surviving_probe()],
1257        );
1258        let outcome = derive_gate_status(&digest, &[a]);
1259        assert_eq!(outcome.status, GateStatus::NeedsVerification);
1260        assert!(outcome.reasons.iter().any(|r| r.starts_with("G1")));
1261    }
1262
1263    #[test]
1264    fn two_independent_matched_probed_attachments_verify() {
1265        let digest = claim_digest("claim X");
1266        let a1 = attach(
1267            &digest,
1268            VerifierMethod::ComputationalSearch,
1269            "cp-sat",
1270            vec![],
1271            vec![surviving_probe()],
1272        );
1273        let a2 = attach(
1274            &digest,
1275            VerifierMethod::ExactArithmeticRecompute,
1276            "pari-gp",
1277            vec![a1.id.clone()],
1278            vec![surviving_probe()],
1279        );
1280        let outcome = derive_gate_status(&digest, &[a1, a2]);
1281        assert_eq!(
1282            outcome.status,
1283            GateStatus::Verified,
1284            "{:?}",
1285            outcome.reasons
1286        );
1287        assert!(outcome.reasons.is_empty());
1288    }
1289
1290    #[test]
1291    fn undischarged_hypothesis_demotes_to_needs_verification() {
1292        // The 678 trap: an otherwise-verifying pair, but one attachment proves the
1293        // claim only under an undischarged hypothesis (a theorem parameter standing
1294        // for an unproven result). It is sorry-free and `#print axioms`-clean —
1295        // nothing in G1-G5 catches it — yet the gate must refuse Verified.
1296        let digest = claim_digest("claim X");
1297        let a1 = attach(
1298            &digest,
1299            VerifierMethod::ComputationalSearch,
1300            "cp-sat",
1301            vec![],
1302            vec![surviving_probe()],
1303        );
1304        let a2 = attach(
1305            &digest,
1306            VerifierMethod::ExactArithmeticRecompute,
1307            "lean4@4.29.1",
1308            vec![a1.id.clone()],
1309            vec![surviving_probe()],
1310        )
1311        .with_undischarged_hypotheses(vec!["h_density : DensityHypothesis".to_string()])
1312        .unwrap();
1313        // id still content-addresses the body after the builder mutation (G4).
1314        assert!(a2.verify().is_ok());
1315        let outcome = derive_gate_status(&digest, &[a1, a2]);
1316        assert_eq!(
1317            outcome.status,
1318            GateStatus::NeedsVerification,
1319            "{:?}",
1320            outcome.reasons
1321        );
1322        assert!(
1323            outcome
1324                .reasons
1325                .iter()
1326                .any(|r| r.contains("conditional") && r.contains("DensityHypothesis")),
1327            "{:?}",
1328            outcome.reasons
1329        );
1330    }
1331
1332    #[test]
1333    fn two_attachments_same_method_fail_independence() {
1334        let digest = claim_digest("claim X");
1335        let a1 = attach(
1336            &digest,
1337            VerifierMethod::ComputationalSearch,
1338            "cp-sat",
1339            vec![],
1340            vec![surviving_probe()],
1341        );
1342        let a2 = attach(
1343            &digest,
1344            VerifierMethod::ComputationalSearch,
1345            "cp-sat",
1346            vec![a1.id.clone()],
1347            vec![surviving_probe()],
1348        );
1349        let outcome = derive_gate_status(&digest, &[a1, a2]);
1350        assert_eq!(outcome.status, GateStatus::NeedsVerification);
1351        assert!(
1352            outcome
1353                .reasons
1354                .iter()
1355                .any(|r| r.contains("same") || r.contains("one method/solver"))
1356        );
1357    }
1358
1359    #[test]
1360    fn refuted_probe_drives_refuted() {
1361        let digest = claim_digest("claim X");
1362        let refuting = AdversarialProbe {
1363            kind: ProbeKind::CaseBConfig,
1364            result: ProbeResult::Refuted,
1365            note: "Case B breaks it".to_string(),
1366        };
1367        let a1 = attach(
1368            &digest,
1369            VerifierMethod::ComputationalSearch,
1370            "cp-sat",
1371            vec![],
1372            vec![surviving_probe()],
1373        );
1374        let a2 = attach(
1375            &digest,
1376            VerifierMethod::LpDualRecompute,
1377            "pulp-cbc",
1378            vec![a1.id.clone()],
1379            vec![refuting],
1380        );
1381        let outcome = derive_gate_status(&digest, &[a1, a2]);
1382        assert_eq!(outcome.status, GateStatus::Refuted);
1383    }
1384
1385    #[test]
1386    fn passed_but_unmatched_does_not_count() {
1387        let digest = claim_digest("claim X");
1388        let wrong_digest = claim_digest("a different claim Y");
1389        // Two passing attachments, but both bound to the wrong claim.
1390        let a1 = attach(
1391            &wrong_digest,
1392            VerifierMethod::ComputationalSearch,
1393            "cp-sat",
1394            vec![],
1395            vec![surviving_probe()],
1396        );
1397        let a2 = attach(
1398            &wrong_digest,
1399            VerifierMethod::LpDualRecompute,
1400            "pulp-cbc",
1401            vec![a1.id.clone()],
1402            vec![surviving_probe()],
1403        );
1404        let outcome = derive_gate_status(&digest, &[a1, a2]);
1405        assert_eq!(outcome.status, GateStatus::NeedsVerification);
1406        assert!(outcome.reasons.iter().any(|r| r.starts_with("G2")));
1407    }
1408
1409    #[test]
1410    fn no_probe_fails_g3() {
1411        let digest = claim_digest("claim X");
1412        let a1 = attach(
1413            &digest,
1414            VerifierMethod::ComputationalSearch,
1415            "cp-sat",
1416            vec![],
1417            vec![],
1418        );
1419        let a2 = attach(
1420            &digest,
1421            VerifierMethod::LpDualRecompute,
1422            "pulp-cbc",
1423            vec![a1.id.clone()],
1424            vec![],
1425        );
1426        let outcome = derive_gate_status(&digest, &[a1, a2]);
1427        assert_eq!(outcome.status, GateStatus::NeedsVerification);
1428        assert!(outcome.reasons.iter().any(|r| r.starts_with("G3")));
1429    }
1430
1431    #[test]
1432    fn formalism_fidelity_refuted_drives_refuted() {
1433        // A FormalismFidelity probe that refutes (statement and negation both
1434        // provable => misformalized) drives the whole gate to Refuted, so a
1435        // kernel-clean proof of an unfaithful statement cannot stand.
1436        let digest = claim_digest("claim X");
1437        let fidelity_refuted = AdversarialProbe {
1438            kind: ProbeKind::FormalismFidelity,
1439            result: ProbeResult::Refuted,
1440            note: "statement and its negation both provable".to_string(),
1441        };
1442        let a1 = attach(
1443            &digest,
1444            VerifierMethod::LeanKernel,
1445            "lean4@4.29.1",
1446            vec![],
1447            vec![fidelity_refuted],
1448        );
1449        let a2 = attach(
1450            &digest,
1451            VerifierMethod::ComputationalSearch,
1452            "cp-sat",
1453            vec![a1.id.clone()],
1454            vec![surviving_probe()],
1455        );
1456        let outcome = derive_gate_status(&digest, &[a1, a2]);
1457        assert_eq!(outcome.status, GateStatus::Refuted);
1458    }
1459
1460    #[test]
1461    fn compromised_attachment_excluded_from_matched() {
1462        // Two attachments that would otherwise verify, but the second ran a
1463        // compromised method (e.g. a native_decide Lean proof). It is
1464        // excluded from the matched set, so the finding falls back to
1465        // NeedsVerification with a G5 reason — never Verified.
1466        let digest = claim_digest("claim X");
1467        let a1 = attach(
1468            &digest,
1469            VerifierMethod::ComputationalSearch,
1470            "cp-sat",
1471            vec![],
1472            vec![surviving_probe()],
1473        );
1474        let a2 = attach(
1475            &digest,
1476            VerifierMethod::LeanKernel,
1477            "lean4@4.29.1",
1478            vec![a1.id.clone()],
1479            vec![surviving_probe()],
1480        )
1481        .with_method_integrity(MethodIntegrity::Compromised)
1482        .unwrap();
1483        let outcome = derive_gate_status(&digest, &[a1, a2]);
1484        assert_eq!(outcome.status, GateStatus::NeedsVerification);
1485        assert!(outcome.reasons.iter().any(|r| r.starts_with("G5")));
1486        // and it must NOT be misreported as a plain claim mismatch
1487        assert!(!outcome.reasons.iter().any(|r| r.starts_with("G2")));
1488    }
1489
1490    #[test]
1491    fn sound_attachment_still_verifies() {
1492        // Regression: explicitly marking integrity Sound on both legs keeps
1493        // the finding Verified (the field defaults out, ids stay stable).
1494        let digest = claim_digest("claim X");
1495        let a1 = attach(
1496            &digest,
1497            VerifierMethod::ComputationalSearch,
1498            "cp-sat",
1499            vec![],
1500            vec![surviving_probe()],
1501        )
1502        .with_method_integrity(MethodIntegrity::Sound)
1503        .unwrap();
1504        let a2 = attach(
1505            &digest,
1506            VerifierMethod::LeanKernel,
1507            "lean4@4.29.1",
1508            vec![a1.id.clone()],
1509            vec![surviving_probe()],
1510        )
1511        .with_method_integrity(MethodIntegrity::Sound)
1512        .unwrap();
1513        let outcome = derive_gate_status(&digest, &[a1, a2]);
1514        assert_eq!(
1515            outcome.status,
1516            GateStatus::Verified,
1517            "{:?}",
1518            outcome.reasons
1519        );
1520    }
1521
1522    #[test]
1523    fn unattested_integrity_serializes_absent_and_id_is_stable() {
1524        // Legacy-id stability: an Unattested attachment must serialize
1525        // without a method_integrity key, so a record minted before this
1526        // field existed re-derives the same vva_ id.
1527        let digest = claim_digest("claim X");
1528        let a = attach(
1529            &digest,
1530            VerifierMethod::ComputationalSearch,
1531            "cp-sat",
1532            vec![],
1533            vec![surviving_probe()],
1534        );
1535        let json = serde_json::to_string(&a).unwrap();
1536        assert!(
1537            !json.contains("method_integrity"),
1538            "default must serialize absent: {json}"
1539        );
1540        a.verify().unwrap();
1541    }
1542
1543    #[test]
1544    fn build_is_content_addressed_and_verifies() {
1545        let digest = claim_digest("claim X");
1546        let a = attach(
1547            &digest,
1548            VerifierMethod::ComputationalSearch,
1549            "cp-sat",
1550            vec![],
1551            vec![surviving_probe()],
1552        );
1553        assert!(a.id.starts_with("vva_"));
1554        a.verify().unwrap();
1555    }
1556
1557    #[test]
1558    fn tampered_id_rejected() {
1559        let digest = claim_digest("claim X");
1560        let mut a = attach(
1561            &digest,
1562            VerifierMethod::ComputationalSearch,
1563            "cp-sat",
1564            vec![],
1565            vec![surviving_probe()],
1566        );
1567        a.solver_id = "totally-different".to_string();
1568        assert!(a.verify().is_err());
1569    }
1570
1571    #[test]
1572    fn claim_digest_matches_python_rule() {
1573        // sha256("claim X")[:16] — same as verifier_gate_reference.py.
1574        let d = claim_digest("  claim X  ");
1575        assert_eq!(d.len(), 16);
1576        // trimming is part of the rule
1577        assert_eq!(d, claim_digest("claim X"));
1578    }
1579}