symforge 11.22.3

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
//! Shared indexed search orchestration above transport-independent search.

use std::path::Path;

use crate::domain::{FileClassification, LanguageId};
use crate::live_index::{LiveIndex, search};

fn enrich_with_callers(
    index: &crate::live_index::LiveIndex,
    result: &mut search::TextSearchResult,
    file_limit: usize,
) {
    use std::collections::HashSet;

    for file_matches in result.files.iter_mut().take(file_limit) {
        // Collect unique enclosing symbol names from this file's matches
        let mut symbol_names: HashSet<String> = HashSet::new();
        for m in &file_matches.matches {
            if let Some(ref enc) = m.enclosing_symbol {
                symbol_names.insert(enc.name.clone());
            }
        }

        if symbol_names.is_empty() {
            continue;
        }

        let mut callers: Vec<search::CallerEntry> = Vec::new();

        for sym_name in &symbol_names {
            let refs = index.find_references_for_name(sym_name, None, false);
            for (ref_file, ref_record) in refs {
                // Get enclosing symbol of the reference
                let enclosing_name = ref_record
                    .enclosing_symbol_index
                    .and_then(|idx| {
                        index
                            .get_file(ref_file)
                            .and_then(|f| f.symbols.get(idx as usize))
                            .map(|s| s.name.clone())
                    })
                    .unwrap_or_else(|| "(top-level)".to_string());

                // Skip self-references only when the caller IS one of the matched
                // symbols (same-file callers from different symbols are useful context)
                if ref_file == file_matches.path && symbol_names.contains(&enclosing_name) {
                    continue;
                }

                callers.push(search::CallerEntry {
                    file: ref_file.to_string(),
                    symbol: enclosing_name,
                    line: ref_record.line_range.0 + 1, // 0-based to 1-based
                });
            }
        }

        // Choose the earliest reference per caller before applying the cap.
        // Symbol-name and reverse-index iteration order must not select rows.
        callers.sort_unstable_by(|left, right| {
            left.file
                .cmp(&right.file)
                .then_with(|| left.symbol.cmp(&right.symbol))
                .then_with(|| left.line.cmp(&right.line))
        });
        callers.dedup_by(|left, right| left.file == right.file && left.symbol == right.symbol);
        callers.truncate(10);

        // Always set callers when follow_refs was requested — distinguishes
        // "not requested" (None) from "ran but found nothing" (Some([]))
        file_matches.callers = Some(callers);
    }
}

/// Strip vendor / personal-tooling paths from a `TextSearchResult` per the
/// caller's `include_vendor` / `include_personal_tooling` flags. Suppressed
/// match counts feed `suppressed_by_noise`, which renders into the existing
/// "N noise-filtered match(es) suppressed" envelope footer.
fn apply_path_predicate_filter(
    result: &mut Result<search::TextSearchResult, search::TextSearchError>,
    include_vendor: bool,
    include_personal_tooling: bool,
) {
    if include_vendor && include_personal_tooling {
        return;
    }
    if let Ok(r) = result {
        let mut filtered: usize = 0;
        r.files.retain(|file| {
            if !include_vendor && crate::live_index::query::is_vendor_path(&file.path) {
                filtered += file.matches.len();
                return false;
            }
            if !include_personal_tooling
                && crate::live_index::query::is_personal_tooling_path(&file.path)
            {
                filtered += file.matches.len();
                return false;
            }
            true
        });
        r.suppressed_by_noise = r.suppressed_by_noise.saturating_add(filtered);
    }
}

fn search_text_compaction_query(query: Option<&str>, terms: Option<&[String]>) -> String {
    if let Some(q) = query.filter(|s| !s.trim().is_empty()) {
        return q.to_string();
    }
    terms
        .map(|items| {
            items
                .iter()
                .map(String::as_str)
                .collect::<Vec<_>>()
                .join(" ")
        })
        .unwrap_or_default()
}

fn maybe_compact_text_search_result(
    result: &mut Result<search::TextSearchResult, search::TextSearchError>,
    query: &str,
) {
    if query.trim().is_empty() {
        return;
    }
    if let Ok(text) = result {
        super::compression::compact_text_search_result(text, query);
    }
}

fn resolve_text_search_enclosing_symbols(
    index: &LiveIndex,
    result: &mut Result<search::TextSearchResult, search::TextSearchError>,
) {
    let Ok(result) = result else {
        return;
    };

    for file_matches in &mut result.files {
        let Some(file) = index.get_file(&file_matches.path) else {
            continue;
        };

        for line_match in &mut file_matches.matches {
            let zero_based_line = line_match.line_number.saturating_sub(1) as u32;
            line_match.enclosing_symbol =
                crate::domain::find_enclosing_symbol(&file.symbols, zero_based_line)
                    .and_then(|idx| file.symbols.get(idx as usize))
                    .map(|symbol| search::EnclosingMatchSymbol {
                        name: symbol.name.clone(),
                        kind: symbol.kind.to_string(),
                        line_range: symbol.line_range,
                        body: None,
                    });
        }
    }
}

