Skip to main content

lean_ctx/shell/
platform.rs

1use std::io::{self, IsTerminal};
2
3/// Sets `LC_CTYPE=C.UTF-8` when no UTF-8 locale is inherited from the parent
4/// process. Without this, commands treat bytes >127 as non-printable (C locale),
5/// mangling Cyrillic, CJK, emoji, etc.
6pub(crate) fn apply_utf8_locale(cmd: &mut std::process::Command) {
7    let has_utf8 = std::env::var("LC_ALL")
8        .or_else(|_| std::env::var("LC_CTYPE"))
9        .or_else(|_| std::env::var("LANG"))
10        .is_ok_and(|v| v.to_ascii_lowercase().contains("utf"));
11
12    if !has_utf8 {
13        cmd.env("LC_CTYPE", "C.UTF-8");
14    }
15}
16
17/// Neutralizes inherited startup-file hooks so a non-login/non-interactive
18/// `sh -c` / `bash -c` cannot be hijacked into sourcing a profile or rc file
19/// (#451). lean-ctx runs the system POSIX shell profile-free and deterministic;
20/// a stray inherited `BASH_ENV` (read by bash even for `bash -c`) or `ENV`
21/// pointing at e.g. an `exec nu` snippet would otherwise silently replace the
22/// shell. Cleared to empty so the expansion names no file. No-op in effect for
23/// PowerShell/cmd, which ignore both variables.
24pub(crate) fn apply_profile_free_env(cmd: &mut std::process::Command) {
25    cmd.env("BASH_ENV", "").env("ENV", "");
26}
27
28pub fn decode_output(bytes: &[u8]) -> String {
29    match String::from_utf8(bytes.to_vec()) {
30        Ok(s) => s,
31        Err(_) => {
32            #[cfg(windows)]
33            {
34                decode_windows_output(bytes)
35            }
36            #[cfg(not(windows))]
37            {
38                String::from_utf8_lossy(bytes).into_owned()
39            }
40        }
41    }
42}
43/// Resolve carriage-return (`\r`) progress overwrites in captured output.
44///
45/// CLI tools like `git`, `cargo`, and `npm` use `\r` to draw in-place progress
46/// updates. When stdout is captured (not a TTY), these bytes survive as literal
47/// `\r` characters and produce glued-together lines (#1140). This function
48/// emulates terminal behaviour: for each line, only the content after the last
49/// `\r` is kept.
50pub fn resolve_carriage_returns(s: &str) -> String {
51    if !s.contains('\r') {
52        return s.to_string();
53    }
54    let mut out = String::with_capacity(s.len());
55    for (i, line) in s.split('\n').enumerate() {
56        if i > 0 {
57            out.push('\n');
58        }
59        let line = line.strip_suffix('\r').unwrap_or(line);
60        if let Some(pos) = line.rfind('\r') {
61            out.push_str(&line[pos + 1..]);
62        } else {
63            out.push_str(line);
64        }
65    }
66    out
67}
68
69#[cfg(windows)]
70fn decode_windows_output(bytes: &[u8]) -> String {
71    use std::os::windows::ffi::OsStringExt;
72
73    let lossy = String::from_utf8_lossy(bytes);
74    let replacement_count = lossy.chars().filter(|&c| c == '\u{FFFD}').count();
75    if replacement_count == 0 {
76        return lossy.into_owned();
77    }
78
79    // SAFETY: declares Win32 API symbols that exist in kernel32; signatures
80    // match the documented ABI.
81    unsafe extern "system" {
82        fn GetACP() -> u32;
83        fn MultiByteToWideChar(
84            cp: u32,
85            flags: u32,
86            src: *const u8,
87            srclen: i32,
88            dst: *mut u16,
89            dstlen: i32,
90        ) -> i32;
91    }
92
93    // SAFETY: `GetACP` takes no arguments and only returns the active code
94    // page; it cannot fail or cause undefined behaviour.
95    let codepage = unsafe { GetACP() };
96    // SAFETY: called with a null destination and length 0 to measure the
97    // required buffer size; `bytes` is a live slice and every pointer/length
98    // argument is valid.
99    let wide_len = unsafe {
100        MultiByteToWideChar(
101            codepage,
102            0,
103            bytes.as_ptr(),
104            bytes.len() as i32,
105            std::ptr::null_mut(),
106            0,
107        )
108    };
109    if wide_len <= 0 {
110        return lossy.into_owned();
111    }
112    let mut wide: Vec<u16> = vec![0u16; wide_len as usize];
113    // SAFETY: `wide` is sized to the previously measured length and `bytes` is
114    // a live slice; the source and destination pointers/lengths are valid and
115    // do not overlap.
116    unsafe {
117        MultiByteToWideChar(
118            codepage,
119            0,
120            bytes.as_ptr(),
121            bytes.len() as i32,
122            wide.as_mut_ptr(),
123            wide_len,
124        );
125    }
126    std::ffi::OsString::from_wide(&wide)
127        .to_string_lossy()
128        .into_owned()
129}
130
131#[cfg(windows)]
132pub(super) fn set_console_utf8() {
133    // SAFETY: declares a Win32 API symbol that exists in kernel32; the
134    // signature matches the documented ABI.
135    unsafe extern "system" {
136        fn SetConsoleOutputCP(id: u32) -> i32;
137    }
138    // SAFETY: `SetConsoleOutputCP` takes a code-page id (65001 = UTF-8) by
139    // value; it cannot cause undefined behaviour.
140    unsafe {
141        SetConsoleOutputCP(65001);
142    }
143}
144
145/// Detects if the current process runs inside a Docker/container environment.
146pub fn is_container() -> bool {
147    #[cfg(unix)]
148    {
149        if std::path::Path::new("/.dockerenv").exists() {
150            return true;
151        }
152        if let Ok(cgroup) = std::fs::read_to_string("/proc/1/cgroup")
153            && (cgroup.contains("/docker/") || cgroup.contains("/lxc/"))
154        {
155            return true;
156        }
157        if let Ok(mounts) = std::fs::read_to_string("/proc/self/mountinfo")
158            && mounts.contains("/docker/containers/")
159        {
160            return true;
161        }
162        false
163    }
164    #[cfg(not(unix))]
165    {
166        false
167    }
168}
169
170/// Returns true if stdin is NOT a terminal (pipe, /dev/null, etc.)
171pub fn is_non_interactive() -> bool {
172    !io::stdin().is_terminal()
173}
174
175/// Returns `true` when `shell_path` points to a PowerShell executable.
176pub(crate) fn is_powershell(shell_path: &str) -> bool {
177    let name = std::path::Path::new(shell_path)
178        .file_name()
179        .and_then(|n| n.to_str())
180        .unwrap_or("")
181        .to_ascii_lowercase();
182    name.contains("powershell") || name.contains("pwsh")
183}
184
185/// Documented default location of the current-user PowerShell profile
186/// (`$PROFILE.CurrentUserCurrentHost`).
187///
188/// Windows PowerShell 7+ stores it under `Documents\PowerShell\…`, but **PowerShell
189/// (pwsh) on macOS/Linux reads `~/.config/powershell/…` instead** — and stat-ing
190/// anything inside `~/Documents` on macOS pops a TCC privacy prompt ("lean-ctx
191/// would like to access files in your Documents folder", #356). Resolving the
192/// profile per-OS keeps pwsh support everywhere while never touching `~/Documents`
193/// on non-Windows hosts.
194///
195/// This is the *default* path only. On Windows the real `Documents` folder is
196/// frequently redirected (OneDrive folder backup), so callers should prefer
197/// [`resolve_powershell_profile_path`], which asks PowerShell for the live location
198/// and uses this as the fallback.
199pub(crate) fn powershell_profile_path(home: &std::path::Path) -> std::path::PathBuf {
200    const PROFILE_FILE: &str = "Microsoft.PowerShell_profile.ps1";
201    if cfg!(windows) {
202        home.join("Documents").join("PowerShell").join(PROFILE_FILE)
203    } else {
204        home.join(".config").join("powershell").join(PROFILE_FILE)
205    }
206}
207
208/// Resolve the **active** current-user PowerShell profile path.
209///
210/// On Windows the profile lives under the *Documents* known folder, which OneDrive
211/// folder backup (enabled by default on most installs) routinely redirects to e.g.
212/// `…\OneDrive\Documents\PowerShell\…`. A hardcoded `~\Documents` therefore misses
213/// the real `$PROFILE`, so `proxy enable` / shell-hook install silently write to a
214/// file PowerShell never reads and the proxy receives no traffic (#558). We ask
215/// PowerShell itself for `$PROFILE.CurrentUserCurrentHost` — authoritative under any
216/// folder redirection — preferring `pwsh` (7+) then Windows PowerShell, and fall back
217/// to [`powershell_profile_path`] only when no PowerShell host can be launched (in
218/// which case the profile is moot anyway).
219///
220/// Non-Windows hosts keep the static `~/.config/powershell` path (never `~/Documents`,
221/// #356) and never spawn a process.
222pub(crate) fn resolve_powershell_profile_path(home: &std::path::Path) -> std::path::PathBuf {
223    #[cfg(windows)]
224    {
225        if let Some(active) = query_active_powershell_profile() {
226            return active;
227        }
228    }
229    powershell_profile_path(home)
230}
231
232/// Ask PowerShell for `$PROFILE.CurrentUserCurrentHost`, the authoritative profile
233/// path under any `Documents` redirection. Returns `None` when no PowerShell host can
234/// be launched or the output is not a usable absolute path.
235#[cfg(windows)]
236fn query_active_powershell_profile() -> Option<std::path::PathBuf> {
237    // `pwsh` (7+) and `powershell.exe` (5.1) use different profile roots; prefer the
238    // modern host (matching the `Documents\PowerShell` default above), then fall back.
239    // Force UTF-8 output so redirected paths with non-ASCII characters survive the pipe.
240    for exe in ["pwsh", "powershell"] {
241        let output = match std::process::Command::new(exe)
242            .args([
243                "-NoProfile",
244                "-NonInteractive",
245                "-Command",
246                "[Console]::OutputEncoding=[Text.Encoding]::UTF8; $PROFILE.CurrentUserCurrentHost",
247            ])
248            .output()
249        {
250            Ok(out) if out.status.success() => out,
251            _ => continue,
252        };
253        let path = std::path::PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
254        if path.is_absolute() && path.file_name().is_some() {
255            return Some(path);
256        }
257    }
258    None
259}
260
261/// Windows only: argument that passes one command string to the shell binary.
262/// `exe_basename` must already be ASCII-lowercase (e.g. `bash.exe`, `cmd.exe`).
263fn windows_shell_flag_for_exe_basename(exe_basename: &str) -> &'static str {
264    if exe_basename.contains("powershell") || exe_basename.contains("pwsh") {
265        "-Command"
266    } else if exe_basename == "cmd.exe" || exe_basename == "cmd" {
267        "/C"
268    } else {
269        "-c"
270    }
271}
272
273pub fn shell_and_flag() -> (String, String) {
274    let shell = detect_shell();
275    let flag = if cfg!(windows) {
276        let name = std::path::Path::new(&shell)
277            .file_name()
278            .and_then(|n| n.to_str())
279            .unwrap_or("")
280            .to_ascii_lowercase();
281        windows_shell_flag_for_exe_basename(&name).to_string()
282    } else {
283        "-c".to_string()
284    };
285    (shell, flag)
286}
287
288/// Returns a short, human-readable shell name (e.g. "bash", "zsh", "powershell", "cmd").
289pub fn shell_name() -> String {
290    let shell = detect_shell();
291    let basename = std::path::Path::new(&shell)
292        .file_name()
293        .and_then(|n| n.to_str())
294        .unwrap_or("sh")
295        .to_ascii_lowercase();
296    basename
297        .strip_suffix(".exe")
298        .unwrap_or(&basename)
299        .to_string()
300}
301
302/// Wrap a command to disable zsh `nomatch` and `equals` (GH #1439, #1448).
303/// - `nomatch`: zsh aborts when unquoted globs match no files; POSIX passes
304///   the word through unchanged. Agents emit `--include=*.go` etc.
305/// - `equals`: zsh expands `=foo` to the path of the `foo` binary, so
306///   `echo ===` fails with "= not found". Agents use `===` as separators.
307pub(crate) fn zsh_safe_command(command: &str, shell: &str) -> String {
308    if cfg!(unix) {
309        let basename = std::path::Path::new(shell)
310            .file_name()
311            .and_then(|n| n.to_str())
312            .unwrap_or("");
313        if basename == "zsh" {
314            return format!("setopt nonomatch noequals; {command}");
315        }
316    }
317    command.to_string()
318}
319
320pub(super) fn detect_shell() -> String {
321    if let Ok(shell) = std::env::var("LEAN_CTX_SHELL") {
322        return shell;
323    }
324
325    if let Ok(shell) = std::env::var("SHELL") {
326        let bin = std::path::Path::new(&shell)
327            .file_name()
328            .and_then(|n| n.to_str())
329            .unwrap_or("sh");
330
331        if bin == "lean-ctx" {
332            return find_real_shell();
333        }
334        // #451: `$SHELL` is the user's *interactive* shell preference, not the
335        // agent's execution shell. Agents emit bash/POSIX command syntax, so an
336        // interactive-only shell like Nushell or Fish silently mis-runs it.
337        // Honor `$SHELL` only when it is POSIX-compatible; otherwise fall back
338        // to a real POSIX shell (deterministic, agent-trained). Set
339        // `LEAN_CTX_SHELL` to force a specific shell regardless of this gate.
340        if shell_acceptable_for_exec(&shell) {
341            return shell;
342        }
343        return find_real_shell();
344    }
345
346    find_real_shell()
347}
348
349/// Whether a `$SHELL` value may be auto-selected as the command-execution shell.
350///
351/// On Unix this rejects non-POSIX interactive shells (Nushell, Fish, Elvish,
352/// xonsh, PowerShell) so lean-ctx never feeds them bash/POSIX syntax (#451). On
353/// Windows the intended shells *are* PowerShell/cmd, so any `$SHELL` is honored
354/// (the POSIX gate would wrongly reject them).
355#[cfg(unix)]
356fn shell_acceptable_for_exec(shell: &str) -> bool {
357    is_posix_compatible_shell(shell)
358}
359
360#[cfg(windows)]
361fn shell_acceptable_for_exec(_shell: &str) -> bool {
362    true
363}
364
365/// `true` if `shell`'s basename is a POSIX-compatible shell that can run
366/// agent-authored bash/POSIX commands. Excludes interactive-only shells
367/// (`nu`, `fish`, `elvish`, `xonsh`) and non-POSIX shells (`pwsh`,
368/// `powershell`, `cmd`) where that syntax fails (#451).
369#[cfg(unix)]
370fn is_posix_compatible_shell(shell: &str) -> bool {
371    let name = std::path::Path::new(shell)
372        .file_name()
373        .and_then(|n| n.to_str())
374        .unwrap_or("")
375        .to_ascii_lowercase();
376    let name = name.strip_suffix(".exe").unwrap_or(&name);
377    matches!(
378        name,
379        "bash" | "zsh" | "sh" | "dash" | "ash" | "ksh" | "ksh93" | "mksh" | "busybox"
380    )
381}
382
383#[cfg(unix)]
384fn find_real_shell() -> String {
385    for shell in &["/bin/zsh", "/bin/bash", "/bin/sh"] {
386        if std::path::Path::new(shell).exists() {
387            return shell.to_string();
388        }
389    }
390    "/bin/sh".to_string()
391}
392
393#[cfg(windows)]
394fn find_real_shell() -> String {
395    if is_running_in_msys_or_gitbash() {
396        for candidate in &["bash.exe", "sh.exe"] {
397            if let Ok(output) = std::process::Command::new("where").arg(candidate).output() {
398                if output.status.success() {
399                    if let Ok(path) = String::from_utf8(output.stdout) {
400                        if let Some(first_line) = path.lines().next() {
401                            let trimmed = first_line.trim();
402                            if !trimmed.is_empty() {
403                                return trimmed.to_string();
404                            }
405                        }
406                    }
407                }
408            }
409        }
410    }
411    if let Ok(pwsh) = which_powershell() {
412        return pwsh;
413    }
414    if let Ok(comspec) = std::env::var("COMSPEC") {
415        return comspec;
416    }
417    "cmd.exe".to_string()
418}
419
420#[cfg(windows)]
421fn is_running_in_msys_or_gitbash() -> bool {
422    std::env::var("MSYSTEM").is_ok() || std::env::var("MINGW_PREFIX").is_ok()
423}
424
425#[cfg(windows)]
426fn which_powershell() -> Result<String, ()> {
427    for candidate in &["pwsh.exe", "powershell.exe"] {
428        if let Ok(output) = std::process::Command::new("where").arg(candidate).output() {
429            if output.status.success() {
430                if let Ok(path) = String::from_utf8(output.stdout) {
431                    if let Some(first_line) = path.lines().next() {
432                        let trimmed = first_line.trim();
433                        if !trimmed.is_empty() {
434                            return Ok(trimmed.to_string());
435                        }
436                    }
437                }
438            }
439        }
440    }
441    Err(())
442}
443
444/// Join multiple CLI arguments into a single command string, using quoting
445/// conventions appropriate for the detected shell.
446///
447/// On Unix, this always produces POSIX-compatible quoting.
448/// On Windows, the quoting adapts to the actual shell (PowerShell, cmd.exe,
449/// or Git Bash / MSYS).
450pub fn join_command(args: &[String]) -> String {
451    let (_, flag) = shell_and_flag();
452    join_command_for(args, &flag)
453}
454
455pub fn join_command_for(args: &[String], shell_flag: &str) -> String {
456    match shell_flag {
457        "-Command" => join_powershell(args),
458        "/C" => join_cmd(args),
459        _ => join_posix(args),
460    }
461}
462
463fn join_posix(args: &[String]) -> String {
464    args.iter()
465        .map(|a| quote_posix(a))
466        .collect::<Vec<_>>()
467        .join(" ")
468}
469
470fn join_powershell(args: &[String]) -> String {
471    if args.len() == 1 && args[0].contains(' ') {
472        return args[0].clone();
473    }
474    let quoted: Vec<String> = args.iter().map(|a| quote_powershell(a)).collect();
475    format!("& {}", quoted.join(" "))
476}
477
478fn join_cmd(args: &[String]) -> String {
479    args.iter()
480        .map(|a| quote_cmd(a))
481        .collect::<Vec<_>>()
482        .join(" ")
483}
484
485fn quote_posix(s: &str) -> String {
486    if s.is_empty() {
487        return "''".to_string();
488    }
489    if s.bytes()
490        .all(|b| b.is_ascii_alphanumeric() || b"-_./=:@,+%^".contains(&b))
491    {
492        return s.to_string();
493    }
494    format!("'{}'", s.replace('\'', "'\\''"))
495}
496
497fn quote_powershell(s: &str) -> String {
498    if s.is_empty() {
499        return "''".to_string();
500    }
501    if s.bytes()
502        .all(|b| b.is_ascii_alphanumeric() || b"-_./=:@,+%^".contains(&b))
503    {
504        return s.to_string();
505    }
506    format!("'{}'", s.replace('\'', "''"))
507}
508
509fn quote_cmd(s: &str) -> String {
510    if s.is_empty() {
511        return "\"\"".to_string();
512    }
513    if s.bytes()
514        .all(|b| b.is_ascii_alphanumeric() || b"-_./=:@,+%^\\".contains(&b))
515    {
516        return s.to_string();
517    }
518    format!("\"{}\"", s.replace('"', "\\\""))
519}
520
521#[cfg(test)]
522mod join_command_tests {
523    use super::*;
524
525    #[test]
526    fn posix_simple_args() {
527        let args: Vec<String> = vec!["git".into(), "status".into()];
528        assert_eq!(join_command_for(&args, "-c"), "git status");
529    }
530
531    #[test]
532    fn posix_path_with_spaces() {
533        let args: Vec<String> = vec!["/usr/local/my app/bin".into(), "--help".into()];
534        assert_eq!(
535            join_command_for(&args, "-c"),
536            "'/usr/local/my app/bin' --help"
537        );
538    }
539
540    #[test]
541    fn posix_single_quotes_escaped() {
542        let args: Vec<String> = vec!["echo".into(), "it's".into()];
543        assert_eq!(join_command_for(&args, "-c"), "echo 'it'\\''s'");
544    }
545
546    #[test]
547    fn posix_empty_arg() {
548        let args: Vec<String> = vec!["cmd".into(), String::new()];
549        assert_eq!(join_command_for(&args, "-c"), "cmd ''");
550    }
551
552    #[test]
553    fn powershell_simple_args() {
554        let args: Vec<String> = vec!["npm".into(), "install".into()];
555        assert_eq!(join_command_for(&args, "-Command"), "& npm install");
556    }
557
558    #[test]
559    fn powershell_path_with_spaces() {
560        let args: Vec<String> = vec![
561            "C:\\Program Files\\nodejs\\npm.cmd".into(),
562            "install".into(),
563        ];
564        assert_eq!(
565            join_command_for(&args, "-Command"),
566            "& 'C:\\Program Files\\nodejs\\npm.cmd' install"
567        );
568    }
569
570    #[test]
571    fn powershell_single_quotes_escaped() {
572        let args: Vec<String> = vec!["echo".into(), "it's done".into()];
573        assert_eq!(join_command_for(&args, "-Command"), "& echo 'it''s done'");
574    }
575
576    #[test]
577    fn cmd_simple_args() {
578        let args: Vec<String> = vec!["npm.cmd".into(), "install".into()];
579        assert_eq!(join_command_for(&args, "/C"), "npm.cmd install");
580    }
581
582    #[test]
583    fn cmd_path_with_spaces() {
584        let args: Vec<String> = vec![
585            "C:\\Program Files\\nodejs\\npm.cmd".into(),
586            "install".into(),
587        ];
588        assert_eq!(
589            join_command_for(&args, "/C"),
590            "\"C:\\Program Files\\nodejs\\npm.cmd\" install"
591        );
592    }
593
594    #[test]
595    fn cmd_double_quotes_escaped() {
596        let args: Vec<String> = vec!["echo".into(), "say \"hello\"".into()];
597        assert_eq!(join_command_for(&args, "/C"), "echo \"say \\\"hello\\\"\"");
598    }
599
600    #[test]
601    fn unknown_flag_uses_posix() {
602        let args: Vec<String> = vec!["ls".into(), "-la".into()];
603        assert_eq!(join_command_for(&args, "--exec"), "ls -la");
604    }
605
606    #[test]
607    fn powershell_single_full_command_not_quoted() {
608        let args: Vec<String> = vec!["git commit -m \"feat: add feature\"".into()];
609        let result = join_command_for(&args, "-Command");
610        assert_eq!(result, "git commit -m \"feat: add feature\"");
611        assert!(
612            !result.starts_with("& '"),
613            "must not wrap full command in & '...'"
614        );
615    }
616
617    #[test]
618    fn powershell_single_no_spaces_still_uses_call_operator() {
619        let args: Vec<String> = vec!["git".into()];
620        assert_eq!(join_command_for(&args, "-Command"), "& git");
621    }
622}
623
624#[cfg(test)]
625mod is_powershell_tests {
626    use super::is_powershell;
627
628    #[test]
629    fn detects_pwsh_exe() {
630        assert!(is_powershell("pwsh.exe"));
631    }
632
633    #[test]
634    fn detects_powershell_exe() {
635        assert!(is_powershell("powershell.exe"));
636    }
637
638    #[test]
639    fn rejects_cmd() {
640        assert!(!is_powershell("cmd.exe"));
641    }
642
643    #[test]
644    fn rejects_bash() {
645        assert!(!is_powershell("/usr/bin/bash"));
646    }
647
648    #[test]
649    fn case_insensitive() {
650        assert!(is_powershell("PWSH.EXE"));
651        assert!(is_powershell("PowerShell.exe"));
652    }
653
654    #[test]
655    fn full_path_with_pwsh() {
656        assert!(is_powershell(
657            "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
658        ));
659        assert!(is_powershell("/usr/local/bin/pwsh"));
660    }
661}
662
663#[cfg(test)]
664mod powershell_profile_tests {
665    use super::{powershell_profile_path, resolve_powershell_profile_path};
666    use std::path::Path;
667
668    #[test]
669    fn always_ends_with_profile_file() {
670        let p = powershell_profile_path(Path::new("/home/u"));
671        assert!(p.ends_with("Microsoft.PowerShell_profile.ps1"));
672    }
673
674    #[cfg(not(windows))]
675    #[test]
676    fn non_windows_uses_config_powershell_never_documents() {
677        // #356: stat-ing anything under ~/Documents pops a macOS TCC prompt, so the
678        // non-Windows profile path must live under ~/.config/powershell instead.
679        let p = powershell_profile_path(Path::new("/Users/jane"));
680        assert_eq!(
681            p,
682            Path::new("/Users/jane/.config/powershell/Microsoft.PowerShell_profile.ps1")
683        );
684        assert!(
685            !p.to_string_lossy().contains("Documents"),
686            "macOS/Linux PowerShell profile must never touch ~/Documents (#356)"
687        );
688    }
689
690    #[cfg(windows)]
691    #[test]
692    fn windows_uses_documents_powershell() {
693        let p = powershell_profile_path(Path::new("C:\\Users\\jane"));
694        assert!(p.ends_with("Documents\\PowerShell\\Microsoft.PowerShell_profile.ps1"));
695    }
696
697    #[cfg(not(windows))]
698    #[test]
699    fn resolver_matches_static_default_on_non_windows() {
700        // Non-Windows never spawns a process: the resolver returns the static config
701        // path verbatim (and must never touch ~/Documents, #356).
702        let home = Path::new("/Users/jane");
703        assert_eq!(
704            resolve_powershell_profile_path(home),
705            powershell_profile_path(home)
706        );
707    }
708
709    #[cfg(windows)]
710    #[test]
711    fn resolver_returns_absolute_profile_on_windows() {
712        // On Windows the resolver asks PowerShell for the live $PROFILE (OneDrive-safe,
713        // #558); whether it queries successfully or falls back, the result is an
714        // absolute path to the profile file.
715        let p = resolve_powershell_profile_path(Path::new("C:\\Users\\jane"));
716        assert!(p.is_absolute(), "resolved profile must be absolute: {p:?}");
717        assert!(p.ends_with("Microsoft.PowerShell_profile.ps1"));
718    }
719}
720
721#[cfg(test)]
722mod windows_shell_flag_tests {
723    use super::windows_shell_flag_for_exe_basename;
724
725    #[test]
726    fn cmd_uses_slash_c() {
727        assert_eq!(windows_shell_flag_for_exe_basename("cmd.exe"), "/C");
728        assert_eq!(windows_shell_flag_for_exe_basename("cmd"), "/C");
729    }
730
731    #[test]
732    fn powershell_uses_command() {
733        assert_eq!(
734            windows_shell_flag_for_exe_basename("powershell.exe"),
735            "-Command"
736        );
737        assert_eq!(windows_shell_flag_for_exe_basename("pwsh.exe"), "-Command");
738    }
739
740    #[test]
741    fn posix_shells_use_dash_c() {
742        assert_eq!(windows_shell_flag_for_exe_basename("bash.exe"), "-c");
743        assert_eq!(windows_shell_flag_for_exe_basename("bash"), "-c");
744        assert_eq!(windows_shell_flag_for_exe_basename("sh.exe"), "-c");
745        assert_eq!(windows_shell_flag_for_exe_basename("zsh.exe"), "-c");
746        assert_eq!(windows_shell_flag_for_exe_basename("fish.exe"), "-c");
747    }
748}
749
750#[cfg(test)]
751mod platform_tests {
752    #[test]
753    fn is_container_returns_bool() {
754        let _ = super::is_container();
755    }
756
757    #[test]
758    fn is_non_interactive_returns_bool() {
759        let _ = super::is_non_interactive();
760    }
761
762    #[test]
763    fn join_command_preserves_structure() {
764        let args = vec![
765            "git".to_string(),
766            "commit".to_string(),
767            "-m".to_string(),
768            "my message".to_string(),
769        ];
770        let joined = super::join_command(&args);
771        assert!(joined.contains("git"));
772        assert!(joined.contains("commit"));
773        assert!(joined.contains("my message") || joined.contains("'my message'"));
774    }
775
776    #[test]
777    fn quote_posix_handles_em_dash() {
778        let result = super::quote_posix("closing — see #407");
779        assert!(
780            result.starts_with('\''),
781            "em-dash args must be single-quoted: {result}"
782        );
783    }
784
785    #[test]
786    fn quote_posix_handles_nested_single_quotes() {
787        let result = super::quote_posix("it's a test");
788        assert!(
789            result.contains("\\'"),
790            "single quotes must be escaped: {result}"
791        );
792    }
793
794    #[test]
795    fn quote_posix_safe_chars_unquoted() {
796        let result = super::quote_posix("simple_word");
797        assert_eq!(result, "simple_word");
798    }
799
800    #[test]
801    fn quote_posix_empty_string() {
802        let result = super::quote_posix("");
803        assert_eq!(result, "''");
804    }
805
806    #[test]
807    fn quote_posix_dollar_expansion_protected() {
808        let result = super::quote_posix("$HOME/test");
809        assert!(
810            result.starts_with('\''),
811            "dollar signs must be single-quoted: {result}"
812        );
813    }
814
815    #[test]
816    fn quote_posix_backtick_protected() {
817        let result = super::quote_posix("echo `date`");
818        assert!(
819            result.starts_with('\''),
820            "backticks must be single-quoted: {result}"
821        );
822    }
823
824    #[test]
825    fn quote_posix_double_quotes_protected() {
826        let result = super::quote_posix(r#"he said "hello""#);
827        assert!(
828            result.starts_with('\''),
829            "double quotes must be single-quoted: {result}"
830        );
831    }
832
833    // #451: a non-interactive `bash -c` sources $BASH_ENV. lean-ctx must run
834    // profile-free, so `apply_profile_free_env` has to neutralize an inherited
835    // BASH_ENV before it can pull in a contaminating startup file.
836    #[cfg(unix)]
837    #[test]
838    fn profile_free_env_blocks_bash_env_contamination() {
839        let Some(bash) = ["/bin/bash", "/usr/bin/bash", "/usr/local/bin/bash"]
840            .into_iter()
841            .find(|p| std::path::Path::new(p).exists())
842        else {
843            return; // no bash on this host → nothing to guard against
844        };
845
846        let startup = std::env::temp_dir().join(format!(
847            "lean_ctx_bashenv_{}_{}.sh",
848            std::process::id(),
849            "guard"
850        ));
851        std::fs::write(&startup, "echo CONTAMINATED\n").expect("write startup file");
852
853        let mut cmd = std::process::Command::new(bash);
854        cmd.arg("-c").arg("echo clean").env("BASH_ENV", &startup);
855        super::apply_profile_free_env(&mut cmd);
856        let out = cmd.output().expect("run bash");
857        let stdout = String::from_utf8_lossy(&out.stdout);
858
859        let _ = std::fs::remove_file(&startup);
860
861        assert!(stdout.contains("clean"), "command output missing: {stdout}");
862        assert!(
863            !stdout.contains("CONTAMINATED"),
864            "apply_profile_free_env must neutralize BASH_ENV, got: {stdout}"
865        );
866    }
867}
868
869#[cfg(all(test, unix))]
870mod posix_shell_gate_tests {
871    use super::{detect_shell, is_posix_compatible_shell};
872
873    #[test]
874    fn accepts_posix_shells() {
875        for s in [
876            "/bin/bash",
877            "/bin/zsh",
878            "/bin/sh",
879            "/usr/bin/dash",
880            "/bin/ash",
881            "/usr/bin/ksh",
882            "/usr/bin/mksh",
883            "bash",
884            "zsh",
885        ] {
886            assert!(is_posix_compatible_shell(s), "{s} must be POSIX-compatible");
887        }
888    }
889
890    #[test]
891    fn rejects_interactive_and_nonposix_shells() {
892        // #451: agent bash/POSIX syntax fails in these — never auto-select them.
893        for s in [
894            "/usr/bin/nu",
895            "/opt/homebrew/bin/nu",
896            "/usr/bin/fish",
897            "/usr/local/bin/elvish",
898            "/usr/bin/xonsh",
899            "/usr/bin/pwsh",
900            "powershell.exe",
901            "cmd.exe",
902        ] {
903            assert!(
904                !is_posix_compatible_shell(s),
905                "{s} must be rejected by the POSIX gate"
906            );
907        }
908    }
909
910    #[test]
911    #[cfg_attr(miri, ignore)]
912    fn detect_shell_falls_back_when_shell_is_nushell() {
913        // Serialize env mutation (set_var/remove_var are process-global).
914        let _lock = crate::core::data_dir::test_env_lock();
915        let saved_shell = std::env::var_os("SHELL");
916        let saved_override = std::env::var_os("LEAN_CTX_SHELL");
917
918        crate::test_env::remove_var("LEAN_CTX_SHELL");
919        crate::test_env::set_var("SHELL", "/usr/bin/nu");
920        let resolved = detect_shell();
921        assert!(
922            is_posix_compatible_shell(&resolved),
923            "a non-POSIX $SHELL (nu) must resolve to a POSIX shell, got {resolved}"
924        );
925        assert!(
926            !resolved.ends_with("/nu") && resolved != "/usr/bin/nu",
927            "must not run agent commands in Nushell, got {resolved}"
928        );
929
930        // A POSIX $SHELL is honored verbatim.
931        crate::test_env::set_var("SHELL", "/bin/sh");
932        assert_eq!(detect_shell(), "/bin/sh");
933
934        // LEAN_CTX_SHELL always wins, even when pointing at a non-POSIX shell.
935        crate::test_env::set_var("LEAN_CTX_SHELL", "/usr/bin/nu");
936        assert_eq!(detect_shell(), "/usr/bin/nu");
937
938        match saved_shell {
939            Some(v) => crate::test_env::set_var("SHELL", v),
940            None => crate::test_env::remove_var("SHELL"),
941        }
942        match saved_override {
943            Some(v) => crate::test_env::set_var("LEAN_CTX_SHELL", v),
944            None => crate::test_env::remove_var("LEAN_CTX_SHELL"),
945        }
946    }
947}
948
949#[cfg(test)]
950mod carriage_return_tests {
951    use super::resolve_carriage_returns;
952
953    #[test]
954    fn no_cr_passthrough() {
955        assert_eq!(resolve_carriage_returns("hello\nworld\n"), "hello\nworld\n");
956    }
957
958    #[test]
959    fn progress_overwrite_keeps_last_segment() {
960        assert_eq!(resolve_carriage_returns("first\rsecond"), "second");
961    }
962
963    #[test]
964    fn git_rebase_progress() {
965        let input = "Rebasing (1/1)\rSuccessfully rebased and updated refs/heads/feat.";
966        assert_eq!(
967            resolve_carriage_returns(input),
968            "Successfully rebased and updated refs/heads/feat."
969        );
970    }
971
972    #[test]
973    fn crlf_line_endings_stripped() {
974        assert_eq!(
975            resolve_carriage_returns("line1\r\nline2\r\n"),
976            "line1\nline2\n"
977        );
978    }
979
980    #[test]
981    fn multiple_cr_on_one_line() {
982        assert_eq!(resolve_carriage_returns("a\rb\rc"), "c");
983    }
984
985    #[test]
986    fn mixed_lines() {
987        let input = "clean line\nprogress\rdone\nalso clean\n";
988        assert_eq!(
989            resolve_carriage_returns(input),
990            "clean line\ndone\nalso clean\n"
991        );
992    }
993
994    #[test]
995    fn trailing_cr_stripped_as_crlf() {
996        assert_eq!(resolve_carriage_returns("visible\r"), "visible");
997    }
998
999    #[test]
1000    fn empty_string_passthrough() {
1001        assert_eq!(resolve_carriage_returns(""), "");
1002    }
1003}
1004
1005#[cfg(test)]
1006mod zsh_safe_tests {
1007    use super::zsh_safe_command;
1008
1009    #[test]
1010    #[cfg(unix)]
1011    fn prepends_nonomatch_noequals_for_zsh() {
1012        let cmd = zsh_safe_command("grep --include=*.go pattern", "/bin/zsh");
1013        assert_eq!(
1014            cmd,
1015            "setopt nonomatch noequals; grep --include=*.go pattern"
1016        );
1017    }
1018
1019    #[test]
1020    #[cfg(unix)]
1021    fn prepends_nonomatch_noequals_for_usr_bin_zsh() {
1022        let cmd = zsh_safe_command("echo *.rs", "/usr/bin/zsh");
1023        assert_eq!(cmd, "setopt nonomatch noequals; echo *.rs");
1024    }
1025
1026    #[test]
1027    #[cfg(unix)]
1028    fn equals_separator_safe_under_zsh() {
1029        let cmd = zsh_safe_command("echo ===", "/bin/zsh");
1030        assert!(cmd.starts_with("setopt nonomatch noequals;"));
1031        assert!(cmd.contains("echo ==="));
1032    }
1033
1034    #[test]
1035    fn passthrough_for_bash() {
1036        let cmd = zsh_safe_command("grep --include=*.go pattern", "/bin/bash");
1037        assert_eq!(cmd, "grep --include=*.go pattern");
1038    }
1039
1040    #[test]
1041    fn passthrough_for_sh() {
1042        let cmd = zsh_safe_command("find -name *.ts", "/bin/sh");
1043        assert_eq!(cmd, "find -name *.ts");
1044    }
1045}