Skip to main content

rpi_tools/
os_env.rs

1//! Mirrors `packages/agent/src/harness/env/nodejs.ts` — `NodeExecutionEnv` →
2//! `OsExecutionEnv`. Real-filesystem + real-process backend via `tokio::fs` +
3//! `tokio::process`.
4//!
5//! Path resolution (\[`resolvePath`\]): tilde (`~`/`~/`, `~\` on Windows),
6//! `file://` URL (parse failure silently keeps the literal string), absolute
7//! → `canonicalize`-style normalize, relative → `cwd.join`. No env-var or
8//! `~user` expansion. No symlink resolution (that's `canonical_path`).
9//!
10//! Shell detection (\[`getShellConfig`\]): explicit override → `RPI_BASH_PATH`
11//! → Windows git-bash probe (`ProgramFiles\Git\bin\bash.exe`,
12//! `ProgramFiles(x86)\…`, the install root of `git.exe` on PATH) →
13//! `where bash.exe` minus WSL → POSIX `/bin/bash` → `which bash` →
14//! `/bin/sh` fallback (POSIX only). **No cmd.exe fallback** on Windows —
15//! failure is `ExecutionError::ShellUnavailable`. Legacy WSL bash
16//! (`System32\bash.exe`) keeps its `bash -s` stdin transport, but discovery
17//! never selects it and an explicit WSL path is refused.
18//!
19//! **WSL bash is deliberately not used**: the `System32\bash.exe` stub either
20//! fails because no distro is installed (exit 1, message written in UTF-16LE,
21//! which decodes as garbage) or runs commands inside Linux, where the caller's
22//! `G:\...` cwd does not exist. An explicit `RPI_BASH_PATH` /
23//! `with_shell_path` pointing at WSL is rejected rather than silently
24//! accepted.
25//!
26//! Windows Bash defaults to `LANG=C.UTF-8` and honors explicit locale values.
27//! Output that is not UTF-8 still falls back to the console code page.
28//!
29//! Kill tree: Windows terminates the shell's job object, falling back to
30//! `taskkill /F /T /PID`; POSIX `kill -PG` (process group, since the child is
31//! spawned as its own group leader) with fallback to `kill -PID`. Best-effort,
32//! errors swallowed.
33//!
34//! `exec` abort+timeout bracketing (plan §5.4): the spawn is `tokio::select!`-ed
35//! against the cancellation token and `tokio::time::timeout`. Resolution
36//! priority: callbackError → timeout → aborted → exit-code-from-success.
37//! `cleanup()` kills tracked child pids best-effort.
38
39use std::collections::{HashMap, HashSet};
40use std::io::{Read, Seek, SeekFrom, Write};
41use std::path::{Path, PathBuf};
42use std::sync::{Arc, Mutex};
43
44use async_trait::async_trait;
45use tokio_util::sync::CancellationToken;
46
47use crate::env::{
48    check_cancel_exec, check_cancel_file, ExecutionEnv, FileContent, FileInfo, FileKind,
49    FileSystem, Shell, ShellExecOptions, ShellOutput, WriterLease,
50};
51use crate::error::{
52    io_to_file_error, ExecutionError, ExecutionErrorCode, FileError, FileErrorCode,
53};
54use crate::file_mutation_queue::{MutatingEnv, MutationQueueRegistry};
55
56/// Max timeout in ms (Int32 max). Mirrors `MAX_TIMEOUT_MS`.
57const MAX_TIMEOUT_MS: u64 = 2_147_483_647;
58/// Max timeout in seconds. Mirrors `MAX_TIMEOUT_SECONDS`.
59const MAX_TIMEOUT_SECONDS: f64 = 2_147_483.647;
60/// Grace period after child exit for trailing stdio. Mirrors
61/// `EXIT_STDIO_GRACE_MS`.
62const EXIT_STDIO_GRACE_MS: u64 = 100;
63
64/// Non-interactive defaults for every spawned shell. A tool call has no
65/// terminal the user can answer: `git` with no credential helper opens
66/// `/dev/tty` directly for `Username for 'https://…':`, bypassing the piped
67/// stdin/stdout/stderr (and the deliberate stdin-close in `exec`). That writes
68/// over the TUI frame as text the editor never owned — so it cannot be selected
69/// or deleted — and blocks the child until the timeout. Failing fast instead
70/// turns it into an ordinary, capturable stderr error.
71///
72/// These are *defaults*, not a policy lock: they are applied before the
73/// inherit loop and before `shell_env` / per-call `env`, so an explicit host
74/// export, `with_shell_env`, or `ShellExecOptions::env` still opts back in.
75/// This is deliberately narrower than the managed-install `harden_git_env`
76/// (which also isolated git config): here the user's own git config and
77/// credential helpers must keep working.
78const NON_INTERACTIVE_SHELL_ENV: &[(&str, &str)] = &[
79    ("GIT_TERMINAL_PROMPT", "0"),
80    ("GCM_INTERACTIVE", "Never"),
81    ("SSH_ASKPASS_REQUIRE", "never"),
82];
83
84/// Env var that pins the Bash executable on Windows. Checked before any
85/// discovery so a host can point every session at one known-good Git Bash (a
86/// portable/GitHub-Desktop install, or a custom drive). A value that does not
87/// exist, or that names the WSL stub, is an error — never a silent fallback.
88pub const BASH_PATH_ENV: &str = "RPI_BASH_PATH";
89
90/// How the command is fed to the shell. Mirrors `commandTransport`.
91#[derive(Clone, Copy, Debug)]
92enum CommandTransport {
93    /// Append the command as the last argv element (`bash -c <cmd>`).
94    Argv,
95    /// Pipe the command to the shell's stdin (`bash -s`).
96    Stdin,
97}
98
99/// Resolved shell config. Mirrors `ShellConfig`.
100#[derive(Debug)]
101struct ShellConfig {
102    shell: PathBuf,
103    args: Vec<String>,
104    transport: CommandTransport,
105}
106
107mod append;
108mod read;
109
110/// The open lock file is the storage-level ownership capability.
111struct OsWriterLease {
112    file: std::fs::File,
113    fence: u64,
114}
115
116#[cfg(unix)]
117impl Drop for OsWriterLease {
118    fn drop(&mut self) {
119        // A child in the fork-to-exec window can still share this open file
120        // description. Unlock even if closing our descriptor is insufficient.
121        let _ = fs2::FileExt::unlock(&self.file);
122    }
123}
124
125impl WriterLease for OsWriterLease {
126    fn verify_fence(&self) -> Result<(), FileError> {
127        let mut probe = self
128            .file
129            .try_clone()
130            .map_err(|error| io_to_file_error(error, Some("writer lease fence")))?;
131        probe
132            .seek(SeekFrom::Start(0))
133            .map_err(|error| io_to_file_error(error, Some("writer lease fence")))?;
134        let mut contents = String::new();
135        probe
136            .read_to_string(&mut contents)
137            .map_err(|error| io_to_file_error(error, Some("writer lease fence")))?;
138        let current = contents.trim().parse::<u64>().map_err(|error| {
139            FileError::new(
140                FileErrorCode::Unknown,
141                format!("invalid persisted writer lease fence: {error}"),
142            )
143        })?;
144        if current != self.fence {
145            return Err(FileError::new(
146                FileErrorCode::PermissionDenied,
147                "writer lease fence changed; reopen the session",
148            ));
149        }
150        Ok(())
151    }
152}
153
154/// Environment variables the **host** sets for its own runtime plumbing, which
155/// must not be handed to a shell it spawns.
156///
157/// A spawned shell is a child process, so anything inherited reaches whatever
158/// that shell runs — including another `rpi`. `RPI_SESSION_ID` names the session
159/// *this process* serves, which is meaningless (and actively misleading) in a
160/// descendant: the child would either report the parent's session or, seeing the
161/// variable already present, refuse to publish its own. Both are wrong answers,
162/// and neither is visible from the child.
163///
164/// This is only the host's own half. An *extension* can publish variables with
165/// the same hazard, and it declares them itself; [`is_host_private_env`] is the
166/// function that answers the full question. Use it rather than reading this
167/// slice, or an extension's channel will be missed — which is precisely the bug
168/// that let `LANGFUSE_PI_PARENT_*` through.
169pub const HOST_PRIVATE_ENV: &[&str] = &[rpi_plugin_sdk::SESSION_ID_ENV];
170
171/// Whether `name` must not be inherited by a spawned shell.
172///
173/// Two sources, because the variables come from two places:
174///
175/// - [`HOST_PRIVATE_ENV`] — the host's own plumbing.
176/// - [`rpi_plugin_sdk::SUBAGENT_PARENT_ENV`] — the family an *extension*
177///   declares for subagent nesting. An inherited copy makes a plain `rpi` started
178///   from inside `bash` adopt its ancestor's trace, hang its root off the
179///   ancestor's root span, and call itself `Subagent Turn` instead of opening its
180///   own trace. A launcher that sets these on the child *it* starts is the
181///   supported nesting path, so this is about not *inheriting* them, not about
182///   forbidding the names.
183///
184/// The extension family is consulted **as the SDK's slice**, never as names
185/// restated here. Restating them is what the previous version did, and it is
186/// how the channel re-leaked when the plugin renamed them: the list went on
187/// matching a name nobody set. Going through the constant means a rename is a
188/// compile error, and a newly added family member is excluded automatically.
189pub fn is_host_private_env(name: &str) -> bool {
190    HOST_PRIVATE_ENV.contains(&name) || rpi_plugin_sdk::SUBAGENT_PARENT_ENV.contains(&name)
191}
192
193/// Real-OS `ExecutionEnv`. Clone shares the tracked-pid set + registry.
194pub struct OsExecutionEnv {
195    cwd: PathBuf,
196    shell_path: Option<PathBuf>,
197    shell_env: Option<HashMap<String, String>>,
198    /// None preserves legacy process inheritance. Some is a closed, immutable
199    /// per-Agent baseline (including HOME for file-path expansion).
200    environment: Option<HashMap<String, String>>,
201    active_pids: Arc<Mutex<HashSet<u32>>>,
202    registry: Arc<MutationQueueRegistry>,
203}
204
205impl OsExecutionEnv {
206    pub fn new() -> Self {
207        Self {
208            cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/")),
209            shell_path: None,
210            shell_env: None,
211            environment: None,
212            active_pids: Arc::new(Mutex::new(HashSet::new())),
213            registry: Arc::new(MutationQueueRegistry::new()),
214        }
215    }
216
217    pub fn with_cwd(cwd: PathBuf) -> Self {
218        Self {
219            cwd,
220            shell_path: None,
221            shell_env: None,
222            environment: None,
223            active_pids: Arc::new(Mutex::new(HashSet::new())),
224            registry: Arc::new(MutationQueueRegistry::new()),
225        }
226    }
227
228    pub fn with_shell_path(mut self, shell_path: PathBuf) -> Self {
229        self.shell_path = Some(shell_path);
230        self
231    }
232
233    pub fn with_shell_env(mut self, env: HashMap<String, String>) -> Self {
234        self.shell_env = Some(env);
235        self
236    }
237
238    /// Replace process environment inheritance with an explicit frozen baseline.
239    /// Unlike `with_shell_env`, absent keys never fall back to process globals.
240    /// Private host channels remain excluded; explicit shell/per-call overlays
241    /// retain their existing semantics. Hosts must supply an absolute shell path
242    /// as well when shell discovery must not consult ambient PATH.
243    pub fn with_environment(mut self, environment: HashMap<String, String>) -> Self {
244        self.environment = Some(environment);
245        self
246    }
247
248    /// Whether process inheritance and ambient HOME fallback are disabled.
249    pub fn has_explicit_environment(&self) -> bool {
250        self.environment.is_some()
251    }
252
253    /// Resolve a path (tilde, file://, absolute/relative) against `cwd`. Pure.
254    fn resolve_path(&self, path: &str) -> PathBuf {
255        let cwd = &self.cwd;
256        let home = || match &self.environment {
257            Some(environment) => environment
258                .get(if cfg!(windows) { "USERPROFILE" } else { "HOME" })
259                .cloned()
260                .unwrap_or_default(),
261            None => home_dir_string(),
262        };
263        let mut p = path.to_string();
264        // Tilde expansion (literal only). A missing HOME in a closed baseline
265        // leaves the tilde literal; it must not turn `~/x` into `/x` or consult
266        // another Agent's ambient home directory.
267        if p == "~" {
268            let home = home();
269            if self.environment.is_none() || !home.is_empty() {
270                p = home;
271            }
272        } else if let Some(rest) = p.strip_prefix("~/") {
273            let home = home();
274            if self.environment.is_none() || !home.is_empty() {
275                p = format!("{home}/{rest}");
276            }
277        } else if cfg!(windows) {
278            if let Some(rest) = p.strip_prefix("~\\") {
279                let home = home();
280                if self.environment.is_none() || !home.is_empty() {
281                    p = format!("{home}\\{rest}");
282                }
283            }
284        }
285        // file:// URL → path. Parse failure silently keeps the literal.
286        if p.starts_with("file://") {
287            if let Some(local) = file_url_to_path(&p) {
288                p = local;
289            }
290        }
291        let pb = PathBuf::from(&p);
292        if pb.is_absolute() {
293            normalize_absolute(&pb)
294        } else {
295            normalize_absolute(&cwd.join(pb))
296        }
297    }
298
299    /// Detect + return the shell config, or `ShellUnavailable`. Mirrors
300    /// `getShellConfig`.
301    ///
302    /// Precedence on Windows: host-configured `shellPath` (settings /
303    /// `with_shell_path`) → `RPI_BASH_PATH` → auto-discovery. A configured
304    /// path is validated here, so a WSL launcher or a missing file fails with
305    /// an actionable error instead of falling back to discovery.
306    async fn get_shell_config(&self) -> Result<ShellConfig, ExecutionError> {
307        // Explicit override. Shell discovery happens on the hot path immediately
308        // before spawning a command. Keep this probe synchronous: putting a
309        // `tokio::fs` metadata future here can queue work on Tokio's blocking
310        // pool and leave a tool run waiting before it has even created a child.
311        if let Some(sp) = &self.shell_path {
312            return validate_bash_path(sp, "Configured shellPath").map(bash_shell_config);
313        }
314        // Windows probe.
315        #[cfg(windows)]
316        {
317            windows_probe_bash().await
318        }
319        // POSIX.
320        #[cfg(not(windows))]
321        {
322            if std::path::Path::new("/bin/bash").is_file() {
323                return Ok(bash_shell_config(PathBuf::from("/bin/bash")));
324            }
325            // `which bash` fallback.
326            if let Some(found) =
327                run_command("which", &["bash"], std::time::Duration::from_millis(5000)).await
328            {
329                let trimmed = found.trim();
330                if !trimmed.is_empty() && std::path::Path::new(trimmed).is_file() {
331                    return Ok(bash_shell_config(PathBuf::from(trimmed)));
332                }
333            }
334            // sh fallback.
335            Ok(bash_shell_config(PathBuf::from("sh")))
336        }
337    }
338}
339
340impl Default for OsExecutionEnv {
341    fn default() -> Self {
342        Self::new()
343    }
344}
345
346fn home_dir_string() -> String {
347    dirs::home_dir()
348        .map(|p| p.to_string_lossy().into_owned())
349        .unwrap_or_default()
350}
351
352fn normalize_absolute(p: &Path) -> PathBuf {
353    // std::path doesn't expose ".."/"." collapse without canonicalize (which
354    // hits the FS). Rebuild component-by-component.
355    let mut out = PathBuf::new();
356    for comp in p.components() {
357        match comp {
358            std::path::Component::ParentDir => {
359                out.pop();
360            }
361            std::path::Component::CurDir => {}
362            other => out.push(other),
363        }
364    }
365    out
366}
367
368fn file_url_to_path(url: &str) -> Option<String> {
369    // Minimal file:// → path conversion. Handles `file:///abs/path` and
370    // Windows `file:///C:/...`. Parse failure → None (caller keeps literal).
371    let rest = url.strip_prefix("file://")?;
372    if let Some(drive_rest) = rest.strip_prefix('/') {
373        // `/C:/...` (Windows drive) or `/abs/path`.
374        if drive_rest.len() >= 2 && drive_rest.as_bytes()[1] == b':' {
375            return Some(drive_rest.to_string());
376        }
377        return Some(format!("/{}", drive_rest));
378    }
379    Some(rest.to_string())
380}
381
382fn bash_shell_config(shell: PathBuf) -> ShellConfig {
383    if is_legacy_wsl_bash_path(&shell) {
384        ShellConfig {
385            shell,
386            args: vec!["-s".to_string()],
387            transport: CommandTransport::Stdin,
388        }
389    } else {
390        ShellConfig {
391            shell,
392            args: vec!["-c".to_string()],
393            transport: CommandTransport::Argv,
394        }
395    }
396}
397
398fn is_legacy_wsl_bash_path(p: &Path) -> bool {
399    let s = p.to_string_lossy().replace('/', "\\").to_ascii_lowercase();
400    s.ends_with("\\windows\\system32\\bash.exe") || s.ends_with("\\windows\\sysnative\\bash.exe")
401}
402
403/// Check an explicitly configured bash path. Refusing WSL and missing files
404/// here keeps the failure at the configuration seam instead of surfacing as a
405/// garbled command result later.
406fn validate_bash_path(path: &Path, source: &str) -> Result<PathBuf, ExecutionError> {
407    if is_legacy_wsl_bash_path(path) {
408        return Err(ExecutionError::new(
409            ExecutionErrorCode::ShellUnavailable,
410            format!(
411                "{source} points at the WSL launcher ({}). The bash tool needs Git Bash \
412                 (or another MSYS2/Cygwin bash) so Windows paths and the host cwd work; \
413                 point {BASH_PATH_ENV} at e.g. C:\\Program Files\\Git\\bin\\bash.exe.",
414                path.display()
415            ),
416        ));
417    }
418    if !path.is_file() {
419        return Err(ExecutionError::new(
420            ExecutionErrorCode::ShellUnavailable,
421            format!("{source} not found: {}", path.display()),
422        ));
423    }
424    Ok(path.to_path_buf())
425}
426
427/// Git for Windows install roots from the usual locations. Kept separate from
428/// the PATH probe so a machine with Git in `D:\Git` (nothing in
429/// `%ProgramFiles%`) is still covered.
430#[cfg(windows)]
431fn windows_git_install_roots() -> Vec<PathBuf> {
432    let mut roots: Vec<PathBuf> = Vec::new();
433    let mut push = |root: PathBuf| {
434        if !roots.contains(&root) {
435            roots.push(root);
436        }
437    };
438    for var in ["ProgramFiles", "ProgramW6432", "ProgramFiles(x86)"] {
439        if let Some(base) = std::env::var_os(var) {
440            push(PathBuf::from(base).join("Git"));
441        }
442    }
443    if let Some(local) = std::env::var_os("LOCALAPPDATA") {
444        // Per-user Git installs (`git update` and some installers).
445        push(PathBuf::from(local).join("Programs").join("Git"));
446    }
447    roots
448}
449
450/// The install root implied by a `git.exe` path:
451/// `<root>\cmd\git.exe`, `<root>\bin\git.exe`, or
452/// `<root>\mingw64\bin\git.exe`.
453#[cfg_attr(not(windows), allow(dead_code))]
454fn git_install_root(git_exe: &Path) -> Option<PathBuf> {
455    let dir = git_exe.parent()?;
456    let dir_name = dir.file_name()?.to_string_lossy().to_ascii_lowercase();
457    if dir_name == "cmd" {
458        return dir.parent().map(Path::to_path_buf);
459    }
460    if dir_name == "bin" {
461        let parent = dir.parent()?;
462        if matches!(
463            parent
464                .file_name()?
465                .to_string_lossy()
466                .to_ascii_lowercase()
467                .as_str(),
468            "mingw64" | "mingw32"
469        ) {
470            return parent.parent().map(Path::to_path_buf);
471        }
472        return Some(parent.to_path_buf());
473    }
474    None
475}
476
477#[cfg(windows)]
478fn git_bash_at(root: &Path) -> Option<PathBuf> {
479    [
480        root.join("bin").join("bash.exe"),
481        root.join("usr").join("bin").join("bash.exe"),
482    ]
483    .into_iter()
484    .find(|candidate| candidate.is_file())
485}
486
487/// Locate a Windows bash. Order: explicit `RPI_BASH_PATH`, known Git install
488/// roots, the install root of `git.exe` on PATH (covers custom drives), then
489/// `where bash.exe` with every WSL launcher skipped. There is no cmd.exe
490/// fallback: nothing found is `ShellUnavailable`.
491#[cfg(windows)]
492async fn windows_probe_bash() -> Result<ShellConfig, ExecutionError> {
493    if let Some(raw) = std::env::var_os(BASH_PATH_ENV) {
494        let raw = raw.to_string_lossy();
495        let raw = raw.trim();
496        if raw.is_empty() {
497            return Err(ExecutionError::new(
498                ExecutionErrorCode::ShellUnavailable,
499                format!(
500                    "{BASH_PATH_ENV} is set but empty; point it at Git Bash \
501                     (e.g. C:\\Program Files\\Git\\bin\\bash.exe)."
502                ),
503            ));
504        }
505        return validate_bash_path(Path::new(raw), BASH_PATH_ENV).map(bash_shell_config);
506    }
507
508    let roots = windows_git_install_roots();
509    if let Some(shell) = roots.iter().find_map(|root| git_bash_at(root)) {
510        return Ok(bash_shell_config(shell));
511    }
512
513    // Portable installs may expose only their `cmd\` directory on PATH.
514    if let Some(found) = run_command(
515        "where",
516        &["git.exe"],
517        std::time::Duration::from_millis(5000),
518    )
519    .await
520    {
521        let shell = found
522            .lines()
523            .filter_map(|line| git_install_root(Path::new(line.trim())))
524            .filter(|root| !roots.contains(root))
525            .find_map(|root| git_bash_at(&root));
526        if let Some(shell) = shell {
527            return Ok(bash_shell_config(shell));
528        }
529    }
530
531    // `where bash.exe` — first non-WSL candidate. On a stock machine the only
532    // hit is System32\bash.exe (WSL), which is exactly what must not be used.
533    if let Some(found) = run_command(
534        "where",
535        &["bash.exe"],
536        std::time::Duration::from_millis(5000),
537    )
538    .await
539    {
540        for line in found.lines() {
541            let line = line.trim();
542            if line.is_empty() {
543                continue;
544            }
545            let candidate = PathBuf::from(line);
546            if candidate.is_file() && !is_legacy_wsl_bash_path(&candidate) {
547                return Ok(bash_shell_config(candidate));
548            }
549        }
550    }
551
552    Err(ExecutionError::new(
553        ExecutionErrorCode::ShellUnavailable,
554        format!(
555            "bash not found. Install Git for Windows \
556             (https://git-scm.com/download/win), or set {BASH_PATH_ENV} to its \
557             bin\\bash.exe. The WSL launcher (C:\\Windows\\System32\\bash.exe) is not \
558             supported: it cannot run Windows-path commands in the host cwd."
559        ),
560    ))
561}
562
563/// Run a quick command, capture stdout, with a timeout. Mirrors `runCommand`
564/// (used only by shell detection). Returns `None` on spawn failure / timeout /
565/// empty stdout.
566async fn run_command(cmd: &str, args: &[&str], timeout: std::time::Duration) -> Option<String> {
567    let mut command = tokio::process::Command::new(cmd);
568    command.args(args);
569    command.stdout(std::process::Stdio::piped());
570    command.stderr(std::process::Stdio::null());
571    command.stdin(std::process::Stdio::null());
572    #[cfg(windows)]
573    {
574        // Hide the console window for the probe.
575        use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
576        command.creation_flags(CREATE_NO_WINDOW);
577    }
578    let child = command.spawn().ok()?;
579    let out = match tokio::time::timeout(timeout, child.wait_with_output()).await {
580        Ok(Ok(o)) => o,
581        _ => return None,
582    };
583    if !out.status.success() {
584        return None;
585    }
586    // `where` prints paths in the console code page (e.g. a Chinese user name).
587    let s = crate::output_decode::decode_output(&out.stdout);
588    if s.trim().is_empty() {
589        None
590    } else {
591        Some(s)
592    }
593}
594
595/// One job object per running shell, by root pid. `taskkill /T` walks parent
596/// pids, and an MSYS shell's children are not on that chain: `sleep` under Git
597/// Bash outlives it. Job membership is inherited by every descendant.
598///
599/// Kill-on-close is armed only when killing, so whatever a command leaves
600/// running on purpose keeps running after it ends normally.
601#[cfg(windows)]
602mod shell_jobs {
603    use std::collections::HashMap;
604    use std::sync::{LazyLock, Mutex};
605
606    use win32job::{ExtendedLimitInfo, Job};
607
608    static JOBS: LazyLock<Mutex<HashMap<u32, Job>>> = LazyLock::new(Default::default);
609
610    /// Put a shell spawned with `CREATE_SUSPENDED` in its own job, then let it
611    /// run: no descendant can start outside the job. A shell that gets no job
612    /// still runs, and cancelling it falls back to `taskkill`.
613    pub fn start(pid: u32, process: std::os::windows::io::RawHandle) -> Result<(), String> {
614        if let Ok(job) = Job::create() {
615            if job.assign_process(process as isize).is_ok() {
616                JOBS.lock().unwrap().insert(pid, job);
617            }
618        }
619        rpi_plugin_sdk::process::resume_child(pid)
620    }
621
622    /// End every process in `pid`'s job: arm kill-on-close, then drop the only
623    /// handle. False when `pid` has no job or arming failed.
624    pub fn terminate(pid: u32) -> bool {
625        let Some(job) = JOBS.lock().unwrap().remove(&pid) else {
626            return false;
627        };
628        let mut info = ExtendedLimitInfo::new();
629        info.limit_kill_on_job_close();
630        job.set_extended_limit_info(&info).is_ok()
631    }
632
633    pub fn forget(pid: u32) {
634        JOBS.lock().unwrap().remove(&pid);
635    }
636}
637
638// A tool or harness can drop exec before its cancellation branch is polled.
639// Own the process group until wait() has actually reaped the shell. The guard
640// must be synchronous: Drop runs while the async execution future is unwinding.
641struct ShellProcessGuard {
642    pid: Option<u32>,
643    active: Arc<Mutex<HashSet<u32>>>,
644}
645impl ShellProcessGuard {
646    fn finish(&mut self) {
647        if let Some(pid) = self.pid.take() {
648            #[cfg(windows)]
649            shell_jobs::forget(pid);
650            self.active
651                .lock()
652                .unwrap_or_else(|e| e.into_inner())
653                .remove(&pid);
654        }
655    }
656}
657impl Drop for ShellProcessGuard {
658    fn drop(&mut self) {
659        if let Some(pid) = self.pid {
660            #[cfg(unix)]
661            {
662                use nix::sys::signal::{kill, Signal};
663                use nix::unistd::Pid;
664                // Every shell is spawned into its own process group. No
665                // unrelated session or successful background command is killed.
666                let _ = kill(Pid::from_raw(-(pid as i32)), Signal::SIGKILL);
667            }
668            #[cfg(windows)]
669            shell_jobs::terminate(pid);
670            self.finish();
671        }
672    }
673}
674
675/// Kill a process tree. Windows: the shell's job object, else
676/// `taskkill /F /T /PID`. POSIX: `kill -PG` with fallback to `kill -PID`.
677/// Best-effort, errors swallowed.
678async fn kill_process_tree(pid: u32) {
679    #[cfg(windows)]
680    {
681        if shell_jobs::terminate(pid) {
682            return;
683        }
684        use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
685        let mut cmd = tokio::process::Command::new("taskkill");
686        cmd.args(&["/F", "/T", "/PID", &pid.to_string()]);
687        cmd.creation_flags(CREATE_NO_WINDOW);
688        cmd.stdin(std::process::Stdio::null());
689        cmd.stdout(std::process::Stdio::null());
690        cmd.stderr(std::process::Stdio::null());
691        // Wait for taskkill itself to finish. Spawning it fire-and-forget lets
692        // the shell's `child.wait()` race the tree termination, and a listener
693        // can keep its inherited stdout/stderr handles open long enough to
694        // deadlock the capture join after Ctrl+C.
695        let _ = cmd.status().await;
696    }
697    #[cfg(unix)]
698    {
699        use nix::sys::signal::{kill, Signal};
700        use nix::unistd::Pid;
701        // Process group: negative pid.
702        let pg = Pid::from_raw(-(pid as i32));
703        if kill(pg, Signal::SIGKILL).is_err() {
704            let _ = kill(Pid::from_raw(pid as i32), Signal::SIGKILL);
705        }
706    }
707    #[cfg(not(any(windows, unix)))]
708    {
709        let _ = pid;
710    }
711}
712
713#[async_trait]
714impl FileSystem for OsExecutionEnv {
715    fn native_file_path(&self, path: &str) -> Option<PathBuf> {
716        #[cfg(unix)]
717        return Some(self.resolve_path(path));
718        #[cfg(not(unix))]
719        {
720            let _ = path;
721            None
722        }
723    }
724
725    async fn try_acquire_writer_lease(
726        &self,
727        path: &str,
728    ) -> Result<Option<Box<dyn WriterLease>>, FileError> {
729        let session_path = self.resolve_path(path);
730        let lock_path = PathBuf::from(format!("{}.lock", session_path.display()));
731        let display_path = session_path.to_string_lossy().into_owned();
732        tokio::task::spawn_blocking(move || {
733            use fs2::FileExt;
734            let mut file = std::fs::OpenOptions::new()
735                .create(true)
736                .read(true)
737                .write(true)
738                .open(&lock_path)
739                .map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
740            file.try_lock_exclusive().map_err(|error| {
741                FileError::new(
742                    FileErrorCode::PermissionDenied,
743                    format!("writer lease is already held for {display_path}"),
744                )
745                .with_path(lock_path.to_string_lossy())
746                .with_source(Box::new(error))
747            })?;
748            file.seek(SeekFrom::Start(0))
749                .map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
750            let mut contents = String::new();
751            file.read_to_string(&mut contents)
752                .map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
753            let previous = if contents.trim().is_empty() {
754                0
755            } else {
756                contents.trim().parse::<u64>().map_err(|error| {
757                    FileError::new(
758                        FileErrorCode::Unknown,
759                        format!("invalid persisted writer lease fence: {error}"),
760                    )
761                    .with_path(lock_path.to_string_lossy())
762                })?
763            };
764            let fence = previous.checked_add(1).ok_or_else(|| {
765                FileError::new(FileErrorCode::Unknown, "writer lease fence exhausted")
766                    .with_path(lock_path.to_string_lossy())
767            })?;
768            file.seek(SeekFrom::Start(0))
769                .and_then(|_| file.set_len(0))
770                .and_then(|_| file.write_all(fence.to_string().as_bytes()))
771                .and_then(|_| file.sync_all())
772                .map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
773            Ok(Some(
774                Box::new(OsWriterLease { file, fence }) as Box<dyn WriterLease>
775            ))
776        })
777        .await
778        .map_err(|error| {
779            FileError::new(
780                FileErrorCode::Unknown,
781                format!("writer lease task failed: {error}"),
782            )
783            .with_path(session_path.to_string_lossy())
784        })?
785    }
786
787    async fn sync_file(
788        &self,
789        path: &str,
790        data_only: bool,
791        cancel: Option<&CancellationToken>,
792    ) -> Result<(), FileError> {
793        check_cancel_file(cancel, Some(path))?;
794        let abs = self.resolve_path(path);
795        let error_path = abs.to_string_lossy().into_owned();
796        let io_path = error_path.clone();
797        tokio::task::spawn_blocking(move || {
798            let file = std::fs::OpenOptions::new()
799                .read(true)
800                .write(true)
801                .open(&abs)
802                .map_err(|error| io_to_file_error(error, Some(&io_path)))?;
803            if data_only {
804                file.sync_data()
805                    .map_err(|error| io_to_file_error(error, Some(&io_path)))
806            } else {
807                file.sync_all()
808                    .map_err(|error| io_to_file_error(error, Some(&io_path)))
809            }
810        })
811        .await
812        .map_err(|error| {
813            FileError::new(
814                FileErrorCode::Unknown,
815                format!("file sync task failed: {error}"),
816            )
817            .with_path(error_path)
818        })??;
819        Ok(())
820    }
821
822    async fn sync_directory(
823        &self,
824        path: &str,
825        cancel: Option<&CancellationToken>,
826    ) -> Result<(), FileError> {
827        check_cancel_file(cancel, Some(path))?;
828        let abs = self.resolve_path(path);
829        #[cfg(unix)]
830        {
831            let error_path = abs.to_string_lossy().into_owned();
832            let io_path = error_path.clone();
833            tokio::task::spawn_blocking(move || {
834                std::fs::File::open(&abs)
835                    .map_err(|error| io_to_file_error(error, Some(&io_path)))?
836                    .sync_all()
837                    .map_err(|error| io_to_file_error(error, Some(&io_path)))
838            })
839            .await
840            .map_err(|error| {
841                FileError::new(
842                    FileErrorCode::Unknown,
843                    format!("directory sync task failed: {error}"),
844                )
845                .with_path(error_path)
846            })??;
847        }
848        #[cfg(not(unix))]
849        {
850            // Windows has no portable directory-handle fsync equivalent in
851            // this abstraction. File contents are still synced above, but
852            // rename-directory durability remains unproved on this target.
853            let _ = abs;
854        }
855        Ok(())
856    }
857
858    async fn sync_file_and_parent(
859        &self,
860        path: &str,
861        cancel: Option<&CancellationToken>,
862    ) -> Result<(), FileError> {
863        check_cancel_file(cancel, Some(path))?;
864        #[cfg(unix)]
865        {
866            let abs = self.resolve_path(path);
867            let info = self.file_info(path, cancel).await?;
868            if info.kind != FileKind::File {
869                return Err(FileError::new(
870                    FileErrorCode::NotSupported,
871                    "journal synchronization requires a regular file",
872                )
873                .with_path(path));
874            }
875            // Use the existing OS implementations, not the compatibility no-op
876            // defaults. Both errors propagate; a file-only sync is not success.
877            self.sync_file(path, false, cancel).await?;
878            let parent = abs.parent().ok_or_else(|| {
879                FileError::new(
880                    FileErrorCode::NotSupported,
881                    "journal has no parent directory",
882                )
883                .with_path(path)
884            })?;
885            self.sync_directory(&parent.to_string_lossy(), cancel).await
886        }
887        #[cfg(not(unix))]
888        {
889            // The legacy directory sync is a no-op on Windows. Do not promote
890            // that compatibility behavior into a physical persistence proof.
891            Err(FileError::new(
892                FileErrorCode::NotSupported,
893                "physical journal synchronization is unsupported on this platform",
894            )
895            .with_path(path))
896        }
897    }
898
899    async fn open_append_file(
900        &self,
901        path: &str,
902    ) -> Result<Option<Box<dyn crate::env::AppendFile>>, FileError> {
903        let path = self.resolve_path(path);
904        Ok(Some(Box::new(append::OsAppendFile::open(path).await?)))
905    }
906
907    async fn open_read_file(
908        &self,
909        path: &str,
910    ) -> Result<Option<Arc<dyn crate::env::ReadFile>>, FileError> {
911        let path = self.resolve_path(path);
912        Ok(Some(Arc::new(read::OsReadFile::open(path).await?)))
913    }
914
915    async fn truncate_file(
916        &self,
917        path: &str,
918        len: u64,
919        cancel: Option<&CancellationToken>,
920    ) -> Result<(), FileError> {
921        check_cancel_file(cancel, Some(path))?;
922        let abs = self.resolve_path(path);
923        let error_path = abs.to_string_lossy().into_owned();
924        tokio::task::spawn_blocking(move || {
925            let file = std::fs::OpenOptions::new().write(true).open(&abs)?;
926            if len > file.metadata()?.len() {
927                return Err(std::io::Error::new(
928                    std::io::ErrorKind::InvalidInput,
929                    "truncation cannot grow a file",
930                ));
931            }
932            file.set_len(len)
933        })
934        .await
935        .map_err(|error| {
936            FileError::new(
937                FileErrorCode::Unknown,
938                format!("file truncation task failed: {error}"),
939            )
940        })?
941        .map_err(|error| io_to_file_error(error, Some(&error_path)))
942    }
943
944    fn cwd(&self) -> &Path {
945        &self.cwd
946    }
947
948    async fn absolute_path(
949        &self,
950        path: &str,
951        cancel: Option<&CancellationToken>,
952    ) -> Result<PathBuf, FileError> {
953        check_cancel_file(cancel, Some(path))?;
954        Ok(self.resolve_path(path))
955    }
956
957    async fn join_path(
958        &self,
959        parts: &[&str],
960        cancel: Option<&CancellationToken>,
961    ) -> Result<PathBuf, FileError> {
962        check_cancel_file(cancel, None)?;
963        let mut out = PathBuf::new();
964        for p in parts {
965            out.push(p);
966        }
967        Ok(out)
968    }
969
970    async fn read_text_file(
971        &self,
972        path: &str,
973        cancel: Option<&CancellationToken>,
974    ) -> Result<String, FileError> {
975        check_cancel_file(cancel, Some(path))?;
976        let abs = self.resolve_path(path);
977        let bytes = read_cancellable(&abs, cancel).await?;
978        String::from_utf8(bytes).map_err(|e| {
979            FileError::new(FileErrorCode::Invalid, format!("invalid utf-8: {e}"))
980                .with_path(abs.to_string_lossy())
981        })
982    }
983
984    async fn read_text_file_bounded(
985        &self,
986        path: &str,
987        max_bytes: usize,
988        cancel: Option<&CancellationToken>,
989    ) -> Result<Option<String>, FileError> {
990        check_cancel_file(cancel, Some(path))?;
991        let abs = self.resolve_path(path);
992        read::read_text_file_bounded(&abs, max_bytes, cancel).await
993    }
994
995    async fn read_text_lines(
996        &self,
997        path: &str,
998        max_lines: Option<usize>,
999        cancel: Option<&CancellationToken>,
1000    ) -> Result<Vec<String>, FileError> {
1001        check_cancel_file(cancel, Some(path))?;
1002        if max_lines.map(|m| m == 0).unwrap_or(false) {
1003            return Ok(Vec::new());
1004        }
1005        let abs = self.resolve_path(path);
1006        read::read_text_lines(&abs, max_lines, cancel).await
1007    }
1008
1009    async fn read_binary_file(
1010        &self,
1011        path: &str,
1012        cancel: Option<&CancellationToken>,
1013    ) -> Result<Vec<u8>, FileError> {
1014        check_cancel_file(cancel, Some(path))?;
1015        let abs = self.resolve_path(path);
1016        read_cancellable(&abs, cancel).await
1017    }
1018
1019    async fn write_file(
1020        &self,
1021        path: &str,
1022        content: FileContent,
1023        cancel: Option<&CancellationToken>,
1024    ) -> Result<(), FileError> {
1025        check_cancel_file(cancel, Some(path))?;
1026        let abs = self.resolve_path(path);
1027        // mkdir parent (recursive).
1028        if let Some(parent) = abs.parent() {
1029            if !parent.as_os_str().is_empty() {
1030                if let Err(e) = tokio::fs::create_dir_all(parent).await {
1031                    return Err(io_to_file_error(e, Some(&abs.to_string_lossy())));
1032                }
1033            }
1034        }
1035        check_cancel_file(cancel, Some(&abs.to_string_lossy()))?;
1036        write_cancellable(abs, content, cancel).await
1037    }
1038
1039    async fn write_new_file(
1040        &self,
1041        path: &str,
1042        content: FileContent,
1043        cancel: Option<&CancellationToken>,
1044    ) -> Result<(), FileError> {
1045        check_cancel_file(cancel, Some(path))?;
1046        let abs = self.resolve_path(path);
1047        let cancel = cancel.cloned();
1048        // One owned blocking operation retains the opened descriptor even if
1049        // its async waiter disappears. O_EXCL/create_new is the authority: no
1050        // separate metadata check, parent mkdir, truncation or cleanup unlink.
1051        tokio::task::spawn_blocking(move || {
1052            let display = abs.to_string_lossy();
1053            check_cancel_file(cancel.as_ref(), Some(&display))?;
1054            let mut options = std::fs::OpenOptions::new();
1055            options.write(true).create_new(true);
1056            #[cfg(unix)]
1057            {
1058                use std::os::unix::fs::OpenOptionsExt;
1059                options.mode(0o600);
1060            }
1061            let mut file = options
1062                .open(&abs)
1063                .map_err(|error| io_to_file_error(error, Some(&display)))?;
1064            for chunk in content.as_bytes().chunks(64 * 1024) {
1065                check_cancel_file(cancel.as_ref(), Some(&display))?;
1066                file.write_all(chunk)
1067                    .map_err(|error| io_to_file_error(error, Some(&display)))?;
1068            }
1069            file.flush()
1070                .map_err(|error| io_to_file_error(error, Some(&display)))
1071        })
1072        .await
1073        .map_err(|_| {
1074            FileError::new(
1075                FileErrorCode::Unknown,
1076                "exclusive file creation task stopped",
1077            )
1078        })?
1079    }
1080
1081    async fn append_file(
1082        &self,
1083        path: &str,
1084        content: FileContent,
1085        cancel: Option<&CancellationToken>,
1086    ) -> Result<(), FileError> {
1087        check_cancel_file(cancel, Some(path))?;
1088        let abs = self.resolve_path(path);
1089        if let Some(parent) = abs.parent() {
1090            if !parent.as_os_str().is_empty() {
1091                let _ = tokio::fs::create_dir_all(parent).await;
1092            }
1093        }
1094        use tokio::io::AsyncWriteExt;
1095        let res = match tokio::fs::OpenOptions::new()
1096            .create(true)
1097            .append(true)
1098            .open(&abs)
1099            .await
1100        {
1101            Ok(mut f) => {
1102                // Tokio may acknowledge a buffered write before the blocking
1103                // filesystem operation completes. Await it before returning so
1104                // an immediate read/metadata call observes the appended bytes.
1105                match f.write_all(content.as_bytes()).await {
1106                    Ok(()) => f.flush().await,
1107                    Err(error) => Err(error),
1108                }
1109            }
1110            Err(e) => return Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
1111        };
1112        res.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
1113    }
1114
1115    async fn rename_file(
1116        &self,
1117        source: &str,
1118        dest: &str,
1119        cancel: Option<&CancellationToken>,
1120    ) -> Result<(), FileError> {
1121        check_cancel_file(cancel, Some(source))?;
1122        let src = self.resolve_path(source);
1123        let dst = self.resolve_path(dest);
1124        tokio::fs::rename(&src, &dst)
1125            .await
1126            .map_err(|e| io_to_file_error(e, Some(&src.to_string_lossy())))
1127    }
1128
1129    async fn file_info(
1130        &self,
1131        path: &str,
1132        cancel: Option<&CancellationToken>,
1133    ) -> Result<FileInfo, FileError> {
1134        check_cancel_file(cancel, Some(path))?;
1135        let abs = self.resolve_path(path);
1136        let meta = tokio::fs::symlink_metadata(&abs)
1137            .await
1138            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1139        let ft = meta.file_type();
1140        let kind = if ft.is_file() {
1141            FileKind::File
1142        } else if ft.is_dir() {
1143            FileKind::Directory
1144        } else if ft.is_symlink() {
1145            FileKind::Symlink
1146        } else {
1147            return Err(
1148                FileError::new(FileErrorCode::Invalid, "Unsupported file type")
1149                    .with_path(abs.to_string_lossy()),
1150            );
1151        };
1152        let mtime_ms = meta
1153            .modified()
1154            .ok()
1155            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1156            .map(|d| d.as_millis() as i64)
1157            .unwrap_or(0);
1158        Ok(FileInfo {
1159            name: abs
1160                .file_name()
1161                .map(|n| n.to_string_lossy().into_owned())
1162                .unwrap_or_else(|| abs.to_string_lossy().into_owned()),
1163            path: abs.clone(),
1164            kind,
1165            size: meta.len(),
1166            mtime_ms,
1167        })
1168    }
1169
1170    async fn list_dir(
1171        &self,
1172        path: &str,
1173        cancel: Option<&CancellationToken>,
1174    ) -> Result<Vec<FileInfo>, FileError> {
1175        check_cancel_file(cancel, Some(path))?;
1176        let abs = self.resolve_path(path);
1177        let mut entries = tokio::fs::read_dir(&abs)
1178            .await
1179            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1180        let mut out = Vec::new();
1181        while let Some(entry) = entries
1182            .next_entry()
1183            .await
1184            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?
1185        {
1186            if let Some(t) = cancel {
1187                if t.is_cancelled() {
1188                    return Err(FileError::aborted().with_path(abs.to_string_lossy()));
1189                }
1190            }
1191            let ep = entry.path();
1192            let meta = match tokio::fs::symlink_metadata(&ep).await {
1193                Ok(m) => m,
1194                Err(e) => {
1195                    // Skip unsupported types silently; propagate real stat errors.
1196                    let code = crate::error::io_to_file_code(&e);
1197                    if code == FileErrorCode::NotSupported {
1198                        continue;
1199                    }
1200                    return Err(io_to_file_error(e, Some(&ep.to_string_lossy())));
1201                }
1202            };
1203            let ft = meta.file_type();
1204            let kind = if ft.is_file() {
1205                FileKind::File
1206            } else if ft.is_dir() {
1207                FileKind::Directory
1208            } else if ft.is_symlink() {
1209                FileKind::Symlink
1210            } else {
1211                continue; // silently skip sockets/fifos/etc.
1212            };
1213            let mtime_ms = meta
1214                .modified()
1215                .ok()
1216                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1217                .map(|d| d.as_millis() as i64)
1218                .unwrap_or(0);
1219            out.push(FileInfo {
1220                name: entry.file_name().to_string_lossy().into_owned(),
1221                path: ep,
1222                kind,
1223                size: meta.len(),
1224                mtime_ms,
1225            });
1226        }
1227        Ok(out)
1228    }
1229
1230    async fn has_file_with_suffix(
1231        &self,
1232        path: &str,
1233        suffix: &str,
1234        cancel: Option<&CancellationToken>,
1235    ) -> Result<bool, FileError> {
1236        check_cancel_file(cancel, Some(path))?;
1237        let abs = self.resolve_path(path);
1238        let error_path = abs.to_string_lossy().into_owned();
1239        let suffix = String::from(suffix);
1240        let cancel = cancel.cloned();
1241        // One blocking job, not one lstat + runtime round-trip per entry. Session
1242        // existence checks need names/types only, not every sidecar's metadata.
1243        tokio::task::spawn_blocking(move || {
1244            check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1245            let entries = std::fs::read_dir(&abs)
1246                .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1247            for entry in entries {
1248                check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1249                let entry = entry.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1250                if !entry.file_name().to_string_lossy().ends_with(&suffix) {
1251                    continue;
1252                }
1253                let kind = match entry.file_type() {
1254                    Ok(kind) => kind,
1255                    Err(error)
1256                        if crate::error::io_to_file_code(&error) == FileErrorCode::NotSupported =>
1257                    {
1258                        continue
1259                    }
1260                    Err(error) => {
1261                        return Err(io_to_file_error(
1262                            error,
1263                            Some(&entry.path().to_string_lossy()),
1264                        ))
1265                    }
1266                };
1267                check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1268                if kind.is_file() || kind.is_symlink() {
1269                    return Ok(true);
1270                }
1271            }
1272            check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1273            Ok(false)
1274        })
1275        .await
1276        .map_err(|error| {
1277            FileError::new(
1278                FileErrorCode::Unknown,
1279                format!("directory scan task failed: {error}"),
1280            )
1281            .with_path(error_path)
1282        })?
1283    }
1284
1285    async fn canonical_path(
1286        &self,
1287        path: &str,
1288        cancel: Option<&CancellationToken>,
1289    ) -> Result<PathBuf, FileError> {
1290        check_cancel_file(cancel, Some(path))?;
1291        let abs = self.resolve_path(path);
1292        tokio::fs::canonicalize(&abs)
1293            .await
1294            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
1295    }
1296
1297    async fn exists(
1298        &self,
1299        path: &str,
1300        cancel: Option<&CancellationToken>,
1301    ) -> Result<bool, FileError> {
1302        check_cancel_file(cancel, Some(path))?;
1303        let abs = self.resolve_path(path);
1304        match tokio::fs::symlink_metadata(&abs).await {
1305            Ok(_) => Ok(true),
1306            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
1307            Err(e) => Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
1308        }
1309    }
1310
1311    async fn create_dir(
1312        &self,
1313        path: &str,
1314        recursive: bool,
1315        cancel: Option<&CancellationToken>,
1316    ) -> Result<(), FileError> {
1317        check_cancel_file(cancel, Some(path))?;
1318        let abs = self.resolve_path(path);
1319        let res = if recursive {
1320            tokio::fs::create_dir_all(&abs).await
1321        } else {
1322            tokio::fs::create_dir(&abs).await
1323        };
1324        res.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
1325    }
1326
1327    async fn remove(
1328        &self,
1329        path: &str,
1330        recursive: bool,
1331        force: bool,
1332        cancel: Option<&CancellationToken>,
1333    ) -> Result<(), FileError> {
1334        check_cancel_file(cancel, Some(path))?;
1335        let abs = self.resolve_path(path);
1336        let res = if recursive {
1337            tokio::fs::remove_dir_all(&abs).await
1338        } else {
1339            // Try file first, then empty dir.
1340            match tokio::fs::remove_file(&abs).await {
1341                Ok(()) => Ok(()),
1342                Err(_) => tokio::fs::remove_dir(&abs).await,
1343            }
1344        };
1345        match res {
1346            Ok(()) => Ok(()),
1347            Err(e) if e.kind() == std::io::ErrorKind::NotFound && force => Ok(()),
1348            Err(e) => Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
1349        }
1350    }
1351
1352    async fn create_temp_dir(
1353        &self,
1354        prefix: Option<&str>,
1355        cancel: Option<&CancellationToken>,
1356    ) -> Result<PathBuf, FileError> {
1357        check_cancel_file(cancel, None)?;
1358        let prefix = prefix.unwrap_or("tmp-");
1359        // Use tempfile's NamedTempFile-less builder for a dir.
1360        let tmp =
1361            tempfile::tempdir_in(std::env::temp_dir()).map_err(|e| io_to_file_error(e, None))?;
1362        // tempfile picks a random name; rename to include the prefix.
1363        let path = tmp.path().to_path_buf();
1364        std::mem::forget(tmp); // keep the dir alive; caller manages cleanup.
1365                               // Build a prefixed sibling.
1366        let final_path = std::env::temp_dir().join(format!("{}{}", prefix, random_suffix()));
1367        // Rename the tempdir into the prefixed path.
1368        if let Err(e) = tokio::fs::rename(&path, &final_path).await {
1369            // Fallback: just return the original random path.
1370            let _ = e;
1371            return Ok(path);
1372        }
1373        Ok(final_path)
1374    }
1375
1376    async fn create_temp_file(
1377        &self,
1378        prefix: &str,
1379        suffix: &str,
1380        cancel: Option<&CancellationToken>,
1381    ) -> Result<PathBuf, FileError> {
1382        check_cancel_file(cancel, None)?;
1383        // Create an isolated temp dir (matching the TS pattern of one dir per
1384        // file), then write an empty file named `<prefix><random><suffix>`.
1385        let dir = self.create_temp_dir(Some("tmp-"), cancel).await?;
1386        let name = format!("{}{}{}", prefix, random_suffix(), suffix);
1387        let path = dir.join(name);
1388        tokio::fs::File::create(&path)
1389            .await
1390            .map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))?;
1391        Ok(path)
1392    }
1393
1394    async fn cleanup(&self) {
1395        let pids: Vec<u32> = self
1396            .active_pids
1397            .lock()
1398            .unwrap_or_else(|e| e.into_inner())
1399            .iter()
1400            .copied()
1401            .collect();
1402        for pid in pids {
1403            kill_process_tree(pid).await;
1404        }
1405        self.active_pids
1406            .lock()
1407            .unwrap_or_else(|e| e.into_inner())
1408            .clear();
1409    }
1410}
1411
1412/// Read a file to bytes, honoring cooperative cancellation.
1413async fn read_cancellable(
1414    path: &Path,
1415    cancel: Option<&CancellationToken>,
1416) -> Result<Vec<u8>, FileError> {
1417    let read = tokio::fs::read(path);
1418    let res = match cancel {
1419        Some(t) => tokio::select! {
1420            r = read => r,
1421            _ = t.cancelled() => return Err(FileError::aborted().with_path(path.to_string_lossy())),
1422        },
1423        None => read.await,
1424    };
1425    res.map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))
1426}
1427
1428/// Observe cancellation immediately before opening the destination. Once
1429/// truncation can begin, wait for the write and report its actual I/O result.
1430async fn write_cancellable(
1431    path: PathBuf,
1432    content: FileContent,
1433    cancel: Option<&CancellationToken>,
1434) -> Result<(), FileError> {
1435    let task_path = path.clone();
1436    let cancel = cancel.cloned();
1437    tokio::task::spawn_blocking(move || {
1438        let path = task_path.to_string_lossy();
1439        check_cancel_file(cancel.as_ref(), Some(&path))?;
1440        let write = || -> std::io::Result<()> {
1441            let mut file = std::fs::File::create(&task_path)?;
1442            file.write_all(content.as_bytes())?;
1443            file.flush()
1444        };
1445        write().map_err(|error| io_to_file_error(error, Some(&path)))
1446    })
1447    .await
1448    .map_err(|error| {
1449        FileError::new(FileErrorCode::Unknown, "file write task failed")
1450            .with_path(path.to_string_lossy())
1451            .with_source(Box::new(error))
1452    })?
1453}
1454
1455fn random_suffix() -> String {
1456    // Short random suffix via uuid v4 (no Time—it's a UUID, not a timestamp).
1457    uuid::Uuid::new_v4().simple().to_string()
1458}
1459
1460async fn drain_shell_pipe(
1461    pipe: Option<impl tokio::io::AsyncRead + Unpin>,
1462    mut callback: Option<Box<dyn FnMut(&str) + Send + '_>>,
1463    retained: &mut String,
1464    streamed: Option<&tokio::sync::mpsc::Sender<String>>,
1465    shell_exited: &CancellationToken,
1466    cancel: Option<&CancellationToken>,
1467) {
1468    use tokio::io::AsyncReadExt;
1469    use tokio::time::{timeout, Duration, Instant};
1470
1471    let Some(mut pipe) = pipe else { return };
1472    let mut buffer = [0u8; 8192];
1473    let mut decoder = crate::output_decode::StreamDecoder::new();
1474    let mut drain_budget = Duration::from_millis(EXIT_STDIO_GRACE_MS);
1475    let cancelled = async {
1476        match cancel {
1477            Some(token) => token.cancelled().await,
1478            None => std::future::pending::<()>().await,
1479        }
1480    };
1481    tokio::pin!(cancelled);
1482    loop {
1483        let read = async {
1484            let read = pipe.read(&mut buffer);
1485            tokio::pin!(read);
1486            tokio::select! {
1487                biased;
1488                _ = shell_exited.cancelled() => {},
1489                result = &mut read => return result.unwrap_or(0),
1490            }
1491
1492            // Apply the post-exit budget only to reading the pipe. Time spent
1493            // delivering a chunk to a slow consumer must not cut off later reads.
1494            if drain_budget.is_zero() {
1495                return 0;
1496            }
1497            let started = Instant::now();
1498            let result = timeout(drain_budget, &mut read).await;
1499            drain_budget = drain_budget.saturating_sub(started.elapsed());
1500            result.ok().and_then(Result::ok).unwrap_or(0)
1501        };
1502        let count = tokio::select! {
1503            biased;
1504            _ = &mut cancelled => 0,
1505            count = read => count,
1506        };
1507        let chunk = if count == 0 {
1508            decoder.finish()
1509        } else {
1510            decoder.push(&buffer[..count])
1511        };
1512        if !chunk.is_empty() {
1513            if let Some(callback) = callback.as_mut() {
1514                callback(&chunk);
1515            }
1516            if let Some(sender) = streamed {
1517                let _ = sender.send(chunk).await;
1518            } else {
1519                retained.push_str(&chunk);
1520            }
1521        }
1522        if count == 0 {
1523            break;
1524        }
1525    }
1526}
1527
1528impl OsExecutionEnv {
1529    async fn exec_inner(
1530        &self,
1531        command: &str,
1532        options: ShellExecOptions<'_>,
1533        streamed: Option<tokio::sync::mpsc::Sender<String>>,
1534    ) -> Result<ShellOutput, ExecutionError> {
1535        // Pre-flight abort.
1536        check_cancel_exec(options.cancel)?;
1537        // Resolve timeout.
1538        let timeout = match resolve_timeout(options.timeout) {
1539            Ok(t) => t,
1540            Err(e) => return Err(e),
1541        };
1542        // Resolve cwd.
1543        let cwd = match &options.cwd {
1544            Some(c) => self.resolve_path(&c.to_string_lossy()),
1545            None => self.cwd.clone(),
1546        };
1547        // Shell config. An explicit override is used by native shell tools
1548        // such as PowerShell; otherwise preserve the default Bash behavior.
1549        let shell_cfg = match &options.shell {
1550            Some(override_shell) => ShellConfig {
1551                shell: override_shell.program.clone(),
1552                args: override_shell.args.clone(),
1553                transport: CommandTransport::Argv,
1554            },
1555            None => self.get_shell_config().await?,
1556        };
1557        self.exec_configured(command, options, streamed, shell_cfg, timeout, cwd)
1558            .await
1559    }
1560
1561    async fn exec_configured(
1562        &self,
1563        command: &str,
1564        options: ShellExecOptions<'_>,
1565        streamed: Option<tokio::sync::mpsc::Sender<String>>,
1566        shell_cfg: ShellConfig,
1567        timeout: Option<std::time::Duration>,
1568        cwd: PathBuf,
1569    ) -> Result<ShellOutput, ExecutionError> {
1570        // Verify cwd exists.
1571        if !cwd.exists() {
1572            return Err(ExecutionError::new(
1573                ExecutionErrorCode::SpawnError,
1574                format!(
1575                    "Working directory does not exist: {}\nCannot execute bash commands.",
1576                    cwd.display()
1577                ),
1578            ));
1579        }
1580
1581        check_cancel_exec(options.cancel)?;
1582        // Build the spawn.
1583        let mut cmd = tokio::process::Command::new(&shell_cfg.shell);
1584        cmd.current_dir(&cwd);
1585        cmd.env_clear();
1586        // Non-interactive defaults apply even when `inherit_env` is false: a
1587        // caller asking for a clean environment is not asking for a prompt.
1588        // They sit before the inherit loop so any explicit value wins.
1589        for (k, v) in NON_INTERACTIVE_SHELL_ENV {
1590            cmd.env(k, v);
1591        }
1592        // Default Git Bash to UTF-8 while preserving explicit POSIX locale
1593        // overrides. LC_ALL would mask LANG and the individual LC_* values.
1594        #[cfg(windows)]
1595        if options.shell.is_none() {
1596            cmd.env("LANG", "C.UTF-8");
1597        }
1598        // Environment: inherit + shell_env + per-call. The host's own private
1599        // plumbing (`HOST_PRIVATE_ENV`) is skipped: it describes *this* process,
1600        // not the shell or anything the shell runs, and inheriting it makes a
1601        // nested `rpi` misreport its session. A caller that genuinely wants a
1602        // value passed down can still set it explicitly through `env`/`shell_env`
1603        // below (those are applied after this loop and win).
1604        if options.inherit_env {
1605            let mut inherit = |name: &str, value: &str| {
1606                if !is_host_private_env(name) {
1607                    cmd.env(name, value);
1608                }
1609            };
1610            match &self.environment {
1611                Some(environment) => {
1612                    for (name, value) in environment {
1613                        inherit(name, value);
1614                    }
1615                }
1616                None => {
1617                    for (name, value) in std::env::vars() {
1618                        inherit(&name, &value);
1619                    }
1620                }
1621            }
1622        }
1623        if let Some(base) = &self.shell_env {
1624            for (k, v) in base {
1625                cmd.env(k, v);
1626            }
1627        }
1628        if let Some(extra) = &options.env {
1629            for (k, v) in extra {
1630                cmd.env(k, v);
1631            }
1632        }
1633        // stdio.
1634        cmd.kill_on_drop(true);
1635        cmd.stdout(std::process::Stdio::piped());
1636        cmd.stderr(std::process::Stdio::piped());
1637        #[cfg(unix)]
1638        {
1639            cmd.process_group(0); // child becomes its own group leader.
1640        }
1641        #[cfg(windows)]
1642        {
1643            use windows_sys::Win32::System::Threading::{CREATE_NO_WINDOW, CREATE_SUSPENDED};
1644            // Suspended until it is in its job (see `shell_jobs::start`).
1645            cmd.creation_flags(CREATE_NO_WINDOW | CREATE_SUSPENDED);
1646        }
1647
1648        cmd.args(&shell_cfg.args);
1649        match shell_cfg.transport {
1650            CommandTransport::Argv => {
1651                // Commands given as arguments have no input. Provide EOF from
1652                // spawn, even while another thread is launching a process.
1653                cmd.stdin(std::process::Stdio::null());
1654                cmd.arg(command);
1655            }
1656            CommandTransport::Stdin => {
1657                // Legacy WSL bash reads the script from stdin via `bash -s`.
1658                cmd.stdin(std::process::Stdio::piped());
1659            }
1660        }
1661
1662        let mut child = match cmd.spawn() {
1663            Ok(c) => c,
1664            Err(e) => {
1665                return Err(ExecutionError::new(
1666                    ExecutionErrorCode::SpawnError,
1667                    format!("failed to spawn shell: {e}"),
1668                ));
1669            }
1670        };
1671        let pid = child.id();
1672        let mut process_guard = ShellProcessGuard {
1673            pid,
1674            active: self.active_pids.clone(),
1675        };
1676        #[cfg(windows)]
1677        {
1678            let started = match (pid, child.raw_handle()) {
1679                (Some(pid), Some(process)) => shell_jobs::start(pid, process),
1680                _ => Err("the shell has no process handle".to_owned()),
1681            };
1682            if let Err(error) = started {
1683                if let Some(pid) = pid {
1684                    shell_jobs::forget(pid);
1685                }
1686                let _ = child.start_kill();
1687                return Err(ExecutionError::new(
1688                    ExecutionErrorCode::SpawnError,
1689                    format!("failed to start shell: {error}"),
1690                ));
1691            }
1692        }
1693        if let Some(pid) = pid {
1694            self.active_pids
1695                .lock()
1696                .unwrap_or_else(|e| e.into_inner())
1697                .insert(pid);
1698        }
1699
1700        let stdin = child.stdin.take();
1701        let stop_input = CancellationToken::new();
1702        let deadline = timeout.map(|duration| tokio::time::Instant::now() + duration);
1703        let mut stdout_buf = String::new();
1704        let mut stderr_buf = String::new();
1705        let cancel = options.cancel;
1706        let shell_exited = CancellationToken::new();
1707        let stdout_task = drain_shell_pipe(
1708            child.stdout.take(),
1709            options.on_stdout,
1710            &mut stdout_buf,
1711            streamed.as_ref(),
1712            &shell_exited,
1713            cancel,
1714        );
1715        let stderr_task = drain_shell_pipe(
1716            child.stderr.take(),
1717            options.on_stderr,
1718            &mut stderr_buf,
1719            streamed.as_ref(),
1720            &shell_exited,
1721            cancel,
1722        );
1723
1724        // Drive script input, both output pipes, and process termination
1725        // together. A shell can fill an output pipe before reading more stdin.
1726        let mut timed_out = false;
1727        let exit_status = {
1728            let status_fut = async {
1729                let expired = async {
1730                    match deadline {
1731                        Some(at) => tokio::time::sleep_until(at).await,
1732                        None => std::future::pending::<()>().await,
1733                    }
1734                };
1735                let cancelled = async {
1736                    match cancel {
1737                        Some(token) => token.cancelled().await,
1738                        None => std::future::pending::<()>().await,
1739                    }
1740                };
1741                tokio::select! {
1742                    status = child.wait() => return status,
1743                    () = expired => timed_out = true,
1744                    () = cancelled => {}
1745                }
1746                stop_input.cancel();
1747                if let Some(pid) = child.id() {
1748                    kill_process_tree(pid).await;
1749                }
1750                child.wait().await
1751            };
1752            tokio::pin!(status_fut, stdout_task, stderr_task);
1753            let (mut stdout_done, mut stderr_done) = (false, false);
1754            let status_res = {
1755                let stdin_task = async {
1756                    let Some(mut stdin) = stdin else { return };
1757                    use tokio::io::AsyncWriteExt;
1758
1759                    // Dropping the pipe signals EOF to bash -s. A shell that
1760                    // exits early can close it first and still report its own
1761                    // exit status.
1762                    tokio::select! {
1763                        biased;
1764                        () = stop_input.cancelled() => {}
1765                        () = async {
1766                            if stdin.write_all(command.as_bytes()).await.is_ok() {
1767                                let _ = stdin.flush().await;
1768                            }
1769                        } => {}
1770                    }
1771                };
1772                tokio::pin!(stdin_task);
1773                let mut stdin_done = false;
1774                loop {
1775                    tokio::select! {
1776                        status = &mut status_fut => break status,
1777                        () = &mut stdin_task, if !stdin_done => stdin_done = true,
1778                        () = &mut stdout_task, if !stdout_done => stdout_done = true,
1779                        () = &mut stderr_task, if !stderr_done => stderr_done = true,
1780                    }
1781                }
1782            };
1783            // Disarm immediately after a successful wait, before any await:
1784            // the shell has been reaped and its PID may now be reused.
1785            if status_res.is_ok() {
1786                process_guard.finish();
1787            }
1788            // Each reader now limits time spent on its pipe so an inherited
1789            // pipe can't hold the call open. Join both readers through delivery.
1790            shell_exited.cancel();
1791            tokio::join!(
1792                async {
1793                    if !stdout_done {
1794                        (&mut stdout_task).await;
1795                    }
1796                },
1797                async {
1798                    if !stderr_done {
1799                        (&mut stderr_task).await;
1800                    }
1801                },
1802            );
1803            status_res
1804        };
1805
1806        // Give trailing stdio a brief grace period. Only the timed-out and
1807        // cancelled paths still owe a wait: on the normal path the drain above
1808        // already capped it.
1809        if timed_out {
1810            let _ = tokio::time::sleep(std::time::Duration::from_millis(EXIT_STDIO_GRACE_MS)).await;
1811        }
1812
1813        // Resolution priority: timedOut → cancelled → status.
1814        let status = match exit_status {
1815            Ok(s) => s,
1816            Err(e) => {
1817                return Err(ExecutionError::new(
1818                    ExecutionErrorCode::SpawnError,
1819                    format!("child wait failed: {e}"),
1820                ));
1821            }
1822        };
1823        if timed_out {
1824            return Err(ExecutionError::timeout(
1825                options.timeout.map(|f| f as u64).unwrap_or(0),
1826            ));
1827        }
1828        if cancel.map(|t| t.is_cancelled()).unwrap_or(false) {
1829            return Err(ExecutionError::aborted());
1830        }
1831        let exit_code = status.code().unwrap_or(0);
1832        Ok(ShellOutput {
1833            stdout: stdout_buf,
1834            stderr: stderr_buf,
1835            exit_code,
1836        })
1837    }
1838}
1839
1840#[async_trait]
1841impl Shell for OsExecutionEnv {
1842    async fn exec<'a>(
1843        &'a self,
1844        command: &str,
1845        options: ShellExecOptions<'a>,
1846    ) -> Result<ShellOutput, ExecutionError> {
1847        self.exec_inner(command, options, None).await
1848    }
1849
1850    async fn exec_streamed<'a>(
1851        &'a self,
1852        command: &str,
1853        options: ShellExecOptions<'a>,
1854        output: tokio::sync::mpsc::Sender<String>,
1855    ) -> Result<i32, ExecutionError> {
1856        self.exec_inner(command, options, Some(output))
1857            .await
1858            .map(|result| result.exit_code)
1859    }
1860
1861    async fn cleanup(&self) {
1862        FileSystem::cleanup(self).await
1863    }
1864}
1865
1866#[async_trait]
1867impl ExecutionEnv for OsExecutionEnv {}
1868
1869#[async_trait]
1870impl MutatingEnv for OsExecutionEnv {
1871    fn as_env(&self) -> &dyn ExecutionEnv {
1872        self
1873    }
1874    fn mutation_registry(&self) -> &MutationQueueRegistry {
1875        &self.registry
1876    }
1877}
1878
1879#[cfg(test)]
1880mod stdin_transport_tests {
1881    use super::*;
1882    use std::time::Duration;
1883
1884    fn long_script(first: &str, last: &str) -> String {
1885        format!(
1886            "{first}\n{}{last}\n",
1887            "# benign stdin pipe fixture data\n".repeat(64 * 1024)
1888        )
1889    }
1890
1891    async fn exec_stdin(
1892        env: &OsExecutionEnv,
1893        script: &str,
1894        options: ShellExecOptions<'_>,
1895    ) -> Result<ShellOutput, ExecutionError> {
1896        let config = ShellConfig {
1897            shell: env.get_shell_config().await?.shell,
1898            args: vec!["-s".to_owned()],
1899            transport: CommandTransport::Stdin,
1900        };
1901        let timeout = resolve_timeout(options.timeout)?;
1902        env.exec_configured(script, options, None, config, timeout, env.cwd.clone())
1903            .await
1904    }
1905
1906    #[tokio::test]
1907    async fn stdin_transport_drains_output_while_sending_the_script() {
1908        let temp = tempfile::tempdir().unwrap();
1909        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1910        let script = long_script(
1911            "head -c 262144 /dev/zero | tr '\\0' a; head -c 262144 /dev/zero | tr '\\0' b >&2",
1912            "printf 'end of script'",
1913        );
1914        let output = tokio::time::timeout(
1915            Duration::from_secs(4),
1916            exec_stdin(
1917                &env,
1918                &script,
1919                ShellExecOptions {
1920                    timeout: Some(3.0),
1921                    ..Default::default()
1922                },
1923            ),
1924        )
1925        .await
1926        .expect("shell blocked feeding stdin while its output pipes were full");
1927        let output = match output {
1928            Err(error) if error.code == ExecutionErrorCode::ShellUnavailable => return,
1929            output => output.unwrap(),
1930        };
1931        assert_eq!(output.exit_code, 0);
1932        assert_eq!(output.stdout.len(), 262144 + "end of script".len());
1933        assert!(output.stdout.ends_with("end of script"));
1934        assert_eq!(output.stderr.len(), 262144);
1935        assert!(output.stderr.bytes().all(|byte| byte == b'b'));
1936    }
1937
1938    #[tokio::test]
1939    async fn stdin_transport_timeout_covers_blocked_script_upload() {
1940        let temp = tempfile::tempdir().unwrap();
1941        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1942        let script = long_script("sleep 30", "printf 'unexpected completion'");
1943        let error = tokio::time::timeout(
1944            Duration::from_secs(3),
1945            exec_stdin(
1946                &env,
1947                &script,
1948                ShellExecOptions {
1949                    timeout: Some(0.15),
1950                    ..Default::default()
1951                },
1952            ),
1953        )
1954        .await
1955        .expect("command timeout did not start while stdin was blocked")
1956        .unwrap_err();
1957        if error.code == ExecutionErrorCode::ShellUnavailable {
1958            return;
1959        }
1960        assert_eq!(error.code, ExecutionErrorCode::Timeout);
1961    }
1962
1963    #[tokio::test]
1964    async fn stdin_transport_cancellation_covers_blocked_script_upload() {
1965        let temp = tempfile::tempdir().unwrap();
1966        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1967        let script = long_script("sleep 30", "printf 'unexpected completion'");
1968        let signal = CancellationToken::new();
1969        let (result, ()) = tokio::join!(
1970            tokio::time::timeout(
1971                Duration::from_secs(3),
1972                exec_stdin(
1973                    &env,
1974                    &script,
1975                    ShellExecOptions {
1976                        cancel: Some(&signal),
1977                        ..Default::default()
1978                    },
1979                ),
1980            ),
1981            async {
1982                tokio::time::sleep(Duration::from_millis(150)).await;
1983                signal.cancel();
1984            },
1985        );
1986        let error = result
1987            .expect("cancellation was not observed while stdin was blocked")
1988            .unwrap_err();
1989        if error.code == ExecutionErrorCode::ShellUnavailable {
1990            return;
1991        }
1992        assert_eq!(error.code, ExecutionErrorCode::Aborted);
1993    }
1994
1995    #[tokio::test]
1996    async fn stdin_transport_keeps_a_deliberate_early_exit_code() {
1997        let temp = tempfile::tempdir().unwrap();
1998        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1999        let script = long_script(
2000            "printf 'early exit'; exit 7",
2001            "printf 'unexpected completion'",
2002        );
2003        let result = tokio::time::timeout(
2004            Duration::from_secs(3),
2005            exec_stdin(&env, &script, ShellExecOptions::default()),
2006        )
2007        .await
2008        .expect("shell blocked after closing its stdin");
2009        let output = match result {
2010            Err(error) if error.code == ExecutionErrorCode::ShellUnavailable => return,
2011            output => output.unwrap(),
2012        };
2013        assert_eq!(output.exit_code, 7);
2014        assert_eq!(output.stdout, "early exit");
2015    }
2016}
2017
2018#[cfg(test)]
2019mod durability_tests {
2020    use super::*;
2021
2022    #[test]
2023    fn queued_overwrite_cancelled_before_open_preserves_existing_bytes() {
2024        let runtime = tokio::runtime::Builder::new_current_thread()
2025            .enable_all()
2026            .max_blocking_threads(1)
2027            .build()
2028            .unwrap();
2029        runtime.block_on(async {
2030            let temp = tempfile::tempdir().unwrap();
2031            let path = temp.path().join("note.txt");
2032            std::fs::write(&path, b"original").unwrap();
2033            let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
2034            let (release_tx, release_rx) = std::sync::mpsc::channel();
2035            let blocker = tokio::task::spawn_blocking(move || {
2036                entered_tx.send(()).unwrap();
2037                release_rx.recv().unwrap();
2038            });
2039            entered_rx.await.unwrap();
2040
2041            let signal = CancellationToken::new();
2042            let write = write_cancellable(
2043                path.clone(),
2044                FileContent::Text("replacement".into()),
2045                Some(&signal),
2046            );
2047            tokio::pin!(write);
2048            let queued = futures::poll!(&mut write).is_pending();
2049            signal.cancel();
2050            release_tx.send(()).unwrap();
2051            blocker.await.unwrap();
2052
2053            assert!(queued, "overwrite should be queued on the blocking pool");
2054            let result = write.await;
2055            let contents = std::fs::read(&path).unwrap();
2056            assert_eq!(
2057                contents, b"original",
2058                "queued cancellation changed the file (write result: {result:?})"
2059            );
2060            assert_eq!(result.unwrap_err().code, FileErrorCode::Aborted);
2061        });
2062    }
2063
2064    #[tokio::test]
2065    async fn os_backend_syncs_staged_file_and_publication_directory() {
2066        let temp = tempfile::tempdir().unwrap();
2067        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
2068        env.write_file("staged", FileContent::Text("durable slice".into()), None)
2069            .await
2070            .unwrap();
2071        env.sync_file("staged", false, None).await.unwrap();
2072        env.sync_directory(".", None).await.unwrap();
2073    }
2074
2075    #[tokio::test]
2076    async fn os_writer_lease_persists_and_verifies_a_monotonic_fence() {
2077        let temp = tempfile::tempdir().unwrap();
2078        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
2079        let first = env
2080            .try_acquire_writer_lease("journal.jsonl")
2081            .await
2082            .unwrap()
2083            .unwrap();
2084        first.verify_fence().unwrap();
2085        drop(first);
2086        let second = env
2087            .try_acquire_writer_lease("journal.jsonl")
2088            .await
2089            .unwrap()
2090            .unwrap();
2091        second.verify_fence().unwrap();
2092        drop(second);
2093        assert_eq!(
2094            std::fs::read_to_string(temp.path().join("journal.jsonl.lock")).unwrap(),
2095            "2"
2096        );
2097    }
2098
2099    #[cfg(unix)]
2100    #[tokio::test]
2101    async fn os_writer_lease_releases_a_shared_open_file_description() {
2102        let temp = tempfile::tempdir().unwrap();
2103        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
2104        let lock = temp.path().join("journal.jsonl.lock");
2105        std::fs::write(&lock, "1").unwrap();
2106        let file = std::fs::OpenOptions::new()
2107            .read(true)
2108            .write(true)
2109            .open(&lock)
2110            .unwrap();
2111        fs2::FileExt::try_lock_exclusive(&file).unwrap();
2112        let inherited = file.try_clone().unwrap();
2113        let lease = OsWriterLease { file, fence: 1 };
2114        assert!(env.try_acquire_writer_lease("journal.jsonl").await.is_err());
2115        drop(lease);
2116        let next = env
2117            .try_acquire_writer_lease("journal.jsonl")
2118            .await
2119            .expect("retired writer retained a lock through the shared description")
2120            .unwrap();
2121        next.verify_fence().unwrap();
2122        assert_eq!(std::fs::read_to_string(lock).unwrap(), "2");
2123        drop(inherited);
2124    }
2125}
2126
2127/// Shell discovery on Windows. The bug these guard: on a machine with Git for
2128/// Windows installed outside `%ProgramFiles%` (e.g. `D:\Git`), the old probe
2129/// missed it and fell through to `where bash.exe`, whose first hit is the WSL
2130/// launcher in `System32` — a stub that exits 1 writing UTF-16LE.
2131#[cfg(all(test, windows))]
2132mod windows_shell_tests {
2133    use super::*;
2134    use std::sync::Mutex;
2135
2136    /// `RPI_BASH_PATH` is process-global, so these tests must not overlap.
2137    static ENV_LOCK: Mutex<()> = Mutex::new(());
2138
2139    fn lock_env() -> std::sync::MutexGuard<'static, ()> {
2140        ENV_LOCK
2141            .lock()
2142            .unwrap_or_else(|poisoned| poisoned.into_inner())
2143    }
2144
2145    /// Clears `RPI_BASH_PATH` even if an assertion panics.
2146    struct EnvGuard;
2147    impl Drop for EnvGuard {
2148        fn drop(&mut self) {
2149            std::env::remove_var(BASH_PATH_ENV);
2150        }
2151    }
2152
2153    #[test]
2154    fn wsl_launcher_is_recognised_on_any_drive_and_separator() {
2155        for path in [
2156            r"C:\Windows\System32\bash.exe",
2157            r"c:\windows\system32\BASH.EXE",
2158            "C:/Windows/System32/bash.exe",
2159            r"D:\Windows\Sysnative\bash.exe",
2160        ] {
2161            assert!(is_legacy_wsl_bash_path(Path::new(path)), "{path}");
2162        }
2163        for path in [
2164            r"D:\Git\bin\bash.exe",
2165            r"C:\Program Files\Git\usr\bin\bash.exe",
2166            r"C:\msys64\usr\bin\bash.exe",
2167            r"C:\Windows\System32\notbash.exe",
2168        ] {
2169            assert!(!is_legacy_wsl_bash_path(Path::new(path)), "{path}");
2170        }
2171    }
2172
2173    #[test]
2174    fn git_exe_maps_to_its_install_root() {
2175        for (exe, root) in [
2176            (r"D:\Git\cmd\git.exe", r"D:\Git"),
2177            (r"D:\Git\bin\git.exe", r"D:\Git"),
2178            (r"D:\Git\mingw64\bin\git.exe", r"D:\Git"),
2179            (r"D:\Git\mingw32\bin\git.exe", r"D:\Git"),
2180        ] {
2181            assert_eq!(
2182                git_install_root(Path::new(exe)),
2183                Some(PathBuf::from(root)),
2184                "{exe}"
2185            );
2186        }
2187        // Not a Git for Windows layout: do not invent a root.
2188        assert_eq!(git_install_root(Path::new(r"D:\tools\git.exe")), None);
2189    }
2190
2191    #[test]
2192    fn wsl_launcher_is_refused_before_it_reaches_the_spawn() {
2193        let error = validate_bash_path(
2194            Path::new(r"C:\Windows\System32\bash.exe"),
2195            "Configured shellPath",
2196        )
2197        .expect_err("WSL is not a supported shell");
2198        assert_eq!(error.code, ExecutionErrorCode::ShellUnavailable);
2199        assert!(error.to_string().contains("WSL"), "{error}");
2200        assert!(error.to_string().contains(BASH_PATH_ENV), "{error}");
2201    }
2202
2203    #[tokio::test]
2204    async fn explicit_bash_path_env_wins_over_discovery() {
2205        let _lock = lock_env();
2206        let _guard = EnvGuard;
2207        let temp = tempfile::tempdir().unwrap();
2208        let fake = temp.path().join("bash.exe");
2209        std::fs::write(&fake, b"").unwrap();
2210        std::env::set_var(BASH_PATH_ENV, &fake);
2211
2212        let config = windows_probe_bash().await.expect("explicit bash path");
2213        assert_eq!(config.shell, fake);
2214        assert_eq!(config.args, vec!["-c".to_string()]);
2215    }
2216
2217    #[tokio::test]
2218    async fn missing_explicit_bash_path_fails_loudly() {
2219        let _lock = lock_env();
2220        let _guard = EnvGuard;
2221        let missing = std::env::temp_dir().join("rpi-no-such-bash.exe");
2222        std::env::set_var(BASH_PATH_ENV, &missing);
2223
2224        let error = windows_probe_bash()
2225            .await
2226            .expect_err("a broken override must not fall back");
2227        assert_eq!(error.code, ExecutionErrorCode::ShellUnavailable);
2228        assert!(error.to_string().contains(BASH_PATH_ENV), "{error}");
2229        assert!(error.to_string().contains("not found"), "{error}");
2230    }
2231
2232    #[tokio::test]
2233    async fn wsl_explicit_bash_path_fails_loudly() {
2234        let _lock = lock_env();
2235        let _guard = EnvGuard;
2236        std::env::set_var(BASH_PATH_ENV, r"C:\Windows\System32\bash.exe");
2237
2238        let error = windows_probe_bash()
2239            .await
2240            .expect_err("WSL must not be accepted as the shell");
2241        assert_eq!(error.code, ExecutionErrorCode::ShellUnavailable);
2242        assert!(error.to_string().contains("WSL"), "{error}");
2243    }
2244}
2245
2246/// Validate a timeout (seconds). Mirrors `resolveTimeoutMs` semantics.
2247fn resolve_timeout(timeout: Option<f64>) -> Result<Option<std::time::Duration>, ExecutionError> {
2248    match timeout {
2249        None => Ok(None),
2250        Some(secs) => {
2251            if !secs.is_finite() || secs <= 0.0 {
2252                return Err(ExecutionError::new(
2253                    ExecutionErrorCode::Timeout,
2254                    "Invalid timeout: must be a finite number of seconds",
2255                ));
2256            }
2257            let ms = secs * 1000.0;
2258            if ms > MAX_TIMEOUT_MS as f64 {
2259                return Err(ExecutionError::new(
2260                    ExecutionErrorCode::Timeout,
2261                    format!(
2262                        "Invalid timeout: maximum is {} seconds",
2263                        MAX_TIMEOUT_SECONDS
2264                    ),
2265                ));
2266            }
2267            Ok(Some(std::time::Duration::from_secs_f64(secs)))
2268        }
2269    }
2270}