Skip to main content

rpi_tools/
env.rs

1//! Mirrors `packages/agent/src/harness/types.ts::ExecutionEnv` — the trait every
2//! tool and test-double implements. `ExecutionEnv = FileSystem + Shell`.
3//!
4//! Contract (plan §5.13): **every method must never panic.** All failures are
5//! encoded in `Result<_, FileError>` / `Result<_, ExecutionError>`. Paths may be
6//! absolute or relative to [`FileSystem::cwd`]; returned paths are "addressed"
7//! (symlink-canonicalized only by [`FileSystem::canonical_path`]).
8//!
9//! The TS `AbortSignal` becomes `&tokio_util::sync::CancellationToken` on every
10//! method. Backends SHOULD check `is_cancelled()` at entry and honor cooperative
11//! cancellation during blocking ops via `tokio::select!`.
12
13use std::collections::HashMap;
14use std::fs::Metadata;
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17
18use async_trait::async_trait;
19use tokio_util::sync::CancellationToken;
20
21use crate::error::{ExecutionError, FileError, FileErrorCode};
22
23/// `file` | `directory` | `symlink`. Mirrors TS `FileKind`.
24///
25/// Backends detect via `symlink_metadata` (lstat) — symlinks are NOT followed
26/// automatically by any `FileSystem` method except `canonical_path`.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum FileKind {
29    File,
30    Directory,
31    Symlink,
32}
33
34/// Mirrors TS `FileInfo`. `path` is the absolute addressed (resolved) path —
35/// NOT symlink-canonicalized. `mtime_ms` is ms since Unix epoch.
36#[derive(Debug, Clone)]
37pub struct FileInfo {
38    pub name: String,
39    pub path: PathBuf,
40    pub kind: FileKind,
41    pub size: u64,
42    pub mtime_ms: i64,
43}
44
45/// Write/append payload. Mirrors the TS `string | Uint8Array` union.
46#[derive(Debug, Clone)]
47pub enum FileContent {
48    Text(String),
49    Bytes(Vec<u8>),
50}
51
52impl FileContent {
53    pub fn as_bytes(&self) -> &[u8] {
54        match self {
55            FileContent::Text(s) => s.as_bytes(),
56            FileContent::Bytes(b) => b,
57        }
58    }
59}
60
61impl From<String> for FileContent {
62    fn from(s: String) -> Self {
63        FileContent::Text(s)
64    }
65}
66
67impl From<&str> for FileContent {
68    fn from(s: &str) -> Self {
69        FileContent::Text(s.to_string())
70    }
71}
72
73impl From<Vec<u8>> for FileContent {
74    fn from(b: Vec<u8>) -> Self {
75        FileContent::Bytes(b)
76    }
77}
78
79/// Result of `Shell::exec`. Mirrors the TS inline return type
80/// `{ stdout, stderr, exitCode }`. Signal kills collapse to `exit_code: 0`
81/// (matching the TS `code ?? 0` rule).
82#[derive(Debug, Clone)]
83pub struct ShellOutput {
84    pub stdout: String,
85    pub stderr: String,
86    pub exit_code: i32,
87}
88
89/// Mirrors TS `ShellExecOptions` (note: `timeout` is in **seconds**, matching
90/// the TS contract). `on_stdout` / `on_stderr` fire per chunk, interleaved in
91/// arrival order; the bash-tool wraps these with throttling + capture.
92#[derive(Clone, Debug)]
93pub struct ShellOverride {
94    pub program: PathBuf,
95    pub args: Vec<String>,
96}
97
98pub struct ShellExecOptions<'a> {
99    /// Optional executable and fixed arguments. `None` keeps the environment's
100    /// default shell (Bash on POSIX/Windows), while tools such as PowerShell
101    /// can select their native interpreter without going through Bash.
102    pub shell: Option<ShellOverride>,
103    pub cwd: Option<PathBuf>,
104    pub env: Option<HashMap<String, String>>,
105    /// Default `true`. When `false`, ONLY `env` is used (no process env, no
106    /// shell base env).
107    pub inherit_env: bool,
108    /// Seconds. `None` = no timeout.
109    pub timeout: Option<f64>,
110    pub cancel: Option<&'a CancellationToken>,
111    pub on_stdout: Option<Box<dyn FnMut(&str) + Send + 'a>>,
112    pub on_stderr: Option<Box<dyn FnMut(&str) + Send + 'a>>,
113}
114
115impl<'a> Default for ShellExecOptions<'a> {
116    fn default() -> Self {
117        Self {
118            shell: None,
119            cwd: None,
120            env: None,
121            inherit_env: true,
122            timeout: None,
123            cancel: None,
124            on_stdout: None,
125            on_stderr: None,
126        }
127    }
128}
129
130impl<'a> ShellExecOptions<'a> {
131    pub fn new() -> Self {
132        Self::default()
133    }
134}
135
136/// A process-local capability proving exclusive ownership of a file-backed
137/// writer. Backends that cannot provide an OS/process boundary return `None`
138/// from [`FileSystem::try_acquire_writer_lease`]; those backends retain their
139/// existing in-process semantics and must not be described as cross-process
140/// fenced.
141///
142/// A backend may also persist a monotonic fence value in the lease record and
143/// verify it before a mutation. This is an additional stale-binding check, not
144/// by itself a complete crash/fencing proof.
145pub trait WriterLease: Send + Sync {
146    fn verify_fence(&self) -> Result<(), FileError> {
147        Ok(())
148    }
149}
150
151/// A completed append range bound to the file generation actually written.
152/// The reader remains valid if the journal path is subsequently replaced.
153#[derive(Clone)]
154pub struct AppendReceipt {
155    pub reader: Arc<dyn ReadFile>,
156    pub offset: u64,
157    pub length: usize,
158}
159
160/// Physical file metadata captured on the same native handle immediately
161/// before and after a successful append.
162pub struct NativeAppendMetadata {
163    pub before: Metadata,
164    pub after: Metadata,
165}
166
167/// An optional, single-owner append capability for a journal.
168#[async_trait]
169pub trait AppendFile: Send + Sync {
170    /// Append and finish the write before acknowledging it. This is the same
171    /// visibility boundary as `FileSystem::append_file`, not a power-loss fsync.
172    async fn append(&mut self, bytes: &[u8]) -> Result<(), FileError>;
173
174    /// Append with an optional stable-generation range. Missing read permission
175    /// or receipt support must not turn a successful append into a failure.
176    async fn append_with_receipt(
177        &mut self,
178        bytes: &[u8],
179    ) -> Result<Option<AppendReceipt>, FileError> {
180        self.append(bytes).await?;
181        Ok(None)
182    }
183
184    /// Append with optional native handle metadata for a derived index.
185    async fn append_with_native_metadata(
186        &mut self,
187        bytes: &[u8],
188    ) -> Result<(Option<AppendReceipt>, Option<NativeAppendMetadata>), FileError> {
189        Ok((self.append_with_receipt(bytes).await?, None))
190    }
191}
192
193/// Read capability bound to one opened file, even if its path is replaced.
194/// Implementations serialize cursor access and return errors on short ranges.
195#[async_trait]
196pub trait ReadFile: Send + Sync {
197    async fn read_all(&self) -> Result<Vec<u8>, FileError>;
198    async fn read_range(&self, offset: u64, length: usize) -> Result<Vec<u8>, FileError>;
199
200    /// Metadata of the opened native handle, when available.
201    fn native_metadata(&self) -> Option<Metadata> {
202        None
203    }
204
205    /// Current byte length of this opened generation, when supported. This is
206    /// not a snapshot: later appends or truncation may change the length.
207    async fn byte_len(&self) -> Result<Option<u64>, FileError> {
208        Ok(None)
209    }
210}
211
212/// Mirrors TS `FileSystem`. All methods async, never panic.
213/// Backends should check cancellation at entry and during long operations.
214#[async_trait]
215pub trait FileSystem: Send + Sync {
216    /// The environment's working directory (absolute).
217    fn cwd(&self) -> &Path;
218
219    /// Resolve a host path when this backend explicitly permits native I/O.
220    /// Abstract and restricted backends do not grant this capability.
221    fn native_file_path(&self, _path: &str) -> Option<PathBuf> {
222        None
223    }
224
225    /// Resolve `path` (relative-to-cwd, `~`, `file://`, absolute) to an absolute
226    /// addressed path. Pure — no FS access, no abort. Mirrors TS `absolutePath`.
227    async fn absolute_path(
228        &self,
229        path: &str,
230        cancel: Option<&CancellationToken>,
231    ) -> Result<PathBuf, FileError>;
232
233    /// Join path components. Pure. Mirrors TS `joinPath`.
234    async fn join_path(
235        &self,
236        parts: &[&str],
237        cancel: Option<&CancellationToken>,
238    ) -> Result<PathBuf, FileError>;
239
240    async fn read_text_file(
241        &self,
242        path: &str,
243        cancel: Option<&CancellationToken>,
244    ) -> Result<String, FileError>;
245
246    /// Stream-read up to `max_lines` lines (split on `\n`; `max_lines <= 0`
247    /// → empty). Mirrors TS `readTextLines{maxLines}`.
248    async fn read_text_lines(
249        &self,
250        path: &str,
251        max_lines: Option<usize>,
252        cancel: Option<&CancellationToken>,
253    ) -> Result<Vec<String>, FileError>;
254
255    async fn read_binary_file(
256        &self,
257        path: &str,
258        cancel: Option<&CancellationToken>,
259    ) -> Result<Vec<u8>, FileError>;
260
261    /// Creates parent directories (recursive) automatically. Mirrors TS
262    /// `writeFile`.
263    async fn write_file(
264        &self,
265        path: &str,
266        content: FileContent,
267        cancel: Option<&CancellationToken>,
268    ) -> Result<(), FileError>;
269
270    /// Atomically create an absent file and write its initial contents, never
271    /// following or replacing an existing final path. The parent must already
272    /// exist; this capability does not create directories or prove durability.
273    ///
274    /// Unsupported backends fail closed rather than emulating this with an
275    /// existence check plus truncating write. Cancellation/error after creation
276    /// may leave a partial new file; never unlink or overwrite it on retry.
277    async fn write_new_file(
278        &self,
279        path: &str,
280        _content: FileContent,
281        _cancel: Option<&CancellationToken>,
282    ) -> Result<(), FileError> {
283        Err(FileError::new(
284            FileErrorCode::NotSupported,
285            "exclusive file creation is unsupported",
286        )
287        .with_path(path))
288    }
289
290    async fn append_file(
291        &self,
292        path: &str,
293        content: FileContent,
294        cancel: Option<&CancellationToken>,
295    ) -> Result<(), FileError>;
296
297    /// Optional reusable append handle for a single-owner journal. Backends
298    /// without this capability keep the existing per-call append path.
299    async fn open_append_file(
300        &self,
301        _path: &str,
302    ) -> Result<Option<Box<dyn AppendFile>>, FileError> {
303        Ok(None)
304    }
305
306    /// Try to acquire an exclusive writer lease for one addressed journal.
307    ///
308    /// `Some` is a held capability whose lifetime owns the backend lock;
309    /// `None` means this backend has no process-level lease primitive (for
310    /// example the in-memory test backend). Contention is an error, not a
311    /// successful `None`, so callers fail closed when a real backend refuses
312    /// ownership.
313    async fn try_acquire_writer_lease(
314        &self,
315        _path: &str,
316    ) -> Result<Option<Box<dyn WriterLease>>, FileError> {
317        Ok(None)
318    }
319
320    /// Flush a staged file's contents through the backend's durability boundary.
321    /// The default is a deliberate no-op for memory/Faux backends; callers must
322    /// not treat it as evidence of physical persistence.
323    async fn sync_file(
324        &self,
325        _path: &str,
326        _data_only: bool,
327        _cancel: Option<&CancellationToken>,
328    ) -> Result<(), FileError> {
329        Ok(())
330    }
331
332    /// Flush the directory metadata needed to make a completed rename durable.
333    /// The default is a deliberate no-op for backends without physical files.
334    async fn sync_directory(
335        &self,
336        _path: &str,
337        _cancel: Option<&CancellationToken>,
338    ) -> Result<(), FileError> {
339        Ok(())
340    }
341
342    /// Sync a regular journal file and its containing directory through an
343    /// explicitly supported physical persistence boundary. Unlike `sync_file`
344    /// and `sync_directory`, the compatibility default fails closed: their
345    /// no-op defaults are not evidence that a journal survived a crash.
346    ///
347    /// The caller must own the journal writer and keep the addressed file and
348    /// parent stable. This does not sync newly-created ancestor directories,
349    /// progress companions, or protect against writers bypassing ownership.
350    async fn sync_file_and_parent(
351        &self,
352        path: &str,
353        _cancel: Option<&CancellationToken>,
354    ) -> Result<(), FileError> {
355        Err(FileError::new(
356            FileErrorCode::NotSupported,
357            "physical journal synchronization is unsupported",
358        )
359        .with_path(path))
360    }
361
362    /// Optional stable-generation reader. Unsupported backends retain eager
363    /// history loading; an actual open failure must be returned, not hidden.
364    async fn open_read_file(
365        &self,
366        _path: &str,
367    ) -> Result<Option<std::sync::Arc<dyn ReadFile>>, FileError> {
368        Ok(None)
369    }
370
371    /// Cut the file at `path` back to `len` bytes, discarding a tail that a
372    /// failed append left behind. It never grows a file. Backends without it
373    /// fail, so a caller cannot take a tail for clean when it was not cut.
374    async fn truncate_file(
375        &self,
376        path: &str,
377        len: u64,
378        cancel: Option<&CancellationToken>,
379    ) -> Result<(), FileError> {
380        let _ = (len, cancel);
381        Err(FileError::new(
382            FileErrorCode::NotSupported,
383            "file truncation is unavailable",
384        )
385        .with_path(path))
386    }
387
388    async fn rename_file(
389        &self,
390        source: &str,
391        dest: &str,
392        cancel: Option<&CancellationToken>,
393    ) -> Result<(), FileError>;
394
395    /// Uses `symlink_metadata` (lstat — symlinks not followed). Mirrors TS
396    /// `fileInfo`.
397    async fn file_info(
398        &self,
399        path: &str,
400        cancel: Option<&CancellationToken>,
401    ) -> Result<FileInfo, FileError>;
402
403    async fn list_dir(
404        &self,
405        path: &str,
406        cancel: Option<&CancellationToken>,
407    ) -> Result<Vec<FileInfo>, FileError>;
408
409    /// Whether a directory contains a file or symlink whose name ends with
410    /// `suffix`. Does not follow symlinks and does not cache negative results.
411    /// Backends may avoid collecting unrelated entries' sizes/timestamps.
412    /// The default preserves compatibility with existing filesystem adapters.
413    async fn has_file_with_suffix(
414        &self,
415        path: &str,
416        suffix: &str,
417        cancel: Option<&CancellationToken>,
418    ) -> Result<bool, FileError> {
419        check_cancel_file(cancel, Some(path))?;
420        let entries = self.list_dir(path, cancel).await?;
421        check_cancel_file(cancel, Some(path))?;
422        Ok(entries
423            .iter()
424            .any(|entry| entry.kind != FileKind::Directory && entry.name.ends_with(suffix)))
425    }
426
427    /// Follows symlinks (`canonicalize`). Mirrors TS `canonicalPath`. Backends
428    /// may return `not_found` or `not_supported` for missing/unsupported paths;
429    /// callers (mutation queue) fall back to absolute path on those codes.
430    async fn canonical_path(
431        &self,
432        path: &str,
433        cancel: Option<&CancellationToken>,
434    ) -> Result<PathBuf, FileError>;
435
436    /// `false` ONLY for `not_found`; other errors propagate. Mirrors TS
437    /// `exists` (which delegates to `fileInfo`, NOT `access(F_OK)`).
438    async fn exists(
439        &self,
440        path: &str,
441        cancel: Option<&CancellationToken>,
442    ) -> Result<bool, FileError>;
443
444    /// Default `recursive=true`. Mirrors TS `createDir{recursive}`.
445    async fn create_dir(
446        &self,
447        path: &str,
448        recursive: bool,
449        cancel: Option<&CancellationToken>,
450    ) -> Result<(), FileError>;
451
452    /// Defaults `recursive=false`, `force=false`. Mirrors TS `remove`.
453    async fn remove(
454        &self,
455        path: &str,
456        recursive: bool,
457        force: bool,
458        cancel: Option<&CancellationToken>,
459    ) -> Result<(), FileError>;
460
461    /// Default prefix `"tmp-"`. Mirrors TS `createTempDir{prefix}`.
462    async fn create_temp_dir(
463        &self,
464        prefix: Option<&str>,
465        cancel: Option<&CancellationToken>,
466    ) -> Result<PathBuf, FileError>;
467
468    /// Mirrors TS `createTempFile{prefix,suffix}` (defaults empty). Note: the
469    /// TS impl creates an isolated temp **dir** per file; backends may simplify
470    /// to a single file in the OS temp dir (document any divergence).
471    async fn create_temp_file(
472        &self,
473        prefix: &str,
474        suffix: &str,
475        cancel: Option<&CancellationToken>,
476    ) -> Result<PathBuf, FileError>;
477
478    /// Best-effort, never returns `Err`. Mirrors TS `cleanup` (kills tracked
479    /// child processes, etc.).
480    async fn cleanup(&self);
481}
482
483/// Mirrors TS `Shell`.
484#[async_trait]
485pub trait Shell: Send + Sync {
486    /// Execute `command` in a bash shell. The TS env resolves a bash binary
487    /// (git-bash on Windows, `/bin/bash` on POSIX, `/bin/sh` fallback on POSIX).
488    /// There is NO cmd.exe fallback on Windows — failure to find bash is
489    /// `ExecutionError::ShellUnavailable`.
490    async fn exec<'a>(
491        &'a self,
492        command: &str,
493        options: ShellExecOptions<'a>,
494    ) -> Result<ShellOutput, ExecutionError>;
495
496    /// Best-effort, never returns `Err`. Mirrors TS `Shell.cleanup`.
497    async fn cleanup(&self);
498}
499
500/// Mirrors TS `ExecutionEnv extends FileSystem, Shell`. A marker combining both
501/// capabilities — tools receive `Arc<dyn ExecutionEnv>` (or a concrete env) and
502/// use `FileSystem` + `Shell` methods interchangeably.
503#[async_trait]
504pub trait ExecutionEnv: FileSystem + Shell {}
505
506/// Check `cancel` at a method entry point, returning `FileError::aborted()`
507/// when set. Mirrors the TS `abortResult<T>(signal, path?)` helper used at the
508/// top of every `FileSystem` method.
509pub fn check_cancel_file(
510    cancel: Option<&CancellationToken>,
511    path: Option<&str>,
512) -> Result<(), FileError> {
513    if let Some(t) = cancel {
514        if t.is_cancelled() {
515            let mut err = FileError::aborted();
516            if let Some(p) = path {
517                err = err.with_path(p);
518            }
519            return Err(err);
520        }
521    }
522    Ok(())
523}
524
525/// Same as [`check_cancel_file`] but for `Shell`-side (returns
526/// `ExecutionError::aborted()`).
527pub fn check_cancel_exec(cancel: Option<&CancellationToken>) -> Result<(), ExecutionError> {
528    if let Some(t) = cancel {
529        if t.is_cancelled() {
530            return Err(ExecutionError::aborted());
531        }
532    }
533    Ok(())
534}
535
536#[cfg(test)]
537mod capability_tests {
538    use super::*;
539
540    // Deliberately implement only the original required methods. These doubles
541    // guard source compatibility as well as dispatch through the trait object.
542    #[derive(Default)]
543    struct LegacyAppender(Vec<u8>);
544
545    #[async_trait]
546    impl AppendFile for LegacyAppender {
547        async fn append(&mut self, bytes: &[u8]) -> Result<(), FileError> {
548            self.0.extend_from_slice(bytes);
549            Ok(())
550        }
551    }
552
553    struct LegacyReader;
554
555    #[async_trait]
556    impl ReadFile for LegacyReader {
557        async fn read_all(&self) -> Result<Vec<u8>, FileError> {
558            Ok(b"legacy".to_vec())
559        }
560
561        async fn read_range(&self, _offset: u64, _length: usize) -> Result<Vec<u8>, FileError> {
562            Err(FileError::new(FileErrorCode::NotSupported, "legacy reader"))
563        }
564    }
565
566    #[tokio::test]
567    async fn legacy_capabilities_keep_their_default_behavior() {
568        let mut writer = LegacyAppender::default();
569        let appender: &mut dyn AppendFile = &mut writer;
570        assert!(appender
571            .append_with_receipt(b"frame\n")
572            .await
573            .unwrap()
574            .is_none());
575        assert_eq!(writer.0, b"frame\n");
576        let reader: Arc<dyn ReadFile> = Arc::new(LegacyReader);
577        assert_eq!(reader.byte_len().await.unwrap(), None);
578        assert_eq!(reader.read_all().await.unwrap(), b"legacy");
579    }
580
581    #[tokio::test]
582    async fn default_receipt_method_preserves_append_errors() {
583        struct FailingAppender;
584        #[async_trait]
585        impl AppendFile for FailingAppender {
586            async fn append(&mut self, _bytes: &[u8]) -> Result<(), FileError> {
587                Err(FileError::new(FileErrorCode::Unknown, "append failed"))
588            }
589        }
590        assert!(FailingAppender.append_with_receipt(b"frame").await.is_err());
591    }
592}