leindex 2.1.1

LeIndex MCP and semantic code search engine for AI tools and large codebases
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
use super::*;

pub(super) fn render_project_map(data: &Value, color: bool) -> String {
    let mut out = header("Project Structure", color);
    out.push('\n');
    out.push_str(&project_map_body(data, color));
    out.push_str(&project_map_stats(data, color));
    out.push_str(&project_map_scope_line(data, color));
    out.push_str(&project_map_legend(data, color));
    out
}

/// Render the structure body: community groups, the handler's tree, a
/// single-root tree, or a flat ranked file list — whichever shape the
/// handler emitted first.
fn project_map_body(data: &Value, color: bool) -> String {
    if data.get("group_by").and_then(|v| v.as_str()) == Some("community") {
        return render_community_groups(data, color);
    }
    if let Some(tree) = data.get("tree").and_then(|v| v.as_array()) {
        return render_tree(tree, color);
    }
    if let Some(roots) = data.get("root").map(|v| vec![v.clone()]) {
        return render_tree(&roots, color);
    }
    if let Some(files) = data.get("files").and_then(|v| v.as_array()) {
        return project_map_files_body(files, color);
    }
    String::new()
}

/// Render the `files` array shape. `build_tree_from_files` returns an
/// empty Vec when no directory info is available in the file entries (the
/// handler ships basenames, not full paths), so render a flat ranked list
/// rather than fabricating fake directories.
fn project_map_files_body(files: &[Value], color: bool) -> String {
    let tree = build_tree_from_files(files);
    if tree.is_empty() {
        return render_flat_files(files, color);
    }
    render_tree(&tree, color)
}

/// Render the optional `stats` block (files, symbols, avg complexity, LOC).
fn project_map_stats(data: &Value, color: bool) -> String {
    let Some(stats) = data.get("stats") else {
        return String::new();
    };
    let mut out = String::from("\n");
    if let Some(v) = stats.get("total_files").and_then(|v| v.as_u64()) {
        out.push_str(&field("Files", &v.to_string(), color));
    }
    if let Some(v) = stats.get("total_symbols").and_then(|v| v.as_u64()) {
        out.push_str(&field("Symbols", &v.to_string(), color));
    }
    if let Some(v) = stats.get("avg_complexity").and_then(|v| v.as_f64()) {
        out.push_str(&field("Avg complexity", &format!("{:.1}", v), color));
    }
    if let Some(v) = stats.get("total_loc").and_then(|v| v.as_u64()) {
        out.push_str(&field("Lines of code", &v.to_string(), color));
    }
    out
}

/// Render the handler's top-level `total_files_in_scope` count (it is not
/// under "stats"). Only a positive count is shown.
fn project_map_scope_line(data: &Value, color: bool) -> String {
    let Some(count) = data
        .get("total_files_in_scope")
        .and_then(|v| v.as_u64())
        .filter(|count| *count > 0)
    else {
        return String::new();
    };
    let mut out = String::new();
    if data.get("stats").is_none() {
        out.push('\n');
    }
    // N-14: state the count basis — "Files in scope" counts source files
    // under the scoped path, which is deliberately different from the
    // indexed-file total shown by diagnostics (skip lists, exclusions,
    // and scoping all apply).
    out.push_str(&field(
        "Files in scope",
        &format!("{} (source files under the scoped path)", count),
        color,
    ));
    out
}

/// N-14: one legend line for the bracket annotations — `[out→in]` is
/// outgoing→incoming dependency counts and `[N symbols]` is the file's
/// indexed symbol count. Previously nowhere documented. Shown whenever
/// any bracket annotation can appear (scoped count, tree, or root).
fn project_map_legend(data: &Value, color: bool) -> String {
    let scoped = data
        .get("total_files_in_scope")
        .and_then(|v| v.as_u64())
        .is_some_and(|count| count > 0);
    if scoped || data.get("tree").is_some() || data.get("root").is_some() {
        return format!(
            "\n  {}Legend: [N symbols] = indexed symbol count; [out→in] = outgoing→incoming dependencies{}\n",
            if color { DIM } else { "" },
            if color { RESET } else { "" },
        );
    }
    String::new()
}

pub(super) fn render_community_groups(data: &Value, color: bool) -> String {
    let Some(communities) = data.get("communities").and_then(|v| v.as_array()) else {
        return "  (no community assignments)\n".to_string();
    };
    if communities.is_empty() {
        return community_groups_empty_note(data);
    }

    let mut out = format!(
        "  {}Community groups ({}):{}\n",
        if color { BOLD } else { "" },
        communities.len(),
        if color { RESET } else { "" },
    );
    for community in communities {
        out.push_str(&community_section(community, color));
    }
    out.push_str(&ungrouped_files_section(data, color));
    out
}

