eclipse-core 0.13.1

Core library for eclipse: providers, tools, sessions, config, runtime
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
//! `search_files`: find where a pattern appears, without reading files one at a time.
//!
//! Two targets, one tool, because they answer the same question — "where is this?" — and a model
//! that has to choose between `search_files` and `find_files` chooses wrong at least once a
//! session:
//!
//! - `target: "content"` (the default) walks the tree and matches `pattern` as a **regular
//!   expression against one line at a time**, printing `path:line:content`.
//! - `target: "files"` matches file **names** — a glob (`*.rs`) or, when the pattern has no glob
//!   characters in it, a substring.
//!
//! The walk is rooted at the workspace the way [`read_file`](crate::tools::ReadFile) is: one
//! [`confine`] call, so a search cannot reach a path a read would be refused. It is also bounded
//! in three places — matches (`limit`), files visited, and bytes per file — because a pattern
//! that matches everything is the normal case (`fn `) and an unbounded answer is a context bill,
//! not a result. Whatever the bound cuts is reported: a search that says "stopped at 50" is
//! usable, one that quietly returns the first 50 is a lie.

use std::path::{Path, PathBuf};

use async_trait::async_trait;
use serde_json::{json, Value};

use crate::tools::{confine, str_arg, Tool, ToolError};

/// Directories a search never enters. Not configurable on purpose: a `target/` walk is 30 seconds
/// of a tool call and `node_modules` is the same, and the answer to "why is my search slow" should
/// not be a config key.
const SKIP_DIRS: [&str; 8] = [
    ".git",
    ".hg",
    ".svn",
    "node_modules",
    "target",
    ".venv",
    "venv",
    "__pycache__",
];

/// Files larger than this are skipped and counted. A 40 MB log is not what a search is for, and
/// reading it to find that out costs more than the search.
const MAX_FILE_BYTES: u64 = 2 * 1024 * 1024;

/// How many directory entries one search may look at. A backstop against a tree that is not a
/// workspace (a home directory, a mount of the whole disk); the cap is reported like the others.
const MAX_ENTRIES: usize = 50_000;

/// The first bytes of a file are checked for NUL: a binary match is noise, and rendering it as
/// text floods the answer with replacement characters.
const SNIFF_BYTES: usize = 8 * 1024;

pub struct SearchFiles {
    root: PathBuf,
    max_bytes: usize,
}

impl SearchFiles {
    pub fn new(root: PathBuf, max_bytes: usize) -> Self {
        Self { root, max_bytes }
    }
}

/// What the call asked for, after the defaults are filled in.
struct Query {
    pattern: String,
    path: String,
    target: Target,
    file_glob: Option<String>,
    context: usize,
    mode: Mode,
    limit: usize,
    offset: usize,
    order: Order,
}

#[derive(PartialEq, Eq, Clone, Copy)]
enum Target {
    Content,
    Files,
}

#[derive(PartialEq, Eq, Clone, Copy)]
enum Mode {
    Content,
    FilesOnly,
    Count,
}

#[derive(PartialEq, Eq, Clone, Copy)]
enum Order {
    Discovery,
    Modified,
}

