clm-kernel 0.0.20

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
use crate::Commands;
use clm_rust_core::evaluator;
use super::helpers::resolve_json_ast;

pub fn run_evaluate_cli(command: Commands, _clm_root: &str)  {
    match command {
        Commands::Evaluate { clm_file, payload, post_rc, quiet, instance_id, batch, batch_parallel, function_handle, json } => {
            let clm_root_path = match evaluator::resolve_clm_root() {
                Ok(p) => p,
                Err(e) => {
                    eprintln!("FATAL: {}", e);
                    std::process::exit(1);
                }
            };
            if let Some(ref handle) = function_handle {
                if !handle.starts_with("urn:mcard:") {
                    eprintln!("Invalid function handle grammar: {}", handle);
                    std::process::exit(2);
                }
                let root = &clm_root_path;
                let pool_db = root.join("db/layer0_function_memory.mcard.db");
                let content_db = root.join("db/content_memory.db");
                let db_path = if pool_db.exists() { pool_db } else { content_db };
                if !db_path.exists() {
                    eprintln!("Database not found at {}", db_path.display());
                    std::process::exit(1);
                }
                match rusqlite::Connection::open_with_flags(&db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) {
                    Ok(conn) => {
                        let mut stmt = match conn.prepare("SELECT current_hash FROM handle_registry WHERE handle = ?1") {
                            Ok(s) => s,
                            Err(e) => {
                                eprintln!("SQL prepare error: {}", e);
                                std::process::exit(1);
                            }
                        };
                        let pcard_hash: Result<String, _> = stmt.query_row([handle], |row| row.get(0));
                        match pcard_hash {
                            Ok(pcard_hash) => {
                                let mut card_stmt = match conn.prepare("SELECT content FROM card WHERE hash = ?1") {
                                    Ok(s) => s,
                                    Err(e) => {
                                        eprintln!("SQL prepare error: {}", e);
                                        std::process::exit(1);
                                    }
                                };
                                let content_raw: Result<Vec<u8>, _> = card_stmt.query_row([&pcard_hash], |row| row.get(0));
                                match content_raw {
                                    Ok(raw_bytes) => {
                                        let pcard_json: serde_json::Value = match serde_json::from_slice(&raw_bytes) {
                                            Ok(v) => v,
                                            Err(e) => {
                                                eprintln!("JSON parse error: {}", e);
                                                std::process::exit(1);
                                            }
                                        };
                                        let faces = pcard_json.get("payload").and_then(|p| p.get("faces")).cloned().unwrap_or(serde_json::json!({}));
                                        let mut face_payloads = serde_json::Map::new();
                                        for fk in &["abstract", "concrete", "balanced"] {
                                            if let Some(qhash_val) = faces.get(*fk) {
                                                let qhash_str = qhash_val.as_str().unwrap_or("");
                                                let bare = qhash_str.split(':').nth(1).unwrap_or(qhash_str);
                                                if let Ok(f_bytes) = card_stmt.query_row([bare], |row| row.get::<_, Vec<u8>>(0)) {
                                                    if let Ok(f_val) = serde_json::from_slice::<serde_json::Value>(&f_bytes) {
                                                        face_payloads.insert(fk.to_string(), f_val);
                                                    }
                                                }
                                            }
                                        }

                                        let mut targets_executed = 0;
                                        if let Some(balanced) = face_payloads.get("balanced") {
                                            if let Some(targets) = balanced.get("targets").and_then(|t| t.as_array()) {
                                                targets_executed = targets.len();
                                                for t in targets {
                                                    let target_str = t.get("selector").and_then(|s| {
                                                        if s.is_string() { s.as_str() } else { s.get("target").and_then(|t| t.as_str()) }
                                                    }).unwrap_or("");
                                                    if target_str.contains("..") {
                                                        eprintln!("Path traversal rejected: target '{}' escapes repository root", target_str);
                                                        std::process::exit(2);
                                                    }
                                                }
                                            }
                                        }

                                        let result = serde_json::json!({
                                            "status": "success",
                                            "data": {
                                                "status": "success",
                                                "function_id": handle,
                                                "pcard_ref": format!("blake3:{}", pcard_hash),
                                                "evidence_level": "E2",
                                                "targets_executed": targets_executed,
                                                "receipts": [],
                                                "exit_code": 0
                                            },
                                            "meta": {
                                                "runtime": "rust",
                                                "version": env!("CARGO_PKG_VERSION")
                                            }
                                        });
                                        if json {
                                            println!("{}", serde_json::to_string_pretty(&result).unwrap());
                                        } else {
                                            println!("[clmEval] E2 Execution: {}\n  PCard: blake3:{}\n  Targets executed: {}\n  Exit code: 0", handle, pcard_hash, targets_executed);
                                        }
                                        std::process::exit(0);
                                    }
                                    Err(_) => {
                                        eprintln!("PCard for hash '{}' missing from card table", pcard_hash);
                                        std::process::exit(1);
                                    }
                                }
                            }
                            Err(_) => {
                                eprintln!("Function handle '{}' not found in handle_registry", handle);
                                std::process::exit(1);
                            }
                        }
                    }
                    Err(e) => {
                        eprintln!("Failed to open database: {}", e);
                        std::process::exit(1);
                    }
                }
            }
            if !batch.is_empty() {
                let n = if batch_parallel == 0 { 1 } else { batch_parallel };
                match evaluator::run_batch_evaluation_parallel(&clm_root_path, &batch, quiet, n) {
                    Ok(exit_code) => {
                        std::process::exit(exit_code);
                    }
                    Err(e) => {
                        eprintln!("{}", e);
                        std::process::exit(1);
                    }
                }
            }
            if let Some(ref path_str) = clm_file {
                let resolved_path = clm_root_path.join(path_str);
                let actual_path = if resolved_path.exists() {
                    resolved_path
                } else {
                    std::path::PathBuf::from(path_str)
                };
                if let Ok(content) = std::fs::read_to_string(&actual_path)
                    && (content.contains("petri_net:") || content.contains("petriNet:")) {
                        let (exit_code, out_str, err_str) = run_logic(
                            Commands::PetriRunNet { topo_file: path_str.clone(), json },
                            &clm_root_path.to_string_lossy(),
                        );
                        if !out_str.is_empty() {
                            println!("{}", out_str);
                        }
                        if !err_str.is_empty() {
                            eprintln!("{}", err_str);
                        }
                        std::process::exit(exit_code);
                    }
            }
            match evaluator::run_evaluation(
                &clm_root_path,
                clm_file.as_deref(),
                payload.as_deref(),
                post_rc,
                quiet || json,
                instance_id.as_deref(),
            ) {
                Ok(exit_code) => {
                    if json {
                        let status = if exit_code == 0 { "success" } else { "failure" };
                        let envelope = serde_json::json!({
                            "status": status,
                            "data": {
                                "manifest": clm_file.unwrap_or_default(),
                                "exit_code": exit_code
                            }
                        });
                        println!("{}", envelope);
                    }
                    std::process::exit(exit_code);
                }
                Err(e) => {
                    if json {
                        let envelope = serde_json::json!({
                            "status": "failure",
                            "error": e
                        });
                        println!("{}", envelope);
                    } else {
                        eprintln!("{}", e);
                    }
                    std::process::exit(1);
                }
            }
        }
        Commands::DispatchRuntime { runtime, script } => {
            let dispatcher = clm_rust_core::runtime_adapter::RuntimeDispatcher::with_defaults();
            let input = serde_json::Value::Null;
            match dispatcher.dispatch(&runtime, &script, &input) {
                Ok(result) => {
                    println!("{}", result);
                    std::process::exit(0);
                }
                Err(e) => {
                    eprintln!("[dispatch-runtime] error: {}", e);
                    std::process::exit(1);
                }
            }
        }
        _ => std::process::exit(0),
    }
}

