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/// File information describes the addressed entry. Native content reads and
26/// writes follow symlinks, and `canonical_path` resolves their targets.
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 /// Read complete UTF-8 text if it fits in `max_bytes`. A larger file
247 /// yields `None`. The compatibility default checks the reported size and
248 /// then the returned text. Native backends can cap the underlying read.
249 async fn read_text_file_bounded(
250 &self,
251 path: &str,
252 max_bytes: usize,
253 cancel: Option<&CancellationToken>,
254 ) -> Result<Option<String>, FileError> {
255 check_cancel_file(cancel, Some(path))?;
256 if self.file_info(path, cancel).await?.size > max_bytes as u64 {
257 return Ok(None);
258 }
259 let text = self.read_text_file(path, cancel).await?;
260 Ok((text.len() <= max_bytes).then_some(text))
261 }
262
263 /// Stream-read up to `max_lines` lines (split on `\n`; `max_lines <= 0`
264 /// → empty). Mirrors TS `readTextLines{maxLines}`.
265 async fn read_text_lines(
266 &self,
267 path: &str,
268 max_lines: Option<usize>,
269 cancel: Option<&CancellationToken>,
270 ) -> Result<Vec<String>, FileError>;
271
272 async fn read_binary_file(
273 &self,
274 path: &str,
275 cancel: Option<&CancellationToken>,
276 ) -> Result<Vec<u8>, FileError>;
277
278 /// Creates parent directories (recursive) automatically. Mirrors TS
279 /// `writeFile`.
280 async fn write_file(
281 &self,
282 path: &str,
283 content: FileContent,
284 cancel: Option<&CancellationToken>,
285 ) -> Result<(), FileError>;
286
287 /// Atomically create an absent file and write its initial contents, never
288 /// following or replacing an existing final path. The parent must already
289 /// exist; this capability does not create directories or prove durability.
290 ///
291 /// Unsupported backends fail closed rather than emulating this with an
292 /// existence check plus truncating write. Cancellation/error after creation
293 /// may leave a partial new file; never unlink or overwrite it on retry.
294 async fn write_new_file(
295 &self,
296 path: &str,
297 _content: FileContent,
298 _cancel: Option<&CancellationToken>,
299 ) -> Result<(), FileError> {
300 Err(FileError::new(
301 FileErrorCode::NotSupported,
302 "exclusive file creation is unsupported",
303 )
304 .with_path(path))
305 }
306
307 async fn append_file(
308 &self,
309 path: &str,
310 content: FileContent,
311 cancel: Option<&CancellationToken>,
312 ) -> Result<(), FileError>;
313
314 /// Optional reusable append handle for a single-owner journal. Backends
315 /// without this capability keep the existing per-call append path.
316 async fn open_append_file(
317 &self,
318 _path: &str,
319 ) -> Result<Option<Box<dyn AppendFile>>, FileError> {
320 Ok(None)
321 }
322
323 /// Try to acquire an exclusive writer lease for one addressed journal.
324 ///
325 /// `Some` is a held capability whose lifetime owns the backend lock;
326 /// `None` means this backend has no process-level lease primitive (for
327 /// example the in-memory test backend). Contention is an error, not a
328 /// successful `None`, so callers fail closed when a real backend refuses
329 /// ownership.
330 async fn try_acquire_writer_lease(
331 &self,
332 _path: &str,
333 ) -> Result<Option<Box<dyn WriterLease>>, FileError> {
334 Ok(None)
335 }
336
337 /// Flush a staged file's contents through the backend's durability boundary.
338 /// The default is a deliberate no-op for memory/Faux backends; callers must
339 /// not treat it as evidence of physical persistence.
340 async fn sync_file(
341 &self,
342 _path: &str,
343 _data_only: bool,
344 _cancel: Option<&CancellationToken>,
345 ) -> Result<(), FileError> {
346 Ok(())
347 }
348
349 /// Flush the directory metadata needed to make a completed rename durable.
350 /// The default is a deliberate no-op for backends without physical files.
351 async fn sync_directory(
352 &self,
353 _path: &str,
354 _cancel: Option<&CancellationToken>,
355 ) -> Result<(), FileError> {
356 Ok(())
357 }
358
359 /// Sync a regular journal file and its containing directory through an
360 /// explicitly supported physical persistence boundary. Unlike `sync_file`
361 /// and `sync_directory`, the compatibility default fails closed: their
362 /// no-op defaults are not evidence that a journal survived a crash.
363 ///
364 /// The caller must own the journal writer and keep the addressed file and
365 /// parent stable. This does not sync newly-created ancestor directories,
366 /// progress companions, or protect against writers bypassing ownership.
367 async fn sync_file_and_parent(
368 &self,
369 path: &str,
370 _cancel: Option<&CancellationToken>,
371 ) -> Result<(), FileError> {
372 Err(FileError::new(
373 FileErrorCode::NotSupported,
374 "physical journal synchronization is unsupported",
375 )
376 .with_path(path))
377 }
378
379 /// Optional stable-generation reader. Unsupported backends retain eager
380 /// history loading; an actual open failure must be returned, not hidden.
381 async fn open_read_file(
382 &self,
383 _path: &str,
384 ) -> Result<Option<std::sync::Arc<dyn ReadFile>>, FileError> {
385 Ok(None)
386 }
387
388 /// Cut the file at `path` back to `len` bytes, discarding a tail that a
389 /// failed append left behind. It never grows a file. Backends without it
390 /// fail, so a caller cannot take a tail for clean when it was not cut.
391 async fn truncate_file(
392 &self,
393 path: &str,
394 len: u64,
395 cancel: Option<&CancellationToken>,
396 ) -> Result<(), FileError> {
397 let _ = (len, cancel);
398 Err(FileError::new(
399 FileErrorCode::NotSupported,
400 "file truncation is unavailable",
401 )
402 .with_path(path))
403 }
404
405 async fn rename_file(
406 &self,
407 source: &str,
408 dest: &str,
409 cancel: Option<&CancellationToken>,
410 ) -> Result<(), FileError>;
411
412 /// Uses `symlink_metadata` (lstat — symlinks not followed). Mirrors TS
413 /// `fileInfo`.
414 async fn file_info(
415 &self,
416 path: &str,
417 cancel: Option<&CancellationToken>,
418 ) -> Result<FileInfo, FileError>;
419
420 async fn list_dir(
421 &self,
422 path: &str,
423 cancel: Option<&CancellationToken>,
424 ) -> Result<Vec<FileInfo>, FileError>;
425
426 /// Whether a directory contains a file or symlink whose name ends with
427 /// `suffix`. Does not follow symlinks and does not cache negative results.
428 /// Backends may avoid collecting unrelated entries' sizes/timestamps.
429 /// The default preserves compatibility with existing filesystem adapters.
430 async fn has_file_with_suffix(
431 &self,
432 path: &str,
433 suffix: &str,
434 cancel: Option<&CancellationToken>,
435 ) -> Result<bool, FileError> {
436 check_cancel_file(cancel, Some(path))?;
437 let entries = self.list_dir(path, cancel).await?;
438 check_cancel_file(cancel, Some(path))?;
439 Ok(entries
440 .iter()
441 .any(|entry| entry.kind != FileKind::Directory && entry.name.ends_with(suffix)))
442 }
443
444 /// Follows symlinks (`canonicalize`). Mirrors TS `canonicalPath`. Backends
445 /// may return `not_found` for a missing path or `not_supported` if they
446 /// cannot resolve canonical paths.
447 async fn canonical_path(
448 &self,
449 path: &str,
450 cancel: Option<&CancellationToken>,
451 ) -> Result<PathBuf, FileError>;
452
453 /// `false` ONLY for `not_found`; other errors propagate. Mirrors TS
454 /// `exists` (which delegates to `fileInfo`, NOT `access(F_OK)`).
455 async fn exists(
456 &self,
457 path: &str,
458 cancel: Option<&CancellationToken>,
459 ) -> Result<bool, FileError>;
460
461 /// Default `recursive=true`. Mirrors TS `createDir{recursive}`.
462 async fn create_dir(
463 &self,
464 path: &str,
465 recursive: bool,
466 cancel: Option<&CancellationToken>,
467 ) -> Result<(), FileError>;
468
469 /// Defaults `recursive=false`, `force=false`. Mirrors TS `remove`.
470 async fn remove(
471 &self,
472 path: &str,
473 recursive: bool,
474 force: bool,
475 cancel: Option<&CancellationToken>,
476 ) -> Result<(), FileError>;
477
478 /// Default prefix `"tmp-"`. Mirrors TS `createTempDir{prefix}`.
479 async fn create_temp_dir(
480 &self,
481 prefix: Option<&str>,
482 cancel: Option<&CancellationToken>,
483 ) -> Result<PathBuf, FileError>;
484
485 /// Mirrors TS `createTempFile{prefix,suffix}` (defaults empty). Note: the
486 /// TS impl creates an isolated temp **dir** per file; backends may simplify
487 /// to a single file in the OS temp dir (document any divergence).
488 async fn create_temp_file(
489 &self,
490 prefix: &str,
491 suffix: &str,
492 cancel: Option<&CancellationToken>,
493 ) -> Result<PathBuf, FileError>;
494
495 /// Best-effort, never returns `Err`. Mirrors TS `cleanup` (kills tracked
496 /// child processes, etc.).
497 async fn cleanup(&self);
498}
499
500/// Mirrors TS `Shell`.
501#[async_trait]
502pub trait Shell: Send + Sync {
503 /// Execute `command` in a bash shell. The TS env resolves a bash binary
504 /// (git-bash on Windows, `/bin/bash` on POSIX, `/bin/sh` fallback on POSIX).
505 /// There is NO cmd.exe fallback on Windows — failure to find bash is
506 /// `ExecutionError::ShellUnavailable`.
507 async fn exec<'a>(
508 &'a self,
509 command: &str,
510 options: ShellExecOptions<'a>,
511 ) -> Result<ShellOutput, ExecutionError>;
512
513 /// Stream merged stdout and stderr in delivery order and return the exit
514 /// code. Native backends can feed the bounded channel directly without
515 /// accumulating the output in `ShellOutput`. The default adapts existing
516 /// synchronous callbacks so custom backends can keep implementing `exec`.
517 async fn exec_streamed<'a>(
518 &'a self,
519 command: &str,
520 mut options: ShellExecOptions<'a>,
521 output: tokio::sync::mpsc::Sender<String>,
522 ) -> Result<i32, ExecutionError> {
523 let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
524 for callback in [&mut options.on_stdout, &mut options.on_stderr] {
525 let sender = sender.clone();
526 let mut previous = callback.take();
527 *callback = Some(Box::new(move |text| {
528 if let Some(callback) = previous.as_mut() {
529 callback(text);
530 }
531 let _ = sender.send(text.to_owned());
532 }));
533 }
534 drop(sender);
535
536 let forward = async move {
537 while let Some(text) = receiver.recv().await {
538 if output.send(text).await.is_err() {
539 break;
540 }
541 }
542 };
543 let (result, ()) = tokio::join!(self.exec(command, options), forward);
544 result.map(|output| output.exit_code)
545 }
546
547 /// Best-effort, never returns `Err`. Mirrors TS `Shell.cleanup`.
548 async fn cleanup(&self);
549}
550
551/// Mirrors TS `ExecutionEnv extends FileSystem, Shell`. A marker combining both
552/// capabilities — tools receive `Arc<dyn ExecutionEnv>` (or a concrete env) and
553/// use `FileSystem` + `Shell` methods interchangeably.
554#[async_trait]
555pub trait ExecutionEnv: FileSystem + Shell {}
556
557/// Check `cancel` at a method entry point, returning `FileError::aborted()`
558/// when set. Mirrors the TS `abortResult<T>(signal, path?)` helper used at the
559/// top of every `FileSystem` method.
560pub fn check_cancel_file(
561 cancel: Option<&CancellationToken>,
562 path: Option<&str>,
563) -> Result<(), FileError> {
564 if let Some(t) = cancel {
565 if t.is_cancelled() {
566 let mut err = FileError::aborted();
567 if let Some(p) = path {
568 err = err.with_path(p);
569 }
570 return Err(err);
571 }
572 }
573 Ok(())
574}
575
576/// Same as [`check_cancel_file`] but for `Shell`-side (returns
577/// `ExecutionError::aborted()`).
578pub fn check_cancel_exec(cancel: Option<&CancellationToken>) -> Result<(), ExecutionError> {
579 if let Some(t) = cancel {
580 if t.is_cancelled() {
581 return Err(ExecutionError::aborted());
582 }
583 }
584 Ok(())
585}
586
587#[cfg(test)]
588mod capability_tests {
589 use super::*;
590
591 // Deliberately implement only the original required methods. These doubles
592 // guard source compatibility as well as dispatch through the trait object.
593 #[derive(Default)]
594 struct LegacyAppender(Vec<u8>);
595
596 #[async_trait]
597 impl AppendFile for LegacyAppender {
598 async fn append(&mut self, bytes: &[u8]) -> Result<(), FileError> {
599 self.0.extend_from_slice(bytes);
600 Ok(())
601 }
602 }
603
604 struct LegacyReader;
605
606 #[async_trait]
607 impl ReadFile for LegacyReader {
608 async fn read_all(&self) -> Result<Vec<u8>, FileError> {
609 Ok(b"legacy".to_vec())
610 }
611
612 async fn read_range(&self, _offset: u64, _length: usize) -> Result<Vec<u8>, FileError> {
613 Err(FileError::new(FileErrorCode::NotSupported, "legacy reader"))
614 }
615 }
616
617 #[tokio::test]
618 async fn legacy_capabilities_keep_their_default_behavior() {
619 let mut writer = LegacyAppender::default();
620 let appender: &mut dyn AppendFile = &mut writer;
621 assert!(appender
622 .append_with_receipt(b"frame\n")
623 .await
624 .unwrap()
625 .is_none());
626 assert_eq!(writer.0, b"frame\n");
627 let reader: Arc<dyn ReadFile> = Arc::new(LegacyReader);
628 assert_eq!(reader.byte_len().await.unwrap(), None);
629 assert_eq!(reader.read_all().await.unwrap(), b"legacy");
630 }
631
632 #[tokio::test]
633 async fn default_receipt_method_preserves_append_errors() {
634 struct FailingAppender;
635 #[async_trait]
636 impl AppendFile for FailingAppender {
637 async fn append(&mut self, _bytes: &[u8]) -> Result<(), FileError> {
638 Err(FileError::new(FileErrorCode::Unknown, "append failed"))
639 }
640 }
641 assert!(FailingAppender.append_with_receipt(b"frame").await.is_err());
642 }
643}