clm-kernel 0.0.15

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

pub(super) fn handle_services_cmd(
    command: &Commands,
    clm_root: &str,
    stdout: &mut String,
    stderr: &mut String,
) -> Option<i32> {
    match command {
        Commands::ObsConfig { tempo, loki, mimir, sampling_rate, db } => {
            match clm_rust_core::observability::configure_observability(db, Some(clm_root), tempo, loki, mimir, Some(*sampling_rate)) {
                Ok(cfg) => {
                    stdout.push_str(&format!("[OBS CONFIG] Configured observability telemetry in {}\n  Tempo: {}\n  Loki: {}\n  Mimir: {}\n  Sampling Rate: {}\n  Handle: {}\n", db, cfg.tempo_endpoint, cfg.loki_endpoint, cfg.mimir_endpoint, cfg.sampling_rate, cfg.handle));
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[OBS CONFIG ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::ObsTraceEmit { trace_id, span_id, parent_span_id, pcard, vcard_hash, duration_ms, db } => {
            match clm_rust_core::observability::emit_trace_span(db, Some(clm_root), trace_id, span_id, parent_span_id.as_deref(), pcard, vcard_hash, *duration_ms) {
                Ok(tr) => {
                    stdout.push_str(&format!("[OBS TRACE EMIT] Emitted trace span {} ({}) in {}\n  PCard: {}\n  VCard Hash: {}\n  Duration: {}ms\n  Handle: {}\n", tr.trace_id, tr.span_id, db, tr.pcard_handle, tr.vcard_hash, tr.duration_ms, tr.handle));
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[OBS TRACE EMIT ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::ObsMetricRecord { metric_name, value, labels, db } => {
            match clm_rust_core::observability::record_metric(db, Some(clm_root), metric_name, *value, labels.as_deref()) {
                Ok(m) => {
                    stdout.push_str(&format!("[OBS METRIC RECORD] Recorded metric {} = {} in {}\n  Labels: {}\n  Handle: {}\n", m.metric_name, m.value, db, m.labels, m.handle));
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[OBS METRIC RECORD ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::ObsLogEmit { trace_id, level, vcard_hash, eoa_did, message, db } => {
            match clm_rust_core::observability::emit_structured_log(db, Some(clm_root), trace_id, level, vcard_hash, eoa_did, message) {
                Ok(l) => {
                    stdout.push_str(&format!("[OBS LOG EMIT] Emitted {} log for trace {} in {}\n  Log ID: {}\n  EOA DID: {}\n  VCard Hash: {}\n  Message: {}\n", l.level, l.trace_id, db, l.log_id, l.eoa_did, l.vcard_hash, l.message));
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[OBS LOG EMIT ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::ObsTraceGet { trace_id, db } => {
            match clm_rust_core::observability::get_trace(db, Some(clm_root), trace_id) {
                Ok(tr) => {
                    stdout.push_str(&format!("[OBS TRACE GET] Found trace span {}\n  PCard: {}\n  VCard Hash: {}\n  Duration: {}ms\n", tr.trace_id, tr.pcard_handle, tr.vcard_hash, tr.duration_ms));
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[OBS TRACE GET ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::ObsMetricGet { metric_name, db } => {
            match clm_rust_core::observability::get_metric(db, Some(clm_root), metric_name) {
                Ok(m) => {
                    stdout.push_str(&format!("[OBS METRIC GET] Found metric {} = {}\n  Labels: {}\n", m.metric_name, m.value, m.labels));
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[OBS METRIC GET ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::BackupCreate { tier, output_dir, db } => {
            match clm_rust_core::backup::create_backup_snapshot(db, Some(clm_root), tier, output_dir) {
                Ok(snap) => {
                    stdout.push_str(&format!("[BACKUP CREATE] Created {} snapshot {} in {}\n  Card Count: {}\n  Merkle DAG Root: {}\n  Handle: {}\n", snap.tier, snap.snapshot_id, output_dir, snap.card_count, snap.merkle_dag_root, snap.handle));
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[BACKUP CREATE ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::BackupRestore { snapshot_id, input_dir, db } => {
            match clm_rust_core::backup::restore_backup_snapshot(db, Some(clm_root), snapshot_id, input_dir) {
                Ok(rec) => {
                    stdout.push_str(&format!("[BACKUP RESTORE] ✅ Restored snapshot {} in {}\n  Cards Restored: {}\n  Verification Verdict: {}\n  Handle: {}\n", rec.snapshot_id, db, rec.cards_restored, rec.verification_verdict, rec.handle));
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[BACKUP RESTORE ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::BackupVerify { snapshot_id, db } => {
            match clm_rust_core::backup::verify_backup_snapshot(db, Some(clm_root), snapshot_id) {
                Ok(verified) => {
                    if verified {
                        stdout.push_str(&format!("[BACKUP VERIFY] ✅ Snapshot {} restore integrity verified\n", snapshot_id));
                        Some(0)
                    } else {
                        stdout.push_str(&format!("[BACKUP VERIFY] ❌ Snapshot {} restore verification failed\n", snapshot_id));
                        Some(1)
                    }
                }
                Err(e) => { stderr.push_str(&format!("[BACKUP VERIFY ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::BackupShardGenerate { did, secret, guardians, threshold, db } => {
            match clm_rust_core::backup::generate_recovery_shards(db, Some(clm_root), did, secret, *guardians, *threshold) {
                Ok(rec) => {
                    stdout.push_str(&format!("[BACKUP SHARD GENERATE] Generated {} recovery shards ({}/{} threshold) for {}\n  Handle: {}\n", rec.guardian_count, rec.threshold, rec.guardian_count, rec.did, rec.handle));
                    for s in &rec.shards {
                        stdout.push_str(&format!("  Shard {}: {}\n", s.index, s.value));
                    }
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[BACKUP SHARD GENERATE ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::BackupKeyReassemble { shards } => {
            match clm_rust_core::backup::reassemble_recovery_key(shards) {
                Ok(secret) => {
                    stdout.push_str(&format!("[BACKUP KEY REASSEMBLE] ✅ Secret key reassembled: {}\n", secret));
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[BACKUP KEY REASSEMBLE ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::DcaMint { content_hash, owner, db } => {
            match clm_rust_core::tokens::mint_dca_nft(db, Some(clm_root), content_hash, owner) {
                Ok(dca) => {
                    stdout.push_str(&format!("[DCA MINT] Minted Digital Content Asset {} (NFT: {}) for {}\n  Content Hash: {}\n  Handle: {}\n", dca.asset_id, dca.token_id, dca.owner_did, dca.content_hash, dca.handle));
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[DCA MINT ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::NftTransfer { token_id, current_owner, new_owner, db } => {
            match clm_rust_core::tokens::transfer_nft(db, Some(clm_root), token_id, current_owner, new_owner) {
                Ok(rec) => {
                    stdout.push_str(&format!("[NFT TRANSFER] ✅ Transferred NFT {} from {} to {}\n  Handle: {}\n", rec.token_id, rec.previous_owner_did, rec.new_owner_did, rec.handle));
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[NFT TRANSFER ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::SbtMint { recipient, role, db } => {
            match clm_rust_core::tokens::mint_soulbound_credential(db, Some(clm_root), recipient, role) {
                Ok(sbt) => {
                    stdout.push_str(&format!("[SBT MINT] Minted Soulbound Credential {} ({}) for {}\n  Transferable: {}\n  Handle: {}\n", sbt.credential_id, sbt.role_name, sbt.recipient_did, sbt.is_transferable, sbt.handle));
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[SBT MINT ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::CreditsMint { recipient, amount, db } => {
            match clm_rust_core::tokens::mint_community_credits(db, Some(clm_root), recipient, *amount) {
                Ok(c) => {
                    stdout.push_str(&format!("[CREDITS MINT] Minted {} community credits for {}\n  New Balance: {}\n  Handle: {}\n", amount, c.did, c.balance, c.handle));
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[CREDITS MINT ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::EditionMint { asset_id, owner, edition_no, max_editions, db } => {
            match clm_rust_core::tokens::mint_edition_token(db, Some(clm_root), asset_id, owner, *edition_no, *max_editions) {
                Ok(ed) => {
                    stdout.push_str(&format!("[EDITION MINT] Minted Edition {} ({}/{}) for asset {} to {}\n  Handle: {}\n", ed.edition_id, ed.edition_number, ed.max_editions, ed.asset_id, ed.owner_did, ed.handle));
                    Some(0)
                }
                Err(e) => { stderr.push_str(&format!("[EDITION MINT ERROR] {}\n", e)); Some(1) }
            }
        }
        Commands::Hash { algo, prefixed, file, input } => {
            let bytes: Result<Vec<u8>, String> = if let Some(path) = file {
                std::fs::read(path).map_err(|e| format!("Failed to read file '{}': {}", path, e))
            } else if let Some(inp) = input {
                Ok(inp.clone().into_bytes())
            } else {
                let mut buffer = Vec::new();
                match std::io::stdin().read_to_end(&mut buffer) {
                    Ok(_) => Ok(buffer),
                    Err(e) => Err(format!("Failed to read stdin: {}", e)),
                }
            };

            match bytes {
                Ok(content) => {
                    let reg = clm_rust_core::hash::global_registry().lock().unwrap();
                    let prefix = if algo.ends_with(':') { algo.clone() } else { format!("{}:", algo) };
                    if let Some(provider) = reg.get(&prefix) {
                        let raw = provider.hash(&content);
                        if *prefixed {
                            stdout.push_str(&format!("{}{}\n", provider.prefix(), raw));
                        } else {
                            stdout.push_str(&format!("{}\n", raw));
                        }
                        Some(0)
                    } else {
                        stderr.push_str(&format!("Unknown hash algorithm: '{}'. Available: {:?}\n", algo, reg.algorithms()));
                        Some(1)
                    }
                }
                Err(e) => {
                    stderr.push_str(&format!("{}\n", e));
                    Some(1)
                }
            }
        }
        _ => None,
    }
}