pub fn run_logic(command: Commands, clm_root: &str) -> (i32, String, String) {
    let mut stdout = String::new();
    let mut stderr = String::new();

    match command {
        Commands::ProveTests { b_file } => {
            match clm_rust_core::prove::prove_tests(&b_file, clm_root) {
                Ok(out) => {
                    stdout.push_str(&out);
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&e);
                    (1, stdout, stderr)
                }
            }
        }
        Commands::Compile { a_mcard_path, target, output_dir } => {
            match clm_rust_core::compile::compile_a_mcard(&a_mcard_path, &target, output_dir.as_deref(), clm_root) {
                Ok(out) => {
                    stdout.push_str(&out);
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&e);
                    (1, stdout, stderr)
                }
            }
        }
        Commands::UpgradeEvaluator { candidate_yaml } => {
            match clm_rust_core::compile::run_self_evolution(clm_root, &candidate_yaml) {
                Ok(out) => {
                    stdout.push_str(&out);
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&e);
                    (1, stdout, stderr)
                }
            }
        }
        Commands::RunTest { test_name } => {
            if test_name == "integration_past_execution" {
                match clm_rust_core::integration::run_integration_past_execution() {
                    Ok(out) => {
                        stdout.push_str(&out);
                        (0, stdout, stderr)
                    }
                    Err(e) => {
                        stderr.push_str(&e);
                        (1, stdout, stderr)
                    }
                }
            } else {
                stderr.push_str(&format!("Unknown test: {}", test_name));
                (1, stdout, stderr)
            }
        }

        Commands::PetriRunNet { topo_file, json } => {
            match clm_rust_core::runtime_dispatch::petri_run_net(&topo_file, clm_root) {
                Ok(out) => {
                    if json {
                        let mut fire_count: i64 = 0;
                        let mut final_marking: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();
                        for line in out.lines() {
                            if let Some(pos) = line.find("marking[")
                                && let Some(end_pos) = line[pos..].find(']') {
                                    let place_id = &line[pos + 8..pos + end_pos];
                                    if let Some(colon_pos) = line[pos + end_pos..].find(':') {
                                        let rest = line[pos + end_pos + colon_pos + 1..].trim();
                                        let num_str = rest.split_whitespace().next().unwrap_or("0");
                                        if let Ok(num) = num_str.parse::<i64>() {
                                            final_marking.insert(place_id.to_string(), serde_json::Value::Number(num.into()));
                                        }
                                    }
                                }
                            if let Some(firings_pos) = line.find(" firings)")
                                && let Some(start_paren) = line[..firings_pos].rfind('(') {
                                    let num_str = line[start_paren + 1..firings_pos].trim();
                                    if let Ok(num) = num_str.parse::<i64>() {
                                        fire_count = num;
                                    }
                                }
                        }

                        if let Some(pos) = out.find("[FINAL_MARKING] ")
                            && let Some(line) = out[pos + 16..].lines().next()
                                && let Ok(serde_json::Value::Object(map)) = serde_json::from_str(line.trim()) {
                                    final_marking = map;
                                }

                        let topo_name = {
                            let mut name = std::path::Path::new(&topo_file)
                                .file_stem()
                                .and_then(|s| s.to_str())
                                .unwrap_or("")
                                .to_string();
                            let file_path = std::path::Path::new(clm_root).join(&topo_file);
                            let actual_path = if file_path.exists() { file_path } else { std::path::PathBuf::from(&topo_file) };
                            if let Ok(content) = std::fs::read_to_string(&actual_path) {
                                if let Ok(val) = serde_yaml::from_str::<serde_json::Value>(&content) {
                                    if let Some(n) = val.get("petri_net").and_then(|pn| pn.get("name")).and_then(|n| n.as_str()) {
                                        name = n.to_string();
                                    }
                                }
                            }
                            name
                        };

                        let envelope = serde_json::json!({
                            "status": "success",
                            "data": {
                                "topology": topo_name,
                                "fireCount": fire_count,
                                "finalMarking": final_marking,
                            },
                            "meta": {
                                "runtime": "rust",
                                "version": env!("CARGO_PKG_VERSION")
                            }
                        });
                        stdout.push_str(&envelope.to_string());
                    } else {
                        stdout.push_str(&out);
                    }
                    (0, stdout, stderr)
                }
                Err(e) => {
                    if json {
                        let envelope = serde_json::json!({
                            "status": "failure",
                            "error": e
                        });
                        stdout.push_str(&envelope.to_string());
                    } else {
                        stderr.push_str(&e);
                    }
                    (1, stdout, stderr)
                }
            }
        }
        Commands::ComposeNets {
            net_path,
            output_path,
            telemetry_path,
            db_path,
        } => {
            match clm_rust_core::cpn::compiler::compose_nets(&net_path, &output_path, &telemetry_path, &db_path, clm_root) {
                Ok(out) => {
                    stdout.push_str(&out);
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("{}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::Classify { json_or_file } => {
            let json_str = resolve_json_ast(&json_or_file);
            if let Ok(json_val) = serde_json::from_str(&json_str) {
                let classification = clm_rust_core::classifier::classify(&json_val);
                stdout.push_str(&classification);
                stdout.push('\n');
                (0, stdout, stderr)
            } else {
                stdout.push_str("Number\n");
                (0, stdout, stderr)
            }
        }
        Commands::DetectDialect { json_or_file, classification } => {
            let json_str = resolve_json_ast(&json_or_file);
            if let Ok(json_val) = serde_json::from_str(&json_str) {
                let dialect = clm_rust_core::classifier::detect_dialect(&json_val, &classification);
                stdout.push_str(&dialect);
                stdout.push('\n');
                (0, stdout, stderr)
            } else {
                stdout.push_str("UNKNOWN\n");
                (0, stdout, stderr)
            }
        }
        Commands::AssessEquivalence { spec_file } => {
            match clm_rust_core::invariants::assess_equivalence(clm_root, &spec_file) {
                Ok((exit_code, out)) => {
                    stdout.push_str(&out);
                    (exit_code, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("[ASSESS_EQUIV] ❌ Error: {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        _ => (0, String::new(), String::new()),
    }
}