clm-kernel 0.0.9

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

impl CoreDispatchRegistry {
    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!("blake3:{}", blake3::hash(json.as_bytes()).to_hex())
    }

    pub fn dispatch_legacy_route(
        &self,
        route: &str,
        payload: &str,
        ctx: &CLMContext,
    ) -> LegacyDispatchResult {
        let Some(entry) = self.resolve_entry(route) else {
            return LegacyDispatchResult {
                exit_code: ClmExitCode::ContentMissing as i32,
                output: String::new(),
                error: Some(format!("OperationNotFoundError: {}", route)),
            };
        };
        let handler = {
            let st = self.state.lock().unwrap();
            st.handlers.get(&entry.op_id).cloned()
        };
        let output = handler.map(|h| h(ctx, payload)).unwrap_or_default();
        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, String> {
        let Some(entry) = self.resolve_entry(op_id_or_route) else {
            return Err(format!("OperationNotFoundError: {}", op_id_or_route));
        };
        let handler = {
            let st = self.state.lock().unwrap();
            st.handlers
                .get(&entry.op_id)
                .cloned()
                .ok_or_else(|| format!("Missing handler for {}", entry.op_id))?
        };

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

        if entry.verification_policy != "required" {
            let output = handler(ctx, payload);
            let output_hash = Some(format!(
                "blake3:{}",
                blake3::hash(output.as_bytes()).to_hex()
            ));
            let receipt = ExecutionReceipt::build(ExecutionReceiptWithoutHash {
                agent_did: ctx.agent_did().to_string(),
                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,
                receipt_id: receipt_id.to_string(),
                schema_version: RECEIPT_SCHEMA_VERSION.to_string(),
                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 entry.pre_gate.as_deref() == Some("gate:payload_nonempty") && payload.trim().is_empty()
        {
            if let Some(mut g) = guard.take() {
                let _ = g.rollback();
            }
            let receipt = ExecutionReceipt::build(ExecutionReceiptWithoutHash {
                agent_did: ctx.agent_did().to_string(),
                error: Some(ReceiptError {
                    code: ClmExitCode::PreconditionOrBoundaryViolation as i32,
                    message: format!(
                        "Precondition {} failed: empty payload",
                        entry.pre_gate.as_deref().unwrap_or("gate")
                    ),
                    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,
                receipt_id: receipt_id.to_string(),
                schema_version: RECEIPT_SCHEMA_VERSION.to_string(),
                status: "precondition_failed".to_string(),
                witness_policy: "post_rollback_witness".to_string(),
            });
            if let Some(ref conns) = stores {
                for (label, conn) in conns {
                    if *label == "execution_log" {
                        let c = conn.lock().unwrap();
                        let _ = c.execute(
                            "INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3);",
                            params![
                                format!("witness:{}", receipt.receipt_id),
                                serde_json::to_vec(&receipt).unwrap_or_default(),
                                g_time
                            ],
                        );
                    }
                }
            }
            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 == "content_memory" {
                    let c = conn.lock().unwrap();
                    let _ = c.execute(
                        "INSERT OR REPLACE INTO card (hash, content, g_time) VALUES ('card_memorized', ?1, ?2);",
                        params![output.as_bytes(), g_time],
                    );
                } else if *label == "execution_log" {
                    let c = conn.lock().unwrap();
                    let _ = c.execute(
                        "INSERT OR REPLACE INTO card (hash, content, g_time) VALUES ('log_in_tx', ?1, ?2);",
                        params![output.as_bytes(), g_time],
                    );
                }
            }
        }

        // 3. Postcondition check (V_post)
        if simulate_post_failure
            || (entry.post_gate.as_deref() == Some("gate:payload_nonempty")
                && output.trim().is_empty())
        {
            if let Some(mut g) = guard.take() {
                let _ = g.rollback();
            }
            let receipt = ExecutionReceipt::build(ExecutionReceiptWithoutHash {
                agent_did: ctx.agent_did().to_string(),
                error: Some(ReceiptError {
                    code: ClmExitCode::PostconditionOrCycleViolation as i32,
                    message: format!(
                        "Postcondition {} failed: digest mismatch",
                        entry.post_gate.as_deref().unwrap_or("gate")
                    ),
                    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,
                receipt_id: receipt_id.to_string(),
                schema_version: RECEIPT_SCHEMA_VERSION.to_string(),
                status: "postcondition_failed".to_string(),
                witness_policy: "post_rollback_witness".to_string(),
            });
            if let Some(ref conns) = stores {
                for (label, conn) in conns {
                    if *label == "execution_log" {
                        let c = conn.lock().unwrap();
                        let _ = c.execute(
                            "INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3);",
                            params![
                                format!("witness:{}", receipt.receipt_id),
                                serde_json::to_vec(&receipt).unwrap_or_default(),
                                g_time
                            ],
                        );
                    }
                }
            }
            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!(
            "blake3:{}",
            blake3::hash(output.as_bytes()).to_hex()
        ));
        let receipt = ExecutionReceipt::build(ExecutionReceiptWithoutHash {
            agent_did: ctx.agent_did().to_string(),
            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,
            receipt_id: receipt_id.to_string(),
            schema_version: RECEIPT_SCHEMA_VERSION.to_string(),
            status: "committed".to_string(),
            witness_policy: "in_transaction".to_string(),
        });
        if let Some(ref conns) = stores {
            for (label, conn) in conns {
                if *label == "execution_log" {
                    let c = conn.lock().unwrap();
                    let _ = c.execute(
                        "INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3);",
                        params![
                            format!("receipt:{}", receipt.idempotency_key),
                            serde_json::to_vec(&receipt).unwrap_or_default(),
                            g_time
                        ],
                    );
                }
            }
        }
        if let Some(mut g) = guard.take() {
            g.commit()?;
        }

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