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