/// Render the empty-communities line, appending the handler's `note`
/// (e.g. why community detection was skipped) when present.
fn community_groups_empty_note(data: &Value) -> String {
    let note = data
        .get("note")
        .and_then(|v| v.as_str())
        .map(|value| format!(" — {value}"))
        .unwrap_or_default();
    format!("  (no communities{note})\n")
}

/// Render one community: its header line (id, label, file count) followed
/// by the member file list.
fn community_section(community: &Value, color: bool) -> String {
    let id = community
        .get("community")
        .and_then(|v| v.as_i64())
        .map(|value| value.to_string())
        .unwrap_or_else(|| "?".to_string());
    let label = community
        .get("label")
        .and_then(|v| v.as_str())
        .unwrap_or("unlabeled");
    let file_count = community
        .get("file_count")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);
    let mut out = format!(
        "\n    {}Community {}{} — {} ({} files){}\n",
        if color { LIGHT_MAGENTA } else { "" },
        id,
        if color { RESET } else { "" },
        label,
        file_count,
        if color { RESET } else { "" },
    );
    if let Some(files) = community.get("files").and_then(|v| v.as_array()) {
        for file in files {
            out.push_str(&community_file_line(file, color));
        }
    }
    out
}

/// Render one community member file: `• <path>  [N symbols]`.
fn community_file_line(file: &Value, color: bool) -> String {
    let path = file
        .get("relative_path")
        .and_then(|v| v.as_str())
        .or_else(|| file.get("path").and_then(|v| v.as_str()))
        .unwrap_or("?");
    let symbols = file
        .get("symbol_count")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);
    format!(
        "      {}•{} {}{}{}  [{} symbols]\n",
        if color { LIGHT_YELLOW } else { "" },
        if color { RESET } else { "" },
        if color { LIGHT_YELLOW } else { "" },
        path,
        if color { RESET } else { "" },
        symbols,
    )
}

/// Render the `ungrouped_files` tail block: a header with the file count
/// followed by one bullet per path. Emits nothing when the array is
/// absent or empty.
fn ungrouped_files_section(data: &Value, color: bool) -> String {
    let Some(files) = data.get("ungrouped_files").and_then(|v| v.as_array()) else {
        return String::new();
    };
    if files.is_empty() {
        return String::new();
    }
    let mut out = format!(
        "\n    {}Ungrouped ({} files):{}\n",
        if color { BOLD } else { "" },
        files.len(),
        if color { RESET } else { "" },
    );
    for file in files {
        let path = file
            .get("relative_path")
            .and_then(|v| v.as_str())
            .or_else(|| file.get("path").and_then(|v| v.as_str()))
            .unwrap_or("?");
        out.push_str(&format!("      • {path}\n"));
    }
    out
}

pub(super) fn render_flat_files(files: &[Value], color: bool) -> String {
    let mut out = String::new();
    out.push_str(&format!(
        "  {}(flat list — files ordered as returned){}\n",
        if color { DIM } else { "" },
        if color { RESET } else { "" },
    ));
    for (i, f) in files.iter().enumerate() {
        let path = f
            .get("path")
            .and_then(|v| v.as_str())
            .or_else(|| f.get("relative_path").and_then(|v| v.as_str()))
            .unwrap_or("?");
        let syms = f.get("symbol_count").and_then(|v| v.as_u64()).unwrap_or(0);
        let cx = f
            .get("total_complexity")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);
        let deps = f
            .get("incoming_dependencies")
            .and_then(|v| v.as_u64())
            .unwrap_or(0)
            + f.get("outgoing_dependencies")
                .and_then(|v| v.as_u64())
                .unwrap_or(0);
        // The complexity value is shown as a colour-coded integer
        // (`cx:{N}`); the human-readable label ("low" / "med" /
        // "high") was previously computed alongside the colour but
        // never rendered, so simplify the conditional to just the
        // colour string. When colour is disabled the colour string
        // is the empty literal.
        let cx_color = if color {
            match cx {
                0..=20 => LIGHT_GREEN,
                21..=60 => LIGHT_YELLOW,
                _ => LIGHT_RED,
            }
        } else {
            ""
        };
        out.push_str(&format!(
            "  {}{:>3}.{} {}{}{}  {}{} sym  cx:{}{}{}  deps:{}\n",
            if color { BOLD } else { "" },
            i + 1,
            if color { RESET } else { "" },
            if color { LIGHT_YELLOW } else { "" },
            path,
            if color { RESET } else { "" },
            if color { DIM } else { "" },
            syms,
            cx_color,
            cx,
            if color { RESET } else { "" },
            deps,
        ));
    }
    out
}

