clm-kernel 0.0.3

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
use serde_json::{Value, Serializer};
use serde_json::ser::PrettyFormatter;
use std::fs;
use std::path::Path;
use crate::db;
use crate::hash::prefixed;
use crate::utils::indent_lines;

pub fn split(clm_file: &str, clm_root: &str) -> Result<String, String> {
    // 1. Read CLM file
    let path = Path::new(clm_file);
    if !path.exists() {
        return Err(format!("File not found: {}", clm_file));
    }
    let yaml_content = fs::read_to_string(path)
        .map_err(|e| format!("Failed to read CLM file: {}", e))?;
    
    // Parse YAML using serde_yaml to preserve insertion order (via Value)
    let mut clm_val: Value = serde_yaml::from_str(&yaml_content)
        .map_err(|e| format!("Failed to parse CLM YAML: {}", e))?;
    
    let clm = clm_val.get_mut("clm")
        .ok_or_else(|| "Not a valid CLM file (missing 'clm:' root)".to_string())?;

    // Get clm_name
    let clm_name = clm.get("concrete_impl")
        .and_then(|c| c.get("operation"))
        .and_then(|o| o.as_str())
        .map(|s| s.to_string())
        .unwrap_or_else(|| {
            path.file_stem()
                .map(|s| s.to_string_lossy().to_string())
                .unwrap_or_else(|| "unknown".to_string())
        });

    let g_time = crate::fs_utils::compute_g_time();
    let output_dir = crate::fs_utils::get_data_dir(clm_root, "content_memory");
    let _ = fs::create_dir_all(&output_dir);

    // -- 1. Extract A-MCard (abstract_spec) --
    let abstract_spec = clm.get("abstract_spec")
        .ok_or_else(|| "CLM has no abstract_spec section".to_string())?
        .clone();
    
    let a_content_json = to_string_pretty_2_spaces(&abstract_spec)?;
    let a_hash = sha256_hash_string(&a_content_json);

    let a_file = output_dir.join(format!("a_{}.yaml", &a_hash[..12]));
    let a_yaml_str = serde_yaml::to_string(&abstract_spec)
        .map_err(|e| format!("Failed to serialize abstract_spec: {}", e))?;
    let a_mcard_content = format!(
        "mcard:\n  hash: \"{}\"\n  g_time: \"{}\"\n  facet: \"abstract_spec\"\n  content_hash: \"{}\"\n  content:\n{}",
        prefixed(&a_hash), g_time, a_hash, indent_lines(&a_yaml_str, 4)
    );
    fs::write(&a_file, &a_mcard_content)
        .map_err(|e| format!("Failed to write A-MCard: {}", e))?;
    eprintln!("[DECOMPOSE] ✅ A-MCard: {}", a_file.to_string_lossy());
    eprintln!("[DECOMPOSE]   hash: {}", a_hash);

    // -- 2. Extract C-MCard (concrete_impl) --
    let mut concrete_impl = clm.get("concrete_impl")
        .ok_or_else(|| "CLM has no concrete_impl section".to_string())?
        .clone();
    
    // Strip gate-binding metadata: .precondition.vcard_pre, .postcondition.vcard_post
    if let Some(obj) = concrete_impl.as_object_mut() {
        if let Some(pre) = obj.get_mut("precondition")
            && let Some(pre_obj) = pre.as_object_mut() {
                pre_obj.remove("vcard_pre");
            }
        if let Some(post) = obj.get_mut("postcondition")
            && let Some(post_obj) = post.as_object_mut() {
                post_obj.remove("vcard_post");
            }
        // Inject a_hash
        obj.insert("a_hash".to_string(), Value::String(prefixed(&a_hash)));
    }

    let c_content_json = to_string_pretty_2_spaces(&concrete_impl)?;
    let c_hash = sha256_hash_string(&c_content_json);

    let c_original_yaml_str = serde_yaml::to_string(&clm.get("concrete_impl").unwrap())
        .map_err(|e| format!("Failed to serialize original concrete_impl: {}", e))?;
    
    let c_file = output_dir.join(format!("c_{}.yaml", &c_hash[..12]));
    let c_mcard_content = format!(
        "mcard:\n  hash: \"{}\"\n  g_time: \"{}\"\n  facet: \"concrete_impl\"\n  content_hash: \"{}\"\n  content:\n    a_hash: \"{}\"\n{}",
        prefixed(&c_hash), g_time, c_hash, prefixed(&a_hash), indent_lines(&c_original_yaml_str, 4)
    );
    fs::write(&c_file, &c_mcard_content)
        .map_err(|e| format!("Failed to write C-MCard: {}", e))?;
    eprintln!("[DECOMPOSE] ✅ C-MCard: {}", c_file.to_string_lossy());
    eprintln!("[DECOMPOSE]   hash: {}", c_hash);
    eprintln!("[DECOMPOSE]   a_hash: {}", a_hash);

    // -- 3. Extract B-MCard (balanced_exp) --
    let has_balanced = clm.get("balanced_exp").is_some();
    let mut b_mcard_content_opt = None;
    let b_hash = if has_balanced {
        let mut balanced_exp = clm.get("balanced_exp").unwrap().clone();
        if let Some(obj) = balanced_exp.as_object_mut() {
            obj.insert("c_hash".to_string(), Value::String(prefixed(&c_hash)));
        }
        let b_content_json = to_string_pretty_2_spaces(&balanced_exp)?;
        let b_hash_val = sha256_hash_string(&b_content_json);

        let b_file = output_dir.join(format!("b_{}.yaml", &b_hash_val[..12]));
        
        let expectation = clm.get("balanced_exp")
            .and_then(|b| b.get("expectation"))
            .and_then(|e| e.as_str())
            .unwrap_or("");
        
        let pending_cases = clm.get("balanced_exp")
            .and_then(|b| b.get("pending_cases"));

        let pending_cases_str = match pending_cases {
            Some(Value::Array(arr)) if !arr.is_empty() => {
                let y = serde_yaml::to_string(arr).unwrap_or_else(|_| "[]".to_string());
                format!("    pending_cases:\n{}", indent_lines(&y, 6))
            }
            _ => "    pending_cases: []".to_string(),
        };

        let b_mcard_content = format!(
            "mcard:\n  hash: \"{}\"\n  g_time: \"{}\"\n  facet: \"balanced_exp\"\n  content_hash: \"{}\"\n  content:\n    c_hash: \"{}\"\n    expectation: \"{}\"\n{}",
            prefixed(&b_hash_val), g_time, b_hash_val, prefixed(&c_hash), expectation, pending_cases_str
        );
        b_mcard_content_opt = Some(b_mcard_content.clone());
        fs::write(&b_file, &b_mcard_content)
            .map_err(|e| format!("Failed to write B-MCard: {}", e))?;
        eprintln!("[DECOMPOSE] ✅ B-MCard: {}", b_file.to_string_lossy());
        eprintln!("[DECOMPOSE]   hash: {}", b_hash_val);
        eprintln!("[DECOMPOSE]   c_hash: {}", c_hash);
        let pending_count = match pending_cases {
            Some(Value::Array(arr)) => arr.len(),
            _ => 0,
        };
        eprintln!("[DECOMPOSE]   pending_cases: {}", pending_count);

        b_hash_val
    } else {
        eprintln!("[DECOMPOSE] ⚠️  No balanced_exp section — B-MCard skipped");
        "none".to_string()
    };

    // -- 4. Compute Merkle Root Hash --
    let b_hash_for_root = if b_hash == "none" { "none" } else { &b_hash };
    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);
    let clm_root_hash = sha256_hash_string(&root_hash_input);

    // -- 5. Register CLM handles in Database --
    let db_pillar = "content_memory";
    let root_content = format!(
        "{{\"@type\":\"CLM_Root\",\"clm_name\":\"{}\",\"clm_root_hash\":\"{}\",\"a_hash\":\"{}\",\"c_hash\":\"{}\",\"b_hash\":\"{}\"}}",
        clm_name, prefixed(&clm_root_hash), prefixed(&a_hash), prefixed(&c_hash), prefixed(&b_hash)
    );

    let _ = db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}", clm_name), &clm_root_hash, &root_content);
    let _ = db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}:a", clm_name), &a_hash, "");
    let _ = db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}:c", clm_name), &c_hash, "");
    if b_hash != "none" {
        let _ = db::handle_register_batch(db_pillar, clm_root, &format!("clm:{}:b", clm_name), &b_hash, "");
    }

    // Register facet handles to match shell split behavior exactly
    let a_mcard_hash = sha256_hash_string(&a_mcard_content);
    let _ = db::handle_register_batch(db_pillar, clm_root, &format!("facet:a:{}", &a_hash[..12]), &a_mcard_hash, &a_mcard_content);

    let c_mcard_hash = sha256_hash_string(&c_mcard_content);
    let _ = db::handle_register_batch(db_pillar, clm_root, &format!("facet:c:{}", &c_hash[..12]), &c_mcard_hash, &c_mcard_content);

    if let Some(ref b_mcard_content) = b_mcard_content_opt {
        let b_mcard_hash = sha256_hash_string(b_mcard_content);
        let _ = db::handle_register_batch(db_pillar, clm_root, &format!("facet:b:{}", &b_hash[..12]), &b_mcard_hash, b_mcard_content);
    }
    eprintln!("[DECOMPOSE] 🔗 Registered handles: clm:{} → {}", clm_name, prefixed(&clm_root_hash));

    // -- 6. Print composite reference exactly like decompose_clm --
    let mut out = String::new();
    out.push_str("\n######################################################\n");
    out.push_str("  Cubical Decomposition Complete\n");
    out.push_str("######################################################\n");
    out.push_str("clm:\n");
    out.push_str(&format!("  clm_root_hash: \"{}\"\n", prefixed(&clm_root_hash)));
    out.push_str(&format!("  clm_name: \"{}\"\n", clm_name));
    out.push_str(&format!("  a_hash: \"{}\"\n", prefixed(&a_hash)));
    out.push_str(&format!("  c_hash: \"{}\"\n", prefixed(&c_hash)));
    if b_hash != "none" {
        out.push_str(&format!("  b_hash: \"{}\"\n", prefixed(&b_hash)));
    }
    out.push('\n');
    out.push_str(&format!("# Chain: A({}) ← C({}) ← B({})\n", a_hash, c_hash, b_hash_for_root));
    out.push_str(&format!("# Root:  {} = H(a:c:b)\n", clm_root_hash));

    Ok(out)
}

