clm-kernel 0.0.0

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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use serde_json::Value;
use crate::memorize;
use crate::yaml;
use crate::db;

#[cfg(unix)]
#[repr(C)]
#[derive(Clone, Copy)]
pub struct timeval {
    pub tv_sec: i64,
    pub tv_usec: i32,
    #[cfg(target_os = "macos")]
    pub _padding: i32,
}

#[cfg(unix)]
#[repr(C)]
pub struct rusage {
    pub ru_utime: timeval,
    pub ru_stime: timeval,
    pub ru_maxrss: i64,
    pub ru_ixrss: i64,
    pub ru_idrss: i64,
    pub ru_isrss: i64,
    pub ru_minflt: i64,
    pub ru_majflt: i64,
    pub ru_nswap: i64,
    pub ru_inblock: i64,
    pub ru_oublock: i64,
    pub ru_msgsnd: i64,
    pub ru_msgrcv: i64,
    pub ru_nsignals: i64,
    pub ru_nvcsw: i64,
    pub ru_nivcsw: i64,
}

#[cfg(unix)]
const RUSAGE_SELF: i32 = 0;
#[cfg(unix)]
const RUSAGE_CHILDREN: i32 = -1;

#[cfg(unix)]
#[allow(dead_code)]
unsafe extern "C" {
    fn dup(fd: i32) -> i32;
    fn dup2(src: i32, dst: i32) -> i32;
    fn close(fd: i32) -> i32;
    fn getrusage(who: i32, usage: *mut rusage) -> i32;
}

#[cfg(unix)]
pub fn get_peak_rss_kb() -> i64 {
    let mut usage = unsafe { std::mem::zeroed::<rusage>() };
    let res = unsafe { getrusage(RUSAGE_SELF, &mut usage) };
    if res == 0 {
        #[cfg(target_os = "macos")]
        {
            usage.ru_maxrss / 1024
        }
        #[cfg(not(target_os = "macos"))]
        {
            usage.ru_maxrss
        }
    } else {
        0
    }
}

#[cfg(unix)]
pub fn get_children_peak_rss_kb() -> i64 {
    let mut usage = unsafe { std::mem::zeroed::<rusage>() };
    let res = unsafe { getrusage(RUSAGE_CHILDREN, &mut usage) };
    if res == 0 {
        #[cfg(target_os = "macos")]
        {
            usage.ru_maxrss / 1024
        }
        #[cfg(not(target_os = "macos"))]
        {
            usage.ru_maxrss
        }
    } else {
        0
    }
}

#[cfg(windows)]
#[repr(C)]
#[allow(non_snake_case)]
struct PROCESS_MEMORY_COUNTERS {
    cb: u32,
    PageFaultCount: u32,
    PeakWorkingSetSize: usize,
    WorkingSetSize: usize,
    QuotaPeakPagedPoolUsage: usize,
    QuotaPagedPoolUsage: usize,
    QuotaPeakNonPagedPoolUsage: usize,
    QuotaNonPagedPoolUsage: usize,
    PagefileUsage: usize,
    PeakPagefileUsage: usize,
}

#[cfg(windows)]
#[link(name = "psapi")]
unsafe extern "system" {
    fn GetCurrentProcess() -> *mut std::ffi::c_void;
    fn GetProcessMemoryInfo(
        process: *mut std::ffi::c_void,
        counters: *mut PROCESS_MEMORY_COUNTERS,
        cb: u32,
    ) -> i32;
}

#[cfg(windows)]
pub fn get_peak_rss_kb() -> i64 {
    let mut counters = unsafe { std::mem::zeroed::<PROCESS_MEMORY_COUNTERS>() };
    counters.cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
    let res = unsafe { GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) };
    if res != 0 {
        (counters.PeakWorkingSetSize / 1024) as i64
    } else {
        0
    }
}

#[cfg(windows)]
pub fn get_children_peak_rss_kb() -> i64 {
    get_peak_rss_kb()
}

pub fn resolve_python_cmd(clm_root: &str) -> String {
    let root_path = std::path::Path::new(clm_root);
    
    // Windows virtual env python
    let venv_py_win = root_path.join(".venv/Scripts/python.exe");
    if venv_py_win.exists() {
        return venv_py_win.to_string_lossy().to_string();
    }
    
    // Unix virtual env python
    let venv_py_unix = root_path.join(".venv/bin/python3");
    if venv_py_unix.exists() {
        return venv_py_unix.to_string_lossy().to_string();
    }
    
    let venv_py_unix_2 = root_path.join(".venv/bin/python");
    if venv_py_unix_2.exists() {
        return venv_py_unix_2.to_string_lossy().to_string();
    }

    if cfg!(target_os = "windows") {
        for cmd in &["python", "python3"] {
            if std::process::Command::new(cmd).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {
                return cmd.to_string();
            }
        }
    } else {
        for cmd in &["python3", "python"] {
            if std::process::Command::new(cmd).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {
                return cmd.to_string();
            }
        }
    }
    
    if cfg!(target_os = "windows") {
        "python".to_string()
    } else {
        "python3".to_string()
    }
}

pub fn get_interpreter_version(interpreter: &str, clm_root: &str) -> Option<String> {
    let cmd_name = match interpreter {
        "python" | "python3" => resolve_python_cmd(clm_root),
        other => other.to_string(),
    };
    let output = std::process::Command::new(&cmd_name)
        .arg("--version")
        .output()
        .ok();
    if let Some(out) = output {
        let text = String::from_utf8_lossy(&out.stdout).to_string()
            + &String::from_utf8_lossy(&out.stderr).to_string();
        let re = regex::Regex::new(r"(\d+\.\d+(?:\.\d+)?)").unwrap();
        if let Some(caps) = re.captures(&text) {
            return Some(caps[1].to_string());
        }
    }
    None
}

