use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use serde_json::Value;
use crate::fs_utils::compute_sha256_hex;
use super::{get_clm_args, get_internal_registry};
use super::runtime;
fn emit_gateway_trace(transition: &str, phase: &str, exit_code: i32) {
if env::var("CLM_DISPATCH_SOCK").is_ok() && env::var("CLM_NESTED_EXEC").is_err() {
let trace = serde_json::json!({
"type": "trace",
"transition": transition,
"phase": phase,
"exit_code": exit_code,
"agent": env::var("ACTIVE_AGENT_DID").unwrap_or_else(|_| "did:clm:bootstrap".to_string()),
});
println!("CLM_TRACE_JSON:{}", trace);
use std::io::Write;
std::io::stdout().flush().ok();
}
}
pub(crate) fn try_internal_dispatch(
clm_root: &Path,
clm_file: &str,
payload: Option<&str>,
post_rc: Option<i32>,
quiet: bool,
) -> Result<i32, String> {
let root_ctx = crate::fiber::Context::root();
try_internal_dispatch_with_context(&root_ctx, clm_root, clm_file, payload, post_rc, quiet)
}
pub(crate) fn try_internal_dispatch_with_context(
ctx: &crate::fiber::Context,
clm_root: &Path,
clm_file: &str,
payload: Option<&str>,
post_rc: Option<i32>,
quiet: bool,
) -> Result<i32, String> {
let clm_path = if Path::new(clm_file).is_absolute() {
PathBuf::from(clm_file)
} else {
clm_root.join(clm_file)
};
if !clm_path.exists() {
return Err(format!("CLM file not found: {:?}", clm_path));
}
let content = fs::read_to_string(&clm_path)
.map_err(|e| format!("Failed to read CLM file: {}", e))?;
let data: serde_yaml::Value = match serde_yaml::from_str::<serde_yaml::Value>(&content) {
Ok(d) => {
let cd = d.get("clm").unwrap_or(&d);
if cd.get("concrete_impl").is_some() {
d
} else {
let normalized_path = crate::normalizer::normalize_syntax(
&clm_path.to_string_lossy(),
clm_root.to_str().unwrap_or(""),
).map_err(|_| "No concrete_impl — not an internal_reference CLM".to_string())?;
let normalized_content = fs::read_to_string(&normalized_path)
.map_err(|e| format!("Failed to read normalized file: {}", e))?;
serde_yaml::from_str(&normalized_content)
.map_err(|e| format!("Failed to parse normalized CLM YAML: {}", e))?
}
}
Err(_) => {
let normalized_path = crate::normalizer::normalize_syntax(
&clm_path.to_string_lossy(),
clm_root.to_str().unwrap_or(""),
).map_err(|e| format!("Failed to parse CLM YAML: {} (normalization also failed: {})", "YAML parse error", e))?;
let normalized_content = fs::read_to_string(&normalized_path)
.map_err(|e| format!("Failed to read normalized file: {}", e))?;
serde_yaml::from_str(&normalized_content)
.map_err(|e| format!("Failed to parse normalized CLM YAML: {}", e))?
}
};
let clm_data = data.get("clm").unwrap_or(&data);
let concrete_impl = match clm_data.get("concrete_impl") {
Some(val) => val,
None => return Err("No concrete_impl — not an internal_reference CLM".to_string()),
};
let operation = concrete_impl.get("operation")
.and_then(|v| v.as_str())
.unwrap_or("");
if operation == "verify_precondition" {
if !quiet {
eprintln!("[clmEval-rs] ⚡ Native gate intercept: verify_precondition (zero-fork)");
}
match super::super::verify::verify_precondition_internal(clm_root, clm_file, quiet) {
Ok(()) => return Ok(0),
Err(e) => {
eprintln!("[clmEval-rs] ❌ Pre-Gate Failed: {}", e);
return Ok(1);
}
}
}
if operation == "validate_postcondition" {
if !quiet {
eprintln!("[clmEval-rs] ⚡ Native gate intercept: validate_postcondition (zero-fork)");
}
let rc = post_rc.unwrap_or(0);
let content = format!("exit code: {}", rc);
let content_hash = format!("sha256:{}", compute_sha256_hex(content.as_bytes()));
let mut op = "unknown".to_string();
let mut impl_hash = "unknown".to_string();
if let Some(pay) = payload {
let pay_path = if Path::new(pay).is_absolute() {
PathBuf::from(pay)
} else {
clm_root.join(pay)
};
let resolved_pay_path = if pay_path.exists() {
pay_path
} else if pay.starts_with("clm/") {
clm_root.join(&pay[4..])
} else {
pay_path
};
if resolved_pay_path.exists() {
if let Ok(c) = fs::read_to_string(&resolved_pay_path)
&& let Ok(yaml) = serde_yaml::from_str::<serde_yaml::Value>(&c) {
let inner = yaml.get("clm").unwrap_or(&yaml);
if let Some(concrete) = inner.get("concrete_impl")
&& let Some(operation_val) = concrete.get("operation").and_then(|v| v.as_str()) {
op = operation_val.to_string();
}
}
if let Ok(bytes) = fs::read(&resolved_pay_path) {
let normalized: Vec<u8> = bytes.into_iter().filter(|&b| b != b'\r').collect();
impl_hash = format!("sha256:{}", compute_sha256_hex(&normalized));
}
}
}
let a_hash = env::var("CLM_ACTIVE_A_HASH").unwrap_or_default();
let c_hash = env::var("CLM_ACTIVE_C_HASH").unwrap_or_default();
let extra_yaml = format!(
"content: \"{}\"\noperation: \"{}\"\nimpl_hash: \"{}\"",
content, op, impl_hash
);
match crate::db::emit_exec_mcard(
"validate_postcondition",
&content_hash,
&extra_yaml,
&a_hash,
&c_hash,
clm_root.to_str().unwrap_or(""),
) {
Ok(exec_mcard_path) => {
if !quiet {
eprintln!("[VCARD POST] ✅ Execution MCard generated: {}", exec_mcard_path);
eprintln!("[VCARD POST] g_time: {}", crate::fs_utils::compute_g_time());
eprintln!("[VCARD POST] content_hash: {}", content_hash);
}
}
Err(e) => {
eprintln!("[VCARD POST] ❌ Failed to generate execution MCard: {}", e);
return Ok(1);
}
}
return Ok(0);
}
if operation.starts_with("ci_validate_") {
let content_type = concrete_impl.get("content_type");
let mime = content_type
.and_then(|ct| ct.get("mime"))
.and_then(|m| m.as_str())
.unwrap_or("");
let payload_file = payload.ok_or_else(|| "No payload file specified for validation".to_string())?;
if !quiet {
eprintln!("[clmEval-rs] ⚡ Native validation intercept: {} for file {} (zero-fork)", operation, payload_file);
}
if let Err(e) = super::super::verify::verify_precondition_internal(clm_root, clm_file, quiet) {
eprintln!("CRITICAL: Pre-Gate Failed: {}", e);
return Ok(1);
}
let is_valid = crate::mime::validate(clm_root.to_str().unwrap_or(""), payload_file, Some(mime));
let exit_code = if is_valid { 0 } else { 1 };
let output = "";
let clm_root_str = clm_root.to_str().unwrap_or("");
if exit_code == 0 {
let a_hash_str = clm_data.get("_meta").and_then(|m| m.get("a_hash")).and_then(|v| v.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| {
let spec = clm_data.get("abstract_spec").cloned().unwrap_or(serde_yaml::Value::Null);
let serialized = serde_yaml::to_string(&spec).unwrap_or_default();
format!("sha256:{}", compute_sha256_hex(serialized.replace('\r', "").as_bytes()))
});
let c_hash_str = clm_data.get("_meta").and_then(|m| m.get("c_hash")).and_then(|v| v.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| {
let spec = clm_data.get("concrete_impl").cloned().unwrap_or(serde_yaml::Value::Null);
let serialized = serde_yaml::to_string(&spec).unwrap_or_default();
format!("sha256:{}", compute_sha256_hex(serialized.replace('\r', "").as_bytes()))
});
let output_hash = format!("sha256:{}", compute_sha256_hex(output.as_bytes()));
let extra_yaml = format!("content: |\n {}", output.replace('\n', "\n "));
let _ = crate::db::emit_exec_mcard(
operation,
&output_hash,
&extra_yaml,
&a_hash_str,
&c_hash_str,
clm_root_str,
);
}
return Ok(exit_code);
}
let runtime_str = concrete_impl.get("runtime")
.and_then(|v| v.as_str())
.unwrap_or("");
let process = match concrete_impl.get("process") {
Some(p) => p,
None => return Err("No process block in concrete_impl".to_string()),
};
let process_type = process.get("type")
.and_then(|v| v.as_str())
.unwrap_or("");
let is_rust = runtime_str == "rust" && process_type == "internal_reference";
let is_non_rust_runtime = runtime_str == "python"
|| runtime_str == "node"
|| runtime_str == "javascript"
|| runtime_str == "shell"
|| runtime_str == "polyglot"
|| runtime_str == "system"
|| runtime_str == "go"
|| runtime_str == "llm"
|| runtime_str == "open_interpreter"
|| (runtime_str == "rust" && process_type == "rust")
|| (runtime_str == "rust" && !is_rust && process_type != "internal_reference")
|| process_type == "compose"
|| process_type == "polyglot"
|| runtime_str == "compose";
if !is_rust && !is_non_rust_runtime {
return Err(format!("runtime is '{}', not 'rust' — falling through to bash", runtime_str));
}
if is_rust
&& process_type != "internal_reference" {
eprintln!("[DEBUG] process_type is '{}', not 'internal_reference'", process_type);
return Err(format!("process.type is '{}', not 'internal_reference'", process_type));
}
let mut module_path_opt = None;
let mut registered_func = None;
if is_rust {
let m_path = process.get("module")
.and_then(|v| v.as_str())
.ok_or_else(|| {
eprintln!("[DEBUG] No process.module specified");
"No process.module specified for internal_reference".to_string()
})?;
module_path_opt = Some(m_path);
registered_func = get_internal_registry(m_path);
if !quiet {
eprintln!("[clmEval-rs] ⚡ Internal dispatch: {} (zero-overhead)", m_path);
}
}
if let Some(pay) = payload {
crate::utils::set_env_var("CLM_PAYLOAD", pay);
}
let skip_conditions = env::var("CLM_SKIP_CONDITIONS").as_deref() == Ok("1");
if !skip_conditions {
emit_gateway_trace("verify_precondition", "pre", 0);
match crate::evaluator::compose::compose_conditions(clm_root, clm_file, "pre", 0, quiet) {
Ok(0) => {}
Ok(rc) => {
eprintln!("CRITICAL: Pre-Gate Failed.");
return Ok(rc);
}
Err(e) => {
eprintln!("CRITICAL: Pre-Gate Failed: {}", e);
return Ok(1);
}
}
}
let clm_root_str = clm_root.to_str().unwrap_or("");
let clm_file_str = clm_path.to_str().unwrap_or("");
let mut a_mcard_opt = None;
let has_signature = if let Some(spec) = clm_data.get("abstract_spec") {
spec.get("signature").is_some()
} else {
clm_data.get("signature").is_some()
};
if has_signature {
match crate::parser::parse_a_mcard(clm_file_str) {
Ok(a) => {
a_mcard_opt = Some(a);
}
Err(e) => {
if !quiet {
eprintln!("[clmEval-rs] ⚠️ Warning: Failed to parse A-MCard spec for validation: {}", e);
}
}
}
}
let mut context_val = serde_json::json!({
"inputs": Value::Null,
"outputs": Value::Null
});
if let Some(ref a_mcard) = a_mcard_opt {
let concrete_args = get_clm_args(clm_file_str).unwrap_or_default();
let mut inputs_map = serde_json::Map::new();
let mut payload_parsed = false;
if let Some(pay) = payload {
let trimmed = pay.trim();
if trimmed.starts_with('{') {
if let Ok(Value::Object(obj)) = serde_json::from_str::<Value>(trimmed) {
for (k, v) in obj {
inputs_map.insert(k, v);
}
payload_parsed = true;
}
} else if trimmed.contains(':')
&& let Ok(data) = serde_yaml::from_str::<Value>(trimmed)
&& let Value::Object(obj) = data {
for (k, v) in obj {
inputs_map.insert(k, v);
}
payload_parsed = true;
}
}
if !payload_parsed
&& let Some(pay) = payload
&& let Value::Object(ref sig_inputs) = a_mcard.signature.inputs
&& sig_inputs.len() == 1 {
let first_key = sig_inputs.keys().next().unwrap();
if let Ok(num) = pay.parse::<i64>() {
inputs_map.insert(first_key.clone(), Value::from(num));
} else if let Ok(f) = pay.parse::<f64>() {
inputs_map.insert(first_key.clone(), Value::from(f));
} else if pay == "true" {
inputs_map.insert(first_key.clone(), Value::Bool(true));
} else if pay == "false" {
inputs_map.insert(first_key.clone(), Value::Bool(false));
} else {
inputs_map.insert(first_key.clone(), Value::String(pay.to_string()));
}
}
if let Value::Object(ref sig_inputs) = a_mcard.signature.inputs {
let keys: Vec<&String> = sig_inputs.keys().collect();
for (i, key) in keys.iter().enumerate() {
if !inputs_map.contains_key(*key)
&& let Some(arg) = concrete_args.get(i) {
if let Ok(num) = arg.parse::<i64>() {
inputs_map.insert((*key).clone(), Value::from(num));
} else if let Ok(f) = arg.parse::<f64>() {
inputs_map.insert((*key).clone(), Value::from(f));
} else if arg == "true" {
inputs_map.insert((*key).clone(), Value::Bool(true));
} else if arg == "false" {
inputs_map.insert((*key).clone(), Value::Bool(false));
} else {
inputs_map.insert((*key).clone(), Value::String(arg.clone()));
}
}
}
}
let inputs_val = Value::Object(inputs_map);
if let Some(obj) = context_val.as_object_mut() {
obj.insert("inputs".to_string(), inputs_val);
}
if !skip_conditions {
for pre in &a_mcard.invariants.preconditions {
match crate::invariants::evaluate_invariant(pre, clm_root_str, &context_val) {
Ok(true) => {
if !quiet {
eprintln!("[VCARD PRE] Invariant '{}' satisfied.", pre);
}
}
Ok(false) => {
eprintln!("[PREP_ERR] Precondition violation: Invariant '{}' failed.", pre);
return Ok(1);
}
Err(e) => {
eprintln!("[PREP_ERR] Precondition check error: Invariant '{}' raised error: {}", pre, e);
return Ok(1);
}
}
}
}
}
let isolated_ctx = ctx.isolate(&["content_memory", "agent_identities", "execution_log"]);
let fiber_id = format!("fiber_{}_{:x}", clm_file.replace(['/', '.'], "_"), rand::random::<u16>());
let fiber = isolated_ctx.spawn_fiber(&fiber_id, vec![]);
let _ = fiber.transition_to(crate::fiber::FiberState::Active);
let sp_token = format!("sp_{}_{:x}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0), rand::random::<u32>());
let mut tri_sp = crate::fiber::disposable::TriDbSavepointGuard::with_pillars(clm_root_str, &sp_token, &["content_memory", "agent_identities"]).ok();
emit_gateway_trace(&format!("execute:{}", operation), "exec", 0);
let run_res = if is_rust {
match registered_func {
Some(f) => f(clm_root_str, clm_file_str),
None => {
let m_path = module_path_opt.unwrap_or("");
if !quiet {
eprintln!("[clmEval-rs] ⚡ Sourcing shell test fallback for unregistered module: {}", m_path);
}
runtime::run_fallback_internal_reference(clm_root_str, clm_file_str, m_path, quiet)
}
}
} else {
runtime::evaluate_non_rust_runtime(clm_root, clm_file, process_type, runtime_str, concrete_impl, payload, post_rc, quiet)
};
match run_res {
Ok((exit_code, output)) => {
let nested_exec = std::env::var("CLM_NESTED_EXEC").unwrap_or_default() == "1";
if !output.is_empty() && (!quiet || nested_exec) {
print!("{}", output);
}
if exit_code == 0 {
if let Some(ref a_mcard) = a_mcard_opt {
let mut outputs_map = serde_json::Map::new();
let trimmed = output.trim();
let mut parsed = false;
if trimmed.starts_with('{') {
if let Ok(Value::Object(obj)) = serde_json::from_str::<Value>(trimmed) {
for (k, v) in obj {
outputs_map.insert(k, v);
}
parsed = true;
}
} else if trimmed.contains(':')
&& let Ok(data) = serde_yaml::from_str::<Value>(trimmed)
&& let Value::Object(obj) = data {
for (k, v) in obj {
outputs_map.insert(k, v);
}
parsed = true;
}
if !parsed
&& let Value::Object(ref sig_outputs) = a_mcard.signature.outputs
&& sig_outputs.len() == 1 {
let first_key = sig_outputs.keys().next().unwrap();
if let Ok(num) = trimmed.parse::<i64>() {
outputs_map.insert(first_key.clone(), Value::from(num));
} else if let Ok(f) = trimmed.parse::<f64>() {
outputs_map.insert(first_key.clone(), Value::from(f));
} else if trimmed == "true" {
outputs_map.insert(first_key.clone(), Value::Bool(true));
} else if trimmed == "false" {
outputs_map.insert(first_key.clone(), Value::Bool(false));
} else {
outputs_map.insert(first_key.clone(), Value::String(trimmed.to_string()));
}
}
if !outputs_map.contains_key("a_hash")
&& let Ok(h) = std::env::var("CLM_ACTIVE_A_HASH") {
outputs_map.insert("a_hash".to_string(), Value::String(h));
}
if !outputs_map.contains_key("c_hash")
&& let Ok(h) = std::env::var("CLM_ACTIVE_C_HASH") {
outputs_map.insert("c_hash".to_string(), Value::String(h));
}
if !outputs_map.contains_key("b_hash")
&& let Ok(h) = std::env::var("CLM_ACTIVE_B_HASH") {
outputs_map.insert("b_hash".to_string(), Value::String(h));
}
if let Some(obj) = context_val.as_object_mut() {
obj.insert("outputs".to_string(), Value::Object(outputs_map));
}
if !skip_conditions {
for post in &a_mcard.invariants.postconditions {
match crate::invariants::evaluate_invariant(post, clm_root_str, &context_val) {
Ok(true) => {
if !quiet {
eprintln!("[VCARD POST] Invariant '{}' satisfied.", post);
}
}
Ok(false) => {
eprintln!("[POST_ERR] Postcondition violation: Invariant '{}' failed.", post);
let _ = fiber.transition_to(crate::fiber::FiberState::Failed(format!("Postcondition violation: {}", post)));
let _ = fiber.dispose();
if let Some(ref mut sp) = tri_sp {
let _ = sp.rollback();
}
return Ok(2);
}
Err(e) => {
eprintln!("[POST_ERR] Postcondition check error: Invariant '{}' raised error: {}", post, e);
let _ = fiber.transition_to(crate::fiber::FiberState::Failed(format!("Postcondition check error: {}", e)));
let _ = fiber.dispose();
if let Some(ref mut sp) = tri_sp {
let _ = sp.rollback();
}
return Ok(2);
}
}
}
}
}
let raw_hex = compute_sha256_hex(output.as_bytes());
let output_hash = format!("sha256:{}", raw_hex);
let a_hash_str = clm_data.get("_meta").and_then(|m| m.get("a_hash")).and_then(|v| v.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| {
let spec = clm_data.get("abstract_spec").cloned().unwrap_or(serde_yaml::Value::Null);
let serialized = serde_yaml::to_string(&spec).unwrap_or_default();
format!("sha256:{}", compute_sha256_hex(serialized.replace('\r', "").as_bytes()))
});
let c_hash_str = clm_data.get("_meta").and_then(|m| m.get("c_hash")).and_then(|v| v.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| {
let spec = clm_data.get("concrete_impl").cloned().unwrap_or(serde_yaml::Value::Null);
let serialized = serde_yaml::to_string(&spec).unwrap_or_default();
format!("sha256:{}", compute_sha256_hex(serialized.replace('\r', "").as_bytes()))
});
let operation = clm_data.get("concrete_impl")
.and_then(|v| v.get("operation"))
.and_then(|v| v.as_str())
.unwrap_or("unknown");
let inputs_len = clm_data.get("concrete_impl")
.and_then(|v| v.get("inputs"))
.and_then(|v| v.as_sequence())
.map(|a| a.len())
.unwrap_or(0);
let outputs_len = clm_data.get("concrete_impl")
.and_then(|v| v.get("outputs"))
.and_then(|v| v.as_sequence())
.map(|a| a.len())
.unwrap_or(0);
let x_t_d = (outputs_len as i32) - (inputs_len as i32);
if !quiet {
eprintln!("[VCARD POST] 🔍 Noetherian P-invariant conservation check: x^T D = 0");
}
if x_t_d == 0 {
if !quiet {
eprintln!(" ✅ P-Inv: place marking conservation holds (x^T D = 0) [OK]");
}
} else {
if !quiet {
eprintln!(" ⚠️ P-Inv: place marking conservation drift detected: x^T D = {} (inputs={}, outputs={})", x_t_d, inputs_len, outputs_len);
}
}
let extra_yaml = format!("content: |\n {}", output.replace('\n', "\n "));
match crate::db::emit_exec_mcard(
operation,
&output_hash,
&extra_yaml,
&a_hash_str,
&c_hash_str,
clm_root_str,
) {
Ok(exec_mcard_path) => {
if !quiet {
eprintln!("[VCARD POST] ✅ Execution MCard generated: {}", exec_mcard_path);
eprintln!("[VCARD POST] g_time: {}", crate::fs_utils::compute_g_time());
eprintln!("[VCARD POST] content_hash: {}", raw_hex);
}
}
Err(e) => {
eprintln!("[VCARD POST] ❌ Failed to emit execution MCard: {}", e);
}
}
}
if !skip_conditions {
emit_gateway_trace("validate_postcondition", "post", exit_code);
match crate::evaluator::compose::compose_conditions(clm_root, clm_file, "post", exit_code, quiet) {
Ok(0) => {}
Ok(rc) => {
eprintln!("CRITICAL: Post-Gate Failed.");
let _ = fiber.transition_to(crate::fiber::FiberState::Failed("Post-Gate Failed".to_string()));
let _ = fiber.dispose();
if let Some(ref mut sp) = tri_sp {
let _ = sp.rollback();
}
return Ok(rc);
}
Err(e) => {
eprintln!("CRITICAL: Post-Gate Failed: {}", e);
let _ = fiber.transition_to(crate::fiber::FiberState::Failed(format!("Post-Gate Failed: {}", e)));
let _ = fiber.dispose();
if let Some(ref mut sp) = tri_sp {
let _ = sp.rollback();
}
return Ok(2);
}
}
}
if let Some(ref mut sp) = tri_sp {
let _ = sp.commit();
}
if exit_code == 0 {
let _ = fiber.dispose();
} else {
let _ = fiber.transition_to(crate::fiber::FiberState::Failed(format!("Exit code {}", exit_code)));
let _ = fiber.dispose();
}
emit_gateway_trace("vcard_seal", "seal", exit_code);
Ok(exit_code)
}
Err(e) => {
eprintln!("[clmEval-rs] ❌ Internal dispatch error: {}", e);
let _ = fiber.transition_to(crate::fiber::FiberState::Failed(format!("Internal dispatch error: {}", e)));
let _ = fiber.dispose();
if let Some(ref mut sp) = tri_sp {
let _ = sp.rollback();
}
Ok(1)
}
}
}