Skip to main content

code_kb_core/
formatters.rs

1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::path::Path;
3
4use crate::edit_check::{BaseSource, EditCheck, EditSite, ShapeChange};
5use crate::models::{
6    BlastRadiusResult, CallingTest, ConstructionSite, ContextSlice, ImpactedSymbol, LabeledSite,
7    OverrideRow, ReferenceReport, ReferenceSite, Registration, SearchExplain, SiteLabel, Symbol,
8    SymbolSearchResult, VariantUse,
9};
10
11/// Format progressive disclosure file skeleton with implementation bodies stripped.
12pub fn format_file_skeleton(
13    file_path: &str,
14    symbols: &[Symbol],
15    line_count: Option<usize>,
16    parse_errors: usize,
17) -> String {
18    let mut out = String::new();
19    let lines_str = match line_count {
20        Some(c) => format!(" (Lines 1-{c})"),
21        None => String::new(),
22    };
23    out.push_str(&format!("// File: {file_path}{lines_str}\n\n"));
24
25    if parse_errors > 0 {
26        let noun = if parse_errors == 1 { "error" } else { "errors" };
27        out.push_str(&format!(
28            "// {parse_errors} parse {noun}: symbols may be incomplete\n\n"
29        ));
30    }
31
32    if symbols.is_empty() {
33        out.push_str("// No exported symbols indexed.\n");
34        return out;
35    }
36
37    // A Rust `impl` block in this file can belong to a type in another file; its methods are roots here.
38    let in_file: HashSet<&str> = symbols.iter().map(|s| s.symbol_id.as_str()).collect();
39    let mut children_map: HashMap<Option<String>, Vec<&Symbol>> = HashMap::new();
40    for s in symbols {
41        let parent = s
42            .parent_symbol_id
43            .clone()
44            .filter(|parent| in_file.contains(parent.as_str()));
45        children_map.entry(parent).or_default().push(s);
46    }
47
48    // Render top-level symbols and their children
49    if let Some(roots) = children_map.get(&None) {
50        for root in roots {
51            render_symbol_skeleton(&mut out, root, None, &children_map, 0);
52        }
53    } else {
54        // If parent relationships are missing or flat, render all sorted by line
55        for s in symbols {
56            render_symbol_skeleton(&mut out, s, None, &children_map, 0);
57        }
58    }
59
60    out
61}
62
63fn is_container_kind(kind: &str) -> bool {
64    let hides_its_body = matches!(
65        kind,
66        "function" | "method" | "constructor" | "destructor" | "operator"
67    );
68    !is_skippable_kind(kind) && !hides_its_body
69}
70
71/// The kind word to show for a symbol. julie reuses code kinds for markup and data files: an
72/// HTML element and a SQL table are `class` rows, a Markdown heading a `module`, a Markdown
73/// link an `import`. `queries::KIND_FILTER` mirrors it in SQL.
74pub(crate) fn display_kind(sym: &Symbol) -> &str {
75    match (sym.language.as_str(), sym.kind.as_str()) {
76        ("html", "class") => "element",
77        ("sql", "class") => "table",
78        ("markdown", "module") => "section",
79        ("markdown", "import") => "link",
80        (language, "property")
81            if language != "fsharp"
82                && sym.signature.as_deref().is_some_and(|sig| {
83                    ["self.", "this.", "cls."]
84                        .iter()
85                        .any(|p| sig.starts_with(p))
86                }) =>
87        {
88            "attribute"
89        }
90        (_, kind) => kind,
91    }
92}
93
94fn is_skippable_kind(kind: &str) -> bool {
95    matches!(kind, "variable" | "parameter" | "import")
96}
97
98/// A value row on one line: the declaration before its `=` stays whole, because its type is part
99/// of the interface, and the value is cut to fit about 120 characters.
100fn value_row_signature(sig: &str) -> std::borrow::Cow<'_, str> {
101    let sig = sig.trim_end().trim_end_matches(';').trim_end();
102    if !sig.contains('\n') && sig.chars().count() <= 120 {
103        return sig.into();
104    }
105    let joined = one_line(sig);
106    let Some(equals) = value_equals(&joined) else {
107        if joined.chars().count() <= 120 {
108            return joined.into();
109        }
110        let cut: String = joined.chars().take(119).collect();
111        return format!("{}…", cut.trim_end()).into();
112    };
113    let (declaration, value) = joined.split_at(equals);
114    let budget = 120usize.saturating_sub(declaration.chars().count()).max(40);
115    if value.chars().count() <= budget {
116        return joined.into();
117    }
118    let cut: String = value.chars().take(budget - 1).collect();
119    format!("{declaration}{}…", cut.trim_end()).into()
120}
121
122/// Joins a multi-line declaration into one line, without trailing `  # ` or `  // ` comments.
123fn one_line(sig: &str) -> String {
124    let mut joined = sig
125        .lines()
126        .map(|line| {
127            let code = ["  # ", "  // "]
128                .iter()
129                .filter_map(|marker| line.find(marker))
130                .min()
131                .map_or(line, |at| &line[..at]);
132            code.trim().trim_end_matches('\\').trim_end()
133        })
134        .filter(|line| !line.is_empty())
135        .collect::<Vec<_>>()
136        .join(" ");
137    for (from, to) in [
138        ("( ", "("),
139        ("[ ", "["),
140        ("{ ", "{"),
141        (", )", ")"),
142        (", ]", "]"),
143        (", }", "}"),
144        (" )", ")"),
145        (" ]", "]"),
146        (" }", "}"),
147    ] {
148        joined = joined.replace(from, to);
149    }
150    joined
151}
152
153/// Whether `sig` assigns a value: an `=` outside brackets, before any `{`, that is not part of
154/// `==`, `=>`, `>=`, `^=`, or another operator.
155fn assigns_a_value(sig: &str) -> bool {
156    value_equals(sig).is_some()
157}
158
159/// The byte index of the `=` that assigns a value, as [`assigns_a_value`] defines it.
160fn value_equals(sig: &str) -> Option<usize> {
161    let bytes = sig.as_bytes();
162    let mut depth = 0usize;
163    for (i, &byte) in bytes.iter().enumerate() {
164        match byte {
165            b'(' | b'[' => depth += 1,
166            b')' | b']' => depth = depth.saturating_sub(1),
167            b'{' if depth == 0 => return None,
168            b'=' if depth == 0 => {
169                let before = i.checked_sub(1).map(|j| bytes[j]);
170                let after = bytes.get(i + 1).copied();
171                let operator_before = before.is_some_and(|b| b"<>!=^*~|$+-/%&:?".contains(&b));
172                let operator_after = after.is_some_and(|b| b == b'=' || b == b'>');
173                if !operator_before && !operator_after {
174                    return Some(i);
175                }
176            }
177            _ => {}
178        }
179    }
180    None
181}
182
183fn sanitize_skeleton_sig<'a>(sig: &'a str, sym: &'a Symbol) -> std::borrow::Cow<'a, str> {
184    if matches!(
185        sym.kind.as_str(),
186        "variable" | "constant" | "property" | "field" | "enum_member"
187    ) && assigns_a_value(sig)
188    {
189        return value_row_signature(sig);
190    }
191    container_signature(sig, sym)
192}
193
194/// The signature cut at its first `{`, which opens the body that the skeleton renders.
195fn container_signature<'a>(sig: &'a str, sym: &'a Symbol) -> std::borrow::Cow<'a, str> {
196    let expression_arrow = if sym.language == "csharp"
197        && matches!(
198            sym.kind.as_str(),
199            "method" | "function" | "constructor" | "operator"
200        ) {
201        sig.match_indices("=>")
202            .find_map(|(idx, _)| sig[..idx].trim_end().ends_with(')').then_some(idx))
203    } else {
204        None
205    };
206    let cutoff = sig
207        .find('{')
208        .into_iter()
209        .chain(expression_arrow)
210        .min()
211        .unwrap_or(sig.len());
212    let clean = sig[..cutoff].trim_end();
213    let trimmed = clean.trim_end_matches(';').trim_end();
214    if trimmed.is_empty() {
215        sym.name.as_str().into()
216    } else {
217        trimmed.into()
218    }
219}
220
221fn signature_without_duplicate_body<'a>(signature: &'a str, body: &str) -> &'a str {
222    let body = body.trim();
223    if body.is_empty() {
224        return signature;
225    }
226
227    let trimmed_signature = signature.trim_end();
228    trimmed_signature
229        .strip_suffix(body)
230        .map(str::trim_end)
231        .unwrap_or(signature)
232}
233
234/// The kind word for a leaf row whose signature does not spell it. A C++ Qt signal is declared
235/// under a `Q_SIGNALS:` label, so its signature reads like a method; the `event` kind goes into
236/// the trailing comment instead.
237fn unspelled_kind(sym: &Symbol) -> &'static str {
238    if sym.kind != "event" {
239        return "";
240    }
241    let spelled = sym.signature.as_deref().is_some_and(|sig| {
242        sig.split_whitespace()
243            .any(|word| word == "signal" || word == "event")
244    });
245    if spelled { "" } else { "event " }
246}
247
248/// `in run(), ` for an attribute that a method assigns, so the skeleton does not present it as
249/// a declaration of the class body.
250fn assigning_method(
251    sym: &Symbol,
252    parent: Option<&Symbol>,
253    children_map: &HashMap<Option<String>, Vec<&Symbol>>,
254) -> String {
255    if !sym
256        .signature
257        .as_deref()
258        .is_some_and(|sig| sig.starts_with("self."))
259    {
260        return String::new();
261    }
262    parent
263        .and_then(|parent| children_map.get(&Some(parent.symbol_id.clone())))
264        .and_then(|siblings| {
265            siblings.iter().find(|method| {
266                matches!(method.kind.as_str(), "method" | "function" | "constructor")
267                    && method.start_line <= sym.start_line
268                    && sym.end_line <= method.end_line
269            })
270        })
271        .map_or_else(String::new, |method| format!("in {}(), ", method.name))
272}
273
274/// julie gives other languages' block locals, markup elements, and data keys a `variable` row
275/// under a parent too; only a Python module or class body declares names that way.
276fn is_shown(sym: &Symbol, parent: Option<&Symbol>) -> bool {
277    let python_declaration = sym.kind == "variable"
278        && sym.language == "python"
279        && parent.is_none_or(|parent| parent.kind == "class");
280    !is_skippable_kind(&sym.kind) || python_declaration
281}
282
283/// `; defines `a`, `b`` for the functions and classes declared inside a hidden body, so a view
284/// or wrapper defined in a factory stays visible. Lambdas are left out.
285/// C and C++ cannot define a function inside a function, so such a row comes from a macro the
286/// parser misread (`JSON_CATCH (...) { }`). Test sections such as doctest `SECTION` are real.
287fn is_misparsed_c_function(child: &Symbol) -> bool {
288    matches!(child.language.as_str(), "c" | "cpp")
289        && matches!(child.kind.as_str(), "function" | "method")
290        && !child.is_test
291        && !child.test_container
292}
293
294fn nested_definitions(children: &[&Symbol]) -> String {
295    let names: Vec<String> = children
296        .iter()
297        .filter(|child| {
298            matches!(
299                child.kind.as_str(),
300                "function" | "method" | "class" | "struct"
301            )
302        })
303        .filter(|child| {
304            !child
305                .signature
306                .as_deref()
307                .is_some_and(|sig| sig.starts_with("lambda"))
308        })
309        .filter(|child| !is_misparsed_c_function(child))
310        .map(|child| format!("`{}`", child.name))
311        .fold(Vec::new(), |mut names, name| {
312            if !names.contains(&name) {
313                names.push(name);
314            }
315            names
316        });
317    match names.len() {
318        0 => String::new(),
319        1..=5 => format!("; defines {}", names.join(", ")),
320        n => format!("; defines {}, +{} more", names[..5].join(", "), n - 5),
321    }
322}
323
324fn render_symbol_skeleton(
325    out: &mut String,
326    sym: &Symbol,
327    parent: Option<&Symbol>,
328    children_map: &HashMap<Option<String>, Vec<&Symbol>>,
329    indent_level: usize,
330) {
331    if !is_shown(sym, parent) {
332        return;
333    }
334
335    let indent = "    ".repeat(indent_level);
336
337    if let Some(ref doc) = sym.doc_comment {
338        let document = crate::queries::DOCUMENTATION_LANGUAGES.contains(&sym.language.as_str());
339        let lines: Vec<_> = if document {
340            doc.lines().collect()
341        } else {
342            doc.lines()
343                .map(doc_line_text)
344                .filter(|line| !line.is_empty())
345                .collect()
346        };
347        let cap = 3;
348        for line in lines.iter().take(cap) {
349            out.push_str(&format!("{indent}/// {line}\n"));
350        }
351        if lines.len() > cap {
352            out.push_str(&format!(
353                "{indent}/// ... ({} more lines)\n",
354                lines.len() - cap
355            ));
356        }
357    }
358
359    let span_str = format!("L{}-{}", sym.start_line, sym.end_line);
360    let leaf_note = format!(
361        "{}{}{span_str}",
362        unspelled_kind(sym),
363        assigning_method(sym, parent, children_map)
364    );
365
366    let children = children_map.get(&Some(sym.symbol_id.clone()));
367
368    let spans_multiple_lines = sym.end_line > sym.start_line;
369
370    if is_container_kind(&sym.kind)
371        && children.is_some_and(|list| list.iter().any(|child| is_shown(child, Some(sym))))
372        && (spans_multiple_lines || sym.kind == "enum")
373    {
374        let raw_sig = sym.signature.as_deref().unwrap_or(&sym.name);
375        let sig = container_signature(raw_sig, sym);
376        out.push_str(&format!("{indent}{sig} {{\n"));
377        if let Some(child_list) = children {
378            for child in child_list {
379                render_symbol_skeleton(out, child, Some(sym), children_map, indent_level + 1);
380            }
381        }
382        out.push_str(&format!("{indent}}} // {span_str}\n\n"));
383    } else {
384        if let Some(count) = sym.hidden_body_line_count() {
385            let raw_sig = sym.signature.as_deref().unwrap_or(&sym.name);
386            let sig = if count > 1 {
387                container_signature(raw_sig, sym)
388            } else {
389                sanitize_skeleton_sig(raw_sig, sym)
390            };
391            let b_start = sym.body_start_line.unwrap_or(sym.start_line);
392            let b_end = sym.body_end_line.unwrap_or(sym.end_line);
393
394            if count > 1 {
395                let defines = nested_definitions(children.map(Vec::as_slice).unwrap_or_default());
396                out.push_str(&format!(
397                    "{indent}{sig} {{ /* {count} lines hidden: L{b_start}-L{b_end}{defines} */ }}\n"
398                ));
399            } else {
400                out.push_str(&format!("{indent}{sig}; // {leaf_note}\n"));
401            }
402        } else if let Some(ref raw_sig) = sym.signature {
403            let sig = sanitize_skeleton_sig(raw_sig, sym);
404            out.push_str(&format!("{indent}{sig}; // {leaf_note}\n"));
405        } else {
406            out.push_str(&format!(
407                "{indent}{} {sym_name}; // {span_str}\n",
408                display_kind(sym),
409                sym_name = sym.name
410            ));
411        }
412        if sym.kind == "namespace"
413            && let Some(child_list) = children
414        {
415            for child in child_list {
416                render_symbol_skeleton(out, child, Some(sym), children_map, indent_level);
417            }
418        }
419    }
420}
421
422/// Node representing directory or file in codebase outline tree.
423#[derive(Default)]
424pub struct OutlineNode {
425    pub files: BTreeMap<String, Vec<String>>, // file_name -> list of top symbol names with kinds
426    pub subdirs: BTreeMap<String, OutlineNode>,
427    /// Files under this directory that lie below the depth limit.
428    pub hidden_files: usize,
429    /// Indexed files in this directory with no function, class, or test to list.
430    pub plain_files: Vec<String>,
431    /// Files under this directory that no extractor reads.
432    pub unsupported_files: usize,
433}
434
435/// The path components of `file_path` below the outline's path filter, or `None` for a path
436/// outside it.
437fn outline_components(file_path: &str, norm_filter: &str) -> Option<Vec<String>> {
438    let normalized = file_path.replace('\\', "/");
439    let rel_path_str = if norm_filter.is_empty() {
440        normalized.as_str()
441    } else if normalized.eq_ignore_ascii_case(norm_filter) {
442        Path::new(&normalized)
443            .file_name()
444            .and_then(|n| n.to_str())
445            .unwrap_or(&normalized)
446    } else if normalized.len() > norm_filter.len()
447        && normalized.as_bytes()[norm_filter.len()] == b'/'
448        && normalized[..norm_filter.len()].eq_ignore_ascii_case(norm_filter)
449    {
450        &normalized[norm_filter.len() + 1..]
451    } else {
452        return None;
453    };
454
455    let path = Path::new(rel_path_str);
456    let components: Vec<String> = path
457        .components()
458        .map(|c| c.as_os_str().to_str().unwrap_or(""))
459        .filter(|s| !s.is_empty())
460        .map(str::to_string)
461        .collect();
462
463    if components.is_empty() {
464        return None;
465    }
466
467    Some(components)
468}
469
470/// Counts a file no extractor reads on the deepest folder the outline already shows for it, or
471/// on its top-level folder. Call it after every indexed file is added.
472pub fn add_unsupported_to_outline(
473    root_node: &mut OutlineNode,
474    file_path: &str,
475    max_depth: usize,
476    norm_filter: &str,
477) {
478    let Some(components) = outline_components(file_path, norm_filter) else {
479        return;
480    };
481    let mut curr = root_node;
482    for (i, comp) in components
483        .iter()
484        .take(components.len() - 1)
485        .take(max_depth)
486        .enumerate()
487    {
488        if i > 0 && !curr.subdirs.contains_key(comp) {
489            break;
490        }
491        curr = curr.subdirs.entry(comp.clone()).or_default();
492    }
493    curr.unsupported_files += 1;
494}
495
496/// Add a file path into the outline tree, bounded by max_depth.
497pub fn add_path_to_outline(
498    root_node: &mut OutlineNode,
499    file_path: &str,
500    symbols_by_file: &HashMap<String, Vec<Symbol>>,
501    counts: &HashMap<String, crate::queries::OutlineCounts>,
502    max_depth: usize,
503    norm_filter: &str,
504) {
505    let Some(components) = outline_components(file_path, norm_filter) else {
506        return;
507    };
508    let normalized = file_path.replace('\\', "/");
509
510    let mut curr = root_node;
511    let depth = components.len();
512
513    for (i, comp) in components.iter().enumerate() {
514        if i == depth - 1 {
515            if depth > max_depth {
516                curr.hidden_files += 1;
517            } else {
518                let mut sym_tags: Vec<String> = symbols_by_file
519                    .get(&normalized)
520                    .into_iter()
521                    .flatten()
522                    .filter(|s| !s.is_test && !s.test_container)
523                    .take(5)
524                    .map(|s| format!("{} {}", display_kind(s), s.name))
525                    .collect();
526                let count = counts.get(&normalized).copied().unwrap_or_default();
527                if count.definitions > sym_tags.len() {
528                    sym_tags.push(format!("+{} more", count.definitions - sym_tags.len()));
529                }
530                if count.tests > 0 {
531                    sym_tags.push(format!("{} {}", count.tests, plural(count.tests, "test")));
532                }
533                if count.fixtures > 0 {
534                    sym_tags.push(format!(
535                        "{} {}",
536                        count.fixtures,
537                        plural(count.fixtures, "fixture")
538                    ));
539                }
540                if sym_tags.is_empty() {
541                    curr.plain_files.push(comp.to_string());
542                } else {
543                    curr.files.insert(comp.to_string(), sym_tags);
544                }
545            }
546        } else if i < max_depth {
547            curr = curr.subdirs.entry(comp.to_string()).or_default();
548        } else {
549            curr.hidden_files += 1;
550            break;
551        }
552    }
553}
554
555/// The most files with definitions a subfolder lists; the folder the outline starts at lists all.
556const FILES_LISTED_PER_FOLDER: usize = 40;
557
558pub fn render_outline_tree(
559    out: &mut String,
560    node: &OutlineNode,
561    prefix: &str,
562    depth: usize,
563    max_depth: usize,
564) {
565    if depth >= max_depth {
566        return;
567    }
568
569    let listed = if depth == 0 {
570        node.files.len()
571    } else {
572        node.files.len().min(FILES_LISTED_PER_FOLDER)
573    };
574    let more_files = node.files.len() - listed;
575    let total_items = node.subdirs.len()
576        + listed
577        + usize::from(more_files > 0)
578        + usize::from(!node.plain_files.is_empty());
579    let mut index = 0;
580
581    // Render subdirectories
582    for (name, sub) in &node.subdirs {
583        index += 1;
584        let is_last = index == total_items;
585        let branch = if is_last { "└── " } else { "├── " };
586        let next_prefix = format!("{}{}", prefix, if is_last { "    " } else { "│   " });
587
588        let hidden = match (sub.hidden_files, sub.unsupported_files) {
589            (0, 0) => String::new(),
590            (0, m) => format!(" ({m} unsupported {})", plural(m, "file")),
591            (n, 0) => format!(" ({n} indexed {})", plural(n, "file")),
592            (n, m) => format!(" ({n} indexed {}, {m} unsupported)", plural(n, "file")),
593        };
594        out.push_str(&format!("{prefix}{branch}{name}/{hidden}\n"));
595        render_outline_tree(out, sub, &next_prefix, depth + 1, max_depth);
596    }
597
598    // Render files
599    for (file_name, syms) in node.files.iter().take(listed) {
600        index += 1;
601        let is_last = index == total_items;
602        let branch = if is_last { "└── " } else { "├── " };
603
604        let sym_suffix = if !syms.is_empty() {
605            format!(" [{}]", syms.join(", "))
606        } else {
607            String::new()
608        };
609
610        out.push_str(&format!("{prefix}{branch}{file_name}{sym_suffix}\n"));
611    }
612
613    if more_files > 0 {
614        index += 1;
615        let branch = if index == total_items {
616            "└── "
617        } else {
618            "├── "
619        };
620        out.push_str(&format!(
621            "{prefix}{branch}(+{more_files} more {} with functions or classes; pass this folder as the path to list them)\n",
622            plural(more_files, "file")
623        ));
624    }
625
626    if !node.plain_files.is_empty() {
627        let count = node.plain_files.len();
628        let names = if count <= 5 {
629            node.plain_files.join(", ")
630        } else {
631            format!("{}, +{} more", node.plain_files[..3].join(", "), count - 3)
632        };
633        out.push_str(&format!(
634            "{prefix}└── ({count} {} without functions or classes: {names})\n",
635            plural(count, "file")
636        ));
637    }
638}
639
640/// Format symbol body with metadata header, signature, and body content.
641/// A symbol's source as written, under a location comment.
642pub fn format_symbol_body(symbol: &Symbol, source: &str) -> String {
643    let mut out = format!(
644        "// {}:{}-{} ({})\n{source}",
645        symbol.path, symbol.start_line, symbol.end_line, symbol.name
646    );
647    if !source.ends_with('\n') {
648        out.push('\n');
649    }
650    out
651}
652
653/// The bodies of one symbol or of its overloads, each under its own location comment.
654pub fn format_symbol_bodies(bodies: &[(Symbol, String)]) -> String {
655    let mut out = overloads_header(bodies.iter().map(|(symbol, _)| symbol));
656    let parts: Vec<String> = bodies
657        .iter()
658        .map(|(symbol, source)| format_symbol_body(symbol, source))
659        .collect();
660    out.push_str(&parts.join("\n"));
661    out
662}
663
664/// The context of one symbol or of each of its overloads.
665pub fn format_context_slices(slices: &[ContextSlice]) -> String {
666    let mut out = overloads_header(slices.iter().map(|slice| &slice.target_symbol));
667    let parts: Vec<String> = slices.iter().map(format_context_slice).collect();
668    out.push_str(&parts.join("\n"));
669    out
670}
671
672fn overloads_header<'a>(symbols: impl ExactSizeIterator<Item = &'a Symbol>) -> String {
673    let count = symbols.len();
674    let mut symbols = symbols;
675    match symbols.next() {
676        Some(first) if count > 1 => format!(
677            "`{}` has {count} overloads in {}; each one follows.\n\n",
678            first.name, first.path
679        ),
680        _ => String::new(),
681    }
682}
683
684/// Format surgical context bundle for a symbol.
685pub fn format_context_slice(slice: &ContextSlice) -> String {
686    let sym = &slice.target_symbol;
687    let mut out = String::new();
688    out.push_str(&format!(
689        "### Target: `{}` ({}:{}-{})\n\n",
690        sym.name, sym.path, sym.start_line, sym.end_line
691    ));
692
693    if let Some(ref sig) = sym.signature {
694        let sig = signature_without_duplicate_body(sig, &slice.target_body);
695        if !sig.trim().is_empty() {
696            out.push_str(&format!("Signature: `{sig}`\n\n"));
697        }
698    }
699
700    out.push_str(&format!("```{}\n", sym.language));
701    out.push_str(&slice.target_body);
702    if !slice.target_body.ends_with('\n') {
703        out.push('\n');
704    }
705    out.push_str("```\n\n");
706
707    if !slice.callee_signatures.is_empty() {
708        out.push_str("### Dependencies (Signatures):\n");
709        for callee in &slice.callee_signatures {
710            out.push_str(&format!("- {callee}\n"));
711        }
712        if slice.callee_signatures.len() >= 10 {
713            out.push_str("[Showing 10 dependencies (limit reached)]\n");
714        }
715        out.push('\n');
716    }
717
718    if !slice.related_types.is_empty() {
719        out.push_str("### Types:\n");
720        for t in &slice.related_types {
721            out.push_str(&format!("- {t}\n"));
722        }
723        out.push('\n');
724    }
725
726    if !slice.related_tests.is_empty() {
727        out.push_str("### Related Tests:\n");
728        for test in &slice.related_tests {
729            out.push_str(&format!(
730                "- `{}` ({}:{})\n",
731                test.name, test.path, test.start_line
732            ));
733        }
734        if slice.related_tests.len() >= 5 {
735            out.push_str("[Showing 5 tests (limit reached)]\n");
736        }
737        out.push_str("These tests call, use, or name this symbol; blast_radius also lists tests that can reach it through callers.\n\n");
738    } else {
739        out.push_str(
740            "### Related Tests:\nNo test calls, uses, or names this symbol; blast_radius lists tests that can reach it through callers.\n",
741        );
742    }
743
744    out
745}
746
747fn cap_notice(shown: usize, limit: usize) -> String {
748    let advice = if limit >= crate::queries::MAX_RESULT_LIMIT {
749        "narrow the query to see more"
750    } else {
751        "increase limit to see more"
752    };
753    format!("\n[Showing {shown} results (limit reached); {advice}.]\n")
754}
755
756/// The FTS match snippet on one line, or `None` when it only repeats the signature. The comment
757/// markers that open each doc-comment line (`//`, `///`, `//!`, `*`) are dropped when lines join.
758fn match_line(snippet: &str, signature: &str) -> Option<String> {
759    let line = snippet
760        .lines()
761        .enumerate()
762        .map(|(i, text)| match i {
763            0 => text.trim(),
764            _ => text.trim().trim_start_matches(['/', '*', '!']).trim(),
765        })
766        .flat_map(str::split_whitespace)
767        .collect::<Vec<_>>()
768        .join(" ");
769    let plain = |text: &str| {
770        text.split_whitespace()
771            .collect::<String>()
772            .replace(['[', ']'], "")
773    };
774    let matched = plain(line.trim_start_matches("...").trim_end_matches("..."));
775    (!line.is_empty() && !plain(signature).contains(&matched)).then_some(line)
776}
777
778/// A callee name on one line. An unresolved call chain longer than 60 characters that holds a
779/// call keeps only its last call, so a multi-line receiver expression never floods the list.
780fn callee_name(name: &str) -> String {
781    let line = name.split_whitespace().collect::<Vec<_>>().join(" ");
782    if line.chars().count() <= 60 || !line.contains('(') {
783        return line;
784    }
785    match line.rsplit_once('.') {
786        Some((_, last)) if !last.is_empty() => format!("….{last}"),
787        _ => line,
788    }
789}
790
791/// Format references list for callers/callees with optional limit footer.
792/// One line for the import statements of a target: their count and the first three sites.
793pub fn format_import_summary(sites: &[(String, usize)]) -> String {
794    if sites.is_empty() {
795        return String::new();
796    }
797    let files: std::collections::BTreeSet<&str> =
798        sites.iter().map(|(path, _)| path.as_str()).collect();
799    let first: Vec<String> = sites
800        .iter()
801        .take(3)
802        .map(|(path, line)| format!("{path}:{line}"))
803        .collect();
804    let more = if sites.len() > 3 { ", …" } else { "" };
805    format!(
806        "Imported {} {} in {} {}: {}{more} (lookup_symbol with kind=\"import\" lists them)\n",
807        sites.len(),
808        plural(sites.len(), "time"),
809        files.len(),
810        plural(files.len(), "file"),
811        first.join(", ")
812    )
813}
814
815pub fn format_references(
816    target_name: &str,
817    refs: &[ReferenceSite],
818    direction: &str,
819    limit: usize,
820) -> String {
821    let mut out = String::new();
822    let dir_label = if direction == "callers" {
823        "Callers of"
824    } else {
825        "Callees called by"
826    };
827    out.push_str(&format!(
828        "{dir_label} `{target_name}` ({} found):\n",
829        refs.len()
830    ));
831
832    if refs.is_empty() {
833        out.push_str("  (none)\n");
834        return out;
835    }
836
837    for r in refs {
838        let line_info = match r.start_line {
839            Some(l) => format!(":{l}"),
840            None => String::new(),
841        };
842        let other = if direction == "callers" {
843            caller_text(r)
844        } else {
845            format!("`{}`", callee_name(&r.to_symbol_name))
846        };
847        let in_file = match r.occurrences {
848            Some(n) => format!(", {n} in file"),
849            None => String::new(),
850        };
851        let target = match &r.target {
852            Some(target) if direction != "callers" => format!(" → {target}"),
853            _ => String::new(),
854        };
855        out.push_str(&format!(
856            "- {other} [{}{line_info}] (kind: {}{in_file}){target}\n",
857            r.path, r.kind
858        ));
859    }
860
861    if refs.len() >= limit {
862        out.push_str(&cap_notice(refs.len(), limit));
863    }
864
865    out
866}
867
868fn caller_text(site: &ReferenceSite) -> String {
869    if site.from_symbol_name.is_empty() && site.enclosing_symbol_name.is_none() {
870        "(no enclosing symbol)".to_string()
871    } else {
872        format!(
873            "`{}`",
874            displayed_symbol_name(
875                &site.from_symbol_name,
876                site.enclosing_symbol_name.as_deref()
877            )
878        )
879    }
880}
881
882const FOLD_FILES_NAMED: usize = 5;
883const TEXT_ONLY_FILES_LISTED: usize = 10;
884const TEXT_ONLY_LINES_PER_FILE: usize = 12;
885
886/// The callers answer: three header lines, the sites in label order up to `limit`, the text-only
887/// lines, the blind spots of the index, and the import summary. Counts are always complete.
888pub fn format_reference_report(report: &ReferenceReport, limit: usize) -> String {
889    let target = &report.target;
890    let counts = &report.counts;
891    let mut out = format!(
892        "References to {} `{}` ({}:{})\nSites: {} · proven {} · likely {} · unresolved {} · excluded {}\n",
893        target.kind,
894        target.display_name,
895        target.path,
896        target.line,
897        counts.sites,
898        counts.proven,
899        counts.likely,
900        counts.unresolved,
901        counts.excluded,
902    );
903    out.push_str(&text_count_line(report));
904    let scan = &report.text_scan;
905    if !scan.complete && scan.skipped.is_none() {
906        out.push_str(&format!(
907            "Text scan stopped after {} s: {} of {} files read; counts cover those files.\n",
908            (scan.elapsed_ms + 500) / 1000,
909            scan.files_scanned,
910            scan.files_total
911        ));
912    }
913
914    let mut body = site_groups(&report.sites, limit);
915    body.push_str(&override_sections(report, limit));
916    body.push_str(&construction_section(&report.constructions, limit));
917    body.push_str(&variant_section(&report.variant_uses, limit));
918    body.push_str(&registration_section(&report.registrations, limit));
919    body.push_str(&test_section(&report.tests, limit));
920    body.push_str(&text_only_section(report));
921    if !report.cannot_see.is_empty() {
922        body.push_str(&format!(
923            "Not visible to this index: {}.\n",
924            report.cannot_see.join("; ")
925        ));
926    }
927    body.push_str(&format_import_summary(&report.imports));
928    if !body.is_empty() {
929        out.push('\n');
930        out.push_str(&body);
931    }
932    out
933}
934
935fn text_count_line(report: &ReferenceReport) -> String {
936    if let Some(class) = &report.text_scan.skipped {
937        return format!(
938            "Text: skipped for a constructor; its call sites spell the class name. Use find_references on `{class}`.\n"
939        );
940    }
941    let counts = &report.counts;
942    format!(
943        "Text: `{}` is on {} {}: {} {}, {} {}, {} {}, {} text only.\n",
944        report.target.name,
945        counts.text_lines,
946        plural(counts.text_lines, "line"),
947        counts.site_lines,
948        plural(counts.site_lines, "site"),
949        counts.definition_lines,
950        plural(counts.definition_lines, "definition"),
951        counts.import_lines,
952        plural(counts.import_lines, "import"),
953        counts.text_only_lines,
954    )
955}
956
957fn site_groups(sites: &[LabeledSite], limit: usize) -> String {
958    let mut out = String::new();
959    let mut listed = 0;
960    for label in SiteLabel::ALL {
961        let group: Vec<&LabeledSite> = sites.iter().filter(|site| site.label == label).collect();
962        if group.is_empty() {
963            continue;
964        }
965        let title = match label {
966            SiteLabel::Proven => "Proven",
967            SiteLabel::Likely => "Likely",
968            SiteLabel::Unresolved => "Unresolved",
969            SiteLabel::Excluded => "Excluded",
970        };
971        out.push_str(&format!("{title} ({}):\n", group.len()));
972        let shown = limit.saturating_sub(listed).min(group.len());
973        for labeled in &group[..shown] {
974            let site = &labeled.site;
975            let line = site.start_line.map(|l| format!(":{l}")).unwrap_or_default();
976            out.push_str(&format!(
977                "- {} [{}{line}] (kind: {}; {}{})\n",
978                caller_text(site),
979                site.path,
980                site.kind,
981                labeled.basis,
982                arg_count_text(labeled)
983            ));
984        }
985        listed += shown;
986        if shown < group.len() {
987            out.push_str(&fold_line(label, &group[shown..]));
988        }
989    }
990    out
991}
992
993/// `; 2 args` after the basis, left out when the basis already starts with the count.
994fn arg_count_text(labeled: &LabeledSite) -> String {
995    match labeled.arg_count {
996        Some(count) => {
997            let noun = if count == 1 { "arg" } else { "args" };
998            let text = format!("{count} {noun}");
999            if labeled.basis.starts_with(&text) {
1000                String::new()
1001            } else {
1002                format!("; {text}")
1003            }
1004        }
1005        None => String::new(),
1006    }
1007}
1008
1009fn fold_line(label: SiteLabel, hidden: &[&LabeledSite]) -> String {
1010    let (files, named) = files_by_count(hidden.iter().map(|labeled| labeled.site.path.as_str()));
1011    format!(
1012        "… {} more {} {} in {files} {}: {named}\n",
1013        hidden.len(),
1014        label.as_str(),
1015        plural(hidden.len(), "site"),
1016        plural(files, "file"),
1017    )
1018}
1019
1020/// How many files hold `paths`, and the first `FOLD_FILES_NAMED` of them as `path (count)`,
1021/// most rows first, with `, …` when more files follow.
1022fn files_by_count<'a>(paths: impl Iterator<Item = &'a str>) -> (usize, String) {
1023    let mut per_file: BTreeMap<&str, usize> = BTreeMap::new();
1024    for path in paths {
1025        *per_file.entry(path).or_default() += 1;
1026    }
1027    let mut files: Vec<(&str, usize)> = per_file.into_iter().collect();
1028    files.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(b.0)));
1029    let named: Vec<String> = files
1030        .iter()
1031        .take(FOLD_FILES_NAMED)
1032        .map(|(path, count)| format!("{path} ({count})"))
1033        .collect();
1034    let more = if files.len() > FOLD_FILES_NAMED {
1035        ", …"
1036    } else {
1037        ""
1038    };
1039    (files.len(), format!("{}{more}", named.join(", ")))
1040}
1041
1042fn override_sections(report: &ReferenceReport, limit: usize) -> String {
1043    let name = &report.target.display_name;
1044    let mut out = method_section(
1045        &format!(
1046            "Overrides ({}): calls through `{name}` can reach these",
1047            report.overrides.len()
1048        ),
1049        &report.overrides,
1050        limit,
1051    );
1052    out.push_str(&method_section(
1053        &format!(
1054            "Overrides of ({}): calls to these can reach `{name}`",
1055            report.overridden.len()
1056        ),
1057        &report.overridden,
1058        limit,
1059    ));
1060    out
1061}
1062
1063fn construction_section(rows: &[ConstructionSite], limit: usize) -> String {
1064    if rows.is_empty() {
1065        return String::new();
1066    }
1067    let shown = limit.min(rows.len());
1068    let mut per_file: Vec<(&str, Vec<String>)> = Vec::new();
1069    for row in &rows[..shown] {
1070        match per_file.last_mut() {
1071            Some((path, lines)) if *path == row.path => lines.push(row.line.to_string()),
1072            _ => per_file.push((&row.path, vec![row.line.to_string()])),
1073        }
1074    }
1075    let listed: Vec<String> = per_file
1076        .iter()
1077        .map(|(path, lines)| format!("{path}: {}", lines.join(", ")))
1078        .collect();
1079    let mut out = format!("Constructions ({}):", rows.len());
1080    if !listed.is_empty() {
1081        out.push_str(&format!(" {}", listed.join(" · ")));
1082    }
1083    out.push('\n');
1084    if shown < rows.len() {
1085        out.push_str(&section_fold(
1086            rows[shown..].iter().map(|row| row.path.as_str()),
1087            "construction",
1088        ));
1089    }
1090    out
1091}
1092
1093fn variant_section(rows: &[VariantUse], limit: usize) -> String {
1094    if rows.is_empty() {
1095        return String::new();
1096    }
1097    let mut out = format!(
1098        "Variant uses ({} {}): a match in them may need a new arm\n",
1099        rows.len(),
1100        plural(rows.len(), "function")
1101    );
1102    let shown = limit.min(rows.len());
1103    for row in &rows[..shown] {
1104        let caller = if row.caller.is_empty() {
1105            "(no enclosing symbol)".to_string()
1106        } else {
1107            format!("`{}`", row.caller)
1108        };
1109        out.push_str(&format!(
1110            "- {caller} [{}:{}] names {} of {} {}\n",
1111            row.path,
1112            row.line,
1113            row.variants_used,
1114            row.variants_total,
1115            plural(row.variants_total, "variant"),
1116        ));
1117    }
1118    if shown < rows.len() {
1119        out.push_str(&section_fold(
1120            rows[shown..].iter().map(|row| row.path.as_str()),
1121            "function",
1122        ));
1123    }
1124    out
1125}
1126
1127fn registration_section(rows: &[Registration], limit: usize) -> String {
1128    if rows.is_empty() {
1129        return String::new();
1130    }
1131    let mut out = format!("Registrations ({}):\n", rows.len());
1132    let shown = limit.min(rows.len());
1133    for row in &rows[..shown] {
1134        out.push_str(&format!(
1135            "- {} [{}:{}]{}\n",
1136            registration_label(row),
1137            row.path,
1138            row.line,
1139            if row.by_name { " (by name)" } else { "" }
1140        ));
1141    }
1142    if shown < rows.len() {
1143        out.push_str(&section_fold(
1144            rows[shown..].iter().map(|row| row.path.as_str()),
1145            "registration",
1146        ));
1147    }
1148    out
1149}
1150
1151fn registration_label(row: &Registration) -> String {
1152    if !row.pattern_id.contains(".route.") {
1153        return row.pattern_id.clone();
1154    }
1155    let template = row.template.as_deref().unwrap_or(&row.pattern_id);
1156    match row.verb.as_deref() {
1157        Some(verb) => format!("route {verb} {template}"),
1158        None => format!("route {template}"),
1159    }
1160}
1161
1162fn section_fold<'a>(hidden: impl ExactSizeIterator<Item = &'a str>, word: &str) -> String {
1163    let count = hidden.len();
1164    let (files, named) = files_by_count(hidden);
1165    format!(
1166        "… {count} more {} in {files} {}: {named}\n",
1167        plural(count, word),
1168        plural(files, "file"),
1169    )
1170}
1171
1172fn test_section(rows: &[CallingTest], limit: usize) -> String {
1173    if rows.is_empty() {
1174        return String::new();
1175    }
1176    let mut out = format!("Tests that call it ({}):\n", rows.len());
1177    let shown = limit.min(rows.len());
1178    for row in &rows[..shown] {
1179        let run = row
1180            .command
1181            .as_ref()
1182            .map(|command| format!(" run: {command}"))
1183            .unwrap_or_default();
1184        let name_only = if row.name_only { " (name only)" } else { "" };
1185        out.push_str(&format!(
1186            "- `{}` [{}:{}]{name_only}{run}\n",
1187            on_one_line(&row.name),
1188            row.path,
1189            row.line
1190        ));
1191    }
1192    if shown < rows.len() {
1193        out.push_str(&section_fold(
1194            rows[shown..].iter().map(|row| row.path.as_str()),
1195            "test",
1196        ));
1197    }
1198    out
1199}
1200
1201/// `text` with each control character and Unicode line separator written as an escape (`\n`,
1202/// `\t`), so a test name never breaks a line of the report.
1203fn on_one_line(text: &str) -> String {
1204    text.chars()
1205        .map(|c| {
1206            if c.is_control() || matches!(c, '\u{2028}' | '\u{2029}') {
1207                c.escape_default().to_string()
1208            } else {
1209                c.to_string()
1210            }
1211        })
1212        .collect()
1213}
1214
1215fn method_section(title: &str, rows: &[OverrideRow], limit: usize) -> String {
1216    if rows.is_empty() {
1217        return String::new();
1218    }
1219    let mut out = format!("{title}\n");
1220    let shown = limit.min(rows.len());
1221    for row in &rows[..shown] {
1222        out.push_str(&format!(
1223            "- `{}.{}` ({}:{})\n",
1224            row.owner, row.name, row.path, row.line
1225        ));
1226    }
1227    if shown < rows.len() {
1228        out.push_str(&section_fold(
1229            rows[shown..].iter().map(|row| row.path.as_str()),
1230            "method",
1231        ));
1232    }
1233    out
1234}
1235
1236fn text_only_section(report: &ReferenceReport) -> String {
1237    if report.text_only.is_empty() {
1238        return String::new();
1239    }
1240    let mut out = format!(
1241        "Text only ({}): docs, comments, strings, or code the index did not record\n",
1242        report.counts.text_only_lines
1243    );
1244    let mut hidden_lines = 0;
1245    let mut hidden_files = 0;
1246    for (index, file) in report.text_only.iter().enumerate() {
1247        let listed = if index < TEXT_ONLY_FILES_LISTED {
1248            file.lines.len().min(TEXT_ONLY_LINES_PER_FILE)
1249        } else {
1250            0
1251        };
1252        if listed > 0 {
1253            let lines: Vec<String> = file.lines[..listed].iter().map(usize::to_string).collect();
1254            out.push_str(&format!("  {}: {}\n", file.path, lines.join(", ")));
1255        }
1256        if listed < file.lines.len() {
1257            hidden_lines += file.lines.len() - listed;
1258            hidden_files += 1;
1259        }
1260    }
1261    if hidden_lines > 0 {
1262        out.push_str(&format!(
1263            "  … {hidden_lines} more {} in {hidden_files} {}\n",
1264            plural(hidden_lines, "line"),
1265            plural(hidden_files, "file")
1266        ));
1267    }
1268    out
1269}
1270
1271pub(crate) fn displayed_symbol_name(name: &str, enclosing_symbol_name: Option<&str>) -> String {
1272    if let Some(enclosing_symbol_name) = enclosing_symbol_name {
1273        format!("<lambda> in {enclosing_symbol_name}")
1274    } else {
1275        name.to_string()
1276    }
1277}
1278
1279/// Formats exact or FTS fallback symbol results with transparent header labeling.
1280/// One line for the lookup rows whose name only starts with or contains the query, shown when
1281/// some row is named exactly: each distinct name once, with its kind and count.
1282fn other_names_line(query: &str, others: &[&Symbol]) -> String {
1283    let mut groups: Vec<(String, &str, usize)> = Vec::new();
1284    for s in others {
1285        let kind = display_kind(s);
1286        match groups
1287            .iter_mut()
1288            .find(|(name, k, _)| *name == s.name && *k == kind)
1289        {
1290            Some(group) => group.2 += 1,
1291            None => groups.push((s.name.clone(), kind, 1)),
1292        }
1293    }
1294    let listed: Vec<String> = groups
1295        .iter()
1296        .take(8)
1297        .map(|(name, kind, count)| match count {
1298            1 => format!("`{name}` ({kind})"),
1299            n => format!("`{name}` ({kind}, {n}×)"),
1300        })
1301        .collect();
1302    let more = match groups.len().saturating_sub(8) {
1303        0 => String::new(),
1304        n => format!(", +{n} more"),
1305    };
1306    format!(
1307        "- {} other {} `{query}`, ignoring case: {}{more} (lookup_symbol with one of these names lists its rows)\n",
1308        others.len(),
1309        if others.len() == 1 {
1310            "row starts with or contains"
1311        } else {
1312            "rows start with or contain"
1313        },
1314        listed.join(", ")
1315    )
1316}
1317
1318/// A doc comment line without its comment marker (`///`, `/**`, ` * `, `#`, `--`) or a
1319/// `<summary>` tag, which julie keeps in the raw comment text.
1320fn doc_line_text(line: &str) -> &str {
1321    let mut text = line.trim();
1322    for marker in [
1323        "///", "//!", "//", "/**", "/*!", "/*", "##", "#'", "#", "--", "*", "'''", "'",
1324    ] {
1325        if let Some(rest) = text.strip_prefix(marker) {
1326            text = rest.trim_start();
1327            break;
1328        }
1329    }
1330    for tag in ["<summary>", "</summary>"] {
1331        text = text.strip_prefix(tag).unwrap_or(text).trim_start();
1332    }
1333    for suffix in ["*/", "</summary>"] {
1334        text = text.strip_suffix(suffix).unwrap_or(text).trim_end();
1335    }
1336    text
1337}
1338
1339/// The byte index of the period that ends the first sentence: a `. ` outside parentheses and not
1340/// before a lowercase word, so `(e.g. route)` and `e.g. route` do not end one.
1341fn sentence_end(text: &str) -> Option<usize> {
1342    let mut depth = 0usize;
1343    for (index, c) in text.char_indices() {
1344        match c {
1345            '(' => depth += 1,
1346            ')' => depth = depth.saturating_sub(1),
1347            '.' if depth == 0 => {
1348                let rest = &text[index + 1..];
1349                if rest.starts_with(' ') && !rest[1..].starts_with(|next: char| next.is_lowercase())
1350                {
1351                    return Some(index);
1352                }
1353            }
1354            _ => {}
1355        }
1356    }
1357    None
1358}
1359
1360/// The first sentence of a doc comment's first paragraph, on one line. A paragraph with no
1361/// sentence end is cut at 200 characters with `…`.
1362fn doc_summary(doc: &str) -> Option<String> {
1363    let paragraph = doc
1364        .lines()
1365        .map(doc_line_text)
1366        .skip_while(|line| line.is_empty())
1367        .take_while(|line| !line.is_empty())
1368        .collect::<Vec<_>>()
1369        .join(" ");
1370    let summary = match sentence_end(&paragraph) {
1371        Some(end) => paragraph[..=end].to_string(),
1372        None if paragraph.chars().count() > 200 => {
1373            format!("{}…", paragraph.chars().take(200).collect::<String>())
1374        }
1375        None => paragraph,
1376    };
1377    (!summary.is_empty()).then_some(summary)
1378}
1379
1380pub fn format_find_symbol_results(
1381    query: &str,
1382    name_rows: &[Symbol],
1383    ranked_rows: &[SymbolSearchResult],
1384    limit: usize,
1385) -> String {
1386    let mut out = String::new();
1387    if !name_rows.is_empty() {
1388        out.push_str(&format_name_rows(query, name_rows, limit));
1389    }
1390    if !ranked_rows.is_empty() {
1391        if !out.is_empty() {
1392            out.push('\n');
1393        }
1394        out.push_str(&format_ranked_rows(query, ranked_rows, limit));
1395    }
1396    if out.is_empty() {
1397        out.push_str(&format!("No symbols found matching \"{query}\".\n"));
1398    }
1399    out
1400}
1401
1402fn format_name_rows(query: &str, exact_matches: &[Symbol], limit: usize) -> String {
1403    let dotted = query.replace("::", ".");
1404    let is_exact = |s: &Symbol| s.name == dotted || s.name.ends_with(&format!(".{dotted}"));
1405    let named_exactly = exact_matches.iter().filter(|s| is_exact(s)).count();
1406    let exact_note = if named_exactly < exact_matches.len() {
1407        format!(" ({named_exactly} named exactly `{query}`; the rest start with or contain it)")
1408    } else {
1409        String::new()
1410    };
1411    let owner = query
1412        .strip_suffix("::")
1413        .or_else(|| query.strip_suffix('.'))
1414        .filter(|owner| !owner.is_empty());
1415    let mut out = match owner {
1416        Some(owner) => format!("Found {} members of `{owner}`:\n\n", exact_matches.len()),
1417        None => format!(
1418            "Found {} symbols matching \"{query}\"{exact_note}:\n\n",
1419            exact_matches.len()
1420        ),
1421    };
1422    let has_definition = exact_matches.iter().any(|s| s.kind != "import");
1423    let folds = |s: &Symbol| crate::queries::folds_into_import_line(query, s, has_definition);
1424    let imports: Vec<&Symbol> = exact_matches.iter().filter(|s| folds(s)).collect();
1425    let (shown, others): (Vec<&Symbol>, Vec<&Symbol>) = exact_matches
1426        .iter()
1427        .filter(|s| !folds(s))
1428        .partition(|s| named_exactly == 0 || is_exact(s));
1429    for s in shown {
1430        let sig = s.signature.as_deref().unwrap_or(&s.name);
1431        out.push_str(&format!(
1432            "- {} `{}` [{}:{}-{}] id={}\n",
1433            display_kind(s),
1434            s.name,
1435            s.path,
1436            s.start_line,
1437            s.end_line,
1438            s.symbol_id
1439        ));
1440        out.push_str(&format!("  Signature: {sig}\n"));
1441        if let Some(doc) = s.doc_comment.as_deref().and_then(doc_summary) {
1442            out.push_str(&format!("  Doc: {doc}\n"));
1443        }
1444    }
1445    if !imports.is_empty() {
1446        let shown = imports
1447            .iter()
1448            .take(3)
1449            .map(|s| format!("{}:{}", s.path, s.start_line))
1450            .collect::<Vec<_>>()
1451            .join(", ");
1452        let more = if imports.len() > 3 { ", …" } else { "" };
1453        let cut_inside_exact_names = exact_matches
1454            .last()
1455            .is_some_and(|s| s.name.eq_ignore_ascii_case(query) || folds(s));
1456        let capped = if exact_matches.len() - imports.len() >= limit && cut_inside_exact_names {
1457            "at least "
1458        } else {
1459            ""
1460        };
1461        out.push_str(&format!(
1462            "- {capped}{} {} of `{query}`: {shown}{more} (lookup_symbol with kind=\"import\" lists them)\n",
1463            imports.len(),
1464            plural(imports.len(), "import")
1465        ));
1466    }
1467    if !others.is_empty() {
1468        out.push_str(&other_names_line(query, &others));
1469    }
1470    if exact_matches.len() - imports.len() >= limit {
1471        out.push_str(&cap_notice(exact_matches.len() - imports.len(), limit));
1472    }
1473    out
1474}
1475
1476fn format_ranked_rows(query: &str, fts_matches: &[SymbolSearchResult], limit: usize) -> String {
1477    let mut out = format!(
1478        "No exact name match; {} full-text matches for \"{query}\":\n\n",
1479        fts_matches.len()
1480    );
1481    for r in fts_matches {
1482        let s = &r.symbol;
1483        let sig = s.signature.as_deref().unwrap_or(&s.name);
1484        out.push_str(&format!(
1485            "- {} `{}` [{}:{}-{}] (score: {:.2}) id={}\n",
1486            display_kind(s),
1487            s.name,
1488            s.path,
1489            s.start_line,
1490            s.end_line,
1491            r.score,
1492            s.symbol_id
1493        ));
1494        out.push_str(&format!("  Signature: {sig}\n"));
1495        if let Some(line) = r.snippet.as_deref().and_then(|m| match_line(m, sig)) {
1496            out.push_str(&format!("  Match: {line}\n"));
1497        } else if let Some(doc) = s.doc_comment.as_deref().and_then(doc_summary) {
1498            out.push_str(&format!("  Doc: {doc}\n"));
1499        }
1500    }
1501    if fts_matches.len() >= limit {
1502        out.push_str(&cap_notice(fts_matches.len(), limit));
1503    }
1504    out
1505}
1506
1507/// Format available structural fact & literal categories.
1508/// The first line of a fact query that matched nothing; it names the path the query was limited to.
1509pub fn no_facts_heading(category: &str, path_filter: Option<&str>) -> String {
1510    match path_filter {
1511        Some(path) => format!("No facts match '{category}' under `{path}`."),
1512        None => format!("No facts match '{category}' in this repository."),
1513    }
1514}
1515
1516/// The answer when a category matches no fact. A known alias gets only the alias summary, and
1517/// `import` says where imports are, because most extractors record imports as symbols. Any other
1518/// category lists every raw category, so the agent can pick one.
1519pub fn format_no_facts(
1520    category: &str,
1521    path_filter: Option<&str>,
1522    categories: &[(String, usize)],
1523) -> String {
1524    let mut out = format!("{}\n\n", no_facts_heading(category, path_filter));
1525    if !crate::queries::is_category_alias(category) {
1526        out.push_str(&format_fact_categories(categories));
1527        return out;
1528    }
1529    if matches!(category.to_ascii_lowercase().as_str(), "import" | "imports") {
1530        out.push_str("Most languages record imports as symbols: lookup_symbol with kind=\"import\" lists them.\n\n");
1531    }
1532    out.push_str(&alias_summary(categories));
1533    out
1534}
1535
1536fn alias_summary(categories: &[(String, usize)]) -> String {
1537    let aliases = crate::queries::alias_fact_counts(categories);
1538    if aliases.is_empty() {
1539        return String::new();
1540    }
1541    let parts: Vec<String> = aliases
1542        .iter()
1543        .map(|(alias, patterns, facts)| {
1544            format!(
1545                "{alias} ({patterns} {}, {facts} {})",
1546                plural(*patterns, "pattern"),
1547                plural(*facts, "fact")
1548            )
1549        })
1550        .collect();
1551    format!("Aliases: {}\n\n", parts.join(", "))
1552}
1553
1554pub fn format_fact_categories(categories: &[(String, usize)]) -> String {
1555    if categories.is_empty() {
1556        return "No structural facts or literals indexed in this repository.".to_string();
1557    }
1558    let mut out = String::new();
1559    out.push_str(&alias_summary(categories));
1560    // A decorated-definition fact only records where a decorated block starts.
1561    let (patterns, literal_kinds): (Vec<_>, Vec<_>) = categories
1562        .iter()
1563        .filter(|(name, _)| !name.ends_with(".decorated_definition.v1"))
1564        .partition(|(name, _)| name.contains('.'));
1565    out.push_str(&format!(
1566        "Available structural fact categories ({} found):\n\n",
1567        patterns.len()
1568    ));
1569    for (name, count) in &patterns {
1570        out.push_str(&format!(
1571            "- `{name}` ({count} {})\n",
1572            plural(*count, "fact")
1573        ));
1574    }
1575    if !literal_kinds.is_empty() {
1576        out.push_str("\nString literal kinds (the same command lists the literals of a kind):\n\n");
1577        for (name, count) in &literal_kinds {
1578            out.push_str(&format!(
1579                "- `{name}` ({count} {})\n",
1580                plural(*count, "literal")
1581            ));
1582        }
1583    }
1584    out
1585}
1586
1587fn plural(count: usize, word: &str) -> String {
1588    if count == 1 {
1589        word.to_string()
1590    } else {
1591        format!("{word}s")
1592    }
1593}
1594
1595/// Format structural facts and matching literals into token-dense markdown.
1596pub fn format_structural_facts(
1597    facts: &[crate::models::StructuralFact],
1598    literals: &[crate::models::LiteralFact],
1599    category: &str,
1600    limit: usize,
1601) -> String {
1602    let mut out = format!(
1603        "Structural facts for '{category}' ({} found):\n",
1604        facts.len()
1605    );
1606    for f in facts {
1607        let label = f.key.as_deref().unwrap_or(&f.capture_name);
1608        let details = format!("{}{}", qt_property_details(f), flask_route_details(f));
1609        let api_style = f
1610            .metadata
1611            .as_ref()
1612            .and_then(|m| m.get("api_style"))
1613            .and_then(|v| v.as_str());
1614        let place = match api_style {
1615            Some("decorator_routing") => "handler",
1616            Some("call_routing") => "registered in",
1617            _ => "in",
1618        };
1619        let parent = f
1620            .containing_symbol_name
1621            .as_deref()
1622            .map(|p| format!(", {place}: {p}"))
1623            .unwrap_or_default();
1624        out.push_str(&format!(
1625            "- {label} [{}:{}] (pattern: {}{details}{parent})\n",
1626            f.path, f.start_line, f.pattern_id
1627        ));
1628    }
1629    if limit > 0 && facts.len() >= limit {
1630        out.push_str(&cap_notice(facts.len(), limit));
1631    }
1632    if facts
1633        .iter()
1634        .any(|f| f.pattern_id.starts_with("flask.route"))
1635    {
1636        out.push_str("Routes as declared in the source. By default Flask also answers HEAD for GET and OPTIONS for every rule, and serves `/static/<path:filename>`; the app or a rule can turn these off.\n");
1637    }
1638    if !literals.is_empty() {
1639        out.push_str(&format!(
1640            "\nMatching literals ({} found):\n",
1641            literals.len()
1642        ));
1643        for l in literals {
1644            out.push_str(&format!(
1645                "- \"{}\" [{}:{}] (kind: {})\n",
1646                l.literal_text, l.path, l.start_line, l.kind
1647            ));
1648        }
1649        if limit > 0 && literals.len() >= limit {
1650            out.push_str(&cap_notice(literals.len(), limit));
1651        }
1652    }
1653    out
1654}
1655
1656/// The endpoint of a Flask route and the view of an `add_url_rule` call. A rule with no view, such
1657/// as `add_url_rule("/", endpoint="index")`, only names an endpoint for `url_for`.
1658fn flask_route_details(fact: &crate::models::StructuralFact) -> String {
1659    if !fact.pattern_id.starts_with("flask.route") {
1660        return String::new();
1661    }
1662    let Some(metadata) = fact.metadata.as_ref() else {
1663        return String::new();
1664    };
1665    let text = |key: &str| metadata.get(key).and_then(|v| v.as_str());
1666    let mut out = String::new();
1667    if let Some(endpoint) = text("endpoint") {
1668        out.push_str(&format!(", endpoint: {endpoint}"));
1669    }
1670    if text("api_style") == Some("call_routing") {
1671        match text("view_target") {
1672            Some(view) => out.push_str(&format!(", view: {view}")),
1673            None => out.push_str(", no view function"),
1674        }
1675    }
1676    out
1677}
1678
1679fn qt_property_details(fact: &crate::models::StructuralFact) -> String {
1680    if fact.pattern_id != "cpp.qt_property.v1" {
1681        return String::new();
1682    }
1683    let Some(metadata) = fact.metadata.as_ref() else {
1684        return String::new();
1685    };
1686    [
1687        "property_type",
1688        "read",
1689        "write",
1690        "notify",
1691        "designable",
1692        "scriptable",
1693        "stored",
1694        "user",
1695        "revision",
1696    ]
1697    .into_iter()
1698    .filter_map(|key| metadata.get(key).map(|value| (key, value)))
1699    .map(|(key, value)| {
1700        let value = value
1701            .as_str()
1702            .map(str::to_owned)
1703            .unwrap_or_else(|| value.to_string());
1704        format!(", {key}: {value}")
1705    })
1706    .collect()
1707}
1708
1709/// Formats FTS5 conceptual search results into token-dense markdown.
1710pub fn format_search_results(query: &str, results: &[SymbolSearchResult], limit: usize) -> String {
1711    if results.is_empty() {
1712        return format!("No symbols found matching concept \"{query}\".");
1713    }
1714
1715    let mut out = format!(
1716        "Found {} symbols matching concept \"{query}\":\n",
1717        results.len()
1718    );
1719    if let Some(explain) = results.first().and_then(|r| r.explain.as_ref()) {
1720        out.push_str(&format!(
1721            "rerank: {} candidates in {} µs",
1722            explain.candidates, explain.rerank_us
1723        ));
1724        if !explain.word_weights.is_empty() {
1725            let words: Vec<String> = explain
1726                .word_weights
1727                .iter()
1728                .map(|(word, weight)| format!("{word} {weight:.2}"))
1729                .collect();
1730            out.push_str(&format!("; words {}", words.join(", ")));
1731        }
1732        out.push('\n');
1733    }
1734    out.push('\n');
1735    for r in results {
1736        let s = &r.symbol;
1737        let sig = s.signature.as_deref().unwrap_or(&s.name);
1738        out.push_str(&format!(
1739            "- {} `{}` [{}:{}-{}] (score: {:.2}) id={}\n",
1740            display_kind(s),
1741            s.name,
1742            s.path,
1743            s.start_line,
1744            s.end_line,
1745            r.score,
1746            s.symbol_id
1747        ));
1748        out.push_str(&format!("  Signature: {sig}\n"));
1749        if let Some(line) = r.snippet.as_deref().and_then(|m| match_line(m, sig)) {
1750            out.push_str(&format!("  Match: {line}\n"));
1751        } else if let Some(doc) = s.doc_comment.as_deref().and_then(doc_summary) {
1752            out.push_str(&format!("  Doc: {doc}\n"));
1753        }
1754        if let Some(explain) = &r.explain {
1755            out.push_str(&format!("  explain: {}\n", explain_line(r.score, explain)));
1756        }
1757    }
1758
1759    if results.len() >= limit {
1760        out.push_str(&cap_notice(results.len(), limit));
1761    }
1762
1763    out
1764}
1765
1766fn explain_line(score: f64, e: &SearchExplain) -> String {
1767    let mut line = format!(
1768        "score {score:.1} = terms {:.1} + name {}({}) {:.1} + kind {:.1} + path {:.1}",
1769        e.term_score, e.name_tier, e.name_strength, e.name_bonus, e.kind_prior, e.path_role,
1770    );
1771    if e.field_diversity_bonus != 0.0 {
1772        line.push_str(&format!(" + field coverage {:.1}", e.field_diversity_bonus));
1773    }
1774    if e.documentation != 0.0 {
1775        line.push_str(&format!(" + doc {:.1}", e.documentation));
1776    }
1777    if e.test_intent != 0.0 {
1778        line.push_str(&format!(" + test {:.1}", e.test_intent));
1779    }
1780    if e.nested != 0.0 {
1781        line.push_str(&format!(" + nested {:.1}", e.nested));
1782    }
1783    line.push_str(&format!(" [{}]", e.branches.join(",")));
1784    if let Some(bm25) = e.bm25 {
1785        line.push_str(&format!(" bm25 {bm25:.2}"));
1786    }
1787    if !e.terms.is_empty() {
1788        let terms: Vec<String> = e
1789            .terms
1790            .iter()
1791            .map(|(term, field, credit)| format!("{term}={field}:{credit}"))
1792            .collect();
1793        line.push_str(&format!(" terms {}", terms.join(" ")));
1794    }
1795    line
1796}
1797
1798const EDIT_SITES_LISTED: usize = 12;
1799const EDIT_TESTS_LISTED: usize = 8;
1800const STOP_SITES_LISTED: usize = 15;
1801
1802/// The post-edit answer: the base, each symbol whose shape changed with its sites split by
1803/// whether the diff reached them, the tests to run, and the blind spots of the index.
1804pub fn format_edit_check(check: &EditCheck) -> String {
1805    let source = match check.source {
1806        BaseSource::Given => "given",
1807        BaseSource::Session => "session base",
1808        BaseSource::Head => "HEAD",
1809    };
1810    let mut out = String::new();
1811    if check.changes.is_empty() {
1812        out.push_str(&format!(
1813            "check_edit: working tree against {} ({source}): no symbol changed shape.\n",
1814            check.rev
1815        ));
1816        push_edit_cuts(&mut out, check);
1817        return out;
1818    }
1819    out.push_str(&format!(
1820        "check_edit: working tree against {} ({source}), {} {} changed\n{} shape {}:\n",
1821        check.rev,
1822        check.files_changed,
1823        plural(check.files_changed, "file"),
1824        check.changes.len(),
1825        plural(check.changes.len(), "change"),
1826    ));
1827    for change in &check.changes {
1828        push_shape_change(&mut out, change);
1829    }
1830    push_edit_cuts(&mut out, check);
1831    if !check.tests.is_empty() {
1832        let shown = check.tests.len().min(EDIT_TESTS_LISTED);
1833        out.push_str(&format!(
1834            "Tests to run: {}",
1835            check.tests[..shown].join("; ")
1836        ));
1837        if shown < check.tests.len() {
1838            out.push_str(&format!("; … {} more", check.tests.len() - shown));
1839        }
1840        out.push('\n');
1841    }
1842    out.push_str("Not checked: calls inside macro arguments, functions passed as values.\n");
1843    out
1844}
1845
1846/// The reason a Stop hook gives for a check: how many `proven` sites outside the diff still use
1847/// the old shape of which symbols, then the first of them. `None` when no change that
1848/// [`blocks_a_stop`] has such a site.
1849pub fn format_stop_reason(check: &EditCheck) -> Option<String> {
1850    let mut rows: Vec<(&EditSite, &ShapeChange)> = Vec::new();
1851    for change in check.changes.iter().filter(|change| blocks_a_stop(change)) {
1852        rows.extend(change.proven.iter().map(|site| (site, change)));
1853    }
1854    if rows.is_empty() {
1855        return None;
1856    }
1857    rows.sort_by(|a, b| {
1858        (&a.0.path, a.0.line, &a.1.display).cmp(&(&b.0.path, b.0.line, &b.1.display))
1859    });
1860    let mut names: Vec<String> = Vec::new();
1861    for (_, change) in &rows {
1862        let name = format!("`{}`", change.display);
1863        if !names.contains(&name) {
1864            names.push(name);
1865        }
1866    }
1867    let mut out = format!(
1868        "Before you finish: {} sites still use the old shape of {}.\n",
1869        rows.len(),
1870        names.join(", ")
1871    );
1872    for (site, change) in rows.iter().take(STOP_SITES_LISTED) {
1873        out.push_str(&format!(
1874            "{}:{}  {}: {}\n",
1875            site.path, site.line, change.display, change.change
1876        ));
1877    }
1878    out.push_str("Edit them or say why they need no change.");
1879    Some(out)
1880}
1881
1882/// A `signature changed` row is often a type change that every call still fits (a nullable
1883/// `?`, a type alias, a return type), and JavaScript ignores the argument count. On clean
1884/// commits of real projects both blocked stops that needed no edit, so neither blocks a stop.
1885fn blocks_a_stop(change: &ShapeChange) -> bool {
1886    let javascript = [".js", ".jsx", ".mjs", ".cjs"]
1887        .iter()
1888        .any(|extension| change.path.ends_with(extension));
1889    !change.change.starts_with("signature changed")
1890        && !(javascript && change.change.starts_with("parameters"))
1891}
1892
1893fn push_edit_cuts(out: &mut String, check: &EditCheck) {
1894    for cut in &check.cuts {
1895        out.push_str(&format!("Cut: {cut}\n"));
1896    }
1897}
1898
1899fn push_shape_change(out: &mut String, change: &ShapeChange) {
1900    out.push_str(&format!(
1901        "  {} `{}` ({}): {}\n",
1902        change.kind, change.display, change.path, change.change
1903    ));
1904    if !change.in_diff.is_empty() {
1905        let shown = change.in_diff.len().min(EDIT_SITES_LISTED);
1906        let places: Vec<String> = change.in_diff[..shown]
1907            .iter()
1908            .map(|site| format!("{}:{}", site.path, site.line))
1909            .collect();
1910        out.push_str(&format!(
1911            "    In your diff ({}): {}",
1912            change.in_diff.len(),
1913            places.join(", ")
1914        ));
1915        if shown < change.in_diff.len() {
1916            out.push_str(&format!(", … {} more", change.in_diff.len() - shown));
1917        }
1918        out.push('\n');
1919    }
1920    for (label, sites) in [("proven", &change.proven), ("likely", &change.likely)] {
1921        if sites.is_empty() {
1922            continue;
1923        }
1924        out.push_str(&format!(
1925            "    Not in your diff, {label} ({}):\n",
1926            sites.len()
1927        ));
1928        for site in &sites[..sites.len().min(EDIT_SITES_LISTED)] {
1929            out.push_str(&edit_site_row(site));
1930        }
1931        if sites.len() > EDIT_SITES_LISTED {
1932            out.push_str(&format!(
1933                "      … {} more {label}\n",
1934                sites.len() - EDIT_SITES_LISTED
1935            ));
1936        }
1937    }
1938    if change.unresolved > 0 {
1939        out.push_str(&format!(
1940            "    Unresolved outside the diff: {}\n",
1941            change.unresolved
1942        ));
1943    }
1944}
1945
1946fn edit_site_row(site: &EditSite) -> String {
1947    let caller = if site.caller.is_empty() {
1948        "(no enclosing symbol)".to_string()
1949    } else {
1950        format!("`{}`", site.caller)
1951    };
1952    let note = site
1953        .note
1954        .as_deref()
1955        .map(|note| format!("  {note}"))
1956        .unwrap_or_default();
1957    format!("      {}:{}  {caller}{note}\n", site.path, site.line)
1958}
1959
1960/// Format blast radius and likely test targets into token-dense markdown.
1961pub fn format_blast_radius(result: &BlastRadiusResult) -> String {
1962    if result.seed_type == "none" {
1963        return "No uncommitted changes detected in git working tree. Pass a 'symbol' or 'file' parameter to analyze blast radius.".to_string();
1964    }
1965
1966    let mut out = String::new();
1967    let seed_label = if result.seed_type == "file" {
1968        format!("Files: {}", result.seeds.join(", "))
1969    } else if result.seed_type == "symbol" {
1970        format!("Symbol: {}", result.seeds.join(", "))
1971    } else {
1972        format!("Seeds: {}", result.seeds.join(", "))
1973    };
1974
1975    out.push_str(&format!("## Blast Radius & Test Impact ({seed_label})\n\n"));
1976
1977    let more = if result.limit_at_maximum {
1978        "limit is at its maximum, so narrow the target to a symbol or fewer files"
1979    } else {
1980        "raise limit to see the rest"
1981    };
1982    let shown_of = |shown: usize, found: usize, noun: &str| {
1983        if found > shown {
1984            format!("Showing {shown} of {found} {noun}; {more}.\n\n")
1985        } else {
1986            format!("Requested limit hid additional {noun}; {more}.\n\n")
1987        }
1988    };
1989    if result.likely_tests_truncated {
1990        out.push_str(&shown_of(
1991            result.likely_tests.len(),
1992            result.likely_tests_found,
1993            "likely tests",
1994        ));
1995    }
1996    if result.impacted_symbols_truncated {
1997        out.push_str(&shown_of(
1998            result.impacted_symbols.len(),
1999            result.impacted_symbols_found,
2000            "impacted symbols",
2001        ));
2002    }
2003    if result.traversal_ceiling_reached {
2004        out.push_str("Traversal stopped at the 200-row discovery ceiling; narrow the target because increasing limit cannot raise this ceiling.\n\n");
2005    }
2006
2007    if !result.likely_tests.is_empty() {
2008        let total = result.likely_tests.len();
2009        out.push_str(&format!("### Likely Tests to Run ({} returned)\n", total));
2010
2011        // Preserve ranked row order; collecting every row by file can put lower-ranked tests first.
2012        let mut previous_path = None;
2013        for t in &result.likely_tests {
2014            if previous_path != Some(t.path.as_str()) {
2015                out.push_str(&format!("{}:\n", t.path));
2016                previous_path = Some(t.path.as_str());
2017            }
2018            out.push_str(&format!(
2019                "  - `{}` [line {}] ({})\n",
2020                t.name, t.line, t.reason
2021            ));
2022        }
2023
2024        out.push('\n');
2025    } else if result.likely_tests_truncated || result.traversal_ceiling_reached {
2026        out.push_str("### Likely Tests to Run (0 returned)\n\n");
2027    } else if let Some(depth) = result.stopped_at_depth {
2028        out.push_str(&format!(
2029            "### Likely Tests to Run (0 returned)\nNo test reaches it within depth {depth}; a larger `depth` may find some. Otherwise run the full test suite.\n\n",
2030        ));
2031    } else {
2032        out.push_str(
2033            "### Likely Tests to Run (0 returned)\nNo test reaches it through the index. Run the full test suite.\n\n",
2034        );
2035    }
2036
2037    if !result.impacted_symbols.is_empty() {
2038        let total = result.impacted_symbols.len();
2039        let mut visible = Vec::new();
2040        let mut low_signal_count = 0;
2041        for s in &result.impacted_symbols {
2042            if matches!(s.kind.as_str(), "import" | "module" | "namespace") {
2043                low_signal_count += 1;
2044            } else {
2045                visible.push(s);
2046            }
2047        }
2048
2049        out.push_str(&format!("### Downstream Impact ({} returned)\n", total));
2050
2051        if visible.is_empty() && low_signal_count > 0 {
2052            let row_word = if low_signal_count == 1 {
2053                "row (import/module)"
2054            } else {
2055                "rows (imports/modules)"
2056            };
2057            out.push_str(&format!(
2058                "All impacted symbols are imports/modules; {low_signal_count} low-signal {row_word} hidden; available in CLI --json.\n"
2059            ));
2060        } else {
2061            let mut syms_by_file: std::collections::BTreeMap<&str, Vec<&ImpactedSymbol>> =
2062                std::collections::BTreeMap::new();
2063            let mut file_order = Vec::new();
2064            for s in &visible {
2065                if !syms_by_file.contains_key(s.path.as_str()) {
2066                    file_order.push(s.path.as_str());
2067                }
2068                syms_by_file.entry(s.path.as_str()).or_default().push(s);
2069            }
2070
2071            for path in file_order {
2072                out.push_str(&format!("{path}:\n"));
2073                if let Some(syms) = syms_by_file.get(path) {
2074                    for s in syms {
2075                        let name =
2076                            displayed_symbol_name(&s.name, s.enclosing_symbol_name.as_deref());
2077                        out.push_str(&format!(
2078                            "  - [depth {}] {} `{}` [line {}]\n",
2079                            s.depth, s.kind, name, s.line
2080                        ));
2081                    }
2082                }
2083            }
2084
2085            if low_signal_count > 0 {
2086                let row_word = if low_signal_count == 1 {
2087                    "row (import/module)"
2088                } else {
2089                    "rows (imports/modules)"
2090                };
2091                out.push_str(&format!(
2092                    "... {low_signal_count} low-signal {row_word} hidden; available in CLI --json.\n"
2093                ));
2094            }
2095        }
2096    } else if result.impacted_symbols_truncated || result.traversal_ceiling_reached {
2097        out.push_str("### Downstream Impact (0 returned)\n");
2098    } else {
2099        out.push_str(
2100            "### Downstream Impact (0 returned)\nNo downstream callers found within depth.\n",
2101        );
2102    }
2103
2104    out
2105}
2106
2107#[cfg(test)]
2108mod tests {
2109    use super::*;
2110    use crate::models::{
2111        ImpactedSymbol, LabeledSite, ReferenceCounts, ReferenceReport, ReferenceTarget, SiteLabel,
2112        TestTarget, TextOnlyLines, TextScanSummary,
2113    };
2114
2115    fn structural_fact(key: Option<&str>) -> crate::models::StructuralFact {
2116        crate::models::StructuralFact {
2117            structural_fact_id: "sf1".into(),
2118            path: ".codex/config.toml".into(),
2119            language: "toml".into(),
2120            pattern_id: "toml.key_value.v1".into(),
2121            capture_name: "key_value".into(),
2122            node_kind: "table".into(),
2123            key: key.map(str::to_string),
2124            metadata: None,
2125            containing_symbol_name: None,
2126            start_line: 2,
2127            end_line: 2,
2128            confidence: 1.0,
2129        }
2130    }
2131
2132    #[test]
2133    fn format_structural_facts_prints_key_and_falls_back_to_capture_name() {
2134        let with_key = format_structural_facts(
2135            &[structural_fact(Some("mcp_servers.code-kb.command"))],
2136            &[],
2137            "config",
2138            30,
2139        );
2140        assert!(with_key.contains(
2141            "- mcp_servers.code-kb.command [.codex/config.toml:2] (pattern: toml.key_value.v1)"
2142        ));
2143
2144        let without_key = format_structural_facts(&[structural_fact(None)], &[], "config", 30);
2145        assert!(
2146            without_key.contains("- key_value [.codex/config.toml:2] (pattern: toml.key_value.v1)")
2147        );
2148    }
2149
2150    #[test]
2151    fn format_structural_facts_renders_selected_qt_property_metadata() {
2152        let mut fact = structural_fact(Some("index"));
2153        fact.pattern_id = "cpp.qt_property.v1".into();
2154        fact.metadata = Some(serde_json::json!({
2155            "property_type": "int",
2156            "designable": false,
2157            "scriptable": true,
2158            "stored": false,
2159            "user": true,
2160            "revision": 2,
2161        }));
2162
2163        let output = format_structural_facts(&[fact], &[], "property", 30);
2164
2165        assert!(output.contains(
2166            "property_type: int, designable: false, scriptable: true, stored: false, user: true, revision: 2"
2167        ));
2168    }
2169
2170    #[test]
2171    fn format_structural_facts_names_the_endpoint_and_view_of_a_flask_route() {
2172        let route = |metadata| crate::models::StructuralFact {
2173            pattern_id: "flask.route.v1".into(),
2174            metadata: Some(metadata),
2175            ..structural_fact(Some("GET /"))
2176        };
2177        let alias = route(serde_json::json!({"api_style": "call_routing", "endpoint": "index"}));
2178        let rule = route(serde_json::json!({"api_style": "call_routing", "view_target": "ping"}));
2179        let decorated = route(serde_json::json!({"api_style": "decorator_routing"}));
2180
2181        let output = format_structural_facts(&[alias, rule, decorated], &[], "route", 30);
2182
2183        assert!(
2184            output.contains("(pattern: flask.route.v1, endpoint: index, no view function)"),
2185            "{output}"
2186        );
2187        assert!(
2188            output.contains("(pattern: flask.route.v1, view: ping)"),
2189            "{output}"
2190        );
2191        assert!(output.contains("(pattern: flask.route.v1)"), "{output}");
2192    }
2193
2194    #[test]
2195    fn doc_summary_ends_at_the_first_sentence_of_the_first_paragraph() {
2196        assert_eq!(
2197            doc_summary(
2198                "The actual WSGI application. This is not implemented in\n:meth:`__call__`."
2199            )
2200            .as_deref(),
2201            Some("The actual WSGI application.")
2202        );
2203        assert_eq!(
2204            doc_summary("\nCreate a runner\nfor tests\n\nMore.").as_deref(),
2205            Some("Create a runner for tests")
2206        );
2207        assert_eq!(
2208            doc_summary("Find facts by category (e.g. route, query). More.").as_deref(),
2209            Some("Find facts by category (e.g. route, query).")
2210        );
2211        assert_eq!(
2212            doc_summary("Use a name, e.g. foo. Then more.").as_deref(),
2213            Some("Use a name, e.g. foo.")
2214        );
2215        assert_eq!(
2216            doc_summary("/// <summary>\n/// Goes to previous page.\n/// </summary>").as_deref(),
2217            Some("Goes to previous page.")
2218        );
2219        assert_eq!(
2220            doc_summary("/**\n * Render the view.\n *\n * @param x\n */").as_deref(),
2221            Some("Render the view.")
2222        );
2223        assert_eq!(
2224            doc_summary("# Given a +hash+ returns the settings\n# for the environment.").as_deref(),
2225            Some("Given a +hash+ returns the settings for the environment.")
2226        );
2227        assert_eq!(
2228            doc_summary("#' A person record.").as_deref(),
2229            Some("A person record.")
2230        );
2231        assert_eq!(doc_summary("  \n"), None);
2232        assert!(doc_summary(&"word ".repeat(60)).unwrap().ends_with('…'));
2233    }
2234
2235    #[test]
2236    fn format_references_reports_the_occurrence_count_of_a_grouped_row() {
2237        let site = |occurrences| ReferenceSite {
2238            from_symbol_name: "Button".into(),
2239            from_symbol_id: "s1".into(),
2240            to_symbol_name: "background".into(),
2241            kind: "member_access".into(),
2242            path: "Ui/Button.qml".into(),
2243            start_line: Some(5),
2244            start_column: Some(4),
2245            occurrences,
2246            target: None,
2247            enclosing_symbol_name: None,
2248        };
2249
2250        let grouped = format_references("Color", &[site(Some(6))], "callers", 30);
2251        assert!(
2252            grouped.contains("- `Button` [Ui/Button.qml:5] (kind: member_access, 6 in file)"),
2253            "{grouped}"
2254        );
2255
2256        let single = format_references("Color", &[site(None)], "callers", 30);
2257        assert!(
2258            single.contains("- `Button` [Ui/Button.qml:5] (kind: member_access)"),
2259            "{single}"
2260        );
2261    }
2262
2263    #[test]
2264    fn a_match_snippet_joins_its_lines_and_is_dropped_when_it_repeats_the_signature() {
2265        assert_eq!(
2266            match_line("...path up to\n the [root] (the [root] excluded)", "fn f()"),
2267            Some("...path up to the [root] (the [root] excluded)".into())
2268        );
2269        assert_eq!(
2270            match_line("// [HelpFunc] returns the\n// [function] set", "fn f()"),
2271            Some("// [HelpFunc] returns the [function] set".into())
2272        );
2273        assert_eq!(
2274            match_line(
2275                "fn [index]_facts(workspace_[root]: &Path) -> Option<[IndexFacts]>",
2276                "fn index_facts(workspace_root: &Path) -> Option<IndexFacts>"
2277            ),
2278            None
2279        );
2280        assert_eq!(
2281            match_line(
2282                "...[root]: &[PathBuf]) -> bool",
2283                "fn f(root: &[PathBuf]) -> bool"
2284            ),
2285            None
2286        );
2287    }
2288
2289    #[test]
2290    fn a_long_unresolved_call_chain_shows_only_its_last_call() {
2291        assert_eq!(
2292            callee_name(
2293                "[\"a\", \"b\"]\n    .into_iter()\n    .find_map(|key| args.get(key)).ok_or_else"
2294            ),
2295            "….ok_or_else"
2296        );
2297        assert_eq!(
2298            callee_name("workspace.resolve_path"),
2299            "workspace.resolve_path"
2300        );
2301        let selector = "html.dash .header, html.dash .breadcrumbs, html.dash .navigation";
2302        assert_eq!(callee_name(selector), selector);
2303    }
2304
2305    #[test]
2306    fn file_skeleton_reports_parse_errors() {
2307        let two = format_file_skeleton("src/lib.rs", &[], Some(35), 2);
2308        assert!(two.contains("// 2 parse errors: symbols may be incomplete"));
2309
2310        let one = format_file_skeleton("src/lib.rs", &[], Some(35), 1);
2311        assert!(one.contains("// 1 parse error: symbols may be incomplete"));
2312
2313        let none = format_file_skeleton("src/lib.rs", &[], Some(35), 0);
2314        assert!(!none.contains("parse error"));
2315    }
2316
2317    #[test]
2318    fn test_format_file_skeleton() {
2319        let syms = vec![Symbol {
2320            symbol_id: "s1".into(),
2321            file_id: "f1".into(),
2322            path: "src/lib.rs".into(),
2323            language: "rust".into(),
2324            name: "do_work".into(),
2325            kind: "function".into(),
2326            signature: Some("pub fn do_work() -> Result<()>".into()),
2327            doc_comment: Some("Performs core work.".into()),
2328            visibility: Some("pub".into()),
2329            parent_symbol_id: None,
2330            start_line: 10,
2331            start_column: 0,
2332            end_line: 30,
2333            end_column: 1,
2334            start_byte: 100,
2335            end_byte: 300,
2336            body_start_line: Some(11),
2337            body_start_column: Some(0),
2338            body_end_line: Some(29),
2339            body_end_column: Some(1),
2340            body_start_byte: Some(130),
2341            body_end_byte: Some(298),
2342            body_hash: None,
2343            semantic_group: None,
2344            is_test: false,
2345            test_container: false,
2346        }];
2347
2348        let skeleton = format_file_skeleton("src/lib.rs", &syms, Some(35), 0);
2349        assert!(skeleton.contains("/// Performs core work."));
2350
2351        let mut commented = syms.clone();
2352        commented[0].doc_comment = Some("/**\n * Performs core work.\n */".into());
2353        let skeleton = format_file_skeleton("src/lib.rs", &commented, Some(35), 0);
2354        assert!(skeleton.contains("/// Performs core work.\n"), "{skeleton}");
2355        assert!(!skeleton.contains("/// /**"), "{skeleton}");
2356        assert!(skeleton.contains("19 lines hidden: L11-L29"));
2357    }
2358
2359    #[test]
2360    fn format_symbol_body_prints_the_source_under_its_location() {
2361        let mut symbol = sample_symbol("plain");
2362        symbol.signature = Some("pub fn plain()".into());
2363
2364        assert_eq!(
2365            format_symbol_body(&symbol, "pub fn plain() {\n    1\n}"),
2366            "// src/lib.rs:1-10 (plain)\npub fn plain() {\n    1\n}\n"
2367        );
2368    }
2369
2370    #[test]
2371    fn test_format_search_results() {
2372        let results = vec![SymbolSearchResult {
2373            symbol: Symbol {
2374                symbol_id: "s1".into(),
2375                file_id: "f1".into(),
2376                path: "src/parser.rs".into(),
2377                language: "rust".into(),
2378                name: "parse_tokens".into(),
2379                kind: "function".into(),
2380                signature: Some("pub fn parse_tokens()".into()),
2381                doc_comment: Some("Parses tokens from stream.".into()),
2382                visibility: Some("pub".into()),
2383                parent_symbol_id: None,
2384                start_line: 15,
2385                start_column: 0,
2386                end_line: 25,
2387                end_column: 1,
2388                start_byte: 100,
2389                end_byte: 250,
2390                body_start_line: None,
2391                body_start_column: None,
2392                body_end_line: None,
2393                body_end_column: None,
2394                body_start_byte: None,
2395                body_end_byte: None,
2396                body_hash: None,
2397                semantic_group: None,
2398                is_test: false,
2399                test_container: false,
2400            },
2401            score: -1.85,
2402            snippet: Some("Parses [tokens] from stream.".into()),
2403            explain: None,
2404        }];
2405
2406        let formatted = format_search_results("tokens", &results, 20);
2407        assert!(formatted.contains("Found 1 symbols matching concept \"tokens\":\n\n- "));
2408        assert!(
2409            formatted.contains("- function `parse_tokens` [src/parser.rs:15-25] (score: -1.85)")
2410        );
2411        assert!(formatted.contains("Match: Parses [tokens] from stream."));
2412        assert!(!formatted.contains("explain"));
2413        assert!(!formatted.contains("rerank"));
2414    }
2415
2416    #[test]
2417    fn exact_lookup_folds_import_rows_into_one_line_when_a_definition_exists() {
2418        let class = Symbol {
2419            kind: "class".into(),
2420            path: "src/flask/app.py".into(),
2421            ..sample_symbol("Flask")
2422        };
2423        let import = |path: &str, line: usize| Symbol {
2424            kind: "import".into(),
2425            path: path.into(),
2426            start_line: line,
2427            symbol_id: format!("id_{path}"),
2428            ..sample_symbol("Flask")
2429        };
2430        let rows = vec![
2431            class,
2432            import("src/flask/cli.py", 34),
2433            import("src/flask/ctx.py", 21),
2434            import("tests/conftest.py", 6),
2435            import("examples/app.py", 1),
2436        ];
2437
2438        let folded = format_find_symbol_results("Flask", &rows, &[], 20);
2439
2440        assert!(
2441            folded.contains("- class `Flask` [src/flask/app.py:"),
2442            "{folded}"
2443        );
2444        assert!(
2445            folded.contains(
2446                "- 4 imports of `Flask`: src/flask/cli.py:34, src/flask/ctx.py:21, tests/conftest.py:6, … (lookup_symbol with kind=\"import\" lists them)"
2447            ),
2448            "{folded}"
2449        );
2450        assert!(!folded.contains("- import `Flask`"), "{folded}");
2451
2452        let capped = format_find_symbol_results("Flask", &rows, &[], 1);
2453        assert!(
2454            capped.contains("- at least 4 imports of `Flask`"),
2455            "{capped}"
2456        );
2457
2458        let mut with_prefix_rows = rows.clone();
2459        with_prefix_rows.push(Symbol {
2460            kind: "class".into(),
2461            ..sample_symbol("FlaskGroup")
2462        });
2463        let cut_after_exact = format_find_symbol_results("Flask", &with_prefix_rows, &[], 6);
2464        assert!(
2465            cut_after_exact.contains("- 4 imports of `Flask`"),
2466            "{cut_after_exact}"
2467        );
2468
2469        let imports_only = format_find_symbol_results("Flask", &rows[1..], &[], 20);
2470        assert_eq!(imports_only.matches("- import `Flask`").count(), 4);
2471    }
2472
2473    #[test]
2474    fn skeleton_shows_python_class_and_module_variables_with_one_line_values() {
2475        let leaf = |name: &str, kind: &str, line: usize, sig: &str| Symbol {
2476            kind: kind.into(),
2477            language: "python".into(),
2478            path: "app.py".into(),
2479            parent_symbol_id: Some("id_App".into()),
2480            start_line: line,
2481            end_line: line,
2482            body_start_line: None,
2483            body_end_line: None,
2484            signature: Some(sig.into()),
2485            ..sample_symbol(name)
2486        };
2487        let class = Symbol {
2488            kind: "class".into(),
2489            language: "python".into(),
2490            path: "app.py".into(),
2491            start_line: 1,
2492            end_line: 20,
2493            body_start_line: None,
2494            body_end_line: None,
2495            signature: Some("class App".into()),
2496            ..sample_symbol("App")
2497        };
2498        let module_variable = Symbol {
2499            kind: "variable".into(),
2500            language: "python".into(),
2501            path: "app.py".into(),
2502            start_line: 30,
2503            end_line: 30,
2504            body_start_line: None,
2505            body_end_line: None,
2506            signature: Some("app = App()".into()),
2507            ..sample_symbol("app")
2508        };
2509        let symbols = vec![
2510            class,
2511            leaf(
2512                "request_class",
2513                "variable",
2514                2,
2515                "request_class: type[Request] = Request",
2516            ),
2517            leaf(
2518                "default_config",
2519                "variable",
2520                3,
2521                "default_config = ImmutableDict(\n    {\n        \"DEBUG\": None,\n    }\n)",
2522            ),
2523            leaf(
2524                "blueprints",
2525                "property",
2526                5,
2527                "self.blueprints: dict[str, Blueprint] = {}",
2528            ),
2529            leaf(
2530                "error_handler_spec",
2531                "property",
2532                7,
2533                "self.error_handler_spec: dict[\n    ft.AppOrBlueprintKey,\n    dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],\n] = defaultdict(lambda: defaultdict(dict), default_factory_argument_that_is_long)  # type: ignore",
2534            ),
2535            module_variable,
2536        ];
2537
2538        let out = format_file_skeleton("app.py", &symbols, None, 0);
2539
2540        assert!(
2541            out.contains("    request_class: type[Request] = Request; // L2-2"),
2542            "{out}"
2543        );
2544        assert!(
2545            out.contains("    default_config = ImmutableDict({\"DEBUG\": None}); // L3-3"),
2546            "{out}"
2547        );
2548        assert!(
2549            out.contains("    self.error_handler_spec: dict[ft.AppOrBlueprintKey, dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]]] = defaultdict(lambda: defaultdict(dict)…; // L7-7"),
2550            "{out}"
2551        );
2552        assert!(
2553            out.contains("    self.blueprints: dict[str, Blueprint] = {}; // L5-5"),
2554            "{out}"
2555        );
2556        assert!(out.contains("app = App(); // L30-30"), "{out}");
2557    }
2558
2559    #[test]
2560    fn skeleton_names_the_method_that_assigns_an_attribute() {
2561        let member = |name: &str, kind: &str, start: usize, end: usize, sig: &str| Symbol {
2562            kind: kind.into(),
2563            language: "python".into(),
2564            parent_symbol_id: Some("id_Flask".into()),
2565            start_line: start,
2566            end_line: end,
2567            body_start_line: None,
2568            body_end_line: None,
2569            signature: Some(sig.into()),
2570            ..sample_symbol(name)
2571        };
2572        let class = Symbol {
2573            kind: "class".into(),
2574            language: "python".into(),
2575            start_line: 1,
2576            end_line: 30,
2577            body_start_line: None,
2578            body_end_line: None,
2579            signature: Some("class Flask(App)".into()),
2580            ..sample_symbol("Flask")
2581        };
2582        let symbols = vec![
2583            class,
2584            member("__init__", "method", 2, 10, "def __init__(self)"),
2585            member("cli", "property", 3, 3, "self.cli = cli.AppGroup()"),
2586            member("run", "method", 12, 20, "def run(self)"),
2587            member("debug", "property", 14, 14, "self.debug = get_debug_flag()"),
2588        ];
2589
2590        let out = format_file_skeleton("app.py", &symbols, None, 0);
2591
2592        assert!(
2593            out.contains("self.cli = cli.AppGroup(); // in __init__(), L3-3"),
2594            "{out}"
2595        );
2596        assert!(
2597            out.contains("self.debug = get_debug_flag(); // in run(), L14-14"),
2598            "{out}"
2599        );
2600    }
2601
2602    #[test]
2603    fn skeleton_hides_variables_that_are_not_python_class_attributes() {
2604        let parent = |name: &str, kind: &str, language: &str| Symbol {
2605            kind: kind.into(),
2606            language: language.into(),
2607            start_line: 1,
2608            end_line: 20,
2609            body_start_line: None,
2610            body_end_line: None,
2611            signature: Some(format!("{kind} {name}")),
2612            ..sample_symbol(name)
2613        };
2614        let child = |name: &str, parent: &str, language: &str, sig: &str| Symbol {
2615            kind: "variable".into(),
2616            language: language.into(),
2617            parent_symbol_id: Some(format!("id_{parent}")),
2618            start_line: 2,
2619            end_line: 2,
2620            body_start_line: None,
2621            body_end_line: None,
2622            signature: Some(sig.into()),
2623            ..sample_symbol(name)
2624        };
2625        let symbols = vec![
2626            parent("Adapters", "class", "java"),
2627            child(
2628                "accessible",
2629                "Adapters",
2630                "java",
2631                "boolean accessible = false",
2632            ),
2633            parent("body", "class", "html"),
2634            child(
2635                "img",
2636                "body",
2637                "html",
2638                "<img class=\"carat\" src=\"carat.png\" alt>",
2639            ),
2640            parent("section", "module", "yaml"),
2641            child("title", "section", "yaml", "title: Invoking jq"),
2642        ];
2643
2644        let out = format_file_skeleton("mixed", &symbols, None, 0);
2645
2646        for hidden in ["accessible", "<img", "title:"] {
2647            assert!(!out.contains(hidden), "{out}");
2648        }
2649    }
2650
2651    #[test]
2652    fn a_multi_line_macro_row_drops_its_line_continuations_and_is_cut_to_one_line() {
2653        let short = "#define PAIR(a, b)   \\\n    a,                \\\n    b";
2654        assert_eq!(value_row_signature(short), "#define PAIR(a, b) a, b");
2655
2656        let long = format!(
2657            "#define WIDE(x) \\\n{}",
2658            "    x + x + x + x + x + x + x + x \\\n".repeat(8)
2659        );
2660        let row = value_row_signature(&long);
2661        assert!(row.starts_with("#define WIDE(x) x + x"), "{row}");
2662        assert!(row.ends_with('…'), "{row}");
2663        assert!(!row.contains('\\'), "{row}");
2664        assert!(row.chars().count() <= 120, "{row}");
2665    }
2666
2667    #[test]
2668    fn skeleton_keeps_values_only_for_real_assignments() {
2669        let row =
2670            |name: &str, kind: &str, line: usize, sig: &str, body: Option<(usize, usize)>| Symbol {
2671                kind: kind.into(),
2672                start_line: line,
2673                end_line: body.map_or(line, |(_, end)| end),
2674                body_start_line: body.map(|(start, _)| start),
2675                body_end_line: body.map(|(_, end)| end),
2676                signature: Some(sig.into()),
2677                ..sample_symbol(name)
2678            };
2679        let symbols = vec![
2680            row(
2681                "img",
2682                "property",
2683                1,
2684                "[class^=rz-] img,[class^=rz-] svg { vertical-align:middle }",
2685                None,
2686            ),
2687            row(
2688                "Coordinates",
2689                "property",
2690                2,
2691                "[JsonProperty(ItemConverterType = typeof(IntToFloatConverter))] public int[,,] Coordinates { get; set; }",
2692                None,
2693            ),
2694            row(
2695                "VERSION_CHECK",
2696                "constant",
2697                3,
2698                "#define VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor)))\n",
2699                None,
2700            ),
2701            row(
2702                "TABLE",
2703                "constant",
2704                4,
2705                "TABLE = {\n  '\"' => '%22',\n  '\\r' => '%0D',\n}.freeze",
2706                Some((4, 8)),
2707            ),
2708            row(
2709                "LIMIT",
2710                "field",
2711                10,
2712                "private static final int LIMIT = 5;",
2713                None,
2714            ),
2715        ];
2716
2717        let out = format_file_skeleton("mixed", &symbols, None, 0);
2718
2719        assert!(
2720            out.contains("[class^=rz-] img,[class^=rz-] svg; // L1-1"),
2721            "{out}"
2722        );
2723        assert!(out.contains("public int[,,] Coordinates; // L2-2"), "{out}");
2724        assert!(
2725            out.contains(
2726                "#define VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))); // L3-3\n"
2727            ),
2728            "{out}"
2729        );
2730        assert!(
2731            out.contains("TABLE = { /* 5 lines hidden: L4-L8 */ }"),
2732            "{out}"
2733        );
2734        assert!(
2735            out.contains("private static final int LIMIT = 5; // L10-10"),
2736            "{out}"
2737        );
2738    }
2739
2740    #[test]
2741    fn skeleton_cuts_a_field_with_members_at_its_brace() {
2742        let field = Symbol {
2743            kind: "field".into(),
2744            language: "java".into(),
2745            start_line: 1,
2746            end_line: 9,
2747            body_start_line: None,
2748            body_end_line: None,
2749            signature: Some(
2750                "public static final TypeAdapter<Class> CLASS = new TypeAdapter<Class>() {\n  @Override\n}"
2751                    .into(),
2752            ),
2753            ..sample_symbol("CLASS")
2754        };
2755        let member = Symbol {
2756            kind: "method".into(),
2757            language: "java".into(),
2758            parent_symbol_id: Some("id_CLASS".into()),
2759            start_line: 2,
2760            end_line: 4,
2761            signature: Some("public void write(JsonWriter out, Class value)".into()),
2762            ..sample_symbol("write")
2763        };
2764
2765        let out = format_file_skeleton("TypeAdapters.java", &[field, member], None, 0);
2766
2767        assert!(
2768            out.contains(
2769                "public static final TypeAdapter<Class> CLASS = new TypeAdapter<Class>() {\n"
2770            ),
2771            "{out}"
2772        );
2773        assert!(!out.contains('…'), "{out}");
2774    }
2775
2776    #[test]
2777    fn import_summary_counts_sites_and_files_and_lists_three() {
2778        let sites = vec![
2779            ("src/flask/__init__.py".to_string(), 2),
2780            ("src/flask/cli.py".to_string(), 34),
2781            ("src/flask/cli.py".to_string(), 45),
2782            ("tests/conftest.py".to_string(), 6),
2783        ];
2784
2785        assert_eq!(
2786            format_import_summary(&sites),
2787            "Imported 4 times in 3 files: src/flask/__init__.py:2, src/flask/cli.py:34, src/flask/cli.py:45, … (lookup_symbol with kind=\"import\" lists them)\n"
2788        );
2789        assert_eq!(format_import_summary(&[]), "");
2790    }
2791
2792    #[test]
2793    fn no_facts_for_an_alias_points_imports_at_lookup_and_skips_the_raw_list() {
2794        let categories = vec![("flask.route.v1".to_string(), 3)];
2795
2796        let imports = format_no_facts("import", None, &categories);
2797        let unknown = format_no_facts("widgets", None, &categories);
2798
2799        assert!(
2800            imports.contains("lookup_symbol with kind=\"import\""),
2801            "{imports}"
2802        );
2803        assert!(!imports.contains("`flask.route.v1`"), "{imports}");
2804        assert!(unknown.contains("`flask.route.v1` (3 facts)"), "{unknown}");
2805    }
2806
2807    #[test]
2808    fn markup_and_data_rows_show_their_own_kind_words() {
2809        let row = |language: &str, kind: &str| Symbol {
2810            language: language.into(),
2811            kind: kind.into(),
2812            ..sample_symbol("x")
2813        };
2814        assert_eq!(display_kind(&row("html", "class")), "element");
2815        assert_eq!(display_kind(&row("sql", "class")), "table");
2816        assert_eq!(display_kind(&row("markdown", "module")), "section");
2817        assert_eq!(display_kind(&row("markdown", "import")), "link");
2818        let attribute = Symbol {
2819            kind: "property".into(),
2820            signature: Some("self.extensions = {}".into()),
2821            ..sample_symbol("extensions")
2822        };
2823        assert_eq!(display_kind(&attribute), "attribute");
2824        let fsharp_member = Symbol {
2825            language: "fsharp".into(),
2826            signature: Some("this.Total = decimal this.Qty * this.Price".into()),
2827            ..attribute
2828        };
2829        assert_eq!(display_kind(&fsharp_member), "property");
2830        assert_eq!(display_kind(&row("python", "class")), "class");
2831    }
2832
2833    #[test]
2834    fn no_facts_heading_names_the_path_filter() {
2835        assert_eq!(
2836            no_facts_heading("config", Some("src/flask")),
2837            "No facts match 'config' under `src/flask`."
2838        );
2839        assert_eq!(
2840            no_facts_heading("config", None),
2841            "No facts match 'config' in this repository."
2842        );
2843    }
2844
2845    #[test]
2846    fn outline_says_how_many_definitions_it_left_out_and_counts_tests() {
2847        let mut root = OutlineNode::default();
2848        let symbol = |name: &str, is_test: bool| Symbol {
2849            kind: "function".into(),
2850            path: "tests/test_basic.py".into(),
2851            is_test,
2852            ..sample_symbol(name)
2853        };
2854        let symbols = HashMap::from([(
2855            "tests/test_basic.py".to_string(),
2856            vec![symbol("helper", false), symbol("test_one", true)],
2857        )]);
2858        let counts = HashMap::from([(
2859            "tests/test_basic.py".to_string(),
2860            crate::queries::OutlineCounts {
2861                definitions: 3,
2862                tests: 90,
2863                fixtures: 2,
2864            },
2865        )]);
2866        add_path_to_outline(&mut root, "tests/test_basic.py", &symbols, &counts, 3, "");
2867
2868        let mut out = String::new();
2869        render_outline_tree(&mut out, &root, "", 0, 3);
2870
2871        assert!(
2872            out.contains("test_basic.py [function helper, +2 more, 90 tests, 2 fixtures]"),
2873            "{out}"
2874        );
2875    }
2876
2877    #[test]
2878    fn outline_counts_the_files_below_the_depth_limit() {
2879        let mut root = OutlineNode::default();
2880        let no_symbols = HashMap::new();
2881        for path in [
2882            "src/flask/app.py",
2883            "src/flask/json/tag.py",
2884            "src/flask/cli.py",
2885            "tests/conftest.py",
2886        ] {
2887            add_path_to_outline(&mut root, path, &no_symbols, &HashMap::new(), 2, "");
2888        }
2889
2890        let mut out = String::new();
2891        render_outline_tree(&mut out, &root, "", 0, 2);
2892
2893        assert!(out.contains("└── flask/ (3 indexed files)"), "{out}");
2894        assert!(!out.contains("tests/ ("), "{out}");
2895    }
2896
2897    #[test]
2898    fn a_lookup_qualified_with_double_colons_names_the_member_exactly() {
2899        let rows = vec![sample_symbol("Flask.handle_user_exception")];
2900
2901        let out = format_find_symbol_results("Flask::handle_user_exception", &rows, &[], 20);
2902
2903        assert!(!out.contains("named exactly"), "{out}");
2904    }
2905
2906    #[test]
2907    fn exact_lookup_folds_only_imports_named_exactly_like_the_query() {
2908        let rows = vec![
2909            Symbol {
2910                kind: "function".into(),
2911                ..sample_symbol("read")
2912            },
2913            Symbol {
2914                kind: "import".into(),
2915                path: "src/flask/cli.py".into(),
2916                start_line: 1034,
2917                ..sample_symbol("readline")
2918            },
2919            Symbol {
2920                kind: "import".into(),
2921                path: "src/Types.kt".into(),
2922                start_line: 18,
2923                ..sample_symbol("com.example.internal.read")
2924            },
2925        ];
2926
2927        let out = format_find_symbol_results("read", &rows, &[], 20);
2928
2929        assert!(
2930            out.contains(
2931                "- 1 other row starts with or contains `read`, ignoring case: `readline` (import) (lookup_symbol"
2932            ),
2933            "{out}"
2934        );
2935        assert!(
2936            out.contains(
2937                "- 1 import of `read`: src/Types.kt:18 (lookup_symbol with kind=\"import\" lists them)"
2938            ),
2939            "{out}"
2940        );
2941    }
2942
2943    #[test]
2944    fn discovery_formatters_append_ids_to_metadata_rows() {
2945        let exact = vec![sample_symbol("exact")];
2946        let fallback = vec![SymbolSearchResult {
2947            symbol: sample_symbol("fallback"),
2948            score: 1.0,
2949            snippet: None,
2950            explain: None,
2951        }];
2952
2953        let outputs = [
2954            (
2955                format_find_symbol_results("exact", &exact, &[], 20),
2956                "id_exact",
2957            ),
2958            (
2959                format_find_symbol_results("fallback query", &[], &fallback, 20),
2960                "id_fallback",
2961            ),
2962            (
2963                format_search_results("fallback", &fallback, 20),
2964                "id_fallback",
2965            ),
2966        ];
2967
2968        for (formatted, id) in outputs {
2969            assert!(
2970                formatted
2971                    .lines()
2972                    .any(|line| line.starts_with("- ") && line.contains(&format!("id={id}"))),
2973                "{formatted}"
2974            );
2975            assert!(!formatted.contains("\n  id="), "{formatted}");
2976        }
2977    }
2978
2979    #[test]
2980    fn lookup_lists_name_rows_before_the_ranked_rows_under_their_own_header() {
2981        let names = vec![sample_symbol("retry_count")];
2982        let ranked = vec![SymbolSearchResult {
2983            symbol: sample_symbol("send_again"),
2984            score: 7.5,
2985            snippet: None,
2986            explain: None,
2987        }];
2988
2989        let out = format_find_symbol_results("retry", &names, &ranked, 20);
2990
2991        let name_header = out.find("Found 1 symbols matching \"retry\"").unwrap();
2992        let ranked_header = out
2993            .find("\nNo exact name match; 1 full-text matches for \"retry\":\n\n")
2994            .unwrap();
2995        assert!(name_header < out.find("`retry_count`").unwrap(), "{out}");
2996        assert!(out.find("`retry_count`").unwrap() < ranked_header, "{out}");
2997        assert!(ranked_header < out.find("`send_again`").unwrap(), "{out}");
2998    }
2999
3000    #[test]
3001    fn every_printed_part_of_the_explain_line_sums_to_the_score() {
3002        let e = SearchExplain {
3003            bm25: Some(-3.21),
3004            branches: vec!["word".into()],
3005            name_tier: "all".into(),
3006            name_strength: 6,
3007            term_score: 24.5,
3008            field_diversity_bonus: 6.0,
3009            name_bonus: 60.0,
3010            kind_prior: 4.0,
3011            path_role: -10.0,
3012            documentation: -200.0,
3013            test_intent: 5.0,
3014            nested: 0.0,
3015            terms: vec![("sha".into(), "name".into(), 3.0)],
3016            word_weights: vec![("sha".into(), 2.6)],
3017            candidates: 1,
3018            rerank_us: 1,
3019        };
3020        let score = e.term_score
3021            + e.field_diversity_bonus
3022            + e.name_bonus
3023            + e.kind_prior
3024            + e.path_role
3025            + e.documentation
3026            + e.test_intent;
3027
3028        let line = explain_line(score, &e);
3029        let parts: f64 = line
3030            .split(" = ")
3031            .nth(1)
3032            .unwrap()
3033            .split(" [")
3034            .next()
3035            .unwrap()
3036            .split(" + ")
3037            .map(|part| part.rsplit(' ').next().unwrap().parse::<f64>().unwrap())
3038            .sum();
3039
3040        assert!(line.starts_with(&format!(
3041            "score {score:.1} = terms 24.5 + name all(6) 60.0 "
3042        )));
3043        assert!(line.contains("+ field coverage 6.0"));
3044        assert_eq!(format!("{parts:.1}"), format!("{score:.1}"));
3045    }
3046
3047    #[test]
3048    fn test_format_search_results_prints_the_explain_breakdown_when_present() {
3049        let mut result = SymbolSearchResult {
3050            symbol: sample_symbol("parseSha256Sidecar"),
3051            score: 71.6,
3052            snippet: Some("parse[Sha256]Sidecar".into()),
3053            explain: Some(SearchExplain {
3054                bm25: Some(-3.21),
3055                branches: vec!["word".into(), "name".into()],
3056                name_tier: "all".into(),
3057                name_strength: 6,
3058                terms: vec![
3059                    ("sha".into(), "name".into(), 3.0),
3060                    ("256".into(), "name".into(), 3.0),
3061                ],
3062                term_score: 12.6,
3063                field_diversity_bonus: 0.0,
3064                name_bonus: 60.0,
3065                kind_prior: 4.0,
3066                path_role: -10.0,
3067                documentation: 0.0,
3068                test_intent: 5.0,
3069                nested: 0.0,
3070                word_weights: vec![("sha".into(), 2.6), ("256".into(), 0.97)],
3071                candidates: 37,
3072                rerank_us: 180,
3073            }),
3074        };
3075
3076        let formatted = format_search_results("sha256", std::slice::from_ref(&result), 20);
3077        assert!(formatted.contains(
3078            "Found 1 symbols matching concept \"sha256\":\nrerank: 37 candidates in 180 µs; words sha 2.60, 256 0.97\n\n- "
3079        ));
3080        assert!(formatted.contains(
3081            "  explain: score 71.6 = terms 12.6 + name all(6) 60.0 + kind 4.0 + path -10.0 + test 5.0 [word,name] bm25 -3.21 terms sha=name:3 256=name:3\n"
3082        ));
3083
3084        result.explain = None;
3085        let silent = format_search_results("sha256", std::slice::from_ref(&result), 20);
3086        assert!(!silent.contains("explain"));
3087        assert!(!silent.contains("rerank"));
3088    }
3089
3090    #[test]
3091    fn test_format_search_results_discloses_a_reached_limit() {
3092        let results = vec![SymbolSearchResult {
3093            symbol: sample_symbol("parse_tokens"),
3094            score: 0.0,
3095            snippet: None,
3096            explain: None,
3097        }];
3098
3099        let formatted = format_search_results("tokens", &results, 1);
3100        assert!(
3101            formatted.contains("[Showing 1 results (limit reached); increase limit to see more.]")
3102        );
3103
3104        let at_ceiling =
3105            format_search_results("tokens", &results, crate::queries::MAX_RESULT_LIMIT);
3106        assert!(!at_ceiling.contains("limit reached"));
3107
3108        let full: Vec<SymbolSearchResult> = (0..crate::queries::MAX_RESULT_LIMIT)
3109            .map(|_| SymbolSearchResult {
3110                symbol: sample_symbol("parse_tokens"),
3111                score: 0.0,
3112                snippet: None,
3113                explain: None,
3114            })
3115            .collect();
3116        let capped = format_search_results("tokens", &full, crate::queries::MAX_RESULT_LIMIT);
3117        assert!(capped.contains("(limit reached); narrow the query to see more.]"));
3118    }
3119
3120    #[test]
3121    fn test_format_blast_radius() {
3122        let res = BlastRadiusResult {
3123            seed_type: "symbol".into(),
3124            seeds: vec!["do_work".into()],
3125            likely_tests: vec![TestTarget {
3126                name: "test_do_work".into(),
3127                path: "tests/work_test.rs".into(),
3128                line: 15,
3129                reason: "direct caller".into(),
3130            }],
3131            impacted_symbols: vec![ImpactedSymbol {
3132                name: "caller_fn".into(),
3133                kind: "function".into(),
3134                path: "src/caller.rs".into(),
3135                line: 42,
3136                depth: 1,
3137                enclosing_symbol_name: None,
3138            }],
3139            traversal_ceiling_reached: false,
3140            likely_tests_truncated: false,
3141            impacted_symbols_truncated: false,
3142            limit_at_maximum: false,
3143            likely_tests_found: 0,
3144            impacted_symbols_found: 0,
3145            stopped_at_depth: None,
3146        };
3147
3148        let formatted = format_blast_radius(&res);
3149        assert!(formatted.contains("## Blast Radius & Test Impact (Symbol: do_work)"));
3150        assert!(formatted.contains("### Likely Tests to Run (1 returned)"));
3151        assert!(
3152            formatted.contains("tests/work_test.rs:\n  - `test_do_work` [line 15] (direct caller)")
3153        );
3154        assert!(formatted.contains("src/caller.rs:\n  - [depth 1] function `caller_fn` [line 42]"));
3155    }
3156
3157    #[test]
3158    fn format_blast_radius_groups_every_returned_test_by_file() {
3159        let mut likely_tests = Vec::new();
3160        for i in 1..=25 {
3161            likely_tests.push(TestTarget {
3162                name: format!("test_{i}"),
3163                path: format!("tests/test_{}.rs", (i % 3) + 1),
3164                line: i * 10,
3165                reason: "direct caller".into(),
3166            });
3167        }
3168
3169        let impacted_symbols = vec![
3170            ImpactedSymbol {
3171                name: "use_foo".into(),
3172                kind: "import".into(),
3173                path: "src/service.rs".into(),
3174                line: 1,
3175                depth: 1,
3176                enclosing_symbol_name: None,
3177            },
3178            ImpactedSymbol {
3179                name: "service_fn".into(),
3180                kind: "function".into(),
3181                path: "src/service.rs".into(),
3182                line: 20,
3183                depth: 1,
3184                enclosing_symbol_name: None,
3185            },
3186            ImpactedSymbol {
3187                name: "api_handler".into(),
3188                kind: "function".into(),
3189                path: "src/api.rs".into(),
3190                line: 45,
3191                depth: 2,
3192                enclosing_symbol_name: None,
3193            },
3194        ];
3195
3196        let res = BlastRadiusResult {
3197            seed_type: "file".into(),
3198            seeds: vec!["src/lib.rs".into()],
3199            likely_tests,
3200            impacted_symbols,
3201            traversal_ceiling_reached: false,
3202            likely_tests_truncated: false,
3203            impacted_symbols_truncated: false,
3204            limit_at_maximum: false,
3205            likely_tests_found: 0,
3206            impacted_symbols_found: 0,
3207            stopped_at_depth: None,
3208        };
3209
3210        let formatted = format_blast_radius(&res);
3211
3212        assert!(formatted.contains("### Likely Tests to Run (25 returned)"));
3213        assert!(
3214            formatted.contains("  - `test_25` [line 250]"),
3215            "{formatted}"
3216        );
3217        assert!(!formatted.contains("hidden by the compact"));
3218
3219        assert!(formatted.contains("tests/test_1.rs:\n"));
3220        assert!(formatted.contains("  - `test_"));
3221
3222        assert!(!formatted.contains("use_foo"));
3223        assert!(
3224            formatted
3225                .contains("... 1 low-signal row (import/module) hidden; available in CLI --json.")
3226        );
3227        assert!(formatted.contains("src/service.rs:\n"));
3228        assert!(formatted.contains("  - [depth 1] function `service_fn` [line 20]"));
3229    }
3230
3231    fn sample_symbol(name: &str) -> Symbol {
3232        Symbol {
3233            symbol_id: format!("id_{name}"),
3234            file_id: "f1".into(),
3235            path: "src/lib.rs".into(),
3236            language: "rust".into(),
3237            name: name.into(),
3238            kind: "function".into(),
3239            signature: Some(format!("pub fn {name}()")),
3240            doc_comment: None,
3241            visibility: Some("pub".into()),
3242            parent_symbol_id: None,
3243            start_line: 1,
3244            start_column: 0,
3245            end_line: 10,
3246            end_column: 1,
3247            start_byte: 0,
3248            end_byte: 100,
3249            body_start_line: Some(2),
3250            body_start_column: Some(0),
3251            body_end_line: Some(9),
3252            body_end_column: Some(1),
3253            body_start_byte: Some(10),
3254            body_end_byte: Some(99),
3255            body_hash: None,
3256            semantic_group: None,
3257            is_test: false,
3258            test_container: false,
3259        }
3260    }
3261
3262    fn sample_context_slice() -> ContextSlice {
3263        ContextSlice {
3264            target_symbol: sample_symbol("target_fn"),
3265            target_body: "    println!(\"hello\");\n".into(),
3266            callee_signatures: Vec::new(),
3267            related_types: Vec::new(),
3268            related_tests: Vec::new(),
3269        }
3270    }
3271
3272    #[test]
3273    fn format_context_slice_does_not_repeat_expression_already_in_signature() {
3274        let body = "=>\n        transport.SendAsync<Response>(\n            HttpMethod.Get,\n            $\"items/{id}\",\n            cancellationToken: cancellationToken)";
3275        let mut slice = sample_context_slice();
3276        slice.target_symbol.language = "csharp".into();
3277        slice.target_symbol.signature = Some(format!(
3278            "public static Task<Response?> GetByIdAsync(\n        int id,\n        CancellationToken cancellationToken = default){body}"
3279        ));
3280        slice.target_body = body.into();
3281
3282        let formatted = format_context_slice(&slice);
3283
3284        assert_eq!(
3285            formatted.matches("transport.SendAsync").count(),
3286            1,
3287            "{formatted}"
3288        );
3289    }
3290
3291    #[test]
3292    fn context_slice_leaves_out_a_signature_that_the_body_already_holds() {
3293        let mut slice = sample_context_slice();
3294        slice.target_symbol.signature = Some("type Person = { Name: string; Age: int }".into());
3295        slice.target_body = "type Person = { Name: string; Age: int }\n".into();
3296
3297        let text = format_context_slice(&slice);
3298
3299        assert!(!text.contains("Signature:"), "{text}");
3300        assert_eq!(text.matches("type Person").count(), 1, "{text}");
3301    }
3302
3303    #[test]
3304    fn context_slice_says_when_no_test_was_found() {
3305        let text = format_context_slice(&sample_context_slice());
3306
3307        assert!(
3308            text.ends_with("### Related Tests:\nNo test calls, uses, or names this symbol; blast_radius lists tests that can reach it through callers.\n"),
3309            "{text}"
3310        );
3311    }
3312
3313    #[test]
3314    fn test_context_slice_shows_truncation_notice_when_caps_hit() {
3315        let mut slice = sample_context_slice();
3316        slice.callee_signatures = (1..=10).map(|i| format!("fn callee_{i}()")).collect();
3317        let text = format_context_slice(&slice);
3318        assert!(text.contains("[Showing 10 dependencies (limit reached)]"));
3319
3320        let mut slice_tests = sample_context_slice();
3321        slice_tests.related_tests = (1..=5)
3322            .map(|i| {
3323                let mut sym = sample_symbol(&format!("test_fn_{i}"));
3324                sym.path = format!("tests/test_{i}.rs");
3325                sym.is_test = true;
3326                sym
3327            })
3328            .collect();
3329        let text_tests = format_context_slice(&slice_tests);
3330        assert!(text_tests.contains("[Showing 5 tests (limit reached)]"));
3331    }
3332
3333    #[test]
3334    fn test_blast_radius_shows_traversal_ceiling_at_200_symbols() {
3335        let impacted_symbols = (1..=200)
3336            .map(|i| ImpactedSymbol {
3337                name: format!("sym_{i}"),
3338                kind: "function".into(),
3339                path: format!("src/mod_{}.rs", i % 10),
3340                line: i,
3341                depth: 1,
3342                enclosing_symbol_name: None,
3343            })
3344            .collect();
3345
3346        let res = BlastRadiusResult {
3347            seed_type: "symbol".into(),
3348            seeds: vec!["root_fn".into()],
3349            likely_tests: Vec::new(),
3350            impacted_symbols,
3351            traversal_ceiling_reached: true,
3352            likely_tests_truncated: false,
3353            impacted_symbols_truncated: false,
3354            limit_at_maximum: false,
3355            likely_tests_found: 0,
3356            impacted_symbols_found: 0,
3357            stopped_at_depth: None,
3358        };
3359
3360        let formatted = format_blast_radius(&res);
3361        assert!(formatted.contains("### Downstream Impact (200 returned)\n"));
3362    }
3363
3364    #[test]
3365    fn blast_radius_does_not_claim_no_results_after_the_traversal_ceiling() {
3366        let res = BlastRadiusResult {
3367            seed_type: "file".into(),
3368            seeds: vec!["src/widget.rs".into()],
3369            likely_tests: Vec::new(),
3370            impacted_symbols: Vec::new(),
3371            likely_tests_truncated: false,
3372            impacted_symbols_truncated: false,
3373            traversal_ceiling_reached: true,
3374            limit_at_maximum: false,
3375            likely_tests_found: 0,
3376            impacted_symbols_found: 0,
3377            stopped_at_depth: None,
3378        };
3379
3380        let formatted = format_blast_radius(&res);
3381        assert!(formatted.contains("Likely Tests to Run (0 returned)"));
3382        assert!(formatted.contains("Downstream Impact (0 returned)"));
3383        assert!(!formatted.contains("No test reaches it through the index"));
3384        assert!(!formatted.contains("No downstream callers found within depth"));
3385
3386        let no_ceiling = BlastRadiusResult {
3387            traversal_ceiling_reached: false,
3388            ..res
3389        };
3390        assert!(
3391            format_blast_radius(&no_ceiling)
3392                .contains("No test reaches it through the index. Run the full test suite.\n")
3393        );
3394
3395        let cut_by_depth = BlastRadiusResult {
3396            stopped_at_depth: Some(2),
3397            ..no_ceiling
3398        };
3399        let formatted = format_blast_radius(&cut_by_depth);
3400        assert!(formatted.contains(
3401            "No test reaches it within depth 2; a larger `depth` may find some. Otherwise run the full test suite.\n"
3402        ));
3403        assert!(!formatted.contains("through the index"));
3404    }
3405
3406    fn skeleton_row(
3407        id: &str,
3408        parent: Option<&str>,
3409        kind: &str,
3410        name: &str,
3411        signature: &str,
3412        lines: (usize, usize),
3413        body: Option<(usize, usize)>,
3414    ) -> Symbol {
3415        Symbol {
3416            symbol_id: id.into(),
3417            file_id: "f1".into(),
3418            path: "src/lib.rs".into(),
3419            language: "rust".into(),
3420            name: name.into(),
3421            kind: kind.into(),
3422            signature: Some(signature.into()),
3423            doc_comment: None,
3424            visibility: None,
3425            parent_symbol_id: parent.map(str::to_string),
3426            start_line: lines.0,
3427            start_column: 0,
3428            end_line: lines.1,
3429            end_column: 1,
3430            start_byte: 0,
3431            end_byte: 0,
3432            body_start_line: body.map(|b| b.0),
3433            body_start_column: None,
3434            body_end_line: body.map(|b| b.1),
3435            body_end_column: None,
3436            body_start_byte: None,
3437            body_end_byte: None,
3438            body_hash: None,
3439            semantic_group: None,
3440            is_test: false,
3441            test_container: false,
3442        }
3443    }
3444
3445    #[test]
3446    fn skeleton_nests_an_object_under_the_field_that_declares_it() {
3447        let syms = vec![
3448            skeleton_row(
3449                "root",
3450                None,
3451                "class",
3452                "shell",
3453                "extends ShellRoot",
3454                (1, 8),
3455                None,
3456            ),
3457            skeleton_row(
3458                "timer",
3459                Some("root"),
3460                "field",
3461                "localPluginReloadTimer",
3462                "localPluginReloadTimer: Timer",
3463                (2, 7),
3464                Some((2, 7)),
3465            ),
3466            skeleton_row(
3467                "interval",
3468                Some("timer"),
3469                "property",
3470                "interval",
3471                "interval: 150",
3472                (3, 3),
3473                None,
3474            ),
3475            skeleton_row(
3476                "fire",
3477                Some("timer"),
3478                "function",
3479                "fire",
3480                "function fire()",
3481                (5, 7),
3482                Some((6, 7)),
3483            ),
3484        ];
3485
3486        assert_eq!(
3487            format_file_skeleton("shell/shell.qml", &syms, Some(8), 0),
3488            "// File: shell/shell.qml (Lines 1-8)\n\
3489             \n\
3490             extends ShellRoot {\n\
3491             \x20   localPluginReloadTimer: Timer {\n\
3492             \x20       interval: 150; // L3-3\n\
3493             \x20       function fire() { /* 2 lines hidden: L6-L7 */ }\n\
3494             \x20   } // L2-7\n\
3495             \n\
3496             } // L1-8\n\
3497             \n"
3498        );
3499    }
3500
3501    #[test]
3502    fn skeleton_renders_a_single_line_symbol_with_children_as_a_leaf() {
3503        let syms = vec![
3504            skeleton_row(
3505                "rusqlite",
3506                None,
3507                "field",
3508                "rusqlite",
3509                "rusqlite = { workspace = true }",
3510                (15, 15),
3511                None,
3512            ),
3513            skeleton_row(
3514                "workspace",
3515                Some("rusqlite"),
3516                "property",
3517                "workspace",
3518                "workspace = true",
3519                (15, 15),
3520                None,
3521            ),
3522        ];
3523
3524        assert_eq!(
3525            format_file_skeleton("Cargo.toml", &syms, Some(15), 0),
3526            "// File: Cargo.toml (Lines 1-15)\n\
3527             \n\
3528             rusqlite = { workspace = true }; // L15-15\n"
3529        );
3530    }
3531
3532    #[test]
3533    fn skeleton_renders_members_of_a_single_line_enum() {
3534        let mut syms = vec![
3535            skeleton_row(
3536                "mode",
3537                None,
3538                "enum",
3539                "DispatchMode",
3540                "public enum DispatchMode",
3541                (21, 21),
3542                None,
3543            ),
3544            skeleton_row(
3545                "provision",
3546                Some("mode"),
3547                "enum_member",
3548                "Provision",
3549                "Provision",
3550                (21, 21),
3551                None,
3552            ),
3553            skeleton_row(
3554                "deprovision",
3555                Some("mode"),
3556                "enum_member",
3557                "Deprovision",
3558                "Deprovision",
3559                (21, 21),
3560                None,
3561            ),
3562            skeleton_row(
3563                "extension",
3564                Some("mode"),
3565                "enum_member",
3566                "Extension",
3567                "Extension",
3568                (21, 21),
3569                None,
3570            ),
3571        ];
3572        for symbol in &mut syms {
3573            symbol.language = "csharp".into();
3574        }
3575
3576        let skeleton = format_file_skeleton("DispatchContext.cs", &syms, Some(21), 0);
3577
3578        for member in ["Provision", "Deprovision", "Extension"] {
3579            assert!(skeleton.contains(member), "{skeleton}");
3580        }
3581    }
3582
3583    #[test]
3584    fn a_hidden_body_names_the_functions_defined_inside_it_but_not_lambdas() {
3585        let mut syms = vec![
3586            skeleton_row(
3587                "factory",
3588                None,
3589                "function",
3590                "create_app",
3591                "def create_app()",
3592                (1, 9),
3593                Some((2, 9)),
3594            ),
3595            skeleton_row(
3596                "hello",
3597                Some("factory"),
3598                "function",
3599                "hello",
3600                "def hello()",
3601                (4, 5),
3602                Some((5, 5)),
3603            ),
3604            skeleton_row(
3605                "lambda",
3606                Some("factory"),
3607                "function",
3608                "lambda_7",
3609                "lambda v: v",
3610                (7, 7),
3611                None,
3612            ),
3613        ];
3614        for symbol in &mut syms {
3615            symbol.language = "python".into();
3616        }
3617
3618        let skeleton = format_file_skeleton("app.py", &syms, Some(9), 0);
3619
3620        assert!(
3621            skeleton.contains("def create_app() { /* 8 lines hidden: L2-L9; defines `hello` */ }"),
3622            "{skeleton}"
3623        );
3624
3625        for symbol in &mut syms {
3626            symbol.language = "cpp".into();
3627        }
3628        let cpp = format_file_skeleton("app.cpp", &syms, Some(9), 0);
3629        assert!(!cpp.contains("defines"), "{cpp}");
3630        syms[1].test_container = true;
3631        let cpp_section = format_file_skeleton("app.cpp", &syms, Some(9), 0);
3632        assert!(cpp_section.contains("defines `hello`"), "{cpp_section}");
3633    }
3634
3635    #[test]
3636    fn skeleton_keeps_plain_fields_and_function_locals_unchanged() {
3637        let syms = vec![
3638            skeleton_row(
3639                "cfg",
3640                None,
3641                "struct",
3642                "Config",
3643                "pub struct Config",
3644                (1, 3),
3645                None,
3646            ),
3647            skeleton_row(
3648                "retries",
3649                Some("cfg"),
3650                "field",
3651                "retries",
3652                "pub retries: u32",
3653                (2, 2),
3654                None,
3655            ),
3656            skeleton_row(
3657                "run",
3658                None,
3659                "function",
3660                "run",
3661                "pub fn run()",
3662                (5, 9),
3663                Some((6, 8)),
3664            ),
3665            skeleton_row(
3666                "tmp",
3667                Some("run"),
3668                "variable",
3669                "tmp",
3670                "let tmp",
3671                (7, 7),
3672                None,
3673            ),
3674        ];
3675
3676        assert_eq!(
3677            format_file_skeleton("src/lib.rs", &syms, Some(9), 0),
3678            "// File: src/lib.rs (Lines 1-9)\n\
3679             \n\
3680             pub struct Config {\n\
3681             \x20   pub retries: u32; // L2-2\n\
3682             } // L1-3\n\
3683             \n\
3684             pub fn run() { /* 3 lines hidden: L6-L8 */ }\n"
3685        );
3686    }
3687
3688    #[test]
3689    fn skeleton_marks_an_event_row_whose_signature_does_not_spell_it() {
3690        let syms = vec![
3691            skeleton_row(
3692                "cls",
3693                None,
3694                "class",
3695                "ColumnViewAttached",
3696                "class ColumnViewAttached : public QObject",
3697                (11, 52),
3698                None,
3699            ),
3700            skeleton_row(
3701                "sig",
3702                Some("cls"),
3703                "event",
3704                "indexChanged",
3705                "void indexChanged()",
3706                (47, 47),
3707                None,
3708            ),
3709            skeleton_row(
3710                "qml",
3711                None,
3712                "event",
3713                "clicked",
3714                "signal clicked()",
3715                (60, 60),
3716                None,
3717            ),
3718        ];
3719
3720        assert_eq!(
3721            format_file_skeleton("src/columnview.h", &syms, Some(60), 0),
3722            "// File: src/columnview.h (Lines 1-60)\n\
3723             \n\
3724             class ColumnViewAttached : public QObject {\n\
3725             \x20   void indexChanged(); // event L47-47\n\
3726             } // L11-52\n\
3727             \n\
3728             signal clicked(); // L60-60\n"
3729        );
3730    }
3731
3732    fn labeled_site(
3733        label: SiteLabel,
3734        path: &str,
3735        line: usize,
3736        caller: &str,
3737        basis: &str,
3738    ) -> LabeledSite {
3739        LabeledSite {
3740            site: ReferenceSite {
3741                from_symbol_name: caller.into(),
3742                from_symbol_id: "c1".into(),
3743                to_symbol_name: "target".into(),
3744                kind: "calls".into(),
3745                path: path.into(),
3746                start_line: Some(line),
3747                start_column: Some(4),
3748                occurrences: None,
3749                target: None,
3750                enclosing_symbol_name: None,
3751            },
3752            label,
3753            basis: basis.into(),
3754            end_line: None,
3755            arg_count: None,
3756        }
3757    }
3758
3759    fn report_of(sites: Vec<LabeledSite>) -> ReferenceReport {
3760        let count = |label| sites.iter().filter(|site| site.label == label).count();
3761        ReferenceReport {
3762            target: ReferenceTarget {
3763                symbol_id: "t1".into(),
3764                name: "from_mapping".into(),
3765                display_name: "Config.from_mapping".into(),
3766                kind: "method".into(),
3767                path: "src/flask/config.py".into(),
3768                line: 304,
3769                definitions_with_name: 1,
3770            },
3771            counts: ReferenceCounts {
3772                sites: sites.len(),
3773                proven: count(SiteLabel::Proven),
3774                likely: count(SiteLabel::Likely),
3775                unresolved: count(SiteLabel::Unresolved),
3776                excluded: count(SiteLabel::Excluded),
3777                text_lines: sites.len(),
3778                site_lines: sites.len(),
3779                ..ReferenceCounts::default()
3780            },
3781            sites,
3782            text_only: Vec::new(),
3783            text_scan: TextScanSummary {
3784                files_scanned: 12,
3785                files_total: 12,
3786                complete: true,
3787                elapsed_ms: 40,
3788                skipped: None,
3789            },
3790            cannot_see: Vec::new(),
3791            imports: Vec::new(),
3792            overrides: Vec::new(),
3793            overridden: Vec::new(),
3794            constructions: Vec::new(),
3795            variant_uses: Vec::new(),
3796            registrations: Vec::new(),
3797            tests: Vec::new(),
3798        }
3799    }
3800
3801    #[test]
3802    fn the_report_header_has_three_lines_with_plural_counts() {
3803        let mut report = report_of(vec![
3804            labeled_site(
3805                SiteLabel::Proven,
3806                "src/flask/config.py",
3807                302,
3808                "Config.from_file",
3809                "same file",
3810            ),
3811            labeled_site(
3812                SiteLabel::Likely,
3813                "tests/test_config.py",
3814                112,
3815                "test_config",
3816                "name only",
3817            ),
3818        ]);
3819        report.counts.text_lines = 17;
3820        report.counts.site_lines = 2;
3821        report.counts.definition_lines = 2;
3822        report.counts.import_lines = 0;
3823        report.counts.text_only_lines = 13;
3824
3825        let text = format_reference_report(&report, 20);
3826
3827        assert_eq!(
3828            text.lines().take(3).collect::<Vec<_>>(),
3829            [
3830                "References to method `Config.from_mapping` (src/flask/config.py:304)",
3831                "Sites: 2 · proven 1 · likely 1 · unresolved 0 · excluded 0",
3832                "Text: `from_mapping` is on 17 lines: 2 sites, 2 definitions, 0 imports, 13 text only.",
3833            ]
3834        );
3835    }
3836
3837    #[test]
3838    fn the_report_header_uses_singular_forms_for_a_count_of_one() {
3839        let mut report = report_of(vec![labeled_site(
3840            SiteLabel::Proven,
3841            "a.py",
3842            3,
3843            "caller",
3844            "same file",
3845        )]);
3846        report.counts.text_lines = 1;
3847        report.counts.site_lines = 1;
3848        report.counts.definition_lines = 1;
3849        report.counts.import_lines = 1;
3850        report.counts.text_only_lines = 0;
3851
3852        let text = format_reference_report(&report, 20);
3853
3854        assert_eq!(
3855            text.lines().nth(2),
3856            Some("Text: `from_mapping` is on 1 line: 1 site, 1 definition, 1 import, 0 text only.")
3857        );
3858    }
3859
3860    #[test]
3861    fn the_report_lists_each_group_in_label_order_with_its_basis() {
3862        let report = report_of(vec![
3863            labeled_site(SiteLabel::Proven, "a.py", 2, "first", "same file"),
3864            labeled_site(SiteLabel::Likely, "l.py", 6, "second", "name only"),
3865            labeled_site(SiteLabel::Unresolved, "u.py", 4, "third", "3 definitions"),
3866            labeled_site(SiteLabel::Excluded, "x.py", 9, "other", "other language"),
3867        ]);
3868
3869        let text = format_reference_report(&report, 20);
3870
3871        let body = text.split_once("\n\n").unwrap().1;
3872        assert_eq!(
3873            body,
3874            "Proven (1):\n\
3875             - `first` [a.py:2] (kind: calls; same file)\n\
3876             Likely (1):\n\
3877             - `second` [l.py:6] (kind: calls; name only)\n\
3878             Unresolved (1):\n\
3879             - `third` [u.py:4] (kind: calls; 3 definitions)\n\
3880             Excluded (1):\n\
3881             - `other` [x.py:9] (kind: calls; other language)\n"
3882        );
3883    }
3884
3885    #[test]
3886    fn a_group_with_no_sites_is_left_out() {
3887        let report = report_of(vec![labeled_site(
3888            SiteLabel::Likely,
3889            "l.py",
3890            6,
3891            "second",
3892            "name only",
3893        )]);
3894
3895        let text = format_reference_report(&report, 20);
3896
3897        assert!(!text.contains("Proven ("), "{text}");
3898        assert!(!text.contains("Excluded ("), "{text}");
3899        assert!(text.contains("Likely (1):\n"), "{text}");
3900    }
3901
3902    #[test]
3903    fn a_report_without_sites_has_only_the_header() {
3904        let report = report_of(Vec::new());
3905
3906        let text = format_reference_report(&report, 20);
3907
3908        assert_eq!(
3909            text,
3910            "References to method `Config.from_mapping` (src/flask/config.py:304)\n\
3911             Sites: 0 · proven 0 · likely 0 · unresolved 0 · excluded 0\n\
3912             Text: `from_mapping` is on 0 lines: 0 sites, 0 definitions, 0 imports, 0 text only.\n"
3913        );
3914    }
3915
3916    #[test]
3917    fn caller_names_follow_the_lambda_and_no_enclosing_symbol_rules() {
3918        let mut lambda = labeled_site(SiteLabel::Proven, "a.py", 1, "lambda_7", "same file");
3919        lambda.site.enclosing_symbol_name = Some("outer".into());
3920        let callerless = labeled_site(SiteLabel::Proven, "a.py", 2, "", "same file");
3921        let report = report_of(vec![lambda, callerless]);
3922
3923        let text = format_reference_report(&report, 20);
3924
3925        assert!(
3926            text.contains("- `<lambda> in outer` [a.py:1] (kind: calls; same file)\n"),
3927            "{text}"
3928        );
3929        assert!(
3930            text.contains("- (no enclosing symbol) [a.py:2] (kind: calls; same file)\n"),
3931            "{text}"
3932        );
3933    }
3934
3935    #[test]
3936    fn rows_past_the_limit_fold_into_one_line_per_label_with_per_file_counts() {
3937        let mut sites = vec![labeled_site(
3938            SiteLabel::Proven,
3939            "a.py",
3940            1,
3941            "p1",
3942            "same file",
3943        )];
3944        for (index, path) in ["b.py", "b.py", "b.py", "c.py", "c.py", "d.py"]
3945            .iter()
3946            .enumerate()
3947        {
3948            sites.push(labeled_site(
3949                SiteLabel::Likely,
3950                path,
3951                10 + index,
3952                "caller",
3953                "name only",
3954            ));
3955        }
3956        sites.push(labeled_site(
3957            SiteLabel::Excluded,
3958            "z.py",
3959            1,
3960            "other",
3961            "other language",
3962        ));
3963        let report = report_of(sites);
3964
3965        let text = format_reference_report(&report, 3);
3966
3967        let body = text.split_once("\n\n").unwrap().1;
3968        assert_eq!(
3969            body,
3970            "Proven (1):\n\
3971             - `p1` [a.py:1] (kind: calls; same file)\n\
3972             Likely (6):\n\
3973             - `caller` [b.py:10] (kind: calls; name only)\n\
3974             - `caller` [b.py:11] (kind: calls; name only)\n\
3975             … 4 more likely sites in 3 files: c.py (2), b.py (1), d.py (1)\n\
3976             Excluded (1):\n\
3977             … 1 more excluded site in 1 file: z.py (1)\n"
3978        );
3979    }
3980
3981    #[test]
3982    fn a_fold_line_names_at_most_five_files() {
3983        let sites = ["a", "b", "c", "d", "e", "f", "g"]
3984            .iter()
3985            .map(|stem| {
3986                labeled_site(
3987                    SiteLabel::Likely,
3988                    &format!("{stem}.py"),
3989                    1,
3990                    "caller",
3991                    "name only",
3992                )
3993            })
3994            .collect();
3995        let report = report_of(sites);
3996
3997        let text = format_reference_report(&report, 1);
3998
3999        assert!(
4000            text.contains(
4001                "… 6 more likely sites in 6 files: b.py (1), c.py (1), d.py (1), e.py (1), f.py (1), …\n"
4002            ),
4003            "{text}"
4004        );
4005    }
4006
4007    #[test]
4008    fn text_only_lines_list_per_file_and_fold_past_ten_files_and_twelve_lines() {
4009        let mut report = report_of(Vec::new());
4010        report.text_only = (0..12)
4011            .map(|index| TextOnlyLines {
4012                path: format!("docs/f{index:02}.rst"),
4013                lines: if index == 0 {
4014                    (1..=15).collect()
4015                } else {
4016                    vec![index + 1, index + 2]
4017                },
4018            })
4019            .collect();
4020        report.counts.text_only_lines = report.text_only.iter().map(|f| f.lines.len()).sum();
4021
4022        let text = format_reference_report(&report, 20);
4023
4024        let section = text.split_once("Text only (").unwrap().1;
4025        let mut lines = section.lines();
4026        assert_eq!(
4027            lines.next(),
4028            Some("37): docs, comments, strings, or code the index did not record")
4029        );
4030        assert_eq!(
4031            lines.next(),
4032            Some("  docs/f00.rst: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12")
4033        );
4034        assert_eq!(lines.next(), Some("  docs/f01.rst: 2, 3"));
4035        assert_eq!(lines.nth(7), Some("  docs/f09.rst: 10, 11"));
4036        assert_eq!(lines.next(), Some("  … 7 more lines in 3 files"));
4037        assert_eq!(lines.next(), None);
4038    }
4039
4040    #[test]
4041    fn a_text_scan_cut_by_its_budget_adds_the_stopped_line() {
4042        let mut report = report_of(Vec::new());
4043        report.text_scan = TextScanSummary {
4044            files_scanned: 410,
4045            files_total: 17334,
4046            complete: false,
4047            elapsed_ms: 3012,
4048            skipped: None,
4049        };
4050
4051        let text = format_reference_report(&report, 20);
4052
4053        assert_eq!(
4054            text.lines().nth(3),
4055            Some("Text scan stopped after 3 s: 410 of 17334 files read; counts cover those files.")
4056        );
4057    }
4058
4059    #[test]
4060    fn a_registration_without_a_verb_or_template_or_route_pattern_prints_what_it_has() {
4061        let registration =
4062            |pattern_id: &str, verb: Option<&str>, template: Option<&str>| Registration {
4063                pattern_id: pattern_id.into(),
4064                verb: verb.map(Into::into),
4065                template: template.map(Into::into),
4066                path: "app.py".into(),
4067                line: 3,
4068                by_name: false,
4069            };
4070        let mut report = report_of(Vec::new());
4071        report.registrations = vec![
4072            registration("flask.route.v1", Some("GET"), Some("/a")),
4073            registration("axum.route.v1", None, Some("/b")),
4074            registration("hapi.route.v1", Some("PUT"), None),
4075            registration("rocket.mount.v1", Some("GET"), Some("/c")),
4076        ];
4077
4078        let text = format_reference_report(&report, 20);
4079
4080        assert!(
4081            text.contains(
4082                "Registrations (4):\n\
4083                 - route GET /a [app.py:3]\n\
4084                 - route /b [app.py:3]\n\
4085                 - route PUT hapi.route.v1 [app.py:3]\n\
4086                 - rocket.mount.v1 [app.py:3]\n"
4087            ),
4088            "{text}"
4089        );
4090    }
4091
4092    #[test]
4093    fn a_constructor_report_replaces_the_text_line_with_the_skip_line() {
4094        let mut report = report_of(Vec::new());
4095        report.text_scan.skipped = Some("Flask".into());
4096
4097        let text = format_reference_report(&report, 20);
4098
4099        assert_eq!(
4100            text.lines().nth(2),
4101            Some(
4102                "Text: skipped for a constructor; its call sites spell the class name. Use find_references on `Flask`."
4103            )
4104        );
4105        assert!(!text.contains("is on"), "{text}");
4106        assert!(!text.contains("Text scan stopped"), "{text}");
4107    }
4108
4109    #[test]
4110    fn the_report_ends_with_the_blind_spots_and_the_import_summary() {
4111        let mut report = report_of(vec![labeled_site(
4112            SiteLabel::Proven,
4113            "a.py",
4114            2,
4115            "first",
4116            "same file",
4117        )]);
4118        report.cannot_see = vec![
4119            "calls through getattr() or names built at runtime".into(),
4120            "calls inside macro bodies".into(),
4121        ];
4122        report.imports = vec![("b.py".into(), 1), ("c.py".into(), 4)];
4123
4124        let text = format_reference_report(&report, 20);
4125
4126        assert!(
4127            text.ends_with(
4128                "Not visible to this index: calls through getattr() or names built at runtime; calls inside macro bodies.\n\
4129                 Imported 2 times in 2 files: b.py:1, c.py:4 (lookup_symbol with kind=\"import\" lists them)\n"
4130            ),
4131            "{text}"
4132        );
4133    }
4134}