agent-file-tools 0.36.0

Agent File Tools — tree-sitter powered code analysis for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
use std::collections::HashMap;
use std::path::Path;

use crate::context::AppContext;
use crate::grep_executor::{self, GrepParams};
use crate::pattern_compile::{self, CompileOpts, CompileResult};
use crate::protocol::{RawRequest, Response};
use crate::search_index::{build_path_filters, GrepMatch, GrepResult, IndexStatus};

pub(crate) use crate::grep_executor::ripgrep_glob;

const DEFAULT_MAX_RESULTS: usize = 100;
const MAX_LINE_CHARS: usize = 200;
const MAX_MATCHES_PER_FILE: usize = 10;
const MAX_DISPLAY_MATCHES_PER_FILE: usize = 5;

pub fn handle_grep(req: &RawRequest, ctx: &AppContext) -> Response {
    let pattern = match req.params.get("pattern").and_then(|value| value.as_str()) {
        Some(pattern) => pattern,
        None => {
            return Response::error(
                &req.id,
                "invalid_request",
                "grep: missing required param 'pattern'",
            );
        }
    };

    let case_sensitive = req
        .params
        .get("case_sensitive")
        .and_then(|value| value.as_bool())
        .unwrap_or(true);
    let include = string_array_param(&req.params, "include");
    let exclude = string_array_param(&req.params, "exclude");
    let max_results = req
        .params
        .get("max_results")
        .and_then(|value| value.as_u64())
        .map(|value| value as usize)
        .unwrap_or(DEFAULT_MAX_RESULTS);

    let compiled = match pattern_compile::compile(
        pattern,
        CompileOpts {
            case_insensitive: !case_sensitive,
            ..CompileOpts::default()
        },
    ) {
        CompileResult::Ok(compiled) => compiled,
        CompileResult::InvalidPattern { message, .. } => {
            return Response::error_with_data(
                &req.id,
                "invalid_pattern",
                message,
                serde_json::json!({"pattern": pattern}),
            );
        }
        CompileResult::UnsupportedSyntax { feature, .. } => {
            return Response::error_with_data(
                &req.id,
                "invalid_pattern",
                format!(
                    "Pattern uses regex syntax not supported by AFT's engine: {feature}. Use hint:'literal' or rewrite without {feature}."
                ),
                serde_json::json!({"pattern": pattern, "feature": feature}),
            );
        }
    };

    if let Err(error) = build_path_filters(&include, &exclude) {
        return Response::error(
            &req.id,
            "invalid_request",
            format!("grep: invalid include/exclude glob: {}", error),
        );
    }

    let scope = match grep_executor::resolve_grep_scope(
        ctx,
        req.params.get("path"),
        max_results,
        &req.id,
    ) {
        Ok(scope) => scope,
        Err(response) => return response,
    };
    let project_root = grep_executor::project_root(ctx);
    let scope_has_files = grep_executor::scope_has_files(&project_root, &scope);

    let search_start = std::time::Instant::now();
    let params = GrepParams {
        include,
        exclude,
        max_results,
    };
    let result = grep_executor::execute(ctx, &compiled, &scope, &params);
    let search_ms = search_start.elapsed().as_secs_f64() * 1000.0;
    let text = format_grep_text(&result, &project_root);

    Response::success(
        &req.id,
        serde_json::json!({
            "text": text,
            "complete": true,
            "no_files_matched_scope": !scope_has_files,
            "matches": result.matches.iter().map(match_to_json).collect::<Vec<_>>(),
            "total_matches": result.total_matches,
            "files_searched": result.files_searched,
            "files_with_matches": result.files_with_matches,
            "index_status": result.index_status.as_str(),
            "truncated": result.truncated,
            "search_ms": (search_ms * 1000.0).round() / 1000.0,
        }),
    )
}

