trusty_code/tools/fs/glob.rs
1//! `glob` tool — find files by glob pattern (e.g. `**/*.py`, `src/*.rs`).
2//!
3//! Why: The engineer's tool registry historically had NO native file discovery,
4//! so every `find`/`ls -R` went through the `bash` tool — the dominant agent-turn
5//! sink on the L1 bake-off (bash was 53-71% of every turn). A structured `glob`
6//! tool lets the model enumerate files in one typed call whose result the harness
7//! can pin and reason about, instead of parsing arbitrary shell output. (#1027.)
8//! What: `GlobTool` walks the working directory with a gitignore-aware walker
9//! (ripgrep's `ignore` crate — hidden files and `.gitignore`d paths are skipped
10//! by default) and returns every project-relative path matching the supplied
11//! glob. An optional `path` scopes the walk to a subdirectory.
12//! Test: See `#[cfg(test)]` below — covers a recursive match, a single-level
13//! match, subdirectory scoping, no-match, and path traversal.
14
15use std::path::{Path, PathBuf};
16
17use async_trait::async_trait;
18use globset::{Glob, GlobMatcher};
19use ignore::WalkBuilder;
20use serde_json::{Value, json};
21
22use crate::tools::fs::{FsError, scoped_path};
23use crate::tools::traits::{ToolExecutor, ToolResult};
24
25/// Maximum number of paths `GlobTool` returns in a single call.
26///
27/// Why: An unbounded match set (`**/*` on a huge tree) would blow the LLM
28/// context window. Capping and flagging truncation keeps the result bounded and
29/// honest.
30/// What: Constant used to truncate the sorted match list.
31/// Test: `glob_truncates_large_result_sets`.
32pub const MAX_GLOB_MATCHES: usize = 500;
33
34/// `ToolExecutor` that lists files matching a glob pattern.
35///
36/// Why: Gives agents a native, sandboxed file-discovery primitive so they stop
37/// shelling out to `find`, cutting round-trips.
38/// What: Implements `ToolExecutor` with `name = "glob"`, scoped to
39/// `working_dir`; rejects traversal attempts in the optional `path` argument.
40/// Test: `cargo test -p trusty-code -- tools::fs::glob`.
41pub struct GlobTool {
42 working_dir: PathBuf,
43}
44
45impl GlobTool {
46 /// Construct a new `GlobTool` scoped to `working_dir`.
47 ///
48 /// Why: The working directory is the security boundary; set once at
49 /// construction so the LLM cannot widen it per-call.
50 /// What: Stores `working_dir`.
51 /// Test: `glob_finds_files_recursively`, et al.
52 pub fn new(working_dir: impl Into<PathBuf>) -> Self {
53 Self {
54 working_dir: working_dir.into(),
55 }
56 }
57
58 /// Walk `root` and collect project-relative paths matching `matcher`.
59 ///
60 /// Why: Centralises the walk + match so `execute` stays short and the cap /
61 /// sort / truncation policy lives in one place.
62 /// What: Uses a gitignore-aware `WalkBuilder`, matches each file's path
63 /// relative to `self.working_dir` against `matcher`, returns sorted matches
64 /// and whether the set was truncated at `MAX_GLOB_MATCHES`.
65 /// Test: All `GlobTool` unit tests.
66 fn collect(&self, root: &Path, matcher: &GlobMatcher) -> (Vec<String>, bool) {
67 // Strip against the CANONICAL working dir: `root` came from `scoped_path`
68 // (canonicalized), so on macOS its entries carry the `/private/var/…`
69 // prefix while `self.working_dir` may be the `/var/…` symlink form —
70 // stripping the raw form would fail and leak absolute paths into the
71 // matcher, breaking single-segment patterns like `src/*.rs`.
72 let base =
73 std::fs::canonicalize(&self.working_dir).unwrap_or_else(|_| self.working_dir.clone());
74 let mut matches = Vec::new();
75 for entry in WalkBuilder::new(root).hidden(true).build().flatten() {
76 // Only match files, not directories.
77 if entry.file_type().is_some_and(|ft| ft.is_dir()) {
78 continue;
79 }
80 let rel = entry.path().strip_prefix(&base).unwrap_or(entry.path());
81 if matcher.is_match(rel) {
82 matches.push(rel.to_string_lossy().into_owned());
83 }
84 }
85 matches.sort();
86 let truncated = matches.len() > MAX_GLOB_MATCHES;
87 matches.truncate(MAX_GLOB_MATCHES);
88 (matches, truncated)
89 }
90
91 /// Resolve the scoped root, compile the glob, and run the walk.
92 ///
93 /// Why: Keeps error handling (traversal, bad pattern) in one place returning
94 /// a single `Result` for `execute` to format.
95 /// What: Scopes `path` (default `working_dir`), compiles `pattern` into a
96 /// `GlobMatcher`, walks, and returns the formatted match listing.
97 /// Test: All `GlobTool` unit tests.
98 fn glob_inner(&self, pattern: &str, sub_path: Option<&str>) -> Result<String, FsError> {
99 let root = match sub_path {
100 Some(p) => scoped_path(&self.working_dir, Path::new(p))?,
101 None => scoped_path(&self.working_dir, Path::new("."))?,
102 };
103
104 let matcher = Glob::new(pattern)
105 .map_err(|e| FsError::GlobPattern {
106 pattern: pattern.to_string(),
107 reason: e.to_string(),
108 })?
109 .compile_matcher();
110
111 let (matches, truncated) = self.collect(&root, &matcher);
112
113 if matches.is_empty() {
114 return Ok(format!("no files matched pattern '{pattern}'"));
115 }
116
117 let mut out = matches.join("\n");
118 if truncated {
119 out.push_str(&format!(
120 "\n… (truncated at {MAX_GLOB_MATCHES} matches; refine the pattern)"
121 ));
122 }
123 Ok(out)
124 }
125}
126
127#[async_trait]
128impl ToolExecutor for GlobTool {
129 fn name(&self) -> &str {
130 "glob"
131 }
132
133 /// OpenAI function-call schema for `glob`.
134 ///
135 /// Why: The LLM constructs its call from this schema; parameters mirror the
136 /// `execute` contract exactly.
137 /// What: JSON object with `pattern` (required) and `path` (optional
138 /// subdirectory to scope the walk).
139 /// Test: `schema_has_required_pattern`.
140 fn schema(&self) -> Value {
141 json!({
142 "type": "function",
143 "function": {
144 "name": "glob",
145 "description": "Find files by glob pattern (e.g. '**/*.py', 'src/*.rs'). Returns matching project-relative paths, one per line. Hidden and .gitignore'd files are skipped. Prefer this over shelling out to 'find'.",
146 "parameters": {
147 "type": "object",
148 "properties": {
149 "pattern": {
150 "type": "string",
151 "description": "Glob pattern to match against project-relative paths. '**' matches any number of directories; '*' matches within a path segment."
152 },
153 "path": {
154 "type": "string",
155 "description": "Optional subdirectory (relative to the working directory) to scope the search. Defaults to the whole project."
156 }
157 },
158 "required": ["pattern"],
159 "additionalProperties": false
160 }
161 }
162 })
163 }
164
165 /// Execute a `glob` tool call.
166 ///
167 /// Why: Enumerates files matching `pattern` within the working directory.
168 /// What: Parses `{pattern, path?}` from `args`, calls `glob_inner`, converts
169 /// the result into a `ToolResult`.
170 /// Test: `glob_finds_files_recursively`, etc.
171 async fn execute(&self, args: Value) -> ToolResult {
172 let Some(pattern) = args.get("pattern").and_then(Value::as_str) else {
173 return ToolResult::err("glob: missing required argument 'pattern'");
174 };
175 let sub_path = args.get("path").and_then(Value::as_str);
176
177 match self.glob_inner(pattern, sub_path) {
178 Ok(listing) => ToolResult::ok(listing),
179 Err(e) => ToolResult::err(e.to_string()),
180 }
181 }
182}
183
184// ── Tests ─────────────────────────────────────────────────────────────────────
185
186#[cfg(test)]
187mod tests {
188 use std::fs;
189
190 use serde_json::json;
191
192 use super::*;
193 use crate::tools::traits::ToolExecutor;
194
195 /// Seed a small tree: `a.py`, `pkg/b.py`, `pkg/c.txt`, `src/main.rs`.
196 fn seed(tmp: &tempfile::TempDir) {
197 fs::write(tmp.path().join("a.py"), "x = 1\n").expect("write");
198 fs::create_dir_all(tmp.path().join("pkg")).expect("mkdir");
199 fs::write(tmp.path().join("pkg/b.py"), "y = 2\n").expect("write");
200 fs::write(tmp.path().join("pkg/c.txt"), "text\n").expect("write");
201 fs::create_dir_all(tmp.path().join("src")).expect("mkdir");
202 fs::write(tmp.path().join("src/main.rs"), "fn main() {}\n").expect("write");
203 }
204
205 /// `glob` with `**/*.py` finds every Python file, at any depth.
206 ///
207 /// Why: The `**` recursive-match is the core of #1027.
208 /// What: Seeds a tree, globs `**/*.py`, asserts both `.py` files appear and
209 /// the `.txt`/`.rs` files do not.
210 /// Test: This test.
211 #[tokio::test]
212 async fn glob_finds_files_recursively() {
213 let tmp = tempfile::tempdir().expect("tempdir");
214 seed(&tmp);
215 let tool = GlobTool::new(tmp.path());
216 let result = tool.execute(json!({"pattern": "**/*.py"})).await;
217 assert!(!result.is_error(), "unexpected error: {}", result.content());
218 let out = result.content();
219 assert!(out.contains("a.py"), "top-level a.py missing: {out}");
220 assert!(out.contains("pkg/b.py"), "nested pkg/b.py missing: {out}");
221 assert!(!out.contains("c.txt"), "non-matching c.txt present: {out}");
222 assert!(
223 !out.contains("main.rs"),
224 "non-matching main.rs present: {out}"
225 );
226 }
227
228 /// `glob` with `src/*.rs` matches only files directly under `src`.
229 ///
230 /// Why: Single-segment `*` must not cross directory boundaries.
231 /// What: Globs `src/*.rs`, asserts `src/main.rs` matches and `a.py` does not.
232 /// Test: This test.
233 #[tokio::test]
234 async fn glob_single_level_pattern() {
235 let tmp = tempfile::tempdir().expect("tempdir");
236 seed(&tmp);
237 let tool = GlobTool::new(tmp.path());
238 let result = tool.execute(json!({"pattern": "src/*.rs"})).await;
239 assert!(!result.is_error());
240 let out = result.content();
241 assert!(out.contains("src/main.rs"), "src/main.rs missing: {out}");
242 assert!(
243 !out.contains("a.py"),
244 "a.py should not match src/*.rs: {out}"
245 );
246 }
247
248 /// `glob` scoped to a subdirectory only walks that subtree.
249 ///
250 /// Why: The optional `path` argument lets the agent narrow the search.
251 /// What: Globs `*.py` scoped to `pkg`, asserts `pkg/b.py` matches and the
252 /// top-level `a.py` does not.
253 /// Test: This test.
254 #[tokio::test]
255 async fn glob_scoped_to_subdirectory() {
256 let tmp = tempfile::tempdir().expect("tempdir");
257 seed(&tmp);
258 let tool = GlobTool::new(tmp.path());
259 let result = tool
260 .execute(json!({"pattern": "**/*.py", "path": "pkg"}))
261 .await;
262 assert!(!result.is_error(), "{}", result.content());
263 let out = result.content();
264 assert!(out.contains("pkg/b.py"), "pkg/b.py missing: {out}");
265 assert!(!out.contains("a.py"), "a.py is outside scoped path: {out}");
266 }
267
268 /// `glob` with no matches returns a clear message, not an error.
269 ///
270 /// Why: "No results" is a normal outcome the model must be able to read.
271 /// What: Globs `**/*.java` over a tree with none, expects the no-match text.
272 /// Test: This test.
273 #[tokio::test]
274 async fn glob_no_matches_reports_clearly() {
275 let tmp = tempfile::tempdir().expect("tempdir");
276 seed(&tmp);
277 let tool = GlobTool::new(tmp.path());
278 let result = tool.execute(json!({"pattern": "**/*.java"})).await;
279 assert!(!result.is_error());
280 assert!(
281 result.content().contains("no files matched"),
282 "unexpected message: {}",
283 result.content()
284 );
285 }
286
287 /// `glob` rejects a `path` that escapes the working directory.
288 ///
289 /// Why: Path traversal must be blocked at the tool boundary.
290 /// What: `execute({pattern:"*", path:"../.."})` must return an error.
291 /// Test: This test.
292 #[tokio::test]
293 async fn glob_path_traversal_is_rejected() {
294 let tmp = tempfile::tempdir().expect("tempdir");
295 let tool = GlobTool::new(tmp.path());
296 let result = tool
297 .execute(json!({"pattern": "*", "path": "../../etc"}))
298 .await;
299 assert!(result.is_error());
300 assert!(
301 result.content().contains("escapes"),
302 "unexpected message: {}",
303 result.content()
304 );
305 }
306
307 /// `glob` reports a bad glob pattern as a recoverable error.
308 ///
309 /// Why: A malformed pattern must surface as a structured error the model can
310 /// correct, not a panic.
311 /// What: `execute({pattern:"[unclosed"})` returns an error mentioning the
312 /// pattern.
313 /// Test: This test.
314 #[tokio::test]
315 async fn glob_bad_pattern_errors() {
316 let tmp = tempfile::tempdir().expect("tempdir");
317 let tool = GlobTool::new(tmp.path());
318 let result = tool.execute(json!({"pattern": "[unclosed"})).await;
319 assert!(result.is_error());
320 assert!(
321 result.content().contains("glob"),
322 "unexpected message: {}",
323 result.content()
324 );
325 }
326
327 /// `glob` truncates match sets larger than `MAX_GLOB_MATCHES`.
328 ///
329 /// Why: An unbounded result would overflow the context window.
330 /// What: Seeds `MAX_GLOB_MATCHES + 5` files, globs `**/*.py`, asserts the
331 /// truncation notice appears and at most the cap of paths is listed.
332 /// Test: This test.
333 #[tokio::test]
334 async fn glob_truncates_large_result_sets() {
335 let tmp = tempfile::tempdir().expect("tempdir");
336 for i in 0..(MAX_GLOB_MATCHES + 5) {
337 fs::write(tmp.path().join(format!("f{i}.py")), "x\n").expect("write");
338 }
339 let tool = GlobTool::new(tmp.path());
340 let result = tool.execute(json!({"pattern": "**/*.py"})).await;
341 assert!(!result.is_error());
342 assert!(
343 result.content().contains("truncated"),
344 "expected truncation notice"
345 );
346 }
347
348 /// The schema lists `pattern` as required.
349 ///
350 /// Why: The LLM omits non-required args; `pattern` must be required.
351 /// What: Parses `schema()` and checks `required` contains "pattern".
352 /// Test: This test.
353 #[test]
354 fn schema_has_required_pattern() {
355 let tmp = tempfile::tempdir().expect("tempdir");
356 let tool = GlobTool::new(tmp.path());
357 let schema = tool.schema();
358 let required = schema["function"]["parameters"]["required"]
359 .as_array()
360 .expect("required array");
361 assert!(
362 required.iter().any(|v| v.as_str() == Some("pattern")),
363 "schema must list 'pattern' as required"
364 );
365 }
366}