trusty_code/tools/fs/grep.rs
1//! `grep` tool — search file contents by regex across the project.
2//!
3//! Why: Content search is the other discovery primitive the engineer lacked, so
4//! every `grep -r` went through the `bash` tool — part of the dominant agent-turn
5//! sink on the L1 bake-off. A structured `grep` tool returns `file:line: text`
6//! hits the harness can pin, instead of raw shell output. (#1027.)
7//! What: `GrepTool` walks the working directory with a gitignore-aware walker
8//! (ripgrep's `ignore` crate) and returns each line matching the supplied regex.
9//! An optional `path` scopes the walk and an optional `glob` filters which files
10//! are searched.
11//! Test: See `#[cfg(test)]` below — covers a content hit, regex semantics, the
12//! glob filter, subdirectory scoping, no-match, bad-regex, and path traversal.
13
14use std::path::{Path, PathBuf};
15
16use async_trait::async_trait;
17use globset::{Glob, GlobMatcher};
18use ignore::WalkBuilder;
19use regex::Regex;
20use serde_json::{Value, json};
21
22use crate::tools::fs::{FsError, scoped_path};
23use crate::tools::traits::{ToolExecutor, ToolResult};
24
25/// Maximum number of matching lines `GrepTool` returns in a single call.
26///
27/// Why: A broad regex over a large tree could return thousands of hits and blow
28/// the LLM context window. Capping and flagging truncation keeps it bounded.
29/// What: Constant used to stop collecting hits.
30/// Test: `grep_truncates_large_result_sets`.
31pub const MAX_GREP_HITS: usize = 200;
32
33/// Skip files larger than this (bytes) — they are almost always assets/binaries.
34///
35/// Why: Reading a multi-MiB blob line-by-line to regex-match is wasteful and
36/// risks non-UTF-8 content; bounding the per-file size keeps grep fast.
37/// What: Files whose metadata length exceeds this are skipped.
38/// Test: Exercised indirectly by the content-hit tests (all small files).
39const MAX_GREP_FILE_BYTES: u64 = 1024 * 1024; // 1 MiB
40
41/// `ToolExecutor` that searches file contents by regex.
42///
43/// Why: Gives agents a native, sandboxed content-search primitive so they stop
44/// shelling out to `grep -r`, cutting round-trips.
45/// What: Implements `ToolExecutor` with `name = "grep"`, scoped to
46/// `working_dir`; rejects traversal attempts in the optional `path` argument.
47/// Test: `cargo test -p trusty-code -- tools::fs::grep`.
48pub struct GrepTool {
49 working_dir: PathBuf,
50}
51
52impl GrepTool {
53 /// Construct a new `GrepTool` scoped to `working_dir`.
54 ///
55 /// Why: The working directory is the security boundary; set once at
56 /// construction so the LLM cannot widen it per-call.
57 /// What: Stores `working_dir`.
58 /// Test: `grep_finds_matching_lines`, et al.
59 pub fn new(working_dir: impl Into<PathBuf>) -> Self {
60 Self {
61 working_dir: working_dir.into(),
62 }
63 }
64
65 /// Walk `root` and collect `file:line: text` hits for `re`.
66 ///
67 /// Why: Centralises the walk + per-line match so `execute` stays short and
68 /// the cap / file-filter / size-skip policy lives in one place.
69 /// What: Uses a gitignore-aware `WalkBuilder`; for each file (optionally
70 /// filtered by `glob`) reads its text and records every line matching `re`,
71 /// stopping at `MAX_GREP_HITS`. Returns hits and whether truncated.
72 /// Test: All `GrepTool` unit tests.
73 fn collect(&self, root: &Path, re: &Regex, glob: Option<&GlobMatcher>) -> (Vec<String>, bool) {
74 // Strip against the CANONICAL working dir (see `GlobTool::collect` for the
75 // macOS `/var` vs `/private/var` rationale) so the optional `glob` file
76 // filter and the `path:line:` display use clean project-relative paths.
77 let base =
78 std::fs::canonicalize(&self.working_dir).unwrap_or_else(|_| self.working_dir.clone());
79 let mut hits = Vec::new();
80 let mut truncated = false;
81
82 'walk: for entry in WalkBuilder::new(root).hidden(true).build().flatten() {
83 if entry.file_type().is_some_and(|ft| ft.is_dir()) {
84 continue;
85 }
86 let path = entry.path();
87 let rel = path.strip_prefix(&base).unwrap_or(path);
88
89 if let Some(g) = glob
90 && !g.is_match(rel)
91 {
92 continue;
93 }
94
95 // Skip oversized files (assets/binaries).
96 if std::fs::metadata(path).is_ok_and(|m| m.len() > MAX_GREP_FILE_BYTES) {
97 continue;
98 }
99
100 // Non-UTF-8 files are skipped silently (read_to_string errors).
101 let Ok(content) = std::fs::read_to_string(path) else {
102 continue;
103 };
104
105 let rel_display = rel.to_string_lossy();
106 for (idx, line) in content.lines().enumerate() {
107 if re.is_match(line) {
108 if hits.len() >= MAX_GREP_HITS {
109 truncated = true;
110 break 'walk;
111 }
112 // 1-based line numbers; trim to keep results compact.
113 hits.push(format!("{}:{}: {}", rel_display, idx + 1, line.trim_end()));
114 }
115 }
116 }
117 (hits, truncated)
118 }
119
120 /// Resolve the scoped root, compile the regex + optional glob, and search.
121 ///
122 /// Why: Keeps error handling (traversal, bad regex, bad glob) in one place
123 /// returning a single `Result` for `execute` to format.
124 /// What: Scopes `path` (default `working_dir`), compiles `pattern` into a
125 /// `Regex` and the optional `glob` into a `GlobMatcher`, walks, and returns
126 /// the formatted hit listing.
127 /// Test: All `GrepTool` unit tests.
128 fn grep_inner(
129 &self,
130 pattern: &str,
131 sub_path: Option<&str>,
132 glob: Option<&str>,
133 ) -> Result<String, FsError> {
134 let root = match sub_path {
135 Some(p) => scoped_path(&self.working_dir, Path::new(p))?,
136 None => scoped_path(&self.working_dir, Path::new("."))?,
137 };
138
139 let re = Regex::new(pattern).map_err(|e| FsError::GrepPattern {
140 pattern: pattern.to_string(),
141 reason: e.to_string(),
142 })?;
143
144 let matcher = match glob {
145 Some(g) => Some(
146 Glob::new(g)
147 .map_err(|e| FsError::GlobPattern {
148 pattern: g.to_string(),
149 reason: e.to_string(),
150 })?
151 .compile_matcher(),
152 ),
153 None => None,
154 };
155
156 let (hits, truncated) = self.collect(&root, &re, matcher.as_ref());
157
158 if hits.is_empty() {
159 return Ok(format!("no matches for pattern '{pattern}'"));
160 }
161
162 let mut out = hits.join("\n");
163 if truncated {
164 out.push_str(&format!(
165 "\n… (truncated at {MAX_GREP_HITS} matches; refine the pattern)"
166 ));
167 }
168 Ok(out)
169 }
170}
171
172#[async_trait]
173impl ToolExecutor for GrepTool {
174 fn name(&self) -> &str {
175 "grep"
176 }
177
178 /// OpenAI function-call schema for `grep`.
179 ///
180 /// Why: The LLM constructs its call from this schema; parameters mirror the
181 /// `execute` contract exactly.
182 /// What: JSON object with `pattern` (required regex), `path` (optional
183 /// subdirectory), and `glob` (optional file filter).
184 /// Test: `schema_has_required_pattern`.
185 fn schema(&self) -> Value {
186 json!({
187 "type": "function",
188 "function": {
189 "name": "grep",
190 "description": "Search file contents by regular expression across the project. Returns matching 'path:line: text' hits, one per line. Hidden and .gitignore'd files are skipped. Prefer this over shelling out to 'grep'.",
191 "parameters": {
192 "type": "object",
193 "properties": {
194 "pattern": {
195 "type": "string",
196 "description": "Regular expression to match against each line of file contents."
197 },
198 "path": {
199 "type": "string",
200 "description": "Optional subdirectory (relative to the working directory) to scope the search. Defaults to the whole project."
201 },
202 "glob": {
203 "type": "string",
204 "description": "Optional glob (e.g. '**/*.py') restricting which files are searched."
205 }
206 },
207 "required": ["pattern"],
208 "additionalProperties": false
209 }
210 }
211 })
212 }
213
214 /// Execute a `grep` tool call.
215 ///
216 /// Why: Searches file contents for `pattern` within the working directory.
217 /// What: Parses `{pattern, path?, glob?}` from `args`, calls `grep_inner`,
218 /// converts the result into a `ToolResult`.
219 /// Test: `grep_finds_matching_lines`, etc.
220 async fn execute(&self, args: Value) -> ToolResult {
221 let Some(pattern) = args.get("pattern").and_then(Value::as_str) else {
222 return ToolResult::err("grep: missing required argument 'pattern'");
223 };
224 let sub_path = args.get("path").and_then(Value::as_str);
225 let glob = args.get("glob").and_then(Value::as_str);
226
227 match self.grep_inner(pattern, sub_path, glob) {
228 Ok(listing) => ToolResult::ok(listing),
229 Err(e) => ToolResult::err(e.to_string()),
230 }
231 }
232}
233
234// ── Tests ─────────────────────────────────────────────────────────────────────
235
236#[cfg(test)]
237mod tests {
238 use std::fs;
239
240 use serde_json::json;
241
242 use super::*;
243 use crate::tools::traits::ToolExecutor;
244
245 /// Seed a tree with searchable content.
246 fn seed(tmp: &tempfile::TempDir) {
247 fs::write(
248 tmp.path().join("app.py"),
249 "import os\ndef handler():\n return TODO_FIXME\n",
250 )
251 .expect("write");
252 fs::create_dir_all(tmp.path().join("lib")).expect("mkdir");
253 fs::write(
254 tmp.path().join("lib/util.rs"),
255 "fn helper() {}\n// TODO_FIXME later\n",
256 )
257 .expect("write");
258 }
259
260 /// `grep` finds a literal substring and reports `path:line: text`.
261 ///
262 /// Why: Basic content-search contract, the core of #1027.
263 /// What: Seeds files containing `TODO_FIXME`, greps for it, asserts both
264 /// files and their line numbers appear.
265 /// Test: This test.
266 #[tokio::test]
267 async fn grep_finds_matching_lines() {
268 let tmp = tempfile::tempdir().expect("tempdir");
269 seed(&tmp);
270 let tool = GrepTool::new(tmp.path());
271 let result = tool.execute(json!({"pattern": "TODO_FIXME"})).await;
272 assert!(!result.is_error(), "unexpected error: {}", result.content());
273 let out = result.content();
274 assert!(out.contains("app.py:3:"), "app.py hit missing: {out}");
275 assert!(out.contains("lib/util.rs:2:"), "util.rs hit missing: {out}");
276 }
277
278 /// `grep` honours regex semantics, not just literal substrings.
279 ///
280 /// Why: The pattern is a regex; anchors/character classes must work.
281 /// What: Greps `^def ` (line starting with `def `), asserts only the
282 /// function-definition line matches.
283 /// Test: This test.
284 #[tokio::test]
285 async fn grep_uses_regex_semantics() {
286 let tmp = tempfile::tempdir().expect("tempdir");
287 seed(&tmp);
288 let tool = GrepTool::new(tmp.path());
289 let result = tool.execute(json!({"pattern": "^def "})).await;
290 assert!(!result.is_error());
291 let out = result.content();
292 assert!(out.contains("def handler"), "def line missing: {out}");
293 assert!(
294 !out.contains("import os"),
295 "import line must not match: {out}"
296 );
297 }
298
299 /// `grep` with a `glob` filter searches only matching files.
300 ///
301 /// Why: The optional glob narrows the file set (e.g. only `.rs`).
302 /// What: Greps `TODO_FIXME` restricted to `**/*.rs`, asserts the `.rs` hit
303 /// appears and the `.py` hit does not.
304 /// Test: This test.
305 #[tokio::test]
306 async fn grep_glob_filter_restricts_files() {
307 let tmp = tempfile::tempdir().expect("tempdir");
308 seed(&tmp);
309 let tool = GrepTool::new(tmp.path());
310 let result = tool
311 .execute(json!({"pattern": "TODO_FIXME", "glob": "**/*.rs"}))
312 .await;
313 assert!(!result.is_error());
314 let out = result.content();
315 assert!(out.contains("lib/util.rs"), "rs hit missing: {out}");
316 assert!(
317 !out.contains("app.py"),
318 "py file must be filtered out: {out}"
319 );
320 }
321
322 /// `grep` scoped to a subdirectory only searches that subtree.
323 ///
324 /// Why: The optional `path` argument narrows the search.
325 /// What: Greps `TODO_FIXME` scoped to `lib`, asserts only the `lib` hit.
326 /// Test: This test.
327 #[tokio::test]
328 async fn grep_scoped_to_subdirectory() {
329 let tmp = tempfile::tempdir().expect("tempdir");
330 seed(&tmp);
331 let tool = GrepTool::new(tmp.path());
332 let result = tool
333 .execute(json!({"pattern": "TODO_FIXME", "path": "lib"}))
334 .await;
335 assert!(!result.is_error());
336 let out = result.content();
337 assert!(out.contains("lib/util.rs"), "lib hit missing: {out}");
338 assert!(!out.contains("app.py"), "app.py is outside scope: {out}");
339 }
340
341 /// `grep` with no matches returns a clear message, not an error.
342 ///
343 /// Why: "No results" is a normal outcome the model must read.
344 /// What: Greps a pattern present in no file, expects the no-match text.
345 /// Test: This test.
346 #[tokio::test]
347 async fn grep_no_matches_reports_clearly() {
348 let tmp = tempfile::tempdir().expect("tempdir");
349 seed(&tmp);
350 let tool = GrepTool::new(tmp.path());
351 let result = tool.execute(json!({"pattern": "ZZZ_NOT_PRESENT"})).await;
352 assert!(!result.is_error());
353 assert!(
354 result.content().contains("no matches"),
355 "unexpected message: {}",
356 result.content()
357 );
358 }
359
360 /// `grep` truncates match sets larger than `MAX_GREP_HITS`.
361 ///
362 /// Why: An unbounded result would overflow the context window — this is the
363 /// exact guarantee `MAX_GREP_HITS`'s doc comment promises.
364 /// What: Seeds a single file with `MAX_GREP_HITS + 5` matching lines, greps
365 /// for the shared marker, asserts the truncation notice appears.
366 /// Test: This test.
367 #[tokio::test]
368 async fn grep_truncates_large_result_sets() {
369 let tmp = tempfile::tempdir().expect("tempdir");
370 let mut content = String::new();
371 for i in 0..(MAX_GREP_HITS + 5) {
372 content.push_str(&format!("MATCH_MARKER line {i}\n"));
373 }
374 fs::write(tmp.path().join("big.txt"), content).expect("write");
375 let tool = GrepTool::new(tmp.path());
376 let result = tool.execute(json!({"pattern": "MATCH_MARKER"})).await;
377 assert!(!result.is_error(), "{}", result.content());
378 assert!(
379 result.content().contains("truncated"),
380 "expected truncation notice: {}",
381 result.content()
382 );
383 }
384
385 /// `grep` reports a bad regex as a recoverable error.
386 ///
387 /// Why: A malformed pattern must surface as a structured error the model can
388 /// correct, not a panic.
389 /// What: `execute({pattern:"(unclosed"})` returns an error mentioning grep.
390 /// Test: This test.
391 #[tokio::test]
392 async fn grep_bad_regex_errors() {
393 let tmp = tempfile::tempdir().expect("tempdir");
394 let tool = GrepTool::new(tmp.path());
395 let result = tool.execute(json!({"pattern": "(unclosed"})).await;
396 assert!(result.is_error());
397 assert!(
398 result.content().contains("grep"),
399 "unexpected message: {}",
400 result.content()
401 );
402 }
403
404 /// `grep` rejects a `path` that escapes the working directory.
405 ///
406 /// Why: Path traversal must be blocked at the tool boundary.
407 /// What: `execute({pattern:"x", path:"../.."})` must return an error.
408 /// Test: This test.
409 #[tokio::test]
410 async fn grep_path_traversal_is_rejected() {
411 let tmp = tempfile::tempdir().expect("tempdir");
412 let tool = GrepTool::new(tmp.path());
413 let result = tool
414 .execute(json!({"pattern": "x", "path": "../../etc"}))
415 .await;
416 assert!(result.is_error());
417 assert!(
418 result.content().contains("escapes"),
419 "unexpected message: {}",
420 result.content()
421 );
422 }
423
424 /// The schema lists `pattern` as required.
425 ///
426 /// Why: The LLM omits non-required args; `pattern` must be required.
427 /// What: Parses `schema()` and checks `required` contains "pattern".
428 /// Test: This test.
429 #[test]
430 fn schema_has_required_pattern() {
431 let tmp = tempfile::tempdir().expect("tempdir");
432 let tool = GrepTool::new(tmp.path());
433 let schema = tool.schema();
434 let required = schema["function"]["parameters"]["required"]
435 .as_array()
436 .expect("required array");
437 assert!(
438 required.iter().any(|v| v.as_str() == Some("pattern")),
439 "schema must list 'pattern' as required"
440 );
441 }
442}