clm-kernel 0.0.17

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Grothendieck Fibration Category: Process -> MCard.
//! Canonical Path: kernel/clm_rust_core/src/fiber/fibration.rs
//! Deliverable: DEL-254-01
//!
//! Formalizes the total category `Process = \int P` over the base category `MCard`.
//! Each object in Process is a pair `(M, F)` where:
//! - `M \in MCard`: Immutable spatial carrier resting state in content-addressed storage (CAS).
//! - `F \in Fiber(M)`: Active cordis execution fiber equipped with an unwinding stack of
//!   reversible side-effects (`DisposableList`).
//!
//! Cartesian Lifting:
//! Given an MCard mutation `f: M -> M'`, the Cartesian lift `lift(f): (M, F) -> (M', F')`
//! unwinds the active fiber's side-effects in strict reverse LIFO order, producing a clean
//! zero-residual state, before rebinding to the codomain `M'`.

use crate::domain::{MCard, PCardDefinition};
use crate::fiber::disposable::DisposableList;
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};

/// Error types occurring during fibration operations or cartesian lifting.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FibrationError {
    DisposableUnwindError(Vec<String>),
    LockError(String),
    AxiomViolation(String),
    CarrierMismatch(String),
}

impl std::fmt::Display for FibrationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::DisposableUnwindError(errs) => {
                write!(f, "Fibration LIFO unwinding failed: {}", errs.join("; "))
            }
            Self::LockError(msg) => write!(f, "Fibration lock error: {}", msg),
            Self::AxiomViolation(msg) => write!(f, "Fibration axiom violation: {}", msg),
            Self::CarrierMismatch(msg) => write!(f, "Fibration carrier mismatch: {}", msg),
        }
    }
}

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

/// The Grothendieck Fibration trait \pi: Process -> MCard.
pub trait Fibration<M = MCard, P = PCardDefinition>: Send + Sync {
    /// Projection functor \pi(M, F) = M.
    /// Maps an active process object to its immutable carrier MCard resting state.
    fn project(&self) -> &M;

    /// Returns the handle pointer for this process (if bound).
    fn carrier_handle(&self) -> Option<&str>;

    /// Executes the Cartesian lift of an MCard mutation f: M -> M'.
    /// Unwinds existing fiber disposables in strict LIFO order, then updates the carrier.
    fn lift_mutation(&mut self, next_carrier: M) -> Result<(), FibrationError>;

    /// Executes Cartesian lift of an alpha-conversion / handle rebinding.
    fn lift_handle_rebind(&mut self, new_handle: impl Into<String>) -> Result<(), FibrationError>;
}

/// An object in the Total Category Process (\int P).
/// Represents the coupled pair (M, F) with thread-safe execution fiber state.
#[derive(Clone)]
pub struct ProcessObject<M = MCard, P = PCardDefinition> {
    /// Immutable carrier MCard resting state.
    pub carrier: M,
    /// Optional handle pointer (e.g. "assets:notes.txt").
    pub carrier_handle: Option<String>,
    /// Thread-safe stack of reversible side-effects for zero residual state.
    pub disposables: Arc<Mutex<DisposableList>>,
    /// Optional PCard definition governing execution rules.
    pub pcard: Option<P>,
    /// Millisecond timestamp of process creation.
    pub created_at: u64,
    /// Whether the fiber is currently active.
    pub is_active: bool,
}

impl<M> ProcessObject<M, PCardDefinition> {
    /// Constructs a new ProcessObject coupled with an empty disposable stack.
    pub fn new(carrier: M) -> Self {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0);

        Self {
            carrier,
            carrier_handle: None,
            disposables: Arc::new(Mutex::new(DisposableList::new())),
            pcard: None,
            created_at: now,
            is_active: true,
        }
    }
}

impl<M, P> ProcessObject<M, P> {
    /// Constructs a ProcessObject with an explicit PCard.
    pub fn new_with_pcard(carrier: M, pcard: P) -> Self {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0);

        Self {
            carrier,
            carrier_handle: None,
            disposables: Arc::new(Mutex::new(DisposableList::new())),
            pcard: Some(pcard),
            created_at: now,
            is_active: true,
        }
    }

    /// Binds an initial handle pointer.
    pub fn with_handle(mut self, handle: impl Into<String>) -> Self {
        self.carrier_handle = Some(handle.into());
        self
    }

    /// Attaches an executable PCard definition.
    pub fn with_pcard(mut self, pcard: P) -> Self {
        self.pcard = Some(pcard);
        self
    }

    /// Registers a reversible cleanup callback onto the fiber's LIFO stack.
    pub fn register_disposable<F>(&self, cleanup: F) -> Result<(), FibrationError>
    where
        F: FnOnce() -> Result<(), String> + Send + 'static,
    {
        let mut list = self
            .disposables
            .lock()
            .map_err(|e| FibrationError::LockError(e.to_string()))?;
        list.push(cleanup);
        Ok(())
    }

    /// Returns the number of registered disposers awaiting unwinding.
    pub fn pending_disposers_count(&self) -> Result<usize, FibrationError> {
        let list = self
            .disposables
            .lock()
            .map_err(|e| FibrationError::LockError(e.to_string()))?;
        Ok(list.len())
    }

    /// Unwinds all registered disposers in strict LIFO order.
    pub fn unwind(&self) -> Result<(), FibrationError> {
        let mut list = self
            .disposables
            .lock()
            .map_err(|e| FibrationError::LockError(e.to_string()))?;
        let active_list = std::mem::take(&mut *list);
        active_list
            .dispose()
            .map_err(FibrationError::DisposableUnwindError)
    }
}

