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    let update_inv = |clm: &mut Value, key: &str, val: &Value| {
29        if let Some(concrete) = clm.get_mut("concrete_impl").and_then(|c| c.as_object_mut()) {
30            concrete.insert(key.to_string(), val.clone());
31        }
32        if let Some(obj) = clm.get_mut("abstract_spec").and_then(|a| a.as_object_mut()) {
33            let inv = obj.entry("invariants".to_string()).or_insert_with(|| serde_json::json!({
34                "preconditions": Vec::<String>::new(), "postconditions": Vec::<String>::new()
35            }));
36            if let Some(arr) = inv.as_object_mut().and_then(|io| io.entry(format!("{}s", key)).or_insert_with(|| Value::Array(Vec::new())).as_array_mut()) {
37                if let Some(new_arr) = val.as_array() { arr.extend(new_arr.clone()); }
38                else if !arr.contains(val) { arr.push(val.clone()); }
39            }
40        }
41    };
42    let append_arr = |target: Option<&mut Value>, field: &str, item: &Value| {
43        if let Some(arr) = target.and_then(|t| t.as_object_mut()).and_then(|obj| obj.entry(field.to_string()).or_insert_with(|| Value::Array(Vec::new())).as_array_mut()) {
44            if let Some(new_arr) = item.as_array() { arr.extend(new_arr.clone()); } else { arr.push(item.clone()); }
45        }
46    };
47
48    if let Some(pre) = aug_val.get("precondition").or_else(|| aug_val.get("vcard_pre")) {
49        update_inv(clm, "precondition", pre);
50    } else if let Some(post) = aug_val.get("postcondition").or_else(|| aug_val.get("vcard_post")) {
51        update_inv(clm, "postcondition", post);
52    } else if let Some(pending) = aug_val.get("pending_cases") {
53        append_arr(clm.get_mut("balanced_exp"), "pending_cases", pending);
54    } else if let Some(criteria) = aug_val.get("success_criteria") {
55        append_arr(clm.get_mut("abstract_spec"), "success_criteria", criteria);
56    } else if let Some(obj) = clm.as_object_mut() && let Some(aug_obj) = aug_val.as_object() {
57        for (k, v) in aug_obj { obj.insert(k.clone(), v.clone()); }
58    }
59
60    let aug_hash = sha256_hash_string(&aug_content);
61    let output_dir = crate::fs_utils::get_data_dir(clm_root, "content_memory");
62    let _ = fs::create_dir_all(&output_dir);
63    let aug_file = output_dir.join(format!("augmented_{}.yaml", &aug_hash[..12]));
64
65    let new_yaml = serde_yaml::to_string(&clm_val)
66        .map_err(|e| format!("Failed to serialize augmented CLM: {}", e))?;
67    fs::write(&aug_file, &new_yaml)
68        .map_err(|e| format!("Failed to write augmented file: {}", e))?;
69
70    // Register CLM handles in Database
71    let root_content = format!(
72        "{{\"@type\":\"CLM_Root\",\"clm_name\":\"augmented_{}\",\"clm_root_hash\":\"{}\",\"a_hash\":\"none\",\"c_hash\":\"none\",\"b_hash\":\"none\"}}",
73        &aug_hash[..12], prefixed(&aug_hash)
74    );
75    let _ = db::handle_register_batch("content_memory", clm_root, &format!("clm:augmented_{}", &aug_hash[..12]), &aug_hash, &root_content);
76
77    Ok(aug_file.to_string_lossy().to_string())
78}
79
80// ── Sprint 167: Dynamic Baldwin Modularity & Fiber HMR ──────────────────────
81
82#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
83pub struct SubsumptionReport {
84    pub fiber_id: String,
85    pub old_hash: String,
86    pub new_hash: String,
87    pub pre_subsumed: bool,
88    pub post_subsumed: bool,
89    pub subsumption_valid: bool,
90    pub witness: String,
91}
92
93/// Helper to extract invariant sets from CLM AST
94pub fn extract_invariants(val: &Value, field: &str) -> std::collections::HashSet<String> {
95    let mut set = std::collections::HashSet::new();
96    let root = if let Some(clm) = val.get("clm") { clm } else { val };
97
98    if let Some(arr) = root.get("abstract_spec")
99        .and_then(|a| a.get("invariants"))
100        .and_then(|inv| inv.get(field))
101        .and_then(|f| f.as_array())
102    {
103        for item in arr {
104            if let Some(s) = item.as_str() {
105                set.insert(s.to_string());
106            }
107        }
108    }
109    if let Some(arr) = root.get("invariants")
110        .and_then(|inv| inv.get(field))
111        .and_then(|f| f.as_array())
112    {
113        for item in arr {
114            if let Some(s) = item.as_str() {
115                set.insert(s.to_string());
116            }
117        }
118    }
119    set
120}
121
122/// Verifies the Type Lattice Subsumption Criterion:
123/// Subsumes(F_new, F_old) <=> (V_pre^new <= V_pre^old) AND (V_post^new >= V_post^old)
124pub fn verify_subsumption(old_ast: &Value, new_ast: &Value) -> Result<SubsumptionReport, String> {
125    let old_pre = extract_invariants(old_ast, "preconditions");
126    let new_pre = extract_invariants(new_ast, "preconditions");
127    let old_post = extract_invariants(old_ast, "postconditions");
128    let new_post = extract_invariants(new_ast, "postconditions");
129
130    // Precondition Contravariance: V_pre^new <= V_pre^old
131    // new_pre must be a subset of old_pre (new cannot require MORE than old).
132    let pre_subsumed = new_pre.is_subset(&old_pre);
133
134    // Postcondition Covariance: V_post^new >= V_post^old
135    // old_post must be a subset of new_post (new must guarantee AT LEAST what old guaranteed).
136    let post_subsumed = old_post.is_subset(&new_post);
137
138    let subsumption_valid = pre_subsumed && post_subsumed;
139
140    let witness = format!(
141        "Pre-subsumption: {} (old_pre={:?}, new_pre={:?}); Post-subsumption: {} (old_post={:?}, new_post={:?})",
142        pre_subsumed, old_pre, new_pre, post_subsumed, old_post, new_post
143    );
144
145    let report = SubsumptionReport {
146        fiber_id: String::new(),
147        old_hash: String::new(),
148        new_hash: String::new(),
149        pre_subsumed,
150        post_subsumed,
151        subsumption_valid,
152        witness,
153    };
154
155    if subsumption_valid {
156        Ok(report)
157    } else {
158        Err(format!("Subsumption check failed: {}", report.witness))
159    }
160}
161
162/// Dynamic Baldwin Operator: Substitute (=) via Hot Module Replacement (HMR)
163/// Replaces an active PCard fiber with a new implementation without dropping tokens.
164pub fn substitute_fiber(
165    ctx: &crate::fiber::Context,
166    fiber_id: &str,
167    new_clm_file: &str,
168    clm_root: &str,
169) -> Result<SubsumptionReport, String> {
170    // 1. Locate existing fiber in active context
171    let old_fiber = ctx.get_fiber(fiber_id)
172        .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
173
174    // 2. Read new implementation file
175    let path = Path::new(new_clm_file);
176    let resolved_path = if path.is_absolute() {
177        path.to_path_buf()
178    } else {
179        Path::new(clm_root).join(new_clm_file)
180    };
181    if !resolved_path.exists() {
182        return Err(format!("New CLM file not found: {}", resolved_path.display()));
183    }
184    let yaml_content = fs::read_to_string(&resolved_path)
185        .map_err(|e| format!("Failed to read new CLM file: {}", e))?;
186
187    let new_ast: Value = serde_yaml::from_str(&yaml_content)
188        .map_err(|e| format!("Failed to parse new CLM YAML: {}", e))?;
189    let new_json_str = serde_json::to_string(&new_ast).unwrap_or_default();
190    let new_hash = sha256_hash_string(&new_json_str);
191
192    // 3. Verify Type Lattice Subsumption against old fiber's AST
193    let old_ast = old_fiber.get_ast().unwrap_or(Value::Null);
194    let old_json_str = serde_json::to_string(&old_ast).unwrap_or_default();
195    let old_hash = sha256_hash_string(&old_json_str);
196
197    let mut report = verify_subsumption(&old_ast, &new_ast)?;
198    report.fiber_id = fiber_id.to_string();
199    report.old_hash = old_hash;
200    report.new_hash = new_hash;
201
202    // 4. Homotopy Lifting Property: pause old fiber & unwind disposables
203    old_fiber.pause()?;
204    let _ = old_fiber.unwind_disposables();
205
206    // 5. Mount replacement fiber in Active state
207    ctx.remove_fiber(fiber_id);
208    let new_fiber = ctx.create_fiber(fiber_id, vec![])?;
209    new_fiber.set_ast(new_ast);
210    new_fiber.activate()?;
211
212    Ok(report)
213}
214
215/// Dynamic Baldwin Operator: Split (//)
216/// Splits an active fiber into an isolated sub-context sandbox.
217pub fn split_fiber(
218    ctx: &crate::fiber::Context,
219    fiber_id: &str,
220    allowed_coeffects: &[&str],
221) -> Result<std::sync::Arc<crate::fiber::Fiber>, String> {
222    let child_ctx = ctx.isolate(allowed_coeffects);
223    let child_id = format!("{}_split", fiber_id);
224    let child_fiber = child_ctx.create_fiber(&child_id, vec![])?;
225    child_fiber.activate()?;
226    Ok(child_fiber)
227}
228
229/// Dynamic Baldwin Operator: Augment (+)
230/// Injects a new coeffect capability to satisfy pending fiber requirements.
231pub fn augment_fiber(
232    ctx: &crate::fiber::Context,
233    fiber_id: &str,
234    coeffect: &str,
235) -> Result<(), String> {
236    let fiber = ctx.get_fiber(fiber_id)
237        .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
238    ctx.provide(coeffect, format!("CoeffectInstance:{}", coeffect));
239    fiber.satisfy_coeffect(coeffect);
240    Ok(())
241}
242
243/// Dynamic Baldwin Operator: Exclude (-)
244/// Quarantines and cleanly disposes an active fiber, releasing all its resources.
245pub fn exclude_fiber(
246    ctx: &crate::fiber::Context,
247    fiber_id: &str,
248) -> Result<(), String> {
249    let fiber = ctx.get_fiber(fiber_id)
250        .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
251    let _ = fiber.dispose();
252    ctx.remove_fiber(fiber_id);
253    Ok(())
254}
255
256// ── Sprint 522: Versioned BaldwinOperation/v1 Private Vector Adapter ──────
257
258#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
259pub struct BaldwinCoeffectsSpec {
260    #[serde(rename = "requiredServices", default)]
261    pub required_services: Vec<String>,
262    #[serde(default)]
263    pub pure: bool,
264}
265
266#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
267pub struct BaldwinVectorNode {
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub id: Option<String>,
270    #[serde(rename = "pcardId", default, skip_serializing_if = "Option::is_none")]
271    pub pcard_id: Option<String>,
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    pub name: Option<String>,
274    #[serde(rename = "pcardType")]
275    pub pcard_type: String,
276    pub signature: String,
277    #[serde(rename = "sourceUri")]
278    pub source_uri: String,
279    pub coeffects: BaldwinCoeffectsSpec,
280}
281
282#[derive(Debug, Clone, PartialEq, Eq)]
283pub struct BaldwinVectorOutcomeOk {
284    pub operator: String,
285    pub target: String,
286    pub after: Vec<BaldwinVectorNode>,
287    pub after_canonical_json: String,
288    pub after_hash: String,
289    pub witness_canonical_json: String,
290    pub witness_hash: String,
291}
292
293#[derive(Debug, Clone, PartialEq, Eq)]
294pub struct BaldwinVectorOutcomeErr {
295    pub code: &'static str,
296    pub message: String,
297}
298
299fn baldwin_err(code: &'static str, msg: impl Into<String>) -> BaldwinVectorOutcomeErr {
300    BaldwinVectorOutcomeErr { code, message: msg.into() }
301}
302
303fn canonical_json_value(val: &Value) -> String {
304    // Sprint 529: single canonicalizer (parity pinned by canonical_parity_tests).
305    crate::layer0::codec::canonical_json(val).unwrap_or_default()
306}
307
308fn normalize_vector_node(node: &BaldwinVectorNode) -> Result<(String, BaldwinVectorNode), BaldwinVectorOutcomeErr> {
309    let candidates: Vec<String> = [&node.id, &node.pcard_id, &node.name]
310        .into_iter().flatten().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
311    if candidates.is_empty() { return Err(baldwin_err("AMBIGUOUS_IDENTIFIER", "Missing node identifier")); }
312    let unique: std::collections::BTreeSet<String> = candidates.iter().cloned().collect();
313    if unique.len() > 1 { return Err(baldwin_err("AMBIGUOUS_IDENTIFIER", "Conflicting identifier aliases")); }
314    let cid = candidates[0].clone();
315    Ok((cid.clone(), BaldwinVectorNode {
316        id: Some(cid), pcard_id: None, name: None,
317        pcard_type: node.pcard_type.clone(), signature: node.signature.clone(),
318        source_uri: node.source_uri.clone(), coeffects: node.coeffects.clone(),
319    }))
320}
321
322/// Evaluate a versioned `BaldwinOperation/v1` JSON vector without mutating input state.
323/// `BTreeMap` lookup is O(log N); state materialization is O(N).
324pub fn evaluate_baldwin_vector(spec: &Value) -> Result<BaldwinVectorOutcomeOk, BaldwinVectorOutcomeErr> {
325    let op = spec.get("operator").and_then(|v| v.as_str()).unwrap_or("");
326    if !matches!(op, "split" | "substitute" | "augment" | "exclude" | "invert" | "port") {
327        return Err(baldwin_err("UNKNOWN_OPERATOR", format!("Unknown operator: {}", op)));
328    }
329    let target = spec.get("target").and_then(|v| v.as_str()).unwrap_or("").to_string();
330    let initial_arr = spec.get("initial_state").and_then(|v| v.as_array()).cloned().unwrap_or_default();
331    let mut index_by_id: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
332    let mut current: Vec<BaldwinVectorNode> = Vec::with_capacity(initial_arr.len());
333    for (idx, raw_val) in initial_arr.iter().enumerate() {
334        let parsed: BaldwinVectorNode = serde_json::from_value(raw_val.clone())
335            .map_err(|e| baldwin_err("AMBIGUOUS_IDENTIFIER", e.to_string()))?;
336        let (cid, norm) = normalize_vector_node(&parsed)?;
337        index_by_id.insert(cid, idx);
338        current.push(norm);
339    }
340
341    let parse_operand = || -> Result<(String, BaldwinVectorNode), BaldwinVectorOutcomeErr> {
342        let op_val = spec.get("operand").ok_or_else(|| baldwin_err("MISSING_SUBJECT", "Missing operand"))?;
343        let parsed: BaldwinVectorNode = serde_json::from_value(op_val.clone())
344            .map_err(|e| baldwin_err("AMBIGUOUS_IDENTIFIER", e.to_string()))?;
345        normalize_vector_node(&parsed)
346    };
347
348    let after: Vec<BaldwinVectorNode> = match op {
349        "split" => {
350            let (matched, mut rest): (Vec<_>, Vec<_>) = current
351                .iter().cloned()
352                .partition(|n| n.id.as_deref() == Some(target.as_str()) || target == "*");
353            if matched.is_empty() { current.clone() } else { rest.extend(matched); rest }
354        }
355        "substitute" => {
356            let &idx = index_by_id.get(&target).ok_or_else(|| baldwin_err("MISSING_SUBJECT", "Target not found"))?;
357            let (_, norm_op) = parse_operand()?;
358            let orig = &current[idx];
359            if orig.pcard_type == "dynamic" && norm_op.pcard_type == "dynamic" && orig.signature != norm_op.signature {
360                return Err(baldwin_err("COVARIANCE_VIOLATION", "Signature mismatch"));
361            }
362            let mut next = current.clone();
363            next[idx] = norm_op;
364            next
365        }
366        "augment" => {
367            let (op_id, norm_op) = parse_operand()?;
368            if index_by_id.contains_key(&op_id) {
369                return Err(baldwin_err("DUPLICATE_SUBJECT", "PCard already exists"));
370            }
371            let mut next = current.clone();
372            next.push(norm_op);
373            next
374        }
375        "exclude" => {
376            if !index_by_id.contains_key(&target) {
377                return Err(baldwin_err("MISSING_SUBJECT", "Target not found"));
378            }
379            current.iter().filter(|n| n.id.as_deref() != Some(target.as_str())).cloned().collect()
380        }
381        "invert" => {
382            let &idx = index_by_id.get(&target).ok_or_else(|| baldwin_err("MISSING_SUBJECT", "Target not found"))?;
383            let svc = spec.get("operand").and_then(|v| v.as_str()).unwrap_or("");
384            let mut inverted = current[idx].clone();
385            inverted.coeffects.required_services.retain(|s| s.as_str() != svc);
386            let mut next = current.clone();
387            next[idx] = inverted;
388            next
389        }
390        _ => {
391            let &idx = index_by_id.get(&target).ok_or_else(|| baldwin_err("MISSING_SUBJECT", "Target not found"))?;
392            let dest = spec.get("operand").and_then(|v| v.as_str()).unwrap_or("").trim();
393            let orig = &current[idx];
394            if dest.is_empty() || orig.source_uri.starts_with(&format!("{}/", dest)) {
395                return Err(baldwin_err("CYCLIC_PORT", "Invalid or cyclic destination layer"));
396            }
397            let mut ported = orig.clone();
398            if ported.pcard_type == "dynamic" {
399                ported.source_uri = format!("{}/{}", dest, orig.source_uri);
400            }
401            let mut next = current.clone();
402            next.push(ported);
403            next
404        }
405    };
406
407    let author = spec.get("author").and_then(|v| v.as_str()).unwrap_or("did:clm:agent:baldwin");
408    let timestamp = spec.get("timestamp").and_then(|v| v.as_i64()).unwrap_or(1_700_000_000_000);
409    let after_canonical_json = canonical_json_value(&serde_json::to_value(&after).unwrap_or_default());
410    let after_hash = format!("blake3:{}", crate::layer0::hash::compute_blake3(after_canonical_json.as_bytes()));
411    let witness_val = serde_json::json!({
412        "afterCount": after.len(), "author": author, "beforeCount": current.len(),
413        "operator": op, "target": target, "timestamp": timestamp, "type": "baldwin_witness",
414    });
415    let witness_canonical_json = canonical_json_value(&witness_val);
416    let witness_hash = format!("blake3:{}", crate::layer0::hash::compute_blake3(witness_canonical_json.as_bytes()));
417
418    Ok(BaldwinVectorOutcomeOk {
419        operator: op.to_string(), target, after, after_canonical_json, after_hash,
420        witness_canonical_json, witness_hash,
421    })
422}
423
424#[cfg(test)]
425mod canonical_parity_tests {
426    use super::canonical_json_value;
427    use crate::layer0::codec::{canonical_json, canonical_parity_corpus};
428
429    #[test]
430    fn baldwin_matches_layer0() {
431        for value in canonical_parity_corpus() {
432            assert_eq!(canonical_json_value(&value), canonical_json(&value).unwrap(), "divergence at {value}");
433        }
434    }
435}