lean-ctx 3.12.5

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
Documentation
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
// SPDX-License-Identifier: Apache-2.0
use crate::dashboard::routes::helpers::detect_project_root_for_dashboard;

pub(super) fn get_route(
    path: &str,
    query_str: &str,
) -> Option<(&'static str, &'static str, String)> {
    match path {
        "/api/heatmap" => Some(heatmap()),
        "/api/graph" => Some(graph()),
        "/api/graph/stats" => Some(stats()),
        "/api/graph-files" => Some(graph_files()),
        "/api/routes" => Some(routes(query_str)),
        _ => None,
    }
}

fn heatmap() -> (&'static str, &'static str, String) {
    let project_root = detect_project_root_for_dashboard();
    let open = match super::open_graph(&project_root) {
        Ok(open) => open,
        Err(building) => return building,
    };
    let entries = build_heatmap_json(&open.provider);
    ("200 OK", "application/json", entries)
}

fn graph() -> (&'static str, &'static str, String) {
    let root = detect_project_root_for_dashboard();
    let open = match super::open_graph(&root) {
        Ok(open) => open,
        Err(building) => return building,
    };
    let gp = &open.provider;

    // Community assignment (stable ids from the hardened Leiden engine). Shared
    // with the call-graph tab via the same provider, so colours stay consistent.
    let community = lean_ctx::core::community::detect_communities_for_provider(gp, &root);
    let community_map = community.assignment_min_size(2);
    let community_count = community
        .communities
        .iter()
        .filter(|c| c.files.len() >= 2)
        .count();

    let all_edges = gp.edges();
    let mut edge_stats: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
    for edge in &all_edges {
        *edge_stats.entry(edge.kind.as_str()).or_default() += 1;
    }
    let connected: std::collections::HashSet<&str> = all_edges
        .iter()
        .flat_map(|e| [e.from.as_str(), e.to.as_str()])
        .collect();
    let file_count = gp.file_count();
    let isolated_count = file_count - connected.len().min(file_count);

    // Graphify-style static analyses over the *real* directed dependency edges
    // (import / reexport) — God-Nodes (most connected) and import cycles.
    let god_nodes = lean_ctx::core::graph_analysis::compute_god_nodes(&all_edges, 12);
    let import_cycles = lean_ctx::core::graph_analysis::find_import_cycles(&all_edges, 20);
    let bridges = lean_ctx::core::graph_analysis::compute_bridge_centrality(&all_edges, 10);
    let surprising_connections =
        lean_ctx::core::graph_analysis::find_surprising_connections(&all_edges, &community_map, 10);

    // Per-community cohesion (module quality): internal vs external edge ratio,
    // already computed by the community engine. Surfaced for the dashboard.
    let mut community_cohesion: Vec<serde_json::Value> = community
        .communities
        .iter()
        .filter(|c| c.files.len() >= 2)
        .map(|c| {
            serde_json::json!({
                "id": c.id,
                "files": c.files.len(),
                "cohesion": (c.cohesion * 1000.0).round() / 1000.0,
                "internal_edges": c.internal_edges,
                "external_edges": c.external_edges,
            })
        })
        .collect();
    community_cohesion.sort_by(|a, b| {
        b["files"]
            .as_u64()
            .unwrap_or(0)
            .cmp(&a["files"].as_u64().unwrap_or(0))
    });
    community_cohesion.truncate(12);

    let files: Vec<serde_json::Value> = gp
        .file_paths()
        .iter()
        .filter_map(|p| {
            gp.get_file_entry(p).map(|f| {
                serde_json::json!({
                    "path": f.path,
                    "language": f.language,
                    "token_count": f.token_count,
                    "line_count": f.line_count,
                    "exports": f.exports,
                    "summary": f.summary,
                    "community": community_map.get(&f.path),
                })
            })
        })
        .collect();

    let edges: Vec<serde_json::Value> = all_edges
        .iter()
        .map(|e| {
            serde_json::json!({
                "from": e.from,
                "to": e.to,
                "kind": e.kind,
                "weight": e.weight,
                "confidence": (lean_ctx::core::graph_analysis::edge_confidence(&e.kind, e.weight)
                    * 1000.0)
                    .round()
                    / 1000.0,
            })
        })
        .collect();

    // When the graph is empty, explain *why*: a project built mostly from
    // graph-unsupported languages (e.g. Lua/Luau, #360) would otherwise leave the
    // dashboard stuck on an unhelpful "run index build" hint that never helps.
    let graph_support = if files.is_empty() {
        let unsupported: Vec<serde_json::Value> =
            lean_ctx::core::language_capabilities::scan_unsupported_source_languages(&root, 5000)
                .into_iter()
                .map(|(language, file_count)| {
                    serde_json::json!({ "language": language, "files": file_count })
                })
                .collect();
        Some(serde_json::json!({
            "supported_languages": lean_ctx::core::language_capabilities::graph_supported_language_names(),
            "unsupported_present": unsupported,
        }))
    } else {
        None
    };

    // Realized per-language coverage (real symbol/import counts) — works for
    // either backend now that the facade surfaces symbols + edges (#696 phase C).
    let language_matrix = super::capability_matrix::realized_from_provider(gp, None, &root);

    let val = serde_json::json!({
        "project_root": super::project_basename(&root),
        "project_root_full": root,
        "files": files,
        "edges": edges,
        "edge_stats": edge_stats,
        "isolated_node_count": isolated_count,
        "orphan_rate": if file_count > 0 {
            (isolated_count as f64 / file_count as f64 * 100.0).round() / 100.0
        } else {
            0.0
        },
        "graph_support": graph_support,
        "language_matrix": language_matrix,
        "community_count": community_count,
        "god_nodes": god_nodes,
        "import_cycles": import_cycles,
        "bridge_nodes": bridges.nodes,
        "betweenness_sampled": bridges.sampled,
        "surprising_connections": surprising_connections,
        "community_cohesion": community_cohesion,
    });
    let json = serde_json::to_string(&val)
        .unwrap_or_else(|_| "{\"error\":\"failed to serialize\"}".to_string());
    ("200 OK", "application/json", json)
}