pub fn merge(a_file: &str, c_file: &str, b_file: Option<&str>) -> Result<String, String> {
    // 1. Read A-MCard
    let a_path = Path::new(a_file);
    if !a_path.exists() {
        return Err(format!("File not found: {}", a_file));
    }
    let a_content = fs::read_to_string(a_path)
        .map_err(|e| format!("Failed to read A-MCard file: {}", e))?;
    let a_mcard: Value = serde_yaml::from_str(&a_content)
        .map_err(|e| format!("Failed to parse A-MCard YAML: {}", e))?;
    let abstract_spec = a_mcard.get("mcard")
        .and_then(|m| m.get("content"))
        .ok_or_else(|| "Missing 'mcard.content' in A-MCard".to_string())?;

    // 2. Read C-MCard
    let c_path = Path::new(c_file);
    if !c_path.exists() {
        return Err(format!("File not found: {}", c_file));
    }
    let c_content = fs::read_to_string(c_path)
        .map_err(|e| format!("Failed to read C-MCard file: {}", e))?;
    let c_mcard: Value = serde_yaml::from_str(&c_content)
        .map_err(|e| format!("Failed to parse C-MCard YAML: {}", e))?;
    let concrete_impl_val = c_mcard.get("mcard")
        .and_then(|m| m.get("content"))
        .ok_or_else(|| "Missing 'mcard.content' in C-MCard".to_string())?;
    
    // Strip a_hash from concrete_impl
    let mut concrete_impl = concrete_impl_val.clone();
    if let Some(obj) = concrete_impl.as_object_mut() {
        obj.remove("a_hash");
    }

    // 3. Read B-MCard (optional)
    let mut balanced_exp = None;
    if let Some(bf) = b_file {
        let b_path = Path::new(bf);
        if b_path.exists() {
            let b_content = fs::read_to_string(b_path)
                .map_err(|e| format!("Failed to read B-MCard file: {}", e))?;
            let b_mcard: Value = serde_yaml::from_str(&b_content)
                .map_err(|e| format!("Failed to parse B-MCard YAML: {}", e))?;
            let balanced_exp_val = b_mcard.get("mcard")
                .and_then(|m| m.get("content"))
                .ok_or_else(|| "Missing 'mcard.content' in B-MCard".to_string())?;
            
            // Strip c_hash from balanced_exp
            let mut b_val = balanced_exp_val.clone();
            if let Some(obj) = b_val.as_object_mut() {
                obj.remove("c_hash");
            }
            balanced_exp = Some(b_val);
        }
    }

    // Reconstruct CLM
    let mut clm_map = serde_json::Map::new();
    clm_map.insert("abstract_spec".to_string(), abstract_spec.clone());
    clm_map.insert("concrete_impl".to_string(), concrete_impl);
    if let Some(b_val) = balanced_exp {
        clm_map.insert("balanced_exp".to_string(), b_val);
    }
    
    let mut root_map = serde_json::Map::new();
    root_map.insert("clm".to_string(), Value::Object(clm_map));

    let root_val = Value::Object(root_map);
    serde_yaml::to_string(&root_val)
        .map_err(|e| format!("Failed to serialize reconstructed CLM: {}", e))
}

