geg 0.3.0

Geg Embeds Gemma: offline semantic grep with EmbeddingGemma 2 and persistent vector caching
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
//! Bounded first-pass retrieval for unindexed repositories. Not exhaustive semantic search.
use crate::{
    codegraph,
    hybrid::{self, Bm25Corpus, reciprocal_rank_fusion},
    input,
    search::{Hit, Response, Searcher, Stats, best_score},
};
use anyhow::{Result, ensure};
use std::{
    cmp::{Ordering, Reverse},
    collections::{BTreeMap, BinaryHeap},
    fs::File,
    io::{BufRead, BufReader, IsTerminal},
    path::Path,
    sync::Mutex,
};

struct Candidate {
    path: String,
    line: u64,
    text: String,
    symbol: String,
    lexical: f32,
    boost: f32,
    frequencies: Vec<u32>,
    token_length: usize,
    test_only: bool,
}
impl PartialEq for Candidate {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}
impl Eq for Candidate {}
impl PartialOrd for Candidate {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for Candidate {
    fn cmp(&self, other: &Self) -> Ordering {
        self.lexical
            .total_cmp(&other.lexical)
            .then_with(|| other.path.cmp(&self.path))
            .then_with(|| other.line.cmp(&self.line))
    }
}
struct Selection {
    terms: Vec<String>,
    fuzzy: Vec<nucleo::pattern::Atom>,
    matcher: nucleo::Matcher,
    chunks: BinaryHeap<Reverse<Candidate>>,
    corpus: Bm25Corpus,
    limit: usize,
    code: bool,
}

fn generated(path: &Path) -> bool {
    let name = path
        .file_name()
        .unwrap_or_default()
        .to_string_lossy()
        .to_lowercase();
    name.ends_with(".lock")
        || name.ends_with("-lock.json")
        || name.ends_with(".min.js")
        || matches!(
            name.as_str(),
            "go.sum" | "pnpm-lock.yaml" | "npm-shrinkwrap.json"
        )
}

fn declaration_match(terms: &[String], text: &str) -> bool {
    let lower = text.to_lowercase();
    lower.lines().any(|line| {
        let mut line = line.trim_start();
        for qualifier in [
            "pub ",
            "pub(crate) ",
            "pub(super) ",
            "export ",
            "default ",
            "async ",
            "unsafe ",
        ] {
            if let Some(rest) = line.strip_prefix(qualifier) {
                line = rest;
            }
        }
        ["fn ", "def ", "func ", "function ", "class ", "int "]
            .iter()
            .any(|prefix| {
                line.strip_prefix(prefix).is_some_and(|body| {
                    terms
                        .iter()
                        .filter(|t| t.is_ascii() && t.len() >= 3)
                        .any(|term| {
                            body.strip_prefix(term.as_str())
                                .is_some_and(|tail| tail.starts_with(['(', '<', ':', ' ']))
                        })
                })
            })
    })
}

fn identifiers(text: &str) -> String {
    // Downweight mentions inside examples/comments without changing the embedded source.
    let mut output = String::with_capacity(text.len());
    let mut quoted = false;
    let mut escaped = false;
    for line in text.lines() {
        let mut chars = line.chars().peekable();
        while let Some(c) = chars.next() {
            if !quoted
                && ((c == '/' && chars.peek() == Some(&'/'))
                    || (c == '#' && line.trim_start().starts_with("# ")))
            {
                break;
            }
            if escaped {
                escaped = false;
                continue;
            }
            if quoted && c == '\\' {
                escaped = true;
                continue;
            }
            if c == '"' {
                quoted = !quoted;
                output.push(' ');
                continue;
            }
            if !quoted {
                output.push(c);
            }
        }
        output.push('\n');
    }
    output
}

fn implementation_content(text: &str, in_import: &mut bool) -> bool {
    let mut meaningful = false;
    for line in text.lines().map(str::trim) {
        if *in_import {
            if line.contains(';') {
                *in_import = false;
            }
            continue;
        }
        if line.starts_with("use ") || line.starts_with("pub use ") {
            *in_import = !line.contains(';');
            continue;
        }
        if line.starts_with("import ")
            || line.starts_with("from ")
            || line.starts_with("package ")
            || line.starts_with("#include")
            || line.starts_with("#[")
            || line.starts_with("//")
            || (line.starts_with("mod ") && line.ends_with(';'))
            || line == "Ok(())"
        {
            continue;
        }
        if line.chars().any(char::is_alphanumeric) {
            meaningful = true;
        }
    }
    meaningful
}

fn source_priority(path: &str) -> f32 {
    match Path::new(path)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
    {
        "rs" | "py" | "js" | "jsx" | "ts" | "tsx" | "c" | "cc" | "cpp" | "h" | "hpp" | "go"
        | "java" | "kt" | "swift" | "cs" | "rb" | "php" | "sh" | "ex" | "exs" | "lua" | "zig"
        | "scala" | "vue" | "svelte" => 4.0,
        _ => 0.0,
    }
}

impl Selection {
    fn new(terms: Vec<String>, limit: usize) -> Self {
        let fuzzy = terms
            .iter()
            .filter(|term| term.is_ascii() && term.len() <= 32)
            .map(|term| {
                nucleo::pattern::Atom::new(
                    term,
                    nucleo::pattern::CaseMatching::Ignore,
                    nucleo::pattern::Normalization::Smart,
                    nucleo::pattern::AtomKind::Fuzzy,
                    false,
                )
            })
            .collect();
        let corpus = Bm25Corpus::new(terms.len());
        Self {
            terms,
            fuzzy,
            matcher: nucleo::Matcher::new(nucleo::Config::DEFAULT.match_paths()),
            chunks: BinaryHeap::with_capacity(limit),
            corpus,
            limit,
            code: false,
        }
    }
    fn offer(&mut self, candidate: Candidate) {
        if self.chunks.len() < self.limit {
            self.chunks.push(Reverse(candidate));
        } else if self.chunks.peek().is_some_and(|worst| candidate > worst.0) {
            *self.chunks.peek_mut().expect("nonempty candidate heap") = Reverse(candidate);
        }
    }
    #[cfg(test)]
    fn ordered(self) -> Vec<Candidate> {
        let mut chunks: Vec<_> = self.chunks.into_iter().map(|item| item.0).collect();
        chunks.sort_unstable_by(|a, b| b.cmp(a));
        chunks
    }
    fn rerank_bm25(mut self, final_limit: usize) -> Vec<Candidate> {
        let mut chunks: Vec<_> = self.chunks.drain().map(|item| item.0).collect();
        for candidate in &mut chunks {
            candidate.lexical = self
                .corpus
                .score(&candidate.frequencies, candidate.token_length)
                + candidate.boost;
        }
        chunks.sort_unstable_by(|a, b| b.cmp(a));
        chunks.truncate(final_limit);
        chunks
    }
    fn inject_codegraph(&mut self, symbols: &[codegraph::Symbol], chunk_lines: u32) {
        const SYMBOL_BOOST: f32 = 32.0;
        for symbol in symbols {
            let retained = std::mem::take(&mut self.chunks).into_iter().filter(|item| {
                item.0.path != symbol.path
                    || item.0.line < symbol.start_line
                    || item.0.line > symbol.end_line
            });
            self.chunks = retained.collect();
            for chunk in codegraph::chunks(symbol, chunk_lines) {
                self.offer(Candidate {
                    path: symbol.path.clone(),
                    line: chunk.line,
                    text: chunk.text,
                    symbol: symbol.name.clone(),
                    lexical: SYMBOL_BOOST,
                    boost: SYMBOL_BOOST,
                    frequencies: vec![0; self.terms.len()],
                    token_length: 0,
                    test_only: Path::new(&symbol.path)
                        .components()
                        .any(|part| matches!(part.as_os_str().to_str(), Some("tests" | "scripts"))),
                });
            }
        }
    }
    fn collect(
        &mut self,
        reader: impl BufRead,
        path: &str,
        chunk_lines: u32,
        stats: &mut Stats,
    ) -> Result<()> {
        let lower_path = path.to_lowercase();
        // fzf-style boundary/camelCase/consecutive/gap scoring is computed once per path,
        // never with a full dynamic-programming matrix for every source-code chunk.
        let mut scratch = Vec::new();
        let path_text = nucleo::Utf32Str::new(path, &mut scratch);
        let fuzzy_bonus: f32 = self
            .fuzzy
            .iter()
            .filter_map(|atom| atom.score(path_text, &mut self.matcher))
            .map(|score| (f32::from(score) / 64.0).min(1.5))
            .sum();
        // Reserve room for other files instead of letting a single lockfile or
        // repeated boilerplate occupy the entire reranking budget.
        let file_limit = if self.code {
            self.limit.div_ceil(4).max(1)
        } else {
            self.limit
        };
        let mut file = Selection::new(Vec::new(), file_limit);
        let mut in_import = false;
        let mut test_only = false;
        input::chunks(reader, chunk_lines, |line, text, symbol| {
            if !input::searchable(text) {
                return Ok(());
            }
            stats.chunks += 1;
            if self.code && !implementation_content(text, &mut in_import) {
                return Ok(());
            }
            test_only |= text.contains("#[cfg(test)]");
            let lower = text.to_lowercase();
            let lower_symbol = symbol.to_lowercase();
            let identifiers = if self.code {
                identifiers(&lower)
            } else {
                lower.clone()
            };
            let frequencies = hybrid::frequencies(&self.terms, &identifiers);
            let token_length = hybrid::tokenize(&identifiers).len();
            self.corpus.observe(&frequencies, token_length);
            let term_score: f32 = self
                .terms
                .iter()
                .map(|term| {
                    let weight = (term.chars().count() as f32).sqrt();
                    weight
                        * (identifiers.matches(term.as_str()).take(3).count() as f32
                            + if self.code {
                                0.15 * lower.matches(term.as_str()).take(3).count() as f32
                            } else {
                                0.0
                            })
                })
                .sum::<f32>();
            let path_symbol_bonus: f32 = self
                .terms
                .iter()
                .map(|term| {
                    (term.chars().count() as f32).sqrt()
                        * (if lower_path.contains(term) { 2.0 } else { 0.0 }
                            + if lower_symbol.contains(term) {
                                1.5
                            } else {
                                0.0
                            })
                })
                .sum();
            let prior = if self.code {
                source_priority(&lower_path)
            } else {
                0.0
            };
            let symbol_bonus = if self.code && declaration_match(&self.terms, text) {
                12.0
            } else {
                0.0
            };
            let boost = (fuzzy_bonus + path_symbol_bonus + prior + symbol_bonus)
                / (1.0 + text.len() as f32 / 2048.0);
            let lexical = term_score / (1.0 + text.len() as f32 / 2048.0) + boost;
            let worth_keeping = file.chunks.len() < file.limit
                || file.chunks.peek().is_some_and(|worst| {
                    lexical.total_cmp(&worst.0.lexical).is_gt()
                        || (lexical == worst.0.lexical
                            && (path, line) < (worst.0.path.as_str(), worst.0.line))
                });
            if worth_keeping {
                file.offer(Candidate {
                    path: path.to_owned(),
                    line,
                    text: text.to_owned(),
                    symbol: symbol.to_owned(),
                    lexical,
                    boost,
                    frequencies,
                    token_length,
                    test_only,
                });
            }
            Ok(())
        })?;
        for candidate in file.chunks {
            self.offer(candidate.0);
        }
        Ok(())
    }
}

impl Searcher<'_> {
    pub fn search_candidates(&mut self, query: &str) -> Result<Response> {
        self.progress
            .begin("scanning text and selecting candidates (no full-repository embedding)");
        let mut stats = Stats::default();
        let candidate_limit = self.args.candidates as usize;
        let pool_limit = candidate_limit.saturating_mul(4);
        let mut selection = Selection {
            code: self.args.code,
            ..Selection::new(hybrid::terms(query), pool_limit)
        };
        let paths = self.args.paths.clone();
        if paths.is_empty() {
            ensure!(
                !std::io::stdin().is_terminal(),
                "provide a file/directory or pipe text to stdin"
            );
            selection.collect(
                std::io::stdin().lock(),
                &self.args.label,
                self.args.chunk_lines,
                &mut stats,
            )?;
        }
        for path in paths {
            if path == Path::new("-") {
                selection.collect(
                    std::io::stdin().lock(),
                    &self.args.label,
                    self.args.chunk_lines,
                    &mut stats,
                )?;
            } else if path.is_dir() {
                self.collect_parallel(&path, &mut selection, &mut stats)?;
            } else {
                self.collect_file(&path, &mut selection, &mut stats, false)?;
            }
        }
        let symbols = if self.args.codegraph {
            codegraph::lookup(&self.args.paths, &selection.terms)
        } else {
            Vec::new()
        };
        selection.inject_codegraph(&symbols, self.args.chunk_lines);
        let chunks = selection.rerank_bm25(candidate_limit);
        stats.candidate_chunks = chunks.len() as u64;
        if stats.chunks > stats.candidate_chunks && !self.args.quiet && !self.args.no_messages {
            self.progress.message(format!(
                "geg: fast search: scanned {} chunks in {} files, semantically reranking {} lexical candidates. This is not exhaustive; use --exhaustive or a full index for broader semantic recall.",
                stats.chunks, stats.files, stats.candidate_chunks
            ));
        }
        if stats.skipped_files > 0 && !self.args.no_messages && !self.args.quiet {
            eprintln!(
                "geg: skipped the unsupported remainder of {} files (invalid UTF-8/binary/oversized lines or read errors); explicit file inputs report errors instead",
                stats.skipped_files
            );
        }
        let mut counts = BTreeMap::new();
        let mut hits = Vec::new();
        let query_terms = hybrid::terms(query);
        let mut ranked = Vec::new();
        if !chunks.is_empty() {
            let query_vector = self.query_vector(query, &mut stats)?;
            let prompts: Vec<_> = chunks
                .iter()
                .map(|candidate| input::prompt(&candidate.symbol, &candidate.text))
                .collect();
            let vectors = self.vectors(&prompts, &mut stats)?;
            let mut scored = Vec::new();
            for (candidate, vector) in chunks.into_iter().zip(vectors) {
                let score = best_score(&query_vector, &vector);
                if self.accepts(score) {
                    scored.push((candidate, score));
                }
            }
            scored.sort_unstable_by(|(a, a_score), (b, b_score)| {
                b_score
                    .total_cmp(a_score)
                    .then_with(|| a.path.cmp(&b.path))
                    .then_with(|| a.line.cmp(&b.line))
            });
            let vector_ranks: BTreeMap<_, _> = scored
                .iter()
                .enumerate()
                .map(|(rank, (candidate, _))| ((candidate.path.clone(), candidate.line), rank + 1))
                .collect();
            scored.sort_unstable_by(|(a, _), (b, _)| {
                b.lexical
                    .total_cmp(&a.lexical)
                    .then_with(|| a.path.cmp(&b.path))
                    .then_with(|| a.line.cmp(&b.line))
            });
            let lexical_ranks: BTreeMap<_, _> = scored
                .iter()
                .enumerate()
                .map(|(rank, (candidate, _))| ((candidate.path.clone(), candidate.line), rank + 1))
                .collect();
            for (candidate, score) in scored {
                let count = counts.entry(candidate.path.clone()).or_insert(0);
                *count += candidate.text.lines().count() as u64;
                let key = (candidate.path.clone(), candidate.line);
                let mut rank = reciprocal_rank_fusion(
                    vector_ranks.get(&key).copied(),
                    lexical_ranks.get(&key).copied(),
                );
                if self.args.code {
                    if declaration_match(&query_terms, &candidate.text) {
                        rank += 0.001;
                    }
                    let support = (candidate.test_only
                        || Path::new(&candidate.path).components().any(|part| {
                            matches!(part.as_os_str().to_str(), Some("tests" | "scripts"))
                        }))
                        && !query_terms.iter().any(|term| {
                            [
                                "test",
                                "tests",
                                "script",
                                "scripts",
                                "benchmark",
                                "regression",
                                "测试",
                                "脚本",
                            ]
                            .contains(&term.as_str())
                        });
                    if support {
                        rank -= 0.001;
                    }
                }
                let symbol = codegraph::symbol_at(&symbols, &candidate.path, candidate.line)
                    .filter(|name| !name.is_empty())
                    .map_or(candidate.symbol, str::to_owned);
                ranked.push((
                    rank,
                    Hit {
                        path: candidate.path,
                        line: candidate.line,
                        text: candidate.text,
                        symbol,
                        score,
                    },
                ));
            }
        }
        ranked.sort_unstable_by(|(a, x), (b, y)| {
            b.total_cmp(a)
                .then_with(|| x.path.cmp(&y.path))
                .then_with(|| x.line.cmp(&y.line))
        });
        for (_, hit) in ranked.into_iter().take(self.limit()) {
            hits.push(hit);
        }
        self.progress.finish(&stats);
        Ok(Response {
            query: query.to_owned(),
            hits,
            counts,
            stats,
        })
    }

