1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
use ignore::WalkBuilder;
use regex::Regex;
use rig::completion::ToolDefinition;
use rig::tool::Tool;
use crate::agent::agent_loop::tool_input_repair::with_contract_hint;
use crate::agent::tools::cache::ToolCache;
use crate::agent::tools::{
AskSender, GrepArgs, MAX_GREP_RESULTS, PermCheck, ToolError, check_perm, check_perm_path,
is_skip_dir,
};
pub struct GrepTool {
pub permission: Option<PermCheck>,
pub ask_tx: Option<AskSender>,
pub cache: Option<ToolCache>,
}
impl GrepTool {
#[allow(dead_code)]
pub fn new(permission: Option<PermCheck>, ask_tx: Option<AskSender>) -> Self {
GrepTool {
permission,
ask_tx,
cache: None,
}
}
pub fn with_cache(
permission: Option<PermCheck>,
ask_tx: Option<AskSender>,
cache: ToolCache,
) -> Self {
GrepTool {
permission,
ask_tx,
cache: Some(cache),
}
}
fn glob_to_regex(glob: &str) -> String {
let mut re = String::with_capacity(glob.len() * 2);
for c in glob.chars() {
match c {
'.' => re.push_str("\\."),
'*' => re.push_str(".*"),
'?' => re.push('.'),
'{' => re.push_str("(?:"),
'}' => re.push(')'),
',' => re.push('|'),
// TOOL-2: escape regex metacharacters in the fallthrough
// so an `include` glob like `*.c++` doesn't compile to
// `.*\.c++` (which the regex engine interprets as a
// possessive `+` quantifier) and `[abc].rs` doesn't
// become a regex character class.
c if "+()[]^$|\\".contains(c) => {
re.push('\\');
re.push(c);
}
_ => re.push(c),
}
}
re
}
fn is_binary(data: &[u8]) -> bool {
data.iter().take(8192).any(|&b| b == 0)
}
}
impl Tool for GrepTool {
const NAME: &'static str = "grep";
type Error = ToolError;
type Args = GrepArgs;
type Output = String;
async fn definition(&self, _prompt: String) -> ToolDefinition {
ToolDefinition {
name: "grep".to_string(),
description: with_contract_hint(
"grep",
"Search FILE CONTENTS for a regex pattern (Rust regex syntax) and return matching lines as file:line. Use this to find where text or code appears across the project. NOT for matching FILENAMES — use `glob` (path patterns) or `find_files` (filename regex); NOT for locating a symbol's definition — use `find_definition`. Respects .gitignore; skips binary files, node_modules, and target.",
),
parameters: serde_json::json!({
"type": "object",
"properties": {
"pattern": {
"type": "string",
"description": "Regex pattern to search for (supports Rust regex syntax)"
},
"path": {
"type": "string",
"description": "Directory to search in (defaults to current working directory)"
},
"include": {
"type": "string",
"description": "Optional file glob pattern to filter (e.g. '*.rs', '*.{ts,tsx}')"
},
"context_lines": {
"type": "integer",
"description": "Number of context lines to show before and after each match (like grep -C)"
},
"include_hidden": {
"type": "boolean",
"description": "Include dotfiles (.env, .gitignore, etc.) in the search. Default false to avoid surfacing secrets and config files."
},
"reason": { "type": "string", "description": "Why you're searching: the specific question this answers and how it serves the current task. Be targeted." }
},
"required": ["pattern", "reason"]
}),
}
}
async fn call(&self, args: GrepArgs) -> Result<String, ToolError> {
check_perm(&self.permission, &self.ask_tx, "grep", &args.pattern).await?;
// Path-side check: previously grep accepted any path
// (`grep("x", "/etc")`) because only the pattern was
// permission-checked. external_directory rules + the
// working-dir Accept-mode logic live in check_perm_path,
// so an extra call here closes the bypass.
let perm_path = args.path.as_deref().unwrap_or(".");
check_perm_path(&self.permission, &self.ask_tx, "grep", perm_path).await?;
// LOOP-3: include dir stamp so external file additions /
// mtime changes within the search root invalidate the
// cache. This is per-DIRECTORY mtime; a child-file edit
// doesn't always bump the parent mtime (depends on the
// filesystem), so the cache may still go stale for in-
// place edits within the dir — but the common case
// (file add/remove/rename) is caught.
let stamp =
crate::agent::tools::cache::fs_stamp_or_cwd(args.path.as_deref().unwrap_or("."));
let cache_key = format!(
"grep:{}:{}:{}:{}:hidden={}:{}",
args.pattern,
args.path.as_deref().unwrap_or("."),
args.include.as_deref().unwrap_or(""),
args.context_lines.unwrap_or(0),
args.include_hidden,
stamp,
);
if let Some(ref cache) = self.cache
&& let Some(cached) = cache.get(&cache_key)
{
return Ok(cached);
}
let re = Regex::new(&args.pattern)
.map_err(|e| ToolError::Msg(format!("Invalid regex pattern: {}", e)))?;
let search_path = args.path.as_deref().unwrap_or(".");
let context = args.context_lines.unwrap_or(0);
// Validate the include glob and surface compile errors
// instead of the previous silent fallback to `.*` (match
// everything). A user passing `include: "[a-z("` would have
// silently matched every file — the include filter would
// appear to do nothing and they'd never know why.
let include_re = match args.include.as_ref() {
Some(g) => {
let pattern = format!("^(?:{})$", Self::glob_to_regex(g));
Some(Regex::new(&pattern).map_err(|e| {
ToolError::Msg(format!(
"Invalid include glob {g:?}: {e}. Use forms like \"*.rs\" or \"*.{{ts,tsx}}\"."
))
})?)
}
None => None,
};
let walker = WalkBuilder::new(search_path)
.git_ignore(true)
.git_global(true)
.git_exclude(true)
.require_git(false)
// F2 carryover: hide dotfiles by default so grep doesn't
// silently surface `.env` / `.git/` internals. Opt-in
// via `include_hidden: true`.
.hidden(!args.include_hidden)
.filter_entry(|entry| {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
!is_skip_dir(entry.file_name().to_str().unwrap_or(""))
} else {
true
}
})
.build();
let mut file_count = 0;
let mut match_count = 0usize;
let mut all_results: Vec<String> = Vec::new();
for entry in walker
.flatten()
.filter(|e| e.file_type().map(|t| t.is_file()).unwrap_or(false))
{
if all_results.len() >= MAX_GREP_RESULTS {
break;
}
if let Some(ref re_include) = include_re {
let fname = entry.file_name().to_string_lossy();
if !re_include.is_match(&fname) {
continue;
}
}
if let Ok(meta) = entry.metadata()
&& meta.len() > 10 * 1024 * 1024
{
continue;
}
let path_str = entry.path().to_string_lossy().to_string();
// Skip files larger than 10 MiB so a single huge file
// can't blow up the process memory. Anything bigger
// than this is realistically not source code the LLM
// would want grepped. `tokio::fs::read` previously
// pulled the whole file into RAM unconditionally.
const MAX_GREP_FILE_BYTES: u64 = 10 * 1024 * 1024;
if let Ok(meta) = tokio::fs::metadata(entry.path()).await
&& meta.len() > MAX_GREP_FILE_BYTES
{
continue;
}
match tokio::fs::read(entry.path()).await {
Ok(data) => {
if Self::is_binary(&data) {
continue;
}
file_count += 1;
let content = String::from_utf8_lossy(&data);
let lines: Vec<&str> = content.lines().collect();
let total = lines.len();
let match_lines: Vec<usize> = lines
.iter()
.enumerate()
.filter(|(_, l)| re.is_match(l))
.map(|(i, _)| i)
.collect();
if match_lines.is_empty() {
continue;
}
match_count += match_lines.len();
// Audit M7b: per-line cap. A minified JS / generated
// SQL / single-line JSON file can produce a match
// on a 10 MB line; pushing that into the output
// verbatim ships 10 MB through the LLM context.
// Truncate each output line to MAX_LINE_BYTES with
// a `…[truncated]` marker. Boundary-safe (lands on
// a UTF-8 char boundary).
const MAX_LINE_BYTES: usize = 4096;
const TRUNC_MARKER: &str = "…[truncated]";
let trim_line = |s: &str| -> String {
if s.len() <= MAX_LINE_BYTES {
return s.to_string();
}
let mut cut = MAX_LINE_BYTES;
while cut > 0 && !s.is_char_boundary(cut) {
cut -= 1;
}
format!("{}{}", &s[..cut], TRUNC_MARKER)
};
if context == 0 {
for &ml in &match_lines {
all_results.push(format!(
"{}:{}:{}",
path_str,
ml + 1,
trim_line(lines[ml])
));
if all_results.len() >= MAX_GREP_RESULTS {
break;
}
}
} else {
let mut shown = vec![false; total];
for &ml in &match_lines {
let start = ml.saturating_sub(context);
let end = (ml + 1 + context).min(total);
for s in &mut shown[start..end] {
*s = true;
}
}
let mut i = 0;
while i < total && all_results.len() < MAX_GREP_RESULTS {
if !shown[i] {
i += 1;
continue;
}
if !all_results.is_empty() {
all_results.push("--".to_string());
}
while i < total && shown[i] && all_results.len() < MAX_GREP_RESULTS {
let is_match = match_lines.binary_search(&i).is_ok();
let sep = if is_match { ':' } else { '-' };
all_results.push(format!(
"{}-{}{} {}",
path_str,
i + 1,
sep,
trim_line(lines[i]),
));
i += 1;
}
}
}
}
Err(_) => continue,
}
}
let result = if all_results.is_empty() {
"No matches found.".to_string()
} else {
let output_lines = all_results.len();
if output_lines >= MAX_GREP_RESULTS {
// `output_lines - MAX_GREP_RESULTS` is always 0 here
// because the walker breaks the moment `all_results`
// hits the cap — the old footer always read
// "...and 0 more". Use the actual match count vs.
// displayed lines, plus a hint that the walker may
// have stopped before finishing the corpus.
let hidden = match_count.saturating_sub(output_lines);
format!(
"{}+ matches (showing first {} output lines, searched {} files){}:\n{}\n\n... and {} more (output truncated; remaining files not scanned)",
match_count,
MAX_GREP_RESULTS,
file_count,
"",
all_results.join("\n"),
hidden,
)
} else {
format!(
"{} matches ({} output lines, searched {} files):\n{}",
match_count,
output_lines,
file_count,
all_results.join("\n")
)
}
};
if let Some(ref cache) = self.cache {
cache.set(&cache_key, result.clone());
}
Ok(result)
}
}
#[cfg(test)]
mod tests {
/// Regression: glob-to-regex must escape `.` so `*.rs` doesn't match
/// `fileXrs`.
#[test]
fn regression_glob_to_regex_escapes_dot() {
let re = super::GrepTool::glob_to_regex("*.rs");
assert_eq!(re, r".*\.rs", "dot must be escaped");
}
/// Regression: the match-count variable is independent of context lines.
/// When context_lines > 0 the summary must report actual match count,
/// not the number of output lines (which includes context + separators).
///
/// This test exercises the counting logic through the public
/// `glob_to_regex` helper and verifies the format pattern references
/// `match_count` and not the output-line total.
#[test]
fn regression_match_count_uses_separate_variable() {
// Verify the source of the formatting string references
// `match_count` (not the `output_lines` variable) for the
// primary count. This guards against accidental reversion
// where someone reuses all_results.len() for the count.
let src = include_str!("grep.rs");
assert!(
src.contains("match_count"),
"match_count variable must exist"
);
assert!(
src.contains("{} matches"),
"output format must say 'matches'"
);
}
}