Skip to main content

ralph_workflow/
workspace.rs

1//! Workspace filesystem abstraction for explicit path resolution.
2//!
3//! This module provides the [`Workspace`] trait and implementations that eliminate
4//! CWD dependencies by making all path operations explicit relative to the repository root.
5//!
6//! # Problem
7//!
8//! The codebase previously relied on `std::env::set_current_dir()` to set the
9//! process CWD to the repository root, then used relative paths (`.agent/`,
10//! `PROMPT.md`, etc.) throughout. This caused:
11//!
12//! - Test flakiness when tests ran in parallel (CWD is process-global)
13//! - Background thread bugs when CWD changed after thread started
14//! - Poor testability without complex CWD manipulation
15//!
16//! # Solution
17//!
18//! The [`Workspace`] trait defines the interface for file operations, with two implementations:
19//!
20//! - [`WorkspaceFs`] - Production implementation using the real filesystem
21//! - `MemoryWorkspace` - Test implementation with in-memory storage (available with `test-utils` feature)
22//!
23//! # Well-Known Paths
24//!
25//! This module defines constants for all Ralph artifact paths:
26//!
27//! - [`AGENT_DIR`] - `.agent/` directory
28//! - [`PLAN_MD`] - `.agent/PLAN.md`
29//! - [`ISSUES_MD`] - `.agent/ISSUES.md`
30//! - [`PROMPT_MD`] - `PROMPT.md` (repository root)
31//! - [`CHECKPOINT_JSON`] - `.agent/checkpoint.json`
32//!
33//! The [`Workspace`] trait provides convenience methods for these paths (e.g., [`Workspace::plan_md`]).
34//!
35//! # Production Example
36//!
37//! ```ignore
38//! use ralph_workflow::workspace::WorkspaceFs;
39//! use std::path::PathBuf;
40//!
41//! let ws = WorkspaceFs::new(PathBuf::from("/path/to/repo"));
42//!
43//! // Get paths to well-known files
44//! let plan = ws.plan_md();  // /path/to/repo/.agent/PLAN.md
45//! let prompt = ws.prompt_md();  // /path/to/repo/PROMPT.md
46//!
47//! // Perform file operations
48//! ws.write(Path::new(".agent/test.txt"), "content")?;
49//! let content = ws.read(Path::new(".agent/test.txt"))?;
50//! ```
51//!
52//! # Testing with MemoryWorkspace
53//!
54//! The `test-utils` feature enables `MemoryWorkspace` for integration tests:
55//!
56//! ```ignore
57//! use ralph_workflow::workspace::{MemoryWorkspace, Workspace};
58//! use std::path::Path;
59//!
60//! // Create a test workspace with pre-populated files
61//! let ws = MemoryWorkspace::new_test()
62//!     .with_file("PROMPT.md", "# Task: Add logging")
63//!     .with_file(".agent/PLAN.md", "1. Add log statements");
64//!
65//! // Verify file operations
66//! assert!(ws.exists(Path::new("PROMPT.md")));
67//! assert_eq!(ws.read(Path::new("PROMPT.md"))?, "# Task: Add logging");
68//!
69//! // Write and verify
70//! ws.write(Path::new(".agent/output.txt"), "result")?;
71//! assert!(ws.was_written(".agent/output.txt"));
72//! ```
73//!
74//! # See Also
75//!
76//! - [`crate::executor::ProcessExecutor`] - Similar abstraction for process execution
77
78// ============================================================================
79// Well-known path constants
80// ============================================================================
81
82/// The `.agent` directory where Ralph stores all artifacts.
83pub const AGENT_DIR: &str = ".agent";
84
85/// The `.agent/tmp` directory for temporary files.
86pub const AGENT_TMP: &str = ".agent/tmp";
87
88// AGENT_LOGS constant removed - use RunLogContext for per-run log directories.
89
90/// Path to the implementation plan file.
91pub const PLAN_MD: &str = ".agent/PLAN.md";
92
93/// Path to the issues file from code review.
94pub const ISSUES_MD: &str = ".agent/ISSUES.md";
95
96/// Path to the status file.
97pub const STATUS_MD: &str = ".agent/STATUS.md";
98
99/// Path to the notes file.
100pub const NOTES_MD: &str = ".agent/NOTES.md";
101
102/// Path to the commit message file.
103pub const COMMIT_MESSAGE_TXT: &str = ".agent/commit-message.txt";
104
105/// Path to the checkpoint file for resume support.
106pub const CHECKPOINT_JSON: &str = ".agent/checkpoint.json";
107
108/// Path to the start commit tracking file.
109pub const START_COMMIT: &str = ".agent/start_commit";
110
111/// Path to the review baseline tracking file.
112pub const REVIEW_BASELINE_TXT: &str = ".agent/review_baseline.txt";
113
114/// Path to the prompt file in repository root.
115pub const PROMPT_MD: &str = "PROMPT.md";
116
117/// Path to the prompt backup file.
118pub const PROMPT_BACKUP: &str = ".agent/PROMPT.md.backup";
119
120/// Path to the agent config file.
121pub const AGENT_CONFIG_TOML: &str = ".agent/config.toml";
122
123/// Path to the agents registry file.
124pub const AGENTS_TOML: &str = ".agent/agents.toml";
125
126// PIPELINE_LOG constant removed - use RunLogContext::pipeline_log() for per-run log paths.
127
128use std::fs;
129use std::io;
130use std::path::{Path, PathBuf};
131
132// ============================================================================
133// DirEntry - abstraction for directory entries
134// ============================================================================
135
136/// A directory entry returned by `Workspace::read_dir`.
137///
138/// This abstracts `std::fs::DirEntry` to allow in-memory implementations.
139#[derive(Debug, Clone)]
140pub struct DirEntry {
141    /// The path of this entry (relative to workspace root).
142    path: PathBuf,
143    /// Whether this entry is a file.
144    is_file: bool,
145    /// Whether this entry is a directory.
146    is_dir: bool,
147    /// Optional modification time (for sorting by recency).
148    modified: Option<std::time::SystemTime>,
149}
150
151impl DirEntry {
152    /// Create a new directory entry.
153    pub fn new(path: PathBuf, is_file: bool, is_dir: bool) -> Self {
154        Self {
155            path,
156            is_file,
157            is_dir,
158            modified: None,
159        }
160    }
161
162    /// Create a new directory entry with modification time.
163    pub fn with_modified(
164        path: PathBuf,
165        is_file: bool,
166        is_dir: bool,
167        modified: std::time::SystemTime,
168    ) -> Self {
169        Self {
170            path,
171            is_file,
172            is_dir,
173            modified: Some(modified),
174        }
175    }
176
177    /// Get the path of this entry.
178    pub fn path(&self) -> &Path {
179        &self.path
180    }
181
182    /// Check if this entry is a file.
183    pub fn is_file(&self) -> bool {
184        self.is_file
185    }
186
187    /// Check if this entry is a directory.
188    pub fn is_dir(&self) -> bool {
189        self.is_dir
190    }
191
192    /// Get the file name of this entry.
193    pub fn file_name(&self) -> Option<&std::ffi::OsStr> {
194        self.path.file_name()
195    }
196
197    /// Get the modification time of this entry, if available.
198    pub fn modified(&self) -> Option<std::time::SystemTime> {
199        self.modified
200    }
201}
202
203// ============================================================================
204// Workspace Trait
205// ============================================================================
206
207/// Trait defining the workspace filesystem interface.
208///
209/// This trait abstracts file operations relative to a repository root, allowing
210/// for both real filesystem access (production) and in-memory storage (testing).
211pub trait Workspace: Send + Sync {
212    /// Get the repository root path.
213    fn root(&self) -> &Path;
214
215    // =========================================================================
216    // File operations
217    // =========================================================================
218
219    /// Read a file relative to the repository root.
220    fn read(&self, relative: &Path) -> io::Result<String>;
221
222    /// Read a file as bytes relative to the repository root.
223    fn read_bytes(&self, relative: &Path) -> io::Result<Vec<u8>>;
224
225    /// Write content to a file relative to the repository root.
226    /// Creates parent directories if they don't exist.
227    fn write(&self, relative: &Path, content: &str) -> io::Result<()>;
228
229    /// Write bytes to a file relative to the repository root.
230    /// Creates parent directories if they don't exist.
231    fn write_bytes(&self, relative: &Path, content: &[u8]) -> io::Result<()>;
232
233    /// Append bytes to a file relative to the repository root.
234    /// Creates the file if it doesn't exist. Creates parent directories if needed.
235    fn append_bytes(&self, relative: &Path, content: &[u8]) -> io::Result<()>;
236
237    /// Check if a path exists relative to the repository root.
238    fn exists(&self, relative: &Path) -> bool;
239
240    /// Check if a path is a file relative to the repository root.
241    fn is_file(&self, relative: &Path) -> bool;
242
243    /// Check if a path is a directory relative to the repository root.
244    fn is_dir(&self, relative: &Path) -> bool;
245
246    /// Remove a file relative to the repository root.
247    fn remove(&self, relative: &Path) -> io::Result<()>;
248
249    /// Remove a file if it exists, silently succeeding if it doesn't.
250    fn remove_if_exists(&self, relative: &Path) -> io::Result<()>;
251
252    /// Remove a directory and all its contents relative to the repository root.
253    ///
254    /// Similar to `std::fs::remove_dir_all`, this removes a directory and everything inside it.
255    /// Returns an error if the directory doesn't exist.
256    fn remove_dir_all(&self, relative: &Path) -> io::Result<()>;
257
258    /// Remove a directory and all its contents if it exists, silently succeeding if it doesn't.
259    fn remove_dir_all_if_exists(&self, relative: &Path) -> io::Result<()>;
260
261    /// Create a directory and all parent directories relative to the repository root.
262    fn create_dir_all(&self, relative: &Path) -> io::Result<()>;
263
264    /// List entries in a directory relative to the repository root.
265    ///
266    /// Returns a vector of `DirEntry`-like information for each entry.
267    /// For production, this wraps `std::fs::read_dir`.
268    /// For testing, this returns entries from the in-memory filesystem.
269    fn read_dir(&self, relative: &Path) -> io::Result<Vec<DirEntry>>;
270
271    /// Rename/move a file from one path to another relative to the repository root.
272    ///
273    /// This is used for backup rotation where files are moved to new names.
274    /// Returns an error if the source file doesn't exist.
275    fn rename(&self, from: &Path, to: &Path) -> io::Result<()>;
276
277    /// Write content to a file atomically using temp file + rename pattern.
278    ///
279    /// This ensures the file is either fully written or not written at all,
280    /// preventing partial writes or corruption from crashes/interruptions.
281    ///
282    /// # Implementation details
283    ///
284    /// - `WorkspaceFs`: Uses `tempfile::NamedTempFile` in the same directory,
285    ///   writes content, syncs to disk, then atomically renames to target.
286    ///   On Unix, temp file has mode 0600 for security.
287    /// - `MemoryWorkspace`: Just calls `write()` since in-memory operations
288    ///   are inherently atomic (no partial state possible).
289    ///
290    /// # When to use
291    ///
292    /// Use `write_atomic()` for critical files where corruption would be problematic:
293    /// - XML outputs (issues.xml, plan.xml, commit_message.xml)
294    /// - Agent artifacts (PLAN.md, commit-message.txt)
295    /// - Any file that must not have partial content
296    ///
297    /// Use regular `write()` for:
298    /// - Log files (append-only, partial is acceptable)
299    /// - Temporary/debug files
300    /// - Files where performance matters more than atomicity
301    fn write_atomic(&self, relative: &Path, content: &str) -> io::Result<()>;
302
303    /// Set a file to read-only permissions.
304    ///
305    /// This is a best-effort operation for protecting files like PROMPT.md backups.
306    /// On Unix, sets permissions to 0o444.
307    /// On Windows, sets the readonly flag.
308    /// In-memory implementations may no-op since permissions aren't relevant for testing.
309    ///
310    /// Returns Ok(()) on success or if the file doesn't exist (nothing to protect).
311    /// Returns Err only if the file exists but permissions cannot be changed.
312    fn set_readonly(&self, relative: &Path) -> io::Result<()>;
313
314    /// Set a file to writable permissions.
315    ///
316    /// Reverses the effect of `set_readonly`.
317    /// On Unix, sets permissions to 0o644.
318    /// On Windows, clears the readonly flag.
319    /// In-memory implementations may no-op since permissions aren't relevant for testing.
320    ///
321    /// Returns Ok(()) on success or if the file doesn't exist.
322    fn set_writable(&self, relative: &Path) -> io::Result<()>;
323
324    // =========================================================================
325    // Path resolution (default implementations)
326    // =========================================================================
327
328    /// Resolve a relative path to an absolute path.
329    fn absolute(&self, relative: &Path) -> PathBuf {
330        self.root().join(relative)
331    }
332
333    /// Resolve a relative path to an absolute path as a string.
334    fn absolute_str(&self, relative: &str) -> String {
335        self.root().join(relative).display().to_string()
336    }
337
338    // =========================================================================
339    // Well-known paths (default implementations)
340    // =========================================================================
341
342    /// Path to the `.agent` directory.
343    fn agent_dir(&self) -> PathBuf {
344        self.root().join(AGENT_DIR)
345    }
346
347    /// Path to the `.agent/tmp` directory.
348    fn agent_tmp(&self) -> PathBuf {
349        self.root().join(AGENT_TMP)
350    }
351
352    /// Path to `.agent/PLAN.md`.
353    fn plan_md(&self) -> PathBuf {
354        self.root().join(PLAN_MD)
355    }
356
357    /// Path to `.agent/ISSUES.md`.
358    fn issues_md(&self) -> PathBuf {
359        self.root().join(ISSUES_MD)
360    }
361
362    /// Path to `.agent/STATUS.md`.
363    fn status_md(&self) -> PathBuf {
364        self.root().join(STATUS_MD)
365    }
366
367    /// Path to `.agent/NOTES.md`.
368    fn notes_md(&self) -> PathBuf {
369        self.root().join(NOTES_MD)
370    }
371
372    /// Path to `.agent/commit-message.txt`.
373    fn commit_message(&self) -> PathBuf {
374        self.root().join(COMMIT_MESSAGE_TXT)
375    }
376
377    /// Path to `.agent/checkpoint.json`.
378    fn checkpoint(&self) -> PathBuf {
379        self.root().join(CHECKPOINT_JSON)
380    }
381
382    /// Path to `.agent/start_commit`.
383    fn start_commit(&self) -> PathBuf {
384        self.root().join(START_COMMIT)
385    }
386
387    /// Path to `.agent/review_baseline.txt`.
388    fn review_baseline(&self) -> PathBuf {
389        self.root().join(REVIEW_BASELINE_TXT)
390    }
391
392    /// Path to `PROMPT.md` in the repository root.
393    fn prompt_md(&self) -> PathBuf {
394        self.root().join(PROMPT_MD)
395    }
396
397    /// Path to `.agent/PROMPT.md.backup`.
398    fn prompt_backup(&self) -> PathBuf {
399        self.root().join(PROMPT_BACKUP)
400    }
401
402    /// Path to `.agent/config.toml`.
403    fn agent_config(&self) -> PathBuf {
404        self.root().join(AGENT_CONFIG_TOML)
405    }
406
407    /// Path to `.agent/agents.toml`.
408    fn agents_toml(&self) -> PathBuf {
409        self.root().join(AGENTS_TOML)
410    }
411
412    /// Path to an XSD schema file in `.agent/tmp/`.
413    fn xsd_path(&self, name: &str) -> PathBuf {
414        self.root().join(format!(".agent/tmp/{}.xsd", name))
415    }
416
417    /// Path to an XML file in `.agent/tmp/`.
418    fn xml_path(&self, name: &str) -> PathBuf {
419        self.root().join(format!(".agent/tmp/{}.xml", name))
420    }
421
422    /// Path to a log file in `.agent/logs/`.
423    fn log_path(&self, name: &str) -> PathBuf {
424        self.root().join(format!(".agent/logs/{}", name))
425    }
426}
427
428// ============================================================================
429// Production Implementation: WorkspaceFs
430// ============================================================================
431
432include!("workspace/workspace_fs.rs");
433
434// ============================================================================
435// Test Implementation: MemoryWorkspace
436// ============================================================================
437
438#[cfg(any(test, feature = "test-utils"))]
439pub mod memory_workspace;
440
441#[cfg(any(test, feature = "test-utils"))]
442pub use memory_workspace::MemoryWorkspace;
443
444// ============================================================================
445// Tests
446// ============================================================================
447
448#[cfg(test)]
449mod tests {
450    use super::*;
451
452    include!("workspace/tests.rs");
453}