pub fn to_string_pretty_2_spaces<T: serde::Serialize>(value: &T) -> Result<String, String> {
    let mut buf = Vec::new();
    let formatter = PrettyFormatter::with_indent(b"  ");
    let mut ser = Serializer::with_formatter(&mut buf, formatter);
    value.serialize(&mut ser)
        .map_err(|e| format!("Failed to serialize pretty JSON: {}", e))?;
    Ok(String::from_utf8(buf).unwrap())
}

pub fn sha256_hash_string(s: &str) -> String {
    crate::hash::raw_hash_string(s)
}



#[allow(dead_code)]
pub fn substitute(clm_file: &str, new_impl_file_or_op: &str, clm_root: &str) -> Result<String, String> {
    let path = Path::new(clm_file);
    if !path.exists() {
        return Err(format!("File not found: {}", clm_file));
    }
    let yaml_content = fs::read_to_string(path)
        .map_err(|e| format!("Failed to read CLM file: {}", e))?;
    let mut clm_val: Value = serde_yaml::from_str(&yaml_content)
        .map_err(|e| format!("Failed to parse CLM YAML: {}", e))?;
    let clm = clm_val.get_mut("clm")
        .ok_or_else(|| "Not a valid CLM file (missing 'clm:' root)".to_string())?;

    let abstract_spec = clm.get("abstract_spec")
        .ok_or_else(|| "CLM has no abstract_spec section".to_string())?
        .clone();

    let new_c_spec: Value = if Path::new(new_impl_file_or_op).exists() {
        let c_content = fs::read_to_string(new_impl_file_or_op)
            .map_err(|e| format!("Failed to read new implementation file: {}", e))?;
        let parsed: Value = serde_yaml::from_str(&c_content)
            .map_err(|e| format!("Failed to parse new implementation YAML: {}", e))?;
        if let Some(c) = parsed.get("clm").and_then(|c| c.get("concrete_impl")) {
            c.clone()
        } else if parsed.get("concrete_impl").is_some() {
            parsed.get("concrete_impl").unwrap().clone()
        } else {
            parsed
        }
    } else {
        serde_json::json!({
            "runtime": "system",
            "operation": new_impl_file_or_op,
            "inputs": Vec::<String>::new(),
            "outputs": Vec::<String>::new(),
            "process": {
                "script_handle": format!("script:{}", new_impl_file_or_op)
            }
        })
    };

    let a_content_json = to_string_pretty_2_spaces(&abstract_spec)?;
    let a_hash = sha256_hash_string(&a_content_json);

    let mut concrete_impl = new_c_spec.clone();
    if let Some(obj) = concrete_impl.as_object_mut() {
        obj.insert("a_hash".to_string(), Value::String(prefixed(&a_hash)));
        if let Some(pre) = obj.get_mut("precondition")
            && let Some(pre_obj) = pre.as_object_mut() {
                pre_obj.remove("vcard_pre");
            }
        if let Some(post) = obj.get_mut("postcondition")
            && let Some(post_obj) = post.as_object_mut() {
                post_obj.remove("vcard_post");
            }
    }

    let c_content_json = to_string_pretty_2_spaces(&concrete_impl)?;
    let c_hash = sha256_hash_string(&c_content_json);

    let b_spec = clm.get("balanced_exp").cloned();
    let expectation = b_spec.as_ref()
        .and_then(|b| b.get("expectation"))
        .and_then(|e| e.as_str())
        .unwrap_or("Substituted implementation pending verification");
    let pending_cases = b_spec.as_ref()
        .and_then(|b| b.get("pending_cases"))
        .cloned()
        .unwrap_or(Value::Array(Vec::new()));

    let mut new_clm = serde_json::Map::new();
    new_clm.insert("abstract_spec".to_string(), abstract_spec);
    new_clm.insert("concrete_impl".to_string(), concrete_impl);
    
    let mut new_b = serde_json::Map::new();
    new_b.insert("expectation".to_string(), Value::String(expectation.to_string()));
    new_b.insert("pending_cases".to_string(), pending_cases);
    new_clm.insert("balanced_exp".to_string(), Value::Object(new_b));

    let mut new_root = serde_json::Map::new();
    new_root.insert("clm".to_string(), Value::Object(new_clm));

    let new_yaml = serde_yaml::to_string(&Value::Object(new_root))
        .map_err(|e| format!("Failed to serialize substituted CLM: {}", e))?;

    let output_dir = crate::fs_utils::get_data_dir(clm_root, "content_memory");
    let _ = fs::create_dir_all(&output_dir);
    let sub_file = output_dir.join(format!("substituted_{}.yaml", &c_hash[..12]));
    fs::write(&sub_file, &new_yaml)
        .map_err(|e| format!("Failed to write substituted file: {}", e))?;

    // Register CLM handles in Database
    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);
    let clm_root_hash = sha256_hash_string(&root_hash_input);
    let root_content = format!(
        "{{\"@type\":\"CLM_Root\",\"clm_name\":\"substituted_{}\",\"clm_root_hash\":\"{}\",\"a_hash\":\"{}\",\"c_hash\":\"{}\",\"b_hash\":\"none\"}}",
        &c_hash[..12], prefixed(&clm_root_hash), prefixed(&a_hash), prefixed(&c_hash)
    );

    let _ = db::handle_register_batch("content_memory", clm_root, &format!("clm:substituted_{}", &c_hash[..12]), &clm_root_hash, &root_content);

    Ok(sub_file.to_string_lossy().to_string())
}

