Skip to main content

code_kb_core/
formatters.rs

1use std::collections::{BTreeMap, HashMap};
2use std::path::Path;
3
4use crate::models::{
5    BlastRadiusResult, ContextSlice, ImpactedSymbol, ReferenceSite, SearchExplain, Symbol,
6    SymbolSearchResult, TestTarget,
7};
8
9/// Format progressive disclosure file skeleton with implementation bodies stripped.
10pub fn format_file_skeleton(
11    file_path: &str,
12    symbols: &[Symbol],
13    line_count: Option<usize>,
14    parse_errors: usize,
15) -> String {
16    let mut out = String::new();
17    let lines_str = match line_count {
18        Some(c) => format!(" (Lines 1-{c})"),
19        None => String::new(),
20    };
21    out.push_str(&format!("// File: {file_path}{lines_str}\n\n"));
22
23    if parse_errors > 0 {
24        let noun = if parse_errors == 1 { "error" } else { "errors" };
25        out.push_str(&format!(
26            "// {parse_errors} parse {noun}: symbols may be incomplete\n\n"
27        ));
28    }
29
30    if symbols.is_empty() {
31        out.push_str("// No exported symbols indexed.\n");
32        return out;
33    }
34
35    // Group symbols by parent to render hierarchically
36    let mut children_map: HashMap<Option<String>, Vec<&Symbol>> = HashMap::new();
37    for s in symbols {
38        children_map
39            .entry(s.parent_symbol_id.clone())
40            .or_default()
41            .push(s);
42    }
43
44    // Render top-level symbols and their children
45    if let Some(roots) = children_map.get(&None) {
46        for root in roots {
47            render_symbol_skeleton(&mut out, root, &children_map, 0);
48        }
49    } else {
50        // If parent relationships are missing or flat, render all sorted by line
51        for s in symbols {
52            render_symbol_skeleton(&mut out, s, &children_map, 0);
53        }
54    }
55
56    out
57}
58
59fn is_container_kind(kind: &str) -> bool {
60    let hides_its_body = matches!(
61        kind,
62        "function" | "method" | "constructor" | "destructor" | "operator"
63    );
64    !is_skippable_kind(kind) && !hides_its_body
65}
66
67fn is_skippable_kind(kind: &str) -> bool {
68    matches!(kind, "variable" | "parameter" | "import")
69}
70
71fn sanitize_skeleton_sig<'a>(sig: &'a str, sym: &'a Symbol) -> &'a str {
72    let expression_arrow = if sym.language == "csharp"
73        && matches!(
74            sym.kind.as_str(),
75            "method" | "function" | "constructor" | "operator"
76        ) {
77        sig.match_indices("=>")
78            .find_map(|(idx, _)| sig[..idx].trim_end().ends_with(')').then_some(idx))
79    } else {
80        None
81    };
82    let cutoff = sig
83        .find('{')
84        .into_iter()
85        .chain(expression_arrow)
86        .min()
87        .unwrap_or(sig.len());
88    let clean = sig[..cutoff].trim_end();
89    let trimmed = clean.trim_end_matches(';').trim_end();
90    if trimmed.is_empty() {
91        &sym.name
92    } else {
93        trimmed
94    }
95}
96
97fn signature_without_duplicate_body<'a>(signature: &'a str, body: &str) -> &'a str {
98    let body = body.trim();
99    if body.is_empty() {
100        return signature;
101    }
102
103    let trimmed_signature = signature.trim_end();
104    trimmed_signature
105        .strip_suffix(body)
106        .map(str::trim_end)
107        .unwrap_or(signature)
108}
109
110/// The kind word for a leaf row whose signature does not spell it. A C++ Qt signal is declared
111/// under a `Q_SIGNALS:` label, so its signature reads like a method; the `event` kind goes into
112/// the trailing comment instead.
113fn unspelled_kind(sym: &Symbol) -> &'static str {
114    if sym.kind != "event" {
115        return "";
116    }
117    let spelled = sym.signature.as_deref().is_some_and(|sig| {
118        sig.split_whitespace()
119            .any(|word| word == "signal" || word == "event")
120    });
121    if spelled { "" } else { "event " }
122}
123
124fn render_symbol_skeleton(
125    out: &mut String,
126    sym: &Symbol,
127    children_map: &HashMap<Option<String>, Vec<&Symbol>>,
128    indent_level: usize,
129) {
130    if is_skippable_kind(&sym.kind) {
131        return;
132    }
133
134    let indent = "    ".repeat(indent_level);
135
136    // Doc comment: cap at 3 lines to prevent dumping huge blocks
137    if let Some(ref doc) = sym.doc_comment {
138        let lines: Vec<_> = doc.lines().collect();
139        let cap = 3;
140        for line in lines.iter().take(cap) {
141            out.push_str(&format!("{indent}/// {line}\n"));
142        }
143        if lines.len() > cap {
144            out.push_str(&format!(
145                "{indent}/// ... ({} more lines)\n",
146                lines.len() - cap
147            ));
148        }
149    }
150
151    let span_str = format!("L{}-{}", sym.start_line, sym.end_line);
152    let leaf_note = format!("{}{span_str}", unspelled_kind(sym));
153
154    let children = children_map.get(&Some(sym.symbol_id.clone()));
155
156    let spans_multiple_lines = sym.end_line > sym.start_line;
157
158    if is_container_kind(&sym.kind)
159        && children.is_some()
160        && (spans_multiple_lines || sym.kind == "enum")
161    {
162        let raw_sig = sym.signature.as_deref().unwrap_or(&sym.name);
163        let sig = sanitize_skeleton_sig(raw_sig, sym);
164        out.push_str(&format!("{indent}{sig} {{\n"));
165        if let Some(child_list) = children {
166            for child in child_list {
167                render_symbol_skeleton(out, child, children_map, indent_level + 1);
168            }
169        }
170        out.push_str(&format!("{indent}}} // {span_str}\n\n"));
171    } else {
172        if let Some(count) = sym.hidden_body_line_count() {
173            let raw_sig = sym.signature.as_deref().unwrap_or(&sym.name);
174            let sig = sanitize_skeleton_sig(raw_sig, sym);
175            let b_start = sym.body_start_line.unwrap_or(sym.start_line);
176            let b_end = sym.body_end_line.unwrap_or(sym.end_line);
177
178            if count > 1 {
179                out.push_str(&format!(
180                    "{indent}{sig} {{ /* {count} lines hidden: L{b_start}-L{b_end} */ }}\n"
181                ));
182            } else {
183                out.push_str(&format!("{indent}{sig}; // {leaf_note}\n"));
184            }
185        } else if let Some(ref raw_sig) = sym.signature {
186            let sig = sanitize_skeleton_sig(raw_sig, sym);
187            out.push_str(&format!("{indent}{sig}; // {leaf_note}\n"));
188        } else {
189            out.push_str(&format!(
190                "{indent}{} {sym_name}; // {span_str}\n",
191                sym.kind,
192                sym_name = sym.name
193            ));
194        }
195        if sym.kind == "namespace"
196            && let Some(child_list) = children
197        {
198            for child in child_list {
199                render_symbol_skeleton(out, child, children_map, indent_level);
200            }
201        }
202    }
203}
204
205/// Node representing directory or file in codebase outline tree.
206#[derive(Default)]
207pub struct OutlineNode {
208    pub files: BTreeMap<String, Vec<String>>, // file_name -> list of top symbol names with kinds
209    pub subdirs: BTreeMap<String, OutlineNode>,
210}
211
212/// Add a file path into the outline tree, bounded by max_depth.
213pub fn add_path_to_outline(
214    root_node: &mut OutlineNode,
215    file_path: &str,
216    symbols_by_file: &HashMap<String, Vec<Symbol>>,
217    max_depth: usize,
218    norm_filter: &str,
219) {
220    let normalized = file_path.replace('\\', "/");
221    let rel_path_str = if norm_filter.is_empty() {
222        normalized.as_str()
223    } else if normalized.eq_ignore_ascii_case(norm_filter) {
224        Path::new(&normalized)
225            .file_name()
226            .and_then(|n| n.to_str())
227            .unwrap_or(&normalized)
228    } else if normalized.len() > norm_filter.len()
229        && normalized.as_bytes()[norm_filter.len()] == b'/'
230        && normalized[..norm_filter.len()].eq_ignore_ascii_case(norm_filter)
231    {
232        &normalized[norm_filter.len() + 1..]
233    } else {
234        return;
235    };
236
237    let path = Path::new(rel_path_str);
238    let components: Vec<&str> = path
239        .components()
240        .map(|c| c.as_os_str().to_str().unwrap_or(""))
241        .filter(|s| !s.is_empty())
242        .collect();
243
244    if components.is_empty() {
245        return;
246    }
247
248    let mut curr = root_node;
249    let depth = components.len();
250
251    for (i, comp) in components.iter().enumerate() {
252        if i == depth - 1 {
253            // Leaf file: only insert if it is within max_depth
254            if depth <= max_depth {
255                let mut sym_tags = Vec::new();
256                if let Some(syms) = symbols_by_file.get(&normalized) {
257                    for s in syms.iter().take(5) {
258                        sym_tags.push(format!("{} {}", s.kind, s.name));
259                    }
260                    if syms.len() > 5 {
261                        sym_tags.push(format!("+{} more", syms.len() - 5));
262                    }
263                }
264                if !sym_tags.is_empty() {
265                    curr.files.insert(comp.to_string(), sym_tags);
266                }
267            }
268        } else if i < max_depth {
269            curr = curr.subdirs.entry(comp.to_string()).or_default();
270        } else {
271            break;
272        }
273    }
274}
275
276pub fn render_outline_tree(
277    out: &mut String,
278    node: &OutlineNode,
279    prefix: &str,
280    depth: usize,
281    max_depth: usize,
282) {
283    if depth >= max_depth {
284        return;
285    }
286
287    let total_items = node.subdirs.len() + node.files.len();
288    let mut index = 0;
289
290    // Render subdirectories
291    for (name, sub) in &node.subdirs {
292        index += 1;
293        let is_last = index == total_items;
294        let branch = if is_last { "└── " } else { "├── " };
295        let next_prefix = format!("{}{}", prefix, if is_last { "    " } else { "│   " });
296
297        out.push_str(&format!("{prefix}{branch}{name}/\n"));
298        render_outline_tree(out, sub, &next_prefix, depth + 1, max_depth);
299    }
300
301    // Render files
302    for (file_name, syms) in &node.files {
303        index += 1;
304        let is_last = index == total_items;
305        let branch = if is_last { "└── " } else { "├── " };
306
307        let sym_suffix = if !syms.is_empty() {
308            format!(" [{}]", syms.join(", "))
309        } else {
310            String::new()
311        };
312
313        out.push_str(&format!("{prefix}{branch}{file_name}{sym_suffix}\n"));
314    }
315}
316
317/// Format symbol body with metadata header, signature, and body content.
318pub fn format_symbol_body(symbol: &Symbol, body: &str) -> String {
319    let mut out = format!(
320        "// {}:{}-{} ({})\n",
321        symbol.path, symbol.start_line, symbol.end_line, symbol.name
322    );
323    if let Some(ref sig) = symbol.signature {
324        let sig = signature_without_duplicate_body(sig, body);
325        out.push_str(sig);
326        if !sig.ends_with('\n') {
327            out.push('\n');
328        }
329    }
330    out.push_str(body);
331    if !body.ends_with('\n') {
332        out.push('\n');
333    }
334    out
335}
336
337/// Format surgical context bundle for a symbol.
338pub fn format_context_slice(slice: &ContextSlice) -> String {
339    let sym = &slice.target_symbol;
340    let mut out = String::new();
341    out.push_str(&format!(
342        "### Target: `{}` ({}:{}-{})\n\n",
343        sym.name, sym.path, sym.start_line, sym.end_line
344    ));
345
346    if let Some(ref sig) = sym.signature {
347        let sig = signature_without_duplicate_body(sig, &slice.target_body);
348        out.push_str(&format!("Signature: `{sig}`\n\n"));
349    }
350
351    out.push_str(&format!("```{}\n", sym.language));
352    out.push_str(&slice.target_body);
353    if !slice.target_body.ends_with('\n') {
354        out.push('\n');
355    }
356    out.push_str("```\n\n");
357
358    if !slice.callee_signatures.is_empty() {
359        out.push_str("### Dependencies (Signatures):\n");
360        for callee in &slice.callee_signatures {
361            out.push_str(&format!("- {callee}\n"));
362        }
363        if slice.callee_signatures.len() >= 10 {
364            out.push_str("[Showing 10 dependencies (limit reached)]\n");
365        }
366        out.push('\n');
367    }
368
369    if !slice.related_types.is_empty() {
370        out.push_str("### Types:\n");
371        for t in &slice.related_types {
372            out.push_str(&format!("- {t}\n"));
373        }
374        out.push('\n');
375    }
376
377    if !slice.related_tests.is_empty() {
378        out.push_str("### Related Tests:\n");
379        for test in &slice.related_tests {
380            out.push_str(&format!(
381                "- `{}` ({}:{})\n",
382                test.name, test.path, test.start_line
383            ));
384        }
385        if slice.related_tests.len() >= 5 {
386            out.push_str("[Showing 5 tests (limit reached)]\n");
387        }
388        out.push('\n');
389    }
390
391    out
392}
393
394fn cap_notice(shown: usize, limit: usize) -> String {
395    let advice = if limit >= crate::queries::MAX_RESULT_LIMIT {
396        "narrow the query to see more"
397    } else {
398        "increase limit to see more"
399    };
400    format!("\n[Showing {shown} results (limit reached); {advice}.]\n")
401}
402
403/// Format references list for callers/callees with optional limit footer.
404pub fn format_references(
405    target_name: &str,
406    refs: &[ReferenceSite],
407    direction: &str,
408    limit: usize,
409) -> String {
410    let mut out = String::new();
411    let dir_label = if direction == "callers" {
412        "Callers of"
413    } else {
414        "Callees called by"
415    };
416    out.push_str(&format!(
417        "{dir_label} `{target_name}` ({} found):\n",
418        refs.len()
419    ));
420
421    if refs.is_empty() {
422        out.push_str("  (none)\n");
423        return out;
424    }
425
426    for r in refs {
427        let line_info = match r.start_line {
428            Some(l) => format!(":{l}"),
429            None => String::new(),
430        };
431        let other = if direction == "callers" {
432            &r.from_symbol_name
433        } else {
434            &r.to_symbol_name
435        };
436        let in_file = match r.occurrences {
437            Some(n) => format!(", {n} in file"),
438            None => String::new(),
439        };
440        out.push_str(&format!(
441            "- `{other}` [{}{line_info}] (kind: {}{in_file})\n",
442            r.path, r.kind
443        ));
444    }
445
446    if refs.len() >= limit {
447        out.push_str(&cap_notice(refs.len(), limit));
448    }
449
450    out
451}
452
453/// Formats exact or FTS fallback symbol results with transparent header labeling.
454pub fn format_find_symbol_results(
455    query: &str,
456    exact_matches: &[Symbol],
457    fts_matches: &[SymbolSearchResult],
458    limit: usize,
459) -> String {
460    if !exact_matches.is_empty() {
461        let mut out = format!(
462            "Found {} symbols matching \"{query}\":\n\n",
463            exact_matches.len()
464        );
465        for s in exact_matches {
466            let sig = s.signature.as_deref().unwrap_or(&s.name);
467            out.push_str(&format!(
468                "- {} `{}` [{}:{}-{}] id={}\n",
469                s.kind, s.name, s.path, s.start_line, s.end_line, s.symbol_id
470            ));
471            out.push_str(&format!("  Signature: {sig}\n"));
472            if let Some(doc) = &s.doc_comment {
473                let first = doc.lines().next().unwrap_or("").trim();
474                if !first.is_empty() {
475                    out.push_str(&format!("  Doc: {first}\n"));
476                }
477            }
478        }
479        if exact_matches.len() >= limit {
480            out.push_str(&cap_notice(exact_matches.len(), limit));
481        }
482        out
483    } else if !fts_matches.is_empty() {
484        let mut out = format!(
485            "No exact name match; {} full-text matches for \"{query}\":\n\n",
486            fts_matches.len()
487        );
488        for r in fts_matches {
489            let s = &r.symbol;
490            let sig = s.signature.as_deref().unwrap_or(&s.name);
491            out.push_str(&format!(
492                "- {} `{}` [{}:{}-{}] (score: {:.2}) id={}\n",
493                s.kind, s.name, s.path, s.start_line, s.end_line, r.score, s.symbol_id
494            ));
495            out.push_str(&format!("  Signature: {sig}\n"));
496            if let Some(snippet) = &r.snippet {
497                let clean = snippet.replace('\r', "").trim().to_string();
498                let first = clean.lines().next().unwrap_or(&clean);
499                out.push_str(&format!("  Match: {first}\n"));
500            } else if let Some(doc) = &s.doc_comment {
501                let first = doc.lines().next().unwrap_or("").trim();
502                if !first.is_empty() {
503                    out.push_str(&format!("  Doc: {first}\n"));
504                }
505            }
506        }
507        if fts_matches.len() >= limit {
508            out.push_str(&cap_notice(fts_matches.len(), limit));
509        }
510        out
511    } else {
512        format!("No symbols found matching \"{query}\".\n")
513    }
514}
515
516/// Format available structural fact & literal categories.
517pub fn format_fact_categories(categories: &[(String, usize)]) -> String {
518    if categories.is_empty() {
519        return "No structural facts or literals indexed in this repository.".to_string();
520    }
521    let mut out = String::new();
522    let aliases = crate::queries::alias_fact_counts(categories);
523    if !aliases.is_empty() {
524        let parts: Vec<String> = aliases
525            .iter()
526            .map(|(alias, patterns, facts)| {
527                format!(
528                    "{alias} ({patterns} {}, {facts} {})",
529                    plural(*patterns, "pattern"),
530                    plural(*facts, "fact")
531                )
532            })
533            .collect();
534        out.push_str(&format!("Aliases: {}\n\n", parts.join(", ")));
535    }
536    out.push_str(&format!(
537        "Available structural fact & literal categories ({} found):\n\n",
538        categories.len()
539    ));
540    for (name, count) in categories {
541        out.push_str(&format!("- `{name}` ({count} occurrences)\n"));
542    }
543    out
544}
545
546fn plural(count: usize, word: &str) -> String {
547    if count == 1 {
548        word.to_string()
549    } else {
550        format!("{word}s")
551    }
552}
553
554/// Format structural facts and matching literals into token-dense markdown.
555pub fn format_structural_facts(
556    facts: &[crate::models::StructuralFact],
557    literals: &[crate::models::LiteralFact],
558    category: &str,
559    limit: usize,
560) -> String {
561    let mut out = format!(
562        "Structural facts for '{category}' ({} found):\n",
563        facts.len()
564    );
565    for f in facts {
566        let label = f.key.as_deref().unwrap_or(&f.capture_name);
567        let details = qt_property_details(f);
568        let parent = f
569            .containing_symbol_name
570            .as_deref()
571            .map(|p| format!(", in: {p}"))
572            .unwrap_or_default();
573        out.push_str(&format!(
574            "- {label} [{}:{}] (pattern: {}{details}{parent})\n",
575            f.path, f.start_line, f.pattern_id
576        ));
577    }
578    if limit > 0 && facts.len() >= limit {
579        out.push_str(&cap_notice(facts.len(), limit));
580    }
581    if !literals.is_empty() {
582        out.push_str(&format!(
583            "\nMatching literals ({} found):\n",
584            literals.len()
585        ));
586        for l in literals {
587            out.push_str(&format!(
588                "- \"{}\" [{}:{}] (kind: {})\n",
589                l.literal_text, l.path, l.start_line, l.kind
590            ));
591        }
592        if limit > 0 && literals.len() >= limit {
593            out.push_str(&cap_notice(literals.len(), limit));
594        }
595    }
596    out
597}
598
599fn qt_property_details(fact: &crate::models::StructuralFact) -> String {
600    if fact.pattern_id != "cpp.qt_property.v1" {
601        return String::new();
602    }
603    let Some(metadata) = fact.metadata.as_ref() else {
604        return String::new();
605    };
606    [
607        "property_type",
608        "read",
609        "write",
610        "notify",
611        "designable",
612        "scriptable",
613        "stored",
614        "user",
615        "revision",
616    ]
617    .into_iter()
618    .filter_map(|key| metadata.get(key).map(|value| (key, value)))
619    .map(|(key, value)| {
620        let value = value
621            .as_str()
622            .map(str::to_owned)
623            .unwrap_or_else(|| value.to_string());
624        format!(", {key}: {value}")
625    })
626    .collect()
627}
628
629/// Formats FTS5 conceptual search results into token-dense markdown.
630pub fn format_search_results(query: &str, results: &[SymbolSearchResult], limit: usize) -> String {
631    if results.is_empty() {
632        return format!("No symbols found matching concept \"{query}\".");
633    }
634
635    let mut out = format!(
636        "Found {} symbols matching concept \"{query}\":\n",
637        results.len()
638    );
639    if let Some(explain) = results.first().and_then(|r| r.explain.as_ref()) {
640        out.push_str(&format!(
641            "rerank: {} candidates in {} µs",
642            explain.candidates, explain.rerank_us
643        ));
644        if !explain.word_weights.is_empty() {
645            let words: Vec<String> = explain
646                .word_weights
647                .iter()
648                .map(|(word, weight)| format!("{word} {weight:.2}"))
649                .collect();
650            out.push_str(&format!("; words {}", words.join(", ")));
651        }
652        out.push('\n');
653    }
654    out.push('\n');
655    for r in results {
656        let s = &r.symbol;
657        let sig = s.signature.as_deref().unwrap_or(&s.name);
658        out.push_str(&format!(
659            "- {} `{}` [{}:{}-{}] (score: {:.2}) id={}\n",
660            s.kind, s.name, s.path, s.start_line, s.end_line, r.score, s.symbol_id
661        ));
662        out.push_str(&format!("  Signature: {sig}\n"));
663        if let Some(snippet) = &r.snippet {
664            let clean_snip = snippet.replace('\r', "").trim().to_string();
665            let first_line = clean_snip.lines().next().unwrap_or(&clean_snip);
666            out.push_str(&format!("  Match: {first_line}\n"));
667        } else if let Some(doc) = &s.doc_comment {
668            let first_line = doc.lines().next().unwrap_or("").trim();
669            if !first_line.is_empty() {
670                out.push_str(&format!("  Doc: {first_line}\n"));
671            }
672        }
673        if let Some(explain) = &r.explain {
674            out.push_str(&format!("  explain: {}\n", explain_line(r.score, explain)));
675        }
676    }
677
678    if results.len() >= limit {
679        out.push_str(&cap_notice(results.len(), limit));
680    }
681
682    out
683}
684
685fn explain_line(score: f64, e: &SearchExplain) -> String {
686    let mut line = format!(
687        "score {score:.1} = terms {:.1} + name {}({}) {:.1} + kind {:.1} + path {:.1}",
688        e.term_score, e.name_tier, e.name_strength, e.name_bonus, e.kind_prior, e.path_role,
689    );
690    if e.documentation != 0.0 {
691        line.push_str(&format!(" + doc {:.1}", e.documentation));
692    }
693    if e.test_intent != 0.0 {
694        line.push_str(&format!(" + test {:.1}", e.test_intent));
695    }
696    line.push_str(&format!(" [{}]", e.branches.join(",")));
697    if let Some(bm25) = e.bm25 {
698        line.push_str(&format!(" bm25 {bm25:.2}"));
699    }
700    if !e.terms.is_empty() {
701        let terms: Vec<String> = e
702            .terms
703            .iter()
704            .map(|(term, field, credit)| format!("{term}={field}:{credit}"))
705            .collect();
706        line.push_str(&format!(" terms {}", terms.join(" ")));
707    }
708    line
709}
710
711/// Format blast radius and likely test targets into token-dense markdown.
712pub fn format_blast_radius(result: &BlastRadiusResult) -> String {
713    if result.seed_type == "none" {
714        return "No uncommitted changes detected in git working tree. Pass a 'symbol' or 'file' parameter to analyze blast radius.".to_string();
715    }
716
717    let mut out = String::new();
718    let seed_label = if result.seed_type == "file" {
719        format!("Files: {}", result.seeds.join(", "))
720    } else if result.seed_type == "symbol" {
721        format!("Symbol: {}", result.seeds.join(", "))
722    } else {
723        format!("Seeds: {}", result.seeds.join(", "))
724    };
725
726    out.push_str(&format!("## Blast Radius & Test Impact ({seed_label})\n\n"));
727
728    const MAX_COMPACT_TESTS: usize = 20;
729    const MAX_COMPACT_IMPACTED: usize = 50;
730
731    if result.likely_tests_truncated {
732        out.push_str("Requested limit hid additional likely tests; increase limit to reveal discovered rows.\n\n");
733    }
734    if result.impacted_symbols_truncated {
735        out.push_str("Requested limit hid additional impacted symbols; increase limit to reveal discovered rows.\n\n");
736    }
737    if result.traversal_ceiling_reached {
738        out.push_str("Traversal stopped at the 200-row discovery ceiling; narrow the target because increasing limit cannot raise this ceiling.\n\n");
739    }
740    if result.test_file_ceiling_reached {
741        out.push_str("Name-matched test discovery hit its fixed ceiling; narrow the target because increasing limit cannot raise it.\n\n");
742    }
743
744    if !result.likely_tests.is_empty() {
745        let total = result.likely_tests.len();
746        if total > MAX_COMPACT_TESTS {
747            out.push_str(&format!(
748                "### Likely Tests to Run ({} returned - showing top {})\n",
749                total, MAX_COMPACT_TESTS
750            ));
751        } else {
752            out.push_str(&format!("### Likely Tests to Run ({} returned)\n", total));
753        }
754
755        let mut tests_by_file: std::collections::BTreeMap<&str, Vec<&TestTarget>> =
756            std::collections::BTreeMap::new();
757        let mut file_order = Vec::new();
758        for t in result.likely_tests.iter().take(MAX_COMPACT_TESTS) {
759            if !tests_by_file.contains_key(t.path.as_str()) {
760                file_order.push(t.path.as_str());
761            }
762            tests_by_file.entry(t.path.as_str()).or_default().push(t);
763        }
764
765        for path in file_order {
766            out.push_str(&format!("{path}:\n"));
767            if let Some(tests) = tests_by_file.get(path) {
768                for t in tests {
769                    out.push_str(&format!(
770                        "  - `{}` [line {}] ({})\n",
771                        t.name, t.line, t.reason
772                    ));
773                }
774            }
775        }
776
777        if total > MAX_COMPACT_TESTS {
778            out.push_str(&format!(
779                "... {} more returned likely tests are hidden by the compact 20-row display. CLI --json shows the full returned list.\n",
780                total - MAX_COMPACT_TESTS
781            ));
782        }
783        out.push('\n');
784    } else if result.likely_tests_truncated
785        || result.traversal_ceiling_reached
786        || result.test_file_ceiling_reached
787    {
788        out.push_str("### Likely Tests to Run (0 returned)\n\n");
789    } else {
790        out.push_str(
791            "### Likely Tests to Run (0 returned)\nNo direct or name-matched tests found.\n\n",
792        );
793    }
794
795    if !result.impacted_symbols.is_empty() {
796        let total = result.impacted_symbols.len();
797        let mut visible = Vec::new();
798        let mut low_signal_count = 0;
799        for s in &result.impacted_symbols {
800            if matches!(s.kind.as_str(), "import" | "module" | "namespace") {
801                low_signal_count += 1;
802            } else {
803                visible.push(s);
804            }
805        }
806
807        out.push_str(&format!("### Downstream Impact ({} returned)\n", total));
808
809        if visible.is_empty() && low_signal_count > 0 {
810            let row_word = if low_signal_count == 1 {
811                "row (import/module)"
812            } else {
813                "rows (imports/modules)"
814            };
815            out.push_str(&format!(
816                "All impacted symbols are imports/modules; {low_signal_count} low-signal {row_word} hidden; available in CLI --json.\n"
817            ));
818        } else {
819            let visible_total = visible.len();
820            let showing_count = visible_total.min(MAX_COMPACT_IMPACTED);
821
822            let mut syms_by_file: std::collections::BTreeMap<&str, Vec<&ImpactedSymbol>> =
823                std::collections::BTreeMap::new();
824            let mut file_order = Vec::new();
825            for s in visible.iter().take(showing_count) {
826                if !syms_by_file.contains_key(s.path.as_str()) {
827                    file_order.push(s.path.as_str());
828                }
829                syms_by_file.entry(s.path.as_str()).or_default().push(s);
830            }
831
832            for path in file_order {
833                out.push_str(&format!("{path}:\n"));
834                if let Some(syms) = syms_by_file.get(path) {
835                    for s in syms {
836                        out.push_str(&format!(
837                            "  - [depth {}] {} `{}` [line {}]\n",
838                            s.depth, s.kind, s.name, s.line
839                        ));
840                    }
841                }
842            }
843
844            if visible_total > MAX_COMPACT_IMPACTED {
845                out.push_str(&format!(
846                    "... {} more returned impacted symbols are hidden by the compact 50-row display. CLI --json shows the full returned list.\n",
847                    visible_total - MAX_COMPACT_IMPACTED
848                ));
849            }
850            if low_signal_count > 0 {
851                let row_word = if low_signal_count == 1 {
852                    "row (import/module)"
853                } else {
854                    "rows (imports/modules)"
855                };
856                out.push_str(&format!(
857                    "... {low_signal_count} low-signal {row_word} hidden; available in CLI --json.\n"
858                ));
859            }
860        }
861    } else if result.impacted_symbols_truncated || result.traversal_ceiling_reached {
862        out.push_str("### Downstream Impact (0 returned)\n");
863    } else {
864        out.push_str(
865            "### Downstream Impact (0 returned)\nNo downstream callers found within depth.\n",
866        );
867    }
868
869    out
870}
871
872#[cfg(test)]
873mod tests {
874    use super::*;
875    use crate::models::{ImpactedSymbol, TestTarget};
876
877    fn structural_fact(key: Option<&str>) -> crate::models::StructuralFact {
878        crate::models::StructuralFact {
879            structural_fact_id: "sf1".into(),
880            path: ".codex/config.toml".into(),
881            language: "toml".into(),
882            pattern_id: "toml.key_value.v1".into(),
883            capture_name: "key_value".into(),
884            node_kind: "table".into(),
885            key: key.map(str::to_string),
886            metadata: None,
887            containing_symbol_name: None,
888            start_line: 2,
889            end_line: 2,
890            confidence: 1.0,
891        }
892    }
893
894    #[test]
895    fn format_structural_facts_prints_key_and_falls_back_to_capture_name() {
896        let with_key = format_structural_facts(
897            &[structural_fact(Some("mcp_servers.code-kb.command"))],
898            &[],
899            "config",
900            30,
901        );
902        assert!(with_key.contains(
903            "- mcp_servers.code-kb.command [.codex/config.toml:2] (pattern: toml.key_value.v1)"
904        ));
905
906        let without_key = format_structural_facts(&[structural_fact(None)], &[], "config", 30);
907        assert!(
908            without_key.contains("- key_value [.codex/config.toml:2] (pattern: toml.key_value.v1)")
909        );
910    }
911
912    #[test]
913    fn format_structural_facts_renders_selected_qt_property_metadata() {
914        let mut fact = structural_fact(Some("index"));
915        fact.pattern_id = "cpp.qt_property.v1".into();
916        fact.metadata = Some(serde_json::json!({
917            "property_type": "int",
918            "designable": false,
919            "scriptable": true,
920            "stored": false,
921            "user": true,
922            "revision": 2,
923        }));
924
925        let output = format_structural_facts(&[fact], &[], "property", 30);
926
927        assert!(output.contains(
928            "property_type: int, designable: false, scriptable: true, stored: false, user: true, revision: 2"
929        ));
930    }
931
932    #[test]
933    fn format_references_reports_the_occurrence_count_of_a_grouped_row() {
934        let site = |occurrences| ReferenceSite {
935            from_symbol_name: "Button".into(),
936            from_symbol_id: "s1".into(),
937            to_symbol_name: "background".into(),
938            kind: "member_access".into(),
939            path: "Ui/Button.qml".into(),
940            start_line: Some(5),
941            start_column: Some(4),
942            occurrences,
943        };
944
945        let grouped = format_references("Color", &[site(Some(6))], "callers", 30);
946        assert!(
947            grouped.contains("- `Button` [Ui/Button.qml:5] (kind: member_access, 6 in file)"),
948            "{grouped}"
949        );
950
951        let single = format_references("Color", &[site(None)], "callers", 30);
952        assert!(
953            single.contains("- `Button` [Ui/Button.qml:5] (kind: member_access)"),
954            "{single}"
955        );
956    }
957
958    #[test]
959    fn file_skeleton_reports_parse_errors() {
960        let two = format_file_skeleton("src/lib.rs", &[], Some(35), 2);
961        assert!(two.contains("// 2 parse errors: symbols may be incomplete"));
962
963        let one = format_file_skeleton("src/lib.rs", &[], Some(35), 1);
964        assert!(one.contains("// 1 parse error: symbols may be incomplete"));
965
966        let none = format_file_skeleton("src/lib.rs", &[], Some(35), 0);
967        assert!(!none.contains("parse error"));
968    }
969
970    #[test]
971    fn test_format_file_skeleton() {
972        let syms = vec![Symbol {
973            symbol_id: "s1".into(),
974            file_id: "f1".into(),
975            path: "src/lib.rs".into(),
976            language: "rust".into(),
977            name: "do_work".into(),
978            kind: "function".into(),
979            signature: Some("pub fn do_work() -> Result<()>".into()),
980            doc_comment: Some("Performs core work.".into()),
981            visibility: Some("pub".into()),
982            parent_symbol_id: None,
983            start_line: 10,
984            start_column: 0,
985            end_line: 30,
986            end_column: 1,
987            start_byte: 100,
988            end_byte: 300,
989            body_start_line: Some(11),
990            body_start_column: Some(0),
991            body_end_line: Some(29),
992            body_end_column: Some(1),
993            body_start_byte: Some(130),
994            body_end_byte: Some(298),
995            body_hash: None,
996            semantic_group: None,
997            is_test: false,
998            test_container: false,
999        }];
1000
1001        let skeleton = format_file_skeleton("src/lib.rs", &syms, Some(35), 0);
1002        assert!(skeleton.contains("/// Performs core work."));
1003        assert!(skeleton.contains("19 lines hidden: L11-L29"));
1004    }
1005
1006    #[test]
1007    fn format_symbol_body_does_not_repeat_expression_already_in_signature() {
1008        let body = "=>\n        transport.SendAsync<OffboardingFormDto>(\n            HttpMethod.Get,\n            $\"ser/{id}\",\n            cancellationToken: cancellationToken)";
1009        let mut symbol = sample_symbol("GetByIdAsync");
1010        symbol.language = "csharp".into();
1011        symbol.signature = Some(format!(
1012            "public Task<OffboardingFormDto?> GetByIdAsync(\n        int id,\n        CancellationToken cancellationToken = default){body}"
1013        ));
1014
1015        let formatted = format_symbol_body(&symbol, body);
1016
1017        assert_eq!(
1018            formatted.matches("transport.SendAsync").count(),
1019            1,
1020            "{formatted}"
1021        );
1022    }
1023
1024    #[test]
1025    fn format_symbol_body_preserves_unmatched_signature_whitespace() {
1026        let mut symbol = sample_symbol("plain");
1027        symbol.signature = Some("pub fn plain()  ".into());
1028
1029        assert_eq!(
1030            format_symbol_body(&symbol, "return 1;"),
1031            "// src/lib.rs:1-10 (plain)\npub fn plain()  \nreturn 1;\n"
1032        );
1033    }
1034
1035    #[test]
1036    fn test_format_search_results() {
1037        let results = vec![SymbolSearchResult {
1038            symbol: Symbol {
1039                symbol_id: "s1".into(),
1040                file_id: "f1".into(),
1041                path: "src/parser.rs".into(),
1042                language: "rust".into(),
1043                name: "parse_tokens".into(),
1044                kind: "function".into(),
1045                signature: Some("pub fn parse_tokens()".into()),
1046                doc_comment: Some("Parses tokens from stream.".into()),
1047                visibility: Some("pub".into()),
1048                parent_symbol_id: None,
1049                start_line: 15,
1050                start_column: 0,
1051                end_line: 25,
1052                end_column: 1,
1053                start_byte: 100,
1054                end_byte: 250,
1055                body_start_line: None,
1056                body_start_column: None,
1057                body_end_line: None,
1058                body_end_column: None,
1059                body_start_byte: None,
1060                body_end_byte: None,
1061                body_hash: None,
1062                semantic_group: None,
1063                is_test: false,
1064                test_container: false,
1065            },
1066            score: -1.85,
1067            snippet: Some("Parses [tokens] from stream.".into()),
1068            explain: None,
1069        }];
1070
1071        let formatted = format_search_results("tokens", &results, 20);
1072        assert!(formatted.contains("Found 1 symbols matching concept \"tokens\":\n\n- "));
1073        assert!(
1074            formatted.contains("- function `parse_tokens` [src/parser.rs:15-25] (score: -1.85)")
1075        );
1076        assert!(formatted.contains("Match: Parses [tokens] from stream."));
1077        assert!(!formatted.contains("explain"));
1078        assert!(!formatted.contains("rerank"));
1079    }
1080
1081    #[test]
1082    fn discovery_formatters_append_ids_to_metadata_rows() {
1083        let exact = vec![sample_symbol("exact")];
1084        let fallback = vec![SymbolSearchResult {
1085            symbol: sample_symbol("fallback"),
1086            score: 1.0,
1087            snippet: None,
1088            explain: None,
1089        }];
1090
1091        let outputs = [
1092            (
1093                format_find_symbol_results("exact", &exact, &[], 20),
1094                "id_exact",
1095            ),
1096            (
1097                format_find_symbol_results("fallback query", &[], &fallback, 20),
1098                "id_fallback",
1099            ),
1100            (
1101                format_search_results("fallback", &fallback, 20),
1102                "id_fallback",
1103            ),
1104        ];
1105
1106        for (formatted, id) in outputs {
1107            assert!(
1108                formatted
1109                    .lines()
1110                    .any(|line| line.starts_with("- ") && line.contains(&format!("id={id}"))),
1111                "{formatted}"
1112            );
1113            assert!(!formatted.contains("\n  id="), "{formatted}");
1114        }
1115    }
1116
1117    #[test]
1118    fn every_printed_part_of_the_explain_line_sums_to_the_score() {
1119        let e = SearchExplain {
1120            bm25: Some(-3.21),
1121            branches: vec!["word".into()],
1122            name_tier: "all".into(),
1123            name_strength: 6,
1124            term_score: 24.5,
1125            name_bonus: 60.0,
1126            kind_prior: 4.0,
1127            path_role: -10.0,
1128            documentation: -200.0,
1129            test_intent: 5.0,
1130            terms: vec![("sha".into(), "name".into(), 3.0)],
1131            word_weights: vec![("sha".into(), 2.6)],
1132            candidates: 1,
1133            rerank_us: 1,
1134        };
1135        let score = e.term_score
1136            + e.name_bonus
1137            + e.kind_prior
1138            + e.path_role
1139            + e.documentation
1140            + e.test_intent;
1141
1142        let line = explain_line(score, &e);
1143        let parts: f64 = line
1144            .split(" = ")
1145            .nth(1)
1146            .unwrap()
1147            .split(" [")
1148            .next()
1149            .unwrap()
1150            .split(" + ")
1151            .map(|part| part.rsplit(' ').next().unwrap().parse::<f64>().unwrap())
1152            .sum();
1153
1154        assert!(line.starts_with(&format!(
1155            "score {score:.1} = terms 24.5 + name all(6) 60.0 "
1156        )));
1157        assert_eq!(format!("{parts:.1}"), format!("{score:.1}"));
1158    }
1159
1160    #[test]
1161    fn test_format_search_results_prints_the_explain_breakdown_when_present() {
1162        let mut result = SymbolSearchResult {
1163            symbol: sample_symbol("parseSha256Sidecar"),
1164            score: 71.6,
1165            snippet: Some("parse[Sha256]Sidecar".into()),
1166            explain: Some(SearchExplain {
1167                bm25: Some(-3.21),
1168                branches: vec!["word".into(), "name".into()],
1169                name_tier: "all".into(),
1170                name_strength: 6,
1171                terms: vec![
1172                    ("sha".into(), "name".into(), 3.0),
1173                    ("256".into(), "name".into(), 3.0),
1174                ],
1175                term_score: 12.6,
1176                name_bonus: 60.0,
1177                kind_prior: 4.0,
1178                path_role: -10.0,
1179                documentation: 0.0,
1180                test_intent: 5.0,
1181                word_weights: vec![("sha".into(), 2.6), ("256".into(), 0.97)],
1182                candidates: 37,
1183                rerank_us: 180,
1184            }),
1185        };
1186
1187        let formatted = format_search_results("sha256", std::slice::from_ref(&result), 20);
1188        assert!(formatted.contains(
1189            "Found 1 symbols matching concept \"sha256\":\nrerank: 37 candidates in 180 µs; words sha 2.60, 256 0.97\n\n- "
1190        ));
1191        assert!(formatted.contains(
1192            "  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"
1193        ));
1194
1195        result.explain = None;
1196        let silent = format_search_results("sha256", std::slice::from_ref(&result), 20);
1197        assert!(!silent.contains("explain"));
1198        assert!(!silent.contains("rerank"));
1199    }
1200
1201    #[test]
1202    fn test_format_search_results_discloses_a_reached_limit() {
1203        let results = vec![SymbolSearchResult {
1204            symbol: sample_symbol("parse_tokens"),
1205            score: 0.0,
1206            snippet: None,
1207            explain: None,
1208        }];
1209
1210        let formatted = format_search_results("tokens", &results, 1);
1211        assert!(
1212            formatted.contains("[Showing 1 results (limit reached); increase limit to see more.]")
1213        );
1214
1215        let at_ceiling =
1216            format_search_results("tokens", &results, crate::queries::MAX_RESULT_LIMIT);
1217        assert!(!at_ceiling.contains("limit reached"));
1218
1219        let full: Vec<SymbolSearchResult> = (0..crate::queries::MAX_RESULT_LIMIT)
1220            .map(|_| SymbolSearchResult {
1221                symbol: sample_symbol("parse_tokens"),
1222                score: 0.0,
1223                snippet: None,
1224                explain: None,
1225            })
1226            .collect();
1227        let capped = format_search_results("tokens", &full, crate::queries::MAX_RESULT_LIMIT);
1228        assert!(capped.contains("(limit reached); narrow the query to see more.]"));
1229    }
1230
1231    #[test]
1232    fn test_format_blast_radius() {
1233        let res = BlastRadiusResult {
1234            seed_type: "symbol".into(),
1235            seeds: vec!["do_work".into()],
1236            likely_tests: vec![TestTarget {
1237                name: "test_do_work".into(),
1238                path: "tests/work_test.rs".into(),
1239                line: 15,
1240                reason: "transitive caller [depth 1]".into(),
1241            }],
1242            impacted_symbols: vec![ImpactedSymbol {
1243                name: "caller_fn".into(),
1244                kind: "function".into(),
1245                path: "src/caller.rs".into(),
1246                line: 42,
1247                depth: 1,
1248            }],
1249            traversal_ceiling_reached: false,
1250            likely_tests_truncated: false,
1251            impacted_symbols_truncated: false,
1252            test_file_ceiling_reached: false,
1253        };
1254
1255        let formatted = format_blast_radius(&res);
1256        assert!(formatted.contains("## Blast Radius & Test Impact (Symbol: do_work)"));
1257        assert!(formatted.contains("### Likely Tests to Run (1 returned)"));
1258        assert!(formatted.contains(
1259            "tests/work_test.rs:\n  - `test_do_work` [line 15] (transitive caller [depth 1])"
1260        ));
1261        assert!(formatted.contains("src/caller.rs:\n  - [depth 1] function `caller_fn` [line 42]"));
1262    }
1263
1264    #[test]
1265    fn test_format_blast_radius_grouped_and_capped() {
1266        let mut likely_tests = Vec::new();
1267        for i in 1..=25 {
1268            likely_tests.push(TestTarget {
1269                name: format!("test_{i}"),
1270                path: format!("tests/test_{}.rs", (i % 3) + 1),
1271                line: i * 10,
1272                reason: "direct caller".into(),
1273            });
1274        }
1275
1276        let impacted_symbols = vec![
1277            ImpactedSymbol {
1278                name: "use_foo".into(),
1279                kind: "import".into(),
1280                path: "src/service.rs".into(),
1281                line: 1,
1282                depth: 1,
1283            },
1284            ImpactedSymbol {
1285                name: "service_fn".into(),
1286                kind: "function".into(),
1287                path: "src/service.rs".into(),
1288                line: 20,
1289                depth: 1,
1290            },
1291            ImpactedSymbol {
1292                name: "api_handler".into(),
1293                kind: "function".into(),
1294                path: "src/api.rs".into(),
1295                line: 45,
1296                depth: 2,
1297            },
1298        ];
1299
1300        let res = BlastRadiusResult {
1301            seed_type: "file".into(),
1302            seeds: vec!["src/lib.rs".into()],
1303            likely_tests,
1304            impacted_symbols,
1305            traversal_ceiling_reached: false,
1306            likely_tests_truncated: false,
1307            impacted_symbols_truncated: false,
1308            test_file_ceiling_reached: false,
1309        };
1310
1311        let formatted = format_blast_radius(&res);
1312
1313        assert!(formatted.contains("### Likely Tests to Run (25 returned - showing top 20)"));
1314        assert!(formatted.contains(
1315            "... 5 more returned likely tests are hidden by the compact 20-row display. CLI --json shows the full returned list."
1316        ));
1317
1318        assert!(formatted.contains("tests/test_1.rs:\n"));
1319        assert!(formatted.contains("  - `test_"));
1320
1321        assert!(!formatted.contains("use_foo"));
1322        assert!(
1323            formatted
1324                .contains("... 1 low-signal row (import/module) hidden; available in CLI --json.")
1325        );
1326        assert!(formatted.contains("src/service.rs:\n"));
1327        assert!(formatted.contains("  - [depth 1] function `service_fn` [line 20]"));
1328    }
1329
1330    fn sample_symbol(name: &str) -> Symbol {
1331        Symbol {
1332            symbol_id: format!("id_{name}"),
1333            file_id: "f1".into(),
1334            path: "src/lib.rs".into(),
1335            language: "rust".into(),
1336            name: name.into(),
1337            kind: "function".into(),
1338            signature: Some(format!("pub fn {name}()")),
1339            doc_comment: None,
1340            visibility: Some("pub".into()),
1341            parent_symbol_id: None,
1342            start_line: 1,
1343            start_column: 0,
1344            end_line: 10,
1345            end_column: 1,
1346            start_byte: 0,
1347            end_byte: 100,
1348            body_start_line: Some(2),
1349            body_start_column: Some(0),
1350            body_end_line: Some(9),
1351            body_end_column: Some(1),
1352            body_start_byte: Some(10),
1353            body_end_byte: Some(99),
1354            body_hash: None,
1355            semantic_group: None,
1356            is_test: false,
1357            test_container: false,
1358        }
1359    }
1360
1361    fn sample_context_slice() -> ContextSlice {
1362        ContextSlice {
1363            target_symbol: sample_symbol("target_fn"),
1364            target_body: "    println!(\"hello\");\n".into(),
1365            callee_signatures: Vec::new(),
1366            related_types: Vec::new(),
1367            related_tests: Vec::new(),
1368        }
1369    }
1370
1371    #[test]
1372    fn format_context_slice_does_not_repeat_expression_already_in_signature() {
1373        let body = "=>\n        transport.SendAsync<Response>(\n            HttpMethod.Get,\n            $\"items/{id}\",\n            cancellationToken: cancellationToken)";
1374        let mut slice = sample_context_slice();
1375        slice.target_symbol.language = "csharp".into();
1376        slice.target_symbol.signature = Some(format!(
1377            "public static Task<Response?> GetByIdAsync(\n        int id,\n        CancellationToken cancellationToken = default){body}"
1378        ));
1379        slice.target_body = body.into();
1380
1381        let formatted = format_context_slice(&slice);
1382
1383        assert_eq!(
1384            formatted.matches("transport.SendAsync").count(),
1385            1,
1386            "{formatted}"
1387        );
1388    }
1389
1390    #[test]
1391    fn test_context_slice_shows_truncation_notice_when_caps_hit() {
1392        let mut slice = sample_context_slice();
1393        slice.callee_signatures = (1..=10).map(|i| format!("fn callee_{i}()")).collect();
1394        let text = format_context_slice(&slice);
1395        assert!(text.contains("[Showing 10 dependencies (limit reached)]"));
1396
1397        let mut slice_tests = sample_context_slice();
1398        slice_tests.related_tests = (1..=5)
1399            .map(|i| {
1400                let mut sym = sample_symbol(&format!("test_fn_{i}"));
1401                sym.path = format!("tests/test_{i}.rs");
1402                sym.is_test = true;
1403                sym
1404            })
1405            .collect();
1406        let text_tests = format_context_slice(&slice_tests);
1407        assert!(text_tests.contains("[Showing 5 tests (limit reached)]"));
1408    }
1409
1410    #[test]
1411    fn test_blast_radius_shows_traversal_ceiling_at_200_symbols() {
1412        let impacted_symbols = (1..=200)
1413            .map(|i| ImpactedSymbol {
1414                name: format!("sym_{i}"),
1415                kind: "function".into(),
1416                path: format!("src/mod_{}.rs", i % 10),
1417                line: i,
1418                depth: 1,
1419            })
1420            .collect();
1421
1422        let res = BlastRadiusResult {
1423            seed_type: "symbol".into(),
1424            seeds: vec!["root_fn".into()],
1425            likely_tests: Vec::new(),
1426            impacted_symbols,
1427            traversal_ceiling_reached: true,
1428            likely_tests_truncated: false,
1429            impacted_symbols_truncated: false,
1430            test_file_ceiling_reached: false,
1431        };
1432
1433        let formatted = format_blast_radius(&res);
1434        assert!(formatted.contains("### Downstream Impact (200 returned)\n"));
1435    }
1436
1437    #[test]
1438    fn blast_radius_does_not_claim_no_results_after_discovery_ceiling() {
1439        let res = BlastRadiusResult {
1440            seed_type: "file".into(),
1441            seeds: vec!["src/widget.rs".into()],
1442            likely_tests: Vec::new(),
1443            impacted_symbols: Vec::new(),
1444            likely_tests_truncated: false,
1445            impacted_symbols_truncated: false,
1446            traversal_ceiling_reached: true,
1447            test_file_ceiling_reached: true,
1448        };
1449
1450        let formatted = format_blast_radius(&res);
1451        assert!(formatted.contains("Likely Tests to Run (0 returned)"));
1452        assert!(formatted.contains("Downstream Impact (0 returned)"));
1453        assert!(formatted.contains("Name-matched test discovery hit its fixed ceiling"));
1454        assert!(!formatted.contains("No direct or name-matched tests found"));
1455        assert!(!formatted.contains("No downstream callers found within depth"));
1456
1457        let no_ceiling = BlastRadiusResult {
1458            traversal_ceiling_reached: false,
1459            test_file_ceiling_reached: false,
1460            ..res.clone()
1461        };
1462        assert!(format_blast_radius(&no_ceiling).contains("No direct or name-matched tests found"));
1463
1464        let traversal_only = BlastRadiusResult {
1465            traversal_ceiling_reached: true,
1466            test_file_ceiling_reached: false,
1467            ..res
1468        };
1469        let traversal_only_text = format_blast_radius(&traversal_only);
1470        assert!(!traversal_only_text.contains("No direct or name-matched tests found"));
1471    }
1472
1473    fn skeleton_row(
1474        id: &str,
1475        parent: Option<&str>,
1476        kind: &str,
1477        name: &str,
1478        signature: &str,
1479        lines: (usize, usize),
1480        body: Option<(usize, usize)>,
1481    ) -> Symbol {
1482        Symbol {
1483            symbol_id: id.into(),
1484            file_id: "f1".into(),
1485            path: "src/lib.rs".into(),
1486            language: "rust".into(),
1487            name: name.into(),
1488            kind: kind.into(),
1489            signature: Some(signature.into()),
1490            doc_comment: None,
1491            visibility: None,
1492            parent_symbol_id: parent.map(str::to_string),
1493            start_line: lines.0,
1494            start_column: 0,
1495            end_line: lines.1,
1496            end_column: 1,
1497            start_byte: 0,
1498            end_byte: 0,
1499            body_start_line: body.map(|b| b.0),
1500            body_start_column: None,
1501            body_end_line: body.map(|b| b.1),
1502            body_end_column: None,
1503            body_start_byte: None,
1504            body_end_byte: None,
1505            body_hash: None,
1506            semantic_group: None,
1507            is_test: false,
1508            test_container: false,
1509        }
1510    }
1511
1512    #[test]
1513    fn skeleton_nests_an_object_under_the_field_that_declares_it() {
1514        let syms = vec![
1515            skeleton_row(
1516                "root",
1517                None,
1518                "class",
1519                "shell",
1520                "extends ShellRoot",
1521                (1, 8),
1522                None,
1523            ),
1524            skeleton_row(
1525                "timer",
1526                Some("root"),
1527                "field",
1528                "localPluginReloadTimer",
1529                "localPluginReloadTimer: Timer",
1530                (2, 7),
1531                Some((2, 7)),
1532            ),
1533            skeleton_row(
1534                "interval",
1535                Some("timer"),
1536                "property",
1537                "interval",
1538                "interval: 150",
1539                (3, 3),
1540                None,
1541            ),
1542            skeleton_row(
1543                "fire",
1544                Some("timer"),
1545                "function",
1546                "fire",
1547                "function fire()",
1548                (5, 7),
1549                Some((6, 7)),
1550            ),
1551        ];
1552
1553        assert_eq!(
1554            format_file_skeleton("shell/shell.qml", &syms, Some(8), 0),
1555            "// File: shell/shell.qml (Lines 1-8)\n\
1556             \n\
1557             extends ShellRoot {\n\
1558             \x20   localPluginReloadTimer: Timer {\n\
1559             \x20       interval: 150; // L3-3\n\
1560             \x20       function fire() { /* 2 lines hidden: L6-L7 */ }\n\
1561             \x20   } // L2-7\n\
1562             \n\
1563             } // L1-8\n\
1564             \n"
1565        );
1566    }
1567
1568    #[test]
1569    fn skeleton_renders_a_single_line_symbol_with_children_as_a_leaf() {
1570        let syms = vec![
1571            skeleton_row(
1572                "rusqlite",
1573                None,
1574                "field",
1575                "rusqlite",
1576                "rusqlite = { workspace = true }",
1577                (15, 15),
1578                None,
1579            ),
1580            skeleton_row(
1581                "workspace",
1582                Some("rusqlite"),
1583                "property",
1584                "workspace",
1585                "workspace = true",
1586                (15, 15),
1587                None,
1588            ),
1589        ];
1590
1591        assert_eq!(
1592            format_file_skeleton("Cargo.toml", &syms, Some(15), 0),
1593            "// File: Cargo.toml (Lines 1-15)\n\
1594             \n\
1595             rusqlite =; // L15-15\n"
1596        );
1597    }
1598
1599    #[test]
1600    fn skeleton_renders_members_of_a_single_line_enum() {
1601        let mut syms = vec![
1602            skeleton_row(
1603                "mode",
1604                None,
1605                "enum",
1606                "DispatchMode",
1607                "public enum DispatchMode",
1608                (21, 21),
1609                None,
1610            ),
1611            skeleton_row(
1612                "provision",
1613                Some("mode"),
1614                "enum_member",
1615                "Provision",
1616                "Provision",
1617                (21, 21),
1618                None,
1619            ),
1620            skeleton_row(
1621                "deprovision",
1622                Some("mode"),
1623                "enum_member",
1624                "Deprovision",
1625                "Deprovision",
1626                (21, 21),
1627                None,
1628            ),
1629            skeleton_row(
1630                "extension",
1631                Some("mode"),
1632                "enum_member",
1633                "Extension",
1634                "Extension",
1635                (21, 21),
1636                None,
1637            ),
1638        ];
1639        for symbol in &mut syms {
1640            symbol.language = "csharp".into();
1641        }
1642
1643        let skeleton = format_file_skeleton("DispatchContext.cs", &syms, Some(21), 0);
1644
1645        for member in ["Provision", "Deprovision", "Extension"] {
1646            assert!(skeleton.contains(member), "{skeleton}");
1647        }
1648    }
1649
1650    #[test]
1651    fn skeleton_keeps_plain_fields_and_function_locals_unchanged() {
1652        let syms = vec![
1653            skeleton_row(
1654                "cfg",
1655                None,
1656                "struct",
1657                "Config",
1658                "pub struct Config",
1659                (1, 3),
1660                None,
1661            ),
1662            skeleton_row(
1663                "retries",
1664                Some("cfg"),
1665                "field",
1666                "retries",
1667                "pub retries: u32",
1668                (2, 2),
1669                None,
1670            ),
1671            skeleton_row(
1672                "run",
1673                None,
1674                "function",
1675                "run",
1676                "pub fn run()",
1677                (5, 9),
1678                Some((6, 8)),
1679            ),
1680            skeleton_row(
1681                "tmp",
1682                Some("run"),
1683                "variable",
1684                "tmp",
1685                "let tmp",
1686                (7, 7),
1687                None,
1688            ),
1689        ];
1690
1691        assert_eq!(
1692            format_file_skeleton("src/lib.rs", &syms, Some(9), 0),
1693            "// File: src/lib.rs (Lines 1-9)\n\
1694             \n\
1695             pub struct Config {\n\
1696             \x20   pub retries: u32; // L2-2\n\
1697             } // L1-3\n\
1698             \n\
1699             pub fn run() { /* 3 lines hidden: L6-L8 */ }\n"
1700        );
1701    }
1702
1703    #[test]
1704    fn skeleton_marks_an_event_row_whose_signature_does_not_spell_it() {
1705        let syms = vec![
1706            skeleton_row(
1707                "cls",
1708                None,
1709                "class",
1710                "ColumnViewAttached",
1711                "class ColumnViewAttached : public QObject",
1712                (11, 52),
1713                None,
1714            ),
1715            skeleton_row(
1716                "sig",
1717                Some("cls"),
1718                "event",
1719                "indexChanged",
1720                "void indexChanged()",
1721                (47, 47),
1722                None,
1723            ),
1724            skeleton_row(
1725                "qml",
1726                None,
1727                "event",
1728                "clicked",
1729                "signal clicked()",
1730                (60, 60),
1731                None,
1732            ),
1733        ];
1734
1735        assert_eq!(
1736            format_file_skeleton("src/columnview.h", &syms, Some(60), 0),
1737            "// File: src/columnview.h (Lines 1-60)\n\
1738             \n\
1739             class ColumnViewAttached : public QObject {\n\
1740             \x20   void indexChanged(); // event L47-47\n\
1741             } // L11-52\n\
1742             \n\
1743             signal clicked(); // L60-60\n"
1744        );
1745    }
1746}