clm-kernel 0.0.4

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
// evaluator/dispatch/orchestrator.rs
// ─────────────────────────────────────────────────────────────
// Central CLM YAML → execution router.
//
// try_internal_dispatch parses a CLM YAML file, determines the
// execution strategy (native Rust, non-Rust runtime, fallback shell),
// and orchestrates pre/postcondition verification and VCard emission.
// ─────────────────────────────────────────────────────────────

use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use serde_json::Value;
use crate::fs_utils::compute_sha256_hex;
use super::{get_clm_args, get_internal_registry};
use super::runtime;

/// Emit a CLM_TRACE_JSON line to stdout when running in gateway mode (CLM_DISPATCH_SOCK set).
/// This allows the WebSocket gateway to stream real-time Petri Net trace events to clients.
fn emit_gateway_trace(transition: &str, phase: &str, exit_code: i32) {
    if env::var("CLM_DISPATCH_SOCK").is_ok() && env::var("CLM_NESTED_EXEC").is_err() {
        let trace = serde_json::json!({
            "type": "trace",
            "transition": transition,
            "phase": phase,
            "exit_code": exit_code,
            "agent": env::var("ACTIVE_AGENT_DID").unwrap_or_else(|_| "did:clm:bootstrap".to_string()),
        });
        println!("CLM_TRACE_JSON:{}", trace);
        use std::io::Write;
        std::io::stdout().flush().ok();
    }
}

pub(crate) fn try_internal_dispatch(
    clm_root: &Path,
    clm_file: &str,
    payload: Option<&str>,
    post_rc: Option<i32>,
    quiet: bool,
) -> Result<i32, String> {
    let root_ctx = crate::fiber::Context::root();
    try_internal_dispatch_with_context(&root_ctx, clm_root, clm_file, payload, post_rc, quiet)
}

