Skip to main content

lean_ctx/tools/
ctx_search.rs

1use std::collections::HashSet;
2use std::path::Path;
3use std::path::PathBuf;
4use std::time::{Duration, Instant};
5
6use glob::Pattern;
7use ignore::WalkBuilder;
8use regex::RegexBuilder;
9
10use crate::core::protocol;
11use crate::core::symbol_map::{self, SymbolMap};
12use crate::core::tokens::count_tokens;
13use crate::tools::CrpMode;
14
15pub(crate) const MAX_FILE_SIZE: u64 = 512_000;
16pub(crate) const MAX_WALK_DEPTH: usize = 20;
17const MAX_MATCH_LINE_WIDTH: usize = 150;
18
19/// Modeled baseline for the *estimated* savings series (GL #479 D1): a native
20/// agent grep tool ships matches with surrounding context lines, per-file
21/// headers and line numbers, which is roughly 2.5x the tokens of the bare
22/// match lines lean-ctx observes. This factor is a documented model
23/// assumption — it feeds `stats.json` ("estimated") only. The signed savings
24/// ledger ("verified") records `observed_tokens` without any factor applied.
25pub const NATIVE_GREP_BASELINE_FACTOR: f64 = 2.5;
26
27/// Result of a search: the rendered output plus both baseline figures.
28pub struct SearchOutcome {
29    /// Rendered, compressed search output.
30    pub text: String,
31    /// Modeled native-tool baseline (`observed_tokens` x [`NATIVE_GREP_BASELINE_FACTOR`]).
32    /// Feeds the estimated stats series.
33    pub modeled_baseline: usize,
34    /// Tokens actually measured in the raw match lines — no model applied.
35    /// Feeds the verified savings ledger.
36    pub observed_tokens: usize,
37}
38
39impl SearchOutcome {
40    fn error(text: String) -> Self {
41        Self {
42            text,
43            modeled_baseline: 0,
44            observed_tokens: 0,
45        }
46    }
47
48    fn from_observed(text: String, observed_tokens: usize) -> Self {
49        let modeled = (observed_tokens as f64 * NATIVE_GREP_BASELINE_FACTOR).ceil() as usize;
50        Self {
51            text,
52            modeled_baseline: modeled.max(observed_tokens),
53            observed_tokens,
54        }
55    }
56}
57
58/// Wall-clock budget for a single `ctx_search` call. The regular-file guard in
59/// the read loop removes the known infinite block — `read_to_string` on a
60/// FIFO/socket/device (#336) — while this deadline is the backstop for any
61/// *other* pathological case (a gigantic corpus, a stuck network mount): the
62/// tool returns partial results with a hint instead of appearing to hang.
63/// Tunable via `LEAN_CTX_SEARCH_DEADLINE_MS` (`0` disables). Default 10s.
64fn search_deadline() -> Option<Duration> {
65    const DEFAULT_MS: u64 = 10_000;
66    let ms = std::env::var("LEAN_CTX_SEARCH_DEADLINE_MS")
67        .ok()
68        .and_then(|v| v.trim().parse::<u64>().ok())
69        .unwrap_or(DEFAULT_MS);
70    (ms > 0).then(|| Duration::from_millis(ms))
71}
72
73/// Searches files for a regex pattern with compressed output and monorepo scope hints.
74pub fn handle(
75    pattern: &str,
76    dir: &str,
77    include: Option<&str>,
78    max_results: usize,
79    _crp_mode: CrpMode,
80    respect_gitignore: bool,
81    allow_secret_paths: bool,
82) -> SearchOutcome {
83    // `include` is a glob matched against each file's path *relative to* `dir`
84    // (e.g. `*.ts`, `*.{rs,ts}`, `src/**/*.tsx`). Brace alternation is expanded
85    // here because the `glob` crate has no native support for it. An empty result
86    // (no `include`, or only unparsable globs) means "no filter", so a typo never
87    // silently drops every match.
88    let include_patterns = compile_include(include);
89    const MAX_PATTERN_LEN: usize = 1024;
90    const MAX_REGEX_SIZE: usize = 1 << 20; // 1 MiB DFA limit
91
92    let redact = crate::core::redaction::redaction_enabled_for_active_role();
93    if pattern.len() > MAX_PATTERN_LEN {
94        return SearchOutcome::error(format!(
95            "ERROR: pattern too long ({} > {MAX_PATTERN_LEN} chars)",
96            pattern.len()
97        ));
98    }
99    let re = match RegexBuilder::new(pattern)
100        .size_limit(MAX_REGEX_SIZE)
101        .dfa_size_limit(MAX_REGEX_SIZE)
102        .build()
103    {
104        Ok(r) => r,
105        Err(e) => return SearchOutcome::error(format!("ERROR: invalid regex: {e}")),
106    };
107
108    let root = Path::new(dir);
109    if !root.exists() {
110        return SearchOutcome::error(format!("ERROR: {dir} does not exist"));
111    }
112    // Broad-root guard (#356 class): with cwd == $HOME a defaulted `path`
113    // would walk the whole home dir and trip macOS TCC privacy prompts.
114    if let Some(err) = crate::tools::walk_guard::deny_unsafe_walk_root(dir) {
115        return SearchOutcome::error(err);
116    }
117
118    let mut files: Vec<PathBuf> = Vec::new();
119    let mut matches = Vec::new();
120    let mut raw_tokens_accum: usize = 0;
121    let mut files_searched = 0u32;
122    let mut files_skipped_size = 0u32;
123    let mut files_skipped_encoding = 0u32;
124    let mut files_skipped_boundary = 0u32;
125    let mut files_skipped_special = 0u32;
126    let mut deadline_hit = false;
127
128    // Fast path: a warm resident trigram index narrows the candidate files in
129    // memory, eliminating the per-call directory walk + full-corpus read. The
130    // index covers the exact same file universe as the walk below, and matches
131    // are still verified line-by-line with the same regex — so results are
132    // identical. Missing/stale index → returns None and triggers a background
133    // (re)build; this call uses the walk fallback.
134    let used_index = if let Some(idx) =
135        crate::core::search_index::get_fresh(dir, respect_gitignore, allow_secret_paths)
136    {
137        files = idx
138            .candidate_paths(pattern, &include_patterns, root)
139            .into_paths();
140        true
141    } else {
142        false
143    };
144
145    if !used_index {
146        // Vendor dirs (node_modules, …) follow the gitignore toggle: explicitly
147        // disabling gitignore is the escape hatch to look inside them (#400).
148        let walker = WalkBuilder::new(root)
149            .hidden(true)
150            .max_depth(Some(MAX_WALK_DEPTH))
151            .git_ignore(respect_gitignore)
152            .git_global(respect_gitignore)
153            .git_exclude(respect_gitignore)
154            .require_git(false)
155            .filter_entry(move |e| {
156                if respect_gitignore {
157                    crate::core::walk_filter::keep_entry(e)
158                } else {
159                    crate::core::cloud_files::keep_entry(e)
160                }
161            })
162            .build();
163
164        for entry in walker.filter_map(std::result::Result::ok) {
165            if entry.file_type().is_none_or(|ft| ft.is_dir()) {
166                continue;
167            }
168
169            if entry.file_type().is_some_and(|ft| ft.is_symlink()) {
170                continue;
171            }
172
173            let path = entry.path();
174
175            if is_binary_ext(path) || is_generated_file(path) {
176                continue;
177            }
178
179            if !allow_secret_paths && crate::core::io_boundary::is_secret_like(path).is_some() {
180                files_skipped_boundary += 1;
181                continue;
182            }
183
184            if !include_patterns.is_empty() {
185                let rel = path.strip_prefix(root).unwrap_or(path);
186                let rel_str = rel.to_string_lossy();
187                if !include_patterns.iter().any(|p| p.matches(&rel_str)) {
188                    continue;
189                }
190            }
191
192            // Size / regular-file filtering happens once in the shared read loop
193            // below, so the walk path and the trigram-index fast path apply the
194            // exact same eligibility rules.
195            files.push(path.to_path_buf());
196        }
197    }
198
199    // Deterministic search: stable file ordering makes max_results truncation reproducible.
200    files.sort_unstable_by(|a, b| a.as_os_str().cmp(b.as_os_str()));
201
202    let root_str = root.to_string_lossy();
203    let deadline = search_deadline().map(|budget| Instant::now() + budget);
204    for path in &files {
205        if matches.len() >= max_results {
206            break;
207        }
208
209        // Stop gracefully instead of appearing to hang on a pathological corpus
210        // or a stuck read (#336): once the wall-clock budget is spent, return
211        // the partial results gathered so far with a hint to narrow the search.
212        if deadline.is_some_and(|dl| Instant::now() >= dl) {
213            deadline_hit = true;
214            break;
215        }
216
217        // Only ever read regular files within the size budget. A FIFO, socket or
218        // device node would block `read_to_string` forever — the root cause of
219        // #336 — and oversized or unstatable files are skipped. `metadata`
220        // (stat) never opens the file, so it cannot block on a special file.
221        let state = match std::fs::metadata(path) {
222            Ok(meta) if !meta.file_type().is_file() => {
223                files_skipped_special += 1;
224                continue;
225            }
226            Ok(meta) if meta.len() > MAX_FILE_SIZE => {
227                files_skipped_size += 1;
228                continue;
229            }
230            Ok(meta) => crate::core::content_cache::FileState::from_metadata(&meta),
231            Err(_) => {
232                files_skipped_encoding += 1;
233                continue;
234            }
235        };
236
237        // Reuse the copy the trigram-index build already read (issue #148): the
238        // corpus is read from disk once and the regex-verify pass here is an
239        // in-memory hit. On a miss (cold cache / evicted) read once and publish
240        // it for the next caller. `(mtime, size)` validation guarantees we never
241        // verify against stale bytes.
242        let content: std::sync::Arc<str> =
243            if let Some(cached) = state.and_then(|s| crate::core::content_cache::get(path, s)) {
244                cached
245            } else {
246                let Ok(text) = std::fs::read_to_string(path) else {
247                    files_skipped_encoding += 1;
248                    continue;
249                };
250                let arc: std::sync::Arc<str> = std::sync::Arc::from(text);
251                if let Some(s) = state {
252                    crate::core::content_cache::insert(path, s, std::sync::Arc::clone(&arc));
253                }
254                arc
255            };
256
257        files_searched += 1;
258
259        for (i, line) in content.lines().enumerate() {
260            if re.is_match(line) {
261                let short_path =
262                    protocol::shorten_path_relative(&path.to_string_lossy(), &root_str);
263                // Count raw tokens incrementally (avoids separate Vec + join)
264                raw_tokens_accum += count_tokens(line.trim()) + 2;
265                let mut shown = if redact {
266                    crate::core::redaction::redact_text(line.trim())
267                } else {
268                    line.trim().to_string()
269                };
270                if shown.len() > MAX_MATCH_LINE_WIDTH {
271                    shown.truncate(shown.floor_char_boundary(MAX_MATCH_LINE_WIDTH));
272                    shown.push_str("...");
273                }
274                matches.push(format!("{short_path}:{} {}", i + 1, shown));
275                if matches.len() >= max_results {
276                    break;
277                }
278            }
279        }
280    }
281
282    if matches.is_empty() {
283        let mut msg = format!("0 matches for '{pattern}' in {files_searched} files");
284        if files_skipped_size > 0 {
285            msg.push_str(&format!(" ({files_skipped_size} large files skipped)"));
286        }
287        if files_skipped_encoding > 0 {
288            msg.push_str(&format!(
289                " ({files_skipped_encoding} files skipped: binary/encoding)"
290            ));
291        }
292        if files_skipped_boundary > 0 {
293            msg.push_str(&format!(
294                " ({files_skipped_boundary} secret-like files skipped by boundary policy)"
295            ));
296        }
297        if files_skipped_special > 0 {
298            msg.push_str(&format!(
299                " ({files_skipped_special} special files skipped: not regular files)"
300            ));
301        }
302        if deadline_hit {
303            msg.push_str(
304                " (search stopped at the time budget — refine the pattern or scope with path=)",
305            );
306        }
307        return SearchOutcome::error(msg);
308    }
309
310    // Prefix-cache-friendly: structural file list before per-query match content
311    let matched_files: Vec<&str> = {
312        let mut seen = HashSet::new();
313        matches
314            .iter()
315            .filter_map(|m| {
316                let file = extract_file_from_match(m);
317                if seen.insert(file) {
318                    Some(file)
319                } else {
320                    None
321                }
322            })
323            .collect()
324    };
325
326    let mut result = format!("{} matches in {} files", matches.len(), files_searched);
327    if matched_files.len() > 1 {
328        if matched_files.len() <= 10 {
329            result.push_str(" [");
330            result.push_str(&matched_files.join(", "));
331            result.push(']');
332        } else {
333            let shown: Vec<&str> = matched_files.iter().take(8).copied().collect();
334            result.push_str(&format!(
335                " [{}, +{} more]",
336                shown.join(", "),
337                matched_files.len() - 8
338            ));
339        }
340    }
341    result.push_str(":\n");
342    result.push_str(&matches.join("\n"));
343
344    if files_skipped_size > 0 {
345        result.push_str(&format!("\n({files_skipped_size} files >512KB skipped)"));
346    }
347    if files_skipped_encoding > 0 {
348        result.push_str(&format!(
349            "\n({files_skipped_encoding} files skipped: binary/encoding)"
350        ));
351    }
352    if files_skipped_boundary > 0 {
353        result.push_str(&format!(
354            "\n({files_skipped_boundary} secret-like files skipped by boundary policy)"
355        ));
356    }
357    if files_skipped_special > 0 {
358        result.push_str(&format!(
359            "\n({files_skipped_special} special files skipped: not regular files)"
360        ));
361    }
362    if deadline_hit {
363        result.push_str(&format!(
364            "\n(search stopped after the {}s budget — {files_searched} files scanned; \
365             refine the pattern or scope with path= for full coverage)",
366            search_deadline().map_or(0, |d| d.as_secs())
367        ));
368    }
369
370    // Determinism contract (#498): the hint must be a pure function of the
371    // results. A show-once AtomicBool here made the first call differ from
372    // every repeat, breaking byte-stability for provider prompt caches.
373    let scope_hint = monorepo_scope_hint(&matches, dir);
374
375    if let Some(delta) = crate::core::search_delta::compute_delta(pattern, &matches) {
376        return SearchOutcome::from_observed(delta, raw_tokens_accum);
377    }
378
379    if symbol_map::substitution_enabled() {
380        let exts = extract_extensions(include);
381        let ext_refs: Vec<&str> = exts.iter().map(String::as_str).collect();
382        let mut sym = SymbolMap::new();
383        let idents = symbol_map::extract_identifiers(&result, &ext_refs);
384        for ident in &idents {
385            sym.register(ident);
386        }
387        if sym.len() >= 3 {
388            let sym_table = sym.format_table();
389            let compressed = sym.apply(&result);
390            let original_tok = count_tokens(&result);
391            let compressed_tok = count_tokens(&compressed) + count_tokens(&sym_table);
392            let net_saving = original_tok.saturating_sub(compressed_tok);
393            if original_tok > 0 && net_saving * 100 / original_tok >= 5 {
394                result = format!("{compressed}{sym_table}");
395            }
396        }
397    }
398
399    if let Some(hint) = scope_hint {
400        result.push_str(&hint);
401    }
402
403    SearchOutcome::from_observed(result, raw_tokens_accum)
404}
405
406pub(crate) fn is_binary_ext(path: &Path) -> bool {
407    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
408    matches!(
409        ext,
410        "png"
411            | "jpg"
412            | "jpeg"
413            | "gif"
414            | "webp"
415            | "ico"
416            | "svg"
417            | "woff"
418            | "woff2"
419            | "ttf"
420            | "eot"
421            | "pdf"
422            | "zip"
423            | "tar"
424            | "gz"
425            | "br"
426            | "zst"
427            | "bz2"
428            | "xz"
429            | "mp3"
430            | "mp4"
431            | "webm"
432            | "ogg"
433            | "wasm"
434            | "so"
435            | "dylib"
436            | "dll"
437            | "exe"
438            | "lock"
439            | "map"
440            | "snap"
441            | "patch"
442            | "db"
443            | "sqlite"
444            | "parquet"
445            | "arrow"
446            | "bin"
447            | "o"
448            | "a"
449            | "class"
450            | "pyc"
451            | "pyo"
452    )
453}
454
455pub(crate) fn is_generated_file(path: &Path) -> bool {
456    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
457    name.ends_with(".min.js")
458        || name.ends_with(".min.css")
459        || name.ends_with(".bundle.js")
460        || name.ends_with(".chunk.js")
461        || name.ends_with(".d.ts")
462        || name.ends_with(".js.map")
463        || name.ends_with(".css.map")
464}
465
466/// Upper bound on the number of globs a single `include` may expand to, so a
467/// pathological brace pattern (`{a,b}{c,d}{e,f}…`) can never blow up.
468const MAX_INCLUDE_GLOBS: usize = 64;
469
470/// Compile an `include` filter into one or more matchers.
471///
472/// Brace alternation (`*.{rs,ts}`) is expanded to multiple globs (`*.rs`,
473/// `*.ts`) because the `glob` crate matches `{` / `}` literally. A file is
474/// included when it matches *any* of the returned patterns. An empty vec means
475/// "no filter": `include` was `None`, or every expansion failed to parse.
476fn compile_include(include: Option<&str>) -> Vec<Pattern> {
477    let Some(raw) = include else {
478        return Vec::new();
479    };
480    expand_braces(raw)
481        .into_iter()
482        .take(MAX_INCLUDE_GLOBS)
483        .filter_map(|g| Pattern::new(&g).ok())
484        .collect()
485}
486
487/// Expand one or more `{a,b,c}` brace groups into the cartesian set of concrete
488/// globs. Patterns without braces (or with an unbalanced brace) are returned
489/// unchanged, so this is safe to call on any input.
490fn expand_braces(pattern: &str) -> Vec<String> {
491    let Some(open) = pattern.find('{') else {
492        return vec![pattern.to_string()];
493    };
494    let Some(close_rel) = pattern[open..].find('}') else {
495        return vec![pattern.to_string()];
496    };
497    let close = open + close_rel;
498    let prefix = &pattern[..open];
499    let inner = &pattern[open + 1..close];
500    let suffix = &pattern[close + 1..];
501
502    let mut out = Vec::new();
503    for alt in inner.split(',') {
504        let alt = alt.trim();
505        for expanded_suffix in expand_braces(suffix) {
506            out.push(format!("{prefix}{alt}{expanded_suffix}"));
507            if out.len() >= MAX_INCLUDE_GLOBS {
508                return out;
509            }
510        }
511    }
512    out
513}
514
515/// Extract the file extensions referenced by an `include` glob, used by the
516/// symbol-substitution pass (which keyword-filters per language).
517///
518/// Only the final path component is inspected, so dots inside directory
519/// segments never leak in. Handles a single trailing extension (`*.rs` → `rs`)
520/// and brace expansion (`*.{rs,ts}` → `rs`, `ts`); a glob without an extension
521/// (`src/**/*`) yields an empty list. Unknown extensions are returned verbatim —
522/// `symbol_map::is_keyword` simply treats them as "no keywords", so no allowlist
523/// has to be kept in sync here.
524fn extract_extensions(include: Option<&str>) -> Vec<String> {
525    let Some(pattern) = include else {
526        return Vec::new();
527    };
528    let filename = pattern.rsplit('/').next().unwrap_or(pattern);
529    let Some(dot) = filename.rfind('.') else {
530        return Vec::new();
531    };
532    let ext_part = &filename[dot + 1..];
533
534    if let Some(inner) = ext_part.strip_prefix('{').and_then(|s| s.strip_suffix('}')) {
535        return inner
536            .split(',')
537            .map(|e| e.trim().to_string())
538            .filter(|e| !e.is_empty())
539            .collect();
540    }
541
542    if ext_part.is_empty() {
543        return Vec::new();
544    }
545    vec![ext_part.to_string()]
546}
547
548/// Extract file path from a grep match line, handling Windows drive letters (e.g. "C:").
549fn extract_file_from_match(line: &str) -> &str {
550    let start = if line.len() >= 2
551        && line.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
552        && line.as_bytes().get(1) == Some(&b':')
553    {
554        2
555    } else {
556        0
557    };
558    match line[start..].find(':') {
559        Some(pos) => &line[..start + pos],
560        None => line,
561    }
562}
563
564fn monorepo_scope_hint(matches: &[String], search_dir: &str) -> Option<String> {
565    let top_dirs: HashSet<&str> = matches
566        .iter()
567        .filter_map(|m| {
568            let path = extract_file_from_match(m);
569            let relative = path.strip_prefix("./").unwrap_or(path);
570            let relative = relative.strip_prefix(search_dir).unwrap_or(relative);
571            let relative = relative.strip_prefix('/').unwrap_or(relative);
572            relative.split('/').next()
573        })
574        .collect();
575
576    if top_dirs.len() > 3 {
577        let mut dirs: Vec<&&str> = top_dirs.iter().collect();
578        dirs.sort();
579        let dir_list: Vec<String> = dirs.iter().take(6).map(|d| format!("'{d}'")).collect();
580        let extra = if top_dirs.len() > 6 {
581            format!(", +{} more", top_dirs.len() - 6)
582        } else {
583            String::new()
584        };
585        Some(format!(
586            "\n\nResults span {} directories ({}{}). \
587             Use the 'path' parameter to scope to a specific service, \
588             e.g. path=\"{}/\".",
589            top_dirs.len(),
590            dir_list.join(", "),
591            extra,
592            dirs[0]
593        ))
594    } else {
595        None
596    }
597}
598
599#[cfg(test)]
600mod tests {
601    use super::*;
602    use crate::tools::CrpMode;
603
604    /// Determinism contract (#498): identical search over identical files
605    /// must produce byte-identical output — a prerequisite for provider
606    /// prompt-cache hits on repeated tool results.
607    #[test]
608    fn search_output_is_byte_stable_across_calls() {
609        let dir = tempfile::tempdir().unwrap();
610        for i in 0..5 {
611            std::fs::write(
612                dir.path().join(format!("f{i}.rs")),
613                format!("fn target_{i}() {{}}\nfn other() {{}}\n"),
614            )
615            .unwrap();
616        }
617        let root = dir.path().to_string_lossy().into_owned();
618        let run = || handle("target", &root, Some("*.rs"), 20, CrpMode::Off, true, true).text;
619        assert_eq!(run(), run(), "search output must be deterministic");
620    }
621
622    #[test]
623    fn search_results_are_deterministically_ordered_by_path() {
624        let dir = tempfile::tempdir().unwrap();
625        let a = dir.path().join("a.txt");
626        let b = dir.path().join("b.txt");
627        std::fs::write(&b, "match\n").unwrap();
628        std::fs::write(&a, "match\n").unwrap();
629
630        let out = handle(
631            "match",
632            dir.path().to_string_lossy().as_ref(),
633            Some("*.txt"),
634            10,
635            CrpMode::Off,
636            true,
637            true,
638        )
639        .text;
640
641        let mut match_lines: Vec<&str> = out
642            .lines()
643            .filter(|l| l.contains(".txt:") && l.contains("match"))
644            .collect();
645        // Expect exactly the 2 match lines, ordered a.txt then b.txt.
646        match_lines.truncate(2);
647        assert_eq!(match_lines.len(), 2);
648        assert!(
649            match_lines[0].contains("a.txt:"),
650            "first match should come from a.txt, got: {}",
651            match_lines[0]
652        );
653        assert!(
654            match_lines[1].contains("b.txt:"),
655            "second match should come from b.txt, got: {}",
656            match_lines[1]
657        );
658    }
659
660    #[test]
661    fn warm_index_and_content_cache_path_returns_correct_matches() {
662        // Exercises the trigram-index fast path together with the shared content
663        // cache (#148): the index build reads the corpus once and publishes it,
664        // then this search reuses those bytes. Results must be byte-identical to
665        // the walk path — this asserts that correctness, independent of whether
666        // any individual file is a cache hit or a fallback re-read.
667        let dir = tempfile::tempdir().unwrap();
668        std::fs::write(
669            dir.path().join("a.rs"),
670            "fn authenticate() {}\nlet x = 1;\n",
671        )
672        .unwrap();
673        std::fs::write(dir.path().join("b.rs"), "fn connect() {}\n").unwrap();
674        let root = dir.path().to_string_lossy().to_string();
675
676        // Synchronously warm the resident trigram index (also populates the
677        // shared content cache for these paths).
678        assert!(
679            crate::core::search_index::warm_blocking(&root, true, false),
680            "index should warm for a small clean corpus"
681        );
682
683        let out = handle("authenticate", &root, None, 10, CrpMode::Off, true, false).text;
684        assert!(
685            out.contains("a.rs"),
686            "warm-index + cache search must find the match: {out}"
687        );
688        assert!(
689            out.contains("authenticate"),
690            "the matched line must be present: {out}"
691        );
692        assert!(
693            !out.contains("b.rs"),
694            "a non-matching file must not appear in results: {out}"
695        );
696    }
697
698    #[test]
699    fn symbol_substitution_is_off_by_default() {
700        let _lock = crate::core::data_dir::test_env_lock();
701        std::env::remove_var("LEAN_CTX_SYMBOL_MAP");
702        let dir = tempfile::tempdir().unwrap();
703        let f = dir.path().join("a.rs");
704        std::fs::write(
705            &f,
706            "fn longIdentifierAlpha() {}\nfn longIdentifierBeta() {}\nfn longIdentifierGamma() {}\n",
707        )
708        .unwrap();
709
710        let out = handle(
711            "longIdentifier",
712            dir.path().to_string_lossy().as_ref(),
713            Some("*.rs"),
714            10,
715            CrpMode::Off,
716            true,
717            true,
718        )
719        .text;
720
721        assert!(
722            !out.contains("§MAP"),
723            "default agent-facing output must not carry a §MAP table: {out}"
724        );
725        assert!(
726            !out.contains('α'),
727            "default agent-facing output must not carry α-symbols: {out}"
728        );
729        assert!(
730            out.contains("longIdentifierAlpha"),
731            "identifiers should appear raw by default: {out}"
732        );
733    }
734
735    #[test]
736    fn secret_like_files_are_skipped_by_default() {
737        let dir = tempfile::tempdir().unwrap();
738        let secret = dir.path().join("key.pem");
739        let ok = dir.path().join("ok.txt");
740        std::fs::write(&secret, "match\n").unwrap();
741        std::fs::write(&ok, "match\n").unwrap();
742
743        let out = handle(
744            "match",
745            dir.path().to_string_lossy().as_ref(),
746            None,
747            10,
748            CrpMode::Off,
749            true,
750            false,
751        )
752        .text;
753
754        assert!(out.contains("ok.txt:"), "expected ok.txt match, got: {out}");
755        assert!(
756            !out.contains("key.pem:"),
757            "secret-like file should be skipped, got: {out}"
758        );
759        assert!(
760            out.contains("secret-like files skipped"),
761            "expected boundary skip note, got: {out}"
762        );
763    }
764
765    #[test]
766    #[cfg(unix)]
767    fn search_skips_named_pipe_without_hanging() {
768        use std::sync::mpsc;
769        // #336: a named pipe (FIFO) in the search universe used to block
770        // `read_to_string` forever, hanging the whole call with no output. It
771        // must be skipped, the real file still matched, and the call must return.
772        let dir = tempfile::tempdir().unwrap();
773        std::fs::write(dir.path().join("real.txt"), "needle_here = 1\n").unwrap();
774        let fifo = dir.path().join("pipe.fifo");
775        let c = std::ffi::CString::new(fifo.to_string_lossy().as_bytes()).unwrap();
776        assert_eq!(
777            // SAFETY: `c` is a live CString providing a valid NUL-terminated
778            // path pointer for the duration of the call.
779            unsafe { libc::mkfifo(c.as_ptr(), 0o644) },
780            0,
781            "mkfifo failed"
782        );
783
784        let dir_path = dir.path().to_string_lossy().to_string();
785        let (tx, rx) = mpsc::channel();
786        std::thread::spawn(move || {
787            // Fresh temp dir → no warm index yet, so this exercises the walk path.
788            let out = handle("needle_here", &dir_path, None, 10, CrpMode::Off, true, true).text;
789            let _ = tx.send(out);
790        });
791        let out = rx
792            .recv_timeout(Duration::from_secs(5))
793            .expect("ctx_search hung on a FIFO (#336 regression)");
794
795        assert!(
796            out.contains("real.txt"),
797            "the real file must still match: {out}"
798        );
799        assert!(
800            out.contains("special files skipped"),
801            "the FIFO must be reported as a skipped special file: {out}"
802        );
803    }
804
805    #[test]
806    fn search_deadline_env_override_is_respected() {
807        let _lock = crate::core::data_dir::test_env_lock();
808        std::env::set_var("LEAN_CTX_SEARCH_DEADLINE_MS", "0");
809        assert!(search_deadline().is_none(), "0 must disable the deadline");
810        std::env::set_var("LEAN_CTX_SEARCH_DEADLINE_MS", "250");
811        assert_eq!(search_deadline(), Some(Duration::from_millis(250)));
812        std::env::remove_var("LEAN_CTX_SEARCH_DEADLINE_MS");
813        assert_eq!(
814            search_deadline(),
815            Some(Duration::from_secs(10)),
816            "default budget is 10s"
817        );
818    }
819
820    #[test]
821    fn extract_extensions_handles_single_brace_and_none() {
822        assert_eq!(extract_extensions(Some("*.rs")), vec!["rs"]);
823        assert_eq!(extract_extensions(Some("src/**/*.tsx")), vec!["tsx"]);
824        assert_eq!(extract_extensions(Some("*.{rs,ts}")), vec!["rs", "ts"]);
825        assert_eq!(
826            extract_extensions(Some("*.{rs, ts , js}")),
827            vec!["rs", "ts", "js"]
828        );
829        assert_eq!(extract_extensions(None), Vec::<String>::new());
830    }
831
832    #[test]
833    fn extract_extensions_ignores_dots_in_directory_segments() {
834        // A dot in a directory name must not be mistaken for the extension.
835        assert_eq!(
836            extract_extensions(Some("config.v2/src/**/*.rs")),
837            vec!["rs"]
838        );
839        assert_eq!(extract_extensions(Some("src/v2.0/*.module.ts")), vec!["ts"]);
840        // No extension on the final component → empty.
841        assert_eq!(extract_extensions(Some("src/**/*")), Vec::<String>::new());
842        assert_eq!(
843            extract_extensions(Some("config.v2/Makefile")),
844            Vec::<String>::new()
845        );
846    }
847
848    #[test]
849    fn include_glob_filters_by_brace_expansion() {
850        let dir = tempfile::tempdir().unwrap();
851        std::fs::write(dir.path().join("a.rs"), "needle\n").unwrap();
852        std::fs::write(dir.path().join("b.ts"), "needle\n").unwrap();
853        std::fs::write(dir.path().join("c.py"), "needle\n").unwrap();
854
855        let out = handle(
856            "needle",
857            dir.path().to_string_lossy().as_ref(),
858            Some("*.{rs,ts}"),
859            10,
860            CrpMode::Off,
861            true,
862            true,
863        )
864        .text;
865
866        assert!(out.contains("a.rs"), "rs file must match: {out}");
867        assert!(out.contains("b.ts"), "ts file must match: {out}");
868        assert!(!out.contains("c.py"), "py file must be excluded: {out}");
869    }
870
871    #[test]
872    fn include_glob_recursive_path_pattern() {
873        let dir = tempfile::tempdir().unwrap();
874        std::fs::create_dir_all(dir.path().join("src/inner")).unwrap();
875        std::fs::write(dir.path().join("src/inner/deep.rs"), "needle\n").unwrap();
876        std::fs::write(dir.path().join("top.rs"), "needle\n").unwrap();
877
878        let out = handle(
879            "needle",
880            dir.path().to_string_lossy().as_ref(),
881            Some("src/**/*.rs"),
882            10,
883            CrpMode::Off,
884            true,
885            true,
886        )
887        .text;
888
889        assert!(out.contains("deep.rs"), "nested match expected: {out}");
890        assert!(
891            !out.contains("top.rs"),
892            "root file outside src/ must be excluded: {out}"
893        );
894    }
895
896    #[test]
897    fn search_refuses_home_directory_root() {
898        // #356 class: the MCP server often runs with cwd == $HOME; a defaulted
899        // `path` must never walk the whole home dir (macOS TCC prompts).
900        let home = dirs::home_dir().expect("home dir in test env");
901        let out = handle(
902            "needle",
903            home.to_string_lossy().as_ref(),
904            None,
905            10,
906            CrpMode::Off,
907            true,
908            true,
909        )
910        .text;
911        assert!(
912            out.starts_with("ERROR:") && out.contains("refusing to scan"),
913            "home root must be refused: {out}"
914        );
915    }
916}