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 → Windows
11//! git-bash probe (`ProgramFiles\Git\bin\bash.exe`, `ProgramFiles(x86)\…`) →
12//! `where bash.exe` → POSIX `/bin/bash` → `which bash` → `/bin/sh` fallback
13//! (POSIX only). **No cmd.exe fallback** on Windows — failure is
14//! `ExecutionError::ShellUnavailable`. Legacy WSL bash (`System32\bash.exe`)
15//! uses `bash -s` stdin transport to avoid argv parse bugs.
16//!
17//! Kill tree: Windows terminates the shell's job object, falling back to
18//! `taskkill /F /T /PID`; POSIX `kill -PG` (process group, since the child is
19//! spawned as its own group leader) with fallback to `kill -PID`. Best-effort,
20//! errors swallowed.
21//!
22//! `exec` abort+timeout bracketing (plan §5.4): the spawn is `tokio::select!`-ed
23//! against the cancellation token and `tokio::time::timeout`. Resolution
24//! priority: callbackError → timeout → aborted → exit-code-from-success.
25//! `cleanup()` kills tracked child pids best-effort.
26
27use std::collections::{HashMap, HashSet};
28use std::io::{Read, Seek, SeekFrom, Write};
29use std::path::{Path, PathBuf};
30use std::sync::{Arc, Mutex};
31
32use async_trait::async_trait;
33use tokio_util::sync::CancellationToken;
34
35use crate::env::{
36    check_cancel_exec, check_cancel_file, ExecutionEnv, FileContent, FileInfo, FileKind,
37    FileSystem, Shell, ShellExecOptions, ShellOutput, WriterLease,
38};
39use crate::error::{
40    io_to_file_error, ExecutionError, ExecutionErrorCode, FileError, FileErrorCode,
41};
42use crate::file_mutation_queue::{MutatingEnv, MutationQueueRegistry};
43
44/// Max timeout in ms (Int32 max). Mirrors `MAX_TIMEOUT_MS`.
45const MAX_TIMEOUT_MS: u64 = 2_147_483_647;
46/// Max timeout in seconds. Mirrors `MAX_TIMEOUT_SECONDS`.
47const MAX_TIMEOUT_SECONDS: f64 = 2_147_483.647;
48/// Grace period after child exit for trailing stdio. Mirrors
49/// `EXIT_STDIO_GRACE_MS`.
50const EXIT_STDIO_GRACE_MS: u64 = 100;
51
52/// Non-interactive defaults for every spawned shell. A tool call has no
53/// terminal the user can answer: `git` with no credential helper opens
54/// `/dev/tty` directly for `Username for 'https://…':`, bypassing the piped
55/// stdin/stdout/stderr (and the deliberate stdin-close in `exec`). That writes
56/// over the TUI frame as text the editor never owned — so it cannot be selected
57/// or deleted — and blocks the child until the timeout. Failing fast instead
58/// turns it into an ordinary, capturable stderr error.
59///
60/// These are *defaults*, not a policy lock: they are applied before the
61/// inherit loop and before `shell_env` / per-call `env`, so an explicit host
62/// export, `with_shell_env`, or `ShellExecOptions::env` still opts back in.
63/// This is deliberately narrower than the managed-install `harden_git_env`
64/// (which also isolated git config): here the user's own git config and
65/// credential helpers must keep working.
66const NON_INTERACTIVE_SHELL_ENV: &[(&str, &str)] = &[
67    ("GIT_TERMINAL_PROMPT", "0"),
68    ("GCM_INTERACTIVE", "Never"),
69    ("SSH_ASKPASS_REQUIRE", "never"),
70];
71
72/// How the command is fed to the shell. Mirrors `commandTransport`.
73#[derive(Clone, Copy)]
74enum CommandTransport {
75    /// Append the command as the last argv element (`bash -c <cmd>`).
76    Argv,
77    /// Pipe the command to the shell's stdin (`bash -s`).
78    Stdin,
79}
80
81/// Resolved shell config. Mirrors `ShellConfig`.
82struct ShellConfig {
83    shell: PathBuf,
84    args: Vec<String>,
85    transport: CommandTransport,
86}
87
88mod append;
89mod read;
90
91/// The open lock file is the storage-level ownership capability.
92struct OsWriterLease {
93    file: std::fs::File,
94    fence: u64,
95}
96
97#[cfg(unix)]
98impl Drop for OsWriterLease {
99    fn drop(&mut self) {
100        // A child in the fork-to-exec window can still share this open file
101        // description. Unlock even if closing our descriptor is insufficient.
102        let _ = fs2::FileExt::unlock(&self.file);
103    }
104}
105
106impl WriterLease for OsWriterLease {
107    fn verify_fence(&self) -> Result<(), FileError> {
108        let mut probe = self
109            .file
110            .try_clone()
111            .map_err(|error| io_to_file_error(error, Some("writer lease fence")))?;
112        probe
113            .seek(SeekFrom::Start(0))
114            .map_err(|error| io_to_file_error(error, Some("writer lease fence")))?;
115        let mut contents = String::new();
116        probe
117            .read_to_string(&mut contents)
118            .map_err(|error| io_to_file_error(error, Some("writer lease fence")))?;
119        let current = contents.trim().parse::<u64>().map_err(|error| {
120            FileError::new(
121                FileErrorCode::Unknown,
122                format!("invalid persisted writer lease fence: {error}"),
123            )
124        })?;
125        if current != self.fence {
126            return Err(FileError::new(
127                FileErrorCode::PermissionDenied,
128                "writer lease fence changed; reopen the session",
129            ));
130        }
131        Ok(())
132    }
133}
134
135/// Environment variables the **host** sets for its own runtime plumbing, which
136/// must not be handed to a shell it spawns.
137///
138/// A spawned shell is a child process, so anything inherited reaches whatever
139/// that shell runs — including another `rpi`. `RPI_SESSION_ID` names the session
140/// *this process* serves, which is meaningless (and actively misleading) in a
141/// descendant: the child would either report the parent's session or, seeing the
142/// variable already present, refuse to publish its own. Both are wrong answers,
143/// and neither is visible from the child.
144///
145/// This is only the host's own half. An *extension* can publish variables with
146/// the same hazard, and it declares them itself; [`is_host_private_env`] is the
147/// function that answers the full question. Use it rather than reading this
148/// slice, or an extension's channel will be missed — which is precisely the bug
149/// that let `LANGFUSE_PI_PARENT_*` through.
150pub const HOST_PRIVATE_ENV: &[&str] = &[rpi_plugin_sdk::SESSION_ID_ENV];
151
152/// Whether `name` must not be inherited by a spawned shell.
153///
154/// Two sources, because the variables come from two places:
155///
156/// - [`HOST_PRIVATE_ENV`] — the host's own plumbing.
157/// - [`rpi_plugin_sdk::SUBAGENT_PARENT_ENV`] — the family an *extension*
158///   declares for subagent nesting. An inherited copy makes a plain `rpi` started
159///   from inside `bash` adopt its ancestor's trace, hang its root off the
160///   ancestor's root span, and call itself `Subagent Turn` instead of opening its
161///   own trace. A launcher that sets these on the child *it* starts is the
162///   supported nesting path, so this is about not *inheriting* them, not about
163///   forbidding the names.
164///
165/// The extension family is consulted **as the SDK's slice**, never as names
166/// restated here. Restating them is what the previous version did, and it is
167/// how the channel re-leaked when the plugin renamed them: the list went on
168/// matching a name nobody set. Going through the constant means a rename is a
169/// compile error, and a newly added family member is excluded automatically.
170pub fn is_host_private_env(name: &str) -> bool {
171    HOST_PRIVATE_ENV.contains(&name) || rpi_plugin_sdk::SUBAGENT_PARENT_ENV.contains(&name)
172}
173
174/// Real-OS `ExecutionEnv`. Clone shares the tracked-pid set + registry.
175pub struct OsExecutionEnv {
176    cwd: PathBuf,
177    shell_path: Option<PathBuf>,
178    shell_env: Option<HashMap<String, String>>,
179    /// None preserves legacy process inheritance. Some is a closed, immutable
180    /// per-Agent baseline (including HOME for file-path expansion).
181    environment: Option<HashMap<String, String>>,
182    active_pids: Arc<Mutex<HashSet<u32>>>,
183    registry: Arc<MutationQueueRegistry>,
184}
185
186impl OsExecutionEnv {
187    pub fn new() -> Self {
188        Self {
189            cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/")),
190            shell_path: None,
191            shell_env: None,
192            environment: None,
193            active_pids: Arc::new(Mutex::new(HashSet::new())),
194            registry: Arc::new(MutationQueueRegistry::new()),
195        }
196    }
197
198    pub fn with_cwd(cwd: PathBuf) -> Self {
199        Self {
200            cwd,
201            shell_path: None,
202            shell_env: None,
203            environment: None,
204            active_pids: Arc::new(Mutex::new(HashSet::new())),
205            registry: Arc::new(MutationQueueRegistry::new()),
206        }
207    }
208
209    pub fn with_shell_path(mut self, shell_path: PathBuf) -> Self {
210        self.shell_path = Some(shell_path);
211        self
212    }
213
214    pub fn with_shell_env(mut self, env: HashMap<String, String>) -> Self {
215        self.shell_env = Some(env);
216        self
217    }
218
219    /// Replace process environment inheritance with an explicit frozen baseline.
220    /// Unlike `with_shell_env`, absent keys never fall back to process globals.
221    /// Private host channels remain excluded; explicit shell/per-call overlays
222    /// retain their existing semantics. Hosts must supply an absolute shell path
223    /// as well when shell discovery must not consult ambient PATH.
224    pub fn with_environment(mut self, environment: HashMap<String, String>) -> Self {
225        self.environment = Some(environment);
226        self
227    }
228
229    /// Whether process inheritance and ambient HOME fallback are disabled.
230    pub fn has_explicit_environment(&self) -> bool {
231        self.environment.is_some()
232    }
233
234    /// Resolve a path (tilde, file://, absolute/relative) against `cwd`. Pure.
235    fn resolve_path(&self, path: &str) -> PathBuf {
236        let cwd = &self.cwd;
237        let home = || match &self.environment {
238            Some(environment) => environment
239                .get(if cfg!(windows) { "USERPROFILE" } else { "HOME" })
240                .cloned()
241                .unwrap_or_default(),
242            None => home_dir_string(),
243        };
244        let mut p = path.to_string();
245        // Tilde expansion (literal only). A missing HOME in a closed baseline
246        // leaves the tilde literal; it must not turn `~/x` into `/x` or consult
247        // another Agent's ambient home directory.
248        if p == "~" {
249            let home = home();
250            if self.environment.is_none() || !home.is_empty() {
251                p = home;
252            }
253        } else if let Some(rest) = p.strip_prefix("~/") {
254            let home = home();
255            if self.environment.is_none() || !home.is_empty() {
256                p = format!("{home}/{rest}");
257            }
258        } else if cfg!(windows) {
259            if let Some(rest) = p.strip_prefix("~\\") {
260                let home = home();
261                if self.environment.is_none() || !home.is_empty() {
262                    p = format!("{home}\\{rest}");
263                }
264            }
265        }
266        // file:// URL → path. Parse failure silently keeps the literal.
267        if p.starts_with("file://") {
268            if let Some(local) = file_url_to_path(&p) {
269                p = local;
270            }
271        }
272        let pb = PathBuf::from(&p);
273        if pb.is_absolute() {
274            normalize_absolute(&pb)
275        } else {
276            normalize_absolute(&cwd.join(pb))
277        }
278    }
279
280    /// Detect + return the shell config, or `ShellUnavailable`. Mirrors
281    /// `getShellConfig`.
282    async fn get_shell_config(&self) -> Result<ShellConfig, ExecutionError> {
283        // Explicit override. Shell discovery happens on the hot path immediately
284        // before spawning a command. Keep this probe synchronous: putting a
285        // `tokio::fs` metadata future here can queue work on Tokio's blocking
286        // pool and leave a tool run waiting before it has even created a child.
287        if let Some(sp) = &self.shell_path {
288            if sp.is_file() {
289                return Ok(bash_shell_config(sp.clone()));
290            }
291            return Err(ExecutionError::new(
292                ExecutionErrorCode::ShellUnavailable,
293                format!("Custom shell path not found: {}", sp.display()),
294            ));
295        }
296        // Windows probe.
297        #[cfg(windows)]
298        {
299            if let Some(cfg) = windows_probe_bash().await {
300                return Ok(cfg);
301            }
302            return Err(ExecutionError::new(
303                ExecutionErrorCode::ShellUnavailable,
304                "bash not found. Install Git for Windows / MSYS2 / Cygwin, or set shellPath.",
305            ));
306        }
307        // POSIX.
308        #[cfg(not(windows))]
309        {
310            if std::path::Path::new("/bin/bash").is_file() {
311                return Ok(ShellConfig {
312                    shell: PathBuf::from("/bin/bash"),
313                    args: vec!["-c".to_string()],
314                    transport: CommandTransport::Argv,
315                });
316            }
317            // `which bash` fallback.
318            if let Some(found) =
319                run_command("which", &["bash"], std::time::Duration::from_millis(5000)).await
320            {
321                let trimmed = found.trim();
322                if !trimmed.is_empty() && std::path::Path::new(trimmed).is_file() {
323                    return Ok(ShellConfig {
324                        shell: PathBuf::from(trimmed),
325                        args: vec!["-c".to_string()],
326                        transport: CommandTransport::Argv,
327                    });
328                }
329            }
330            // sh fallback.
331            return Ok(ShellConfig {
332                shell: PathBuf::from("sh"),
333                args: vec!["-c".to_string()],
334                transport: CommandTransport::Argv,
335            });
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_lowercase();
400    let re = regex::Regex::new(r"^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$").unwrap();
401    re.is_match(&s)
402}
403
404#[cfg(windows)]
405async fn windows_probe_bash() -> Option<ShellConfig> {
406    let pf = std::env::var("ProgramFiles").ok();
407    let pf86 = std::env::var("ProgramFiles(x86)").ok();
408    let mut candidates: Vec<PathBuf> = Vec::new();
409    if let Some(p) = pf {
410        candidates.push(PathBuf::from(p).join("Git").join("bin").join("bash.exe"));
411    }
412    if let Some(p) = pf86 {
413        candidates.push(PathBuf::from(p).join("Git").join("bin").join("bash.exe"));
414    }
415    for c in &candidates {
416        if tokio::fs::metadata(c).await.is_ok() {
417            return Some(bash_shell_config(c.clone()));
418        }
419    }
420    // `where bash.exe`.
421    if let Some(found) = run_command(
422        "where",
423        &["bash.exe"],
424        std::time::Duration::from_millis(5000),
425    )
426    .await
427    {
428        let first = found.lines().next().unwrap_or("").trim().to_string();
429        if !first.is_empty() && tokio::fs::metadata(&first).await.is_ok() {
430            return Some(bash_shell_config(PathBuf::from(first)));
431        }
432    }
433    None
434}
435
436/// Run a quick command, capture stdout, with a timeout. Mirrors `runCommand`
437/// (used only by shell detection). Returns `None` on spawn failure / timeout /
438/// empty stdout.
439async fn run_command(cmd: &str, args: &[&str], timeout: std::time::Duration) -> Option<String> {
440    let mut command = tokio::process::Command::new(cmd);
441    command.args(args);
442    command.stdout(std::process::Stdio::piped());
443    command.stderr(std::process::Stdio::null());
444    command.stdin(std::process::Stdio::null());
445    #[cfg(windows)]
446    {
447        // Hide the console window for the probe.
448        use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
449        command.creation_flags(CREATE_NO_WINDOW);
450    }
451    let child = command.spawn().ok()?;
452    let out = match tokio::time::timeout(timeout, child.wait_with_output()).await {
453        Ok(Ok(o)) => o,
454        _ => return None,
455    };
456    if !out.status.success() {
457        return None;
458    }
459    // `where` prints paths in the console code page (e.g. a Chinese user name).
460    let s = crate::output_decode::decode_output(&out.stdout);
461    if s.trim().is_empty() {
462        None
463    } else {
464        Some(s)
465    }
466}
467
468/// One job object per running shell, by root pid. `taskkill /T` walks parent
469/// pids, and an MSYS shell's children are not on that chain: `sleep` under Git
470/// Bash outlives it. Job membership is inherited by every descendant.
471///
472/// Kill-on-close is armed only when killing, so whatever a command leaves
473/// running on purpose keeps running after it ends normally.
474#[cfg(windows)]
475mod shell_jobs {
476    use std::collections::HashMap;
477    use std::sync::{LazyLock, Mutex};
478
479    use win32job::{ExtendedLimitInfo, Job};
480
481    static JOBS: LazyLock<Mutex<HashMap<u32, Job>>> = LazyLock::new(Default::default);
482
483    /// Put a shell spawned with `CREATE_SUSPENDED` in its own job, then let it
484    /// run: no descendant can start outside the job. A shell that gets no job
485    /// still runs, and cancelling it falls back to `taskkill`.
486    pub fn start(pid: u32, process: std::os::windows::io::RawHandle) -> Result<(), String> {
487        if let Ok(job) = Job::create() {
488            if job.assign_process(process as isize).is_ok() {
489                JOBS.lock().unwrap().insert(pid, job);
490            }
491        }
492        rpi_plugin_sdk::process::resume_child(pid)
493    }
494
495    /// End every process in `pid`'s job: arm kill-on-close, then drop the only
496    /// handle. False when `pid` has no job or arming failed.
497    pub fn terminate(pid: u32) -> bool {
498        let Some(job) = JOBS.lock().unwrap().remove(&pid) else {
499            return false;
500        };
501        let mut info = ExtendedLimitInfo::new();
502        info.limit_kill_on_job_close();
503        job.set_extended_limit_info(&info).is_ok()
504    }
505
506    pub fn forget(pid: u32) {
507        JOBS.lock().unwrap().remove(&pid);
508    }
509}
510
511// A tool or harness can drop exec before its cancellation branch is polled.
512// Own the process group until wait() has actually reaped the shell. The guard
513// must be synchronous: Drop runs while the async execution future is unwinding.
514struct ShellProcessGuard {
515    pid: Option<u32>,
516    active: Arc<Mutex<HashSet<u32>>>,
517}
518impl ShellProcessGuard {
519    fn finish(&mut self) {
520        if let Some(pid) = self.pid.take() {
521            #[cfg(windows)]
522            shell_jobs::forget(pid);
523            self.active
524                .lock()
525                .unwrap_or_else(|e| e.into_inner())
526                .remove(&pid);
527        }
528    }
529}
530impl Drop for ShellProcessGuard {
531    fn drop(&mut self) {
532        if let Some(pid) = self.pid {
533            #[cfg(unix)]
534            {
535                use nix::sys::signal::{kill, Signal};
536                use nix::unistd::Pid;
537                // Every shell is spawned into its own process group. No
538                // unrelated session or successful background command is killed.
539                let _ = kill(Pid::from_raw(-(pid as i32)), Signal::SIGKILL);
540            }
541            #[cfg(windows)]
542            shell_jobs::terminate(pid);
543            self.finish();
544        }
545    }
546}
547
548/// Kill a process tree. Windows: the shell's job object, else
549/// `taskkill /F /T /PID`. POSIX: `kill -PG` with fallback to `kill -PID`.
550/// Best-effort, errors swallowed.
551async fn kill_process_tree(pid: u32) {
552    #[cfg(windows)]
553    {
554        if shell_jobs::terminate(pid) {
555            return;
556        }
557        use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
558        let mut cmd = tokio::process::Command::new("taskkill");
559        cmd.args(&["/F", "/T", "/PID", &pid.to_string()]);
560        cmd.creation_flags(CREATE_NO_WINDOW);
561        cmd.stdin(std::process::Stdio::null());
562        cmd.stdout(std::process::Stdio::null());
563        cmd.stderr(std::process::Stdio::null());
564        // Wait for taskkill itself to finish. Spawning it fire-and-forget lets
565        // the shell's `child.wait()` race the tree termination, and a listener
566        // can keep its inherited stdout/stderr handles open long enough to
567        // deadlock the capture join after Ctrl+C.
568        let _ = cmd.status().await;
569    }
570    #[cfg(unix)]
571    {
572        use nix::sys::signal::{kill, Signal};
573        use nix::unistd::Pid;
574        // Process group: negative pid.
575        let pg = Pid::from_raw(-(pid as i32));
576        if kill(pg, Signal::SIGKILL).is_err() {
577            let _ = kill(Pid::from_raw(pid as i32), Signal::SIGKILL);
578        }
579    }
580    #[cfg(not(any(windows, unix)))]
581    {
582        let _ = pid;
583    }
584}
585
586#[async_trait]
587impl FileSystem for OsExecutionEnv {
588    fn native_file_path(&self, path: &str) -> Option<PathBuf> {
589        #[cfg(unix)]
590        return Some(self.resolve_path(path));
591        #[cfg(not(unix))]
592        {
593            let _ = path;
594            None
595        }
596    }
597
598    async fn try_acquire_writer_lease(
599        &self,
600        path: &str,
601    ) -> Result<Option<Box<dyn WriterLease>>, FileError> {
602        let session_path = self.resolve_path(path);
603        let lock_path = PathBuf::from(format!("{}.lock", session_path.display()));
604        let display_path = session_path.to_string_lossy().into_owned();
605        tokio::task::spawn_blocking(move || {
606            use fs2::FileExt;
607            let mut file = std::fs::OpenOptions::new()
608                .create(true)
609                .read(true)
610                .write(true)
611                .open(&lock_path)
612                .map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
613            file.try_lock_exclusive().map_err(|error| {
614                FileError::new(
615                    FileErrorCode::PermissionDenied,
616                    format!("writer lease is already held for {display_path}"),
617                )
618                .with_path(lock_path.to_string_lossy())
619                .with_source(Box::new(error))
620            })?;
621            file.seek(SeekFrom::Start(0))
622                .map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
623            let mut contents = String::new();
624            file.read_to_string(&mut contents)
625                .map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
626            let previous = if contents.trim().is_empty() {
627                0
628            } else {
629                contents.trim().parse::<u64>().map_err(|error| {
630                    FileError::new(
631                        FileErrorCode::Unknown,
632                        format!("invalid persisted writer lease fence: {error}"),
633                    )
634                    .with_path(lock_path.to_string_lossy())
635                })?
636            };
637            let fence = previous.checked_add(1).ok_or_else(|| {
638                FileError::new(FileErrorCode::Unknown, "writer lease fence exhausted")
639                    .with_path(lock_path.to_string_lossy())
640            })?;
641            file.seek(SeekFrom::Start(0))
642                .and_then(|_| file.set_len(0))
643                .and_then(|_| file.write_all(fence.to_string().as_bytes()))
644                .and_then(|_| file.sync_all())
645                .map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
646            Ok(Some(
647                Box::new(OsWriterLease { file, fence }) as Box<dyn WriterLease>
648            ))
649        })
650        .await
651        .map_err(|error| {
652            FileError::new(
653                FileErrorCode::Unknown,
654                format!("writer lease task failed: {error}"),
655            )
656            .with_path(session_path.to_string_lossy())
657        })?
658    }
659
660    async fn sync_file(
661        &self,
662        path: &str,
663        data_only: bool,
664        cancel: Option<&CancellationToken>,
665    ) -> Result<(), FileError> {
666        check_cancel_file(cancel, Some(path))?;
667        let abs = self.resolve_path(path);
668        let error_path = abs.to_string_lossy().into_owned();
669        let io_path = error_path.clone();
670        tokio::task::spawn_blocking(move || {
671            let file = std::fs::OpenOptions::new()
672                .read(true)
673                .write(true)
674                .open(&abs)
675                .map_err(|error| io_to_file_error(error, Some(&io_path)))?;
676            if data_only {
677                file.sync_data()
678                    .map_err(|error| io_to_file_error(error, Some(&io_path)))
679            } else {
680                file.sync_all()
681                    .map_err(|error| io_to_file_error(error, Some(&io_path)))
682            }
683        })
684        .await
685        .map_err(|error| {
686            FileError::new(
687                FileErrorCode::Unknown,
688                format!("file sync task failed: {error}"),
689            )
690            .with_path(error_path)
691        })??;
692        Ok(())
693    }
694
695    async fn sync_directory(
696        &self,
697        path: &str,
698        cancel: Option<&CancellationToken>,
699    ) -> Result<(), FileError> {
700        check_cancel_file(cancel, Some(path))?;
701        let abs = self.resolve_path(path);
702        #[cfg(unix)]
703        {
704            let error_path = abs.to_string_lossy().into_owned();
705            let io_path = error_path.clone();
706            tokio::task::spawn_blocking(move || {
707                std::fs::File::open(&abs)
708                    .map_err(|error| io_to_file_error(error, Some(&io_path)))?
709                    .sync_all()
710                    .map_err(|error| io_to_file_error(error, Some(&io_path)))
711            })
712            .await
713            .map_err(|error| {
714                FileError::new(
715                    FileErrorCode::Unknown,
716                    format!("directory sync task failed: {error}"),
717                )
718                .with_path(error_path)
719            })??;
720        }
721        #[cfg(not(unix))]
722        {
723            // Windows has no portable directory-handle fsync equivalent in
724            // this abstraction. File contents are still synced above, but
725            // rename-directory durability remains unproved on this target.
726            let _ = abs;
727        }
728        Ok(())
729    }
730
731    async fn sync_file_and_parent(
732        &self,
733        path: &str,
734        cancel: Option<&CancellationToken>,
735    ) -> Result<(), FileError> {
736        check_cancel_file(cancel, Some(path))?;
737        #[cfg(unix)]
738        {
739            let abs = self.resolve_path(path);
740            let info = self.file_info(path, cancel).await?;
741            if info.kind != FileKind::File {
742                return Err(FileError::new(
743                    FileErrorCode::NotSupported,
744                    "journal synchronization requires a regular file",
745                )
746                .with_path(path));
747            }
748            // Use the existing OS implementations, not the compatibility no-op
749            // defaults. Both errors propagate; a file-only sync is not success.
750            self.sync_file(path, false, cancel).await?;
751            let parent = abs.parent().ok_or_else(|| {
752                FileError::new(
753                    FileErrorCode::NotSupported,
754                    "journal has no parent directory",
755                )
756                .with_path(path)
757            })?;
758            self.sync_directory(&parent.to_string_lossy(), cancel).await
759        }
760        #[cfg(not(unix))]
761        {
762            // The legacy directory sync is a no-op on Windows. Do not promote
763            // that compatibility behavior into a physical persistence proof.
764            Err(FileError::new(
765                FileErrorCode::NotSupported,
766                "physical journal synchronization is unsupported on this platform",
767            )
768            .with_path(path))
769        }
770    }
771
772    async fn open_append_file(
773        &self,
774        path: &str,
775    ) -> Result<Option<Box<dyn crate::env::AppendFile>>, FileError> {
776        let path = self.resolve_path(path);
777        Ok(Some(Box::new(append::OsAppendFile::open(path).await?)))
778    }
779
780    async fn open_read_file(
781        &self,
782        path: &str,
783    ) -> Result<Option<Arc<dyn crate::env::ReadFile>>, FileError> {
784        let path = self.resolve_path(path);
785        Ok(Some(Arc::new(read::OsReadFile::open(path).await?)))
786    }
787
788    async fn truncate_file(
789        &self,
790        path: &str,
791        len: u64,
792        cancel: Option<&CancellationToken>,
793    ) -> Result<(), FileError> {
794        check_cancel_file(cancel, Some(path))?;
795        let abs = self.resolve_path(path);
796        let error_path = abs.to_string_lossy().into_owned();
797        tokio::task::spawn_blocking(move || {
798            let file = std::fs::OpenOptions::new().write(true).open(&abs)?;
799            if len > file.metadata()?.len() {
800                return Err(std::io::Error::new(
801                    std::io::ErrorKind::InvalidInput,
802                    "truncation cannot grow a file",
803                ));
804            }
805            file.set_len(len)
806        })
807        .await
808        .map_err(|error| {
809            FileError::new(
810                FileErrorCode::Unknown,
811                format!("file truncation task failed: {error}"),
812            )
813        })?
814        .map_err(|error| io_to_file_error(error, Some(&error_path)))
815    }
816
817    fn cwd(&self) -> &Path {
818        &self.cwd
819    }
820
821    async fn absolute_path(
822        &self,
823        path: &str,
824        cancel: Option<&CancellationToken>,
825    ) -> Result<PathBuf, FileError> {
826        check_cancel_file(cancel, Some(path))?;
827        Ok(self.resolve_path(path))
828    }
829
830    async fn join_path(
831        &self,
832        parts: &[&str],
833        cancel: Option<&CancellationToken>,
834    ) -> Result<PathBuf, FileError> {
835        check_cancel_file(cancel, None)?;
836        let mut out = PathBuf::new();
837        for p in parts {
838            out.push(p);
839        }
840        Ok(out)
841    }
842
843    async fn read_text_file(
844        &self,
845        path: &str,
846        cancel: Option<&CancellationToken>,
847    ) -> Result<String, FileError> {
848        check_cancel_file(cancel, Some(path))?;
849        let abs = self.resolve_path(path);
850        let bytes = read_cancellable(&abs, cancel).await?;
851        String::from_utf8(bytes).map_err(|e| {
852            FileError::new(FileErrorCode::Invalid, format!("invalid utf-8: {e}"))
853                .with_path(abs.to_string_lossy())
854        })
855    }
856
857    async fn read_text_lines(
858        &self,
859        path: &str,
860        max_lines: Option<usize>,
861        cancel: Option<&CancellationToken>,
862    ) -> Result<Vec<String>, FileError> {
863        check_cancel_file(cancel, Some(path))?;
864        if max_lines.map(|m| m == 0).unwrap_or(false) {
865            return Ok(Vec::new());
866        }
867        let abs = self.resolve_path(path);
868        read::read_text_lines(&abs, max_lines, cancel).await
869    }
870
871    async fn read_binary_file(
872        &self,
873        path: &str,
874        cancel: Option<&CancellationToken>,
875    ) -> Result<Vec<u8>, FileError> {
876        check_cancel_file(cancel, Some(path))?;
877        let abs = self.resolve_path(path);
878        read_cancellable(&abs, cancel).await
879    }
880
881    async fn write_file(
882        &self,
883        path: &str,
884        content: FileContent,
885        cancel: Option<&CancellationToken>,
886    ) -> Result<(), FileError> {
887        check_cancel_file(cancel, Some(path))?;
888        let abs = self.resolve_path(path);
889        // mkdir parent (recursive).
890        if let Some(parent) = abs.parent() {
891            if !parent.as_os_str().is_empty() {
892                if let Err(e) = tokio::fs::create_dir_all(parent).await {
893                    return Err(io_to_file_error(e, Some(&abs.to_string_lossy())));
894                }
895            }
896        }
897        check_cancel_file(cancel, Some(&abs.to_string_lossy()))?;
898        write_cancellable(&abs, content.as_bytes(), cancel).await
899    }
900
901    async fn write_new_file(
902        &self,
903        path: &str,
904        content: FileContent,
905        cancel: Option<&CancellationToken>,
906    ) -> Result<(), FileError> {
907        check_cancel_file(cancel, Some(path))?;
908        let abs = self.resolve_path(path);
909        let cancel = cancel.cloned();
910        // One owned blocking operation retains the opened descriptor even if
911        // its async waiter disappears. O_EXCL/create_new is the authority: no
912        // separate metadata check, parent mkdir, truncation or cleanup unlink.
913        tokio::task::spawn_blocking(move || {
914            let display = abs.to_string_lossy();
915            check_cancel_file(cancel.as_ref(), Some(&display))?;
916            let mut options = std::fs::OpenOptions::new();
917            options.write(true).create_new(true);
918            #[cfg(unix)]
919            {
920                use std::os::unix::fs::OpenOptionsExt;
921                options.mode(0o600);
922            }
923            let mut file = options
924                .open(&abs)
925                .map_err(|error| io_to_file_error(error, Some(&display)))?;
926            for chunk in content.as_bytes().chunks(64 * 1024) {
927                check_cancel_file(cancel.as_ref(), Some(&display))?;
928                file.write_all(chunk)
929                    .map_err(|error| io_to_file_error(error, Some(&display)))?;
930            }
931            file.flush()
932                .map_err(|error| io_to_file_error(error, Some(&display)))
933        })
934        .await
935        .map_err(|_| {
936            FileError::new(
937                FileErrorCode::Unknown,
938                "exclusive file creation task stopped",
939            )
940        })?
941    }
942
943    async fn append_file(
944        &self,
945        path: &str,
946        content: FileContent,
947        cancel: Option<&CancellationToken>,
948    ) -> Result<(), FileError> {
949        check_cancel_file(cancel, Some(path))?;
950        let abs = self.resolve_path(path);
951        if let Some(parent) = abs.parent() {
952            if !parent.as_os_str().is_empty() {
953                let _ = tokio::fs::create_dir_all(parent).await;
954            }
955        }
956        use tokio::io::AsyncWriteExt;
957        let res = match tokio::fs::OpenOptions::new()
958            .create(true)
959            .append(true)
960            .open(&abs)
961            .await
962        {
963            Ok(mut f) => {
964                // Tokio may acknowledge a buffered write before the blocking
965                // filesystem operation completes. Await it before returning so
966                // an immediate read/metadata call observes the appended bytes.
967                match f.write_all(content.as_bytes()).await {
968                    Ok(()) => f.flush().await,
969                    Err(error) => Err(error),
970                }
971            }
972            Err(e) => return Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
973        };
974        res.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
975    }
976
977    async fn rename_file(
978        &self,
979        source: &str,
980        dest: &str,
981        cancel: Option<&CancellationToken>,
982    ) -> Result<(), FileError> {
983        check_cancel_file(cancel, Some(source))?;
984        let src = self.resolve_path(source);
985        let dst = self.resolve_path(dest);
986        tokio::fs::rename(&src, &dst)
987            .await
988            .map_err(|e| io_to_file_error(e, Some(&src.to_string_lossy())))
989    }
990
991    async fn file_info(
992        &self,
993        path: &str,
994        cancel: Option<&CancellationToken>,
995    ) -> Result<FileInfo, FileError> {
996        check_cancel_file(cancel, Some(path))?;
997        let abs = self.resolve_path(path);
998        let meta = tokio::fs::symlink_metadata(&abs)
999            .await
1000            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1001        let ft = meta.file_type();
1002        let kind = if ft.is_file() {
1003            FileKind::File
1004        } else if ft.is_dir() {
1005            FileKind::Directory
1006        } else if ft.is_symlink() {
1007            FileKind::Symlink
1008        } else {
1009            return Err(
1010                FileError::new(FileErrorCode::Invalid, "Unsupported file type")
1011                    .with_path(abs.to_string_lossy()),
1012            );
1013        };
1014        let mtime_ms = meta
1015            .modified()
1016            .ok()
1017            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1018            .map(|d| d.as_millis() as i64)
1019            .unwrap_or(0);
1020        Ok(FileInfo {
1021            name: abs
1022                .file_name()
1023                .map(|n| n.to_string_lossy().into_owned())
1024                .unwrap_or_else(|| abs.to_string_lossy().into_owned()),
1025            path: abs.clone(),
1026            kind,
1027            size: meta.len(),
1028            mtime_ms,
1029        })
1030    }
1031
1032    async fn list_dir(
1033        &self,
1034        path: &str,
1035        cancel: Option<&CancellationToken>,
1036    ) -> Result<Vec<FileInfo>, FileError> {
1037        check_cancel_file(cancel, Some(path))?;
1038        let abs = self.resolve_path(path);
1039        let mut entries = tokio::fs::read_dir(&abs)
1040            .await
1041            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1042        let mut out = Vec::new();
1043        while let Some(entry) = entries
1044            .next_entry()
1045            .await
1046            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?
1047        {
1048            if let Some(t) = cancel {
1049                if t.is_cancelled() {
1050                    return Err(FileError::aborted().with_path(abs.to_string_lossy()));
1051                }
1052            }
1053            let ep = entry.path();
1054            let meta = match tokio::fs::symlink_metadata(&ep).await {
1055                Ok(m) => m,
1056                Err(e) => {
1057                    // Skip unsupported types silently; propagate real stat errors.
1058                    let code = crate::error::io_to_file_code(&e);
1059                    if code == FileErrorCode::NotSupported {
1060                        continue;
1061                    }
1062                    return Err(io_to_file_error(e, Some(&ep.to_string_lossy())));
1063                }
1064            };
1065            let ft = meta.file_type();
1066            let kind = if ft.is_file() {
1067                FileKind::File
1068            } else if ft.is_dir() {
1069                FileKind::Directory
1070            } else if ft.is_symlink() {
1071                FileKind::Symlink
1072            } else {
1073                continue; // silently skip sockets/fifos/etc.
1074            };
1075            let mtime_ms = meta
1076                .modified()
1077                .ok()
1078                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1079                .map(|d| d.as_millis() as i64)
1080                .unwrap_or(0);
1081            out.push(FileInfo {
1082                name: entry.file_name().to_string_lossy().into_owned(),
1083                path: ep,
1084                kind,
1085                size: meta.len(),
1086                mtime_ms,
1087            });
1088        }
1089        Ok(out)
1090    }
1091
1092    async fn has_file_with_suffix(
1093        &self,
1094        path: &str,
1095        suffix: &str,
1096        cancel: Option<&CancellationToken>,
1097    ) -> Result<bool, FileError> {
1098        check_cancel_file(cancel, Some(path))?;
1099        let abs = self.resolve_path(path);
1100        let error_path = abs.to_string_lossy().into_owned();
1101        let suffix = String::from(suffix);
1102        let cancel = cancel.cloned();
1103        // One blocking job, not one lstat + runtime round-trip per entry. Session
1104        // existence checks need names/types only, not every sidecar's metadata.
1105        tokio::task::spawn_blocking(move || {
1106            check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1107            let entries = std::fs::read_dir(&abs)
1108                .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1109            for entry in entries {
1110                check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1111                let entry = entry.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1112                if !entry.file_name().to_string_lossy().ends_with(&suffix) {
1113                    continue;
1114                }
1115                let kind = match entry.file_type() {
1116                    Ok(kind) => kind,
1117                    Err(error)
1118                        if crate::error::io_to_file_code(&error) == FileErrorCode::NotSupported =>
1119                    {
1120                        continue
1121                    }
1122                    Err(error) => {
1123                        return Err(io_to_file_error(
1124                            error,
1125                            Some(&entry.path().to_string_lossy()),
1126                        ))
1127                    }
1128                };
1129                check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1130                if kind.is_file() || kind.is_symlink() {
1131                    return Ok(true);
1132                }
1133            }
1134            check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1135            Ok(false)
1136        })
1137        .await
1138        .map_err(|error| {
1139            FileError::new(
1140                FileErrorCode::Unknown,
1141                format!("directory scan task failed: {error}"),
1142            )
1143            .with_path(error_path)
1144        })?
1145    }
1146
1147    async fn canonical_path(
1148        &self,
1149        path: &str,
1150        cancel: Option<&CancellationToken>,
1151    ) -> Result<PathBuf, FileError> {
1152        check_cancel_file(cancel, Some(path))?;
1153        let abs = self.resolve_path(path);
1154        tokio::fs::canonicalize(&abs)
1155            .await
1156            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
1157    }
1158
1159    async fn exists(
1160        &self,
1161        path: &str,
1162        cancel: Option<&CancellationToken>,
1163    ) -> Result<bool, FileError> {
1164        check_cancel_file(cancel, Some(path))?;
1165        let abs = self.resolve_path(path);
1166        match tokio::fs::symlink_metadata(&abs).await {
1167            Ok(_) => Ok(true),
1168            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
1169            Err(e) => Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
1170        }
1171    }
1172
1173    async fn create_dir(
1174        &self,
1175        path: &str,
1176        recursive: bool,
1177        cancel: Option<&CancellationToken>,
1178    ) -> Result<(), FileError> {
1179        check_cancel_file(cancel, Some(path))?;
1180        let abs = self.resolve_path(path);
1181        let res = if recursive {
1182            tokio::fs::create_dir_all(&abs).await
1183        } else {
1184            tokio::fs::create_dir(&abs).await
1185        };
1186        res.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
1187    }
1188
1189    async fn remove(
1190        &self,
1191        path: &str,
1192        recursive: bool,
1193        force: bool,
1194        cancel: Option<&CancellationToken>,
1195    ) -> Result<(), FileError> {
1196        check_cancel_file(cancel, Some(path))?;
1197        let abs = self.resolve_path(path);
1198        let res = if recursive {
1199            tokio::fs::remove_dir_all(&abs).await
1200        } else {
1201            // Try file first, then empty dir.
1202            match tokio::fs::remove_file(&abs).await {
1203                Ok(()) => Ok(()),
1204                Err(_) => tokio::fs::remove_dir(&abs).await,
1205            }
1206        };
1207        match res {
1208            Ok(()) => Ok(()),
1209            Err(e) if e.kind() == std::io::ErrorKind::NotFound && force => Ok(()),
1210            Err(e) => Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
1211        }
1212    }
1213
1214    async fn create_temp_dir(
1215        &self,
1216        prefix: Option<&str>,
1217        cancel: Option<&CancellationToken>,
1218    ) -> Result<PathBuf, FileError> {
1219        check_cancel_file(cancel, None)?;
1220        let prefix = prefix.unwrap_or("tmp-");
1221        // Use tempfile's NamedTempFile-less builder for a dir.
1222        let tmp =
1223            tempfile::tempdir_in(std::env::temp_dir()).map_err(|e| io_to_file_error(e, None))?;
1224        // tempfile picks a random name; rename to include the prefix.
1225        let path = tmp.path().to_path_buf();
1226        std::mem::forget(tmp); // keep the dir alive; caller manages cleanup.
1227                               // Build a prefixed sibling.
1228        let final_path = std::env::temp_dir().join(format!("{}{}", prefix, random_suffix()));
1229        // Rename the tempdir into the prefixed path.
1230        if let Err(e) = tokio::fs::rename(&path, &final_path).await {
1231            // Fallback: just return the original random path.
1232            let _ = e;
1233            return Ok(path);
1234        }
1235        Ok(final_path)
1236    }
1237
1238    async fn create_temp_file(
1239        &self,
1240        prefix: &str,
1241        suffix: &str,
1242        cancel: Option<&CancellationToken>,
1243    ) -> Result<PathBuf, FileError> {
1244        check_cancel_file(cancel, None)?;
1245        // Create an isolated temp dir (matching the TS pattern of one dir per
1246        // file), then write an empty file named `<prefix><random><suffix>`.
1247        let dir = self.create_temp_dir(Some("tmp-"), cancel).await?;
1248        let name = format!("{}{}{}", prefix, random_suffix(), suffix);
1249        let path = dir.join(name);
1250        tokio::fs::File::create(&path)
1251            .await
1252            .map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))?;
1253        Ok(path)
1254    }
1255
1256    async fn cleanup(&self) {
1257        let pids: Vec<u32> = self
1258            .active_pids
1259            .lock()
1260            .unwrap_or_else(|e| e.into_inner())
1261            .iter()
1262            .copied()
1263            .collect();
1264        for pid in pids {
1265            kill_process_tree(pid).await;
1266        }
1267        self.active_pids
1268            .lock()
1269            .unwrap_or_else(|e| e.into_inner())
1270            .clear();
1271    }
1272}
1273
1274/// Read a file to bytes, honoring cooperative cancellation.
1275async fn read_cancellable(
1276    path: &Path,
1277    cancel: Option<&CancellationToken>,
1278) -> Result<Vec<u8>, FileError> {
1279    let read = tokio::fs::read(path);
1280    let res = match cancel {
1281        Some(t) => tokio::select! {
1282            r = read => r,
1283            _ = t.cancelled() => return Err(FileError::aborted().with_path(path.to_string_lossy())),
1284        },
1285        None => read.await,
1286    };
1287    res.map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))
1288}
1289
1290/// Write bytes to a file (truncate), honoring cooperative cancellation.
1291async fn write_cancellable(
1292    path: &Path,
1293    bytes: &[u8],
1294    cancel: Option<&CancellationToken>,
1295) -> Result<(), FileError> {
1296    use tokio::io::AsyncWriteExt;
1297    let f = tokio::fs::File::create(path)
1298        .await
1299        .map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))?;
1300    let write = async {
1301        let mut f = f;
1302        f.write_all(bytes).await?;
1303        f.flush().await?;
1304        Ok::<(), std::io::Error>(())
1305    };
1306    let res = match cancel {
1307        Some(t) => tokio::select! {
1308            r = write => r,
1309            _ = t.cancelled() => return Err(FileError::aborted().with_path(path.to_string_lossy())),
1310        },
1311        None => write.await,
1312    };
1313    res.map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))
1314}
1315
1316fn random_suffix() -> String {
1317    // Short random suffix via uuid v4 (no Time—it's a UUID, not a timestamp).
1318    uuid::Uuid::new_v4().simple().to_string()
1319}
1320
1321#[async_trait]
1322impl Shell for OsExecutionEnv {
1323    async fn exec<'a>(
1324        &'a self,
1325        command: &str,
1326        options: ShellExecOptions<'a>,
1327    ) -> Result<ShellOutput, ExecutionError> {
1328        // Pre-flight abort.
1329        check_cancel_exec(options.cancel)?;
1330        // Resolve timeout.
1331        let timeout = match resolve_timeout(options.timeout) {
1332            Ok(t) => t,
1333            Err(e) => return Err(e),
1334        };
1335        // Resolve cwd.
1336        let cwd = match &options.cwd {
1337            Some(c) => self.resolve_path(&c.to_string_lossy()),
1338            None => self.cwd.clone(),
1339        };
1340        // Shell config. An explicit override is used by native shell tools
1341        // such as PowerShell; otherwise preserve the default Bash behavior.
1342        let shell_cfg = match &options.shell {
1343            Some(override_shell) => ShellConfig {
1344                shell: override_shell.program.clone(),
1345                args: override_shell.args.clone(),
1346                transport: CommandTransport::Argv,
1347            },
1348            None => self.get_shell_config().await?,
1349        };
1350        // Verify cwd exists.
1351        if !cwd.exists() {
1352            return Err(ExecutionError::new(
1353                ExecutionErrorCode::SpawnError,
1354                format!(
1355                    "Working directory does not exist: {}\nCannot execute bash commands.",
1356                    cwd.display()
1357                ),
1358            ));
1359        }
1360
1361        // Build the spawn.
1362        let mut cmd = tokio::process::Command::new(&shell_cfg.shell);
1363        cmd.current_dir(&cwd);
1364        cmd.env_clear();
1365        // Non-interactive defaults apply even when `inherit_env` is false: a
1366        // caller asking for a clean environment is not asking for a prompt.
1367        // They sit before the inherit loop so any explicit value wins.
1368        for (k, v) in NON_INTERACTIVE_SHELL_ENV {
1369            cmd.env(k, v);
1370        }
1371        // Environment: inherit + shell_env + per-call. The host's own private
1372        // plumbing (`HOST_PRIVATE_ENV`) is skipped: it describes *this* process,
1373        // not the shell or anything the shell runs, and inheriting it makes a
1374        // nested `rpi` misreport its session. A caller that genuinely wants a
1375        // value passed down can still set it explicitly through `env`/`shell_env`
1376        // below (those are applied after this loop and win).
1377        if options.inherit_env {
1378            let mut inherit = |name: &str, value: &str| {
1379                if !is_host_private_env(name) {
1380                    cmd.env(name, value);
1381                }
1382            };
1383            match &self.environment {
1384                Some(environment) => {
1385                    for (name, value) in environment {
1386                        inherit(name, value);
1387                    }
1388                }
1389                None => {
1390                    for (name, value) in std::env::vars() {
1391                        inherit(&name, &value);
1392                    }
1393                }
1394            }
1395        }
1396        if let Some(base) = &self.shell_env {
1397            for (k, v) in base {
1398                cmd.env(k, v);
1399            }
1400        }
1401        if let Some(extra) = &options.env {
1402            for (k, v) in extra {
1403                cmd.env(k, v);
1404            }
1405        }
1406        // stdio.
1407        cmd.kill_on_drop(true);
1408        cmd.stdin(std::process::Stdio::piped());
1409        cmd.stdout(std::process::Stdio::piped());
1410        cmd.stderr(std::process::Stdio::piped());
1411        #[cfg(unix)]
1412        {
1413            cmd.process_group(0); // child becomes its own group leader.
1414        }
1415        #[cfg(windows)]
1416        {
1417            use windows_sys::Win32::System::Threading::{CREATE_NO_WINDOW, CREATE_SUSPENDED};
1418            // Suspended until it is in its job (see `shell_jobs::start`).
1419            cmd.creation_flags(CREATE_NO_WINDOW | CREATE_SUSPENDED);
1420        }
1421
1422        // Args: stdin transport → `bash -s` (no command argv); argv → append.
1423        let transport = shell_cfg.transport;
1424        cmd.args(&shell_cfg.args);
1425        if matches!(transport, CommandTransport::Argv) {
1426            cmd.arg(command);
1427        }
1428
1429        let mut child = match cmd.spawn() {
1430            Ok(c) => c,
1431            Err(e) => {
1432                return Err(ExecutionError::new(
1433                    ExecutionErrorCode::SpawnError,
1434                    format!("failed to spawn shell: {e}"),
1435                ));
1436            }
1437        };
1438        let pid = child.id();
1439        let mut process_guard = ShellProcessGuard {
1440            pid,
1441            active: self.active_pids.clone(),
1442        };
1443        #[cfg(windows)]
1444        {
1445            let started = match (pid, child.raw_handle()) {
1446                (Some(pid), Some(process)) => shell_jobs::start(pid, process),
1447                _ => Err("the shell has no process handle".to_owned()),
1448            };
1449            if let Err(error) = started {
1450                if let Some(pid) = pid {
1451                    shell_jobs::forget(pid);
1452                }
1453                let _ = child.start_kill();
1454                return Err(ExecutionError::new(
1455                    ExecutionErrorCode::SpawnError,
1456                    format!("failed to start shell: {error}"),
1457                ));
1458            }
1459        }
1460        if let Some(pid) = pid {
1461            self.active_pids
1462                .lock()
1463                .unwrap_or_else(|e| e.into_inner())
1464                .insert(pid);
1465        }
1466
1467        // Stdin transport: write command then close. Closing happens on BOTH
1468        // transports, and deliberately: anything that prompts (`npx` asking to
1469        // install, `npm init`, a `read` in a script) must see EOF and fail fast,
1470        // not block on a pipe that nothing will ever write to or close. tokio's
1471        // `Child::wait` also drops stdin as a deadlock guard, but relying on that
1472        // would make the guarantee a side effect of an implementation detail.
1473        let mut stdin = child.stdin.take();
1474        if matches!(transport, CommandTransport::Stdin) {
1475            if let Some(stdin) = stdin.as_mut() {
1476                use tokio::io::AsyncWriteExt;
1477                let _ = stdin.write_all(command.as_bytes()).await;
1478                let _ = stdin.flush().await;
1479            }
1480        }
1481        drop(stdin);
1482
1483        // Collect stdout/stderr via separate read tasks, firing callbacks.
1484        let mut stdout_buf = String::new();
1485        let mut stderr_buf = String::new();
1486        let cancel = options.cancel;
1487        let stop_readers = CancellationToken::new();
1488        let mut on_stdout = options.on_stdout;
1489        let mut on_stderr = options.on_stderr;
1490
1491        let mut stdout = child.stdout.take();
1492        let mut stderr = child.stderr.take();
1493
1494        let stdout_task = async {
1495            if let Some(s) = stdout.as_mut() {
1496                let mut buf = vec![0u8; 8192];
1497                let mut decoder = crate::output_decode::StreamDecoder::new();
1498                use tokio::io::AsyncReadExt;
1499                loop {
1500                    let read_result = tokio::select! {
1501                        biased;
1502                        _ = stop_readers.cancelled() => break,
1503                        _ = async {
1504                            match cancel {
1505                                Some(token) => token.cancelled().await,
1506                                None => std::future::pending::<()>().await,
1507                            }
1508                        } => break,
1509                        result = s.read(&mut buf) => result,
1510                    };
1511                    let n = match read_result {
1512                        Ok(0) => break,
1513                        Ok(n) => n,
1514                        Err(_) => break,
1515                    };
1516                    let chunk = decoder.push(&buf[..n]);
1517                    if chunk.is_empty() {
1518                        continue;
1519                    }
1520                    if let Some(cb) = on_stdout.as_mut() {
1521                        // Callback errors are swallowed (TS sets callbackError;
1522                        // v1 simplifies — the callback contract is best-effort).
1523                        cb(&chunk);
1524                    }
1525                    stdout_buf.push_str(&chunk);
1526                }
1527                let tail = decoder.finish();
1528                if !tail.is_empty() {
1529                    if let Some(cb) = on_stdout.as_mut() {
1530                        cb(&tail);
1531                    }
1532                    stdout_buf.push_str(&tail);
1533                }
1534            }
1535        };
1536        let stderr_task = async {
1537            if let Some(s) = stderr.as_mut() {
1538                let mut buf = vec![0u8; 8192];
1539                let mut decoder = crate::output_decode::StreamDecoder::new();
1540                use tokio::io::AsyncReadExt;
1541                loop {
1542                    let read_result = tokio::select! {
1543                        biased;
1544                        _ = stop_readers.cancelled() => break,
1545                        _ = async {
1546                            match cancel {
1547                                Some(token) => token.cancelled().await,
1548                                None => std::future::pending::<()>().await,
1549                            }
1550                        } => break,
1551                        result = s.read(&mut buf) => result,
1552                    };
1553                    let n = match read_result {
1554                        Ok(0) => break,
1555                        Ok(n) => n,
1556                        Err(_) => break,
1557                    };
1558                    let chunk = decoder.push(&buf[..n]);
1559                    if chunk.is_empty() {
1560                        continue;
1561                    }
1562                    if let Some(cb) = on_stderr.as_mut() {
1563                        cb(&chunk);
1564                    }
1565                    stderr_buf.push_str(&chunk);
1566                }
1567                let tail = decoder.finish();
1568                if !tail.is_empty() {
1569                    if let Some(cb) = on_stderr.as_mut() {
1570                        cb(&tail);
1571                    }
1572                    stderr_buf.push_str(&tail);
1573                }
1574            }
1575        };
1576
1577        // Wait for the child, with timeout + cancellation.
1578        let mut timed_out = false;
1579        let exit_status = {
1580            // We pin stdout/stderr take handles + the wait future, then drive
1581            // them concurrently inside a single select! block. `child` is only
1582            // touched again AFTER the join completes (kill + reap), so the
1583            // borrow ends cleanly.
1584            let status_fut = async {
1585                match (timeout, cancel) {
1586                    (Some(to), Some(token)) => {
1587                        tokio::select! {
1588                            status = child.wait() => status,
1589                            _ = tokio::time::sleep(to) => {
1590                                timed_out = true;
1591                                if let Some(pid) = child.id() {
1592                                    kill_process_tree(pid).await;
1593                                }
1594                                child.wait().await
1595                            }
1596                            _ = token.cancelled() => {
1597                                if let Some(pid) = child.id() {
1598                                    kill_process_tree(pid).await;
1599                                }
1600                                child.wait().await
1601                            }
1602                        }
1603                    }
1604                    (Some(to), None) => match tokio::time::timeout(to, child.wait()).await {
1605                        Ok(status) => status,
1606                        Err(_) => {
1607                            timed_out = true;
1608                            if let Some(pid) = child.id() {
1609                                kill_process_tree(pid).await;
1610                            }
1611                            child.wait().await
1612                        }
1613                    },
1614                    (None, Some(token)) => {
1615                        tokio::select! {
1616                            status = child.wait() => status,
1617                            _ = token.cancelled() => {
1618                                if let Some(pid) = child.id() {
1619                                    kill_process_tree(pid).await;
1620                                }
1621                                child.wait().await
1622                            }
1623                        }
1624                    }
1625                    (None, None) => child.wait().await,
1626                }
1627            };
1628            // Run stdio + status concurrently — but the CHILD is the driver:
1629            // once it is reaped the command is over, and the call has to end even
1630            // if something else still holds the stdout/stderr pipes open.
1631            //
1632            // This is the "`npm run` 卡住" shape. A script that starts a watcher,
1633            // a dev-server or a background daemon leaves a grandchild running with
1634            // the inherited pipes, so reading to EOF waits for a process the
1635            // command no longer owns. No timeout rescues that: the timeout wraps
1636            // `child.wait()` and the child already exited successfully.
1637            //
1638            // The pipes are still read while the child runs: a command that writes
1639            // more than the pipe buffer (64 KiB on Linux) blocks until someone
1640            // reads, so waiting for the child first would deadlock on any broad
1641            // `rg` or build log.
1642            tokio::pin!(status_fut, stdout_task, stderr_task);
1643            let (mut stdout_done, mut stderr_done) = (false, false);
1644            let status_res = loop {
1645                tokio::select! {
1646                    status = &mut status_fut => break status,
1647                    () = &mut stdout_task, if !stdout_done => stdout_done = true,
1648                    () = &mut stderr_task, if !stderr_done => stderr_done = true,
1649                }
1650            };
1651            // Disarm immediately after a successful wait, before any await:
1652            // the shell has been reaped and its PID may now be reused.
1653            if status_res.is_ok() {
1654                process_guard.finish();
1655            }
1656            // Drain what is already in the pipe — a completed write is already in
1657            // the pipe buffer, so this is not a race — then stop, without waiting
1658            // for an EOF that may never come. A command whose own process is gone
1659            // should not be able to hold the call open.
1660            let drain = async {
1661                tokio::join!(
1662                    async {
1663                        if !stdout_done {
1664                            (&mut stdout_task).await;
1665                        }
1666                    },
1667                    async {
1668                        if !stderr_done {
1669                            (&mut stderr_task).await;
1670                        }
1671                    },
1672                );
1673            };
1674            tokio::pin!(drain);
1675            if tokio::time::timeout(
1676                std::time::Duration::from_millis(EXIT_STDIO_GRACE_MS),
1677                &mut drain,
1678            )
1679            .await
1680            .is_err()
1681            {
1682                // Stop reads, not their futures: both decoders must finish and
1683                // deliver already-read tails to callbacks and captured output.
1684                stop_readers.cancel();
1685                drain.await;
1686            }
1687            status_res
1688        };
1689
1690        // Give trailing stdio a brief grace period. Only the timed-out and
1691        // cancelled paths still owe a wait: on the normal path the drain above
1692        // already capped it.
1693        if timed_out {
1694            let _ = tokio::time::sleep(std::time::Duration::from_millis(EXIT_STDIO_GRACE_MS)).await;
1695        }
1696
1697        // Resolution priority: timedOut → cancelled → status.
1698        let status = match exit_status {
1699            Ok(s) => s,
1700            Err(e) => {
1701                return Err(ExecutionError::new(
1702                    ExecutionErrorCode::SpawnError,
1703                    format!("child wait failed: {e}"),
1704                ));
1705            }
1706        };
1707        if timed_out {
1708            return Err(ExecutionError::timeout(
1709                options.timeout.map(|f| f as u64).unwrap_or(0),
1710            ));
1711        }
1712        if cancel.map(|t| t.is_cancelled()).unwrap_or(false) {
1713            return Err(ExecutionError::aborted());
1714        }
1715        let exit_code = status.code().unwrap_or(0);
1716        Ok(ShellOutput {
1717            stdout: stdout_buf,
1718            stderr: stderr_buf,
1719            exit_code,
1720        })
1721    }
1722
1723    async fn cleanup(&self) {
1724        FileSystem::cleanup(self).await
1725    }
1726}
1727
1728#[async_trait]
1729impl ExecutionEnv for OsExecutionEnv {}
1730
1731#[async_trait]
1732impl MutatingEnv for OsExecutionEnv {
1733    fn as_env(&self) -> &dyn ExecutionEnv {
1734        self
1735    }
1736    fn mutation_registry(&self) -> &MutationQueueRegistry {
1737        &self.registry
1738    }
1739}
1740
1741/// Validate a timeout (seconds). Mirrors `resolveTimeoutMs` semantics.
1742#[cfg(test)]
1743mod durability_tests {
1744    use super::*;
1745
1746    #[tokio::test]
1747    async fn os_backend_syncs_staged_file_and_publication_directory() {
1748        let temp = tempfile::tempdir().unwrap();
1749        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1750        env.write_file("staged", FileContent::Text("durable slice".into()), None)
1751            .await
1752            .unwrap();
1753        env.sync_file("staged", false, None).await.unwrap();
1754        env.sync_directory(".", None).await.unwrap();
1755    }
1756
1757    #[tokio::test]
1758    async fn os_writer_lease_persists_and_verifies_a_monotonic_fence() {
1759        let temp = tempfile::tempdir().unwrap();
1760        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1761        let first = env
1762            .try_acquire_writer_lease("journal.jsonl")
1763            .await
1764            .unwrap()
1765            .unwrap();
1766        first.verify_fence().unwrap();
1767        drop(first);
1768        let second = env
1769            .try_acquire_writer_lease("journal.jsonl")
1770            .await
1771            .unwrap()
1772            .unwrap();
1773        second.verify_fence().unwrap();
1774        drop(second);
1775        assert_eq!(
1776            std::fs::read_to_string(temp.path().join("journal.jsonl.lock")).unwrap(),
1777            "2"
1778        );
1779    }
1780
1781    #[cfg(unix)]
1782    #[tokio::test]
1783    async fn os_writer_lease_releases_a_shared_open_file_description() {
1784        let temp = tempfile::tempdir().unwrap();
1785        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1786        let lock = temp.path().join("journal.jsonl.lock");
1787        std::fs::write(&lock, "1").unwrap();
1788        let file = std::fs::OpenOptions::new()
1789            .read(true)
1790            .write(true)
1791            .open(&lock)
1792            .unwrap();
1793        fs2::FileExt::try_lock_exclusive(&file).unwrap();
1794        let inherited = file.try_clone().unwrap();
1795        let lease = OsWriterLease { file, fence: 1 };
1796        assert!(env.try_acquire_writer_lease("journal.jsonl").await.is_err());
1797        drop(lease);
1798        let next = env
1799            .try_acquire_writer_lease("journal.jsonl")
1800            .await
1801            .expect("retired writer retained a lock through the shared description")
1802            .unwrap();
1803        next.verify_fence().unwrap();
1804        assert_eq!(std::fs::read_to_string(lock).unwrap(), "2");
1805        drop(inherited);
1806    }
1807}
1808
1809fn resolve_timeout(timeout: Option<f64>) -> Result<Option<std::time::Duration>, ExecutionError> {
1810    match timeout {
1811        None => Ok(None),
1812        Some(secs) => {
1813            if !secs.is_finite() || secs <= 0.0 {
1814                return Err(ExecutionError::new(
1815                    ExecutionErrorCode::Timeout,
1816                    "Invalid timeout: must be a finite number of seconds",
1817                ));
1818            }
1819            let ms = secs * 1000.0;
1820            if ms > MAX_TIMEOUT_MS as f64 {
1821                return Err(ExecutionError::new(
1822                    ExecutionErrorCode::Timeout,
1823                    format!(
1824                        "Invalid timeout: maximum is {} seconds",
1825                        MAX_TIMEOUT_SECONDS
1826                    ),
1827                ));
1828            }
1829            Ok(Some(std::time::Duration::from_secs_f64(secs)))
1830        }
1831    }
1832}