use crate::layer0::vocabulary::{HANDLE_MCARD};
use serde_json::Value;
use std::fs;
use std::path::Path;
use crate::parser::parse_a_mcard;
use crate::db::handle_register_batch;
use crate::baldwin::{sha256_hash_string, to_string_pretty_2_spaces};
use crate::utils::indent_lines;
use crate::hash::prefixed;
pub fn compile_a_mcard(
a_mcard_path: &str,
target: &str,
output_dir: Option<&str>,
clm_root: &str,
) -> Result<String, String> {
let a_mcard = parse_a_mcard(a_mcard_path)
.map_err(|e| format!("Failed to parse A-MCard: {}", e))?;
let out_dir = if let Some(dir) = output_dir {
let p = Path::new(dir);
if !p.exists() {
fs::create_dir_all(p).map_err(|e| format!("Failed to create output dir: {}", e))?;
}
p.to_path_buf()
} else {
let p = crate::fs_utils::get_data_dir(clm_root, crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY);
if !p.exists() {
let _ = fs::create_dir_all(&p);
}
p
};
let a_ast = crate::parser::parse_manifest(a_mcard_path)?;
let root = if let Some(clm) = a_ast.get("clm") { clm } else { &a_ast };
let abstract_spec = root.get("abstract_spec").unwrap_or(root);
let a_content_json = to_string_pretty_2_spaces(abstract_spec)?;
let a_hash = sha256_hash_string(&a_content_json);
let g_time = crate::fs_utils::compute_g_time();
let name = &a_mcard.signature.name;
let mut c_content = serde_json::Map::new();
c_content.insert("a_hash".to_string(), Value::String(prefixed(&a_hash)));
c_content.insert("runtime".to_string(), Value::String(target.to_string()));
c_content.insert("operation".to_string(), Value::String(name.clone()));
let mut process = serde_json::Map::new();
match target {
"sql" => {
process.insert("type".to_string(), Value::String("sql".to_string()));
let operation_content = format!("operation: {}", name);
let record = crate::layer0::mcard_record::MCardRecord::create(operation_content.as_bytes(), None)?;
process.insert("query".into(), Value::String(format!(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES ('{}', '{}', '{}');",
record.hash, operation_content.replace('\'', "''"), record.g_time.replace('\'', "''"))));
}
"wasm" => {
process.insert("type".to_string(), Value::String("wasm".to_string()));
process.insert("entry_point".to_string(), Value::String(name.clone()));
process.insert("script".to_string(), Value::String("<WASM_BIN_PENDING>".to_string()));
}
_ => { process.insert("type".to_string(), Value::String("internal_reference".to_string()));
process.insert("module".to_string(), Value::String("clm_rust_core::test::compiled_op".to_string()));
process.insert("args".to_string(), Value::Array(Vec::new()));
}
}
c_content.insert("process".to_string(), Value::Object(process));
let c_content_json = to_string_pretty_2_spaces(&c_content)?;
let c_hash = sha256_hash_string(&c_content_json);
let c_yaml_str = serde_yaml::to_string(&c_content)
.map_err(|e| format!("Failed to serialize concrete content to YAML: {}", e))?;
let c_mcard_content = format!(
"{HANDLE_MCARD}\n hash: \"{}\"\n g_time: \"{}\"\n facet: \"concrete_impl\"\n content_hash: \"{}\"\n content:\n{}",
prefixed(&c_hash), g_time, c_hash, indent_lines(&c_yaml_str, 4)
);
let c_file = out_dir.join(format!("c_{}.yaml", &c_hash[..12]));
fs::write(&c_file, &c_mcard_content)
.map_err(|e| format!("Failed to write C-MCard file: {}", e))?;
let mut b_content = serde_json::Map::new();
b_content.insert("c_hash".to_string(), Value::String(prefixed(&c_hash)));
b_content.insert("expectation".to_string(), Value::String(format!("Verification suite for {}", name)));
let mut polyglot_cases = Vec::new();
let mut pos_case = serde_json::Map::new();
pos_case.insert("name".to_string(), Value::String("positive_path".to_string()));
let mut pos_given = serde_json::Map::new();
let mut pos_inputs = serde_json::Map::new();
pos_inputs.insert("val".to_string(), Value::from(5));
pos_given.insert("inputs".to_string(), Value::Object(pos_inputs));
pos_given.insert("runtimes".to_string(), Value::Array(vec![Value::String("rust".to_string())]));
pos_case.insert("given".to_string(), Value::Object(pos_given));
pos_case.insert("when".to_string(), Value::String(name.clone()));
let mut pos_then = serde_json::Map::new();
pos_then.insert("exit_code".to_string(), Value::from(0));
pos_then.insert("internal_reference".to_string(), Value::String("clm_rust_core::test::compiled_op".to_string()));
pos_case.insert("then".to_string(), Value::Object(pos_then));
polyglot_cases.push(Value::Object(pos_case));
let mut neg_case = serde_json::Map::new();
neg_case.insert("name".to_string(), Value::String("negative_path".to_string()));
let mut neg_given = serde_json::Map::new();
let mut neg_inputs = serde_json::Map::new();
neg_inputs.insert("val".to_string(), Value::from(-5));
neg_given.insert("inputs".to_string(), Value::Object(neg_inputs));
neg_given.insert("runtimes".to_string(), Value::Array(vec![Value::String("rust".to_string())]));
neg_case.insert("given".to_string(), Value::Object(neg_given));
neg_case.insert("when".to_string(), Value::String(name.clone()));
let mut neg_then = serde_json::Map::new();
neg_then.insert("exit_code".to_string(), Value::from(1)); neg_then.insert("internal_reference".to_string(), Value::String("clm_rust_core::test::compiled_op".to_string()));
neg_case.insert("then".to_string(), Value::Object(neg_then));
polyglot_cases.push(Value::Object(neg_case));
let mut braid_case = serde_json::Map::new();
braid_case.insert("name".to_string(), Value::String("concurrency_braiding".to_string()));
let mut braid_given = serde_json::Map::new();
let mut braid_inputs = serde_json::Map::new();
braid_inputs.insert("val".to_string(), Value::from(5));
braid_given.insert("inputs".to_string(), Value::Object(braid_inputs));
braid_given.insert("runtimes".to_string(), Value::Array(vec![Value::String("rust".to_string())]));
braid_case.insert("given".to_string(), Value::Object(braid_given));
braid_case.insert("when".to_string(), Value::String(name.clone()));
let mut braid_then = serde_json::Map::new();
braid_then.insert("exit_code".to_string(), Value::from(0));
braid_then.insert("internal_reference".to_string(), Value::String("clm_rust_core::test::compiled_op".to_string()));
braid_case.insert("then".to_string(), Value::Object(braid_then));
polyglot_cases.push(Value::Object(braid_case));
b_content.insert("polyglot_cases".to_string(), Value::Array(polyglot_cases));
let b_content_json = to_string_pretty_2_spaces(&b_content)?;
let b_hash = sha256_hash_string(&b_content_json);
let b_yaml_str = serde_yaml::to_string(&b_content)
.map_err(|e| format!("Failed to serialize boundary content to YAML: {}", e))?;
let b_mcard_content = format!(
"{HANDLE_MCARD}\n hash: \"{}\"\n g_time: \"{}\"\n facet: \"balanced_exp\"\n content_hash: \"{}\"\n content:\n{}",
prefixed(&b_hash), g_time, b_hash, indent_lines(&b_yaml_str, 4)
);
let b_file = out_dir.join(format!("b_{}.yaml", &b_hash[..12]));
fs::write(&b_file, &b_mcard_content)
.map_err(|e| format!("Failed to write B-MCard file: {}", e))?;
let db_pillar = crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY;
let root_content = serde_json::json!({
"@type": "CLM_Root", "clm_name": name,
"a_hash": prefixed(&a_hash), "c_hash": prefixed(&c_hash), "b_hash": prefixed(&b_hash),
}).to_string();
let clm_root_hash = crate::hash::raw_hash_string(&root_content);
for (handle, hash, content) in [
(format!("clm:{}", name), &clm_root_hash, root_content.as_str()),
(format!("clm:{}:a", name), &a_hash, a_content_json.as_str()),
(format!("clm:{}:c", name), &c_hash, c_content_json.as_str()),
(format!("clm:{}:b", name), &b_hash, b_content_json.as_str()),
] { handle_register_batch(db_pillar, clm_root, &handle, hash, content).map_err(|e| e.to_string())?; }
let mut out = String::new();
out.push_str("\n######################################################\n");
out.push_str(" Triadic Compilation Complete\n");
out.push_str("######################################################\n");
out.push_str("clm:\n");
out.push_str(&format!(" clm_root_hash: \"{}\"\n", prefixed(&clm_root_hash)));
out.push_str(&format!(" clm_name: \"{}\"\n", name));
out.push_str(&format!(" a_hash: \"{}\"\n", prefixed(&a_hash)));
out.push_str(&format!(" c_hash: \"{}\"\n", prefixed(&c_hash)));
out.push_str(&format!(" b_hash: \"{}\"\n", prefixed(&b_hash)));
out.push_str(&format!(" c_file: \"{}\"\n", c_file.to_string_lossy()));
out.push_str(&format!(" b_file: \"{}\"\n", b_file.to_string_lossy()));
out.push('\n');
Ok(out)
}
pub fn run_self_evolution(
clm_root: &str,
candidate_yaml: &str,
) -> Result<String, String> {
let content = fs::read_to_string(candidate_yaml)
.map_err(|e| format!("Failed to read candidate C-MCard file: {}", e))?;
let _: serde_json::Value = serde_yaml::from_str(&content).map_err(|e| e.to_string())?;
let record = crate::layer0::mcard_record::MCardRecord::create(content.as_bytes(), None)?;
let c_hash = record.hash.as_str();
let g_time = record.g_time.as_str();
let conn = crate::db::get_connection(crate::layer0::vocabulary_env::PILLAR_AGENT_IDENTITIES, clm_root).map_err(|e| e.to_string())?;
crate::layer2::record_store::insert_record(&conn, &record).map_err(|e| e.to_string())?;
crate::tape::register_handle(&conn, "upgrade:evaluator", c_hash, g_time)?;
let temp_dir = std::env::temp_dir();
let test_clm = temp_dir.join("upgrade_val_test.yaml");
let test_content = r#"
clm:
abstract_spec:
signature:
name: "test_math_op"
inputs:
val: "int"
outputs:
result: "int"
invariants:
preconditions: []
postconditions: []
concrete_impl:
runtime: rust
operation: test_math_op
process:
type: internal_reference
module: clm_rust_core::test::compiled_op
args: []
"#;
fs::write(&test_clm, test_content)
.map_err(|e| format!("Failed to write validation test CLM: {}", e))?;
let sandbox_id = "evaluator_upgrade_sandbox";
let _guard = crate::db::DatabaseSandboxGuard::activate(sandbox_id);
let _ = crate::db::get_connection(crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY, clm_root)
.map_err(|e| format!("Failed to initialize content_memory in sandbox: {}", e))?;
let _ = crate::db::get_connection(crate::layer0::vocabulary_env::PILLAR_AGENT_IDENTITIES, clm_root)
.map_err(|e| format!("Failed to initialize agent_identities in sandbox: {}", e))?;
let clm_root_path = Path::new(clm_root);
let run_res = crate::evaluator::run_evaluation(
clm_root_path,
Some(test_clm.to_str().unwrap()),
Some("val: 5"),
None,
true,
Some(sandbox_id),
);
match run_res {
Ok(exit_code) => {
if exit_code == 0 {
conn.execute(
"INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES ('clm:evaluator', ?, ?);",
rusqlite::params![c_hash, g_time],
).map_err(|e| format!("Failed to promote evaluator handle: {}", e))?;
conn.execute(
"INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES ('agent:root', ?, ?);",
rusqlite::params![c_hash, g_time],
).map_err(|e| format!("Failed to promote agent root handle: {}", e))?;
let mut out = String::new();
out.push_str("\n======================================================\n");
out.push_str(" Evaluator Self-Evolution Upgrade Successful!\n");
out.push_str("======================================================\n");
out.push_str(&format!(" Candidate hash: {}\n", prefixed(c_hash)));
out.push_str(" Status: Promoted to active clm:evaluator and agent:root\n");
Ok(out)
} else {
Err(format!("Validation run failed with exit code: {}", exit_code))
}
}
Err(e) => Err(format!("Validation run error: {}", e)),
}
}