clm-kernel 0.0.22

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Contract parameters as `PrimitivePCard` tokens under Function-Number Duality (INV-597).
//!
//! A parameter value of type `tau_p` is the constant morphism `1 -> tau_p`: it reifies to the
//! `TokenMCard` bound at `urn:mcard:mcard:contract:param:<key>` and reflects back unchanged. A
//! `ParameterContext` is the contract `NetMCard` whose marking holds one token per parameter; its
//! digest is the context's identity, and the default context must digest to `CONTRACT_NET_DIGEST`.

use std::collections::BTreeMap;

use serde_json::Value;

use crate::cpn::mcard_token::{reflect_mcard_to_pcard, reify_pcard_to_mcard, NetMCard, PrimitiveConstant, TokenMCard};
use crate::layer0::parameter_context::{ParameterContext, ParameterValue, CONTRACT_NET_DIGEST, PARAMETER_TYPES};
use crate::layer0::vocabulary::{HANDLE_CONTRACT_PARAM, HANDLE_CONTRACT_RUNTIME, HANDLE_VCARD_CONTRACT_PARAM};
use crate::layer0::vocabulary_types::TYPE_URI_PARAM;

/// Why a parameter card could not be reified, reflected, or verified.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ParameterCardError {
    /// The key names no contract parameter.
    UnknownParameter(String),
    /// The token is not bound under `urn:mcard:mcard:contract:param:`.
    ForeignToken(String),
    /// The token's type URI is not the parameter's refinement type.
    WrongType { key: String, found: String },
    /// The recomputed contract `NetMCard` digest differs from the compiled-in seed.
    DigestMismatch(String),
    /// The token envelope could not be built.
    Reify(String),
}

impl std::fmt::Display for ParameterCardError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}

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

/// `urn:mcard:mcard:contract:param:<key>`, the handle that binds the parameter's card.
pub fn parameter_handle(key: &str) -> String {
    HANDLE_CONTRACT_PARAM.to_string() + key
}

/// `urn:vcard:contract:param:<key>`, the VCard that guards the parameter's refinement.
pub fn parameter_vcard_handle(key: &str) -> String {
    HANDLE_VCARD_CONTRACT_PARAM.to_string() + key
}

fn type_uri(key: &str) -> Result<String, ParameterCardError> {
    PARAMETER_TYPES
        .iter()
        .find(|(name, _)| *name == key)
        .map(|(_, base)| TYPE_URI_PARAM.to_string() + base)
        .ok_or_else(|| ParameterCardError::UnknownParameter(key.to_string()))
}

fn json_value(value: &ParameterValue) -> Value {
    match value {
        ParameterValue::Int(number) => Value::from(*number),
        ParameterValue::Text(text) => Value::from(text.clone()),
        ParameterValue::Bool(flag) => Value::from(*flag),
    }
}

/// Phi: the parameter as the `TokenMCard` bound at its handle.
pub fn reify_parameter(key: &str, value: &ParameterValue) -> Result<TokenMCard, ParameterCardError> {
    let pcard = PrimitiveConstant { constant_value: json_value(value), output_type: type_uri(key)? };
    reify_pcard_to_mcard(&pcard, &parameter_handle(key), None, None).map_err(ParameterCardError::Reify)
}

/// Psi: `(key, value)` from a parameter `TokenMCard`; rejects any other token.
pub fn reflect_parameter(token: &TokenMCard) -> Result<(String, Value), ParameterCardError> {
    let key = token
        .token_id
        .strip_prefix(HANDLE_CONTRACT_PARAM)
        .ok_or_else(|| ParameterCardError::ForeignToken(token.token_id.clone()))?;
    let pcard = reflect_mcard_to_pcard(token);
    if pcard.output_type != type_uri(key)? {
        return Err(ParameterCardError::WrongType { key: key.to_string(), found: pcard.output_type });
    }
    Ok((key.to_string(), pcard.constant_value))
}

/// The contract `NetMCard`: each parameter handle marks the token of its resolved value.
pub fn contract_net_mcard(context: &ParameterContext) -> Result<NetMCard, ParameterCardError> {
    let mut marking = BTreeMap::new();
    for (key, value) in context.as_mapping() {
        marking.insert(parameter_handle(key), vec![reify_parameter(key, &value)?]);
    }
    NetMCard::create(HANDLE_CONTRACT_RUNTIME, Vec::new(), Vec::new(), marking, None, None).map_err(ParameterCardError::Reify)
}

/// BLAKE3 digest of the context's contract `NetMCard`; the defaults hash to `CONTRACT_NET_DIGEST`.
pub fn parameter_context_hash(context: &ParameterContext) -> Result<String, ParameterCardError> {
    Ok(contract_net_mcard(context)?.card.hash.clone())
}

/// Recompute the default contract `NetMCard` and require the compiled-in digest (process bootstrap).
pub fn verify_contract_digest() -> Result<String, ParameterCardError> {
    let digest = parameter_context_hash(&ParameterContext::default())?;
    if digest != CONTRACT_NET_DIGEST {
        return Err(ParameterCardError::DigestMismatch(digest));
    }
    Ok(digest)
}