#[allow(dead_code)]
pub fn augment(clm_file: &str, aug_source: &str, clm_root: &str) -> Result<String, String> {
    let path = Path::new(clm_file);
    if !path.exists() {
        return Err(format!("File not found: {}", clm_file));
    }
    let yaml_content = fs::read_to_string(path)
        .map_err(|e| format!("Failed to read CLM file: {}", e))?;
    let mut clm_val: Value = serde_yaml::from_str(&yaml_content)
        .map_err(|e| format!("Failed to parse CLM YAML: {}", e))?;
    
    let clm = clm_val.get_mut("clm")
        .ok_or_else(|| "Not a valid CLM file (missing 'clm:' root)".to_string())?;

    let aug_content = if Path::new(aug_source).exists() {
        fs::read_to_string(aug_source)
            .map_err(|e| format!("Failed to read augmentation file: {}", e))?
    } else {
        aug_source.to_string()
    };

    let aug_val: Value = serde_yaml::from_str(&aug_content)
        .map_err(|e| format!("Failed to parse augmentation YAML: {}", e))?;

    if let Some(pre) = aug_val.get("precondition").or_else(|| aug_val.get("vcard_pre")) {
        if let Some(concrete_impl) = clm.get_mut("concrete_impl")
            && let Some(obj) = concrete_impl.as_object_mut() {
                obj.insert("precondition".to_string(), pre.clone());
            }
        if let Some(abstract_spec) = clm.get_mut("abstract_spec")
            && let Some(obj) = abstract_spec.as_object_mut() {
                let invariants = obj.entry("invariants".to_string())
                    .or_insert_with(|| serde_json::json!({
                        "preconditions": Vec::<String>::new(),
                        "postconditions": Vec::<String>::new()
                    }));
                if let Some(inv_obj) = invariants.as_object_mut() {
                    let pre_list = inv_obj.entry("preconditions".to_string())
                        .or_insert_with(|| Value::Array(Vec::new()));
                    if let Some(arr) = pre_list.as_array_mut() {
                        if let Some(new_arr) = pre.as_array() {
                            arr.extend(new_arr.clone());
                        } else {
                            if !arr.contains(pre) {
                                arr.push(pre.clone());
                            }
                        }
                    }
                }
            }
    } else if let Some(post) = aug_val.get("postcondition").or_else(|| aug_val.get("vcard_post")) {
        if let Some(concrete_impl) = clm.get_mut("concrete_impl")
            && let Some(obj) = concrete_impl.as_object_mut() {
                obj.insert("postcondition".to_string(), post.clone());
            }
        if let Some(abstract_spec) = clm.get_mut("abstract_spec")
            && let Some(obj) = abstract_spec.as_object_mut() {
                let invariants = obj.entry("invariants".to_string())
                    .or_insert_with(|| serde_json::json!({
                        "preconditions": Vec::<String>::new(),
                        "postconditions": Vec::<String>::new()
                    }));
                if let Some(inv_obj) = invariants.as_object_mut() {
                    let post_list = inv_obj.entry("postconditions".to_string())
                        .or_insert_with(|| Value::Array(Vec::new()));
                    if let Some(arr) = post_list.as_array_mut() {
                        if let Some(new_arr) = post.as_array() {
                            arr.extend(new_arr.clone());
                        } else {
                            if !arr.contains(post) {
                                arr.push(post.clone());
                            }
                        }
                    }
                }
            }
    }
 else if let Some(pending) = aug_val.get("pending_cases") {
        if let Some(balanced_exp) = clm.get_mut("balanced_exp")
            && let Some(obj) = balanced_exp.as_object_mut() {
                let existing = obj.entry("pending_cases".to_string())
                    .or_insert(Value::Array(Vec::new()));
                if let Some(arr) = existing.as_array_mut() {
                    if let Some(new_arr) = pending.as_array() {
                        arr.extend(new_arr.clone());
                    } else {
                        arr.push(pending.clone());
                    }
                }
            }
    } else if let Some(criteria) = aug_val.get("success_criteria") {
        if let Some(abstract_spec) = clm.get_mut("abstract_spec")
            && let Some(obj) = abstract_spec.as_object_mut() {
                let existing = obj.entry("success_criteria".to_string())
                    .or_insert(Value::Array(Vec::new()));
                if let Some(arr) = existing.as_array_mut() {
                    if let Some(new_arr) = criteria.as_array() {
                        arr.extend(new_arr.clone());
                    } else {
                        arr.push(criteria.clone());
                    }
                }
            }
    } else {
        if let Some(obj) = clm.as_object_mut()
            && let Some(aug_obj) = aug_val.as_object() {
                for (k, v) in aug_obj {
                    obj.insert(k.clone(), v.clone());
                }
            }
    }

    let aug_hash = sha256_hash_string(&aug_content);
    let output_dir = crate::fs_utils::get_data_dir(clm_root, "content_memory");
    let _ = fs::create_dir_all(&output_dir);
    let aug_file = output_dir.join(format!("augmented_{}.yaml", &aug_hash[..12]));

    let new_yaml = serde_yaml::to_string(&clm_val)
        .map_err(|e| format!("Failed to serialize augmented CLM: {}", e))?;
    fs::write(&aug_file, &new_yaml)
        .map_err(|e| format!("Failed to write augmented file: {}", e))?;

    // Register CLM handles in Database
    let root_content = format!(
        "{{\"@type\":\"CLM_Root\",\"clm_name\":\"augmented_{}\",\"clm_root_hash\":\"{}\",\"a_hash\":\"none\",\"c_hash\":\"none\",\"b_hash\":\"none\"}}",
        &aug_hash[..12], prefixed(&aug_hash)
    );
    let _ = db::handle_register_batch("content_memory", clm_root, &format!("clm:augmented_{}", &aug_hash[..12]), &aug_hash, &root_content);

    Ok(aug_file.to_string_lossy().to_string())
}

