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