clm-kernel 0.0.5

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
// evaluator/dispatch/runtime.rs
// ─────────────────────────────────────────────────────────────
// Non-Rust runtime execution and helper utilities.
//
// Functions:
//   evaluate_non_rust_runtime — dispatch to python, node, shell, compose, system, go, llm, etc.
//   run_fallback_internal_reference — source bash test scripts for unregistered modules
//   find_test_script — recursive directory search for test script files
//   resolve_script_body — resolve inline script or script_handle to content
//   find_script_file — recursive search for script files by name + extension
//   run_command_and_capture — execute a Command and capture stdout/stderr
// ─────────────────────────────────────────────────────────────

use std::fs;
use std::path::{Path, PathBuf};
use crate::evaluator::run_evaluation;

// ── Public API (used by orchestrator) ───────────────────────

pub(crate) fn evaluate_non_rust_runtime(
    clm_root: &Path,
    clm_file: &str,
    process_type: &str,
    runtime: &str,
    concrete_impl: &serde_yaml::Value,
    payload: Option<&str>,
    post_rc: Option<i32>,
    quiet: bool,
) -> Result<(i32, String), String> {
    eprintln!("[DEBUG] evaluate_non_rust_runtime for clm_file: {}", clm_file);
    let clm_root_str = clm_root.to_str().ok_or("Invalid CLM_ROOT path")?;
    let process = concrete_impl.get("process")
        .ok_or_else(|| "No process block in concrete_impl".to_string())?;
    
    if process_type == "compose" || runtime == "compose" {
        if !quiet {
            eprintln!("[PAL] Dispatching: type=compose");
        }
        let steps = process.get("steps")
            .and_then(|v| v.as_sequence())
            .ok_or_else(|| "No steps in compose process block".to_string())?;
        
        let mut exit_code = 0;
        for (i, step_ref_val) in steps.iter().enumerate() {
            if let Some(step_ref) = step_ref_val.as_str() {
                let step_path = if Path::new(step_ref).is_absolute() {
                    PathBuf::from(step_ref)
                } else {
                    let joined = clm_root.join(step_ref);
                    if joined.exists() {
                        joined
                    } else if let Some(suffix) = step_ref.strip_prefix("clm/") {
                        clm_root.join(suffix)
                    } else {
                        joined
                    }
                };
                if !step_path.exists() {
                    return Err(format!("[COMPOSE_FN] Step {}: failed to load '{}'", i + 1, step_path.to_string_lossy()));
                }
                if !quiet {
                    eprintln!("[COMPOSE_FN]   Step {}: (from {})", i + 1, step_ref);
                }
                let rc = run_evaluation(
                    clm_root,
                    Some(step_path.to_str().unwrap()),
                    payload,
                    None,
                    quiet,
                    None,
                )?;
                if rc != 0 {
                    exit_code = rc;
                    break;
                }
            }
        }
        return Ok((exit_code, "".to_string()));
    }

    if runtime == "polyglot" || process_type == "polyglot" {
        return match crate::polyglot::exec_polyglot(clm_file, payload, clm_root_str) {
            Ok((code, output)) => Ok((code, output)),
            Err(e) => Err(e),
        };
    }

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

    let project_root_str = std::env::var("PROJECT_ROOT").unwrap_or_else(|_| {
        clm_root.parent()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_else(|| clm_root_str.to_string())
    });

    if runtime == "system" && process_type != "python" && process_type != "node" && process_type != "javascript" && process_type != "shell" {
        let op_clm_path = clm_root.join("computable_knowledge/Abstract/layer5_system/bootstrap/governance").join(format!("{}.yaml", entry_point));
        let op_clm_path = if op_clm_path.exists() {
            op_clm_path
        } else {
            PathBuf::from(&project_root_str).join("clm/computable_knowledge/Abstract/layer5_system/bootstrap/governance").join(format!("{}.yaml", entry_point))
        };
        
        if !op_clm_path.exists() {
            return Err(format!("[EXEC] System operation CLM not found: {:?}", op_clm_path));
        }
        
        crate::utils::set_env_var("TARGET_FILE", clm_file);
        
        if !quiet {
            eprintln!("[clmEval-rs] Dispatching to system governance operation: {} (via CLM evaluate)", entry_point);
        }
        
        let rc = run_evaluation(
            clm_root,
            Some(op_clm_path.to_str().ok_or("Invalid path")?),
            payload,
            None,
            quiet,
            None,
        )?;
        
        return Ok((rc, "".to_string()));
    }

    let identity_db = crate::db::get_db_path("agent_identities", clm_root_str).to_string_lossy().to_string();
    let content_db = crate::db::get_db_path("content_memory", clm_root_str).to_string_lossy().to_string();
    let execution_log_db = crate::db::get_db_path("execution_log", clm_root_str).to_string_lossy().to_string();

    let mlp_json = serde_json::json!({
      "$schema": "https://mcard.org/schemas/mlp-context-v1.json",
      "context": {
        "operation": entry_point,
        "clm_file": clm_file,
        "a_hash": std::env::var("CLM_ACTIVE_A_HASH").unwrap_or_default(),
        "c_hash": std::env::var("CLM_ACTIVE_C_HASH").unwrap_or_default(),
        "payload": payload.unwrap_or("")
      },
      "environment": {
        "CLM_ROOT": clm_root_str,
        "PROJECT_ROOT": project_root_str,
        "g_time": crate::fs_utils::compute_g_time()
      },
      "databases": {
        "identity_db": identity_db,
        "content_db": content_db,
        "execution_log_db": execution_log_db
      }
    });
    let mlp_json_str = serde_json::to_string(&mlp_json).unwrap_or_default();

    let mut env_vars = std::collections::HashMap::new();
    if let Some(pay) = payload {
        env_vars.insert("CLM_PAYLOAD".to_string(), pay.to_string());
        env_vars.insert("TARGET_FILE".to_string(), pay.to_string());
    }
    env_vars.insert("CLM_ROOT".to_string(), clm_root_str.to_string());
    env_vars.insert("PROJECT_ROOT".to_string(), project_root_str);
    env_vars.insert("CLM_MLP_CONTEXT".to_string(), mlp_json_str);

    if let Ok(val) = std::env::var("CLM_ACTIVE_A_HASH") {
        env_vars.insert("CLM_ACTIVE_A_HASH".to_string(), val);
    }
    if let Ok(val) = std::env::var("CLM_ACTIVE_C_HASH") {
        env_vars.insert("CLM_ACTIVE_C_HASH".to_string(), val);
    }
    if let Ok(val) = std::env::var("CLM_ACTIVE_B_HASH") {
        env_vars.insert("CLM_ACTIVE_B_HASH".to_string(), val);
    }

    for (k, v) in std::env::vars() {
        if k.starts_with("CLM_MOCK_") {
            env_vars.insert(k, v);
        }
    }

    let governance_vars = [
        "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 &governance_vars {
        if let Ok(val) = std::env::var(var_name) {
            env_vars.insert(var_name.to_string(), val);
        }
    }

    if runtime == "go" || runtime == "llm" || (runtime == "rust" && process_type == "rust") {
        let adapter_name = if runtime == "rust" { "rust" } else { runtime };
        let script = format!(
            "clm_root() {{ echo \"{}\"; }}\n\
             export -f clm_root\n\
             source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/layer1_cpn_vm/runtime_adapters.sh\"\n\
             _adapter_{} \"{}\" \"{}\" \"{}\"\n",
            clm_root_str,
            clm_root_str,
            adapter_name,
            clm_file,
            entry_point,
            payload.unwrap_or("")
        );
        
        let old_no_sandbox = std::env::var("CLM_NO_SANDBOX");
        if runtime == "llm" {
            crate::utils::set_env_var("CLM_NO_SANDBOX", "true");
        }
        let cmd = crate::polyglot::create_sandboxed_command(&crate::fs_utils::get_bash_command(), &["-c".to_string(), script], &env_vars, clm_root_str);
        if runtime == "llm" {
            match old_no_sandbox {
                Ok(val) => crate::utils::set_env_var("CLM_NO_SANDBOX", &val),
                Err(_) => crate::utils::remove_env_var("CLM_NO_SANDBOX"),
            }
        }
        return run_command_and_capture(cmd);
    }

    if runtime == "open_interpreter" {
        let py_cmd = crate::polyglot::resolve_python_cmd(clm_root_str);
        let mut cmd_args = vec![
            "-c".to_string(),
            "import sys; from clm.layer3.open_interpreter_adapter import main_cli; sys.exit(main_cli())".to_string(),
            clm_file.to_string(),
            entry_point.to_string(),
        ];
        if let Some(p) = payload {
            cmd_args.push(p.to_string());
        }
        let mut custom_env_vars = env_vars.clone();
        custom_env_vars.insert("PYTHONPATH".to_string(), format!("{}/kernel/scripts", clm_root_str));
        
        let old_no_sandbox = std::env::var("CLM_NO_SANDBOX");
        crate::utils::set_env_var("CLM_NO_SANDBOX", "true");
        
        let cmd = crate::polyglot::create_sandboxed_command(&py_cmd, &cmd_args, &custom_env_vars, clm_root_str);
        
        match old_no_sandbox {
            Ok(val) => crate::utils::set_env_var("CLM_NO_SANDBOX", &val),
            Err(_) => crate::utils::remove_env_var("CLM_NO_SANDBOX"),
        }
        
        return run_command_and_capture(cmd);
    }

    let runner_type = if process_type == "python" || process_type == "node" || process_type == "javascript" || process_type == "shell" {
        process_type
    } else {
        runtime
    };

    // Otherwise, it is a script-based runtime: python, node, javascript, shell
    let script_content = resolve_script_body(clm_root, process, runner_type)?;
    eprintln!("[DEBUG] script body resolved: {} bytes, dispatching to {} runtime", script_content.len(), runner_type);

    let mut args: Vec<String> = match payload {
        Some(p) => p.split_whitespace().map(|s| s.to_string()).collect(),
        None => Vec::new(),
    };
    // For post-condition gates, append the exit code so shell gate functions
    // receive both the payload (CLM file) and the evaluation exit code.
    if let Some(rc) = post_rc {
        args.push(rc.to_string());
    }

    match runner_type {
        "python" => {
            let py_cmd = crate::polyglot::resolve_python_cmd(clm_root_str);
            let mut cmd_args = vec!["-c".to_string(), script_content];
            cmd_args.extend(args);
            let mut py_env_vars = env_vars.clone();
            py_env_vars.insert("PYTHONPATH".to_string(), format!("{}/kernel/scripts", clm_root_str));
            let cmd = crate::polyglot::create_sandboxed_command(&py_cmd, &cmd_args, &py_env_vars, clm_root_str);
            run_command_and_capture(cmd)
        }
        "node" | "javascript" => {
            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(args);
            let cmd = crate::polyglot::create_sandboxed_command("node", &cmd_args, &env_vars, clm_root_str);
            let res = run_command_and_capture(cmd);
            let _ = std::fs::remove_file(&temp_file);
            res
        }
        "shell" => {
            let header = format!(
                "clm_root() {{ echo \"{}\"; }}\n\
                 export -f clm_root\n\
                 source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/evaluator/shell_utils.sh\" 2>/dev/null || true\n\
                 source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/layer0_core/mcard_storage.sh\" 2>/dev/null || true\n\
                 source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/layer0_core/mcard_verification.sh\" 2>/dev/null || true\n\
                 source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/layer0_core/clm_algebra.sh\" 2>/dev/null || true\n\
                 source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/layer0_core/clm_bootstrap.sh\" 2>/dev/null || true\n\
                 source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/layer0_core/type_registry.sh\" 2>/dev/null || true\n\
                 source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/governance/grammar_ops.sh\" 2>/dev/null || true\n\
                 source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/governance/define_grammar.sh\" 2>/dev/null || true\n\
                 source \"{}/computable_knowledge/Concrete/layer5_system/bootstrap/governance/validate_grammar.sh\" 2>/dev/null || true\n\
                 source \"{}/data/ipc/evaluator_cache.sh\" 2>/dev/null || true\n\
                 clm_preload 2>/dev/null || true\n",
                clm_root_str, clm_root_str, clm_root_str, clm_root_str, clm_root_str, clm_root_str, clm_root_str, clm_root_str, clm_root_str, clm_root_str, clm_root_str
            );
            let wrapped_body = if !entry_point.is_empty() {
                format!("_clm_run_block() {{\n{}\n}}\n_clm_run_block \"$@\"\nif type -t {1} &>/dev/null; then {1} \"$@\"; fi\n", script_content, entry_point)
            } else {
                format!("_clm_run_block() {{\n{}\n}}\n_clm_run_block \"$@\"\n", script_content)
            };
            let full_script = header + &wrapped_body;
            let mut cmd_args = vec!["-s".to_string(), "--".to_string()];
            cmd_args.extend(args);
            let mut cmd = crate::polyglot::create_sandboxed_command(&crate::fs_utils::get_bash_command(), &cmd_args, &env_vars, clm_root_str);
            cmd.stdin(std::process::Stdio::piped());
            cmd.stdout(std::process::Stdio::piped());
            cmd.stderr(std::process::Stdio::piped());

            let mut child = cmd.spawn().map_err(|e| format!("Failed to spawn bash: {}", e))?;
            if let Some(mut stdin) = child.stdin.take() {
                use std::io::Write;
                stdin.write_all(full_script.as_bytes()).map_err(|e| format!("Failed to write to bash stdin: {}", e))?;
            }

            let output = child.wait_with_output().map_err(|e| format!("Failed to wait for bash: {}", e))?;
            if !output.stderr.is_empty() {
                use std::io::Write;
                std::io::stderr().write_all(&output.stderr).ok();
            }
            let exit_code = output.status.code().unwrap_or(1);
            let stdout_str = String::from_utf8_lossy(&output.stdout).to_string();
            Ok((exit_code, stdout_str))
        }
        other => Err(format!("Unsupported non-rust runtime: {}", other)),
    }
}

