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(overview): stop contradicting the dead-code pass, and rank barrels down (#1464)
Raghav Chamadiya58223b10a3c2
diff --git a/packages/core/src/repowise/core/generation/context/assembler.py b/packages/core/src/repowise/core/generation/context/assembler.pyindex 9d6fcb626..7ab5bb232 100644--- a/packages/core/src/repowise/core/generation/context/assembler.py+++ b/packages/core/src/repowise/core/generation/context/assembler.py@@ -13,6 +13,7 @@ from repowise.core.ids import file_path_of, is_externalfrom repowise.core.ingestion.models import ParsedFile, RepoStructure, Symbolfrom ..categories import file_category+from ..entry_points import entry_point_rank_keyfrom ..models import GenerationConfigfrom .contexts import (ApiContractContext,@@ -57,6 +58,28 @@ def _is_foreign_edge(node: str, path: str) -> bool:_MAX_IMPORTS = 30# Maximum top-files to include in repo overview_MAX_TOP_FILES = 20++# Languages whose imports name a package rather than a file, so most files in a+# live package carry no file-level in-edge. The dead-code analyzer delegates+# these to per-language reachability helpers.+_PACKAGE_GRANULAR_SUFFIXES = re.compile(r"\.(go|java|kt|c|cc|cpp|cxx|h|hh|hpp|hxx)$", re.I)+# Deliberate copy of ``dead_code.analyzer._BARREL_FILENAMES``. Importing the+# analyzer would drag the whole dead-code stack into generation for one+# frozenset. The real fix is a shared reachability predicate both call; until+# then this must be kept in step by hand.+_BARREL_FILENAMES: frozenset[str] = frozenset(+ {+ "__init__.py",+ "index.ts",+ "index.tsx",+ "index.js",+ "index.jsx",+ "index.mts",+ "index.cts",+ "index.mjs",+ "index.cjs",+ }+)# How many rows the concept index may carry. A module page groups directories,# so a wide one can reach several hundred public symbols and the table would# then be longer than the page it is attached to. Rows past this are counted@@ -229,6 +252,50 @@ def _file_dependency_neighbors(graph: Any, path: str, *, incoming: bool) -> listreturn neighbors+def _flow_entry_is_reachable(flow: Any, graph: Any) -> bool:+ """Can anything actually get to this flow's entry point?++ Execution-flow scoring treats zero inbound calls as its strongest positive+ signal, because a symbol nothing calls looks like a front door. File-level+ reachability reads the same evidence in the opposite direction: a file+ nothing imports is ``unreachable_file``. So a file with no importers was+ promoted to Primary Execution Flow #1 *and* reported as dead code, from+ the same fact, on the same index.++ Dead code is right in that argument and the flow is wrong, so drop the+ flow. A conventional entry point is exempt for the same reason the+ dead-code pass exempts it: nothing imports ``main.py`` either.++ Deliberately more forgiving than ``unreachable_file``, in one direction+ only. The analyzer rescues a zero-in-degree file through a dozen further+ checks, several of which need state built during analysis (bundler alias+ targets, never-flag whitelists, per-language package maps) and are not+ reachable from here. Rather than reimplement a second, subtly different+ reachability, this bails out wherever the analyzer is known to be kinder:+ an unresolvable entry point, a barrel, and the languages whose imports are+ package-granular rather than file-granular. A missed drop leaves a wrong+ flow on the page; an over-eager one silently empties the section, which is+ the failure the caller's own comment exists to prevent. See the backlog:+ the real fix is one shared predicate.+ """+ node = graph.nodes.get(flow.entry_point_id, {})+ path = node.get("file_path") or file_path_of(flow.entry_point_id) or ""+ if not path or path not in graph:+ return True+ if graph.nodes[path].get("is_entry_point"):+ return True+ # Go, JVM and C/C++ resolve imports per package, so most files in a live+ # package carry no file-level in-edge at all. The analyzer delegates to a+ # per-language helper here; without one, this check would drop nearly+ # every flow on such a repository.+ if _PACKAGE_GRANULAR_SUFFIXES.search(path):+ return True+ # A barrel is reached by the names it forwards, never by its own path.+ if PurePosixPath(path).name in _BARREL_FILENAMES:+ return True+ return bool(_file_dependency_neighbors(graph, path, incoming=True))++# ---------------------------------------------------------------------------# ContextAssembler# ---------------------------------------------------------------------------@@ -773,6 +840,18 @@ class ContextAssembler:flow_report.flows,key=lambda f: (-f.entry_point_score, f.entry_point_id),)+ flow_graph = graph_builder.graph()+ kept = [f for f in ranked if _flow_entry_is_reachable(f, flow_graph)]+ if len(kept) != len(ranked):+ # The section disappears when this empties it, and a+ # silently empty section is the failure the comment+ # below was written to end. Say how many and why.+ log.info(+ "overview_flows_dropped_unreachable",+ dropped=len(ranked) - len(kept),+ kept=len(kept),+ )+ ranked = keptfor flow in ranked[:5]:execution_flows_list.append({@@ -805,7 +884,16 @@ class ContextAssembler:language_distribution=repo_structure.root_language_distribution,total_files=repo_structure.total_files,total_loc=repo_structure.total_loc,- entry_points=repo_structure.entry_points,+ # Ranked, not filtered. ``is_entry_point`` is a filename heuristic+ # whose generic stem set includes ``index``, so a buried re-export+ # barrel arrived here indistinguishable from a real front door and+ # could lead the list. Dropping glue outright is what the KG+ # curator does, but it would also drop ``packages/cli/src/index.ts``,+ # a genuine package front door in exactly the monorepo shape this+ # product targets. Ranking demotes glue below every real entry+ # without losing one, and ``entry_point_rank_key`` already encodes+ # that order for the KG's answer to the same question.+ entry_points=sorted(repo_structure.entry_points, key=entry_point_rank_key),top_files_by_pagerank=top_files,circular_dependency_count=circular_count,communities=communities_list,diff --git a/tests/unit/generation/test_overview_execution_flows.py b/tests/unit/generation/test_overview_execution_flows.pyindex 8afd666da..3adc974e2 100644--- a/tests/unit/generation/test_overview_execution_flows.py+++ b/tests/unit/generation/test_overview_execution_flows.py@@ -10,6 +10,9 @@ then dropped the section without a word.from __future__ import annotations+from dataclasses import replace++import networkx as nximport pytestfrom structlog.testing import capture_logs@@ -18,14 +21,20 @@ from repowise.core.generation.context_assembler import ContextAssemblerclass _Builder:- """Minimal stand-in for the graph builder's two overview-facing calls."""+ """Minimal stand-in for the graph builder's three overview-facing calls."""- def __init__(self, flows):+ def __init__(self, flows, graph=None):self._flows = flows+ # An empty graph resolves no entry point to a file, which is the+ # "cannot tell" case: the reachability filter keeps every flow.+ self._graph = graph if graph is not None else nx.DiGraph()def community_info(self):return []+ def graph(self):+ return self._graph+def execution_flows(self):return ExecutionFlowReport(total_entry_points_scored=len(self._flows),@@ -87,6 +96,155 @@ def test_overview_context_ranks_flows_by_score(sample_config, sample_repo_struct]+# ---------------------------------------------------------------------------+# a flow entry point nothing can reach is dead code, not a front door+# ---------------------------------------------------------------------------+++def _graph_with(files: dict[str, dict], imports: list[tuple[str, str]]) -> nx.DiGraph:+ """A file graph plus one symbol node per file, as the real builder shapes it."""+ g = nx.DiGraph()+ for path, attrs in files.items():+ g.add_node(path, node_type="file", language="python", **attrs)+ g.add_node(f"{path}::f", node_type="symbol", file_path=path, name="f")+ g.add_edge(path, f"{path}::f", edge_type="defines")+ for src, dst in imports:+ g.add_edge(src, dst, edge_type="imports")+ return g+++def test_unreachable_entry_point_is_not_a_flow(sample_config, sample_repo_structure):+ """Zero inbound calls is the strongest positive signal for a flow entry+ point and the definition of ``unreachable_file``. The same file was+ Primary Execution Flow #1 and dead code on the same index."""+ graph = _graph_with(+ {+ "src/orphan.py": {"is_entry_point": False},+ "src/service.py": {"is_entry_point": False},+ "src/caller.py": {"is_entry_point": False},+ },+ imports=[("src/caller.py", "src/service.py")],+ )+ flows = [_flow("src/orphan.py::f", 0.95, ["a", "b"]), _flow("src/service.py::f", 0.4, ["a"])]++ assembler = ContextAssembler(sample_config)+ ctx = assembler.assemble_repo_overview(+ sample_repo_structure, {}, [], {}, graph_builder=_Builder(flows, graph)+ )++ assert [f["entry_point"] for f in ctx.execution_flows] == ["src/service.py::f"]+++def test_conventional_entry_point_survives_having_no_importers(+ sample_config, sample_repo_structure+):+ """Nothing imports ``main.py`` either, which is why the dead-code pass+ exempts it, and why this filter must too."""+ graph = _graph_with({"src/main.py": {"is_entry_point": True}}, imports=[])+ flows = [_flow("src/main.py::f", 0.95, ["a", "b"])]++ assembler = ContextAssembler(sample_config)+ ctx = assembler.assemble_repo_overview(+ sample_repo_structure, {}, [], {}, graph_builder=_Builder(flows, graph)+ )++ assert [f["entry_point"] for f in ctx.execution_flows] == ["src/main.py::f"]+++ "path",+ [+ "internal/scheduler/queue.go", # Go imports name a package+ "src/main/java/app/Queue.java",+ "src/Queue.kt",+ "src/engine/queue.cpp",+ "include/engine/queue.h",+ "src/features/api/index.ts", # barrel: reached by the names it forwards+ "pkg/sub/__init__.py",+ ],+)+def test_filter_bails_out_where_dead_code_is_kinder(sample_config, sample_repo_structure, path):+ """The analyzer rescues these from unreachable_file through checks this+ filter cannot reach. Over-dropping empties the section silently, so where+ the two models are known to diverge the flow is kept."""+ graph = _graph_with({path: {"is_entry_point": False}}, imports=[])+ flows = [_flow(f"{path}::f", 0.95, ["a", "b"])]++ assembler = ContextAssembler(sample_config)+ ctx = assembler.assemble_repo_overview(+ sample_repo_structure, {}, [], {}, graph_builder=_Builder(flows, graph)+ )++ assert [f["entry_point"] for f in ctx.execution_flows] == [f"{path}::f"]+++def test_dropping_a_flow_is_logged(sample_config, sample_repo_structure):+ """An empty section is a fine outcome; a silent one is not."""+ graph = _graph_with({"src/orphan.py": {"is_entry_point": False}}, imports=[])+ flows = [_flow("src/orphan.py::f", 0.95, ["a", "b"])]++ assembler = ContextAssembler(sample_config)+ with capture_logs() as logs:+ assembler.assemble_repo_overview(+ sample_repo_structure, {}, [], {}, graph_builder=_Builder(flows, graph)+ )++ dropped = [e for e in logs if e["event"] == "overview_flows_dropped_unreachable"]+ assert len(dropped) == 1+ assert dropped[0]["dropped"] == 1+ assert dropped[0]["kept"] == 0+++def test_co_change_alone_does_not_make_an_entry_point_reachable(+ sample_config, sample_repo_structure+):+ """Co-change is a historical association, not a caller."""+ graph = _graph_with({"src/orphan.py": {"is_entry_point": False}}, imports=[])+ graph.add_node("docs/notes.md", node_type="file", language="markdown")+ graph.add_edge("docs/notes.md", "src/orphan.py", edge_type="co_changes")+ flows = [_flow("src/orphan.py::f", 0.95, ["a", "b"])]++ assembler = ContextAssembler(sample_config)+ ctx = assembler.assemble_repo_overview(+ sample_repo_structure, {}, [], {}, graph_builder=_Builder(flows, graph)+ )++ assert ctx.execution_flows == []+++# ---------------------------------------------------------------------------+# barrels are not execution entry points+# ---------------------------------------------------------------------------+++def test_barrels_rank_below_real_entry_points(sample_config, sample_repo_structure):+ """``is_entry_point`` is a filename heuristic whose generic stem set+ includes ``index``, so a buried re-export barrel arrived indistinguishable+ from a front door and could lead the list.++ Demoted rather than dropped: ``packages/cli/src/index.ts`` is a genuine+ package front door in a monorepo, and dropping every glue stem would lose+ it.+ """+ # ``sample_repo_structure`` is module-scoped, so mutating it in place leaks+ # into every later test in this file.+ structure = replace(+ sample_repo_structure,+ entry_points=[+ "src/features/checkout/api/index.ts", # buried re-export leaf+ "packages/cli/src/index.ts", # buried, but a real package entry+ "src/main.py", # conventional name, shallow+ ],+ )++ assembler = ContextAssembler(sample_config)+ ctx = assembler.assemble_repo_overview(structure, {}, [], {})++ # Conventional name first; nothing lost.+ assert ctx.entry_points[0] == "src/main.py"+ assert set(ctx.entry_points) == set(structure.entry_points)++def test_overview_context_warns_when_flows_cannot_be_read(sample_config, sample_repo_structure):"""A builder that raises must say so. This is the failure that hid for a year."""