commit 225b1774b018b280593076ec46581c846c55a46d parent 56b5405787a104584fb19e16fbaca352d1596dee Author: triesap <tyson@radroots.org> Date: Sun, 18 Oct 2026 06:36:45 +0000 execution: expose coherent native operation receipts - authenticate and compare complete retained operation snapshots - preserve independent issuance, installation and wait observations - own native adapter conformance in the composing facade - verify portable APIs, strict lint and unchanged coverage gates Diffstat:
31 files changed, 2616 insertions(+), 13 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock @@ -3041,6 +3041,7 @@ name = "radroots" version = "0.1.0-alpha" dependencies = [ "futures", + "nostr 0.44.7", "radroots_core", "radroots_domain", "radroots_event", @@ -3048,6 +3049,7 @@ dependencies = [ "radroots_execution", "radroots_identity", "radroots_nostr", + "radroots_protocol", "radroots_sdk", "radroots_secrets", "radroots_signing", @@ -3056,6 +3058,7 @@ dependencies = [ "radroots_trade", "radroots_transport", "serde_json", + "sqlx", "tempfile", "tokio", "toml 0.8.23", @@ -3171,6 +3174,7 @@ dependencies = [ "radroots_event", "radroots_event_codec", "radroots_identity", + "radroots_protocol", "radroots_signing", "radroots_storage", ] diff --git a/contracts/api_baselines/radroots.txt b/contracts/api_baselines/radroots.txt @@ -1,10 +1,19 @@ pub mod radroots +pub use radroots::ArtifactObservation pub use radroots::AttachmentInput pub use radroots::AttachmentProof +pub use radroots::BusinessInstallation pub use radroots::CommandContext +pub use radroots::Delivery +pub use radroots::DeliveryObservation pub use radroots::Error +pub use radroots::Issuance pub use radroots::OperationId +pub use radroots::OperationReceipt +pub use radroots::RecoveryRequirement pub use radroots::Result +pub use radroots::TargetObservation +pub use radroots::WaitTermination pub use radroots::WorkspaceSession pub mod radroots::client #[non_exhaustive] pub enum radroots::client::StartMode diff --git a/contracts/api_baselines/radroots_execution.txt b/contracts/api_baselines/radroots_execution.txt @@ -71,10 +71,16 @@ pub fn radroots_execution::workspace::WorkspaceSession::fmt(&self, &mut core::fm pub radroots_execution::Admission::Confirmed pub radroots_execution::Admission::NotAdmitted pub radroots_execution::Admission::Unknown +#[non_exhaustive] pub enum radroots_execution::BusinessInstallation +pub radroots_execution::BusinessInstallation::Installed +pub radroots_execution::BusinessInstallation::NotApplicable +pub radroots_execution::BusinessInstallation::NotInstalled +pub radroots_execution::BusinessInstallation::Uncertain #[non_exhaustive] pub enum radroots_execution::Code pub radroots_execution::Code::AuthorityConflict pub radroots_execution::Code::CapabilityUnavailable pub radroots_execution::Code::CommitUnknown +pub radroots_execution::Code::DeadlineExceeded pub radroots_execution::Code::Deficit pub radroots_execution::Code::DeliveryPending pub radroots_execution::Code::GrantRevoked @@ -103,6 +109,11 @@ impl radroots_execution::Code pub const radroots_execution::Code::ALL: &'static [Self] pub const fn radroots_execution::Code::as_str(self) -> &'static str pub const fn radroots_execution::Code::message(self) -> &'static str +#[non_exhaustive] pub enum radroots_execution::Delivery +pub radroots_execution::Delivery::NotStarted +pub radroots_execution::Delivery::Observed +pub radroots_execution::Delivery::Pending +pub radroots_execution::Delivery::Unknown #[non_exhaustive] pub enum radroots_execution::Field pub radroots_execution::Field::Approval pub radroots_execution::Field::Authority @@ -131,6 +142,12 @@ pub radroots_execution::InvalidErrorContext::RetainedRetryRequired impl core::error::Error for radroots_execution::InvalidErrorContext impl core::fmt::Display for radroots_execution::InvalidErrorContext pub fn radroots_execution::InvalidErrorContext::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_execution::Issuance +pub radroots_execution::Issuance::None +pub radroots_execution::Issuance::Obtained +pub radroots_execution::Issuance::Pending +pub radroots_execution::Issuance::ProvablyUnissued +pub radroots_execution::Issuance::Unknown #[non_exhaustive] pub enum radroots_execution::Reason pub radroots_execution::Reason::Conflict pub radroots_execution::Reason::InvalidEncoding @@ -144,6 +161,12 @@ pub const radroots_execution::Reason::ALL: &'static [Self] pub const fn radroots_execution::Reason::as_str(self) -> &'static str impl core::fmt::Display for radroots_execution::Reason pub fn radroots_execution::Reason::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_execution::RecoveryRequirement +pub radroots_execution::RecoveryRequirement::ContinueOriginalOperation +pub radroots_execution::RecoveryRequirement::InstallObtainedEvidence +pub radroots_execution::RecoveryRequirement::ManualReconciliation +pub radroots_execution::RecoveryRequirement::ReconcileIssuance +pub radroots_execution::RecoveryRequirement::ResumeDelivery #[non_exhaustive] pub enum radroots_execution::RetryClass pub radroots_execution::RetryClass::AfterStateRefresh pub radroots_execution::RetryClass::ManualReconciliation @@ -151,6 +174,40 @@ pub radroots_execution::RetryClass::Never pub radroots_execution::RetryClass::SafeSameOperation impl radroots_execution::RetryClass pub const fn radroots_execution::RetryClass::as_str(self) -> &'static str +#[non_exhaustive] pub enum radroots_execution::TargetObservation +pub radroots_execution::TargetObservation::Accepted +pub radroots_execution::TargetObservation::Disconnected +pub radroots_execution::TargetObservation::Rejected +pub radroots_execution::TargetObservation::TimedOut +pub radroots_execution::TargetObservation::Unknown +#[non_exhaustive] pub enum radroots_execution::WaitTermination +pub radroots_execution::WaitTermination::Cancelled +pub radroots_execution::WaitTermination::ClientClosed +pub radroots_execution::WaitTermination::DeadlineExceeded +pub radroots_execution::WaitTermination::Returned +pub struct radroots_execution::ArtifactObservation +impl radroots_execution::ArtifactObservation +pub const fn radroots_execution::ArtifactObservation::attempt_id(&self) -> core::option::Option<radroots_domain::identifier::SigningAttemptId> +pub const fn radroots_execution::ArtifactObservation::capture_transaction_id(&self) -> core::option::Option<radroots_domain::identifier::TransactionId> +pub const fn radroots_execution::ArtifactObservation::claim_transaction_id(&self) -> core::option::Option<radroots_domain::identifier::TransactionId> +pub const fn radroots_execution::ArtifactObservation::expected_event(&self) -> core::option::Option<radroots_domain::identifier::EnvelopeEventId> +pub const fn radroots_execution::ArtifactObservation::intent_digest(&self) -> core::option::Option<[u8; 32]> +pub const fn radroots_execution::ArtifactObservation::issuance(&self) -> radroots_execution::Issuance +pub const fn radroots_execution::ArtifactObservation::observed_at_unix_ms(&self) -> core::option::Option<core::num::nonzero::NonZeroU64> +pub const fn radroots_execution::ArtifactObservation::obtained_digest(&self) -> core::option::Option<[u8; 32]> +pub const fn radroots_execution::ArtifactObservation::recipient(&self) -> core::option::Option<radroots_identity::key::PublicKey> +pub const fn radroots_execution::ArtifactObservation::role(&self) -> radroots_protocol::intent::ArtifactRole +impl core::fmt::Debug for radroots_execution::ArtifactObservation +pub fn radroots_execution::ArtifactObservation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_execution::DeliveryObservation +impl radroots_execution::DeliveryObservation +pub const fn radroots_execution::DeliveryObservation::event_id(&self) -> radroots_domain::identifier::EnvelopeEventId +pub const fn radroots_execution::DeliveryObservation::observed_at_unix_ms(&self) -> core::option::Option<core::num::nonzero::NonZeroU64> +pub const fn radroots_execution::DeliveryObservation::outcome(&self) -> radroots_execution::TargetObservation +pub const fn radroots_execution::DeliveryObservation::recipient(&self) -> core::option::Option<radroots_identity::key::PublicKey> +pub fn radroots_execution::DeliveryObservation::target(&self) -> &str +impl core::fmt::Debug for radroots_execution::DeliveryObservation +pub fn radroots_execution::DeliveryObservation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_execution::Detail impl radroots_execution::Detail pub const fn radroots_execution::Detail::field(self) -> radroots_execution::Field @@ -173,4 +230,35 @@ pub const fn radroots_execution::OperationContext::admission_unknown(radroots_do pub const fn radroots_execution::OperationContext::operation_id(self) -> core::option::Option<radroots_domain::identifier::OperationId> pub const fn radroots_execution::OperationContext::proposed(core::option::Option<radroots_domain::identifier::OperationId>) -> Self pub const fn radroots_execution::OperationContext::retained(radroots_domain::identifier::OperationId) -> Self +pub struct radroots_execution::OperationReceipt<T> +impl radroots_execution::OperationReceipt<()> +pub fn radroots_execution::OperationReceipt<()>::from_snapshot(&radroots_storage::command::snapshot::OperationSnapshot) -> Self +impl<T> radroots_execution::OperationReceipt<T> +pub const fn radroots_execution::OperationReceipt<T>::admission(&self) -> radroots_execution::Admission +pub const fn radroots_execution::OperationReceipt<T>::admission_transaction_id(&self) -> radroots_domain::identifier::TransactionId +pub fn radroots_execution::OperationReceipt<T>::artifacts(&self) -> &[radroots_execution::ArtifactObservation] +pub const fn radroots_execution::OperationReceipt<T>::authority_checkpoint(&self) -> &radroots_domain::context::CheckpointRef +pub const fn radroots_execution::OperationReceipt<T>::business_installation(&self) -> radroots_execution::BusinessInstallation +pub fn radroots_execution::OperationReceipt<T>::business_result(&self) -> core::option::Option<&T> +pub const fn radroots_execution::OperationReceipt<T>::command_digest(&self) -> radroots_domain::identifier::CommandDigest +pub fn radroots_execution::OperationReceipt<T>::conflicting_records(&self) -> &[radroots_domain::identifier::RecordId] +pub fn radroots_execution::OperationReceipt<T>::conflicting_sources(&self) -> &[radroots_domain::identifier::SourceId] +pub const fn radroots_execution::OperationReceipt<T>::context(&self) -> &radroots_domain::context::CommandContextData +pub const fn radroots_execution::OperationReceipt<T>::delivery(&self) -> radroots_execution::Delivery +pub fn radroots_execution::OperationReceipt<T>::delivery_observations(&self) -> &[radroots_execution::DeliveryObservation] +pub const fn radroots_execution::OperationReceipt<T>::durable(&self) -> bool +pub const fn radroots_execution::OperationReceipt<T>::error(&self) -> core::option::Option<radroots_execution::Error> +pub const fn radroots_execution::OperationReceipt<T>::issuance(&self) -> radroots_execution::Issuance +pub const fn radroots_execution::OperationReceipt<T>::issuance_window(&self) -> radroots_domain::issuance::IssuanceWindow +pub const fn radroots_execution::OperationReceipt<T>::message_id(&self) -> core::option::Option<radroots_domain::identifier::MessageId> +pub fn radroots_execution::OperationReceipt<T>::missing_sources(&self) -> &[radroots_domain::identifier::SourceId] +pub const fn radroots_execution::OperationReceipt<T>::observed_at(&self) -> radroots_domain::context::UnixSeconds +pub const fn radroots_execution::OperationReceipt<T>::operation_checkpoint(&self) -> radroots_domain::identifier::CheckpointDigest +pub const fn radroots_execution::OperationReceipt<T>::plan_transaction_id(&self) -> core::option::Option<radroots_domain::identifier::TransactionId> +pub fn radroots_execution::OperationReceipt<T>::record_ids(&self) -> &[radroots_domain::identifier::RecordId] +pub fn radroots_execution::OperationReceipt<T>::recovery(&self) -> &[radroots_execution::RecoveryRequirement] +pub const fn radroots_execution::OperationReceipt<T>::wait_termination(&self) -> radroots_execution::WaitTermination +pub fn radroots_execution::OperationReceipt<T>::with_wait_termination(self, radroots_execution::WaitTermination) -> Self +impl<T> core::fmt::Debug for radroots_execution::OperationReceipt<T> +pub fn radroots_execution::OperationReceipt<T>::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub type radroots_execution::Result<T> = core::result::Result<T, radroots_execution::Error> diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -795,6 +795,14 @@ pub radroots_storage::command::PlanBindingOutcome::Committed(radroots_storage::c pub radroots_storage::command::PlanBindingOutcome::Unknown(radroots_storage::command::CommitAttempt) impl core::fmt::Debug for radroots_storage::command::PlanBindingOutcome pub fn radroots_storage::command::PlanBindingOutcome::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub enum radroots_storage::command::RetainedOperation +pub radroots_storage::command::RetainedOperation::Planned(alloc::boxed::Box<radroots_storage::command::BoundSigningPlan>) +pub radroots_storage::command::RetainedOperation::Prepared(radroots_storage::command::PreparedOperation) +impl radroots_storage::command::RetainedOperation +pub fn radroots_storage::command::RetainedOperation::bound_plan(&self) -> core::option::Option<&radroots_storage::command::BoundSigningPlan> +pub fn radroots_storage::command::RetainedOperation::prepared(&self) -> &radroots_storage::command::PreparedOperation +impl core::fmt::Debug for radroots_storage::command::RetainedOperation +pub fn radroots_storage::command::RetainedOperation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage::command::AdmissionRequest impl radroots_storage::command::AdmissionRequest pub const fn radroots_storage::command::AdmissionRequest::binding(&self) -> &radroots_storage::workspace::WorkspaceBinding @@ -833,6 +841,21 @@ pub const fn radroots_storage::command::ClaimAttemptRequest::plan_digest(&self) pub const fn radroots_storage::command::ClaimAttemptRequest::recipient(&self) -> radroots_identity::key::PublicKey impl core::fmt::Debug for radroots_storage::command::ClaimAttemptRequest pub fn radroots_storage::command::ClaimAttemptRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::command::ClaimSnapshot +impl radroots_storage::command::ClaimSnapshot +pub const fn radroots_storage::command::ClaimSnapshot::attempt_id(self) -> radroots_domain::identifier::SigningAttemptId +pub const fn radroots_storage::command::ClaimSnapshot::claimed_at(self) -> radroots_domain::context::UnixSeconds +pub const fn radroots_storage::command::ClaimSnapshot::command_digest(self) -> radroots_domain::identifier::CommandDigest +pub const fn radroots_storage::command::ClaimSnapshot::event_id(self) -> radroots_domain::identifier::EnvelopeEventId +pub fn radroots_storage::command::ClaimSnapshot::from_store_report(&radroots_storage::command::SigningAttempt) -> Self +pub const fn radroots_storage::command::ClaimSnapshot::intent(self) -> radroots_protocol::intent::IntentBinding +pub const fn radroots_storage::command::ClaimSnapshot::operation_id(self) -> radroots_domain::identifier::OperationId +pub const fn radroots_storage::command::ClaimSnapshot::plan_digest(&self) -> &[u8; 32] +pub const fn radroots_storage::command::ClaimSnapshot::recipient(self) -> radroots_identity::key::PublicKey +pub const fn radroots_storage::command::ClaimSnapshot::transaction_id(self) -> radroots_domain::identifier::TransactionId +pub const fn radroots_storage::command::ClaimSnapshot::workspace_id(self) -> radroots_domain::identifier::WorkspaceId +impl core::fmt::Debug for radroots_storage::command::ClaimSnapshot +pub fn radroots_storage::command::ClaimSnapshot::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage::command::CommitAttempt impl radroots_storage::command::CommitAttempt pub const fn radroots_storage::command::CommitAttempt::command_digest(self) -> radroots_domain::identifier::CommandDigest @@ -852,6 +875,17 @@ pub const fn radroots_storage::command::EvidenceReceipt::operation_id(&self) -> pub const fn radroots_storage::command::EvidenceReceipt::recipient(&self) -> radroots_identity::key::PublicKey pub const fn radroots_storage::command::EvidenceReceipt::transaction_id(&self) -> radroots_domain::identifier::TransactionId pub const fn radroots_storage::command::EvidenceReceipt::workspace_id(&self) -> radroots_domain::identifier::WorkspaceId +pub struct radroots_storage::command::OperationSnapshot +impl radroots_storage::command::OperationSnapshot +pub fn radroots_storage::command::OperationSnapshot::bound_plan(&self) -> core::option::Option<&radroots_storage::command::BoundSigningPlan> +pub fn radroots_storage::command::OperationSnapshot::checkpoint_digest(&self) -> radroots_domain::identifier::CheckpointDigest +pub fn radroots_storage::command::OperationSnapshot::from_store_report(radroots_storage::command::RetainedOperation, alloc::vec::Vec<radroots_storage::command::RecipientSnapshot>, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage::command::OperationSnapshot::message_id(&self) -> core::option::Option<radroots_domain::identifier::MessageId> +pub const fn radroots_storage::command::OperationSnapshot::observed_at(&self) -> radroots_domain::context::UnixSeconds +pub fn radroots_storage::command::OperationSnapshot::prepared(&self) -> &radroots_storage::command::PreparedOperation +pub fn radroots_storage::command::OperationSnapshot::recipients(&self) -> &[radroots_storage::command::RecipientSnapshot] +impl core::fmt::Debug for radroots_storage::command::OperationSnapshot +pub fn radroots_storage::command::OperationSnapshot::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage::command::PreparedOperation impl radroots_storage::command::PreparedOperation pub fn radroots_storage::command::PreparedOperation::from_committed_store(radroots_storage::command::AdmissionRequest, radroots_domain::identifier::TransactionId, radroots_domain::context::Sequence, radroots_domain::issuance::IssuanceWindow) -> core::result::Result<Self, radroots_storage::command::OperationError> @@ -862,6 +896,15 @@ pub const fn radroots_storage::command::PreparedOperation::revision(&self) -> ra pub const fn radroots_storage::command::PreparedOperation::transaction_id(&self) -> radroots_domain::identifier::TransactionId impl core::fmt::Debug for radroots_storage::command::PreparedOperation pub fn radroots_storage::command::PreparedOperation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::command::RecipientSnapshot +impl radroots_storage::command::RecipientSnapshot +pub const fn radroots_storage::command::RecipientSnapshot::claim(self) -> core::option::Option<radroots_storage::command::ClaimSnapshot> +pub const fn radroots_storage::command::RecipientSnapshot::expected_event(self) -> core::option::Option<radroots_domain::identifier::EnvelopeEventId> +pub const fn radroots_storage::command::RecipientSnapshot::from_store_report(radroots_identity::key::PublicKey, core::option::Option<radroots_domain::identifier::EnvelopeEventId>, core::option::Option<radroots_storage::command::ClaimSnapshot>, core::option::Option<radroots_storage::command::EvidenceReceipt>) -> Self +pub const fn radroots_storage::command::RecipientSnapshot::obtained(self) -> core::option::Option<radroots_storage::command::EvidenceReceipt> +pub const fn radroots_storage::command::RecipientSnapshot::recipient(self) -> radroots_identity::key::PublicKey +impl core::fmt::Debug for radroots_storage::command::RecipientSnapshot +pub fn radroots_storage::command::RecipientSnapshot::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage::command::SealEvidence impl radroots_storage::command::SealEvidence pub const fn radroots_storage::command::SealEvidence::attempt_id(&self) -> radroots_domain::identifier::SigningAttemptId @@ -901,6 +944,7 @@ pub fn radroots_storage::command::OperationJournal::capture_evidence<'a>(&'a sel pub fn radroots_storage::command::OperationJournal::claim_attempt(&self, radroots_storage::command::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::ClaimAttemptOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage::command::OperationJournal::obtained_evidence(&self, radroots_storage::command::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::CapturedSeal>, radroots_storage::command::OperationError>> pub fn radroots_storage::command::OperationJournal::operation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::PreparedOperation>, radroots_storage::command::OperationError>> +pub fn radroots_storage::command::OperationJournal::operation_snapshot(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::OperationSnapshot>, radroots_storage::command::OperationError>> pub fn radroots_storage::command::OperationJournal::signing_attempt(&self, radroots_storage::command::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::SigningAttempt>, radroots_storage::command::OperationError>> pub fn radroots_storage::command::OperationJournal::signing_plan(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::BoundSigningPlan>, radroots_storage::command::OperationError>> pub mod radroots_storage::event diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -386,6 +386,7 @@ pub fn radroots_storage_sqlite::workspace::NativeWorkspace::capture_evidence<'a> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::claim_attempt(&self, radroots_storage::command::issuance::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::issuance::ClaimAttemptOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::obtained_evidence(&self, radroots_storage::command::issuance::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::issuance::CapturedSeal>, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::operation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::PreparedOperation>, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::operation_snapshot(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::snapshot::OperationSnapshot>, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::signing_attempt(&self, radroots_storage::command::issuance::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::issuance::SigningAttempt>, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::signing_plan(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::BoundSigningPlan>, radroots_storage::command::OperationError>> impl radroots_storage::workspace::WorkspaceStore for radroots_storage_sqlite::workspace::NativeWorkspace diff --git a/contracts/coverage-profiles.toml b/contracts/coverage-profiles.toml @@ -5,7 +5,8 @@ test_threads = 1 [profiles.crates."radroots_execution"] no_default_features = false -features = ["session", "signer_session", "client_session", "workspace_session"] +features = ["session", "signer_session", "client_session", "workspace_session", "radroots/native"] +test_packages = ["radroots"] test_threads = 1 [profiles.crates."radroots_protocol"] @@ -45,5 +46,9 @@ features = ["full"] test_threads = 1 [profiles.crates."radroots_storage"] -features = ["command_journal"] -test_packages = ["radroots_storage_sqlite"] +features = ["command_journal", "radroots/native"] +test_packages = ["radroots_storage_sqlite", "radroots"] + +[profiles.crates."radroots_storage_sqlite"] +features = ["radroots/native"] +test_packages = ["radroots"] diff --git a/contracts/protocol/chat.v1.json b/contracts/protocol/chat.v1.json @@ -119,5 +119,29 @@ "schema": 5, "schema_objects": 11, "remaining": "Ordinary client-owned orchestration and full operation receipts, route/provider approval, installation/outbox/delivery, target graph retirement and all consumer/final gates" + }, + "native_operation_snapshot": { + "state": "native_snapshot_and_receipt_component_implemented", + "snapshot_owner": "radroots_storage::command::OperationSnapshot", + "query": "OperationJournal::operation_snapshot on the existing native owner", + "receipt_owner": "radroots_execution::OperationReceipt; ordinary facade reexports", + "native_schema": 5, + "transaction": "Authenticate complete original preparation/plan/expected claims and obtained evidence outside transaction; recheck current grant, all retained and absent facts and complete graph counts under BEGIN IMMEDIATE; confirmed rollback before reporting", + "extra_or_orphan_rows": "Recovery required; never silently omitted from a complete report", + "memory": "One complete owned plan and at most two sorted unique boxed recipient reports; no private raw bytes or automatic payload serialization in receipt diagnostics", + "progress_digest": "SHA-256 with radroots.operation.snapshot.v1 NUL separator; workspace/operation/command, T0 transaction/revision/window, authority checkpoint digest, optional T1 plan/transaction/time, each recipient claim/intent/time and obtained transaction/event/raw digest/optional time; excludes query time and diagnostic correlation", + "dimensions": [ + "durable_admission", + "business_installation", + "per_recipient_issuance", + "delivery", + "caller_wait_termination", + "recovery" + ], + "first_issue_expiry": "Remaining unrequested work is blocked; obtained and unknown classifications are preserved. Expiry proves no nonissuance.", + "scope": "Original actor/workspace/authority/route, command/transactions/window, authority evidence checkpoint, logical-message and structured-record namespaces, protected artifact references and nullable original observations", + "construction_authority": "Pure values do not authenticate a principal, qualify a custom adapter, permit dispatch or prove installation/delivery", + "remaining": "Native T2 installation/publication work, exact wrapping/delivery, library-owned ordinary inbox jobs, complete browser/binding/consumer closure and final acceptance", + "count_bounds": "Whole-operation extra-recipient count checks stop at excess sentinels 3 claims, 3 obtained manifests and 9 parts; absent-operation checks use EXISTS. Existing protected per-recipient part bounds and authentication remain mandatory." } } diff --git a/crates/execution/Cargo.toml b/crates/execution/Cargo.toml @@ -17,10 +17,12 @@ default = [] session = ["dep:futures"] signer_session = ["session", "dep:radroots_signing"] client_session = ["signer_session"] -workspace_session = ["client_session", "dep:radroots_storage"] +workspace_session = ["client_session", "receipts"] +receipts = ["dep:radroots_storage", "radroots_storage/command_journal"] [dependencies] radroots_domain = { workspace = true, default-features = false } +radroots_protocol = { workspace = true, default-features = false, features = ["intent"] } futures = { workspace = true, optional = true } radroots_signing = { workspace = true, default-features = false, optional = true } radroots_storage = { workspace = true, default-features = false, optional = true } diff --git a/crates/execution/README.md b/crates/execution/README.md @@ -98,3 +98,16 @@ Package upload is not authorized. Actual durable command transactions, outbox workers, inventory authority, public listing/private chat execution, browser attachment and new bindings remain separate requirements. Revalidating a context is not durable admission; the authoritative transaction must recheck its scope. + + +`OperationReceipt<T>` owns the original captured scope, command and transaction +identities, issuance window, authority checkpoint and coherent progress digest. +It separates installation, per-recipient issuance, delivery and caller waiting. +Its diagnostics contain no private command text or ciphertext. The optional +`receipts` feature projects a Storage operation snapshot without I/O; the +concrete adapter must qualify the underlying authenticated coherent query. +The current native T0/T1/S profile reports no business installation or delivery. +Expired remaining first issuance is blocked while obtained and unknown facts +remain retained. Changing a wait observation cannot change those facts. +Default receipt values remain usable without an async runtime on noStd targets; +the Storage-backed projection is a separately selected host feature. diff --git a/crates/execution/src/error.rs b/crates/execution/src/error.rs @@ -40,6 +40,7 @@ codes! { GrantRevoked => ("grant_revoked", "The authorizing grant was revoked", false), MissingAuthority => ("missing_authority", "Selected execution authority is missing", false), StaleState => ("stale_state", "Expected state must be refreshed and approved", false), + DeadlineExceeded => ("deadline_exceeded", "The captured first-issue deadline has elapsed", false), MissingSource => ("missing_source", "Required source evidence is missing", false), MissingHistory => ("missing_history", "Required authenticated history is missing", false), UnsupportedVersion => ("unsupported_version", "The version is unsupported", false), @@ -191,6 +192,27 @@ pub struct Error { } impl Error { + #[cfg(feature = "receipts")] + pub(crate) const fn retained_deadline_exceeded(operation: OperationId) -> Self { + Self { + code: Code::DeadlineExceeded, + context: OperationContext::retained(operation), + retry: RetryClass::ManualReconciliation, + detail: Some(Detail::new( + crate::Field::Operation, + crate::Reason::OutOfRange, + )), + } + } + #[cfg(feature = "receipts")] + pub(crate) const fn retained_signing_unknown(operation: OperationId) -> Self { + Self { + code: Code::SigningUnknown, + context: OperationContext::retained(operation), + retry: RetryClass::ManualReconciliation, + detail: Some(Detail::new(crate::Field::Signer, crate::Reason::Unknown)), + } + } #[cfg(feature = "workspace_session")] pub(crate) const fn workspace( error: radroots_storage::workspace::WorkspaceError, diff --git a/crates/execution/src/lib.rs b/crates/execution/src/lib.rs @@ -5,6 +5,12 @@ mod diagnostic; mod error; +extern crate alloc; +mod receipt; +pub use receipt::{ + ArtifactObservation, BusinessInstallation, Delivery, DeliveryObservation, Issuance, + OperationReceipt, RecoveryRequirement, TargetObservation, WaitTermination, +}; #[cfg(feature = "session")] extern crate std; diff --git a/crates/execution/src/receipt.rs b/crates/execution/src/receipt.rs @@ -0,0 +1,501 @@ +//! Owned operation observations. Receipt values grant no authority, prove no +//! custom adapter qualification and never restart a retained signing operation. +use crate::{Admission, Error}; +use alloc::boxed::Box; +use core::{fmt, num::NonZeroU64}; +use radroots_domain::{ + CheckpointDigest, CheckpointRef, CommandContextData, CommandDigest, EnvelopeEventId, + IssuanceWindow, MessageId, PublicKey, RecordId, SigningAttemptId, SourceId, TransactionId, + UnixSeconds, +}; +use radroots_protocol::intent::ArtifactRole; + +/// Installation is independent of signature and relay observations. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum BusinessInstallation { + /// This effect class has no business installation. + NotApplicable, + /// No installation is confirmed. + NotInstalled, + /// Actual installation was confirmed. + Installed, + /// Installation completion requires reconciliation. + Uncertain, +} +/// Issuance classification, without conflating recipients or delivery. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum Issuance { + /// No retained issuance work has been bound. + None, + /// Retained work remains before complete obtained evidence. + Pending, + /// Every expected artifact has obtained evidence. + Obtained, + /// At least one retained invocation lacks a known obtained result. + Unknown, + /// Qualified evidence explicitly proves no issuance; absence alone does not. + ProvablyUnissued, +} +/// Delivery observation progress; observed does not mean every relay accepted. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum Delivery { + /// No exact publication work has started. + NotStarted, + /// Retained publication work awaits observations. + Pending, + /// The requested observation scope has completed; inspect each target. + Observed, + /// Publication completion remains unknown. + Unknown, +} +/// Why a caller's observation ended, independently of retained operation state. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum WaitTermination { + /// The caller received this observation, possibly of a pending operation. + Returned, + /// The caller stopped waiting. + Cancelled, + /// The caller's wait deadline elapsed. + DeadlineExceeded, + /// The client closed its observation scope. + ClientClosed, +} +/// Required continuation is explicit and never permission for blind reissue. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum RecoveryRequirement { + /// Continue using the original captured command and retained identity. + ContinueOriginalOperation, + /// Reconcile the original potential issuance using its qualified contract. + ReconcileIssuance, + /// Install matching already obtained evidence without releasing its claims. + InstallObtainedEvidence, + /// Continue retained exact publication work. + ResumeDelivery, + /// An operator must reconcile the original state. + ManualReconciliation, +} +/// One exact event/target observation, separate from business success. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum TargetObservation { + /// The target explicitly accepted this exact event. + Accepted, + /// The target explicitly rejected this exact event. + Rejected, + /// No matching observation arrived before the bounded attempt ended. + TimedOut, + /// The transport disconnected without a matching acknowledgement. + Disconnected, + /// Completion requires reconciliation. + Unknown, +} +macro_rules! copied { + ($name:ident, $ty:ty, $field:ident, $doc:literal) => { + #[doc=$doc] + pub const fn $name(&self) -> $ty { + self.$field + } + }; +} + +/// A protected artifact reference and its independent original issuance facts. +/// No raw signed bytes, ciphertext or private command text is retained here. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct ArtifactObservation { + role: ArtifactRole, + recipient: Option<PublicKey>, + expected_event: Option<EnvelopeEventId>, + issuance: Issuance, + attempt: Option<SigningAttemptId>, + claim_transaction: Option<TransactionId>, + intent_digest: Option<[u8; 32]>, + capture_transaction: Option<TransactionId>, + obtained_digest: Option<[u8; 32]>, + observed_at: Option<NonZeroU64>, +} +impl ArtifactObservation { + copied!( + role, + ArtifactRole, + role, + "Exact artifact purpose, not command permission." + ); + copied!( + recipient, + Option<PublicKey>, + recipient, + "Exact intended recipient, when private." + ); + copied!( + expected_event, + Option<EnvelopeEventId>, + expected_event, + "Exact seal/event identity, never a logical record ID." + ); + copied!( + issuance, + Issuance, + issuance, + "This artifact's independent issuance state." + ); + copied!( + attempt_id, + Option<SigningAttemptId>, + attempt, + "Original full-width attempt identity." + ); + copied!( + claim_transaction_id, + Option<TransactionId>, + claim_transaction, + "Original confirmed claim transaction." + ); + copied!( + intent_digest, + Option<[u8; 32]>, + intent_digest, + "Exact original intent commitment." + ); + copied!( + capture_transaction_id, + Option<TransactionId>, + capture_transaction, + "Original protected capture transaction." + ); + copied!( + obtained_digest, + Option<[u8; 32]>, + obtained_digest, + "Digest of the exact original obtained representation." + ); + copied!( + observed_at_unix_ms, + Option<NonZeroU64>, + observed_at, + "Original optional observation; missing remains explicit." + ); +} +impl fmt::Debug for ArtifactObservation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ArtifactObservation(<redacted>)") + } +} +/// Actual retained event/target observation. An empty collection reports no +/// delivery observations; selecting a route is not an acknowledgement. +pub struct DeliveryObservation { + event: EnvelopeEventId, + recipient: Option<PublicKey>, + target: Box<str>, + outcome: TargetObservation, + observed_at: Option<NonZeroU64>, +} +impl DeliveryObservation { + copied!( + event_id, + EnvelopeEventId, + event, + "Exact event whose target observation was checked." + ); + copied!( + recipient, + Option<PublicKey>, + recipient, + "Retained recipient scope, when private." + ); + copied!( + outcome, + TargetObservation, + outcome, + "Individual target observation; no business effect is implied." + ); + copied!( + observed_at_unix_ms, + Option<NonZeroU64>, + observed_at, + "Original optional target observation time." + ); + /// Borrows the exact retained target for authorized presentation. + pub fn target(&self) -> &str { + &self.target + } +} +impl fmt::Debug for DeliveryObservation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("DeliveryObservation(<redacted>)") + } +} + +/// Owned observation of one original operation. It does not authenticate a +/// principal or qualify a custom host. Business, issuance, delivery and caller +/// wait dimensions remain independent; private payloads never enter diagnostics. +pub struct OperationReceipt<T> { + context: CommandContextData, + command_digest: CommandDigest, + admission: Admission, + admission_transaction: TransactionId, + plan_transaction: Option<TransactionId>, + issuance_window: IssuanceWindow, + authority_checkpoint: CheckpointRef, + operation_checkpoint: CheckpointDigest, + conflicting_records: Box<[RecordId]>, + conflicting_sources: Box<[SourceId]>, + observed_at: UnixSeconds, + business_installation: BusinessInstallation, + business_result: Option<T>, + message_id: Option<MessageId>, + record_ids: Box<[RecordId]>, + artifacts: Box<[ArtifactObservation]>, + issuance: Issuance, + delivery: Delivery, + delivery_observations: Box<[DeliveryObservation]>, + wait_termination: WaitTermination, + recovery: Box<[RecoveryRequirement]>, + error: Option<Error>, +} +impl<T> OperationReceipt<T> { + /// Original captured data; this is not an authenticated executable context. + pub const fn context(&self) -> &CommandContextData { + &self.context + } + copied!( + command_digest, + CommandDigest, + command_digest, + "Original semantic command commitment." + ); + copied!( + admission, + Admission, + admission, + "Actual reported initial-admission disposition." + ); + /// Reports confirmed preparation only, independently of later effects. + pub const fn durable(&self) -> bool { + matches!(self.admission, Admission::Confirmed) + } + copied!( + admission_transaction_id, + TransactionId, + admission_transaction, + "Original confirmed preparation transaction." + ); + copied!( + plan_transaction_id, + Option<TransactionId>, + plan_transaction, + "Original complete-plan transaction, when present." + ); + copied!( + issuance_window, + IssuanceWindow, + issuance_window, + "Original first-issue bounds; never restarted by a receipt." + ); + /// Authority/evidence checkpoint originally captured by the operation. + pub const fn authority_checkpoint(&self) -> &CheckpointRef { + &self.authority_checkpoint + } + copied!( + operation_checkpoint, + CheckpointDigest, + operation_checkpoint, + "Stable identity of this coherent retained progress observation." + ); + /// Missing sources at the original authority checkpoint; partial coverage + /// never becomes global completeness because a local query succeeded. + pub fn missing_sources(&self) -> &[SourceId] { + self.authority_checkpoint.missing() + } + /// Structured-record conflicts in this scoped observation. Empty does not + /// establish complete remote history. + pub fn conflicting_records(&self) -> &[RecordId] { + &self.conflicting_records + } + /// Source conflicts in this scoped observation, separate from record IDs. + pub fn conflicting_sources(&self) -> &[SourceId] { + &self.conflicting_sources + } + copied!( + observed_at, + UnixSeconds, + observed_at, + "Actual query observation; no global freshness guarantee." + ); + copied!( + business_installation, + BusinessInstallation, + business_installation, + "Installation outcome independently of signing and delivery." + ); + /// Borrows the owned installed business snapshot when actually available. + pub fn business_result(&self) -> Option<&T> { + self.business_result.as_ref() + } + copied!( + message_id, + Option<MessageId>, + message_id, + "Original logical message identity, separate from signed event IDs." + ); + /// Borrows actual structured record IDs; chat message IDs are not cast here. + pub fn record_ids(&self) -> &[RecordId] { + &self.record_ids + } + /// Borrows independent exact artifact references and issuance observations. + pub fn artifacts(&self) -> &[ArtifactObservation] { + &self.artifacts + } + copied!( + issuance, + Issuance, + issuance, + "Aggregate issuance; any unresolved invocation stays unknown." + ); + copied!( + delivery, + Delivery, + delivery, + "Delivery progress, never a business rollback signal." + ); + /// Borrows actual exact event/target observations. + pub fn delivery_observations(&self) -> &[DeliveryObservation] { + &self.delivery_observations + } + copied!( + wait_termination, + WaitTermination, + wait_termination, + "Caller waiting is independent of retained effects." + ); + /// Purely changes this caller observation's wait termination. It does not + /// cancel, revoke, abort, install or deliver any operation. + pub fn with_wait_termination(mut self, termination: WaitTermination) -> Self { + self.wait_termination = termination; + self + } + /// Borrows explicit original-operation recovery requirements. + pub fn recovery(&self) -> &[RecoveryRequirement] { + &self.recovery + } + copied!( + error, + Option<Error>, + error, + "Fixed redacted execution cause, when known." + ); +} +impl<T> fmt::Debug for OperationReceipt<T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("OperationReceipt(<redacted>)") + } +} + +#[cfg(feature = "receipts")] +impl OperationReceipt<()> { + /// Projects a structurally validated T0/T1/S report. Only the concrete + /// adapter's actual authenticated coherent query qualifies the facts. This + /// conversion performs no I/O, issuance, installation or publication. + pub fn from_snapshot(snapshot: &radroots_storage::command::OperationSnapshot) -> Self { + use alloc::{vec, vec::Vec}; + let prepared = snapshot.prepared(); + let mut artifacts = Vec::with_capacity(snapshot.recipients().len()); + for recipient in snapshot.recipients() { + let claim = recipient.claim(); + let obtained = recipient.obtained(); + let issuance = if obtained.is_some() { + Issuance::Obtained + } else if claim.is_some() { + Issuance::Unknown + } else if snapshot.bound_plan().is_some() { + Issuance::Pending + } else { + Issuance::None + }; + artifacts.push(ArtifactObservation { + role: ArtifactRole::BusinessSeal, + recipient: Some(recipient.recipient()), + expected_event: recipient.expected_event(), + issuance, + attempt: claim.map(|value| value.attempt_id()), + claim_transaction: claim.map(|value| value.transaction_id()), + intent_digest: claim.map(|value| *value.intent().digest()), + capture_transaction: obtained.map(|value| value.transaction_id()), + obtained_digest: obtained.map(|value| *value.digest()), + observed_at: obtained.and_then(|value| value.observed_at_unix_ms()), + }); + } + let unknown = artifacts + .iter() + .any(|value| value.issuance == Issuance::Unknown); + let obtained = artifacts + .iter() + .any(|value| value.issuance == Issuance::Obtained); + let issuance = if unknown { + Issuance::Unknown + } else if artifacts + .iter() + .all(|value| value.issuance == Issuance::Obtained) + { + Issuance::Obtained + } else if snapshot.bound_plan().is_some() { + Issuance::Pending + } else { + Issuance::None + }; + let expired = !unknown + && issuance != Issuance::Obtained + && snapshot.observed_at() >= prepared.issuance_window().first_issue_not_after(); + let mut recovery = Vec::new(); + if unknown { + recovery.push(RecoveryRequirement::ReconcileIssuance); + } + if obtained { + recovery.push(RecoveryRequirement::InstallObtainedEvidence); + } + if expired { + recovery.push(RecoveryRequirement::ManualReconciliation); + } + if recovery.is_empty() { + recovery.push(RecoveryRequirement::ContinueOriginalOperation); + } + Self { + context: prepared.request().command().context().clone(), + command_digest: prepared.identity().command_digest(), + admission: Admission::Confirmed, + admission_transaction: prepared.transaction_id(), + plan_transaction: snapshot.bound_plan().map(|value| value.transaction_id()), + issuance_window: prepared.issuance_window(), + authority_checkpoint: prepared.request().binding().input().checkpoint().clone(), + operation_checkpoint: snapshot.checkpoint_digest(), + conflicting_records: vec![].into_boxed_slice(), + conflicting_sources: vec![].into_boxed_slice(), + observed_at: snapshot.observed_at(), + business_installation: BusinessInstallation::NotInstalled, + business_result: None, + message_id: snapshot.message_id(), + record_ids: vec![].into_boxed_slice(), + artifacts: artifacts.into_boxed_slice(), + issuance, + delivery: Delivery::NotStarted, + delivery_observations: vec![].into_boxed_slice(), + wait_termination: WaitTermination::Returned, + recovery: recovery.into_boxed_slice(), + error: if unknown { + Some(Error::retained_signing_unknown( + prepared.identity().operation_id(), + )) + } else if expired { + Some(Error::retained_deadline_exceeded( + prepared.identity().operation_id(), + )) + } else { + None + }, + } + } +} diff --git a/crates/radroots/Cargo.toml b/crates/radroots/Cargo.toml @@ -61,10 +61,14 @@ knowledge = ["client", "radroots_sdk/knowledge"] full = ["native", "radroots_sdk/full"] [dev-dependencies] +radroots_protocol = { workspace = true, default-features = false, features = ["chat"] } +radroots_signing = { workspace = true, features = ["chat"] } +nostr = { workspace = true, default-features = false, features = ["std", "nip44"] } +sqlx = { workspace = true, features = ["runtime-tokio", "sqlite-bundled"] } radroots_secrets = { workspace = true, features = ["file"] } futures = { workspace = true } radroots_event_codec = { workspace = true, default-features = false } -radroots_nostr = { workspace = true, features = ["signing"] } +radroots_nostr = { workspace = true, features = ["signing", "nip17"] } serde_json = { workspace = true, features = ["std"] } tempfile = { workspace = true } tokio = { workspace = true, features = ["macros", "rt"] } diff --git a/crates/radroots/README.md b/crates/radroots/README.md @@ -81,3 +81,11 @@ The reviewed Rust API lives in [`contracts/api_baselines/radroots.txt`](../../contracts/api_baselines/radroots.txt). The approved successor ownership and host contracts live in [`shared_sdk_refactor.v1.json`](../../contracts/architecture/decisions/shared_sdk_refactor.v1.json). + + +The common `OperationReceipt<T>` types are exported by this facade. Their owned +observations preserve original identities and independent issuance, installation, +delivery and caller-wait dimensions. The advanced native journal can supply a +coherent T0/T1/S snapshot for this projection. Ordinary inbox job orchestration, +T2 business installation/outbox and exact delivery remain required before the +complete native submission workflow is available. diff --git a/crates/radroots/src/lib.rs b/crates/radroots/src/lib.rs @@ -21,5 +21,9 @@ pub use client::NativeConfig; pub use client::{Client, CloseReceipt, SessionStatus, StartMode}; pub use radroots_domain::OperationId; pub use radroots_execution::workspace::{CommandContext, WorkspaceSession}; +pub use radroots_execution::{ + ArtifactObservation, BusinessInstallation, Delivery, DeliveryObservation, Issuance, + OperationReceipt, RecoveryRequirement, TargetObservation, WaitTermination, +}; pub use radroots_execution::{Error, Result}; pub use radroots_storage::workspace::{AttachmentInput, AttachmentProof}; diff --git a/crates/radroots/tests/package_boundary.rs b/crates/radroots/tests/package_boundary.rs @@ -63,7 +63,10 @@ fn root_has_exact_exports_and_no_sdk_namespace() { assert!( ROOT.contains("pub use radroots_storage::workspace::{AttachmentInput, AttachmentProof};") ); - assert_eq!(ROOT.matches("pub use ").count(), 6); + assert!(ROOT.contains( + "pub use radroots_execution::{\n ArtifactObservation, BusinessInstallation, Delivery, DeliveryObservation, Issuance,\n OperationReceipt, RecoveryRequirement, TargetObservation, WaitTermination,\n};" + )); + assert_eq!(ROOT.matches("pub use ").count(), 7); assert!(README.contains("```compile_fail\nuse radroots::sdk;\n```")); } diff --git a/crates/radroots/tests/receipts.rs b/crates/radroots/tests/receipts.rs @@ -0,0 +1,234 @@ +#![cfg(all(unix, feature = "native"))] + +#[path = "support/receipt_plans.rs"] +mod plans; + +use radroots_domain::{ + CommandContextData, CommandDigest, CorrelationId, OperationId, PublicKey, UnixSeconds, +}; +use radroots_secrets::{ + SecretId, SecretRef, + envelope::Nonce, + file::{FileOpenMode, FileProvider}, + id::{BackendKind, KeyVersion}, + provider::AccessPolicy, + wrapping::SecretMaterial, +}; +use radroots_storage::{ + command::{ + AdmissionOutcome, AdmissionRequest, OperationError, OperationJournal, PreparedOperation, + }, + workspace::{ + AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceError, + }, +}; +use radroots_storage_sqlite::workspace::{LocalOutboxConfig, NativeWorkspace, WorkspaceCrypto}; +use serde_json::json; +use sqlx::{Connection, SqliteConnection}; +use std::{ + path::PathBuf, + sync::{ + Arc, Mutex, + atomic::{AtomicU64, Ordering}, + mpsc, + }, + time::Duration, +}; + +struct Pause { + skip: usize, + reached: mpsc::SyncSender<()>, + resume: mpsc::Receiver<()>, +} +struct Clock { + now: AtomicU64, + pause: Mutex<Option<Pause>>, +} +impl Clock { + fn arm(&self, skip: usize) -> (mpsc::Receiver<()>, mpsc::SyncSender<()>) { + let (reached, receive) = mpsc::sync_channel(1); + let (resume, released) = mpsc::sync_channel(1); + *self.pause.lock().unwrap() = Some(Pause { + skip, + reached, + resume: released, + }); + (receive, resume) + } +} +impl WorkspaceClock for Clock { + fn now(&self) -> Result<UnixSeconds, WorkspaceError> { + let pause = { + let mut selected = self.pause.lock().unwrap(); + if let Some(pause) = selected.as_mut() { + if pause.skip == 0 { + selected.take() + } else { + pause.skip -= 1; + None + } + } else { + None + } + }; + if let Some(pause) = pause { + pause + .reached + .send(()) + .map_err(|_| WorkspaceError::Unavailable)?; + pause + .resume + .recv_timeout(Duration::from_secs(10)) + .map_err(|_| WorkspaceError::Unavailable)?; + } + UnixSeconds::new(self.now.load(Ordering::SeqCst)).map_err(|_| WorkspaceError::Unavailable) + } +} +struct Fixture { + _root: tempfile::TempDir, + path: PathBuf, + provider: Arc<FileProvider>, + clock: Arc<Clock>, +} +impl Fixture { + fn new() -> Self { + let root = tempfile::tempdir().unwrap(); + let base = root.path().canonicalize().unwrap(); + let provider = Arc::new( + FileProvider::open( + base.join("vault"), + FileOpenMode::CreateNew, + SecretMaterial::from_slice(&[0xa5; 32]).unwrap(), + ) + .unwrap(), + ); + provider + .provision( + &reference(), + &SecretMaterial::from_slice(&[0x41; 32]).unwrap(), + Nonce::new([0x11; 24]), + ) + .unwrap(); + Self { + _root: root, + path: base.join("outbox"), + provider, + clock: Arc::new(Clock { + now: AtomicU64::new(100), + pause: Mutex::new(None), + }), + } + } + fn crypto(&self) -> WorkspaceCrypto { + WorkspaceCrypto::new( + self.provider.clone(), + reference(), + SecretMaterial::from_slice(&[0x41; 32]).unwrap(), + AccessPolicy::standard(), + ) + .unwrap() + } + async fn create( + &self, + ) -> ( + Arc<NativeWorkspace>, + AttachmentInput, + AttachmentProof, + WorkspaceBinding, + ) { + self.create_with_expiry(200).await + } + async fn create_with_expiry( + &self, + expiry: u64, + ) -> ( + Arc<NativeWorkspace>, + AttachmentInput, + AttachmentProof, + WorkspaceBinding, + ) { + let (store, input, proof) = NativeWorkspace::initialize_local_outbox( + &self.path, + LocalOutboxConfig::new( + key(), + key(), + "synthetic-device", + UnixSeconds::new(expiry).unwrap(), + ) + .unwrap(), + self.crypto(), + self.clock.clone(), + ) + .await + .unwrap(); + let binding = store.authenticate(input.clone(), &proof).await.unwrap(); + (Arc::new(store), input, proof, binding) + } + async fn database(&self) -> SqliteConnection { + SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(self.path.join("execution_v1.sqlite")) + .create_if_missing(false), + ) + .await + .unwrap() + } + async fn reopen(&self, input: AttachmentInput) -> NativeWorkspace { + NativeWorkspace::open_existing(&self.path, input, self.crypto(), self.clock.clone()) + .await + .unwrap() + } +} +fn reference() -> SecretRef { + SecretRef::new( + SecretId::parse("workspace-key").unwrap(), + BackendKind::File, + KeyVersion::new(1).unwrap(), + ) +} +fn key() -> PublicKey { + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() +} +fn copy(proof: &AttachmentProof) -> AttachmentProof { + proof.with_secret(|secret| AttachmentProof::from_protected_input(secret).unwrap()) +} +fn request(binding: &WorkspaceBinding, id: u8, text: &str, correlation: &str) -> AdmissionRequest { + request_until(binding, id, text, correlation, 150) +} +fn request_until( + binding: &WorkspaceBinding, + id: u8, + text: &str, + correlation: &str, + not_after: u64, +) -> AdmissionRequest { + let input = binding.input(); + let context = CommandContextData::new( + OperationId::from_bytes([id; 32]), + binding.actor(), + input.workspace_id(), + input.authority(), + input.route_digest(), + None, + None, + UnixSeconds::new(not_after).unwrap(), + Some(CorrelationId::new(correlation).unwrap()), + ) + .unwrap(); + let bytes = serde_json::to_vec(&json!({"type": "inbox.inquire", "context": context, + "input": {"thread_id": "66".repeat(32), "peer": key(), "source": null, "text": text}})) + .unwrap(); + AdmissionRequest::from_protected_wire(binding.clone(), &bytes).unwrap() +} +fn committed(outcome: AdmissionOutcome) -> PreparedOperation { + match outcome { + AdmissionOutcome::Committed(result) => result, + AdmissionOutcome::Unknown(_) => panic!("unexpected unknown completion"), + } +} +async fn reached(receiver: mpsc::Receiver<()>) { + tokio::task::spawn_blocking(move || receiver.recv_timeout(Duration::from_secs(10))) + .await + .unwrap() + .unwrap(); +} diff --git a/crates/radroots/tests/support/receipt_issuance.rs b/crates/radroots/tests/support/receipt_issuance.rs @@ -0,0 +1,122 @@ +use super::*; +use core::cell::Cell; +use radroots_nostr::{ + key::parse_secret_key, + signing::{LocalSigner, OsNonceSource}, +}; +use radroots_signing::{ + issuance::{OutcomeKind, SigningIntent}, + provider::{ParticipantProvider, ProviderCall}, + request::CancellationSignal, +}; +use radroots_storage::command::{ + ClaimAttemptOutcome, ClaimAttemptRequest, SealEvidence, SigningAttempt, +}; +thread_local! {static CALLS:Cell<usize>=const {Cell::new(0)};static MISSING:Cell<bool>=const {Cell::new(false)};} +fn signer_clock() -> Result<u64, radroots_signing::Error> { + let count = CALLS.with(|calls| { + let value = calls.get() + 1; + calls.set(value); + value + }); + if count > 1 && MISSING.with(Cell::get) { + Err(radroots_signing::Error::new( + radroots_signing::error::Kind::InternalError, + )) + } else { + Ok(100_000) + } +} +pub(super) fn selection( + binding: &WorkspaceBinding, + prepared: &PreparedOperation, + plan_digest: [u8; 32], + recipient: PublicKey, +) -> ClaimAttemptRequest { + ClaimAttemptRequest::new( + binding.clone(), + prepared.identity().operation_id(), + prepared.identity().command_digest(), + plan_digest, + recipient, + ) +} +pub(super) fn claim(outcome: ClaimAttemptOutcome) -> SigningAttempt { + match outcome { + ClaimAttemptOutcome::Claimed(value) => value, + _ => panic!("first actual claim must confirm its commit"), + } +} +pub(super) async fn prepare( + fixture: &Fixture, + store: &NativeWorkspace, + binding: &WorkspaceBinding, + proof: &AttachmentProof, + id: u8, + large: bool, +) -> (PreparedOperation, [u8; 32], Vec<PublicKey>) { + let mut captured = peer_request(binding, id); + if large { + let mut value: serde_json::Value = + serde_json::from_slice(captured.command().protected_wire()).unwrap(); + value["input"]["text"] = "\0".repeat(3500).into(); + captured = AdmissionRequest::from_protected_wire( + binding.clone(), + &serde_json::to_vec(&value).unwrap(), + ) + .unwrap(); + } + let prepared = committed( + store + .admit_command_and_hold(captured, copy(proof)) + .await + .unwrap(), + ); + let plan = plan(prepared.request().command(), 100, "native-issuance"); + let digest = *plan.digest(); + let recipients = plan.seals().iter().map(|seal| seal.recipient()).collect(); + bound( + store + .bind_signing_intents(binding.clone(), plan, copy(proof)) + .await + .unwrap(), + ); + let _ = fixture; + (prepared, digest, recipients) +} +pub(super) async fn obtain(attempt: &SigningAttempt, missing: bool) -> SealEvidence { + CALLS.with(|calls| calls.set(0)); + MISSING.with(|value| value.set(missing)); + // Published synthetic key in a qualified local provider, isolated from all host custody. + let signer = LocalSigner::with_clock( + parse_secret_key("0000000000000000000000000000000000000000000000000000000000000001") + .unwrap(), + signer_clock, + ) + .unwrap() + .with_nonce_source(Arc::new(OsNonceSource)); + let observed = signer.provider_state().await.unwrap(); + assert_eq!(observed.identity(), key()); + assert_eq!( + observed.exact_issuance(), + Some(radroots_signing::recovery::ReplayCapability::NonReplayable) + ); + let intent = SigningIntent::from_chat_seal( + attempt.binding().operation_id(), + attempt.bound_plan().prepared().identity().command_digest(), + attempt.seal(), + ProviderCall::new(key(), attempt.deadline_unix_ms(), CancellationSignal::new()), + ) + .unwrap(); + assert_eq!(intent.binding(), attempt.binding()); + let outcome = signer.sign_exact(intent).await; + assert_eq!(outcome.binding(), attempt.binding()); + let (_, kind) = outcome.into_parts(); + let OutcomeKind::Obtained(artifact) = kind else { + panic!("actual local exact signing must obtain") + }; + assert_eq!(artifact.observed_at_unix_ms().is_none(), missing); + artifact.with_json(|raw| { + SealEvidence::verify(attempt, raw, artifact.observed_at_unix_ms()).unwrap() + }) +} diff --git a/crates/radroots/tests/support/receipt_plans.rs b/crates/radroots/tests/support/receipt_plans.rs @@ -0,0 +1,92 @@ +//! Native storage tests use real synthetic NIP-44 data, never host custody. +#[path = "receipt_issuance.rs"] +mod issuance; +#[path = "receipt_snapshots.rs"] +mod snapshots; +use super::*; +use nostr::{JsonUtil, nips::nip44}; +use radroots_domain::EnvelopeEventId; +use radroots_protocol::chat::{CapturedDmRoute, ChatReplay, ChatRumor, ChatSeal, ChatSigningPlan}; +use radroots_storage::command::{BoundSigningPlan, PlanBindingOutcome}; +fn keys(last: u8) -> nostr::Keys { + let mut bytes = [0; 32]; + bytes[31] = last; + nostr::Keys::new(nostr::SecretKey::from_slice(&bytes).unwrap()) +} +fn peer_request(binding: &WorkspaceBinding, id: u8) -> AdmissionRequest { + let request = request(binding, id, "protected complete private plan", "original"); + let mut value: serde_json::Value = + serde_json::from_slice(request.command().protected_wire()).unwrap(); + value["input"]["peer"] = keys(2).public_key().to_hex().into(); + AdmissionRequest::from_protected_wire(binding.clone(), &serde_json::to_vec(&value).unwrap()) + .unwrap() +} +fn plan( + command: &radroots_protocol::command::CapturedChatCommand, + created: u64, + suffix: &str, +) -> ChatSigningPlan { + let rumor = ChatRumor::from_command(command, UnixSeconds::new(created).unwrap()).unwrap(); + let author = keys(1); + let mut seals = Vec::new(); + let mut routes = Vec::new(); + for recipient in rumor.recipients() { + let target = nostr::PublicKey::from_slice(recipient.as_bytes()).unwrap(); + let ciphertext = nip44::encrypt( + author.secret_key(), + &target, + rumor.json(), + nip44::Version::V2, + ) + .unwrap(); + seals.push( + ChatSeal::new( + &rumor, + *recipient, + UnixSeconds::new(created - 1).unwrap(), + &ciphertext, + ) + .unwrap(), + ); + let signer = if recipient == &key() { + keys(1) + } else { + keys(2) + }; + let url = format!("wss://relay.example/{suffix}"); + let source = nostr::UnsignedEvent { + id: None, + pubkey: signer.public_key(), + created_at: nostr::Timestamp::from_secs(created - 1), + kind: nostr::Kind::Custom(10050), + tags: nostr::Tags::from_list(vec![nostr::Tag::parse(["relay", &url]).unwrap()]), + content: "public signed route provenance ".repeat(1000), + } + .sign_with_keys(&signer) + .unwrap(); + source.verify().unwrap(); + routes.push( + CapturedDmRoute::from_observed_descriptor( + *recipient, + EnvelopeEventId::from_bytes(*source.id.as_bytes()), + &source.as_json(), + &[url], + ) + .unwrap(), + ); + } + ChatSigningPlan::new( + command, + UnixSeconds::new(created).unwrap(), + seals, + routes, + ChatReplay::NonReplayable, + ) + .unwrap() +} +fn bound(outcome: PlanBindingOutcome) -> BoundSigningPlan { + match outcome { + PlanBindingOutcome::Committed(bound) => bound, + PlanBindingOutcome::Unknown(_) => panic!("fixture must confirm T1"), + } +} diff --git a/crates/radroots/tests/support/receipt_snapshots.rs b/crates/radroots/tests/support/receipt_snapshots.rs @@ -0,0 +1,753 @@ +use super::issuance::{claim, obtain, prepare, selection}; +use super::*; +use radroots_execution::{ + BusinessInstallation, Delivery, Issuance, OperationReceipt, RecoveryRequirement, + WaitTermination, +}; +use radroots_storage::command::{OperationSnapshot, RecipientSnapshot, RetainedOperation}; + +#[tokio::test] +async fn structural_reports_reject_incomplete_recipient_sets_and_cross_operation_evidence() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let (prepared, digest, recipients) = + prepare(&fixture, &store, &binding, &proof, 180, false).await; + let first = claim( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof), + ) + .await + .unwrap(), + ); + let bytes = obtain(&first, true).await; + store + .capture_evidence(input.clone(), &proof, &bytes) + .await + .unwrap(); + let original = store + .operation_snapshot( + binding.clone(), + prepared.identity().operation_id(), + None, + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + let (other, other_digest, other_recipients) = + prepare(&fixture, &store, &binding, &proof, 181, false).await; + let other_claim = claim( + store + .claim_attempt( + selection(&binding, &other, other_digest, other_recipients[0]), + copy(&proof), + ) + .await + .unwrap(), + ); + let other_bytes = obtain(&other_claim, true).await; + store + .capture_evidence(input, &proof, &other_bytes) + .await + .unwrap(); + let other = store + .operation_snapshot( + binding.clone(), + other.identity().operation_id(), + None, + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + let first = original.recipients()[0]; + let second = original.recipients()[1]; + let foreign = other.recipients()[0]; + let cases = [ + (vec![], 100), + (vec![first], 100), + (vec![first, second, first], 100), + (vec![second, first], 100), + (vec![first, first], 100), + (vec![first, second], 0), + ( + vec![ + RecipientSnapshot::from_store_report( + first.recipient(), + None, + first.claim(), + first.obtained(), + ), + second, + ], + 100, + ), + ( + vec![ + RecipientSnapshot::from_store_report( + first.recipient(), + first.expected_event(), + None, + first.obtained(), + ), + second, + ], + 100, + ), + ( + vec![ + RecipientSnapshot::from_store_report( + first.recipient(), + first.expected_event(), + foreign.claim(), + foreign.obtained(), + ), + second, + ], + 100, + ), + ( + vec![ + RecipientSnapshot::from_store_report( + first.recipient(), + first.expected_event(), + first.claim(), + foreign.obtained(), + ), + second, + ], + 100, + ), + ]; + for (recipients, time) in cases { + let bound = store + .signing_plan( + binding.clone(), + prepared.identity().operation_id(), + prepared.identity().command_digest(), + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + assert!(matches!( + OperationSnapshot::from_store_report( + RetainedOperation::Planned(Box::new(bound)), + recipients, + UnixSeconds::new(time).unwrap() + ), + Err(OperationError::RecoveryRequired) + )); + } + let report = store + .operation( + binding, + prepared.identity().operation_id(), + None, + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + assert!(matches!( + OperationSnapshot::from_store_report( + RetainedOperation::Prepared(report), + original.recipients().to_vec(), + UnixSeconds::new(100).unwrap() + ), + Err(OperationError::RecoveryRequired) + )); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn expiry_blocks_remaining_first_issuance_without_erasing_obtained_or_unknown_facts() { + for mode in 0u8..=3 { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let (prepared, planned) = if mode == 0 { + ( + committed( + store + .admit_command_and_hold(peer_request(&binding, 174), copy(&proof)) + .await + .unwrap(), + ), + None, + ) + } else { + let (prepared, digest, recipients) = + prepare(&fixture, &store, &binding, &proof, 174 + mode, false).await; + (prepared, Some((digest, recipients))) + }; + if let Some((digest, recipients)) = planned + && mode >= 2 + { + for recipient in recipients.into_iter().take(if mode == 2 { 1 } else { 2 }) { + let original = claim( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipient), + copy(&proof), + ) + .await + .unwrap(), + ); + if mode == 3 { + let bytes = obtain(&original, true).await; + store + .capture_evidence(input.clone(), &proof, &bytes) + .await + .unwrap(); + } + } + } + fixture.clock.now.store(151, Ordering::SeqCst); + let snapshot = store + .operation_snapshot( + binding, + prepared.identity().operation_id(), + None, + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + let receipt = OperationReceipt::from_snapshot(&snapshot); + assert!(receipt.durable()); + assert_eq!( + receipt.admission_transaction_id(), + prepared.transaction_id() + ); + assert_eq!( + receipt.business_installation(), + BusinessInstallation::NotInstalled + ); + assert_eq!(receipt.delivery(), Delivery::NotStarted); + match mode { + 0 | 1 => { + assert_eq!( + receipt.error().unwrap().code(), + radroots_execution::Code::DeadlineExceeded + ); + assert!( + receipt + .recovery() + .contains(&RecoveryRequirement::ManualReconciliation) + ); + assert!(!matches!( + receipt.issuance(), + Issuance::Obtained | Issuance::ProvablyUnissued + )); + } + 2 => { + assert_eq!(receipt.issuance(), Issuance::Unknown); + assert_eq!( + receipt.error().unwrap().code(), + radroots_execution::Code::SigningUnknown + ); + assert!( + receipt + .recovery() + .contains(&RecoveryRequirement::ReconcileIssuance) + ); + } + 3 => { + assert_eq!(receipt.issuance(), Issuance::Obtained); + assert_eq!(receipt.error(), None); + } + _ => unreachable!(), + } + store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn full_receipts_keep_obtained_and_unknown_recipients_separate_and_bind_original_provenance() +{ + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let (prepared, digest, recipients) = + prepare(&fixture, &store, &binding, &proof, 173, false).await; + let first = claim( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof), + ) + .await + .unwrap(), + ); + let first_bytes = obtain(&first, true).await; + store + .capture_evidence(input.clone(), &proof, &first_bytes) + .await + .unwrap(); + let second = claim( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[1]), + copy(&proof), + ) + .await + .unwrap(), + ); + let snapshot = store + .operation_snapshot( + binding.clone(), + prepared.identity().operation_id(), + None, + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + let view = OperationReceipt::from_snapshot(&snapshot); + assert_eq!(view.command_digest(), prepared.identity().command_digest()); + assert_eq!(view.artifacts()[0].issuance(), Issuance::Obtained); + assert_eq!(view.artifacts()[1].issuance(), Issuance::Unknown); + assert_eq!(view.issuance(), Issuance::Unknown); + assert_eq!( + view.business_installation(), + BusinessInstallation::NotInstalled + ); + assert_eq!(view.business_result(), None); + assert_eq!(view.delivery(), Delivery::NotStarted); + assert!(view.delivery_observations().is_empty()); + assert!(view.conflicting_records().is_empty()); + assert!(view.conflicting_sources().is_empty()); + assert_eq!( + view.missing_sources(), + binding.input().checkpoint().missing() + ); + assert!( + view.recovery() + .contains(&RecoveryRequirement::InstallObtainedEvidence) + ); + assert!( + view.recovery() + .contains(&RecoveryRequirement::ReconcileIssuance) + ); + let original = &view.artifacts()[0]; + assert_eq!( + original.role(), + radroots_protocol::intent::ArtifactRole::BusinessSeal + ); + assert_eq!(original.recipient(), Some(first.seal().recipient())); + assert_eq!( + original.expected_event().unwrap().as_bytes(), + &first.seal().event_id() + ); + assert_eq!(original.attempt_id(), Some(first.attempt_id())); + assert_eq!( + original.claim_transaction_id(), + Some(first.transaction_id()) + ); + assert_eq!(original.intent_digest(), Some(*first.binding().digest())); + assert_eq!(original.obtained_digest(), Some(*first_bytes.digest())); + assert_eq!( + original.capture_transaction_id(), + snapshot.recipients()[0] + .obtained() + .map(|value| value.transaction_id()) + ); + assert_eq!(original.observed_at_unix_ms(), None); + let second_bytes = obtain(&second, false).await; + store + .capture_evidence(input, &proof, &second_bytes) + .await + .unwrap(); + let snapshot = store + .operation_snapshot( + binding.clone(), + prepared.identity().operation_id(), + None, + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + let completed = OperationReceipt::from_snapshot(&snapshot); + assert_eq!(completed.issuance(), Issuance::Obtained); + assert_eq!(completed.error(), None); + assert_eq!( + completed.artifacts()[1].observed_at_unix_ms(), + second_bytes.observed_at_unix_ms() + ); + assert_ne!( + completed.operation_checkpoint(), + view.operation_checkpoint() + ); + let checkpoint = completed.operation_checkpoint(); + fixture.clock.now.store(110, Ordering::SeqCst); + let later = store + .operation_snapshot( + binding, + prepared.identity().operation_id(), + None, + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + let later = OperationReceipt::from_snapshot(&later); + assert_eq!(later.observed_at().get(), 110); + assert_eq!(later.operation_checkpoint(), checkpoint); + assert_eq!(later.artifacts()[1].attempt_id(), Some(second.attempt_id())); + assert_eq!(later.issuance_window(), prepared.issuance_window()); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn coherent_snapshots_retain_t0_t1_and_independent_recipient_claim_and_capture_after_reopen() +{ + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let request = peer_request(&binding, 170); + let operation = request.command().context().operation_id(); + let digest = request.command().digest(); + assert!( + store + .operation_snapshot(binding.clone(), operation, Some(digest), copy(&proof)) + .await + .unwrap() + .is_none() + ); + let prepared = committed( + store + .admit_command_and_hold(request, copy(&proof)) + .await + .unwrap(), + ); + let snapshot = store + .operation_snapshot(binding.clone(), operation, None, copy(&proof)) + .await + .unwrap() + .unwrap(); + assert_eq!( + snapshot.prepared().transaction_id(), + prepared.transaction_id() + ); + assert!(snapshot.bound_plan().is_none()); + let receipt = OperationReceipt::from_snapshot(&snapshot); + assert!(receipt.durable()); + assert_eq!(receipt.issuance(), Issuance::None); + assert_eq!( + receipt.business_installation(), + BusinessInstallation::NotInstalled + ); + assert_eq!(receipt.delivery(), Delivery::NotStarted); + assert!(receipt.business_result().is_none()); + assert!(receipt.record_ids().is_empty()); + assert_eq!(receipt.context(), prepared.request().command().context()); + assert_eq!( + receipt.admission_transaction_id(), + prepared.transaction_id() + ); + assert_eq!(receipt.issuance_window(), prepared.issuance_window()); + assert_eq!(receipt.authority_checkpoint(), binding.input().checkpoint()); + let initial_checkpoint = receipt.operation_checkpoint(); + assert_eq!(snapshot.message_id(), None); + assert_eq!(snapshot.recipients().len(), 2); + assert!( + snapshot + .recipients() + .iter() + .all(|value| value.expected_event().is_none() + && value.claim().is_none() + && value.obtained().is_none()) + ); + let plan = plan(prepared.request().command(), 100, "snapshot"); + let plan_digest = *plan.digest(); + let message = plan.message_id(); + let plan_receipt = bound( + store + .bind_signing_intents(binding.clone(), plan, copy(&proof)) + .await + .unwrap(), + ); + let snapshot = store + .operation_snapshot(binding.clone(), operation, Some(digest), copy(&proof)) + .await + .unwrap() + .unwrap(); + assert_eq!(snapshot.message_id(), Some(message)); + let receipt = OperationReceipt::from_snapshot(&snapshot); + assert_eq!(receipt.issuance(), Issuance::Pending); + assert_ne!(receipt.operation_checkpoint(), initial_checkpoint); + assert_eq!( + snapshot.bound_plan().unwrap().transaction_id(), + plan_receipt.transaction_id() + ); + assert!( + snapshot + .recipients() + .iter() + .all(|value| value.expected_event().is_some() && value.claim().is_none()) + ); + let first = snapshot.recipients()[0].recipient(); + let second = snapshot.recipients()[1].recipient(); + let attempt = claim( + store + .claim_attempt( + selection(&binding, &prepared, plan_digest, first), + copy(&proof), + ) + .await + .unwrap(), + ); + let snapshot = store + .operation_snapshot(binding.clone(), operation, None, copy(&proof)) + .await + .unwrap() + .unwrap(); + assert_eq!( + snapshot.recipients()[0].claim().unwrap().attempt_id(), + attempt.attempt_id() + ); + assert!(snapshot.recipients()[0].obtained().is_none()); + let receipt = OperationReceipt::from_snapshot(&snapshot); + assert_eq!(receipt.issuance(), Issuance::Unknown); + assert_eq!(receipt.artifacts()[0].issuance(), Issuance::Unknown); + assert_eq!(receipt.artifacts()[1].issuance(), Issuance::Pending); + assert_eq!( + receipt.error().unwrap().code(), + radroots_execution::Code::SigningUnknown + ); + assert!( + receipt + .recovery() + .contains(&RecoveryRequirement::ReconcileIssuance) + ); + assert!(snapshot.recipients()[1].claim().is_none()); + let evidence = obtain(&attempt, true).await; + let receipt = match store + .capture_evidence(input.clone(), &proof, &evidence) + .await + .unwrap() + { + radroots_storage::command::EvidenceCaptureOutcome::Committed(value) => value, + _ => panic!("capture must confirm"), + }; + let snapshot = store + .operation_snapshot(binding.clone(), operation, None, copy(&proof)) + .await + .unwrap() + .unwrap(); + assert_eq!(snapshot.recipients()[0].obtained(), Some(receipt)); + let view = OperationReceipt::from_snapshot(&snapshot); + assert_eq!(view.issuance(), Issuance::Pending); + assert_eq!(view.artifacts()[0].issuance(), Issuance::Obtained); + assert_eq!(view.artifacts()[1].issuance(), Issuance::Pending); + assert_eq!(view.artifacts()[0].observed_at_unix_ms(), None); + assert!( + view.recovery() + .contains(&RecoveryRequirement::InstallObtainedEvidence) + ); + assert_eq!(view.error(), None); + assert_eq!(format!("{view:?}"), "OperationReceipt(<redacted>)"); + assert_eq!( + format!("{:?}", view.artifacts()[0]), + "ArtifactObservation(<redacted>)" + ); + let captured_checkpoint = view.operation_checkpoint(); + let stopped = view.with_wait_termination(WaitTermination::DeadlineExceeded); + assert_eq!( + stopped.wait_termination(), + WaitTermination::DeadlineExceeded + ); + assert_eq!(stopped.operation_checkpoint(), captured_checkpoint); + assert_eq!(stopped.issuance(), Issuance::Pending); + assert_eq!( + stopped.business_installation(), + BusinessInstallation::NotInstalled + ); + assert_eq!(stopped.delivery(), Delivery::NotStarted); + assert!(stopped.durable()); + assert_eq!( + snapshot.recipients()[0] + .obtained() + .unwrap() + .observed_at_unix_ms(), + None + ); + assert_eq!(snapshot.recipients()[1].recipient(), second); + assert!(snapshot.recipients()[1].claim().is_none()); + assert_eq!(format!("{snapshot:?}"), "OperationSnapshot(<redacted>)"); + store.close().await.unwrap(); + fixture.clock.now.store(151, Ordering::SeqCst); + let reopened = fixture.reopen(input.clone()).await; + let snapshot = reopened + .operation_snapshot(binding.clone(), operation, Some(digest), copy(&proof)) + .await + .unwrap() + .unwrap(); + assert_eq!(snapshot.prepared().identity(), prepared.identity()); + assert_eq!(snapshot.message_id(), Some(message)); + assert_eq!(snapshot.recipients()[0].obtained(), Some(receipt)); + let view = OperationReceipt::from_snapshot(&snapshot); + assert_eq!(view.operation_checkpoint(), captured_checkpoint); + assert_eq!(view.message_id(), Some(message)); + assert!(snapshot.recipients()[1].obtained().is_none()); + assert!(matches!( + reopened + .operation_snapshot( + binding.clone(), + operation, + Some(CommandDigest::from_bytes([0; 32])), + copy(&proof) + ) + .await, + Err(OperationError::IdempotencyConflict) + )); + reopened.revoke(input, &proof).await.unwrap(); + assert!(matches!( + reopened + .operation_snapshot(binding, operation, None, copy(&proof)) + .await, + Err(OperationError::Workspace(WorkspaceError::GrantRevoked)) + )); + reopened.close().await.unwrap(); +} + +#[tokio::test] +async fn complete_snapshot_rejects_extra_recipient_claims_and_orphan_parts_without_repair() { + let fixture = Fixture::new(); + let (store, _, proof, binding) = fixture.create().await; + let (prepared, digest, recipients) = + prepare(&fixture, &store, &binding, &proof, 171, false).await; + claim( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof), + ) + .await + .unwrap(), + ); + let mut database = fixture.database().await; + sqlx::query("PRAGMA foreign_keys=OFF") + .execute(&mut database) + .await + .unwrap(); + let third = keys(3).public_key(); + for number in 3u8..=12 { + sqlx::query("INSERT INTO signing_attempts(workspace,operation_id,recipient,attempt_id,transaction_id,plan_digest,intent_digest,protected) SELECT workspace,operation_id,?,?,?,plan_digest,intent_digest,protected FROM signing_attempts LIMIT 1") + .bind(keys(number).public_key().as_bytes().as_slice()).bind([number;32].as_slice()).bind([number;32].as_slice()).execute(&mut database).await.unwrap(); + } + assert!(matches!( + store + .operation_snapshot( + binding.clone(), + prepared.identity().operation_id(), + None, + copy(&proof) + ) + .await, + Err(OperationError::RecoveryRequired) + )); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_attempts") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(count, 11); + sqlx::query("DELETE FROM signing_attempts WHERE recipient!=?") + .bind(recipients[0].as_bytes().as_slice()) + .execute(&mut database) + .await + .unwrap(); + for number in 3u8..=12 { + sqlx::query("INSERT INTO seal_evidence_parts(workspace,operation_id,recipient,part,protected) VALUES(?,?,?,1,zeroblob(1))") + .bind(binding.input().workspace_id().as_bytes().as_slice()).bind(prepared.identity().operation_id().as_bytes().as_slice()).bind(keys(number).public_key().as_bytes().as_slice()).execute(&mut database).await.unwrap(); + } + assert!(matches!( + store + .operation_snapshot( + binding.clone(), + prepared.identity().operation_id(), + None, + copy(&proof) + ) + .await, + Err(OperationError::RecoveryRequired) + )); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM seal_evidence_parts") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(count, 10); + sqlx::query("DELETE FROM seal_evidence_parts") + .execute(&mut database) + .await + .unwrap(); + let missing = OperationId::from_bytes([237; 32]); + sqlx::query("INSERT INTO seal_evidence_parts(workspace,operation_id,recipient,part,protected) VALUES(?,?,?,1,zeroblob(1))") + .bind(binding.input().workspace_id().as_bytes().as_slice()).bind(missing.as_bytes().as_slice()).bind(third.as_bytes().as_slice()).execute(&mut database).await.unwrap(); + assert!(matches!( + store + .operation_snapshot(binding.clone(), missing, None, copy(&proof)) + .await, + Err(OperationError::RecoveryRequired) + )); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM seal_evidence_parts") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(count, 1); + sqlx::query("DELETE FROM seal_evidence_parts") + .execute(&mut database) + .await + .unwrap(); + assert!( + store + .operation_snapshot( + binding, + prepared.identity().operation_id(), + None, + copy(&proof) + ) + .await + .unwrap() + .is_some() + ); + database.close().await.unwrap(); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn losing_a_snapshot_observer_does_not_detach_the_owner_or_prevent_safe_close() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let (prepared, _, _) = prepare(&fixture, &store, &binding, &proof, 172, false).await; + let (arrived, resume) = fixture.clock.arm(1); + let mut query = store.operation_snapshot( + binding.clone(), + prepared.identity().operation_id(), + None, + copy(&proof), + ); + assert!(futures::poll!(query.as_mut()).is_pending()); + reached(arrived).await; + drop(query); + resume.send(()).unwrap(); + store.close().await.unwrap(); + let reopened = fixture.reopen(input).await; + assert_eq!( + reopened + .operation_snapshot( + binding, + prepared.identity().operation_id(), + None, + copy(&proof) + ) + .await + .unwrap() + .unwrap() + .prepared() + .transaction_id(), + prepared.transaction_id() + ); + reopened.close().await.unwrap(); +} diff --git a/crates/storage/README.md b/crates/storage/README.md @@ -305,3 +305,12 @@ every expected field; native capture must additionally compare its own retained claim. Capture borrows the caller's evidence and credential so failure cannot consume the sole obtained copy. It preserves the first optional observation and does not apply a new issuance deadline. Queries still require current access. + + +`OperationJournal::operation_snapshot` queries the complete original T0/T1/S +graph coherently. The concrete adapter authenticates every retained claim and +obtained artifact, then compares both presence and absence together before +returning. Per-recipient reports share one owned plan; bounded boxed collections +discard spare caller capacity. The scoped progress digest excludes query time +and diagnostic correlation. Structural snapshot construction supplies no +backend qualification, dispatch permission or installed business result. diff --git a/crates/storage/src/command.rs b/crates/storage/src/command.rs @@ -12,10 +12,12 @@ use radroots_protocol::command::CapturedChatCommand; use radroots_transport::BoxFuture; mod issuance; +mod snapshot; pub use issuance::{ CapturedSeal, ClaimAttemptOutcome, ClaimAttemptRequest, EvidenceCaptureOutcome, EvidenceReceipt, SealEvidence, SigningAttempt, }; +pub use snapshot::{ClaimSnapshot, OperationSnapshot, RecipientSnapshot, RetainedOperation}; /// Fixed operation-store failures known before a successful admission commit. #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -254,6 +256,15 @@ impl fmt::Debug for AdmissionOutcome { /// Typed transaction port, implemented by actual shared storage adapters. /// Applications do not implement a second orchestration or stock engine here. pub trait OperationJournal: WorkspaceStore { + /// Queries one coherent original preparation/plan/per-recipient evidence + /// graph under current access. Reported absence grants no safe reissue. + fn operation_snapshot( + &self, + binding: WorkspaceBinding, + operation_id: OperationId, + expected_digest: Option<CommandDigest>, + proof: AttachmentProof, + ) -> BoxFuture<'_, Result<Option<OperationSnapshot>, OperationError>>; /// Commits a first claim before dispatch. Retained/unknown outcomes never /// authorize another invocation; the concrete executor owns that decision. fn claim_attempt( diff --git a/crates/storage/src/command/snapshot.rs b/crates/storage/src/command/snapshot.rs @@ -0,0 +1,350 @@ +//! Coherent retained graph reports. Values are not persistence qualification or +//! dispatch permission; concrete owners must authenticate and compare all facts. +use super::{BoundSigningPlan, EvidenceReceipt, OperationError, PreparedOperation, SigningAttempt}; +use core::fmt; +use radroots_domain::{ + CommandDigest, EnvelopeEventId, MessageId, OperationId, PublicKey, SigningAttemptId, + TransactionId, UnixSeconds, WorkspaceId, +}; +use radroots_protocol::intent::IntentBinding; +use sha2::{Digest, Sha256}; +use std::{boxed::Box, vec, vec::Vec}; + +/// Fixed original claim facts, without another copy of its complete private plan. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct ClaimSnapshot { + workspace: WorkspaceId, + operation: OperationId, + command: CommandDigest, + plan: [u8; 32], + recipient: PublicKey, + attempt: SigningAttemptId, + transaction: TransactionId, + claimed_at: UnixSeconds, + event: EnvelopeEventId, + intent: IntentBinding, +} +impl ClaimSnapshot { + /// Copies a structural store report; no backend claim or nonissuance proof + /// is created by this conversion. + pub fn from_store_report(attempt: &SigningAttempt) -> Self { + let identity = attempt.bound_plan().prepared().identity(); + Self { + workspace: identity.workspace_id(), + operation: identity.operation_id(), + command: identity.command_digest(), + plan: *attempt.bound_plan().plan().digest(), + recipient: attempt.seal().recipient(), + attempt: attempt.attempt_id(), + transaction: attempt.transaction_id(), + claimed_at: attempt.claimed_at(), + event: EnvelopeEventId::from_bytes(attempt.seal().event_id()), + intent: attempt.binding(), + } + } + /// Original workspace identity. + pub const fn workspace_id(self) -> WorkspaceId { + self.workspace + } + /// Original operation identity. + pub const fn operation_id(self) -> OperationId { + self.operation + } + /// Original semantic command commitment. + pub const fn command_digest(self) -> CommandDigest { + self.command + } + /// Original complete plan commitment. + pub const fn plan_digest(&self) -> &[u8; 32] { + &self.plan + } + /// Exact intended recipient. + pub const fn recipient(self) -> PublicKey { + self.recipient + } + /// Full-width retained attempt identity. + pub const fn attempt_id(self) -> SigningAttemptId { + self.attempt + } + /// Original claim transaction. + pub const fn transaction_id(self) -> TransactionId { + self.transaction + } + /// Original claim observation, never a fresh deadline. + pub const fn claimed_at(self) -> UnixSeconds { + self.claimed_at + } + /// Expected exact signed seal ID, not a logical record identity. + pub const fn event_id(self) -> EnvelopeEventId { + self.event + } + /// Exact original intent commitment. + pub const fn intent(self) -> IntentBinding { + self.intent + } +} +impl fmt::Debug for ClaimSnapshot { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ClaimSnapshot(<redacted>)") + } +} + +/// One expected recipient's independent retained facts. Absence of obtained +/// evidence for a retained claim never establishes safe reissue. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct RecipientSnapshot { + recipient: PublicKey, + expected_event: Option<EnvelopeEventId>, + claim: Option<ClaimSnapshot>, + obtained: Option<EvidenceReceipt>, +} +impl RecipientSnapshot { + /// Structural report; the complete snapshot constructor checks its scope. + pub const fn from_store_report( + recipient: PublicKey, + expected_event: Option<EnvelopeEventId>, + claim: Option<ClaimSnapshot>, + obtained: Option<EvidenceReceipt>, + ) -> Self { + Self { + recipient, + expected_event, + claim, + obtained, + } + } + /// Exact expected recipient. + pub const fn recipient(self) -> PublicKey { + self.recipient + } + /// Expected retained seal ID, when a complete plan exists. + pub const fn expected_event(self) -> Option<EnvelopeEventId> { + self.expected_event + } + /// Original potential invocation; not permission to invoke again. + pub const fn claim(self) -> Option<ClaimSnapshot> { + self.claim + } + /// Original protected obtained-artifact reference and optional observation. + pub const fn obtained(self) -> Option<EvidenceReceipt> { + self.obtained + } +} +impl fmt::Debug for RecipientSnapshot { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("RecipientSnapshot(<redacted>)") + } +} + +/// One owned preparation and at most one complete plan, shared by all recipient +/// reports without duplicating protected private plan data per recipient. +pub enum RetainedOperation { + /// Confirmed preparation without a bound complete plan. + Prepared(PreparedOperation), + /// Confirmed preparation and complete immutable plan. + Planned(Box<BoundSigningPlan>), +} +impl RetainedOperation { + /// Borrows original committed preparation. + pub fn prepared(&self) -> &PreparedOperation { + match self { + Self::Prepared(value) => value, + Self::Planned(value) => value.prepared(), + } + } + /// Borrows the complete plan, if retained. + pub fn bound_plan(&self) -> Option<&BoundSigningPlan> { + match self { + Self::Prepared(_) => None, + Self::Planned(value) => Some(value), + } + } +} +impl fmt::Debug for RetainedOperation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("RetainedOperation(<redacted>)") + } +} + +/// Bounded coherent T0/T1/S graph report. Construction checks data relationships +/// only. It grants no authentication, backend qualification or installation fact. +pub struct OperationSnapshot { + retained: RetainedOperation, + recipients: Box<[RecipientSnapshot]>, + observed_at: UnixSeconds, +} +impl OperationSnapshot { + /// Stable scoped progress identity over original transaction, command, + /// plan, claim and obtained references. Query time and diagnostic correlation + /// are excluded. Hashing grants no backend authority. + pub fn checkpoint_digest(&self) -> radroots_domain::CheckpointDigest { + let prepared = self.prepared(); + let identity = prepared.identity(); + let mut digest = Sha256::new(); + digest.update(b"radroots.operation.snapshot.v1\0"); + digest.update(identity.workspace_id().as_bytes()); + digest.update(identity.operation_id().as_bytes()); + digest.update(identity.command_digest().as_bytes()); + digest.update(prepared.transaction_id().as_bytes()); + digest.update(prepared.revision().get().to_be_bytes()); + digest.update(prepared.issuance_window().prepared_at().get().to_be_bytes()); + digest.update( + prepared + .issuance_window() + .first_issue_not_after() + .get() + .to_be_bytes(), + ); + digest.update( + prepared + .request() + .binding() + .input() + .checkpoint() + .digest() + .as_bytes(), + ); + match self.bound_plan() { + Some(bound) => { + digest.update([1]); + digest.update(bound.plan().digest()); + digest.update(bound.transaction_id().as_bytes()); + digest.update(bound.bound_at().get().to_be_bytes()); + } + None => digest.update([0]), + } + for recipient in self.recipients() { + digest.update(recipient.recipient().as_bytes()); + match recipient.claim() { + Some(claim) => { + digest.update([1]); + digest.update(claim.attempt_id().as_bytes()); + digest.update(claim.transaction_id().as_bytes()); + digest.update(claim.intent().digest()); + digest.update(claim.claimed_at().get().to_be_bytes()); + } + None => digest.update([0]), + } + match recipient.obtained() { + Some(obtained) => { + digest.update([1]); + digest.update(obtained.transaction_id().as_bytes()); + digest.update(obtained.event_id().as_bytes()); + digest.update(obtained.digest()); + match obtained.observed_at_unix_ms() { + Some(time) => { + digest.update([1]); + digest.update(time.get().to_be_bytes()); + } + None => digest.update([0]), + } + } + None => digest.update([0]), + } + } + radroots_domain::CheckpointDigest::from_bytes(digest.finalize().into()) + } + /// Checks the exact complete recipient set, original claim scope and obtained + /// references. Concrete adapters must independently authenticate all rows and + /// compare both retained and absent facts in one coherent transaction. + pub fn from_store_report( + retained: RetainedOperation, + recipients: Vec<RecipientSnapshot>, + observed_at: UnixSeconds, + ) -> Result<Self, OperationError> { + if recipients.is_empty() || recipients.len() > 2 || observed_at.get() == 0 { + return Err(OperationError::RecoveryRequired); + } + let prepared = retained.prepared(); + let command = prepared.request().command(); + let mut expected = vec![command.context().actor().participant(), command.peer()]; + expected.sort_unstable(); + expected.dedup(); + if recipients.len() != expected.len() { + return Err(OperationError::RecoveryRequired); + } + for (recipient, expected) in recipients.iter().zip(expected) { + if recipient.recipient != expected { + return Err(OperationError::RecoveryRequired); + } + let Some(bound) = retained.bound_plan() else { + if recipient.expected_event.is_some() + || recipient.claim.is_some() + || recipient.obtained.is_some() + { + return Err(OperationError::RecoveryRequired); + } + continue; + }; + let seal = bound + .plan() + .seals() + .iter() + .find(|seal| seal.recipient() == expected) + .ok_or(OperationError::RecoveryRequired)?; + let event = EnvelopeEventId::from_bytes(seal.event_id()); + if recipient.expected_event != Some(event) { + return Err(OperationError::RecoveryRequired); + } + if let Some(claim) = recipient.claim { + let identity = prepared.identity(); + if claim.workspace != identity.workspace_id() + || claim.operation != identity.operation_id() + || claim.command != identity.command_digest() + || &claim.plan != bound.plan().digest() + || claim.recipient != expected + || claim.event != event + || claim.intent.operation_id() != identity.operation_id() + || claim.intent.command_digest() != identity.command_digest().as_bytes() + || claim.claimed_at < bound.bound_at() + || claim.claimed_at >= prepared.issuance_window().first_issue_not_after() + { + return Err(OperationError::RecoveryRequired); + } + if let Some(obtained) = recipient.obtained + && (obtained.workspace_id() != claim.workspace + || obtained.operation_id() != claim.operation + || obtained.command_digest() != claim.command + || obtained.attempt_id() != claim.attempt + || obtained.recipient() != expected + || obtained.event_id() != event) + { + return Err(OperationError::RecoveryRequired); + } + } else if recipient.obtained.is_some() { + return Err(OperationError::RecoveryRequired); + } + } + Ok(Self { + retained, + recipients: recipients.into_boxed_slice(), + observed_at, + }) + } + /// Original preparation, without a fabricated installed business result. + pub fn prepared(&self) -> &PreparedOperation { + self.retained.prepared() + } + /// Complete retained plan, when present. + pub fn bound_plan(&self) -> Option<&BoundSigningPlan> { + self.retained.bound_plan() + } + /// Exact original logical message identity, separate from seal event IDs. + pub fn message_id(&self) -> Option<MessageId> { + self.bound_plan().map(|bound| bound.plan().message_id()) + } + /// Complete sorted unique recipient set and independent outcomes. + pub fn recipients(&self) -> &[RecipientSnapshot] { + &self.recipients + } + /// Actual query clock observation; never an issuance restart or global + /// freshness guarantee. + pub const fn observed_at(&self) -> UnixSeconds { + self.observed_at + } +} +impl fmt::Debug for OperationSnapshot { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("OperationSnapshot(<redacted>)") + } +} diff --git a/crates/storage_sqlite/README.md b/crates/storage_sqlite/README.md @@ -236,3 +236,12 @@ observation clock; this grants no new issuance or read rights. The first raw representation and optional observation are immutable. Borrowed capture input keeps the caller's original through error or unknown completion. Evidence uses a protected manifest and at most four 16 KiB data parts, bounded before reads. + + +The native operation snapshot reads and authenticates the original preparation, +optional plan and complete expected peer/self outcomes before taking a write +lock. It rechecks current access, all retained and absent facts and whole-graph +counts under one `BEGIN IMMEDIATE`, rejecting extra or orphan rows. It performs +no signing or graph mutation and confirms rollback before returning. Window +expiry does not erase retained facts. The existing owner drains accepted reads +after a lost observer and closes explicitly. Workspace schema 5 stays unchanged. diff --git a/crates/storage_sqlite/src/workspace/attempt.rs b/crates/storage_sqlite/src/workspace/attempt.rs @@ -7,7 +7,7 @@ use radroots_domain::{ CommandDigest, EnvelopeEventId, GrantId, OperationId, PublicKey, SigningAttemptId, TransactionId, UnixSeconds, WorkspaceId, }; -use radroots_storage::command::{BoundSigningPlan, OperationError, SigningAttempt}; +use radroots_storage::command::{BoundSigningPlan, ClaimSnapshot, OperationError, SigningAttempt}; use serde::{Deserialize, Serialize}; use sqlx::{Row, SqliteConnection}; use zeroize::Zeroizing; @@ -184,9 +184,20 @@ pub(super) async fn unchanged( attempt: &SigningAttempt, protected: &[u8], ) -> Result<(), OperationError> { - let identity = attempt.bound_plan().prepared().identity(); + unchanged_snapshot( + connection, + ClaimSnapshot::from_store_report(attempt), + protected, + ) + .await +} +pub(super) async fn unchanged_snapshot( + connection: &mut SqliteConnection, + snapshot: ClaimSnapshot, + protected: &[u8], +) -> Result<(), OperationError> { let count:i64=sqlx::query_scalar("SELECT count(*) FROM signing_attempts WHERE workspace=? AND operation_id=? AND recipient=? AND attempt_id=? AND transaction_id=? AND plan_digest=? AND intent_digest=? AND protected=?") - .bind(identity.workspace_id().as_bytes().as_slice()).bind(identity.operation_id().as_bytes().as_slice()).bind(attempt.seal().recipient().as_bytes().as_slice()).bind(attempt.attempt_id().as_bytes().as_slice()).bind(attempt.transaction_id().as_bytes().as_slice()).bind(attempt.bound_plan().plan().digest().as_slice()).bind(attempt.binding().digest().as_slice()).bind(protected).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?; + .bind(snapshot.workspace_id().as_bytes().as_slice()).bind(snapshot.operation_id().as_bytes().as_slice()).bind(snapshot.recipient().as_bytes().as_slice()).bind(snapshot.attempt_id().as_bytes().as_slice()).bind(snapshot.transaction_id().as_bytes().as_slice()).bind(snapshot.plan_digest().as_slice()).bind(snapshot.intent().digest().as_slice()).bind(protected).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?; if count != 1 { return Err(OperationError::RecoveryRequired); } diff --git a/crates/storage_sqlite/src/workspace/evidence.rs b/crates/storage_sqlite/src/workspace/evidence.rs @@ -1,7 +1,7 @@ //! Append-only protected obtained bytes and exact original observation data. use super::{ attempt, - crypto::{IssuancePayload, PRIVATE_PAYLOAD_MAX_BYTES, WorkspaceCrypto}, + crypto::{IssuancePayload, IssuanceScope, PRIVATE_PAYLOAD_MAX_BYTES, WorkspaceCrypto}, }; use core::num::NonZeroU64; use radroots_domain::{ @@ -242,7 +242,13 @@ pub(super) async fn unchanged( attempt: &SigningAttempt, value: Option<&ProtectedEvidence>, ) -> Result<(), OperationError> { - let scope = attempt::scope(attempt); + unchanged_scope(connection, attempt::scope(attempt), value).await +} +pub(super) async fn unchanged_scope( + connection: &mut SqliteConnection, + scope: IssuanceScope, + value: Option<&ProtectedEvidence>, +) -> Result<(), OperationError> { let count: i64 = sqlx::query_scalar( "SELECT count(*) FROM seal_evidence WHERE workspace=? AND operation_id=? AND recipient=?", ) diff --git a/crates/storage_sqlite/src/workspace/issuance.rs b/crates/storage_sqlite/src/workspace/issuance.rs @@ -542,7 +542,7 @@ impl Journal<'_> { } } } -async fn absent_claim( +pub(super) async fn absent_claim( connection: &mut SqliteConnection, selected: &AttachmentInput, operation: OperationId, diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -14,6 +14,7 @@ mod issuance; mod operation; mod plan; mod record; +mod snapshot; mod worker; #[cfg(test)] @@ -217,6 +218,24 @@ impl WorkspaceStore for NativeWorkspace { } } impl radroots_storage::command::OperationJournal for NativeWorkspace { + fn operation_snapshot( + &self, + binding: WorkspaceBinding, + operation_id: radroots_domain::OperationId, + expected_digest: Option<radroots_domain::CommandDigest>, + proof: AttachmentProof, + ) -> BoxFuture< + '_, + Result< + Option<radroots_storage::command::OperationSnapshot>, + radroots_storage::command::OperationError, + >, + > { + Box::pin( + self.worker + .operation_snapshot(binding, operation_id, expected_digest, proof), + ) + } fn claim_attempt( &self, request: radroots_storage::command::ClaimAttemptRequest, diff --git a/crates/storage_sqlite/src/workspace/snapshot.rs b/crates/storage_sqlite/src/workspace/snapshot.rs @@ -0,0 +1,200 @@ +//! One authenticated coherent observation of the complete retained T0/T1/S graph. +use super::{ + AttachmentProof, WorkspaceBinding, + admission::{Journal, recheck, same_binding}, + attempt, + crypto::IssuanceScope, + evidence::{self, ProtectedEvidence}, + issuance::absent_claim, + operation, plan, +}; +use radroots_domain::{CommandDigest, EnvelopeEventId, OperationId, PublicKey}; +use radroots_storage::command::{ + BoundSigningPlan, ClaimSnapshot, OperationError, OperationSnapshot, RecipientSnapshot, + RetainedOperation, SigningAttempt, +}; +use sqlx::{Connection, SqliteConnection}; + +struct SeenRecipient { + report: RecipientSnapshot, + claim: Option<Vec<u8>>, + evidence: Option<ProtectedEvidence>, +} +impl Journal<'_> { + pub(super) async fn query_snapshot( + &mut self, + binding: WorkspaceBinding, + operation_id: OperationId, + expected_digest: Option<CommandDigest>, + proof: AttachmentProof, + ) -> Result<Option<OperationSnapshot>, OperationError> { + let (record, grant, _) = self.access(&binding, &proof).await?; + let original = + operation::read(self.connection, self.selected, operation_id, self.crypto).await?; + let mut recipients = Vec::new(); + let mut protected_plan = None; + let retained = if let Some((prepared, protected)) = original { + operation::check_digest(&prepared, binding.actor(), expected_digest)?; + same_binding(prepared.request().binding(), &binding)?; + let (prepared, bound) = + plan::read(self.connection, self.selected, prepared, self.crypto).await?; + let source = if let Some((plan, transaction, time, protected)) = bound { + protected_plan = Some(protected); + let mut bound = + BoundSigningPlan::from_committed_store(prepared, plan, transaction, time)?; + let keys: Vec<PublicKey> = bound + .plan() + .seals() + .iter() + .map(|seal| seal.recipient()) + .collect(); + for recipient in keys { + let (returned, claim) = attempt::read( + self.connection, + self.selected, + bound, + recipient, + self.crypto, + ) + .await?; + let expected = returned + .plan() + .seals() + .iter() + .find(|seal| seal.recipient() == recipient) + .map(|seal| EnvelopeEventId::from_bytes(seal.event_id())) + .ok_or(OperationError::RecoveryRequired)?; + if let Some((id, transaction, time, protected)) = claim { + let attempt = SigningAttempt::from_committed_store( + returned, + recipient, + id, + transaction, + time, + )?; + let captured = + evidence::read(self.connection, &attempt, self.crypto).await?; + let claim = ClaimSnapshot::from_store_report(&attempt); + let (obtained, evidence) = match captured { + Some((_, protected)) => (Some(protected.receipt), Some(protected)), + None => (None, None), + }; + recipients.push(SeenRecipient { + report: RecipientSnapshot::from_store_report( + recipient, + Some(expected), + Some(claim), + obtained, + ), + claim: Some(protected), + evidence, + }); + bound = attempt.into_bound_plan(); + } else { + recipients.push(SeenRecipient { + report: RecipientSnapshot::from_store_report( + recipient, + Some(expected), + None, + None, + ), + claim: None, + evidence: None, + }); + bound = returned; + } + } + RetainedOperation::Planned(Box::new(bound)) + } else { + let command = prepared.request().command(); + let mut keys = vec![command.context().actor().participant(), command.peer()]; + keys.sort_unstable(); + keys.dedup(); + for recipient in keys { + recipients.push(SeenRecipient { + report: RecipientSnapshot::from_store_report(recipient, None, None, None), + claim: None, + evidence: None, + }); + } + RetainedOperation::Prepared(prepared) + }; + Some((source, protected)) + } else { + None + }; + // No provider or signature verification work occurs under this lock. + let mut transaction = self + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked = async { + let observed = recheck(&mut transaction, self.namespace, self.selected, &grant, &record, &binding, &proof, self.clock).await?; + if let Some((source, protected)) = &retained { + operation::unchanged(&mut transaction, source.prepared(), protected).await?; + plan::unchanged(&mut transaction, source.prepared(), protected_plan.as_ref()).await?; + for seen in &recipients { + if let (Some(claim), Some(protected)) = (seen.report.claim(), &seen.claim) { + attempt::unchanged_snapshot(&mut transaction, claim, protected).await?; + let scope = IssuanceScope { + workspace: claim.workspace_id(), operation: claim.operation_id(), + plan_digest: *claim.plan_digest(), attempt: claim.attempt_id(), recipient: claim.recipient(), + }; + evidence::unchanged_scope(&mut transaction, scope, seen.evidence.as_ref()).await?; + } else { + absent_claim(&mut transaction, self.selected, operation_id, seen.report.recipient()).await?; + } + } + graph_counts(&mut transaction, self.selected.workspace_id().as_bytes(), operation_id.as_bytes(), &recipients).await?; + } else { + let count:i64=sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM operations WHERE workspace=?1 AND operation_id=?2)+EXISTS(SELECT 1 FROM signing_plans WHERE workspace=?1 AND operation_id=?2)+EXISTS(SELECT 1 FROM signing_plan_parts WHERE workspace=?1 AND operation_id=?2)+EXISTS(SELECT 1 FROM signing_attempts WHERE workspace=?1 AND operation_id=?2)+EXISTS(SELECT 1 FROM seal_evidence WHERE workspace=?1 AND operation_id=?2)+EXISTS(SELECT 1 FROM seal_evidence_parts WHERE workspace=?1 AND operation_id=?2)") + .bind(self.selected.workspace_id().as_bytes().as_slice()).bind(operation_id.as_bytes().as_slice()).fetch_one(&mut *transaction).await.map_err(|_|OperationError::RecoveryRequired)?; + if count != 0 { return Err(OperationError::RecoveryRequired); } + } + Ok::<_,OperationError>(observed.observed_at()) + }.await; + if transaction.rollback().await.is_err() { + *self.uncertain = true; + return Err(OperationError::RecoveryRequired); + } + let observed = checked?; + match retained { + Some((source, _)) => OperationSnapshot::from_store_report( + source, + recipients.into_iter().map(|seen| seen.report).collect(), + observed, + ) + .map(Some), + None => Ok(None), + } + } +} +async fn graph_counts( + connection: &mut SqliteConnection, + workspace: &[u8; 32], + operation: &[u8; 32], + recipients: &[SeenRecipient], +) -> Result<(), OperationError> { + // The valid graph has at most two claims, two obtained manifests and eight + // data parts. One excess sentinel is sufficient to reject arbitrary extras. + let counts:(i64,i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM (SELECT 1 FROM signing_attempts WHERE workspace=?1 AND operation_id=?2 LIMIT 3)),(SELECT count(*) FROM (SELECT 1 FROM seal_evidence WHERE workspace=?1 AND operation_id=?2 LIMIT 3)),(SELECT count(*) FROM (SELECT 1 FROM seal_evidence_parts WHERE workspace=?1 AND operation_id=?2 LIMIT 9))") + .bind(workspace.as_slice()).bind(operation.as_slice()).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let claims = recipients + .iter() + .filter(|seen| seen.claim.is_some()) + .count() as i64; + let evidence = recipients + .iter() + .filter(|seen| seen.evidence.is_some()) + .count() as i64; + let parts = recipients + .iter() + .filter_map(|seen| seen.evidence.as_ref()) + .map(|value| value.parts.len() as i64) + .sum::<i64>(); + if counts != (claims, evidence, parts) { + return Err(OperationError::RecoveryRequired); + } + Ok(()) +} diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -7,7 +7,8 @@ use radroots_domain::{CommandDigest, OperationId}; use radroots_storage::command::{ AdmissionOutcome, AdmissionRequest, BoundSigningPlan, CapturedSeal, ChatSigningPlan, ClaimAttemptOutcome, ClaimAttemptRequest, CommitAttempt, EvidenceCaptureOutcome, - OperationError, PlanBindingOutcome, PreparedOperation, SealEvidence, SigningAttempt, + OperationError, OperationSnapshot, PlanBindingOutcome, PreparedOperation, SealEvidence, + SigningAttempt, }; use sqlx::{ Connection, Row, SqliteConnection, @@ -32,6 +33,13 @@ const QUEUE_CAPACITY: usize = 32; const TABLE: &str = "CREATE TABLE workspace_grant (singleton INTEGER PRIMARY KEY CHECK(singleton=1), workspace BLOB NOT NULL CHECK(length(workspace)=32), grant_id BLOB NOT NULL CHECK(length(grant_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT"; type Reply<T, E = WorkspaceError> = oneshot::Sender<Result<T, E>>; enum Job { + Snapshot( + Box<WorkspaceBinding>, + OperationId, + Option<CommandDigest>, + AttachmentProof, + Reply<Option<OperationSnapshot>, OperationError>, + ), Claim( Box<ClaimAttemptRequest>, AttachmentProof, @@ -171,6 +179,19 @@ impl Handle { if ready.send(Ok(())).is_ok() { while let Ok(Queued { job, _budget }) = requests.recv() { match job { + Job::Snapshot(binding, operation, digest, proof, reply) => { + let result = Journal { + connection: &mut connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + } + .query_snapshot(*binding, operation, digest, proof) + .await; + let _ = reply.send(result); + } Job::Claim(request, proof, reply) => { let result = Journal { connection: &mut connection, @@ -372,6 +393,23 @@ impl Handle { mpsc::TrySendError::Disconnected(_) => WorkspaceError::Closed, }) } + pub(super) async fn operation_snapshot( + &self, + binding: WorkspaceBinding, + operation: OperationId, + digest: Option<CommandDigest>, + proof: AttachmentProof, + ) -> Result<Option<OperationSnapshot>, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::Snapshot( + Box::new(binding), + operation, + digest, + proof, + reply, + ))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } pub(super) async fn claim_attempt( &self, request: ClaimAttemptRequest, diff --git a/crates/storage_sqlite/tests/support/workspace_issuance.rs b/crates/storage_sqlite/tests/support/workspace_issuance.rs @@ -513,6 +513,17 @@ async fn actual_claim_commit_uncertainty_latches_and_reopen_never_infers_a_safe_ } assert!(matches!( store + .operation_snapshot( + binding.clone(), + prepared.identity().operation_id(), + None, + copy(&proof) + ) + .await, + Err(OperationError::RecoveryRequired) + )); + assert!(matches!( + store .signing_attempt( selection(&binding, &prepared, digest, recipients[0]), copy(&proof)