impl Query {
    fn from_args(args: &Value) -> Result<Self, ToolError> {
        let target = match args.get("target").and_then(Value::as_str) {
            None | Some("content") => Target::Content,
            Some("files") => Target::Files,
            Some(other) => {
                return Err(ToolError::InvalidArgs(format!(
                    "`target` is `content` or `files`, not `{other}`"
                )))
            }
        };
        let mode = match args.get("output_mode").and_then(Value::as_str) {
            None => {
                if target == Target::Files {
                    Mode::FilesOnly
                } else {
                    Mode::Content
                }
            }
            Some("content") => Mode::Content,
            Some("files_only") => Mode::FilesOnly,
            Some("count") => Mode::Count,
            Some(other) => {
                return Err(ToolError::InvalidArgs(format!(
                    "`output_mode` is `content`, `files_only` or `count`, not `{other}`"
                )))
            }
        };
        let order = match args.get("order").and_then(Value::as_str) {
            None | Some("discovery") => Order::Discovery,
            Some("modified") => Order::Modified,
            Some(other) => {
                return Err(ToolError::InvalidArgs(format!(
                    "`order` is `discovery` or `modified`, not `{other}`"
                )))
            }
        };
        let number = |key: &str, default: i64, low: i64, high: i64| -> Result<usize, ToolError> {
            match args.get(key) {
                None => Ok(default as usize),
                Some(v) => v
                    .as_i64()
                    .filter(|n| *n >= low && *n <= high)
                    .map(|n| n as usize)
                    .ok_or_else(|| {
                        ToolError::InvalidArgs(format!("`{key}` is a number from {low} to {high}"))
                    }),
            }
        };
        Ok(Self {
            pattern: str_arg(args, "pattern")?.to_string(),
            path: args
                .get("path")
                .and_then(Value::as_str)
                .unwrap_or(".")
                .to_string(),
            target,
            file_glob: args
                .get("file_glob")
                .and_then(Value::as_str)
                .map(str::to_string),
            context: number("context", 0, 0, 20)?,
            mode,
            limit: number(
                "limit",
                if target == Target::Files { 100 } else { 50 },
                1,
                5_000,
            )?,
            offset: number("offset", 0, 0, 1_000_000)?,
            order,
        })
    }
}

/// One file found by the walk, with what the caller may need about it.
struct Found {
    path: PathBuf,
    /// Relative to the search root, which is how every line of output is spelled.
    shown: String,
    modified: Option<std::time::SystemTime>,
}

#[async_trait]
impl Tool for SearchFiles {
    fn name(&self) -> &str {
        "search_files"
    }

    fn description(&self) -> &str {
        "Find where something is in the workspace, instead of reading files one at a time. \
`target: \"content\"` matches `pattern` as a regular expression against one line at a time and \
answers `path:line:content`; `file_glob` narrows to file names, `context` adds lines either side, \
and `output_mode` picks `content`, `files_only` or `count`. `target: \"files\"` matches file names \
(a glob like `*.rs`, or a plain substring) and answers one path per line, newest first with \
`order: \"modified\"`. `.git`, `node_modules`, `target` and virtualenvs are not walked. Stops at \
`limit` matches and says so; `offset` pages through a wide search."
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "pattern": {
                    "type": "string",
                    "description": "Regular expression matched against one line at a time (target `content`), or a file-name glob / substring (target `files`)"
                },
                "path": {
                    "type": "string",
                    "description": "Directory to walk, relative to the workspace (default `.`)"
                },
                "target": {
                    "type": "string",
                    "enum": ["content", "files"],
                    "description": "`content` searches inside files (default); `files` searches file names"
                },
                "file_glob": {
                    "type": "string",
                    "description": "Only files whose name matches this glob, e.g. `*.rs` (target `content`)"
                },
                "context": {
                    "type": "integer",
                    "description": "Lines before and after each match (0-20, default 0)"
                },
                "output_mode": {
                    "type": "string",
                    "enum": ["content", "files_only", "count"],
                    "description": "`content` prints matching lines, `files_only` one path per file, `count` a per-file histogram"
                },
                "limit": {
                    "type": "integer",
                    "description": "Stop after this many matches (default 50) or files (default 100)"
                },
                "offset": {
                    "type": "integer",
                    "description": "Skip this many matches first, to page through a wide result"
                },
                "order": {
                    "type": "string",
                    "enum": ["discovery", "modified"],
                    "description": "Walk order (default) or newest-modified first (target `files`)"
                }
            },
            "required": ["pattern"]
        })
    }

    fn describe_call(&self, args: &Value) -> String {
        let pattern = args["pattern"].as_str().unwrap_or("?");
        let where_ = args["path"].as_str().unwrap_or(".");
        if args["target"].as_str() == Some("files") {
            return format!("search for files named {pattern} in {where_}");
        }
        format!("search {where_} for {pattern}")
    }

    async fn call(&self, args: Value) -> Result<String, ToolError> {
        let query = Query::from_args(&args)?;
        let start = confine(&self.root, &query.path)?;
        if !start.is_dir() {
            return Err(ToolError::Failed(format!(
                "{}: not a directory",
                query.path
            )));
        }
        // The walk is blocking work over the filesystem, and the cap above is what keeps it
        // short; doing it off the runtime keeps one slow search from stalling a run's stream.
        let root = self.root.clone();
        let max_bytes = self.max_bytes;
        tokio::task::spawn_blocking(move || run(&root, &start, &query, max_bytes))
            .await
            .map_err(|e| ToolError::Failed(format!("search panicked: {e}")))?
    }
}

