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