Skip to main content

vela_protocol/analysis/
transfer.rs

1//! Typed, signed, content-addressed cross-domain Transfer (`vtr_`).
2//!
3//! ## The asset this is
4//!
5//! A `vtr_` certifies that claim **A** (gate-verified in domain X) discharges a
6//! named **premise of claim B** (domain Y), via a verification-preserving map
7//! (a verifier-homomorphism) whose soundness is itself kernel-verified. It is
8//! the one record a single-domain captive substrate structurally cannot mint:
9//! it has no second frontier's gate-verified claim to point at and no
10//! cross-frontier theorem to anchor the link.
11//!
12//! ## What it does NOT claim
13//!
14//! A transfer **does not re-prove A and does not re-run A's verifier.** It
15//! binds three references to already-trusted objects:
16//!   1. A's *existing* gate outcome (by claim digest + the `vva_` attachment ids
17//!      that earn it),
18//!   2. a kernel-verified `Transfer A B` theorem (by its `vlv_`), and
19//!   3. the exact premise of B it discharges (by digest).
20//! The trust base is the Lean kernel + the `tcb_policy` axiom allowlist (via the
21//! `vlv_` axiom audit) + A's own G1–G5 gate. Nothing platform-adjudicated. A
22//! consumer who already trusts A and the kernel gets B's premise discharged for
23//! free; a consumer who trusts neither inherits exactly those two dependencies,
24//! made auditable. It does not claim B is true (one premise is discharged), nor
25//! that A is true beyond its gate status.
26//!
27//! Like every other status in the substrate (`gate_status`, Belnap,
28//! `attempt_resolutions`), admission is a pure function of signed objects,
29//! recomputed on read via [`derive_transfer_status`] — never a stored boolean.
30//! That is precisely what lets two independent consumers reach the same verdict.
31
32use ed25519_dalek::SigningKey;
33use serde::{Deserialize, Serialize};
34use sha2::{Digest, Sha256};
35
36pub const TRANSFER_SCHEMA: &str = "vela.transfer.v0.1";
37
38/// The witness the homomorphism's soundness rests on.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(rename_all = "snake_case")]
41pub enum TransferKind {
42    /// Soundness is a kernel-verified Lean verifier-homomorphism (a
43    /// `Transfer A B` whose `sound` field is a real proof). The strong form:
44    /// trust base is the Lean kernel + the axiom allowlist.
45    LeanHomomorphism,
46    /// Soundness is an executable frozen verifier that re-checks the mapped
47    /// object passes B's verifier. Weaker: the trust base additionally includes
48    /// that verifier, which `derive_transfer_status` flags in its reasons.
49    FrozenVerifier,
50}
51
52/// The verification-preserving map A → B, named by the artifact that proves it.
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct HomomorphismDescriptor {
55    pub kind: TransferKind,
56    /// For `LeanHomomorphism`: the Lean decl implementing `Transfer A B`
57    /// (e.g. "Vela.TransferCWCtoDNA.cwcToDNA"). For `FrozenVerifier`: the
58    /// verifier id (e.g. "vela-verify:dnacode").
59    pub map_decl: String,
60    /// Source frontier type tag — must equal A's domain (e.g. "constant_weight_code").
61    pub source_type: String,
62    /// Target frontier type tag — must equal B's premise domain (e.g. "dna_code").
63    pub target_type: String,
64    /// The `vlv_` Lean verification of the transfer theorem (`LeanHomomorphism`).
65    /// Empty for `FrozenVerifier`.
66    #[serde(default, skip_serializing_if = "String::is_empty")]
67    pub theorem_verification: String,
68    /// The Theorem-23-family theorem id in the lean-anchors registry.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub theorem_id: Option<u32>,
71}
72
73/// A signed, content-addressed cross-domain transfer.
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75pub struct Transfer {
76    pub schema: String,
77    /// `vtr_<16hex>`, content-addressed over the canonical body with
78    /// `transfer_id`, `signature`, `signer_pubkey_hex` zeroed. Key-independent
79    /// so Rust and Python derive the same id from the same body.
80    pub transfer_id: String,
81
82    // --- SOURCE (the carried claim, domain X) ---
83    /// The source claim object (`vf_`/`vfr_`/`vat_`) in domain X.
84    pub source_claim: String,
85    /// `sha256(A.claim.trim())[:16]` — the same digest the gate keys A on.
86    pub source_claim_digest: String,
87    /// A's gate status AS DECLARED. DISPLAY ONLY; re-derived at verify time via
88    /// `derive_transfer_status`, never trusted from here (mirrors
89    /// `attempt.claimed_status`).
90    #[serde(default, skip_serializing_if = "String::is_empty")]
91    pub source_gate_status_claimed: String,
92    /// The `vva_` attachment ids that earn A's gate status (the evidence set,
93    /// bound into the signed body).
94    #[serde(default, skip_serializing_if = "Vec::is_empty")]
95    pub source_attachments: Vec<String>,
96
97    // --- TARGET (the discharged premise, domain Y) ---
98    /// The target claim object (`vf_`/`vfr_`) whose premise this discharges.
99    pub target_claim: String,
100    /// `sha256(premise.trim())[:16]` of the *exact* premise A discharges — not
101    /// all of B. Pins the link to one obligation.
102    pub target_premise_digest: String,
103    /// The `vva_` attachment ids proving the TARGET verifier gate-verified the
104    /// mapped object φ(A) — the second of the two verifier receipts a
105    /// `FrozenVerifier` link stands on. `derive_transfer_status` requires the
106    /// gate over these to be `Verified`. Always present (an empty list for a
107    /// `LeanHomomorphism` link, whose theorem already covers every input).
108    pub target_attachments: Vec<String>,
109
110    // --- THE LINK ---
111    pub homomorphism: HomomorphismDescriptor,
112
113    #[serde(default, skip_serializing_if = "is_default_provenance")]
114    pub provenance: crate::attempt::Provenance,
115    #[serde(default, skip_serializing_if = "String::is_empty")]
116    pub note: String,
117
118    pub signature: String,
119    pub signer_pubkey_hex: String,
120}
121
122fn is_default_provenance(p: &crate::attempt::Provenance) -> bool {
123    *p == crate::attempt::Provenance::default()
124}
125
126/// Everything needed to build a [`Transfer`] except the derived id/signature.
127/// `Deserialize` so a producer can mint from a draft JSON (`vela transfer mint`).
128#[derive(Deserialize)]
129pub struct TransferDraft {
130    pub source_claim: String,
131    pub source_claim_digest: String,
132    #[serde(default)]
133    pub source_gate_status_claimed: String,
134    #[serde(default)]
135    pub source_attachments: Vec<String>,
136    pub target_claim: String,
137    pub target_premise_digest: String,
138    #[serde(default)]
139    pub target_attachments: Vec<String>,
140    pub homomorphism: HomomorphismDescriptor,
141    #[serde(default)]
142    pub provenance: crate::attempt::Provenance,
143    #[serde(default)]
144    pub note: String,
145}
146
147impl Transfer {
148    /// Build + sign. The id is a pure content address of the canonical body
149    /// (key-independent); the signature binds the signer. Mirrors `Attempt::build`.
150    pub fn build(draft: TransferDraft, key: &SigningKey) -> Result<Self, String> {
151        if draft.source_claim.trim().is_empty() {
152            return Err("transfer.source_claim cannot be empty".to_string());
153        }
154        if draft.target_claim.trim().is_empty() {
155            return Err("transfer.target_claim cannot be empty".to_string());
156        }
157        if draft.target_premise_digest.trim().is_empty() {
158            return Err(
159                "transfer.target_premise_digest cannot be empty (T5: a transfer must \
160                        discharge a specific premise, not all of B)"
161                    .to_string(),
162            );
163        }
164        let h = &draft.homomorphism;
165        if h.map_decl.trim().is_empty() {
166            return Err("transfer.homomorphism.map_decl cannot be empty".to_string());
167        }
168        if h.source_type.trim().is_empty() || h.target_type.trim().is_empty() {
169            return Err(
170                "transfer.homomorphism source_type/target_type cannot be empty".to_string(),
171            );
172        }
173        if h.kind == TransferKind::LeanHomomorphism && !h.theorem_verification.starts_with("vlv_") {
174            return Err(
175                "a LeanHomomorphism transfer requires a `vlv_` theorem_verification".to_string(),
176            );
177        }
178        let mut t = Transfer {
179            schema: TRANSFER_SCHEMA.to_string(),
180            transfer_id: String::new(),
181            source_claim: draft.source_claim,
182            source_claim_digest: draft.source_claim_digest,
183            source_gate_status_claimed: draft.source_gate_status_claimed,
184            source_attachments: draft.source_attachments,
185            target_claim: draft.target_claim,
186            target_premise_digest: draft.target_premise_digest,
187            target_attachments: draft.target_attachments,
188            homomorphism: draft.homomorphism,
189            provenance: draft.provenance,
190            note: draft.note,
191            signature: String::new(),
192            signer_pubkey_hex: hex::encode(key.verifying_key().to_bytes()),
193        };
194        let preimage = t.id_preimage_bytes()?;
195        t.signature = hex::encode(crate::sign::sign_bytes(key, &preimage));
196        t.transfer_id = t.derive_id()?;
197        Ok(t)
198    }
199
200    /// The canonical-JSON bytes the id and signature are taken over: the body
201    /// with `transfer_id`, `signature`, `signer_pubkey_hex` zeroed.
202    fn id_preimage_bytes(&self) -> Result<Vec<u8>, String> {
203        let mut preimage = self.clone();
204        preimage.transfer_id = String::new();
205        preimage.signature = String::new();
206        preimage.signer_pubkey_hex = String::new();
207        crate::canonical::to_canonical_bytes(&preimage)
208            .map_err(|e| format!("canonicalize transfer preimage: {e}"))
209    }
210
211    /// `vtr_<16hex>` over the canonical content preimage.
212    pub fn derive_id(&self) -> Result<String, String> {
213        let bytes = self.id_preimage_bytes()?;
214        Ok(format!(
215            "vtr_{}",
216            &hex::encode(Sha256::digest(&bytes))[..16]
217        ))
218    }
219
220    /// Structural verify: re-derive the id, verify the signature over the
221    /// content preimage. Any hand-edit to the body fails here. (Admission — that
222    /// the link is sound — is a separate read-time check, [`derive_transfer_status`].)
223    pub fn verify(&self) -> Result<(), String> {
224        if self.schema != TRANSFER_SCHEMA {
225            return Err(format!(
226                "transfer.schema must be `{TRANSFER_SCHEMA}`, got `{}`",
227                self.schema
228            ));
229        }
230        if !self.transfer_id.starts_with("vtr_") {
231            return Err(format!(
232                "transfer id must start with `vtr_`, got `{}`",
233                self.transfer_id
234            ));
235        }
236        let preimage = self.id_preimage_bytes()?;
237        if !crate::sign::verify_action_signature(
238            &preimage,
239            &self.signature,
240            &self.signer_pubkey_hex,
241        )? {
242            return Err("transfer signature does not verify under the declared pubkey".to_string());
243        }
244        let rederived = self.derive_id()?;
245        if rederived != self.transfer_id {
246            return Err(format!(
247                "transfer_id mismatch: declared {}, rebuilt {}",
248                self.transfer_id, rederived
249            ));
250        }
251        Ok(())
252    }
253
254    /// Build the canonical `transfer.deposited` event. The full object travels
255    /// in `payload.transfer`; the reducer verifies and upserts it.
256    #[must_use]
257    pub fn deposit_event(
258        &self,
259        actor_id: &str,
260        actor_type: &str,
261        reason: &str,
262    ) -> crate::events::StateEvent {
263        let payload =
264            serde_json::json!({ "transfer": serde_json::to_value(self).unwrap_or_default() });
265        crate::events::new_transfer_deposited_event(
266            &self.transfer_id,
267            actor_id,
268            actor_type,
269            reason,
270            payload,
271            vec![
272                "A signed cross-domain transfer. It certifies the LINK is sound given A's \
273                 gate-status; it does NOT re-prove A or re-run A's verifier."
274                    .to_string(),
275            ],
276        )
277    }
278}
279
280/// The derived admission status of a transfer. Like [`crate::verifier_attachment::GateStatus`],
281/// there is no constructor that sets this directly — only [`derive_transfer_status`].
282#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
283#[serde(rename_all = "snake_case")]
284pub enum TransferStatus {
285    /// The default: not enough verified evidence to admit the link.
286    NeedsVerification,
287    /// T1–T5 all satisfied: A's claim discharges B's premise.
288    Admitted,
289    /// A's source claim is refuted, or the transfer theorem's method integrity
290    /// is compromised (e.g. `native_decide`/`sorry`). Terminal until revised.
291    Rejected,
292}
293
294/// The full outcome: a status plus the reasons it is not [`TransferStatus::Admitted`]
295/// (empty exactly when admitted).
296#[derive(Debug, Clone, PartialEq, Eq)]
297pub struct TransferOutcome {
298    pub status: TransferStatus,
299    pub reasons: Vec<String>,
300}
301
302impl TransferOutcome {
303    #[must_use]
304    pub fn is_admitted(&self) -> bool {
305        self.status == TransferStatus::Admitted
306    }
307}
308
309/// The domain tags a resolver pulled from A's actual frontier and B's premise.
310#[derive(Debug, Clone, PartialEq, Eq)]
311pub struct DomainTags {
312    pub source: String,
313    pub target: String,
314}
315
316/// The frozen-verifier ids admissible as a `FrozenVerifier` transfer witness.
317/// Anything else forces `NeedsVerification` (the weaker form is gated to known,
318/// audited executable verifiers, never an arbitrary string).
319const ALLOWED_FROZEN_VERIFIERS: &[&str] = &[
320    "vela-verify:sidon",
321    "vela-verify:cap",
322    "vela-verify:golomb",
323    "vela-verify:bh",
324    "vela-verify:constantweight",
325    "vela-verify:linearcode",
326    "vela-verify:dnacode",
327    "vela-verify:covering",
328    "vela-verify:stabilizer",
329];
330
331/// Derive whether a transfer is admitted: a pure function of already-signed
332/// objects (T1–T5), recomputed on read, never stored. Mirrors
333/// [`crate::verifier_attachment::derive_gate_status`].
334///
335/// - `source_gate`: A's gate outcome, derived by the caller over the `vva_`
336///   attachments matching `transfer.source_claim_digest`.
337/// - `target_gate`: the TARGET verifier's outcome over the mapped object φ(A),
338///   derived over `transfer.target_attachments` / `target_premise_digest`. The
339///   `FrozenVerifier` lane requires this `Verified` (the 2-verifier rule);
340///   `LeanHomomorphism` ignores it (its theorem covers every input).
341/// - `theorem_verification`: the `vlv_` of the transfer theorem (for
342///   `LeanHomomorphism`); `None` is allowed only for `FrozenVerifier`.
343/// - `domain_tags`: A's actual domain and B's premise's domain, resolved from state.
344#[must_use]
345pub fn derive_transfer_status(
346    transfer: &Transfer,
347    source_gate: &crate::verifier_attachment::GateOutcome,
348    target_gate: &crate::verifier_attachment::GateOutcome,
349    theorem_verification: Option<&crate::lean_verification::LeanVerification>,
350    domain_tags: &DomainTags,
351) -> TransferOutcome {
352    use crate::verifier_attachment::{GateStatus, MethodIntegrity};
353    let mut reasons = Vec::new();
354    let mut rejected = false;
355
356    // T4 well-formed (structural integrity of the link itself).
357    if let Err(e) = transfer.verify() {
358        reasons.push(format!("T4: transfer is not well-formed: {e}"));
359    }
360
361    // T1 source-verified — consume A's EXISTING gate outcome, never recompute.
362    match source_gate.status {
363        GateStatus::Verified => {}
364        GateStatus::Refuted => {
365            rejected = true;
366            reasons.push(
367                "T1: source claim A is REFUTED — the transfer cannot discharge B".to_string(),
368            );
369        }
370        GateStatus::NeedsVerification => {
371            reasons.push("T1: source claim A is not gate-verified (NeedsVerification)".to_string());
372        }
373    }
374
375    // T2 method integrity of the homomorphism witness.
376    match transfer.homomorphism.kind {
377        TransferKind::LeanHomomorphism => match theorem_verification {
378            None => reasons.push(
379                "T2: LeanHomomorphism transfer has no resolved `vlv_` theorem verification"
380                    .to_string(),
381            ),
382            Some(v) => {
383                if let Err(e) = v.verify() {
384                    reasons.push(format!("T2: transfer theorem `vlv_` does not verify: {e}"));
385                } else if v.status != "verified" {
386                    reasons.push(format!(
387                        "T2: transfer theorem status is `{}`, not `verified`",
388                        v.status
389                    ));
390                }
391                match v.to_attachment_integrity() {
392                    MethodIntegrity::Sound => {}
393                    MethodIntegrity::Compromised => {
394                        rejected = true;
395                        reasons.push("T2: transfer theorem method integrity COMPROMISED \
396                                      (forbidden axiom — e.g. native_decide/sorry — or failed kernel re-check)"
397                            .to_string());
398                    }
399                    MethodIntegrity::Unattested => reasons
400                        .push("T2: transfer theorem has no axiom audit (Unattested)".to_string()),
401                }
402            }
403        },
404        TransferKind::FrozenVerifier => {
405            if ALLOWED_FROZEN_VERIFIERS.contains(&transfer.homomorphism.map_decl.as_str()) {
406                reasons.push(format!(
407                    "note: FrozenVerifier transfer — trust base additionally includes the executable \
408                     verifier `{}`, not only the Lean kernel",
409                    transfer.homomorphism.map_decl
410                ));
411            } else {
412                reasons.push(format!(
413                    "T2: FrozenVerifier `{}` is not in the audited allowlist",
414                    transfer.homomorphism.map_decl
415                ));
416            }
417            // T6 (the 2-verifier rule): the FrozenVerifier lane does not trust the
418            // map φ, so it requires the TARGET verifier to have INDEPENDENTLY
419            // gate-verified the mapped object φ(A). Two verifiers, two receipts:
420            // `source_gate` (V_A on A) above, and `target_gate` (V_B on φ(A)) here.
421            // The map is only a hint; the target receipt is the proof.
422            // (LeanHomomorphism needs no such receipt — its theorem covers every input.)
423            match target_gate.status {
424                GateStatus::Verified => {}
425                GateStatus::Refuted => {
426                    rejected = true;
427                    reasons.push(
428                        "T6: the target verifier REFUTED the mapped object φ(A) — the link cannot \
429                         discharge B"
430                            .to_string(),
431                    );
432                }
433                GateStatus::NeedsVerification => reasons.push(
434                    "T6: FrozenVerifier transfer requires a Verified target-verifier receipt on \
435                     φ(A) (target_attachments); none resolved"
436                        .to_string(),
437                ),
438            }
439        }
440    }
441
442    // T3 type-match: the homomorphism's declared A→B types must equal A's actual
443    // domain and B's premise's domain. A map proven for X→Y cannot discharge a Z premise.
444    if transfer.homomorphism.source_type != domain_tags.source {
445        reasons.push(format!(
446            "T3: homomorphism source_type `{}` != A's domain `{}`",
447            transfer.homomorphism.source_type, domain_tags.source
448        ));
449    }
450    if transfer.homomorphism.target_type != domain_tags.target {
451        reasons.push(format!(
452            "T3: homomorphism target_type `{}` != B's premise domain `{}`",
453            transfer.homomorphism.target_type, domain_tags.target
454        ));
455    }
456
457    // T5 premise-binding: a specific premise, not all of B.
458    if transfer.target_premise_digest.trim().is_empty() {
459        reasons.push("T5: target_premise_digest is empty (no specific premise pinned)".to_string());
460    }
461
462    // A `note:` reason (the FrozenVerifier trust-base disclosure) does not block
463    // admission; only T-clause failures do.
464    let blocking = reasons.iter().any(|r| !r.starts_with("note:"));
465    let status = if rejected {
466        TransferStatus::Rejected
467    } else if blocking {
468        TransferStatus::NeedsVerification
469    } else {
470        TransferStatus::Admitted
471    };
472    TransferOutcome { status, reasons }
473}
474
475#[cfg(test)]
476mod tests {
477    use super::*;
478    use crate::lean_verification::{KernelRecheck, LeanVerification, VerificationDraft};
479    use crate::tcb_policy::AxiomVerdict;
480    use crate::verifier_attachment::{GateOutcome, GateStatus};
481    use rand::rngs::OsRng;
482
483    fn key() -> SigningKey {
484        SigningKey::generate(&mut OsRng)
485    }
486
487    fn lean_decl_descriptor(theorem_verification: &str) -> HomomorphismDescriptor {
488        HomomorphismDescriptor {
489            kind: TransferKind::LeanHomomorphism,
490            map_decl: "Vela.TransferCWCtoDNA.cwcToDNA".to_string(),
491            source_type: "constant_weight_code".to_string(),
492            target_type: "dna_code".to_string(),
493            theorem_verification: theorem_verification.to_string(),
494            theorem_id: Some(35),
495        }
496    }
497
498    fn draft(theorem_verification: &str) -> TransferDraft {
499        TransferDraft {
500            source_claim: "vat_aaaaaaaaaaaaaaaa".to_string(),
501            source_claim_digest: crate::verifier_attachment::claim_digest("A(n,d,w) >= 12"),
502            source_gate_status_claimed: "verified".to_string(),
503            source_attachments: vec!["vva_bbbbbbbbbbbbbbbb".to_string()],
504            target_claim: "vfr_cccccccccccccccc".to_string(),
505            target_premise_digest: crate::verifier_attachment::claim_digest(
506                "a DNA code of size >= 12 exists",
507            ),
508            // Empty: a LeanHomomorphism link needs no target receipt (its theorem
509            // is universal). The admits_* tests confirm it still reaches Admitted.
510            target_attachments: vec![],
511            homomorphism: lean_decl_descriptor(theorem_verification),
512            provenance: crate::attempt::Provenance::default(),
513            note: String::new(),
514        }
515    }
516
517    /// A kernel-clean (or compromised) Lean verification for the transfer theorem.
518    fn lean_v(kernel_clean: bool) -> LeanVerification {
519        let d = VerificationDraft {
520            anchor_id: "vla_dddddddddddddddd".to_string(),
521            theorem_id: 35,
522            module: "Vela/Transfer.lean".to_string(),
523            module_sha256: "0".repeat(64),
524            lean_toolchain: "leanprover/lean4:v4.29.1".to_string(),
525            mathlib_revision: "abc".to_string(),
526            verifier_output_hash: "0".repeat(64),
527            status: if kernel_clean {
528                "verified".to_string()
529            } else {
530                "failed_axiom_check".to_string()
531            },
532            verified_at: "2026-06-09T00:00:00Z".to_string(),
533            verifier_actor: "test".to_string(),
534            tcb_id: "vtcb_dddddddddddddddd".to_string(),
535            axioms: vec![
536                "propext".to_string(),
537                "Classical.choice".to_string(),
538                "Quot.sound".to_string(),
539            ],
540            axiom_verdict: Some(if kernel_clean {
541                AxiomVerdict::KernelClean
542            } else {
543                AxiomVerdict::ForbiddenAxiom
544            }),
545            kernel_recheck: Some(KernelRecheck::Passed),
546            axioms_output_hash: "0".repeat(64),
547        };
548        LeanVerification::build(d, &key()).unwrap()
549    }
550
551    fn verified_gate() -> GateOutcome {
552        GateOutcome {
553            status: GateStatus::Verified,
554            reasons: vec![],
555        }
556    }
557
558    #[test]
559    fn build_verify_roundtrip_and_id_prefix() {
560        let t = Transfer::build(draft("vlv_eeeeeeeeeeeeeeee"), &key()).unwrap();
561        assert!(t.transfer_id.starts_with("vtr_"));
562        t.verify().unwrap();
563    }
564
565    #[test]
566    fn tampered_body_fails_t4() {
567        let mut t = Transfer::build(draft("vlv_eeeeeeeeeeeeeeee"), &key()).unwrap();
568        t.target_premise_digest = crate::verifier_attachment::claim_digest("a DIFFERENT premise");
569        assert!(t.verify().is_err());
570    }
571
572    #[test]
573    fn admits_when_all_clauses_pass() {
574        let v = lean_v(true);
575        let t = Transfer::build(draft(&v.verification_id), &key()).unwrap();
576        let tags = DomainTags {
577            source: "constant_weight_code".into(),
578            target: "dna_code".into(),
579        };
580        let out = derive_transfer_status(&t, &verified_gate(), &verified_gate(), Some(&v), &tags);
581        assert_eq!(
582            out.status,
583            TransferStatus::Admitted,
584            "reasons: {:?}",
585            out.reasons
586        );
587    }
588
589    #[test]
590    fn native_decide_theorem_cannot_admit() {
591        let v = lean_v(false); // forbidden axiom -> Compromised integrity
592        let t = Transfer::build(draft(&v.verification_id), &key()).unwrap();
593        let tags = DomainTags {
594            source: "constant_weight_code".into(),
595            target: "dna_code".into(),
596        };
597        let out = derive_transfer_status(&t, &verified_gate(), &verified_gate(), Some(&v), &tags);
598        assert_eq!(out.status, TransferStatus::Rejected);
599    }
600
601    #[test]
602    fn refuted_source_drives_rejected() {
603        let v = lean_v(true);
604        let t = Transfer::build(draft(&v.verification_id), &key()).unwrap();
605        let tags = DomainTags {
606            source: "constant_weight_code".into(),
607            target: "dna_code".into(),
608        };
609        let refuted = GateOutcome {
610            status: GateStatus::Refuted,
611            reasons: vec!["probe refuted".into()],
612        };
613        let out = derive_transfer_status(&t, &refuted, &verified_gate(), Some(&v), &tags);
614        assert_eq!(out.status, TransferStatus::Rejected);
615    }
616
617    #[test]
618    fn type_mismatch_is_not_admitted() {
619        let v = lean_v(true);
620        let t = Transfer::build(draft(&v.verification_id), &key()).unwrap();
621        let tags = DomainTags {
622            source: "sidon".into(),
623            target: "dna_code".into(),
624        }; // wrong source
625        let out = derive_transfer_status(&t, &verified_gate(), &verified_gate(), Some(&v), &tags);
626        assert_eq!(out.status, TransferStatus::NeedsVerification);
627        assert!(out.reasons.iter().any(|r| r.starts_with("T3")));
628    }
629
630    #[test]
631    fn unverified_source_needs_verification() {
632        let v = lean_v(true);
633        let t = Transfer::build(draft(&v.verification_id), &key()).unwrap();
634        let tags = DomainTags {
635            source: "constant_weight_code".into(),
636            target: "dna_code".into(),
637        };
638        let needs = GateOutcome {
639            status: GateStatus::NeedsVerification,
640            reasons: vec![],
641        };
642        let out = derive_transfer_status(&t, &needs, &verified_gate(), Some(&v), &tags);
643        assert_eq!(out.status, TransferStatus::NeedsVerification);
644    }
645
646    // --- The 2-verifier rule (T6) for the FrozenVerifier lane ---
647
648    fn frozen_draft() -> TransferDraft {
649        TransferDraft {
650            source_claim: "vf_sidon_a7".to_string(),
651            source_claim_digest: crate::verifier_attachment::claim_digest("a Sidon set of size 7"),
652            source_gate_status_claimed: "verified".to_string(),
653            source_attachments: vec!["vva_source_sidon".to_string()],
654            target_claim: "vfr_golomb".to_string(),
655            target_premise_digest: crate::verifier_attachment::claim_digest(
656                "a Golomb ruler of size 7 exists",
657            ),
658            target_attachments: vec!["vva_target_golomb".to_string()],
659            homomorphism: HomomorphismDescriptor {
660                kind: TransferKind::FrozenVerifier,
661                map_decl: "vela-verify:golomb".to_string(),
662                source_type: "sidon".to_string(),
663                target_type: "golomb".to_string(),
664                theorem_verification: String::new(),
665                theorem_id: None,
666            },
667            provenance: Default::default(),
668            note: String::new(),
669        }
670    }
671
672    fn golomb_tags() -> DomainTags {
673        DomainTags {
674            source: "sidon".into(),
675            target: "golomb".into(),
676        }
677    }
678
679    fn needs_gate() -> GateOutcome {
680        GateOutcome {
681            status: GateStatus::NeedsVerification,
682            reasons: vec![],
683        }
684    }
685
686    #[test]
687    fn frozen_admits_only_with_both_verifier_receipts() {
688        let t = Transfer::build(frozen_draft(), &key()).unwrap();
689        // Source verified + target verified -> the two-verifier rule is satisfied.
690        let out =
691            derive_transfer_status(&t, &verified_gate(), &verified_gate(), None, &golomb_tags());
692        assert_eq!(
693            out.status,
694            TransferStatus::Admitted,
695            "reasons: {:?}",
696            out.reasons
697        );
698    }
699
700    #[test]
701    fn frozen_without_target_receipt_is_not_admitted() {
702        let t = Transfer::build(frozen_draft(), &key()).unwrap();
703        // Source verified but NO target receipt: must NOT admit on the verifier's
704        // name alone. This is the hole the 2-verifier rule closes.
705        let out = derive_transfer_status(&t, &verified_gate(), &needs_gate(), None, &golomb_tags());
706        assert_eq!(out.status, TransferStatus::NeedsVerification);
707        assert!(
708            out.reasons.iter().any(|r| r.starts_with("T6")),
709            "reasons: {:?}",
710            out.reasons
711        );
712    }
713
714    #[test]
715    fn frozen_with_refuted_target_is_rejected() {
716        let t = Transfer::build(frozen_draft(), &key()).unwrap();
717        let refuted = GateOutcome {
718            status: GateStatus::Refuted,
719            reasons: vec!["golomb verifier refuted φ(A)".into()],
720        };
721        let out = derive_transfer_status(&t, &verified_gate(), &refuted, None, &golomb_tags());
722        assert_eq!(out.status, TransferStatus::Rejected);
723    }
724}