Skip to main content

rpi_tools/
in_memory.rs

1//! `InMemoryExecutionEnv` — an in-memory `ExecutionEnv` for tests. NOT a direct
2//! mirror of a single TS file (the TS harness has no in-memory env; it tests
3//! against `NodeExecutionEnv` + tempdirs). This is the Rust port's primary test
4//! double, modeled to satisfy the same `FileSystem` + `Shell` contract so the
5//! conformance suite can run identical assertions against both `InMemory` and
6//! `Os`.
7//!
8//! Storage: `BTreeMap<String, InMemoryFile>` keyed by absolute path string.
9//! `mtime_ms` advances on each mutation (synthetic — there's no real clock, so
10//! we use a monotonic counter so order is stable + determinisitic-ish; the TS
11//! uses real `Date.now()` but tests only check is_newer-than-prev).
12
13use std::collections::BTreeMap;
14use std::path::{Path, PathBuf};
15use std::sync::Arc;
16
17use async_trait::async_trait;
18use tokio::sync::Mutex;
19use tokio_util::sync::CancellationToken;
20
21use crate::env::{
22    check_cancel_exec, check_cancel_file, ExecutionEnv, FileContent, FileInfo, FileKind,
23    FileSystem, Shell, ShellExecOptions, ShellOutput,
24};
25#[cfg(test)]
26use crate::error::ExecutionErrorCode;
27use crate::error::{io_to_file_code, ExecutionError, FileError, FileErrorCode};
28use crate::file_mutation_queue::{MutatingEnv, MutationQueueRegistry};
29
30/// An in-memory file: bytes + mtime counter.
31#[derive(Clone)]
32struct InMemoryFile {
33    bytes: Vec<u8>,
34    mtime_ms: i64,
35    kind: FileKind,
36}
37
38#[derive(Default)]
39struct Inner {
40    cwd: PathBuf,
41    files: BTreeMap<String, InMemoryFile>,
42    /// Synthetic monotonic clock — every mutation bumps this so `mtime_ms`
43    /// strictly increases within a process.
44    clock: i64,
45    /// Registered shell scripts: command-prefix → canned result. The `exec`
46    /// impl looks up the longest matching prefix.
47    shell_scripts: Vec<(String, ShellScript)>,
48    /// Tracked "child pids" — simulated; `cleanup` clears them. Kept as a set
49    /// of opaque i64 handles.
50    active_pids: Vec<i64>,
51}
52
53/// A canned shell result for `InMemoryExecutionEnv::exec`.
54#[derive(Clone)]
55pub struct ShellScript {
56    pub stdout: String,
57    pub stderr: String,
58    pub exit_code: i32,
59    /// Optional delay before the result resolves (simulates a slow command for
60    /// timeout/abort tests).
61    pub delay_ms: Option<u64>,
62}
63
64impl ShellScript {
65    pub fn success(stdout: impl Into<String>) -> Self {
66        Self {
67            stdout: stdout.into(),
68            stderr: String::new(),
69            exit_code: 0,
70            delay_ms: None,
71        }
72    }
73    pub fn failure(exit_code: i32, stderr: impl Into<String>) -> Self {
74        Self {
75            stdout: String::new(),
76            stderr: stderr.into(),
77            exit_code,
78            delay_ms: None,
79        }
80    }
81}
82
83/// In-memory `ExecutionEnv`. Clone shares the underlying state (cheap — the
84/// `Arc<Mutex<Inner>>` is shared).
85#[derive(Clone)]
86pub struct InMemoryExecutionEnv {
87    inner: Arc<Mutex<Inner>>,
88    registry: Arc<MutationQueueRegistry>,
89    /// Cwd snapshot, set at construction and never mutated. Stored outside the
90    /// mutex so the sync `FileSystem::cwd()` can return `&Path` without locking.
91    cwd_snapshot: Arc<PathBuf>,
92}
93
94impl InMemoryExecutionEnv {
95    pub fn new() -> Self {
96        Self::with_cwd(PathBuf::from("/"))
97    }
98
99    pub fn with_cwd(cwd: PathBuf) -> Self {
100        let snap = Arc::new(cwd.clone());
101        let mut files: BTreeMap<String, InMemoryFile> = BTreeMap::new();
102        // The cwd (and every ancestor) always exists on a real fs — you're in
103        // it. Register them as directories so tools that default their search
104        // path to `.` (ls/find/grep) can `list_dir`/`exists` the cwd without the
105        // test needing to `make_dir` it first. Matches `OsExecutionEnv` where
106        // `cwd()` is guaranteed to resolve + be listable.
107        let cwd_norm = Self::norm(&cwd.to_string_lossy());
108        let mut acc = String::new();
109        for seg in cwd_norm.trim_matches('/').split('/') {
110            acc = if acc.is_empty() {
111                format!("/{seg}")
112            } else {
113                format!("{acc}/{seg}")
114            };
115            files.insert(
116                acc.clone(),
117                InMemoryFile {
118                    bytes: Vec::new(),
119                    mtime_ms: 0,
120                    kind: FileKind::Directory,
121                },
122            );
123        }
124        Self {
125            inner: Arc::new(Mutex::new(Inner {
126                cwd,
127                files,
128                clock: 0,
129                shell_scripts: Vec::new(),
130                active_pids: Vec::new(),
131            })),
132            registry: Arc::new(MutationQueueRegistry::new()),
133            cwd_snapshot: snap,
134        }
135    }
136
137    /// Register a canned shell result for commands whose start matches `prefix`.
138    /// Longest-prefix match wins. Mirrors the faux-provider script pattern.
139    pub async fn register_shell(&self, prefix: impl Into<String>, script: ShellScript) {
140        let mut g = self.inner.lock().await;
141        g.shell_scripts.push((prefix.into(), script));
142        // Stable: longest-prefix-first lookup below.
143        g.shell_scripts.sort_by(|a, b| b.0.len().cmp(&a.0.len()));
144    }
145
146    /// Directly seed a file at an absolute path (test setup). Bumps mtime.
147    pub async fn seed_file(&self, abs_path: &str, bytes: Vec<u8>) {
148        let mut g = self.inner.lock().await;
149        g.clock += 1;
150        let mtime = g.clock;
151        g.files.insert(
152            abs_path.to_string(),
153            InMemoryFile {
154                bytes,
155                mtime_ms: mtime,
156                kind: FileKind::File,
157            },
158        );
159    }
160
161    async fn bump_clock(&self, inner: &mut Inner) -> i64 {
162        inner.clock += 1;
163        inner.clock
164    }
165
166    /// Resolve a path to an absolute `PathBuf` using the env's cwd.
167    ///
168    /// After joining, `.`/`..` components are collapsed component-by-component
169    /// (without a FS round-trip) to match `OsExecutionEnv::normalize_absolute`.
170    /// This matters because `PathBuf::join` preserves `.` as a `CurDir`
171    /// component: `cwd.join(".")` yields `/tmp/work/.`, which would miss the
172    /// `BTreeMap` key `/tmp/work` (and break tools that default their search
173    /// path to `.`). Collapsing here keeps the in-memory env consistent with the
174    /// OS env — every `absolute_path`/`resolve_key` consumer sees the same
175    /// canonical form both in tests (`InMemory`) and in production (`Os`).
176    fn resolve(cwd: &Path, path: &str) -> PathBuf {
177        let pb = PathBuf::from(path);
178        let joined = if pb.is_absolute() { pb } else { cwd.join(pb) };
179        let mut out = PathBuf::new();
180        for comp in joined.components() {
181            match comp {
182                std::path::Component::ParentDir => {
183                    out.pop();
184                }
185                std::path::Component::CurDir => {}
186                other => out.push(other),
187            }
188        }
189        out
190    }
191
192    /// Normalize a path string to forward slashes. The internal `BTreeMap` keys
193    /// are always stored normalized so that path-separator differences across
194    /// platforms (Windows `\` vs POSIX `/`) do not break the prefix-based
195    /// `list_dir` / `remove` lookups against POSIX-style test paths like
196    /// `/sessions` / `/proj`. `PathBuf::push`/`join` insert the OS separator
197    /// (`\` on Windows); without normalization, a file written at
198    /// `/sessions\--proj--\file.jsonl` would never match a `list_dir` prefix of
199    /// `/sessions/--proj--/` — which is exactly the cross-platform bug this
200    /// guards. This is a test double, so canonicalizing to `/` is safe and keeps
201    /// test paths portable.
202    fn norm(s: &str) -> String {
203        s.replace('\\', "/")
204    }
205
206    /// Resolve `path` against `cwd` and normalize to a forward-slash absolute
207    /// string suitable for use as a `BTreeMap` key.
208    fn resolve_key(cwd: &Path, path: &str) -> String {
209        Self::norm(&Self::resolve(cwd, path).to_string_lossy())
210    }
211}
212
213impl Default for InMemoryExecutionEnv {
214    fn default() -> Self {
215        Self::new()
216    }
217}
218
219#[async_trait]
220impl FileSystem for InMemoryExecutionEnv {
221    fn cwd(&self) -> &Path {
222        &self.cwd_snapshot
223    }
224
225    async fn absolute_path(
226        &self,
227        path: &str,
228        cancel: Option<&CancellationToken>,
229    ) -> Result<PathBuf, FileError> {
230        check_cancel_file(cancel, Some(path))?;
231        let g = self.inner.lock().await;
232        let resolved = Self::resolve(&g.cwd, path).to_string_lossy().into_owned();
233        // Normalize to forward slashes so absolute_path() returns a string
234        // consistent with the BTreeMap keys (POSIX-style), keeping the repo's
235        // join_path + write_file + list_dir chain coherent on Windows.
236        Ok(PathBuf::from(Self::norm(&resolved)))
237    }
238
239    async fn join_path(
240        &self,
241        parts: &[&str],
242        cancel: Option<&CancellationToken>,
243    ) -> Result<PathBuf, FileError> {
244        check_cancel_file(cancel, None)?;
245        let mut out = String::new();
246        for p in parts {
247            if out.is_empty() {
248                out = p.to_string();
249            } else if out.ends_with('/') {
250                out.push_str(p);
251            } else {
252                out.push('/');
253                out.push_str(p);
254            }
255        }
256        // Normalize any `\` the parts may carry to `/`.
257        Ok(PathBuf::from(Self::norm(&out)))
258    }
259
260    async fn read_text_file(
261        &self,
262        path: &str,
263        cancel: Option<&CancellationToken>,
264    ) -> Result<String, FileError> {
265        let bytes = self.read_binary_file(path, cancel).await?;
266        String::from_utf8(bytes).map_err(|e| {
267            FileError::new(FileErrorCode::Invalid, format!("invalid utf-8: {e}")).with_path(path)
268        })
269    }
270
271    async fn read_text_lines(
272        &self,
273        path: &str,
274        max_lines: Option<usize>,
275        cancel: Option<&CancellationToken>,
276    ) -> Result<Vec<String>, FileError> {
277        check_cancel_file(cancel, Some(path))?;
278        if max_lines.map(|m| m == 0).unwrap_or(false) {
279            return Ok(Vec::new());
280        }
281        let text = self.read_text_file(path, cancel).await?;
282        let mut lines: Vec<String> = text.split('\n').map(|s| s.to_string()).collect();
283        if text.ends_with('\n') {
284            if lines.last().map(|s| s.is_empty()).unwrap_or(false) {
285                lines.pop();
286            }
287        }
288        if let Some(m) = max_lines {
289            lines.truncate(m);
290        }
291        Ok(lines)
292    }
293
294    async fn read_binary_file(
295        &self,
296        path: &str,
297        cancel: Option<&CancellationToken>,
298    ) -> Result<Vec<u8>, FileError> {
299        check_cancel_file(cancel, Some(path))?;
300        let g = self.inner.lock().await;
301        let abs = Self::resolve_key(&g.cwd, path);
302        match g.files.get(&abs) {
303            Some(f) if f.kind == FileKind::File => Ok(f.bytes.clone()),
304            Some(f) if f.kind == FileKind::Directory => Err(FileError::new(
305                FileErrorCode::IsDirectory,
306                "path is a directory",
307            )
308            .with_path(&abs)),
309            Some(f) if f.kind == FileKind::Symlink => {
310                // Symlinks aren't really modeled here; treat as not-supported.
311                Err(
312                    FileError::new(FileErrorCode::NotSupported, "symlink read unsupported")
313                        .with_path(&abs),
314                )
315            }
316            _ => Err(FileError::not_found(&abs)),
317        }
318    }
319
320    async fn write_file(
321        &self,
322        path: &str,
323        content: FileContent,
324        cancel: Option<&CancellationToken>,
325    ) -> Result<(), FileError> {
326        check_cancel_file(cancel, Some(path))?;
327        let mut g = self.inner.lock().await;
328        let abs = Self::resolve_key(&g.cwd, path);
329        // Auto-create parent dirs (normalized so the key matches what later
330        // reads/writes look up).
331        let parent = Path::new(&abs)
332            .parent()
333            .map(|p| Self::norm(&p.to_string_lossy()));
334        if let Some(p) = parent {
335            if !p.is_empty() && !g.files.contains_key(&p) {
336                let mtime = self.bump_clock(&mut g).await;
337                g.files.insert(
338                    p,
339                    InMemoryFile {
340                        bytes: Vec::new(),
341                        mtime_ms: mtime,
342                        kind: FileKind::Directory,
343                    },
344                );
345            }
346        }
347        let mtime = self.bump_clock(&mut g).await;
348        g.files.insert(
349            abs.clone(),
350            InMemoryFile {
351                bytes: content.as_bytes().to_vec(),
352                mtime_ms: mtime,
353                kind: FileKind::File,
354            },
355        );
356        Ok(())
357    }
358
359    async fn append_file(
360        &self,
361        path: &str,
362        content: FileContent,
363        cancel: Option<&CancellationToken>,
364    ) -> Result<(), FileError> {
365        check_cancel_file(cancel, Some(path))?;
366        let mut g = self.inner.lock().await;
367        let abs = Self::resolve_key(&g.cwd, path);
368        let mtime = self.bump_clock(&mut g).await;
369        match g.files.get_mut(&abs) {
370            Some(f) if f.kind == FileKind::File => {
371                f.bytes.extend_from_slice(content.as_bytes());
372                f.mtime_ms = mtime;
373                Ok(())
374            }
375            Some(f) if f.kind == FileKind::Directory => Err(FileError::new(
376                FileErrorCode::IsDirectory,
377                "path is a directory",
378            )
379            .with_path(&abs)),
380            _ => {
381                g.files.insert(
382                    abs.clone(),
383                    InMemoryFile {
384                        bytes: content.as_bytes().to_vec(),
385                        mtime_ms: mtime,
386                        kind: FileKind::File,
387                    },
388                );
389                Ok(())
390            }
391        }
392    }
393
394    async fn truncate_file(
395        &self,
396        path: &str,
397        len: u64,
398        cancel: Option<&CancellationToken>,
399    ) -> Result<(), FileError> {
400        check_cancel_file(cancel, Some(path))?;
401        let mut g = self.inner.lock().await;
402        let abs = Self::resolve_key(&g.cwd, path);
403        let mtime = self.bump_clock(&mut g).await;
404        match g.files.get_mut(&abs) {
405            Some(f) if f.kind == FileKind::File => {
406                if len > f.bytes.len() as u64 {
407                    return Err(FileError::new(
408                        FileErrorCode::Invalid,
409                        "truncation cannot grow a file",
410                    )
411                    .with_path(&abs));
412                }
413                f.bytes.truncate(len as usize);
414                f.mtime_ms = mtime;
415                Ok(())
416            }
417            Some(f) if f.kind == FileKind::Directory => Err(FileError::new(
418                FileErrorCode::IsDirectory,
419                "path is a directory",
420            )
421            .with_path(&abs)),
422            _ => Err(FileError::new(FileErrorCode::NotFound, "path not found").with_path(&abs)),
423        }
424    }
425
426    async fn rename_file(
427        &self,
428        source: &str,
429        dest: &str,
430        cancel: Option<&CancellationToken>,
431    ) -> Result<(), FileError> {
432        check_cancel_file(cancel, Some(source))?;
433        let mut g = self.inner.lock().await;
434        let src_abs = Self::resolve_key(&g.cwd, source);
435        let dst_abs = Self::resolve_key(&g.cwd, dest);
436        match g.files.remove(&src_abs) {
437            Some(f) => {
438                let mtime = self.bump_clock(&mut g).await;
439                g.files.insert(
440                    dst_abs.clone(),
441                    InMemoryFile {
442                        bytes: f.bytes,
443                        mtime_ms: mtime,
444                        kind: f.kind,
445                    },
446                );
447                Ok(())
448            }
449            None => Err(FileError::not_found(&src_abs)),
450        }
451    }
452
453    async fn file_info(
454        &self,
455        path: &str,
456        cancel: Option<&CancellationToken>,
457    ) -> Result<FileInfo, FileError> {
458        check_cancel_file(cancel, Some(path))?;
459        let g = self.inner.lock().await;
460        let abs = Self::resolve_key(&g.cwd, path);
461        match g.files.get(&abs) {
462            Some(f) => Ok(FileInfo {
463                name: Path::new(&abs)
464                    .file_name()
465                    .map(|n| n.to_string_lossy().into_owned())
466                    .unwrap_or_else(|| abs.clone()),
467                path: PathBuf::from(&abs),
468                kind: f.kind,
469                size: f.bytes.len() as u64,
470                mtime_ms: f.mtime_ms,
471            }),
472            None => Err(FileError::not_found(&abs)),
473        }
474    }
475
476    async fn list_dir(
477        &self,
478        path: &str,
479        cancel: Option<&CancellationToken>,
480    ) -> Result<Vec<FileInfo>, FileError> {
481        check_cancel_file(cancel, Some(path))?;
482        let g = self.inner.lock().await;
483        let abs = Self::resolve_key(&g.cwd, path);
484        // Normalize the directory prefix for matching children.
485        let prefix = if abs.ends_with('/') {
486            abs.clone()
487        } else {
488            format!("{abs}/")
489        };
490        // Verify the dir itself exists.
491        let dir_exists = g
492            .files
493            .get(&abs)
494            .map(|f| f.kind == FileKind::Directory)
495            .unwrap_or(abs == "/");
496        if !dir_exists {
497            return Err(if g.files.contains_key(&abs) {
498                FileError::new(FileErrorCode::NotDirectory, "path is not a directory")
499                    .with_path(&abs)
500            } else {
501                FileError::not_found(&abs)
502            });
503        }
504        let mut out = Vec::new();
505        for (k, f) in g.files.iter() {
506            if let Some(rest) = k.strip_prefix(&prefix) {
507                // Direct child: no further '/'.
508                if !rest.is_empty() && !rest.contains('/') {
509                    out.push(FileInfo {
510                        name: rest.to_string(),
511                        path: PathBuf::from(k),
512                        kind: f.kind,
513                        size: f.bytes.len() as u64,
514                        mtime_ms: f.mtime_ms,
515                    });
516                }
517            }
518        }
519        Ok(out)
520    }
521
522    async fn canonical_path(
523        &self,
524        path: &str,
525        cancel: Option<&CancellationToken>,
526    ) -> Result<PathBuf, FileError> {
527        check_cancel_file(cancel, Some(path))?;
528        let g = self.inner.lock().await;
529        let abs = Self::resolve_key(&g.cwd, path);
530        if g.files.contains_key(&abs) || abs == "/" {
531            Ok(PathBuf::from(&abs))
532        } else {
533            Err(FileError::not_found(&abs))
534        }
535    }
536
537    async fn exists(
538        &self,
539        path: &str,
540        cancel: Option<&CancellationToken>,
541    ) -> Result<bool, FileError> {
542        check_cancel_file(cancel, Some(path))?;
543        let g = self.inner.lock().await;
544        let abs = Self::resolve_key(&g.cwd, path);
545        Ok(g.files.contains_key(&abs) || abs == "/")
546    }
547
548    async fn create_dir(
549        &self,
550        path: &str,
551        recursive: bool,
552        cancel: Option<&CancellationToken>,
553    ) -> Result<(), FileError> {
554        check_cancel_file(cancel, Some(path))?;
555        let mut g = self.inner.lock().await;
556        let abs = Self::resolve_key(&g.cwd, path);
557        if recursive {
558            // Create all ancestor dirs.
559            let mut acc = String::new();
560            for seg in abs.trim_matches('/').split('/') {
561                if acc.is_empty() {
562                    acc = format!("/{seg}");
563                } else {
564                    acc = format!("{acc}/{seg}");
565                }
566                if !g.files.contains_key(&acc) {
567                    let mtime = self.bump_clock(&mut g).await;
568                    g.files.insert(
569                        acc.clone(),
570                        InMemoryFile {
571                            bytes: Vec::new(),
572                            mtime_ms: mtime,
573                            kind: FileKind::Directory,
574                        },
575                    );
576                }
577            }
578        } else {
579            if !g.files.contains_key(&abs) {
580                let mtime = self.bump_clock(&mut g).await;
581                g.files.insert(
582                    abs.clone(),
583                    InMemoryFile {
584                        bytes: Vec::new(),
585                        mtime_ms: mtime,
586                        kind: FileKind::Directory,
587                    },
588                );
589            }
590        }
591        Ok(())
592    }
593
594    async fn remove(
595        &self,
596        path: &str,
597        recursive: bool,
598        force: bool,
599        cancel: Option<&CancellationToken>,
600    ) -> Result<(), FileError> {
601        check_cancel_file(cancel, Some(path))?;
602        let mut g = self.inner.lock().await;
603        let abs = Self::resolve_key(&g.cwd, path);
604        if !g.files.contains_key(&abs) {
605            if force {
606                return Ok(());
607            }
608            return Err(FileError::not_found(&abs));
609        }
610        if recursive {
611            // Remove this + all descendants.
612            let prefix = if abs.ends_with('/') {
613                abs.clone()
614            } else {
615                format!("{abs}/")
616            };
617            let to_remove: Vec<String> = g
618                .files
619                .keys()
620                .filter(|k| *k == &abs || k.starts_with(&prefix))
621                .cloned()
622                .collect();
623            for k in to_remove {
624                g.files.remove(&k);
625            }
626        } else {
627            // Non-recursive: error if dir has children.
628            let prefix = if abs.ends_with('/') {
629                abs.clone()
630            } else {
631                format!("{abs}/")
632            };
633            let has_children = g.files.keys().any(|k| k.starts_with(&prefix));
634            if has_children {
635                return Err(FileError::new(
636                    FileErrorCode::NotSupported,
637                    "directory not empty (use recursive)",
638                )
639                .with_path(&abs));
640            }
641            g.files.remove(&abs);
642        }
643        Ok(())
644    }
645
646    async fn create_temp_dir(
647        &self,
648        prefix: Option<&str>,
649        cancel: Option<&CancellationToken>,
650    ) -> Result<PathBuf, FileError> {
651        check_cancel_file(cancel, None)?;
652        let mut g = self.inner.lock().await;
653        let prefix = prefix.unwrap_or("tmp-");
654        // Use the synthetic clock for a unique suffix.
655        let n = g.clock + 1;
656        let name = format!("{}{}", prefix, unique_suffix(n));
657        let abs = format!("/tmp/{name}");
658        let mtime = self.bump_clock(&mut g).await;
659        g.files.insert(
660            abs.clone(),
661            InMemoryFile {
662                bytes: Vec::new(),
663                mtime_ms: mtime,
664                kind: FileKind::Directory,
665            },
666        );
667        Ok(PathBuf::from(abs))
668    }
669
670    async fn create_temp_file(
671        &self,
672        prefix: &str,
673        suffix: &str,
674        cancel: Option<&CancellationToken>,
675    ) -> Result<PathBuf, FileError> {
676        check_cancel_file(cancel, None)?;
677        let mut g = self.inner.lock().await;
678        let n = g.clock + 1;
679        let name = format!("{}{}{}", prefix, unique_suffix(n), suffix);
680        let abs = format!("/tmp/{name}");
681        let mtime = self.bump_clock(&mut g).await;
682        g.files.insert(
683            abs.clone(),
684            InMemoryFile {
685                bytes: Vec::new(),
686                mtime_ms: mtime,
687                kind: FileKind::File,
688            },
689        );
690        Ok(PathBuf::from(abs))
691    }
692
693    async fn cleanup(&self) {
694        let mut g = self.inner.lock().await;
695        g.active_pids.clear();
696    }
697}
698
699#[async_trait]
700impl Shell for InMemoryExecutionEnv {
701    async fn exec<'a>(
702        &'a self,
703        command: &str,
704        mut options: ShellExecOptions<'a>,
705    ) -> Result<ShellOutput, ExecutionError> {
706        check_cancel_exec(options.cancel)?;
707        let scripts = {
708            let g = self.inner.lock().await;
709            g.shell_scripts.clone()
710        };
711        // Longest-prefix match.
712        let matched = scripts.iter().find(|(p, _)| command.starts_with(p));
713        let script = match matched {
714            Some((_, s)) => s.clone(),
715            None => ShellScript {
716                stdout: String::new(),
717                stderr: format!("no shell script registered for: {command}"),
718                exit_code: 127,
719                delay_ms: None,
720            },
721        };
722
723        // Simulate a child pid tracking.
724        {
725            let mut g = self.inner.lock().await;
726            let pid = g.clock;
727            g.active_pids.push(pid);
728        }
729
730        // Optional delay — honor cancellation during it.
731        if let Some(ms) = script.delay_ms {
732            let dur = std::time::Duration::from_millis(ms);
733            if let Some(token) = options.cancel {
734                tokio::select! {
735                    _ = tokio::time::sleep(dur) => {}
736                    _ = token.cancelled() => {
737                        return Err(ExecutionError::aborted());
738                    }
739                }
740            } else if let Some(secs) = options.timeout {
741                let to = std::time::Duration::from_secs_f64(secs);
742                let sleep = tokio::time::sleep(dur.min(to));
743                tokio::pin!(sleep);
744                let deadline = tokio::time::sleep(to);
745                tokio::pin!(deadline);
746                tokio::select! {
747                    _ = &mut sleep => {}
748                    _ = &mut deadline => {
749                        return Err(ExecutionError::timeout(secs as u64));
750                    }
751                }
752            } else {
753                tokio::time::sleep(dur).await;
754            }
755        } else if let Some(secs) = options.timeout {
756            // No delay but a timeout — simulate instant completion; the timeout
757            // only matters if `delay_ms` exceeds it (handled above). If a test
758            // wants timeout-without-delay it should register a script with
759            // delay_ms > timeout.
760            let _ = secs;
761        }
762
763        // Stream stdout/stderr to the callbacks (single chunk).
764        if let Some(cb) = options.on_stdout.as_mut() {
765            if !script.stdout.is_empty() {
766                cb(&script.stdout);
767            }
768        }
769        if let Some(cb) = options.on_stderr.as_mut() {
770            if !script.stderr.is_empty() {
771                cb(&script.stderr);
772            }
773        }
774
775        Ok(ShellOutput {
776            stdout: script.stdout,
777            stderr: script.stderr,
778            exit_code: script.exit_code,
779        })
780    }
781
782    async fn cleanup(&self) {
783        let mut g = self.inner.lock().await;
784        g.active_pids.clear();
785    }
786}
787
788#[async_trait]
789impl ExecutionEnv for InMemoryExecutionEnv {}
790
791#[async_trait]
792impl MutatingEnv for InMemoryExecutionEnv {
793    fn as_env(&self) -> &dyn ExecutionEnv {
794        self
795    }
796    fn mutation_registry(&self) -> &MutationQueueRegistry {
797        &self.registry
798    }
799}
800
801/// Generate a deterministic-ish unique suffix from a counter. Mirrors
802/// `mkdtemp`'s 6-char suffix shape loosely (test-only).
803fn unique_suffix(n: i64) -> String {
804    // Base36 of the counter, zero-padded to 6 chars.
805    let mut s = String::new();
806    let mut v = n.max(0) as u64;
807    if v == 0 {
808        return "000000".to_string();
809    }
810    while v > 0 {
811        let d = (v % 36) as u8;
812        let c = if d < 10 { b'0' + d } else { b'a' + (d - 10) };
813        s.insert(0, c as char);
814        v /= 36;
815    }
816    while s.len() < 6 {
817        s.insert(0, '0');
818    }
819    s
820}
821
822/// io classification helper re-exported for env consumers (e.g. `OsExecutionEnv`
823/// test doubles). Kept here so the in-memory env can classify synthetic errors
824/// without duplicating the table.
825#[allow(dead_code)]
826fn unused_io_reexport(_: std::io::Error) -> FileErrorCode {
827    io_to_file_code(&std::io::Error::from(std::io::ErrorKind::Other))
828}
829
830#[cfg(test)]
831mod tests {
832    use super::*;
833
834    #[tokio::test]
835    async fn write_read_roundtrip() {
836        let env = InMemoryExecutionEnv::new();
837        env.write_file("/a/b.txt", "hello".into(), None)
838            .await
839            .unwrap();
840        let text = env.read_text_file("/a/b.txt", None).await.unwrap();
841        assert_eq!(text, "hello");
842        // Parent dir auto-created.
843        assert!(env.exists("/a", None).await.unwrap());
844    }
845
846    #[tokio::test]
847    async fn rename_moves_bytes() {
848        let env = InMemoryExecutionEnv::new();
849        env.write_file("/x.txt", "data".into(), None).await.unwrap();
850        env.rename_file("/x.txt", "/y.txt", None).await.unwrap();
851        assert!(!env.exists("/x.txt", None).await.unwrap());
852        assert_eq!(env.read_text_file("/y.txt", None).await.unwrap(), "data");
853    }
854
855    #[tokio::test]
856    async fn list_dir_children() {
857        let env = InMemoryExecutionEnv::new();
858        env.create_dir("/d", true, None).await.unwrap();
859        env.write_file("/d/a.txt", "1".into(), None).await.unwrap();
860        env.write_file("/d/b.txt", "2".into(), None).await.unwrap();
861        let entries = env.list_dir("/d", None).await.unwrap();
862        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
863        assert!(names.contains(&"a.txt"));
864        assert!(names.contains(&"b.txt"));
865    }
866
867    #[tokio::test]
868    async fn remove_recursive() {
869        let env = InMemoryExecutionEnv::new();
870        env.create_dir("/r", true, None).await.unwrap();
871        env.write_file("/r/a.txt", "1".into(), None).await.unwrap();
872        env.remove("/r", true, true, None).await.unwrap();
873        assert!(!env.exists("/r", None).await.unwrap());
874        assert!(!env.exists("/r/a.txt", None).await.unwrap());
875    }
876
877    #[tokio::test]
878    async fn temp_dir_and_file_are_unique() {
879        let env = InMemoryExecutionEnv::new();
880        let d1 = env.create_temp_dir(Some("prefix-"), None).await.unwrap();
881        let d2 = env.create_temp_dir(Some("prefix-"), None).await.unwrap();
882        assert_ne!(d1, d2);
883        let f1 = env.create_temp_file("pre-", "-suf", None).await.unwrap();
884        let f2 = env.create_temp_file("pre-", "-suf", None).await.unwrap();
885        assert_ne!(f1, f2);
886    }
887
888    #[tokio::test]
889    async fn shell_script_longest_prefix_match() {
890        let env = InMemoryExecutionEnv::new();
891        env.register_shell("git", ShellScript::success("git-out"))
892            .await;
893        env.register_shell("git status", ShellScript::success("clean"))
894            .await;
895        let out = env
896            .exec("git status", ShellExecOptions::default())
897            .await
898            .unwrap();
899        assert_eq!(out.stdout, "clean");
900        let out2 = env
901            .exec("git log", ShellExecOptions::default())
902            .await
903            .unwrap();
904        assert_eq!(out2.stdout, "git-out");
905    }
906
907    #[tokio::test]
908    async fn cancel_returns_aborted() {
909        let env = InMemoryExecutionEnv::new();
910        let token = CancellationToken::new();
911        token.cancel();
912        let r = env
913            .exec(
914                "anything",
915                ShellExecOptions {
916                    cancel: Some(&token),
917                    ..Default::default()
918                },
919            )
920            .await;
921        assert!(matches!(
922            r,
923            Err(ExecutionError {
924                code: ExecutionErrorCode::Aborted,
925                ..
926            })
927        ));
928    }
929}