/// SF-TE-08: attach each enclosing symbol's source once, on its first
/// SURVIVING match. Runs after compaction, which may drop any match line.
fn attach_symbol_bodies(
    index: &LiveIndex,
    result: &mut Result<search::TextSearchResult, search::TextSearchError>,
) {
    let Ok(result) = result else {
        return;
    };
    for file_matches in &mut result.files {
        let Some(file) = index.get_file(&file_matches.path) else {
            continue;
        };
        let mut bodied = std::collections::HashSet::new();
        for line_match in &mut file_matches.matches {
            let zero_based_line = line_match.line_number.saturating_sub(1) as u32;
            let Some(idx) = crate::domain::find_enclosing_symbol(&file.symbols, zero_based_line)
            else {
                continue;
            };
            let (Some(enclosing), Some(symbol)) = (
                line_match.enclosing_symbol.as_mut(),
                file.symbols.get(idx as usize),
            ) else {
                continue;
            };
            if bodied.insert(idx) {
                let (start, end) = symbol.byte_range;
                enclosing.body = file
                    .content
                    .get(start as usize..end as usize)
                    .map(|bytes| String::from_utf8_lossy(bytes).into_owned());
            }
        }
    }
}

fn search_symbols_total_matches(result: &search::SymbolSearchResult) -> usize {
    result.hits.len().saturating_add(result.overflow_count)
}

fn hidden_search_symbols_noise_count(
    index: &LiveIndex,
    query: &str,
    kind: Option<&str>,
    options: &search::SymbolSearchOptions,
    visible: &search::SymbolSearchResult,
) -> usize {
    // Every default-hidden class counts (SF-TE-06): a hidden test or generated
    // symbol is a non-default condition the envelope must name.
    if options.noise_policy.include_vendor
        && options.noise_policy.include_tests
        && options.noise_policy.include_generated
        && options.include_personal_tooling
    {
        return 0;
    }

    let mut unfiltered_options = options.clone();
    unfiltered_options.noise_policy.include_vendor = true;
    unfiltered_options.noise_policy.include_tests = true;
    unfiltered_options.noise_policy.include_generated = true;
    unfiltered_options.include_personal_tooling = true;
    let unfiltered = search::search_symbols_with_options(index, query, kind, &unfiltered_options);
    search_symbols_total_matches(&unfiltered).saturating_sub(search_symbols_total_matches(visible))
}

pub(crate) struct TextSearchExecution {
    pub result: Result<search::TextSearchResult, search::TextSearchError>,
    pub options: search::TextSearchOptions,
    pub is_regex: bool,
    pub structural: bool,
    pub auto_detected_regex: bool,
    pub auto_corrected_regex: bool,
    pub effective_query: Option<String>,
    /// Count mode only: matches `include_tests=true` would add, measured by a
    /// second run. `None` when not measured.
    pub hidden_test_matches: Option<usize>,
    /// Zero-hit code search only: matches the same query has in documentation files.
    pub hidden_documentation: Option<HiddenDocumentation>,
}

/// Matches a zero-hit code search missed because they sit in documentation files, which
/// `search_text` does not search.
pub(crate) struct HiddenDocumentation {
    pub matches: usize,
    /// The count stopped at the scan cap: there may be more.
    pub capped: bool,
    pub files: Vec<String>,
}

/// Matches counted per documentation rerun; a count that reaches it prints as `N+`.
const HIDDEN_DOCUMENTATION_SCAN_CAP: usize = 1_000;

impl TextSearchExecution {
    /// One paragraph naming the documentation matches and the call that shows them.
    pub(crate) fn hidden_documentation_note(&self) -> Option<String> {
        let hidden = self.hidden_documentation.as_ref()?;
        let query = self.effective_query.as_deref()?;
        let count = if hidden.capped {
            format!("{}+", hidden.matches)
        } else {
            hidden.matches.to_string()
        };
        let noun = if hidden.matches == 1 && !hidden.capped {
            "match"
        } else {
            "matches"
        };
        // `search_knowledge` matches literal text, so a regex gets the count alone.
        let next = if self.is_regex {
            "search_knowledge matches literal text, so a regex cannot be passed to it".to_string()
        } else {
            format!("Next: search_knowledge(query={})", json_string(query))
        };
        Some(format!(
            "{count} {noun} in documentation ({}); search_text() searches code only. {next}",
            hidden.files.join(", "),
        ))
    }
}

fn json_string(text: &str) -> String {
    serde_json::to_string(text).unwrap_or_else(|_| format!("\"{text}\""))
}

