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, "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!(
"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") {
if let Some(pre_obj) = pre.as_object_mut() {
pre_obj.remove("vcard_pre");
}
}
if let Some(post) = obj.get_mut("postcondition") {
if 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!(
"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 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);
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!(
"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 b_hash_for_root = if b_hash == "none" { "none" } else { &b_hash };
let root_hash_input = format!("{}:{}:{}:{}:{}:{}", crate::hash::DEFAULT_HASH_PREFIX, a_hash, crate::hash::DEFAULT_HASH_PREFIX, c_hash, crate::hash::DEFAULT_HASH_PREFIX, b_hash_for_root);
let clm_root_hash = sha256_hash_string(&root_hash_input);
let db_pillar = "content_memory";
let root_content = format!(
"{{\"@type\":\"CLM_Root\",\"clm_name\":\"{}\",\"clm_root_hash\":\"{}\",\"a_hash\":\"{}\",\"c_hash\":\"{}\",\"b_hash\":\"{}\"}}",
clm_name, prefixed(&clm_root_hash), prefixed(&a_hash), prefixed(&c_hash), prefixed(&b_hash)
);
let _ = db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}", clm_name), &clm_root_hash, &root_content);
let _ = db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}:a", clm_name), &a_hash, "");
let _ = db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}:c", clm_name), &c_hash, "");
if b_hash != "none" {
let _ = db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}:b", clm_name), &b_hash, "");
}
let a_mcard_hash = sha256_hash_string(&a_mcard_content);
let _ = db::handle_register_batch(db_pillar, clm_root, &format!("facet:a:{}", &a_hash[..12]), &a_mcard_hash, &a_mcard_content);
let c_mcard_hash = sha256_hash_string(&c_mcard_content);
let _ = db::handle_register_batch(db_pillar, clm_root, &format!("facet:c:{}", &c_hash[..12]), &c_mcard_hash, &c_mcard_content);
if let Some(ref b_mcard_content) = b_mcard_content_opt {
let b_mcard_hash = sha256_hash_string(b_mcard_content);
let _ = db::handle_register_batch(db_pillar, clm_root, &format!("facet:b:{}", &b_hash[..12]), &b_mcard_hash, b_mcard_content);
}
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_for_root));
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") {
if let Some(pre_obj) = pre.as_object_mut() {
pre_obj.remove("vcard_pre");
}
}
if let Some(post) = obj.get_mut("postcondition") {
if 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, "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 _ = db::handle_register_batch("content_memory", clm_root, &format!("clm:substituted_{}", &c_hash[..12]), &clm_root_hash, &root_content);
Ok(sub_file.to_string_lossy().to_string())
}
#[allow(dead_code)]
pub fn augment(clm_file: &str, aug_source: &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 aug_content = if Path::new(aug_source).exists() {
fs::read_to_string(aug_source)
.map_err(|e| format!("Failed to read augmentation file: {}", e))?
} else {
aug_source.to_string()
};
let aug_val: Value = serde_yaml::from_str(&aug_content)
.map_err(|e| format!("Failed to parse augmentation YAML: {}", e))?;
if let Some(pre) = aug_val.get("precondition").or_else(|| aug_val.get("vcard_pre")) {
if let Some(concrete_impl) = clm.get_mut("concrete_impl") {
if let Some(obj) = concrete_impl.as_object_mut() {
obj.insert("precondition".to_string(), pre.clone());
}
}
if let Some(abstract_spec) = clm.get_mut("abstract_spec") {
if let Some(obj) = abstract_spec.as_object_mut() {
let invariants = obj.entry("invariants".to_string())
.or_insert_with(|| serde_json::json!({
"preconditions": Vec::<String>::new(),
"postconditions": Vec::<String>::new()
}));
if let Some(inv_obj) = invariants.as_object_mut() {
let pre_list = inv_obj.entry("preconditions".to_string())
.or_insert_with(|| Value::Array(Vec::new()));
if let Some(arr) = pre_list.as_array_mut() {
if let Some(new_arr) = pre.as_array() {
arr.extend(new_arr.clone());
} else {
if !arr.contains(pre) {
arr.push(pre.clone());
}
}
}
}
}
}
} else if let Some(post) = aug_val.get("postcondition").or_else(|| aug_val.get("vcard_post")) {
if let Some(concrete_impl) = clm.get_mut("concrete_impl") {
if let Some(obj) = concrete_impl.as_object_mut() {
obj.insert("postcondition".to_string(), post.clone());
}
}
if let Some(abstract_spec) = clm.get_mut("abstract_spec") {
if let Some(obj) = abstract_spec.as_object_mut() {
let invariants = obj.entry("invariants".to_string())
.or_insert_with(|| serde_json::json!({
"preconditions": Vec::<String>::new(),
"postconditions": Vec::<String>::new()
}));
if let Some(inv_obj) = invariants.as_object_mut() {
let post_list = inv_obj.entry("postconditions".to_string())
.or_insert_with(|| Value::Array(Vec::new()));
if let Some(arr) = post_list.as_array_mut() {
if let Some(new_arr) = post.as_array() {
arr.extend(new_arr.clone());
} else {
if !arr.contains(post) {
arr.push(post.clone());
}
}
}
}
}
}
}
else if let Some(pending) = aug_val.get("pending_cases") {
if let Some(balanced_exp) = clm.get_mut("balanced_exp") {
if let Some(obj) = balanced_exp.as_object_mut() {
let existing = obj.entry("pending_cases".to_string())
.or_insert(Value::Array(Vec::new()));
if let Some(arr) = existing.as_array_mut() {
if let Some(new_arr) = pending.as_array() {
arr.extend(new_arr.clone());
} else {
arr.push(pending.clone());
}
}
}
}
} else if let Some(criteria) = aug_val.get("success_criteria") {
if let Some(abstract_spec) = clm.get_mut("abstract_spec") {
if let Some(obj) = abstract_spec.as_object_mut() {
let existing = obj.entry("success_criteria".to_string())
.or_insert(Value::Array(Vec::new()));
if let Some(arr) = existing.as_array_mut() {
if let Some(new_arr) = criteria.as_array() {
arr.extend(new_arr.clone());
} else {
arr.push(criteria.clone());
}
}
}
}
} else {
if let Some(obj) = clm.as_object_mut() {
if let Some(aug_obj) = aug_val.as_object() {
for (k, v) in aug_obj {
obj.insert(k.clone(), v.clone());
}
}
}
}
let aug_hash = sha256_hash_string(&aug_content);
let output_dir = crate::fs_utils::get_data_dir(clm_root, "content_memory");
let _ = fs::create_dir_all(&output_dir);
let aug_file = output_dir.join(format!("augmented_{}.yaml", &aug_hash[..12]));
let new_yaml = serde_yaml::to_string(&clm_val)
.map_err(|e| format!("Failed to serialize augmented CLM: {}", e))?;
fs::write(&aug_file, &new_yaml)
.map_err(|e| format!("Failed to write augmented file: {}", e))?;
let root_content = format!(
"{{\"@type\":\"CLM_Root\",\"clm_name\":\"augmented_{}\",\"clm_root_hash\":\"{}\",\"a_hash\":\"none\",\"c_hash\":\"none\",\"b_hash\":\"none\"}}",
&aug_hash[..12], prefixed(&aug_hash)
);
let _ = db::handle_register_batch("content_memory", clm_root, &format!("clm:augmented_{}", &aug_hash[..12]), &aug_hash, &root_content);
Ok(aug_file.to_string_lossy().to_string())
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct SubsumptionReport {
pub fiber_id: String,
pub old_hash: String,
pub new_hash: String,
pub pre_subsumed: bool,
pub post_subsumed: bool,
pub subsumption_valid: bool,
pub witness: String,
}
pub fn extract_invariants(val: &Value, field: &str) -> std::collections::HashSet<String> {
let mut set = std::collections::HashSet::new();
let root = if let Some(clm) = val.get("clm") { clm } else { val };
if let Some(arr) = root.get("abstract_spec")
.and_then(|a| a.get("invariants"))
.and_then(|inv| inv.get(field))
.and_then(|f| f.as_array())
{
for item in arr {
if let Some(s) = item.as_str() {
set.insert(s.to_string());
}
}
}
if let Some(arr) = root.get("invariants")
.and_then(|inv| inv.get(field))
.and_then(|f| f.as_array())
{
for item in arr {
if let Some(s) = item.as_str() {
set.insert(s.to_string());
}
}
}
set
}
pub fn verify_subsumption(old_ast: &Value, new_ast: &Value) -> Result<SubsumptionReport, String> {
let old_pre = extract_invariants(old_ast, "preconditions");
let new_pre = extract_invariants(new_ast, "preconditions");
let old_post = extract_invariants(old_ast, "postconditions");
let new_post = extract_invariants(new_ast, "postconditions");
let pre_subsumed = new_pre.is_subset(&old_pre);
let post_subsumed = old_post.is_subset(&new_post);
let subsumption_valid = pre_subsumed && post_subsumed;
let witness = format!(
"Pre-subsumption: {} (old_pre={:?}, new_pre={:?}); Post-subsumption: {} (old_post={:?}, new_post={:?})",
pre_subsumed, old_pre, new_pre, post_subsumed, old_post, new_post
);
let report = SubsumptionReport {
fiber_id: String::new(),
old_hash: String::new(),
new_hash: String::new(),
pre_subsumed,
post_subsumed,
subsumption_valid,
witness,
};
if subsumption_valid {
Ok(report)
} else {
Err(format!("Subsumption check failed: {}", report.witness))
}
}
pub fn substitute_fiber(
ctx: &crate::fiber::Context,
fiber_id: &str,
new_clm_file: &str,
clm_root: &str,
) -> Result<SubsumptionReport, String> {
let old_fiber = ctx.get_fiber(fiber_id)
.ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
let path = Path::new(new_clm_file);
let resolved_path = if path.is_absolute() {
path.to_path_buf()
} else {
Path::new(clm_root).join(new_clm_file)
};
if !resolved_path.exists() {
return Err(format!("New CLM file not found: {}", resolved_path.display()));
}
let yaml_content = fs::read_to_string(&resolved_path)
.map_err(|e| format!("Failed to read new CLM file: {}", e))?;
let new_ast: Value = serde_yaml::from_str(&yaml_content)
.map_err(|e| format!("Failed to parse new CLM YAML: {}", e))?;
let new_json_str = serde_json::to_string(&new_ast).unwrap_or_default();
let new_hash = sha256_hash_string(&new_json_str);
let old_ast = old_fiber.get_ast().unwrap_or(Value::Null);
let old_json_str = serde_json::to_string(&old_ast).unwrap_or_default();
let old_hash = sha256_hash_string(&old_json_str);
let mut report = verify_subsumption(&old_ast, &new_ast)?;
report.fiber_id = fiber_id.to_string();
report.old_hash = old_hash;
report.new_hash = new_hash;
old_fiber.pause()?;
let _ = old_fiber.unwind_disposables();
ctx.remove_fiber(fiber_id);
let new_fiber = ctx.create_fiber(fiber_id, vec![])?;
new_fiber.set_ast(new_ast);
new_fiber.activate()?;
Ok(report)
}
pub fn split_fiber(
ctx: &crate::fiber::Context,
fiber_id: &str,
allowed_coeffects: &[&str],
) -> Result<std::sync::Arc<crate::fiber::Fiber>, String> {
let child_ctx = ctx.isolate(allowed_coeffects);
let child_id = format!("{}_split", fiber_id);
let child_fiber = child_ctx.create_fiber(&child_id, vec![])?;
child_fiber.activate()?;
Ok(child_fiber)
}
pub fn augment_fiber(
ctx: &crate::fiber::Context,
fiber_id: &str,
coeffect: &str,
) -> Result<(), String> {
let fiber = ctx.get_fiber(fiber_id)
.ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
ctx.provide(coeffect, format!("CoeffectInstance:{}", coeffect));
fiber.satisfy_coeffect(coeffect);
Ok(())
}
pub fn exclude_fiber(
ctx: &crate::fiber::Context,
fiber_id: &str,
) -> Result<(), String> {
let fiber = ctx.get_fiber(fiber_id)
.ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
let _ = fiber.dispose();
ctx.remove_fiber(fiber_id);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_subsumption_verification_soundness() {
let old_ast = serde_json::json!({
"abstract_spec": {
"invariants": {
"preconditions": ["pre_a", "pre_b"],
"postconditions": ["post_x"]
}
}
});
let compliant_new_ast = serde_json::json!({
"abstract_spec": {
"invariants": {
"preconditions": ["pre_a"],
"postconditions": ["post_x", "post_y"]
}
}
});
let res = verify_subsumption(&old_ast, &compliant_new_ast);
assert!(res.is_ok());
let report = res.unwrap();
assert!(report.pre_subsumed);
assert!(report.post_subsumed);
assert!(report.subsumption_valid);
let breaking_pre_ast = serde_json::json!({
"abstract_spec": {
"invariants": {
"preconditions": ["pre_a", "pre_c"],
"postconditions": ["post_x"]
}
}
});
assert!(verify_subsumption(&old_ast, &breaking_pre_ast).is_err());
let breaking_post_ast = serde_json::json!({
"abstract_spec": {
"invariants": {
"preconditions": ["pre_a"],
"postconditions": ["post_z"]
}
}
});
assert!(verify_subsumption(&old_ast, &breaking_post_ast).is_err());
}
#[test]
fn test_dynamic_baldwin_fiber_lifecycle() {
let ctx = crate::fiber::Context::root();
let fiber = ctx.create_fiber("test_fiber", vec!["effect_1".to_string()]).unwrap();
assert_eq!(fiber.get_state(), crate::fiber::FiberState::Pending);
augment_fiber(&ctx, "test_fiber", "effect_1").unwrap();
assert_eq!(fiber.get_state(), crate::fiber::FiberState::Active);
let split_res = split_fiber(&ctx, "test_fiber", &["effect_1"]);
assert!(split_res.is_ok());
exclude_fiber(&ctx, "test_fiber").unwrap();
assert!(ctx.get_fiber("test_fiber").is_none());
}
}