pub(crate) fn format_grep_text(result: &GrepResult, project_root: &Path) -> String {
    // Preserve the incoming match order (callers sort by mtime-desc upstream via
    // sort_grep_matches_by_mtime_desc). A BTreeMap here would re-sort groups
    // alphabetically by path and silently discard that ordering — both wasting
    // the upstream sort and giving a different ordering contract than the
    // semantic path, which groups in result order. Group by file preserving
    // first-appearance order instead.
    let mut group_order: Vec<String> = Vec::new();
    let mut groups: HashMap<String, Vec<&GrepMatch>> = HashMap::new();

    for grep_match in &result.matches {
        // Use relative path within project, absolute otherwise
        let display_path = grep_match
            .file
            .strip_prefix(project_root)
            .unwrap_or(&grep_match.file)
            .display()
            .to_string();
        if !groups.contains_key(&display_path) {
            group_order.push(display_path.clone());
        }
        groups.entry(display_path).or_default().push(grep_match);
    }

    let mut sections = Vec::new();

    for file in &group_order {
        let matches = &groups[file];
        let mut section = file.clone();
        let display_count = if matches.len() > MAX_MATCHES_PER_FILE {
            MAX_DISPLAY_MATCHES_PER_FILE
        } else {
            matches.len()
        };

        for grep_match in matches.iter().take(display_count) {
            section.push_str(&format!(
                "\n{}: {}",
                grep_match.line,
                truncate_line_text(&grep_match.line_text)
            ));
        }

        if matches.len() > MAX_MATCHES_PER_FILE {
            section.push_str(&format!(
                "\n... and {} more matches",
                matches.len() - MAX_DISPLAY_MATCHES_PER_FILE
            ));
        }

        sections.push(section);
    }

    let footer = format!(
        "Found {} match(es) across {} file(s). [index: {}]",
        result.total_matches,
        result.files_with_matches,
        index_status_label(result.index_status),
    );

    if sections.is_empty() {
        footer
    } else {
        format!("{}\n\n{}", sections.join("\n\n"), footer)
    }
}

pub(crate) fn truncate_line_text(text: &str) -> String {
    let char_count = text.chars().count();
    if char_count <= MAX_LINE_CHARS {
        return text.to_string();
    }
    let truncated: String = text.chars().take(MAX_LINE_CHARS).collect();
    format!("{}", truncated)
}

fn index_status_label(status: IndexStatus) -> &'static str {
    match status {
        IndexStatus::Ready => "ready",
        IndexStatus::Building => "building",
        IndexStatus::Fallback => "fallback",
        IndexStatus::Disabled => "disabled",
    }
}

fn match_to_json(grep_match: &GrepMatch) -> serde_json::Value {
    serde_json::json!({
        "file": grep_match.file.display().to_string(),
        "line": grep_match.line,
        "column": grep_match.column,
        "line_text": grep_match.line_text,
        "match_text": grep_match.match_text,
    })
}

fn string_array_param(params: &serde_json::Value, key: &str) -> Vec<String> {
    let Some(value) = params.get(key) else {
        return Vec::new();
    };
    if let Some(values) = value.as_array() {
        return values
            .iter()
            .filter_map(|item| item.as_str().map(ToOwned::to_owned))
            .flat_map(|raw| split_brace_aware(&raw))
            .filter(|item| !item.is_empty())
            .collect();
    }
    if let Some(raw) = value.as_str() {
        return split_brace_aware(raw)
            .into_iter()
            .filter(|item| !item.is_empty())
            .collect();
    }
    Vec::new()
}

