Skip to main content

trusty_code/tools/fs/
mod.rs

1//! Filesystem tools for the tcode tool registry.
2//!
3//! Why: AI coding loops (e.g. the ai-coding-bake-off L1 agentic loop) need the
4//! agent to create, read, and patch files on the host filesystem. Providing typed
5//! `ToolExecutor` implementations instead of raw shell-exec keeps error handling
6//! structured, scoping to a working directory enforced, and path traversal
7//! impossible.
8//! What: `ToolExecutor` impls for the engineer's filesystem surface —
9//! `ReadFileTool`, `WriteFileTool`, `EditTool`, plus the batch-write and
10//! exploration tools `WriteFilesTool` (#2681), `GlobTool`, `GrepTool`, and
11//! `ListDirTool` (#1027) — each with an OpenAI-function-call schema and
12//! registration helpers. `EditTool` (#2068) supports three edit wire formats —
13//! SEARCH/REPLACE, unified-diff, and whole-file — selected per-model via
14//! `edit_format`. The exploration tools give the engineer native file discovery
15//! so it no longer shells out to `find`/`grep`/`ls` (the dominant bake-off
16//! agent-turn sink). Errors use `thiserror` for clean structured error types.
17//! Test: `read.rs`, `write.rs`, `write_files.rs`, `glob.rs`, `grep.rs`,
18//! `list_dir.rs`, and `edit.rs` each carry tempdir-based unit tests;
19//! `edit_format` carries its own matrix/application tests; `registry_tests`
20//! verifies the tools appear in `schemas()` and dispatch through
21//! `dispatch_gated`.
22
23pub mod edit;
24pub mod edit_format;
25pub mod glob;
26pub mod grep;
27pub mod list_dir;
28pub mod read;
29pub mod write;
30pub mod write_files;
31
32pub use edit::EditTool;
33pub use glob::GlobTool;
34pub use grep::GrepTool;
35pub use list_dir::ListDirTool;
36pub use read::ReadFileTool;
37pub use write::WriteFileTool;
38pub use write_files::{WRITE_FILES_TOOL_NAME, WriteFilesTool};
39
40use std::path::{Path, PathBuf};
41
42use thiserror::Error;
43
44/// Errors produced by filesystem tools.
45///
46/// Why: A single error type for all three FS tools makes calling code concise
47/// and lets `ToolResult::err` convert cleanly via `Display`.
48/// What: Variants cover all failure modes: traversal, missing file, size cap,
49/// IO, and unique-match violations.
50/// Test: Each variant is exercised by at least one unit test in the tool modules.
51#[derive(Debug, Error)]
52pub enum FsError {
53    /// The requested path would escape the permitted working directory.
54    #[error("path escapes working directory: {0}")]
55    PathTraversal(PathBuf),
56
57    /// The file or directory was not found.
58    #[error("not found: {0}")]
59    NotFound(PathBuf),
60
61    /// `list_dir` was pointed at a path that is not a directory.
62    #[error("not a directory: {0}")]
63    NotADirectory(PathBuf),
64
65    /// A `glob`/`grep` glob pattern failed to compile.
66    #[error("glob: invalid pattern '{pattern}': {reason}")]
67    GlobPattern { pattern: String, reason: String },
68
69    /// A `grep` regular expression failed to compile.
70    #[error("grep: invalid pattern '{pattern}': {reason}")]
71    GrepPattern { pattern: String, reason: String },
72
73    /// The file exceeds the maximum allowed read size.
74    #[error("file too large ({bytes} bytes, max {max} bytes): {path}")]
75    FileTooLarge { path: PathBuf, bytes: u64, max: u64 },
76
77    /// `edit` found zero occurrences of `old_string`.
78    #[error("edit: old_string not found in {path}")]
79    EditNotFound { path: PathBuf },
80
81    /// `edit` found more than one occurrence of `old_string`.
82    #[error("edit: old_string is ambiguous ({count} matches) in {path}")]
83    EditAmbiguous { path: PathBuf, count: usize },
84
85    /// `HarnessMode::Parity` (#2073) requires a `diff` payload and none was
86    /// supplied — SEARCH/REPLACE and whole-file payloads are ignored under
87    /// Parity, never used as a fallback.
88    #[error(
89        "edit: Parity mode requires a unified-diff edit (provide 'diff'); \
90         SEARCH/REPLACE and whole-file are not accepted under Parity for {path}"
91    )]
92    ParityDiffRequired { path: PathBuf },
93
94    /// A `unified_diff` edit's hunk header (`@@ -l,s +l,s @@`) could not be parsed.
95    #[error("edit: invalid unified diff: {reason}")]
96    DiffHunkHeader { reason: String },
97
98    /// A `unified_diff` edit's context or removal line did not match the
99    /// file's current content at the expected position.
100    #[error("edit: diff context mismatch in {path} near original line {line}: {reason}")]
101    DiffContextMismatch {
102        path: PathBuf,
103        line: usize,
104        reason: String,
105    },
106
107    /// Underlying IO error.
108    #[error("io error on {path}: {source}")]
109    Io {
110        path: PathBuf,
111        #[source]
112        source: std::io::Error,
113    },
114}
115
116impl FsError {
117    /// Wrap an `std::io::Error` with a path context.
118    ///
119    /// Why: Every IO call needs the affected path in the error message.
120    /// What: Boxes the `std::io::Error` as `FsError::Io { path, source }`.
121    /// Test: Used internally by all three tool modules.
122    pub(crate) fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
123        FsError::Io {
124            path: path.into(),
125            source,
126        }
127    }
128}
129
130/// Resolve `raw_path` relative to `base_dir`, canonicalizing both and asserting
131/// the result is strictly inside `base_dir`.
132///
133/// Why: The tool arguments come from an LLM. Normalising before the prefix check
134/// collapses `..` components so `../../etc/passwd` cannot escape the sandbox.
135/// Absolute paths that resolve inside `base_dir` are accepted (the bake-off uses
136/// absolute output dirs built from the working dir).
137/// What: Returns the canonical absolute path on success. Returns
138/// `FsError::PathTraversal` if the resolved path is not prefixed by `base_dir`.
139/// On macOS, `/var/folders/…` is a symlink to `/private/var/…`; we canonicalize
140/// the base dir AND resolve as much of the candidate as possible (by
141/// canonicalizing the longest existing prefix) so both sides use the same
142/// physical root.
143/// Test: `read::tests::path_traversal_is_rejected`,
144///       `write::tests::path_traversal_is_rejected`,
145///       `edit::tests::path_traversal_is_rejected`.
146pub(crate) fn scoped_path(base_dir: &Path, raw_path: &Path) -> Result<PathBuf, FsError> {
147    // Build the candidate before canonicalising — the file may not exist yet.
148    let joined = if raw_path.is_absolute() {
149        raw_path.to_path_buf()
150    } else {
151        base_dir.join(raw_path)
152    };
153
154    // Canonicalize the base_dir so symlinks are resolved (e.g. /var → /private/var on macOS).
155    let canonical_base = std::fs::canonicalize(base_dir).map_err(|e| FsError::io(base_dir, e))?;
156
157    // Resolve the candidate using the same symlink-aware approach: canonicalize
158    // the longest existing ancestor, then append the non-existing tail.
159    let resolved = resolve_candidate(&canonical_base, &joined)?;
160
161    if !resolved.starts_with(&canonical_base) {
162        return Err(FsError::PathTraversal(raw_path.to_path_buf()));
163    }
164
165    Ok(resolved)
166}
167
168/// Resolve a candidate path that may not fully exist by canonicalizing its
169/// longest existing ancestor and appending the non-existing tail.
170///
171/// Why: `std::fs::canonicalize` fails on non-existent paths; `write_file` needs
172/// to validate paths for files that do not exist yet. By walking up until we find
173/// an existing prefix, we resolve symlinks in that prefix, then normalise the
174/// non-existing tail lexically.
175/// What: Returns a fully-resolved `PathBuf`. Any `..` in the non-existing tail
176/// is expanded by `normalize_path`.
177/// Test: Exercised by `write_file` tests (new files) and traversal-guard tests.
178fn resolve_candidate(_canonical_base: &Path, candidate: &Path) -> Result<PathBuf, FsError> {
179    // Try to canonicalize the full path first (handles the file-exists case).
180    if let Ok(c) = std::fs::canonicalize(candidate) {
181        return Ok(c);
182    }
183
184    // Walk up to find the longest existing ancestor.
185    let mut existing = candidate.to_path_buf();
186    let mut tail = std::collections::VecDeque::new();
187
188    loop {
189        if existing.exists() {
190            break;
191        }
192        match existing.file_name() {
193            Some(name) => {
194                tail.push_front(name.to_owned());
195                existing = existing
196                    .parent()
197                    .unwrap_or(existing.as_path())
198                    .to_path_buf();
199            }
200            None => break,
201        }
202    }
203
204    // Canonicalize whatever we found (may be the fs root in pathological cases).
205    let mut resolved = if existing.exists() {
206        std::fs::canonicalize(&existing).unwrap_or(existing)
207    } else {
208        existing
209    };
210
211    for component in tail {
212        resolved.push(component);
213    }
214
215    // A final lexical normalize in case the tail had `..`.
216    Ok(normalize_path(&resolved))
217}
218
219/// Lexically normalize a path by resolving `.` and `..` components without
220/// touching the filesystem (no `canonicalize` call).
221///
222/// Why: `std::fs::canonicalize` requires the path to exist; for `write_file` the
223/// target may not yet exist. This function produces a clean absolute path that
224/// `starts_with` checks work correctly on.
225/// What: Iterates path components, skipping `.` and backtracking on `..`, then
226/// reconstructs into a `PathBuf`.
227/// Test: Exercised indirectly via `scoped_path` in traversal-guard tests.
228fn normalize_path(path: &Path) -> PathBuf {
229    let mut components = Vec::new();
230    for component in path.components() {
231        use std::path::Component;
232        match component {
233            Component::Prefix(p) => components.push(Component::Prefix(p).as_os_str().to_owned()),
234            Component::RootDir => {
235                components.clear();
236                components.push(std::ffi::OsString::from("/"));
237            }
238            Component::CurDir => {}
239            Component::ParentDir => {
240                // Only pop if there is a non-root component to remove.
241                let last_is_root = components
242                    .last()
243                    .map(|c| c.as_encoded_bytes() == b"/")
244                    .unwrap_or(false);
245                if !components.is_empty() && !last_is_root {
246                    components.pop();
247                }
248            }
249            Component::Normal(n) => components.push(n.to_owned()),
250        }
251    }
252
253    // Reconstruct.
254    let mut out = PathBuf::new();
255    for (i, c) in components.iter().enumerate() {
256        if i == 0 && c.as_encoded_bytes() == b"/" {
257            out.push("/");
258        } else {
259            out.push(c);
260        }
261    }
262    out
263}
264
265// ── Tests for the shared helpers ─────────────────────────────────────────────
266
267#[cfg(test)]
268mod tests {
269    use std::path::Path;
270
271    use super::*;
272
273    /// `scoped_path` accepts a relative path inside the working dir.
274    ///
275    /// Why: Happy-path guard for the traversal helper.
276    /// What: `scoped_path(tmp, "foo.txt")` returns a path under the canonical tmp.
277    /// Test: This test.
278    #[test]
279    fn scoped_path_accepts_relative_inside_dir() {
280        let tmp = tempfile::tempdir().expect("tempdir");
281        // Use the canonical form for comparison — on macOS /var is a symlink to
282        // /private/var, so `tmp.path()` and the resolved path differ in prefix.
283        let canonical_tmp = std::fs::canonicalize(tmp.path()).expect("canonicalize tmp");
284        let resolved = scoped_path(tmp.path(), Path::new("foo.txt")).expect("should accept");
285        assert!(
286            resolved.starts_with(&canonical_tmp),
287            "resolved {resolved:?} must be inside canonical tmp {canonical_tmp:?}"
288        );
289    }
290
291    /// `scoped_path` rejects an attempt to escape via `../`.
292    ///
293    /// Why: Core traversal guard contract.
294    /// What: `scoped_path(tmp, "../etc/passwd")` returns `FsError::PathTraversal`.
295    /// Test: This test.
296    #[test]
297    fn scoped_path_rejects_parent_traversal() {
298        let tmp = tempfile::tempdir().expect("tempdir");
299        let err = scoped_path(tmp.path(), Path::new("../etc/passwd"));
300        assert!(
301            matches!(err, Err(FsError::PathTraversal(_))),
302            "expected PathTraversal, got {err:?}"
303        );
304    }
305
306    /// `scoped_path` accepts an absolute path that resolves inside the working dir.
307    ///
308    /// Why: The bake-off uses absolute output paths built from the working dir.
309    /// What: An absolute path whose canonical form is a child of `base_dir` is OK.
310    /// Test: This test.
311    #[test]
312    fn scoped_path_accepts_absolute_inside_dir() {
313        let tmp = tempfile::tempdir().expect("tempdir");
314        let canonical_tmp = std::fs::canonicalize(tmp.path()).expect("canonicalize tmp");
315        // Build the absolute path using the canonical form so it passes the check.
316        let abs = canonical_tmp.join("subdir").join("file.py");
317        let resolved = scoped_path(tmp.path(), &abs).expect("should accept absolute inside dir");
318        assert!(
319            resolved.starts_with(&canonical_tmp),
320            "resolved {resolved:?} must be inside canonical tmp {canonical_tmp:?}"
321        );
322    }
323
324    /// `scoped_path` rejects an absolute path that is outside the working dir.
325    ///
326    /// Why: Absolute paths not rooted in `base_dir` must be blocked.
327    /// What: `/etc/passwd` is not under `tmp` — `PathTraversal` is returned.
328    /// Test: This test.
329    #[test]
330    fn scoped_path_rejects_absolute_outside_dir() {
331        let tmp = tempfile::tempdir().expect("tempdir");
332        let err = scoped_path(tmp.path(), Path::new("/etc/passwd"));
333        assert!(
334            matches!(err, Err(FsError::PathTraversal(_))),
335            "expected PathTraversal, got {err:?}"
336        );
337    }
338}