pub fn compare_versions(current: &str, op: &str, req: &str) -> bool {
    let parse_ver = |s: &str| -> (u32, u32, u32) {
        let parts: Vec<&str> = s.split('.').collect();
        let major = parts.get(0).and_then(|v| v.parse().ok()).unwrap_or(0);
        let minor = parts.get(1).and_then(|v| v.parse().ok()).unwrap_or(0);
        let patch = parts.get(2).and_then(|v| v.parse().ok()).unwrap_or(0);
        (major, minor, patch)
    };
    let v1 = parse_ver(current);
    let v2 = parse_ver(req);
    match op {
        ">=" => v1 >= v2,
        "<=" => v1 <= v2,
        ">" => v1 > v2,
        "<" => v1 < v2,
        _ => v1 == v2,
    }
}

pub fn check_precondition(req_str: &str, clm_root: &str) -> bool {
    let re = regex::Regex::new(r"^interpreter:([a-zA-Z0-9_-]+)(>=|<=|>|<|==|=)([0-9.]+)$").unwrap();
    if let Some(caps) = re.captures(req_str) {
        let interpreter = &caps[1];
        let op = &caps[2];
        let req_ver = &caps[3];
        if let Some(current_ver) = get_interpreter_version(interpreter, clm_root) {
            compare_versions(&current_ver, op, req_ver)
        } else {
            false
        }
    } else {
        true
    }
}

pub fn create_sandboxed_command(
    program: &str,
    args: &[String],
    envs: &HashMap<String, String>,
    clm_root: &str,
) -> std::process::Command {
    let clm_no_sandbox = std::env::var("CLM_NO_SANDBOX").unwrap_or_default() == "true";
    let has_sandbox_exec = std::process::Command::new("which")
        .arg("sandbox-exec")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);

    let mut cmd = if !clm_no_sandbox && has_sandbox_exec {
        let home_dir = std::env::var("HOME").unwrap_or_default();
        let profile = format!(
            r#"(version 1)
(deny default)
(allow file-read-metadata)
(allow file-read-data)
(allow file-write-data)
(allow file-read*
    (subpath "/usr")
    (subpath "/System")
    (subpath "/Library")
    (subpath "/private")
    (subpath "/var")
    (subpath "/tmp")
    (subpath "/etc")
    (subpath "/opt")
    (subpath "/dev")
    (subpath "{}")
    (subpath "{}"))
(allow file-write*
    (subpath "{}/data")
    (subpath "{}/db")
    (subpath "{}/types/meta")
    (literal "{}/result_open_interpreter.txt")
    (subpath "{}/.clm")
    (subpath "/private/var")
    (subpath "/private/tmp")
    (subpath "/var")
    (subpath "/tmp")
    (literal "/dev/null")
    (literal "/dev/zero"))
(allow file-map-executable
    (subpath "/usr")
    (subpath "/System")
    (subpath "/Library")
    (subpath "/opt")
    (subpath "{}")
    (subpath "{}"))
(allow process-exec
    (subpath "/bin")
    (subpath "/usr/bin")
    (subpath "/usr/local/bin")
    (subpath "/opt/homebrew")
    (subpath "/Library/Frameworks/Python.framework")
    (subpath "/Library/Developer/CommandLineTools")
    (subpath "/private/var")
    (subpath "/var")
    (subpath "/tmp")
    (subpath "{}")
    (subpath "{}"))
(allow process-fork)
(allow process-info*)
(allow ipc-posix*)
(allow sysctl-read)
(allow mach-lookup)
(allow dynamic-code-generation)
(allow network-bind)
(allow network-inbound)
(allow network-outbound)
(deny file-read*
    (literal "/private/etc/passwd")
    (literal "/etc/passwd"))
(deny file-read-data
    (literal "/private/etc/passwd")
    (literal "/etc/passwd"))"#,
            clm_root, home_dir, clm_root, clm_root, clm_root, clm_root, home_dir, clm_root, home_dir, clm_root, home_dir
        );
        let mut c = std::process::Command::new("sandbox-exec");
        c.arg("-p").arg(profile).arg(program);
        c
    } else {
        std::process::Command::new(program)
    };

    cmd.env_clear();
    for (k, v) in std::env::vars() {
        if !k.starts_with("CLM_") {
            cmd.env(k, v);
        }
    }
    let clm_whitelist = [
        "CLM_NESTED_EXEC", "CLM_RUST_DAEMON_PORT", "CLM_RUNTIME_BACKEND",
        "CLM_POLYGLOT_RUNTIME", "CLM_RUN_ID", "CLM_ZERO_FS", "CLM_PETRI_MARKING_DIR", "CLM_EVENT_LOG_PATH",
        "CLM_ROOT", "PROJECT_ROOT", "CLM_TARGET_FILE", "CLM_PAYLOAD_FILE",
        "CLM_ACTIVE_A_HASH", "CLM_ACTIVE_C_HASH", "CLM_MLP_CONTEXT", "CLM_PAYLOAD",
        "CLM_SESSION_DELEGATION", "CLM_KENOTIC_SPONSOR_DID", "CLM_EXECUTION_LOCALE_HASH",
        "CLM_TRANSPORT_REF", "CLM_PETRI_KENOTIC", "CLM_REPL_TRACE", "CLM_NO_SANDBOX",
        "CLM_SYMBOL_HANDLES", "CLM_DB_BACKEND", "CLM_MEMBROKER_PORT", "CLM_MEMBROKER_NO_DISK",
        "CLM_MEMBROKER_SNAP_DIR", "CLM_SCRATCH", "CLM_TEST_FAST_BOOT", "CLM_SKIP_GRAMMAR",
        "CLM_PETRI_HALT", "CLM_PETRI_VISUAL", "CLM_QUIET",
        "CLM_NATIVE_PETRI_VM", "CLM_DISPATCH_SOCK", "CLM_SCRIPT_CONTENT",
        "CLM_ENTRY_POINT", "CLM_FILE", "CLM_RUST_PORT_FILE",
        "CLM_ACTIVE_B_HASH", "CLM_SKIP_CONDITIONS", "ACTIVE_AGENT_DID",
        "CLM_TARGET_PATH", "CLM_AGENT_CLASS", "CLM_AGENT_ROLE",
        "CLM_RISK_LEVEL", "CLM_EOA_APPROVAL", "CLM_AGENT_DID",
        "CLM_ACTIVE_FILE", "CLM_LAST_MCARD_HASH", "CLM_LAST_MCARD_FILE"
    ];
    for var_name in &clm_whitelist {
        if let Ok(val) = std::env::var(var_name) {
            cmd.env(var_name, val);
        }
    }
    for (k, v) in envs {
        cmd.env(k, v);
    }
    for a in args {
        cmd.arg(a);
    }
    cmd
}

