use crate::layer0::vocabulary::{HANDLE_MCARD};
use serde_json::{Value, Serializer};
use serde_json::ser::PrettyFormatter;
use std::fs;
use std::path::Path;
use crate::db;
use crate::hash::prefixed;
use crate::utils::indent_lines;
pub fn split(clm_file: &str, clm_root: &str) -> Result<String, String> {
let path = Path::new(clm_file);
if !path.exists() {
return Err(format!("File not found: {}", clm_file));
}
let yaml_content = fs::read_to_string(path)
.map_err(|e| format!("Failed to read CLM file: {}", e))?;
let mut clm_val: Value = serde_yaml::from_str(&yaml_content)
.map_err(|e| format!("Failed to parse CLM YAML: {}", e))?;
let clm = clm_val.get_mut("clm")
.ok_or_else(|| "Not a valid CLM file (missing 'clm:' root)".to_string())?;
let clm_name = clm.get("concrete_impl")
.and_then(|c| c.get("operation"))
.and_then(|o| o.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| {
path.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_else(|| "unknown".to_string())
});
let g_time = crate::fs_utils::compute_g_time();
let output_dir = crate::fs_utils::get_data_dir(clm_root, crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY);
let _ = fs::create_dir_all(&output_dir);
let abstract_spec = clm.get("abstract_spec")
.ok_or_else(|| "CLM has no abstract_spec section".to_string())?
.clone();
let a_content_json = to_string_pretty_2_spaces(&abstract_spec)?;
let a_hash = sha256_hash_string(&a_content_json);
let a_file = output_dir.join(format!("a_{}.yaml", &a_hash[..12]));
let a_yaml_str = serde_yaml::to_string(&abstract_spec)
.map_err(|e| format!("Failed to serialize abstract_spec: {}", e))?;
let a_mcard_content = format!(
"{HANDLE_MCARD}\n hash: \"{}\"\n g_time: \"{}\"\n facet: \"abstract_spec\"\n content_hash: \"{}\"\n content:\n{}",
prefixed(&a_hash), g_time, a_hash, indent_lines(&a_yaml_str, 4)
);
fs::write(&a_file, &a_mcard_content)
.map_err(|e| format!("Failed to write A-MCard: {}", e))?;
eprintln!("[DECOMPOSE] ✅ A-MCard: {}", a_file.to_string_lossy());
eprintln!("[DECOMPOSE] hash: {}", a_hash);
let mut concrete_impl = clm.get("concrete_impl")
.ok_or_else(|| "CLM has no concrete_impl section".to_string())?
.clone();
if let Some(obj) = concrete_impl.as_object_mut() {
if let Some(pre) = obj.get_mut("precondition")
&& let Some(pre_obj) = pre.as_object_mut() {
pre_obj.remove("vcard_pre");
}
if let Some(post) = obj.get_mut("postcondition")
&& let Some(post_obj) = post.as_object_mut() {
post_obj.remove("vcard_post");
}
obj.insert("a_hash".to_string(), Value::String(prefixed(&a_hash)));
}
let c_content_json = to_string_pretty_2_spaces(&concrete_impl)?;
let c_hash = sha256_hash_string(&c_content_json);
let c_original_yaml_str = serde_yaml::to_string(&clm.get("concrete_impl").unwrap())
.map_err(|e| format!("Failed to serialize original concrete_impl: {}", e))?;
let c_file = output_dir.join(format!("c_{}.yaml", &c_hash[..12]));
let c_mcard_content = format!(
"{HANDLE_MCARD}\n hash: \"{}\"\n g_time: \"{}\"\n facet: \"concrete_impl\"\n content_hash: \"{}\"\n content:\n a_hash: \"{}\"\n{}",
prefixed(&c_hash), g_time, c_hash, prefixed(&a_hash), indent_lines(&c_original_yaml_str, 4)
);
fs::write(&c_file, &c_mcard_content)
.map_err(|e| format!("Failed to write C-MCard: {}", e))?;
eprintln!("[DECOMPOSE] ✅ C-MCard: {}", c_file.to_string_lossy());
eprintln!("[DECOMPOSE] hash: {}", c_hash);
eprintln!("[DECOMPOSE] a_hash: {}", a_hash);
let has_balanced = clm.get("balanced_exp").is_some();
let mut b_mcard_content_opt = None;
let mut b_payload_content = None;
let b_hash = if has_balanced {
let mut balanced_exp = clm.get("balanced_exp").unwrap().clone();
if let Some(obj) = balanced_exp.as_object_mut() {
obj.insert("c_hash".to_string(), Value::String(prefixed(&c_hash)));
}
let b_content_json = to_string_pretty_2_spaces(&balanced_exp)?;
let b_hash_val = sha256_hash_string(&b_content_json);
b_payload_content = Some(b_content_json);
let b_file = output_dir.join(format!("b_{}.yaml", &b_hash_val[..12]));
let expectation = clm.get("balanced_exp")
.and_then(|b| b.get("expectation"))
.and_then(|e| e.as_str())
.unwrap_or("");
let pending_cases = clm.get("balanced_exp")
.and_then(|b| b.get("pending_cases"));
let pending_cases_str = match pending_cases {
Some(Value::Array(arr)) if !arr.is_empty() => {
let y = serde_yaml::to_string(arr).unwrap_or_else(|_| "[]".to_string());
format!(" pending_cases:\n{}", indent_lines(&y, 6))
}
_ => " pending_cases: []".to_string(),
};
let b_mcard_content = format!(
"{HANDLE_MCARD}\n hash: \"{}\"\n g_time: \"{}\"\n facet: \"balanced_exp\"\n content_hash: \"{}\"\n content:\n c_hash: \"{}\"\n expectation: \"{}\"\n{}",
prefixed(&b_hash_val), g_time, b_hash_val, prefixed(&c_hash), expectation, pending_cases_str
);
b_mcard_content_opt = Some(b_mcard_content.clone());
fs::write(&b_file, &b_mcard_content)
.map_err(|e| format!("Failed to write B-MCard: {}", e))?;
eprintln!("[DECOMPOSE] ✅ B-MCard: {}", b_file.to_string_lossy());
eprintln!("[DECOMPOSE] hash: {}", b_hash_val);
eprintln!("[DECOMPOSE] c_hash: {}", c_hash);
let pending_count = match pending_cases {
Some(Value::Array(arr)) => arr.len(),
_ => 0,
};
eprintln!("[DECOMPOSE] pending_cases: {}", pending_count);
b_hash_val
} else {
eprintln!("[DECOMPOSE] ⚠️ No balanced_exp section — B-MCard skipped");
"none".to_string()
};
let db_pillar = crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY;
let root_content = serde_json::json!({"@type":"CLM_Root", "clm_name":clm_name,
"a_hash":prefixed(&a_hash), "c_hash":prefixed(&c_hash), "b_hash":prefixed(&b_hash)}).to_string();
let clm_root_hash = sha256_hash_string(&root_content);
for (handle, hash, content) in [
(format!("clm:{}", clm_name), &clm_root_hash, root_content.as_str()),
(format!("clm:{}:a", clm_name), &a_hash, a_content_json.as_str()),
(format!("clm:{}:c", clm_name), &c_hash, c_content_json.as_str()),
] { db::handle_register_batch(db_pillar, clm_root, &handle, hash, content).map_err(|e| e.to_string())?; }
if let Some(content) = b_payload_content {
db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}:b", clm_name), &b_hash, &content).map_err(|e| e.to_string())?;
}
let a_mcard_hash = sha256_hash_string(&a_mcard_content);
db::handle_register_batch(db_pillar, clm_root, &format!("facet:a:{}", &a_hash[..12]), &a_mcard_hash, &a_mcard_content).map_err(|e| e.to_string())?;
let c_mcard_hash = sha256_hash_string(&c_mcard_content);
db::handle_register_batch(db_pillar, clm_root, &format!("facet:c:{}", &c_hash[..12]), &c_mcard_hash, &c_mcard_content).map_err(|e| e.to_string())?;
if let Some(ref b_mcard_content) = b_mcard_content_opt {
let b_mcard_hash = sha256_hash_string(b_mcard_content);
db::handle_register_batch(db_pillar, clm_root, &format!("facet:b:{}", &b_hash[..12]), &b_mcard_hash, b_mcard_content).map_err(|e| e.to_string())?;
}
eprintln!("[DECOMPOSE] 🔗 Registered handles: clm:{} → {}", clm_name, prefixed(&clm_root_hash));
let mut out = String::new();
out.push_str("\n######################################################\n");
out.push_str(" Cubical Decomposition 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", clm_name));
out.push_str(&format!(" a_hash: \"{}\"\n", prefixed(&a_hash)));
out.push_str(&format!(" c_hash: \"{}\"\n", prefixed(&c_hash)));
if b_hash != "none" {
out.push_str(&format!(" b_hash: \"{}\"\n", prefixed(&b_hash)));
}
out.push('\n');
out.push_str(&format!("# Chain: A({}) ← C({}) ← B({})\n", a_hash, c_hash, b_hash));
out.push_str(&format!("# Root: {} = H(a:c:b)\n", clm_root_hash));
Ok(out)
}
pub fn merge(a_file: &str, c_file: &str, b_file: Option<&str>) -> Result<String, String> {
let a_path = Path::new(a_file);
if !a_path.exists() {
return Err(format!("File not found: {}", a_file));
}
let a_content = fs::read_to_string(a_path)
.map_err(|e| format!("Failed to read A-MCard file: {}", e))?;
let a_mcard: Value = serde_yaml::from_str(&a_content)
.map_err(|e| format!("Failed to parse A-MCard YAML: {}", e))?;
let abstract_spec = a_mcard.get("mcard")
.and_then(|m| m.get("content"))
.ok_or_else(|| "Missing 'mcard.content' in A-MCard".to_string())?;
let c_path = Path::new(c_file);
if !c_path.exists() {
return Err(format!("File not found: {}", c_file));
}
let c_content = fs::read_to_string(c_path)
.map_err(|e| format!("Failed to read C-MCard file: {}", e))?;
let c_mcard: Value = serde_yaml::from_str(&c_content)
.map_err(|e| format!("Failed to parse C-MCard YAML: {}", e))?;
let concrete_impl_val = c_mcard.get("mcard")
.and_then(|m| m.get("content"))
.ok_or_else(|| "Missing 'mcard.content' in C-MCard".to_string())?;
let mut concrete_impl = concrete_impl_val.clone();
if let Some(obj) = concrete_impl.as_object_mut() {
obj.remove("a_hash");
}
let mut balanced_exp = None;
if let Some(bf) = b_file {
let b_path = Path::new(bf);
if b_path.exists() {
let b_content = fs::read_to_string(b_path)
.map_err(|e| format!("Failed to read B-MCard file: {}", e))?;
let b_mcard: Value = serde_yaml::from_str(&b_content)
.map_err(|e| format!("Failed to parse B-MCard YAML: {}", e))?;
let balanced_exp_val = b_mcard.get("mcard")
.and_then(|m| m.get("content"))
.ok_or_else(|| "Missing 'mcard.content' in B-MCard".to_string())?;
let mut b_val = balanced_exp_val.clone();
if let Some(obj) = b_val.as_object_mut() {
obj.remove("c_hash");
}
balanced_exp = Some(b_val);
}
}
let mut clm_map = serde_json::Map::new();
clm_map.insert("abstract_spec".to_string(), abstract_spec.clone());
clm_map.insert("concrete_impl".to_string(), concrete_impl);
if let Some(b_val) = balanced_exp {
clm_map.insert("balanced_exp".to_string(), b_val);
}
let mut root_map = serde_json::Map::new();
root_map.insert("clm".to_string(), Value::Object(clm_map));
let root_val = Value::Object(root_map);
serde_yaml::to_string(&root_val)
.map_err(|e| format!("Failed to serialize reconstructed CLM: {}", e))
}
pub fn to_string_pretty_2_spaces<T: serde::Serialize>(value: &T) -> Result<String, String> {
let mut buf = Vec::new();
let formatter = PrettyFormatter::with_indent(b" ");
let mut ser = Serializer::with_formatter(&mut buf, formatter);
value.serialize(&mut ser)
.map_err(|e| format!("Failed to serialize pretty JSON: {}", e))?;
Ok(String::from_utf8(buf).unwrap())
}
pub fn sha256_hash_string(s: &str) -> String {
crate::hash::raw_hash_string(s)
}
#[allow(dead_code)]
pub fn substitute(clm_file: &str, new_impl_file_or_op: &str, clm_root: &str) -> Result<String, String> {
let path = Path::new(clm_file);
if !path.exists() {
return Err(format!("File not found: {}", clm_file));
}
let yaml_content = fs::read_to_string(path)
.map_err(|e| format!("Failed to read CLM file: {}", e))?;
let mut clm_val: Value = serde_yaml::from_str(&yaml_content)
.map_err(|e| format!("Failed to parse CLM YAML: {}", e))?;
let clm = clm_val.get_mut("clm")
.ok_or_else(|| "Not a valid CLM file (missing 'clm:' root)".to_string())?;
let abstract_spec = clm.get("abstract_spec")
.ok_or_else(|| "CLM has no abstract_spec section".to_string())?
.clone();
let new_c_spec: Value = if Path::new(new_impl_file_or_op).exists() {
let c_content = fs::read_to_string(new_impl_file_or_op)
.map_err(|e| format!("Failed to read new implementation file: {}", e))?;
let parsed: Value = serde_yaml::from_str(&c_content)
.map_err(|e| format!("Failed to parse new implementation YAML: {}", e))?;
if let Some(c) = parsed.get("clm").and_then(|c| c.get("concrete_impl")) {
c.clone()
} else if parsed.get("concrete_impl").is_some() {
parsed.get("concrete_impl").unwrap().clone()
} else {
parsed
}
} else {
serde_json::json!({
"runtime": "system",
"operation": new_impl_file_or_op,
"inputs": Vec::<String>::new(),
"outputs": Vec::<String>::new(),
"process": {
"script_handle": format!("script:{}", new_impl_file_or_op)
}
})
};
let a_content_json = to_string_pretty_2_spaces(&abstract_spec)?;
let a_hash = sha256_hash_string(&a_content_json);
let mut concrete_impl = new_c_spec.clone();
if let Some(obj) = concrete_impl.as_object_mut() {
obj.insert("a_hash".to_string(), Value::String(prefixed(&a_hash)));
if let Some(pre) = obj.get_mut("precondition")
&& let Some(pre_obj) = pre.as_object_mut() {
pre_obj.remove("vcard_pre");
}
if let Some(post) = obj.get_mut("postcondition")
&& let Some(post_obj) = post.as_object_mut() {
post_obj.remove("vcard_post");
}
}
let c_content_json = to_string_pretty_2_spaces(&concrete_impl)?;
let c_hash = sha256_hash_string(&c_content_json);
let b_spec = clm.get("balanced_exp").cloned();
let expectation = b_spec.as_ref()
.and_then(|b| b.get("expectation"))
.and_then(|e| e.as_str())
.unwrap_or("Substituted implementation pending verification");
let pending_cases = b_spec.as_ref()
.and_then(|b| b.get("pending_cases"))
.cloned()
.unwrap_or(Value::Array(Vec::new()));
let mut new_clm = serde_json::Map::new();
new_clm.insert("abstract_spec".to_string(), abstract_spec);
new_clm.insert("concrete_impl".to_string(), concrete_impl);
let mut new_b = serde_json::Map::new();
new_b.insert("expectation".to_string(), Value::String(expectation.to_string()));
new_b.insert("pending_cases".to_string(), pending_cases);
new_clm.insert("balanced_exp".to_string(), Value::Object(new_b));
let mut new_root = serde_json::Map::new();
new_root.insert("clm".to_string(), Value::Object(new_clm));
let new_yaml = serde_yaml::to_string(&Value::Object(new_root))
.map_err(|e| format!("Failed to serialize substituted CLM: {}", e))?;
let output_dir = crate::fs_utils::get_data_dir(clm_root, crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY);
let _ = fs::create_dir_all(&output_dir);
let sub_file = output_dir.join(format!("substituted_{}.yaml", &c_hash[..12]));
fs::write(&sub_file, &new_yaml)
.map_err(|e| format!("Failed to write substituted file: {}", e))?;
let root_hash_input = format!("{}:{}:{}:{}:{}:none", crate::hash::DEFAULT_HASH_PREFIX, a_hash, crate::hash::DEFAULT_HASH_PREFIX, c_hash, crate::hash::DEFAULT_HASH_PREFIX);
let clm_root_hash = sha256_hash_string(&root_hash_input);
let root_content = format!(
"{{\"@type\":\"CLM_Root\",\"clm_name\":\"substituted_{}\",\"clm_root_hash\":\"{}\",\"a_hash\":\"{}\",\"c_hash\":\"{}\",\"b_hash\":\"none\"}}",
&c_hash[..12], prefixed(&clm_root_hash), prefixed(&a_hash), prefixed(&c_hash)
);
let stored_root_hash = sha256_hash_string(&root_content);
db::handle_register_batch(crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY, clm_root, &format!("clm:substituted_{}", &c_hash[..12]), &stored_root_hash, &root_content).map_err(|e| e.to_string())?;
Ok(sub_file.to_string_lossy().to_string())
}
#[path = "baldwin_augment.rs"]
mod baldwin_augment;
#[allow(unused_imports)]
pub use baldwin_augment::*;
#[cfg(test)]
#[path = "baldwin_tests.rs"]
mod tests;