// ── Sprint 167: Dynamic Baldwin Modularity & Fiber HMR ──────────────────────

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct SubsumptionReport {
    pub fiber_id: String,
    pub old_hash: String,
    pub new_hash: String,
    pub pre_subsumed: bool,
    pub post_subsumed: bool,
    pub subsumption_valid: bool,
    pub witness: String,
}

/// Helper to extract invariant sets from CLM AST
pub fn extract_invariants(val: &Value, field: &str) -> std::collections::HashSet<String> {
    let mut set = std::collections::HashSet::new();
    let root = if let Some(clm) = val.get("clm") { clm } else { val };

    if let Some(arr) = root.get("abstract_spec")
        .and_then(|a| a.get("invariants"))
        .and_then(|inv| inv.get(field))
        .and_then(|f| f.as_array())
    {
        for item in arr {
            if let Some(s) = item.as_str() {
                set.insert(s.to_string());
            }
        }
    }
    if let Some(arr) = root.get("invariants")
        .and_then(|inv| inv.get(field))
        .and_then(|f| f.as_array())
    {
        for item in arr {
            if let Some(s) = item.as_str() {
                set.insert(s.to_string());
            }
        }
    }
    set
}

/// Verifies the Type Lattice Subsumption Criterion:
/// Subsumes(F_new, F_old) <=> (V_pre^new <= V_pre^old) AND (V_post^new >= V_post^old)
pub fn verify_subsumption(old_ast: &Value, new_ast: &Value) -> Result<SubsumptionReport, String> {
    let old_pre = extract_invariants(old_ast, "preconditions");
    let new_pre = extract_invariants(new_ast, "preconditions");
    let old_post = extract_invariants(old_ast, "postconditions");
    let new_post = extract_invariants(new_ast, "postconditions");

    // Precondition Contravariance: V_pre^new <= V_pre^old
    // new_pre must be a subset of old_pre (new cannot require MORE than old).
    let pre_subsumed = new_pre.is_subset(&old_pre);

    // Postcondition Covariance: V_post^new >= V_post^old
    // old_post must be a subset of new_post (new must guarantee AT LEAST what old guaranteed).
    let post_subsumed = old_post.is_subset(&new_post);

    let subsumption_valid = pre_subsumed && post_subsumed;

    let witness = format!(
        "Pre-subsumption: {} (old_pre={:?}, new_pre={:?}); Post-subsumption: {} (old_post={:?}, new_post={:?})",
        pre_subsumed, old_pre, new_pre, post_subsumed, old_post, new_post
    );

    let report = SubsumptionReport {
        fiber_id: String::new(),
        old_hash: String::new(),
        new_hash: String::new(),
        pre_subsumed,
        post_subsumed,
        subsumption_valid,
        witness,
    };

    if subsumption_valid {
        Ok(report)
    } else {
        Err(format!("Subsumption check failed: {}", report.witness))
    }
}