pub(crate) fn run_fallback_internal_reference(
    clm_root: &str,
    _clm_file: &str,
    module_path: &str,
    _quiet: bool,
) -> Result<(i32, String), String> {
    let test_name = module_path.split("::").last().unwrap_or(module_path);
    let overrides = [
        ("test_petri_net_suite", "petri_net_cases.sh"),
        ("test_petri_binding_suite", "petri_binding_cases.sh"),
        ("test_petri_invariants", "petri_invariant_cases.sh"),
        ("test_monadic_pcard_resolve_handle", "test_monadic_pcards.sh"),
        ("test_monadic_pcard_check_precondition", "test_monadic_pcards.sh"),
        ("test_monadic_pcard_execute_payload", "test_monadic_pcards.sh"),
        ("test_monadic_pcard_validate_postcondition", "test_monadic_pcards.sh"),
    ];

    let mut target_filename = format!("{}.sh", test_name);
    for &(k, v) in &overrides {
        if test_name == k {
            target_filename = v.to_string();
            break;
        }
    }

    let clm_root_path = Path::new(clm_root);
    let target_path = find_test_script(&clm_root_path.join("tests"), &target_filename)
        .ok_or_else(|| format!("Test script not found for filename: {}", target_filename))?;

    let test_func = match test_name {
        "test_petri_math" => "test_petri_math_suite",
        "test_petri_invariants" => "test_petri_invariant_suite",
        other => other,
    };

    let script_content = format!(
        "export CLM_ROOT=\"{clm_root}\"\n\
         export PATH=\"$CLM_ROOT:$CLM_ROOT/kernel/scripts:$PATH\"\n\
         clm_root() {{ echo \"$CLM_ROOT\"; }}\n\
         export -f clm_root\n\
         exit() {{ return \"${{1:-0}}\"; }}\n\
         while IFS= read -r f; do\n\
             if [[ \"$f\" != *\"clmEval.sh\"* && \"$f\" != *\"main.sh\"* && \"$f\" != *\"evaluator.sh\"* ]]; then\n\
                 source \"$f\" 2>/dev/null || true\n\
             fi\n\
         done < <(find \"$CLM_ROOT/computable_knowledge/Concrete/layer5_system/bootstrap\" -name \"node_modules\" -prune -o -name \"*.sh\" -print)\n\
         unset -f exit\n\
         source \"{script_path}\" && {test_func}\n",
        clm_root = clm_root,
        script_path = target_path.to_string_lossy(),
        test_func = test_func
    );

    let output = {
        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_fallback_{}_{}.sh", std::process::id(), std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)));
        std::fs::write(&temp_file, &script_content)
            .map_err(|e| format!("Failed to write temp fallback script: {}", e))?;

        #[cfg(windows)]
        {
            let temp_path_str = temp_file.to_string_lossy().replace('\\', "/");
            let temp_path_unix = if temp_path_str.len() >= 2 && temp_path_str.as_bytes()[1] == b':' {
                let drive = (temp_path_str.as_bytes()[0] as char).to_ascii_lowercase();
                format!("/{}{}", drive, &temp_path_str[2..])
            } else {
                temp_path_str
            };
            let mut cmd = std::process::Command::new(crate::fs_utils::get_bash_command());
            cmd.current_dir(clm_root);
            cmd.arg(&temp_path_unix);
            for (k, v) in std::env::vars() {
                cmd.env(k, v);
            }
            let result = cmd.output().map_err(|e| format!("Failed to execute fallback bash command: {}", e));
            let _ = std::fs::remove_file(&temp_file);
            result?
        }
        #[cfg(not(windows))]
        {
            let mut cmd = std::process::Command::new(crate::fs_utils::get_bash_command());
            cmd.current_dir(clm_root);
            cmd.arg(&temp_file);
            for (k, v) in std::env::vars() {
                cmd.env(k, v);
            }
            let result = cmd.output().map_err(|e| format!("Failed to execute fallback bash command: {}", e));
            let _ = std::fs::remove_file(&temp_file);
            result?
        }
    };
    
    if !output.stderr.is_empty() {
        use std::io::Write;
        std::io::stderr().write_all(&output.stderr).ok();
    }

    let exit_code = output.status.code().unwrap_or(1);
    let stdout_str = String::from_utf8_lossy(&output.stdout).to_string();
    Ok((exit_code, stdout_str))
}