/// Run `rerun` over documentation (knowledge) files with the search's own filters and
/// count what it finds. `None` when nothing matches or the run failed.
fn hidden_documentation_matches(
    options: &search::TextSearchOptions,
    rerun: impl FnOnce(
        &search::TextSearchOptions,
    ) -> Result<search::TextSearchResult, search::TextSearchError>,
) -> Option<HiddenDocumentation> {
    let mut docs = options.clone();
    docs.search_scope = search::SearchScope::Text;
    docs.language_filter = Some(LanguageId::Markdown);
    docs.total_limit = HIDDEN_DOCUMENTATION_SCAN_CAP;
    docs.max_per_file = HIDDEN_DOCUMENTATION_SCAN_CAP;
    let found = rerun(&docs).ok()?;
    let matches: usize = found.files.iter().map(|file| file.matches.len()).sum();
    if matches == 0 {
        return None;
    }
    Some(HiddenDocumentation {
        matches,
        capped: matches >= HIDDEN_DOCUMENTATION_SCAN_CAP,
        files: found
            .files
            .iter()
            .take(3)
            .map(|file| file.path.clone())
            .collect(),
    })
}

/// Shared request semantics above the indexed text/AST search engine. Transport
/// presentation, admission and session accounting stay with the caller.
pub(crate) fn execute_text_search(
    generation: &crate::live_index::PublishedGeneration,
    input: &super::search_contract::SearchTextInput,
) -> Result<TextSearchExecution, String> {
    use super::search_contract::search_text_options_from_input;
    let index = &generation.live;
    let mut options = search_text_options_from_input(input)?;
    let count_mode = input.group_by.as_deref() == Some(GROUP_BY_COUNT);
    let include_body = input.include_body.unwrap_or(false);
    if include_body && (input.group_by.as_deref() != Some("symbol") || input.context.is_some()) {
        return Err(
            "Error: include_body=true requires group_by=\"symbol\" and no `context`.".to_owned(),
        );
    }
    if count_mode
        && (input.context.is_some()
            || input.follow_refs == Some(true)
            || input.ranked == Some(true))
    {
        return Err(
            "Error: group_by=\"count\" cannot be combined with `context`, `follow_refs` or `ranked`."
                .to_owned(),
        );
    }
    if count_mode {
        // SF-TE-07: a count is only true when nothing caps it. Display caps,
        // context windows and ranking (which keeps at most 500 files) are off.
        // ponytail: every matching line is retained, so a sweep holds all hits
        // in memory; carry a per-file counter instead if sweeps grow huge.
        options.total_limit = usize::MAX;
        options.max_per_file = usize::MAX;
        options.context = None;
        options.ranked = false;
    }
    let follow_refs = input.follow_refs.unwrap_or(false) && !count_mode;
    let finish = |mut result: Result<search::TextSearchResult, search::TextSearchError>| {
        resolve_text_search_enclosing_symbols(index, &mut result);
        if follow_refs && let Ok(result) = &mut result {
            enrich_with_callers(index, result, input.follow_refs_limit.unwrap_or(3) as usize);
        }
        apply_path_predicate_filter(
            &mut result,
            input.include_vendor.unwrap_or(false),
            input.include_personal_tooling.unwrap_or(false),
        );
        result
    };
    if input.structural.unwrap_or(false) {
        let pattern = input
            .query
            .as_deref()
            .map(str::trim)
            .filter(|pattern| !pattern.is_empty())
            .ok_or_else(|| "Error: `query` is required for structural search.".to_owned())?;
        let mut result = finish(search::search_structural(index, pattern, &options));
        if !count_mode {
            maybe_compact_text_search_result(&mut result, pattern);
        }
        if include_body {
            attach_symbol_bodies(index, &mut result);
        }
        let hidden_test_matches = count_mode
            .then(|| {
                hidden_test_match_count(&options, &result, |opts| {
                    finish(search::search_structural(index, pattern, opts))
                })
            })
            .flatten();
        return Ok(TextSearchExecution {
            result,
            options,
            is_regex: false,
            structural: true,
            auto_detected_regex: false,
            auto_corrected_regex: false,
            effective_query: Some(pattern.to_owned()),
            hidden_test_matches,
            hidden_documentation: None,
        });
    }
    let mut is_regex = input.regex.unwrap_or(false);
    let mut auto_detected_regex = false;
    if !is_regex
        && let Some(query) = &input.query
        && ["\\w", "\\d", "\\s", "\\b", "\\W", "\\D", "\\S"]
            .iter()
            .any(|escape| query.contains(escape))
    {
        is_regex = true;
        auto_detected_regex = true;
        if input.include_tests.is_none() {
            options.noise_policy.include_tests = true;
        }
    }
    if options.ranked {
        let temporal = &generation.code_signals.temporal;
        if matches!(
            temporal.state,
            crate::live_index::git_temporal::GitTemporalState::Ready
        ) {
            let scores: std::collections::HashMap<String, f32> = temporal
                .files
                .iter()
                .map(|(path, history)| (path.clone(), history.churn_score))
                .collect();
            if !scores.is_empty() {
                options.churn_scores = Some(scores);
            }
        }
    }
    let run = |query: Option<&str>, opts: &search::TextSearchOptions| {
        finish(search::search_text_with_options(
            index,
            query,
            input.terms.as_deref(),
            is_regex,
            opts,
        ))
    };
    let mut result = run(input.query.as_deref(), &options);
    let mut effective_query = input.query.clone();
    let mut auto_corrected_regex = false;
    let should_retry = matches!(&result, Err(search::TextSearchError::InvalidRegex { .. }))
        || matches!(&result, Ok(result) if result.files.is_empty());
    if is_regex
        && should_retry
        && let Some(query) = &input.query
        && let Some(fixed) = super::filters::fix_common_double_escapes(query)
    {
        let retry = run(Some(&fixed), &options);
        if matches!(&retry, Ok(result) if !result.files.is_empty()) {
            result = retry;
            effective_query = Some(fixed);
            auto_corrected_regex = true;
        }
    }
    if !auto_corrected_regex && !count_mode {
        let compaction =
            search_text_compaction_query(input.query.as_deref(), input.terms.as_deref());
        maybe_compact_text_search_result(&mut result, &compaction);
    }
    if include_body {
        attach_symbol_bodies(index, &mut result);
    }
    let hidden_test_matches = count_mode
        .then(|| {
            hidden_test_match_count(&options, &result, |opts| {
                run(effective_query.as_deref(), opts)
            })
        })
        .flatten();
    // FR-029: a code search with no match still says what the documentation holds.
    let hidden_documentation = (!count_mode
        && matches!(&result, Ok(found) if found.files.is_empty()))
    .then(|| hidden_documentation_matches(&options, |opts| run(effective_query.as_deref(), opts)))
    .flatten();
    Ok(TextSearchExecution {
        result,
        options,
        is_regex,
        structural: false,
        auto_detected_regex,
        auto_corrected_regex,
        effective_query,
        hidden_test_matches,
        hidden_documentation,
    })
}

