clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use std::collections::HashMap;
use super::types::TransitionYaml;

/// Post-transition sheaf gluing check: verify that concurrent writes to overlapping
/// output places are cohomologically consistent. If the transition's output places
/// overlap with places that already have markings from a prior concurrent transition,
/// detect conflicts.
pub fn check_transition_sheaf_gluing(
    t: &TransitionYaml,
    place_colors: &HashMap<String, String>,
    final_content: &str,
    per_trans_agent_did: &str,
    db_conn: &rusqlite::Connection,
) -> Result<(), String> {
    if t.outputs.len() > 1 {
        let output_open_set = crate::sheaf::OpenSet::from_places(
            t.outputs.iter().map(|id| crate::sheaf::Place::new(id.clone())),
        );
        let mut output_marking = crate::sheaf::Marking::new();
        for outp in &t.outputs {
            if let Some(col) = place_colors.get(outp)
                && !col.is_empty() {
                    output_marking = output_marking.with_token(outp, col);
                }
        }
        let new_section = crate::sheaf::Section::new(
            output_open_set.clone(),
            output_marking.with_token(&t.outputs[0], final_content),
        );

        // Build a section from the current place markings for
        // the same output places (the "prior" state).
        let mut prior_marking = crate::sheaf::Marking::new();
        for outp in &t.outputs {
            if let Some(col) = place_colors.get(outp)
                && !col.is_empty() && col != final_content {
                    prior_marking = prior_marking.with_token(outp, col);
                }
        }
        if !prior_marking.by_place.is_empty() {
            let prior_section = crate::sheaf::Section::new(
                output_open_set.clone(),
                prior_marking,
            );
            let sheaf = crate::sheaf::Sheaf::new();
            let cover = vec![output_open_set.clone(), output_open_set.clone()];
            if let Err(ref e) = sheaf.gluing_check(
                &[prior_section, new_section],
                &cover,
            ) {
                let report = crate::sheaf::CohomologyConflictReport::from_error(
                    e,
                    vec![per_trans_agent_did.to_string()],
                );
                if let Some(ref r) = report {
                    let _ = crate::sheaf::store_conflict_report(r, db_conn);
                    eprintln!("[VM] COHOMOLOGICAL_OBSTRUCTION: {}", r.to_yaml());
                }
                return Err(format!(
                    "COHOMOLOGICAL_OBSTRUCTION: transition {} produced inconsistent state on overlapping places",
                    t.id
                ));
            }
        }
    }
    Ok(())
}