Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(communities): exclude external nodes from community membership (#2611)
Aman11814310c4ea
diff --git a/packages/core/src/repowise/core/analysis/communities.py b/packages/core/src/repowise/core/analysis/communities.pyindex d90d4d78e..cb5ced286 100644--- a/packages/core/src/repowise/core/analysis/communities.py+++ b/packages/core/src/repowise/core/analysis/communities.py@@ -36,6 +36,29 @@ log = structlog.get_logger(__name__)_MAX_COMMUNITY_FRACTION = 0.30_MIN_SPLIT_SIZE = 20+# Stored community id for a node the partition leaves out. Persisted rows carry+# a NOT NULL id defaulting to 0, which is the largest real community, so an+# external node must not fall through to it.+NO_COMMUNITY = -1+++def stored_community_id(assignment: dict[str, int], node_id: str) -> int:+ """Community id to persist for *node_id*: its own, else 0, or ``NO_COMMUNITY`` for external code."""+ if node_id in assignment:+ return assignment[node_id]+ return NO_COMMUNITY if is_external(node_id) else 0+++def has_community(community_id: int | None) -> bool:+ """True when *community_id* names a real community.++ ``None`` (never assigned) and ``NO_COMMUNITY`` (external code, left out of+ the partition) both mean no community, so readers must not treat them as a+ cluster.+ """+ return community_id is not None and community_id >= 0++# Edge types to include when building file-level community subgraph.# Was {imports, framework, dynamic, extends, implements}: "dynamic" matched no# real edge, and extends/implements are symbol-to-symbol so they never joined@@ -530,12 +553,14 @@ def detect_file_communities(- communities_info: {community_id: CommunityInfo}- algorithm_used: "leiden" or "louvain""""- # Extract file nodes (exclude external nodes — they're structural noise)+ # Extract file nodes. External and framework nodes are stored as files but+ # are code we do not own: left in, they join the partition (two files that+ # both import `os` get pulled together through it) and inflate members/size.# Sorted: node order seeds the undirected graph's insertion order, and# Louvain/Leiden partitions depend on iteration order even when seeded.file_nodes = sorted(n for n, d in graph.nodes(data=True)- if d.get("node_type", "file") == "file"+ if d.get("node_type", "file") == "file" and not is_external(n))if not file_nodes:@@ -642,19 +667,11 @@ def detect_file_communities(# Labels and conductance come from the production members: tests were kept# out of the partition so they would not shape a community, and they must# not name it either. The non-core catch-all is labelled from what it has.- #- # External and framework nodes are stored as files, so they reach the- # partition, but they must not name a community either. They have no- # directory, so a big community with no dominant segment fell through to- # the filename-stem strategy, where eight `external:rich.*` imports share- # the stem `external:rich` and won: this repo's largest community was- # labelled after a third-party library that every view hides.label_members: dict[int, list[str]] = {}for cid, members in community_members.items():sorted_members = sorted(members)prod_members = [m for m in sorted_members if not non_core[m]]- owned = [m for m in prod_members if not is_external(m)]- label_members[cid] = owned or prod_members or sorted_members+ label_members[cid] = prod_members or sorted_memberscommunities_info[cid] = CommunityInfo(community_id=cid,label=_heuristic_label(label_members[cid], cid, extra_generic),diff --git a/packages/core/src/repowise/core/ingestion/graph/_metrics.py b/packages/core/src/repowise/core/ingestion/graph/_metrics.pyindex ee3a2113c..a5d7569ca 100644--- a/packages/core/src/repowise/core/ingestion/graph/_metrics.py+++ b/packages/core/src/repowise/core/ingestion/graph/_metrics.py@@ -72,6 +72,8 @@ class MetricsMixin:Used to materialize the ``graph_metrics`` table. Computes every metricfrom NetworkX (or returns the cached/SQL-loaded values when present)."""+ from repowise.core.analysis.communities import stored_community_id+pr = self.pagerank()bc = self.betweenness_centrality()cd = self.community_detection()@@ -86,7 +88,7 @@ class MetricsMixin:n: {"pagerank": pr.get(n, 0.0),"betweenness": bc.get(n, 0.0),- "community_id": cd.get(n, 0),+ "community_id": stored_community_id(cd, n),"in_degree": ind.get(n, 0),"out_degree": outd.get(n, 0),}diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.pyindex 7013a95c3..03c8b816a 100644--- a/packages/core/src/repowise/core/persistence/crud/graph.py+++ b/packages/core/src/repowise/core/persistence/crud/graph.py@@ -845,6 +845,8 @@ async def get_cross_community_edges(GraphEdge.__table__.c.repository_id == repository_id,source_node.c.community_id == community_id,target_node.c.community_id != community_id,+ # External code is stored with no community (-1); it is not a target.+ target_node.c.community_id >= 0,# Only count file-level edges for meaningful community crossingsource_node.c.node_type == "file",target_node.c.node_type == "file",diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex 0e4e7a6af..773651844 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -416,6 +416,7 @@ async def persist_graph_nodes(update path can refresh ``graph_nodes`` (including symbol-levelPageRank / betweenness) without constructing a full ``PipelineResult``."""+ from repowise.core.analysis.communities import stored_community_idfrom repowise.core.persistence import (batch_upsert_graph_metrics,batch_upsert_graph_node_membership,@@ -465,7 +466,7 @@ async def persist_graph_nodes(# per-symbol UI panel shows real centrality instead of 0."pagerank": pr.get(node_id, sym_pr.get(node_id, 0.0)),"betweenness": bc.get(node_id, sym_bc.get(node_id, 0.0)),- "community_id": cd.get(node_id, 0),+ "community_id": stored_community_id(cd, node_id),}# Scored → its commit; in no scoring → NULL, the unscored marker;diff --git a/packages/server/src/repowise/server/mcp_server/_graph_utils.py b/packages/server/src/repowise/server/mcp_server/_graph_utils.pyindex 13b4996ad..b8b527199 100644--- a/packages/server/src/repowise/server/mcp_server/_graph_utils.py+++ b/packages/server/src/repowise/server/mcp_server/_graph_utils.py@@ -10,6 +10,7 @@ import jsonfrom collections import Counterfrom typing import Any+from repowise.core.analysis.communities import has_communityfrom repowise.core.analysis.execution_flows import FlowTermination, classify_terminationfrom repowise.core.analysis.execution_graph import (is_excluded_execution_path,@@ -204,7 +205,7 @@ async def resolve_trace_communities(for nid in trace:n = node_cache.get(nid)cid = n.community_id if n else 0- if cid is not None and cid not in seen:+ if has_community(cid) and cid not in seen:seen.add(cid)communities_visited.append(cid)@@ -273,8 +274,12 @@ def build_visual_context(# --- Community analysis ---src_meta = node_meta.get(source)tgt_meta = node_meta.get(target)- src_community = src_meta.community_id if src_meta else None- tgt_community = tgt_meta.community_id if tgt_meta else None+ src_community = (+ src_meta.community_id if src_meta and has_community(src_meta.community_id) else None+ )+ tgt_community = (+ tgt_meta.community_id if tgt_meta and has_community(tgt_meta.community_id) else None+ )context["community"] = {"source_community": src_community,@@ -287,7 +292,8 @@ def build_visual_context(bridge_nodes = []nodes_by_community: dict[int, set[str]] = {}for n in nodes:- nodes_by_community.setdefault(n.community_id, set()).add(n.node_id)+ if has_community(n.community_id):+ nodes_by_community.setdefault(n.community_id, set()).add(n.node_id)src_community_nodes = nodes_by_community.get(src_community, set())tgt_community_nodes = nodes_by_community.get(tgt_community, set())diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.pyindex 28d7481d6..ec427cc68 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py@@ -17,6 +17,7 @@ from sqlalchemy import func, selectfrom sqlalchemy.exc import SQLAlchemyErrorfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.communities import has_communityfrom repowise.core.analysis.doc_drift.constants import (REFERENCE_BASIS,UNAVAILABLE_NO_TABLE,@@ -638,7 +639,7 @@ async def _resolve_community(repo_id = repository.idnode = await get_graph_node(session, repo_id, target)- if node is None or node.community_id is None:+ if node is None or not has_community(node.community_id):result_data["community"] = Nonereturndiff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.pyindex a2b29d32c..3b56f58b0 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py@@ -18,6 +18,7 @@ from typing import Anyfrom sqlalchemy import func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.communities import has_communityfrom repowise.core.analysis.decisions.lifecycle import is_governingfrom repowise.core.analysis.decisions.scope import binds_to_pathsfrom repowise.core.generation.page_selection import STALE_STATUSES@@ -844,7 +845,7 @@ async def _resolve_one_target())gn = res.scalar_one_or_none()- if gn and gn.community_id is not None:+ if gn and has_community(gn.community_id):_cmeta: dict[str, Any] = {}with contextlib.suppress(json.JSONDecodeError, TypeError):_cmeta = json.loads(gn.community_meta_json or "{}")diff --git a/packages/server/src/repowise/server/mcp_server/tool_dependency.py b/packages/server/src/repowise/server/mcp_server/tool_dependency.pyindex 829749a18..ca31a4685 100644--- a/packages/server/src/repowise/server/mcp_server/tool_dependency.py+++ b/packages/server/src/repowise/server/mcp_server/tool_dependency.py@@ -6,6 +6,7 @@ from typing import Anyfrom sqlalchemy import select+from repowise.core.analysis.communities import has_communityfrom repowise.core.co_change import parse_partnersfrom repowise.core.ingestion.models import TEMPORAL_EDGE_TYPESfrom repowise.core.persistence.database import get_session@@ -232,8 +233,12 @@ def _build_visual_context(# --- Community analysis ---src_meta = node_meta.get(source)tgt_meta = node_meta.get(target)- src_community = src_meta.community_id if src_meta else None- tgt_community = tgt_meta.community_id if tgt_meta else None+ src_community = (+ src_meta.community_id if src_meta and has_community(src_meta.community_id) else None+ )+ tgt_community = (+ tgt_meta.community_id if tgt_meta and has_community(tgt_meta.community_id) else None+ )context["community"] = {"source_community": src_community,@@ -246,8 +251,9 @@ def _build_visual_context(# Find nodes that have edges crossing these two communitiesbridge_nodes = []nodes_by_community: dict[int, set[str]] = {}- for n in nodes:- nodes_by_community.setdefault(n.community_id, set()).add(n.node_id)+ for n in nodes:+ if has_community(n.community_id):+ nodes_by_community.setdefault(n.community_id, set()).add(n.node_id)src_community_nodes = nodes_by_community.get(src_community, set())tgt_community_nodes = nodes_by_community.get(tgt_community, set())diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/graph.py b/packages/server/src/repowise/server/mcp_server/tool_overview/graph.pyindex 87b6e35b3..26a29e896 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview/graph.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/graph.py@@ -78,7 +78,7 @@ def _build_community_summary(all_nodes: list[GraphNode]) -> list[dict[str, Any]]"""Top-10 communities by size, skipping generic/unhelpful labels."""community_groups: dict[int, list[GraphNode]] = defaultdict(list)for n in all_nodes:- if n.node_type == "file" and n.community_id is not None:+ if n.node_type == "file" and n.community_id is not None and n.community_id >= 0:community_groups[n.community_id].append(n)generic_labels = {"packages", "src", "lib", "core", "app", ""}diff --git a/tests/unit/analysis/test_community_labels.py b/tests/unit/analysis/test_community_labels.pyindex 6bf039fb2..fad36b9ae 100644--- a/tests/unit/analysis/test_community_labels.py+++ b/tests/unit/analysis/test_community_labels.py@@ -130,6 +130,25 @@ class TestExternalNodesNeverName:assert not ci.label.startswith("external:")+class TestExternalNodesAreNotMembers:+ def test_no_member_is_external_and_size_counts_repo_files_only(self):+ prod = [f"pkg/area{i}/f{i}.py" for i in range(6)]+ ext = ["external:os", "external:rich.console", "framework:django"]+ edges = list(itertools.pairwise(prod)) + [(p, e) for p in prod for e in ext]+ assignment, info, _ = detect_file_communities(_graph(prod + ext, edges))+ assert not any(e in assignment for e in ext)+ members = [m for ci in info.values() for m in ci.members]+ assert sorted(members) == sorted(prod)+ assert sum(ci.size for ci in info.values()) == len(prod)++ def test_shared_external_import_does_not_join_unrelated_files(self):+ # Two files with no edge between them, both importing external:os.+ paths = ["a/one.py", "b/two.py", "external:os"]+ edges = [("a/one.py", "external:os"), ("b/two.py", "external:os")]+ assignment, _info, _ = detect_file_communities(_graph(paths, edges))+ assert assignment["a/one.py"] != assignment["b/two.py"]++class TestRootFirstLabels:def test_sub_label_follows_path_order(self):# Frequency picks "ingestion" (in every path) as primary and "engine"diff --git a/tests/unit/persistence/test_external_nodes_have_no_community.py b/tests/unit/persistence/test_external_nodes_have_no_community.pynew file mode 100644index 000000000..b9a057b64--- /dev/null+++ b/tests/unit/persistence/test_external_nodes_have_no_community.py@@ -0,0 +1,67 @@+"""External nodes are stored with no community, not as members of community 0.++``graph_nodes.community_id`` is NOT NULL and defaults to 0, which is the largest+real community. An external node left out of the partition must not fall+through to it, or it reappears in that community's member list.+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.communities import NO_COMMUNITY, has_community, stored_community_id+from repowise.core.persistence.crud.graph import (+ batch_upsert_graph_edges,+ batch_upsert_graph_nodes,+ get_community_members,+ get_cross_community_edges,+)+from tests.unit.persistence.helpers import insert_repo+++def test_stored_community_id():+ assignment = {"a.py": 3}+ assert stored_community_id(assignment, "a.py") == 3+ assert stored_community_id(assignment, "external:os") == NO_COMMUNITY+ assert stored_community_id(assignment, "framework:django") == NO_COMMUNITY+ # A symbol is not in the file assignment and keeps the default.+ assert stored_community_id(assignment, "a.py::f") == 0+++def _node(node_id: str, community_id: int) -> dict:+ return {"node_id": node_id, "node_type": "file", "community_id": community_id}+++def test_has_community():+ assert has_community(0)+ assert has_community(7)+ assert not has_community(None)+ assert not has_community(NO_COMMUNITY)+++async def test_external_is_not_a_member_or_a_cross_community_target(async_session):+ repo = await insert_repo(async_session)+ await batch_upsert_graph_nodes(+ async_session,+ repo.id,+ [+ _node("a.py", 0),+ _node("b.py", 1),+ _node("external:os", stored_community_id({}, "external:os")),+ ],+ )+ await batch_upsert_graph_edges(+ async_session,+ repo.id,+ [+ {"source_node_id": "a.py", "target_node_id": "b.py", "edge_type": "imports"},+ {"source_node_id": "a.py", "target_node_id": "external:os", "edge_type": "imports"},+ ],+ )+ await async_session.commit()++ members = await get_community_members(async_session, repo.id, 0)+ assert [m.node_id for m in members] == ["a.py"]+ crossing = await get_cross_community_edges(async_session, repo.id, 0)+ assert crossing == [{"target_community_id": 1, "edge_count": 1}]diff --git a/tests/unit/server/mcp/test_external_nodes_not_a_community.py b/tests/unit/server/mcp/test_external_nodes_not_a_community.pynew file mode 100644index 000000000..d109246f7--- /dev/null+++ b/tests/unit/server/mcp/test_external_nodes_not_a_community.py@@ -0,0 +1,18 @@+from types import SimpleNamespace++import pytest++from repowise.server.mcp_server._graph_utils import resolve_trace_communities+++async def test_external_trace_node_is_not_a_visited_community():+ cache = {+ "a.py": SimpleNamespace(community_id=0),+ "external:os": SimpleNamespace(community_id=-1),+ }+ visited, crosses = await resolve_trace_communities(+ None, "repo", ["a.py", "external:os"], cache+ )+ assert visited == [0]+ assert crosses is False\ No newline at end of file