/// Convert a flat list of `{path, relative_path, symbol_count, ...}`
/// entries into a nested directory tree suitable for `render_tree`.
/// Returns an empty Vec if the file entries don't carry directory
/// information (caller falls back to flat rendering).
pub(super) fn build_tree_from_files(files: &[Value]) -> Vec<Value> {
    use std::collections::BTreeMap;

    // Bail out unless at least one entry has a path with a directory
    // separator — otherwise we'd fabricate a meaningless single-level
    // tree from basenames.
    let any_with_dir = files.iter().any(|f| {
        f.get("relative_path")
            .and_then(|v| v.as_str())
            .or_else(|| f.get("path").and_then(|v| v.as_str()))
            .map(|p| p.contains('/') || p.contains('\\'))
            .unwrap_or(false)
    });
    if !any_with_dir {
        return Vec::new();
    }

    // A `Node` here is a tiny tree of name -> (entry, children).
    struct Node {
        entry: Option<Value>,
        children: BTreeMap<String, Node>,
    }

    impl Node {
        fn new() -> Self {
            Self {
                entry: None,
                children: BTreeMap::new(),
            }
        }
        /// Convert a directory node to a `{name, type, children}` JSON
        /// value. File nodes pass through their entry. Each child is
        /// converted using its own key as the name so nested directory
        /// labels stay distinct instead of inheriting the parent's
        /// segment.
        fn into_value(self, name: &str) -> Value {
            let children: Vec<Value> = self
                .children
                .into_iter()
                .map(|(child_name, child)| child.into_value(&child_name))
                .collect();
            if let Some(mut entry) = self.entry {
                if let Some(obj) = entry.as_object_mut() {
                    if !children.is_empty() {
                        obj.insert("children".to_string(), Value::Array(children));
                    }
                }
                entry
            } else {
                serde_json::json!({
                    "name": name,
                    "type": "directory",
                    "children": children,
                })
            }
        }
    }

    let mut root = Node::new();
    for file in files {
        let rel = file
            .get("relative_path")
            .and_then(|v| v.as_str())
            .or_else(|| file.get("path").and_then(|v| v.as_str()))
            .unwrap_or("?");
        // Normalize to forward slashes for stable tree building.
        let rel = rel.replace('\\', "/");
        let parts: Vec<&str> = rel.split('/').filter(|p| !p.is_empty()).collect();
        let mut node = &mut root;
        for (i, part) in parts.iter().enumerate() {
            let key = part.to_string();
            let is_file = i + 1 == parts.len();
            let child = node.children.entry(key.clone()).or_insert_with(Node::new);
            if is_file {
                let mut entry = file.clone();
                if let Some(obj) = entry.as_object_mut() {
                    obj.entry("name".to_string())
                        .or_insert(Value::String((*part).to_string()));
                    obj.entry("type".to_string())
                        .or_insert(Value::String("file".to_string()));
                }
                child.entry = Some(entry);
            }
            node = child;
        }
    }

    // The root is a virtual container with no name of its own — return
    // its top-level children directly so `render_tree` shows them as
    // siblings rather than nested under a fabricated "root" node.
    let mut top: Vec<Value> = Vec::new();
    for (name, child) in root.children.into_iter() {
        top.push(child.into_value(&name));
    }
    top
}

pub(super) fn render_impact_risk(data: &Value, color: bool) -> String {
    let Some(risk) = data.get("risk_level").and_then(|v| v.as_str()) else {
        return String::new();
    };
    let (icon, risk_color) = if color {
        match risk.to_lowercase().as_str() {
            "high" => ("●", LIGHT_RED),
            "medium" => ("●", LIGHT_YELLOW),
            "low" => ("●", LIGHT_GREEN),
            _ => ("○", WHITE),
        }
    } else {
        ("●", "")
    };
    format!(
        "  {}Risk:{} {risk_color}{icon} {risk}{}\n",
        if color { BOLD } else { "" },
        if color { RESET } else { "" },
        if color { RESET } else { "" },
    )
}

