clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
#![allow(unused_imports)]
use crate::layer0::vocabulary::{HASH_PREFIX_BLAKE3};
use super::*;

/// Receipt fields and gate ids that the Hoare dispatcher writes more than once (each named once here).
const STATUS_COMMITTED: &str = "committed";
const WITNESS_POST_ROLLBACK: &str = "post_rollback_witness";
const GATE_PAYLOAD_NONEMPTY: &str = "gate:payload_nonempty";
const GATE_TRUE: &str = "gate:true";
const GATE_HASH_MATCHES: &str = "gate:hash_matches";
const GATE_DB_ACCESSIBLE: &str = "gate:db_accessible";
const GATE_UNNAMED: &str = "gate";

fn payload_variables(value: &str) -> serde_json::Value {
    match serde_json::from_str::<serde_json::Value>(value) {
        Ok(obj @ serde_json::Value::Object(_)) => obj,
        _ => serde_json::Value::Object(serde_json::Map::new()),
    }
}

impl CoreDispatchRegistry {
    fn evaluate_hoare_gate(
        &self,
        gate: Option<&str>,
        value: &str,
        input_payload: &str,
        stores: Option<&Vec<(&str, Arc<Mutex<Connection>>)>>,
    ) -> bool {
        let Some(gate_expr) = gate else {
            return true;
        };
        if let Some(custom) = self.state.lock().unwrap().host_gates.get(gate_expr).cloned() {
            return custom(value, input_payload, stores.is_some());
        }
        match gate_expr {
            GATE_TRUE => true,
            GATE_PAYLOAD_NONEMPTY => !value.trim().is_empty(),
            GATE_HASH_MATCHES => {
                let expected = format!("{HASH_PREFIX_BLAKE3}{}", blake3::hash(input_payload.as_bytes()).to_hex());
                value == expected
            }
            GATE_DB_ACCESSIBLE => match stores {
                None => true,
                Some(conns) => conns.iter().all(|(_label, conn)| {
                    conn.lock().ok().is_some_and(|c| c.is_readonly(rusqlite::DatabaseName::Main).is_ok())
                }),
            },
            expr => {
                let ctx_json = payload_variables(value);
                let verdict = crate::layer1::guard_semantics::evaluate_guard(expr, &ctx_json);
                verdict.outcome() == crate::layer0::vocabulary::GUARD_OUTCOME_PASS
            }
        }
    }
    pub fn list_core_op_ids(&self) -> Vec<String> {
        let st = self.state.lock().unwrap();
        st.core_entries.keys().cloned().collect()
    }

    pub fn list_all_op_ids(&self) -> Vec<String> {
        let st = self.state.lock().unwrap();
        let mut keys: Vec<String> = st
            .core_entries
            .keys()
            .chain(st.plugin_entries.keys())
            .cloned()
            .collect();
        keys.sort();
        keys.dedup();
        keys
    }

    pub fn export_canonical_catalog_json(&self) -> String {
        let st = self.state.lock().unwrap();
        let entries: Vec<DispatchCatalogEntry> = st.core_entries.values().cloned().collect();
        let doc = DispatchCatalogDoc {
            catalog_version: CATALOG_VERSION.to_string(),
            entries,
            schema: CATALOG_SCHEMA_REF.to_string(),
        };
        let mut out = serde_json::to_string_pretty(&doc).expect("serialize catalog");
        out.push('\n');
        out
    }

    pub fn catalog_blake3_hash(&self) -> String {
        let json = self.export_canonical_catalog_json();
        format!("{HASH_PREFIX_BLAKE3}{}", blake3::hash(json.as_bytes()).to_hex())
    }

