Skip to main content

vela_protocol/objects/
attempt.rs

1//! Typed, signed, content-addressed Attempt (`vat_`) + ResolutionEvent
2//! (`vre_`).
3//!
4//! ## The hole this closes
5//!
6//! Our own banked work lived in a Python ledger
7//! (`scripts/canopus_attempts.py`) whose records are hand-editable JSON with
8//! `att_` ids hashed from a pipe-delimited string. A proposer agent could
9//! silently rewrite a banked attempt, and negatives/failed searches had no
10//! first-class shape. This module lifts the attempt into the protocol as a
11//! content-addressed, Ed25519-signed object — so any edit to a banked attempt
12//! breaks both its `vat_` id and its signature in one `verify()` — and makes
13//! the failed-attempt denominator and reproduction fraction first-class.
14//!
15//! ## Two objects, mirroring the Contradiction precedent
16//!
17//! - [`Attempt`] (`vat_`) is the immutable, signed deposit. Its id is
18//!   content-addressed over the canonical body (id + signature +
19//!   signer_pubkey zeroed), so the **same logical body yields the same id in
20//!   Rust and Python** (`conformance/attempt-id.json` pins this), exactly like
21//!   the `vex_` experiment. The signature binds a named signer to that body.
22//! - [`ResolutionEvent`] (`vre_`) is an append-only lifecycle transition
23//!   (`candidate → verified | refuted | superseded | redundant_with_literature`).
24//!   It travels in a signed `attempt.resolved` [`crate::events::StateEvent`]
25//!   (added in events.rs), and the reducer keeps the latest per attempt. The
26//!   `verified` outcome carries a `gate_ref`, never a stored boolean — the
27//!   gate result is derived from the `vva_` attachments on read, the same
28//!   discipline the substrate already uses for `gate_status`.
29
30use ed25519_dalek::SigningKey;
31use serde::{Deserialize, Serialize};
32use sha2::{Digest, Sha256};
33
34pub const ATTEMPT_SCHEMA: &str = "vela.attempt.v0.1";
35pub const RESOLUTION_EVENT_SCHEMA: &str = "vela.resolution_event.v0.1";
36
37/// Reproduction as an explicit fraction: `successes` of `total` independent
38/// re-runs reproduced the claim. `0/0` means not yet reproduced.
39#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
40pub struct Reproduction {
41    pub successes: u64,
42    pub total: u64,
43}
44
45/// The full cost of an attempt, including the failures that the headline
46/// success hides. A frontier that shows only wins reproduces the exact
47/// transparency hole the community calls out in lab repos.
48#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
49pub struct AttemptCost {
50    /// Total attempts run for this claim (successes + failures + triage).
51    pub total_attempts: u64,
52    /// How many of those failed (the denominator made explicit).
53    pub failed_attempts: u64,
54    /// Free-form compute note (e.g. "788K randomized runs, 16 cores, 3h").
55    #[serde(default, skip_serializing_if = "String::is_empty")]
56    pub compute_note: String,
57}
58
59/// Who/what proposed the attempt and when.
60#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
61pub struct Provenance {
62    #[serde(default, skip_serializing_if = "String::is_empty")]
63    pub proposer: String,
64    #[serde(default, skip_serializing_if = "String::is_empty")]
65    pub run: String,
66    #[serde(default, skip_serializing_if = "String::is_empty")]
67    pub date: String,
68}
69
70/// The generic Producer primitive (v0.700 minimal core): which system emitted
71/// the attempt, its version, and a digest of its configuration. Generalizes the
72/// Sidon producer so any solver, an API reasoning model, an open prover, or a
73/// closed agent, declares itself uniformly. The ablation and the retained-loop
74/// handoff key on this to compare like producers and detect cross-producer reuse.
75#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
76pub struct ProducerRef {
77    #[serde(default, skip_serializing_if = "String::is_empty")]
78    pub system: String,
79    #[serde(default, skip_serializing_if = "String::is_empty")]
80    pub version: String,
81    #[serde(default, skip_serializing_if = "String::is_empty")]
82    pub config_digest: String,
83}
84
85fn is_default_producer(p: &ProducerRef) -> bool {
86    *p == ProducerRef::default()
87}
88
89/// A signed, content-addressed banked attempt.
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91pub struct Attempt {
92    pub schema: String,
93    /// `vat_<16hex>`, content-addressed over the canonical body with
94    /// `attempt_id`, `signature`, `signer_pubkey_hex` zeroed. Key-independent
95    /// so Rust and Python derive the same id from the same body.
96    pub attempt_id: String,
97    /// The Erdős problem number this attempt targets, or `0` for a
98    /// domain-general attempt (sidon / diff_triangle / other foundry kinds with
99    /// no Erdős number — identified by `frontier` + `kind` + `claim` instead).
100    /// Skip-guarded so every existing problem-numbered attempt content-addresses
101    /// byte-identically; a `0` simply omits the field for a new id.
102    #[serde(default, skip_serializing_if = "is_zero_u32")]
103    pub problem: u32,
104    #[serde(default, skip_serializing_if = "String::is_empty")]
105    pub frontier: String,
106    pub kind: String,
107    pub claim: String,
108    #[serde(default, skip_serializing_if = "String::is_empty")]
109    pub detail: String,
110    /// The proposer's self-reported status. DISPLAY ONLY; never trusted. The
111    /// verified status is derived from the gate + ResolutionEvents on read.
112    #[serde(default, skip_serializing_if = "String::is_empty")]
113    pub claimed_status: String,
114    /// `sha256(claim.trim())[:16]`, the same rule the gate and Python use.
115    pub claim_digest: String,
116    #[serde(default, skip_serializing_if = "is_default_reproduction")]
117    pub reproduction: Reproduction,
118    #[serde(default, skip_serializing_if = "is_default_cost")]
119    pub cost: AttemptCost,
120    /// What was learned, including from failure — so negatives survive as
121    /// research assets, not as nothing.
122    #[serde(default, skip_serializing_if = "String::is_empty")]
123    pub insight: String,
124    #[serde(default, skip_serializing_if = "Vec::is_empty")]
125    pub depends_on: Vec<String>,
126    #[serde(default, skip_serializing_if = "Vec::is_empty")]
127    pub related_problems: Vec<u32>,
128    #[serde(default, skip_serializing_if = "String::is_empty")]
129    pub reusable_for: String,
130    /// Ids of the `vva_` verifier attachments that earn this attempt's trust.
131    #[serde(default, skip_serializing_if = "Vec::is_empty")]
132    pub verifier_attachments: Vec<String>,
133    /// Honest deliverable grade (anti-inflation), if assigned.
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub deliverable_grade: Option<String>,
136    #[serde(default, skip_serializing_if = "is_default_provenance")]
137    pub provenance: Provenance,
138    // ── v0.700 Attempt Packet (the producer-forced minimal-core promotion) ──
139    // Additive + skip-guarded, so legacy attempts serialize and content-address
140    // byte-identically. These fields make the retained-producer handoff and the
141    // inherited-state ablation measurable.
142    /// The frontier root this attempt was made against. The pin that makes
143    /// "Agent B with vs without Agent A's accepted state" a controlled compare,
144    /// and that lets a later root be a clean continuation.
145    #[serde(default, skip_serializing_if = "String::is_empty")]
146    pub base_frontier_root: String,
147    /// The residual obligation this attempt targeted (free-form id; the
148    /// Obligation/StatementVariant nouns stay domain-local until promoted).
149    #[serde(default, skip_serializing_if = "String::is_empty")]
150    pub target_obligation_id: String,
151    /// The statement variant attempted (free-form id).
152    #[serde(default, skip_serializing_if = "String::is_empty")]
153    pub statement_variant_id: String,
154    /// Method families exercised. Drives duplicate-search detection in the ablation.
155    #[serde(default, skip_serializing_if = "Vec::is_empty")]
156    pub method_families: Vec<String>,
157    /// Obligations left open after this attempt (free-form ids).
158    #[serde(default, skip_serializing_if = "Vec::is_empty")]
159    pub remaining_obligations: Vec<String>,
160    /// Named obstructions encountered, free-form `kind:scope` until the
161    /// Obstruction noun is promoted under a second producer's pressure.
162    #[serde(default, skip_serializing_if = "Vec::is_empty")]
163    pub named_obstructions: Vec<String>,
164    /// What produced this attempt (the generic Producer primitive).
165    #[serde(default, skip_serializing_if = "is_default_producer")]
166    pub producer: ProducerRef,
167    pub signature: String,
168    pub signer_pubkey_hex: String,
169}
170
171fn is_zero_u32(n: &u32) -> bool {
172    *n == 0
173}
174fn is_default_reproduction(r: &Reproduction) -> bool {
175    *r == Reproduction::default()
176}
177fn is_default_cost(c: &AttemptCost) -> bool {
178    *c == AttemptCost::default()
179}
180fn is_default_provenance(p: &Provenance) -> bool {
181    *p == Provenance::default()
182}
183
184/// Fields a caller supplies; schema, id, claim_digest, and signature are
185/// derived.
186#[derive(Debug, Clone, Default)]
187pub struct AttemptDraft {
188    pub problem: u32,
189    pub frontier: String,
190    pub kind: String,
191    pub claim: String,
192    pub detail: String,
193    pub claimed_status: String,
194    pub reproduction: Reproduction,
195    pub cost: AttemptCost,
196    pub insight: String,
197    pub depends_on: Vec<String>,
198    pub related_problems: Vec<u32>,
199    pub reusable_for: String,
200    pub verifier_attachments: Vec<String>,
201    pub deliverable_grade: Option<String>,
202    pub provenance: Provenance,
203    // v0.700 Attempt Packet fields (all optional).
204    pub base_frontier_root: String,
205    pub target_obligation_id: String,
206    pub statement_variant_id: String,
207    pub method_families: Vec<String>,
208    pub remaining_obligations: Vec<String>,
209    pub named_obstructions: Vec<String>,
210    pub producer: ProducerRef,
211}
212
213/// The one canonical claim digest (`sha256(claim.trim())[:16]`), defined in
214/// `verifier_attachment` and re-exported here so a claim has one digest
215/// everywhere (and matches `verifier_gate_reference.py`).
216pub use crate::verifier_attachment::claim_digest;
217
218impl Attempt {
219    /// Build and sign a banked attempt. The id is content-addressed over the
220    /// canonical body (key-independent); the signature binds the signer.
221    pub fn build(draft: AttemptDraft, key: &SigningKey) -> Result<Self, String> {
222        // `problem == 0` is a valid domain-general attempt (no Erdős number);
223        // such an attempt must instead name its frontier so it is still
224        // attributable to a target surface.
225        if draft.problem == 0 && draft.frontier.trim().is_empty() {
226            return Err(
227                "attempt needs a positive Erdős problem number or a frontier id".to_string(),
228            );
229        }
230        if draft.kind.trim().is_empty() {
231            return Err("attempt.kind cannot be empty".to_string());
232        }
233        if draft.claim.trim().is_empty() {
234            return Err("attempt.claim cannot be empty".to_string());
235        }
236        if draft.cost.failed_attempts > draft.cost.total_attempts {
237            return Err("attempt.cost.failed_attempts cannot exceed total_attempts".to_string());
238        }
239        if draft.reproduction.successes > draft.reproduction.total {
240            return Err("attempt.reproduction.successes cannot exceed total".to_string());
241        }
242        let mut att = Attempt {
243            schema: ATTEMPT_SCHEMA.to_string(),
244            attempt_id: String::new(),
245            problem: draft.problem,
246            frontier: draft.frontier,
247            kind: draft.kind,
248            claim_digest: claim_digest(&draft.claim),
249            claim: draft.claim,
250            detail: draft.detail,
251            claimed_status: draft.claimed_status,
252            reproduction: draft.reproduction,
253            cost: draft.cost,
254            insight: draft.insight,
255            depends_on: draft.depends_on,
256            related_problems: draft.related_problems,
257            reusable_for: draft.reusable_for,
258            verifier_attachments: draft.verifier_attachments,
259            deliverable_grade: draft.deliverable_grade,
260            provenance: draft.provenance,
261            base_frontier_root: draft.base_frontier_root,
262            target_obligation_id: draft.target_obligation_id,
263            statement_variant_id: draft.statement_variant_id,
264            method_families: draft.method_families,
265            remaining_obligations: draft.remaining_obligations,
266            named_obstructions: draft.named_obstructions,
267            producer: draft.producer,
268            signature: String::new(),
269            signer_pubkey_hex: hex::encode(key.verifying_key().to_bytes()),
270        };
271        let preimage = att.id_preimage_bytes()?;
272        att.signature = hex::encode(crate::sign::sign_bytes(key, &preimage));
273        att.attempt_id = att.derive_id()?;
274        Ok(att)
275    }
276
277    /// The canonical-JSON bytes the id and signature are taken over: the body
278    /// with `attempt_id`, `signature`, and `signer_pubkey_hex` zeroed. Zeroing
279    /// the signer keeps the id a pure content address of the attempt, the same
280    /// in Rust and Python.
281    fn id_preimage_bytes(&self) -> Result<Vec<u8>, String> {
282        let mut preimage = self.clone();
283        preimage.attempt_id = String::new();
284        preimage.signature = String::new();
285        preimage.signer_pubkey_hex = String::new();
286        crate::canonical::to_canonical_bytes(&preimage)
287            .map_err(|e| format!("canonicalize attempt preimage: {e}"))
288    }
289
290    /// `vat_<16hex>` over the canonical content preimage.
291    pub fn derive_id(&self) -> Result<String, String> {
292        let bytes = self.id_preimage_bytes()?;
293        Ok(format!(
294            "vat_{}",
295            &hex::encode(Sha256::digest(&bytes))[..16]
296        ))
297    }
298
299    /// Build the canonical `attempt.deposited` event that persists this
300    /// signed deposit to the frontier event log. The full object travels in
301    /// `payload.attempt`; the reducer verifies and upserts it.
302    #[must_use]
303    pub fn deposit_event(
304        &self,
305        actor_id: &str,
306        actor_type: &str,
307        reason: &str,
308    ) -> crate::events::StateEvent {
309        let payload =
310            serde_json::json!({ "attempt": serde_json::to_value(self).unwrap_or_default() });
311        crate::events::new_attempt_deposited_event(
312            &self.attempt_id,
313            actor_id,
314            actor_type,
315            reason,
316            payload,
317            vec![
318                "A signed banked attempt. Trust is earned via its verifier_attachments + the gate, never from claimed_status."
319                    .to_string(),
320            ],
321        )
322    }
323
324    /// Verify: re-derive the id, verify the signature over the content
325    /// preimage under the declared pubkey, and check `claim_digest` matches
326    /// the claim. Any hand-edit to the body fails here.
327    pub fn verify(&self) -> Result<(), String> {
328        if self.schema != ATTEMPT_SCHEMA {
329            return Err(format!(
330                "attempt.schema must be `{ATTEMPT_SCHEMA}`, got `{}`",
331                self.schema
332            ));
333        }
334        if !self.attempt_id.starts_with("vat_") {
335            return Err(format!(
336                "attempt id must start with `vat_`, got `{}`",
337                self.attempt_id
338            ));
339        }
340        if self.claim_digest != claim_digest(&self.claim) {
341            return Err("attempt.claim_digest does not match claim".to_string());
342        }
343        let preimage = self.id_preimage_bytes()?;
344        if !crate::sign::verify_action_signature(
345            &preimage,
346            &self.signature,
347            &self.signer_pubkey_hex,
348        )? {
349            return Err("attempt signature does not verify under the declared pubkey".to_string());
350        }
351        let rederived = self.derive_id()?;
352        if rederived != self.attempt_id {
353            return Err(format!(
354                "attempt_id mismatch: declared {}, rebuilt {}",
355                self.attempt_id, rederived
356            ));
357        }
358        Ok(())
359    }
360}
361
362/// The terminal outcome a ResolutionEvent records. `verified` carries the
363/// gate reference rather than a stored boolean; `refuted` names the probe;
364/// `superseded`/`redundant_with_literature` carry the pointer.
365#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
366#[serde(tag = "outcome", rename_all = "snake_case")]
367pub enum AttemptResolution {
368    /// The gate derived `verified` from the attached `vva_` evidence. The
369    /// `gate_ref` cites the evaluation; the boolean is never stored.
370    Verified { gate_ref: String },
371    /// An adversarial probe refuted the claim. `by_probe` names it.
372    Refuted { by_probe: String },
373    /// A later attempt supersedes this one (corrected statement / better
374    /// bound). `by` is the superseding `vat_` id.
375    Superseded { by: String },
376    /// Found to duplicate prior literature. `refs` are the citations.
377    RedundantWithLiterature { refs: Vec<String> },
378}
379
380impl AttemptResolution {
381    #[must_use]
382    pub fn as_str(&self) -> &'static str {
383        match self {
384            Self::Verified { .. } => "verified",
385            Self::Refuted { .. } => "refuted",
386            Self::Superseded { .. } => "superseded",
387            Self::RedundantWithLiterature { .. } => "redundant_with_literature",
388        }
389    }
390}
391
392/// An append-only lifecycle transition on an [`Attempt`]. Content-addressed
393/// (`vre_`); authenticity comes from the signed `attempt.resolved`
394/// [`crate::events::StateEvent`] it travels in (mirrors how a Contradiction's
395/// resolution is carried by a signed event, not self-signed).
396#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
397pub struct ResolutionEvent {
398    pub schema: String,
399    /// `vre_<16hex>` over `attempt_id | resolution | actor | at`.
400    pub resolution_id: String,
401    /// The `vat_` this resolves.
402    pub attempt_id: String,
403    pub resolution: AttemptResolution,
404    /// The named actor rendering the judgment (`reviewer:` / `agent:`).
405    pub actor: String,
406    /// ISO-8601 valid time of the transition.
407    pub at: String,
408    #[serde(default, skip_serializing_if = "String::is_empty")]
409    pub note: String,
410}
411
412impl ResolutionEvent {
413    /// Build a resolution event, deriving its content-addressed id.
414    pub fn new(
415        attempt_id: &str,
416        resolution: AttemptResolution,
417        actor: &str,
418        at: &str,
419        note: &str,
420    ) -> Result<Self, String> {
421        if !attempt_id.starts_with("vat_") {
422            return Err(format!(
423                "resolution target must be a `vat_` id, got `{attempt_id}`"
424            ));
425        }
426        if actor.trim().is_empty() {
427            return Err("resolution actor cannot be empty".to_string());
428        }
429        let mut ev = ResolutionEvent {
430            schema: RESOLUTION_EVENT_SCHEMA.to_string(),
431            resolution_id: String::new(),
432            attempt_id: attempt_id.to_string(),
433            resolution,
434            actor: actor.to_string(),
435            at: at.to_string(),
436            note: note.to_string(),
437        };
438        ev.resolution_id = ev.derive_id()?;
439        Ok(ev)
440    }
441
442    /// `vre_<16hex>` over the canonical body with the id zeroed.
443    pub fn derive_id(&self) -> Result<String, String> {
444        let mut preimage = self.clone();
445        preimage.resolution_id = String::new();
446        let bytes = crate::canonical::to_canonical_bytes(&preimage)
447            .map_err(|e| format!("canonicalize resolution preimage: {e}"))?;
448        Ok(format!(
449            "vre_{}",
450            &hex::encode(Sha256::digest(&bytes))[..16]
451        ))
452    }
453
454    /// Build the canonical `attempt.resolved` event carrying this transition.
455    /// Authenticity comes from the signed event log; the object travels in
456    /// `payload.resolution`.
457    #[must_use]
458    pub fn to_state_event(&self, actor_type: &str, reason: &str) -> crate::events::StateEvent {
459        let payload =
460            serde_json::json!({ "resolution": serde_json::to_value(self).unwrap_or_default() });
461        crate::events::new_attempt_resolved_event(
462            &self.attempt_id,
463            &self.actor,
464            actor_type,
465            reason,
466            payload,
467            vec![],
468        )
469    }
470
471    /// Structural validity: schema, id prefix, id integrity.
472    pub fn verify(&self) -> Result<(), String> {
473        if self.schema != RESOLUTION_EVENT_SCHEMA {
474            return Err(format!(
475                "resolution.schema must be `{RESOLUTION_EVENT_SCHEMA}`, got `{}`",
476                self.schema
477            ));
478        }
479        if !self.resolution_id.starts_with("vre_") {
480            return Err(format!(
481                "resolution id must start with `vre_`, got `{}`",
482                self.resolution_id
483            ));
484        }
485        let derived = self.derive_id()?;
486        if derived != self.resolution_id {
487            return Err(format!(
488                "resolution id mismatch: stored {}, derived {}",
489                self.resolution_id, derived
490            ));
491        }
492        Ok(())
493    }
494}
495
496#[cfg(test)]
497mod tests {
498    use super::*;
499    use rand::rngs::OsRng;
500
501    fn key() -> SigningKey {
502        SigningKey::generate(&mut OsRng)
503    }
504
505    fn ok_draft() -> AttemptDraft {
506        AttemptDraft {
507            problem: 309,
508            frontier: "sidon-a309370".to_string(),
509            kind: "lower_bound".into(),
510            claim: "a(8) >= 33".to_string(),
511            detail: "witness of 33 binary vectors, pairwise sums distinct".to_string(),
512            claimed_status: "verified_computationally".to_string(),
513            reproduction: Reproduction {
514                successes: 3,
515                total: 3,
516            },
517            cost: AttemptCost {
518                total_attempts: 1200,
519                failed_attempts: 1199,
520                compute_note: "CP-SAT, 8 cores".to_string(),
521            },
522            insight: "binary alphabet keeps sums in {0,1,2}".to_string(),
523            depends_on: vec![],
524            related_problems: vec![773],
525            reusable_for: "any B2 set over {0,1}^n".to_string(),
526            verifier_attachments: vec!["vva_0123456789abcdef".to_string()],
527            deliverable_grade: Some("improved_published_bound".to_string()),
528            provenance: Provenance {
529                proposer: "Opus 4.8".to_string(),
530                run: "wf_demo".to_string(),
531                date: "2026-06-09".to_string(),
532            },
533            ..Default::default()
534        }
535    }
536
537    #[test]
538    fn packet_fields_round_trip_and_legacy_id_is_stable() {
539        // A packet-bearing attempt carries the v0.700 fields, round-trips through
540        // canonical JSON, and re-verifies; the producer/root/obstruction fields
541        // are part of the content address (a tampered root breaks the id).
542        let mut d = ok_draft();
543        d.base_frontier_root = "sha256:deadbeef".into();
544        d.target_obligation_id = "sidon:a309370:n8".into();
545        d.method_families = vec!["cp-sat".into(), "randomized-restart".into()];
546        d.remaining_obligations = vec!["sidon:a309370:n9".into()];
547        d.named_obstructions = vec!["search-does-not-scale:greedy".into()];
548        d.producer = ProducerRef {
549            system: "claude".into(),
550            version: "opus-4-8".into(),
551            config_digest: "sha256:cfg".into(),
552        };
553        let a = Attempt::build(d, &key()).unwrap();
554        a.verify().unwrap();
555        let round: Attempt = serde_json::from_str(&serde_json::to_string(&a).unwrap()).unwrap();
556        assert_eq!(round, a);
557        round.verify().unwrap();
558        assert_eq!(round.producer.system, "claude");
559        assert_eq!(round.base_frontier_root, "sha256:deadbeef");
560        // A legacy attempt (no packet fields) keeps a distinct, stable id.
561        let legacy = Attempt::build(ok_draft(), &key()).unwrap();
562        assert_ne!(legacy.attempt_id, a.attempt_id);
563    }
564
565    #[test]
566    fn domain_general_attempt_omits_problem_and_round_trips() {
567        // A foundry attempt against a non-Erdős frontier (sidon/diff_triangle)
568        // carries problem == 0: it builds, the canonical body OMITS the problem
569        // field (skip-guarded), and it content-addresses + re-verifies. A
570        // problem-numbered attempt with the SAME other fields gets a distinct id
571        // (problem is part of the content address), so legacy ids never move.
572        let d = AttemptDraft {
573            problem: 0,
574            frontier: "diff-triangle".to_string(),
575            kind: "diff_triangle".into(),
576            claim: "DTS(7,5) scope 231".to_string(),
577            ..Default::default()
578        };
579        let a = Attempt::build(d, &key()).unwrap();
580        a.verify().unwrap();
581        let json = serde_json::to_string(&a).unwrap();
582        assert!(
583            !json.contains("\"problem\""),
584            "problem must be omitted when 0"
585        );
586        let round: Attempt = serde_json::from_str(&json).unwrap();
587        assert_eq!(round, a);
588        assert_eq!(round.problem, 0);
589        round.verify().unwrap();
590        // problem == 0 with no frontier is still rejected (unattributable).
591        let bad = AttemptDraft {
592            problem: 0,
593            kind: "diff_triangle".into(),
594            claim: "x".into(),
595            ..Default::default()
596        };
597        assert!(Attempt::build(bad, &key()).is_err());
598    }
599
600    #[test]
601    fn builds_signs_and_verifies() {
602        let a = Attempt::build(ok_draft(), &key()).unwrap();
603        assert!(a.attempt_id.starts_with("vat_"));
604        assert_eq!(a.claim_digest, claim_digest("a(8) >= 33"));
605        a.verify().unwrap();
606    }
607
608    #[test]
609    fn tampered_body_breaks_id_and_signature() {
610        let mut a = Attempt::build(ok_draft(), &key()).unwrap();
611        // Hand-edit a banked attempt: the claim no longer matches the digest,
612        // the id no longer re-derives, and the signature no longer verifies.
613        a.claim = "a(8) >= 99".to_string();
614        assert!(a.verify().is_err());
615    }
616
617    #[test]
618    fn id_is_key_independent_content_address() {
619        // The same body signed by two DIFFERENT keys yields the SAME vat_ id
620        // (the id is a content address; the signer is recorded separately).
621        let a1 = Attempt::build(ok_draft(), &key()).unwrap();
622        let a2 = Attempt::build(ok_draft(), &key()).unwrap();
623        assert_eq!(a1.attempt_id, a2.attempt_id);
624        assert_ne!(a1.signature, a2.signature);
625        assert_ne!(a1.signer_pubkey_hex, a2.signer_pubkey_hex);
626    }
627
628    #[test]
629    fn cross_impl_pinned_id() {
630        // Pinned vat_ id for fixed inputs under the all-zeros key. The Python
631        // ledger's canonical-JSON derivation must reproduce this byte-for-byte
632        // (conformance/attempt-id.json + verify_attempt_id.py).
633        let key = SigningKey::from_bytes(&[0u8; 32]);
634        let draft = AttemptDraft {
635            problem: 1,
636            frontier: "f".to_string(),
637            kind: "k".into(),
638            claim: "c".to_string(),
639            ..Default::default()
640        };
641        let a = Attempt::build(draft, &key).unwrap();
642        // Pinned id, reproduced byte-for-byte by `conformance/verify_attempt_id.py`
643        // from the same canonical body. Cross-impl drift flags here.
644        assert_eq!(a.attempt_id, "vat_0008df5d18b5bdea");
645        assert_eq!(a.claim_digest, "2e7d2c03a9507ae2");
646    }
647
648    #[test]
649    fn rejects_impossible_reproduction_and_cost() {
650        let mut d = ok_draft();
651        d.reproduction = Reproduction {
652            successes: 5,
653            total: 3,
654        };
655        assert!(Attempt::build(d, &key()).is_err());
656        let mut d2 = ok_draft();
657        d2.cost = AttemptCost {
658            total_attempts: 2,
659            failed_attempts: 9,
660            compute_note: String::new(),
661        };
662        assert!(Attempt::build(d2, &key()).is_err());
663    }
664
665    #[test]
666    fn resolution_event_is_content_addressed() {
667        let a = Attempt::build(ok_draft(), &key()).unwrap();
668        let ev = ResolutionEvent::new(
669            &a.attempt_id,
670            AttemptResolution::Verified {
671                gate_ref: "gate@vva_0123456789abcdef".to_string(),
672            },
673            "reviewer:will-blair",
674            "2026-06-09T00:00:00Z",
675            "two independent methods + surviving probe",
676        )
677        .unwrap();
678        assert!(ev.resolution_id.starts_with("vre_"));
679        assert_eq!(ev.resolution.as_str(), "verified");
680        ev.verify().unwrap();
681    }
682
683    #[test]
684    fn resolution_rejects_non_vat_target() {
685        let r = ResolutionEvent::new(
686            "vf_not_an_attempt",
687            AttemptResolution::Refuted {
688                by_probe: "case_b".to_string(),
689            },
690            "reviewer:x",
691            "2026-06-09T00:00:00Z",
692            "",
693        );
694        assert!(r.is_err());
695    }
696
697    #[test]
698    fn json_roundtrip() {
699        let a = Attempt::build(ok_draft(), &key()).unwrap();
700        let s = serde_json::to_string(&a).unwrap();
701        let back: Attempt = serde_json::from_str(&s).unwrap();
702        assert_eq!(a, back);
703        back.verify().unwrap();
704    }
705}