#![allow(unused_imports)]
use super::*;
#[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")
&& 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")
&& 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")
&& 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")
&& 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")
&& 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")
&& 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()
&& 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(())
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct BaldwinCoeffectsSpec {
#[serde(rename = "requiredServices", default)]
pub required_services: Vec<String>,
#[serde(default)]
pub pure: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct BaldwinVectorNode {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "pcardId", default, skip_serializing_if = "Option::is_none")]
pub pcard_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "pcardType")]
pub pcard_type: String,
pub signature: String,
#[serde(rename = "sourceUri")]
pub source_uri: String,
pub coeffects: BaldwinCoeffectsSpec,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BaldwinVectorOutcomeOk {
pub operator: String,
pub target: String,
pub after: Vec<BaldwinVectorNode>,
pub after_canonical_json: String,
pub after_hash: String,
pub witness_canonical_json: String,
pub witness_hash: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BaldwinVectorOutcomeErr {
pub code: &'static str,
pub message: String,
}
fn baldwin_err(code: &'static str, msg: impl Into<String>) -> BaldwinVectorOutcomeErr {
BaldwinVectorOutcomeErr { code, message: msg.into() }
}
fn canonical_json_value(val: &Value) -> String {
match val {
Value::Null => "null".to_string(),
Value::Bool(b) => if *b { "true".to_string() } else { "false".to_string() },
Value::Number(n) => n.to_string(),
Value::String(s) => serde_json::to_string(s).unwrap_or_else(|_| "\"\"".to_string()),
Value::Array(arr) => format!("[{}]", arr.iter().map(canonical_json_value).collect::<Vec<_>>().join(",")),
Value::Object(map) => {
let mut keys: Vec<&String> = map.keys().collect();
keys.sort();
let pairs: Vec<String> = keys
.into_iter()
.map(|k| format!("{}:{}", serde_json::to_string(k).unwrap_or_default(), canonical_json_value(&map[k])))
.collect();
format!("{{{}}}", pairs.join(","))
}
}
}
fn normalize_vector_node(node: &BaldwinVectorNode) -> Result<(String, BaldwinVectorNode), BaldwinVectorOutcomeErr> {
let candidates: Vec<String> = [&node.id, &node.pcard_id, &node.name]
.into_iter().flatten().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
if candidates.is_empty() { return Err(baldwin_err("AMBIGUOUS_IDENTIFIER", "Missing node identifier")); }
let unique: std::collections::BTreeSet<String> = candidates.iter().cloned().collect();
if unique.len() > 1 { return Err(baldwin_err("AMBIGUOUS_IDENTIFIER", "Conflicting identifier aliases")); }
let cid = candidates[0].clone();
Ok((cid.clone(), BaldwinVectorNode {
id: Some(cid), pcard_id: None, name: None,
pcard_type: node.pcard_type.clone(), signature: node.signature.clone(),
source_uri: node.source_uri.clone(), coeffects: node.coeffects.clone(),
}))
}
pub fn evaluate_baldwin_vector(spec: &Value) -> Result<BaldwinVectorOutcomeOk, BaldwinVectorOutcomeErr> {
let op = spec.get("operator").and_then(|v| v.as_str()).unwrap_or("");
if !matches!(op, "split" | "substitute" | "augment" | "exclude" | "invert" | "port") {
return Err(baldwin_err("UNKNOWN_OPERATOR", format!("Unknown operator: {}", op)));
}
let target = spec.get("target").and_then(|v| v.as_str()).unwrap_or("").to_string();
let initial_arr = spec.get("initial_state").and_then(|v| v.as_array()).cloned().unwrap_or_default();
let mut index_by_id: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
let mut current: Vec<BaldwinVectorNode> = Vec::with_capacity(initial_arr.len());
for (idx, raw_val) in initial_arr.iter().enumerate() {
let parsed: BaldwinVectorNode = serde_json::from_value(raw_val.clone())
.map_err(|e| baldwin_err("AMBIGUOUS_IDENTIFIER", e.to_string()))?;
let (cid, norm) = normalize_vector_node(&parsed)?;
index_by_id.insert(cid, idx);
current.push(norm);
}
let parse_operand = || -> Result<(String, BaldwinVectorNode), BaldwinVectorOutcomeErr> {
let op_val = spec.get("operand").ok_or_else(|| baldwin_err("MISSING_SUBJECT", "Missing operand"))?;
let parsed: BaldwinVectorNode = serde_json::from_value(op_val.clone())
.map_err(|e| baldwin_err("AMBIGUOUS_IDENTIFIER", e.to_string()))?;
normalize_vector_node(&parsed)
};
let after: Vec<BaldwinVectorNode> = match op {
"split" => {
let (matched, mut rest): (Vec<_>, Vec<_>) = current
.iter().cloned()
.partition(|n| n.id.as_deref() == Some(target.as_str()) || target == "*");
if matched.is_empty() { current.clone() } else { rest.extend(matched); rest }
}
"substitute" => {
let &idx = index_by_id.get(&target).ok_or_else(|| baldwin_err("MISSING_SUBJECT", "Target not found"))?;
let (_, norm_op) = parse_operand()?;
let orig = ¤t[idx];
if orig.pcard_type == "dynamic" && norm_op.pcard_type == "dynamic" && orig.signature != norm_op.signature {
return Err(baldwin_err("COVARIANCE_VIOLATION", "Signature mismatch"));
}
let mut next = current.clone();
next[idx] = norm_op;
next
}
"augment" => {
let (op_id, norm_op) = parse_operand()?;
if index_by_id.contains_key(&op_id) {
return Err(baldwin_err("DUPLICATE_SUBJECT", "PCard already exists"));
}
let mut next = current.clone();
next.push(norm_op);
next
}
"exclude" => {
if !index_by_id.contains_key(&target) {
return Err(baldwin_err("MISSING_SUBJECT", "Target not found"));
}
current.iter().filter(|n| n.id.as_deref() != Some(target.as_str())).cloned().collect()
}
"invert" => {
let &idx = index_by_id.get(&target).ok_or_else(|| baldwin_err("MISSING_SUBJECT", "Target not found"))?;
let svc = spec.get("operand").and_then(|v| v.as_str()).unwrap_or("");
let mut inverted = current[idx].clone();
inverted.coeffects.required_services.retain(|s| s.as_str() != svc);
let mut next = current.clone();
next[idx] = inverted;
next
}
_ => {
let &idx = index_by_id.get(&target).ok_or_else(|| baldwin_err("MISSING_SUBJECT", "Target not found"))?;
let dest = spec.get("operand").and_then(|v| v.as_str()).unwrap_or("").trim();
let orig = ¤t[idx];
if dest.is_empty() || orig.source_uri.starts_with(&format!("{}/", dest)) {
return Err(baldwin_err("CYCLIC_PORT", "Invalid or cyclic destination layer"));
}
let mut ported = orig.clone();
if ported.pcard_type == "dynamic" {
ported.source_uri = format!("{}/{}", dest, orig.source_uri);
}
let mut next = current.clone();
next.push(ported);
next
}
};
let author = spec.get("author").and_then(|v| v.as_str()).unwrap_or("did:clm:agent:baldwin");
let timestamp = spec.get("timestamp").and_then(|v| v.as_i64()).unwrap_or(1_700_000_000_000);
let after_canonical_json = canonical_json_value(&serde_json::to_value(&after).unwrap_or_default());
let after_hash = format!("blake3:{}", crate::layer0::hash::compute_blake3(after_canonical_json.as_bytes()));
let witness_val = serde_json::json!({
"afterCount": after.len(), "author": author, "beforeCount": current.len(),
"operator": op, "target": target, "timestamp": timestamp, "type": "baldwin_witness",
});
let witness_canonical_json = canonical_json_value(&witness_val);
let witness_hash = format!("blake3:{}", crate::layer0::hash::compute_blake3(witness_canonical_json.as_bytes()));
Ok(BaldwinVectorOutcomeOk {
operator: op.to_string(), target, after, after_canonical_json, after_hash,
witness_canonical_json, witness_hash,
})
}