Skip to main content

trusty_code/tools/fs/
list_dir.rs

1//! `list_dir` tool — list the entries of a single directory.
2//!
3//! Why: Complements `glob`/`grep` (#1027) — the cheapest discovery primitive is
4//! "what's in this directory?", which the engineer previously could only get by
5//! shelling out to `ls`. A structured, non-recursive listing lets the model
6//! orient itself in one typed call instead of a bash round-trip.
7//! What: `ListDirTool` reads one directory (default: the working-directory root)
8//! and returns its immediate entries, each tagged as a directory (`name/`) or a
9//! file (`name`). Non-recursive by design — recursion is `glob`'s job.
10//! Test: See `#[cfg(test)]` below — covers a mixed listing, subdirectory
11//! listing, missing directory, not-a-directory, and path traversal.
12
13use std::path::{Path, PathBuf};
14
15use async_trait::async_trait;
16use serde_json::{Value, json};
17
18use crate::tools::fs::{FsError, scoped_path};
19use crate::tools::traits::{ToolExecutor, ToolResult};
20
21/// `ToolExecutor` that lists the immediate entries of a directory.
22///
23/// Why: Gives agents a native, sandboxed directory-listing primitive so they
24/// stop shelling out to `ls`, cutting round-trips.
25/// What: Implements `ToolExecutor` with `name = "list_dir"`, scoped to
26/// `working_dir`; rejects traversal attempts in the optional `path` argument.
27/// Test: `cargo test -p trusty-code -- tools::fs::list_dir`.
28pub struct ListDirTool {
29    working_dir: PathBuf,
30}
31
32impl ListDirTool {
33    /// Construct a new `ListDirTool` scoped to `working_dir`.
34    ///
35    /// Why: The working directory is the security boundary; set once at
36    /// construction so the LLM cannot widen it per-call.
37    /// What: Stores `working_dir`.
38    /// Test: `list_dir_lists_entries`, et al.
39    pub fn new(working_dir: impl Into<PathBuf>) -> Self {
40        Self {
41            working_dir: working_dir.into(),
42        }
43    }
44
45    /// List the immediate entries of `sub_path` (default: the working dir).
46    ///
47    /// Why: Centralises the scope + read_dir + formatting so `execute` stays
48    /// short.
49    /// What: Scopes the path, verifies it is a directory, reads its entries,
50    /// tags each as `name/` (dir) or `name` (file), and returns them sorted.
51    /// Test: All `ListDirTool` unit tests.
52    fn list_inner(&self, sub_path: Option<&str>) -> Result<String, FsError> {
53        let target = match sub_path {
54            Some(p) => scoped_path(&self.working_dir, Path::new(p))?,
55            None => scoped_path(&self.working_dir, Path::new("."))?,
56        };
57
58        let meta = std::fs::metadata(&target).map_err(|e| {
59            if e.kind() == std::io::ErrorKind::NotFound {
60                FsError::NotFound(target.clone())
61            } else {
62                FsError::io(&target, e)
63            }
64        })?;
65
66        if !meta.is_dir() {
67            return Err(FsError::NotADirectory(target));
68        }
69
70        let read = std::fs::read_dir(&target).map_err(|e| FsError::io(&target, e))?;
71        let mut entries = Vec::new();
72        for dirent in read {
73            let dirent = dirent.map_err(|e| FsError::io(&target, e))?;
74            let name = dirent.file_name().to_string_lossy().into_owned();
75            // A trailing slash marks directories so the model can tell them
76            // apart without a second call.
77            let is_dir = dirent.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
78            if is_dir {
79                entries.push(format!("{name}/"));
80            } else {
81                entries.push(name);
82            }
83        }
84
85        if entries.is_empty() {
86            return Ok("(empty directory)".to_string());
87        }
88
89        entries.sort();
90        Ok(entries.join("\n"))
91    }
92}
93
94#[async_trait]
95impl ToolExecutor for ListDirTool {
96    fn name(&self) -> &str {
97        "list_dir"
98    }
99
100    /// OpenAI function-call schema for `list_dir`.
101    ///
102    /// Why: The LLM constructs its call from this schema; parameters mirror the
103    /// `execute` contract exactly.
104    /// What: JSON object with an optional `path` (directory to list; defaults to
105    /// the working-directory root).
106    /// Test: `schema_has_no_required_fields`.
107    fn schema(&self) -> Value {
108        json!({
109            "type": "function",
110            "function": {
111                "name": "list_dir",
112                "description": "List the immediate entries of a directory (non-recursive). Directories are suffixed with '/'. Defaults to the project root. Prefer this over shelling out to 'ls'.",
113                "parameters": {
114                    "type": "object",
115                    "properties": {
116                        "path": {
117                            "type": "string",
118                            "description": "Directory to list, relative to the working directory. Defaults to the project root."
119                        }
120                    },
121                    "required": [],
122                    "additionalProperties": false
123                }
124            }
125        })
126    }
127
128    /// Execute a `list_dir` tool call.
129    ///
130    /// Why: Lists the entries of a directory within the working directory.
131    /// What: Parses the optional `{path}` from `args`, calls `list_inner`,
132    /// converts the result into a `ToolResult`.
133    /// Test: `list_dir_lists_entries`, etc.
134    async fn execute(&self, args: Value) -> ToolResult {
135        let sub_path = args.get("path").and_then(Value::as_str);
136        match self.list_inner(sub_path) {
137            Ok(listing) => ToolResult::ok(listing),
138            Err(e) => ToolResult::err(e.to_string()),
139        }
140    }
141}
142
143// ── Tests ─────────────────────────────────────────────────────────────────────
144
145#[cfg(test)]
146mod tests {
147    use std::fs;
148
149    use serde_json::json;
150
151    use super::*;
152    use crate::tools::traits::ToolExecutor;
153
154    /// `list_dir` at the root lists files and directories, tagging dirs with `/`.
155    ///
156    /// Why: Basic listing contract, the core of the complement to #1027.
157    /// What: Seeds a file and a subdir, lists the root, asserts both appear with
158    /// the directory tagged by a trailing slash.
159    /// Test: This test.
160    #[tokio::test]
161    async fn list_dir_lists_entries() {
162        let tmp = tempfile::tempdir().expect("tempdir");
163        fs::write(tmp.path().join("main.py"), "x\n").expect("write");
164        fs::create_dir_all(tmp.path().join("pkg")).expect("mkdir");
165        let tool = ListDirTool::new(tmp.path());
166        let result = tool.execute(json!({})).await;
167        assert!(!result.is_error(), "unexpected error: {}", result.content());
168        let out = result.content();
169        assert!(out.contains("main.py"), "file missing: {out}");
170        assert!(out.contains("pkg/"), "dir must be tagged with '/': {out}");
171    }
172
173    /// `list_dir` scoped to a subdirectory lists that directory's entries.
174    ///
175    /// Why: The optional `path` argument narrows the listing.
176    /// What: Seeds `pkg/mod.py`, lists `pkg`, asserts `mod.py` appears and the
177    /// root's `main.py` does not.
178    /// Test: This test.
179    #[tokio::test]
180    async fn list_dir_scoped_to_subdirectory() {
181        let tmp = tempfile::tempdir().expect("tempdir");
182        fs::write(tmp.path().join("main.py"), "x\n").expect("write");
183        fs::create_dir_all(tmp.path().join("pkg")).expect("mkdir");
184        fs::write(tmp.path().join("pkg/mod.py"), "y\n").expect("write");
185        let tool = ListDirTool::new(tmp.path());
186        let result = tool.execute(json!({"path": "pkg"})).await;
187        assert!(!result.is_error());
188        let out = result.content();
189        assert!(out.contains("mod.py"), "pkg/mod.py entry missing: {out}");
190        assert!(!out.contains("main.py"), "root file must not appear: {out}");
191    }
192
193    /// `list_dir` on an empty directory returns a clear marker.
194    ///
195    /// Why: An empty listing must be distinguishable from an error.
196    /// What: Lists an empty subdir, expects the empty-directory marker.
197    /// Test: This test.
198    #[tokio::test]
199    async fn list_dir_empty_directory() {
200        let tmp = tempfile::tempdir().expect("tempdir");
201        fs::create_dir_all(tmp.path().join("empty")).expect("mkdir");
202        let tool = ListDirTool::new(tmp.path());
203        let result = tool.execute(json!({"path": "empty"})).await;
204        assert!(!result.is_error());
205        assert!(
206            result.content().contains("empty directory"),
207            "unexpected message: {}",
208            result.content()
209        );
210    }
211
212    /// `list_dir` on a missing directory returns a not-found error.
213    ///
214    /// Why: Missing paths must surface as `ToolResult::Error`, not panic.
215    /// What: Lists a non-existent subdir, expects a "not found" error.
216    /// Test: This test.
217    #[tokio::test]
218    async fn list_dir_missing_directory_errors() {
219        let tmp = tempfile::tempdir().expect("tempdir");
220        let tool = ListDirTool::new(tmp.path());
221        let result = tool.execute(json!({"path": "does_not_exist"})).await;
222        assert!(result.is_error());
223        assert!(
224            result.content().contains("not found"),
225            "unexpected message: {}",
226            result.content()
227        );
228    }
229
230    /// `list_dir` on a file (not a directory) returns a clear error.
231    ///
232    /// Why: Listing a file makes no sense; the error must say so.
233    /// What: Seeds a file, lists it as if a directory, expects a not-a-directory
234    /// error.
235    /// Test: This test.
236    #[tokio::test]
237    async fn list_dir_on_file_errors() {
238        let tmp = tempfile::tempdir().expect("tempdir");
239        fs::write(tmp.path().join("f.txt"), "x\n").expect("write");
240        let tool = ListDirTool::new(tmp.path());
241        let result = tool.execute(json!({"path": "f.txt"})).await;
242        assert!(result.is_error());
243        assert!(
244            result.content().contains("not a directory"),
245            "unexpected message: {}",
246            result.content()
247        );
248    }
249
250    /// `list_dir` rejects a `path` that escapes the working directory.
251    ///
252    /// Why: Path traversal must be blocked at the tool boundary.
253    /// What: `execute({path:"../.."})` must return an error.
254    /// Test: This test.
255    #[tokio::test]
256    async fn list_dir_path_traversal_is_rejected() {
257        let tmp = tempfile::tempdir().expect("tempdir");
258        let tool = ListDirTool::new(tmp.path());
259        let result = tool.execute(json!({"path": "../../etc"})).await;
260        assert!(result.is_error());
261        assert!(
262            result.content().contains("escapes"),
263            "unexpected message: {}",
264            result.content()
265        );
266    }
267
268    /// The schema declares `path` optional (empty `required` list).
269    ///
270    /// Why: `list_dir` must work with zero arguments (list the root).
271    /// What: Parses `schema()` and asserts `required` is empty.
272    /// Test: This test.
273    #[test]
274    fn schema_has_no_required_fields() {
275        let tmp = tempfile::tempdir().expect("tempdir");
276        let tool = ListDirTool::new(tmp.path());
277        let schema = tool.schema();
278        let required = schema["function"]["parameters"]["required"]
279            .as_array()
280            .expect("required array");
281        assert!(required.is_empty(), "list_dir must have no required fields");
282    }
283}