commit 7d3683c0c6da11feb7153c241a6a793e1c7227f0
parent d54173b399ec1d1923bfd7766252df81e0617c30
Author: triesap <tyson@radroots.org>
Date: Fri, 30 Oct 2026 01:25:53 +0000
domain: validate scoped replacement authorizations
- Check exact replacement sources and opposite-party authorization
- Preserve explicit selection and refuse causal or authorization conflicts
- Require native digest, current state and stock-effect revalidation
- Verify causal bounds, role cases, consumers and portable API freshness
Diffstat:
7 files changed, 843 insertions(+), 0 deletions(-)
diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt
@@ -13,6 +13,23 @@ pub radroots_domain::causal::CausalReadiness::Complete
pub radroots_domain::causal::CausalReadiness::Conflicted
pub radroots_domain::causal::CausalReadiness::MissingHistory
pub radroots_domain::causal::CausalReadiness::Uninterpreted
+#[non_exhaustive] pub enum radroots_domain::causal::ReplacementTermsError
+pub radroots_domain::causal::ReplacementTermsError::ClockAhead
+pub radroots_domain::causal::ReplacementTermsError::Conflicted
+pub radroots_domain::causal::ReplacementTermsError::ConflictingAuthorizations
+pub radroots_domain::causal::ReplacementTermsError::Expired
+pub radroots_domain::causal::ReplacementTermsError::InvalidGraph
+pub radroots_domain::causal::ReplacementTermsError::MissingHistory
+pub radroots_domain::causal::ReplacementTermsError::Rejected
+pub radroots_domain::causal::ReplacementTermsError::TermsDigestMismatch
+pub radroots_domain::causal::ReplacementTermsError::Uninterpreted
+pub radroots_domain::causal::ReplacementTermsError::Withdrawn
+pub radroots_domain::causal::ReplacementTermsError::WrongAuthorization
+pub radroots_domain::causal::ReplacementTermsError::WrongBase
+pub radroots_domain::causal::ReplacementTermsError::WrongProposal
+impl core::error::Error for radroots_domain::causal::ReplacementTermsError
+impl core::fmt::Display for radroots_domain::causal::ReplacementTermsError
+pub fn radroots_domain::causal::ReplacementTermsError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
#[non_exhaustive] pub enum radroots_domain::causal::RequestClaimError
pub radroots_domain::causal::RequestClaimError::ClockAhead
pub radroots_domain::causal::RequestClaimError::Conflicted
@@ -64,10 +81,28 @@ pub const fn radroots_domain::causal::InitialRequestClaim<'_>::request(&self) ->
pub const fn radroots_domain::causal::InitialRequestClaim<'_>::terms(&self) -> &radroots_domain::Terms
impl core::fmt::Debug for radroots_domain::causal::InitialRequestClaim<'_>
pub fn radroots_domain::causal::InitialRequestClaim<'_>::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
+pub struct radroots_domain::causal::ReplacementTermsClaim<'a>
+impl radroots_domain::causal::ReplacementTermsClaim<'_>
+pub const fn radroots_domain::causal::ReplacementTermsClaim<'_>::base_commitment(&self) -> radroots_domain::AgreementCommitment
+pub const fn radroots_domain::causal::ReplacementTermsClaim<'_>::expires_at(&self) -> radroots_domain::UnixSeconds
+pub const fn radroots_domain::causal::ReplacementTermsClaim<'_>::selection(&self) -> radroots_domain::causal::ReplacementTermsSelection
+pub const fn radroots_domain::causal::ReplacementTermsClaim<'_>::terms(&self) -> &radroots_domain::Terms
+impl core::fmt::Debug for radroots_domain::causal::ReplacementTermsClaim<'_>
+pub fn radroots_domain::causal::ReplacementTermsClaim<'_>::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
+pub struct radroots_domain::causal::ReplacementTermsSelection
+impl radroots_domain::causal::ReplacementTermsSelection
+pub const fn radroots_domain::causal::ReplacementTermsSelection::authorization(self) -> radroots_domain::RecordId
+pub const fn radroots_domain::causal::ReplacementTermsSelection::base_agreement(self) -> radroots_domain::RecordId
+pub const fn radroots_domain::causal::ReplacementTermsSelection::new(radroots_domain::RecordId, radroots_domain::RecordId, radroots_domain::RecordId, radroots_domain::TermsDigest) -> Self
+pub const fn radroots_domain::causal::ReplacementTermsSelection::proposal(self) -> radroots_domain::RecordId
+pub const fn radroots_domain::causal::ReplacementTermsSelection::terms_digest(self) -> radroots_domain::TermsDigest
+impl core::fmt::Debug for radroots_domain::causal::ReplacementTermsSelection
+pub fn radroots_domain::causal::ReplacementTermsSelection::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub const radroots_domain::causal::MAX_CAUSAL_RECORDS: usize
pub const radroots_domain::causal::MAX_CAUSAL_SOURCES: usize
pub fn radroots_domain::causal::analyze(radroots_domain::causal::CausalScope, &[radroots_domain::causal::CausalRecord<'_>], &[radroots_domain::SourceId], &[radroots_domain::SourceId]) -> core::result::Result<radroots_domain::causal::CausalAnalysis, radroots_domain::causal::CausalError>
pub fn radroots_domain::causal::prepare_initial_request<'a>(radroots_domain::causal::CausalScope, radroots_domain::RecordId, &[radroots_domain::causal::CausalRecord<'a>], &[radroots_domain::SourceId], &[radroots_domain::SourceId], radroots_domain::UnixSeconds) -> core::result::Result<radroots_domain::causal::InitialRequestClaim<'a>, radroots_domain::causal::RequestClaimError>
+pub fn radroots_domain::causal::prepare_replacement_terms<'a>(radroots_domain::causal::CausalScope, radroots_domain::causal::ReplacementTermsSelection, &[radroots_domain::causal::CausalRecord<'a>], &[radroots_domain::SourceId], &[radroots_domain::SourceId], radroots_domain::UnixSeconds) -> core::result::Result<radroots_domain::causal::ReplacementTermsClaim<'a>, radroots_domain::causal::ReplacementTermsError>
pub mod radroots_domain::listing
pub enum radroots_domain::listing::FulfillmentMode
pub radroots_domain::listing::FulfillmentMode::Delivery
diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json
@@ -1092,6 +1092,16 @@
"first_issuance_seconds": 120
},
"stock_accounting": {
+ "replacement_terms_admission": {
+ "owner": "radroots_domain.causal.prepare_replacement_terms",
+ "scope": "explicit_existing_agreement_proposal_and_counterparty_authorization",
+ "complete_local_causal_coverage_required": true,
+ "conflicting_authorizations_require_reconciliation": true,
+ "native_canonical_digest_recompute_required": true,
+ "native_current_head_and_residual_required": true,
+ "claim_grants_current_authority": false,
+ "claim_creates_stock_effects": false
+ },
"native_inspection": {
"model_owner": "radroots_storage.inventory.StockSnapshot",
"facade_method": "Stock.inspect",
diff --git a/crates/domain/src/commerce/causal.rs b/crates/domain/src/commerce/causal.rs
@@ -12,6 +12,11 @@ use alloc::{
use core::fmt;
mod request;
pub use request::{InitialRequestClaim, RequestClaimError, prepare_initial_request};
+mod replacement;
+pub use replacement::{
+ ReplacementTermsClaim, ReplacementTermsError, ReplacementTermsSelection,
+ prepare_replacement_terms,
+};
/// One exact bilateral order scope, including seller quotes in its null-order
/// author chain. The scope itself is untrusted data, not evidence coverage.
diff --git a/crates/domain/src/commerce/causal/replacement.rs b/crates/domain/src/commerce/causal/replacement.rs
@@ -0,0 +1,267 @@
+//! Replacement authorization claims. Actual source authentication, canonical
+//! terms hashing, current installed state and stock effects belong to execution.
+use super::*;
+use crate::{AgreementCommitment, CommercePayload, Terms, TermsDigest, UnixSeconds};
+
+/// Explicit existing-agreement/proposal/authorization selectors and an
+/// independently computed complete terms digest. Construction proves no claim.
+#[derive(Clone, Copy, Eq, PartialEq)]
+pub struct ReplacementTermsSelection {
+ base: RecordId,
+ proposal: RecordId,
+ authorization: RecordId,
+ digest: TermsDigest,
+}
+impl ReplacementTermsSelection {
+ /// Captures exact identities only. The consumer must recompute the digest
+ /// from the actual complete proposal and compare the live installed head.
+ pub const fn new(
+ base: RecordId,
+ proposal: RecordId,
+ authorization: RecordId,
+ digest: TermsDigest,
+ ) -> Self {
+ Self {
+ base,
+ proposal,
+ authorization,
+ digest,
+ }
+ }
+ /// Explicit existing agreement, not proof that it is the current head.
+ pub const fn base_agreement(self) -> RecordId {
+ self.base
+ }
+ /// Exact selected complete replacement proposal.
+ pub const fn proposal(self) -> RecordId {
+ self.proposal
+ }
+ /// Exact selected counterparty authorization.
+ pub const fn authorization(self) -> RecordId {
+ self.authorization
+ }
+ /// Declared expected digest; this value performs no canonical hashing.
+ pub const fn terms_digest(self) -> TermsDigest {
+ self.digest
+ }
+}
+impl fmt::Debug for ReplacementTermsSelection {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("ReplacementTermsSelection(<private identities>)")
+ }
+}
+
+/// Borrowed replacement claims after bounded local causal/time checks. This
+/// grants no authenticity, consent, current authority, residual or stock effect.
+pub struct ReplacementTermsClaim<'a> {
+ selection: ReplacementTermsSelection,
+ base: AgreementCommitment,
+ terms: &'a Terms,
+ expires: UnixSeconds,
+}
+impl ReplacementTermsClaim<'_> {
+ /// Exact selected identities and declared terms digest.
+ pub const fn selection(&self) -> ReplacementTermsSelection {
+ self.selection
+ }
+ /// Original base commitment claim, not current executor authority.
+ pub const fn base_commitment(&self) -> AgreementCommitment {
+ self.base
+ }
+ /// Complete proposed terms; execution must independently hash these bytes.
+ pub const fn terms(&self) -> &Terms {
+ self.terms
+ }
+ /// Earliest proposal/authorization deadline, excluding executor bounds.
+ pub const fn expires_at(&self) -> UnixSeconds {
+ self.expires
+ }
+}
+impl fmt::Debug for ReplacementTermsClaim<'_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("ReplacementTermsClaim(<private data>)")
+ }
+}
+
+/// Bounded input-free failures of the selected replacement claims.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+#[non_exhaustive]
+pub enum ReplacementTermsError {
+ /// Source bounds, identities or the declared bilateral scope differ.
+ InvalidGraph,
+ /// Required original records or causal predecessors are absent.
+ MissingHistory,
+ /// Known author forks or cycles prevent a complete scoped claim.
+ Conflicted,
+ /// Retained authenticated uninterpreted evidence prevents reduction.
+ Uninterpreted,
+ /// The selected base is not a seller agreement commitment in this scope.
+ WrongBase,
+ /// The proposal does not identify the exact selected existing agreement.
+ WrongProposal,
+ /// The authorization names another proposal or is authored by its proposer.
+ WrongAuthorization,
+ /// The authorization differs from the supplied complete terms digest.
+ TermsDigestMismatch,
+ /// The current observation is at or beyond either selected deadline.
+ Expired,
+ /// A known scoped author time is ahead of the supplied observation.
+ ClockAhead,
+ /// The author withdrew the selected authorization.
+ Withdrawn,
+ /// The counterparty rejected the selected proposal.
+ Rejected,
+ /// Another live authorization for this base declares incompatible terms.
+ ConflictingAuthorizations,
+}
+impl fmt::Display for ReplacementTermsError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(match self {
+ Self::InvalidGraph => "invalid replacement graph",
+ Self::MissingHistory => "replacement history missing",
+ Self::Conflicted => "replacement history conflicted",
+ Self::Uninterpreted => "replacement history uninterpreted",
+ Self::WrongBase => "replacement base differs",
+ Self::WrongProposal => "replacement proposal differs",
+ Self::WrongAuthorization => "replacement authorization differs",
+ Self::TermsDigestMismatch => "replacement terms digest differs",
+ Self::Expired => "replacement deadline expired",
+ Self::ClockAhead => "replacement clock observation insufficient",
+ Self::Withdrawn => "replacement authorization withdrawn",
+ Self::Rejected => "replacement proposal rejected",
+ Self::ConflictingAuthorizations => "replacement authorizations conflict",
+ })
+ }
+}
+impl core::error::Error for ReplacementTermsError {}
+
+/// Checks one explicit replacement proposal/authorization against the complete
+/// supplied local graph, with either participant permitted to propose. Generic
+/// external sources cannot substitute for the three selected original records.
+/// Losing observation or expiry does not erase an already prepared operation;
+/// recover such an operation before using this fresh-claim planner.
+///
+/// The caller must authenticate all sources, independently recompute the actual
+/// complete proposal digest, and revalidate current installed agreement, residual,
+/// permissions, original allocations and pending-operation fences in its native
+/// transaction. This pure result does not select a current agreement or acquire,
+/// release, consume, restore or resolve any physical backing or deficit.
+pub fn prepare_replacement_terms<'a>(
+ scope: CausalScope,
+ selected: ReplacementTermsSelection,
+ records: &[CausalRecord<'a>],
+ external: &[SourceId],
+ uninterpreted: &[SourceId],
+ observed_at: UnixSeconds,
+) -> Result<ReplacementTermsClaim<'a>, ReplacementTermsError> {
+ use ReplacementTermsError as E;
+ let analysis = analyze(scope, records, external, uninterpreted).map_err(|_| E::InvalidGraph)?;
+ match analysis.readiness() {
+ CausalReadiness::Complete => {}
+ CausalReadiness::MissingHistory => return Err(E::MissingHistory),
+ CausalReadiness::Conflicted => return Err(E::Conflicted),
+ CausalReadiness::Uninterpreted => return Err(E::Uninterpreted),
+ }
+ let known: BTreeMap<_, _> = records
+ .iter()
+ .map(|record| (record.id, record.content))
+ .collect();
+ let base = known
+ .get(&selected.base)
+ .copied()
+ .ok_or(E::MissingHistory)?;
+ let CommercePayload::AgreementCommitted(base) = base.payload() else {
+ return Err(E::WrongBase);
+ };
+ let proposal = known
+ .get(&selected.proposal)
+ .copied()
+ .ok_or(E::MissingHistory)?;
+ let CommercePayload::TermsProposed(terms) = proposal.payload() else {
+ return Err(E::WrongProposal);
+ };
+ if terms.base_agreement() != Some(selected.base) {
+ return Err(E::WrongProposal);
+ }
+ let authorization = known
+ .get(&selected.authorization)
+ .copied()
+ .ok_or(E::MissingHistory)?;
+ let CommercePayload::TermsAuthorized(authorized) = authorization.payload() else {
+ return Err(E::WrongAuthorization);
+ };
+ if authorized.proposal() != selected.proposal
+ || authorization.header().author() == proposal.header().author()
+ {
+ return Err(E::WrongAuthorization);
+ }
+ if authorized.terms_digest() != selected.digest {
+ return Err(E::TermsDigestMismatch);
+ }
+ if records
+ .iter()
+ .any(|record| record.content.header().created_at() > observed_at)
+ {
+ return Err(E::ClockAhead);
+ }
+ let expires = terms.expires_at().min(authorized.expires_at());
+ if observed_at >= expires {
+ return Err(E::Expired);
+ }
+ let withdrawn = |id, author| {
+ known.values().any(|record| {
+ record.header().author() == author && matches!(record.payload(), CommercePayload::WithdrawalRequested(value) if value.target() == id)
+ })
+ };
+ let rejected = |id, author| {
+ known.values().any(|record| {
+ record.header().author() != author && matches!(record.payload(), CommercePayload::TermsRejected(value) if value.target() == id)
+ })
+ };
+ if withdrawn(selected.authorization, authorization.header().author()) {
+ return Err(E::Withdrawn);
+ }
+ if rejected(selected.proposal, proposal.header().author()) {
+ return Err(E::Rejected);
+ }
+ for (id, other) in &known {
+ let CommercePayload::TermsAuthorized(other_authorization) = other.payload() else {
+ continue;
+ };
+ if *id == selected.authorization
+ || other_authorization.expires_at() <= observed_at
+ || withdrawn(*id, other.header().author())
+ {
+ continue;
+ }
+ let other_proposal = known
+ .get(&other_authorization.proposal())
+ .ok_or(E::MissingHistory)?;
+ let CommercePayload::TermsProposed(other_terms) = other_proposal.payload() else {
+ return Err(E::WrongAuthorization);
+ };
+ if other_proposal.header().author() == other.header().author() {
+ return Err(E::WrongAuthorization);
+ }
+ if other_terms.base_agreement() != Some(selected.base)
+ || other_terms.expires_at() <= observed_at
+ || rejected(
+ other_authorization.proposal(),
+ other_proposal.header().author(),
+ )
+ {
+ continue;
+ }
+ if other_terms.terms() != terms.terms()
+ || other_authorization.terms_digest() != selected.digest
+ {
+ return Err(E::ConflictingAuthorizations);
+ }
+ }
+ Ok(ReplacementTermsClaim {
+ selection: selected,
+ base: *base,
+ terms: terms.terms(),
+ expires,
+ })
+}
diff --git a/crates/domain/tests/support/causal.rs b/crates/domain/tests/support/causal.rs
@@ -1,5 +1,7 @@
use super::agreement::{buyer, group, line, money, seller, terms};
use radroots_domain::{causal::*, *};
+#[path = "terms_authorization.rs"]
+mod terms_authorization;
fn id(value: u64) -> RecordId {
let mut out = [0; 32];
diff --git a/crates/domain/tests/support/terms_authorization.rs b/crates/domain/tests/support/terms_authorization.rs
@@ -0,0 +1,471 @@
+//! Independent complete replacement claims; no source authentication or store.
+use super::*;
+
+fn time(value: u64) -> UnixSeconds {
+ UnixSeconds::new(value).unwrap()
+}
+fn digest(value: u8) -> TermsDigest {
+ TermsDigest::from_bytes([value; 32])
+}
+fn complete(different: bool) -> Terms {
+ terms(
+ vec![line(if different { 8 } else { 7 }, 9)],
+ vec![group(9)],
+ money("50"),
+ money("700"),
+ )
+ .unwrap()
+}
+fn content(
+ author: PublicKey,
+ sequence: u64,
+ previous: Option<u64>,
+ extra: &[u64],
+ payload: CommercePayload,
+) -> CommerceContent {
+ let mut parents = vec![SourceId::from_bytes([3; 32])];
+ parents.extend(previous.map(src));
+ parents.extend(extra.iter().copied().map(src));
+ parents.sort();
+ parents.dedup();
+ CommerceContent::new(
+ CommerceHeader::new(
+ thread(),
+ Some(order()),
+ author,
+ buyer(),
+ seller(),
+ time(100),
+ Sequence::new(sequence).unwrap(),
+ previous.map(id),
+ parents,
+ )
+ .unwrap(),
+ payload,
+ )
+ .unwrap()
+}
+fn proposal(base: Option<u64>, different: bool, expires: u64) -> CommercePayload {
+ CommercePayload::TermsProposed(
+ TermsProposal::new(
+ base.map(id),
+ complete(different),
+ time(expires),
+ "Private replacement",
+ )
+ .unwrap(),
+ )
+}
+fn authorization(proposal: u64, declared: u8, expires: u64) -> CommercePayload {
+ CommercePayload::TermsAuthorized(TermsAuthorization::new(
+ id(proposal),
+ digest(declared),
+ time(expires),
+ ))
+}
+fn fixture(buyer_proposes: bool) -> Vec<(u64, CommerceContent)> {
+ let base = content(
+ seller(),
+ 1,
+ None,
+ &[9000],
+ CommercePayload::AgreementCommitted(
+ AgreementCommitment::new(
+ None,
+ id(9000),
+ digest(40),
+ AuthorityRef::new(
+ ExecutorId::from_bytes([20; 32]),
+ Generation::new(1).unwrap(),
+ ),
+ Sequence::new(1).unwrap(),
+ )
+ .unwrap(),
+ ),
+ );
+ let (proposed, authorized) = if buyer_proposes {
+ (
+ content(buyer(), 1, None, &[1], proposal(Some(1), false, 200)),
+ content(seller(), 2, Some(1), &[2], authorization(2, 42, 190)),
+ )
+ } else {
+ (
+ content(seller(), 2, Some(1), &[], proposal(Some(1), false, 200)),
+ content(buyer(), 1, None, &[2], authorization(2, 42, 190)),
+ )
+ };
+ vec![(1, base), (2, proposed), (3, authorized)]
+}
+fn selection() -> ReplacementTermsSelection {
+ ReplacementTermsSelection::new(id(1), id(2), id(3), digest(42))
+}
+fn claim_at(
+ values: &[(u64, CommerceContent)],
+ at: u64,
+) -> Result<ReplacementTermsClaim<'_>, ReplacementTermsError> {
+ prepare_replacement_terms(
+ scope(),
+ selection(),
+ &values
+ .iter()
+ .map(|(id_value, value)| CausalRecord::new(id(*id_value), value))
+ .collect::<Vec<_>>(),
+ &[src(9000), SourceId::from_bytes([3; 32])],
+ &[],
+ time(at),
+ )
+}
+
+#[test]
+fn either_counterparty_can_propose_and_all_arrival_orders_preserve_exact_selected_claims() {
+ for buyer_proposes in [false, true] {
+ let values = fixture(buyer_proposes);
+ for order in [
+ [0, 1, 2],
+ [0, 2, 1],
+ [1, 0, 2],
+ [1, 2, 0],
+ [2, 0, 1],
+ [2, 1, 0],
+ ] {
+ let shuffled = order.map(|index| values[index].clone());
+ let selected = claim_at(&shuffled, 150).unwrap();
+ assert_eq!(selected.selection(), selection());
+ assert_eq!(selected.base_commitment().seller_sequence().get(), 1);
+ assert_eq!(selected.terms(), &complete(false));
+ assert_eq!(selected.expires_at(), time(190));
+ assert_eq!(
+ format!("{selected:?}"),
+ "ReplacementTermsClaim(<private data>)"
+ );
+ }
+ let duplicated = [values.as_slice(), values.as_slice()].concat();
+ assert!(claim_at(&duplicated, 150).is_ok());
+ }
+ assert_eq!(
+ format!("{:?}", selection()),
+ "ReplacementTermsSelection(<private identities>)"
+ );
+}
+
+#[test]
+fn same_author_cannot_self_authorize_replacement_even_with_a_contiguous_author_chain() {
+ for buyer_proposes in [false, true] {
+ let mut values = fixture(buyer_proposes);
+ values[2].1 = if buyer_proposes {
+ content(buyer(), 2, Some(2), &[], authorization(2, 42, 190))
+ } else {
+ content(seller(), 3, Some(2), &[], authorization(2, 42, 190))
+ };
+ assert_eq!(
+ claim_at(&values, 150).unwrap_err(),
+ ReplacementTermsError::WrongAuthorization
+ );
+ }
+}
+
+#[test]
+fn exact_base_proposal_authorization_and_declared_digest_are_separate_required_bindings() {
+ let mut values = fixture(false);
+ values[0].1 = content(
+ seller(),
+ 1,
+ None,
+ &[9000],
+ CommercePayload::Decline(RecordReason::new(id(9000), "declined").unwrap()),
+ );
+ assert_eq!(
+ claim_at(&values, 150).unwrap_err(),
+ ReplacementTermsError::WrongBase
+ );
+ let mut values = fixture(false);
+ values[1].1 = content(seller(), 2, Some(1), &[], proposal(None, false, 200));
+ assert_eq!(
+ claim_at(&values, 150).unwrap_err(),
+ ReplacementTermsError::WrongProposal
+ );
+ let mut values = fixture(false);
+ values[2].1 = content(buyer(), 1, None, &[1], authorization(1, 42, 190));
+ assert_eq!(
+ claim_at(&values, 150).unwrap_err(),
+ ReplacementTermsError::WrongAuthorization
+ );
+ let mut values = fixture(false);
+ values[2].1 = content(buyer(), 1, None, &[2], authorization(2, 43, 190));
+ assert_eq!(
+ claim_at(&values, 150).unwrap_err(),
+ ReplacementTermsError::TermsDigestMismatch
+ );
+}
+
+#[test]
+fn exact_deadlines_and_future_claims_refuse_fresh_admission_without_erasing_history() {
+ let values = fixture(false);
+ assert!(claim_at(&values, 189).is_ok());
+ assert_eq!(
+ claim_at(&values, 190).unwrap_err(),
+ ReplacementTermsError::Expired
+ );
+ assert_eq!(
+ claim_at(&values, 99).unwrap_err(),
+ ReplacementTermsError::ClockAhead
+ );
+ let mut values = values;
+ values[1].1 = content(seller(), 2, Some(1), &[], proposal(Some(1), false, 140));
+ assert_eq!(
+ claim_at(&values, 150).unwrap_err(),
+ ReplacementTermsError::Expired
+ );
+ assert_eq!(values.len(), 3);
+}
+
+#[test]
+fn observed_withdrawal_and_counterparty_rejection_block_only_their_actual_selected_claims() {
+ let mut values = fixture(false);
+ values.push((
+ 4,
+ content(
+ buyer(),
+ 2,
+ Some(3),
+ &[],
+ CommercePayload::WithdrawalRequested(RecordReason::new(id(3), "withdraw").unwrap()),
+ ),
+ ));
+ assert_eq!(
+ claim_at(&values, 150).unwrap_err(),
+ ReplacementTermsError::Withdrawn
+ );
+ values.pop();
+ values.push((
+ 4,
+ content(
+ buyer(),
+ 2,
+ Some(3),
+ &[2],
+ CommercePayload::TermsRejected(RecordReason::new(id(2), "reject").unwrap()),
+ ),
+ ));
+ assert_eq!(
+ claim_at(&values, 150).unwrap_err(),
+ ReplacementTermsError::Rejected
+ );
+ let mut values = fixture(false);
+ values.push((
+ 4,
+ content(
+ seller(),
+ 3,
+ Some(2),
+ &[],
+ CommercePayload::TermsRejected(
+ RecordReason::new(id(2), "proposer is not counterparty").unwrap(),
+ ),
+ ),
+ ));
+ assert!(claim_at(&values, 150).is_ok());
+ let mut values = fixture(true);
+ values.push((
+ 4,
+ content(
+ buyer(),
+ 2,
+ Some(2),
+ &[3],
+ CommercePayload::WithdrawalRequested(
+ RecordReason::new(id(3), "not the author of this authorization").unwrap(),
+ ),
+ ),
+ ));
+ assert!(claim_at(&values, 150).is_ok());
+}
+
+fn competing(different: bool) -> Vec<(u64, CommerceContent)> {
+ let mut values = fixture(false);
+ values.push((
+ 4,
+ content(
+ seller(),
+ 3,
+ Some(2),
+ &[1],
+ proposal(Some(1), different, 200),
+ ),
+ ));
+ values.push((
+ 5,
+ content(
+ buyer(),
+ 2,
+ Some(3),
+ &[4],
+ authorization(4, if different { 43 } else { 42 }, 190),
+ ),
+ ));
+ values
+}
+#[test]
+fn incompatible_live_authorizations_never_choose_by_arrival_time_but_compatible_claims_remain_usable()
+ {
+ let mut values = competing(true);
+ assert_eq!(
+ claim_at(&values, 150).unwrap_err(),
+ ReplacementTermsError::ConflictingAuthorizations
+ );
+ values.reverse();
+ assert_eq!(
+ claim_at(&values, 150).unwrap_err(),
+ ReplacementTermsError::ConflictingAuthorizations
+ );
+ values.reverse();
+ values.push((
+ 6,
+ content(
+ buyer(),
+ 3,
+ Some(5),
+ &[],
+ CommercePayload::WithdrawalRequested(
+ RecordReason::new(id(5), "withdraw competing authorization").unwrap(),
+ ),
+ ),
+ ));
+ assert!(claim_at(&values, 150).is_ok());
+ assert!(claim_at(&competing(false), 150).is_ok());
+}
+
+#[test]
+fn incompatible_counterproposals_authorized_by_different_parties_still_require_reconciliation() {
+ let mut values = fixture(false);
+ values.push((
+ 4,
+ content(buyer(), 2, Some(3), &[1], proposal(Some(1), true, 200)),
+ ));
+ values.push((
+ 5,
+ content(seller(), 3, Some(2), &[4], authorization(4, 43, 190)),
+ ));
+ assert_eq!(
+ claim_at(&values, 150).unwrap_err(),
+ ReplacementTermsError::ConflictingAuthorizations
+ );
+}
+
+#[test]
+fn selected_originals_cannot_be_filled_by_generic_sources_and_unknown_or_forked_history_never_falls_back()
+ {
+ let values = fixture(false);
+ let no_authorization = &values[..2];
+ let records = no_authorization
+ .iter()
+ .map(|(i, v)| CausalRecord::new(id(*i), v))
+ .collect::<Vec<_>>();
+ assert_eq!(
+ prepare_replacement_terms(
+ scope(),
+ selection(),
+ &records,
+ &[src(9000), SourceId::from_bytes([3; 32]), src(3)],
+ &[],
+ time(150)
+ )
+ .unwrap_err(),
+ ReplacementTermsError::MissingHistory
+ );
+ let records = values
+ .iter()
+ .map(|(i, v)| CausalRecord::new(id(*i), v))
+ .collect::<Vec<_>>();
+ assert_eq!(
+ prepare_replacement_terms(
+ scope(),
+ selection(),
+ &records,
+ &[src(9000), SourceId::from_bytes([3; 32])],
+ &[src(8000)],
+ time(150)
+ )
+ .unwrap_err(),
+ ReplacementTermsError::Uninterpreted
+ );
+ let mut fork = values.clone();
+ fork.push((
+ 4,
+ content(seller(), 2, Some(1), &[], proposal(Some(1), true, 200)),
+ ));
+ assert_eq!(
+ claim_at(&fork, 150).unwrap_err(),
+ ReplacementTermsError::Conflicted
+ );
+ let mut missing = values.clone();
+ missing.remove(0);
+ assert_eq!(
+ claim_at(&missing, 150).unwrap_err(),
+ ReplacementTermsError::MissingHistory
+ );
+}
+
+#[test]
+fn record_quota_counts_duplicates_and_never_returns_a_claim_from_an_oversized_scope() {
+ let values = fixture(false);
+ let mut records = values
+ .iter()
+ .map(|(i, value)| CausalRecord::new(id(*i), value))
+ .collect::<Vec<_>>();
+ records.resize(MAX_CAUSAL_RECORDS + 1, records[2]);
+ assert_eq!(
+ prepare_replacement_terms(
+ scope(),
+ selection(),
+ &records,
+ &[src(9000), SourceId::from_bytes([3; 32])],
+ &[],
+ time(150),
+ )
+ .unwrap_err(),
+ ReplacementTermsError::InvalidGraph
+ );
+}
+
+#[test]
+fn complete_scope_and_declared_digest_checks_do_not_authenticate_sources_or_mint_current_authority()
+{
+ let values = fixture(false);
+ let records = values
+ .iter()
+ .map(|(i, v)| CausalRecord::new(id(*i), v))
+ .collect::<Vec<_>>();
+ let foreign =
+ CausalScope::new(ThreadId::from_bytes([99; 32]), order(), buyer(), seller()).unwrap();
+ assert_eq!(
+ prepare_replacement_terms(foreign, selection(), &records, &[], &[], time(150)).unwrap_err(),
+ ReplacementTermsError::InvalidGraph
+ );
+ // These are deliberately caller-declared IDs/digests, not a signed carrier
+ // or a canonical hash proof. Native admission must independently prove both.
+ let selected = claim_at(&values, 150).unwrap();
+ assert_eq!(selected.selection().terms_digest(), digest(42));
+ assert_eq!(selected.base_commitment().authority().generation().get(), 1);
+ assert_eq!(selection().base_agreement(), id(1));
+ assert_eq!(selection().proposal(), id(2));
+ assert_eq!(selection().authorization(), id(3));
+ for error in [
+ ReplacementTermsError::InvalidGraph,
+ ReplacementTermsError::MissingHistory,
+ ReplacementTermsError::Conflicted,
+ ReplacementTermsError::Uninterpreted,
+ ReplacementTermsError::WrongBase,
+ ReplacementTermsError::WrongProposal,
+ ReplacementTermsError::WrongAuthorization,
+ ReplacementTermsError::TermsDigestMismatch,
+ ReplacementTermsError::Expired,
+ ReplacementTermsError::ClockAhead,
+ ReplacementTermsError::Withdrawn,
+ ReplacementTermsError::Rejected,
+ ReplacementTermsError::ConflictingAuthorizations,
+ ] {
+ assert!(error.to_string().len() < 80);
+ assert!(core::error::Error::source(&error).is_none());
+ }
+}
diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs
@@ -43,6 +43,7 @@ struct Policy {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StockAccounting {
+ replacement_terms_admission: ReplacementTermsAdmission,
native_inspection: NativeInspection,
value_owner: String,
scope: String,
@@ -59,6 +60,19 @@ struct StockAccounting {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
+struct ReplacementTermsAdmission {
+ owner: String,
+ scope: String,
+ complete_local_causal_coverage_required: bool,
+ conflicting_authorizations_require_reconciliation: bool,
+ native_canonical_digest_recompute_required: bool,
+ native_current_head_and_residual_required: bool,
+ claim_grants_current_authority: bool,
+ claim_creates_stock_effects: bool,
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
struct NativeCorrection {
catalog: u8,
selection: String,
@@ -764,6 +778,19 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> {
let p: Policy = serde_json::from_slice(raw)
.map_err(|_| "shared SDK contract: invalid closed JSON shape".to_owned())?;
let accounting = &p.stock_accounting;
+ let replacement = &accounting.replacement_terms_admission;
+ require(
+ replacement.owner == "radroots_domain.causal.prepare_replacement_terms"
+ && replacement.scope
+ == "explicit_existing_agreement_proposal_and_counterparty_authorization"
+ && replacement.complete_local_causal_coverage_required
+ && replacement.conflicting_authorizations_require_reconciliation
+ && replacement.native_canonical_digest_recompute_required
+ && replacement.native_current_head_and_residual_required
+ && !replacement.claim_grants_current_authority
+ && !replacement.claim_creates_stock_effects,
+ "replacement claim/native authority boundary policy drift",
+ )?;
let inspection = &accounting.native_inspection;
require(
inspection.model_owner == "radroots_storage.inventory.StockSnapshot"
@@ -1872,6 +1899,32 @@ mod tests {
}
#[test]
+ fn replacement_claims_require_native_digest_head_and_effect_revalidation() {
+ for (field, value) in [
+ ("owner", json!("application")),
+ ("scope", json!("latest_timestamp_wins")),
+ ("complete_local_causal_coverage_required", json!(false)),
+ (
+ "conflicting_authorizations_require_reconciliation",
+ json!(false),
+ ),
+ ("native_canonical_digest_recompute_required", json!(false)),
+ ("native_current_head_and_residual_required", json!(false)),
+ ("claim_grants_current_authority", json!(true)),
+ ("claim_creates_stock_effects", json!(true)),
+ ] {
+ assert!(
+ validate_bytes(&changed(
+ &format!("/stock_accounting/replacement_terms_admission/{field}"),
+ value,
+ ))
+ .is_err(),
+ "{field}"
+ );
+ }
+ }
+
+ #[test]
fn native_corrections_require_original_allocations_and_atomic_deficits() {
for (field, value) in [
("catalog", json!(18)),