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 {
395            read_only: true,
396            external_side_effect: false,
397            needs_approval: false,
398            idempotent: true,
399            high_impact_write: false,
400        }
401    }
402
403    fn output_trust(
404        &self,
405        arguments: &str,
406        roots: &crate::semantics::TrustRoots<'_>,
407    ) -> aidaemon_core::SourceTrust {
408        // A search with no `path` runs in the working directory.
409        let args = serde_json::from_str::<Value>(arguments).ok();
410        let path = match args.as_ref().map(|args| args.get("path")) {
411            Some(None) | Some(Some(Value::Null)) => Some("."),
412            Some(Some(value)) => value.as_str(),
413            None => None,
414        };
415        match path {
416            Some(path) if roots.contains(path) => aidaemon_core::SourceTrust::Trusted,
417            _ => aidaemon_core::SourceTrust::Untrusted,
418        }
419    }
420
421    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
422        let path = serde_json::from_str::<Value>(arguments)
423            .ok()
424            .and_then(|args| {
425                args.get("path")
426                    .and_then(|value| value.as_str())
427                    .map(str::to_string)
428            })
429            .unwrap_or_default();
430
431        ToolCallSemantics::observation()
432            .with_verification_mode(ToolVerificationMode::ResultContent)
433            .with_target_hint(ToolTargetHintKind::Path, path)
434    }
435}
436
437fn oversized_note(count: usize) -> String {
438    format!(
439        "Skipped {} oversized file{} larger than {} bytes during content search.",
440        count,
441        if count == 1 { "" } else { "s" },
442        MAX_CONTENT_SEARCH_FILE_SIZE
443    )
444}
445
446struct SearchResult {
447    path: BackendPath,
448    /// (line number, text, whether the line matched): matches and, with
449    /// `context_lines`, the lines around them.
450    lines: Vec<(usize, String, bool)>,
451    /// Matching lines past `max_per_file`, counted, not shown.
452    more: usize,
453}
454
455/// How much of each file's matches a result shows.
456#[derive(Clone, Copy)]
457struct MatchShape {
458    per_file: usize,
459    context: usize,
460}
461
462/// A file's shown lines before its path is known.
463struct FoundLines {
464    lines: Vec<(usize, String, bool)>,
465    more: usize,
466}
467
468impl FoundLines {
469    fn at(self, path: BackendPath) -> SearchResult {
470        SearchResult {
471            path,
472            lines: self.lines,
473            more: self.more,
474        }
475    }
476}
477
478/// The lines of `bytes` that match `re`, the first `shape.per_file` shown
479/// with `shape.context` lines around them (overlapping context merged), the
480/// rest counted. `None` when nothing matches.
481fn search_content(bytes: &[u8], re: &Regex, shape: MatchShape) -> Option<FoundLines> {
482    let content = String::from_utf8_lossy(bytes);
483    let all: Vec<&str> = content.lines().collect();
484    let matched: Vec<usize> = all
485        .iter()
486        .enumerate()
487        .filter(|(_, line)| re.is_match(line))
488        .map(|(index, _)| index)
489        .collect();
490    if matched.is_empty() {
491        return None;
492    }
493    let shown = &matched[..matched.len().min(shape.per_file)];
494    let mut keep = std::collections::BTreeSet::new();
495    for &index in shown {
496        let from = index.saturating_sub(shape.context);
497        let to = (index + shape.context).min(all.len().saturating_sub(1));
498        keep.extend(from..=to);
499    }
500    let shown_set: std::collections::BTreeSet<usize> = shown.iter().copied().collect();
501    Some(FoundLines {
502        lines: keep
503            .into_iter()
504            .map(|index| {
505                (
506                    index + 1,
507                    all[index].to_string(),
508                    shown_set.contains(&index),
509                )
510            })
511            .collect(),
512        more: matched.len() - shown.len(),
513    })
514}
515
516/// A search whose `path` is one file: that file alone, by the same rules a
517/// walk applies to each file it finds.
518#[allow(clippy::too_many_arguments)]
519async fn search_one_file(
520    backend: &SharedBackend,
521    path: &BackendPath,
522    len: u64,
523    content_regex: &Option<Regex>,
524    glob_matcher: &Option<GlobMatcher>,
525    shape: MatchShape,
526    results: &mut Vec<SearchResult>,
527    stats: &mut SearchStats,
528) {
529    let file_name = path.file_name().unwrap_or_default().to_string();
530    if glob_matcher
531        .as_ref()
532        .is_some_and(|matcher| !matcher.is_match(&file_name))
533    {
534        return;
535    }
536    stats.files_scanned += 1;
537    let Some(content_re) = content_regex else {
538        results.push(SearchResult {
539            path: path.clone(),
540            lines: Vec::new(),
541            more: 0,
542        });
543        return;
544    };
545    if len > MAX_CONTENT_SEARCH_FILE_SIZE {
546        stats.oversized_files_skipped += 1;
547        return;
548    }
549    if let Ok(bytes) = backend.read(path).await
550        && let Some(found) = search_content(&bytes, content_re, shape)
551    {
552        results.push(found.at(path.clone()));
553    }
554}
555
556#[derive(Default)]
557struct SearchStats {
558    files_scanned: usize,
559    oversized_files_skipped: usize,
560    /// Directory entries visited during the walk (files + dirs, matched or not).
561    entries_visited: usize,
562    /// True when the walk stopped early (entry or wall-clock budget) — the
563    /// "no matches" result is then partial, not definitive.
564    truncated: bool,
565}
566
567/// Fast whole-machine lookup hint. Crawling the entire disk file-by-file is
568/// slow and permission-fenced; the OS file index answers in milliseconds.
569fn whole_machine_search_hint(shell: &str) -> String {
570    #[cfg(target_os = "macos")]
571    {
572        format!(
573            "For a whole-machine filename search, use the {shell} tool with Spotlight instead of crawling: mdfind -name \"<filename>\" (instant, indexed)."
574        )
575    }
576    #[cfg(not(target_os = "macos"))]
577    {
578        format!(
579            "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."
580        )
581    }
582}
583
584/// Honest coverage note for a budget-truncated walk. Without it, "no matches"
585/// reads as definitive and the model stops looking.
586fn truncation_note(stats: &SearchStats) -> String {
587    format!(
588        "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.",
589        stats.entries_visited
590    )
591}
592
593impl SearchResult {
594    fn format(&self) -> String {
595        let path_str = self.path.display();
596        if self.lines.is_empty() {
597            path_str.to_string()
598        } else {
599            // grep's convention: ':' after a matching line's number, '-'
600            // after a context line's, "--" between separate blocks.
601            let mut s = format!("{}:", path_str);
602            let mut previous: Option<usize> = None;
603            for (line_num, line, matched) in &self.lines {
604                // Blocks are separated only when context lines make them
605                // blocks; plain matches need no separator.
606                let has_context = self.lines.iter().any(|line| !line.2);
607                if has_context && previous.is_some_and(|previous| *line_num > previous + 1) {
608                    s.push_str("\n  --");
609                }
610                let truncated = crate::util::truncate_str(line, 203);
611                let mark = if *matched { ':' } else { '-' };
612                s.push_str(&format!("\n  {line_num:>4}{mark} {truncated}"));
613                previous = Some(*line_num);
614            }
615            if self.more > 0 {
616                s.push_str(&format!(
617                    "\n  (+{} more match{} in this file; raise max_per_file to see them)",
618                    self.more,
619                    if self.more == 1 { "" } else { "es" }
620                ));
621            }
622            s
623        }
624    }
625}
626
627fn compile_glob(glob: &str) -> anyhow::Result<GlobMatcher> {
628    Glob::new(glob)
629        .map(|glob| glob.compile_matcher())
630        .map_err(|e| anyhow::anyhow!("Invalid glob pattern '{}': {}", glob, e))
631}
632
633/// Wall-clock budget for one search walk. Large trees (a whole home
634/// directory) must return a partial-but-fast answer, never hang until the
635/// tool watchdog kills the call.
636const MAX_WALK_MILLIS: u128 = 15_000;
637
638/// Run one filesystem call inside the walk's time budget. `None`: the budget
639/// ran out first. A directory can hang (a stalled mount, an OS permission
640/// prompt), and the check between entries never runs while it does.
641async fn within_budget<T>(
642    started: std::time::Instant,
643    call: impl std::future::Future<Output = T>,
644) -> Option<T> {
645    let budget = std::time::Duration::from_millis(MAX_WALK_MILLIS as u64);
646    tokio::time::timeout(budget.saturating_sub(started.elapsed()), call)
647        .await
648        .ok()
649}
650
651/// Breadth-first, budgeted directory walk.
652///
653/// BFS matters: a file in a shallow user directory (~/Downloads/x.pdf) is
654/// found within the first few thousand entries even when a sibling tree
655/// (~/Library) holds hundreds of thousands — depth-first got lost in the
656/// deep tree and timed out. `max_entries` bounds total entries visited;
657/// exceeding it (or the time budget) sets `stats.truncated`.
658#[allow(clippy::too_many_arguments)]
659async fn walk_dir(
660    backend: SharedBackend,
661    policy: &dyn FilePolicy,
662    root: &BackendPath,
663    content_regex: &Option<Regex>,
664    glob_matcher: &Option<GlobMatcher>,
665    max_results: usize,
666    max_entries: usize,
667    collaboration_root: Option<&BackendPath>,
668    shape: MatchShape,
669    results: &mut Vec<SearchResult>,
670    stats: &mut SearchStats,
671) {
672    let started = std::time::Instant::now();
673    let mut queue: std::collections::VecDeque<(BackendPath, usize)> =
674        std::collections::VecDeque::new();
675    queue.push_back((root.clone(), 0));
676
677    while let Some((dir, depth)) = queue.pop_front() {
678        if results.len() >= max_results || stats.files_scanned >= MAX_FILES_SCANNED {
679            return;
680        }
681
682        let Some(listed) = within_budget(started, backend.read_dir(&dir)).await else {
683            stats.truncated = true;
684            return;
685        };
686        let entries = match listed {
687            Ok(e) => e,
688            Err(_) => continue,
689        };
690
691        for entry in entries {
692            if results.len() >= max_results || stats.files_scanned >= MAX_FILES_SCANNED {
693                return;
694            }
695            stats.entries_visited += 1;
696            if stats.entries_visited >= max_entries
697                || started.elapsed().as_millis() > MAX_WALK_MILLIS
698            {
699                stats.truncated = true;
700                return;
701            }
702
703            let mut path = entry.path;
704            if let Some(root) = collaboration_root {
705                if policy.is_sensitive(std::path::Path::new(path.as_str())) {
706                    continue;
707                }
708                let Ok(canonical) = backend.canonicalize(&path).await else {
709                    continue;
710                };
711                if !std::path::Path::new(canonical.as_str())
712                    .starts_with(std::path::Path::new(root.as_str()))
713                    || policy.is_sensitive(std::path::Path::new(canonical.as_str()))
714                {
715                    continue;
716                }
717                path = canonical;
718            }
719            let file_name = path.file_name().unwrap_or_default().to_string();
720
721            if entry.metadata.file_type == BackendFileType::Directory {
722                if depth < MAX_DEPTH
723                    && !DEFAULT_IGNORE_DIRS.contains(&file_name.as_str())
724                    && !file_name.starts_with('.')
725                {
726                    queue.push_back((path, depth + 1));
727                }
728                continue;
729            }
730
731            if entry.metadata.file_type != BackendFileType::File {
732                continue;
733            }
734
735            // Check glob match on filename
736            if let Some(matcher) = glob_matcher
737                && !matcher.is_match(&file_name)
738            {
739                continue;
740            }
741
742            stats.files_scanned += 1;
743
744            // If content pattern specified, search contents
745            if let Some(content_re) = content_regex {
746                if entry.metadata.len > MAX_CONTENT_SEARCH_FILE_SIZE {
747                    stats.oversized_files_skipped += 1;
748                    continue;
749                }
750                let Some(read) = within_budget(started, backend.read(&path)).await else {
751                    stats.truncated = true;
752                    return;
753                };
754                if let Ok(bytes) = read
755                    && let Some(found) = search_content(&bytes, content_re, shape)
756                {
757                    results.push(found.at(path));
758                }
759            } else {
760                // Glob-only: just list the file
761                results.push(SearchResult {
762                    path,
763                    lines: Vec::new(),
764                    more: 0,
765                });
766            }
767        }
768    }
769}
770
771#[cfg(test)]
772mod tests {
773    use super::*;
774    use crate::fs::{WorkspaceBackend, WorkspaceFilePolicy};
775
776    #[tokio::test(start_paused = true)]
777    async fn a_call_that_never_answers_ends_with_the_budget() {
778        let started = std::time::Instant::now();
779        let hung = within_budget(started, std::future::pending::<()>()).await;
780        assert!(hung.is_none());
781        let answered = within_budget(started, std::future::ready(7)).await;
782        assert_eq!(answered, Some(7));
783    }
784
785    fn parts(path: &std::path::Path) -> (SharedBackend, WorkspaceFilePolicy) {
786        let workspace = Workspace::new(path).unwrap();
787        (
788            Arc::new(WorkspaceBackend::new(workspace.clone())),
789            WorkspaceFilePolicy::new(workspace),
790        )
791    }
792
793    #[tokio::test]
794    async fn breadth_first_walk_finds_shallow_file_under_tight_budget() {
795        // A file two levels down (~/Downloads/x.pdf shape) must be found
796        // before the walk exhausts its budget inside a deep sibling tree —
797        // the failure mode that made home-directory searches time out.
798        let root = tempfile::tempdir().unwrap();
799        let deep = root.path().join("aaa_huge").join("lvl1");
800        std::fs::create_dir_all(&deep).unwrap();
801        for i in 0..300 {
802            std::fs::write(deep.join(format!("noise_{i}.txt")), "x").unwrap();
803        }
804        let shallow = root.path().join("bbb_docs");
805        std::fs::create_dir(&shallow).unwrap();
806        std::fs::write(shallow.join("target.pdf"), "pdf").unwrap();
807
808        let glob = compile_glob("*target.pdf").unwrap();
809        let mut results = Vec::new();
810        let mut stats = SearchStats::default();
811        let (backend, policy) = parts(root.path());
812        let root_path = backend
813            .resolve_path(&root.path().to_string_lossy())
814            .await
815            .unwrap();
816        walk_dir(
817            backend,
818            &policy,
819            &root_path,
820            &None,
821            &Some(glob),
822            10,
823            50, // entry budget far smaller than the deep tree
824            None,
825            MatchShape {
826                per_file: DEFAULT_MATCHES_PER_FILE,
827                context: 0,
828            },
829            &mut results,
830            &mut stats,
831        )
832        .await;
833
834        assert_eq!(results.len(), 1, "shallow file must be found under budget");
835        assert!(results[0].path.as_str().ends_with("target.pdf"));
836    }
837
838    #[tokio::test]
839    async fn search_files_finds_unrelated_project_config_toml() {
840        let root = tempfile::tempdir().unwrap();
841        std::fs::write(root.path().join("config.toml"), "title = \"a\"").unwrap();
842        let glob = compile_glob("*config.toml").unwrap();
843        let mut results = Vec::new();
844        let mut stats = SearchStats::default();
845        let (backend, policy) = parts(root.path());
846        let root_path = backend
847            .resolve_path(&root.path().to_string_lossy())
848            .await
849            .unwrap();
850        walk_dir(
851            backend,
852            &policy,
853            &root_path,
854            &None,
855            &Some(glob),
856            10,
857            50,
858            None,
859            MatchShape {
860                per_file: DEFAULT_MATCHES_PER_FILE,
861                context: 0,
862            },
863            &mut results,
864            &mut stats,
865        )
866        .await;
867        assert_eq!(results.len(), 1);
868    }
869
870    #[tokio::test]
871    async fn walk_truncates_at_entry_budget_and_reports_it() {
872        let root = tempfile::tempdir().unwrap();
873        for i in 0..50 {
874            std::fs::write(root.path().join(format!("file_{i}.txt")), "x").unwrap();
875        }
876
877        let glob = compile_glob("*.zzz").unwrap();
878        let mut results = Vec::new();
879        let mut stats = SearchStats::default();
880        let (backend, policy) = parts(root.path());
881        let root_path = backend
882            .resolve_path(&root.path().to_string_lossy())
883            .await
884            .unwrap();
885        walk_dir(
886            backend,
887            &policy,
888            &root_path,
889            &None,
890            &Some(glob),
891            10,
892            10,
893            None,
894            MatchShape {
895                per_file: DEFAULT_MATCHES_PER_FILE,
896                context: 0,
897            },
898            &mut results,
899            &mut stats,
900        )
901        .await;
902
903        assert!(stats.truncated, "budget exhaustion must set truncated");
904        assert!(results.is_empty());
905    }
906
907    #[tokio::test]
908    async fn truncated_search_output_carries_honest_note() {
909        // The output must tell the model coverage was partial — otherwise
910        // "no matches" reads as a definitive answer and it gives up.
911        let dir = tempfile::tempdir().unwrap();
912        for i in 0..30 {
913            std::fs::write(dir.path().join(format!("file_{i}.txt")), "x").unwrap();
914        }
915        // max_results=1 path is fine; we exercise the public call with a
916        // glob that cannot match, against a tree we know exceeds the test
917        // budget via the internal walker — so use walk_dir + render check
918        // indirectly: the call() budget is large, so instead assert the
919        // note constant is wired by checking a tiny-budget walk + format.
920        let glob = compile_glob("*.zzz").unwrap();
921        let mut results = Vec::new();
922        let mut stats = SearchStats::default();
923        let (backend, policy) = parts(dir.path());
924        let root_path = backend
925            .resolve_path(&dir.path().to_string_lossy())
926            .await
927            .unwrap();
928        walk_dir(
929            backend,
930            &policy,
931            &root_path,
932            &None,
933            &Some(glob),
934            10,
935            5,
936            None,
937            MatchShape {
938                per_file: DEFAULT_MATCHES_PER_FILE,
939                context: 0,
940            },
941            &mut results,
942            &mut stats,
943        )
944        .await;
945        assert!(stats.truncated);
946        let note = truncation_note(&stats);
947        assert!(note.contains("partial"), "note: {note}");
948        assert!(
949            note.contains("path"),
950            "note must steer toward narrower path"
951        );
952    }
953
954    #[test]
955    fn test_glob_to_regex() {
956        let re = compile_glob("*.rs").unwrap();
957        assert!(re.is_match("main.rs"));
958        assert!(!re.is_match("main.py"));
959
960        let re = compile_glob("Cargo.*").unwrap();
961        assert!(re.is_match("Cargo.toml"));
962        assert!(re.is_match("Cargo.lock"));
963    }
964
965    #[test]
966    fn glob_matches_literal_regex_metacharacters_and_commas() {
967        let re = compile_glob("a+b.txt").unwrap();
968        assert!(re.is_match("a+b.txt"));
969        assert!(!re.is_match("aaab.txt"));
970
971        let re = compile_glob("report,final.txt").unwrap();
972        assert!(re.is_match("report,final.txt"));
973        assert!(!re.is_match("report-draft.txt"));
974        assert!(!re.is_match("final.txt"));
975    }
976
977    /// The tool over a temp folder holding a synthetic source file.
978    async fn search(args: Value) -> String {
979        let root = tempfile::tempdir().unwrap();
980        let mut text = String::new();
981        for i in 1..=30 {
982            if i % 3 == 0 {
983                text.push_str(&format!("let Value_{i} = compute({i});\n"));
984            } else {
985                text.push_str(&format!("// plain line {i}\n"));
986            }
987        }
988        std::fs::write(root.path().join("lib.rs"), &text).unwrap();
989        std::fs::write(root.path().join("other.rs"), "nothing here\n").unwrap();
990        let tool = SearchFiles::new(Workspace::new(root.path()).unwrap());
991        let mut args = args;
992        if let Some(name) = args.get("path").and_then(Value::as_str).map(str::to_string) {
993            args["path"] = json!(root.path().join(name).to_string_lossy());
994        } else {
995            args["path"] = json!(root.path().to_string_lossy());
996        }
997        tool.run(&args.to_string(), &ToolCallContext::default())
998            .await
999            .unwrap()
1000    }
1001
1002    /// A file path searches that file (it used to fail "Not a directory").
1003    #[tokio::test]
1004    async fn a_file_path_searches_that_file() {
1005        let out = search(json!({"pattern": "compute", "path": "lib.rs"})).await;
1006        assert!(out.contains("lib.rs:"), "{out}");
1007        assert!(out.contains("   3: let Value_3"), "{out}");
1008        assert!(!out.contains("other.rs"), "{out}");
1009    }
1010
1011    /// Matches past the per-file limit are counted, and `max_per_file`
1012    /// shows more.
1013    #[tokio::test]
1014    async fn matches_past_the_limit_are_counted() {
1015        let out = search(json!({"pattern": "compute"})).await;
1016        assert!(out.contains("  15: let Value_15"), "{out}");
1017        assert!(!out.contains("Value_18"), "{out}");
1018        assert!(out.contains("(+5 more matches in this file"), "{out}");
1019        let out = search(json!({"pattern": "compute", "max_per_file": 50})).await;
1020        assert!(
1021            out.contains("Value_30") && !out.contains("more match"),
1022            "{out}"
1023        );
1024    }
1025
1026    /// Context lines come before and after each match, marked like grep.
1027    #[tokio::test]
1028    async fn context_lines_surround_each_match() {
1029        let out = search(json!({"pattern": "Value_3 ", "context_lines": 1})).await;
1030        assert!(out.contains("   2- // plain line 2"), "{out}");
1031        assert!(out.contains("   3: let Value_3 "), "{out}");
1032        assert!(out.contains("   4- // plain line 4"), "{out}");
1033    }
1034
1035    /// The pattern can ignore letter case.
1036    #[tokio::test]
1037    async fn the_pattern_can_ignore_case() {
1038        let out = search(json!({"pattern": "value_6"})).await;
1039        assert!(out.starts_with("No matches"), "{out}");
1040        let out = search(json!({"pattern": "value_6", "case_insensitive": true})).await;
1041        assert!(out.contains("   6: let Value_6"), "{out}");
1042    }
1043}