    pub fn dispatch_legacy_route(
        &self,
        route: &str,
        payload: &str,
        ctx: &CLMContext,
    ) -> LegacyDispatchResult {
        let bound = self.resolve_entry(route)
            .ok_or_else(|| DispatchError::NotFound(route.to_string()))
            .and_then(|entry| self.bound_handler(&entry.op_id));
        let handler = match bound {
            Ok(handler) => handler,
            Err(error) => {
                return LegacyDispatchResult { exit_code: error.exit_code(), output: String::new(), error: Some(error.to_string()) };
            }
        };
        let output = handler(ctx, payload);
        LegacyDispatchResult {
            exit_code: ClmExitCode::Ok as i32,
            output,
            error: None,
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub fn dispatch_with_hoare(
        &self,
        op_id_or_route: &str,
        payload: &str,
        ctx: &CLMContext,
        stores: Option<Vec<(&str, Arc<Mutex<Connection>>)>>,
        simulate_post_failure: bool,
        receipt_id: &str,
        idempotency_key: &str,
        g_time: &str,
    ) -> Result<HoareDispatchResult, DispatchError> {
        let entry = self.resolve_entry(op_id_or_route).ok_or_else(|| DispatchError::NotFound(op_id_or_route.to_string()))?;
        // An unbound id halts here, before any receipt is minted.
        let handler = self.bound_handler(&entry.op_id)?;

        let input_hash = format!("{HASH_PREFIX_BLAKE3}{}", blake3::hash(payload.as_bytes()).to_hex());

        if entry.verification_policy != "required" {
            let output = handler(ctx, payload);
            let output_hash = Some(format!(
                "{HASH_PREFIX_BLAKE3}{}",
                blake3::hash(output.as_bytes()).to_hex()
            ));
            let receipt = ExecutionReceipt::build(ExecutionReceiptWithoutHash {
                agent_did: ctx.agent_did().to_string(),
                dispatch_catalog_hash: None,
                error: None,
                exit_code: ClmExitCode::Ok as i32,
                g_time: g_time.to_string(),
                handler_key: entry.handler_key,
                idempotency_key: idempotency_key.to_string(),
                input_hash,
                op_id: entry.op_id,
                output_hash,
                parameter_context_hash: None,
                receipt_id: receipt_id.to_string(),
                schema_version: RECEIPT_SCHEMA_VERSION.to_string(),
                status: STATUS_COMMITTED.to_string(),
                witness_policy: "none".to_string(),
            });
            return Ok(HoareDispatchResult {
                exit_code: ClmExitCode::Ok as i32,
                output,
                handler_called: true,
                receipt,
            });
        }

        let sp_name = format!("sp_hoare_{}", receipt_id.replace('-', "_"));
        let mut guard = match stores.as_ref() {
            Some(conns) => Some(TriDbSavepointGuard::with_connections(
                &sp_name,
                conns.clone(),
            )?),
            None => None,
        };

        // 1. Precondition check (V_pre)
        if !self.evaluate_hoare_gate(entry.pre_gate.as_deref(), payload, payload, stores.as_ref())
        {
            if let Some(mut g) = guard.take() {
                let _ = g.rollback();
            }
            let receipt = ExecutionReceipt::build(ExecutionReceiptWithoutHash {
                agent_did: ctx.agent_did().to_string(),
                dispatch_catalog_hash: None,
                error: Some(ReceiptError {
                    code: ClmExitCode::PreconditionOrBoundaryViolation as i32,
                    message: format!(
                        "Precondition {} failed: empty payload",
                        entry.pre_gate.as_deref().unwrap_or(GATE_UNNAMED)
                    ),
                    phase: "precondition".to_string(),
                }),
                exit_code: ClmExitCode::PreconditionOrBoundaryViolation as i32,
                g_time: g_time.to_string(),
                handler_key: entry.handler_key,
                idempotency_key: idempotency_key.to_string(),
                input_hash,
                op_id: entry.op_id,
                output_hash: None,
                parameter_context_hash: None,
                receipt_id: receipt_id.to_string(),
                schema_version: RECEIPT_SCHEMA_VERSION.to_string(),
                status: "precondition_failed".to_string(),
                witness_policy: WITNESS_POST_ROLLBACK.to_string(),
            });
            if let Some(ref conns) = stores {
                for (label, conn) in conns {
                    if *label == crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG {
                        let c = conn.lock().unwrap();
                        crate::layer2::record_store::store_named_content(&c, &format!("witness:{}", receipt.receipt_id),
                            &serde_json::to_vec(&receipt).map_err(|e| DispatchError::Store(e.to_string()))?)?;
                    }
                }
            }
            return Ok(HoareDispatchResult {
                exit_code: ClmExitCode::PreconditionOrBoundaryViolation as i32,
                output: String::new(),
                handler_called: false,
                receipt,
            });
        }

        // 2. Handler execution (PCard)
        let output = handler(ctx, payload);
        if let Some(ref conns) = stores {
            for (label, conn) in conns {
                if *label == crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY {
                    let c = conn.lock().unwrap();
                    crate::layer2::record_store::store_named_content(&c, "card_memorized", output.as_bytes())?;
                } else if *label == crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG {
                    let c = conn.lock().unwrap();
                    crate::layer2::record_store::store_named_content(&c, "log_in_tx", output.as_bytes())?;
                }
            }
        }

        // 3. Postcondition check (V_post)
        if simulate_post_failure
            || !self.evaluate_hoare_gate(entry.post_gate.as_deref(), &output, payload, stores.as_ref())
        {
            if let Some(mut g) = guard.take() {
                let _ = g.rollback();
            }
            let receipt = ExecutionReceipt::build(ExecutionReceiptWithoutHash {
                agent_did: ctx.agent_did().to_string(),
                dispatch_catalog_hash: None,
                error: Some(ReceiptError {
                    code: ClmExitCode::PostconditionOrCycleViolation as i32,
                    message: format!(
                        "Postcondition {} failed: digest mismatch",
                        entry.post_gate.as_deref().unwrap_or(GATE_UNNAMED)
                    ),
                    phase: "postcondition".to_string(),
                }),
                exit_code: ClmExitCode::PostconditionOrCycleViolation as i32,
                g_time: g_time.to_string(),
                handler_key: entry.handler_key,
                idempotency_key: idempotency_key.to_string(),
                input_hash,
                op_id: entry.op_id,
                output_hash: None,
                parameter_context_hash: None,
                receipt_id: receipt_id.to_string(),
                schema_version: RECEIPT_SCHEMA_VERSION.to_string(),
                status: "postcondition_failed".to_string(),
                witness_policy: WITNESS_POST_ROLLBACK.to_string(),
            });
            if let Some(ref conns) = stores {
                for (label, conn) in conns {
                    if *label == crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG {
                        let c = conn.lock().unwrap();
                        crate::layer2::record_store::store_named_content(&c, &format!("witness:{}", receipt.receipt_id),
                            &serde_json::to_vec(&receipt).map_err(|e| DispatchError::Store(e.to_string()))?)?;
                    }
                }
            }
            return Ok(HoareDispatchResult {
                exit_code: ClmExitCode::PostconditionOrCycleViolation as i32,
                output: String::new(),
                handler_called: true,
                receipt,
            });
        }

        // 4. Success: write receipt in-transaction and commit savepoint
        let output_hash = Some(format!(
            "{HASH_PREFIX_BLAKE3}{}",
            blake3::hash(output.as_bytes()).to_hex()
        ));
        let receipt = ExecutionReceipt::build(ExecutionReceiptWithoutHash {
            agent_did: ctx.agent_did().to_string(),
            dispatch_catalog_hash: None,
            error: None,
            exit_code: ClmExitCode::Ok as i32,
            g_time: g_time.to_string(),
            handler_key: entry.handler_key,
            idempotency_key: idempotency_key.to_string(),
            input_hash,
            op_id: entry.op_id,
            output_hash,
            parameter_context_hash: None,
            receipt_id: receipt_id.to_string(),
            schema_version: RECEIPT_SCHEMA_VERSION.to_string(),
            status: STATUS_COMMITTED.to_string(),
            witness_policy: "in_transaction".to_string(),
        });
        if let Some(ref conns) = stores {
            for (label, conn) in conns {
                if *label == crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG {
                    let c = conn.lock().unwrap();
                    crate::layer2::record_store::store_named_content(&c, &format!("receipt:{}", receipt.idempotency_key),
                            &serde_json::to_vec(&receipt).map_err(|e| DispatchError::Store(e.to_string()))?)?;
                }
            }
        }
        if let Some(mut g) = guard.take() {
            g.commit()?;
        }

        Ok(HoareDispatchResult {
            exit_code: ClmExitCode::Ok as i32,
            output,
            handler_called: true,
            receipt,
        })
    }
}