/// Dynamic Baldwin Operator: Substitute (=) via Hot Module Replacement (HMR)
/// Replaces an active PCard fiber with a new implementation without dropping tokens.
pub fn substitute_fiber(
    ctx: &crate::fiber::Context,
    fiber_id: &str,
    new_clm_file: &str,
    clm_root: &str,
) -> Result<SubsumptionReport, String> {
    // 1. Locate existing fiber in active context
    let old_fiber = ctx.get_fiber(fiber_id)
        .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;

    // 2. Read new implementation file
    let path = Path::new(new_clm_file);
    let resolved_path = if path.is_absolute() {
        path.to_path_buf()
    } else {
        Path::new(clm_root).join(new_clm_file)
    };
    if !resolved_path.exists() {
        return Err(format!("New CLM file not found: {}", resolved_path.display()));
    }
    let yaml_content = fs::read_to_string(&resolved_path)
        .map_err(|e| format!("Failed to read new CLM file: {}", e))?;

    let new_ast: Value = serde_yaml::from_str(&yaml_content)
        .map_err(|e| format!("Failed to parse new CLM YAML: {}", e))?;
    let new_json_str = serde_json::to_string(&new_ast).unwrap_or_default();
    let new_hash = sha256_hash_string(&new_json_str);

    // 3. Verify Type Lattice Subsumption against old fiber's AST
    let old_ast = old_fiber.get_ast().unwrap_or(Value::Null);
    let old_json_str = serde_json::to_string(&old_ast).unwrap_or_default();
    let old_hash = sha256_hash_string(&old_json_str);

    let mut report = verify_subsumption(&old_ast, &new_ast)?;
    report.fiber_id = fiber_id.to_string();
    report.old_hash = old_hash;
    report.new_hash = new_hash;

    // 4. Homotopy Lifting Property: pause old fiber & unwind disposables
    old_fiber.pause()?;
    let _ = old_fiber.unwind_disposables();

    // 5. Mount replacement fiber in Active state
    ctx.remove_fiber(fiber_id);
    let new_fiber = ctx.create_fiber(fiber_id, vec![])?;
    new_fiber.set_ast(new_ast);
    new_fiber.activate()?;

    Ok(report)
}