pub(crate) fn try_internal_dispatch_with_context(
    ctx: &crate::fiber::Context,
    clm_root: &Path,
    clm_file: &str,
    payload: Option<&str>,
    post_rc: Option<i32>,
    quiet: bool,
) -> Result<i32, String> {
    let clm_path = if Path::new(clm_file).is_absolute() {
        PathBuf::from(clm_file)
    } else {
        clm_root.join(clm_file)
    };

    if !clm_path.exists() {
        return Err(format!("CLM file not found: {:?}", clm_path));
    }

    let content = fs::read_to_string(&clm_path)
        .map_err(|e| format!("Failed to read CLM file: {}", e))?;
    let data: serde_yaml::Value = match serde_yaml::from_str::<serde_yaml::Value>(&content) {
        Ok(d) => {
            // Check if this is actually a CLM with concrete_impl
            let cd = d.get("clm").unwrap_or(&d);
            if cd.get("concrete_impl").is_some() {
                d
            } else {
                // YAML parsed but no concrete_impl — might be XML or other format
                // that YAML mis-parsed as a plain string
                let normalized_path = crate::normalizer::normalize_syntax(
                    &clm_path.to_string_lossy(),
                    clm_root.to_str().unwrap_or(""),
                ).map_err(|_| "No concrete_impl — not an internal_reference CLM".to_string())?;
                let normalized_content = fs::read_to_string(&normalized_path)
                    .map_err(|e| format!("Failed to read normalized file: {}", e))?;
                serde_yaml::from_str(&normalized_content)
                    .map_err(|e| format!("Failed to parse normalized CLM YAML: {}", e))?
            }
        }
        Err(_) => {
            // Non-YAML file (JSONL, JSON, XML, TXT): normalize to YAML first
            let normalized_path = crate::normalizer::normalize_syntax(
                &clm_path.to_string_lossy(),
                clm_root.to_str().unwrap_or(""),
            ).map_err(|e| format!("Failed to parse CLM YAML: {} (normalization also failed: {})", "YAML parse error", e))?;
            let normalized_content = fs::read_to_string(&normalized_path)
                .map_err(|e| format!("Failed to read normalized file: {}", e))?;
            serde_yaml::from_str(&normalized_content)
                .map_err(|e| format!("Failed to parse normalized CLM YAML: {}", e))?
        }
    };

    let clm_data = data.get("clm").unwrap_or(&data);
    let concrete_impl = match clm_data.get("concrete_impl") {
        Some(val) => val,
        None => return Err("No concrete_impl — not an internal_reference CLM".to_string()),
    };

    let operation = concrete_impl.get("operation")
        .and_then(|v| v.as_str())
        .unwrap_or("");

    // Intercept internal gate CLMs that have no script body on disk.
    // These are handled directly by Rust code.
    if operation == "verify_precondition" {
        if !quiet {
            eprintln!("[clmEval-rs] ⚡ Native gate intercept: verify_precondition (zero-fork)");
        }
        match super::super::verify::verify_precondition_internal(clm_root, clm_file, quiet) {
            Ok(()) => return Ok(0),
            Err(e) => {
                eprintln!("[clmEval-rs] ❌ Pre-Gate Failed: {}", e);
                return Ok(1);
            }
        }
    }
    if operation == "validate_postcondition" {
        if !quiet {
            eprintln!("[clmEval-rs] ⚡ Native gate intercept: validate_postcondition (zero-fork)");
        }
        let rc = post_rc.unwrap_or(0);
        let content = format!("exit code: {}", rc);
        let content_hash = format!("sha256:{}", compute_sha256_hex(content.as_bytes()));
        
        let mut op = "unknown".to_string();
        let mut impl_hash = "unknown".to_string();
        if let Some(pay) = payload {
            let pay_path = if Path::new(pay).is_absolute() {
                PathBuf::from(pay)
            } else {
                clm_root.join(pay)
            };
            
            let resolved_pay_path = if pay_path.exists() {
                pay_path
            } else if pay.starts_with("clm/") {
                clm_root.join(&pay[4..])
            } else {
                pay_path
            };
            
            if resolved_pay_path.exists() {
                if let Ok(c) = fs::read_to_string(&resolved_pay_path)
                    && let Ok(yaml) = serde_yaml::from_str::<serde_yaml::Value>(&c) {
                        let inner = yaml.get("clm").unwrap_or(&yaml);
                        if let Some(concrete) = inner.get("concrete_impl")
                            && let Some(operation_val) = concrete.get("operation").and_then(|v| v.as_str()) {
                                op = operation_val.to_string();
                            }
                    }
                if let Ok(bytes) = fs::read(&resolved_pay_path) {
                    let normalized: Vec<u8> = bytes.into_iter().filter(|&b| b != b'\r').collect();
                    impl_hash = format!("sha256:{}", compute_sha256_hex(&normalized));
                }
            }
        }
        
        let a_hash = env::var("CLM_ACTIVE_A_HASH").unwrap_or_default();
        let c_hash = env::var("CLM_ACTIVE_C_HASH").unwrap_or_default();
        
        let extra_yaml = format!(
            "content: \"{}\"\noperation: \"{}\"\nimpl_hash: \"{}\"",
            content, op, impl_hash
        );
        
        match crate::db::emit_exec_mcard(
            "validate_postcondition",
            &content_hash,
            &extra_yaml,
            &a_hash,
            &c_hash,
            clm_root.to_str().unwrap_or(""),
        ) {
            Ok(exec_mcard_path) => {
                if !quiet {
                    eprintln!("[VCARD POST] ✅ Execution MCard generated: {}", exec_mcard_path);
                    eprintln!("[VCARD POST]   g_time: {}", crate::fs_utils::compute_g_time());
                    eprintln!("[VCARD POST]   content_hash: {}", content_hash);
                }
            }
            Err(e) => {
                eprintln!("[VCARD POST] ❌ Failed to generate execution MCard: {}", e);
                return Ok(1);
            }
        }
        
        return Ok(0);
    }

    if operation.starts_with("ci_validate_") {
        let content_type = concrete_impl.get("content_type");
        let mime = content_type
            .and_then(|ct| ct.get("mime"))
            .and_then(|m| m.as_str())
            .unwrap_or("");
        
        let payload_file = payload.ok_or_else(|| "No payload file specified for validation".to_string())?;
        
        if !quiet {
            eprintln!("[clmEval-rs] ⚡ Native validation intercept: {} for file {} (zero-fork)", operation, payload_file);
        }
        
        if let Err(e) = super::super::verify::verify_precondition_internal(clm_root, clm_file, quiet) {
            eprintln!("CRITICAL: Pre-Gate Failed: {}", e);
            return Ok(1);
        }

        let is_valid = crate::mime::validate(clm_root.to_str().unwrap_or(""), payload_file, Some(mime));
        let exit_code = if is_valid { 0 } else { 1 };

        let output = "";
        let clm_root_str = clm_root.to_str().unwrap_or("");
        
        if exit_code == 0 {
            let a_hash_str = clm_data.get("_meta").and_then(|m| m.get("a_hash")).and_then(|v| v.as_str())
                .map(|s| s.to_string())
                .unwrap_or_else(|| {
                    let spec = clm_data.get("abstract_spec").cloned().unwrap_or(serde_yaml::Value::Null);
                    let serialized = serde_yaml::to_string(&spec).unwrap_or_default();
                    format!("sha256:{}", compute_sha256_hex(serialized.replace('\r', "").as_bytes()))
                });
            
            let c_hash_str = clm_data.get("_meta").and_then(|m| m.get("c_hash")).and_then(|v| v.as_str())
                .map(|s| s.to_string())
                .unwrap_or_else(|| {
                    let spec = clm_data.get("concrete_impl").cloned().unwrap_or(serde_yaml::Value::Null);
                    let serialized = serde_yaml::to_string(&spec).unwrap_or_default();
                    format!("sha256:{}", compute_sha256_hex(serialized.replace('\r', "").as_bytes()))
                });

            let output_hash = format!("sha256:{}", compute_sha256_hex(output.as_bytes()));
            let extra_yaml = format!("content: |\n  {}", output.replace('\n', "\n  "));
            let _ = crate::db::emit_exec_mcard(
                operation,
                &output_hash,
                &extra_yaml,
                &a_hash_str,
                &c_hash_str,
                clm_root_str,
            );
        }
        
        return Ok(exit_code);
    }

    let runtime_str = concrete_impl.get("runtime")
        .and_then(|v| v.as_str())
        .unwrap_or("");

    let process = match concrete_impl.get("process") {
        Some(p) => p,
        None => return Err("No process block in concrete_impl".to_string()),
    };

    let process_type = process.get("type")
        .and_then(|v| v.as_str())
        .unwrap_or("");

    let is_rust = runtime_str == "rust" && process_type == "internal_reference";
    let is_non_rust_runtime = runtime_str == "python"
        || runtime_str == "node"
        || runtime_str == "javascript"
        || runtime_str == "shell"
        || runtime_str == "polyglot"
        || runtime_str == "system"
        || runtime_str == "go"
        || runtime_str == "llm"
        || runtime_str == "open_interpreter"
        || (runtime_str == "rust" && process_type == "rust")
        || (runtime_str == "rust" && !is_rust && process_type != "internal_reference")
        || process_type == "compose"
        || process_type == "polyglot"
        || runtime_str == "compose";

    if !is_rust && !is_non_rust_runtime {
        return Err(format!("runtime is '{}', not 'rust' — falling through to bash", runtime_str));
    }

    if is_rust
        && process_type != "internal_reference" {
            eprintln!("[DEBUG] process_type is '{}', not 'internal_reference'", process_type);
            return Err(format!("process.type is '{}', not 'internal_reference'", process_type));
        }

    let mut module_path_opt = None;
    let mut registered_func = None;

    if is_rust {
        let m_path = process.get("module")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                eprintln!("[DEBUG] No process.module specified");
                "No process.module specified for internal_reference".to_string()
            })?;
        module_path_opt = Some(m_path);
        registered_func = get_internal_registry(m_path);

        if !quiet {
            eprintln!("[clmEval-rs] ⚡ Internal dispatch: {} (zero-overhead)", m_path);
        }
    }

    if let Some(pay) = payload {
        crate::utils::set_env_var("CLM_PAYLOAD", pay);
    }

    let skip_conditions = env::var("CLM_SKIP_CONDITIONS").as_deref() == Ok("1");

    if !skip_conditions {
        emit_gateway_trace("verify_precondition", "pre", 0);
        match crate::evaluator::compose::compose_conditions(clm_root, clm_file, "pre", 0, quiet) {
            Ok(0) => {}
            Ok(rc) => {
                eprintln!("CRITICAL: Pre-Gate Failed.");
                return Ok(rc);
            }
            Err(e) => {
                eprintln!("CRITICAL: Pre-Gate Failed: {}", e);
                return Ok(1);
            }
        }
    }

    let clm_root_str = clm_root.to_str().unwrap_or("");
    let clm_file_str = clm_path.to_str().unwrap_or("");

    let mut a_mcard_opt = None;
    match crate::parser::parse_a_mcard(clm_file_str) {
        Ok(a) => {
            a_mcard_opt = Some(a);
        }
        Err(e) => {
            if !quiet {
                eprintln!("[clmEval-rs] ⚠️ Warning: Failed to parse A-MCard spec for validation: {}", e);
            }
        }
    }


    let mut context_val = serde_json::json!({
        "inputs": Value::Null,
        "outputs": Value::Null
    });

    if let Some(ref a_mcard) = a_mcard_opt {
        let concrete_args = get_clm_args(clm_file_str).unwrap_or_default();
        let mut inputs_map = serde_json::Map::new();

        let mut payload_parsed = false;
        if let Some(pay) = payload {
            let trimmed = pay.trim();
            if trimmed.starts_with('{') {
                if let Ok(Value::Object(obj)) = serde_json::from_str::<Value>(trimmed) {
                    for (k, v) in obj {
                        inputs_map.insert(k, v);
                    }
                    payload_parsed = true;
                }
            } else if trimmed.contains(':')
                && let Ok(data) = serde_yaml::from_str::<Value>(trimmed)
                    && let Value::Object(obj) = data {
                        for (k, v) in obj {
                            inputs_map.insert(k, v);
                        }
                        payload_parsed = true;
                    }
        }

        if !payload_parsed
            && let Some(pay) = payload
                && let Value::Object(ref sig_inputs) = a_mcard.signature.inputs
                    && sig_inputs.len() == 1 {
                        let first_key = sig_inputs.keys().next().unwrap();
                        if let Ok(num) = pay.parse::<i64>() {
                            inputs_map.insert(first_key.clone(), Value::from(num));
                        } else if let Ok(f) = pay.parse::<f64>() {
                            inputs_map.insert(first_key.clone(), Value::from(f));
                        } else if pay == "true" {
                            inputs_map.insert(first_key.clone(), Value::Bool(true));
                        } else if pay == "false" {
                            inputs_map.insert(first_key.clone(), Value::Bool(false));
                        } else {
                            inputs_map.insert(first_key.clone(), Value::String(pay.to_string()));
                        }
                    }

        if let Value::Object(ref sig_inputs) = a_mcard.signature.inputs {
            let keys: Vec<&String> = sig_inputs.keys().collect();
            for (i, key) in keys.iter().enumerate() {
                if !inputs_map.contains_key(*key)
                    && let Some(arg) = concrete_args.get(i) {
                        if let Ok(num) = arg.parse::<i64>() {
                            inputs_map.insert((*key).clone(), Value::from(num));
                        } else if let Ok(f) = arg.parse::<f64>() {
                            inputs_map.insert((*key).clone(), Value::from(f));
                        } else if arg == "true" {
                            inputs_map.insert((*key).clone(), Value::Bool(true));
                        } else if arg == "false" {
                            inputs_map.insert((*key).clone(), Value::Bool(false));
                        } else {
                            inputs_map.insert((*key).clone(), Value::String(arg.clone()));
                        }
                    }
            }
        }

        let inputs_val = Value::Object(inputs_map);
        if let Some(obj) = context_val.as_object_mut() {
            obj.insert("inputs".to_string(), inputs_val);
        }

        if !skip_conditions {
            for pre in &a_mcard.invariants.preconditions {
                match crate::invariants::evaluate_invariant(pre, clm_root_str, &context_val) {
                    Ok(true) => {
                        if !quiet {
                            eprintln!("[VCARD PRE] Invariant '{}' satisfied.", pre);
                        }
                    }
                    Ok(false) => {
                        eprintln!("[PREP_ERR] Precondition violation: Invariant '{}' failed.", pre);
                        return Ok(1);
                    }
                    Err(e) => {
                        eprintln!("[PREP_ERR] Precondition check error: Invariant '{}' raised error: {}", pre, e);
                        return Ok(1);
                    }
                }
            }
        }
    }

    let isolated_ctx = ctx.isolate(&["content_memory", "agent_identities", "execution_log"]);
    let fiber_id = format!("fiber_{}_{:x}", clm_file.replace(['/', '.'], "_"), rand::random::<u16>());
    let fiber = isolated_ctx.spawn_fiber(&fiber_id, vec![]);
    let _ = fiber.transition_to(crate::fiber::FiberState::Active);

    let sp_token = format!("sp_{}_{:x}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0), rand::random::<u32>());
    let mut tri_sp = crate::fiber::disposable::TriDbSavepointGuard::new(clm_root_str, &sp_token, is_rust).ok();

    emit_gateway_trace(&format!("execute:{}", operation), "exec", 0);
    let run_res = if is_rust {
        match registered_func {
            Some(f) => f(clm_root_str, clm_file_str),
            None => {
                let m_path = module_path_opt.unwrap_or("");
                if !quiet {
                    eprintln!("[clmEval-rs] ⚡ Sourcing shell test fallback for unregistered module: {}", m_path);
                }
                runtime::run_fallback_internal_reference(clm_root_str, clm_file_str, m_path, quiet)
            }
        }
    } else {
        runtime::evaluate_non_rust_runtime(clm_root, clm_file, process_type, runtime_str, concrete_impl, payload, post_rc, quiet)
    };

    match run_res {
        Ok((exit_code, output)) => {
            if !output.is_empty() {
                print!("{}", output);
            }

            if exit_code == 0 {
                if let Some(ref a_mcard) = a_mcard_opt {
                    let mut outputs_map = serde_json::Map::new();
                    let trimmed = output.trim();
                    let mut parsed = false;

                    if trimmed.starts_with('{') {
                        if let Ok(Value::Object(obj)) = serde_json::from_str::<Value>(trimmed) {
                            for (k, v) in obj {
                                outputs_map.insert(k, v);
                            }
                            parsed = true;
                        }
                    } else if trimmed.contains(':')
                        && let Ok(data) = serde_yaml::from_str::<Value>(trimmed)
                            && let Value::Object(obj) = data {
                                for (k, v) in obj {
                                    outputs_map.insert(k, v);
                                }
                                parsed = true;
                            }

                    if !parsed
                        && let Value::Object(ref sig_outputs) = a_mcard.signature.outputs
                            && sig_outputs.len() == 1 {
                                let first_key = sig_outputs.keys().next().unwrap();
                                if let Ok(num) = trimmed.parse::<i64>() {
                                    outputs_map.insert(first_key.clone(), Value::from(num));
                                } else if let Ok(f) = trimmed.parse::<f64>() {
                                    outputs_map.insert(first_key.clone(), Value::from(f));
                                } else if trimmed == "true" {
                                    outputs_map.insert(first_key.clone(), Value::Bool(true));
                                } else if trimmed == "false" {
                                    outputs_map.insert(first_key.clone(), Value::Bool(false));
                                } else {
                                    outputs_map.insert(first_key.clone(), Value::String(trimmed.to_string()));
                                }
                            }

                    if !outputs_map.contains_key("a_hash")
                        && let Ok(h) = std::env::var("CLM_ACTIVE_A_HASH") {
                            outputs_map.insert("a_hash".to_string(), Value::String(h));
                        }
                    if !outputs_map.contains_key("c_hash")
                        && let Ok(h) = std::env::var("CLM_ACTIVE_C_HASH") {
                            outputs_map.insert("c_hash".to_string(), Value::String(h));
                        }
                    if !outputs_map.contains_key("b_hash")
                        && let Ok(h) = std::env::var("CLM_ACTIVE_B_HASH") {
                            outputs_map.insert("b_hash".to_string(), Value::String(h));
                        }

                    if let Some(obj) = context_val.as_object_mut() {
                        obj.insert("outputs".to_string(), Value::Object(outputs_map));
                    }

                    if !skip_conditions {
                        for post in &a_mcard.invariants.postconditions {
                            match crate::invariants::evaluate_invariant(post, clm_root_str, &context_val) {
                                Ok(true) => {
                                    if !quiet {
                                        eprintln!("[VCARD POST] Invariant '{}' satisfied.", post);
                                    }
                                }
                                Ok(false) => {
                                    eprintln!("[POST_ERR] Postcondition violation: Invariant '{}' failed.", post);
                                    let _ = fiber.transition_to(crate::fiber::FiberState::Failed(format!("Postcondition violation: {}", post)));
                                    let _ = fiber.dispose();
                                    if let Some(ref mut sp) = tri_sp {
                                        let _ = sp.rollback();
                                    }
                                    return Ok(2);
                                }
                                Err(e) => {
                                    eprintln!("[POST_ERR] Postcondition check error: Invariant '{}' raised error: {}", post, e);
                                    let _ = fiber.transition_to(crate::fiber::FiberState::Failed(format!("Postcondition check error: {}", e)));
                                    let _ = fiber.dispose();
                                    if let Some(ref mut sp) = tri_sp {
                                        let _ = sp.rollback();
                                    }
                                    return Ok(2);
                                }
                            }
                        }
                    }
                }

                let raw_hex = compute_sha256_hex(output.as_bytes());
                let output_hash = format!("sha256:{}", raw_hex);
                
                let a_hash_str = clm_data.get("_meta").and_then(|m| m.get("a_hash")).and_then(|v| v.as_str())
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| {
                        let spec = clm_data.get("abstract_spec").cloned().unwrap_or(serde_yaml::Value::Null);
                        let serialized = serde_yaml::to_string(&spec).unwrap_or_default();
                        format!("sha256:{}", compute_sha256_hex(serialized.replace('\r', "").as_bytes()))
                    });
                
                let c_hash_str = clm_data.get("_meta").and_then(|m| m.get("c_hash")).and_then(|v| v.as_str())
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| {
                        let spec = clm_data.get("concrete_impl").cloned().unwrap_or(serde_yaml::Value::Null);
                        let serialized = serde_yaml::to_string(&spec).unwrap_or_default();
                        format!("sha256:{}", compute_sha256_hex(serialized.replace('\r', "").as_bytes()))
                    });
                
                let operation = clm_data.get("concrete_impl")
                    .and_then(|v| v.get("operation"))
                    .and_then(|v| v.as_str())
                    .unwrap_or("unknown");

                let inputs_len = clm_data.get("concrete_impl")
                    .and_then(|v| v.get("inputs"))
                    .and_then(|v| v.as_sequence())
                    .map(|a| a.len())
                    .unwrap_or(0);
                let outputs_len = clm_data.get("concrete_impl")
                    .and_then(|v| v.get("outputs"))
                    .and_then(|v| v.as_sequence())
                    .map(|a| a.len())
                    .unwrap_or(0);
                
                let x_t_d = (outputs_len as i32) - (inputs_len as i32);
                
                if !quiet {
                    eprintln!("[VCARD POST] 🔍 Noetherian P-invariant conservation check: x^T D = 0");
                }
                
                if x_t_d == 0 {
                    if !quiet {
                        eprintln!("   ✅ P-Inv: place marking conservation holds (x^T D = 0) [OK]");
                    }
                } else {
                    if !quiet {
                        eprintln!("   ⚠️ P-Inv: place marking conservation drift detected: x^T D = {} (inputs={}, outputs={})", x_t_d, inputs_len, outputs_len);
                    }
                }

                let extra_yaml = format!("content: |\n  {}", output.replace('\n', "\n  "));
                match crate::db::emit_exec_mcard(
                    operation,
                    &output_hash,
                    &extra_yaml,
                    &a_hash_str,
                    &c_hash_str,
                    clm_root_str,
                ) {
                    Ok(exec_mcard_path) => {
                        if !quiet {
                            eprintln!("[VCARD POST] ✅ Execution MCard generated: {}", exec_mcard_path);
                            eprintln!("[VCARD POST]   g_time: {}", crate::fs_utils::compute_g_time());
                            eprintln!("[VCARD POST]   content_hash: {}", raw_hex);
                        }
                    }
                    Err(e) => {
                        eprintln!("[VCARD POST] ❌ Failed to emit execution MCard: {}", e);
                    }
                }
            }

            if !skip_conditions {
                emit_gateway_trace("validate_postcondition", "post", exit_code);
                match crate::evaluator::compose::compose_conditions(clm_root, clm_file, "post", exit_code, quiet) {
                    Ok(0) => {}
                    Ok(rc) => {
                        eprintln!("CRITICAL: Post-Gate Failed.");
                        let _ = fiber.transition_to(crate::fiber::FiberState::Failed("Post-Gate Failed".to_string()));
                        let _ = fiber.dispose();
                        if let Some(ref mut sp) = tri_sp {
                            let _ = sp.rollback();
                        }
                        return Ok(rc);
                    }
                    Err(e) => {
                        eprintln!("CRITICAL: Post-Gate Failed: {}", e);
                        let _ = fiber.transition_to(crate::fiber::FiberState::Failed(format!("Post-Gate Failed: {}", e)));
                        let _ = fiber.dispose();
                        if let Some(ref mut sp) = tri_sp {
                            let _ = sp.rollback();
                        }
                        return Ok(2);
                    }
                }
            }
            
            if let Some(ref mut sp) = tri_sp {
                let _ = sp.commit();
            }

            if exit_code == 0 {
                let _ = fiber.dispose();
            } else {
                let _ = fiber.transition_to(crate::fiber::FiberState::Failed(format!("Exit code {}", exit_code)));
                let _ = fiber.dispose();
            }

            emit_gateway_trace("vcard_seal", "seal", exit_code);
            Ok(exit_code)
        }
        Err(e) => {
            eprintln!("[clmEval-rs] ❌ Internal dispatch error: {}", e);
            let _ = fiber.transition_to(crate::fiber::FiberState::Failed(format!("Internal dispatch error: {}", e)));
            let _ = fiber.dispose();
            if let Some(ref mut sp) = tri_sp {
                let _ = sp.rollback();
            }
            Ok(1)
        }
    }
}