/// Split a comma-separated glob string into multiple globs while preserving
/// brace alternations (`**/*.{ts,tsx}`). Treats `,` as a separator only when
/// the surrounding `{` / `}` depth is zero, mirroring the plugin-layer
/// `splitIncludeArg` so direct binary callers (bash rewrite, CLI users,
/// future hosts) get the same robustness.
///
/// Defends against issue #33: agents passing `"**/*.{ts,tsx},**/*.{js,jsx}"`
/// would previously be naively split by some caller into the two broken
/// fragments `**/*.{ts` and `**/*.{js`, both rejected by the globset parser.
/// This helper is brace-aware so the brace groups stay intact.
fn split_brace_aware(raw: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    let mut buf = String::new();
    let mut depth = 0i32;
    for ch in raw.chars() {
        match ch {
            '{' => {
                depth += 1;
                buf.push(ch);
            }
            '}' => {
                if depth > 0 {
                    depth -= 1;
                }
                buf.push(ch);
            }
            ',' if depth == 0 => {
                let trimmed = buf.trim();
                if !trimmed.is_empty() {
                    out.push(trimmed.to_string());
                }
                buf.clear();
            }
            _ => buf.push(ch),
        }
    }
    let tail = buf.trim();
    if !tail.is_empty() {
        out.push(tail.to_string());
    }
    out
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::*;

    fn grep_match(file: &str, line: u32, line_text: &str) -> GrepMatch {
        GrepMatch {
            file: PathBuf::from(file),
            line,
            column: 1,
            line_text: line_text.to_string(),
            match_text: "needle".to_string(),
        }
    }

    fn grep_result(
        matches: Vec<GrepMatch>,
        total_matches: usize,
        files_searched: usize,
        files_with_matches: usize,
        index_status: IndexStatus,
        truncated: bool,
    ) -> GrepResult {
        GrepResult {
            matches,
            total_matches,
            files_searched,
            files_with_matches,
            index_status,
            truncated,
            fully_degraded: false,
            engine_capped: false,
        }
    }

    fn root() -> PathBuf {
        PathBuf::from("/project")
    }

    #[test]
    fn grep_groups_truncates_and_adds_footer() {
        let long_line = format!("{}xyz", "a".repeat(220));
        let result = grep_result(
            vec![
                grep_match(
                    "/project/crates/aft/src/commands/grep.rs",
                    14,
                    "pub fn handle_grep(req: &RawRequest, ctx: &AppContext) -> Response {",
                ),
                grep_match("/project/crates/aft/src/commands/grep.rs", 116, &long_line),
                grep_match(
                    "/project/crates/aft/src/main.rs",
                    116,
                    "        \"grep\" => aft::commands::grep::handle_grep(&req, ctx),",
                ),
            ],
            3,
            2,
            2,
            IndexStatus::Ready,
            false,
        );

        let text = format_grep_text(&result, &root());

        // Relative paths, no decorators, no match count in header
        assert!(text.contains("crates/aft/src/commands/grep.rs\n"));
        assert!(text
            .contains("14: pub fn handle_grep(req: &RawRequest, ctx: &AppContext) -> Response {"));
        // Long line truncated at 200 chars
        assert!(text.contains("116: aaaaaaa"));
        assert!(text.contains(""));
        assert!(text.contains("crates/aft/src/main.rs\n"));
        assert!(text.ends_with("Found 3 match(es) across 2 file(s). [index: ready]"));
    }

    #[test]
    fn grep_caps_large_file_sections() {
        let matches = (1..=11)
            .map(|line| grep_match("/project/src/large.rs", line, &format!("line {line}")))
            .collect::<Vec<_>>();
        let result = grep_result(matches, 11, 1, 1, IndexStatus::Fallback, false);

        let text = format_grep_text(&result, &root());

        assert!(text.contains("src/large.rs\n"));
        assert!(text.contains("1: line 1"));
        assert!(text.contains("5: line 5"));
        assert!(!text.contains("6: line 6"));
        assert!(text.contains("... and 6 more matches"));
    }

    #[test]
    fn grep_returns_zero_results_footer() {
        let result = grep_result(Vec::new(), 0, 0, 0, IndexStatus::Fallback, false);

        let text = format_grep_text(&result, &root());

        assert_eq!(
            text,
            "Found 0 match(es) across 0 file(s). [index: fallback]"
        );
    }

    // Issue #33 regression: brace-aware include/exclude splitting at the Rust
    // boundary. Defends direct binary callers (bash rewrite, CLI users) and
    // hosts that pass a comma-separated string instead of an already-split
    // array of globs.
    #[test]
    fn split_preserves_single_brace_group() {
        assert_eq!(split_brace_aware("**/*.{ts,tsx}"), vec!["**/*.{ts,tsx}"]);
    }

    #[test]
    fn split_handles_top_level_commas_with_braces() {
        assert_eq!(
            split_brace_aware("**/*.{ts,tsx},**/*.{js,jsx}"),
            vec!["**/*.{ts,tsx}", "**/*.{js,jsx}"],
        );
    }

    #[test]
    fn split_strips_whitespace_around_top_level_separators() {
        assert_eq!(
            split_brace_aware("**/*.{ts,tsx}, **/*.{js,jsx}"),
            vec!["**/*.{ts,tsx}", "**/*.{js,jsx}"],
        );
    }

    #[test]
    fn split_handles_nested_braces() {
        assert_eq!(
            split_brace_aware("**/{a,{b,c},d}.ts"),
            vec!["**/{a,{b,c},d}.ts"],
        );
    }

    #[test]
    fn split_tolerates_unbalanced_brace_without_panic() {
        // Don't crash on malformed input; treat the unclosed brace as part
        // of the buffer and let the globset parser surface the real error.
        let result = split_brace_aware("**/*.{ts,tsx");
        assert_eq!(result, vec!["**/*.{ts,tsx"]);
    }

    #[test]
    fn split_returns_empty_for_blank_input() {
        assert!(split_brace_aware("").is_empty());
        assert!(split_brace_aware("   ").is_empty());
    }

    #[test]
    fn string_array_param_accepts_string_with_braces() {
        let params = serde_json::json!({"include": "**/*.{ts,tsx},**/*.{js,jsx}"});
        let result = string_array_param(&params, "include");
        assert_eq!(result, vec!["**/*.{ts,tsx}", "**/*.{js,jsx}"]);
    }

    #[test]
    fn string_array_param_accepts_array_input() {
        let params = serde_json::json!({"include": ["**/*.ts", "**/*.tsx"]});
        let result = string_array_param(&params, "include");
        assert_eq!(result, vec!["**/*.ts", "**/*.tsx"]);
    }

    #[test]
    fn string_array_param_normalizes_array_with_brace_strings() {
        let params = serde_json::json!({"include": ["**/*.{ts,tsx}", "*.json"]});
        let result = string_array_param(&params, "include");
        assert_eq!(result, vec!["**/*.{ts,tsx}", "*.json"]);
    }
}