Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(mcp,claude-md): serve curated entry points, cap tour barrels (#418)

Raghav Chamadiyad7d0e965ad6f
diff --git a/packages/core/src/repowise/core/analysis/kg_curation.py b/packages/core/src/repowise/core/analysis/kg_curation.py
index 15c7a5162..fb64e57c6 100644
--- a/packages/core/src/repowise/core/analysis/kg_curation.py
+++ b/packages/core/src/repowise/core/analysis/kg_curation.py
@@ -1078,6 +1078,26 @@ def _anchor_fanout_rank(graph_builder: Any) -> dict[str, int]:
}
+def _drop_extra_barrels(paths: list[str], barrels: set[str], keep: int = 1) -> list[str]:
+ """Return *paths* with all but the first *keep* re-export barrels removed.
+
+ A barrel (``index.ts`` / ``__init__.py``) re-exports a package's public
+ surface; one such stop orients a reader, but five identical "re-export hub"
+ stops are noise that crowds out real code. *paths* is in execution/BFS-depth
+ order, so the first barrel kept is the shallowest. Dropping the rest before
+ the budget truncation lets real code files beyond the budget slide up.
+ """
+ out: list[str] = []
+ kept = 0
+ for p in paths:
+ if p in barrels:
+ if kept >= keep:
+ continue
+ kept += 1
+ out.append(p)
+ return out
+
+
def _curate_tour(
kg: KnowledgeGraphResult, parsed_files: list[Any], graph_builder: Any
) -> list[dict] | None:
@@ -1272,7 +1292,7 @@ def _curate_tour(
# The walk = build_tour's execution order minus adjacent-layer stops
# and example programs (documentation-by-code, not the system),
# truncated up front so later swaps land inside the kept window.
- walk = [
+ walk_all = [
s.target_path
for s in base
if s.kind == "code"
@@ -1280,7 +1300,9 @@ def _curate_tour(
and file_layers.get(s.target_path) not in ADJACENT_LAYERS
and not is_support_path(s.target_path)
]
- walk = walk[:budget]
+ # One re-export barrel earns a stop; the rest are demoted so real code
+ # fills the budget instead of a run of identical "public surface" hubs.
+ walk = _drop_extra_barrels(walk_all, barrels)[:budget]
# --- Diversify for layer coverage (swap slots, never re-sort) -----
seen_layers: set[str] = set()
@@ -1308,6 +1330,7 @@ def _curate_tour(
if p not in walk
and p != overview_target
and not is_support_path(p)
+ and p not in barrels # a re-export shell is never a layer's face
and not PurePosixPath(p).parts[0].startswith(".") # never a layer face
and PurePosixPath(p).name not in manifest_names
]
diff --git a/packages/core/src/repowise/core/generation/editor_files/fetcher.py b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
index bfd9d37eb..eb2313080 100644
--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py
+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
@@ -6,6 +6,7 @@ Uses the existing CRUD layer where possible; raw selects for aggregate queries.
from __future__ import annotations
+import json
import re
import subprocess
from datetime import UTC, datetime
@@ -139,7 +140,23 @@ class EditorFileDataFetcher:
return modules
async def _get_entry_points(self) -> list[str]:
- """Files tagged as entry points, sorted by PageRank desc."""
+ """Curated orientation entry points (re-export barrels and sinks demoted).
+
+ Prefers the curated ``kg_project_meta`` list. The raw ``is_entry_point``
+ flag also tags every package-export file (cn.ts, types/*.ts) — high
+ fan-in sinks that are the opposite of where a reader starts, and ordering
+ them by PageRank floats those sinks to the top. Falls back to the
+ flag (PageRank-ordered) only for indexes built before the curation pass.
+ """
+ meta = await crud.get_kg_project_meta(self._session, self._repo_id)
+ if meta is not None:
+ try:
+ curated = json.loads(meta.entry_points_json or "[]")
+ except (json.JSONDecodeError, TypeError):
+ curated = []
+ if curated:
+ return curated[:_MAX_ENTRY_POINTS]
+
result = await self._session.execute(
select(GraphNode.node_id)
.where(
diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.py
index 1ed2919ee..cf11bd2f4 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py
@@ -23,6 +23,9 @@ from repowise.core.persistence.crud import (
from repowise.core.persistence.crud import (
get_kg_layers as _get_kg_layers,
)
+from repowise.core.persistence.crud import (
+ get_kg_project_meta as _get_kg_project_meta,
+)
from repowise.core.persistence.crud import (
get_kg_tour_steps as _get_kg_tour_steps,
)
@@ -44,6 +47,7 @@ from repowise.server.mcp_server._helpers import (
_resolve_repo_context,
filter_graph_nodes,
filter_rows_by_attr,
+ is_excluded,
)
from repowise.server.mcp_server._meta import build_meta as _build_meta
@@ -272,25 +276,53 @@ async def get_overview(repo: str | None = None) -> dict:
"\n".join(f"{p.title}: {p.target_path}" for p in all_module_pages[20:]),
)
- # Get entry point files from graph nodes (exclude tests & fixtures)
- result = await session.execute(
- select(GraphNode).where(
- GraphNode.repository_id == repository.id,
- GraphNode.is_entry_point == True, # noqa: E712
- GraphNode.is_test == False, # noqa: E712
- )
- )
- entry_nodes = filter_graph_nodes(
- [
- n
- for n in result.scalars().all()
- if not any(
- seg in n.node_id.lower()
+ # Entry points: prefer the curated orientation list — re-export barrels
+ # and package-export sinks demoted, survivors ranked by execution
+ # centrality. The raw ``is_entry_point`` flag also tags every npm-exported
+ # file (cn.ts, types/*.ts): high fan-in sinks that are the opposite of
+ # where a reader starts. Fall back to the flag only for indexes built
+ # before the curation pass (no ``kg_project_meta`` row).
+ def _drop_fixtures(ids: list[str]) -> list[str]:
+ return [
+ nid
+ for nid in ids
+ if not is_excluded(nid, exclude_spec)
+ and not any(
+ seg in nid.lower()
for seg in ("fixture", "test_data", "testdata", "sample_repo")
)
- ],
- exclude_spec,
- )
+ ]
+
+ proj_meta = await _get_kg_project_meta(session, repository.id)
+ curated_ids: list[str] = []
+ if proj_meta is not None:
+ try:
+ curated_ids = json.loads(proj_meta.entry_points_json or "[]")
+ except (json.JSONDecodeError, TypeError):
+ curated_ids = []
+
+ if curated_ids:
+ entry_point_ids = _drop_fixtures(curated_ids)
+ else:
+ result = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repository.id,
+ GraphNode.is_entry_point == True, # noqa: E712
+ GraphNode.is_test == False, # noqa: E712
+ )
+ )
+ entry_nodes = filter_graph_nodes(
+ [
+ n
+ for n in result.scalars().all()
+ if not any(
+ seg in n.node_id.lower()
+ for seg in ("fixture", "test_data", "testdata", "sample_repo")
+ )
+ ],
+ exclude_spec,
+ )
+ entry_point_ids = [n.node_id for n in entry_nodes]
# Phase 4: repo-wide git health summary
git_res = await session.execute(
@@ -621,7 +653,7 @@ async def get_overview(repo: str | None = None) -> dict:
}
for p in module_pages
],
- "entry_points": _capped_entry_points(entry_nodes, collector),
+ "entry_points": _capped_entry_points(entry_point_ids, collector),
"git_health": git_health,
"knowledge_map": knowledge_map,
"community_summary": community_summary,
@@ -685,11 +717,11 @@ async def get_overview(repo: str | None = None) -> dict:
return result
-def _capped_entry_points(entry_nodes: list, collector: OmissionCollector) -> list[str]:
+def _capped_entry_points(entry_ids: list[str], collector: OmissionCollector) -> list[str]:
"""First 15 entry-point ids; the remainder goes to the omission store."""
- if len(entry_nodes) > 15:
+ if len(entry_ids) > 15:
collector.add(
- f"entry points beyond cap=15 ({len(entry_nodes) - 15} dropped)",
- "\n".join(n.node_id for n in entry_nodes[15:]),
+ f"entry points beyond cap=15 ({len(entry_ids) - 15} dropped)",
+ "\n".join(entry_ids[15:]),
)
- return [n.node_id for n in entry_nodes[:15]]
+ return entry_ids[:15]
diff --git a/tests/unit/analysis/test_kg_curation.py b/tests/unit/analysis/test_kg_curation.py
index 846ee253b..6b28cfc43 100644
--- a/tests/unit/analysis/test_kg_curation.py
+++ b/tests/unit/analysis/test_kg_curation.py
@@ -637,6 +637,24 @@ class TestCuratedTour:
assert "An entry point" not in s["reason"]
assert "re-export hub" in s["reason"]
+ def test_tour_keeps_at_most_one_barrel(self):
+ # Five package barrels would otherwise each take a walk slot with the
+ # same "re-export hub" reason. Only one earns a stop; real code beyond
+ # the budget slides up to fill the freed slots.
+ barrels = {f"packages/pkg{i}/src/index.ts" for i in range(5)}
+ code = ["src/cli/main.py"] + [f"src/services/svc{i}.py" for i in range(5)]
+ repo = build_repo(
+ sorted(barrels) + code,
+ entries={"src/cli/main.py", *barrels},
+ barrels=barrels,
+ edges=[("src/cli/main.py", p) for p in code[1:]],
+ )
+ kg = _curate(repo, enabled=True)
+ barrel_steps = [s for s in kg.tour if s["target_path"] in barrels]
+ assert len(barrel_steps) <= 1, [s["target_path"] for s in kg.tour]
+ # Demoting the barrels did not empty the walk of real code.
+ assert any(s["target_path"] in code for s in kg.tour)
+
class TestEntryPointFallback:
def test_filename_scorers_fill_in_when_nothing_is_flagged(self):
diff --git a/tests/unit/generation/test_editor_file_fetcher.py b/tests/unit/generation/test_editor_file_fetcher.py
index 78ccc9cc4..3a03adc7a 100644
--- a/tests/unit/generation/test_editor_file_fetcher.py
+++ b/tests/unit/generation/test_editor_file_fetcher.py
@@ -196,6 +196,31 @@ async def test_fetch_entry_points_sorted_by_pagerank(session, repo, tmp_path):
assert data.entry_points[0] == "src/high.py"
+async def test_fetch_entry_points_prefers_curated_list(session, repo, tmp_path):
+ # The raw is_entry_point flag tags package-export sinks (a high-pagerank
+ # cn.ts-style leaf). When the curation pass has run, its orientation list
+ # wins over the flag — the sink must not surface as an entry point.
+ import json
+
+ from repowise.core.persistence.models import KnowledgeGraphProjectMeta
+
+ await _add_graph_node(session, repo.id, "src/ui/cn.ts", is_entry_point=True, pagerank=0.99)
+ session.add(
+ KnowledgeGraphProjectMeta(
+ repository_id=repo.id,
+ entry_points_json=json.dumps(["src/cli/main.py"]),
+ entry_candidates_json=json.dumps(["src/cli/main.py"]),
+ )
+ )
+ await session.commit()
+
+ fetcher = EditorFileDataFetcher(session, repo.id, tmp_path)
+ data = await fetcher.fetch()
+
+ assert data.entry_points == ["src/cli/main.py"]
+ assert "src/ui/cn.ts" not in data.entry_points
+
+
async def test_fetch_hotspots(session, repo, tmp_path):
await _add_git_meta(
session, repo.id, "src/billing.py", is_hotspot=True, churn_pct=0.95, owner="@alice"
diff --git a/tests/unit/server/mcp/test_overview.py b/tests/unit/server/mcp/test_overview.py
index c5a700844..900813a38 100644
--- a/tests/unit/server/mcp/test_overview.py
+++ b/tests/unit/server/mcp/test_overview.py
@@ -6,9 +6,32 @@ test data, mirroring the conftest pattern from the REST API tests.
from __future__ import annotations
+import json
+
import pytest
+async def test_get_overview_prefers_curated_entry_points(setup_mcp, session):
+ from repowise.core.persistence.models import KnowledgeGraphProjectMeta
+ from repowise.server.mcp_server import get_overview
+
+ # The fixture flags src/auth/service.py via the raw is_entry_point flag (a
+ # high-pagerank sink). With a curated orientation list present, get_overview
+ # must serve that instead of the flagged sink.
+ session.add(
+ KnowledgeGraphProjectMeta(
+ repository_id="repo1",
+ entry_points_json=json.dumps(["src/cli/main.py"]),
+ entry_candidates_json=json.dumps(["src/cli/main.py"]),
+ )
+ )
+ await session.commit()
+
+ result = await get_overview()
+ assert result["entry_points"] == ["src/cli/main.py"]
+
+
@pytest.mark.asyncio
async def test_get_overview(setup_mcp):
from repowise.server.mcp_server import get_overview