clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use crate::Commands;

pub(super) fn handle_db_cmd(
    command: &Commands,
    clm_root: &str,
    stdout: &mut String,
    stderr: &mut String,
) -> Option<i32> {
    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,
                            ));
                        }
                        Some(0)
                    }
                    Err(e) => {
                        stderr.push_str(&format!("Tri-DB compaction failed: {}", e));
                        Some(1)
                    }
                }
            }
            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,
                            ));
                        }
                        Some(0)
                    }
                    Err(e) => {
                        stderr.push_str(&format!("Tri-DB prune failed: {}", e));
                        Some(1)
                    }
                }
            }
        },
        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,
                        ));
                    }
                    Some(0)
                }
                Err(e) => {
                    stderr.push_str(&format!("Tri-DB compaction failed: {}", e));
                    Some(1)
                }
            }
        },
        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,
                        ));
                    }
                    Some(0)
                }
                Err(e) => {
                    stderr.push_str(&format!("Tri-DB prune failed: {}", e));
                    Some(1)
                }
            }
        },
        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");
                    }
                    Some(0)
                }
                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));
                    }
                    Some(1)
                }
            }
        },
        Commands::ResolveHandle { handle, pillar_pos, pillar, hash_only, json } => {
            let actual_pillar = pillar_pos.as_deref().unwrap_or(pillar.as_str());
            match clm_rust_core::db::resolve_handle_content(actual_pillar, clm_root, handle) {
                Ok(Some(content)) => {
                    let hash = clm_rust_core::db::resolve_handle_hash(actual_pillar, clm_root, handle)
                        .ok()
                        .flatten()
                        .unwrap_or_default();
                    if *json {
                        let envelope = serde_json::json!({
                            "status": "success",
                            "data": { "handle": handle, "hash": hash, "content": content, "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');
                    } else if *hash_only {
                        stdout.push_str(&hash);
                        stdout.push('\n');
                    } else {
                        stdout.push_str(&content);
                        stdout.push('\n');
                    }
                    Some(0)
                }
                Ok(None) => {
                    if *json {
                        let envelope = serde_json::json!({
                            "status": "failure",
                            "error": { "code": "HANDLE_NOT_FOUND", "message": format!("Handle '{}' not found in pillar '{}'", handle, 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');
                    } else {
                        stderr.push_str(&format!("Handle '{}' not found in pillar '{}'\n", handle, actual_pillar));
                    }
                    Some(1)
                }
                Err(e) => {
                    stderr.push_str(&format!("Resolve error: {}\n", e));
                    Some(1)
                }
            }
        }
        Commands::DirectoryFsScan { spec_file } => {
            match clm_rust_core::directory_ingest::directory_fs_scan(clm_root, spec_file) {
                Ok((exit_code, out)) => { stdout.push_str(&out); Some(exit_code) }
                Err(e) => { stderr.push_str(&format!("[DIR_FS_SCAN] ❌ Error: {}\n", e)); Some(1) }
            }
        }
        Commands::DirectoryToDb { spec_file } => {
            match clm_rust_core::directory_ingest::directory_to_db(clm_root, spec_file) {
                Ok((exit_code, out)) => { stdout.push_str(&out); Some(exit_code) }
                Err(e) => { stderr.push_str(&format!("[DIR_TO_DB] ❌ Error: {}\n", e)); Some(1) }
            }
        }
        Commands::JsonlEmit { event_type, kv_args } => {
            match clm_rust_core::jsonl::jsonl_emit(event_type, kv_args.clone(), clm_root) {
                Ok(line) => { stdout.push_str(&line); stdout.push('\n'); Some(0) }
                Err(e) => { stderr.push_str(&format!("[JSONL_EMIT] ❌ Error: {}\n", e)); Some(1) }
            }
        }
        Commands::SqlQueryParameterized { pillar, query, params, json } => {
            match clm_rust_core::db::sql_query_parameterized(pillar, clm_root, query, params.clone(), *json) {
                Ok(res) => {
                    if *json {
                        let parsed: serde_json::Value = serde_json::from_str(&res).unwrap_or_else(|_| serde_json::json!([]));
                        let envelope = serde_json::json!({
                            "status": "success", "data": parsed,
                            "meta": { "runtime": "rust", "version": env!("CARGO_PKG_VERSION") }
                        });
                        stdout.push_str(&serde_json::to_string_pretty(&envelope).unwrap());
                        stdout.push('\n');
                    } else if !res.is_empty() {
                        stdout.push_str(&res);
                        stdout.push('\n');
                    }
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[SQL_QUERY] ❌ Error: {}\n", e)); Some(1) }
            }
        }
        Commands::HandleRegisterBatch { pillar, handle, hash_val, content } => {
            match clm_rust_core::db::handle_register_batch(pillar, clm_root, handle, hash_val, content) {
                Ok(_) => Some(0),
                Err(e) => { stderr.push_str(&format!("[HANDLE_REGISTER] ❌ Error: {}\n", e)); Some(1) }
            }
        }
        Commands::HandleDeleteBatch { pillar, handle } => {
            match clm_rust_core::db::handle_delete_batch(pillar, clm_root, handle) {
                Ok(_) => Some(0),
                Err(e) => { stderr.push_str(&format!("[HANDLE_DELETE] ❌ Error: {}\n", e)); Some(1) }
            }
        }
        Commands::ArchiveCreate { dir, output, did } => {
            let dir_path = std::path::Path::new(dir);
            let out_path = std::path::Path::new(output);
            match clm_rust_core::archive::create_archive(dir_path, out_path, did.as_deref(), clm_root) {
                Ok((manifest, vcard_seal)) => {
                    stdout.push_str(&format!("[ARCHIVE] Created sovereign archive: {}\n[ARCHIVE] Top-level VCard seal: {}\n[ARCHIVE] Registered manifest MCard: {}\n", output, vcard_seal, manifest.archive_id));
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[ARCHIVE ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::ArchiveRestore { input, dir } => {
            let input_path = std::path::Path::new(input);
            let dir_path = std::path::Path::new(dir);
            match clm_rust_core::archive::restore_archive(input_path, dir_path, clm_root) {
                Ok(manifest) => {
                    stdout.push_str(&format!("[RESTORE] Restored sovereign archive: {}\n[RESTORE] Total verified files: {}\n", manifest.archive_id, manifest.files.len()));
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[RESTORE ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::ArchiveVerify { input, dir } => {
            let input_path = std::path::Path::new(input);
            let dir_path = std::path::Path::new(dir);
            match clm_rust_core::archive::verify_archive(input_path, dir_path) {
                Ok(true) => { stdout.push_str("[VERIFY] Sovereign archive verification PASSED. All file hashes match.\n"); Some(0) }
                Ok(false) => { stderr.push_str("[VERIFY ERROR] Verification FAILED. Hash mismatch or missing files.\n"); Some(1) }
                Err(e) => { stderr.push_str(&format!("[VERIFY ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::SyncDeltaCompute { local, peer } => {
            let (local_path, peer_path) = (std::path::Path::new(local), std::path::Path::new(peer));
            let local_json = match std::fs::read_to_string(local_path) {
                Ok(c) => c,
                Err(e) => { stderr.push_str(&format!("[SYNC ERROR] Failed to read local manifest: {}\n", e)); return Some(1); }
            };
            let peer_json = match std::fs::read_to_string(peer_path) {
                Ok(c) => c,
                Err(e) => { stderr.push_str(&format!("[SYNC ERROR] Failed to read peer manifest: {}\n", e)); return Some(1); }
            };
            let local_manifest: clm_rust_core::archive::ArchiveManifest = match serde_json::from_str(&local_json) {
                Ok(m) => m,
                Err(e) => { stderr.push_str(&format!("[SYNC ERROR] Failed to parse local manifest: {}\n", e)); return Some(1); }
            };
            let peer_manifest: clm_rust_core::archive::ArchiveManifest = match serde_json::from_str(&peer_json) {
                Ok(m) => m,
                Err(e) => { stderr.push_str(&format!("[SYNC ERROR] Failed to parse peer manifest: {}\n", e)); return Some(1); }
            };
            let delta = clm_rust_core::crdt::compute_manifest_delta(&local_manifest, &peer_manifest);
            let delta_json = serde_json::to_string_pretty(&delta).unwrap_or_default();
            stdout.push_str(&format!("[SYNC DELTA] Computed delta set size: {}\n{}\n", delta.len(), delta_json));
            Some(0)
        }
        Commands::SyncMerge { target_db, sharing_mode, hash, content } => {
            let db_name = target_db.as_deref().unwrap_or("content_memory.db");
            let mode = clm_rust_core::crdt::PartialSharingMode::from_str(sharing_mode);
            let now = chrono::Utc::now().to_rfc3339();
            match clm_rust_core::crdt::merge_gset_cards(db_name, clm_root, &[(hash.clone(), content.clone(), now)], mode) {
                Ok(merged) => { stdout.push_str(&format!("[SYNC MERGE] Merged {} card(s) into {}\n", merged, db_name)); Some(0) }
                Err(e) => { stderr.push_str(&format!("[SYNC MERGE ERROR] {}\n", e)); Some(1) }
            }
        }
        _ => None,
    }
}