clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Formal invariant evaluator delegating to `layer0::guard_term_eval` (`INV-627`).

use std::path::Path;

use serde_json::Value;

use crate::layer0::guard_grammar::{
    AUTH_POLICY_STRICT, PROFILE_RULE, RESOLVER_KIND_FIELD, RESOLVER_KIND_GATE, SEP_NUL,
};
use crate::layer0::guard_term_eval::{ResolverReply, evaluate_compiled_term, get_compiled_guard};
use crate::layer0::limits::SPEC_SHA256_HEX_CHARS;
use crate::layer0::vocabulary::{
    GATE_FILE_EXISTS, GATE_IS_SHA256, GATE_NOETHERIAN_CHECK, GATE_PAYLOAD_NONEMPTY,
    GATE_RESULT_SEALED, GUARD_COLON, GUARD_COMMA, GUARD_DOT, GUARD_LPAREN, GUARD_OUTCOME_FAIL,
    GUARD_OUTCOME_PASS, GUARD_OUTCOME_UNMATCHED, GUARD_PROP_A_HASH, GUARD_PROP_C_HASH,
    GUARD_PROP_INPUTS, GUARD_PROP_OUTPUTS, GUARD_PROP_PAYLOAD, GUARD_RPAREN,
};
use crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY;

#[derive(Default, Debug)]
struct RelationOptions {
    normalize_newlines: bool,
    trim_whitespace: bool,
    ignore_ansi: bool,
    ignore_case: bool,
    stop_on_first_mismatch: bool,
    required_degree: Option<f64>,
}

fn strip_ansi(s: &str) -> String {
    let re = regex::Regex::new(r"\x1B\[[0-9;]*m").unwrap_or_else(|_| regex::Regex::new("").unwrap());
    re.replace_all(s, "").into_owned()
}

fn normalize_output(s: &str, opts: &RelationOptions) -> String {
    let mut out = s.to_string();
    if opts.normalize_newlines { out = out.replace("\r\n", "\n").replace('\r', "\n"); }
    if opts.trim_whitespace { out = out.trim().to_string(); }
    if opts.ignore_ansi { out = strip_ansi(&out); }
    if opts.ignore_case { out = out.to_lowercase(); }
    out
}

fn find_divergence(a: &str, b: &str) -> Option<(usize, char, char)> {
    let a_chars: Vec<char> = a.chars().collect();
    let b_chars: Vec<char> = b.chars().collect();
    for i in 0..a_chars.len().min(b_chars.len()) {
        if a_chars[i] != b_chars[i] { return Some((i, a_chars[i], b_chars[i])); }
    }
    if a_chars.len() != b_chars.len() {
        let idx = a_chars.len().max(b_chars.len()) - 1;
        return Some((idx, a_chars.get(idx).copied().unwrap_or('\0'), b_chars.get(idx).copied().unwrap_or('\0')));
    }
    None
}

fn resolve_value<'a>(path: &str, context: &'a Value) -> Option<&'a Value> {
    let mut current = context;
    for part in path.split(GUARD_DOT) {
        current = current.get(part)?;
    }
    Some(current)
}

pub fn parse_expression(expr: &str) -> Result<(String, String, Vec<String>), String> {
    let expr = expr.trim();
    let colon_idx = expr
        .find(GUARD_COLON)
        .ok_or_else(|| format!("Invalid expression format (missing prefix): {expr}"))?;
    let prefix = expr[..colon_idx].trim().to_string();
    let rest = expr[colon_idx + 1..].trim();
    if let Some(paren_start) = rest.find(GUARD_LPAREN) {
        let paren_end = rest
            .rfind(GUARD_RPAREN)
            .ok_or_else(|| format!("Missing closing parenthesis in expression: {expr}"))?;
        let func_name = rest[..paren_start].trim().to_string();
        let args_str = rest[paren_start + 1..paren_end].trim();
        let args = if args_str.is_empty() {
            Vec::new()
        } else {
            args_str.split(GUARD_COMMA).map(|a| a.trim().to_string()).collect()
        };
        Ok((prefix, func_name, args))
    } else {
        Ok((prefix, rest.to_string(), Vec::new()))
    }
}

fn clean_call_args(raw_args: &[String]) -> Result<Vec<String>, String> {
    let mut out = Vec::with_capacity(raw_args.len());
    for a in raw_args {
        if let Some(unresolved) = a.strip_prefix(SEP_NUL) {
            if unresolved.starts_with(GUARD_PROP_INPUTS) || unresolved.starts_with(GUARD_PROP_OUTPUTS) {
                return Err(format!("Could not resolve path reference: {unresolved}"));
            }
            out.push(unresolved.to_string());
        } else {
            out.push(a.clone());
        }
    }
    Ok(out)
}

type InvariantGateFn = fn(&str, &Value, &[String]) -> Result<bool, String>;

