clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Wire frame, outbox port, and Petri gate result types for Layer 2 MCard sync.

use crate::layer0::vocabulary::{HASH_PREFIX_BLAKE3};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;

pub const SYNC_CONTRACT_VERSION: &str = "v1";

pub(crate) const TERMINAL_ERROR_CODES: &[&str] =
    &["declared-mismatch", "signed-bad", "algorithm-downgrade", "malformed"];

pub(crate) fn kind_to_lifecycle(kind: &str) -> Option<&'static str> {
    match kind {
        "CREATE" => Some("t_create"),
        "UPDATE" => Some("t_update"),
        "SEAL" => Some("t_seal"),
        "RELOCATE" => Some("t_relocate_out"),
        "ROTATE" => Some("t_rotate"),
        "TOMBSTONE" => Some("t_tombstone"),
        "SEED" => Some("t_seed"),
        "FORK" => Some("t_fork"),
        "PIN" => Some("t_pin"),
        "CONFLICT_BRANCH" => Some("t_conflict_branch"),
        _ => None,
    }
}

pub(crate) fn normalize_qualified_hash(hash: &str) -> String {
    if hash.contains(':') { hash.to_string() } else { format!("{HASH_PREFIX_BLAKE3}{hash}") }
}

#[derive(Debug)]
pub struct SyncContractError {
    pub error_code: String,
    pub reason: String,
}

impl SyncContractError {
    /// Constructs a structured sync contract error from a canonical code and reason.
    pub fn new(error_code: &str, reason: impl Into<String>) -> Self {
        Self { error_code: error_code.to_string(), reason: reason.into() }
    }
}

impl fmt::Display for SyncContractError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.error_code, self.reason)
    }
}

impl std::error::Error for SyncContractError {}

/// Durable storage port for loading and saving per-node sync outbox entries.
pub trait SyncOutboxPort: Send + Sync {
    fn load_outbox(&self) -> Result<Vec<SyncOutboxEntry>, String>;
    fn save_outbox(&self, entries: &[SyncOutboxEntry]) -> Result<(), String>;
}

/// Wire transport port for delivering framed MCard record batches to a peer node.
pub trait SyncFrameTransport: Send + Sync {
    fn send_transfer(
        &self,
        attempt: &TransferAttempt,
        records: &[RecordFrame],
    ) -> Result<TransferSendResult, String>;
}

pub use crate::layer0::transition::{CHANGE_CALCULUS, TransitionPayload};

pub use crate::layer0::mcard_record::MCardRecord;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecordFrame {
    pub hash: String,
    pub content_base64: String,
    pub g_time: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncPageCursor {
    pub offset: usize,
    pub last_hash: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FramedRecordPage {
    pub records: Vec<RecordFrame>,
    pub next_cursor: Option<SyncPageCursor>,
    pub has_more: bool,
    pub total_bytes: usize,
}


#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransitionGateResult {
    pub enabled: bool,
    pub transition_id: String,
    pub pre_marking: BTreeMap<String, i64>,
    pub post_marking: BTreeMap<String, i64>,
    pub pre_state_hash: String,
    pub post_state_hash: String,
    pub error_code: Option<String>,
    pub reason: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncOutboxEntry {
    pub transfer_id: String,
    pub delivery_id: String,
    pub target_node_id: String,
    pub status: String,
    pub attempt_count: u32,
    pub records: Vec<RecordFrame>,
    pub transitions: Vec<TransitionPayload>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prior_transfer_id: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransferAttempt {
    pub transfer_id: String,
    pub delivery_id: String,
    pub source_node_id: String,
    pub target_node_id: String,
    pub record_hashes: Vec<String>,
    pub transitions: Vec<TransitionPayload>,
    pub attempt_count: u32,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransferSendResult {
    pub ok: bool,
    pub committed: bool,
    pub replayed: bool,
    pub transient: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReceiveOutcome {
    pub ok: bool,
    pub committed: bool,
    pub replayed: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RetryOutcome {
    pub ok: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entry: Option<SyncOutboxEntry>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}