Skip to main content

clm_rust_core/
baldwin_augment.rs

1#![allow(unused_imports)]
2use super::*;
3
4#[allow(dead_code)]
5pub fn augment(clm_file: &str, aug_source: &str, clm_root: &str) -> Result<String, String> {
6    let path = Path::new(clm_file);
7    if !path.exists() {
8        return Err(format!("File not found: {}", clm_file));
9    }
10    let yaml_content = fs::read_to_string(path)
11        .map_err(|e| format!("Failed to read CLM file: {}", e))?;
12    let mut clm_val: Value = serde_yaml::from_str(&yaml_content)
13        .map_err(|e| format!("Failed to parse CLM YAML: {}", e))?;
14    
15    let clm = clm_val.get_mut("clm")
16        .ok_or_else(|| "Not a valid CLM file (missing 'clm:' root)".to_string())?;
17
18    let aug_content = if Path::new(aug_source).exists() {
19        fs::read_to_string(aug_source)
20            .map_err(|e| format!("Failed to read augmentation file: {}", e))?
21    } else {
22        aug_source.to_string()
23    };
24
25    let aug_val: Value = serde_yaml::from_str(&aug_content)
26        .map_err(|e| format!("Failed to parse augmentation YAML: {}", e))?;
27
28    if let Some(pre) = aug_val.get("precondition").or_else(|| aug_val.get("vcard_pre")) {
29        if let Some(concrete_impl) = clm.get_mut("concrete_impl")
30            && let Some(obj) = concrete_impl.as_object_mut() {
31                obj.insert("precondition".to_string(), pre.clone());
32            }
33        if let Some(abstract_spec) = clm.get_mut("abstract_spec")
34            && let Some(obj) = abstract_spec.as_object_mut() {
35                let invariants = obj.entry("invariants".to_string())
36                    .or_insert_with(|| serde_json::json!({
37                        "preconditions": Vec::<String>::new(),
38                        "postconditions": Vec::<String>::new()
39                    }));
40                if let Some(inv_obj) = invariants.as_object_mut() {
41                    let pre_list = inv_obj.entry("preconditions".to_string())
42                        .or_insert_with(|| Value::Array(Vec::new()));
43                    if let Some(arr) = pre_list.as_array_mut() {
44                        if let Some(new_arr) = pre.as_array() {
45                            arr.extend(new_arr.clone());
46                        } else {
47                            if !arr.contains(pre) {
48                                arr.push(pre.clone());
49                            }
50                        }
51                    }
52                }
53            }
54    } else if let Some(post) = aug_val.get("postcondition").or_else(|| aug_val.get("vcard_post")) {
55        if let Some(concrete_impl) = clm.get_mut("concrete_impl")
56            && let Some(obj) = concrete_impl.as_object_mut() {
57                obj.insert("postcondition".to_string(), post.clone());
58            }
59        if let Some(abstract_spec) = clm.get_mut("abstract_spec")
60            && let Some(obj) = abstract_spec.as_object_mut() {
61                let invariants = obj.entry("invariants".to_string())
62                    .or_insert_with(|| serde_json::json!({
63                        "preconditions": Vec::<String>::new(),
64                        "postconditions": Vec::<String>::new()
65                    }));
66                if let Some(inv_obj) = invariants.as_object_mut() {
67                    let post_list = inv_obj.entry("postconditions".to_string())
68                        .or_insert_with(|| Value::Array(Vec::new()));
69                    if let Some(arr) = post_list.as_array_mut() {
70                        if let Some(new_arr) = post.as_array() {
71                            arr.extend(new_arr.clone());
72                        } else {
73                            if !arr.contains(post) {
74                                arr.push(post.clone());
75                            }
76                        }
77                    }
78                }
79            }
80    }
81 else if let Some(pending) = aug_val.get("pending_cases") {
82        if let Some(balanced_exp) = clm.get_mut("balanced_exp")
83            && let Some(obj) = balanced_exp.as_object_mut() {
84                let existing = obj.entry("pending_cases".to_string())
85                    .or_insert(Value::Array(Vec::new()));
86                if let Some(arr) = existing.as_array_mut() {
87                    if let Some(new_arr) = pending.as_array() {
88                        arr.extend(new_arr.clone());
89                    } else {
90                        arr.push(pending.clone());
91                    }
92                }
93            }
94    } else if let Some(criteria) = aug_val.get("success_criteria") {
95        if let Some(abstract_spec) = clm.get_mut("abstract_spec")
96            && let Some(obj) = abstract_spec.as_object_mut() {
97                let existing = obj.entry("success_criteria".to_string())
98                    .or_insert(Value::Array(Vec::new()));
99                if let Some(arr) = existing.as_array_mut() {
100                    if let Some(new_arr) = criteria.as_array() {
101                        arr.extend(new_arr.clone());
102                    } else {
103                        arr.push(criteria.clone());
104                    }
105                }
106            }
107    } else {
108        if let Some(obj) = clm.as_object_mut()
109            && let Some(aug_obj) = aug_val.as_object() {
110                for (k, v) in aug_obj {
111                    obj.insert(k.clone(), v.clone());
112                }
113            }
114    }
115
116    let aug_hash = sha256_hash_string(&aug_content);
117    let output_dir = crate::fs_utils::get_data_dir(clm_root, "content_memory");
118    let _ = fs::create_dir_all(&output_dir);
119    let aug_file = output_dir.join(format!("augmented_{}.yaml", &aug_hash[..12]));
120
121    let new_yaml = serde_yaml::to_string(&clm_val)
122        .map_err(|e| format!("Failed to serialize augmented CLM: {}", e))?;
123    fs::write(&aug_file, &new_yaml)
124        .map_err(|e| format!("Failed to write augmented file: {}", e))?;
125
126    // Register CLM handles in Database
127    let root_content = format!(
128        "{{\"@type\":\"CLM_Root\",\"clm_name\":\"augmented_{}\",\"clm_root_hash\":\"{}\",\"a_hash\":\"none\",\"c_hash\":\"none\",\"b_hash\":\"none\"}}",
129        &aug_hash[..12], prefixed(&aug_hash)
130    );
131    let _ = db::handle_register_batch("content_memory", clm_root, &format!("clm:augmented_{}", &aug_hash[..12]), &aug_hash, &root_content);
132
133    Ok(aug_file.to_string_lossy().to_string())
134}
135
136// ── Sprint 167: Dynamic Baldwin Modularity & Fiber HMR ──────────────────────
137
138#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
139pub struct SubsumptionReport {
140    pub fiber_id: String,
141    pub old_hash: String,
142    pub new_hash: String,
143    pub pre_subsumed: bool,
144    pub post_subsumed: bool,
145    pub subsumption_valid: bool,
146    pub witness: String,
147}
148
149/// Helper to extract invariant sets from CLM AST
150pub fn extract_invariants(val: &Value, field: &str) -> std::collections::HashSet<String> {
151    let mut set = std::collections::HashSet::new();
152    let root = if let Some(clm) = val.get("clm") { clm } else { val };
153
154    if let Some(arr) = root.get("abstract_spec")
155        .and_then(|a| a.get("invariants"))
156        .and_then(|inv| inv.get(field))
157        .and_then(|f| f.as_array())
158    {
159        for item in arr {
160            if let Some(s) = item.as_str() {
161                set.insert(s.to_string());
162            }
163        }
164    }
165    if let Some(arr) = root.get("invariants")
166        .and_then(|inv| inv.get(field))
167        .and_then(|f| f.as_array())
168    {
169        for item in arr {
170            if let Some(s) = item.as_str() {
171                set.insert(s.to_string());
172            }
173        }
174    }
175    set
176}
177
178/// Verifies the Type Lattice Subsumption Criterion:
179/// Subsumes(F_new, F_old) <=> (V_pre^new <= V_pre^old) AND (V_post^new >= V_post^old)
180pub fn verify_subsumption(old_ast: &Value, new_ast: &Value) -> Result<SubsumptionReport, String> {
181    let old_pre = extract_invariants(old_ast, "preconditions");
182    let new_pre = extract_invariants(new_ast, "preconditions");
183    let old_post = extract_invariants(old_ast, "postconditions");
184    let new_post = extract_invariants(new_ast, "postconditions");
185
186    // Precondition Contravariance: V_pre^new <= V_pre^old
187    // new_pre must be a subset of old_pre (new cannot require MORE than old).
188    let pre_subsumed = new_pre.is_subset(&old_pre);
189
190    // Postcondition Covariance: V_post^new >= V_post^old
191    // old_post must be a subset of new_post (new must guarantee AT LEAST what old guaranteed).
192    let post_subsumed = old_post.is_subset(&new_post);
193
194    let subsumption_valid = pre_subsumed && post_subsumed;
195
196    let witness = format!(
197        "Pre-subsumption: {} (old_pre={:?}, new_pre={:?}); Post-subsumption: {} (old_post={:?}, new_post={:?})",
198        pre_subsumed, old_pre, new_pre, post_subsumed, old_post, new_post
199    );
200
201    let report = SubsumptionReport {
202        fiber_id: String::new(),
203        old_hash: String::new(),
204        new_hash: String::new(),
205        pre_subsumed,
206        post_subsumed,
207        subsumption_valid,
208        witness,
209    };
210
211    if subsumption_valid {
212        Ok(report)
213    } else {
214        Err(format!("Subsumption check failed: {}", report.witness))
215    }
216}
217
218/// Dynamic Baldwin Operator: Substitute (=) via Hot Module Replacement (HMR)
219/// Replaces an active PCard fiber with a new implementation without dropping tokens.
220pub fn substitute_fiber(
221    ctx: &crate::fiber::Context,
222    fiber_id: &str,
223    new_clm_file: &str,
224    clm_root: &str,
225) -> Result<SubsumptionReport, String> {
226    // 1. Locate existing fiber in active context
227    let old_fiber = ctx.get_fiber(fiber_id)
228        .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
229
230    // 2. Read new implementation file
231    let path = Path::new(new_clm_file);
232    let resolved_path = if path.is_absolute() {
233        path.to_path_buf()
234    } else {
235        Path::new(clm_root).join(new_clm_file)
236    };
237    if !resolved_path.exists() {
238        return Err(format!("New CLM file not found: {}", resolved_path.display()));
239    }
240    let yaml_content = fs::read_to_string(&resolved_path)
241        .map_err(|e| format!("Failed to read new CLM file: {}", e))?;
242
243    let new_ast: Value = serde_yaml::from_str(&yaml_content)
244        .map_err(|e| format!("Failed to parse new CLM YAML: {}", e))?;
245    let new_json_str = serde_json::to_string(&new_ast).unwrap_or_default();
246    let new_hash = sha256_hash_string(&new_json_str);
247
248    // 3. Verify Type Lattice Subsumption against old fiber's AST
249    let old_ast = old_fiber.get_ast().unwrap_or(Value::Null);
250    let old_json_str = serde_json::to_string(&old_ast).unwrap_or_default();
251    let old_hash = sha256_hash_string(&old_json_str);
252
253    let mut report = verify_subsumption(&old_ast, &new_ast)?;
254    report.fiber_id = fiber_id.to_string();
255    report.old_hash = old_hash;
256    report.new_hash = new_hash;
257
258    // 4. Homotopy Lifting Property: pause old fiber & unwind disposables
259    old_fiber.pause()?;
260    let _ = old_fiber.unwind_disposables();
261
262    // 5. Mount replacement fiber in Active state
263    ctx.remove_fiber(fiber_id);
264    let new_fiber = ctx.create_fiber(fiber_id, vec![])?;
265    new_fiber.set_ast(new_ast);
266    new_fiber.activate()?;
267
268    Ok(report)
269}
270
271/// Dynamic Baldwin Operator: Split (//)
272/// Splits an active fiber into an isolated sub-context sandbox.
273pub fn split_fiber(
274    ctx: &crate::fiber::Context,
275    fiber_id: &str,
276    allowed_coeffects: &[&str],
277) -> Result<std::sync::Arc<crate::fiber::Fiber>, String> {
278    let child_ctx = ctx.isolate(allowed_coeffects);
279    let child_id = format!("{}_split", fiber_id);
280    let child_fiber = child_ctx.create_fiber(&child_id, vec![])?;
281    child_fiber.activate()?;
282    Ok(child_fiber)
283}
284
285/// Dynamic Baldwin Operator: Augment (+)
286/// Injects a new coeffect capability to satisfy pending fiber requirements.
287pub fn augment_fiber(
288    ctx: &crate::fiber::Context,
289    fiber_id: &str,
290    coeffect: &str,
291) -> Result<(), String> {
292    let fiber = ctx.get_fiber(fiber_id)
293        .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
294    ctx.provide(coeffect, format!("CoeffectInstance:{}", coeffect));
295    fiber.satisfy_coeffect(coeffect);
296    Ok(())
297}
298
299/// Dynamic Baldwin Operator: Exclude (-)
300/// Quarantines and cleanly disposes an active fiber, releasing all its resources.
301pub fn exclude_fiber(
302    ctx: &crate::fiber::Context,
303    fiber_id: &str,
304) -> Result<(), String> {
305    let fiber = ctx.get_fiber(fiber_id)
306        .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
307    let _ = fiber.dispose();
308    ctx.remove_fiber(fiber_id);
309    Ok(())
310}
311