clm-kernel 0.0.23

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use serde_json::Value;
use std::path::Path;

/// Optional per-relation tuning parsed from the spec YAML.
#[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 {
    // Remove ANSI escape sequences: ESC [ ... m
    let re =
        regex::Regex::new(r"\x1B\[[0-9;]*m").unwrap_or_else(|_| regex::Regex::new(r"").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;
        let ac = a_chars.get(idx).copied().unwrap_or('\0');
        let bc = b_chars.get(idx).copied().unwrap_or('\0');
        return Some((idx, ac, bc));
    }
    None
}

/// Parses an invariant expression of the form:
/// prefix:func_name(arg1, arg2, ...) or prefix:func_name
pub fn parse_expression(expr: &str) -> Result<(String, String, Vec<String>), String> {
    let expr = expr.trim();
    let colon_idx = expr
        .find(':')
        .ok_or_else(|| format!("Invalid expression format (missing prefix): {}", expr))?;
    let prefix = expr[0..colon_idx].trim().to_string();
    let rest = &expr[colon_idx + 1..].trim();

    if let Some(paren_start) = rest.find('(') {
        let paren_end = rest
            .rfind(')')
            .ok_or_else(|| format!("Missing closing parenthesis in expression: {}", expr))?;
        let func_name = rest[0..paren_start].trim().to_string();
        let args_str = rest[paren_start + 1..paren_end].trim();
        let mut args = Vec::new();
        if !args_str.is_empty() {
            for arg in args_str.split(',') {
                args.push(arg.trim().to_string());
            }
        }
        Ok((prefix, func_name, args))
    } else {
        let func_name = rest.to_string();
        Ok((prefix, func_name, Vec::new()))
    }
}

/// Evaluates a formal invariant checking gate.
/// Resolves variables in arguments using the provided JSON context.
pub fn evaluate_invariant(expr: &str, clm_root: &str, context: &Value) -> Result<bool, String> {
    let expr = expr.trim();
    if expr.is_empty() {
        return Ok(true);
    }

    let has_compound_boolean = expr.contains(crate::layer0::vocabulary::GUARD_OP_AND)
        || expr.contains(crate::layer0::vocabulary::GUARD_OP_OR)
        || expr.starts_with(crate::layer0::vocabulary::GUARD_LPAREN)
        || (expr.starts_with(crate::layer0::vocabulary::GUARD_OP_NOT)
            && !expr.starts_with(crate::layer0::vocabulary::GUARD_CMP_NE));
    if has_compound_boolean {
        let ast = crate::layer1::guard_semantics::parse_guard_expression(expr, true)?;
        let verdict = crate::layer1::guard_semantics::evaluate_guard_ast(&ast, &|atom| {
            match evaluate_single_invariant(atom, clm_root, context) {
                Ok(true) => crate::layer1::guard_semantics::GuardVerdict::Pass,
                Ok(false) => crate::layer1::guard_semantics::GuardVerdict::Fail(atom.to_string()),
                Err(_) => crate::layer1::guard_semantics::evaluate_guard_atom(atom, context),
            }
        });
        return match verdict {
            crate::layer1::guard_semantics::GuardVerdict::Pass => Ok(true),
            crate::layer1::guard_semantics::GuardVerdict::Fail(_) => Ok(false),
            crate::layer1::guard_semantics::GuardVerdict::Unmatched(e) => {
                Err(format!("Unmatched invariant expression: {}", e))
            }
        };
    }

    evaluate_single_invariant(expr, clm_root, context)
}