/// `group_by` value for the per-file count view (SF-TE-07).
pub(crate) const GROUP_BY_COUNT: &str = "count";

/// Matches that `include_tests=true` would add to a count, measured by running
/// the same search with tests included. `None` when tests are already included
/// or either run failed (nothing observed, nothing claimed).
fn hidden_test_match_count(
    options: &search::TextSearchOptions,
    visible: &Result<search::TextSearchResult, search::TextSearchError>,
    rerun: impl FnOnce(
        &search::TextSearchOptions,
    ) -> Result<search::TextSearchResult, search::TextSearchError>,
) -> Option<usize> {
    if options.noise_policy.include_tests {
        return None;
    }
    let mut with_tests = options.clone();
    with_tests.noise_policy.include_tests = true;
    let matched = |result: &search::TextSearchResult| -> usize {
        result.files.iter().map(|file| file.matches.len()).sum()
    };
    let visible = matched(visible.as_ref().ok()?);
    let all = matched(&rerun(&with_tests).ok()?);
    Some(all.saturating_sub(visible))
}

pub(crate) struct SymbolSearchExecution {
    pub result: search::SymbolSearchResult,
    pub options: search::SymbolSearchOptions,
    pub suppressed_by_noise: usize,
    pub text_fallback: Vec<(String, usize)>,
    /// Set when no exact match existed and `result` holds the symbols containing all
    /// these (lower-cased) words.
    pub all_words_rule: Option<Vec<String>>,
}

pub(crate) fn execute_symbol_search(
    index: &LiveIndex,
    input: &super::search_contract::SearchSymbolsInput,
) -> Result<SymbolSearchExecution, String> {
    let query = input.query.as_deref().unwrap_or("").trim();
    let is_browse = query.is_empty();
    if is_browse && input.kind.is_none() && input.path_prefix.is_none() {
        return Err("search_symbols requires at least one of: query, kind, or path_prefix".into());
    }
    let options = super::search_contract::search_symbols_options_from_input(input)?;
    let mut result =
        search::search_symbols_with_options(index, query, input.kind.as_deref(), &options);
    // FR-030: a several-word query with no match returns the symbols whose names
    // contain all the words, and the rendering says so.
    let mut all_words_rule = None;
    if result.hits.is_empty() && !is_browse {
        let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
        if let Some(found) = all_words_symbol_matches(index, input, &options, &words) {
            result = found;
            all_words_rule = Some(words);
        }
    }
    let suppressed_by_noise =
        hidden_search_symbols_noise_count(index, query, input.kind.as_deref(), &options, &result);
    let mut text_fallback = Vec::new();
    if !is_browse && query.len() >= 2 && result.hits.len() < options.result_limit.get() / 2 {
        let mut text_options = search::TextSearchOptions::for_current_code_search();
        text_options.path_scope = options.path_scope.clone();
        text_options.noise_policy = options.noise_policy;
        text_options.include_personal_tooling = options.include_personal_tooling;
        text_options.language_filter = options.language_filter;
        text_options.total_limit = 15;
        text_options.max_per_file = 1;
        if let Ok(text) =
            search::search_text_with_options(index, Some(query), None, false, &text_options)
        {
            let paths: std::collections::HashSet<&str> =
                result.hits.iter().map(|hit| hit.path.as_str()).collect();
            text_fallback = text
                .files
                .into_iter()
                .filter(|file| !paths.contains(file.path.as_str()))
                .filter_map(|file| {
                    file.matches
                        .first()
                        .map(|hit| (file.path.clone(), hit.line_number))
                })
                .take(10)
                .collect();
        }
    }
    Ok(SymbolSearchExecution {
        result,
        options,
        suppressed_by_noise,
        text_fallback,
        all_words_rule,
    })
}