    fn collect_parallel(
        &mut self,
        path: &Path,
        selection: &mut Selection,
        stats: &mut Stats,
    ) -> Result<()> {
        // dust's useful property: thread-local collection, one merge per worker,
        // not one contended lock or another metadata lookup per source chunk.
        struct Local<'a> {
            selection: Selection,
            stats: Stats,
            merged: &'a Mutex<(Selection, Stats, Option<anyhow::Error>)>,
        }
        impl Drop for Local<'_> {
            fn drop(&mut self) {
                let mut merged = self.merged.lock().expect("candidate merge poisoned");
                merged.0.corpus.merge(&self.selection.corpus);
                for candidate in self.selection.chunks.drain() {
                    merged.0.offer(candidate.0);
                }
                merged.1.files += self.stats.files;
                merged.1.chunks += self.stats.chunks;
                merged.1.skipped_files += self.stats.skipped_files;
            }
        }
        let merged = Mutex::new((
            Selection {
                code: selection.code,
                ..Selection::new(selection.terms.clone(), selection.limit)
            },
            Stats::default(),
            None,
        ));
        let chunk_lines = self.args.chunk_lines;
        let cancellation = self.revision.clone();
        let terms = selection.terms.clone();
        let limit = selection.limit;
        let code = selection.code;
        let mut walker = input::walker(
            path,
            self.args.no_ignore,
            self.args.hidden,
            self.args.dereference_recursive,
        );
        walker.threads(std::thread::available_parallelism().map_or(1, |n| n.get().min(4)));
        walker.build_parallel().run(|| {
            let mut local = Local {
                selection: Selection {
                    code,
                    ..Selection::new(terms.clone(), limit)
                },
                stats: Stats::default(),
                merged: &merged,
            };
            let cancellation = cancellation.clone();
            Box::new(move |entry| {
                if cancellation.as_ref().is_some_and(|(revision, expected)| {
                    revision.load(std::sync::atomic::Ordering::Relaxed) != *expected
                }) {
                    return ignore::WalkState::Quit;
                }
                let entry = match entry {
                    Ok(entry) => entry,
                    Err(error)
                        if error
                            .io_error()
                            .is_some_and(|e| e.kind() == std::io::ErrorKind::PermissionDenied) =>
                    {
                        local.stats.skipped_files += 1;
                        return ignore::WalkState::Continue;
                    }
                    Err(error) => {
                        local.merged.lock().expect("candidate merge poisoned").2 =
                            Some(error.into());
                        return ignore::WalkState::Quit;
                    }
                };
                if !entry.file_type().is_some_and(|kind| kind.is_file()) {
                    return ignore::WalkState::Continue;
                }
                if code
                    && (generated(entry.path())
                        || source_priority(&entry.path().to_string_lossy().to_lowercase()) == 0.0)
                {
                    return ignore::WalkState::Continue;
                }
                local.stats.files += 1;
                let mut read = || -> Result<()> {
                    let mut reader = BufReader::new(File::open(entry.path())?);
                    if reader.fill_buf()?.contains(&0) {
                        return Ok(());
                    }
                    local.selection.collect(
                        reader,
                        &entry.path().to_string_lossy(),
                        chunk_lines,
                        &mut local.stats,
                    )
                };
                if (read)().is_err() {
                    local.stats.skipped_files += 1;
                }
                ignore::WalkState::Continue
            })
        });
        self.check_cancelled()?;
        let (collected, local_stats, error) =
            merged.into_inner().expect("candidate merge poisoned");
        if let Some(error) = error {
            return Err(error);
        }
        for candidate in collected.chunks {
            selection.offer(candidate.0);
        }
        selection.corpus.merge(&collected.corpus);
        stats.chunks += local_stats.chunks;
        stats.skipped_files += local_stats.skipped_files;
        for _ in 0..local_stats.files {
            self.note_file(stats);
        }
        self.progress.update(stats);
        Ok(())
    }

    fn collect_file(
        &mut self,
        path: &Path,
        selection: &mut Selection,
        stats: &mut Stats,
        allow_skip: bool,
    ) -> Result<()> {
        self.check_cancelled()?;
        self.note_file(stats);
        let lines = self.args.chunk_lines;
        let result = self.read_file(path, |_, reader, label| {
            selection.collect(reader, label, lines, stats)
        });
        if allow_skip && result.is_err() {
            stats.skipped_files += 1;
            Ok(())
        } else {
            result
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hybrid::terms;
    #[test]
    fn bounded_heap_matches_full_sort_with_stable_ties() {
        let mut selection = Selection::new(vec![], 7);
        let make = |i: u64| Candidate {
            path: format!("p{:03}", 99 - i),
            line: i,
            text: String::new(),
            symbol: String::new(),
            lexical: (i % 4) as f32,
            boost: 0.0,
            frequencies: vec![],
            token_length: 0,
            test_only: false,
        };
        for i in 0..100 {
            selection.offer(make(i));
        }
        let mut expected: Vec<_> = (0..100).map(make).collect();
        expected.sort_unstable_by(|a, b| b.cmp(a));
        let actual = selection.ordered();
        assert_eq!(actual.len(), 7);
        assert!(actual.iter().zip(expected).all(|(a, b)| a == &b));
    }
    #[test]
    fn fuzzy_path_score_finds_abbreviated_camel_case() -> Result<()> {
        let mut selection = Selection::new(terms("reqrt"), 1);
        let mut stats = Stats::default();
        for path in ["src/aaa.rs", "src/requestRetry.rs"] {
            selection.collect("same body\n".as_bytes(), path, 1, &mut stats)?;
        }
        assert_eq!(selection.ordered()[0].path, "src/requestRetry.rs");
        Ok(())
    }
    #[test]
    fn declarations_ignore_quoted_examples_and_import_only_chunks() {
        let terms = terms("主函数");
        assert_eq!(
            identifiers("let sample = \"fn main() {}\"; // main\n"),
            "let sample =   ; \n"
        );
        assert!(declaration_match(&terms, "pub async fn main() {}"));
        assert!(!declaration_match(
            &terms,
            "let example = \"fn main() {}\";"
        ));
        assert!(!declaration_match(&terms, "// fn main() {}"));
        let mut imported = false;
        assert!(!implementation_content(
            "use std::{\n    fs,\n",
            &mut imported
        ));
        assert!(!implementation_content(
            "    io,\n};\nmod cache;\nOk(())\n",
            &mut imported
        ));
        assert!(implementation_content(
            "fn main() { run(); }",
            &mut imported
        ));
    }
    #[test]
    fn chinese_entry_query_keeps_real_code_and_limits_single_file_boilerplate() -> Result<()> {
        let mut selection = Selection {
            code: true,
            ..Selection::new(terms("主函数"), 32)
        };
        let mut stats = Stats::default();
        selection.collect(
            "主函数 main example\n".repeat(100).as_bytes(),
            "README.md",
            1,
            &mut stats,
        )?;
        let source = format!(
            "{}fn main() {{ run(); }}\n",
            "use crate::something;\n".repeat(64)
        );
        selection.collect(source.as_bytes(), "src/main.rs", 1, &mut stats)?;
        let chunks = selection.ordered();
        assert!(
            chunks
                .iter()
                .any(|c| c.path == "src/main.rs" && c.text.contains("fn main"))
        );
        assert!(chunks.iter().filter(|c| c.path == "README.md").count() <= 8);
        assert!(generated(Path::new("Cargo.lock")) && generated(Path::new("package-lock.json")));
        assert!(!generated(Path::new("src/main.rs")));
        Ok(())
    }
    #[test]
    fn chinese_bigrams_and_ascii_identifiers_are_searchable() {
        let tokens = terms("失败请求的重试逻辑 HTTP_retry");
        assert!(tokens.contains(&"重试".to_owned()));
        assert!(tokens.contains(&"retry".to_owned()));
        let mut selection = Selection::new(tokens, 1);
        let mut stats = Stats::default();
        selection
            .collect(
                "unrelated cats\n# 失败请求的重试逻辑\n".as_bytes(),
                "a.py",
                1,
                &mut stats,
            )
            .unwrap();
        assert_eq!(selection.ordered()[0].line, 2);
        assert_eq!(stats.chunks, 2);
    }
}