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, Symbol, SymbolSearchResult,
6    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\n",
536        results.len()
537    );
538    for r in results {
539        let s = &r.symbol;
540        let sig = s.signature.as_deref().unwrap_or(&s.name);
541        out.push_str(&format!(
542            "- {} `{}` [{}:{}-{}] (score: {:.2})\n",
543            s.kind, s.name, s.path, s.start_line, s.end_line, r.score
544        ));
545        out.push_str(&format!("  Signature: {sig}\n"));
546        if let Some(snippet) = &r.snippet {
547            let clean_snip = snippet.replace('\r', "").trim().to_string();
548            let first_line = clean_snip.lines().next().unwrap_or(&clean_snip);
549            out.push_str(&format!("  Match: {first_line}\n"));
550        } else if let Some(doc) = &s.doc_comment {
551            let first_line = doc.lines().next().unwrap_or("").trim();
552            if !first_line.is_empty() {
553                out.push_str(&format!("  Doc: {first_line}\n"));
554            }
555        }
556    }
557
558    if results.len() >= limit {
559        out.push_str(&cap_notice(results.len(), limit));
560    }
561
562    out
563}
564
565/// Format blast radius and likely test targets into token-dense markdown.
566pub fn format_blast_radius(result: &BlastRadiusResult) -> String {
567    if result.seed_type == "none"
568        || (result.seeds.is_empty()
569            && result.likely_tests.is_empty()
570            && result.impacted_symbols.is_empty())
571    {
572        return "No uncommitted changes detected in git working tree. Pass a 'symbol' or 'file' parameter to analyze blast radius.".to_string();
573    }
574
575    let mut out = String::new();
576    let seed_label = if result.seed_type == "file" {
577        format!("Files: {}", result.seeds.join(", "))
578    } else if result.seed_type == "symbol" {
579        format!("Symbol: {}", result.seeds.join(", "))
580    } else {
581        format!("Seeds: {}", result.seeds.join(", "))
582    };
583
584    out.push_str(&format!("## Blast Radius & Test Impact ({seed_label})\n\n"));
585
586    const MAX_COMPACT_TESTS: usize = 20;
587    const MAX_COMPACT_IMPACTED: usize = 50;
588
589    if !result.likely_tests.is_empty() {
590        let total = result.likely_tests.len();
591        if total > MAX_COMPACT_TESTS {
592            out.push_str(&format!(
593                "### Likely Tests to Run ({} found - showing top {})\n",
594                total, MAX_COMPACT_TESTS
595            ));
596        } else {
597            out.push_str(&format!("### Likely Tests to Run ({} found)\n", total));
598        }
599
600        let mut tests_by_file: std::collections::BTreeMap<&str, Vec<&TestTarget>> =
601            std::collections::BTreeMap::new();
602        let mut file_order = Vec::new();
603        for t in result.likely_tests.iter().take(MAX_COMPACT_TESTS) {
604            if !tests_by_file.contains_key(t.path.as_str()) {
605                file_order.push(t.path.as_str());
606            }
607            tests_by_file.entry(t.path.as_str()).or_default().push(t);
608        }
609
610        for path in file_order {
611            out.push_str(&format!("{path}:\n"));
612            if let Some(tests) = tests_by_file.get(path) {
613                for t in tests {
614                    out.push_str(&format!(
615                        "  - `{}` [line {}] ({})\n",
616                        t.name, t.line, t.reason
617                    ));
618                }
619            }
620        }
621
622        if total > MAX_COMPACT_TESTS {
623            out.push_str(&format!(
624                "... {} more likely tests; narrow the target. CLI --json shows the full returned list.\n",
625                total - MAX_COMPACT_TESTS
626            ));
627        }
628        out.push('\n');
629    } else {
630        out.push_str("### Likely Tests to Run\nNo direct or stem-matched tests found.\n\n");
631    }
632
633    if !result.impacted_symbols.is_empty() {
634        let total = result.impacted_symbols.len();
635        let mut visible = Vec::new();
636        let mut low_signal_count = 0;
637        for s in &result.impacted_symbols {
638            if matches!(s.kind.as_str(), "import" | "module" | "namespace") {
639                low_signal_count += 1;
640            } else {
641                visible.push(s);
642            }
643        }
644
645        if result.traversal_ceiling_reached || total >= 200 {
646            out.push_str("### Downstream Impact (200+ symbols - traversal ceiling reached; increase depth/limit or narrow target)\n");
647        } else {
648            out.push_str(&format!("### Downstream Impact ({} symbols)\n", total));
649        }
650
651        if visible.is_empty() && low_signal_count > 0 {
652            let row_word = if low_signal_count == 1 {
653                "row (import/module)"
654            } else {
655                "rows (imports/modules)"
656            };
657            out.push_str(&format!(
658                "All impacted symbols are imports/modules; {low_signal_count} low-signal {row_word} hidden; available in CLI --json.\n"
659            ));
660        } else {
661            let visible_total = visible.len();
662            let showing_count = visible_total.min(MAX_COMPACT_IMPACTED);
663
664            let mut syms_by_file: std::collections::BTreeMap<&str, Vec<&ImpactedSymbol>> =
665                std::collections::BTreeMap::new();
666            let mut file_order = Vec::new();
667            for s in visible.iter().take(showing_count) {
668                if !syms_by_file.contains_key(s.path.as_str()) {
669                    file_order.push(s.path.as_str());
670                }
671                syms_by_file.entry(s.path.as_str()).or_default().push(s);
672            }
673
674            for path in file_order {
675                out.push_str(&format!("{path}:\n"));
676                if let Some(syms) = syms_by_file.get(path) {
677                    for s in syms {
678                        out.push_str(&format!(
679                            "  - [depth {}] {} `{}` [line {}]\n",
680                            s.depth, s.kind, s.name, s.line
681                        ));
682                    }
683                }
684            }
685
686            if visible_total > MAX_COMPACT_IMPACTED {
687                out.push_str(&format!(
688                    "... {} more impacted symbols; narrow the target. CLI --json shows the full returned list.\n",
689                    visible_total - MAX_COMPACT_IMPACTED
690                ));
691            }
692            if low_signal_count > 0 {
693                let row_word = if low_signal_count == 1 {
694                    "row (import/module)"
695                } else {
696                    "rows (imports/modules)"
697                };
698                out.push_str(&format!(
699                    "... {low_signal_count} low-signal {row_word} hidden; available in CLI --json.\n"
700                ));
701            }
702        }
703    } else {
704        out.push_str("### Downstream Impact\nNo downstream callers found within depth.\n");
705    }
706
707    out
708}
709
710#[cfg(test)]
711mod tests {
712    use super::*;
713    use crate::models::{ImpactedSymbol, TestTarget};
714
715    fn structural_fact(key: Option<&str>) -> crate::models::StructuralFact {
716        crate::models::StructuralFact {
717            structural_fact_id: "sf1".into(),
718            path: ".codex/config.toml".into(),
719            language: "toml".into(),
720            pattern_id: "toml.key_value.v1".into(),
721            capture_name: "key_value".into(),
722            node_kind: "table".into(),
723            key: key.map(str::to_string),
724            containing_symbol_name: None,
725            start_line: 2,
726            end_line: 2,
727            confidence: 1.0,
728        }
729    }
730
731    #[test]
732    fn format_structural_facts_prints_key_and_falls_back_to_capture_name() {
733        let with_key = format_structural_facts(
734            &[structural_fact(Some("mcp_servers.code-kb.command"))],
735            &[],
736            "config",
737        );
738        assert!(with_key.contains(
739            "- mcp_servers.code-kb.command [.codex/config.toml:2] (pattern: toml.key_value.v1)"
740        ));
741
742        let without_key = format_structural_facts(&[structural_fact(None)], &[], "config");
743        assert!(
744            without_key.contains("- key_value [.codex/config.toml:2] (pattern: toml.key_value.v1)")
745        );
746    }
747
748    #[test]
749    fn file_skeleton_reports_parse_errors() {
750        let two = format_file_skeleton("src/lib.rs", &[], Some(35), 2);
751        assert!(two.contains("// 2 parse errors: symbols may be incomplete"));
752
753        let one = format_file_skeleton("src/lib.rs", &[], Some(35), 1);
754        assert!(one.contains("// 1 parse error: symbols may be incomplete"));
755
756        let none = format_file_skeleton("src/lib.rs", &[], Some(35), 0);
757        assert!(!none.contains("parse error"));
758    }
759
760    #[test]
761    fn test_format_file_skeleton() {
762        let syms = vec![Symbol {
763            symbol_id: "s1".into(),
764            file_id: "f1".into(),
765            path: "src/lib.rs".into(),
766            language: "rust".into(),
767            name: "do_work".into(),
768            kind: "function".into(),
769            signature: Some("pub fn do_work() -> Result<()>".into()),
770            doc_comment: Some("Performs core work.".into()),
771            visibility: Some("pub".into()),
772            parent_symbol_id: None,
773            start_line: 10,
774            start_column: 0,
775            end_line: 30,
776            end_column: 1,
777            start_byte: 100,
778            end_byte: 300,
779            body_start_line: Some(11),
780            body_start_column: Some(0),
781            body_end_line: Some(29),
782            body_end_column: Some(1),
783            body_start_byte: Some(130),
784            body_end_byte: Some(298),
785            body_hash: None,
786            semantic_group: None,
787            is_test: false,
788            test_container: false,
789        }];
790
791        let skeleton = format_file_skeleton("src/lib.rs", &syms, Some(35), 0);
792        assert!(skeleton.contains("/// Performs core work."));
793        assert!(skeleton.contains("19 lines hidden: L11-L29"));
794    }
795
796    #[test]
797    fn test_format_search_results() {
798        let results = vec![SymbolSearchResult {
799            symbol: Symbol {
800                symbol_id: "s1".into(),
801                file_id: "f1".into(),
802                path: "src/parser.rs".into(),
803                language: "rust".into(),
804                name: "parse_tokens".into(),
805                kind: "function".into(),
806                signature: Some("pub fn parse_tokens()".into()),
807                doc_comment: Some("Parses tokens from stream.".into()),
808                visibility: Some("pub".into()),
809                parent_symbol_id: None,
810                start_line: 15,
811                start_column: 0,
812                end_line: 25,
813                end_column: 1,
814                start_byte: 100,
815                end_byte: 250,
816                body_start_line: None,
817                body_start_column: None,
818                body_end_line: None,
819                body_end_column: None,
820                body_start_byte: None,
821                body_end_byte: None,
822                body_hash: None,
823                semantic_group: None,
824                is_test: false,
825                test_container: false,
826            },
827            score: -1.85,
828            snippet: Some("Parses [tokens] from stream.".into()),
829        }];
830
831        let formatted = format_search_results("tokens", &results, 20);
832        assert!(formatted.contains("Found 1 symbols matching concept \"tokens\":"));
833        assert!(
834            formatted.contains("- function `parse_tokens` [src/parser.rs:15-25] (score: -1.85)")
835        );
836        assert!(formatted.contains("Match: Parses [tokens] from stream."));
837    }
838
839    #[test]
840    fn test_format_search_results_discloses_a_reached_limit() {
841        let results = vec![SymbolSearchResult {
842            symbol: sample_symbol("parse_tokens"),
843            score: 0.0,
844            snippet: None,
845        }];
846
847        let formatted = format_search_results("tokens", &results, 1);
848        assert!(
849            formatted.contains("[Showing 1 results (limit reached); increase limit to see more.]")
850        );
851
852        let at_ceiling =
853            format_search_results("tokens", &results, crate::queries::MAX_RESULT_LIMIT);
854        assert!(!at_ceiling.contains("limit reached"));
855
856        let full: Vec<SymbolSearchResult> = (0..crate::queries::MAX_RESULT_LIMIT)
857            .map(|_| SymbolSearchResult {
858                symbol: sample_symbol("parse_tokens"),
859                score: 0.0,
860                snippet: None,
861            })
862            .collect();
863        let capped = format_search_results("tokens", &full, crate::queries::MAX_RESULT_LIMIT);
864        assert!(capped.contains("(limit reached); narrow the query to see more.]"));
865    }
866
867    #[test]
868    fn test_format_blast_radius() {
869        let res = BlastRadiusResult {
870            seed_type: "symbol".into(),
871            seeds: vec!["do_work".into()],
872            likely_tests: vec![TestTarget {
873                name: "test_do_work".into(),
874                path: "tests/work_test.rs".into(),
875                line: 15,
876                reason: "transitive caller [depth 1]".into(),
877            }],
878            impacted_symbols: vec![ImpactedSymbol {
879                name: "caller_fn".into(),
880                kind: "function".into(),
881                path: "src/caller.rs".into(),
882                line: 42,
883                depth: 1,
884            }],
885            traversal_ceiling_reached: false,
886        };
887
888        let formatted = format_blast_radius(&res);
889        assert!(formatted.contains("## Blast Radius & Test Impact (Symbol: do_work)"));
890        assert!(formatted.contains("### Likely Tests to Run (1 found)"));
891        assert!(formatted.contains(
892            "tests/work_test.rs:\n  - `test_do_work` [line 15] (transitive caller [depth 1])"
893        ));
894        assert!(formatted.contains("src/caller.rs:\n  - [depth 1] function `caller_fn` [line 42]"));
895    }
896
897    #[test]
898    fn test_format_blast_radius_grouped_and_capped() {
899        let mut likely_tests = Vec::new();
900        for i in 1..=25 {
901            likely_tests.push(TestTarget {
902                name: format!("test_{i}"),
903                path: format!("tests/test_{}.rs", (i % 3) + 1),
904                line: i * 10,
905                reason: "direct caller".into(),
906            });
907        }
908
909        let impacted_symbols = vec![
910            ImpactedSymbol {
911                name: "use_foo".into(),
912                kind: "import".into(),
913                path: "src/service.rs".into(),
914                line: 1,
915                depth: 1,
916            },
917            ImpactedSymbol {
918                name: "service_fn".into(),
919                kind: "function".into(),
920                path: "src/service.rs".into(),
921                line: 20,
922                depth: 1,
923            },
924            ImpactedSymbol {
925                name: "api_handler".into(),
926                kind: "function".into(),
927                path: "src/api.rs".into(),
928                line: 45,
929                depth: 2,
930            },
931        ];
932
933        let res = BlastRadiusResult {
934            seed_type: "file".into(),
935            seeds: vec!["src/lib.rs".into()],
936            likely_tests,
937            impacted_symbols,
938            traversal_ceiling_reached: false,
939        };
940
941        let formatted = format_blast_radius(&res);
942
943        assert!(formatted.contains("### Likely Tests to Run (25 found - showing top 20)"));
944        assert!(formatted.contains(
945            "... 5 more likely tests; narrow the target. CLI --json shows the full returned list."
946        ));
947
948        assert!(formatted.contains("tests/test_1.rs:\n"));
949        assert!(formatted.contains("  - `test_"));
950
951        assert!(!formatted.contains("use_foo"));
952        assert!(
953            formatted
954                .contains("... 1 low-signal row (import/module) hidden; available in CLI --json.")
955        );
956        assert!(formatted.contains("src/service.rs:\n"));
957        assert!(formatted.contains("  - [depth 1] function `service_fn` [line 20]"));
958    }
959
960    #[test]
961    fn test_format_replace_symbol_result_shows_syntax_status() {
962        let res_checked = crate::edit::EditResult {
963            symbol_name: "my_fn".into(),
964            file_path: "src/lib.rs".into(),
965            old_body_hash: "aaa".into(),
966            new_body_hash: "bbb".into(),
967            bytes_written: 120,
968            syntax_checked: true,
969        };
970        let out_checked = format_replace_symbol_result(&res_checked);
971        assert!(out_checked.contains("Syntax: Verified"));
972
973        let res_skipped = crate::edit::EditResult {
974            symbol_name: "my_fn".into(),
975            file_path: "src/script.rb".into(),
976            old_body_hash: "aaa".into(),
977            new_body_hash: "bbb".into(),
978            bytes_written: 120,
979            syntax_checked: false,
980        };
981        let out_skipped = format_replace_symbol_result(&res_skipped);
982        assert!(out_skipped.contains("Syntax: Skipped (grammar not available for file extension)"));
983    }
984
985    fn sample_symbol(name: &str) -> Symbol {
986        Symbol {
987            symbol_id: format!("id_{name}"),
988            file_id: "f1".into(),
989            path: "src/lib.rs".into(),
990            language: "rust".into(),
991            name: name.into(),
992            kind: "function".into(),
993            signature: Some(format!("pub fn {name}()")),
994            doc_comment: None,
995            visibility: Some("pub".into()),
996            parent_symbol_id: None,
997            start_line: 1,
998            start_column: 0,
999            end_line: 10,
1000            end_column: 1,
1001            start_byte: 0,
1002            end_byte: 100,
1003            body_start_line: Some(2),
1004            body_start_column: Some(0),
1005            body_end_line: Some(9),
1006            body_end_column: Some(1),
1007            body_start_byte: Some(10),
1008            body_end_byte: Some(99),
1009            body_hash: None,
1010            semantic_group: None,
1011            is_test: false,
1012            test_container: false,
1013        }
1014    }
1015
1016    fn sample_context_slice() -> ContextSlice {
1017        ContextSlice {
1018            target_symbol: sample_symbol("target_fn"),
1019            target_body: "    println!(\"hello\");\n".into(),
1020            callee_signatures: Vec::new(),
1021            related_types: Vec::new(),
1022            related_tests: Vec::new(),
1023        }
1024    }
1025
1026    #[test]
1027    fn test_context_slice_shows_truncation_notice_when_caps_hit() {
1028        let mut slice = sample_context_slice();
1029        slice.callee_signatures = (1..=10).map(|i| format!("fn callee_{i}()")).collect();
1030        let text = format_context_slice(&slice);
1031        assert!(text.contains("[Showing 10 dependencies (limit reached)]"));
1032
1033        let mut slice_tests = sample_context_slice();
1034        slice_tests.related_tests = (1..=5)
1035            .map(|i| {
1036                let mut sym = sample_symbol(&format!("test_fn_{i}"));
1037                sym.path = format!("tests/test_{i}.rs");
1038                sym.is_test = true;
1039                sym
1040            })
1041            .collect();
1042        let text_tests = format_context_slice(&slice_tests);
1043        assert!(text_tests.contains("[Showing 5 tests (limit reached)]"));
1044    }
1045
1046    #[test]
1047    fn test_blast_radius_shows_traversal_ceiling_at_200_symbols() {
1048        let impacted_symbols = (1..=200)
1049            .map(|i| ImpactedSymbol {
1050                name: format!("sym_{i}"),
1051                kind: "function".into(),
1052                path: format!("src/mod_{}.rs", i % 10),
1053                line: i,
1054                depth: 1,
1055            })
1056            .collect();
1057
1058        let res = BlastRadiusResult {
1059            seed_type: "symbol".into(),
1060            seeds: vec!["root_fn".into()],
1061            likely_tests: Vec::new(),
1062            impacted_symbols,
1063            traversal_ceiling_reached: true,
1064        };
1065
1066        let formatted = format_blast_radius(&res);
1067        assert!(formatted.contains(
1068            "### Downstream Impact (200+ symbols - traversal ceiling reached; increase depth/limit or narrow target)\n"
1069        ));
1070    }
1071}