/// How much NFA a supplied pattern may compile (`#427`). A megabyte is far past any pattern a
/// search needs and far short of what a pathological one would build.
const NFA_SIZE_LIMIT: usize = 1 << 20;

fn run(root: &Path, start: &Path, query: &Query, max_bytes: usize) -> Result<String, ToolError> {
    let matcher = match query.target {
        Target::Content => Some(
            // `#427`: a pattern is model-supplied and its NFA is not bounded by anything else, so
            // compiling `(a|b|c|…){1,1000}` could cost whatever it liked before the first file was
            // read. One megabyte of NFA refuses the monstrosity and leaves every real pattern
            // (a grep, a symbol, a line shape) untouched.
            regex_automata::meta::Regex::builder()
                .configure(
                    regex_automata::meta::Config::new()
                        .nfa_size_limit(Some(NFA_SIZE_LIMIT))
                        .dfa_size_limit(Some(NFA_SIZE_LIMIT)),
                )
                .build(&query.pattern)
                .map_err(|e| ToolError::InvalidArgs(format!("`pattern` is not a regex: {e}")))?,
        ),
        Target::Files => None,
    };
    let mut files = walk(start, root, query.order)?;
    if query.order == Order::Modified {
        files.sort_by(|a, b| b.modified.cmp(&a.modified).then(a.shown.cmp(&b.shown)));
    }

    match query.target {
        Target::Files => Ok(list_files(files, query)),
        Target::Content => Ok(search_content(
            files,
            matcher.as_ref().expect("a content search has a matcher"),
            query,
            max_bytes,
        )),
    }
}

/// Every regular file under `start`, skipping the ignored directories, not following symlinks.
///
/// Symlinks are skipped rather than resolved: `confine` already refuses a path that leaves the
/// workspace, but a walk that follows links can still leave and come back, and "the search says
/// the file is in the workspace" is worth keeping simple.
fn walk(start: &Path, root: &Path, order: Order) -> Result<Vec<Found>, ToolError> {
    let mut out = Vec::new();
    let mut stack = vec![start.to_path_buf()];
    let mut looked = 0usize;
    while let Some(dir) = stack.pop() {
        let entries = match std::fs::read_dir(&dir) {
            Ok(entries) => entries,
            // An unreadable directory is not an error the caller can act on: it is walked past,
            // the way `rg` walks past it.
            Err(_) => continue,
        };
        for entry in entries.flatten() {
            looked += 1;
            if looked > MAX_ENTRIES {
                return Ok(out);
            }
            let name = entry.file_name().to_string_lossy().into_owned();
            let path = entry.path();
            let Ok(kind) = entry.file_type() else {
                continue;
            };
            if kind.is_dir() {
                if !SKIP_DIRS.contains(&name.as_str()) {
                    stack.push(path);
                }
                continue;
            }
            if !kind.is_file() {
                continue;
            }
            let shown = path
                .strip_prefix(root)
                .unwrap_or(&path)
                .display()
                .to_string();
            let modified = if order == Order::Modified {
                entry.metadata().ok().and_then(|m| m.modified().ok())
            } else {
                None
            };
            out.push(Found {
                path,
                shown,
                modified,
            });
        }
    }
    out.sort_by(|a, b| a.shown.cmp(&b.shown));
    Ok(out)
}

