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 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 _ = db::handle_register_batch(crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY, clm_root, &format!("clm:augmented_{}", &aug_hash[..12]), &aug_hash, &root_content);
77
78 Ok(aug_file.to_string_lossy().to_string())
79}
80
81#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
84pub struct SubsumptionReport {
85 pub fiber_id: String,
86 pub old_hash: String,
87 pub new_hash: String,
88 pub pre_subsumed: bool,
89 pub post_subsumed: bool,
90 pub subsumption_valid: bool,
91 pub witness: String,
92}
93
94pub fn extract_invariants(val: &Value, field: &str) -> std::collections::HashSet<String> {
96 let mut set = std::collections::HashSet::new();
97 let root = if let Some(clm) = val.get("clm") { clm } else { val };
98
99 if let Some(arr) = root.get("abstract_spec")
100 .and_then(|a| a.get("invariants"))
101 .and_then(|inv| inv.get(field))
102 .and_then(|f| f.as_array())
103 {
104 for item in arr {
105 if let Some(s) = item.as_str() {
106 set.insert(s.to_string());
107 }
108 }
109 }
110 if let Some(arr) = root.get("invariants")
111 .and_then(|inv| inv.get(field))
112 .and_then(|f| f.as_array())
113 {
114 for item in arr {
115 if let Some(s) = item.as_str() {
116 set.insert(s.to_string());
117 }
118 }
119 }
120 set
121}
122
123pub fn verify_subsumption(old_ast: &Value, new_ast: &Value) -> Result<SubsumptionReport, String> {
126 let old_pre = extract_invariants(old_ast, "preconditions");
127 let new_pre = extract_invariants(new_ast, "preconditions");
128 let old_post = extract_invariants(old_ast, "postconditions");
129 let new_post = extract_invariants(new_ast, "postconditions");
130
131 let pre_subsumed = new_pre.is_subset(&old_pre);
134
135 let post_subsumed = old_post.is_subset(&new_post);
138
139 let subsumption_valid = pre_subsumed && post_subsumed;
140
141 let witness = format!(
142 "Pre-subsumption: {} (old_pre={:?}, new_pre={:?}); Post-subsumption: {} (old_post={:?}, new_post={:?})",
143 pre_subsumed, old_pre, new_pre, post_subsumed, old_post, new_post
144 );
145
146 let report = SubsumptionReport {
147 fiber_id: String::new(),
148 old_hash: String::new(),
149 new_hash: String::new(),
150 pre_subsumed,
151 post_subsumed,
152 subsumption_valid,
153 witness,
154 };
155
156 if subsumption_valid {
157 Ok(report)
158 } else {
159 Err(format!("Subsumption check failed: {}", report.witness))
160 }
161}
162
163pub fn substitute_fiber(
166 ctx: &crate::fiber::Context,
167 fiber_id: &str,
168 new_clm_file: &str,
169 clm_root: &str,
170) -> Result<SubsumptionReport, String> {
171 let old_fiber = ctx.get_fiber(fiber_id)
173 .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
174
175 let path = Path::new(new_clm_file);
177 let resolved_path = if path.is_absolute() {
178 path.to_path_buf()
179 } else {
180 Path::new(clm_root).join(new_clm_file)
181 };
182 if !resolved_path.exists() {
183 return Err(format!("New CLM file not found: {}", resolved_path.display()));
184 }
185 let yaml_content = fs::read_to_string(&resolved_path)
186 .map_err(|e| format!("Failed to read new CLM file: {}", e))?;
187
188 let new_ast: Value = serde_yaml::from_str(&yaml_content)
189 .map_err(|e| format!("Failed to parse new CLM YAML: {}", e))?;
190 let new_json_str = serde_json::to_string(&new_ast).unwrap_or_default();
191 let new_hash = sha256_hash_string(&new_json_str);
192
193 let old_ast = old_fiber.get_ast().unwrap_or(Value::Null);
195 let old_json_str = serde_json::to_string(&old_ast).unwrap_or_default();
196 let old_hash = sha256_hash_string(&old_json_str);
197
198 let mut report = verify_subsumption(&old_ast, &new_ast)?;
199 report.fiber_id = fiber_id.to_string();
200 report.old_hash = old_hash;
201 report.new_hash = new_hash;
202
203 old_fiber.pause()?;
205 let _ = old_fiber.unwind_disposables();
206
207 ctx.remove_fiber(fiber_id);
209 let new_fiber = ctx.create_fiber(fiber_id, vec![])?;
210 new_fiber.set_ast(new_ast);
211 new_fiber.activate()?;
212
213 Ok(report)
214}
215
216pub fn split_fiber(
219 ctx: &crate::fiber::Context,
220 fiber_id: &str,
221 allowed_coeffects: &[&str],
222) -> Result<std::sync::Arc<crate::fiber::Fiber>, String> {
223 let child_ctx = ctx.isolate(allowed_coeffects);
224 let child_id = format!("{}_split", fiber_id);
225 let child_fiber = child_ctx.create_fiber(&child_id, vec![])?;
226 child_fiber.activate()?;
227 Ok(child_fiber)
228}
229
230pub fn augment_fiber(
233 ctx: &crate::fiber::Context,
234 fiber_id: &str,
235 coeffect: &str,
236) -> Result<(), String> {
237 let fiber = ctx.get_fiber(fiber_id)
238 .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
239 ctx.provide(coeffect, format!("CoeffectInstance:{}", coeffect));
240 fiber.satisfy_coeffect(coeffect);
241 Ok(())
242}
243
244pub fn exclude_fiber(
247 ctx: &crate::fiber::Context,
248 fiber_id: &str,
249) -> Result<(), String> {
250 let fiber = ctx.get_fiber(fiber_id)
251 .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
252 let _ = fiber.dispose();
253 ctx.remove_fiber(fiber_id);
254 Ok(())
255}
256
257#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
260pub struct BaldwinCoeffectsSpec {
261 #[serde(rename = "requiredServices", default)]
262 pub required_services: Vec<String>,
263 #[serde(default)]
264 pub pure: bool,
265}
266
267#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
268pub struct BaldwinVectorNode {
269 #[serde(default, skip_serializing_if = "Option::is_none")]
270 pub id: Option<String>,
271 #[serde(rename = "pcardId", default, skip_serializing_if = "Option::is_none")]
272 pub pcard_id: Option<String>,
273 #[serde(default, skip_serializing_if = "Option::is_none")]
274 pub name: Option<String>,
275 #[serde(rename = "pcardType")]
276 pub pcard_type: String,
277 pub signature: String,
278 #[serde(rename = "sourceUri")]
279 pub source_uri: String,
280 pub coeffects: BaldwinCoeffectsSpec,
281}
282
283#[derive(Debug, Clone, PartialEq, Eq)]
284pub struct BaldwinVectorOutcomeOk {
285 pub operator: String,
286 pub target: String,
287 pub after: Vec<BaldwinVectorNode>,
288 pub after_canonical_json: String,
289 pub after_hash: String,
290 pub witness_canonical_json: String,
291 pub witness_hash: String,
292}
293
294#[derive(Debug, Clone, PartialEq, Eq)]
295pub struct BaldwinVectorOutcomeErr {
296 pub code: &'static str,
297 pub message: String,
298}
299
300fn baldwin_err(code: &'static str, msg: impl Into<String>) -> BaldwinVectorOutcomeErr {
301 BaldwinVectorOutcomeErr { code, message: msg.into() }
302}
303
304fn canonical_json_value(val: &Value) -> String {
305 crate::layer0::codec::canonical_json(val).unwrap_or_default()
307}
308
309fn normalize_vector_node(node: &BaldwinVectorNode) -> Result<(String, BaldwinVectorNode), BaldwinVectorOutcomeErr> {
310 let candidates: Vec<String> = [&node.id, &node.pcard_id, &node.name]
311 .into_iter().flatten().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
312 if candidates.is_empty() { return Err(baldwin_err("AMBIGUOUS_IDENTIFIER", "Missing node identifier")); }
313 let unique: std::collections::BTreeSet<String> = candidates.iter().cloned().collect();
314 if unique.len() > 1 { return Err(baldwin_err("AMBIGUOUS_IDENTIFIER", "Conflicting identifier aliases")); }
315 let cid = candidates[0].clone();
316 Ok((cid.clone(), BaldwinVectorNode {
317 id: Some(cid), pcard_id: None, name: None,
318 pcard_type: node.pcard_type.clone(), signature: node.signature.clone(),
319 source_uri: node.source_uri.clone(), coeffects: node.coeffects.clone(),
320 }))
321}
322
323pub fn evaluate_baldwin_vector(spec: &Value) -> Result<BaldwinVectorOutcomeOk, BaldwinVectorOutcomeErr> {
326 let op = spec.get("operator").and_then(|v| v.as_str()).unwrap_or("");
327 if !matches!(op, "split" | "substitute" | "augment" | "exclude" | "invert" | "port") {
328 return Err(baldwin_err("UNKNOWN_OPERATOR", format!("Unknown operator: {}", op)));
329 }
330 let target = spec.get("target").and_then(|v| v.as_str()).unwrap_or("").to_string();
331 let initial_arr = spec.get("initial_state").and_then(|v| v.as_array()).cloned().unwrap_or_default();
332 let mut index_by_id: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
333 let mut current: Vec<BaldwinVectorNode> = Vec::with_capacity(initial_arr.len());
334 for (idx, raw_val) in initial_arr.iter().enumerate() {
335 let parsed: BaldwinVectorNode = serde_json::from_value(raw_val.clone())
336 .map_err(|e| baldwin_err("AMBIGUOUS_IDENTIFIER", e.to_string()))?;
337 let (cid, norm) = normalize_vector_node(&parsed)?;
338 index_by_id.insert(cid, idx);
339 current.push(norm);
340 }
341
342 let parse_operand = || -> Result<(String, BaldwinVectorNode), BaldwinVectorOutcomeErr> {
343 let op_val = spec.get("operand").ok_or_else(|| baldwin_err("MISSING_SUBJECT", "Missing operand"))?;
344 let parsed: BaldwinVectorNode = serde_json::from_value(op_val.clone())
345 .map_err(|e| baldwin_err("AMBIGUOUS_IDENTIFIER", e.to_string()))?;
346 normalize_vector_node(&parsed)
347 };
348
349 let after: Vec<BaldwinVectorNode> = match op {
350 "split" => {
351 let (matched, mut rest): (Vec<_>, Vec<_>) = current
352 .iter().cloned()
353 .partition(|n| n.id.as_deref() == Some(target.as_str()) || target == "*");
354 if matched.is_empty() { current.clone() } else { rest.extend(matched); rest }
355 }
356 "substitute" => {
357 let &idx = index_by_id.get(&target).ok_or_else(|| baldwin_err("MISSING_SUBJECT", "Target not found"))?;
358 let (_, norm_op) = parse_operand()?;
359 let orig = ¤t[idx];
360 if orig.pcard_type == "dynamic" && norm_op.pcard_type == "dynamic" && orig.signature != norm_op.signature {
361 return Err(baldwin_err("COVARIANCE_VIOLATION", "Signature mismatch"));
362 }
363 let mut next = current.clone();
364 next[idx] = norm_op;
365 next
366 }
367 "augment" => {
368 let (op_id, norm_op) = parse_operand()?;
369 if index_by_id.contains_key(&op_id) {
370 return Err(baldwin_err("DUPLICATE_SUBJECT", "PCard already exists"));
371 }
372 let mut next = current.clone();
373 next.push(norm_op);
374 next
375 }
376 "exclude" => {
377 if !index_by_id.contains_key(&target) {
378 return Err(baldwin_err("MISSING_SUBJECT", "Target not found"));
379 }
380 current.iter().filter(|n| n.id.as_deref() != Some(target.as_str())).cloned().collect()
381 }
382 "invert" => {
383 let &idx = index_by_id.get(&target).ok_or_else(|| baldwin_err("MISSING_SUBJECT", "Target not found"))?;
384 let svc = spec.get("operand").and_then(|v| v.as_str()).unwrap_or("");
385 let mut inverted = current[idx].clone();
386 inverted.coeffects.required_services.retain(|s| s.as_str() != svc);
387 let mut next = current.clone();
388 next[idx] = inverted;
389 next
390 }
391 _ => {
392 let &idx = index_by_id.get(&target).ok_or_else(|| baldwin_err("MISSING_SUBJECT", "Target not found"))?;
393 let dest = spec.get("operand").and_then(|v| v.as_str()).unwrap_or("").trim();
394 let orig = ¤t[idx];
395 if dest.is_empty() || orig.source_uri.starts_with(&format!("{}/", dest)) {
396 return Err(baldwin_err("CYCLIC_PORT", "Invalid or cyclic destination layer"));
397 }
398 let mut ported = orig.clone();
399 if ported.pcard_type == "dynamic" {
400 ported.source_uri = format!("{}/{}", dest, orig.source_uri);
401 }
402 let mut next = current.clone();
403 next.push(ported);
404 next
405 }
406 };
407
408 let author = spec.get("author").and_then(|v| v.as_str()).unwrap_or(crate::layer0::vocabulary_identities::DID_CLM_AGENT_BALDWIN);
409 let timestamp = spec.get("timestamp").and_then(|v| v.as_i64()).unwrap_or(1_700_000_000_000);
410 let after_canonical_json = canonical_json_value(&serde_json::to_value(&after).unwrap_or_default());
411 let after_hash = format!("{HASH_PREFIX_BLAKE3}{}", crate::layer0::hash::compute_blake3(after_canonical_json.as_bytes()));
412 let witness_val = serde_json::json!({
413 "afterCount": after.len(), "author": author, "beforeCount": current.len(),
414 "operator": op, "target": target, "timestamp": timestamp, "type": "baldwin_witness",
415 });
416 let witness_canonical_json = canonical_json_value(&witness_val);
417 let witness_hash = format!("{HASH_PREFIX_BLAKE3}{}", crate::layer0::hash::compute_blake3(witness_canonical_json.as_bytes()));
418
419 Ok(BaldwinVectorOutcomeOk {
420 operator: op.to_string(), target, after, after_canonical_json, after_hash,
421 witness_canonical_json, witness_hash,
422 })
423}
424
425#[cfg(test)]
426mod canonical_parity_tests {
427 use super::canonical_json_value;
428 use crate::layer0::codec::{canonical_json, canonical_parity_corpus};
429
430 #[test]
431 fn baldwin_matches_layer0() {
432 for value in canonical_parity_corpus() {
433 assert_eq!(canonical_json_value(&value), canonical_json(&value).unwrap(), "divergence at {value}");
434 }
435 }
436}