fn evaluate_single_invariant(expr: &str, clm_root: &str, context: &Value) -> Result<bool, String> {
    let expr = expr.trim();
    if expr.is_empty() {
        return Ok(true);
    }

    // Check if it is a prefix expression prefix:func_name(args)
    // We assume it is prefix if it contains ':' and does not contain infix comparison operators.
    let is_prefix = expr.contains(':')
        && !expr.contains('>')
        && !expr.contains('<')
        && !expr.contains("==")
        && !expr.contains("!=")
        && !expr.contains('%');

    if is_prefix {
        let (prefix, func_name, args) = parse_expression(expr)?;

        let mut resolved_args = Vec::new();
        for arg in &args {
            if arg.starts_with('"') && arg.ends_with('"') {
                resolved_args.push(arg[1..arg.len() - 1].to_string());
            } else if arg.starts_with("inputs.") || arg.starts_with("outputs.") {
                let val = resolve_value(arg, context)
                    .ok_or_else(|| format!("Could not resolve path reference: {}", arg))?;
                resolved_args.push(
                    val.as_str()
                        .map(|s| s.to_string())
                        .unwrap_or_else(|| val.to_string()),
                );
            } else {
                if let Some(val) = resolve_value(arg, context) {
                    resolved_args.push(
                        val.as_str()
                            .map(|s| s.to_string())
                            .unwrap_or_else(|| val.to_string()),
                    );
                } else {
                    resolved_args.push(arg.clone());
                }
            }
        }

        match (prefix.as_str(), func_name.as_str()) {
            ("gate", "file_exists") => {
                if resolved_args.is_empty() {
                    return Err("gate:file_exists requires at least 1 argument".to_string());
                }
                let path_str = &resolved_args[0];
                let path = Path::new(path_str);
                let resolved_path = if path.is_absolute() {
                    path.to_path_buf()
                } else {
                    Path::new(clm_root).join(path_str)
                };
                Ok(resolved_path.exists())
            }
            ("gate", "is_sha256") => {
                if resolved_args.is_empty() {
                    return Err("gate:is_sha256 requires at least 1 argument".to_string());
                }
                let hash_str = &resolved_args[0];
                if !hash_str.starts_with(crate::hash::DEFAULT_HASH_PREFIX) || hash_str.len() != 71 {
                    return Ok(false);
                }
                let hex_part = crate::hash::strip_prefix(hash_str);
                Ok(hex_part.chars().all(|c| c.is_ascii_hexdigit()))
            }
            ("gate", "payload_nonempty") => {
                let payload = if resolved_args.is_empty() {
                    crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_PAYLOAD)
                        .unwrap_or_default()
                } else {
                    resolved_args[0].clone()
                };
                Ok(!payload.trim().is_empty())
            }
            ("gate", "result_sealed") => {
                let hash = if resolved_args.is_empty() {
                    if let Some(v) = resolve_value("outputs.a_hash", context) {
                        v.as_str().unwrap_or("").to_string()
                    } else if let Some(v) = resolve_value("outputs.c_hash", context) {
                        v.as_str().unwrap_or("").to_string()
                    } else {
                        // Try env CLM_ACTIVE_C_HASH
                        crate::layer0::environment::var(
                            crate::layer0::vocabulary_env::ENV_CLM_ACTIVE_C_HASH,
                        )
                        .unwrap_or_default()
                    }
                } else {
                    resolved_args[0].clone()
                };
                if hash.is_empty() {
                    return Ok(false);
                }
                let exists = crate::db::card_exists(
                    crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY,
                    clm_root,
                    &hash,
                )
                .map_err(|e| format!("Database check failed: {}", e))?;
                Ok(exists)
            }
            ("conservation", "noetherian_check") => {
                for hash in &resolved_args {
                    let exists = crate::db::card_exists(
                        crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY,
                        clm_root,
                        hash,
                    )
                    .map_err(|e| format!("Database check failed: {}", e))?;
                    if !exists {
                        return Ok(false);
                    }
                }
                Ok(true)
            }
            _ => Err(format!(
                "Unknown invariant function: {}:{}",
                prefix, func_name
            )),
        }
    } else {
        // Fall back to math/comparison expression
        evaluate_infix_expression(expr, context)
    }
}