fn list_files(files: Vec<Found>, query: &Query) -> String {
    let wanted: Vec<&Found> = files
        .iter()
        .filter(|f| {
            let name = f.path.file_name().unwrap_or_default().to_string_lossy();
            name_matches(&query.pattern, &name)
        })
        .collect();
    let total = wanted.len();
    let page: Vec<&Found> = wanted
        .into_iter()
        .skip(query.offset)
        .take(query.limit)
        .collect();
    if page.is_empty() {
        return format!(
            "no file name matches `{}` under {}",
            query.pattern,
            if query.path.is_empty() {
                "."
            } else {
                &query.path
            }
        );
    }
    let mut out: Vec<String> = page.iter().map(|f| f.shown.clone()).collect();
    let shown = out.len();
    if total > query.offset + shown {
        out.push(format!(
            "[{} of {total} files — raise `limit` or narrow the pattern]",
            query.offset + shown
        ));
    }
    out.join("\n")
}

fn search_content(
    files: Vec<Found>,
    matcher: &regex_automata::meta::Regex,
    query: &Query,
    max_bytes: usize,
) -> String {
    // The registry would cut a long answer mid-line and say `[output truncated]`. Stopping here
    // instead keeps the answer a set of whole matches and says which cap it hit, which is the
    // difference between a page someone can use and a page someone has to re-run.
    let budget = max_bytes.saturating_sub(256);
    let mut out = String::new();
    let mut capped = false;
    let mut matches_seen = 0usize; // counted before `offset`, so paging is stable
    let mut printed = 0usize;
    let mut skipped_big = 0usize;
    let mut binary = 0usize;
    // `count` and `files_only` print one line per file, so they page by file, not by match.
    let per_file = query.mode != Mode::Content;
    let mut files_printed = 0usize;

    'files: for file in files {
        if let Some(glob) = &query.file_glob {
            let name = file.path.file_name().unwrap_or_default().to_string_lossy();
            if !glob_matches(glob, &name) {
                continue;
            }
        }
        let Ok(meta) = std::fs::metadata(&file.path) else {
            continue;
        };
        if meta.len() > MAX_FILE_BYTES {
            skipped_big += 1;
            continue;
        }
        let Ok(bytes) = std::fs::read(&file.path) else {
            continue;
        };
        let head = &bytes[..bytes.len().min(SNIFF_BYTES)];
        if head.contains(&0u8) {
            binary += 1;
            continue;
        }
        let text = String::from_utf8_lossy(&bytes);
        let lines: Vec<&str> = text.lines().collect();
        let hits: Vec<usize> = lines
            .iter()
            .enumerate()
            .filter(|(_, line)| matcher.is_match(line.as_bytes()))
            .map(|(i, _)| i)
            .collect();
        if hits.is_empty() {
            continue;
        }
        if per_file {
            if matches_seen + hits.len() <= query.offset {
                matches_seen += hits.len();
                continue;
            }
            if files_printed >= query.offset + query.limit {
                matches_seen += hits.len();
                continue;
            }
            files_printed += 1;
            if files_printed > query.offset {
                match query.mode {
                    Mode::FilesOnly => out.push_str(&format!("{}\n", file.shown)),
                    Mode::Count => {
                        out.push_str(&format!("{}:{}\n", file.shown, hits.len()));
                    }
                    Mode::Content => {}
                }
            }
            matches_seen += hits.len();
            if files_printed >= query.offset + query.limit {
                break 'files;
            }
            continue;
        }
        for i in &hits {
            matches_seen += 1;
            if matches_seen <= query.offset {
                continue;
            }
            if printed >= query.limit {
                // One match past the page is enough to know more remain; the rest of the walk is
                // spent for nothing.
                break 'files;
            }
            if out.len() >= budget {
                capped = true;
                break 'files;
            }
            if query.context > 0 {
                if !out.is_empty() {
                    out.push_str("--\n");
                }
                let from = i.saturating_sub(query.context);
                let to = (i + query.context).min(lines.len().saturating_sub(1));
                for (j, line) in lines.iter().enumerate().take(to + 1).skip(from) {
                    let sep = if j == *i { ':' } else { '-' };
                    out.push_str(&format!("{}{sep}{}{sep}{}\n", file.shown, j + 1, line));
                }
            } else {
                out.push_str(&format!("{}:{}:{}\n", file.shown, i + 1, lines[*i]));
            }
            printed += 1;
        }
    }

    let mut tail = Vec::new();
    if capped {
        tail.push(format!(
            "[output reached the {max_bytes}-byte cap — narrow the pattern, or page with `offset`]"
        ));
    }
    if printed == 0 && !capped && query.mode == Mode::Content {
        let mut said = format!(
            "no match for `{}` under {}",
            query.pattern,
            if query.path.is_empty() {
                "."
            } else {
                &query.path
            }
        );
        if let Some(glob) = &query.file_glob {
            said.push_str(&format!(" in files named {glob}"));
        }
        if skipped_big > 0 || binary > 0 {
            said.push_str(&format!(
                " ({} file(s) over {} KiB and {binary} binary skipped)",
                skipped_big,
                MAX_FILE_BYTES / 1024
            ));
        }
        return said;
    }
    if printed >= query.limit {
        tail.push(format!(
            "[stopped at {} matches — more may remain; raise `limit` or narrow the pattern]",
            query.limit
        ));
    }
    if skipped_big > 0 {
        tail.push(format!(
            "[{skipped_big} file(s) over {} KiB skipped]",
            MAX_FILE_BYTES / 1024
        ));
    }
    if binary > 0 {
        tail.push(format!("[{binary} binary file(s) skipped]"));
    }
    let body = out.trim_end().to_string();
    if tail.is_empty() {
        return body;
    }
    format!("{body}\n{}", tail.join("\n"))
}

