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.

refactor(entry-points): rank the last entry-point lists the shared way (#1556)

Swati Ahuja5f77f081af22
diff --git a/docs/architecture/editor-files.md b/docs/architecture/editor-files.md
index 5d5d7e927..0bec13885 100644
--- a/docs/architecture/editor-files.md
+++ b/docs/architecture/editor-files.md
@@ -69,7 +69,9 @@ CLAUDE.md written to repo root
- Best-effort in `repowise update` — never fails the command
- Instant — no LLM calls, typically < 200ms
- Idempotent — re-running produces identical output if data hasn't changed
-- Deterministic — lists sorted by stable keys (PageRank desc, path asc as tiebreaker)
+- Deterministic — lists sorted by stable keys, with path asc as the final
+ tiebreaker. Most lists lead on PageRank desc; entry points deliberately do
+ not, and rank on execution-start evidence instead.
---
@@ -125,7 +127,7 @@ Auto-generated from indexed data. Updates on every `repowise update`.
|-------------|--------|-----|
| Architecture summary | First 4 sentences from `repo_overview` wiki page | 4 sentences |
| Key Modules | `module_page` pages sorted by PageRank desc, joined with git_metadata for owner | Top 10 |
-| Entry Points | `graph_nodes` where `is_entry_point=True`, sorted by PageRank desc | Top 10 |
+| Entry Points | The curated `kg_project_meta` list; otherwise `graph_nodes` where `is_entry_point=True`, ranked on execution-start evidence | Top 10 |
| Tech Stack | Filesystem scan (package.json, pyproject.toml, Cargo.toml, go.mod, etc.) | All detected |
| Hotspots | `git_metadata` where `is_hotspot=True`, sorted by `churn_percentile` desc | Top 5 |
@@ -173,13 +175,22 @@ LIMIT 10
```
**Entry points** (`_get_entry_points`)
+
+The curated `kg_project_meta.entry_points_json` list wins when the curation
+pass has run. Otherwise the raw flag is read unbounded and ranked in Python,
+because the ordering cannot be expressed as an `ORDER BY`:
+
```python
-SELECT node_id FROM graph_nodes
+SELECT node_id, pagerank, betweenness FROM graph_nodes
WHERE repository_id = :repo_id AND is_entry_point = TRUE
-ORDER BY pagerank DESC
-LIMIT 10
+# then rank_entry_points(...): conventional entry name, then shallower path,
+# then centrality as a tiebreak; sliced to 10 after ranking.
```
+PageRank deliberately does **not** lead here. Centrality rewards fan-in, so it
+floats a widely-imported barrel above the real front door — see
+`generation/entry_points.py`.
+
**Hotspots** (`_get_hotspots`)
```python
SELECT file_path, churn_percentile, commit_count_90d, primary_owner_name
diff --git a/docs/architecture/graph-algorithms.md b/docs/architecture/graph-algorithms.md
index a468e00e5..b3e6747ae 100644
--- a/docs/architecture/graph-algorithms.md
+++ b/docs/architecture/graph-algorithms.md
@@ -163,7 +163,7 @@ If co-change edges fed into PageRank, files that happen to change alongside many
1. **Documentation priority**: High PageRank files get wiki pages generated first. If budget is limited, the most depended-on files are documented.
2. **Generation depth**: Low PageRank + low git churn → "minimal" docs (saves LLM tokens and cost).
3. **Significant file selection**: Files above the PageRank threshold get detailed Level 2 wiki pages. Files below get summarized in module-level pages.
-4. **CLAUDE.md generation**: When generating editor context files, files are sorted by PageRank descending — the most important files appear first for AI coding assistants.
+4. **CLAUDE.md generation**: When generating editor context files, the key-modules list is sorted by PageRank descending — the most depended-on modules appear first for AI coding assistants. The entry-point list is the exception and is ranked on execution-start evidence, because centrality rewards fan-in and would float a sink above the front door.
---
diff --git a/packages/core/src/repowise/core/generation/concept_tree/naming.py b/packages/core/src/repowise/core/generation/concept_tree/naming.py
index cc14bfef3..efd1ace9b 100644
--- a/packages/core/src/repowise/core/generation/concept_tree/naming.py
+++ b/packages/core/src/repowise/core/generation/concept_tree/naming.py
@@ -9,11 +9,15 @@ plausible-looking paths — have nowhere to enter through. A group the model
forgets to name keeps a deterministic name; a group id it invents is discarded.
Coverage is therefore unchanged by anything the model does or fails to do.
-The payload conveys breadth, never importance. Ranking the input by PageRank
-and sampling the top files produced 12.7% coverage against 91.7% for the full
-inventory, because hub files are infrastructure — ``models.py``, ``client.ts``,
-``__init__.py`` — and an outline built around them describes the plumbing
-rather than the product.
+The file inventory conveys breadth, never importance. Ranking the input by
+PageRank and sampling the top files produced 12.7% coverage against 91.7% for
+the full inventory, because hub files are infrastructure — ``models.py``,
+``client.ts``, ``__init__.py`` — and an outline built around them describes the
+plumbing rather than the product. Every truncated field in the payload is
+nonetheless ordered for what its truncation should keep — filenames round-robin
+across directories, entry points by execution-start evidence — because the sort
+in front of a ``[:n]`` decides what the model sees, and none of those orders is
+centrality.
Repo docs do not come in here as prose. Nine thousand characters of README
injected alongside a 145-directory structural task collapsed the outline to
@@ -32,6 +36,7 @@ from typing import Any
import structlog
+from ..entry_points import rank_entry_point_paths
from ..onboarding.grounding import check_grounding
from .grouping import ConceptGroup
@@ -528,9 +533,14 @@ def build_payload(
hint = hints.get(gid)
if hint:
entry["suggested_name"] = hint
- group_entries = sorted(e.rsplit("/", 1)[-1] for e in entries if e in set(group.members))
+ # Ranked, not alphabetical by basename: this is truncated to three, so
+ # the sort decides which three the namer ever sees. Basenames are taken
+ # after ranking for the reason the docstring gives — a full path is
+ # something the model would quote back as a citation.
+ members = set(group.members)
+ group_entries = rank_entry_point_paths(e for e in entries if e in members)
if group_entries:
- entry["entry_points"] = group_entries[:3]
+ entry["entry_points"] = [e.rsplit("/", 1)[-1] for e in group_entries[:3]]
entries_out.append(entry)
return {"repo": "", "groups": entries_out}, index
diff --git a/packages/core/src/repowise/core/generation/context/assembler.py b/packages/core/src/repowise/core/generation/context/assembler.py
index 45eed7b86..6be3ee90c 100644
--- a/packages/core/src/repowise/core/generation/context/assembler.py
+++ b/packages/core/src/repowise/core/generation/context/assembler.py
@@ -18,7 +18,7 @@ from repowise.core.ids import file_path_of, is_external
from repowise.core.ingestion.models import ParsedFile, RepoStructure, Symbol
from ..categories import file_category
-from ..entry_points import orientation_entry_points
+from ..entry_points import orientation_entry_points, rank_entry_point_paths
from ..models import GenerationConfig
from .contexts import (
ApiContractContext,
@@ -466,7 +466,13 @@ class ContextAssembler:
public_symbols = sum(
sum(1 for s in fc.symbols if s.get("visibility") == "public") for fc in file_contexts
)
- entry_points = [fc.file_path for fc in file_contexts if fc.is_entry_point]
+ # ``module_page.j2`` renders these under a literal "Entry points"
+ # heading, so this is a displayed ordering and takes the shared rule.
+ # The input is ``file_contexts`` order, which is whatever the selector
+ # handed over.
+ entry_points = rank_entry_point_paths(
+ fc.file_path for fc in file_contexts if fc.is_entry_point
+ )
files = [fc.file_path for fc in file_contexts]
# Aggregate dependencies/dependents across all files in module
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 d8749d86c..23781f1c2 100644
--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py
+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
@@ -17,6 +17,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.perf.coverage import coverage_for_metrics
from repowise.core.analysis.health.scoring import hotspot_health, nloc_weighted_score
+from repowise.core.entry_candidacy import conventional_entry_stems
+from repowise.core.generation.entry_points import rank_entry_points
from repowise.core.persistence import crud
from repowise.core.persistence.models import (
DecisionRecord,
@@ -146,13 +148,25 @@ class EditorFileDataFetcher:
async def _get_entry_points(self) -> list[str]:
"""Curated orientation entry points (re-export barrels and sinks demoted).
- Prefers the curated ``kg_project_meta`` list. The raw ``is_entry_point``
- flag still tags shallow package-export files (a package-root ``cn.ts``
- or ``types/index.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. Ingestion's candidacy rule removed the deeper ones from the
- flag, which narrows the gap without closing it. Falls back to the flag
- (PageRank-ordered) only for indexes built before the curation pass.
+ Prefers the curated ``kg_project_meta`` list, and falls back to the raw
+ ``is_entry_point`` flag whenever that list is absent or empty — an
+ index written before the curation pass, a run with
+ ``REPOWISE_KG_CURATION=0``, or a repo whose candidates were all
+ filtered out.
+
+ The fallback used to read ``ORDER BY pagerank DESC``, which is the
+ ordering :mod:`repowise.core.generation.entry_points` exists to argue
+ against: centrality rewards fan-in, so a package-root ``types/index.ts``
+ floated above the real front door precisely because everything imports
+ it. It now ranks on execution-start evidence and keeps PageRank as the
+ tiebreak the shared key already defines.
+
+ Ranking has to happen after the read, not in the ``ORDER BY``, so the
+ query is bounded by the flag rather than by ``LIMIT``. Measured over 42
+ local indexes the widest flag set is 9,644 rows of one path and two
+ floats. That is per call, and the call is not once per run: the CLI
+ makes one per editor file, and ``GET /repos/{id}/claude-md`` makes one
+ per request.
"""
meta = await crud.get_kg_project_meta(self._session, self._repo_id)
if meta is not None:
@@ -164,15 +178,14 @@ class EditorFileDataFetcher:
return curated[:_MAX_ENTRY_POINTS]
result = await self._session.execute(
- select(GraphNode.node_id)
- .where(
+ select(GraphNode.node_id, GraphNode.pagerank, GraphNode.betweenness).where(
GraphNode.repository_id == self._repo_id,
GraphNode.is_entry_point == True, # noqa: E712
)
- .order_by(GraphNode.pagerank.desc())
- .limit(_MAX_ENTRY_POINTS)
)
- return [row[0] for row in result.all()]
+ candidates = [(node_id, pr or 0.0, bt or 0.0) for node_id, pr, bt in result.all()]
+ ranked = rank_entry_points(candidates, conventional_entry_stems())
+ return ranked[:_MAX_ENTRY_POINTS]
async def _get_hotspots(self) -> list[HotspotFile]:
"""Top attention-worthy files: bug-fix history first, churn as fallback.
diff --git a/packages/core/src/repowise/core/generation/entry_points.py b/packages/core/src/repowise/core/generation/entry_points.py
index 52e8f5282..98f77c0a5 100644
--- a/packages/core/src/repowise/core/generation/entry_points.py
+++ b/packages/core/src/repowise/core/generation/entry_points.py
@@ -15,10 +15,28 @@ This module ranks candidates by execution-start evidence instead — a
conventional entry filename and a shallow path — and uses centrality only to
break ties. It is deliberately free of any DB/graph/LLM dependency so the
ordering can be unit-tested directly.
+
+Three callable shapes, one rule: :func:`orientation_entry_points` for a
+``RepoStructure``, :func:`rank_entry_point_paths` for bare paths, and
+:func:`rank_entry_points` for callers holding centrality.
+
+One ordering of entry points is deliberately not this one:
+``tour.tour_landmark_paths`` orders by ``score_entry_points`` and truncates,
+because it answers a *selection* question — which files are guaranteed a page —
+and its score reads the ``is_entry_point`` flag itself, which this key never
+sees. Sharing the key there would decide page selection on filename, depth and
+centrality with the one direct piece of evidence dropped.
+
+**Ranking cannot rescue bad candidacy, and the corpus still shows it.** On
+``spring-petclinic`` the Spring stamper flags 24 entity and controller classes
+and never flags ``PetClinicApplication.java``, so no ordering over that set can
+name the front door: the best this key can do is pick a different wrong file.
+That is a candidacy gap, tracked separately.
"""
from __future__ import annotations
+from collections.abc import Iterable
from pathlib import PurePosixPath
from typing import Any
@@ -67,6 +85,19 @@ def entry_point_rank_key(
)
+def rank_entry_point_paths(paths: Iterable[str]) -> list[str]:
+ """Rank bare paths, best entry first, with no centrality to break ties.
+
+ The sibling for callers that hold a set or a query result rather than a
+ ``RepoStructure``. Centrality is only a tiebreak between paths that already
+ agree on name and depth, and the path component keeps the order total, so
+ omitting it costs nothing but determinism-preserving arbitrariness.
+ Callers that do hold centrality should use :func:`rank_entry_points`.
+ """
+ stems = conventional_entry_stems()
+ return sorted(paths, key=lambda p: entry_point_rank_key(p, conventional_stems=stems))
+
+
def orientation_entry_points(repo_structure: Any, *, limit: int | None = None) -> list[str]:
"""The repository's entry points, ordered the way every surface should show them.
@@ -126,11 +157,7 @@ def orientation_entry_points(repo_structure: Any, *, limit: int | None = None) -
so a React ``src/components/App.tsx`` is published as an execution entry
point, as is any ``run.py`` / ``server.ts`` at any depth.
"""
- paths = list(getattr(repo_structure, "entry_points", None) or [])
- ranked = sorted(
- paths,
- key=lambda p: entry_point_rank_key(p, conventional_stems=conventional_entry_stems()),
- )
+ ranked = rank_entry_point_paths(getattr(repo_structure, "entry_points", None) or [])
return ranked if limit is None else ranked[:limit]
diff --git a/tests/unit/generation/test_concept_outline.py b/tests/unit/generation/test_concept_outline.py
index f8dcd315c..2c109a043 100644
--- a/tests/unit/generation/test_concept_outline.py
+++ b/tests/unit/generation/test_concept_outline.py
@@ -330,6 +330,35 @@ class TestPayload:
assert any(n.startswith("a") for n in names)
assert any(n.startswith("z") for n in names), names
+ def test_entry_point_hints_are_ranked_not_alphabetical(self):
+ """The hint is truncated to three, so the sort picks which three.
+
+ Alphabetical by basename put ``api.ts`` and the two barrels ahead of
+ ``main.py``, and this feeds the prompt that names the group.
+ """
+ from repowise.core.generation.concept_tree.grouping import ConceptGroup
+
+ members = [
+ "src/api.ts",
+ "src/deep/nested/index.ts",
+ "src/bootstrap.py",
+ "src/main.py",
+ "src/zzz/server.py",
+ ]
+ group = ConceptGroup(members=members, dirs=["src"], target_path="src")
+ payload, _ = build_payload([group], entry_points=set(members))
+ assert payload["groups"][0]["entry_points"] == ["bootstrap.py", "main.py", "server.py"]
+
+ def test_entry_point_hints_only_cover_the_group(self):
+ """A repo-wide entry set is filtered to this group's own members."""
+ from repowise.core.generation.concept_tree.grouping import ConceptGroup
+
+ group = ConceptGroup(members=["src/main.py"], dirs=["src"], target_path="src")
+ payload, _ = build_payload(
+ [group], entry_points={"src/main.py", "other/cli.py"}
+ )
+ assert payload["groups"][0]["entry_points"] == ["main.py"]
+
def test_sibling_directories_are_shown_relative_to_what_they_share(self):
from repowise.core.generation.concept_tree.grouping import ConceptGroup
diff --git a/tests/unit/generation/test_context_assembler.py b/tests/unit/generation/test_context_assembler.py
index a35e3af8c..670769271 100644
--- a/tests/unit/generation/test_context_assembler.py
+++ b/tests/unit/generation/test_context_assembler.py
@@ -310,6 +310,36 @@ def test_assemble_module_page_public_symbols(
assert ctx.public_symbols >= 0
+def test_assemble_module_page_ranks_its_entry_points(
+ sample_config, sample_parsed_file, sample_graph, graph_metrics, sample_source_bytes
+):
+ """``module_page.j2`` renders these under an "Entry points" heading.
+
+ The input is ``file_contexts`` order — whatever the selector handed over —
+ so without ranking the heading led with whichever entry point happened to
+ be assembled first. Here that is a deep glue leaf.
+ """
+ from dataclasses import replace
+
+ assembler = ContextAssembler(sample_config)
+ base = assembler.assemble_file_page(
+ sample_parsed_file,
+ sample_graph,
+ graph_metrics["pagerank"],
+ graph_metrics["betweenness"],
+ graph_metrics["community"],
+ sample_source_bytes,
+ )
+ contexts = [
+ replace(base, file_path="src/features/api/index.ts", is_entry_point=True),
+ replace(base, file_path="src/util.py", is_entry_point=False),
+ replace(base, file_path="src/main.py", is_entry_point=True),
+ ]
+ ctx = assembler.assemble_module_page("python_pkg", "python", contexts, sample_graph)
+
+ assert ctx.entry_points == ["src/main.py", "src/features/api/index.ts"]
+
+
# ---------------------------------------------------------------------------
# assemble_scc_page
# ---------------------------------------------------------------------------
diff --git a/tests/unit/generation/test_editor_file_fetcher.py b/tests/unit/generation/test_editor_file_fetcher.py
index 8b79836d9..a597479b8 100644
--- a/tests/unit/generation/test_editor_file_fetcher.py
+++ b/tests/unit/generation/test_editor_file_fetcher.py
@@ -199,7 +199,14 @@ async def test_fetch_entry_points(session, repo, tmp_path):
assert "src/utils.py" not in data.entry_points
-async def test_fetch_entry_points_sorted_by_pagerank(session, repo, tmp_path):
+async def test_fetch_entry_points_breaks_ties_on_pagerank(session, repo, tmp_path):
+ """PageRank is the tiebreak, and only that.
+
+ Both names are neutral and both sit at depth 1, so nothing above centrality
+ in the shared rank key separates them and the more central file still leads.
+ Renamed from ``..._sorted_by_pagerank``: PageRank used to be the whole
+ ordering here, and the name outlived it by one commit.
+ """
await _add_graph_node(session, repo.id, "src/low.py", is_entry_point=True, pagerank=0.1)
await _add_graph_node(session, repo.id, "src/high.py", is_entry_point=True, pagerank=0.9)
await session.commit()
@@ -210,6 +217,22 @@ 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_ranks_execution_start_above_pagerank(session, repo, tmp_path):
+ """The fallback's own defect: centrality rewards fan-in, so a widely
+ imported barrel outranked the real front door precisely because everything
+ depends on it. ``ORDER BY pagerank DESC`` led with ``types/index.ts``."""
+ await _add_graph_node(
+ session, repo.id, "src/types/index.ts", is_entry_point=True, pagerank=0.99
+ )
+ await _add_graph_node(session, repo.id, "src/main.py", is_entry_point=True, pagerank=0.01)
+ await session.commit()
+
+ fetcher = EditorFileDataFetcher(session, repo.id, tmp_path)
+ data = await fetcher.fetch()
+
+ assert data.entry_points == ["src/main.py", "src/types/index.ts"]
+
+
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
diff --git a/tests/unit/generation/test_orientation_entry_points.py b/tests/unit/generation/test_orientation_entry_points.py
index fde86e09c..cc6c2462e 100644
--- a/tests/unit/generation/test_orientation_entry_points.py
+++ b/tests/unit/generation/test_orientation_entry_points.py
@@ -20,6 +20,7 @@ before that change hands it over.
from __future__ import annotations
from dataclasses import replace
+from types import SimpleNamespace
import pytest
@@ -189,6 +190,80 @@ def test_kg_project_block_is_ranked():
assert result.project["entry_points"] == RANKED
+class _RecordingClient:
+ """Captures the user prompt and returns nothing the caller can parse.
+
+ Both LLM-backed surfaces below build their prompt, then fall back when the
+ response carries no usable key. Returning an empty object exercises the
+ prompt *and* the fallback in one call, without a provider.
+ """
+
+ def __init__(self):
+ self.prompts: list[str] = []
+
+ async def generate(self, _system, user_prompt, **_kwargs):
+ self.prompts.append(user_prompt)
+ return SimpleNamespace(content="{}")
+
+
+def _entry_points_line(prompt: str) -> list[str]:
+ for line in prompt.splitlines():
+ if line.startswith("Entry points: "):
+ return [p.strip() for p in line[len("Entry points: ") :].split(",")]
+ raise AssertionError("prompt carries no 'Entry points:' line")
+
+
+async def test_kg_layer_naming_prompt_is_ranked():
+ """``_build_layer_naming_prompt`` (via ``_enrich_layers``).
+
+ Untested until now, so reverting its call to a raw prefix of
+ ``repo_structure.entry_points`` was green everywhere. The prompt truncates
+ to 5, and the model is asked to name communities against it, so an unranked
+ list decides which front doors the namer is told the repo has.
+ """
+ from repowise.core.generation.knowledge_graph import _enrich_layers
+
+ client = _RecordingClient()
+ await _enrich_layers(
+ layers=[{"id": "L1", "name": "App", "nodeIds": [f"file:{p}" for p in RAW]}],
+ llm_client=client,
+ graph_builder=SimpleNamespace(pagerank=lambda: {}),
+ repo_structure=_structure(RAW),
+ tech_stack=[],
+ )
+
+ assert client.prompts, "the layer batch never reached the client"
+ assert _entry_points_line(client.prompts[0]) == RANKED[:5]
+
+
+async def test_kg_tour_prompt_is_ranked_and_so_is_its_fallback():
+ """``_generate_tour``. Also untested until now.
+
+ ``test_deterministic_kg_tour_starts_at_the_best_entry_point`` does not
+ cover this: it hands ``build_deterministic_tour`` an already-ranked list.
+ This asserts both halves of the real call — the prompt the model sees and
+ the deterministic tour built from the same list when the model's answer is
+ unusable.
+ """
+ from repowise.core.generation.knowledge_graph import _generate_tour
+
+ client = _RecordingClient()
+ layers = [{"name": "App", "nodeIds": [f"file:{p}" for p in RAW]}]
+ tour = await _generate_tour(
+ layers=layers,
+ llm_client=client,
+ graph_builder=SimpleNamespace(pagerank=lambda: {p: 0.1 for p in RAW}),
+ repo_structure=_structure(RAW),
+ kg_skeleton=None,
+ )
+
+ assert client.prompts, "the tour request never reached the client"
+ assert _entry_points_line(client.prompts[0]) == RANKED[:10]
+ assert tour and tour[0]["nodeIds"] == ["file:src/main.py"]
+
+
def test_deterministic_kg_tour_starts_at_the_best_entry_point():
"""``build_deterministic_tour`` opens at ``entry_points[0]``. It is handed
the already-truncated list from the tour generator, so an unranked list