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
219fn file_bytes<'a>(
220    files: &'a BTreeMap<String, InMemoryFile>,
221    abs: &str,
222) -> Result<&'a [u8], FileError> {
223    match files.get(abs) {
224        Some(f) if f.kind == FileKind::File => Ok(&f.bytes),
225        Some(f) if f.kind == FileKind::Directory => {
226            Err(FileError::new(FileErrorCode::IsDirectory, "path is a directory").with_path(abs))
227        }
228        Some(f) if f.kind == FileKind::Symlink => {
229            // Symlinks aren't really modeled here; treat as not-supported.
230            Err(
231                FileError::new(FileErrorCode::NotSupported, "symlink read unsupported")
232                    .with_path(abs),
233            )
234        }
235        _ => Err(FileError::not_found(abs)),
236    }
237}
238
239#[async_trait]
240impl FileSystem for InMemoryExecutionEnv {
241    fn cwd(&self) -> &Path {
242        &self.cwd_snapshot
243    }
244
245    async fn absolute_path(
246        &self,
247        path: &str,
248        cancel: Option<&CancellationToken>,
249    ) -> Result<PathBuf, FileError> {
250        check_cancel_file(cancel, Some(path))?;
251        let g = self.inner.lock().await;
252        let resolved = Self::resolve(&g.cwd, path).to_string_lossy().into_owned();
253        // Normalize to forward slashes so absolute_path() returns a string
254        // consistent with the BTreeMap keys (POSIX-style), keeping the repo's
255        // join_path + write_file + list_dir chain coherent on Windows.
256        Ok(PathBuf::from(Self::norm(&resolved)))
257    }
258
259    async fn join_path(
260        &self,
261        parts: &[&str],
262        cancel: Option<&CancellationToken>,
263    ) -> Result<PathBuf, FileError> {
264        check_cancel_file(cancel, None)?;
265        let mut out = String::new();
266        for p in parts {
267            if out.is_empty() {
268                out = p.to_string();
269            } else if out.ends_with('/') {
270                out.push_str(p);
271            } else {
272                out.push('/');
273                out.push_str(p);
274            }
275        }
276        // Normalize any `\` the parts may carry to `/`.
277        Ok(PathBuf::from(Self::norm(&out)))
278    }
279
280    async fn read_text_file(
281        &self,
282        path: &str,
283        cancel: Option<&CancellationToken>,
284    ) -> Result<String, FileError> {
285        let bytes = self.read_binary_file(path, cancel).await?;
286        String::from_utf8(bytes).map_err(|e| {
287            FileError::new(FileErrorCode::Invalid, format!("invalid utf-8: {e}")).with_path(path)
288        })
289    }
290
291    async fn read_text_lines(
292        &self,
293        path: &str,
294        max_lines: Option<usize>,
295        cancel: Option<&CancellationToken>,
296    ) -> Result<Vec<String>, FileError> {
297        check_cancel_file(cancel, Some(path))?;
298        if max_lines.map(|m| m == 0).unwrap_or(false) {
299            return Ok(Vec::new());
300        }
301        let text = self.read_text_file(path, cancel).await?;
302        let mut lines: Vec<String> = text.split('\n').map(|s| s.to_string()).collect();
303        if text.ends_with('\n') {
304            if lines.last().map(|s| s.is_empty()).unwrap_or(false) {
305                lines.pop();
306            }
307        }
308        if let Some(m) = max_lines {
309            lines.truncate(m);
310        }
311        Ok(lines)
312    }
313
314    async fn read_binary_file(
315        &self,
316        path: &str,
317        cancel: Option<&CancellationToken>,
318    ) -> Result<Vec<u8>, FileError> {
319        check_cancel_file(cancel, Some(path))?;
320        let g = self.inner.lock().await;
321        let abs = Self::resolve_key(&g.cwd, path);
322        Ok(file_bytes(&g.files, &abs)?.to_vec())
323    }
324
325    async fn read_text_file_bounded(
326        &self,
327        path: &str,
328        max_bytes: usize,
329        cancel: Option<&CancellationToken>,
330    ) -> Result<Option<String>, FileError> {
331        check_cancel_file(cancel, Some(path))?;
332        let g = self.inner.lock().await;
333        let abs = Self::resolve_key(&g.cwd, path);
334        let bytes = file_bytes(&g.files, &abs)?;
335        if bytes.len() > max_bytes {
336            return Ok(None);
337        }
338        let bytes = bytes.to_vec();
339        drop(g);
340        String::from_utf8(bytes).map(Some).map_err(|e| {
341            FileError::new(FileErrorCode::Invalid, format!("invalid utf-8: {e}")).with_path(path)
342        })
343    }
344
345    async fn write_file(
346        &self,
347        path: &str,
348        content: FileContent,
349        cancel: Option<&CancellationToken>,
350    ) -> Result<(), FileError> {
351        check_cancel_file(cancel, Some(path))?;
352        let mut g = self.inner.lock().await;
353        let abs = Self::resolve_key(&g.cwd, path);
354        // Auto-create parent dirs (normalized so the key matches what later
355        // reads/writes look up).
356        let parent = Path::new(&abs)
357            .parent()
358            .map(|p| Self::norm(&p.to_string_lossy()));
359        if let Some(p) = parent {
360            if !p.is_empty() && !g.files.contains_key(&p) {
361                let mtime = self.bump_clock(&mut g).await;
362                g.files.insert(
363                    p,
364                    InMemoryFile {
365                        bytes: Vec::new(),
366                        mtime_ms: mtime,
367                        kind: FileKind::Directory,
368                    },
369                );
370            }
371        }
372        let mtime = self.bump_clock(&mut g).await;
373        g.files.insert(
374            abs.clone(),
375            InMemoryFile {
376                bytes: content.as_bytes().to_vec(),
377                mtime_ms: mtime,
378                kind: FileKind::File,
379            },
380        );
381        Ok(())
382    }
383
384    async fn append_file(
385        &self,
386        path: &str,
387        content: FileContent,
388        cancel: Option<&CancellationToken>,
389    ) -> Result<(), FileError> {
390        check_cancel_file(cancel, Some(path))?;
391        let mut g = self.inner.lock().await;
392        let abs = Self::resolve_key(&g.cwd, path);
393        let mtime = self.bump_clock(&mut g).await;
394        match g.files.get_mut(&abs) {
395            Some(f) if f.kind == FileKind::File => {
396                f.bytes.extend_from_slice(content.as_bytes());
397                f.mtime_ms = mtime;
398                Ok(())
399            }
400            Some(f) if f.kind == FileKind::Directory => Err(FileError::new(
401                FileErrorCode::IsDirectory,
402                "path is a directory",
403            )
404            .with_path(&abs)),
405            _ => {
406                g.files.insert(
407                    abs.clone(),
408                    InMemoryFile {
409                        bytes: content.as_bytes().to_vec(),
410                        mtime_ms: mtime,
411                        kind: FileKind::File,
412                    },
413                );
414                Ok(())
415            }
416        }
417    }
418
419    async fn truncate_file(
420        &self,
421        path: &str,
422        len: u64,
423        cancel: Option<&CancellationToken>,
424    ) -> Result<(), FileError> {
425        check_cancel_file(cancel, Some(path))?;
426        let mut g = self.inner.lock().await;
427        let abs = Self::resolve_key(&g.cwd, path);
428        let mtime = self.bump_clock(&mut g).await;
429        match g.files.get_mut(&abs) {
430            Some(f) if f.kind == FileKind::File => {
431                if len > f.bytes.len() as u64 {
432                    return Err(FileError::new(
433                        FileErrorCode::Invalid,
434                        "truncation cannot grow a file",
435                    )
436                    .with_path(&abs));
437                }
438                f.bytes.truncate(len as usize);
439                f.mtime_ms = mtime;
440                Ok(())
441            }
442            Some(f) if f.kind == FileKind::Directory => Err(FileError::new(
443                FileErrorCode::IsDirectory,
444                "path is a directory",
445            )
446            .with_path(&abs)),
447            _ => Err(FileError::new(FileErrorCode::NotFound, "path not found").with_path(&abs)),
448        }
449    }
450
451    async fn rename_file(
452        &self,
453        source: &str,
454        dest: &str,
455        cancel: Option<&CancellationToken>,
456    ) -> Result<(), FileError> {
457        check_cancel_file(cancel, Some(source))?;
458        let mut g = self.inner.lock().await;
459        let src_abs = Self::resolve_key(&g.cwd, source);
460        let dst_abs = Self::resolve_key(&g.cwd, dest);
461        match g.files.remove(&src_abs) {
462            Some(f) => {
463                let mtime = self.bump_clock(&mut g).await;
464                g.files.insert(
465                    dst_abs.clone(),
466                    InMemoryFile {
467                        bytes: f.bytes,
468                        mtime_ms: mtime,
469                        kind: f.kind,
470                    },
471                );
472                Ok(())
473            }
474            None => Err(FileError::not_found(&src_abs)),
475        }
476    }
477
478    async fn file_info(
479        &self,
480        path: &str,
481        cancel: Option<&CancellationToken>,
482    ) -> Result<FileInfo, FileError> {
483        check_cancel_file(cancel, Some(path))?;
484        let g = self.inner.lock().await;
485        let abs = Self::resolve_key(&g.cwd, path);
486        match g.files.get(&abs) {
487            Some(f) => Ok(FileInfo {
488                name: Path::new(&abs)
489                    .file_name()
490                    .map(|n| n.to_string_lossy().into_owned())
491                    .unwrap_or_else(|| abs.clone()),
492                path: PathBuf::from(&abs),
493                kind: f.kind,
494                size: f.bytes.len() as u64,
495                mtime_ms: f.mtime_ms,
496            }),
497            None => Err(FileError::not_found(&abs)),
498        }
499    }
500
501    async fn list_dir(
502        &self,
503        path: &str,
504        cancel: Option<&CancellationToken>,
505    ) -> Result<Vec<FileInfo>, FileError> {
506        check_cancel_file(cancel, Some(path))?;
507        let g = self.inner.lock().await;
508        let abs = Self::resolve_key(&g.cwd, path);
509        // Normalize the directory prefix for matching children.
510        let prefix = if abs.ends_with('/') {
511            abs.clone()
512        } else {
513            format!("{abs}/")
514        };
515        // Verify the dir itself exists.
516        let dir_exists = g
517            .files
518            .get(&abs)
519            .map(|f| f.kind == FileKind::Directory)
520            .unwrap_or(abs == "/");
521        if !dir_exists {
522            return Err(if g.files.contains_key(&abs) {
523                FileError::new(FileErrorCode::NotDirectory, "path is not a directory")
524                    .with_path(&abs)
525            } else {
526                FileError::not_found(&abs)
527            });
528        }
529        let mut out = Vec::new();
530        for (k, f) in g.files.iter() {
531            if let Some(rest) = k.strip_prefix(&prefix) {
532                // Direct child: no further '/'.
533                if !rest.is_empty() && !rest.contains('/') {
534                    out.push(FileInfo {
535                        name: rest.to_string(),
536                        path: PathBuf::from(k),
537                        kind: f.kind,
538                        size: f.bytes.len() as u64,
539                        mtime_ms: f.mtime_ms,
540                    });
541                }
542            }
543        }
544        Ok(out)
545    }
546
547    async fn canonical_path(
548        &self,
549        path: &str,
550        cancel: Option<&CancellationToken>,
551    ) -> Result<PathBuf, FileError> {
552        check_cancel_file(cancel, Some(path))?;
553        let g = self.inner.lock().await;
554        let abs = Self::resolve_key(&g.cwd, path);
555        if g.files.contains_key(&abs) || abs == "/" {
556            Ok(PathBuf::from(&abs))
557        } else {
558            Err(FileError::not_found(&abs))
559        }
560    }
561
562    async fn exists(
563        &self,
564        path: &str,
565        cancel: Option<&CancellationToken>,
566    ) -> Result<bool, FileError> {
567        check_cancel_file(cancel, Some(path))?;
568        let g = self.inner.lock().await;
569        let abs = Self::resolve_key(&g.cwd, path);
570        Ok(g.files.contains_key(&abs) || abs == "/")
571    }
572
573    async fn create_dir(
574        &self,
575        path: &str,
576        recursive: bool,
577        cancel: Option<&CancellationToken>,
578    ) -> Result<(), FileError> {
579        check_cancel_file(cancel, Some(path))?;
580        let mut g = self.inner.lock().await;
581        let abs = Self::resolve_key(&g.cwd, path);
582        if recursive {
583            // Create all ancestor dirs.
584            let mut acc = String::new();
585            for seg in abs.trim_matches('/').split('/') {
586                if acc.is_empty() {
587                    acc = format!("/{seg}");
588                } else {
589                    acc = format!("{acc}/{seg}");
590                }
591                if !g.files.contains_key(&acc) {
592                    let mtime = self.bump_clock(&mut g).await;
593                    g.files.insert(
594                        acc.clone(),
595                        InMemoryFile {
596                            bytes: Vec::new(),
597                            mtime_ms: mtime,
598                            kind: FileKind::Directory,
599                        },
600                    );
601                }
602            }
603        } else {
604            if !g.files.contains_key(&abs) {
605                let mtime = self.bump_clock(&mut g).await;
606                g.files.insert(
607                    abs.clone(),
608                    InMemoryFile {
609                        bytes: Vec::new(),
610                        mtime_ms: mtime,
611                        kind: FileKind::Directory,
612                    },
613                );
614            }
615        }
616        Ok(())
617    }
618
619    async fn remove(
620        &self,
621        path: &str,
622        recursive: bool,
623        force: bool,
624        cancel: Option<&CancellationToken>,
625    ) -> Result<(), FileError> {
626        check_cancel_file(cancel, Some(path))?;
627        let mut g = self.inner.lock().await;
628        let abs = Self::resolve_key(&g.cwd, path);
629        if !g.files.contains_key(&abs) {
630            if force {
631                return Ok(());
632            }
633            return Err(FileError::not_found(&abs));
634        }
635        if recursive {
636            // Remove this + all descendants.
637            let prefix = if abs.ends_with('/') {
638                abs.clone()
639            } else {
640                format!("{abs}/")
641            };
642            let to_remove: Vec<String> = g
643                .files
644                .keys()
645                .filter(|k| *k == &abs || k.starts_with(&prefix))
646                .cloned()
647                .collect();
648            for k in to_remove {
649                g.files.remove(&k);
650            }
651        } else {
652            // Non-recursive: error if dir has children.
653            let prefix = if abs.ends_with('/') {
654                abs.clone()
655            } else {
656                format!("{abs}/")
657            };
658            let has_children = g.files.keys().any(|k| k.starts_with(&prefix));
659            if has_children {
660                return Err(FileError::new(
661                    FileErrorCode::NotSupported,
662                    "directory not empty (use recursive)",
663                )
664                .with_path(&abs));
665            }
666            g.files.remove(&abs);
667        }
668        Ok(())
669    }
670
671    async fn create_temp_dir(
672        &self,
673        prefix: Option<&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 prefix = prefix.unwrap_or("tmp-");
679        // Use the synthetic clock for a unique suffix.
680        let n = g.clock + 1;
681        let name = format!("{}{}", prefix, unique_suffix(n));
682        let abs = format!("/tmp/{name}");
683        let mtime = self.bump_clock(&mut g).await;
684        g.files.insert(
685            abs.clone(),
686            InMemoryFile {
687                bytes: Vec::new(),
688                mtime_ms: mtime,
689                kind: FileKind::Directory,
690            },
691        );
692        Ok(PathBuf::from(abs))
693    }
694
695    async fn create_temp_file(
696        &self,
697        prefix: &str,
698        suffix: &str,
699        cancel: Option<&CancellationToken>,
700    ) -> Result<PathBuf, FileError> {
701        check_cancel_file(cancel, None)?;
702        let mut g = self.inner.lock().await;
703        let n = g.clock + 1;
704        let name = format!("{}{}{}", prefix, unique_suffix(n), suffix);
705        let abs = format!("/tmp/{name}");
706        let mtime = self.bump_clock(&mut g).await;
707        g.files.insert(
708            abs.clone(),
709            InMemoryFile {
710                bytes: Vec::new(),
711                mtime_ms: mtime,
712                kind: FileKind::File,
713            },
714        );
715        Ok(PathBuf::from(abs))
716    }
717
718    async fn cleanup(&self) {
719        let mut g = self.inner.lock().await;
720        g.active_pids.clear();
721    }
722}
723
724#[async_trait]
725impl Shell for InMemoryExecutionEnv {
726    async fn exec<'a>(
727        &'a self,
728        command: &str,
729        mut options: ShellExecOptions<'a>,
730    ) -> Result<ShellOutput, ExecutionError> {
731        check_cancel_exec(options.cancel)?;
732        let scripts = {
733            let g = self.inner.lock().await;
734            g.shell_scripts.clone()
735        };
736        // Longest-prefix match.
737        let matched = scripts.iter().find(|(p, _)| command.starts_with(p));
738        let script = match matched {
739            Some((_, s)) => s.clone(),
740            None => ShellScript {
741                stdout: String::new(),
742                stderr: format!("no shell script registered for: {command}"),
743                exit_code: 127,
744                delay_ms: None,
745            },
746        };
747
748        // Simulate a child pid tracking.
749        {
750            let mut g = self.inner.lock().await;
751            let pid = g.clock;
752            g.active_pids.push(pid);
753        }
754
755        // Optional delay — honor cancellation during it.
756        if let Some(ms) = script.delay_ms {
757            let dur = std::time::Duration::from_millis(ms);
758            if let Some(token) = options.cancel {
759                tokio::select! {
760                    _ = tokio::time::sleep(dur) => {}
761                    _ = token.cancelled() => {
762                        return Err(ExecutionError::aborted());
763                    }
764                }
765            } else if let Some(secs) = options.timeout {
766                let to = std::time::Duration::from_secs_f64(secs);
767                let sleep = tokio::time::sleep(dur.min(to));
768                tokio::pin!(sleep);
769                let deadline = tokio::time::sleep(to);
770                tokio::pin!(deadline);
771                tokio::select! {
772                    _ = &mut sleep => {}
773                    _ = &mut deadline => {
774                        return Err(ExecutionError::timeout(secs as u64));
775                    }
776                }
777            } else {
778                tokio::time::sleep(dur).await;
779            }
780        } else if let Some(secs) = options.timeout {
781            // No delay but a timeout — simulate instant completion; the timeout
782            // only matters if `delay_ms` exceeds it (handled above). If a test
783            // wants timeout-without-delay it should register a script with
784            // delay_ms > timeout.
785            let _ = secs;
786        }
787
788        // Stream stdout/stderr to the callbacks (single chunk).
789        if let Some(cb) = options.on_stdout.as_mut() {
790            if !script.stdout.is_empty() {
791                cb(&script.stdout);
792            }
793        }
794        if let Some(cb) = options.on_stderr.as_mut() {
795            if !script.stderr.is_empty() {
796                cb(&script.stderr);
797            }
798        }
799
800        Ok(ShellOutput {
801            stdout: script.stdout,
802            stderr: script.stderr,
803            exit_code: script.exit_code,
804        })
805    }
806
807    async fn cleanup(&self) {
808        let mut g = self.inner.lock().await;
809        g.active_pids.clear();
810    }
811}
812
813#[async_trait]
814impl ExecutionEnv for InMemoryExecutionEnv {}
815
816#[async_trait]
817impl MutatingEnv for InMemoryExecutionEnv {
818    fn as_env(&self) -> &dyn ExecutionEnv {
819        self
820    }
821    fn mutation_registry(&self) -> &MutationQueueRegistry {
822        &self.registry
823    }
824}
825
826/// Generate a deterministic-ish unique suffix from a counter. Mirrors
827/// `mkdtemp`'s 6-char suffix shape loosely (test-only).
828fn unique_suffix(n: i64) -> String {
829    // Base36 of the counter, zero-padded to 6 chars.
830    let mut s = String::new();
831    let mut v = n.max(0) as u64;
832    if v == 0 {
833        return "000000".to_string();
834    }
835    while v > 0 {
836        let d = (v % 36) as u8;
837        let c = if d < 10 { b'0' + d } else { b'a' + (d - 10) };
838        s.insert(0, c as char);
839        v /= 36;
840    }
841    while s.len() < 6 {
842        s.insert(0, '0');
843    }
844    s
845}
846
847/// io classification helper re-exported for env consumers (e.g. `OsExecutionEnv`
848/// test doubles). Kept here so the in-memory env can classify synthetic errors
849/// without duplicating the table.
850#[allow(dead_code)]
851fn unused_io_reexport(_: std::io::Error) -> FileErrorCode {
852    io_to_file_code(&std::io::Error::from(std::io::ErrorKind::Other))
853}
854
855#[cfg(test)]
856mod tests {
857    use super::*;
858
859    #[tokio::test]
860    async fn write_read_roundtrip() {
861        let env = InMemoryExecutionEnv::new();
862        env.write_file("/a/b.txt", "hello".into(), None)
863            .await
864            .unwrap();
865        let text = env.read_text_file("/a/b.txt", None).await.unwrap();
866        assert_eq!(text, "hello");
867        // Parent dir auto-created.
868        assert!(env.exists("/a", None).await.unwrap());
869    }
870
871    #[tokio::test]
872    async fn rename_moves_bytes() {
873        let env = InMemoryExecutionEnv::new();
874        env.write_file("/x.txt", "data".into(), None).await.unwrap();
875        env.rename_file("/x.txt", "/y.txt", None).await.unwrap();
876        assert!(!env.exists("/x.txt", None).await.unwrap());
877        assert_eq!(env.read_text_file("/y.txt", None).await.unwrap(), "data");
878    }
879
880    #[tokio::test]
881    async fn list_dir_children() {
882        let env = InMemoryExecutionEnv::new();
883        env.create_dir("/d", true, None).await.unwrap();
884        env.write_file("/d/a.txt", "1".into(), None).await.unwrap();
885        env.write_file("/d/b.txt", "2".into(), None).await.unwrap();
886        let entries = env.list_dir("/d", None).await.unwrap();
887        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
888        assert!(names.contains(&"a.txt"));
889        assert!(names.contains(&"b.txt"));
890    }
891
892    #[tokio::test]
893    async fn remove_recursive() {
894        let env = InMemoryExecutionEnv::new();
895        env.create_dir("/r", true, None).await.unwrap();
896        env.write_file("/r/a.txt", "1".into(), None).await.unwrap();
897        env.remove("/r", true, true, None).await.unwrap();
898        assert!(!env.exists("/r", None).await.unwrap());
899        assert!(!env.exists("/r/a.txt", None).await.unwrap());
900    }
901
902    #[tokio::test]
903    async fn temp_dir_and_file_are_unique() {
904        let env = InMemoryExecutionEnv::new();
905        let d1 = env.create_temp_dir(Some("prefix-"), None).await.unwrap();
906        let d2 = env.create_temp_dir(Some("prefix-"), None).await.unwrap();
907        assert_ne!(d1, d2);
908        let f1 = env.create_temp_file("pre-", "-suf", None).await.unwrap();
909        let f2 = env.create_temp_file("pre-", "-suf", None).await.unwrap();
910        assert_ne!(f1, f2);
911    }
912
913    #[tokio::test]
914    async fn shell_script_longest_prefix_match() {
915        let env = InMemoryExecutionEnv::new();
916        env.register_shell("git", ShellScript::success("git-out"))
917            .await;
918        env.register_shell("git status", ShellScript::success("clean"))
919            .await;
920        let out = env
921            .exec("git status", ShellExecOptions::default())
922            .await
923            .unwrap();
924        assert_eq!(out.stdout, "clean");
925        let out2 = env
926            .exec("git log", ShellExecOptions::default())
927            .await
928            .unwrap();
929        assert_eq!(out2.stdout, "git-out");
930    }
931
932    #[tokio::test]
933    async fn cancel_returns_aborted() {
934        let env = InMemoryExecutionEnv::new();
935        let token = CancellationToken::new();
936        token.cancel();
937        let r = env
938            .exec(
939                "anything",
940                ShellExecOptions {
941                    cancel: Some(&token),
942                    ..Default::default()
943                },
944            )
945            .await;
946        assert!(matches!(
947            r,
948            Err(ExecutionError {
949                code: ExecutionErrorCode::Aborted,
950                ..
951            })
952        ));
953    }
954}