const INVARIANT_GATE_TABLE: &[(&str, InvariantGateFn)] = &[
    (GATE_FILE_EXISTS, |clm_root, _, args| {
        let path_str = args.first().ok_or_else(|| "gate:file_exists requires at least 1 argument".to_string())?;
        let p = Path::new(path_str);
        let resolved = if p.is_absolute() { p.to_path_buf() } else { Path::new(clm_root).join(path_str) };
        Ok(resolved.exists())
    }),
    (GATE_IS_SHA256, |_, _, args| {
        let hash_str = args.first().ok_or_else(|| "gate:is_sha256 requires at least 1 argument".to_string())?;
        let expected_len = crate::hash::DEFAULT_HASH_PREFIX.len() + (SPEC_SHA256_HEX_CHARS as usize);
        if !hash_str.starts_with(crate::hash::DEFAULT_HASH_PREFIX) || hash_str.len() != expected_len {
            return Ok(false);
        }
        Ok(crate::hash::strip_prefix(hash_str).chars().all(|c| c.is_ascii_hexdigit()))
    }),
    (GATE_PAYLOAD_NONEMPTY, |_, ctx, args| {
        let payload = if let Some(first) = args.first() {
            first.clone()
        } else {
            resolve_value(GUARD_PROP_PAYLOAD, ctx).and_then(|v| v.as_str()).unwrap_or("").to_string()
        };
        Ok(!payload.trim().is_empty())
    }),
    (GATE_RESULT_SEALED, |clm_root, ctx, args| {
        let hash = if let Some(first) = args.first() {
            first.clone()
        } else {
            let a_p = format!("{GUARD_PROP_OUTPUTS}{GUARD_DOT}{GUARD_PROP_A_HASH}");
            let c_p = format!("{GUARD_PROP_OUTPUTS}{GUARD_DOT}{GUARD_PROP_C_HASH}");
            resolve_value(&a_p, ctx)
                .or_else(|| resolve_value(&c_p, ctx))
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string()
        };
        if hash.is_empty() {
            return Ok(false);
        }
        crate::db::card_exists(PILLAR_CONTENT_MEMORY, clm_root, &hash)
            .map_err(|e| format!("Database check failed: {e}"))
    }),
    (GATE_NOETHERIAN_CHECK, |clm_root, _, args| {
        for hash in args {
            let exists = crate::db::card_exists(PILLAR_CONTENT_MEMORY, clm_root, hash)
                .map_err(|e| format!("Database check failed: {e}"))?;
            if !exists {
                return Ok(false);
            }
        }
        Ok(true)
    }),
];

pub fn evaluate_invariant(expr: &str, clm_root: &str, context: &Value) -> Result<bool, String> {
    let trimmed = expr.trim();
    if trimmed.is_empty() {
        return Ok(true);
    }
    let compiled = get_compiled_guard(trimmed, PROFILE_RULE)
        .map_err(|e| format!("Invalid invariant expression '{trimmed}': {}", e.message))?;

    let mut resolver = |kind: &str, arg: &str, _arg2: &str, raw_args: &[String]| -> ResolverReply<'_> {
        if kind == RESOLVER_KIND_FIELD {
            return ResolverReply::FieldRef(
                resolve_value(arg, context)
                    .or_else(|| crate::layer1::guard_semantics::resolve_json_field_ref(arg, context, false)),
            );
        }
        if kind == RESOLVER_KIND_GATE {
            let args = match clean_call_args(raw_args) {
                Ok(a) => a,
                Err(e) => return ResolverReply::GateErr(e),
            };
            if let Some(&(_, handler)) = INVARIANT_GATE_TABLE.iter().find(|&&(k, _)| k == arg) {
                return match handler(clm_root, context, &args) {
                    Ok(true) => ResolverReply::Gate(GUARD_OUTCOME_PASS, String::new()),
                    Ok(false) => ResolverReply::Gate(GUARD_OUTCOME_FAIL, String::new()),
                    Err(e) => ResolverReply::GateErr(e),
                };
            }
            return ResolverReply::GateErr(format!("Unknown invariant function: {arg}"));
        }
        ResolverReply::FieldRef(None)
    };

    let verdict = evaluate_compiled_term(&compiled, &mut resolver, GUARD_OUTCOME_UNMATCHED, AUTH_POLICY_STRICT)?;
    if verdict.outcome == GUARD_OUTCOME_PASS {
        Ok(true)
    } else if verdict.outcome == GUARD_OUTCOME_FAIL {
        Ok(false)
    } else {
        Err(format!("Unmatched invariant expression: {}", if verdict.invariant_code.is_empty() { trimmed } else { &verdict.invariant_code }))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_parse_expression() {
        let (p, f, args) = parse_expression("gate:file_exists(inputs.clm_file)").unwrap();
        assert_eq!(p, "gate");
        assert_eq!(f, "file_exists");
        assert_eq!(args, vec!["inputs.clm_file"]);

        let (p2, f2, args2) = parse_expression("gate:payload_nonempty").unwrap();
        assert_eq!(p2, "gate");
        assert_eq!(f2, "payload_nonempty");
        assert_eq!(args2.len(), 0);
    }

    #[test]
    fn test_evaluate_invariant_prefix() {
        let context = json!({ "inputs": { "clm_file": "Cargo.toml" } });
        assert!(evaluate_invariant("gate:file_exists(inputs.clm_file)", ".", &context).unwrap());
        assert!(!evaluate_invariant("gate:file_exists(\"non_existent_file.yaml\")", ".", &context).unwrap());
    }

    #[test]
    fn test_evaluate_invariant_infix_math() {
        let context = json!({ "inputs": { "val": 5, "tag": "a" }, "outputs": { "result": 8 } });
        assert!(evaluate_invariant("inputs.val > 0", ".", &context).unwrap());
        assert!(!evaluate_invariant("inputs.val < 0", ".", &context).unwrap());
        assert!(evaluate_invariant("outputs.result % 2 == 0", ".", &context).unwrap());
        assert!(!evaluate_invariant("outputs.result % 3 == 0", ".", &context).unwrap());
        assert!(evaluate_invariant("inputs.val + 3 == outputs.result", ".", &context).unwrap());
        assert!(evaluate_invariant("inputs.tag in ['a', 'b']", ".", &context).unwrap());
    }
}

#[path = "invariants_equivalence.rs"]
mod invariants_equivalence;
#[allow(unused_imports)]
pub use invariants_equivalence::*;
#[path = "invariants_pcard.rs"]
mod invariants_pcard;
#[allow(unused_imports)]
pub use invariants_pcard::*;