// ── Internal Helpers ────────────────────────────────────────

fn find_test_script(dir: &Path, target: &str) -> Option<PathBuf> {
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_file() {
                if path.file_name().and_then(|s| s.to_str()) == Some(target) {
                    return Some(path);
                }
            } else if path.is_dir()
                && let Some(p) = find_test_script(&path, target) {
                    return Some(p);
                }
        }
    }
    None
}

fn resolve_script_body(clm_root: &Path, process: &serde_yaml::Value, runner_type: &str) -> Result<String, String> {
    eprintln!("[DEBUG] resolve_script_body called with runner_type: {}", runner_type);
    eprintln!("[DEBUG] process object: {:?}", process);
    if let Some(script) = process.get("script").and_then(|v| v.as_str()) {
        eprintln!("[DEBUG] resolve_script_body: found 'script' field, length: {}", script.len());
        if !script.is_empty() {
            return Ok(script.to_string());
        }
    }

    if let Some(handle) = process.get("script_handle").and_then(|v| v.as_str()) {
        eprintln!("[DEBUG] resolve_script_body: trying to resolve handle: {:?}", handle);
        if handle.starts_with("script:") {
            let handle_name = handle.trim_start_matches("script:");
            // First check database
            match crate::db::resolve_handle_content("content_memory", clm_root.to_str().unwrap_or(""), handle) {
                Ok(Some(content)) if !content.is_empty() => {
                    eprintln!("[DEBUG] resolve_script_body: resolved '{}' from content_memory DB ({} bytes)", handle, content.len());
                    return Ok(content);
                }
                Ok(_) => eprintln!("[DEBUG] resolve_script_body: '{}' not in DB, falling back to disk search", handle),
                Err(e) => eprintln!("[DEBUG] resolve_script_body: DB resolve error for '{}': {}, falling back to disk search", handle, e),
            }

            // Search on disk
            let extensions = match runner_type {
                "python" => vec![".py"],
                "node" | "javascript" => vec![".js", ".cjs"],
                "shell" => vec![".sh"],
                _ => vec![".sh", ".py", ".js", ".cjs"],
            };
            eprintln!("[DEBUG] resolve_script_handle: searching for '{}' with extensions {:?}", handle_name, extensions);
            let search_dirs = ["scripts", "tests", "kernel/scripts", "computable_knowledge"];
            for dir_name in &search_dirs {
                let dir_path = clm_root.join(dir_name);
                if dir_path.exists()
                    && let Some(path) = find_script_file(&dir_path, handle_name, &extensions) {
                        eprintln!("[DEBUG] found path: {:?}, trying to read...", path);
                        match fs::read_to_string(&path) {
                            Ok(content) => return Ok(content),
                            Err(e) => eprintln!("[DEBUG] failed to read {:?}: {}", path, e),
                        }
                    }
            }
        } else {
            // Handle without "script:" prefix — treat as a function name.
            // Source gate_library.sh which defines gate_* functions.
            let gate_lib = clm_root.join("computable_knowledge/Concrete/layer5_system/bootstrap/governance/gate_library.sh");
            if gate_lib.exists()
                && let Ok(content) = fs::read_to_string(&gate_lib) {
                    // Return the library content; the entry_point (handle name) will be called
                    // by the shell wrapper's type -t guard.
                    return Ok(content);
                }
        }
    }

    Err("Empty script body and failed to resolve script_handle".to_string())
}