/// `POST /api/graph/enrich`: writes git commits, tests and knowledge entries
/// into the project's PropertyGraph and returns the counts. A GET is refused:
/// reads never write.
pub(super) fn enrich_route(method: &str) -> (&'static str, &'static str, String) {
    if method.eq_ignore_ascii_case("POST") {
        enrich()
    } else {
        (
            "405 Method Not Allowed",
            "application/json",
            crate::dashboard::routes::helpers::json_err(
                "use POST to enrich the project graph: it writes to the graph",
            ),
        )
    }
}

fn enrich() -> (&'static str, &'static str, String) {
    let root = detect_project_root_for_dashboard();
    let project_path = std::path::Path::new(&root);
    let outcome = match lean_ctx::core::property_graph::CodeGraph::open(&root) {
        Ok(graph) => {
            match lean_ctx::core::graph_enricher::enrich_graph(&graph, project_path, 500) {
                Ok(stats) => {
                    let nc = graph.node_count().unwrap_or(0);
                    let ec = graph.edge_count().unwrap_or(0);
                    Ok(serde_json::json!({
                        "commits_indexed": stats.commits_indexed,
                        "tests_indexed": stats.tests_indexed,
                        "knowledge_indexed": stats.knowledge_indexed,
                        "edges_created": stats.edges_created,
                        "total_nodes": nc,
                        "total_edges": ec,
                    }))
                }
                Err(e) => {
                    tracing::warn!("graph enrich error: {e}");
                    Err(EnrichFailure::Enrichment)
                }
            }
        }
        Err(e) => {
            tracing::warn!("graph open error: {e}");
            Err(EnrichFailure::GraphUnavailable)
        }
    };
    enrich_response(outcome)
}

/// Why `POST /api/graph/enrich` wrote nothing.
#[derive(Debug, Clone, Copy)]
enum EnrichFailure {
    GraphUnavailable,
    Enrichment,
}

/// Maps an enrichment outcome to its HTTP answer: a failure carries an error
/// status and the dashboard's `{"error": …}` body, never `200 OK`.
fn enrich_response(
    outcome: Result<serde_json::Value, EnrichFailure>,
) -> (&'static str, &'static str, String) {
    use crate::dashboard::routes::helpers::json_err;
    match outcome {
        Ok(counts) => ("200 OK", "application/json", counts.to_string()),
        Err(EnrichFailure::GraphUnavailable) => (
            "503 Service Unavailable",
            "application/json",
            json_err("the project graph could not be opened; retry once it is free"),
        ),
        Err(EnrichFailure::Enrichment) => (
            "500 Internal Server Error",
            "application/json",
            json_err("graph enrichment failed; the dashboard log names the cause"),
        ),
    }
}

fn stats() -> (&'static str, &'static str, String) {
    let root = detect_project_root_for_dashboard();
    let result = match lean_ctx::core::graph_provider::open_best_effort(&root) {
        Some(open) => {
            let nc = open.provider.node_count().unwrap_or(0);
            let ec = open.provider.edge_count().unwrap_or(0);
            match open.source {
                lean_ctx::core::graph_provider::GraphProviderSource::PropertyGraph => {
                    serde_json::json!({
                        "source": "property_graph",
                        "node_count": nc,
                        "edge_count": ec,
                    })
                }
                lean_ctx::core::graph_provider::GraphProviderSource::GraphIndex => {
                    serde_json::json!({
                        "source": "graph_index",
                        "node_count": nc,
                        "edge_count": ec,
                    })
                }
            }
        }
        _ => {
            serde_json::json!({
                "source": "none",
                "node_count": 0,
                "edge_count": 0,
            })
        }
    };
    let json = serde_json::to_string(&result).unwrap_or_else(|_| "{}".to_string());
    ("200 OK", "application/json", json)
}

