leindex 2.0.3

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
use super::helpers::{
    extract_bool, extract_string, extract_usize, get_direct_callers, node_type_str,
};
use super::protocol::JsonRpcError;
use super::read_symbol_handler::{catalog_is_fresh, parse_live_file, read_live_bytes};
use super::request_meta::WorkBudget;
use crate::cli::live_project::LiveProject;
use crate::cli::registry::ProjectRegistry;
use crate::storage::{CatalogReader, CatalogSymbol};
use serde_json::Value;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;

/// Handler for LeIndex [file_summary — structured file analysis replacing Read.
#[derive(Clone)]
pub struct FileSummaryHandler;

#[allow(missing_docs)]
impl FileSummaryHandler {
    pub fn name(&self) -> &str {
        "leindex_file_summary"
    }
    pub fn title(&self) -> &str {
        "LeIndex [File Summary]"
    }
    pub fn description(&self) -> &str {
        "File overview: symbol inventory, complexity scores, cross-file dependencies, and module role."
    }

    pub fn argument_schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "file_path": { "type": "string", "description": "File to analyze" },
                "project_path": { "type": "string", "description": "Project directory" },
                "token_budget": { "type": "integer", "default": 1000 },
                "include_source": { "type": "boolean", "default": false },
                "focus_symbol": { "type": "string" },
                "max_latency_ms": { "type": "integer", "default": 250, "minimum": 0, "maximum": 60000 },
                "allow_partial": { "type": "boolean", "default": true }
            },
            "required": ["file_path"]
        })
    }

    pub async fn execute(
        &self,
        registry: &Arc<ProjectRegistry>,
        args: Value,
    ) -> Result<Value, JsonRpcError> {
        let requested_file = extract_string(&args, "file_path")?;
        let include_source = extract_bool(&args, "include_source", false);
        let focus_symbol = args.get("focus_symbol").and_then(|v| v.as_str());
        let token_budget = extract_usize(&args, "token_budget", 1000)?;
        let budget = WorkBudget {
            max_latency_ms: extract_usize(&args, "max_latency_ms", 250)?.min(60000) as u64,
            allow_partial: extract_bool(&args, "allow_partial", true),
        };
        let started = Instant::now();
        let project_path = match args.get("project_path").and_then(|v| v.as_str()) {
            Some(path) => PathBuf::from(path),
            None => registry.default_project_path().await?,
        };
        let live = LiveProject::resolve(&project_path.to_string_lossy()).map_err(|e| {
            JsonRpcError::invalid_params(format!(
                "Cannot resolve project_path '{}': {}",
                project_path.display(),
                e
            ))
        })?;
        let file = live
            .file(&requested_file)
            .map_err(|e| JsonRpcError::invalid_params(e.to_string()))?;
        let (catalog_response, source_stale) = catalog_file_summary(
            registry,
            &live,
            &file,
            include_source,
            focus_symbol,
            token_budget,
            budget,
            started,
        )
        .await?;
        if let Some(response) = catalog_response {
            return Ok(response);
        }
        let parsed = parse_live_file(file.clone()).await?;
        let (relations, pdg_status) = resident_file_relations(
            registry,
            &live,
            &parsed.symbols,
            source_stale,
            budget,
            started,
        )
        .await;
        file_summary_response(
            &file,
            &parsed.bytes,
            parsed.symbols,
            include_source,
            focus_symbol,
            token_budget,
            SummaryProvenance {
                live_parse: true,
                catalog_truncated: false,
                catalog_total: None,
            },
            &relations,
            pdg_status,
            budget,
        )
    }
}