pub fn normalize_output(raw_out: &str) -> String {
    use serde_json::Value;
    let stripped = raw_out.replace('\r', "");
    let stripped = stripped.trim_end().to_string();
    if let Ok(val) = serde_json::from_str::<Value>(&stripped) {
        serde_json::to_string(&val).unwrap_or(stripped)
    } else {
        stripped
    }
}

pub fn print_diff(first_norm: &str, second_norm: &str) {
    let temp_dir = std::env::temp_dir().join("clm_execution_logs/.tmp");
    let f1 = temp_dir.join(format!("norm_f1_{}", std::process::id()));
    let f2 = temp_dir.join(format!("norm_f2_{}", std::process::id()));
    let _ = std::fs::write(&f1, first_norm);
    let _ = std::fs::write(&f2, second_norm);
    
    let diff_output = std::process::Command::new("diff")
        .arg("-u")
        .arg(&f1)
        .arg(&f2)
        .output();
    if let Ok(out) = diff_output {
        let text = String::from_utf8_lossy(&out.stdout);
        eprintln!("{}", text);
    }
    
    let _ = std::fs::remove_file(f1);
    let _ = std::fs::remove_file(f2);
}

pub fn resolve_self_exe(clm_root: &str) -> PathBuf {
    if let Ok(self_exe) = std::env::current_exe() {
        if self_exe.to_string_lossy().contains("deps") {
            let alt_exe = Path::new(clm_root).join({
                #[cfg(windows)] { "kernel/clm_rust_core/target/debug/clm_rust_core.exe" }
                #[cfg(not(windows))] { "kernel/clm_rust_core/target/debug/clm_rust_core" }
            });
            if alt_exe.exists() {
                return alt_exe;
            }
            let alt_exe_release = Path::new(clm_root).join({
                #[cfg(windows)] { "kernel/clm_rust_core/target/release/clm_rust_core.exe" }
                #[cfg(not(windows))] { "kernel/clm_rust_core/target/release/clm_rust_core" }
            });
            if alt_exe_release.exists() {
                return alt_exe_release;
            }
        }
        if let Some(parent) = self_exe.parent() {
            let local_exe = parent.join({
                #[cfg(windows)] { "clm_rust_core.exe" }
                #[cfg(not(windows))] { "clm_rust_core" }
            });
            if local_exe.exists() {
                return local_exe;
            }
        }
        return self_exe;
    }
    Path::new(clm_root).join({
        #[cfg(windows)] { "kernel/clm_rust_core/target/release/clm_rust_core.exe" }
        #[cfg(not(windows))] { "kernel/clm_rust_core/target/release/clm_rust_core" }
    })
}

