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(crate::layer0::vocabulary_env::ENV_CLM_DISPATCH_SOCK).is_some()
&& crate::cross_cutting::context::CLMContext::get_scoped_or_env(crate::layer0::vocabulary_env::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(|| crate::layer0::vocabulary_identities::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,
clock_nanos: fn() -> u128,
) -> Result<i32, crate::evaluator::DispatchError> {
let root_ctx = crate::fiber::Context::root();
try_internal_dispatch_with_context(&root_ctx, clm_root, clm_file, payload, post_rc, quiet, clock_nanos)
}
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,
clock_nanos: fn() -> u128,
) -> Result<i32, crate::evaluator::DispatchError> {
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).into());
}
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".into()),
};
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.map_err(Into::into);
}
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".into()),
};
let process_type = process.get("type")
.and_then(|v| v.as_str())
.unwrap_or("");
let route = super::orchestrator_routes::classify_orchestrator_route(runtime_str, process_type);
let is_rust = match route {
super::orchestrator_routes::OrchestratorRoute::RustInternal => true,
super::orchestrator_routes::OrchestratorRoute::NonRust => false,
super::orchestrator_routes::OrchestratorRoute::FallbackBash => {
return Err(format!("runtime is '{}', not 'rust' — falling through to bash", runtime_str).into());
}
};
if is_rust && process_type != "internal_reference" {
return Err(format!("process.type is '{}', not 'internal_reference'", process_type).into());
}
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(crate::layer0::vocabulary_env::ENV_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(crate::layer0::vocabulary_env::ENV_CLM_SKIP_CONDITIONS)
.as_deref() == Some("1");
if !skip_conditions {
emit_gateway_trace("verify_precondition", "pre", 0);
match crate::evaluator::compose::compose_conditions_dispatch(clm_root, clm_file, "pre", 0, quiet) {
Ok(0) => {}
Ok(rc) => {
eprintln!("CRITICAL: Pre-Gate Failed.");
return Ok(rc);
}
Err(e @ crate::evaluator::DispatchError::SovereignSubprocessForbidden(_)) => {
return Err(e);
}
Err(e) => {
eprintln!("CRITICAL: Pre-Gate Failed: {}", e);
return Ok(crate::layer0::runtime_contract::ClmExitCode::PreconditionOrBoundaryViolation.code());
}
}
}
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,
clock_nanos,
};
execute_orchestrator_pipeline(pipeline_args, emit_gateway_trace)
}