async fn catalog_file_summary(
    registry: &Arc<ProjectRegistry>,
    live: &LiveProject,
    file: &Path,
    include_source: bool,
    focus_symbol: Option<&str>,
    token_budget: usize,
    budget: WorkBudget,
    started: Instant,
) -> Result<(Option<Value>, bool), JsonRpcError> {
    // D6: the resident PDG is the graph store — inventory the file's symbols
    // against it first; without a resident project, inventory against the
    // published Pdg layer (the unhydrated fast path); the SQL catalog remains
    // the legacy fallback (and still serves the freshness record, which
    // survives the graph flip).
    let db_path = live.catalog_db();
    let mut graph = match registry.try_get_loaded(live.root()).await {
        Some(handle) => {
            let guard = handle.read().await;
            guard.pdg().map(|pdg| {
                (
                    crate::storage::catalog::graph::symbols_in_file(pdg, live.root(), file),
                    crate::storage::catalog::graph::count_symbols_in_file(pdg, live.root(), file),
                )
            })
        }
        None => None,
    };
    if graph
        .as_ref()
        .map(|(symbols, _)| symbols.is_empty())
        .unwrap_or(true)
    {
        let layer_symbols =
            crate::storage::catalog::layer::symbols_in_file(live.storage(), live.root(), file);
        if !layer_symbols.is_empty() {
            graph = Some((
                layer_symbols,
                crate::storage::catalog::layer::count_symbols_in_file(
                    live.storage(),
                    live.root(),
                    file,
                ),
            ));
        }
    }
    let (graph_symbols, graph_total) = graph
        .map(|(symbols, total)| (Some(symbols), Some(total)))
        .unwrap_or((None, None));

    let catalog = if db_path.is_file() {
        CatalogReader::open(&db_path, live.root())
            .await
            .ok()
            .flatten()
    } else {
        None
    };

    let symbols = match graph_symbols {
        Some(symbols) => symbols,
        None => match &catalog {
            Some(catalog) => catalog.symbols_in_file(file).await.ok().unwrap_or_default(),
            None => Vec::new(),
        },
    };
    // Resolve each symbol's live path; skip (drop) symbols whose lookup fails
    // rather than aborting the whole request. All-stale -> empty -> the caller
    // falls back to live parsing. `external` rows are import/reference
    // markers (see the summary comment on the resolver below).
    let mut dropped_external = 0usize;
    let symbols = resolve_live_symbol_paths(live, symbols, &mut dropped_external);
    if symbols.is_empty() {
        return Ok((None, false));
    }
    let catalog_total = match graph_total {
        Some(count) => Some(count),
        None => match &catalog {
            Some(catalog) => catalog.count_symbols_in_file(file).await.ok(),
            None => None,
        },
    };
    // The row cap compares against ALL rows (externals included), so add the
    // filtered markers back when deciding whether the DEFINITION list was cut.
    let catalog_truncated = catalog_total
        .map(|total| total > symbols.len() + dropped_external)
        .unwrap_or(symbols.len() >= 200);
    let bytes = read_live_bytes(file.to_path_buf()).await?;
    let fresh = match &catalog {
        Some(catalog) => catalog_is_fresh(catalog, file, &bytes).await,
        // No freshness record exists to verify against; fall back to live
        // parsing rather than trusting an unverifiable graph view.
        None => false,
    };
    if !fresh {
        return Ok((None, true));
    }

    let (relations, pdg_status) =
        resident_file_relations(registry, live, &symbols, false, budget, started).await;
    let response = file_summary_response(
        file,
        &bytes,
        symbols,
        include_source,
        focus_symbol,
        token_budget,
        SummaryProvenance {
            live_parse: false,
            catalog_truncated,
            catalog_total,
        },
        &relations,
        pdg_status,
        budget,
    )?;
    Ok((Some(response), false))
}

/// Resolve each symbol's live path and drop the rows a summary must not
/// carry; returns the resolved definitions and (by out-param) how many
/// `external` import/reference markers were dropped.
///
/// A file's DEFINITIONS are what a summary should inventory. `external`
/// rows are import/reference markers (qualified paths like
/// `crate.cli.index_job.IndexJobSnapshot` from call-target resolution) —
/// the audit found them dominating the list and drowning the file's own
/// symbols. They are dropped here rather than in the shared catalog query
/// so other catalog consumers keep their semantics.
fn resolve_live_symbol_paths(
    live: &LiveProject,
    symbols: Vec<crate::storage::catalog::CatalogSymbol>,
    dropped_external: &mut usize,
) -> Vec<crate::storage::catalog::CatalogSymbol> {
    let mut resolved = Vec::with_capacity(symbols.len());
    for mut symbol in symbols {
        if symbol.node_type.eq_ignore_ascii_case("external") {
            *dropped_external += 1;
            continue;
        }
        if let Ok(path) = live.file(&symbol.file_path.to_string_lossy()) {
            symbol.file_path = path;
            resolved.push(symbol);
        }
    }
    resolved
}

/// Provenance markers for a file summary: where the symbol list came from and
/// how trustworthy it is. Rendered into the response so clients can tell a
/// live-parse summary from a catalog-backed one.
#[derive(Debug, Clone, Copy)]
struct SummaryProvenance {
    /// True when the symbol list came from a live parse (always current).
    live_parse: bool,
    /// True when the catalog query hit its row cap before returning all rows.
    catalog_truncated: bool,
    /// Total catalog rows for the file, when known.
    catalog_total: Option<usize>,
}

