use crate::epiplexity::{compute_epiplexity_for_transition, EpiplexityMetrics};
use super::types::TransitionYaml;
use super::sys_ffi::{run_command_with_timeout, get_file_fd, sys_close, FdRedirectGuard};
use super::token_ops::vcard_gate;
use super::EVAL_CALLBACK;
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::Path;
pub fn execute_pcard_binding(
db_conn: &rusqlite::Connection,
t: &TransitionYaml,
clm_root: &str,
per_trans_agent_did: &str,
sponsor_did: &str,
pcard_hash: &str,
input_color: &str,
previous_metrics: Option<&EpiplexityMetrics>,
threshold_signature: Option<&str>,
guardian_dids: Option<&[String]>,
) -> Result<(i64, String, String, String, EpiplexityMetrics), String> {
let mut exec_exit_code;
let mut exec_output;
let _ = vcard_gate(
db_conn,
"callback",
pcard_hash,
"null",
&[],
&chrono::Local::now()
.format("%Y-%m-%dT%H:%M:%S%z")
.to_string(),
per_trans_agent_did,
sponsor_did,
"self",
&env::var("CLM_EXECUTION_LOCALE_HASH").unwrap_or_default(),
&env::var("CLM_TRANSPORT_REF").unwrap_or_else(|_| "local".to_string()),
clm_root,
None,
threshold_signature,
guardian_dids,
)?;
if let Some(binding) = &t.binding {
let mut retry_count = 0;
loop {
let mut base_path = binding.path.clone();
let mut symbol_part = String::new();
if let Some(pos) = binding.path.find('#') {
base_path = binding.path[..pos].to_string();
symbol_part = binding.path[pos + 1..].to_string();
}
let mut resolved_path = Path::new(&base_path).to_path_buf();
if !resolved_path.exists() {
let alt_path = Path::new(clm_root).join(&base_path);
if alt_path.exists() {
resolved_path = alt_path;
}
}
let mut cmd_envs = HashMap::new();
cmd_envs.insert("CLM_STATE_TOKEN".to_string(), input_color.to_string());
cmd_envs.insert("CLM_BINDING_TYPE".to_string(), binding.r#type.clone());
cmd_envs.insert("CLM_ROOT".to_string(), clm_root.to_string());
cmd_envs.insert("TARGET_FILE".to_string(), input_color.to_string());
cmd_envs.insert("CLM_PAYLOAD".to_string(), input_color.to_string());
for (k, v) in &binding.context {
cmd_envs.insert(k.clone(), v.clone());
}
for (k, v) in crate::utils::collect_clm_mock_vars() {
cmd_envs.insert(k, v);
}
match binding.r#type.as_str() {
"script" => {
let mut cmd = if !symbol_part.is_empty() {
let mut c = std::process::Command::new(crate::fs_utils::get_bash_command());
c.arg("-c");
c.arg(format!(
"source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/evaluator/shell_utils.sh\" && source \"{}\" && \"{}\" \"$@\"",
clm_root,
resolved_path.to_string_lossy(),
symbol_part
));
c.arg("--");
c
} else {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if let Ok(metadata) = fs::metadata(&resolved_path) {
let mut perms = metadata.permissions();
perms.set_mode(0o755);
let _ = fs::set_permissions(&resolved_path, perms);
}
std::process::Command::new(&resolved_path)
}
#[cfg(windows)]
{
let mut c = std::process::Command::new(crate::fs_utils::get_bash_command());
c.arg("-c");
c.arg(format!("source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/evaluator/shell_utils.sh\" && source \"{}\"", clm_root, resolved_path.to_string_lossy()));
c
}
};
cmd.env_clear();
for (k, v) in std::env::vars() {
if !k.starts_with("CLM_") {
cmd.env(k, v);
}
}
let clm_whitelist = [
"CLM_NESTED_EXEC",
"CLM_RUST_DAEMON_PORT",
"CLM_RUNTIME_BACKEND",
"CLM_RUN_ID", "CLM_ZERO_FS", "CLM_PETRI_MARKING_DIR", "CLM_EVENT_LOG_PATH",
"CLM_ROOT", "PROJECT_ROOT", "CLM_TARGET_FILE", "CLM_PAYLOAD_FILE",
"CLM_ACTIVE_A_HASH", "CLM_ACTIVE_C_HASH", "CLM_MLP_CONTEXT", "CLM_PAYLOAD",
"CLM_SESSION_DELEGATION", "CLM_KENOTIC_SPONSOR_DID", "CLM_EXECUTION_LOCALE_HASH",
"CLM_TRANSPORT_REF", "CLM_PETRI_KENOTIC", "CLM_REPL_TRACE", "CLM_NO_SANDBOX",
"CLM_SYMBOL_HANDLES", "CLM_DB_BACKEND", "CLM_MEMBROKER_PORT", "CLM_MEMBROKER_NO_DISK",
"CLM_MEMBROKER_SNAP_DIR", "CLM_SCRATCH", "CLM_TEST_FAST_BOOT", "CLM_SKIP_GRAMMAR",
"CLM_PETRI_HALT", "CLM_PETRI_VISUAL", "CLM_QUIET",
"CLM_NATIVE_PETRI_VM", "CLM_DISPATCH_SOCK", "CLM_SCRIPT_CONTENT",
"CLM_ENTRY_POINT", "CLM_FILE", "CLM_RUST_PORT_FILE"
];
for var_name in &clm_whitelist {
if let Ok(val) = std::env::var(var_name) {
cmd.env(var_name, val);
}
}
for arg in &binding.args {
cmd.arg(arg);
}
for (k, v) in &cmd_envs {
cmd.env(k, v);
}
let timeout = std::time::Duration::from_secs(binding.timeout);
match run_command_with_timeout(&mut cmd, timeout) {
Ok((status, stdout_str, stderr_str)) => {
exec_exit_code = status.code().unwrap_or(0) as i64;
exec_output = stdout_str;
if exec_exit_code != 0 {
eprintln!(
"Transition binding failed (exit {}): {}",
exec_exit_code, stderr_str
);
}
}
Err(e) => {
eprintln!("run_command_with_timeout failed: {}", e);
exec_exit_code = 124;
exec_output = e;
}
}
}
"yaml" => {
if let Ok(content) = fs::read_to_string(&resolved_path) {
exec_output = content;
exec_exit_code = 0;
} else {
exec_output = format!(
"Failed to read YAML binding file: {}",
resolved_path.display()
);
exec_exit_code = 1;
}
}
"hash" => {
let mut hash_content = String::new();
if let Ok(Some(content)) = crate::db::resolve_handle_content(
"content_memory",
clm_root,
&binding.r#ref,
) {
hash_content = content;
} else if let Ok(Some(content)) = crate::db::resolve_handle_content(
"execution_log",
clm_root,
&binding.r#ref,
) {
hash_content = content;
} else {
let card_content: Option<String> = db_conn
.query_row(
"SELECT content FROM card WHERE hash = ?",
rusqlite::params![binding.r#ref],
|row| row.get(0),
)
.ok();
if let Some(c) = card_content {
hash_content = c;
}
}
if !hash_content.is_empty() {
exec_output = hash_content;
exec_exit_code = 0;
} else {
exec_output = format!(
"Hash not found in card stores: {}",
binding.r#ref
);
exec_exit_code = 1;
}
}
"clm" if std::env::var("CLM_RUNTIME_BACKEND").as_deref() == Ok("rust") => {
let old_envs: HashMap<String, String> = std::env::vars().collect();
let clm_whitelist = [
"CLM_NESTED_EXEC",
"CLM_RUST_DAEMON_PORT",
"CLM_RUNTIME_BACKEND",
"CLM_RUN_ID", "CLM_ZERO_FS", "CLM_PETRI_MARKING_DIR", "CLM_EVENT_LOG_PATH",
"CLM_ROOT", "PROJECT_ROOT", "CLM_TARGET_FILE", "CLM_PAYLOAD_FILE",
"CLM_ACTIVE_A_HASH", "CLM_ACTIVE_C_HASH", "CLM_MLP_CONTEXT", "CLM_PAYLOAD",
"CLM_SESSION_DELEGATION", "CLM_KENOTIC_SPONSOR_DID", "CLM_EXECUTION_LOCALE_HASH",
"CLM_TRANSPORT_REF", "CLM_PETRI_KENOTIC", "CLM_REPL_TRACE", "CLM_NO_SANDBOX",
"CLM_SYMBOL_HANDLES", "CLM_DB_BACKEND", "CLM_MEMBROKER_PORT", "CLM_MEMBROKER_NO_DISK",
"CLM_MEMBROKER_SNAP_DIR", "CLM_SCRATCH", "CLM_TEST_FAST_BOOT", "CLM_SKIP_GRAMMAR",
"CLM_PETRI_HALT", "CLM_PETRI_VISUAL", "CLM_QUIET",
"CLM_NATIVE_PETRI_VM", "CLM_DISPATCH_SOCK", "CLM_SCRIPT_CONTENT",
"CLM_ENTRY_POINT", "CLM_FILE", "CLM_RUST_PORT_FILE", "CLM_SKIP_CONDITIONS",
"CLM_TARGET_PATH", "CLM_AGENT_CLASS", "CLM_AGENT_ROLE",
"CLM_RISK_LEVEL", "CLM_EOA_APPROVAL", "CLM_AGENT_DID",
"CLM_ACTIVE_FILE", "CLM_LAST_MCARD_HASH", "CLM_LAST_MCARD_FILE"
];
for k in old_envs.keys() {
if k.starts_with("CLM_") && !clm_whitelist.contains(&k.as_str()) && !k.starts_with("CLM_MOCK_") {
crate::utils::remove_env_var(k);
}
}
crate::utils::set_env_var("CLM_NESTED_EXEC", "1");
crate::utils::set_env_var("CLM_SKIP_CONDITIONS", "1");
let nested_file_path = resolved_path.to_string_lossy().to_string();
crate::utils::set_env_var("CLM_NESTED_FILE", &nested_file_path);
for (k, v) in &cmd_envs {
crate::utils::set_env_var(k, v);
}
let depth = crate::db::thread_local_depth_increment();
let current_id = crate::db::TEST_SANDBOX_DB_ID.with(|id| {
id.borrow().clone().unwrap_or_else(|| "default".to_string())
});
let nested_id = format!("{}_depth_{}", current_id, depth);
let sandbox_guard = crate::db::DatabaseSandboxGuard::activate(&nested_id);
let quiet = std::env::var("CLM_QUIET").as_deref() == Ok("true");
let run_res = {
let temp_dir = std::env::temp_dir();
let temp_path = temp_dir.join(format!("clm_captured_stdout_{}", std::process::id()));
let temp_file_res = std::fs::File::create(&temp_path);
match temp_file_res {
Ok(temp_file) => {
let temp_fd = get_file_fd(&temp_file);
if temp_fd < 0 {
let _ = std::fs::remove_file(&temp_path);
Err("Failed to get file descriptor".to_string())
} else {
match FdRedirectGuard::redirect_stdout_to(temp_fd) {
Ok(mut guard) => {
let eval_fn = {
let lock = EVAL_CALLBACK.read().unwrap();
*lock
};
let res = if let Some(f) = eval_fn {
f(
Path::new(clm_root),
Some(&nested_file_path),
if input_color == "null" || input_color.is_empty() {
None
} else {
Some(input_color)
},
None,
quiet,
Some(&format!("nested_{}", depth)),
)
} else {
Err("Evaluator callback not registered".to_string())
};
let _ = guard.restore();
unsafe { sys_close(temp_fd); }
let mut captured = String::new();
if let Ok(mut read_file) = std::fs::File::open(&temp_path) {
use std::io::Read;
read_file.read_to_string(&mut captured).ok();
}
let _ = std::fs::remove_file(&temp_path);
match res {
Ok(exit_code) => Ok((exit_code as i64, captured)),
Err(e) => Err(e),
}
}
Err(err) => {
unsafe { sys_close(temp_fd); }
let _ = std::fs::remove_file(&temp_path);
Err(format!("Failed to redirect stdout: {}", err))
}
}
}
}
Err(e) => Err(format!("Failed to create temp file: {}", e)),
}
};
crate::db::thread_local_depth_decrement();
drop(sandbox_guard);
for (k, _) in std::env::vars() {
if k.starts_with("CLM_") {
crate::utils::remove_env_var(&k);
}
}
for (k, v) in old_envs {
crate::utils::set_env_var(&k, &v);
}
match run_res {
Ok((exit_code, output)) => {
exec_exit_code = exit_code;
exec_output = output;
if exec_exit_code != 0 {
eprintln!("CLM native nested invoke failed with exit {}", exec_exit_code);
}
}
Err(e) => {
eprintln!("In-process CPN-VM transition evaluation failed: {}", e);
exec_exit_code = 124;
exec_output = e;
}
}
}
"clm" => {
let mut c = std::process::Command::new(crate::fs_utils::get_bash_command());
c.env_clear();
for (k, v) in std::env::vars() {
if !k.starts_with("CLM_") {
c.env(k, v);
}
}
for (k, v) in crate::utils::collect_clm_mock_vars() {
c.env(k, v);
}
let clm_whitelist = [
"CLM_NESTED_EXEC",
"CLM_RUST_DAEMON_PORT",
"CLM_RUNTIME_BACKEND",
"CLM_RUN_ID", "CLM_ZERO_FS", "CLM_PETRI_MARKING_DIR", "CLM_EVENT_LOG_PATH",
"CLM_ROOT", "PROJECT_ROOT", "CLM_TARGET_FILE", "CLM_PAYLOAD_FILE",
"CLM_ACTIVE_A_HASH", "CLM_ACTIVE_C_HASH", "CLM_MLP_CONTEXT", "CLM_PAYLOAD",
"CLM_SESSION_DELEGATION", "CLM_KENOTIC_SPONSOR_DID", "CLM_EXECUTION_LOCALE_HASH",
"CLM_TRANSPORT_REF", "CLM_PETRI_KENOTIC", "CLM_REPL_TRACE", "CLM_NO_SANDBOX",
"CLM_SYMBOL_HANDLES", "CLM_DB_BACKEND", "CLM_MEMBROKER_PORT", "CLM_MEMBROKER_NO_DISK",
"CLM_MEMBROKER_SNAP_DIR", "CLM_SCRATCH", "CLM_TEST_FAST_BOOT", "CLM_SKIP_GRAMMAR",
"CLM_PETRI_HALT", "CLM_PETRI_VISUAL", "CLM_QUIET",
"CLM_TARGET_PATH", "CLM_AGENT_CLASS", "CLM_AGENT_ROLE",
"CLM_RISK_LEVEL", "CLM_EOA_APPROVAL", "CLM_AGENT_DID",
"CLM_ACTIVE_FILE", "CLM_LAST_MCARD_HASH", "CLM_LAST_MCARD_FILE"
];
for var_name in &clm_whitelist {
if let Ok(val) = std::env::var(var_name) {
c.env(var_name, val);
}
}
c.arg("-c");
c.arg(format!(
"source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/evaluator/shell_utils.sh\" && source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/layer1_cpn_vm/runtime_adapters.sh\" && source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/layer1_cpn_vm/process_dispatch.sh\" && invoke_process \"{}\" \"{}\"",
clm_root, clm_root, clm_root, resolved_path.to_string_lossy(), input_color
));
for (k, v) in &cmd_envs {
c.env(k, v);
}
let timeout = std::time::Duration::from_secs(binding.timeout);
match run_command_with_timeout(&mut c, timeout) {
Ok((status, stdout_str, stderr_str)) => {
exec_exit_code = status.code().unwrap_or(0) as i64;
exec_output = stdout_str;
if exec_exit_code != 0 {
eprintln!(
"CLM invoke failed (exit {}): {}",
exec_exit_code, stderr_str
);
}
}
Err(e) => {
eprintln!("run_command_with_timeout (clm) failed: {}", e);
exec_exit_code = 124;
exec_output = e;
}
}
}
other => {
let dispatcher = crate::runtime_adapter::RuntimeDispatcher::with_defaults();
if dispatcher.has(other) {
let script_content = if resolved_path.exists() {
fs::read_to_string(&resolved_path)
.map_err(|e| format!("Failed to read runtime script: {}", e))?
} else {
binding.path.clone()
};
let input = serde_json::Value::String(input_color.to_string());
match dispatcher.dispatch(other, &script_content, &input) {
Ok(result) => {
let output = match result {
serde_json::Value::String(s) => s,
serde_json::Value::Number(n) => n.to_string(),
serde_json::Value::Bool(b) => b.to_string(),
serde_json::Value::Null => String::new(),
other_val => other_val.to_string(),
};
exec_exit_code = 0;
exec_output = output;
}
Err(e) => {
exec_exit_code = 1;
exec_output = e;
}
}
} else {
return Err(format!("Unknown binding type: {}", other));
}
}
}
if exec_exit_code == 2
&& exec_output.contains("type: \"meta/content_missing\"")
&& retry_count < 1
{
let mut missing_handle = String::new();
for line in exec_output.lines() {
if line.contains("handle:")
&& let Some(start_pos) = line.find('"')
&& let Some(end_pos) = line[start_pos + 1..].find('"') {
missing_handle = line
[start_pos + 1..start_pos + 1 + end_pos]
.to_string();
break;
}
}
if !missing_handle.is_empty() {
eprintln!(
"[IoC] VM Intercepted ContentMissing for handle: {}",
missing_handle
);
let mut r_cmd = std::process::Command::new(crate::fs_utils::get_bash_command());
r_cmd.arg("-c");
r_cmd.arg(format!(
"source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/evaluator/shell_utils.sh\" && source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/layer3_network/route_handle.sh\" && route_handle \"{}\"",
clm_root, clm_root, missing_handle
));
if r_cmd.status().map(|s| s.success()).unwrap_or(false) {
eprintln!(
"[IoC] VM successfully resolved {} externally. Retrying transition...",
missing_handle
);
retry_count += 1;
continue;
} else {
eprintln!("[IoC] VM failed to resolve {} externally.", missing_handle);
}
}
}
break;
}
} else {
exec_exit_code = t.exit_code;
exec_output = t
.content
.clone()
.unwrap_or_else(|| format!("output_{}", t.id));
}
let final_content = if let Some(binding) = &t.binding {
match binding.output_map.as_str() {
"stdout" => exec_output.clone(),
"exit_code" => exec_exit_code.to_string(),
"combined" => format!("exit_code={}\n{}", exec_exit_code, exec_output),
_ => exec_output.clone(),
}
} else {
exec_output.clone()
};
let metrics = compute_epiplexity_for_transition(&[], 0, 0, previous_metrics);
let dp_hash = vcard_gate(
db_conn,
"dispatch",
pcard_hash,
&exec_exit_code.to_string(),
&[],
&chrono::Local::now()
.format("%Y-%m-%dT%H:%M:%S%z")
.to_string(),
per_trans_agent_did,
sponsor_did,
"self",
&env::var("CLM_EXECUTION_LOCALE_HASH").unwrap_or_default(),
&env::var("CLM_TRANSPORT_REF").unwrap_or_else(|_| "local".to_string()),
clm_root,
Some(&metrics),
threshold_signature,
guardian_dids,
)?;
Ok((exec_exit_code, exec_output, dp_hash, final_content, metrics))
}