use std::fs;
use std::path::{Path, PathBuf};
use super::get_internal_registry;
use super::orchestrator_intercepts::handle_gate_intercepts;
use super::orchestrator_pipeline::{execute_orchestrator_pipeline, PipelineArgs};
fn emit_gateway_trace(transition: &str, phase: &str, exit_code: i32) {
if crate::cross_cutting::context::CLMContext::get_scoped_or_env("CLM_DISPATCH_SOCK").is_some()
&& crate::cross_cutting::context::CLMContext::get_scoped_or_env("CLM_NESTED_EXEC").is_none()
{
let trace = serde_json::json!({
"type": "trace",
"transition": transition,
"phase": phase,
"exit_code": exit_code,
"agent": crate::cross_cutting::context::CLMContext::get_scoped_or_env("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 let Some(res) = handle_gate_intercepts(
operation, clm_root, clm_file, payload, post_rc, quiet, concrete_impl, clm_data,
) {
return res;
}
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" {
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(|| "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);
}
}
let _payload_guard = if let Some(pay) = payload {
let mut overrides = crate::cross_cutting::context::CLMContextOverrides::default();
overrides.scoped_vars.insert("CLM_PAYLOAD".to_string(), pay.to_string());
let child = crate::cross_cutting::context::CLMContext::current().with_child_scope(overrides);
Some(child.enter_scope())
} else {
None
};
let skip_conditions = crate::cross_cutting::context::CLMContext::get_scoped_or_env("CLM_SKIP_CONDITIONS")
.as_deref() == Some("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) if e.contains("SovereignSubprocessForbiddenError") => {
return Err(e);
}
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 pipeline_args = PipelineArgs {
ctx,
clm_root,
clm_file,
payload,
post_rc,
quiet,
clm_data,
concrete_impl,
operation,
is_rust,
registered_func,
module_path_opt,
process_type,
runtime_str,
skip_conditions,
clm_root_str,
clm_file_str,
};
execute_orchestrator_pipeline(pipeline_args, emit_gateway_trace)
}