fn find_script_file(dir: &Path, script_name: &str, extensions: &[&str]) -> Option<PathBuf> {
    // Handle names may contain path separators (e.g. "finetuning/dataset_intake").
    // Extract the basename for matching against file names.
    let basename = script_name.rsplit('/').next().unwrap_or(script_name);
    // eprintln!("[DEBUG] find_script_file: searching dir {:?}", dir); // too noisy
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_file() {
                if let Some(file_name) = path.file_name().and_then(|s| s.to_str()) {
                    if file_name.contains(basename) {
                        eprintln!("[DEBUG] file_name: '{}', script_name: '{}', basename: '{}'", file_name, script_name, basename);
                    }
                    for ext in extensions {
                        if file_name.contains(basename) {
                            eprintln!("[DEBUG] comparing '{}' with '{}' and '{}'", file_name, format!("{}{}", script_name, ext), format!("{}{}", basename, ext));
                        }
                        if file_name == format!("{}{}", script_name, ext)
                            || file_name == format!("{}{}", basename, ext)
                        {
                            return Some(path);
                        }
                    }
                }
            } else if path.is_dir()
                && let Some(p) = find_script_file(&path, script_name, extensions) {
                    return Some(p);
                }
        }
    }
    None
}

fn run_command_and_capture(mut cmd: std::process::Command) -> Result<(i32, String), String> {
    eprintln!("[DEBUG] run_command_and_capture: spawning {:?} ({} args), waiting for exit...", cmd.get_program(), cmd.get_args().count());
    let output = cmd.output().map_err(|e| format!("Failed to execute process: {}", e))?;
    eprintln!("[DEBUG] run_command_and_capture: {:?} exited with {:?}", cmd.get_program(), output.status.code());
    if !output.stderr.is_empty() {
        use std::io::Write;
        std::io::stderr().write_all(&output.stderr).ok();
    }
    let exit_code = output.status.code().unwrap_or(1);
    let stdout_str = String::from_utf8_lossy(&output.stdout).to_string();
    Ok((exit_code, stdout_str))
}