fn file_summary_response(
    file_path: &Path,
    bytes: &[u8],
    symbols: Vec<CatalogSymbol>,
    include_source: bool,
    focus_symbol: Option<&str>,
    token_budget: usize,
    provenance: SummaryProvenance,
    relations: &HashMap<String, Value>,
    pdg_status: &'static str,
    budget: WorkBudget,
) -> Result<Value, JsonRpcError> {
    let content = std::str::from_utf8(bytes).map_err(|e| {
        JsonRpcError::invalid_params(format!(
            "Source '{}' is not UTF-8: {}",
            file_path.display(),
            e
        ))
    })?;
    let mut total_chars = 0usize;
    let char_budget = token_budget * 4;
    let mut shown = Vec::new();
    let mut total = 0usize;
    for symbol in symbols {
        if symbol.symbol_name.is_empty()
            || focus_symbol.is_some_and(|focus| {
                !symbol
                    .symbol_name
                    .to_lowercase()
                    .contains(&focus.to_lowercase())
            })
        {
            continue;
        }
        total += 1;
        if total_chars >= char_budget {
            continue;
        }
        let (start, end) = symbol.byte_range;
        if start > end
            || end > bytes.len()
            || !content.is_char_boundary(start)
            || !content.is_char_boundary(end)
        {
            return Err(JsonRpcError::invalid_params(format!(
                "Indexed byte range for '{}' is outside live UTF-8 source boundaries",
                symbol.symbol_name
            )));
        }
        let relation = relations.get(&symbol.node_id).cloned().unwrap_or_else(|| {
            serde_json::json!({
                "dependencies": [], "dependents": [], "cross_file_refs": []
            })
        });
        let mut value = serde_json::json!({
            "name": symbol.symbol_name,
            "qualified_name": symbol.qualified_name,
            "type": symbol.node_type,
            "byte_range": symbol.byte_range,
            "complexity": symbol.complexity,
            "dependencies": relation["dependencies"],
            "dependents": relation["dependents"],
            "cross_file_refs": relation["cross_file_refs"]
        });
        if include_source {
            value["source"] = Value::String(content[start..end].chars().take(500).collect());
        }
        total_chars += value.to_string().len();
        shown.push(value);
    }
    let function_count = shown
        .iter()
        .filter(|symbol| symbol["type"] == "function")
        .count();
    let class_count = shown
        .iter()
        .filter(|symbol| symbol["type"] == "class")
        .count();
    let symbol_count = provenance.catalog_total.unwrap_or(total);
    Ok(serde_json::json!({
        "file_path": file_path,
        "language": file_path.extension().and_then(|ext| ext.to_str()).unwrap_or("text"),
        "line_count": content.lines().count(),
        "symbol_count": symbol_count,
        "symbols_shown": shown.len(),
        "symbols_truncated": shown.len() < symbol_count || provenance.catalog_truncated,
        "catalog_truncated": provenance.catalog_truncated,
        "symbols": shown,
        "module_role": if class_count > function_count { "Class definitions" } else { "Function module" },
        "symbol_index_miss": provenance.live_parse,
        "source_freshness": "live",
        "pdg_status": pdg_status,
        "retrieval": {
            "tfidf_status": "not_used_exact",
            "neural_status": "not_used_exact",
            "partial": matches!(pdg_status, "partial" | "stale"),
            "max_latency_ms": budget.max_latency_ms,
            "allow_partial": budget.allow_partial
        }
    }))
}

async fn resident_file_relations(
    registry: &Arc<ProjectRegistry>,
    live: &LiveProject,
    symbols: &[CatalogSymbol],
    source_stale: bool,
    budget: WorkBudget,
    started: Instant,
) -> (HashMap<String, Value>, &'static str) {
    if source_stale {
        return (HashMap::new(), "stale");
    }

    let Some(handle) = registry.try_get_loaded(live.root()).await else {
        return (HashMap::new(), "not_loaded");
    };
    let guard = handle.read().await;
    let Some(pdg) = guard.pdg() else {
        return (HashMap::new(), "not_loaded");
    };
    let mut result = HashMap::new();
    for symbol in symbols {
        if budget.elapsed(started) {
            return (result, "partial");
        }
        let Some(node_id) = pdg
            .find_by_symbol(&symbol.node_id)
            .or_else(|| pdg.find_by_symbol(&symbol.symbol_name))
        else {
            continue;
        };
        let dependencies: Vec<Value> = pdg.neighbors(node_id).iter().filter_map(|&id| {
            let node = pdg.get_node(id)?;
            let file = live.file(&node.file_path).ok()?;
            Some(serde_json::json!({ "name": node.name, "type": node_type_str(&node.node_type), "file": file }))
        }).take(50).collect();
        let dependents: Vec<Value> = get_direct_callers(pdg, node_id).iter().filter_map(|&id| {
            let node = pdg.get_node(id)?;
            let file = live.file(&node.file_path).ok()?;
            Some(serde_json::json!({ "name": node.name, "type": node_type_str(&node.node_type), "file": file }))
        }).take(50).collect();
        let cross_file_refs: Vec<Value> = pdg.neighbors(node_id).iter().filter_map(|&id| {
            let node = pdg.get_node(id)?;
            let file = live.file(&node.file_path).ok()?;
            if file != symbol.file_path { Some(serde_json::json!({ "symbol": node.name, "file": file, "relationship": "dependency" })) } else { None }
        }).take(50).collect();
        result.insert(
            symbol.node_id.clone(),
            serde_json::json!({
                "dependencies": dependencies,
                "dependents": dependents,
                "cross_file_refs": cross_file_refs,
            }),
        );
    }
    (result, "fresh")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::mcp::helpers::test_registry_for;
    use tempfile::tempdir;

    #[tokio::test]
    async fn test_file_summary_requires_indexed_project() {
        let dir = tempdir().unwrap();
        let registry = test_registry_for(dir.path());
        let args = serde_json::json!({ "file_path": "/some/file.rs" });
        assert!(FileSummaryHandler.execute(&registry, args).await.is_err());
    }
}