1use 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
40pub struct Reproduction {
41 pub successes: u64,
42 pub total: u64,
43}
44
45#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
49pub struct AttemptCost {
50 pub total_attempts: u64,
52 pub failed_attempts: u64,
54 #[serde(default, skip_serializing_if = "String::is_empty")]
56 pub compute_note: String,
57}
58
59#[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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91pub struct Attempt {
92 pub schema: String,
93 pub attempt_id: String,
97 #[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 #[serde(default, skip_serializing_if = "String::is_empty")]
113 pub claimed_status: String,
114 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 #[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 #[serde(default, skip_serializing_if = "Vec::is_empty")]
132 pub verifier_attachments: Vec<String>,
133 #[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 #[serde(default, skip_serializing_if = "String::is_empty")]
146 pub base_frontier_root: String,
147 #[serde(default, skip_serializing_if = "String::is_empty")]
150 pub target_obligation_id: String,
151 #[serde(default, skip_serializing_if = "String::is_empty")]
153 pub statement_variant_id: String,
154 #[serde(default, skip_serializing_if = "Vec::is_empty")]
156 pub method_families: Vec<String>,
157 #[serde(default, skip_serializing_if = "Vec::is_empty")]
159 pub remaining_obligations: Vec<String>,
160 #[serde(default, skip_serializing_if = "Vec::is_empty")]
163 pub named_obstructions: Vec<String>,
164 #[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#[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 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
213pub use crate::verifier_attachment::claim_digest;
217
218impl Attempt {
219 pub fn build(draft: AttemptDraft, key: &SigningKey) -> Result<Self, String> {
222 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 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 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 #[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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
366#[serde(tag = "outcome", rename_all = "snake_case")]
367pub enum AttemptResolution {
368 Verified { gate_ref: String },
371 Refuted { by_probe: String },
373 Superseded { by: String },
376 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
397pub struct ResolutionEvent {
398 pub schema: String,
399 pub resolution_id: String,
401 pub attempt_id: String,
403 pub resolution: AttemptResolution,
404 pub actor: String,
406 pub at: String,
408 #[serde(default, skip_serializing_if = "String::is_empty")]
409 pub note: String,
410}
411
412impl ResolutionEvent {
413 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 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 #[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 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 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 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 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 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 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 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 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 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}