pub fn exec_polyglot(
    file_path: &str,
    payload: Option<&str>,
    clm_root: &str,
) -> std::result::Result<(i32, String), String> {
    let payload = payload.filter(|s| !s.is_empty());

    // Register CLM manifest file and its AST cards in the database
    memorize::check_and_register_file_mcard(file_path, clm_root)?;

    // 1. Load the manifest content as JSON
    let json_str = yaml::parse_to_mcards(file_path).map_err(|e| e.to_string())?;
    let parsed: Value = serde_json::from_str(&json_str)
        .map_err(|e| format!("Failed to parse JSON AST: {}", e))?;

    // 2. Locate polyglot cases
    let polyglot_cases = yaml::evaluate_jq(&parsed, ".clm.balanced_exp.polyglot_cases");
    let cases_arr = match polyglot_cases {
        Value::Array(arr) => arr,
        _ => return Err("No polyglot_cases found".to_string()),
    };

    // 3. Find the target cases to run
    let mut target_cases = Vec::new();
    if let Some(p) = payload {
        let mut found = false;
        for c in cases_arr.iter() {
            if let Some(name) = c.get("name").and_then(|v| v.as_str()) {
                if name == p {
                    target_cases.push(c.clone());
                    found = true;
                    break;
                }
            }
        }
        if !found {
            return Err(format!("Case matching payload '{}' not found", p));
        }
    } else {
        // Run all cases
        for c in cases_arr.iter() {
            target_cases.push(c.clone());
        }
    }

    if target_cases.is_empty() {
        return Err("No cases to execute".to_string());
    }

    let target_runtime = std::env::var("CLM_POLYGLOT_RUNTIME").ok();
    if let Some(target) = &target_runtime {
        eprintln!("[PAL:polyglot] Active runtime choice: {}", target);
    }

    // Resolve active hashes
    let active_a_hash = std::env::var("CLM_ACTIVE_A_HASH").unwrap_or_default();
    let active_c_hash = std::env::var("CLM_ACTIVE_C_HASH").unwrap_or_default();

    let mut last_case_output = String::new();
    let mut consensus_exit_code = 0;

    for case in &target_cases {
        let case_name = case.get("name").and_then(|v| v.as_str()).unwrap_or("unnamed_case");
        let given = case.get("given").ok_or_else(|| format!("No given block found in case '{}'", case_name))?;

        // Extract runtimes list and determine active runtime choice
        let runtimes = match given.get("runtimes") {
            Some(Value::Array(arr)) => arr.iter().filter_map(|v| v.as_str()).map(|s| s.to_string()).collect::<Vec<String>>(),
            _ => return Err(format!("No runtimes found in given block of case '{}'", case_name)),
        };

        let active_runtimes = if let Some(target) = &target_runtime {
            vec![target.clone()]
        } else {
            runtimes.clone()
        };

        // Inputs (excluding runtimes and requires)
        let mut inputs = serde_json::Map::new();
        let mut env_vars = std::collections::HashMap::new();
        let mut pos_args = Vec::new();
        if let Value::Object(map) = given {
            for (k, v) in map {
                if k != "runtimes" && k != "requires" {
                    inputs.insert(k.clone(), v.clone());
                    let val_str = match v {
                        Value::String(s) => s.clone(),
                        other => other.to_string(),
                    };
                    env_vars.insert(k.clone(), val_str.clone());
                    pos_args.push(val_str);
                }
            }
        }

        for (k, v) in crate::utils::collect_clm_mock_vars() {
            env_vars.insert(k, v);
        }

        // Mutual exclusivity checks
        let then = case.get("then").ok_or_else(|| format!("No then block found in case '{}'", case_name))?;
        let internal_ref = then.get("internal_reference").and_then(|v| v.as_str());
        let native_harness = then.get("native_harness");
        
        if internal_ref.is_some() && native_harness.is_some() {
            return Err(format!("Schema validation failed in case '{}': internal_reference and native_harness are mutually exclusive", case_name));
        }

        // SLA specifications
        let sla = then.get("performance_sla");
        let max_duration_ms = sla.and_then(|s| s.get("max_duration_ms")).and_then(|v| v.as_i64());
        let max_rss_kb = sla.and_then(|s| s.get("max_rss_kb")).and_then(|v| v.as_i64());
        let max_forks = sla.and_then(|s| s.get("max_forks")).and_then(|v| v.as_i64());

        // Validate max_forks: 0 for internal_reference
        if internal_ref.is_some() {
            if let Some(mf) = max_forks {
                if mf != 0 {
                    return Err(format!("Schema validation failed in case '{}': max_forks must be 0 for internal_reference cases", case_name));
                }
            }
        }

        let mut executed_runtimes = Vec::new();
        let mut runtime_outputs = Vec::new();
        let mut runtime_exit_codes = Vec::new();
        let mut runtime_exec_hashes = Vec::new();

        for runtime in &active_runtimes {
            // Enforce Gherkin cover check
            if !runtimes.contains(runtime) {
                eprintln!("[PAL:polyglot] ⏭️ Target runtime '{}' not requested in Gherkin cover: {:?}", runtime, runtimes);
                continue;
            }

            // Verify supported runtimes
            if runtime != "shell" && runtime != "python" && runtime != "node" && runtime != "rust" {
                if target_runtime.is_some() {
                    return Err(format!("Target runtime '{}' is not supported in Sprint 97", runtime));
                } else {
                    eprintln!("[PAL:polyglot] ⏭️ Skipping unsupported runtime '{}' in cover", runtime);
                    continue;
                }
            }

            // Check preconditions
            if let Some(req_guard) = given.get("requires").and_then(|v| v.get(runtime)).and_then(|v| v.as_str()) {
                if !check_precondition(req_guard, clm_root) {
                    eprintln!("[PAL:polyglot] ⏭️ Pruning runtime '{}' (precondition not met: {})", runtime, req_guard);
                    continue;
                }
            }

            let mut fork_count = 0;
            let elapsed_ms;
            let peak_rss_val;

            let (run_status, stdout_data, stderr_data) = if runtime == "rust" && internal_ref.is_some() {
                // Zero-overhead in-process execution
                let ref_path = internal_ref.unwrap();
                let func = crate::evaluator::get_internal_registry(ref_path)
                    .ok_or_else(|| format!("No internal function registered for path '{}'", ref_path))?;
                
                let start_time = std::time::Instant::now();
                let _start_rss = get_peak_rss_kb();

                // Setup Sandbox & execute
                let run_res = {
                    let _sandbox_guard = crate::db::DatabaseSandboxGuard::activate(case_name);
                    func(clm_root, file_path)
                };

                elapsed_ms = start_time.elapsed().as_millis() as i64;
                let end_rss = get_peak_rss_kb();
                peak_rss_val = end_rss; // peak of the process self

                let (code, out) = run_res.map_err(|e| format!("Internal dispatch error: {}", e))?;
                (code, out, String::new())
            } else if let Some(harness) = native_harness {
                // Native harness execution
                let tool = harness.get("tool").and_then(|v| v.as_str()).ok_or("No tool specified in native_harness")?;
                let cmd_arg = harness.get("command").and_then(|v| v.as_str()).ok_or("No command specified in native_harness")?;
                
                fork_count += 1;
                let full_cmd = format!("{} {}", tool, cmd_arg);
                let start_time = std::time::Instant::now();
                let start_rss = get_children_peak_rss_kb();

                let mut cmd = create_sandboxed_command(&crate::fs_utils::get_bash_command(), &["-c".to_string(), full_cmd], &env_vars, clm_root);
                let output = cmd.output().map_err(|e| format!("Failed to spawn native_harness: {}", e))?;
                
                elapsed_ms = start_time.elapsed().as_millis() as i64;
                let end_rss = get_children_peak_rss_kb();
                peak_rss_val = if end_rss > start_rss { end_rss - start_rss } else { 0 };

                (
                    output.status.code().unwrap_or(0),
                    String::from_utf8_lossy(&output.stdout).into_owned(),
                    String::from_utf8_lossy(&output.stderr).into_owned(),
                )
            } else {
                // Legacy Fallback Script compilation & execution
                let impl_path = format!(".clm.concrete_impl.process.implementations.{}", runtime);
                let script_val = yaml::evaluate_jq(&parsed, &format!("{}.script", impl_path));
                let handle_val = yaml::evaluate_jq(&parsed, &format!("{}.script_handle", impl_path));
                let cargo_val = yaml::evaluate_jq(&parsed, &format!("{}.cargo_test", impl_path));
                
                let mut script_content = script_val.as_str().unwrap_or("").to_string();
                let cargo_test_name = cargo_val.as_str().unwrap_or("").to_string();

                if script_content.is_empty() {
                    if let Some(handle) = handle_val.as_str() {
                        if handle.starts_with("script:") {
                            let s_name = handle.trim_start_matches("script:");
                            let sh_path = Path::new(clm_root).join("scripts").join(format!("{}.sh", s_name));
                            if let Ok(content) = std::fs::read_to_string(&sh_path) {
                                script_content = content;
                            } else {
                                // Fallback check test dir
                                let sh_path = Path::new(clm_root).join("tests").join("00_microkernel").join(format!("{}.sh", s_name));
                                if let Ok(content) = std::fs::read_to_string(&sh_path) {
                                    script_content = content;
                                }
                            }
                        }
                    }
                }

                if script_content.is_empty() && cargo_test_name.is_empty() {
                    eprintln!("[PAL:polyglot] Skipping runtime '{}' because no script or cargo_test is defined", runtime);
                    continue;
                }

                let entry_point_val = yaml::evaluate_jq(&parsed, ".clm.concrete_impl.process.entry_point");
                let entry_point = entry_point_val.as_str().unwrap_or("");

                fork_count += 1;
                let start_time = std::time::Instant::now();
                let _start_rss = get_children_peak_rss_kb();

                let (code, out, err) = match runtime.as_str() {
                    "shell" => {
                        let entry_call = if !entry_point.is_empty() {
                            let mut call = format!("{} ", entry_point);
                            for a in &pos_args {
                                call.push_str(&format!("\"{}\" ", a.replace('\"', "\\\"")));
                            }
                            call
                        } else {
                            "".to_string()
                        };
                        let full_script = format!("{}\n{}", script_content, entry_call);
                        let mut cmd = create_sandboxed_command(&crate::fs_utils::get_bash_command(), &["-c".to_string(), full_script], &env_vars, clm_root);
                        let output = cmd.output().map_err(|e| format!("Failed to spawn bash: {}", e))?;
                        (
                            output.status.code().unwrap_or(0),
                            String::from_utf8_lossy(&output.stdout).into_owned(),
                            String::from_utf8_lossy(&output.stderr).into_owned(),
                        )
                    }
                    "python" => {
                        let py_cmd = resolve_python_cmd(clm_root);
                        let mut cmd_args = vec!["-c".to_string(), script_content.to_string()];
                        cmd_args.extend(pos_args.clone());
                        let mut py_env_vars = env_vars.clone();
                        py_env_vars.insert("PYTHONPATH".to_string(), format!("{}/kernel/scripts", clm_root));
                        let mut cmd = create_sandboxed_command(&py_cmd, &cmd_args, &py_env_vars, clm_root);
                        let output = cmd.output().map_err(|e| format!("Failed to spawn python: {}", e))?;
                        (
                            output.status.code().unwrap_or(0),
                            String::from_utf8_lossy(&output.stdout).into_owned(),
                            String::from_utf8_lossy(&output.stderr).into_owned(),
                        )
                    }
                    "node" => {
                        let rand_id = std::time::SystemTime::now()
                            .duration_since(std::time::UNIX_EPOCH)
                            .map(|d| d.as_nanos())
                            .unwrap_or(0);
                        let pid = std::process::id();
                        let temp_dir = std::env::temp_dir().join("clm_execution_logs/.tmp");
                        let _ = std::fs::create_dir_all(&temp_dir);
                        let temp_file = temp_dir.join(format!("clm_node_inline_{}_{}.cjs", rand_id, pid));
                        std::fs::write(&temp_file, script_content).map_err(|e| format!("Failed to write node inline script: {}", e))?;

                        let mut cmd_args = vec!["--trace-uncaught".to_string(), temp_file.to_string_lossy().to_string()];
                        cmd_args.extend(pos_args.clone());
                        let mut cmd = create_sandboxed_command("node", &cmd_args, &env_vars, clm_root);
                        // eprintln!("[DEBUG NODE] args={:?} envs={:?}", cmd_args, env_vars);
                        let output = cmd.output();
                        let _ = std::fs::remove_file(&temp_file);

                        let output = output.map_err(|e| format!("Failed to spawn node: {}", e))?;
                        (
                            output.status.code().unwrap_or(0),
                            String::from_utf8_lossy(&output.stdout).into_owned(),
                            String::from_utf8_lossy(&output.stderr).into_owned(),
                        )
                    }
                    "rust" => {
                        if !cargo_test_name.is_empty() {
                            let self_exe = resolve_self_exe(clm_root);
                            let mut cmd = create_sandboxed_command(
                                &self_exe.to_string_lossy(),
                                &["run-test".to_string(), cargo_test_name.to_string()],
                                &env_vars,
                                clm_root,
                            );
                            cmd.current_dir(Path::new(clm_root).join("kernel/clm_rust_core"));

                            let output = cmd.output().map_err(|e| format!("Failed to spawn clm_rust_core: {}", e))?;
                            (
                                output.status.code().unwrap_or(if output.status.success() { 0 } else { 1 }),
                                String::from_utf8_lossy(&output.stdout).into_owned(),
                                String::from_utf8_lossy(&output.stderr).into_owned(),
                            )
                        } else {
                            let rand_id = std::time::SystemTime::now()
                                .duration_since(std::time::UNIX_EPOCH)
                                .map(|d| d.as_nanos())
                                .unwrap_or(0);
                            let pid = std::process::id();
                            let temp_dir = std::env::temp_dir().join("clm_execution_logs/.tmp");
                            let _ = std::fs::create_dir_all(&temp_dir);
                            let src_file = temp_dir.join(format!("clm_rust_inline_{}_{}.rs", rand_id, pid));
                            let bin_file = temp_dir.join(format!("clm_rust_bin_{}_{}", rand_id, pid));

                            let full_rust_src = if !script_content.contains("fn main") {
                                format!(
                                    "use std::io::{{self, Read}};\nfn main() {{\n{}\n}}",
                                    script_content
                                )
                            } else {
                                script_content.to_string()
                            };
                            std::fs::write(&src_file, full_rust_src).map_err(|e| format!("Failed to write rust inline source: {}", e))?;

                            let compile_output = std::process::Command::new("rustc")
                                .arg("-O")
                                .arg("-o")
                                .arg(&bin_file)
                                .arg(&src_file)
                                .output();
                            let _ = std::fs::remove_file(&src_file);

                            let compile_res = compile_output.map_err(|e| format!("Failed to run rustc: {}", e))?;
                            if !compile_res.status.success() {
                                return Err(format!("Rust compilation failed:\n{}", String::from_utf8_lossy(&compile_res.stderr)));
                            }

                            let mut cmd = std::process::Command::new(&bin_file);
                            for a in &pos_args {
                                cmd.arg(a);
                            }
                            for (k, v) in &env_vars {
                                cmd.env(k, v);
                            }
                            cmd.current_dir(clm_root);

                            let output = cmd.output();
                            let _ = std::fs::remove_file(&bin_file);
                            
                            let output = output.map_err(|e| format!("Failed to run rust binary: {}", e))?;
                            (
                                output.status.code().unwrap_or(0),
                                String::from_utf8_lossy(&output.stdout).into_owned(),
                                String::from_utf8_lossy(&output.stderr).into_owned(),
                            )
                        }
                    }
                    _ => unreachable!(),
                };

                elapsed_ms = start_time.elapsed().as_millis() as i64;
                let end_rss = get_children_peak_rss_kb();
                #[cfg(unix)]
                {
                    peak_rss_val = if end_rss > _start_rss { end_rss - _start_rss } else { 0 };
                }
                #[cfg(windows)]
                {
                    peak_rss_val = end_rss;
                }

                (code, out, err)
            };

            if !stderr_data.is_empty() {
                eprintln!("{}", stderr_data);
            }

            // Enforce SLA resource usage checks
            if let Some(max_dur) = max_duration_ms {
                if elapsed_ms > max_dur {
                    return Err(format!("❌ [SLA_VIOLATION] Case '{}' runtime '{}' exceeded max_duration_ms: {}ms > {}ms", case_name, runtime, elapsed_ms, max_dur));
                }
            }
            if let Some(max_rss) = max_rss_kb {
                if peak_rss_val > max_rss {
                    return Err(format!("❌ [SLA_VIOLATION] Case '{}' runtime '{}' exceeded max_rss_kb: {}KB > {}KB", case_name, runtime, peak_rss_val, max_rss));
                }
            }
            if let Some(max_f) = max_forks {
                if fork_count > max_f {
                    return Err(format!("❌ [SLA_VIOLATION] Case '{}' runtime '{}' exceeded max_forks: {} > {}", case_name, runtime, fork_count, max_f));
                }
            }

            // Generate exec_hash and register Execution MCard
            let runtime_facts = std::env::var("CLM_RUNTIME_FACTS").unwrap_or_default();
            let clean_out = stdout_data.trim_end();
            let exec_hash_input = format!(
                "inputs: {} | outputs: {} | exit_code: {} | runtime: {} | runtime_facts: {}",
                Value::Object(inputs.clone()), clean_out, run_status, runtime, runtime_facts
            );
            let exec_hash = crate::fs_utils::compute_content_hash(&exec_hash_input);

            // Format extra fields
            let mut extra_fields = format!(
                "exit_code: {}\noutputs:\n  result: \"{}\"\ninputs:\n",
                run_status, clean_out.replace('\"', "\\\"")
            );
            for (k, v) in &inputs {
                let val_str = match v {
                    Value::String(s) => s.clone(),
                    other => other.to_string(),
                };
                extra_fields.push_str(&format!("  {}: {}\n", k, val_str));
            }

            // Write Execution MCard to db (isolated to sandbox if active)
            let mcard_path = db::emit_exec_mcard(
                &format!("polyglot_execution_{}", runtime),
                &exec_hash,
                &extra_fields,
                &active_a_hash,
                &active_c_hash,
                clm_root,
            ).map_err(|e| e.to_string())?;

            eprintln!("[PAL:polyglot] ✅ Execution MCard ({}) registered: {}", runtime, mcard_path);

            executed_runtimes.push(runtime.clone());
            runtime_outputs.push(stdout_data);
            runtime_exit_codes.push(run_status);
            runtime_exec_hashes.push(exec_hash);
        }

        let exec_count = executed_runtimes.len();
        if exec_count == 0 {
            return Err(format!("No runtimes were successfully executed for case '{}'.", case_name));
        }

        // 6. Parity check and equivalence verification
        let first_out = &runtime_outputs[0];
        let first_code = runtime_exit_codes[0];
        let first_norm = normalize_output(first_out);

        let mut parity_failed = false;
        let mut mismatch_rt = "";
        let mut mismatch_out = String::new();

        for i in 1..exec_count {
            let r_name = &executed_runtimes[i];
            let r_out = &runtime_outputs[i];
            let r_code = runtime_exit_codes[i];
            let r_norm = normalize_output(r_out);

            if r_code != first_code {
                parity_failed = true;
                mismatch_rt = r_name;
                mismatch_out = format!("Exit code mismatch: {}={} vs {}={}", executed_runtimes[0], first_code, r_name, r_code);
                break;
            }

            if r_norm != first_norm {
                parity_failed = true;
                mismatch_rt = r_name;
                mismatch_out = r_out.clone();
                break;
            }
        }

        if parity_failed {
            let err_msg = format!(
                "COHOMOLOGICAL OBSTRUCTION: Cross-Runtime Parity Fail\n\
                 ❌ [PARITY_ERR] Polyglot execution mismatch between '{}' and '{}' in case '{}'!\n\
                 --- Outputs:\n\
                 1. {}: {}\n\
                 2. {}: {}\n\
                 --- Diff:\n",
                executed_runtimes[0], mismatch_rt, case_name,
                executed_runtimes[0], first_out.trim(),
                mismatch_rt, mismatch_out.trim()
            );
            print_diff(&first_norm, &normalize_output(&mismatch_out));
            return Err(err_msg);
        }

        if exec_count > 1 {
            // Write consensus Execution MCard representing the parity check VCard witness
            let mut sorted_hashes = runtime_exec_hashes.clone();
            sorted_hashes.sort();
            let fold_input = sorted_hashes.join("");
            let parity_hash = crate::fs_utils::compute_sha256_hex(fold_input.as_bytes());

            let clean_first_out = first_out.trim_end();
            let mut parity_fields = format!(
                "consensus_exit_code: {}\nconsensus_result: \"{}\"\nactive_runtimes:\n",
                first_code, clean_first_out.replace('\"', "\\\"")
            );
            for r in &executed_runtimes {
                parity_fields.push_str(&format!("  - {}\n", r));
            }
            let parity_file = db::emit_exec_mcard(
                "polyglot_parity",
                &parity_hash,
                &parity_fields,
                &active_a_hash,
                &active_c_hash,
                clm_root,
            ).map_err(|e| e.to_string())?;

            eprintln!("[PAL:polyglot] ✅ Consensus Parity MCard registered: {}", parity_file);
        }

        // Log Epiplexity Metrics
        let shared_points = if exec_count > 1 { 1 } else { 0 };
        let cross_confirmed = if exec_count > 1 { exec_count - 1 } else { 0 };
        eprintln!(
            "[EPIPLEXITY] Metrics for case '{}': runtimes={}, shared_test_points={}, cross_confirmed_assertions={}",
            case_name, exec_count, shared_points, cross_confirmed
        );

        consensus_exit_code = first_code;
        last_case_output = first_out.clone();
    }

    Ok((consensus_exit_code, last_case_output))
}