/// Symbols whose name contains every word (case-insensitive, `_` ignored), or `None` for
/// a single-word query or no such symbol. The first word's substring search supplies the
/// candidates, widened past the caller's limit so the filter is not starved.
fn all_words_symbol_matches(
    index: &LiveIndex,
    input: &super::search_contract::SearchSymbolsInput,
    options: &search::SymbolSearchOptions,
    words: &[String],
) -> Option<search::SymbolSearchResult> {
    // ponytail: candidates come from one word's substring search capped at 2,000 rows;
    // a full all-words index scan if a first word ever matches more symbols than that.
    const CANDIDATE_LIMIT: usize = 2_000;
    let strip = |text: &str| text.to_lowercase().replace('_', "");
    let (first, rest) = words.split_first()?;
    if rest.is_empty() {
        return None;
    }
    let mut widened = options.clone();
    widened.result_limit =
        search::ResultLimit::new(CANDIDATE_LIMIT.max(options.result_limit.get()));
    let candidates =
        search::search_symbols_with_options(index, first, input.kind.as_deref(), &widened);
    let words: Vec<String> = words.iter().map(|word| strip(word)).collect();
    let mut hits: Vec<_> = candidates
        .hits
        .into_iter()
        .filter(|hit| {
            let name = strip(&hit.name);
            words.iter().all(|word| name.contains(word.as_str()))
        })
        .collect();
    if hits.is_empty() {
        return None;
    }
    let overflow_count = hits.len().saturating_sub(options.result_limit.get());
    hits.truncate(options.result_limit.get());
    let file_count = hits
        .iter()
        .map(|hit| hit.path.as_str())
        .collect::<std::collections::HashSet<_>>()
        .len();
    Some(search::SymbolSearchResult {
        file_count,
        hits,
        overflow_count,
    })
}

fn language_for_path(path: &str) -> Option<LanguageId> {
    Path::new(path)
        .extension()
        .and_then(|extension| extension.to_str())
        .map(str::to_ascii_lowercase)
        .and_then(|extension| LanguageId::from_extension(&extension))
}

/// The untracked paths `live` does not know.
///
/// `live` is the caller's CAPTURED publication — the same bundle that produced
/// the response beside this verdict — so "not in the index" cannot disagree
/// with the rows the receipt names. Taking a `&LiveIndex` rather than the
/// server is what enforces that: this function has no route to
/// `SharedIndexHandle`, so a second, later read is a compile error rather than
/// something a reviewer has to catch.
pub(crate) fn untracked_paths_not_in_index(
    repo: &crate::git::GitRepo,
    live: &LiveIndex,
) -> Vec<String> {
    let Ok(mut paths) = repo.untracked_paths() else {
        return Vec::new();
    };

    paths.retain(|path| live.get_file(path).is_none());
    paths.sort();
    paths.dedup();
    paths
}

pub(crate) fn untracked_file_diagnostic(paths: &[String]) -> Option<String> {
    let first = paths.first()?;
    Some(format!(
        "untracked file may match: {} untracked path(s) are not indexed. To index the first match, call analyze_file_impact(\"{first}\", new_file=true), or re-run index_folder.",
        paths.len(),
    ))
}

pub(crate) fn append_untracked_file_diagnostic(output: &mut String, paths: &[String]) {
    if let Some(diagnostic) = untracked_file_diagnostic(paths) {
        output.push_str("\n\n");
        output.push_str(&diagnostic);
    }
}

fn untracked_text_path_allowed(path: &str, options: &search::TextSearchOptions) -> bool {
    let classification = FileClassification::for_code_path(path);
    options.path_scope.matches(path)
        && options.search_scope.allows(&classification)
        && options.noise_policy.allows(&classification)
        && (options.noise_policy.include_vendor || !crate::live_index::query::is_vendor_path(path))
        && (options.include_personal_tooling
            || !crate::live_index::query::is_personal_tooling_path(path))
        && options
            .language_filter
            .as_ref()
            .is_none_or(|language| language_for_path(path).as_ref() == Some(language))
        && untracked_text_globs_allow(path, options)
}

