use std::path::{Path, PathBuf};
use serde_yaml::Value;
pub fn compose_conditions(
clm_root: &Path,
clm_file: &str,
phase: &str,
exit_code: i32,
quiet: bool,
) -> Result<i32, String> {
compose_conditions_dispatch(clm_root, clm_file, phase, exit_code, quiet)
.map_err(|e| e.to_string())
}
pub(crate) fn compose_conditions_dispatch(
clm_root: &Path,
clm_file: &str,
phase: &str,
exit_code: i32,
quiet: bool,
) -> Result<i32, super::DispatchError> {
let clm_path = Path::new(clm_file);
let mut custom_pcard = None;
if clm_path.exists()
&& let Ok(content) = std::fs::read_to_string(clm_path)
&& let Ok(yaml) = serde_yaml::from_str::<Value>(&content) {
let root = yaml.get("clm").unwrap_or(&yaml);
if let Some(concrete) = root.get("concrete_impl") {
if phase == "pre" {
if let Some(pre) = concrete.get("precondition")
&& let Some(v) = pre.get("vcard_pre")
&& let Some(s) = v.as_str() {
custom_pcard = Some(s.to_string());
}
} else if phase == "post"
&& let Some(post) = concrete.get("postcondition")
&& let Some(v) = post.get("vcard_post")
&& let Some(s) = v.as_str() {
custom_pcard = Some(s.to_string());
}
}
}
if let Some(ref mut pcard) = custom_pcard {
if pcard.starts_with("gate:") {
let gate_name = pcard.trim_start_matches("gate:");
*pcard = format!("computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/{}.yaml", gate_name);
} else if pcard.starts_with(crate::hash::DEFAULT_HASH_PREFIX)
|| pcard.starts_with(crate::layer0::vocabulary::HASH_PREFIX_BLAKE3)
|| pcard.starts_with(crate::layer0::vocabulary::HASH_PREFIX_SHA256)
|| pcard.starts_with("sha512:")
|| pcard.starts_with("custom-")
{
let clm_root_str = clm_root.to_str().unwrap_or("");
if let Ok(Some(content)) = crate::db::get_card_content(crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY, clm_root_str, pcard) {
let temp_dir = std::env::temp_dir().join("clm_execution_logs/.tmp");
let _ = std::fs::create_dir_all(&temp_dir);
let safe_hash = pcard.replace([':', '/', '\\'], "_");
let temp_file = temp_dir.join(format!("handle_mat_{}.yaml", safe_hash));
if std::fs::write(&temp_file, &content).is_ok() {
if !quiet {
eprintln!("[COMPOSE] Resolved {} gate reference: {} -> {:?}", phase, pcard, temp_file);
}
*pcard = temp_file.to_string_lossy().to_string();
}
}
}
}
if let Some(ref pcard_str) = custom_pcard {
let resolved_path = if Path::new(pcard_str).is_absolute() {
if Path::new(pcard_str).exists() { Some(PathBuf::from(pcard_str)) } else { None }
} else {
let joined = clm_root.join(pcard_str);
if joined.exists() {
Some(joined)
} else if let Some(suffix) = pcard_str.strip_prefix("clm/") {
let joined_suffix = clm_root.join(suffix);
if joined_suffix.exists() {
Some(joined_suffix)
} else {
None
}
} else {
None
}
};
let mut custom_gate_name = None;
if let Some(ref path) = resolved_path
&& let Ok(content) = std::fs::read_to_string(path)
&& let Ok(yaml) = serde_yaml::from_str::<Value>(&content) {
let root = yaml.get("clm").unwrap_or(&yaml);
if let Some(concrete) = root.get("concrete_impl")
&& let Some(op) = concrete.get("operation")
&& let Some(s) = op.as_str() {
custom_gate_name = Some(s.to_string());
}
}
if let Some(gate_name) = custom_gate_name
&& !quiet {
eprintln!("[COMPOSE] Discovered custom {} gate: {} (from {})", phase, gate_name, pcard_str);
}
}
let expr;
let override_gate = crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_GATE_OVERRIDE).unwrap_or_else(|_| "0".to_string()) == "1";
if phase == "pre" {
if let Some(custom) = custom_pcard {
if override_gate {
expr = custom;
} else if custom == "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/verify_precondition.yaml"
|| custom == "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/payload_nonempty.yaml"
|| custom == "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/agent_authorized.yaml"
|| custom == "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/db_accessible.yaml"
|| custom == "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/file_exists.yaml"
|| custom == "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/hash_matches.yaml"
|| custom == "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/valid_yaml.yaml"
|| custom == "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/valid_clm.yaml"
|| custom == "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/type_conforms.yaml"
{
expr = "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/verify_precondition.yaml".to_string();
} else {
expr = format!("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/verify_precondition.yaml >>> {}", custom);
}
} else {
expr = "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/verify_precondition.yaml".to_string();
}
} else {
if let Some(custom) = custom_pcard {
if override_gate {
expr = custom;
} else if custom == "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/validate_postcondition.yaml"
|| custom == "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/result_sealed.yaml"
|| custom == "computable_knowledge/Abstract/layer5_system/bootstrap/governance/gates/refinement_loop_sealed.yaml"
{
expr = "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/validate_postcondition.yaml".to_string();
} else {
expr = format!("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/validate_postcondition.yaml >>> {}", custom);
}
} else {
expr = "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/validate_postcondition.yaml".to_string();
}
}
execute_composed_pcard(clm_root, &expr, phase, exit_code, clm_file, quiet)
}
fn execute_composed_pcard(
clm_root: &Path,
expr: &str,
phase: &str,
exit_code: i32,
payload: &str,
quiet: bool,
) -> Result<i32, super::DispatchError> {
let seq_gates: Vec<&str> = expr.split(">>>").map(|s| s.trim()).collect();
if seq_gates.len() > 1 {
for gate in seq_gates {
if !quiet {
eprintln!("[COMPOSE] Executing Sequential Step: {}", gate);
}
let rc = execute_composed_pcard(clm_root, gate, phase, exit_code, payload, quiet)?;
if rc != 0 {
return Ok(rc);
}
}
return Ok(0);
}
let gate = expr.trim();
if gate.is_empty() {
return Ok(0);
}
if gate == "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/verify_precondition.yaml" {
if !quiet {
eprintln!("[COMPOSE] Executing verify_precondition natively (zero-fork)");
}
match crate::evaluator::verify::verify_precondition_internal(clm_root, payload, quiet) {
Ok(_) => return Ok(0),
Err(e) => {
eprintln!("[COMPOSE] verify_precondition failed: {}", e);
return Ok(1);
}
}
}
if gate == "computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/validate_postcondition.yaml" {
if !quiet {
eprintln!("[COMPOSE] Executing validate_postcondition natively (zero-fork)");
}
let content = format!("exit code: {}", exit_code);
let content_hash = crate::hash::raw_hash_string(&content);
let extra_yaml = format!("content: \"{}\"", content);
let operation = "validate_postcondition";
match crate::db::emit_exec_mcard(operation, &content_hash, &extra_yaml, "", "", &clm_root.display().to_string()) {
Ok(mcard_path) => {
if !quiet {
eprintln!("[VCARD POST] ✅ Execution MCard generated: {}", mcard_path);
eprintln!("[VCARD POST] content_hash: {}", content_hash);
}
}
Err(e) => {
eprintln!("[VCARD POST] ❌ Failed to emit execution MCard: {}", e);
}
}
return Ok(0);
}
if !quiet {
eprintln!("[COMPOSE] Executing Base Gate: {}", gate);
}
let gate_path = if gate.starts_with("clm/") {
&gate[4..]
} else {
gate
};
let sub_card_path = if Path::new(gate_path).is_absolute() {
PathBuf::from(gate_path)
} else {
clm_root.join(gate_path)
};
let mut overrides = crate::cross_cutting::context::CLMContextOverrides {
project_root: Some(clm_root.to_path_buf()),
nested_exec: Some(true),
..Default::default()
};
overrides
.scoped_vars
.insert(crate::layer0::vocabulary_env::ENV_CLM_PAYLOAD.to_string(), payload.to_string());
overrides
.scoped_vars
.insert(crate::layer0::vocabulary_env::ENV_CLM_NESTED_EXEC.to_string(), "1".to_string());
overrides
.scoped_vars
.insert(crate::layer0::vocabulary_env::ENV_CLM_SKIP_CONDITIONS.to_string(), "1".to_string());
if phase != "pre" {
overrides
.scoped_vars
.insert(crate::layer0::vocabulary_env::ENV_CLM_POST_RC.to_string(), exit_code.to_string());
} else {
overrides.masked_vars.insert(crate::layer0::vocabulary_env::ENV_CLM_POST_RC.to_string());
}
if quiet {
overrides
.scoped_vars
.insert(crate::layer0::vocabulary_env::ENV_CLM_QUIET.to_string(), "1".to_string());
}
let child_ctx = crate::cross_cutting::context::CLMContext::current().with_child_scope(overrides);
let sp_name = format!(
"sp_nested_{}_{:x}",
phase,
rand::random::<u32>()
);
let mut sp_guard = crate::fiber::disposable::TriDbSavepointGuard::with_pillars(
&clm_root.to_string_lossy(),
&sp_name,
&[crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY, crate::layer0::vocabulary_env::PILLAR_AGENT_IDENTITIES],
)
.ok();
match crate::evaluator::evaluate_card_with_context_dispatch(&child_ctx, &sub_card_path) {
Ok(0) => {
if let Some(ref mut sp) = sp_guard {
let _ = sp.commit();
}
Ok(0)
}
Ok(rc) => {
if let Some(ref mut sp) = sp_guard {
let _ = sp.rollback();
}
Ok(rc)
}
Err(e @ super::DispatchError::SovereignSubprocessForbidden(_)) => {
if let Some(ref mut sp) = sp_guard {
let _ = sp.rollback();
}
Err(e)
}
Err(e) => {
if let Some(ref mut sp) = sp_guard {
let _ = sp.rollback();
}
eprintln!("[COMPOSE] Failed to execute gate {}: {}", gate, e);
Ok(1)
}
}
}