/// Execute a script in the named runtime and return (exit_code, stdout, stderr).
///
/// This is a standalone runtime dispatch function that handles shell, python, node,
/// and rust runtimes with environment variables, entry points, and cargo test support.
/// It is called by the `exec-runtime-script` CLI command to enable Python code to
/// delegate runtime execution to the Rust binary instead of spawning subprocesses.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RuntimeScriptInput {
    pub runtime: String,
    pub script: String,
    #[serde(default)]
    pub env: HashMap<String, String>,
    #[serde(default)]
    pub entry_point: String,
    #[serde(default)]
    pub cargo_test: String,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub clm_root: String,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RuntimeScriptOutput {
    pub exit_code: i32,
    pub stdout: String,
    pub stderr: String,
}

pub fn exec_runtime_script(input: &RuntimeScriptInput) -> Result<RuntimeScriptOutput, String> {
    let clm_root = if input.clm_root.is_empty() {
        std::env::var("CLM_ROOT").unwrap_or_default()
    } else {
        input.clm_root.clone()
    };

    let runtime = input.runtime.as_str();
    let script_content = input.script.as_str();
    let entry_point = input.entry_point.as_str();
    let cargo_test_name = input.cargo_test.as_str();
    let pos_args = &input.args;

    let (code, out, err) = match runtime {
        "shell" => {
            let entry_call = if !entry_point.is_empty() {
                let mut call = format!("{} ", entry_point);
                for a in pos_args {
                    call.push_str(&format!("\"{}\" ", a.replace('"', "\\\"")));
                }
                call
            } else {
                String::new()
            };
            let full_script = format!("{}\n{}", script_content, entry_call);
            let mut cmd = create_sandboxed_command(
                &crate::fs_utils::get_bash_command(),
                &["-c".to_string(), full_script],
                &input.env,
                &clm_root,
            );
            let output = cmd.output().map_err(|e| format!("Failed to spawn bash: {}", e))?;
            (
                output.status.code().unwrap_or(0),
                String::from_utf8_lossy(&output.stdout).into_owned(),
                String::from_utf8_lossy(&output.stderr).into_owned(),
            )
        }
        "python" => {
            let py_cmd = resolve_python_cmd(&clm_root);
            let mut cmd_args = vec!["-c".to_string(), script_content.to_string()];
            cmd_args.extend(pos_args.clone());
            let mut py_env = input.env.clone();
            py_env.insert("PYTHONPATH".to_string(), format!("{}/kernel/scripts", clm_root));
            let mut cmd = create_sandboxed_command(&py_cmd, &cmd_args, &py_env, &clm_root);
            let output = cmd.output().map_err(|e| format!("Failed to spawn python: {}", e))?;
            (
                output.status.code().unwrap_or(0),
                String::from_utf8_lossy(&output.stdout).into_owned(),
                String::from_utf8_lossy(&output.stderr).into_owned(),
            )
        }
        "node" => {
            let rand_id = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0);
            let pid = std::process::id();
            let temp_dir = std::env::temp_dir().join("clm_execution_logs/.tmp");
            let _ = std::fs::create_dir_all(&temp_dir);
            let temp_file = temp_dir.join(format!("clm_node_inline_{}_{}.cjs", rand_id, pid));
            std::fs::write(&temp_file, script_content)
                .map_err(|e| format!("Failed to write node inline script: {}", e))?;
            let mut cmd_args = vec!["--trace-uncaught".to_string(), temp_file.to_string_lossy().to_string()];
            cmd_args.extend(pos_args.clone());
            let mut cmd = create_sandboxed_command("node", &cmd_args, &input.env, &clm_root);
            let output = cmd.output();
            let _ = std::fs::remove_file(&temp_file);
            let output = output.map_err(|e| format!("Failed to spawn node: {}", e))?;
            (
                output.status.code().unwrap_or(0),
                String::from_utf8_lossy(&output.stdout).into_owned(),
                String::from_utf8_lossy(&output.stderr).into_owned(),
            )
        }
        "rust" => {
            if !cargo_test_name.is_empty() {
                let self_exe = resolve_self_exe(&clm_root);
                let mut cmd = create_sandboxed_command(
                    &self_exe.to_string_lossy(),
                    &["run-test".to_string(), cargo_test_name.to_string()],
                    &input.env,
                    &clm_root,
                );
                cmd.current_dir(Path::new(&clm_root).join("kernel/clm_rust_core"));
                let output = cmd.output().map_err(|e| format!("Failed to spawn clm_rust_core: {}", e))?;
                (
                    output.status.code().unwrap_or(if output.status.success() { 0 } else { 1 }),
                    String::from_utf8_lossy(&output.stdout).into_owned(),
                    String::from_utf8_lossy(&output.stderr).into_owned(),
                )
            } else {
                let rand_id = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_nanos())
                    .unwrap_or(0);
                let pid = std::process::id();
                let temp_dir = std::env::temp_dir().join("clm_execution_logs/.tmp");
                let _ = std::fs::create_dir_all(&temp_dir);
                let src_file = temp_dir.join(format!("clm_rust_inline_{}_{}.rs", rand_id, pid));
                let bin_file = temp_dir.join(format!("clm_rust_bin_{}_{}", rand_id, pid));
                let full_rust_src = if !script_content.contains("fn main") {
                    format!("use std::io::{{self, Read}};\nfn main() {{\n{}\n}}", script_content)
                } else {
                    script_content.to_string()
                };
                std::fs::write(&src_file, full_rust_src)
                    .map_err(|e| format!("Failed to write rust inline source: {}", e))?;
                let compile_output = std::process::Command::new("rustc")
                    .arg("-O")
                    .arg("-o")
                    .arg(&bin_file)
                    .arg(&src_file)
                    .output();
                let _ = std::fs::remove_file(&src_file);
                let compile_res = compile_output.map_err(|e| format!("Failed to run rustc: {}", e))?;
                if !compile_res.status.success() {
                    return Ok(RuntimeScriptOutput {
                        exit_code: 1,
                        stdout: String::new(),
                        stderr: format!("Rust compilation failed:\n{}", String::from_utf8_lossy(&compile_res.stderr)),
                    });
                }
                let mut cmd = std::process::Command::new(&bin_file);
                for a in pos_args {
                    cmd.arg(a);
                }
                for (k, v) in &input.env {
                    cmd.env(k, v);
                }
                cmd.current_dir(&clm_root);
                let output = cmd.output();
                let _ = std::fs::remove_file(&bin_file);
                let output = output.map_err(|e| format!("Failed to run rust binary: {}", e))?;
                (
                    output.status.code().unwrap_or(0),
                    String::from_utf8_lossy(&output.stdout).into_owned(),
                    String::from_utf8_lossy(&output.stderr).into_owned(),
                )
            }
        }
        _ => {
            return Err(format!("Unsupported runtime: {}", runtime));
        }
    };

    Ok(RuntimeScriptOutput {
        exit_code: code,
        stdout: out,
        stderr: err,
    })
}