impl<M: Send + Sync, P: Send + Sync> Fibration<M, P> for ProcessObject<M, P> {
    fn project(&self) -> &M {
        &self.carrier
    }

    fn carrier_handle(&self) -> Option<&str> {
        self.carrier_handle.as_deref()
    }

    fn lift_mutation(&mut self, next_carrier: M) -> Result<(), FibrationError> {
        // Step 1: Unwind all fiber disposables in strict LIFO order
        self.unwind()?;

        // Step 2: Rebind carrier resting state
        self.carrier = next_carrier;

        // Step 3: Re-arm clean disposable list
        let mut list = self
            .disposables
            .lock()
            .map_err(|e| FibrationError::LockError(e.to_string()))?;
        *list = DisposableList::new();
        self.is_active = true;

        Ok(())
    }

    fn lift_handle_rebind(&mut self, new_handle: impl Into<String>) -> Result<(), FibrationError> {
        self.carrier_handle = Some(new_handle.into());
        Ok(())
    }
}

/// Cartesian Lift Engine verifying Grothendieck fibration category laws.
pub struct CartesianLiftEngine;

impl CartesianLiftEngine {
    /// Lifts mutation f: M -> M' on a process object.
    pub fn lift_mutation<M: Send + Sync, P: Send + Sync>(
        process: &mut ProcessObject<M, P>,
        next_carrier: M,
    ) -> Result<(), FibrationError> {
        process.lift_mutation(next_carrier)
    }

    /// Lifts alpha-conversion handle rebind.
    pub fn lift_handle_rebind<M: Send + Sync, P: Send + Sync>(
        process: &mut ProcessObject<M, P>,
        new_handle: impl Into<String>,
    ) -> Result<(), FibrationError> {
        process.lift_handle_rebind(new_handle)
    }
}

/// Validates Grothendieck fibration axioms:
/// 1. Base Projection Commutativity: \pi(lift(f)) == cod(f).
/// 2. Zero Residual State: Fiber disposables after lift == 0.
pub fn verify_fibration_axioms<M: PartialEq + Send + Sync, P: Send + Sync>(
    initial: &ProcessObject<M, P>,
    lifted: &ProcessObject<M, P>,
    target_carrier: &M,
) -> Result<(), FibrationError> {
    // Axiom 1: Base projection commutativity
    if lifted.project() != target_carrier {
        return Err(FibrationError::AxiomViolation(
            "Projection commutativity failed: pi(lift(f)) != cod(f)".to_string(),
        ));
    }

    // Axiom 2: Zero residual state after mutation lift
    if lifted.pending_disposers_count()? != 0 {
        return Err(FibrationError::AxiomViolation(
            "Zero-residual state failed: lifted fiber retained pending disposers".to_string(),
        ));
    }

    // Verify initial is unaffected
    let _ = initial.project();

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::{MCard, MCardPayload};
    use crate::types::AgentDid;

    #[test]
    fn test_fibration_projection_and_lifo_unwind() {
        let author = AgentDid::new("did:key:alice").unwrap();
        let card1 = MCard::new(
            "mcard:test/1",
            MCardPayload::Text("Initial".to_string()),
            author.clone(),
            1,
        );
        let card2 = MCard::new(
            "mcard:test/2",
            MCardPayload::Text("Updated".to_string()),
            author,
            2,
        );

        let mut process = ProcessObject::new(card1.clone()).with_handle("assets:doc.md");

        // Verify initial projection \pi(M, F) = M
        assert_eq!(process.project().uri, "mcard:test/1");
        assert_eq!(process.carrier_handle(), Some("assets:doc.md"));

        // Register 3 disposables that push their indices into an unwinding log
        let log = Arc::new(Mutex::new(Vec::new()));
        let log1 = log.clone();
        let log2 = log.clone();
        let log3 = log.clone();

        process
            .register_disposable(move || {
                log1.lock().unwrap().push(1);
                Ok(())
            })
            .unwrap();

        process
            .register_disposable(move || {
                log2.lock().unwrap().push(2);
                Ok(())
            })
            .unwrap();

        process
            .register_disposable(move || {
                log3.lock().unwrap().push(3);
                Ok(())
            })
            .unwrap();

        assert_eq!(process.pending_disposers_count().unwrap(), 3);

        // Execute Cartesian lift of mutation f: card1 -> card2
        process.lift_mutation(card2.clone()).unwrap();

        // 1. Verify projection commutativity: \pi(lift(f)) == card2
        assert_eq!(process.project().uri, "mcard:test/2");

        // 2. Verify strict LIFO unwinding order [3, 2, 1]
        let recorded = log.lock().unwrap().clone();
        assert_eq!(recorded, vec![3, 2, 1], "Unwinding order must be strict reverse LIFO");

        // 3. Verify zero residual state in fiber
        assert_eq!(process.pending_disposers_count().unwrap(), 0);

        // Test axiom verification helper
        verify_fibration_axioms(&ProcessObject::new(card1), &process, &card2).unwrap();
    }

    #[test]
    fn test_handle_rebinding() {
        let author = AgentDid::new("did:key:alice").unwrap();
        let card = MCard::new(
            "mcard:test/rebind",
            MCardPayload::Text("Hello".to_string()),
            author,
            1,
        );

        let mut process = ProcessObject::new(card);
        assert_eq!(process.carrier_handle(), None);

        process.lift_handle_rebind("assets:renamed.txt").unwrap();
        assert_eq!(process.carrier_handle(), Some("assets:renamed.txt"));
    }
}