/// `*` and `?` against one file name, plus the substring reading a pattern without either gets.
fn name_matches(pattern: &str, name: &str) -> bool {
    if pattern.contains(['*', '?']) {
        glob_matches(pattern, name)
    } else {
        name.contains(pattern)
    }
}

fn glob_matches(pattern: &str, name: &str) -> bool {
    let p: Vec<char> = pattern.chars().collect();
    let n: Vec<char> = name.chars().collect();
    // Iterative backtracking on `*`, so `*.tar.gz` and `a*b*c` work without a dependency.
    let (mut pi, mut ni) = (0usize, 0usize);
    let (mut star, mut mark) = (None, 0usize);
    while ni < n.len() {
        if pi < p.len() && (p[pi] == '?' || p[pi] == n[ni]) {
            pi += 1;
            ni += 1;
        } else if pi < p.len() && p[pi] == '*' {
            star = Some(pi);
            mark = ni;
            pi += 1;
        } else if let Some(s) = star {
            pi = s + 1;
            mark += 1;
            ni = mark;
        } else {
            return false;
        }
    }
    while pi < p.len() && p[pi] == '*' {
        pi += 1;
    }
    pi == p.len()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn tree(files: &[(&str, &str)]) -> tempdir_lite::Dir {
        let dir = tempdir_lite::Dir::new();
        for (path, body) in files {
            let full = dir.path().join(path);
            std::fs::create_dir_all(full.parent().unwrap()).unwrap();
            std::fs::write(full, body).unwrap();
        }
        dir
    }

    async fn search(dir: &tempdir_lite::Dir, args: Value) -> String {
        SearchFiles::new(dir.path().to_path_buf(), 60_000)
            .call(args)
            .await
            .unwrap()
    }

    /// `#427`: a supplied pattern is compiled before a single file is read, and the size of the
    /// machine it builds was bounded by nothing. A repetition over a wide union is a few hundred
    /// bytes of text and tens of megabytes of NFA, which is the shape that costs whatever it likes.
    #[tokio::test]
    async fn a_pattern_whose_nfa_is_too_large_is_refused() {
        let dir = tree(&[("a.txt", "hello\n")]);
        // A bounded repetition over any-byte, from a 12-character pattern: 2 000 copies of the
        // state is past a megabyte and under the library's own 10 MB default, so this tests the
        // cap and not the default. A union of literals was deduplicated away by the compiler.
        let pattern = "(?s).{1,2000}".to_string();
        let err = SearchFiles::new(dir.path().to_path_buf(), 60_000)
            .call(serde_json::json!({"pattern": pattern}))
            .await
            .expect_err("the NFA cap refuses it");
        let message = err.to_string();
        assert!(
            message.contains("not a regex"),
            "it is reported as the bad argument it is: {message}"
        );
    }

    #[tokio::test]
    async fn a_pattern_is_found_with_its_line_and_a_glob_narrows_it() {
        let dir = tree(&[
            ("a.rs", "fn main() {}\nlet needle = 1;\n"),
            ("b.md", "the needle is here too\n"),
            ("sub/c.rs", "// needle in a subdirectory\n"),
        ]);
        let all = search(&dir, json!({"pattern": "needle"})).await;
        assert!(all.contains("a.rs:2:let needle = 1;"), "{all}");
        assert!(all.contains("b.md:1:the needle is here too"), "{all}");
        assert!(
            all.contains(&format!("sub{}c.rs:1", std::path::MAIN_SEPARATOR)),
            "{all}"
        );

        let narrow = search(&dir, json!({"pattern": "needle", "file_glob": "*.rs"})).await;
        assert!(!narrow.contains("b.md"), "{narrow}");
        assert!(narrow.contains("a.rs:2"), "{narrow}");
        assert!(narrow.contains("c.rs:1"), "{narrow}");
    }

    #[tokio::test]
    async fn the_ignored_directories_are_not_walked_and_the_workspace_is_the_fence() {
        let dir = tree(&[
            ("src/a.rs", "needle\n"),
            ("target/debug/junk.rs", "needle\n"),
            ("node_modules/pkg/index.js", "needle\n"),
        ]);
        let found = search(&dir, json!({"pattern": "needle"})).await;
        assert!(found.contains("a.rs:1"), "{found}");
        assert!(!found.contains("target"), "{found}");
        assert!(!found.contains("node_modules"), "{found}");

        let outside = SearchFiles::new(dir.path().to_path_buf(), 60_000)
            .call(json!({"pattern": "needle", "path": "../.."}))
            .await;
        assert!(outside.is_err(), "a path above the workspace is refused");
    }

    #[tokio::test]
    async fn a_limit_is_reported_rather_than_silently_short() {
        let body: String = (1..=80).map(|i| format!("needle {i}\n")).collect();
        let dir = tree(&[("big.txt", &body)]);
        let page = search(&dir, json!({"pattern": "needle", "limit": 5})).await;
        assert_eq!(page.matches("needle ").count(), 5, "{page}");
        assert!(page.contains("stopped at 5 matches"), "{page}");

        let next = search(&dir, json!({"pattern": "needle", "limit": 5, "offset": 5})).await;
        assert!(next.starts_with("big.txt:6:needle 6"), "{next}");
    }

    #[tokio::test]
    async fn context_lines_come_with_the_match_and_are_not_confused_with_it() {
        let dir = tree(&[("a.txt", "one\ntwo\nneedle\nfour\nfive\n")]);
        let with = search(&dir, json!({"pattern": "needle", "context": 1})).await;
        assert!(with.contains("a.txt-2-two"), "{with}");
        assert!(with.contains("a.txt:3:needle"), "{with}");
        assert!(with.contains("a.txt-4-four"), "{with}");
        assert!(!with.contains("one"), "{with}");
    }

    #[tokio::test]
    async fn files_are_found_by_name_and_count_says_how_many_times() {
        let dir = tree(&[
            ("a.rs", "needle\nneedle\n"),
            ("b.rs", "needle\n"),
            ("c.md", "nothing\n"),
        ]);
        let names = search(&dir, json!({"target": "files", "pattern": "*.rs"})).await;
        assert_eq!(
            names.lines().filter(|l| l.ends_with(".rs")).count(),
            2,
            "{names}"
        );
        assert!(!names.contains("c.md"), "{names}");

        let histogram = search(&dir, json!({"pattern": "needle", "output_mode": "count"})).await;
        assert!(histogram.contains("a.rs:2"), "{histogram}");
        assert!(histogram.contains("b.rs:1"), "{histogram}");
        assert!(!histogram.contains("c.md"), "{histogram}");

        let only = search(
            &dir,
            json!({"pattern": "needle", "output_mode": "files_only"}),
        )
        .await;
        assert_eq!(
            only.lines().filter(|l| l.ends_with(".rs")).count(),
            2,
            "{only}"
        );
    }

    #[tokio::test]
    async fn a_pattern_that_is_not_a_regex_is_refused_by_name_and_nothing_is_walked() {
        let dir = tree(&[("a.txt", "x\n")]);
        let err = SearchFiles::new(dir.path().to_path_buf(), 60_000)
            .call(json!({"pattern": "a(b"}))
            .await
            .unwrap_err();
        assert!(err.to_string().contains("not a regex"), "{err}");
    }

    #[tokio::test]
    async fn binary_files_are_skipped_and_said_to_be() {
        let dir = tree(&[("a.txt", "needle\n")]);
        std::fs::write(dir.path().join("blob.bin"), b"needle\x00\x01\x02").unwrap();
        let found = search(&dir, json!({"pattern": "needle"})).await;
        assert!(found.contains("a.txt:1"), "{found}");
        assert!(!found.contains("blob.bin"), "{found}");
    }

    /// #337: these tests share a process and a clock. Two directories made in the same tick must
    /// still be two directories, or one test's `Drop` deletes the tree another is searching.
    #[test]
    fn two_directories_made_together_are_two_directories() {
        let dirs: Vec<tempdir_lite::Dir> = (0..200).map(|_| tempdir_lite::Dir::new()).collect();
        let mut seen: Vec<&std::path::Path> = dirs.iter().map(|d| d.path()).collect();
        seen.sort();
        seen.dedup();
        assert_eq!(seen.len(), 200, "every path is its own");
        for d in &dirs {
            assert!(
                d.path().is_dir(),
                "and every one is there: {}",
                d.path().display()
            );
        }
    }
    #[test]
    fn a_glob_matches_a_name_the_way_a_person_writes_it() {
        assert!(glob_matches("*.rs", "main.rs"));
        assert!(glob_matches("m?in.rs", "main.rs"));
        assert!(glob_matches("*.tar.gz", "a.tar.gz"));
        assert!(!glob_matches("*.rs", "main.rss"));
        assert!(!glob_matches("a*b*c", "abcx"));
        // A pattern with no glob characters is a substring, and the case is the caller's.
        assert!(!name_matches("cargo", "Cargo.toml"));
        assert!(name_matches("Cargo", "Cargo.toml"));
    }
}

#[cfg(test)]
mod tempdir_lite {
    //! A directory that deletes itself, without pulling a dev-dependency in for it.
    //!
    //! The name used to be the clock alone (`as_nanos() ^ (pid << 32)`), and that is not a source of
    //! uniqueness: cargo runs these tests as parallel threads of **one** process, so two of them
    //! calling `new()` inside the same clock tick got the *same* directory — and the first `Drop`
    //! then deleted it from under the second, which saw an empty tree and failed with "no match for
    //! `needle` under .". It happened on a CI runner with a coarse clock (`msrv` on #337) where it
    //! reads as a search bug. A counter makes the name unique per call, which no clock can promise.
    pub struct Dir(std::path::PathBuf);

    impl Dir {
        pub fn new() -> Self {
            static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
            let seq = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            let mut path = std::env::temp_dir();
            let tag: u64 = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos() as u64)
                .unwrap_or(0)
                ^ (std::process::id() as u64) << 32;
            path.push(format!("eclipse-search-{tag:x}-{seq}"));
            std::fs::create_dir_all(&path).unwrap();
            Self(path)
        }

        pub fn path(&self) -> &std::path::Path {
            &self.0
        }
    }

    impl Drop for Dir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }
}