Skip to main content

clm_rust_core/layer0/
baldwin_augment.rs

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