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