fn evaluate_infix_expression(expr: &str, context: &Value) -> Result<bool, String> {
    let expr = expr.trim();
    let operators = vec!["==", "!=", ">=", "<=", ">", "<"];
    let mut found_op = None;
    for op in &operators {
        if let Some(idx) = expr.find(op) {
            found_op = Some((*op, idx));
            break;
        }
    }

    if let Some((op, idx)) = found_op {
        let lhs_str = expr[0..idx].trim();
        let rhs_str = expr[idx + op.len()..].trim();

        let lhs_val = evaluate_arithmetic(lhs_str, context)?;
        let rhs_val = evaluate_arithmetic(rhs_str, context)?;

        match op {
            "==" => Ok(lhs_val == rhs_val),
            "!=" => Ok(lhs_val != rhs_val),
            ">" => {
                let l = lhs_val
                    .as_f64()
                    .ok_or_else(|| format!("LHS is not a number: {}", lhs_str))?;
                let r = rhs_val
                    .as_f64()
                    .ok_or_else(|| format!("RHS is not a number: {}", rhs_str))?;
                Ok(l > r)
            }
            ">=" => {
                let l = lhs_val
                    .as_f64()
                    .ok_or_else(|| format!("LHS is not a number: {}", lhs_str))?;
                let r = rhs_val
                    .as_f64()
                    .ok_or_else(|| format!("RHS is not a number: {}", rhs_str))?;
                Ok(l >= r)
            }
            "<" => {
                let l = lhs_val
                    .as_f64()
                    .ok_or_else(|| format!("LHS is not a number: {}", lhs_str))?;
                let r = rhs_val
                    .as_f64()
                    .ok_or_else(|| format!("RHS is not a number: {}", rhs_str))?;
                Ok(l < r)
            }
            "<=" => {
                let l = lhs_val
                    .as_f64()
                    .ok_or_else(|| format!("LHS is not a number: {}", lhs_str))?;
                let r = rhs_val
                    .as_f64()
                    .ok_or_else(|| format!("RHS is not a number: {}", rhs_str))?;
                Ok(l <= r)
            }
            _ => unreachable!(),
        }
    } else {
        let val = evaluate_arithmetic(expr, context)?;
        if let Some(b) = val.as_bool() {
            Ok(b)
        } else if let Some(n) = val.as_i64() {
            Ok(n != 0)
        } else if let Some(s) = val.as_str() {
            Ok(!s.is_empty())
        } else {
            Ok(!val.is_null())
        }
    }
}

fn evaluate_arithmetic(expr: &str, context: &Value) -> Result<Value, String> {
    let expr = expr.trim();
    if let Some(idx) = expr.find('%') {
        let lhs_str = expr[0..idx].trim();
        let rhs_str = expr[idx + 1..].trim();
        let lhs_val = evaluate_arithmetic(lhs_str, context)?;
        let rhs_val = evaluate_arithmetic(rhs_str, context)?;
        let l = lhs_val
            .as_i64()
            .ok_or_else(|| format!("LHS of % is not an integer: {}", lhs_str))?;
        let r = rhs_val
            .as_i64()
            .ok_or_else(|| format!("RHS of % is not an integer: {}", rhs_str))?;
        if r == 0 {
            return Err("Modulo by zero".to_string());
        }
        return Ok(Value::from(l % r));
    }

    if expr.starts_with('"') && expr.ends_with('"') {
        return Ok(Value::String(expr[1..expr.len() - 1].to_string()));
    }

    if let Ok(n) = expr.parse::<i64>() {
        return Ok(Value::from(n));
    }
    if let Ok(f) = expr.parse::<f64>() {
        return Ok(Value::from(f));
    }

    if expr == "true" {
        return Ok(Value::Bool(true));
    }
    if expr == "false" {
        return Ok(Value::Bool(false));
    }

    if let Some(val) = resolve_value(expr, context) {
        return Ok(val.clone());
    }

    Err(format!("Could not resolve token or value: {}", expr))
}

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

#[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"
            }
        });
        let res = evaluate_invariant("gate:file_exists(inputs.clm_file)", ".", &context).unwrap();
        assert!(res);

        let res2 = evaluate_invariant(
            "gate:file_exists(\"non_existent_file.yaml\")",
            ".",
            &context,
        )
        .unwrap();
        assert!(!res2);
    }

    #[test]
    fn test_evaluate_invariant_infix_math() {
        let context = json!({
            "inputs": {
                "val": 5
            },
            "outputs": {
                "result": 8
            }
        });

        let res1 = evaluate_invariant("inputs.val > 0", ".", &context).unwrap();
        assert!(res1);

        let res2 = evaluate_invariant("inputs.val < 0", ".", &context).unwrap();
        assert!(!res2);

        let res3 = evaluate_invariant("outputs.result % 2 == 0", ".", &context).unwrap();
        assert!(res3);

        let res4 = evaluate_invariant("outputs.result % 3 == 0", ".", &context).unwrap();
        assert!(!res4);
    }
}

#[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::*;