Skip to main content

clm_rust_core/
baldwin.rs

1use serde_json::{Value, Serializer};
2use serde_json::ser::PrettyFormatter;
3use std::fs;
4use std::path::Path;
5use crate::db;
6use crate::hash::prefixed;
7use crate::utils::indent_lines;
8
9pub fn split(clm_file: &str, clm_root: &str) -> Result<String, String> {
10    // 1. Read CLM file
11    let path = Path::new(clm_file);
12    if !path.exists() {
13        return Err(format!("File not found: {}", clm_file));
14    }
15    let yaml_content = fs::read_to_string(path)
16        .map_err(|e| format!("Failed to read CLM file: {}", e))?;
17    
18    // Parse YAML using serde_yaml to preserve insertion order (via Value)
19    let mut clm_val: Value = serde_yaml::from_str(&yaml_content)
20        .map_err(|e| format!("Failed to parse CLM YAML: {}", e))?;
21    
22    let clm = clm_val.get_mut("clm")
23        .ok_or_else(|| "Not a valid CLM file (missing 'clm:' root)".to_string())?;
24
25    // Get clm_name
26    let clm_name = clm.get("concrete_impl")
27        .and_then(|c| c.get("operation"))
28        .and_then(|o| o.as_str())
29        .map(|s| s.to_string())
30        .unwrap_or_else(|| {
31            path.file_stem()
32                .map(|s| s.to_string_lossy().to_string())
33                .unwrap_or_else(|| "unknown".to_string())
34        });
35
36    let g_time = crate::fs_utils::compute_g_time();
37    let output_dir = crate::fs_utils::get_data_dir(clm_root, "content_memory");
38    let _ = fs::create_dir_all(&output_dir);
39
40    // -- 1. Extract A-MCard (abstract_spec) --
41    let abstract_spec = clm.get("abstract_spec")
42        .ok_or_else(|| "CLM has no abstract_spec section".to_string())?
43        .clone();
44    
45    let a_content_json = to_string_pretty_2_spaces(&abstract_spec)?;
46    let a_hash = sha256_hash_string(&a_content_json);
47
48    let a_file = output_dir.join(format!("a_{}.yaml", &a_hash[..12]));
49    let a_yaml_str = serde_yaml::to_string(&abstract_spec)
50        .map_err(|e| format!("Failed to serialize abstract_spec: {}", e))?;
51    let a_mcard_content = format!(
52        "mcard:\n  hash: \"{}\"\n  g_time: \"{}\"\n  facet: \"abstract_spec\"\n  content_hash: \"{}\"\n  content:\n{}",
53        prefixed(&a_hash), g_time, a_hash, indent_lines(&a_yaml_str, 4)
54    );
55    fs::write(&a_file, &a_mcard_content)
56        .map_err(|e| format!("Failed to write A-MCard: {}", e))?;
57    eprintln!("[DECOMPOSE] ✅ A-MCard: {}", a_file.to_string_lossy());
58    eprintln!("[DECOMPOSE]   hash: {}", a_hash);
59
60    // -- 2. Extract C-MCard (concrete_impl) --
61    let mut concrete_impl = clm.get("concrete_impl")
62        .ok_or_else(|| "CLM has no concrete_impl section".to_string())?
63        .clone();
64    
65    // Strip gate-binding metadata: .precondition.vcard_pre, .postcondition.vcard_post
66    if let Some(obj) = concrete_impl.as_object_mut() {
67        if let Some(pre) = obj.get_mut("precondition")
68            && let Some(pre_obj) = pre.as_object_mut() {
69                pre_obj.remove("vcard_pre");
70            }
71        if let Some(post) = obj.get_mut("postcondition")
72            && let Some(post_obj) = post.as_object_mut() {
73                post_obj.remove("vcard_post");
74            }
75        // Inject a_hash
76        obj.insert("a_hash".to_string(), Value::String(prefixed(&a_hash)));
77    }
78
79    let c_content_json = to_string_pretty_2_spaces(&concrete_impl)?;
80    let c_hash = sha256_hash_string(&c_content_json);
81
82    let c_original_yaml_str = serde_yaml::to_string(&clm.get("concrete_impl").unwrap())
83        .map_err(|e| format!("Failed to serialize original concrete_impl: {}", e))?;
84    
85    let c_file = output_dir.join(format!("c_{}.yaml", &c_hash[..12]));
86    let c_mcard_content = format!(
87        "mcard:\n  hash: \"{}\"\n  g_time: \"{}\"\n  facet: \"concrete_impl\"\n  content_hash: \"{}\"\n  content:\n    a_hash: \"{}\"\n{}",
88        prefixed(&c_hash), g_time, c_hash, prefixed(&a_hash), indent_lines(&c_original_yaml_str, 4)
89    );
90    fs::write(&c_file, &c_mcard_content)
91        .map_err(|e| format!("Failed to write C-MCard: {}", e))?;
92    eprintln!("[DECOMPOSE] ✅ C-MCard: {}", c_file.to_string_lossy());
93    eprintln!("[DECOMPOSE]   hash: {}", c_hash);
94    eprintln!("[DECOMPOSE]   a_hash: {}", a_hash);
95
96    // -- 3. Extract B-MCard (balanced_exp) --
97    let has_balanced = clm.get("balanced_exp").is_some();
98    let mut b_mcard_content_opt = None;
99    let b_hash = if has_balanced {
100        let mut balanced_exp = clm.get("balanced_exp").unwrap().clone();
101        if let Some(obj) = balanced_exp.as_object_mut() {
102            obj.insert("c_hash".to_string(), Value::String(prefixed(&c_hash)));
103        }
104        let b_content_json = to_string_pretty_2_spaces(&balanced_exp)?;
105        let b_hash_val = sha256_hash_string(&b_content_json);
106
107        let b_file = output_dir.join(format!("b_{}.yaml", &b_hash_val[..12]));
108        
109        let expectation = clm.get("balanced_exp")
110            .and_then(|b| b.get("expectation"))
111            .and_then(|e| e.as_str())
112            .unwrap_or("");
113        
114        let pending_cases = clm.get("balanced_exp")
115            .and_then(|b| b.get("pending_cases"));
116
117        let pending_cases_str = match pending_cases {
118            Some(Value::Array(arr)) if !arr.is_empty() => {
119                let y = serde_yaml::to_string(arr).unwrap_or_else(|_| "[]".to_string());
120                format!("    pending_cases:\n{}", indent_lines(&y, 6))
121            }
122            _ => "    pending_cases: []".to_string(),
123        };
124
125        let b_mcard_content = format!(
126            "mcard:\n  hash: \"{}\"\n  g_time: \"{}\"\n  facet: \"balanced_exp\"\n  content_hash: \"{}\"\n  content:\n    c_hash: \"{}\"\n    expectation: \"{}\"\n{}",
127            prefixed(&b_hash_val), g_time, b_hash_val, prefixed(&c_hash), expectation, pending_cases_str
128        );
129        b_mcard_content_opt = Some(b_mcard_content.clone());
130        fs::write(&b_file, &b_mcard_content)
131            .map_err(|e| format!("Failed to write B-MCard: {}", e))?;
132        eprintln!("[DECOMPOSE] ✅ B-MCard: {}", b_file.to_string_lossy());
133        eprintln!("[DECOMPOSE]   hash: {}", b_hash_val);
134        eprintln!("[DECOMPOSE]   c_hash: {}", c_hash);
135        let pending_count = match pending_cases {
136            Some(Value::Array(arr)) => arr.len(),
137            _ => 0,
138        };
139        eprintln!("[DECOMPOSE]   pending_cases: {}", pending_count);
140
141        b_hash_val
142    } else {
143        eprintln!("[DECOMPOSE] ⚠️  No balanced_exp section — B-MCard skipped");
144        "none".to_string()
145    };
146
147    // -- 4. Compute Merkle Root Hash --
148    let b_hash_for_root = if b_hash == "none" { "none" } else { &b_hash };
149    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);
150    let clm_root_hash = sha256_hash_string(&root_hash_input);
151
152    // -- 5. Register CLM handles in Database --
153    let db_pillar = "content_memory";
154    let root_content = format!(
155        "{{\"@type\":\"CLM_Root\",\"clm_name\":\"{}\",\"clm_root_hash\":\"{}\",\"a_hash\":\"{}\",\"c_hash\":\"{}\",\"b_hash\":\"{}\"}}",
156        clm_name, prefixed(&clm_root_hash), prefixed(&a_hash), prefixed(&c_hash), prefixed(&b_hash)
157    );
158
159    let _ = db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}", clm_name), &clm_root_hash, &root_content);
160    let _ = db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}:a", clm_name), &a_hash, "");
161    let _ = db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}:c", clm_name), &c_hash, "");
162    if b_hash != "none" {
163        let _ = db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}:b", clm_name), &b_hash, "");
164    }
165
166    // Register facet handles to match shell split behavior exactly
167    let a_mcard_hash = sha256_hash_string(&a_mcard_content);
168    let _ = db::handle_register_batch(db_pillar, clm_root, &format!("facet:a:{}", &a_hash[..12]), &a_mcard_hash, &a_mcard_content);
169
170    let c_mcard_hash = sha256_hash_string(&c_mcard_content);
171    let _ = db::handle_register_batch(db_pillar, clm_root, &format!("facet:c:{}", &c_hash[..12]), &c_mcard_hash, &c_mcard_content);
172
173    if let Some(ref b_mcard_content) = b_mcard_content_opt {
174        let b_mcard_hash = sha256_hash_string(b_mcard_content);
175        let _ = db::handle_register_batch(db_pillar, clm_root, &format!("facet:b:{}", &b_hash[..12]), &b_mcard_hash, b_mcard_content);
176    }
177    eprintln!("[DECOMPOSE] 🔗 Registered handles: clm:{} → {}", clm_name, prefixed(&clm_root_hash));
178
179    // -- 6. Print composite reference exactly like decompose_clm --
180    let mut out = String::new();
181    out.push_str("\n######################################################\n");
182    out.push_str("  Cubical Decomposition Complete\n");
183    out.push_str("######################################################\n");
184    out.push_str("clm:\n");
185    out.push_str(&format!("  clm_root_hash: \"{}\"\n", prefixed(&clm_root_hash)));
186    out.push_str(&format!("  clm_name: \"{}\"\n", clm_name));
187    out.push_str(&format!("  a_hash: \"{}\"\n", prefixed(&a_hash)));
188    out.push_str(&format!("  c_hash: \"{}\"\n", prefixed(&c_hash)));
189    if b_hash != "none" {
190        out.push_str(&format!("  b_hash: \"{}\"\n", prefixed(&b_hash)));
191    }
192    out.push('\n');
193    out.push_str(&format!("# Chain: A({}) ← C({}) ← B({})\n", a_hash, c_hash, b_hash_for_root));
194    out.push_str(&format!("# Root:  {} = H(a:c:b)\n", clm_root_hash));
195
196    Ok(out)
197}
198
199pub fn merge(a_file: &str, c_file: &str, b_file: Option<&str>) -> Result<String, String> {
200    // 1. Read A-MCard
201    let a_path = Path::new(a_file);
202    if !a_path.exists() {
203        return Err(format!("File not found: {}", a_file));
204    }
205    let a_content = fs::read_to_string(a_path)
206        .map_err(|e| format!("Failed to read A-MCard file: {}", e))?;
207    let a_mcard: Value = serde_yaml::from_str(&a_content)
208        .map_err(|e| format!("Failed to parse A-MCard YAML: {}", e))?;
209    let abstract_spec = a_mcard.get("mcard")
210        .and_then(|m| m.get("content"))
211        .ok_or_else(|| "Missing 'mcard.content' in A-MCard".to_string())?;
212
213    // 2. Read C-MCard
214    let c_path = Path::new(c_file);
215    if !c_path.exists() {
216        return Err(format!("File not found: {}", c_file));
217    }
218    let c_content = fs::read_to_string(c_path)
219        .map_err(|e| format!("Failed to read C-MCard file: {}", e))?;
220    let c_mcard: Value = serde_yaml::from_str(&c_content)
221        .map_err(|e| format!("Failed to parse C-MCard YAML: {}", e))?;
222    let concrete_impl_val = c_mcard.get("mcard")
223        .and_then(|m| m.get("content"))
224        .ok_or_else(|| "Missing 'mcard.content' in C-MCard".to_string())?;
225    
226    // Strip a_hash from concrete_impl
227    let mut concrete_impl = concrete_impl_val.clone();
228    if let Some(obj) = concrete_impl.as_object_mut() {
229        obj.remove("a_hash");
230    }
231
232    // 3. Read B-MCard (optional)
233    let mut balanced_exp = None;
234    if let Some(bf) = b_file {
235        let b_path = Path::new(bf);
236        if b_path.exists() {
237            let b_content = fs::read_to_string(b_path)
238                .map_err(|e| format!("Failed to read B-MCard file: {}", e))?;
239            let b_mcard: Value = serde_yaml::from_str(&b_content)
240                .map_err(|e| format!("Failed to parse B-MCard YAML: {}", e))?;
241            let balanced_exp_val = b_mcard.get("mcard")
242                .and_then(|m| m.get("content"))
243                .ok_or_else(|| "Missing 'mcard.content' in B-MCard".to_string())?;
244            
245            // Strip c_hash from balanced_exp
246            let mut b_val = balanced_exp_val.clone();
247            if let Some(obj) = b_val.as_object_mut() {
248                obj.remove("c_hash");
249            }
250            balanced_exp = Some(b_val);
251        }
252    }
253
254    // Reconstruct CLM
255    let mut clm_map = serde_json::Map::new();
256    clm_map.insert("abstract_spec".to_string(), abstract_spec.clone());
257    clm_map.insert("concrete_impl".to_string(), concrete_impl);
258    if let Some(b_val) = balanced_exp {
259        clm_map.insert("balanced_exp".to_string(), b_val);
260    }
261    
262    let mut root_map = serde_json::Map::new();
263    root_map.insert("clm".to_string(), Value::Object(clm_map));
264
265    let root_val = Value::Object(root_map);
266    serde_yaml::to_string(&root_val)
267        .map_err(|e| format!("Failed to serialize reconstructed CLM: {}", e))
268}
269
270pub fn to_string_pretty_2_spaces<T: serde::Serialize>(value: &T) -> Result<String, String> {
271    let mut buf = Vec::new();
272    let formatter = PrettyFormatter::with_indent(b"  ");
273    let mut ser = Serializer::with_formatter(&mut buf, formatter);
274    value.serialize(&mut ser)
275        .map_err(|e| format!("Failed to serialize pretty JSON: {}", e))?;
276    Ok(String::from_utf8(buf).unwrap())
277}
278
279pub fn sha256_hash_string(s: &str) -> String {
280    crate::hash::raw_hash_string(s)
281}
282
283
284
285#[allow(dead_code)]
286pub fn substitute(clm_file: &str, new_impl_file_or_op: &str, clm_root: &str) -> Result<String, String> {
287    let path = Path::new(clm_file);
288    if !path.exists() {
289        return Err(format!("File not found: {}", clm_file));
290    }
291    let yaml_content = fs::read_to_string(path)
292        .map_err(|e| format!("Failed to read CLM file: {}", e))?;
293    let mut clm_val: Value = serde_yaml::from_str(&yaml_content)
294        .map_err(|e| format!("Failed to parse CLM YAML: {}", e))?;
295    let clm = clm_val.get_mut("clm")
296        .ok_or_else(|| "Not a valid CLM file (missing 'clm:' root)".to_string())?;
297
298    let abstract_spec = clm.get("abstract_spec")
299        .ok_or_else(|| "CLM has no abstract_spec section".to_string())?
300        .clone();
301
302    let new_c_spec: Value = if Path::new(new_impl_file_or_op).exists() {
303        let c_content = fs::read_to_string(new_impl_file_or_op)
304            .map_err(|e| format!("Failed to read new implementation file: {}", e))?;
305        let parsed: Value = serde_yaml::from_str(&c_content)
306            .map_err(|e| format!("Failed to parse new implementation YAML: {}", e))?;
307        if let Some(c) = parsed.get("clm").and_then(|c| c.get("concrete_impl")) {
308            c.clone()
309        } else if parsed.get("concrete_impl").is_some() {
310            parsed.get("concrete_impl").unwrap().clone()
311        } else {
312            parsed
313        }
314    } else {
315        serde_json::json!({
316            "runtime": "system",
317            "operation": new_impl_file_or_op,
318            "inputs": Vec::<String>::new(),
319            "outputs": Vec::<String>::new(),
320            "process": {
321                "script_handle": format!("script:{}", new_impl_file_or_op)
322            }
323        })
324    };
325
326    let a_content_json = to_string_pretty_2_spaces(&abstract_spec)?;
327    let a_hash = sha256_hash_string(&a_content_json);
328
329    let mut concrete_impl = new_c_spec.clone();
330    if let Some(obj) = concrete_impl.as_object_mut() {
331        obj.insert("a_hash".to_string(), Value::String(prefixed(&a_hash)));
332        if let Some(pre) = obj.get_mut("precondition")
333            && let Some(pre_obj) = pre.as_object_mut() {
334                pre_obj.remove("vcard_pre");
335            }
336        if let Some(post) = obj.get_mut("postcondition")
337            && let Some(post_obj) = post.as_object_mut() {
338                post_obj.remove("vcard_post");
339            }
340    }
341
342    let c_content_json = to_string_pretty_2_spaces(&concrete_impl)?;
343    let c_hash = sha256_hash_string(&c_content_json);
344
345    let b_spec = clm.get("balanced_exp").cloned();
346    let expectation = b_spec.as_ref()
347        .and_then(|b| b.get("expectation"))
348        .and_then(|e| e.as_str())
349        .unwrap_or("Substituted implementation pending verification");
350    let pending_cases = b_spec.as_ref()
351        .and_then(|b| b.get("pending_cases"))
352        .cloned()
353        .unwrap_or(Value::Array(Vec::new()));
354
355    let mut new_clm = serde_json::Map::new();
356    new_clm.insert("abstract_spec".to_string(), abstract_spec);
357    new_clm.insert("concrete_impl".to_string(), concrete_impl);
358    
359    let mut new_b = serde_json::Map::new();
360    new_b.insert("expectation".to_string(), Value::String(expectation.to_string()));
361    new_b.insert("pending_cases".to_string(), pending_cases);
362    new_clm.insert("balanced_exp".to_string(), Value::Object(new_b));
363
364    let mut new_root = serde_json::Map::new();
365    new_root.insert("clm".to_string(), Value::Object(new_clm));
366
367    let new_yaml = serde_yaml::to_string(&Value::Object(new_root))
368        .map_err(|e| format!("Failed to serialize substituted CLM: {}", e))?;
369
370    let output_dir = crate::fs_utils::get_data_dir(clm_root, "content_memory");
371    let _ = fs::create_dir_all(&output_dir);
372    let sub_file = output_dir.join(format!("substituted_{}.yaml", &c_hash[..12]));
373    fs::write(&sub_file, &new_yaml)
374        .map_err(|e| format!("Failed to write substituted file: {}", e))?;
375
376    // Register CLM handles in Database
377    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);
378    let clm_root_hash = sha256_hash_string(&root_hash_input);
379    let root_content = format!(
380        "{{\"@type\":\"CLM_Root\",\"clm_name\":\"substituted_{}\",\"clm_root_hash\":\"{}\",\"a_hash\":\"{}\",\"c_hash\":\"{}\",\"b_hash\":\"none\"}}",
381        &c_hash[..12], prefixed(&clm_root_hash), prefixed(&a_hash), prefixed(&c_hash)
382    );
383
384    let _ = db::handle_register_batch("content_memory", clm_root, &format!("clm:substituted_{}", &c_hash[..12]), &clm_root_hash, &root_content);
385
386    Ok(sub_file.to_string_lossy().to_string())
387}
388
389#[allow(dead_code)]
390pub fn augment(clm_file: &str, aug_source: &str, clm_root: &str) -> Result<String, String> {
391    let path = Path::new(clm_file);
392    if !path.exists() {
393        return Err(format!("File not found: {}", clm_file));
394    }
395    let yaml_content = fs::read_to_string(path)
396        .map_err(|e| format!("Failed to read CLM file: {}", e))?;
397    let mut clm_val: Value = serde_yaml::from_str(&yaml_content)
398        .map_err(|e| format!("Failed to parse CLM YAML: {}", e))?;
399    
400    let clm = clm_val.get_mut("clm")
401        .ok_or_else(|| "Not a valid CLM file (missing 'clm:' root)".to_string())?;
402
403    let aug_content = if Path::new(aug_source).exists() {
404        fs::read_to_string(aug_source)
405            .map_err(|e| format!("Failed to read augmentation file: {}", e))?
406    } else {
407        aug_source.to_string()
408    };
409
410    let aug_val: Value = serde_yaml::from_str(&aug_content)
411        .map_err(|e| format!("Failed to parse augmentation YAML: {}", e))?;
412
413    if let Some(pre) = aug_val.get("precondition").or_else(|| aug_val.get("vcard_pre")) {
414        if let Some(concrete_impl) = clm.get_mut("concrete_impl")
415            && let Some(obj) = concrete_impl.as_object_mut() {
416                obj.insert("precondition".to_string(), pre.clone());
417            }
418        if let Some(abstract_spec) = clm.get_mut("abstract_spec")
419            && let Some(obj) = abstract_spec.as_object_mut() {
420                let invariants = obj.entry("invariants".to_string())
421                    .or_insert_with(|| serde_json::json!({
422                        "preconditions": Vec::<String>::new(),
423                        "postconditions": Vec::<String>::new()
424                    }));
425                if let Some(inv_obj) = invariants.as_object_mut() {
426                    let pre_list = inv_obj.entry("preconditions".to_string())
427                        .or_insert_with(|| Value::Array(Vec::new()));
428                    if let Some(arr) = pre_list.as_array_mut() {
429                        if let Some(new_arr) = pre.as_array() {
430                            arr.extend(new_arr.clone());
431                        } else {
432                            if !arr.contains(pre) {
433                                arr.push(pre.clone());
434                            }
435                        }
436                    }
437                }
438            }
439    } else if let Some(post) = aug_val.get("postcondition").or_else(|| aug_val.get("vcard_post")) {
440        if let Some(concrete_impl) = clm.get_mut("concrete_impl")
441            && let Some(obj) = concrete_impl.as_object_mut() {
442                obj.insert("postcondition".to_string(), post.clone());
443            }
444        if let Some(abstract_spec) = clm.get_mut("abstract_spec")
445            && let Some(obj) = abstract_spec.as_object_mut() {
446                let invariants = obj.entry("invariants".to_string())
447                    .or_insert_with(|| serde_json::json!({
448                        "preconditions": Vec::<String>::new(),
449                        "postconditions": Vec::<String>::new()
450                    }));
451                if let Some(inv_obj) = invariants.as_object_mut() {
452                    let post_list = inv_obj.entry("postconditions".to_string())
453                        .or_insert_with(|| Value::Array(Vec::new()));
454                    if let Some(arr) = post_list.as_array_mut() {
455                        if let Some(new_arr) = post.as_array() {
456                            arr.extend(new_arr.clone());
457                        } else {
458                            if !arr.contains(post) {
459                                arr.push(post.clone());
460                            }
461                        }
462                    }
463                }
464            }
465    }
466 else if let Some(pending) = aug_val.get("pending_cases") {
467        if let Some(balanced_exp) = clm.get_mut("balanced_exp")
468            && let Some(obj) = balanced_exp.as_object_mut() {
469                let existing = obj.entry("pending_cases".to_string())
470                    .or_insert(Value::Array(Vec::new()));
471                if let Some(arr) = existing.as_array_mut() {
472                    if let Some(new_arr) = pending.as_array() {
473                        arr.extend(new_arr.clone());
474                    } else {
475                        arr.push(pending.clone());
476                    }
477                }
478            }
479    } else if let Some(criteria) = aug_val.get("success_criteria") {
480        if let Some(abstract_spec) = clm.get_mut("abstract_spec")
481            && let Some(obj) = abstract_spec.as_object_mut() {
482                let existing = obj.entry("success_criteria".to_string())
483                    .or_insert(Value::Array(Vec::new()));
484                if let Some(arr) = existing.as_array_mut() {
485                    if let Some(new_arr) = criteria.as_array() {
486                        arr.extend(new_arr.clone());
487                    } else {
488                        arr.push(criteria.clone());
489                    }
490                }
491            }
492    } else {
493        if let Some(obj) = clm.as_object_mut()
494            && let Some(aug_obj) = aug_val.as_object() {
495                for (k, v) in aug_obj {
496                    obj.insert(k.clone(), v.clone());
497                }
498            }
499    }
500
501    let aug_hash = sha256_hash_string(&aug_content);
502    let output_dir = crate::fs_utils::get_data_dir(clm_root, "content_memory");
503    let _ = fs::create_dir_all(&output_dir);
504    let aug_file = output_dir.join(format!("augmented_{}.yaml", &aug_hash[..12]));
505
506    let new_yaml = serde_yaml::to_string(&clm_val)
507        .map_err(|e| format!("Failed to serialize augmented CLM: {}", e))?;
508    fs::write(&aug_file, &new_yaml)
509        .map_err(|e| format!("Failed to write augmented file: {}", e))?;
510
511    // Register CLM handles in Database
512    let root_content = format!(
513        "{{\"@type\":\"CLM_Root\",\"clm_name\":\"augmented_{}\",\"clm_root_hash\":\"{}\",\"a_hash\":\"none\",\"c_hash\":\"none\",\"b_hash\":\"none\"}}",
514        &aug_hash[..12], prefixed(&aug_hash)
515    );
516    let _ = db::handle_register_batch("content_memory", clm_root, &format!("clm:augmented_{}", &aug_hash[..12]), &aug_hash, &root_content);
517
518    Ok(aug_file.to_string_lossy().to_string())
519}
520
521// ── Sprint 167: Dynamic Baldwin Modularity & Fiber HMR ──────────────────────
522
523#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
524pub struct SubsumptionReport {
525    pub fiber_id: String,
526    pub old_hash: String,
527    pub new_hash: String,
528    pub pre_subsumed: bool,
529    pub post_subsumed: bool,
530    pub subsumption_valid: bool,
531    pub witness: String,
532}
533
534/// Helper to extract invariant sets from CLM AST
535pub fn extract_invariants(val: &Value, field: &str) -> std::collections::HashSet<String> {
536    let mut set = std::collections::HashSet::new();
537    let root = if let Some(clm) = val.get("clm") { clm } else { val };
538
539    if let Some(arr) = root.get("abstract_spec")
540        .and_then(|a| a.get("invariants"))
541        .and_then(|inv| inv.get(field))
542        .and_then(|f| f.as_array())
543    {
544        for item in arr {
545            if let Some(s) = item.as_str() {
546                set.insert(s.to_string());
547            }
548        }
549    }
550    if let Some(arr) = root.get("invariants")
551        .and_then(|inv| inv.get(field))
552        .and_then(|f| f.as_array())
553    {
554        for item in arr {
555            if let Some(s) = item.as_str() {
556                set.insert(s.to_string());
557            }
558        }
559    }
560    set
561}
562
563/// Verifies the Type Lattice Subsumption Criterion:
564/// Subsumes(F_new, F_old) <=> (V_pre^new <= V_pre^old) AND (V_post^new >= V_post^old)
565pub fn verify_subsumption(old_ast: &Value, new_ast: &Value) -> Result<SubsumptionReport, String> {
566    let old_pre = extract_invariants(old_ast, "preconditions");
567    let new_pre = extract_invariants(new_ast, "preconditions");
568    let old_post = extract_invariants(old_ast, "postconditions");
569    let new_post = extract_invariants(new_ast, "postconditions");
570
571    // Precondition Contravariance: V_pre^new <= V_pre^old
572    // new_pre must be a subset of old_pre (new cannot require MORE than old).
573    let pre_subsumed = new_pre.is_subset(&old_pre);
574
575    // Postcondition Covariance: V_post^new >= V_post^old
576    // old_post must be a subset of new_post (new must guarantee AT LEAST what old guaranteed).
577    let post_subsumed = old_post.is_subset(&new_post);
578
579    let subsumption_valid = pre_subsumed && post_subsumed;
580
581    let witness = format!(
582        "Pre-subsumption: {} (old_pre={:?}, new_pre={:?}); Post-subsumption: {} (old_post={:?}, new_post={:?})",
583        pre_subsumed, old_pre, new_pre, post_subsumed, old_post, new_post
584    );
585
586    let report = SubsumptionReport {
587        fiber_id: String::new(),
588        old_hash: String::new(),
589        new_hash: String::new(),
590        pre_subsumed,
591        post_subsumed,
592        subsumption_valid,
593        witness,
594    };
595
596    if subsumption_valid {
597        Ok(report)
598    } else {
599        Err(format!("Subsumption check failed: {}", report.witness))
600    }
601}
602
603/// Dynamic Baldwin Operator: Substitute (=) via Hot Module Replacement (HMR)
604/// Replaces an active PCard fiber with a new implementation without dropping tokens.
605pub fn substitute_fiber(
606    ctx: &crate::fiber::Context,
607    fiber_id: &str,
608    new_clm_file: &str,
609    clm_root: &str,
610) -> Result<SubsumptionReport, String> {
611    // 1. Locate existing fiber in active context
612    let old_fiber = ctx.get_fiber(fiber_id)
613        .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
614
615    // 2. Read new implementation file
616    let path = Path::new(new_clm_file);
617    let resolved_path = if path.is_absolute() {
618        path.to_path_buf()
619    } else {
620        Path::new(clm_root).join(new_clm_file)
621    };
622    if !resolved_path.exists() {
623        return Err(format!("New CLM file not found: {}", resolved_path.display()));
624    }
625    let yaml_content = fs::read_to_string(&resolved_path)
626        .map_err(|e| format!("Failed to read new CLM file: {}", e))?;
627
628    let new_ast: Value = serde_yaml::from_str(&yaml_content)
629        .map_err(|e| format!("Failed to parse new CLM YAML: {}", e))?;
630    let new_json_str = serde_json::to_string(&new_ast).unwrap_or_default();
631    let new_hash = sha256_hash_string(&new_json_str);
632
633    // 3. Verify Type Lattice Subsumption against old fiber's AST
634    let old_ast = old_fiber.get_ast().unwrap_or(Value::Null);
635    let old_json_str = serde_json::to_string(&old_ast).unwrap_or_default();
636    let old_hash = sha256_hash_string(&old_json_str);
637
638    let mut report = verify_subsumption(&old_ast, &new_ast)?;
639    report.fiber_id = fiber_id.to_string();
640    report.old_hash = old_hash;
641    report.new_hash = new_hash;
642
643    // 4. Homotopy Lifting Property: pause old fiber & unwind disposables
644    old_fiber.pause()?;
645    let _ = old_fiber.unwind_disposables();
646
647    // 5. Mount replacement fiber in Active state
648    ctx.remove_fiber(fiber_id);
649    let new_fiber = ctx.create_fiber(fiber_id, vec![])?;
650    new_fiber.set_ast(new_ast);
651    new_fiber.activate()?;
652
653    Ok(report)
654}
655
656/// Dynamic Baldwin Operator: Split (//)
657/// Splits an active fiber into an isolated sub-context sandbox.
658pub fn split_fiber(
659    ctx: &crate::fiber::Context,
660    fiber_id: &str,
661    allowed_coeffects: &[&str],
662) -> Result<std::sync::Arc<crate::fiber::Fiber>, String> {
663    let child_ctx = ctx.isolate(allowed_coeffects);
664    let child_id = format!("{}_split", fiber_id);
665    let child_fiber = child_ctx.create_fiber(&child_id, vec![])?;
666    child_fiber.activate()?;
667    Ok(child_fiber)
668}
669
670/// Dynamic Baldwin Operator: Augment (+)
671/// Injects a new coeffect capability to satisfy pending fiber requirements.
672pub fn augment_fiber(
673    ctx: &crate::fiber::Context,
674    fiber_id: &str,
675    coeffect: &str,
676) -> Result<(), String> {
677    let fiber = ctx.get_fiber(fiber_id)
678        .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
679    ctx.provide(coeffect, format!("CoeffectInstance:{}", coeffect));
680    fiber.satisfy_coeffect(coeffect);
681    Ok(())
682}
683
684/// Dynamic Baldwin Operator: Exclude (-)
685/// Quarantines and cleanly disposes an active fiber, releasing all its resources.
686pub fn exclude_fiber(
687    ctx: &crate::fiber::Context,
688    fiber_id: &str,
689) -> Result<(), String> {
690    let fiber = ctx.get_fiber(fiber_id)
691        .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
692    let _ = fiber.dispose();
693    ctx.remove_fiber(fiber_id);
694    Ok(())
695}
696
697#[cfg(test)]
698mod tests {
699    use super::*;
700
701    #[test]
702    fn test_subsumption_verification_soundness() {
703        let old_ast = serde_json::json!({
704            "abstract_spec": {
705                "invariants": {
706                    "preconditions": ["pre_a", "pre_b"],
707                    "postconditions": ["post_x"]
708                }
709            }
710        });
711
712        // Valid replacement: weaker precondition (pre_a only) and stronger postcondition (post_x, post_y)
713        let compliant_new_ast = serde_json::json!({
714            "abstract_spec": {
715                "invariants": {
716                    "preconditions": ["pre_a"],
717                    "postconditions": ["post_x", "post_y"]
718                }
719            }
720        });
721
722        let res = verify_subsumption(&old_ast, &compliant_new_ast);
723        assert!(res.is_ok());
724        let report = res.unwrap();
725        assert!(report.pre_subsumed);
726        assert!(report.post_subsumed);
727        assert!(report.subsumption_valid);
728
729        // Invalid replacement: stronger precondition (requires extra pre_c)
730        let breaking_pre_ast = serde_json::json!({
731            "abstract_spec": {
732                "invariants": {
733                    "preconditions": ["pre_a", "pre_c"],
734                    "postconditions": ["post_x"]
735                }
736            }
737        });
738        assert!(verify_subsumption(&old_ast, &breaking_pre_ast).is_err());
739
740        // Invalid replacement: weaker postcondition (missing post_x)
741        let breaking_post_ast = serde_json::json!({
742            "abstract_spec": {
743                "invariants": {
744                    "preconditions": ["pre_a"],
745                    "postconditions": ["post_z"]
746                }
747            }
748        });
749        assert!(verify_subsumption(&old_ast, &breaking_post_ast).is_err());
750    }
751
752    #[test]
753    fn test_dynamic_baldwin_fiber_lifecycle() {
754        let ctx = crate::fiber::Context::root();
755        let fiber = ctx.create_fiber("test_fiber", vec!["effect_1".to_string()]).unwrap();
756        assert_eq!(fiber.get_state(), crate::fiber::FiberState::Pending);
757
758        // Augment: satisfy effect_1
759        augment_fiber(&ctx, "test_fiber", "effect_1").unwrap();
760        assert_eq!(fiber.get_state(), crate::fiber::FiberState::Active);
761
762        // Split: create child fiber in isolated context
763        let split_res = split_fiber(&ctx, "test_fiber", &["effect_1"]);
764        assert!(split_res.is_ok());
765
766        // Exclude: cleanly terminate and remove
767        exclude_fiber(&ctx, "test_fiber").unwrap();
768        assert!(ctx.get_fiber("test_fiber").is_none());
769    }
770}
771
772