fn untracked_text_globs_allow(path: &str, options: &search::TextSearchOptions) -> bool {
    let include_matches = match options.glob.as_deref() {
        Some(pattern) => globset::GlobBuilder::new(pattern)
            .literal_separator(false)
            .build()
            .map(|glob| glob.compile_matcher().is_match(path))
            .unwrap_or(false),
        None => true,
    };
    let exclude_matches = match options.exclude_glob.as_deref() {
        Some(pattern) => globset::GlobBuilder::new(pattern)
            .literal_separator(false)
            .build()
            .map(|glob| glob.compile_matcher().is_match(path))
            .unwrap_or(false),
        None => false,
    };
    include_matches && !exclude_matches
}

fn whole_word_contains(haystack: &str, needle: &str) -> bool {
    haystack.match_indices(needle).any(|(idx, matched)| {
        let before_is_word = haystack[..idx]
            .chars()
            .next_back()
            .is_some_and(|ch| ch == '_' || ch.is_alphanumeric());
        let after_idx = idx + matched.len();
        let after_is_word = haystack[after_idx..]
            .chars()
            .next()
            .is_some_and(|ch| ch == '_' || ch.is_alphanumeric());
        !before_is_word && !after_is_word
    })
}

fn untracked_text_matches(
    content: &str,
    query: Option<&str>,
    terms: Option<&[String]>,
    is_regex: bool,
    options: &search::TextSearchOptions,
) -> bool {
    let case_sensitive = options.case_sensitive.unwrap_or(is_regex);
    if is_regex {
        let Some(pattern) = query.map(str::trim).filter(|pattern| !pattern.is_empty()) else {
            return false;
        };
        return regex::RegexBuilder::new(pattern)
            .case_insensitive(!case_sensitive)
            .build()
            .map(|regex| regex.is_match(content))
            .unwrap_or(false);
    }

    let normalized_terms: Vec<&str> = match terms {
        Some(raw_terms) if !raw_terms.is_empty() => raw_terms
            .iter()
            .map(|term| term.trim())
            .filter(|term| !term.is_empty())
            .collect(),
        _ => query
            .map(str::trim)
            .filter(|text| !text.is_empty())
            .map(|text| vec![text])
            .unwrap_or_default(),
    };
    if normalized_terms.is_empty() {
        return false;
    }

    if case_sensitive {
        if options.whole_word {
            normalized_terms
                .iter()
                .any(|term| whole_word_contains(content, term))
        } else {
            normalized_terms.iter().any(|term| content.contains(term))
        }
    } else {
        let lowered = content.to_lowercase();
        normalized_terms.iter().any(|term| {
            let lowered_term = term.to_lowercase();
            if options.whole_word {
                whole_word_contains(&lowered, &lowered_term)
            } else {
                lowered.contains(&lowered_term)
            }
        })
    }
}

/// The untracked paths a zero-hit text search could have missed: unknown to
/// `live`, inside the search's own filters, and matching the query over the
/// bytes `admit` returns. `admit` is the caller's gated working-tree read; it
/// runs BEFORE any matching, because the caller's own regex is evaluated
/// against this content and an anchored pattern would otherwise recover a
/// refused file character by character from which paths come back. A refusal
/// drops the path, disclosing neither content nor existence-by-match.
pub(crate) fn matching_untracked_paths_for_search_text(
    repo: &crate::git::GitRepo,
    live: &LiveIndex,
    query: Option<&str>,
    terms: Option<&[String]>,
    is_regex: bool,
    options: &search::TextSearchOptions,
    admit: &mut dyn FnMut(&str) -> Result<Option<String>, String>,
) -> Vec<String> {
    untracked_paths_not_in_index(repo, live)
        .into_iter()
        .filter(|path| untracked_text_path_allowed(path, options))
        .filter(|path| {
            admit(path).ok().flatten().is_some_and(|content| {
                untracked_text_matches(&content, query, terms, is_regex, options)
            })
        })
        .collect()
}

pub(crate) fn untracked_path_has_component(path: &str, component: &str) -> bool {
    path.split('/')
        .any(|part| part.eq_ignore_ascii_case(component))
}

pub(crate) fn untracked_common_path_filters_allow(
    path: &str,
    include_vendor: bool,
    include_personal_tooling: bool,
) -> bool {
    (include_vendor || !crate::live_index::query::is_vendor_path(path))
        && (include_personal_tooling || !crate::live_index::query::is_personal_tooling_path(path))
}

