Skip to main content

aidaemon_tools/
search_files.rs

1//! `search_files`: a budgeted, breadth-first search by filename and content,
2//! through an [`ExecutionBackend`](crate::backend::ExecutionBackend).
3
4use std::sync::Arc;
5
6use aidaemon_core::{AccessManifest, ToolAnnotations};
7use async_trait::async_trait;
8use globset::{Glob, GlobMatcher};
9use regex::{Regex, RegexBuilder};
10use serde_json::{Value, json};
11
12use crate::backend::{BackendFileType, BackendPath};
13use crate::fs::{DEFAULT_IGNORE_DIRS, FilePolicy, SharedBackend, ToolText, workspace_parts};
14use crate::outcome::{OutcomeTool, core_tool};
15use crate::semantics::{
16    ToolCallContext, ToolCallOutcome, ToolCallSemantics, ToolCapabilities, ToolRole,
17    ToolTargetHintKind, ToolVerificationMode,
18};
19use crate::workspace::Workspace;
20
21pub struct SearchFiles {
22    backend: SharedBackend,
23    policy: Arc<dyn FilePolicy>,
24    text: ToolText,
25}
26
27impl SearchFiles {
28    /// A tool confined to `workspace`.
29    pub fn new(workspace: Workspace) -> Self {
30        let (backend, policy) = workspace_parts(workspace);
31        Self::on_backend(backend, policy)
32    }
33
34    /// A tool working through `backend` under an application's `policy`.
35    pub fn on_backend(backend: SharedBackend, policy: Arc<dyn FilePolicy>) -> Self {
36        Self {
37            backend,
38            policy,
39            text: ToolText {
40                short: "Search for files by name pattern or content regex".into(),
41                schema: "Search for files by name pattern (glob) and/or content (regex). Skips \
42                         .git, node_modules, target and similar directories."
43                    .into(),
44            },
45        }
46    }
47
48    /// Replace the model-facing descriptions.
49    pub fn with_text(mut self, text: ToolText) -> Self {
50        self.text = text;
51        self
52    }
53}
54
55const MAX_RESULTS: usize = 200;
56const DEFAULT_MAX_RESULTS: usize = 50;
57const MAX_FILES_SCANNED: usize = 10_000;
58const MAX_DEPTH: usize = 20;
59/// Total directory entries one walk may visit before returning a partial
60/// result. Keeps whole-home searches fast instead of watchdog-fatal.
61const MAX_ENTRIES_VISITED: usize = 150_000;
62const MAX_CONTENT_SEARCH_FILE_SIZE: u64 = 1024 * 1024; // 1 MiB per file
63/// Matching lines shown per file unless `max_per_file` asks for more.
64const DEFAULT_MATCHES_PER_FILE: usize = 5;
65const MAX_MATCHES_PER_FILE: usize = 50;
66/// The most `context_lines` a call may ask for around each match.
67const MAX_CONTEXT_LINES: usize = 5;
68
69#[async_trait]
70impl OutcomeTool for SearchFiles {
71    fn name(&self) -> &str {
72        "search_files"
73    }
74
75    fn description(&self) -> &str {
76        &self.text.short
77    }
78
79    fn schema(&self) -> Value {
80        json!({
81            "name": "search_files",
82            "description": self.text.schema,
83            "parameters": {
84                "type": "object",
85                "properties": {
86                    "pattern": {
87                        "type": "string",
88                        "description": "Regex pattern to search file contents for"
89                    },
90                    "glob": {
91                        "type": "string",
92                        "description": "Filename glob pattern (e.g., '*.rs', '*.ts', 'Cargo.*')"
93                    },
94                    "path": {
95                        "type": "string",
96                        "description": "Directory to search in, or one file to search (default: current directory)"
97                    },
98                    "max_results": {
99                        "type": "integer",
100                        "description": "Maximum files to return (default: 50, max: 200)"
101                    },
102                    "max_per_file": {
103                        "type": "integer",
104                        "minimum": 1,
105                        "description": "Matching lines shown per file (default: 5, max: 50); the rest are counted"
106                    },
107                    "context_lines": {
108                        "type": "integer",
109                        "minimum": 0,
110                        "description": "Lines of context shown before and after each match (default: 0, max: 5)"
111                    },
112                    "case_insensitive": {
113                        "type": "boolean",
114                        "description": "Match the pattern regardless of letter case (default: false)"
115                    }
116                },
117                "additionalProperties": false
118            }
119        })
120    }
121
122    async fn execute(
123        &self,
124        arguments: &str,
125        facts: &ToolCallContext,
126    ) -> anyhow::Result<ToolCallOutcome> {
127        self.run(arguments, facts)
128            .await
129            .map(ToolCallOutcome::from_output)
130    }
131}
132
133core_tool!(
134    SearchFiles,
135    annotations: ToolAnnotations::READ_ONLY,
136    access: |this, arguments| AccessManifest {
137        reads: vec![this.policy.declare_path(
138            arguments.get("path").and_then(Value::as_str).unwrap_or(".")
139        )],
140        ..Default::default()
141    }
142);
143
144impl SearchFiles {
145    /// Run one call with the dispatcher's `facts`.
146    pub(crate) async fn run(
147        &self,
148        arguments: &str,
149        facts: &ToolCallContext,
150    ) -> anyhow::Result<String> {
151        let args: Value = serde_json::from_str(arguments)?;
152        let content_pattern = args["pattern"].as_str();
153        let glob_pattern = args["glob"].as_str();
154        let path_value = args.get("path").and_then(|v| v.as_str());
155        let path_str = path_value.unwrap_or(".");
156        let used_default_path = path_value.is_none();
157        let max_results = args["max_results"]
158            .as_u64()
159            .map(|n| (n as usize).min(MAX_RESULTS))
160            .unwrap_or(DEFAULT_MAX_RESULTS);
161        let shape = MatchShape {
162            per_file: args["max_per_file"]
163                .as_u64()
164                .map(|n| (n as usize).clamp(1, MAX_MATCHES_PER_FILE))
165                .unwrap_or(DEFAULT_MATCHES_PER_FILE),
166            context: args["context_lines"]
167                .as_u64()
168                .map(|n| (n as usize).min(MAX_CONTEXT_LINES))
169                .unwrap_or(0),
170        };
171        let case_insensitive = args["case_insensitive"].as_bool().unwrap_or(false);
172
173        if content_pattern.is_none() && glob_pattern.is_none() {
174            anyhow::bail!(
175                "At least one of 'pattern' (content regex) or 'glob' (filename pattern) is required"
176            );
177        }
178
179        let backend = self.backend.clone();
180        let mut search_dir = backend.resolve_path(path_str).await?;
181        if backend.metadata(&search_dir).await.is_err() {
182            // Paths copy-pasted from prose or earlier tool output often carry
183            // trailing punctuation ("…/projects)" from a parenthesized
184            // mention). Only fall back when the literal path is missing and
185            // the trimmed one is a real directory.
186            let trimmed = path_str
187                .trim_end()
188                .trim_end_matches([')', ':', ',', ';', '.'])
189                .trim_end();
190            if trimmed != path_str
191                && !trimmed.is_empty()
192                && let Ok(candidate) = backend.resolve_path(trimmed).await
193                && backend
194                    .metadata(&candidate)
195                    .await
196                    .is_ok_and(|metadata| metadata.is_dir())
197            {
198                search_dir = candidate;
199            }
200        }
201        let search_metadata = backend
202            .metadata(&search_dir)
203            .await
204            .map_err(|_| crate::TargetNotFound(format!("Directory not found: {search_dir}")))?;
205        // One file is searched on its own (live 2026-11-14 to 11-20: a file
206        // `path` failed "Not a directory" nine times and was redone with grep).
207        let single_file = !search_metadata.is_dir();
208        let collaboration_root = if let Some(root) = facts.workspace_collaboration_root.as_deref() {
209            anyhow::ensure!(
210                backend.kind() == crate::backend::BackendKind::Local,
211                "Workspace collaboration requires a local execution backend"
212            );
213            let resolved_root = backend.resolve_path(root).await?;
214            let canonical_root = backend.canonicalize(&resolved_root).await?;
215            anyhow::ensure!(
216                canonical_root.as_str() == root,
217                "Delegated project path changed after authorization"
218            );
219            let canonical_search = backend.canonicalize(&search_dir).await?;
220            anyhow::ensure!(
221                std::path::Path::new(canonical_search.as_str())
222                    .starts_with(std::path::Path::new(canonical_root.as_str())),
223                "Search path is outside the delegated project"
224            );
225            search_dir = canonical_search;
226            Some(canonical_root)
227        } else {
228            None
229        };
230
231        let content_regex = if let Some(pat) = content_pattern {
232            Some(
233                RegexBuilder::new(pat)
234                    .case_insensitive(case_insensitive)
235                    .build()
236                    .map_err(|e| anyhow::anyhow!("Invalid regex '{}': {}", pat, e))?,
237            )
238        } else {
239            None
240        };
241
242        let glob_matcher = if let Some(g) = glob_pattern {
243            Some(compile_glob(g)?)
244        } else {
245            None
246        };
247
248        let mut results = Vec::new();
249        let mut stats = SearchStats::default();
250
251        if single_file {
252            if self
253                .policy
254                .is_sensitive(std::path::Path::new(search_dir.as_str()))
255            {
256                anyhow::bail!("Refusing to search a protected file: {}", search_dir);
257            }
258            search_one_file(
259                &backend,
260                &search_dir,
261                search_metadata.len,
262                &content_regex,
263                &glob_matcher,
264                shape,
265                &mut results,
266                &mut stats,
267            )
268            .await;
269        } else {
270            walk_dir(
271                backend,
272                self.policy.as_ref(),
273                &search_dir,
274                &content_regex,
275                &glob_matcher,
276                max_results,
277                MAX_ENTRIES_VISITED,
278                collaboration_root.as_ref(),
279                shape,
280                &mut results,
281                &mut stats,
282            )
283            .await;
284        }
285
286        let default_path_note = used_default_path.then(|| {
287            format!(
288                "Note: no 'path' was provided, so search_files defaulted to current directory: {}",
289                search_dir
290            )
291        });
292
293        if results.is_empty() {
294            // The scanned dir must end its line cleanly: models copy-paste it
295            // into later calls, and a glued ")" produces invalid paths.
296            let mut output = format!(
297                "No matches found. {} files scanned in {}",
298                stats.files_scanned, search_dir
299            );
300            if stats.truncated {
301                output.push('\n');
302                output.push_str(&truncation_note(&stats));
303            }
304            if let Some(note) = &default_path_note {
305                output.push('\n');
306                output.push_str(note);
307                // The model gave no 'path' and found nothing in cwd — point it
308                // at common user locations so it retries instead of giving up.
309                output.push('\n');
310                output.push_str(
311                    "The file may live elsewhere. Retry with an explicit 'path' — common user locations: ~/Downloads, ~/Desktop, ~/Documents, or ~ to search the whole home directory.",
312                );
313                output.push('\n');
314                output.push_str(&whole_machine_search_hint(self.policy.shell_tool_name()));
315            }
316            if stats.oversized_files_skipped > 0 {
317                output.push('\n');
318                output.push_str(&oversized_note(stats.oversized_files_skipped));
319            }
320            return Ok(output);
321        }
322
323        let mut output = String::new();
324        if let Some(note) = &default_path_note {
325            output.push_str(note);
326            output.push_str("\n\n");
327        }
328        // Content matches are counted as lines, files as files: "1 match"
329        // over ten matching lines read as a contradiction (live 2026-11-21).
330        let matching_lines: usize = results
331            .iter()
332            .map(|result| result.lines.iter().filter(|line| line.2).count() + result.more)
333            .sum();
334        let files = format!(
335            "{} file{}",
336            results.len(),
337            if results.len() == 1 { "" } else { "s" }
338        );
339        let found = if matching_lines > 0 {
340            format!(
341                "Found {matching_lines} matching line{} in {files}",
342                if matching_lines == 1 { "" } else { "s" }
343            )
344        } else {
345            format!("Found {files}")
346        };
347        output.push_str(&format!(
348            "{found}. {} files scanned in {}\n\n",
349            stats.files_scanned, search_dir
350        ));
351        if stats.oversized_files_skipped > 0 {
352            output.push_str(&oversized_note(stats.oversized_files_skipped));
353            output.push_str("\n\n");
354        }
355
356        for result in &results {
357            output.push_str(&result.format());
358            output.push('\n');
359        }
360
361        if results.len() >= max_results {
362            output.push_str(&format!(
363                "\n(Results capped at {}. Use a more specific pattern or glob to narrow results.)",
364                max_results
365            ));
366        }
367
368        Ok(output)
369    }
370}
371
372impl crate::semantics::ToolSemantics for SearchFiles {
373    fn dispatch_facts(&self) -> crate::semantics::ToolDispatchFacts {
374        crate::semantics::ToolDispatchFacts {
375            offering: crate::semantics::Offering::Core,
376            same_tool_streak: crate::semantics::SameToolStreak::Versatile,
377            recap: crate::semantics::RecapKind::Search,
378            activity: crate::semantics::ToolActivity::Fixed(
379                aidaemon_core::card::ActivityKind::Search,
380            ),
381            project_dir_argument: crate::semantics::ProjectDirArgument::SearchRoot,
382            evidence: crate::semantics::EvidenceSource::FileSearch,
383            semantic_scope: Some(crate::semantics::ToolSemanticScope::LocalWorkspace),
384            status_label: Some("searching files"),
385            ..Default::default()
386        }
387    }
388
389    fn tool_role(&self) -> ToolRole {
390        ToolRole::Action
391    }
392
393    fn capabilities(&self) -> ToolCapabilities {
394        ToolCapabilities::READ_ONLY
395    }
396
397    fn output_trust(
398        &self,
399        arguments: &str,
400        roots: &crate::semantics::TrustRoots<'_>,
401    ) -> aidaemon_core::SourceTrust {
402        // A search with no `path` runs in the working directory.
403        let args = serde_json::from_str::<Value>(arguments).ok();
404        let path = match args.as_ref().map(|args| args.get("path")) {
405            Some(None) | Some(Some(Value::Null)) => Some("."),
406            Some(Some(value)) => value.as_str(),
407            None => None,
408        };
409        match path {
410            Some(path) if roots.contains(path) => aidaemon_core::SourceTrust::Trusted,
411            _ => aidaemon_core::SourceTrust::Untrusted,
412        }
413    }
414
415    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
416        let path = serde_json::from_str::<Value>(arguments)
417            .ok()
418            .and_then(|args| {
419                args.get("path")
420                    .and_then(|value| value.as_str())
421                    .map(str::to_string)
422            })
423            .unwrap_or_default();
424
425        ToolCallSemantics::observation()
426            .with_verification_mode(ToolVerificationMode::ResultContent)
427            .with_target_hint(ToolTargetHintKind::Path, path)
428    }
429}
430
431fn oversized_note(count: usize) -> String {
432    format!(
433        "Skipped {} oversized file{} larger than {} bytes during content search.",
434        count,
435        if count == 1 { "" } else { "s" },
436        MAX_CONTENT_SEARCH_FILE_SIZE
437    )
438}
439
440struct SearchResult {
441    path: BackendPath,
442    /// (line number, text, whether the line matched): matches and, with
443    /// `context_lines`, the lines around them.
444    lines: Vec<(usize, String, bool)>,
445    /// Matching lines past `max_per_file`, counted, not shown.
446    more: usize,
447}
448
449/// How much of each file's matches a result shows.
450#[derive(Clone, Copy)]
451struct MatchShape {
452    per_file: usize,
453    context: usize,
454}
455
456/// A file's shown lines before its path is known.
457struct FoundLines {
458    lines: Vec<(usize, String, bool)>,
459    more: usize,
460}
461
462impl FoundLines {
463    fn at(self, path: BackendPath) -> SearchResult {
464        SearchResult {
465            path,
466            lines: self.lines,
467            more: self.more,
468        }
469    }
470}
471
472/// The lines of `bytes` that match `re`, the first `shape.per_file` shown
473/// with `shape.context` lines around them (overlapping context merged), the
474/// rest counted. `None` when nothing matches.
475fn search_content(bytes: &[u8], re: &Regex, shape: MatchShape) -> Option<FoundLines> {
476    let content = String::from_utf8_lossy(bytes);
477    let all: Vec<&str> = content.lines().collect();
478    let matched: Vec<usize> = all
479        .iter()
480        .enumerate()
481        .filter(|(_, line)| re.is_match(line))
482        .map(|(index, _)| index)
483        .collect();
484    if matched.is_empty() {
485        return None;
486    }
487    let shown = &matched[..matched.len().min(shape.per_file)];
488    let mut keep = std::collections::BTreeSet::new();
489    for &index in shown {
490        let from = index.saturating_sub(shape.context);
491        let to = (index + shape.context).min(all.len().saturating_sub(1));
492        keep.extend(from..=to);
493    }
494    let shown_set: std::collections::BTreeSet<usize> = shown.iter().copied().collect();
495    Some(FoundLines {
496        lines: keep
497            .into_iter()
498            .map(|index| {
499                (
500                    index + 1,
501                    all[index].to_string(),
502                    shown_set.contains(&index),
503                )
504            })
505            .collect(),
506        more: matched.len() - shown.len(),
507    })
508}
509
510/// A search whose `path` is one file: that file alone, by the same rules a
511/// walk applies to each file it finds.
512#[allow(clippy::too_many_arguments)]
513async fn search_one_file(
514    backend: &SharedBackend,
515    path: &BackendPath,
516    len: u64,
517    content_regex: &Option<Regex>,
518    glob_matcher: &Option<GlobMatcher>,
519    shape: MatchShape,
520    results: &mut Vec<SearchResult>,
521    stats: &mut SearchStats,
522) {
523    let file_name = path.file_name().unwrap_or_default().to_string();
524    if glob_matcher
525        .as_ref()
526        .is_some_and(|matcher| !matcher.is_match(&file_name))
527    {
528        return;
529    }
530    stats.files_scanned += 1;
531    let Some(content_re) = content_regex else {
532        results.push(SearchResult {
533            path: path.clone(),
534            lines: Vec::new(),
535            more: 0,
536        });
537        return;
538    };
539    if len > MAX_CONTENT_SEARCH_FILE_SIZE {
540        stats.oversized_files_skipped += 1;
541        return;
542    }
543    if let Ok(bytes) = backend.read(path).await
544        && let Some(found) = search_content(&bytes, content_re, shape)
545    {
546        results.push(found.at(path.clone()));
547    }
548}
549
550#[derive(Default)]
551struct SearchStats {
552    files_scanned: usize,
553    oversized_files_skipped: usize,
554    /// Directory entries visited during the walk (files + dirs, matched or not).
555    entries_visited: usize,
556    /// True when the walk stopped early (entry or wall-clock budget) — the
557    /// "no matches" result is then partial, not definitive.
558    truncated: bool,
559}
560
561/// Fast whole-machine lookup hint. Crawling the entire disk file-by-file is
562/// slow and permission-fenced; the OS file index answers in milliseconds.
563fn whole_machine_search_hint(shell: &str) -> String {
564    #[cfg(target_os = "macos")]
565    {
566        format!(
567            "For a whole-machine filename search, use the {shell} tool with Spotlight instead of crawling: mdfind -name \"<filename>\" (instant, indexed)."
568        )
569    }
570    #[cfg(not(target_os = "macos"))]
571    {
572        format!(
573            "For a whole-machine filename search, use the {shell} tool with the file index if available: locate \"<filename>\" (or plocate), falling back to find / -name."
574        )
575    }
576}
577
578/// Honest coverage note for a budget-truncated walk. Without it, "no matches"
579/// reads as definitive and the model stops looking.
580fn truncation_note(stats: &SearchStats) -> String {
581    format!(
582        "Note: the search stopped early after visiting {} directory entries — coverage was partial, NOT exhaustive. The file may still exist. Retry with a narrower 'path' (e.g. ~/Downloads, ~/Documents) for a complete scan of that directory.",
583        stats.entries_visited
584    )
585}
586
587impl SearchResult {
588    fn format(&self) -> String {
589        let path_str = self.path.display();
590        if self.lines.is_empty() {
591            path_str.to_string()
592        } else {
593            // grep's convention: ':' after a matching line's number, '-'
594            // after a context line's, "--" between separate blocks.
595            let mut s = format!("{}:", path_str);
596            let mut previous: Option<usize> = None;
597            for (line_num, line, matched) in &self.lines {
598                // Blocks are separated only when context lines make them
599                // blocks; plain matches need no separator.
600                let has_context = self.lines.iter().any(|line| !line.2);
601                if has_context && previous.is_some_and(|previous| *line_num > previous + 1) {
602                    s.push_str("\n  --");
603                }
604                let truncated = crate::text::truncate_str(line, 203);
605                let mark = if *matched { ':' } else { '-' };
606                s.push_str(&format!("\n  {line_num:>4}{mark} {truncated}"));
607                previous = Some(*line_num);
608            }
609            if self.more > 0 {
610                s.push_str(&format!(
611                    "\n  (+{} more match{} in this file; raise max_per_file to see them)",
612                    self.more,
613                    if self.more == 1 { "" } else { "es" }
614                ));
615            }
616            s
617        }
618    }
619}
620
621fn compile_glob(glob: &str) -> anyhow::Result<GlobMatcher> {
622    Glob::new(glob)
623        .map(|glob| glob.compile_matcher())
624        .map_err(|e| anyhow::anyhow!("Invalid glob pattern '{}': {}", glob, e))
625}
626
627/// Wall-clock budget for one search walk. Large trees (a whole home
628/// directory) must return a partial-but-fast answer, never hang until the
629/// tool watchdog kills the call.
630const MAX_WALK_MILLIS: u128 = 15_000;
631
632/// Run one filesystem call inside the walk's time budget. `None`: the budget
633/// ran out first. A directory can hang (a stalled mount, an OS permission
634/// prompt), and the check between entries never runs while it does.
635async fn within_budget<T>(
636    started: std::time::Instant,
637    call: impl std::future::Future<Output = T>,
638) -> Option<T> {
639    let budget = std::time::Duration::from_millis(MAX_WALK_MILLIS as u64);
640    tokio::time::timeout(budget.saturating_sub(started.elapsed()), call)
641        .await
642        .ok()
643}
644
645/// Breadth-first, budgeted directory walk.
646///
647/// BFS matters: a file in a shallow user directory (~/Downloads/x.pdf) is
648/// found within the first few thousand entries even when a sibling tree
649/// (~/Library) holds hundreds of thousands — depth-first got lost in the
650/// deep tree and timed out. `max_entries` bounds total entries visited;
651/// exceeding it (or the time budget) sets `stats.truncated`.
652#[allow(clippy::too_many_arguments)]
653async fn walk_dir(
654    backend: SharedBackend,
655    policy: &dyn FilePolicy,
656    root: &BackendPath,
657    content_regex: &Option<Regex>,
658    glob_matcher: &Option<GlobMatcher>,
659    max_results: usize,
660    max_entries: usize,
661    collaboration_root: Option<&BackendPath>,
662    shape: MatchShape,
663    results: &mut Vec<SearchResult>,
664    stats: &mut SearchStats,
665) {
666    let started = std::time::Instant::now();
667    let mut queue: std::collections::VecDeque<(BackendPath, usize)> =
668        std::collections::VecDeque::new();
669    queue.push_back((root.clone(), 0));
670
671    while let Some((dir, depth)) = queue.pop_front() {
672        if results.len() >= max_results || stats.files_scanned >= MAX_FILES_SCANNED {
673            return;
674        }
675
676        let Some(listed) = within_budget(started, backend.read_dir(&dir)).await else {
677            stats.truncated = true;
678            return;
679        };
680        let entries = match listed {
681            Ok(e) => e,
682            Err(_) => continue,
683        };
684
685        for entry in entries {
686            if results.len() >= max_results || stats.files_scanned >= MAX_FILES_SCANNED {
687                return;
688            }
689            stats.entries_visited += 1;
690            if stats.entries_visited >= max_entries
691                || started.elapsed().as_millis() > MAX_WALK_MILLIS
692            {
693                stats.truncated = true;
694                return;
695            }
696
697            let mut path = entry.path;
698            if let Some(root) = collaboration_root {
699                if policy.is_sensitive(std::path::Path::new(path.as_str())) {
700                    continue;
701                }
702                let Ok(canonical) = backend.canonicalize(&path).await else {
703                    continue;
704                };
705                if !std::path::Path::new(canonical.as_str())
706                    .starts_with(std::path::Path::new(root.as_str()))
707                    || policy.is_sensitive(std::path::Path::new(canonical.as_str()))
708                {
709                    continue;
710                }
711                path = canonical;
712            }
713            let file_name = path.file_name().unwrap_or_default().to_string();
714
715            if entry.metadata.file_type == BackendFileType::Directory {
716                if depth < MAX_DEPTH
717                    && !DEFAULT_IGNORE_DIRS.contains(&file_name.as_str())
718                    && !file_name.starts_with('.')
719                {
720                    queue.push_back((path, depth + 1));
721                }
722                continue;
723            }
724
725            if entry.metadata.file_type != BackendFileType::File {
726                continue;
727            }
728
729            // Check glob match on filename
730            if let Some(matcher) = glob_matcher
731                && !matcher.is_match(&file_name)
732            {
733                continue;
734            }
735
736            stats.files_scanned += 1;
737
738            // If content pattern specified, search contents
739            if let Some(content_re) = content_regex {
740                if entry.metadata.len > MAX_CONTENT_SEARCH_FILE_SIZE {
741                    stats.oversized_files_skipped += 1;
742                    continue;
743                }
744                let Some(read) = within_budget(started, backend.read(&path)).await else {
745                    stats.truncated = true;
746                    return;
747                };
748                if let Ok(bytes) = read
749                    && let Some(found) = search_content(&bytes, content_re, shape)
750                {
751                    results.push(found.at(path));
752                }
753            } else {
754                // Glob-only: just list the file
755                results.push(SearchResult {
756                    path,
757                    lines: Vec::new(),
758                    more: 0,
759                });
760            }
761        }
762    }
763}
764
765#[cfg(test)]
766mod tests {
767    use super::*;
768    use crate::fs::{WorkspaceBackend, WorkspaceFilePolicy};
769
770    #[tokio::test(start_paused = true)]
771    async fn a_call_that_never_answers_ends_with_the_budget() {
772        let started = std::time::Instant::now();
773        let hung = within_budget(started, std::future::pending::<()>()).await;
774        assert!(hung.is_none());
775        let answered = within_budget(started, std::future::ready(7)).await;
776        assert_eq!(answered, Some(7));
777    }
778
779    fn parts(path: &std::path::Path) -> (SharedBackend, WorkspaceFilePolicy) {
780        let workspace = Workspace::new(path).unwrap();
781        (
782            Arc::new(WorkspaceBackend::new(workspace.clone())),
783            WorkspaceFilePolicy::new(workspace),
784        )
785    }
786
787    #[tokio::test]
788    async fn breadth_first_walk_finds_shallow_file_under_tight_budget() {
789        // A file two levels down (~/Downloads/x.pdf shape) must be found
790        // before the walk exhausts its budget inside a deep sibling tree —
791        // the failure mode that made home-directory searches time out.
792        let root = tempfile::tempdir().unwrap();
793        let deep = root.path().join("aaa_huge").join("lvl1");
794        std::fs::create_dir_all(&deep).unwrap();
795        for i in 0..300 {
796            std::fs::write(deep.join(format!("noise_{i}.txt")), "x").unwrap();
797        }
798        let shallow = root.path().join("bbb_docs");
799        std::fs::create_dir(&shallow).unwrap();
800        std::fs::write(shallow.join("target.pdf"), "pdf").unwrap();
801
802        let glob = compile_glob("*target.pdf").unwrap();
803        let mut results = Vec::new();
804        let mut stats = SearchStats::default();
805        let (backend, policy) = parts(root.path());
806        let root_path = backend
807            .resolve_path(&root.path().to_string_lossy())
808            .await
809            .unwrap();
810        walk_dir(
811            backend,
812            &policy,
813            &root_path,
814            &None,
815            &Some(glob),
816            10,
817            50, // entry budget far smaller than the deep tree
818            None,
819            MatchShape {
820                per_file: DEFAULT_MATCHES_PER_FILE,
821                context: 0,
822            },
823            &mut results,
824            &mut stats,
825        )
826        .await;
827
828        assert_eq!(results.len(), 1, "shallow file must be found under budget");
829        assert!(results[0].path.as_str().ends_with("target.pdf"));
830    }
831
832    #[tokio::test]
833    async fn search_files_finds_unrelated_project_config_toml() {
834        let root = tempfile::tempdir().unwrap();
835        std::fs::write(root.path().join("config.toml"), "title = \"a\"").unwrap();
836        let glob = compile_glob("*config.toml").unwrap();
837        let mut results = Vec::new();
838        let mut stats = SearchStats::default();
839        let (backend, policy) = parts(root.path());
840        let root_path = backend
841            .resolve_path(&root.path().to_string_lossy())
842            .await
843            .unwrap();
844        walk_dir(
845            backend,
846            &policy,
847            &root_path,
848            &None,
849            &Some(glob),
850            10,
851            50,
852            None,
853            MatchShape {
854                per_file: DEFAULT_MATCHES_PER_FILE,
855                context: 0,
856            },
857            &mut results,
858            &mut stats,
859        )
860        .await;
861        assert_eq!(results.len(), 1);
862    }
863
864    #[tokio::test]
865    async fn walk_truncates_at_entry_budget_and_reports_it() {
866        let root = tempfile::tempdir().unwrap();
867        for i in 0..50 {
868            std::fs::write(root.path().join(format!("file_{i}.txt")), "x").unwrap();
869        }
870
871        let glob = compile_glob("*.zzz").unwrap();
872        let mut results = Vec::new();
873        let mut stats = SearchStats::default();
874        let (backend, policy) = parts(root.path());
875        let root_path = backend
876            .resolve_path(&root.path().to_string_lossy())
877            .await
878            .unwrap();
879        walk_dir(
880            backend,
881            &policy,
882            &root_path,
883            &None,
884            &Some(glob),
885            10,
886            10,
887            None,
888            MatchShape {
889                per_file: DEFAULT_MATCHES_PER_FILE,
890                context: 0,
891            },
892            &mut results,
893            &mut stats,
894        )
895        .await;
896
897        assert!(stats.truncated, "budget exhaustion must set truncated");
898        assert!(results.is_empty());
899    }
900
901    #[tokio::test]
902    async fn truncated_search_output_carries_honest_note() {
903        // The output must tell the model coverage was partial — otherwise
904        // "no matches" reads as a definitive answer and it gives up.
905        let dir = tempfile::tempdir().unwrap();
906        for i in 0..30 {
907            std::fs::write(dir.path().join(format!("file_{i}.txt")), "x").unwrap();
908        }
909        // max_results=1 path is fine; we exercise the public call with a
910        // glob that cannot match, against a tree we know exceeds the test
911        // budget via the internal walker — so use walk_dir + render check
912        // indirectly: the call() budget is large, so instead assert the
913        // note constant is wired by checking a tiny-budget walk + format.
914        let glob = compile_glob("*.zzz").unwrap();
915        let mut results = Vec::new();
916        let mut stats = SearchStats::default();
917        let (backend, policy) = parts(dir.path());
918        let root_path = backend
919            .resolve_path(&dir.path().to_string_lossy())
920            .await
921            .unwrap();
922        walk_dir(
923            backend,
924            &policy,
925            &root_path,
926            &None,
927            &Some(glob),
928            10,
929            5,
930            None,
931            MatchShape {
932                per_file: DEFAULT_MATCHES_PER_FILE,
933                context: 0,
934            },
935            &mut results,
936            &mut stats,
937        )
938        .await;
939        assert!(stats.truncated);
940        let note = truncation_note(&stats);
941        assert!(note.contains("partial"), "note: {note}");
942        assert!(
943            note.contains("path"),
944            "note must steer toward narrower path"
945        );
946    }
947
948    #[test]
949    fn test_glob_to_regex() {
950        let re = compile_glob("*.rs").unwrap();
951        assert!(re.is_match("main.rs"));
952        assert!(!re.is_match("main.py"));
953
954        let re = compile_glob("Cargo.*").unwrap();
955        assert!(re.is_match("Cargo.toml"));
956        assert!(re.is_match("Cargo.lock"));
957    }
958
959    #[test]
960    fn glob_matches_literal_regex_metacharacters_and_commas() {
961        let re = compile_glob("a+b.txt").unwrap();
962        assert!(re.is_match("a+b.txt"));
963        assert!(!re.is_match("aaab.txt"));
964
965        let re = compile_glob("report,final.txt").unwrap();
966        assert!(re.is_match("report,final.txt"));
967        assert!(!re.is_match("report-draft.txt"));
968        assert!(!re.is_match("final.txt"));
969    }
970
971    /// The tool over a temp folder holding a synthetic source file.
972    async fn search(args: Value) -> String {
973        let root = tempfile::tempdir().unwrap();
974        let mut text = String::new();
975        for i in 1..=30 {
976            if i % 3 == 0 {
977                text.push_str(&format!("let Value_{i} = compute({i});\n"));
978            } else {
979                text.push_str(&format!("// plain line {i}\n"));
980            }
981        }
982        std::fs::write(root.path().join("lib.rs"), &text).unwrap();
983        std::fs::write(root.path().join("other.rs"), "nothing here\n").unwrap();
984        let tool = SearchFiles::new(Workspace::new(root.path()).unwrap());
985        let mut args = args;
986        if let Some(name) = args.get("path").and_then(Value::as_str).map(str::to_string) {
987            args["path"] = json!(root.path().join(name).to_string_lossy());
988        } else {
989            args["path"] = json!(root.path().to_string_lossy());
990        }
991        tool.run(&args.to_string(), &ToolCallContext::default())
992            .await
993            .unwrap()
994    }
995
996    /// A file path searches that file (it used to fail "Not a directory").
997    #[tokio::test]
998    async fn a_file_path_searches_that_file() {
999        let out = search(json!({"pattern": "compute", "path": "lib.rs"})).await;
1000        assert!(out.contains("lib.rs:"), "{out}");
1001        assert!(out.contains("   3: let Value_3"), "{out}");
1002        assert!(!out.contains("other.rs"), "{out}");
1003    }
1004
1005    /// Matches past the per-file limit are counted, and `max_per_file`
1006    /// shows more.
1007    #[tokio::test]
1008    async fn matches_past_the_limit_are_counted() {
1009        let out = search(json!({"pattern": "compute"})).await;
1010        assert!(out.contains("  15: let Value_15"), "{out}");
1011        assert!(!out.contains("Value_18"), "{out}");
1012        assert!(out.contains("(+5 more matches in this file"), "{out}");
1013        let out = search(json!({"pattern": "compute", "max_per_file": 50})).await;
1014        assert!(
1015            out.contains("Value_30") && !out.contains("more match"),
1016            "{out}"
1017        );
1018    }
1019
1020    /// Context lines come before and after each match, marked like grep.
1021    #[tokio::test]
1022    async fn context_lines_surround_each_match() {
1023        let out = search(json!({"pattern": "Value_3 ", "context_lines": 1})).await;
1024        assert!(out.contains("   2- // plain line 2"), "{out}");
1025        assert!(out.contains("   3: let Value_3 "), "{out}");
1026        assert!(out.contains("   4- // plain line 4"), "{out}");
1027    }
1028
1029    /// The pattern can ignore letter case.
1030    #[tokio::test]
1031    async fn the_pattern_can_ignore_case() {
1032        let out = search(json!({"pattern": "value_6"})).await;
1033        assert!(out.starts_with("No matches"), "{out}");
1034        let out = search(json!({"pattern": "value_6", "case_insensitive": true})).await;
1035        assert!(out.contains("   6: let Value_6"), "{out}");
1036    }
1037}