snapshot.rs (33009B)
1 //! Coherent retained graph reports. Values are not persistence qualification or 2 //! dispatch permission; concrete owners must authenticate and compare all facts. 3 use super::{ 4 BoundSigningPlan, ChatInstallation, DeliveryAttemptSummary, DeliveryObservation, 5 EvidenceReceipt, ListingInstallation, OperationError, PreparedOperation, PublicPublicationWork, 6 PublicationArtifact, PublicationWork, SigningAttempt, 7 }; 8 use core::fmt; 9 use radroots_domain::{ 10 ChatMessage, ChatRelation, CommandDigest, EnvelopeEventId, MessageId, OperationId, PublicKey, 11 SigningAttemptId, TransactionId, UnixSeconds, WorkspaceId, 12 }; 13 use radroots_protocol::{intent::IntentBinding, plan::SigningTarget}; 14 use sha2::{Digest, Sha256}; 15 use std::{ 16 boxed::Box, 17 collections::{BTreeMap, BTreeSet}, 18 vec, 19 vec::Vec, 20 }; 21 22 /// Fixed original claim facts, without another copy of its complete plan. 23 #[derive(Clone, Copy, Eq, PartialEq)] 24 pub struct ClaimSnapshot { 25 workspace: WorkspaceId, 26 operation: OperationId, 27 command: CommandDigest, 28 plan: [u8; 32], 29 target: SigningTarget, 30 attempt: SigningAttemptId, 31 transaction: TransactionId, 32 claimed_at: UnixSeconds, 33 event: EnvelopeEventId, 34 intent: IntentBinding, 35 } 36 impl ClaimSnapshot { 37 /// Copies a structural store report; no backend claim or nonissuance proof 38 /// is created by this conversion. 39 pub fn from_store_report(attempt: &SigningAttempt) -> Result<Self, OperationError> { 40 let identity = attempt.bound_plan().prepared().identity(); 41 Ok(Self { 42 workspace: identity.workspace_id(), 43 operation: identity.operation_id(), 44 command: identity.command_digest(), 45 plan: *attempt.bound_plan().plan().digest(), 46 target: attempt.target(), 47 attempt: attempt.attempt_id(), 48 transaction: attempt.transaction_id(), 49 claimed_at: attempt.claimed_at(), 50 event: EnvelopeEventId::from_bytes(attempt.artifact()?.event_id()), 51 intent: attempt.binding(), 52 }) 53 } 54 /// Original workspace identity. 55 pub const fn workspace_id(self) -> WorkspaceId { 56 self.workspace 57 } 58 /// Original operation identity. 59 pub const fn operation_id(self) -> OperationId { 60 self.operation 61 } 62 /// Original semantic command commitment. 63 pub const fn command_digest(self) -> CommandDigest { 64 self.command 65 } 66 /// Original complete plan commitment. 67 pub const fn plan_digest(&self) -> &[u8; 32] { 68 &self.plan 69 } 70 /// Exact intended recipient. 71 pub const fn target(self) -> SigningTarget { 72 self.target 73 } 74 pub fn recipient(self) -> Result<PublicKey, OperationError> { 75 self.target 76 .recipient() 77 .ok_or(OperationError::UnsupportedOperation) 78 } 79 /// Full-width retained attempt identity. 80 pub const fn attempt_id(self) -> SigningAttemptId { 81 self.attempt 82 } 83 /// Original claim transaction. 84 pub const fn transaction_id(self) -> TransactionId { 85 self.transaction 86 } 87 /// Original claim observation, never a fresh deadline. 88 pub const fn claimed_at(self) -> UnixSeconds { 89 self.claimed_at 90 } 91 /// Expected exact signed seal ID, not a logical record identity. 92 pub const fn event_id(self) -> EnvelopeEventId { 93 self.event 94 } 95 /// Exact original intent commitment. 96 pub const fn intent(self) -> IntentBinding { 97 self.intent 98 } 99 } 100 impl fmt::Debug for ClaimSnapshot { 101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 102 f.write_str("ClaimSnapshot(<redacted>)") 103 } 104 } 105 106 /// One exact artifact's independent retained facts. Absence of obtained 107 /// evidence for a retained claim never establishes safe reissue. 108 #[derive(Clone, Copy, Eq, PartialEq)] 109 pub struct ArtifactSnapshot { 110 target: SigningTarget, 111 expected_event: Option<EnvelopeEventId>, 112 claim: Option<ClaimSnapshot>, 113 obtained: Option<EvidenceReceipt>, 114 } 115 impl ArtifactSnapshot { 116 /// Structural report; the complete snapshot constructor checks its scope. 117 pub fn from_store_report( 118 target: impl Into<SigningTarget>, 119 expected_event: Option<EnvelopeEventId>, 120 claim: Option<ClaimSnapshot>, 121 obtained: Option<EvidenceReceipt>, 122 ) -> Self { 123 Self { 124 target: target.into(), 125 expected_event, 126 claim, 127 obtained, 128 } 129 } 130 /// Exact expected recipient. 131 pub const fn target(self) -> SigningTarget { 132 self.target 133 } 134 pub fn recipient(self) -> Result<PublicKey, OperationError> { 135 self.target 136 .recipient() 137 .ok_or(OperationError::UnsupportedOperation) 138 } 139 /// Expected retained seal ID, when a complete plan exists. 140 pub const fn expected_event(self) -> Option<EnvelopeEventId> { 141 self.expected_event 142 } 143 /// Original potential invocation; not permission to invoke again. 144 pub const fn claim(self) -> Option<ClaimSnapshot> { 145 self.claim 146 } 147 /// Original protected obtained-artifact reference and optional observation. 148 pub const fn obtained(self) -> Option<EvidenceReceipt> { 149 self.obtained 150 } 151 } 152 impl fmt::Debug for ArtifactSnapshot { 153 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 154 f.write_str("ArtifactSnapshot(<redacted>)") 155 } 156 } 157 158 /// One owned preparation and at most one complete plan, shared by all recipient 159 /// reports without duplicating protected private plan data per recipient. 160 pub enum RetainedOperation { 161 /// Confirmed preparation without a bound complete plan. 162 Prepared(PreparedOperation), 163 /// Confirmed preparation and complete immutable plan. 164 Planned(Box<BoundSigningPlan>), 165 } 166 impl RetainedOperation { 167 /// Borrows original committed preparation. 168 pub fn prepared(&self) -> &PreparedOperation { 169 match self { 170 Self::Prepared(value) => value, 171 Self::Planned(value) => value.prepared(), 172 } 173 } 174 /// Borrows the complete plan, if retained. 175 pub fn bound_plan(&self) -> Option<&BoundSigningPlan> { 176 match self { 177 Self::Prepared(_) => None, 178 Self::Planned(value) => Some(value), 179 } 180 } 181 } 182 impl fmt::Debug for RetainedOperation { 183 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 184 f.write_str("RetainedOperation(<redacted>)") 185 } 186 } 187 188 /// Bounded coherent T0/T1/S graph report. Construction checks data relationships 189 /// only. It grants no authentication, backend qualification or installation fact. 190 pub struct OperationSnapshot { 191 retained: RetainedOperation, 192 artifacts: Box<[ArtifactSnapshot]>, 193 observed_at: UnixSeconds, 194 installation: Option<ChatInstallation>, 195 message: Option<ChatMessage>, 196 publications: Box<[PublicationWork]>, 197 listing_installation: Option<ListingInstallation>, 198 public_publications: Box<[PublicPublicationWork]>, 199 deliveries: Box<[DeliveryAttemptSummary]>, 200 observations: Box<[DeliveryObservation]>, 201 } 202 impl OperationSnapshot { 203 /// Stable scoped progress identity over original transaction, command, 204 /// plan, claim and obtained references. Query time and diagnostic correlation 205 /// are excluded. Hashing grants no backend authority. 206 pub fn checkpoint_digest(&self) -> radroots_domain::CheckpointDigest { 207 let prepared = self.prepared(); 208 let identity = prepared.identity(); 209 let mut digest = Sha256::new(); 210 digest.update(b"radroots.operation.snapshot.v3\0"); 211 digest.update(identity.workspace_id().as_bytes()); 212 digest.update(identity.operation_id().as_bytes()); 213 digest.update(identity.command_digest().as_bytes()); 214 digest.update(prepared.transaction_id().as_bytes()); 215 digest.update(prepared.revision().get().to_be_bytes()); 216 digest.update(prepared.issuance_window().prepared_at().get().to_be_bytes()); 217 digest.update( 218 prepared 219 .issuance_window() 220 .first_issue_not_after() 221 .get() 222 .to_be_bytes(), 223 ); 224 digest.update( 225 prepared 226 .request() 227 .binding() 228 .input() 229 .checkpoint() 230 .digest() 231 .as_bytes(), 232 ); 233 match self.bound_plan() { 234 Some(bound) => { 235 digest.update([1]); 236 digest.update(bound.plan().digest()); 237 digest.update(bound.transaction_id().as_bytes()); 238 digest.update(bound.bound_at().get().to_be_bytes()); 239 } 240 None => digest.update([0]), 241 } 242 for recipient in self.artifacts() { 243 digest.update(recipient.target().key()); 244 match recipient.claim() { 245 Some(claim) => { 246 digest.update([1]); 247 digest.update(claim.attempt_id().as_bytes()); 248 digest.update(claim.transaction_id().as_bytes()); 249 digest.update(claim.intent().digest()); 250 digest.update(claim.claimed_at().get().to_be_bytes()); 251 } 252 None => digest.update([0]), 253 } 254 match recipient.obtained() { 255 Some(obtained) => { 256 digest.update([1]); 257 digest.update(obtained.transaction_id().as_bytes()); 258 digest.update(obtained.event_id().as_bytes()); 259 digest.update(obtained.digest()); 260 match obtained.observed_at_unix_ms() { 261 Some(time) => { 262 digest.update([1]); 263 digest.update(time.get().to_be_bytes()); 264 } 265 None => digest.update([0]), 266 } 267 } 268 None => digest.update([0]), 269 } 270 } 271 match self.installation() { 272 Some(installed) => { 273 digest.update([1]); 274 digest.update(installed.transaction_id().as_bytes()); 275 digest.update(installed.installed_at().get().to_be_bytes()); 276 digest.update(installed.basis().transaction_id().as_bytes()); 277 } 278 None => digest.update([0]), 279 } 280 for work in self.publications() { 281 digest.update(work.evidence().target().key()); 282 digest.update(work.transaction_id().as_bytes()); 283 digest.update(work.queued_at().get().to_be_bytes()); 284 } 285 if let Some(installed) = self.listing_installation() { 286 // Preserve original private checkpoint bytes exactly. The public 287 // extension binds actual installation/work, never a message ID. 288 digest.update(b"radroots.operation.public_installation.v1\0"); 289 digest.update(installed.author().as_bytes()); 290 digest.update(installed.listing_id().as_bytes()); 291 digest.update(installed.revision().as_bytes()); 292 digest.update(installed.transaction_id().as_bytes()); 293 digest.update(installed.installed_at().get().to_be_bytes()); 294 for work in self.public_publications() { 295 digest.update(work.transaction_id().as_bytes()); 296 digest.update(work.queued_at().get().to_be_bytes()); 297 } 298 } 299 for attempt in self.delivery_attempts() { 300 digest.update(attempt.work().evidence().target().key()); 301 digest.update(attempt.intent().digest()); 302 digest.update(attempt.envelope_digest()); 303 digest.update(attempt.transaction_id().as_bytes()); 304 digest.update(attempt.retained_at().get().to_be_bytes()); 305 digest.update(attempt.target_ordinals()); 306 } 307 for observation in self.delivery_observations() { 308 digest.update(observation.work().evidence().target().key()); 309 digest.update(observation.request_id().as_str().as_bytes()); 310 digest.update(observation.event_id().as_bytes()); 311 digest.update(observation.envelope_digest()); 312 digest.update( 313 observation 314 .target_receipt() 315 .target() 316 .fingerprint() 317 .as_str() 318 .as_bytes(), 319 ); 320 digest.update([observation.kind().code()]); 321 digest.update([ 322 observation.target_ordinal(), 323 u8::from(observation.target_receipt().was_attempted()), 324 ]); 325 let outcome = observation.target_receipt().outcome(); 326 digest.update([match outcome.kind() { 327 radroots_transport::outcome::DeliveryOutcomeKind::Accepted => 0, 328 radroots_transport::outcome::DeliveryOutcomeKind::Delivered => 1, 329 radroots_transport::outcome::DeliveryOutcomeKind::Rejected => 2, 330 radroots_transport::outcome::DeliveryOutcomeKind::Unavailable => 3, 331 radroots_transport::outcome::DeliveryOutcomeKind::Failed => 4, 332 }]); 333 digest.update([match outcome.retryability() { 334 radroots_transport::outcome::Retryability::NotApplicable => 0, 335 radroots_transport::outcome::Retryability::Retryable => 1, 336 radroots_transport::outcome::Retryability::Terminal => 2, 337 }]); 338 for value in [outcome.code(), outcome.message()] { 339 match value { 340 Some(value) => { 341 digest.update([1]); 342 digest.update((value.len() as u32).to_be_bytes()); 343 digest.update(value.as_bytes()); 344 } 345 None => digest.update([0]), 346 } 347 } 348 match observation.observed_at_unix_ms() { 349 Some(time) => { 350 digest.update([1]); 351 digest.update(time.get().to_be_bytes()); 352 } 353 None => digest.update([0]), 354 } 355 } 356 radroots_domain::CheckpointDigest::from_bytes(digest.finalize().into()) 357 } 358 /// Checks the exact complete artifact set, original claim scope and obtained 359 /// references. Concrete adapters must independently authenticate all rows and 360 /// compare both retained and absent facts in one coherent transaction. 361 pub fn from_store_report( 362 retained: RetainedOperation, 363 artifacts: Vec<ArtifactSnapshot>, 364 observed_at: UnixSeconds, 365 ) -> Result<Self, OperationError> { 366 if artifacts.is_empty() || artifacts.len() > 2 || observed_at.get() == 0 { 367 return Err(OperationError::RecoveryRequired); 368 } 369 let prepared = retained.prepared(); 370 let mut expected = match prepared.request().command().chat() { 371 Some(command) => vec![ 372 SigningTarget::BusinessSeal(command.context().actor().participant()), 373 SigningTarget::BusinessSeal(command.peer()), 374 ], 375 None => vec![SigningTarget::PublicEvent], 376 }; 377 expected.sort_unstable_by_key(|target| target.key()); 378 expected.dedup(); 379 if artifacts.len() != expected.len() { 380 return Err(OperationError::RecoveryRequired); 381 } 382 for (recipient, expected) in artifacts.iter().zip(expected) { 383 if recipient.target != expected { 384 return Err(OperationError::RecoveryRequired); 385 } 386 let Some(bound) = retained.bound_plan() else { 387 if recipient.expected_event.is_some() 388 || recipient.claim.is_some() 389 || recipient.obtained.is_some() 390 { 391 return Err(OperationError::RecoveryRequired); 392 } 393 continue; 394 }; 395 let artifact = bound 396 .plan() 397 .artifact(expected) 398 .map_err(|_| OperationError::RecoveryRequired)?; 399 let event = EnvelopeEventId::from_bytes(artifact.event_id()); 400 if recipient.expected_event != Some(event) { 401 return Err(OperationError::RecoveryRequired); 402 } 403 if let Some(claim) = recipient.claim { 404 let identity = prepared.identity(); 405 if claim.workspace != identity.workspace_id() 406 || claim.operation != identity.operation_id() 407 || claim.command != identity.command_digest() 408 || &claim.plan != bound.plan().digest() 409 || claim.target != expected 410 || claim.event != event 411 || claim.intent.operation_id() != identity.operation_id() 412 || claim.intent.command_digest() != identity.command_digest().as_bytes() 413 || claim.claimed_at < bound.bound_at() 414 || claim.claimed_at >= prepared.issuance_window().first_issue_not_after() 415 { 416 return Err(OperationError::RecoveryRequired); 417 } 418 if let Some(obtained) = recipient.obtained 419 && (obtained.workspace_id() != claim.workspace 420 || obtained.operation_id() != claim.operation 421 || obtained.command_digest() != claim.command 422 || obtained.attempt_id() != claim.attempt 423 || obtained.target() != expected 424 || obtained.event_id() != event) 425 { 426 return Err(OperationError::RecoveryRequired); 427 } 428 } else if recipient.obtained.is_some() { 429 return Err(OperationError::RecoveryRequired); 430 } 431 } 432 Ok(Self { 433 retained, 434 artifacts: artifacts.into_boxed_slice(), 435 observed_at, 436 installation: None, 437 message: None, 438 publications: Vec::new().into_boxed_slice(), 439 listing_installation: None, 440 public_publications: Vec::new().into_boxed_slice(), 441 deliveries: Vec::new().into_boxed_slice(), 442 observations: Vec::new().into_boxed_slice(), 443 }) 444 } 445 /// Adds structurally checked T2 reports to this data snapshot. The concrete 446 /// owner must authenticate and atomically compare these records with the 447 /// complete original graph. This transformation performs no installation. 448 pub fn with_installation( 449 mut self, 450 installation: Option<ChatInstallation>, 451 publications: Vec<PublicationWork>, 452 ) -> Result<Self, OperationError> { 453 if self.listing_installation.is_some() 454 || !self.public_publications.is_empty() 455 || !self.deliveries.is_empty() 456 || !self.observations.is_empty() 457 { 458 return Err(OperationError::RecoveryRequired); 459 } 460 let Some(installed) = installation else { 461 if !publications.is_empty() { 462 return Err(OperationError::RecoveryRequired); 463 } 464 self.installation = None; 465 self.message = None; 466 self.publications = Vec::new().into_boxed_slice(); 467 return Ok(self); 468 }; 469 let bound = self.bound_plan().ok_or(OperationError::RecoveryRequired)?; 470 let checked = ChatInstallation::from_committed_store( 471 bound, 472 installed.basis(), 473 installed.transaction_id(), 474 installed.installed_at(), 475 )?; 476 if checked != installed 477 || !self 478 .artifacts() 479 .iter() 480 .any(|recipient| recipient.obtained() == Some(installed.basis())) 481 || publications.is_empty() 482 || publications.len() > self.artifacts().len() 483 { 484 return Err(OperationError::RecoveryRequired); 485 } 486 let mut previous = None; 487 let mut basis_linked = false; 488 for work in &publications { 489 let recipient = work.recipient(); 490 if previous.is_some_and(|key| key >= recipient) 491 || PublicationWork::from_committed_store( 492 bound, 493 installed, 494 work.evidence(), 495 work.transaction_id(), 496 work.queued_at(), 497 )? != *work 498 || !self 499 .artifacts() 500 .iter() 501 .any(|value| value.obtained() == Some(work.evidence())) 502 { 503 return Err(OperationError::RecoveryRequired); 504 } 505 previous = Some(recipient); 506 basis_linked |= work.evidence() == installed.basis(); 507 } 508 if !basis_linked { 509 return Err(OperationError::RecoveryRequired); 510 } 511 let command = bound.prepared().request().chat_command()?; 512 let relation = match command.parent() { 513 Some(parent) => ChatRelation::Reply { parent }, 514 None => ChatRelation::Inquire { 515 source: command.source().map(|source| source.event_id()), 516 }, 517 }; 518 let message = ChatMessage::new( 519 installed.message_id(), 520 command.thread_id(), 521 command.context().actor().participant(), 522 command.peer(), 523 bound.plan().created_at(), 524 relation, 525 command.text(), 526 ) 527 .map_err(|_| OperationError::RecoveryRequired)?; 528 self.installation = Some(installed); 529 self.message = Some(message); 530 self.publications = publications.into_boxed_slice(); 531 Ok(self) 532 } 533 /// Adds structurally checked public T2 facts. The concrete store must 534 /// authenticate the creation decision and atomically retain both records. 535 pub fn with_public_installation( 536 mut self, 537 installation: Option<ListingInstallation>, 538 publications: Vec<PublicPublicationWork>, 539 ) -> Result<Self, OperationError> { 540 if !self.deliveries.is_empty() || !self.observations.is_empty() { 541 return Err(OperationError::RecoveryRequired); 542 } 543 let Some(installed) = installation else { 544 if !publications.is_empty() { 545 return Err(OperationError::RecoveryRequired); 546 } 547 self.listing_installation = None; 548 self.public_publications = Vec::new().into_boxed_slice(); 549 return Ok(self); 550 }; 551 if self.installation.is_some() || self.message.is_some() || !self.publications.is_empty() { 552 return Err(OperationError::RecoveryRequired); 553 } 554 let bound = self.bound_plan().ok_or(OperationError::RecoveryRequired)?; 555 if ListingInstallation::from_committed_store( 556 bound, 557 installed.basis(), 558 installed.transaction_id(), 559 installed.installed_at(), 560 )? != installed 561 || self.artifacts().len() != 1 562 || self.artifacts()[0].obtained() != Some(installed.basis()) 563 || publications.len() != 1 564 { 565 return Err(OperationError::RecoveryRequired); 566 } 567 let work = publications[0]; 568 if PublicPublicationWork::from_committed_store( 569 bound, 570 installed, 571 work.evidence(), 572 work.transaction_id(), 573 work.queued_at(), 574 )? != work 575 || work.transaction_id() != installed.transaction_id() 576 || work.queued_at() != installed.installed_at() 577 { 578 return Err(OperationError::RecoveryRequired); 579 } 580 self.listing_installation = Some(installed); 581 self.public_publications = publications.into_boxed_slice(); 582 Ok(self) 583 } 584 /// Actual original listing installation, when retained by the owner. 585 pub const fn listing_installation(&self) -> Option<ListingInstallation> { 586 self.listing_installation 587 } 588 /// Original pending direct-publication references, without wrapping or ACK. 589 pub fn public_publications(&self) -> &[PublicPublicationWork] { 590 &self.public_publications 591 } 592 /// Actual retained installation report, when supplied by the concrete owner. 593 pub const fn installation(&self) -> Option<ChatInstallation> { 594 self.installation 595 } 596 /// Owned bounded logical business result, reconstructed from the original 597 /// protected command and complete plan, never a caller's replacement body. 598 pub fn installed_message(&self) -> Option<&ChatMessage> { 599 self.message.as_ref() 600 } 601 /// Independent retained recipient publication work. No outer envelope or 602 /// relay observation is inferred from these references. 603 pub fn publications(&self) -> &[PublicationWork] { 604 &self.publications 605 } 606 /// Adds bounded original D references and append-only target observations. 607 /// The native owner must authenticate and fence the complete actual graph; 608 /// constructing these values proves neither execution nor permission. 609 pub fn with_delivery( 610 mut self, 611 mut attempts: Vec<DeliveryAttemptSummary>, 612 mut observations: Vec<DeliveryObservation>, 613 ) -> Result<Self, OperationError> { 614 if attempts.len() > 384 || observations.len() > 2304 { 615 return Err(OperationError::RecoveryRequired); 616 } 617 attempts.sort_by(|a, b| { 618 ( 619 a.work().evidence().target().recipient(), 620 a.intent().request_id().as_str(), 621 ) 622 .cmp(&( 623 b.work().evidence().target().recipient(), 624 b.intent().request_id().as_str(), 625 )) 626 }); 627 let mut keys = BTreeSet::new(); 628 let mut transactions = BTreeSet::new(); 629 let mut counters = BTreeMap::<(Option<PublicKey>, &str), BTreeSet<u8>>::new(); 630 let mut slots = 0usize; 631 let mut policies = BTreeMap::new(); 632 for attempt in &attempts { 633 let recipient = attempt.work().recipient(); 634 slots = slots 635 .checked_add(attempt.intent().selection().len()) 636 .filter(|n| *n <= 384) 637 .ok_or(OperationError::RecoveryRequired)?; 638 if !self.contains_publication(attempt.work()) 639 || !keys.insert((recipient, attempt.intent().request_id().as_str())) 640 || !transactions.insert(attempt.transaction_id()) 641 || attempt.target_ordinals().len() != attempt.intent().selection().len() 642 || policies 643 .insert(recipient, *attempt.intent().publication_policy_digest()) 644 .is_some_and(|previous| { 645 previous != *attempt.intent().publication_policy_digest() 646 }) 647 { 648 return Err(OperationError::RecoveryRequired); 649 } 650 for (target, ordinal) in attempt 651 .intent() 652 .selected_targets() 653 .zip(attempt.target_ordinals()) 654 { 655 if !(1..=12).contains(ordinal) 656 || !counters 657 .entry((recipient, target.uri().as_str())) 658 .or_default() 659 .insert(*ordinal) 660 { 661 return Err(OperationError::RecoveryRequired); 662 } 663 } 664 } 665 if counters 666 .values() 667 .any(|values| values.iter().copied().ne(1..=values.len() as u8)) 668 { 669 return Err(OperationError::RecoveryRequired); 670 } 671 observations.sort_by(|a, b| { 672 ( 673 a.work().evidence().target().recipient(), 674 a.request_id().as_str(), 675 a.target_receipt().target().fingerprint().as_str(), 676 a.kind().code(), 677 ) 678 .cmp(&( 679 b.work().evidence().target().recipient(), 680 b.request_id().as_str(), 681 b.target_receipt().target().fingerprint().as_str(), 682 b.kind().code(), 683 )) 684 }); 685 let mut seen = BTreeSet::new(); 686 for observation in &observations { 687 let attempt = attempts 688 .iter() 689 .find(|attempt| { 690 attempt.work() == observation.work() 691 && attempt.intent().request_id() == observation.request_id() 692 }) 693 .ok_or(OperationError::RecoveryRequired)?; 694 let ordinal = attempt 695 .intent() 696 .selection() 697 .iter() 698 .position(|target| target == observation.target_receipt().target().fingerprint()) 699 .and_then(|index| attempt.target_ordinals().get(index)) 700 .copied(); 701 if ordinal != Some(observation.target_ordinal()) { 702 return Err(OperationError::RecoveryRequired); 703 } 704 if observation.event_id() != attempt.intent().event_id() 705 || observation.envelope_digest() != attempt.envelope_digest() 706 || !attempt 707 .intent() 708 .targets() 709 .targets() 710 .contains(observation.target_receipt().target()) 711 || !seen.insert(( 712 observation.work().recipient(), 713 observation.request_id().as_str(), 714 observation.target_receipt().target().fingerprint().as_str(), 715 observation.kind().code(), 716 )) 717 { 718 return Err(OperationError::RecoveryRequired); 719 } 720 } 721 self.deliveries = attempts.into_boxed_slice(); 722 self.observations = observations.into_boxed_slice(); 723 Ok(self) 724 } 725 fn contains_publication(&self, work: PublicationArtifact) -> bool { 726 match work { 727 PublicationArtifact::Private(v) => self.publications.contains(&v), 728 PublicationArtifact::Public(v) => self.public_publications.contains(&v), 729 } 730 } 731 /// Original exact-envelope/target intent references, with no duplicated raw payload. 732 pub fn delivery_attempts(&self) -> &[DeliveryAttemptSummary] { 733 &self.deliveries 734 } 735 /// Individual original per-attempt target facts; absence is never an ACK. 736 pub fn delivery_observations(&self) -> &[DeliveryObservation] { 737 &self.observations 738 } 739 /// Evaluates the original full publication criterion across all exact 740 /// attempts for this work. Retry selection never narrows the criterion; 741 /// an earlier acceptance remains authoritative across later failures. 742 pub fn publication_accepted( 743 &self, 744 work: impl Into<PublicationArtifact>, 745 ) -> Result<bool, OperationError> { 746 let work = work.into(); 747 if !self.contains_publication(work) { 748 return Err(OperationError::InvalidEvidence); 749 } 750 let Some(original) = self 751 .deliveries 752 .iter() 753 .find(|attempt| attempt.work() == work) 754 else { 755 return Ok(false); 756 }; 757 radroots_transport::policy::evaluate_satisfaction( 758 original.intent().policy(), 759 original.intent().targets(), 760 self.observations 761 .iter() 762 .filter(|value| value.work() == work) 763 .map(|value| { 764 ( 765 value.target_receipt().target().fingerprint(), 766 value.target_receipt().outcome(), 767 ) 768 }), 769 ) 770 .map(|state| state == radroots_transport::policy::SatisfactionState::Satisfied) 771 .map_err(|_| OperationError::RecoveryRequired) 772 } 773 /// Original preparation, without a fabricated installed business result. 774 pub fn prepared(&self) -> &PreparedOperation { 775 self.retained.prepared() 776 } 777 /// Complete retained plan, when present. 778 pub fn bound_plan(&self) -> Option<&BoundSigningPlan> { 779 self.retained.bound_plan() 780 } 781 /// Exact original logical message identity, separate from seal event IDs. 782 pub fn message_id(&self) -> Option<MessageId> { 783 self.bound_plan() 784 .and_then(|bound| bound.plan().chat()) 785 .map(|plan| plan.message_id()) 786 } 787 /// Complete sorted unique recipient set and independent outcomes. 788 pub fn artifacts(&self) -> &[ArtifactSnapshot] { 789 &self.artifacts 790 } 791 /// Actual query clock observation; never an issuance restart or global 792 /// freshness guarantee. 793 pub const fn observed_at(&self) -> UnixSeconds { 794 self.observed_at 795 } 796 } 797 impl fmt::Debug for OperationSnapshot { 798 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 799 f.write_str("OperationSnapshot(<redacted>)") 800 } 801 }