Skip to main content

agent_hub_runtime/core/
worktree_search.rs

1//! Bounded text search and optimistic replacements inside one authorized checkout.
2use anyhow::{bail, Context, Result};
3use regex::{Regex, RegexBuilder};
4use serde::{Deserialize, Serialize};
5use sha2::{Digest, Sha256};
6use std::{
7    path::Path,
8    time::{Duration, Instant},
9};
10
11use super::{path_guard, project_file_edit, project_worktrees};
12const MAX_MATCHES: usize = 1000;
13const MAX_BYTES: usize = 32 * 1024 * 1024;
14const MAX_ENTRIES: usize = 20_000;
15
16#[derive(Clone, Deserialize)]
17pub struct SearchOptions {
18    pub query: String,
19    pub case_sensitive: bool,
20    pub whole_word: bool,
21    pub regex: bool,
22    pub include: String,
23    pub exclude: String,
24    pub use_ignore: bool,
25}
26#[derive(Serialize)]
27pub struct SearchMatch {
28    pub line: usize,
29    /// One-based UTF-16 columns, matching the editor's coordinates.
30    pub column: usize,
31    pub end_column: usize,
32    pub preview: String,
33    pub preview_start: usize,
34}
35#[derive(Serialize, Deserialize)]
36pub struct SearchFile {
37    pub path: String,
38    pub fingerprint: String,
39    #[serde(skip_deserializing)]
40    pub matches: Vec<SearchMatch>,
41}
42#[derive(Serialize, Default)]
43pub struct SearchResult {
44    pub files: Vec<SearchFile>,
45    pub count: usize,
46    pub truncated: bool,
47    pub skipped: usize,
48}
49
50fn matcher(options: &SearchOptions) -> Result<Regex> {
51    if options.query.is_empty() || options.query.len() > 4096 {
52        bail!("Enter a search query between 1 and 4096 bytes");
53    }
54    let pattern = if options.regex {
55        options.query.clone()
56    } else {
57        regex::escape(&options.query)
58    };
59    let pattern = if options.whole_word {
60        format!(r"\b(?:{pattern})\b")
61    } else {
62        pattern
63    };
64    RegexBuilder::new(&pattern)
65        .case_insensitive(!options.case_sensitive)
66        .multi_line(true)
67        .size_limit(1024 * 1024)
68        .build()
69        .context("Invalid search expression")
70}
71
72/// The include/exclude fields accept comma-separated paths with *, ** and ?.
73fn path_filter(raw: &str) -> Result<Option<Regex>> {
74    if raw.len() > 4096 {
75        bail!("File filters exceed the 4096 byte limit");
76    }
77    let mut patterns = Vec::new();
78    for pattern in raw
79        .split(',')
80        .map(str::trim)
81        .filter(|part| !part.is_empty())
82    {
83        let pattern = pattern.trim_end_matches('/');
84        let mut chars = pattern.chars().peekable();
85        let mut expression = if pattern.contains('/') {
86            "^".to_string()
87        } else {
88            "(?:^|/)".to_string()
89        };
90        while let Some(ch) = chars.next() {
91            match ch {
92                '*' if chars.peek() == Some(&'*') => {
93                    chars.next();
94                    if chars.peek() == Some(&'/') {
95                        chars.next();
96                        expression.push_str("(?:.*/)?");
97                    } else {
98                        expression.push_str(".*");
99                    }
100                }
101                '*' => expression.push_str("[^/]*"),
102                '?' => expression.push_str("[^/]"),
103                _ => expression.push_str(&regex::escape(&ch.to_string())),
104            }
105        }
106        expression.push_str("(?:/.*)?$");
107        patterns.push(expression);
108    }
109    if patterns.is_empty() {
110        return Ok(None);
111    }
112    Ok(Some(Regex::new(&patterns.join("|"))?))
113}
114fn fingerprint(content: &str) -> String {
115    hex::encode(Sha256::digest(content.as_bytes()))
116}
117
118fn find_matches(content: &str, regex: &Regex, remaining: usize) -> (Vec<SearchMatch>, bool) {
119    let mut result = Vec::new();
120    let mut line_start = 0;
121    let mut line_number = 1;
122    for found in regex.find_iter(content) {
123        if result.len() == remaining {
124            return (result, true);
125        }
126        while let Some(newline) = content[line_start..found.start()].find('\n') {
127            line_start += newline + 1;
128            line_number += 1;
129        }
130        let line_end = content[found.start()..]
131            .find('\n')
132            .map_or(content.len(), |offset| found.start() + offset);
133        // Bound long lines around the match, on Unicode character boundaries.
134        let mut preview_start = found.start().saturating_sub(160).max(line_start);
135        while !content.is_char_boundary(preview_start) {
136            preview_start += 1;
137        }
138        let mut preview_end = (found.start() + 240).min(line_end);
139        while !content.is_char_boundary(preview_end) {
140            preview_end -= 1;
141        }
142        let preview = content[preview_start..preview_end]
143            .trim_end_matches('\r')
144            .to_string();
145        result.push(SearchMatch {
146            line: line_number,
147            column: content[line_start..found.start()].encode_utf16().count() + 1,
148            end_column: content[line_start..found.end().min(line_end)]
149                .encode_utf16()
150                .count()
151                + 1,
152            preview,
153            preview_start: content[line_start..preview_start].encode_utf16().count() + 1,
154        });
155    }
156    (result, false)
157}
158
159fn excluded(
160    entry: &walkdir::DirEntry,
161    root: &Path,
162    options: &SearchOptions,
163    repo: Option<&git2::Repository>,
164    exclude: Option<&Regex>,
165) -> bool {
166    let name = entry.file_name().to_string_lossy();
167    if name.eq_ignore_ascii_case(".git") {
168        return true;
169    }
170    if options.use_ignore
171        && matches!(
172            name.as_ref(),
173            "node_modules" | "target" | "dist" | ".next" | ".cache"
174        )
175        && entry.file_type().is_dir()
176    {
177        return true;
178    }
179    if entry.file_type().is_symlink() {
180        return true;
181    }
182    if let Ok(metadata) = std::fs::symlink_metadata(entry.path()) {
183        if path_guard::is_link_or_reparse_point(&metadata) {
184            return true;
185        }
186    }
187    let Ok(relative) = entry.path().strip_prefix(root) else {
188        return true;
189    };
190    let relative = relative.to_string_lossy().replace('\\', "/");
191    if exclude.is_some_and(|filter| filter.is_match(&relative)) {
192        return true;
193    }
194    if options.use_ignore
195        && repo.is_some_and(|repo| {
196            repo.status_should_ignore(Path::new(&relative))
197                .unwrap_or(false)
198        })
199    {
200        return true;
201    }
202    false
203}
204
205pub fn search(root: &Path, options: &SearchOptions) -> Result<SearchResult> {
206    let regex = matcher(options)?;
207    let include = path_filter(&options.include)?;
208    let exclude = path_filter(&options.exclude)?;
209    let repo =
210        git2::Repository::open_ext(root, git2::RepositoryOpenFlags::NO_SEARCH, &[] as &[&Path])
211            .ok();
212    let started = Instant::now();
213    let mut result = SearchResult::default();
214    let mut bytes = 0;
215    let mut walker = walkdir::WalkDir::new(root)
216        .min_depth(1)
217        .follow_links(false)
218        .into_iter();
219    let mut visited = 0;
220    while let Some(entry) = walker.next() {
221        visited += 1;
222        if visited > MAX_ENTRIES || bytes >= MAX_BYTES || started.elapsed() > Duration::from_secs(3)
223        {
224            result.truncated = true;
225            break;
226        }
227        let entry = match entry {
228            Ok(entry) => entry,
229            Err(_) => {
230                result.skipped += 1;
231                continue;
232            }
233        };
234        if excluded(&entry, root, options, repo.as_ref(), exclude.as_ref()) {
235            if entry.file_type().is_dir() {
236                walker.skip_current_dir();
237            }
238            continue;
239        }
240        if !entry.file_type().is_file() {
241            continue;
242        }
243        let path = entry
244            .path()
245            .strip_prefix(root)?
246            .to_string_lossy()
247            .replace('\\', "/");
248        if include
249            .as_ref()
250            .is_some_and(|filter| !filter.is_match(&path))
251        {
252            continue;
253        }
254        let metadata = match entry.metadata() {
255            Ok(metadata) => metadata,
256            Err(_) => {
257                result.skipped += 1;
258                continue;
259            }
260        };
261        if metadata.len() > 1024 * 1024 {
262            result.skipped += 1;
263            continue;
264        }
265        bytes += metadata.len() as usize;
266        let content = match project_worktrees::read_file(root, &path) {
267            Ok(content) => content,
268            Err(_) => {
269                result.skipped += 1;
270                continue;
271            }
272        };
273        let (matches, truncated) = find_matches(&content, &regex, MAX_MATCHES - result.count);
274        result.count += matches.len();
275        if !matches.is_empty() {
276            result.files.push(SearchFile {
277                path,
278                fingerprint: fingerprint(&content),
279                matches,
280            });
281        }
282        if truncated {
283            result.truncated = true;
284            break;
285        }
286    }
287    result
288        .files
289        .sort_by(|left, right| left.path.cmp(&right.path));
290    Ok(result)
291}
292
293fn replacement_content(
294    original: &str,
295    regex: &Regex,
296    replacement: &str,
297    expand: bool,
298) -> Result<(String, usize)> {
299    const LIMIT: usize = 1024 * 1024;
300    let mut updated = String::new();
301    let mut previous = 0;
302    let mut count = 0;
303    for captures in regex.captures_iter(original) {
304        let found = captures.get(0).context("Missing search match")?;
305        count += 1;
306        if count > MAX_MATCHES {
307            bail!("Too many replacements; narrow the search first");
308        }
309        let mut expanded = String::new();
310        let replacement = if expand && replacement.contains('$') {
311            let max_capture = captures
312                .iter()
313                .flatten()
314                .map(|value| value.len())
315                .max()
316                .unwrap_or(0);
317            if replacement.len().saturating_mul(max_capture + 1) > 2 * LIMIT {
318                bail!("Replacement expansion exceeds the editor limit");
319            }
320            captures.expand(replacement, &mut expanded);
321            expanded.as_str()
322        } else {
323            replacement
324        };
325        if updated.len() + found.start() - previous + replacement.len() > LIMIT {
326            bail!("Replacement exceeds the 1 MiB editor limit");
327        }
328        updated.push_str(&original[previous..found.start()]);
329        updated.push_str(replacement);
330        previous = found.end();
331    }
332    if updated.len() + original.len() - previous > LIMIT {
333        bail!("Replacement exceeds the 1 MiB editor limit");
334    }
335    updated.push_str(&original[previous..]);
336    Ok((updated, count))
337}
338
339#[derive(Serialize)]
340pub struct ReplaceResult {
341    pub replaced: usize,
342    pub files: usize,
343    pub errors: Vec<String>,
344}
345/// Every file is verified against its search snapshot, then saved through the editor's atomic writer.
346pub fn replace(
347    root: &Path,
348    options: &SearchOptions,
349    replacement: &str,
350    files: &[SearchFile],
351) -> Result<ReplaceResult> {
352    if files.is_empty() || files.len() > MAX_MATCHES || replacement.len() > 64 * 1024 {
353        bail!("Invalid replacement request");
354    }
355    let regex = matcher(options)?;
356    let mut result = ReplaceResult {
357        replaced: 0,
358        files: 0,
359        errors: Vec::new(),
360    };
361    for file in files {
362        let attempt = (|| -> Result<usize> {
363            let original = project_worktrees::read_file(root, &file.path)?;
364            if fingerprint(&original) != file.fingerprint {
365                bail!("File changed on disk; search again before replacing");
366            }
367            let (updated, count) =
368                replacement_content(&original, &regex, replacement, options.regex)?;
369            project_file_edit::save(root, &file.path, &original, &updated)?;
370            Ok(count)
371        })();
372        match attempt {
373            Ok(count) => {
374                result.replaced += count;
375                result.files += 1;
376            }
377            Err(error) => result.errors.push(format!("{}: {error}", file.path)),
378        }
379    }
380    Ok(result)
381}
382
383#[cfg(test)]
384mod tests;