pub(super) fn render_impact_list(
    data: &Value,
    key: &str,
    title: &str,
    arrow: &str,
    item_color: &str,
    limit: usize,
    show_more: bool,
    color: bool,
) -> String {
    let Some(items) = data.get(key).and_then(|v| v.as_array()) else {
        return String::new();
    };
    if items.is_empty() {
        return String::new();
    }
    let (bold, dim, reset, line_color) = if color {
        (BOLD, DIM, RESET, item_color)
    } else {
        ("", "", "", "")
    };
    let mut out = format!("\n  {bold}{title} ({}):{reset}\n", items.len());
    for item in items.iter().take(limit) {
        let name = item
            .as_str()
            .or_else(|| item.get("name").and_then(|v| v.as_str()))
            .unwrap_or("?");
        out.push_str(&format!("    {line_color}{arrow} {name}{reset}\n"));
    }
    if show_more && items.len() > limit {
        out.push_str(&format!("    {dim}… {} more{reset}\n", items.len() - limit));
    }
    out
}

pub(super) fn render_impact_communities(data: &Value, color: bool) -> String {
    let Some(breakdown) = data.get("community_breakdown") else {
        return String::new();
    };
    if breakdown.is_null() {
        return String::new();
    }
    let same = breakdown
        .get("same_community")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);
    let crossing = breakdown
        .get("crossing")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);
    let mut out = String::from("\n");
    out.push_str(&format!(
        "  {}Community boundaries:{}\n",
        if color { BOLD } else { "" },
        if color { RESET } else { "" },
    ));
    out.push_str(&format!("    Same community: {same}\n"));
    out.push_str(&format!("    Crossing communities: {crossing}\n"));
    if let Some(boundaries) = breakdown.get("boundaries").and_then(|v| v.as_array()) {
        for boundary in boundaries {
            let from = boundary
                .get("from")
                .and_then(|v| v.as_u64())
                .map(|value| value.to_string())
                .unwrap_or_else(|| "?".to_string());
            let to = boundary
                .get("to")
                .and_then(|v| v.as_u64())
                .map(|value| value.to_string())
                .unwrap_or_else(|| "?".to_string());
            let symbols = boundary
                .get("symbols")
                .and_then(|v| v.as_u64())
                .unwrap_or(0);
            out.push_str(&format!(
                "    {}{} → {}{}: {} symbols\n",
                if color { LIGHT_MAGENTA } else { "" },
                from,
                to,
                if color { RESET } else { "" },
                symbols,
            ));
        }
    }
    out
}

pub(super) fn render_impact_counts(data: &Value, color: bool) -> String {
    let affected_files = data
        .get("transitive_affected_files")
        .and_then(|v| v.as_u64());
    let transitive_callers = data.get("transitive_callers").and_then(|v| v.as_u64());
    if affected_files.is_none() && transitive_callers.is_none() {
        return String::new();
    }

    let mut out = String::from("\n");
    if let Some(count) = affected_files {
        out.push_str(&field("Affected files", &count.to_string(), color));
    }
    if let Some(count) = transitive_callers {
        out.push_str(&field("Transitive callers", &count.to_string(), color));
    }
    out
}

pub(super) fn render_impact(data: &Value, color: bool) -> String {
    let mut out = header("Impact Analysis", color);
    out.push('\n');
    if let Some(sym) = data.get("symbol").and_then(|v| v.as_str()) {
        out.push_str(&field("Symbol", sym, color));
    }
    if let Some(file) = data.get("file").and_then(|v| v.as_str()) {
        out.push_str(&field("File", file, color));
    }
    if let Some(ct) = data.get("change_type").and_then(|v| v.as_str()) {
        out.push_str(&field("Change type", ct, color));
    }
    out.push_str(&render_impact_risk(data, color));

    out.push_str(&render_impact_list(
        data,
        "direct_callers",
        "Direct callers",
        "←",
        LIGHT_CYAN,
        20,
        false,
        color,
    ));

    out.push_str(&render_impact_list(
        data,
        "transitive_affected_symbols",
        "Transitive affected symbols",
        "→",
        LIGHT_YELLOW,
        30,
        true,
        color,
    ));

    // Summary with numeric counts
    if let Some(s) = data.get("summary").and_then(|v| v.as_str()) {
        out.push('\n');
        out.push_str(&format!(
            "  {}Summary:{} {}\n",
            if color { BOLD } else { "" },
            if color { RESET } else { "" },
            s,
        ));
    }

    out.push_str(&render_impact_counts(data, color));
    out.push_str(&render_impact_communities(data, color));

    out
}