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    matches!(
61        kind,
62        "struct" | "class" | "trait" | "interface" | "enum" | "impl" | "module" | "namespace"
63    )
64}
65
66fn is_skippable_kind(kind: &str) -> bool {
67    matches!(kind, "variable" | "parameter" | "import")
68}
69
70fn sanitize_skeleton_sig<'a>(sig: &'a str, name: &'a str) -> &'a str {
71    let clean = if let Some(idx) = sig.find('{') {
72        sig[..idx].trim_end()
73    } else {
74        sig.trim_end()
75    };
76    let trimmed = clean.trim_end_matches(';').trim_end();
77    if trimmed.is_empty() { name } else { trimmed }
78}
79
80fn render_symbol_skeleton(
81    out: &mut String,
82    sym: &Symbol,
83    children_map: &HashMap<Option<String>, Vec<&Symbol>>,
84    indent_level: usize,
85) {
86    if is_skippable_kind(&sym.kind) {
87        return;
88    }
89
90    let indent = "    ".repeat(indent_level);
91
92    // Doc comment: cap at 3 lines to prevent dumping huge blocks
93    if let Some(ref doc) = sym.doc_comment {
94        let lines: Vec<_> = doc.lines().collect();
95        let cap = 3;
96        for line in lines.iter().take(cap) {
97            out.push_str(&format!("{indent}/// {line}\n"));
98        }
99        if lines.len() > cap {
100            out.push_str(&format!(
101                "{indent}/// ... ({} more lines)\n",
102                lines.len() - cap
103            ));
104        }
105    }
106
107    let span_str = format!("L{}-{}", sym.start_line, sym.end_line);
108
109    // Check if this symbol is a container (class, struct, trait, enum, etc.)
110    let children = children_map.get(&Some(sym.symbol_id.clone()));
111
112    if is_container_kind(&sym.kind) && children.is_some() {
113        let raw_sig = sym.signature.as_deref().unwrap_or(&sym.name);
114        let sig = sanitize_skeleton_sig(raw_sig, &sym.name);
115        out.push_str(&format!("{indent}{sig} {{\n"));
116        if let Some(child_list) = children {
117            for child in child_list {
118                render_symbol_skeleton(out, child, children_map, indent_level + 1);
119            }
120        }
121        out.push_str(&format!("{indent}}} // {span_str}\n\n"));
122    } else {
123        // Leaf symbol or function/method
124        if let Some(count) = sym.hidden_body_line_count() {
125            let raw_sig = sym.signature.as_deref().unwrap_or(&sym.name);
126            let sig = sanitize_skeleton_sig(raw_sig, &sym.name);
127            let b_start = sym.body_start_line.unwrap_or(sym.start_line);
128            let b_end = sym.body_end_line.unwrap_or(sym.end_line);
129
130            if count > 1 {
131                out.push_str(&format!(
132                    "{indent}{sig} {{ /* {count} lines hidden: L{b_start}-L{b_end} */ }}\n"
133                ));
134            } else {
135                out.push_str(&format!("{indent}{sig}; // {span_str}\n"));
136            }
137        } else if let Some(ref raw_sig) = sym.signature {
138            let sig = sanitize_skeleton_sig(raw_sig, &sym.name);
139            out.push_str(&format!("{indent}{sig}; // {span_str}\n"));
140        } else {
141            out.push_str(&format!(
142                "{indent}{} {sym_name}; // {span_str}\n",
143                sym.kind,
144                sym_name = sym.name
145            ));
146        }
147    }
148}
149
150/// Node representing directory or file in codebase outline tree.
151#[derive(Default)]
152pub struct OutlineNode {
153    pub files: BTreeMap<String, Vec<String>>, // file_name -> list of top symbol names with kinds
154    pub subdirs: BTreeMap<String, OutlineNode>,
155}
156
157/// Add a file path into the outline tree, bounded by max_depth.
158pub fn add_path_to_outline(
159    root_node: &mut OutlineNode,
160    file_path: &str,
161    symbols_by_file: &HashMap<String, Vec<Symbol>>,
162    max_depth: usize,
163    norm_filter: &str,
164) {
165    let normalized = file_path.replace('\\', "/");
166    let rel_path_str = if norm_filter.is_empty() {
167        normalized.as_str()
168    } else if normalized.eq_ignore_ascii_case(norm_filter) {
169        Path::new(&normalized)
170            .file_name()
171            .and_then(|n| n.to_str())
172            .unwrap_or(&normalized)
173    } else if normalized.len() > norm_filter.len()
174        && normalized.as_bytes()[norm_filter.len()] == b'/'
175        && normalized[..norm_filter.len()].eq_ignore_ascii_case(norm_filter)
176    {
177        &normalized[norm_filter.len() + 1..]
178    } else {
179        return;
180    };
181
182    let path = Path::new(rel_path_str);
183    let components: Vec<&str> = path
184        .components()
185        .map(|c| c.as_os_str().to_str().unwrap_or(""))
186        .filter(|s| !s.is_empty())
187        .collect();
188
189    if components.is_empty() {
190        return;
191    }
192
193    let mut curr = root_node;
194    let depth = components.len();
195
196    for (i, comp) in components.iter().enumerate() {
197        if i == depth - 1 {
198            // Leaf file: only insert if it is within max_depth
199            if depth <= max_depth {
200                let mut sym_tags = Vec::new();
201                if let Some(syms) = symbols_by_file.get(&normalized) {
202                    for s in syms.iter().take(5) {
203                        sym_tags.push(format!("{} {}", s.kind, s.name));
204                    }
205                    if syms.len() > 5 {
206                        sym_tags.push(format!("+{} more", syms.len() - 5));
207                    }
208                }
209                if !sym_tags.is_empty() {
210                    curr.files.insert(comp.to_string(), sym_tags);
211                }
212            }
213        } else if i < max_depth {
214            curr = curr.subdirs.entry(comp.to_string()).or_default();
215        } else {
216            break;
217        }
218    }
219}
220
221pub fn render_outline_tree(
222    out: &mut String,
223    node: &OutlineNode,
224    prefix: &str,
225    depth: usize,
226    max_depth: usize,
227) {
228    if depth >= max_depth {
229        return;
230    }
231
232    let total_items = node.subdirs.len() + node.files.len();
233    let mut index = 0;
234
235    // Render subdirectories
236    for (name, sub) in &node.subdirs {
237        index += 1;
238        let is_last = index == total_items;
239        let branch = if is_last { "└── " } else { "├── " };
240        let next_prefix = format!("{}{}", prefix, if is_last { "    " } else { "│   " });
241
242        out.push_str(&format!("{prefix}{branch}{name}/\n"));
243        render_outline_tree(out, sub, &next_prefix, depth + 1, max_depth);
244    }
245
246    // Render files
247    for (file_name, syms) in &node.files {
248        index += 1;
249        let is_last = index == total_items;
250        let branch = if is_last { "└── " } else { "├── " };
251
252        let sym_suffix = if !syms.is_empty() {
253            format!(" [{}]", syms.join(", "))
254        } else {
255            String::new()
256        };
257
258        out.push_str(&format!("{prefix}{branch}{file_name}{sym_suffix}\n"));
259    }
260}
261
262/// Format symbol body with metadata header, signature, and body content.
263pub fn format_symbol_body(symbol: &Symbol, body: &str) -> String {
264    let body_hash = crate::edit::hash_content(body);
265    let mut out = format!(
266        "// {}:{}-{} ({}) body_hash={body_hash}\n",
267        symbol.path, symbol.start_line, symbol.end_line, symbol.name
268    );
269    if let Some(ref sig) = symbol.signature {
270        out.push_str(sig);
271        if !sig.ends_with('\n') {
272            out.push('\n');
273        }
274    }
275    out.push_str(body);
276    if !body.ends_with('\n') {
277        out.push('\n');
278    }
279    out
280}
281
282/// Format surgical context bundle for a symbol.
283pub fn format_context_slice(slice: &ContextSlice) -> String {
284    let sym = &slice.target_symbol;
285    let mut out = String::new();
286    let body_hash = crate::edit::hash_content(&slice.target_body);
287
288    out.push_str(&format!(
289        "### Target: `{}` ({}:{}-{}) body_hash={body_hash}\n\n",
290        sym.name, sym.path, sym.start_line, sym.end_line
291    ));
292
293    if let Some(ref sig) = sym.signature {
294        out.push_str(&format!("Signature: `{sig}`\n\n"));
295    }
296
297    out.push_str(&format!("```{}\n", sym.language));
298    out.push_str(&slice.target_body);
299    if !slice.target_body.ends_with('\n') {
300        out.push('\n');
301    }
302    out.push_str("```\n\n");
303
304    if !slice.callee_signatures.is_empty() {
305        out.push_str("### Dependencies (Signatures):\n");
306        for callee in &slice.callee_signatures {
307            out.push_str(&format!("- {callee}\n"));
308        }
309        if slice.callee_signatures.len() >= 10 {
310            out.push_str("[Showing 10 dependencies (limit reached)]\n");
311        }
312        out.push('\n');
313    }
314
315    if !slice.related_types.is_empty() {
316        out.push_str("### Types:\n");
317        for t in &slice.related_types {
318            out.push_str(&format!("- {t}\n"));
319        }
320        out.push('\n');
321    }
322
323    if !slice.related_tests.is_empty() {
324        out.push_str("### Related Tests:\n");
325        for test in &slice.related_tests {
326            out.push_str(&format!(
327                "- `{}` ({}:{})\n",
328                test.name, test.path, test.start_line
329            ));
330        }
331        if slice.related_tests.len() >= 5 {
332            out.push_str("[Showing 5 tests (limit reached)]\n");
333        }
334        out.push('\n');
335    }
336
337    out
338}
339
340fn cap_notice(shown: usize, limit: usize) -> String {
341    let advice = if limit >= crate::queries::MAX_RESULT_LIMIT {
342        "narrow the query to see more"
343    } else {
344        "increase limit to see more"
345    };
346    format!("\n[Showing {shown} results (limit reached); {advice}.]\n")
347}
348
349/// Format references list for callers/callees with optional limit footer.
350pub fn format_references(
351    target_name: &str,
352    refs: &[ReferenceSite],
353    direction: &str,
354    limit: usize,
355) -> String {
356    let mut out = String::new();
357    let dir_label = if direction == "callers" {
358        "Callers of"
359    } else {
360        "Callees called by"
361    };
362    out.push_str(&format!(
363        "{dir_label} `{target_name}` ({} found):\n",
364        refs.len()
365    ));
366
367    if refs.is_empty() {
368        out.push_str("  (none)\n");
369        return out;
370    }
371
372    for r in refs {
373        let line_info = match r.start_line {
374            Some(l) => format!(":{l}"),
375            None => String::new(),
376        };
377        let other = if direction == "callers" {
378            &r.from_symbol_name
379        } else {
380            &r.to_symbol_name
381        };
382        out.push_str(&format!(
383            "- `{other}` [{}{line_info}] (kind: {})\n",
384            r.path, r.kind
385        ));
386    }
387
388    if refs.len() >= limit {
389        out.push_str(&cap_notice(refs.len(), limit));
390    }
391
392    out
393}
394
395/// Formats exact or FTS fallback symbol results with transparent header labeling.
396pub fn format_find_symbol_results(
397    query: &str,
398    exact_matches: &[Symbol],
399    fts_matches: &[SymbolSearchResult],
400    limit: usize,
401) -> String {
402    if !exact_matches.is_empty() {
403        let mut out = format!(
404            "Found {} symbols matching \"{query}\":\n\n",
405            exact_matches.len()
406        );
407        for s in exact_matches {
408            let sig = s.signature.as_deref().unwrap_or(&s.name);
409            out.push_str(&format!(
410                "- {} `{}` [{}:{}-{}]\n",
411                s.kind, s.name, s.path, s.start_line, s.end_line
412            ));
413            out.push_str(&format!("  Signature: {sig}\n"));
414            if let Some(doc) = &s.doc_comment {
415                let first = doc.lines().next().unwrap_or("").trim();
416                if !first.is_empty() {
417                    out.push_str(&format!("  Doc: {first}\n"));
418                }
419            }
420        }
421        if exact_matches.len() >= limit {
422            out.push_str(&cap_notice(exact_matches.len(), limit));
423        }
424        out
425    } else if !fts_matches.is_empty() {
426        let mut out = format!(
427            "No exact name match; {} full-text matches for \"{query}\":\n\n",
428            fts_matches.len()
429        );
430        for r in fts_matches {
431            let s = &r.symbol;
432            let sig = s.signature.as_deref().unwrap_or(&s.name);
433            out.push_str(&format!(
434                "- {} `{}` [{}:{}-{}] (score: {:.2})\n",
435                s.kind, s.name, s.path, s.start_line, s.end_line, r.score
436            ));
437            out.push_str(&format!("  Signature: {sig}\n"));
438            if let Some(snippet) = &r.snippet {
439                let clean = snippet.replace('\r', "").trim().to_string();
440                let first = clean.lines().next().unwrap_or(&clean);
441                out.push_str(&format!("  Match: {first}\n"));
442            } else if let Some(doc) = &s.doc_comment {
443                let first = doc.lines().next().unwrap_or("").trim();
444                if !first.is_empty() {
445                    out.push_str(&format!("  Doc: {first}\n"));
446                }
447            }
448        }
449        if fts_matches.len() >= limit {
450            out.push_str(&cap_notice(fts_matches.len(), limit));
451        }
452        out
453    } else {
454        format!("No symbols found matching \"{query}\".\n")
455    }
456}
457
458/// Format available structural fact & literal categories.
459pub fn format_fact_categories(categories: &[(String, usize)]) -> String {
460    if categories.is_empty() {
461        return "No structural facts or literals indexed in this repository.".to_string();
462    }
463    let mut out = format!(
464        "Available structural fact & literal categories ({} found):\n\n",
465        categories.len()
466    );
467    for (name, count) in categories {
468        out.push_str(&format!("- `{name}` ({count} occurrences)\n"));
469    }
470    out
471}
472
473/// Format structural facts and matching literals into token-dense markdown.
474pub fn format_structural_facts(
475    facts: &[crate::models::StructuralFact],
476    literals: &[crate::models::LiteralFact],
477    category: &str,
478) -> String {
479    let mut out = format!(
480        "Structural facts for '{category}' ({} found):\n",
481        facts.len()
482    );
483    for f in facts {
484        let label = f.key.as_deref().unwrap_or(&f.capture_name);
485        let parent = f
486            .containing_symbol_name
487            .as_deref()
488            .map(|p| format!(", in: {p}"))
489            .unwrap_or_default();
490        out.push_str(&format!(
491            "- {label} [{}:{}] (pattern: {}{parent})\n",
492            f.path, f.start_line, f.pattern_id
493        ));
494    }
495    if !literals.is_empty() {
496        out.push_str(&format!(
497            "\nMatching literals ({} found):\n",
498            literals.len()
499        ));
500        for l in literals {
501            out.push_str(&format!(
502                "- \"{}\" [{}:{}] (kind: {})\n",
503                l.literal_text, l.path, l.start_line, l.kind
504            ));
505        }
506    }
507    out
508}
509
510/// Format result of atomic symbol body replacement.
511pub fn format_replace_symbol_result(res: &crate::edit::EditResult) -> String {
512    let syntax_line = if res.syntax_checked {
513        "Syntax: Verified"
514    } else {
515        "Syntax: Skipped (grammar not available for file extension)"
516    };
517    format!(
518        "Successfully replaced body of `{}` in `{}`.\nOld Hash: {}\nNew Hash: {}\nBytes Written: {}\n{}",
519        res.symbol_name,
520        res.file_path,
521        res.old_body_hash,
522        res.new_body_hash,
523        res.bytes_written,
524        syntax_line
525    )
526}
527
528/// Formats FTS5 conceptual search results into token-dense markdown.
529pub fn format_search_results(query: &str, results: &[SymbolSearchResult], limit: usize) -> String {
530    if results.is_empty() {
531        return format!("No symbols found matching concept \"{query}\".");
532    }
533
534    let mut out = format!(
535        "Found {} symbols matching concept \"{query}\":\n",
536        results.len()
537    );
538    if let Some(explain) = results.first().and_then(|r| r.explain.as_ref()) {
539        out.push_str(&format!(
540            "rerank: {} candidates in {} µs",
541            explain.candidates, explain.rerank_us
542        ));
543        if !explain.word_weights.is_empty() {
544            let words: Vec<String> = explain
545                .word_weights
546                .iter()
547                .map(|(word, weight)| format!("{word} {weight:.2}"))
548                .collect();
549            out.push_str(&format!("; words {}", words.join(", ")));
550        }
551        out.push('\n');
552    }
553    out.push('\n');
554    for r in results {
555        let s = &r.symbol;
556        let sig = s.signature.as_deref().unwrap_or(&s.name);
557        out.push_str(&format!(
558            "- {} `{}` [{}:{}-{}] (score: {:.2})\n",
559            s.kind, s.name, s.path, s.start_line, s.end_line, r.score
560        ));
561        out.push_str(&format!("  Signature: {sig}\n"));
562        if let Some(snippet) = &r.snippet {
563            let clean_snip = snippet.replace('\r', "").trim().to_string();
564            let first_line = clean_snip.lines().next().unwrap_or(&clean_snip);
565            out.push_str(&format!("  Match: {first_line}\n"));
566        } else if let Some(doc) = &s.doc_comment {
567            let first_line = doc.lines().next().unwrap_or("").trim();
568            if !first_line.is_empty() {
569                out.push_str(&format!("  Doc: {first_line}\n"));
570            }
571        }
572        if let Some(explain) = &r.explain {
573            out.push_str(&format!("  explain: {}\n", explain_line(r.score, explain)));
574        }
575    }
576
577    if results.len() >= limit {
578        out.push_str(&cap_notice(results.len(), limit));
579    }
580
581    out
582}
583
584fn explain_line(score: f64, e: &SearchExplain) -> String {
585    let mut line = format!(
586        "score {score:.1} = terms {:.1} + name {}({}) {:.1} + kind {:.1} + path {:.1}",
587        e.term_score, e.name_tier, e.name_strength, e.name_bonus, e.kind_prior, e.path_role,
588    );
589    if e.documentation != 0.0 {
590        line.push_str(&format!(" + doc {:.1}", e.documentation));
591    }
592    if e.test_intent != 0.0 {
593        line.push_str(&format!(" + test {:.1}", e.test_intent));
594    }
595    line.push_str(&format!(" [{}]", e.branches.join(",")));
596    if let Some(bm25) = e.bm25 {
597        line.push_str(&format!(" bm25 {bm25:.2}"));
598    }
599    if !e.terms.is_empty() {
600        let terms: Vec<String> = e
601            .terms
602            .iter()
603            .map(|(term, field, credit)| format!("{term}={field}:{credit}"))
604            .collect();
605        line.push_str(&format!(" terms {}", terms.join(" ")));
606    }
607    line
608}
609
610/// Format blast radius and likely test targets into token-dense markdown.
611pub fn format_blast_radius(result: &BlastRadiusResult) -> String {
612    if result.seed_type == "none"
613        || (result.seeds.is_empty()
614            && result.likely_tests.is_empty()
615            && result.impacted_symbols.is_empty())
616    {
617        return "No uncommitted changes detected in git working tree. Pass a 'symbol' or 'file' parameter to analyze blast radius.".to_string();
618    }
619
620    let mut out = String::new();
621    let seed_label = if result.seed_type == "file" {
622        format!("Files: {}", result.seeds.join(", "))
623    } else if result.seed_type == "symbol" {
624        format!("Symbol: {}", result.seeds.join(", "))
625    } else {
626        format!("Seeds: {}", result.seeds.join(", "))
627    };
628
629    out.push_str(&format!("## Blast Radius & Test Impact ({seed_label})\n\n"));
630
631    const MAX_COMPACT_TESTS: usize = 20;
632    const MAX_COMPACT_IMPACTED: usize = 50;
633
634    if !result.likely_tests.is_empty() {
635        let total = result.likely_tests.len();
636        if total > MAX_COMPACT_TESTS {
637            out.push_str(&format!(
638                "### Likely Tests to Run ({} found - showing top {})\n",
639                total, MAX_COMPACT_TESTS
640            ));
641        } else {
642            out.push_str(&format!("### Likely Tests to Run ({} found)\n", total));
643        }
644
645        let mut tests_by_file: std::collections::BTreeMap<&str, Vec<&TestTarget>> =
646            std::collections::BTreeMap::new();
647        let mut file_order = Vec::new();
648        for t in result.likely_tests.iter().take(MAX_COMPACT_TESTS) {
649            if !tests_by_file.contains_key(t.path.as_str()) {
650                file_order.push(t.path.as_str());
651            }
652            tests_by_file.entry(t.path.as_str()).or_default().push(t);
653        }
654
655        for path in file_order {
656            out.push_str(&format!("{path}:\n"));
657            if let Some(tests) = tests_by_file.get(path) {
658                for t in tests {
659                    out.push_str(&format!(
660                        "  - `{}` [line {}] ({})\n",
661                        t.name, t.line, t.reason
662                    ));
663                }
664            }
665        }
666
667        if total > MAX_COMPACT_TESTS {
668            out.push_str(&format!(
669                "... {} more likely tests; narrow the target. CLI --json shows the full returned list.\n",
670                total - MAX_COMPACT_TESTS
671            ));
672        }
673        out.push('\n');
674    } else {
675        out.push_str("### Likely Tests to Run\nNo direct or stem-matched tests found.\n\n");
676    }
677
678    if !result.impacted_symbols.is_empty() {
679        let total = result.impacted_symbols.len();
680        let mut visible = Vec::new();
681        let mut low_signal_count = 0;
682        for s in &result.impacted_symbols {
683            if matches!(s.kind.as_str(), "import" | "module" | "namespace") {
684                low_signal_count += 1;
685            } else {
686                visible.push(s);
687            }
688        }
689
690        if result.traversal_ceiling_reached || total >= 200 {
691            out.push_str("### Downstream Impact (200+ symbols - traversal ceiling reached; increase depth/limit or narrow target)\n");
692        } else {
693            out.push_str(&format!("### Downstream Impact ({} symbols)\n", total));
694        }
695
696        if visible.is_empty() && low_signal_count > 0 {
697            let row_word = if low_signal_count == 1 {
698                "row (import/module)"
699            } else {
700                "rows (imports/modules)"
701            };
702            out.push_str(&format!(
703                "All impacted symbols are imports/modules; {low_signal_count} low-signal {row_word} hidden; available in CLI --json.\n"
704            ));
705        } else {
706            let visible_total = visible.len();
707            let showing_count = visible_total.min(MAX_COMPACT_IMPACTED);
708
709            let mut syms_by_file: std::collections::BTreeMap<&str, Vec<&ImpactedSymbol>> =
710                std::collections::BTreeMap::new();
711            let mut file_order = Vec::new();
712            for s in visible.iter().take(showing_count) {
713                if !syms_by_file.contains_key(s.path.as_str()) {
714                    file_order.push(s.path.as_str());
715                }
716                syms_by_file.entry(s.path.as_str()).or_default().push(s);
717            }
718
719            for path in file_order {
720                out.push_str(&format!("{path}:\n"));
721                if let Some(syms) = syms_by_file.get(path) {
722                    for s in syms {
723                        out.push_str(&format!(
724                            "  - [depth {}] {} `{}` [line {}]\n",
725                            s.depth, s.kind, s.name, s.line
726                        ));
727                    }
728                }
729            }
730
731            if visible_total > MAX_COMPACT_IMPACTED {
732                out.push_str(&format!(
733                    "... {} more impacted symbols; narrow the target. CLI --json shows the full returned list.\n",
734                    visible_total - MAX_COMPACT_IMPACTED
735                ));
736            }
737            if low_signal_count > 0 {
738                let row_word = if low_signal_count == 1 {
739                    "row (import/module)"
740                } else {
741                    "rows (imports/modules)"
742                };
743                out.push_str(&format!(
744                    "... {low_signal_count} low-signal {row_word} hidden; available in CLI --json.\n"
745                ));
746            }
747        }
748    } else {
749        out.push_str("### Downstream Impact\nNo downstream callers found within depth.\n");
750    }
751
752    out
753}
754
755#[cfg(test)]
756mod tests {
757    use super::*;
758    use crate::models::{ImpactedSymbol, TestTarget};
759
760    fn structural_fact(key: Option<&str>) -> crate::models::StructuralFact {
761        crate::models::StructuralFact {
762            structural_fact_id: "sf1".into(),
763            path: ".codex/config.toml".into(),
764            language: "toml".into(),
765            pattern_id: "toml.key_value.v1".into(),
766            capture_name: "key_value".into(),
767            node_kind: "table".into(),
768            key: key.map(str::to_string),
769            containing_symbol_name: None,
770            start_line: 2,
771            end_line: 2,
772            confidence: 1.0,
773        }
774    }
775
776    #[test]
777    fn format_structural_facts_prints_key_and_falls_back_to_capture_name() {
778        let with_key = format_structural_facts(
779            &[structural_fact(Some("mcp_servers.code-kb.command"))],
780            &[],
781            "config",
782        );
783        assert!(with_key.contains(
784            "- mcp_servers.code-kb.command [.codex/config.toml:2] (pattern: toml.key_value.v1)"
785        ));
786
787        let without_key = format_structural_facts(&[structural_fact(None)], &[], "config");
788        assert!(
789            without_key.contains("- key_value [.codex/config.toml:2] (pattern: toml.key_value.v1)")
790        );
791    }
792
793    #[test]
794    fn file_skeleton_reports_parse_errors() {
795        let two = format_file_skeleton("src/lib.rs", &[], Some(35), 2);
796        assert!(two.contains("// 2 parse errors: symbols may be incomplete"));
797
798        let one = format_file_skeleton("src/lib.rs", &[], Some(35), 1);
799        assert!(one.contains("// 1 parse error: symbols may be incomplete"));
800
801        let none = format_file_skeleton("src/lib.rs", &[], Some(35), 0);
802        assert!(!none.contains("parse error"));
803    }
804
805    #[test]
806    fn test_format_file_skeleton() {
807        let syms = vec![Symbol {
808            symbol_id: "s1".into(),
809            file_id: "f1".into(),
810            path: "src/lib.rs".into(),
811            language: "rust".into(),
812            name: "do_work".into(),
813            kind: "function".into(),
814            signature: Some("pub fn do_work() -> Result<()>".into()),
815            doc_comment: Some("Performs core work.".into()),
816            visibility: Some("pub".into()),
817            parent_symbol_id: None,
818            start_line: 10,
819            start_column: 0,
820            end_line: 30,
821            end_column: 1,
822            start_byte: 100,
823            end_byte: 300,
824            body_start_line: Some(11),
825            body_start_column: Some(0),
826            body_end_line: Some(29),
827            body_end_column: Some(1),
828            body_start_byte: Some(130),
829            body_end_byte: Some(298),
830            body_hash: None,
831            semantic_group: None,
832            is_test: false,
833            test_container: false,
834        }];
835
836        let skeleton = format_file_skeleton("src/lib.rs", &syms, Some(35), 0);
837        assert!(skeleton.contains("/// Performs core work."));
838        assert!(skeleton.contains("19 lines hidden: L11-L29"));
839    }
840
841    #[test]
842    fn test_format_search_results() {
843        let results = vec![SymbolSearchResult {
844            symbol: Symbol {
845                symbol_id: "s1".into(),
846                file_id: "f1".into(),
847                path: "src/parser.rs".into(),
848                language: "rust".into(),
849                name: "parse_tokens".into(),
850                kind: "function".into(),
851                signature: Some("pub fn parse_tokens()".into()),
852                doc_comment: Some("Parses tokens from stream.".into()),
853                visibility: Some("pub".into()),
854                parent_symbol_id: None,
855                start_line: 15,
856                start_column: 0,
857                end_line: 25,
858                end_column: 1,
859                start_byte: 100,
860                end_byte: 250,
861                body_start_line: None,
862                body_start_column: None,
863                body_end_line: None,
864                body_end_column: None,
865                body_start_byte: None,
866                body_end_byte: None,
867                body_hash: None,
868                semantic_group: None,
869                is_test: false,
870                test_container: false,
871            },
872            score: -1.85,
873            snippet: Some("Parses [tokens] from stream.".into()),
874            explain: None,
875        }];
876
877        let formatted = format_search_results("tokens", &results, 20);
878        assert!(formatted.contains("Found 1 symbols matching concept \"tokens\":\n\n- "));
879        assert!(
880            formatted.contains("- function `parse_tokens` [src/parser.rs:15-25] (score: -1.85)")
881        );
882        assert!(formatted.contains("Match: Parses [tokens] from stream."));
883        assert!(!formatted.contains("explain"));
884        assert!(!formatted.contains("rerank"));
885    }
886
887    #[test]
888    fn every_printed_part_of_the_explain_line_sums_to_the_score() {
889        let e = SearchExplain {
890            bm25: Some(-3.21),
891            branches: vec!["word".into()],
892            name_tier: "all".into(),
893            name_strength: 6,
894            term_score: 24.5,
895            name_bonus: 60.0,
896            kind_prior: 4.0,
897            path_role: -10.0,
898            documentation: -200.0,
899            test_intent: 5.0,
900            terms: vec![("sha".into(), "name".into(), 3.0)],
901            word_weights: vec![("sha".into(), 2.6)],
902            candidates: 1,
903            rerank_us: 1,
904        };
905        let score = e.term_score
906            + e.name_bonus
907            + e.kind_prior
908            + e.path_role
909            + e.documentation
910            + e.test_intent;
911
912        let line = explain_line(score, &e);
913        let parts: f64 = line
914            .split(" = ")
915            .nth(1)
916            .unwrap()
917            .split(" [")
918            .next()
919            .unwrap()
920            .split(" + ")
921            .map(|part| part.rsplit(' ').next().unwrap().parse::<f64>().unwrap())
922            .sum();
923
924        assert!(line.starts_with(&format!(
925            "score {score:.1} = terms 24.5 + name all(6) 60.0 "
926        )));
927        assert_eq!(format!("{parts:.1}"), format!("{score:.1}"));
928    }
929
930    #[test]
931    fn test_format_search_results_prints_the_explain_breakdown_when_present() {
932        let mut result = SymbolSearchResult {
933            symbol: sample_symbol("parseSha256Sidecar"),
934            score: 71.6,
935            snippet: Some("parse[Sha256]Sidecar".into()),
936            explain: Some(SearchExplain {
937                bm25: Some(-3.21),
938                branches: vec!["word".into(), "name".into()],
939                name_tier: "all".into(),
940                name_strength: 6,
941                terms: vec![
942                    ("sha".into(), "name".into(), 3.0),
943                    ("256".into(), "name".into(), 3.0),
944                ],
945                term_score: 12.6,
946                name_bonus: 60.0,
947                kind_prior: 4.0,
948                path_role: -10.0,
949                documentation: 0.0,
950                test_intent: 5.0,
951                word_weights: vec![("sha".into(), 2.6), ("256".into(), 0.97)],
952                candidates: 37,
953                rerank_us: 180,
954            }),
955        };
956
957        let formatted = format_search_results("sha256", std::slice::from_ref(&result), 20);
958        assert!(formatted.contains(
959            "Found 1 symbols matching concept \"sha256\":\nrerank: 37 candidates in 180 µs; words sha 2.60, 256 0.97\n\n- "
960        ));
961        assert!(formatted.contains(
962            "  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"
963        ));
964
965        result.explain = None;
966        let silent = format_search_results("sha256", std::slice::from_ref(&result), 20);
967        assert!(!silent.contains("explain"));
968        assert!(!silent.contains("rerank"));
969    }
970
971    #[test]
972    fn test_format_search_results_discloses_a_reached_limit() {
973        let results = vec![SymbolSearchResult {
974            symbol: sample_symbol("parse_tokens"),
975            score: 0.0,
976            snippet: None,
977            explain: None,
978        }];
979
980        let formatted = format_search_results("tokens", &results, 1);
981        assert!(
982            formatted.contains("[Showing 1 results (limit reached); increase limit to see more.]")
983        );
984
985        let at_ceiling =
986            format_search_results("tokens", &results, crate::queries::MAX_RESULT_LIMIT);
987        assert!(!at_ceiling.contains("limit reached"));
988
989        let full: Vec<SymbolSearchResult> = (0..crate::queries::MAX_RESULT_LIMIT)
990            .map(|_| SymbolSearchResult {
991                symbol: sample_symbol("parse_tokens"),
992                score: 0.0,
993                snippet: None,
994                explain: None,
995            })
996            .collect();
997        let capped = format_search_results("tokens", &full, crate::queries::MAX_RESULT_LIMIT);
998        assert!(capped.contains("(limit reached); narrow the query to see more.]"));
999    }
1000
1001    #[test]
1002    fn test_format_blast_radius() {
1003        let res = BlastRadiusResult {
1004            seed_type: "symbol".into(),
1005            seeds: vec!["do_work".into()],
1006            likely_tests: vec![TestTarget {
1007                name: "test_do_work".into(),
1008                path: "tests/work_test.rs".into(),
1009                line: 15,
1010                reason: "transitive caller [depth 1]".into(),
1011            }],
1012            impacted_symbols: vec![ImpactedSymbol {
1013                name: "caller_fn".into(),
1014                kind: "function".into(),
1015                path: "src/caller.rs".into(),
1016                line: 42,
1017                depth: 1,
1018            }],
1019            traversal_ceiling_reached: false,
1020        };
1021
1022        let formatted = format_blast_radius(&res);
1023        assert!(formatted.contains("## Blast Radius & Test Impact (Symbol: do_work)"));
1024        assert!(formatted.contains("### Likely Tests to Run (1 found)"));
1025        assert!(formatted.contains(
1026            "tests/work_test.rs:\n  - `test_do_work` [line 15] (transitive caller [depth 1])"
1027        ));
1028        assert!(formatted.contains("src/caller.rs:\n  - [depth 1] function `caller_fn` [line 42]"));
1029    }
1030
1031    #[test]
1032    fn test_format_blast_radius_grouped_and_capped() {
1033        let mut likely_tests = Vec::new();
1034        for i in 1..=25 {
1035            likely_tests.push(TestTarget {
1036                name: format!("test_{i}"),
1037                path: format!("tests/test_{}.rs", (i % 3) + 1),
1038                line: i * 10,
1039                reason: "direct caller".into(),
1040            });
1041        }
1042
1043        let impacted_symbols = vec![
1044            ImpactedSymbol {
1045                name: "use_foo".into(),
1046                kind: "import".into(),
1047                path: "src/service.rs".into(),
1048                line: 1,
1049                depth: 1,
1050            },
1051            ImpactedSymbol {
1052                name: "service_fn".into(),
1053                kind: "function".into(),
1054                path: "src/service.rs".into(),
1055                line: 20,
1056                depth: 1,
1057            },
1058            ImpactedSymbol {
1059                name: "api_handler".into(),
1060                kind: "function".into(),
1061                path: "src/api.rs".into(),
1062                line: 45,
1063                depth: 2,
1064            },
1065        ];
1066
1067        let res = BlastRadiusResult {
1068            seed_type: "file".into(),
1069            seeds: vec!["src/lib.rs".into()],
1070            likely_tests,
1071            impacted_symbols,
1072            traversal_ceiling_reached: false,
1073        };
1074
1075        let formatted = format_blast_radius(&res);
1076
1077        assert!(formatted.contains("### Likely Tests to Run (25 found - showing top 20)"));
1078        assert!(formatted.contains(
1079            "... 5 more likely tests; narrow the target. CLI --json shows the full returned list."
1080        ));
1081
1082        assert!(formatted.contains("tests/test_1.rs:\n"));
1083        assert!(formatted.contains("  - `test_"));
1084
1085        assert!(!formatted.contains("use_foo"));
1086        assert!(
1087            formatted
1088                .contains("... 1 low-signal row (import/module) hidden; available in CLI --json.")
1089        );
1090        assert!(formatted.contains("src/service.rs:\n"));
1091        assert!(formatted.contains("  - [depth 1] function `service_fn` [line 20]"));
1092    }
1093
1094    #[test]
1095    fn test_format_replace_symbol_result_shows_syntax_status() {
1096        let res_checked = crate::edit::EditResult {
1097            symbol_name: "my_fn".into(),
1098            file_path: "src/lib.rs".into(),
1099            old_body_hash: "aaa".into(),
1100            new_body_hash: "bbb".into(),
1101            bytes_written: 120,
1102            syntax_checked: true,
1103        };
1104        let out_checked = format_replace_symbol_result(&res_checked);
1105        assert!(out_checked.contains("Syntax: Verified"));
1106
1107        let res_skipped = crate::edit::EditResult {
1108            symbol_name: "my_fn".into(),
1109            file_path: "src/script.rb".into(),
1110            old_body_hash: "aaa".into(),
1111            new_body_hash: "bbb".into(),
1112            bytes_written: 120,
1113            syntax_checked: false,
1114        };
1115        let out_skipped = format_replace_symbol_result(&res_skipped);
1116        assert!(out_skipped.contains("Syntax: Skipped (grammar not available for file extension)"));
1117    }
1118
1119    fn sample_symbol(name: &str) -> Symbol {
1120        Symbol {
1121            symbol_id: format!("id_{name}"),
1122            file_id: "f1".into(),
1123            path: "src/lib.rs".into(),
1124            language: "rust".into(),
1125            name: name.into(),
1126            kind: "function".into(),
1127            signature: Some(format!("pub fn {name}()")),
1128            doc_comment: None,
1129            visibility: Some("pub".into()),
1130            parent_symbol_id: None,
1131            start_line: 1,
1132            start_column: 0,
1133            end_line: 10,
1134            end_column: 1,
1135            start_byte: 0,
1136            end_byte: 100,
1137            body_start_line: Some(2),
1138            body_start_column: Some(0),
1139            body_end_line: Some(9),
1140            body_end_column: Some(1),
1141            body_start_byte: Some(10),
1142            body_end_byte: Some(99),
1143            body_hash: None,
1144            semantic_group: None,
1145            is_test: false,
1146            test_container: false,
1147        }
1148    }
1149
1150    fn sample_context_slice() -> ContextSlice {
1151        ContextSlice {
1152            target_symbol: sample_symbol("target_fn"),
1153            target_body: "    println!(\"hello\");\n".into(),
1154            callee_signatures: Vec::new(),
1155            related_types: Vec::new(),
1156            related_tests: Vec::new(),
1157        }
1158    }
1159
1160    #[test]
1161    fn test_context_slice_shows_truncation_notice_when_caps_hit() {
1162        let mut slice = sample_context_slice();
1163        slice.callee_signatures = (1..=10).map(|i| format!("fn callee_{i}()")).collect();
1164        let text = format_context_slice(&slice);
1165        assert!(text.contains("[Showing 10 dependencies (limit reached)]"));
1166
1167        let mut slice_tests = sample_context_slice();
1168        slice_tests.related_tests = (1..=5)
1169            .map(|i| {
1170                let mut sym = sample_symbol(&format!("test_fn_{i}"));
1171                sym.path = format!("tests/test_{i}.rs");
1172                sym.is_test = true;
1173                sym
1174            })
1175            .collect();
1176        let text_tests = format_context_slice(&slice_tests);
1177        assert!(text_tests.contains("[Showing 5 tests (limit reached)]"));
1178    }
1179
1180    #[test]
1181    fn test_blast_radius_shows_traversal_ceiling_at_200_symbols() {
1182        let impacted_symbols = (1..=200)
1183            .map(|i| ImpactedSymbol {
1184                name: format!("sym_{i}"),
1185                kind: "function".into(),
1186                path: format!("src/mod_{}.rs", i % 10),
1187                line: i,
1188                depth: 1,
1189            })
1190            .collect();
1191
1192        let res = BlastRadiusResult {
1193            seed_type: "symbol".into(),
1194            seeds: vec!["root_fn".into()],
1195            likely_tests: Vec::new(),
1196            impacted_symbols,
1197            traversal_ceiling_reached: true,
1198        };
1199
1200        let formatted = format_blast_radius(&res);
1201        assert!(formatted.contains(
1202            "### Downstream Impact (200+ symbols - traversal ceiling reached; increase depth/limit or narrow target)\n"
1203        ));
1204    }
1205}