Skip to main content

lean_ctx/core/
sandbox.rs

1use std::collections::HashMap;
2#[cfg(unix)]
3use std::os::unix::process::CommandExt;
4use std::process::Command;
5
6#[derive(Debug, Clone)]
7pub struct SandboxResult {
8    pub stdout: String,
9    pub stderr: String,
10    pub exit_code: i32,
11    pub language: String,
12    pub duration_ms: u64,
13}
14
15const TIMEOUT_SECS: u64 = 30;
16const MAX_OUTPUT_BYTES: usize = 32_768;
17/// Upper bound on the `code` payload. Generous for real scripts while preventing an
18/// agent from forcing a multi-megabyte temp-file write / interpreter argv → memory abuse.
19const MAX_CODE_BYTES: usize = 256 * 1024;
20
21pub fn execute(language: &str, code: &str, timeout_secs: Option<u64>) -> SandboxResult {
22    if code.len() > MAX_CODE_BYTES {
23        return SandboxResult {
24            stdout: String::new(),
25            stderr: format!(
26                "Code exceeds the {MAX_CODE_BYTES}-byte limit ({} bytes). Split it into smaller scripts.",
27                code.len()
28            ),
29            exit_code: 1,
30            language: language.to_string(),
31            duration_ms: 0,
32        };
33    }
34
35    let timeout = timeout_secs.unwrap_or(TIMEOUT_SECS);
36    let start = std::time::Instant::now();
37
38    let Some(runtime) = resolve_runtime(language) else {
39        return SandboxResult {
40            stdout: String::new(),
41            stderr: format!(
42                "Unsupported language: {language}. Supported: javascript, typescript, python, shell, ruby, go, rust, php, perl, r, elixir"
43            ),
44            exit_code: 1,
45            language: language.to_string(),
46            duration_ms: 0,
47        };
48    };
49
50    let sandbox_level = std::env::var("LEAN_CTX_SANDBOX_LEVEL")
51        .ok()
52        .and_then(|v| v.parse::<u8>().ok())
53        .unwrap_or_else(|| crate::core::config::Config::load().sandbox_level);
54
55    if sandbox_level >= 1 && cfg!(target_os = "macos") {
56        let result = seatbelt_execute(&runtime, code, timeout);
57        let duration_ms = start.elapsed().as_millis() as u64;
58        return match result {
59            Ok((stdout, stderr, exit_code)) => SandboxResult {
60                stdout: truncate_output(&stdout),
61                stderr: truncate_smart(&stderr, 2048),
62                exit_code,
63                language: language.to_string(),
64                duration_ms,
65            },
66            Err(e) => SandboxResult {
67                stdout: String::new(),
68                stderr: format!("Seatbelt execution error: {e}"),
69                exit_code: 1,
70                language: language.to_string(),
71                duration_ms,
72            },
73        };
74    } else if sandbox_level >= 1 {
75        #[cfg(target_os = "linux")]
76        {
77            let result = landlock_execute(&runtime, code, timeout);
78            let duration_ms = start.elapsed().as_millis() as u64;
79            return match result {
80                Ok((stdout, stderr, exit_code)) => SandboxResult {
81                    stdout: truncate_output(&stdout),
82                    stderr: truncate_smart(&stderr, 2048),
83                    exit_code,
84                    language: language.to_string(),
85                    duration_ms,
86                },
87                Err(e) => SandboxResult {
88                    stdout: String::new(),
89                    stderr: format!("Landlock execution error: {e}"),
90                    exit_code: 1,
91                    language: language.to_string(),
92                    duration_ms,
93                },
94            };
95        }
96
97        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
98        eprintln!(
99            "[lean-ctx] sandbox_level=1 requested but sandboxing not available on this platform; falling back to Level 0"
100        );
101    }
102
103    let result = if runtime.needs_temp_file {
104        execute_with_file(&runtime, code, timeout)
105    } else {
106        execute_with_stdin(&runtime, code, timeout)
107    };
108
109    let duration_ms = start.elapsed().as_millis() as u64;
110
111    match result {
112        Ok((stdout, stderr, code)) => SandboxResult {
113            stdout: truncate_output(&stdout),
114            stderr: truncate_smart(&stderr, 2048),
115            exit_code: code,
116            language: language.to_string(),
117            duration_ms,
118        },
119        Err(e) => SandboxResult {
120            stdout: String::new(),
121            stderr: format!("Execution error: {e}"),
122            exit_code: 1,
123            language: language.to_string(),
124            duration_ms,
125        },
126    }
127}
128
129pub fn batch_execute(items: &[(String, String)]) -> Vec<SandboxResult> {
130    items
131        .iter()
132        .map(|(lang, code)| execute(lang, code, None))
133        .collect()
134}
135
136struct RuntimeConfig {
137    command: String,
138    args: Vec<String>,
139    needs_temp_file: bool,
140    file_extension: String,
141    env: HashMap<String, String>,
142}
143
144fn resolve_runtime(language: &str) -> Option<RuntimeConfig> {
145    let lang = language.to_lowercase();
146    let lang = lang.as_str();
147
148    match lang {
149        "javascript" | "js" | "node" => Some(RuntimeConfig {
150            command: find_binary(&["bun", "node"])?,
151            args: vec!["-e".to_string()],
152            needs_temp_file: false,
153            file_extension: "js".to_string(),
154            env: HashMap::new(),
155        }),
156        "typescript" | "ts" => Some(RuntimeConfig {
157            command: find_binary(&["bun", "npx"])?,
158            args: if which_exists("bun") {
159                vec!["-e".to_string()]
160            } else {
161                vec!["tsx".to_string(), "-e".to_string()]
162            },
163            needs_temp_file: false,
164            file_extension: "ts".to_string(),
165            env: HashMap::new(),
166        }),
167        "python" | "py" => Some(RuntimeConfig {
168            command: find_binary(&["python3", "python"])?,
169            args: vec!["-c".to_string()],
170            needs_temp_file: false,
171            file_extension: "py".to_string(),
172            env: HashMap::from([("PYTHONDONTWRITEBYTECODE".into(), "1".into())]),
173        }),
174        "shell" | "bash" | "sh" => {
175            #[cfg(target_os = "windows")]
176            {
177                Some(RuntimeConfig {
178                    command: "cmd".to_string(),
179                    args: vec!["/C".to_string()],
180                    needs_temp_file: false,
181                    file_extension: "bat".to_string(),
182                    env: HashMap::new(),
183                })
184            }
185            #[cfg(not(target_os = "windows"))]
186            {
187                Some(RuntimeConfig {
188                    command: find_binary(&["bash", "sh"])?,
189                    args: vec!["-c".to_string()],
190                    needs_temp_file: false,
191                    file_extension: "sh".to_string(),
192                    env: HashMap::new(),
193                })
194            }
195        }
196        "ruby" | "rb" => Some(RuntimeConfig {
197            command: find_binary(&["ruby"])?,
198            args: vec!["-e".to_string()],
199            needs_temp_file: false,
200            file_extension: "rb".to_string(),
201            env: HashMap::new(),
202        }),
203        "go" | "golang" => Some(RuntimeConfig {
204            command: find_binary(&["go"])?,
205            args: vec!["run".to_string()],
206            needs_temp_file: true,
207            file_extension: "go".to_string(),
208            env: HashMap::new(),
209        }),
210        "rust" | "rs" => Some(RuntimeConfig {
211            command: "rustc_script".to_string(),
212            args: vec![],
213            needs_temp_file: true,
214            file_extension: "rs".to_string(),
215            env: HashMap::new(),
216        }),
217        "php" => Some(RuntimeConfig {
218            command: find_binary(&["php"])?,
219            args: vec!["-r".to_string()],
220            needs_temp_file: false,
221            file_extension: "php".to_string(),
222            env: HashMap::new(),
223        }),
224        "perl" | "pl" => Some(RuntimeConfig {
225            command: find_binary(&["perl"])?,
226            args: vec!["-e".to_string()],
227            needs_temp_file: false,
228            file_extension: "pl".to_string(),
229            env: HashMap::new(),
230        }),
231        "r" => Some(RuntimeConfig {
232            command: find_binary(&["Rscript"])?,
233            args: vec!["-e".to_string()],
234            needs_temp_file: false,
235            file_extension: "R".to_string(),
236            env: HashMap::new(),
237        }),
238        "elixir" | "ex" => Some(RuntimeConfig {
239            command: find_binary(&["elixir"])?,
240            args: vec!["-e".to_string()],
241            needs_temp_file: false,
242            file_extension: "exs".to_string(),
243            env: HashMap::new(),
244        }),
245        _ => None,
246    }
247}
248
249fn seatbelt_execute(
250    runtime: &RuntimeConfig,
251    code: &str,
252    timeout: u64,
253) -> Result<(String, String, i32), String> {
254    let tmp_dir = std::env::temp_dir().join("lean-ctx-sandbox");
255    let _ = std::fs::create_dir_all(&tmp_dir);
256
257    let env_pairs: Vec<(String, String)> = runtime
258        .env
259        .iter()
260        .map(|(k, v)| (k.clone(), v.clone()))
261        .collect();
262
263    if runtime.needs_temp_file {
264        let suffix = format!(".{}", runtime.file_extension);
265        let tmp = tempfile::Builder::new()
266            .prefix("exec_")
267            .suffix(&suffix)
268            .tempfile_in(&tmp_dir)
269            .map_err(|e| format!("Failed to create temp file: {e}"))?;
270        let file_path = tmp.into_temp_path();
271        std::fs::write(&file_path, code).map_err(|e| format!("Failed to write temp file: {e}"))?;
272
273        let allowed = [file_path.to_path_buf()];
274        let allowed_refs: Vec<&std::path::Path> =
275            allowed.iter().map(std::path::PathBuf::as_path).collect();
276        let file_str = file_path.to_string_lossy().to_string();
277
278        let mut args: Vec<&str> = runtime
279            .args
280            .iter()
281            .map(std::string::String::as_str)
282            .collect();
283        args.push(&file_str);
284
285        let result = super::sandbox_seatbelt::execute_sandboxed(
286            &runtime.command,
287            &args,
288            &allowed_refs,
289            &env_pairs,
290            timeout,
291        );
292        let _ = std::fs::remove_file(&file_path);
293        result
294    } else {
295        let mut args: Vec<&str> = runtime
296            .args
297            .iter()
298            .map(std::string::String::as_str)
299            .collect();
300        args.push(code);
301        super::sandbox_seatbelt::execute_sandboxed(
302            &runtime.command,
303            &args,
304            &[],
305            &env_pairs,
306            timeout,
307        )
308    }
309}
310
311#[cfg(target_os = "linux")]
312fn landlock_execute(
313    runtime: &RuntimeConfig,
314    code: &str,
315    timeout: u64,
316) -> Result<(String, String, i32), String> {
317    let tmp_dir = std::env::temp_dir().join("lean-ctx-sandbox");
318    let _ = std::fs::create_dir_all(&tmp_dir);
319
320    let env_pairs: Vec<(String, String)> = runtime
321        .env
322        .iter()
323        .map(|(k, v)| (k.clone(), v.clone()))
324        .collect();
325
326    if runtime.needs_temp_file {
327        let suffix = format!(".{}", runtime.file_extension);
328        let tmp = tempfile::Builder::new()
329            .prefix("exec_")
330            .suffix(&suffix)
331            .tempfile_in(&tmp_dir)
332            .map_err(|e| format!("Failed to create temp file: {e}"))?;
333        let file_path = tmp.into_temp_path();
334        std::fs::write(&file_path, code).map_err(|e| format!("Failed to write temp file: {e}"))?;
335
336        let allowed = [file_path.to_path_buf()];
337        let allowed_refs: Vec<&std::path::Path> =
338            allowed.iter().map(std::path::PathBuf::as_path).collect();
339        let file_str = file_path.to_string_lossy().to_string();
340
341        let mut args: Vec<&str> = runtime
342            .args
343            .iter()
344            .map(std::string::String::as_str)
345            .collect();
346        args.push(&file_str);
347
348        let result = super::sandbox_landlock::execute_sandboxed(
349            &runtime.command,
350            &args,
351            &allowed_refs,
352            &env_pairs,
353            timeout,
354        );
355        let _ = std::fs::remove_file(&file_path);
356        result
357    } else {
358        let mut args: Vec<&str> = runtime
359            .args
360            .iter()
361            .map(std::string::String::as_str)
362            .collect();
363        args.push(code);
364        super::sandbox_landlock::execute_sandboxed(
365            &runtime.command,
366            &args,
367            &[],
368            &env_pairs,
369            timeout,
370        )
371    }
372}
373
374const SANDBOX_ENV_ALLOWLIST: &[&str] = &[
375    "PATH",
376    "HOME",
377    "USER",
378    "LANG",
379    "LC_ALL",
380    "TERM",
381    "TMPDIR",
382    "TMP",
383    "TEMP",
384    "SYSTEMROOT",
385    "WINDIR",
386];
387
388fn apply_sandbox_env(cmd: &mut Command, runtime: &RuntimeConfig) {
389    cmd.env_clear();
390    for key in SANDBOX_ENV_ALLOWLIST {
391        if let Ok(val) = std::env::var(key) {
392            cmd.env(key, val);
393        }
394    }
395    for (k, v) in &runtime.env {
396        cmd.env(k, v);
397    }
398    cmd.env("LEAN_CTX_SANDBOX", "1");
399}
400
401fn execute_with_stdin(
402    runtime: &RuntimeConfig,
403    code: &str,
404    timeout: u64,
405) -> Result<(String, String, i32), String> {
406    let mut cmd = Command::new(&runtime.command);
407    for arg in &runtime.args {
408        cmd.arg(arg);
409    }
410    cmd.arg(code);
411    apply_sandbox_env(&mut cmd, runtime);
412    // GH #1347: isolate child into its own process group so an interactive
413    // shell (bash -ic) cannot SIGTSTP the MCP server, and close stdin to
414    // prevent terminal job-control attempts.
415    cmd.stdin(std::process::Stdio::null());
416    cmd.stdout(std::process::Stdio::piped());
417    cmd.stderr(std::process::Stdio::piped());
418    #[cfg(unix)]
419    cmd.process_group(0);
420
421    let child = cmd
422        .spawn()
423        .map_err(|e| format!("Failed to spawn {}: {e}", runtime.command))?;
424
425    let output = wait_with_timeout(child, timeout)?;
426    Ok((
427        crate::shell::decode_output(&output.stdout),
428        crate::shell::decode_output(&output.stderr),
429        output.status.code().unwrap_or(1),
430    ))
431}
432
433fn execute_with_file(
434    runtime: &RuntimeConfig,
435    code: &str,
436    timeout: u64,
437) -> Result<(String, String, i32), String> {
438    let tmp_dir = std::env::temp_dir().join("lean-ctx-sandbox");
439    let _ = std::fs::create_dir_all(&tmp_dir);
440
441    let suffix = format!(".{}", runtime.file_extension);
442    let tmp = tempfile::Builder::new()
443        .prefix("exec_")
444        .suffix(&suffix)
445        .tempfile_in(&tmp_dir)
446        .map_err(|e| format!("Failed to create temp file: {e}"))?;
447    let file_path = tmp.into_temp_path();
448
449    std::fs::write(&file_path, code).map_err(|e| format!("Failed to write temp file: {e}"))?;
450
451    let result = if runtime.command == "rustc_script" {
452        execute_rust(&file_path, timeout)
453    } else {
454        let mut cmd = Command::new(&runtime.command);
455        for arg in &runtime.args {
456            cmd.arg(arg);
457        }
458        cmd.arg(&file_path);
459        apply_sandbox_env(&mut cmd, runtime);
460        cmd.stdin(std::process::Stdio::null());
461        cmd.stdout(std::process::Stdio::piped());
462        cmd.stderr(std::process::Stdio::piped());
463        #[cfg(unix)]
464        cmd.process_group(0);
465
466        let child = cmd
467            .spawn()
468            .map_err(|e| format!("Failed to spawn {}: {e}", runtime.command))?;
469        let output = wait_with_timeout(child, timeout)?;
470        Ok((
471            crate::shell::decode_output(&output.stdout),
472            crate::shell::decode_output(&output.stderr),
473            output.status.code().unwrap_or(1),
474        ))
475    };
476
477    let _ = std::fs::remove_file(&file_path);
478    result
479}
480
481fn execute_rust(
482    source_path: &std::path::Path,
483    timeout: u64,
484) -> Result<(String, String, i32), String> {
485    let binary_path = source_path.with_extension("");
486
487    let mut compile_cmd = Command::new("rustc");
488    compile_cmd.arg(source_path).arg("-o").arg(&binary_path);
489    compile_cmd.env_clear();
490    for key in SANDBOX_ENV_ALLOWLIST {
491        if let Ok(val) = std::env::var(key) {
492            compile_cmd.env(key, val);
493        }
494    }
495    compile_cmd.env("LEAN_CTX_SANDBOX", "1");
496
497    let compile = compile_cmd
498        .output()
499        .map_err(|e| format!("rustc not found: {e}"))?;
500
501    if !compile.status.success() {
502        let stderr = crate::shell::decode_output(&compile.stderr);
503        let _ = std::fs::remove_file(&binary_path);
504        return Ok((String::new(), stderr, compile.status.code().unwrap_or(1)));
505    }
506
507    let mut run_cmd = Command::new(&binary_path);
508    run_cmd.env_clear();
509    for key in SANDBOX_ENV_ALLOWLIST {
510        if let Ok(val) = std::env::var(key) {
511            run_cmd.env(key, val);
512        }
513    }
514    run_cmd.env("LEAN_CTX_SANDBOX", "1");
515    run_cmd.stdin(std::process::Stdio::null());
516    run_cmd.stdout(std::process::Stdio::piped());
517    run_cmd.stderr(std::process::Stdio::piped());
518    #[cfg(unix)]
519    run_cmd.process_group(0);
520
521    let child = run_cmd
522        .spawn()
523        .map_err(|e| format!("Failed to run compiled binary: {e}"))?;
524
525    let output = wait_with_timeout(child, timeout)?;
526    let _ = std::fs::remove_file(&binary_path);
527
528    Ok((
529        crate::shell::decode_output(&output.stdout),
530        crate::shell::decode_output(&output.stderr),
531        output.status.code().unwrap_or(1),
532    ))
533}
534
535fn wait_with_timeout(
536    child: std::process::Child,
537    timeout_secs: u64,
538) -> Result<std::process::Output, String> {
539    let mut child = child;
540    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
541
542    loop {
543        match child.try_wait() {
544            Ok(Some(_)) => return child.wait_with_output().map_err(|e| e.to_string()),
545            Ok(None) => {
546                if std::time::Instant::now() > deadline {
547                    kill_process_tree(&mut child);
548                    // GH #1504: after killing, drain whatever the child wrote
549                    // before the timeout so partial output is preserved instead
550                    // of being silently discarded.
551                    if let Ok(mut output) = child.wait_with_output() {
552                        output.stderr.extend_from_slice(
553                            format!("\n[lean-ctx] Execution timed out after {timeout_secs}s")
554                                .as_bytes(),
555                        );
556                        return Ok(output);
557                    }
558                    return Err(format!("Execution timed out after {timeout_secs}s"));
559                }
560                std::thread::sleep(std::time::Duration::from_millis(50));
561            }
562            Err(e) => return Err(e.to_string()),
563        }
564    }
565}
566
567/// Kill a child process and its entire process group (Unix) or just the child
568/// (non-Unix). Uses SIGKILL on the negative PID to hit the whole group created
569/// by `process_group(0)`.
570fn kill_process_tree(child: &mut std::process::Child) {
571    #[cfg(unix)]
572    {
573        let pid = child.id() as i32;
574        // SAFETY: libc::kill with negative pid targets the process group.
575        unsafe { libc::kill(-pid, libc::SIGKILL) };
576    }
577    #[cfg(not(unix))]
578    {
579        let _ = child.kill();
580    }
581}
582
583fn find_binary(candidates: &[&str]) -> Option<String> {
584    for name in candidates {
585        if which_exists(name) {
586            return Some(name.to_string());
587        }
588    }
589    None
590}
591
592fn which_exists(name: &str) -> bool {
593    #[cfg(target_os = "windows")]
594    let check_cmd = Command::new("where")
595        .arg(name)
596        .stdout(std::process::Stdio::null())
597        .stderr(std::process::Stdio::null())
598        .status();
599
600    #[cfg(not(target_os = "windows"))]
601    let check_cmd = Command::new("which")
602        .arg(name)
603        .stdout(std::process::Stdio::null())
604        .stderr(std::process::Stdio::null())
605        .status();
606
607    check_cmd.is_ok_and(|s| s.success())
608}
609
610fn truncate_output(output: &str) -> String {
611    if output.len() <= MAX_OUTPUT_BYTES {
612        return output.to_string();
613    }
614    truncate_smart(output, MAX_OUTPUT_BYTES)
615}
616
617fn truncate_smart(output: &str, max_bytes: usize) -> String {
618    if output.len() <= max_bytes {
619        return output.to_string();
620    }
621
622    let lines: Vec<&str> = output.lines().collect();
623    let total_lines = lines.len();
624
625    let head_count = (total_lines * 60) / 100;
626    let tail_count = total_lines - head_count;
627
628    let head: Vec<&str> = lines.iter().take(head_count).copied().collect();
629    let tail: Vec<&str> = lines
630        .iter()
631        .skip(total_lines - tail_count)
632        .copied()
633        .collect();
634
635    let head_text = head.join("\n");
636    let tail_text = tail.join("\n");
637
638    if head_text.len() + tail_text.len() + 100 > max_bytes {
639        let half = max_bytes / 2;
640        let h = &output[..output.floor_char_boundary(half.min(output.len()))];
641        let t_start = output.ceil_char_boundary(output.len().saturating_sub(half));
642        let t = &output[t_start..];
643        let skipped = output.len() - h.len() - t.len();
644        return format!("{h}\n\n... [{skipped} bytes truncated — showing head + tail] ...\n\n{t}");
645    }
646
647    let skipped_lines = total_lines - head_count - tail_count;
648    let skipped_bytes = output.len() - head_text.len() - tail_text.len();
649    format!(
650        "{head_text}\n\n... [{skipped_lines} lines / {skipped_bytes} bytes truncated — showing first {head_count} + last {tail_count} lines] ...\n\n{tail_text}"
651    )
652}
653
654pub fn supported_languages() -> &'static [&'static str] {
655    &[
656        "javascript",
657        "typescript",
658        "python",
659        "shell",
660        "ruby",
661        "go",
662        "rust",
663        "php",
664        "perl",
665        "r",
666        "elixir",
667    ]
668}
669
670#[cfg(test)]
671pub mod tests {
672    use super::*;
673
674    fn python_available() -> bool {
675        find_binary(&["python3", "python"]).is_some()
676    }
677
678    #[test]
679    fn execute_python_hello() {
680        if !python_available() {
681            return;
682        }
683        let result = execute("python", "print('hello sandbox')", None);
684        assert_eq!(result.exit_code, 0);
685        assert!(result.stdout.contains("hello sandbox"));
686    }
687
688    #[test]
689    #[cfg(not(target_os = "windows"))]
690    fn execute_shell_echo() {
691        let result = execute("shell", "echo 'test output'", None);
692        assert_eq!(result.exit_code, 0);
693        assert!(result.stdout.contains("test output"));
694    }
695
696    #[test]
697    fn execute_unsupported_language() {
698        let result = execute("brainfuck", "++++", None);
699        assert_eq!(result.exit_code, 1);
700        assert!(result.stderr.contains("Unsupported language"));
701    }
702
703    #[test]
704    fn execute_rejects_oversized_code() {
705        let huge = "a".repeat(MAX_CODE_BYTES + 1);
706        let result = execute("python", &huge, None);
707        assert_eq!(result.exit_code, 1);
708        assert!(result.stderr.contains("exceeds the"));
709    }
710
711    #[test]
712    fn execute_python_error() {
713        if !python_available() {
714            return;
715        }
716        let result = execute("python", "raise ValueError('test error')", None);
717        assert_ne!(result.exit_code, 0);
718        assert!(result.stderr.contains("ValueError"));
719    }
720
721    #[test]
722    fn execute_with_timeout() {
723        if !python_available() {
724            return;
725        }
726        let result = execute("python", "import time; time.sleep(60)", Some(1));
727        assert_ne!(result.exit_code, 0);
728        assert!(
729            result.stderr.contains("timed out"),
730            "stderr should mention timeout: {}",
731            result.stderr
732        );
733    }
734
735    /// GH #1504: partial stdout emitted before a timeout must be preserved.
736    #[test]
737    fn timeout_preserves_partial_output() {
738        if !python_available() {
739            return;
740        }
741        let result = execute(
742            "python",
743            "import sys; sys.stdout.write('PARTIAL_1504'); sys.stdout.flush(); import time; time.sleep(60)",
744            Some(2),
745        );
746        assert_ne!(result.exit_code, 0);
747        assert!(
748            result.stdout.contains("PARTIAL_1504"),
749            "partial stdout before timeout must be preserved, got: {:?}",
750            result.stdout
751        );
752        assert!(
753            result.stderr.contains("timed out"),
754            "stderr should mention timeout: {}",
755            result.stderr
756        );
757    }
758
759    #[test]
760    fn truncate_preserves_head_and_tail() {
761        let lines: Vec<String> = (0..100)
762            .map(|i| format!("line {i}: some content here"))
763            .collect();
764        let output = lines.join("\n");
765        let truncated = truncate_smart(&output, 500);
766        assert!(truncated.contains("line 0:"));
767        assert!(truncated.contains("line 99:"));
768        assert!(truncated.contains("truncated"));
769    }
770
771    #[test]
772    fn supported_languages_list() {
773        let langs = supported_languages();
774        assert!(langs.contains(&"python"));
775        assert!(langs.contains(&"javascript"));
776        assert!(langs.contains(&"rust"));
777        assert_eq!(langs.len(), 11);
778    }
779
780    #[test]
781    fn sandbox_env_is_set() {
782        if !python_available() {
783            return;
784        }
785        let result = execute(
786            "python",
787            "import os; print(os.environ.get('LEAN_CTX_SANDBOX', 'missing'))",
788            None,
789        );
790        assert_eq!(result.exit_code, 0);
791        assert!(result.stdout.contains('1'));
792    }
793
794    #[test]
795    #[cfg(not(target_os = "windows"))]
796    fn batch_execute_multiple() {
797        let items = vec![
798            ("python".to_string(), "print(1+1)".to_string()),
799            ("shell".to_string(), "echo hello".to_string()),
800        ];
801        let results = batch_execute(&items);
802        assert_eq!(results.len(), 2);
803        assert!(results[0].stdout.contains('2'));
804        assert!(results[1].stdout.contains("hello"));
805    }
806}