pub(crate) fn untracked_path_matches_search_files_query(path: &str, query: &str) -> bool {
    let normalized_query = normalize_untracked_search_path(query);
    if normalized_query.is_empty() {
        return false;
    }

    let is_glob = normalized_query.contains('*')
        || normalized_query.contains('?')
        || normalized_query.contains('[');
    if is_glob
        && let Ok(glob) = globset::GlobBuilder::new(&normalized_query)
            .literal_separator(false)
            .build()
    {
        return glob.compile_matcher().is_match(path);
    }

    let path_lower = path.to_ascii_lowercase();
    let normalized_query_lower = normalized_query.to_ascii_lowercase();
    let has_path_context = normalized_query.contains('/');
    if path_lower == normalized_query_lower
        || (has_path_context && path_lower.ends_with(&normalized_query_lower))
    {
        return true;
    }

    let tokens: Vec<String> = normalized_query
        .split(|ch: char| ch == '/' || ch.is_whitespace())
        .filter(|part| !part.is_empty())
        .map(str::to_ascii_lowercase)
        .collect();
    let Some(basename_token) = tokens.last() else {
        return false;
    };
    let component_tokens = if tokens.len() > 1 {
        &tokens[..tokens.len() - 1]
    } else {
        &[][..]
    };
    let file_name = Path::new(path)
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("");
    if file_name.eq_ignore_ascii_case(basename_token)
        && component_tokens
            .iter()
            .all(|component| untracked_path_has_component(path, component))
    {
        return true;
    }

    if basename_token.len() >= 3 {
        let file_stem = Path::new(path)
            .file_stem()
            .and_then(|stem| stem.to_str())
            .unwrap_or("");
        if file_stem.to_ascii_lowercase().starts_with(basename_token) {
            return true;
        }
    }

    tokens.iter().all(|token| path_lower.contains(token))
}

/// MCP `search_text`'s rendered answer over one publication: the result
/// envelope, the grouped view and the zero-hit untracked diagnostic for
/// `matching_untracked_paths`, which the caller swept from its own git root.
#[allow(clippy::too_many_arguments)]
pub(crate) fn render_search_text_output(
    // T046: the caller's entry capture — banner and parse-state come off the
    // SAME publication that produced the rows, not fresh loads taken here.
    generation: &crate::live_index::store::PublishedGeneration,
    result: Result<search::TextSearchResult, search::TextSearchError>,
    query: Option<&str>,
    structural: bool,
    group_by: Option<&str>,
    terms: Option<&[String]>,
    options: &search::TextSearchOptions,
    is_regex: bool,
    auto_detected_regex: bool,
    auto_corrected_regex: bool,
    matching_untracked_paths: &[String],
    hidden_test_matches: Option<usize>,
    // Spec 036: what this call observed about its files against the disk.
    check: &super::freshen::AnswerCheck,
) -> String {
    use super::search_envelope::{
        SourceAuthority, format_search_envelope, search_completeness_label, search_scope_summary,
        search_text_evidence, search_text_match_type_label,
    };
    let envelope = match &result {
        Ok(result) if !result.files.is_empty() => Some(format_search_envelope(
            &search_text_match_type_label(
                structural,
                is_regex,
                terms,
                auto_detected_regex,
                auto_corrected_regex,
                options.ranked,
            ),
            SourceAuthority::from_check(check),
            super::reference_read::search_parse_state_for_paths(
                &generation.live,
                result.files.iter().map(|file| file.path.as_str()),
            ),
            &search_completeness_label(
                result.overflow_count,
                result.suppressed_by_noise,
                result.unparsed_files,
            ),
            &search_scope_summary(
                &options.path_scope,
                options.language_filter.as_ref(),
                &options.noise_policy,
                options.include_personal_tooling,
                options.glob.as_deref(),
                options.exclude_glob.as_deref(),
                options.ranked,
            ),
            &search_text_evidence(result),
        )),
        _ => None,
    };
    let confidence = if auto_corrected_regex {
        0.75f32
    } else if is_regex && auto_detected_regex {
        0.80
    } else if is_regex {
        0.85
    } else if options.ranked {
        0.80
    } else {
        0.95
    };
    let suggestion_ctx = super::search_render::SearchSuggestionContext {
        regex: is_regex,
        include_tests: options.noise_policy.include_tests,
        multi_word_literal: !is_regex
            && query.is_some_and(|q| q.trim().contains(char::is_whitespace)),
    };
    let output = if group_by == Some(GROUP_BY_COUNT) {
        super::search_render::search_text_count_view(result, hidden_test_matches, suggestion_ctx)
    } else {
        super::search_render::search_text_result_view(
            result,
            group_by,
            terms,
            Some(confidence),
            suggestion_ctx,
        )
    };
    let mut rendered = match envelope {
        Some(envelope) => format!("{envelope}\n\n{output}"),
        None => output,
    };
    append_untracked_file_diagnostic(&mut rendered, matching_untracked_paths);
    // Spec 036: the caller fits `check`'s notes inside its budget.
    rendered
}

/// An empty or untruncated text search claims its whole scope (FR-017),
/// unless it skipped files whose parse was cancelled or failed.
pub(crate) fn text_search_claim(
    result: &Result<search::TextSearchResult, search::TextSearchError>,
) -> super::freshen::Claim {
    super::freshen::Claim::whole_if(
        matches!(result, Ok(found) if found.overflow_count == 0 && found.unparsed_files == 0),
    )
}

