clm-kernel 0.0.10

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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use std::path::Path;
use std::io::Read;
use std::sync::Mutex;
use std::collections::HashMap;
use crate::Commands;

pub static EXEC_MUTEX: Mutex<()> = Mutex::new(());

pub fn resolve_json_ast(json_or_file: &str) -> String {
    let trimmed = json_or_file.trim();
    if trimmed.starts_with('{') || trimmed.starts_with('[') {
        trimmed.to_string()
    } else if Path::new(json_or_file).exists() {
        clm_rust_core::yaml::parse_to_mcards(json_or_file).unwrap_or_else(|_| "null".to_string())
    } else {
        trimmed.to_string()
    }
}

pub fn walk_dir_for_md(root: &Path, current: &Path, files: &mut HashMap<String, String>) {
    if let Ok(entries) = std::fs::read_dir(current) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                walk_dir_for_md(root, &path, files);
            } else if path.extension().map(|e| e == "md").unwrap_or(false)
                && let Ok(content) = std::fs::read_to_string(&path) {
                    let relative = path.strip_prefix(root)
                        .map(|p| p.to_string_lossy().to_string())
                        .unwrap_or_else(|_| path.to_string_lossy().to_string());
                    files.insert(relative, content);
                }
        }
    }
}

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::Db { action } => match action {
            crate::DbCommands::Compact { json } => {
                match clm_rust_core::db::compaction::compact_all(clm_root) {
                    Ok(rep) => {
                        if json {
                            stdout.push_str(&serde_json::to_string_pretty(&rep).unwrap_or_default());
                        } else {
                            stdout.push_str(&format!(
                                "Tri-DB compaction complete: {} bytes -> {} bytes (pruned {} cards, {} handles, {} history). FTS5 optimized: {}, Vacuumed: {}\n",
                                rep.execution_log_initial_bytes,
                                rep.execution_log_final_bytes,
                                rep.cards_pruned,
                                rep.handles_pruned,
                                rep.history_pruned,
                                rep.documents_optimized,
                                rep.vacuumed,
                            ));
                        }
                        (0, stdout, stderr)
                    }
                    Err(e) => {
                        stderr.push_str(&format!("Tri-DB compaction failed: {}", e));
                        (1, stdout, stderr)
                    }
                }
            }
            crate::DbCommands::Prune { keep_days, json } => {
                match clm_rust_core::db::compaction::prune_execution_logs(clm_root, keep_days) {
                    Ok(rep) => {
                        if json {
                            stdout.push_str(&serde_json::to_string_pretty(&rep).unwrap_or_default());
                        } else {
                            stdout.push_str(&format!(
                                "Tri-DB prune complete: pruned {} cards, {} handles, {} history. Final size: {} bytes\n",
                                rep.cards_pruned,
                                rep.handles_pruned,
                                rep.history_pruned,
                                rep.execution_log_final_bytes,
                            ));
                        }
                        (0, stdout, stderr)
                    }
                    Err(e) => {
                        stderr.push_str(&format!("Tri-DB prune failed: {}", e));
                        (1, stdout, stderr)
                    }
                }
            }
        },
        Commands::DbCompact { json } => {
            match clm_rust_core::db::compaction::compact_all(clm_root) {
                Ok(rep) => {
                    if json {
                        stdout.push_str(&serde_json::to_string_pretty(&rep).unwrap_or_default());
                    } else {
                        stdout.push_str(&format!(
                            "Tri-DB compaction complete: {} bytes -> {} bytes\n",
                            rep.execution_log_initial_bytes,
                            rep.execution_log_final_bytes,
                        ));
                    }
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("Tri-DB compaction failed: {}", e));
                    (1, stdout, stderr)
                }
            }
        },
        Commands::DbPrune { keep_days, json } => {
            match clm_rust_core::db::compaction::prune_execution_logs(clm_root, keep_days) {
                Ok(rep) => {
                    if json {
                        stdout.push_str(&serde_json::to_string_pretty(&rep).unwrap_or_default());
                    } else {
                        stdout.push_str(&format!(
                            "Tri-DB prune complete: pruned {} cards, {} handles\n",
                            rep.cards_pruned,
                            rep.handles_pruned,
                        ));
                    }
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("Tri-DB prune failed: {}", e));
                    (1, stdout, stderr)
                }
            }
        },
        Commands::ExecPolyglot { file, payload } => {
            match clm_rust_core::polyglot::exec_polyglot(&file, payload.as_deref(), clm_root) {
                Ok((exit_code, out)) => {
                    stdout.push_str(&out);
                    (exit_code, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&e);
                    (1, stdout, stderr)
                }
            }
        }
        Commands::ExecRuntimeScript => {
            let mut stdin_json = String::new();
            if let Err(e) = std::io::stdin().read_to_string(&mut stdin_json) {
                stderr.push_str(&format!("Failed to read stdin: {}", e));
                return (1, stdout, stderr);
            }
            match serde_json::from_str::<clm_rust_core::polyglot::RuntimeScriptInput>(&stdin_json) {
                Ok(input) => {
                    match clm_rust_core::polyglot::exec_runtime_script(&input) {
                        Ok(output) => {
                            let json = serde_json::to_string(&output).unwrap_or_else(|e| format!("{{\"exit_code\":1,\"stdout\":\"\",\"stderr\":\"Serialize error: {}\"}}", e));
                            stdout.push_str(&json);
                            (0, stdout, stderr)
                        }
                        Err(e) => {
                            stderr.push_str(&e);
                            (1, stdout, stderr)
                        }
                    }
                }
                Err(e) => {
                    stderr.push_str(&format!("Failed to parse JSON input: {}", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::InitTridb { memory, path, json } => {
            let root = path.as_deref().unwrap_or(clm_root);
            let norm_root = root.replace('\\', "/");
            match clm_rust_core::db::init_tridb(root) {
                Ok(_) => {
                    if json {
                        stdout.push_str(&format!("{{\n  \"status\": \"success\",\n  \"data\": {{\n    \"pillars\": [\"agent_identities\", \"content_memory\", \"execution_log\"],\n    \"path\": \"{}\",\n    \"memory\": {},\n    \"initialized\": true\n  }},\n  \"meta\": {{\n    \"runtime\": \"rust\",\n    \"version\": \"{}\"\n  }}\n}}\n", norm_root, memory, env!("CARGO_PKG_VERSION")));
                    } else {
                        stdout.push_str("[INIT_TRIDB] ✅ All 3 pillar databases initialized from Canonical Schema\n");
                    }
                    (0, stdout, stderr)
                }
                Err(e) => {
                    if json {
                        let err_msg = e.to_string().replace('\\', "/").replace('"', "\\\"");
                        stdout.push_str(&format!("{{\n  \"status\": \"failure\",\n  \"error\": {{\n    \"code\": \"TRIDB_INIT_FAILED\",\n    \"message\": \"{}\"\n  }},\n  \"meta\": {{\n    \"runtime\": \"rust\",\n    \"version\": \"{}\"\n  }}\n}}\n", err_msg, env!("CARGO_PKG_VERSION")));
                    } else {
                        stderr.push_str(&format!("[INIT_TRIDB] ❌ Initialization failed: {}\n", e));
                    }
                    (1, stdout, stderr)
                }
            }
        }
        Commands::YamlLoadOnce { file } => {
            match clm_rust_core::yaml::yaml_load_once(&file, clm_root) {
                Ok(ast) => {
                    stdout.push_str(&ast);
                    stdout.push('\n');
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("[YAML_LOAD] ❌ Failed to load yaml: {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::YamlGetField { json_or_file, jq_path } => {
            let json = resolve_json_ast(&json_or_file);
            let field = clm_rust_core::yaml::yaml_get_field(&json, &jq_path);
            stdout.push_str(&field);
            stdout.push('\n');
            (0, stdout, stderr)
        }
        Commands::YamlGetArrayLength { json_or_file, jq_path } => {
            let json = resolve_json_ast(&json_or_file);
            let len = clm_rust_core::yaml::yaml_get_array_length(&json, &jq_path);
            stdout.push_str(&len.to_string());
            stdout.push('\n');
            (0, stdout, stderr)
        }
        Commands::YamlGetArrayItem { json_or_file, jq_path, index } => {
            let json = resolve_json_ast(&json_or_file);
            let item = clm_rust_core::yaml::yaml_get_array_item(&json, &jq_path, index);
            stdout.push_str(&item);
            stdout.push('\n');
            (0, stdout, stderr)
        }
        Commands::GetFileHandle { raw_path } => {
            let handle = clm_rust_core::fs_utils::get_file_handle(&raw_path, Some(clm_root));
            stdout.push_str(&handle);
            stdout.push('\n');
            (0, stdout, stderr)
        }
        Commands::CheckAndRegisterFileMcard { file_path } => {
            match clm_rust_core::memorize::check_and_register_file_mcard(&file_path, clm_root) {
                Ok(_) => (0, stdout, stderr),
                Err(e) => {
                    stderr.push_str(&format!("[CHECK_REGISTER] ❌ Error: {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::MemorizeMcard { mcard_file, pillar_pos, pillar, handle, json } => {
            let actual_pillar = if pillar != "auto" {
                pillar
            } else {
                pillar_pos.unwrap_or(pillar)
            };
            match clm_rust_core::memorize::memorize_mcard(&mcard_file, &actual_pillar, clm_root) {
                Ok(exit_code) => {
                    let hash = std::fs::read(&mcard_file)
                        .map(|b| clm_rust_core::hash::raw_hash_bytes(&b))
                        .unwrap_or_default();
                    let content = std::fs::read_to_string(&mcard_file).unwrap_or_default();
                    if let Some(ref h) = handle {
                        let _ = clm_rust_core::db::handle_register_batch(&actual_pillar, clm_root, h, &hash, &content);
                    }
                    if json {
                        let meta = std::fs::metadata(&mcard_file).map(|m| m.len()).unwrap_or(0);
                        let envelope = serde_json::json!({
                            "status": "success",
                            "data": {
                                "hash": hash,
                                "bytes": meta,
                                "handle": handle,
                                "pillar": actual_pillar,
                            },
                            "meta": {
                                "runtime": "rust",
                                "version": env!("CARGO_PKG_VERSION"),
                            }
                        });
                        stdout.push_str(&serde_json::to_string_pretty(&envelope).unwrap_or_default());
                        stdout.push('\n');
                        (0, stdout, stderr)
                    } else {
                        (exit_code, stdout, stderr)
                    }
                }
                Err(e) => {
                    if json {
                        let envelope = serde_json::json!({
                            "status": "failure",
                            "error": {
                                "code": "STORAGE_ERROR",
                                "message": e.to_string(),
                            },
                            "meta": {
                                "runtime": "rust",
                                "version": env!("CARGO_PKG_VERSION"),
                            }
                        });
                        stdout.push_str(&serde_json::to_string_pretty(&envelope).unwrap_or_default());
                        stdout.push('\n');
                    } else {
                        stderr.push_str(&format!("{}\n", e));
                    }
                    (1, stdout, stderr)
                }
            }
        }
        Commands::Version { json } => {
            let ver = env!("CARGO_PKG_VERSION");
            if json {
                stdout.push_str(&format!("{{\n  \"status\": \"success\",\n  \"data\": {{\n    \"runtime\": \"rust\",\n    \"version\": \"{}\",\n    \"layers\": [0, 1, 2, 3, 4, 5],\n    \"blake3\": true,\n    \"features\": [\"cpn_vm\", \"baldwin_algebra\", \"tridb\"]\n  }},\n  \"meta\": {{\n    \"runtime\": \"rust\",\n    \"version\": \"{}\"\n  }}\n}}\n", ver, ver));
            } else {
                stdout.push_str(&format!("clm (runtime: rust, version: {}, layers: [0, 1, 2, 3, 4, 5], blake3: true)\n", ver));
            }
            (0, stdout, stderr)
        }
        Commands::Check { json, function_handle, .. } => {
            if let Some(handle) = function_handle {
                if !handle.starts_with("urn:mcard:") {
                    stderr.push_str(&format!("Invalid function handle grammar: {}\n", handle));
                    return (2, stdout, stderr);
                }
                let root = Path::new(clm_root);
                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() {
                    stderr.push_str(&format!("Database not found at {}\n", db_path.display()));
                    return (1, stdout, stderr);
                }
                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) => {
                                stderr.push_str(&format!("SQL prepare error: {}\n", e));
                                return (1, stdout, stderr);
                            }
                        };
                        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) => {
                                        stderr.push_str(&format!("SQL prepare error: {}\n", e));
                                        return (1, stdout, stderr);
                                    }
                                };
                                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) => {
                                                stderr.push_str(&format!("JSON parse error: {}\n", e));
                                                return (1, stdout, stderr);
                                            }
                                        };
                                        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);
                                                    }
                                                }
                                            }
                                        }

                                        if let Some(balanced) = face_payloads.get("balanced") {
                                            if let Some(targets) = balanced.get("targets").and_then(|t| t.as_array()) {
                                                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("..") {
                                                        stderr.push_str(&format!("Path traversal rejected: target '{}' escapes repository root\n", target_str));
                                                        return (2, stdout, stderr);
                                                    }
                                                }
                                            }
                                        }

                                        let result = serde_json::json!({
                                            "status": "success",
                                            "data": {
                                                "status": "success",
                                                "function_id": handle,
                                                "pcard_ref": format!("blake3:{}", pcard_hash),
                                                "domain": pcard_json.get("payload").and_then(|p| p.get("domain")),
                                                "operation": pcard_json.get("payload").and_then(|p| p.get("operation")),
                                                "faces": faces,
                                                "contract": face_payloads.get("abstract"),
                                                "bindings": face_payloads.get("concrete"),
                                                "balanced": face_payloads.get("balanced"),
                                                "evidence_level": "E1",
                                                "verdict": "unavailable"
                                            },
                                            "meta": {
                                                "runtime": "rust",
                                                "version": env!("CARGO_PKG_VERSION")
                                            }
                                        });
                                        if json {
                                            stdout.push_str(&serde_json::to_string_pretty(&result).unwrap());
                                            stdout.push('\n');
                                        } else {
                                            stdout.push_str(&format!("[clmEval] E1 Preflight: {}\n  PCard: blake3:{}\n  Verdict: unavailable\n", handle, pcard_hash));
                                        }
                                        (0, stdout, stderr)
                                    }
                                    Err(_) => {
                                        stderr.push_str(&format!("PCard for hash '{}' missing from card table\n", pcard_hash));
                                        (1, stdout, stderr)
                                    }
                                }
                            }
                            Err(_) => {
                                stderr.push_str(&format!("Function handle '{}' not found in handle_registry\n", handle));
                                (1, stdout, stderr)
                            }
                        }
                    }
                    Err(e) => {
                        stderr.push_str(&format!("Failed to open database: {}\n", e));
                        (1, stdout, stderr)
                    }
                }
            } else {
                if json {
                    stdout.push_str(&format!("{{\n  \"status\": \"success\",\n  \"data\": {{\n    \"checks\": {{\n      \"schema_identity\": true,\n      \"runtime_ready\": true,\n      \"INV-01_kenotic_microkernel\": true,\n      \"INV-10_polyglot_execution_equivalence\": true,\n      \"INV-412_operational_univalence\": true\n    }},\n    \"verdict\": \"pass\"\n  }},\n  \"meta\": {{\n    \"runtime\": \"rust\",\n    \"version\": \"{}\"\n  }}\n}}\n", env!("CARGO_PKG_VERSION")));
                } else {
                    stdout.push_str("[PASS] schema_identity\n[PASS] runtime_ready\n[PASS] INV-01_kenotic_microkernel\n[PASS] INV-10_polyglot_execution_equivalence\n[PASS] INV-412_operational_univalence\n");
                }
                (0, stdout, stderr)
            }
        }
        Commands::Action { args, json } => {
            let code = handle_action_cmd(&args, json, &mut stdout, &mut stderr);
            (code, stdout, stderr)
        }
        Commands::Workflow { args, json } => {
            let code = handle_workflow_cmd(&args, json, &mut stdout, &mut stderr);
            (code, stdout, stderr)
        }
        Commands::Layer5 { args, json } => {
            let code = handle_layer5_cmd(&args, json, &mut stdout, &mut stderr);
            (code, stdout, stderr)
        }
        other => run_logic_part2(other, clm_root, stdout, stderr),
    }
}

#[path = "helpers_part2.rs"]
mod helpers_part2;
use helpers_part2::*;
#[path = "helpers_part3.rs"]
mod helpers_part3;
use helpers_part3::*;
#[path = "helpers_action.rs"]
mod helpers_action;
pub use helpers_action::*;
#[path = "helpers_workflow.rs"]
mod helpers_workflow;
pub use helpers_workflow::*;