/// Dynamic Baldwin Operator: Split (//)
/// Splits an active fiber into an isolated sub-context sandbox.
pub fn split_fiber(
    ctx: &crate::fiber::Context,
    fiber_id: &str,
    allowed_coeffects: &[&str],
) -> Result<std::sync::Arc<crate::fiber::Fiber>, String> {
    let child_ctx = ctx.isolate(allowed_coeffects);
    let child_id = format!("{}_split", fiber_id);
    let child_fiber = child_ctx.create_fiber(&child_id, vec![])?;
    child_fiber.activate()?;
    Ok(child_fiber)
}

/// Dynamic Baldwin Operator: Augment (+)
/// Injects a new coeffect capability to satisfy pending fiber requirements.
pub fn augment_fiber(
    ctx: &crate::fiber::Context,
    fiber_id: &str,
    coeffect: &str,
) -> Result<(), String> {
    let fiber = ctx.get_fiber(fiber_id)
        .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
    ctx.provide(coeffect, format!("CoeffectInstance:{}", coeffect));
    fiber.satisfy_coeffect(coeffect);
    Ok(())
}

/// Dynamic Baldwin Operator: Exclude (-)
/// Quarantines and cleanly disposes an active fiber, releasing all its resources.
pub fn exclude_fiber(
    ctx: &crate::fiber::Context,
    fiber_id: &str,
) -> Result<(), String> {
    let fiber = ctx.get_fiber(fiber_id)
        .ok_or_else(|| format!("Fiber '{}' not found in active context", fiber_id))?;
    let _ = fiber.dispose();
    ctx.remove_fiber(fiber_id);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_subsumption_verification_soundness() {
        let old_ast = serde_json::json!({
            "abstract_spec": {
                "invariants": {
                    "preconditions": ["pre_a", "pre_b"],
                    "postconditions": ["post_x"]
                }
            }
        });

        // Valid replacement: weaker precondition (pre_a only) and stronger postcondition (post_x, post_y)
        let compliant_new_ast = serde_json::json!({
            "abstract_spec": {
                "invariants": {
                    "preconditions": ["pre_a"],
                    "postconditions": ["post_x", "post_y"]
                }
            }
        });

        let res = verify_subsumption(&old_ast, &compliant_new_ast);
        assert!(res.is_ok());
        let report = res.unwrap();
        assert!(report.pre_subsumed);
        assert!(report.post_subsumed);
        assert!(report.subsumption_valid);

        // Invalid replacement: stronger precondition (requires extra pre_c)
        let breaking_pre_ast = serde_json::json!({
            "abstract_spec": {
                "invariants": {
                    "preconditions": ["pre_a", "pre_c"],
                    "postconditions": ["post_x"]
                }
            }
        });
        assert!(verify_subsumption(&old_ast, &breaking_pre_ast).is_err());

        // Invalid replacement: weaker postcondition (missing post_x)
        let breaking_post_ast = serde_json::json!({
            "abstract_spec": {
                "invariants": {
                    "preconditions": ["pre_a"],
                    "postconditions": ["post_z"]
                }
            }
        });
        assert!(verify_subsumption(&old_ast, &breaking_post_ast).is_err());
    }

    #[test]
    fn test_dynamic_baldwin_fiber_lifecycle() {
        let ctx = crate::fiber::Context::root();
        let fiber = ctx.create_fiber("test_fiber", vec!["effect_1".to_string()]).unwrap();
        assert_eq!(fiber.get_state(), crate::fiber::FiberState::Pending);

        // Augment: satisfy effect_1
        augment_fiber(&ctx, "test_fiber", "effect_1").unwrap();
        assert_eq!(fiber.get_state(), crate::fiber::FiberState::Active);

        // Split: create child fiber in isolated context
        let split_res = split_fiber(&ctx, "test_fiber", &["effect_1"]);
        assert!(split_res.is_ok());

        // Exclude: cleanly terminate and remove
        exclude_fiber(&ctx, "test_fiber").unwrap();
        assert!(ctx.get_fiber("test_fiber").is_none());
    }
}