Skip to main content

lean_ctx_ext/core/community/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Community detection on the code graph.
3//!
4//! A hardened Leiden engine (`leiden`) clusters files into cohesive modules,
5//! with robustness passes for super-hubs and oversized/low-cohesion communities
6//! (`hardening`) and **stable ids across rebuilds** (`stable_ids`). The
7//! engine is storage-agnostic: it runs on the PropertyGraph (SQLite) and on any
8//! [`GraphProvider`], so `ctx_architecture` and the dashboard graph view share
9//! one implementation and report identical community ids.
10
11use std::collections::HashMap;
12
13use rusqlite::Connection;
14use serde::Serialize;
15
16use crate::core::graph_provider::GraphProvider;
17use crate::core::property_graph::GraphSource;
18
19pub mod graph;
20pub mod hardening;
21pub mod leiden;
22pub mod stable_ids;
23#[cfg(test)]
24pub mod tests;
25
26use graph::{AdjGraph, edge_counts};
27
28#[derive(Debug, Clone, Serialize)]
29pub struct Community {
30    pub id: usize,
31    pub files: Vec<String>,
32    pub internal_edges: usize,
33    pub external_edges: usize,
34    pub cohesion: f64,
35}
36
37#[derive(Debug, Clone, Serialize)]
38pub struct CommunityResult {
39    pub communities: Vec<Community>,
40    pub modularity: f64,
41    pub node_count: usize,
42    pub edge_count: usize,
43}
44
45impl CommunityResult {
46    fn empty() -> Self {
47        Self {
48            communities: Vec::new(),
49            modularity: 0.0,
50            node_count: 0,
51            edge_count: 0,
52        }
53    }
54
55    /// `file_path → community_id` for every assigned node.
56    pub fn assignment(&self) -> HashMap<String, usize> {
57        self.assignment_min_size(1)
58    }
59
60    /// `file_path → community_id`, restricted to communities with at least
61    /// `min_size` members. Singletons (isolated files) are dropped so the
62    /// dashboard can fall back to a neutral/language colour instead of painting
63    /// every orphan file a distinct hue.
64    pub fn assignment_min_size(&self, min_size: usize) -> HashMap<String, usize> {
65        let mut map = HashMap::new();
66        for community in &self.communities {
67            if community.files.len() < min_size {
68                continue;
69            }
70            for file in &community.files {
71                map.insert(file.clone(), community.id);
72            }
73        }
74        map
75    }
76}
77
78/// Detect communities on the PropertyGraph (ids are deterministic but not
79/// remapped to a previous run). Prefer [`detect_communities_stable`] when a
80/// project root is available.
81pub fn detect_communities(conn: &Connection) -> CommunityResult {
82    let graph = AdjGraph::from_property_graph(conn);
83    analyze(&graph, None).1
84}
85
86/// Detect communities on the PropertyGraph with ids kept stable across rebuilds
87/// (remapped to, and persisted alongside, the project's previous assignment).
88///
89/// Pass the opened `CodeGraph` for a result that is served: the partition and
90/// every number in the result are then computed over the files served now
91/// (`AdjGraph::from_property_graph`). A bare connection reads the raw store.
92pub fn detect_communities_stable<S: GraphSource + ?Sized>(
93    source: &S,
94    project_root: &str,
95) -> CommunityResult {
96    let graph = AdjGraph::from_property_graph(source);
97    detect_stable(&graph, project_root)
98}
99
100/// Detect communities on any [`GraphProvider`] (PropertyGraph or graph index)
101/// with stable ids. This is the entry point for the dashboard graph view.
102pub fn detect_communities_for_provider(gp: &GraphProvider, project_root: &str) -> CommunityResult {
103    let graph = AdjGraph::from_provider(gp);
104    detect_stable(&graph, project_root)
105}
106
107fn detect_stable(graph: &AdjGraph, project_root: &str) -> CommunityResult {
108    if graph.node_count() == 0 {
109        return CommunityResult::empty();
110    }
111    // The persisted assignment is itself derived from the sources of an
112    // earlier run. Only the entries of files in today's graph are used; it is
113    // rewritten below from today's graph, so a withdrawn file leaves it.
114    let previous = stable_ids::load_previous(project_root).map(|mut previous| {
115        previous.retain(|file, _| graph.node_to_idx.contains_key(file));
116        previous
117    });
118    let (assignment, result) = analyze(graph, previous.as_ref());
119    stable_ids::save_assignment(project_root, &graph.node_ids, &assignment);
120    result
121}
122
123/// Full pipeline: partition (hub-aware) → resplit → canonicalize → optional
124/// remap to the previous assignment. Returns the final per-node assignment and
125/// the presentation-ready result.
126fn analyze(
127    graph: &AdjGraph,
128    previous: Option<&HashMap<String, usize>>,
129) -> (Vec<usize>, CommunityResult) {
130    let n = graph.node_count();
131    if n == 0 {
132        return (Vec::new(), CommunityResult::empty());
133    }
134
135    let mut assignment = hardening::partition_with_hub_exclusion(graph);
136    hardening::split_oversized_and_incohesive(graph, &mut assignment);
137    let mut assignment = stable_ids::canonicalize(graph, &assignment);
138    if let Some(prev) = previous
139        && !prev.is_empty()
140    {
141        assignment = stable_ids::remap_to_previous(graph, &assignment, prev);
142    }
143
144    let result = build_result(graph, &assignment);
145    (assignment, result)
146}
147
148fn build_result(graph: &AdjGraph, assignment: &[usize]) -> CommunityResult {
149    let mut groups: HashMap<usize, Vec<usize>> = HashMap::new();
150    for (i, &c) in assignment.iter().enumerate() {
151        groups.entry(c).or_default().push(i);
152    }
153
154    let mut communities: Vec<Community> = groups
155        .into_iter()
156        .map(|(id, mut members)| {
157            members.sort_unstable();
158            let (internal, external) = edge_counts(graph, &members);
159            let total = (internal + external).max(1) as f64;
160            Community {
161                id,
162                files: members.iter().map(|&i| graph.node_ids[i].clone()).collect(),
163                internal_edges: internal,
164                external_edges: external,
165                cohesion: internal as f64 / total,
166            }
167        })
168        .collect();
169
170    // Largest, most cohesive communities first; ids stay meaningful/stable.
171    communities.sort_by(|a, b| {
172        b.files
173            .len()
174            .cmp(&a.files.len())
175            .then(
176                b.cohesion
177                    .partial_cmp(&a.cohesion)
178                    .unwrap_or(std::cmp::Ordering::Equal),
179            )
180            .then(a.id.cmp(&b.id))
181    });
182
183    CommunityResult {
184        communities,
185        modularity: leiden::compute_modularity(graph, assignment),
186        node_count: graph.node_count(),
187        edge_count: graph.edge_count(),
188    }
189}