fn graph_files() -> (&'static str, &'static str, String) {
    let root = detect_project_root_for_dashboard();
    let open = match super::open_graph(&root) {
        Ok(open) => open,
        Err(building) => return building,
    };
    let gp = &open.provider;
    let mut files: Vec<serde_json::Value> = gp
        .file_paths()
        .iter()
        .filter_map(|p| {
            gp.get_file_entry(p).map(|f| {
                serde_json::json!({
                    "path": f.path,
                    "language": f.language,
                    "token_count": f.token_count,
                    "line_count": f.line_count,
                })
            })
        })
        .collect();
    files.sort_by(|a, b| {
        b["token_count"]
            .as_u64()
            .unwrap_or(0)
            .cmp(&a["token_count"].as_u64().unwrap_or(0))
    });
    files.truncate(500);
    let json = serde_json::json!({ "files": files, "project_root_full": root });
    let out = serde_json::to_string(&json).unwrap_or_else(|_| "{\"files\":[]}".to_string());
    ("200 OK", "application/json", out)
}

fn routes(_query_str: &str) -> (&'static str, &'static str, String) {
    let root = detect_project_root_for_dashboard();
    let open = match super::open_graph(&root) {
        Ok(open) => open,
        Err(building) => return building,
    };
    let gp = &open.provider;
    let file_paths = gp.file_paths();

    let routes = lean_ctx::core::route_extractor::extract_routes_from_project(&root, &file_paths);
    let route_candidate_count = file_paths
        .iter()
        .filter(|p| {
            std::path::Path::new(p.as_str())
                .extension()
                .and_then(|e| e.to_str())
                .is_some_and(|e| {
                    matches!(e, "js" | "ts" | "py" | "rs" | "java" | "rb" | "go" | "kt")
                })
        })
        .count();
    let payload = serde_json::json!({
        "routes": routes,
        "indexed_file_count": file_paths.len(),
        "route_candidate_count": route_candidate_count,
    });
    let json = serde_json::to_string(&payload).unwrap_or_else(|_| "{\"routes\":[]}".to_string());
    ("200 OK", "application/json", json)
}

fn build_heatmap_json(gp: &lean_ctx::core::graph_provider::GraphProvider) -> String {
    let all_edges = gp.edges();
    let mut connection_counts: std::collections::HashMap<String, usize> =
        std::collections::HashMap::new();
    for edge in &all_edges {
        *connection_counts.entry(edge.from.clone()).or_default() += 1;
        *connection_counts.entry(edge.to.clone()).or_default() += 1;
    }

    let paths = gp.file_paths();
    let mut max_tokens = 1usize;
    for path in &paths {
        if let Some(entry) = gp.get_file_entry(path) {
            max_tokens = max_tokens.max(entry.token_count);
        }
    }
    let max_tokens = max_tokens as f64;
    let max_connections = connection_counts.values().max().copied().unwrap_or(1) as f64;

    let mut entries: Vec<serde_json::Value> = paths
        .iter()
        .filter_map(|p| {
            gp.get_file_entry(p).map(|f| {
                let connections = connection_counts.get(&f.path).copied().unwrap_or(0);
                let token_norm = f.token_count as f64 / max_tokens;
                let conn_norm = connections as f64 / max_connections;
                let heat = token_norm * 0.4 + conn_norm * 0.6;
                serde_json::json!({
                    "path": f.path,
                    "tokens": f.token_count,
                    "connections": connections,
                    "language": f.language,
                    "heat": (heat * 100.0).round() / 100.0,
                })
            })
        })
        .collect();

    entries.sort_by(|a, b| {
        b["heat"]
            .as_f64()
            .unwrap_or(0.0)
            .partial_cmp(&a["heat"].as_f64().unwrap_or(0.0))
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    serde_json::to_string(&entries).unwrap_or_else(|_| "[]".to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn failed_enrichment_answers_an_error_status() {
        for (failure, status) in [
            (EnrichFailure::GraphUnavailable, "503 Service Unavailable"),
            (EnrichFailure::Enrichment, "500 Internal Server Error"),
        ] {
            let (got, kind, body) = enrich_response(Err(failure));
            assert_eq!(got, status);
            assert_eq!(kind, "application/json");
            let json: serde_json::Value = serde_json::from_str(&body).unwrap();
            assert!(json["error"].is_string(), "{body}");
            assert_eq!(json.as_object().map(serde_json::Map::len), Some(1));
        }
        let (got, _, body) = enrich_response(Ok(serde_json::json!({"edges_created": 3})));
        assert_eq!(got, "200 OK");
        assert!(body.contains("\"edges_created\":3"), "{body}");
    }
}