Skip to main content

pixie_pi/tools/
find.rs

1//! `find` tool — find files by glob pattern (gitignore-aware, in-process).
2
3use std::path::{Path, PathBuf};
4
5use async_trait::async_trait;
6use serde::Deserialize;
7use serde_json::{json, Value};
8use tokio_util::sync::CancellationToken;
9
10use crate::agent::tool::{AgentTool, ToolResult};
11use crate::tools::truncate::{format_size, truncate_head, DEFAULT_MAX_BYTES};
12use crate::tools::util::{display_path, resolve_to_cwd};
13
14const DEFAULT_RESULT_LIMIT: usize = 1000;
15
16pub struct FindTool {
17    pub cwd: PathBuf,
18}
19
20#[derive(Debug, Deserialize)]
21struct FindInput {
22    pattern: String,
23    #[serde(default)]
24    path: Option<String>,
25    #[serde(default)]
26    limit: Option<usize>,
27}
28
29#[async_trait]
30impl AgentTool for FindTool {
31    fn name(&self) -> &str {
32        "find"
33    }
34    fn description(&self) -> &str {
35        "Search for files by glob pattern. Returns matching file paths relative to the search directory. Respects .gitignore. Output is truncated to 1000 results or 50KB (whichever is hit first)."
36    }
37    fn input_schema(&self) -> Value {
38        json!({
39            "type": "object",
40            "properties": {
41                "pattern": { "type": "string", "description": "Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'" },
42                "path": { "type": "string", "description": "Directory to search in (default: current directory)" },
43                "limit": { "type": "number", "description": "Maximum number of results (default: 1000)" }
44            },
45            "required": ["pattern"]
46        })
47    }
48
49    async fn execute(&self, args: Value, _cancel: CancellationToken) -> anyhow::Result<ToolResult> {
50        let input: FindInput = serde_json::from_value(args)?;
51        // Clamp to >= 1: a degenerate `limit: 0` would otherwise cap the result
52        // set to zero and report "No files found" even when matches exist. grep
53        // already does this; ls mirrors the same guard for consistency.
54        let effective_limit = input.limit.unwrap_or(DEFAULT_RESULT_LIMIT).max(1);
55        let search_path = resolve_to_cwd(input.path.as_deref().unwrap_or("."), &self.cwd);
56        if !search_path.exists() {
57            anyhow::bail!(
58                "Path not found: {}",
59                display_path(input.path.as_deref().unwrap_or("."), &self.cwd)
60            );
61        }
62
63        // A glob like "*.ts" should match by basename; "**/*.json" matches the
64        // full relative path. Test both.
65        let matcher = globset::Glob::new(&input.pattern)
66            .map_err(|e| anyhow::anyhow!("Invalid glob pattern: {e}"))?
67            .compile_matcher();
68
69        let mut matches: Vec<String> = Vec::new();
70        // Collect up to one past the limit so we can tell "exactly N matches"
71        // (no truncation) from "more than N" (genuine truncation). Without the
72        // +1 probe, a result set of exactly `effective_limit` files would spuriously
73        // report "limit reached" even though nothing was held back.
74        let mut result_limit_reached = false;
75        for file in collect_files(&search_path) {
76            let rel = file
77                .strip_prefix(&search_path)
78                .unwrap_or(&file)
79                .to_string_lossy()
80                .replace('\\', "/");
81            let base = file
82                .file_name()
83                .map(|n| n.to_string_lossy().to_string())
84                .unwrap_or_default();
85            if matcher.is_match(&rel) || matcher.is_match(&base) {
86                matches.push(rel);
87            }
88            if matches.len() > effective_limit {
89                result_limit_reached = true;
90                break;
91            }
92        }
93
94        // Drop the surplus probe entry; the displayed set is identical to the
95        // pre-fix behavior (the first `effective_limit` matches in walk order).
96        matches.truncate(effective_limit);
97        matches.sort();
98
99        if matches.is_empty() {
100            return Ok(ToolResult::text("No files found matching pattern"));
101        }
102
103        let raw = matches.join("\n");
104        let trunc = truncate_head(&raw, None, None);
105        let mut output = trunc.content;
106        let mut notices: Vec<String> = Vec::new();
107        if result_limit_reached {
108            notices.push(format!(
109                "{effective_limit} results limit reached. Use limit={} for more, or refine pattern",
110                effective_limit * 2
111            ));
112        }
113        if trunc.truncated {
114            notices.push(format!("{} limit reached", format_size(DEFAULT_MAX_BYTES)));
115        }
116        if !notices.is_empty() {
117            output.push_str(&format!("\n\n[{}]", notices.join(". ")));
118        }
119        Ok(ToolResult::text(output))
120    }
121}
122
123fn collect_files(root: &Path) -> Vec<PathBuf> {
124    let mut files = Vec::new();
125    if root.is_file() {
126        files.push(root.to_path_buf());
127        return files;
128    }
129    let walker = ignore::WalkBuilder::new(root)
130        .hidden(false)
131        .git_ignore(true)
132        .git_global(true)
133        .parents(true)
134        .build();
135    for entry in walker.flatten() {
136        if entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
137            files.push(entry.into_path());
138        }
139    }
140    files
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146    use crate::agent::tool::AgentTool;
147    use tokio_util::sync::CancellationToken;
148
149    fn scratch_dir(label: &str) -> PathBuf {
150        let dir = std::env::temp_dir()
151            .join(format!("pi-find-test-{label}-{}", uuid::Uuid::new_v4()));
152        std::fs::create_dir_all(&dir).unwrap();
153        dir
154    }
155
156    async fn run_find(cwd: PathBuf, args: serde_json::Value) -> String {
157        let tool = FindTool { cwd };
158        let res = tool.execute(args, CancellationToken::new()).await.unwrap();
159        match res.content.into_iter().next() {
160            Some(crate::ai::types::ToolResultContent::Text { text }) => text,
161            _ => panic!("expected text tool result"),
162        }
163    }
164
165    #[tokio::test]
166    async fn limit_not_reported_when_results_equal_limit_exactly() {
167        // Exactly `limit` files match → all are shown, and the "limit reached"
168        // notice must NOT fire (nothing was held back).
169        let dir = scratch_dir("at-limit");
170        for i in 1..=3 {
171            std::fs::write(dir.join(format!("match{i}.txt")), "x").unwrap();
172        }
173
174        let out = run_find(
175            dir.clone(),
176            serde_json::json!({ "pattern": "match*.txt", "path": dir.to_string_lossy(), "limit": 3 }),
177        )
178        .await;
179
180        assert_eq!(out.matches(".txt").count(), 3, "all 3 results shown");
181        assert!(
182            !out.contains("limit reached"),
183            "no false-positive limit notice\n{out}"
184        );
185
186        let _ = std::fs::remove_dir_all(&dir);
187    }
188
189    #[tokio::test]
190    async fn limit_reported_and_capped_when_results_exceed_limit() {
191        // One more result than the limit → notice fires and exactly `limit`
192        // results are emitted.
193        let dir = scratch_dir("over-limit");
194        for i in 1..=4 {
195            std::fs::write(dir.join(format!("match{i}.txt")), "x").unwrap();
196        }
197
198        let out = run_find(
199            dir.clone(),
200            serde_json::json!({ "pattern": "match*.txt", "path": dir.to_string_lossy(), "limit": 3 }),
201        )
202        .await;
203
204        assert_eq!(out.matches(".txt").count(), 3, "exactly 3 results shown");
205        assert!(
206            out.contains("limit reached"),
207            "truncation notice present\n{out}"
208        );
209
210        let _ = std::fs::remove_dir_all(&dir);
211    }
212
213    #[tokio::test]
214    async fn limit_zero_is_clamped_to_one_not_reported_empty() {
215        // A degenerate `limit: 0` is clamped to 1 (matching grep), so at least
216        // one match is shown instead of the misleading "No files found".
217        let dir = scratch_dir("zero-limit");
218        std::fs::write(dir.join("match.txt"), "x").unwrap();
219
220        let out = run_find(
221            dir.clone(),
222            serde_json::json!({ "pattern": "match*.txt", "path": dir.to_string_lossy(), "limit": 0 }),
223        )
224        .await;
225
226        assert!(
227            out.contains("match.txt"),
228            "limit:0 should be clamped to 1 and show the match, got: {out}"
229        );
230        assert!(
231            !out.contains("No files found"),
232            "limit:0 must not report 'No files found' when a file matches: {out}"
233        );
234
235        let _ = std::fs::remove_dir_all(&dir);
236    }
237}