/// MCP `search_symbols`' rendered answer over one publication: the result
/// envelope, the tiered view and the sparse-hit text fallback.
pub(crate) fn render_symbol_search(
    generation: &crate::live_index::store::PublishedGeneration,
    execution: &SymbolSearchExecution,
    query: &str,
    check: &super::freshen::AnswerCheck,
) -> String {
    use super::search_envelope::{
        SourceAuthority, format_search_envelope, search_completeness_label, search_scope_summary,
        search_symbols_evidence, search_symbols_match_type_label,
    };
    let result = &execution.result;
    let options = &execution.options;
    let is_browse = query.is_empty();
    // Browse ordering is owned by the engine (search::search_symbols_with_options),
    // which ranks browse results by importance (reference count -> kind -> path ->
    // line). Do NOT re-sort here: a tool-level re-sort would override that order and
    // reintroduce the symbol_kind_priority display-kind mismatch ("fn" -> 0.1). (018 US2)
    let envelope = if result.hits.is_empty() {
        None
    } else {
        Some(format_search_envelope(
            search_symbols_match_type_label(result, is_browse),
            SourceAuthority::from_check(check),
            super::reference_read::search_parse_state_for_paths(
                &generation.live,
                result.hits.iter().map(|hit| hit.path.as_str()),
            ),
            &search_completeness_label(result.overflow_count, execution.suppressed_by_noise, 0),
            &search_scope_summary(
                &options.path_scope,
                options.language_filter.as_ref(),
                &options.noise_policy,
                options.include_personal_tooling,
                None,
                None,
                false,
            ),
            &search_symbols_evidence(result),
        ))
    };
    let output = super::search_render::search_symbols_result_view(result, query);
    let output = match &execution.all_words_rule {
        Some(words) => format!(
            "No exact match for \"{query}\"; showing symbols whose names contain all words ({}).\n{output}",
            words.join(", ")
        ),
        None => output,
    };
    let output = match envelope {
        Some(envelope) => format!("{envelope}\n\n{output}"),
        None => output,
    };
    let output = if execution.text_fallback.is_empty() {
        output
    } else {
        let paths: Vec<_> = execution
            .text_fallback
            .iter()
            .map(|(path, line)| format!("{path}:{line}"))
            .collect();
        format!(
            "{output}\n\nText path fallback (sparse symbol hits):\n{}",
            paths.join("\n")
        )
    };
    // Spec 036: the caller fits `check`'s notes inside its budget.
    output
}

/// MCP `search_files`' zero-hit diagnostic: untracked worktree paths the
/// publication does not know whose names match `query`.
pub(crate) fn matching_untracked_paths_for_search_files(
    repo: &crate::git::GitRepo,
    live: &LiveIndex,
    query: &str,
    include_vendor: bool,
    include_personal_tooling: bool,
) -> Vec<String> {
    untracked_paths_not_in_index(repo, live)
        .into_iter()
        .filter(|path| {
            untracked_common_path_filters_allow(path, include_vendor, include_personal_tooling)
                && untracked_path_matches_search_files_query(path, query)
        })
        .collect()
}

pub(crate) fn normalize_untracked_search_path(raw: &str) -> String {
    let mut normalized = raw.trim().replace('\\', "/");
    while normalized.starts_with("./") {
        normalized = normalized[2..].to_string();
    }
    normalized.trim_matches('/').to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn caller_enrichment_selects_stable_rows_and_earliest_reference_before_cap() {
        let root = tempfile::tempdir().unwrap();
        std::fs::write(
            root.path().join("targets.rs"),
            "pub fn zebra() {}\npub fn alpha() {}\n",
        )
        .unwrap();
        for name in ["z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] {
            std::fs::write(
                root.path().join(format!("{name}.rs")),
                format!("fn caller_{name}() {{\n zebra();\n alpha();\n}}\n"),
            )
            .unwrap();
        }
        let shared = crate::live_index::LiveIndex::load(root.path()).unwrap();
        let index = shared.read();
        let result = search::search_text_with_options(
            &index,
            Some("pub fn"),
            None,
            false,
            &search::TextSearchOptions {
                path_scope: search::PathScope::exact("targets.rs"),
                max_per_file: 20,
                ..search::TextSearchOptions::default()
            },
        )
        .unwrap();
        for _ in 0..64 {
            let mut result = Ok(result.clone());
            resolve_text_search_enclosing_symbols(&index, &mut result);
            let mut result = result.unwrap();
            enrich_with_callers(&index, &mut result, 1);
            let callers = result.files[0].callers.as_ref().unwrap();
            let paths: Vec<_> = callers.iter().map(|caller| caller.file.as_str()).collect();
            assert_eq!(
                paths,
                vec![
                    "a.rs", "b.rs", "c.rs", "d.rs", "e.rs", "f.rs", "g.rs", "h.rs", "i.rs", "j.rs"
                ]
            );
            assert!(callers.iter().all(|caller| caller.line == 2));
        }
    }
}