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    // Unlike POSIX, `@` (splatting, `@(…)`) and `,` (array operator) are
502    // syntax in PowerShell, so they are not safe bare (#1848).
503    if s.bytes()
504        .all(|b| b.is_ascii_alphanumeric() || b"-_./=:+%^".contains(&b))
505    {
506        return s.to_string();
507    }
508    format!("'{}'", s.replace('\'', "''"))
509}
510
511fn quote_cmd(s: &str) -> String {
512    if s.is_empty() {
513        return "\"\"".to_string();
514    }
515    if s.bytes()
516        .all(|b| b.is_ascii_alphanumeric() || b"-_./=:@,+%^\\".contains(&b))
517    {
518        return s.to_string();
519    }
520    format!("\"{}\"", s.replace('"', "\\\""))
521}
522
523#[cfg(test)]
524mod join_command_tests {
525    use super::*;
526
527    #[test]
528    fn posix_simple_args() {
529        let args: Vec<String> = vec!["git".into(), "status".into()];
530        assert_eq!(join_command_for(&args, "-c"), "git status");
531    }
532
533    #[test]
534    fn posix_path_with_spaces() {
535        let args: Vec<String> = vec!["/usr/local/my app/bin".into(), "--help".into()];
536        assert_eq!(
537            join_command_for(&args, "-c"),
538            "'/usr/local/my app/bin' --help"
539        );
540    }
541
542    #[test]
543    fn posix_single_quotes_escaped() {
544        let args: Vec<String> = vec!["echo".into(), "it's".into()];
545        assert_eq!(join_command_for(&args, "-c"), "echo 'it'\\''s'");
546    }
547
548    #[test]
549    fn posix_empty_arg() {
550        let args: Vec<String> = vec!["cmd".into(), String::new()];
551        assert_eq!(join_command_for(&args, "-c"), "cmd ''");
552    }
553
554    #[test]
555    fn powershell_simple_args() {
556        let args: Vec<String> = vec!["npm".into(), "install".into()];
557        assert_eq!(join_command_for(&args, "-Command"), "& npm install");
558    }
559
560    #[test]
561    fn powershell_path_with_spaces() {
562        let args: Vec<String> = vec![
563            "C:\\Program Files\\nodejs\\npm.cmd".into(),
564            "install".into(),
565        ];
566        assert_eq!(
567            join_command_for(&args, "-Command"),
568            "& 'C:\\Program Files\\nodejs\\npm.cmd' install"
569        );
570    }
571
572    #[test]
573    fn powershell_single_quotes_escaped() {
574        let args: Vec<String> = vec!["echo".into(), "it's done".into()];
575        assert_eq!(join_command_for(&args, "-Command"), "& echo 'it''s done'");
576    }
577
578    #[test]
579    fn powershell_quotes_splat_and_array_syntax() {
580        let args: Vec<String> = vec!["echo".into(), "@args".into(), "a,b".into()];
581        assert_eq!(join_command_for(&args, "-Command"), "& echo '@args' 'a,b'");
582    }
583
584    #[test]
585    fn cmd_simple_args() {
586        let args: Vec<String> = vec!["npm.cmd".into(), "install".into()];
587        assert_eq!(join_command_for(&args, "/C"), "npm.cmd install");
588    }
589
590    #[test]
591    fn cmd_path_with_spaces() {
592        let args: Vec<String> = vec![
593            "C:\\Program Files\\nodejs\\npm.cmd".into(),
594            "install".into(),
595        ];
596        assert_eq!(
597            join_command_for(&args, "/C"),
598            "\"C:\\Program Files\\nodejs\\npm.cmd\" install"
599        );
600    }
601
602    #[test]
603    fn cmd_double_quotes_escaped() {
604        let args: Vec<String> = vec!["echo".into(), "say \"hello\"".into()];
605        assert_eq!(join_command_for(&args, "/C"), "echo \"say \\\"hello\\\"\"");
606    }
607
608    #[test]
609    fn unknown_flag_uses_posix() {
610        let args: Vec<String> = vec!["ls".into(), "-la".into()];
611        assert_eq!(join_command_for(&args, "--exec"), "ls -la");
612    }
613
614    #[test]
615    fn powershell_single_full_command_not_quoted() {
616        let args: Vec<String> = vec!["git commit -m \"feat: add feature\"".into()];
617        let result = join_command_for(&args, "-Command");
618        assert_eq!(result, "git commit -m \"feat: add feature\"");
619        assert!(
620            !result.starts_with("& '"),
621            "must not wrap full command in & '...'"
622        );
623    }
624
625    #[test]
626    fn powershell_single_no_spaces_still_uses_call_operator() {
627        let args: Vec<String> = vec!["git".into()];
628        assert_eq!(join_command_for(&args, "-Command"), "& git");
629    }
630}
631
632#[cfg(test)]
633mod is_powershell_tests {
634    use super::is_powershell;
635
636    #[test]
637    fn detects_pwsh_exe() {
638        assert!(is_powershell("pwsh.exe"));
639    }
640
641    #[test]
642    fn detects_powershell_exe() {
643        assert!(is_powershell("powershell.exe"));
644    }
645
646    #[test]
647    fn rejects_cmd() {
648        assert!(!is_powershell("cmd.exe"));
649    }
650
651    #[test]
652    fn rejects_bash() {
653        assert!(!is_powershell("/usr/bin/bash"));
654    }
655
656    #[test]
657    fn case_insensitive() {
658        assert!(is_powershell("PWSH.EXE"));
659        assert!(is_powershell("PowerShell.exe"));
660    }
661
662    #[test]
663    fn full_path_with_pwsh() {
664        assert!(is_powershell(
665            "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
666        ));
667        assert!(is_powershell("/usr/local/bin/pwsh"));
668    }
669}
670
671#[cfg(test)]
672mod powershell_profile_tests {
673    use super::{powershell_profile_path, resolve_powershell_profile_path};
674    use std::path::Path;
675
676    #[test]
677    fn always_ends_with_profile_file() {
678        let p = powershell_profile_path(Path::new("/home/u"));
679        assert!(p.ends_with("Microsoft.PowerShell_profile.ps1"));
680    }
681
682    #[cfg(not(windows))]
683    #[test]
684    fn non_windows_uses_config_powershell_never_documents() {
685        // #356: stat-ing anything under ~/Documents pops a macOS TCC prompt, so the
686        // non-Windows profile path must live under ~/.config/powershell instead.
687        let p = powershell_profile_path(Path::new("/Users/jane"));
688        assert_eq!(
689            p,
690            Path::new("/Users/jane/.config/powershell/Microsoft.PowerShell_profile.ps1")
691        );
692        assert!(
693            !p.to_string_lossy().contains("Documents"),
694            "macOS/Linux PowerShell profile must never touch ~/Documents (#356)"
695        );
696    }
697
698    #[cfg(windows)]
699    #[test]
700    fn windows_uses_documents_powershell() {
701        let p = powershell_profile_path(Path::new("C:\\Users\\jane"));
702        assert!(p.ends_with("Documents\\PowerShell\\Microsoft.PowerShell_profile.ps1"));
703    }
704
705    #[cfg(not(windows))]
706    #[test]
707    fn resolver_matches_static_default_on_non_windows() {
708        // Non-Windows never spawns a process: the resolver returns the static config
709        // path verbatim (and must never touch ~/Documents, #356).
710        let home = Path::new("/Users/jane");
711        assert_eq!(
712            resolve_powershell_profile_path(home),
713            powershell_profile_path(home)
714        );
715    }
716
717    #[cfg(windows)]
718    #[test]
719    fn resolver_returns_absolute_profile_on_windows() {
720        // On Windows the resolver asks PowerShell for the live $PROFILE (OneDrive-safe,
721        // #558); whether it queries successfully or falls back, the result is an
722        // absolute path to the profile file.
723        let p = resolve_powershell_profile_path(Path::new("C:\\Users\\jane"));
724        assert!(p.is_absolute(), "resolved profile must be absolute: {p:?}");
725        assert!(p.ends_with("Microsoft.PowerShell_profile.ps1"));
726    }
727}
728
729#[cfg(test)]
730mod windows_shell_flag_tests {
731    use super::windows_shell_flag_for_exe_basename;
732
733    #[test]
734    fn cmd_uses_slash_c() {
735        assert_eq!(windows_shell_flag_for_exe_basename("cmd.exe"), "/C");
736        assert_eq!(windows_shell_flag_for_exe_basename("cmd"), "/C");
737    }
738
739    #[test]
740    fn powershell_uses_command() {
741        assert_eq!(
742            windows_shell_flag_for_exe_basename("powershell.exe"),
743            "-Command"
744        );
745        assert_eq!(windows_shell_flag_for_exe_basename("pwsh.exe"), "-Command");
746    }
747
748    #[test]
749    fn posix_shells_use_dash_c() {
750        assert_eq!(windows_shell_flag_for_exe_basename("bash.exe"), "-c");
751        assert_eq!(windows_shell_flag_for_exe_basename("bash"), "-c");
752        assert_eq!(windows_shell_flag_for_exe_basename("sh.exe"), "-c");
753        assert_eq!(windows_shell_flag_for_exe_basename("zsh.exe"), "-c");
754        assert_eq!(windows_shell_flag_for_exe_basename("fish.exe"), "-c");
755    }
756}
757
758#[cfg(test)]
759mod platform_tests {
760    #[test]
761    fn is_container_returns_bool() {
762        let _ = super::is_container();
763    }
764
765    #[test]
766    fn is_non_interactive_returns_bool() {
767        let _ = super::is_non_interactive();
768    }
769
770    #[test]
771    fn join_command_preserves_structure() {
772        let args = vec![
773            "git".to_string(),
774            "commit".to_string(),
775            "-m".to_string(),
776            "my message".to_string(),
777        ];
778        let joined = super::join_command(&args);
779        assert!(joined.contains("git"));
780        assert!(joined.contains("commit"));
781        assert!(joined.contains("my message") || joined.contains("'my message'"));
782    }
783
784    #[test]
785    fn quote_posix_handles_em_dash() {
786        let result = super::quote_posix("closing — see #407");
787        assert!(
788            result.starts_with('\''),
789            "em-dash args must be single-quoted: {result}"
790        );
791    }
792
793    #[test]
794    fn quote_posix_handles_nested_single_quotes() {
795        let result = super::quote_posix("it's a test");
796        assert!(
797            result.contains("\\'"),
798            "single quotes must be escaped: {result}"
799        );
800    }
801
802    #[test]
803    fn quote_posix_safe_chars_unquoted() {
804        let result = super::quote_posix("simple_word");
805        assert_eq!(result, "simple_word");
806    }
807
808    #[test]
809    fn quote_posix_empty_string() {
810        let result = super::quote_posix("");
811        assert_eq!(result, "''");
812    }
813
814    #[test]
815    fn quote_posix_dollar_expansion_protected() {
816        let result = super::quote_posix("$HOME/test");
817        assert!(
818            result.starts_with('\''),
819            "dollar signs must be single-quoted: {result}"
820        );
821    }
822
823    #[test]
824    fn quote_posix_backtick_protected() {
825        let result = super::quote_posix("echo `date`");
826        assert!(
827            result.starts_with('\''),
828            "backticks must be single-quoted: {result}"
829        );
830    }
831
832    #[test]
833    fn quote_posix_double_quotes_protected() {
834        let result = super::quote_posix(r#"he said "hello""#);
835        assert!(
836            result.starts_with('\''),
837            "double quotes must be single-quoted: {result}"
838        );
839    }
840
841    // #451: a non-interactive `bash -c` sources $BASH_ENV. lean-ctx must run
842    // profile-free, so `apply_profile_free_env` has to neutralize an inherited
843    // BASH_ENV before it can pull in a contaminating startup file.
844    #[cfg(unix)]
845    #[test]
846    fn profile_free_env_blocks_bash_env_contamination() {
847        let Some(bash) = ["/bin/bash", "/usr/bin/bash", "/usr/local/bin/bash"]
848            .into_iter()
849            .find(|p| std::path::Path::new(p).exists())
850        else {
851            return; // no bash on this host → nothing to guard against
852        };
853
854        let startup = std::env::temp_dir().join(format!(
855            "lean_ctx_bashenv_{}_{}.sh",
856            std::process::id(),
857            "guard"
858        ));
859        std::fs::write(&startup, "echo CONTAMINATED\n").expect("write startup file");
860
861        let mut cmd = std::process::Command::new(bash);
862        cmd.arg("-c").arg("echo clean").env("BASH_ENV", &startup);
863        super::apply_profile_free_env(&mut cmd);
864        let out = cmd.output().expect("run bash");
865        let stdout = String::from_utf8_lossy(&out.stdout);
866
867        let _ = std::fs::remove_file(&startup);
868
869        assert!(stdout.contains("clean"), "command output missing: {stdout}");
870        assert!(
871            !stdout.contains("CONTAMINATED"),
872            "apply_profile_free_env must neutralize BASH_ENV, got: {stdout}"
873        );
874    }
875}
876
877#[cfg(all(test, unix))]
878mod posix_shell_gate_tests {
879    use super::{detect_shell, is_posix_compatible_shell};
880
881    #[test]
882    fn accepts_posix_shells() {
883        for s in [
884            "/bin/bash",
885            "/bin/zsh",
886            "/bin/sh",
887            "/usr/bin/dash",
888            "/bin/ash",
889            "/usr/bin/ksh",
890            "/usr/bin/mksh",
891            "bash",
892            "zsh",
893        ] {
894            assert!(is_posix_compatible_shell(s), "{s} must be POSIX-compatible");
895        }
896    }
897
898    #[test]
899    fn rejects_interactive_and_nonposix_shells() {
900        // #451: agent bash/POSIX syntax fails in these — never auto-select them.
901        for s in [
902            "/usr/bin/nu",
903            "/opt/homebrew/bin/nu",
904            "/usr/bin/fish",
905            "/usr/local/bin/elvish",
906            "/usr/bin/xonsh",
907            "/usr/bin/pwsh",
908            "powershell.exe",
909            "cmd.exe",
910        ] {
911            assert!(
912                !is_posix_compatible_shell(s),
913                "{s} must be rejected by the POSIX gate"
914            );
915        }
916    }
917
918    #[test]
919    #[cfg_attr(miri, ignore)]
920    fn detect_shell_falls_back_when_shell_is_nushell() {
921        // Serialize env mutation (set_var/remove_var are process-global).
922        let _lock = crate::core::data_dir::test_env_lock();
923        let saved_shell = std::env::var_os("SHELL");
924        let saved_override = std::env::var_os("LEAN_CTX_SHELL");
925
926        crate::test_env::remove_var("LEAN_CTX_SHELL");
927        crate::test_env::set_var("SHELL", "/usr/bin/nu");
928        let resolved = detect_shell();
929        assert!(
930            is_posix_compatible_shell(&resolved),
931            "a non-POSIX $SHELL (nu) must resolve to a POSIX shell, got {resolved}"
932        );
933        assert!(
934            !resolved.ends_with("/nu") && resolved != "/usr/bin/nu",
935            "must not run agent commands in Nushell, got {resolved}"
936        );
937
938        // A POSIX $SHELL is honored verbatim.
939        crate::test_env::set_var("SHELL", "/bin/sh");
940        assert_eq!(detect_shell(), "/bin/sh");
941
942        // LEAN_CTX_SHELL always wins, even when pointing at a non-POSIX shell.
943        crate::test_env::set_var("LEAN_CTX_SHELL", "/usr/bin/nu");
944        assert_eq!(detect_shell(), "/usr/bin/nu");
945
946        match saved_shell {
947            Some(v) => crate::test_env::set_var("SHELL", v),
948            None => crate::test_env::remove_var("SHELL"),
949        }
950        match saved_override {
951            Some(v) => crate::test_env::set_var("LEAN_CTX_SHELL", v),
952            None => crate::test_env::remove_var("LEAN_CTX_SHELL"),
953        }
954    }
955}
956
957#[cfg(test)]
958mod carriage_return_tests {
959    use super::resolve_carriage_returns;
960
961    #[test]
962    fn no_cr_passthrough() {
963        assert_eq!(resolve_carriage_returns("hello\nworld\n"), "hello\nworld\n");
964    }
965
966    #[test]
967    fn progress_overwrite_keeps_last_segment() {
968        assert_eq!(resolve_carriage_returns("first\rsecond"), "second");
969    }
970
971    #[test]
972    fn git_rebase_progress() {
973        let input = "Rebasing (1/1)\rSuccessfully rebased and updated refs/heads/feat.";
974        assert_eq!(
975            resolve_carriage_returns(input),
976            "Successfully rebased and updated refs/heads/feat."
977        );
978    }
979
980    #[test]
981    fn crlf_line_endings_stripped() {
982        assert_eq!(
983            resolve_carriage_returns("line1\r\nline2\r\n"),
984            "line1\nline2\n"
985        );
986    }
987
988    #[test]
989    fn multiple_cr_on_one_line() {
990        assert_eq!(resolve_carriage_returns("a\rb\rc"), "c");
991    }
992
993    #[test]
994    fn mixed_lines() {
995        let input = "clean line\nprogress\rdone\nalso clean\n";
996        assert_eq!(
997            resolve_carriage_returns(input),
998            "clean line\ndone\nalso clean\n"
999        );
1000    }
1001
1002    #[test]
1003    fn trailing_cr_stripped_as_crlf() {
1004        assert_eq!(resolve_carriage_returns("visible\r"), "visible");
1005    }
1006
1007    #[test]
1008    fn empty_string_passthrough() {
1009        assert_eq!(resolve_carriage_returns(""), "");
1010    }
1011}
1012
1013#[cfg(test)]
1014mod zsh_safe_tests {
1015    use super::zsh_safe_command;
1016
1017    #[test]
1018    #[cfg(unix)]
1019    fn prepends_nonomatch_noequals_for_zsh() {
1020        let cmd = zsh_safe_command("grep --include=*.go pattern", "/bin/zsh");
1021        assert_eq!(
1022            cmd,
1023            "setopt nonomatch noequals; grep --include=*.go pattern"
1024        );
1025    }
1026
1027    #[test]
1028    #[cfg(unix)]
1029    fn prepends_nonomatch_noequals_for_usr_bin_zsh() {
1030        let cmd = zsh_safe_command("echo *.rs", "/usr/bin/zsh");
1031        assert_eq!(cmd, "setopt nonomatch noequals; echo *.rs");
1032    }
1033
1034    #[test]
1035    #[cfg(unix)]
1036    fn equals_separator_safe_under_zsh() {
1037        let cmd = zsh_safe_command("echo ===", "/bin/zsh");
1038        assert!(cmd.starts_with("setopt nonomatch noequals;"));
1039        assert!(cmd.contains("echo ==="));
1040    }
1041
1042    #[test]
1043    fn passthrough_for_bash() {
1044        let cmd = zsh_safe_command("grep --include=*.go pattern", "/bin/bash");
1045        assert_eq!(cmd, "grep --include=*.go pattern");
1046    }
1047
1048    #[test]
1049    fn passthrough_for_sh() {
1050        let cmd = zsh_safe_command("find -name *.ts", "/bin/sh");
1051        assert_eq!(cmd, "find -name *.ts");
1052    }
1053}