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(generation): rank orientation entry points the same way on every surface (#1488)

Raghav Chamadiyaf74599423528
diff --git a/packages/core/src/repowise/core/analysis/kg_curation.py b/packages/core/src/repowise/core/analysis/kg_curation.py
index d393ecf13..c86de0360 100644
--- a/packages/core/src/repowise/core/analysis/kg_curation.py
+++ b/packages/core/src/repowise/core/analysis/kg_curation.py
@@ -33,7 +33,9 @@ from typing import Any
from repowise.core.analysis.knowledge_graph import KnowledgeGraphResult, _slugify
from repowise.core.generation.entry_points import (
- GLUE_STEMS,
+ CONVENTIONAL_ENTRY_STEMS as _CONVENTIONAL_ENTRY_STEMS,
+)
+from repowise.core.generation.entry_points import (
is_glue_leaf,
rank_entry_points,
)
@@ -70,9 +72,6 @@ _TEST_PROJECT_DIR_SUFFIXES: tuple[str, ...] = _LANG_REGISTRY.test_dir_suffixes()
_NON_CODE_ENTRY_LANGUAGES: frozenset[str] = (
_LANG_REGISTRY.config_languages() | _LANG_REGISTRY.infra_languages()
)
-# Conventional execution-start filename stems (main/app/cli/manage/…) minus
-# the dispatch-glue stems (index/mod) — drives the entry-point name ranking.
-_CONVENTIONAL_ENTRY_STEMS: frozenset[str] = _LANG_REGISTRY.entry_filename_stems() - GLUE_STEMS
# Honest-degradation thresholds. Density = (imports + tested_by)
# edges per dominant-language file — the same definition the validation
diff --git a/packages/core/src/repowise/core/analysis/knowledge_graph.py b/packages/core/src/repowise/core/analysis/knowledge_graph.py
index 472b254c3..8053d951f 100644
--- a/packages/core/src/repowise/core/analysis/knowledge_graph.py
+++ b/packages/core/src/repowise/core/analysis/knowledge_graph.py
@@ -16,6 +16,8 @@ from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath
from typing import Any
+from repowise.core.generation.entry_points import orientation_entry_points
+
_log = logging.getLogger(__name__)
#: Schema version of the ``knowledge-graph.json`` artifact. Bump whenever a
@@ -243,7 +245,7 @@ def build_knowledge_graph_skeleton(
"name": repo_path.name if repo_path else "",
"is_monorepo": repo_structure.is_monorepo if repo_structure else False,
"total_files": repo_structure.total_files if repo_structure else len(parsed_files),
- "entry_points": list(repo_structure.entry_points) if repo_structure else [],
+ "entry_points": orientation_entry_points(repo_structure),
"tech_stack": tech_stack[:20],
}
diff --git a/packages/core/src/repowise/core/generation/context/assembler.py b/packages/core/src/repowise/core/generation/context/assembler.py
index 82c08e244..45eed7b86 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 entry_point_rank_key
+from ..entry_points import orientation_entry_points
from ..models import GenerationConfig
from .contexts import (
ApiContractContext,
@@ -826,16 +826,11 @@ class ContextAssembler:
language_distribution=repo_structure.root_language_distribution,
total_files=repo_structure.total_files,
total_loc=repo_structure.total_loc,
- # 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),
+ # Ranked, not filtered, and ranked by the helper every other
+ # orientation surface now calls so they cannot name different
+ # front doors. Why it is ranked at all is on
+ # ``orientation_entry_points``.
+ entry_points=orientation_entry_points(repo_structure),
top_files_by_pagerank=top_files,
circular_dependency_count=circular_count,
communities=communities_list,
diff --git a/packages/core/src/repowise/core/generation/entry_points.py b/packages/core/src/repowise/core/generation/entry_points.py
index 491ea0ec9..f763c5e0f 100644
--- a/packages/core/src/repowise/core/generation/entry_points.py
+++ b/packages/core/src/repowise/core/generation/entry_points.py
@@ -16,6 +16,9 @@ ordering can be unit-tested directly.
from __future__ import annotations
from pathlib import PurePosixPath
+from typing import Any
+
+from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY
# Generic module stems that *dispatch or re-export* rather than start a program.
# ``index`` (a JS/TS barrel or a per-language resolver shell) and ``mod`` (a Rust
@@ -30,6 +33,15 @@ GLUE_STEMS: frozenset[str] = frozenset({"index", "mod"})
# reader enters the system.
SHALLOW_ENTRY_DEPTH = 1
+# Filename stems that name a real execution start, minus the glue stems above
+# so ``index``/``mod`` cannot be both at once. Registry-derived rather than
+# written out, so a language that adds an entry stem is covered here too.
+# Defined here, next to the ranking that reads it, because the KG curator and
+# the wiki surfaces must answer "is this a conventional entry name" the same
+# way. The registry is a pure data table, so this module keeps its promise of
+# no DB / graph / LLM dependency.
+CONVENTIONAL_ENTRY_STEMS: frozenset[str] = _LANG_REGISTRY.entry_filename_stems() - GLUE_STEMS
+
def entry_point_depth(path: str) -> int:
"""Directory depth — 0 for a root file, 1 for one level deep, etc."""
@@ -87,6 +99,65 @@ def entry_point_rank_key(
)
+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.
+
+ ``RepoStructure.entry_points`` arrives ``sorted()`` by path
+ (``ingestion/traverser.py:470``) — deterministic, and meaningless as an
+ orientation order. Lexicographic order puts ``.github/`` first, then
+ ``apps/``, ``benchmarks/``, ``crates/``, ``docs/``; ``src/main.py`` sorts
+ near the end. Six surfaces read that field. One ranked it and five took a
+ raw prefix, so a truncated list showed whatever sorted first: PowerToys led
+ its list with ``.github/scripts/telemetry-pr-check.js``, fastapi with a
+ German docs page, pydantic with ``docs/index.md``.
+
+ Ranked, not filtered, which is the same trade the overview already makes:
+ ``packages/cli/src/index.ts`` is a genuine package front door in a
+ monorepo, so dropping every glue stem would lose it, while ranking demotes
+ glue below every real entry without losing one. The knowledge-graph
+ curator filters as well, because it owns a candidacy question this does
+ not: it is choosing what may appear at all, not ordering what already has.
+
+ ``CONVENTIONAL_ENTRY_STEMS`` is passed, which the overview's own call did
+ not do — ``sorted(..., key=entry_point_rank_key)`` calls the key
+ positionally, so its ``conventional_stems`` defaulted to empty. Without the
+ set the key degenerates to "glue last, then shallowest first", and depth
+ alone is a bad primary signal: on the 41 indexed repos under
+ ``test-repos/`` it puts a ``.github/scripts`` helper ahead of
+ ``src/runner/main.cpp``, ``packages/cli/README.md`` first on dub, and a
+ Cypress config first on jhipster. With the set those lead with
+ ``src/runner/main.cpp``, ``apps/web/lib/axiom/server.ts`` and
+ ``src/main/docker/app.yml``.
+
+ It is a net win and not a clean sweep. Of the 24 repos whose leader moves,
+ two get worse, and one of those is the stem set's own doing: osv-scalibr
+ demotes ``binary/scalibr/scalibr.go``, the actual product binary, below
+ ``linter/plugger/main.go``, because a binary named after its repo is not a
+ conventional stem and ``main`` is. See the backlog.
+
+ Ceiling, deliberate: no centrality is threaded through, so the
+ ``pagerank`` / ``betweenness`` tiebreak :func:`entry_point_rank_key`
+ accepts stays at zero. Every caller here holds a ``RepoStructure`` and not
+ a graph, and it only separates paths that already agree on name and depth.
+
+ Separately, and NOT addressed here: ordering cannot fix candidacy, and
+ candidacy is the larger defect. ``repo_structure.entry_points`` carries
+ ``.github/workflows/main.yml``, ``README.md`` and test files, so some
+ repos lead with one whatever the order. The knowledge-graph curator drops
+ those (``kg_curation._not_an_execution_start``) and the wiki surfaces do
+ not; sharing that rule is the follow-up. Same for the heuristic's own
+ false positives: ``app`` is a generic entry stem, 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),
+ )
+ return ranked if limit is None else ranked[:limit]
+
+
def rank_entry_points(
candidates: list[tuple[str, float, float]],
conventional_stems: frozenset[str],
diff --git a/packages/core/src/repowise/core/generation/knowledge_graph.py b/packages/core/src/repowise/core/generation/knowledge_graph.py
index a94124fb7..f8c4689e5 100644
--- a/packages/core/src/repowise/core/generation/knowledge_graph.py
+++ b/packages/core/src/repowise/core/generation/knowledge_graph.py
@@ -14,6 +14,7 @@ from typing import Any
import structlog
+from repowise.core.generation.entry_points import orientation_entry_points
from repowise.core.ids import file_path_of, kg_file_path_of
logger = structlog.get_logger(__name__)
@@ -236,7 +237,7 @@ def _build_layer_naming_prompt(
repo_structure: Any,
) -> str:
tech_names = [t.get("name", "") for t in tech_stack[:10] if t.get("name")]
- entry_points = list(repo_structure.entry_points)[:5] if repo_structure else []
+ entry_points = orientation_entry_points(repo_structure, limit=5)
lines = [
"Assign a concise semantic name (2-4 words) and a one-sentence description "
@@ -282,7 +283,7 @@ async def _generate_tour(
) -> list[dict]:
"""Generate guided tour from enriched layers + entry points."""
pagerank = graph_builder.pagerank()
- entry_points = list(repo_structure.entry_points)[:10] if repo_structure else []
+ entry_points = orientation_entry_points(repo_structure, limit=10)
top_files = sorted(pagerank.keys(), key=lambda p: pagerank.get(p, 0.0), reverse=True)[:15]
layer_summaries = []
diff --git a/packages/core/src/repowise/core/generation/onboarding/subkinds/getting_started.py b/packages/core/src/repowise/core/generation/onboarding/subkinds/getting_started.py
index f06685737..2f2d9d166 100644
--- a/packages/core/src/repowise/core/generation/onboarding/subkinds/getting_started.py
+++ b/packages/core/src/repowise/core/generation/onboarding/subkinds/getting_started.py
@@ -15,6 +15,7 @@ from __future__ import annotations
import re
from dataclasses import dataclass, field
+from ...entry_points import orientation_entry_points
from ..registry import SubkindSpec, register
from ..signals import OnboardingSignals
from ..slots import SLOT_GETTING_STARTED, SLOT_TITLES
@@ -176,7 +177,7 @@ def _build(signals: OnboardingSignals) -> GettingStartedContext | None:
runtime_dependencies=runtime,
dev_dependencies=dev,
readme_sections=readme_sections,
- entry_points=list(getattr(signals.repo_structure, "entry_points", []))[:6],
+ entry_points=orientation_entry_points(signals.repo_structure, limit=6),
)
diff --git a/packages/core/src/repowise/core/generation/onboarding/subkinds/how_it_works.py b/packages/core/src/repowise/core/generation/onboarding/subkinds/how_it_works.py
index 3a7ae2544..604a048a3 100644
--- a/packages/core/src/repowise/core/generation/onboarding/subkinds/how_it_works.py
+++ b/packages/core/src/repowise/core/generation/onboarding/subkinds/how_it_works.py
@@ -21,6 +21,7 @@ from typing import Literal
import structlog
+from ...entry_points import orientation_entry_points
from ..registry import SubkindSpec, register
from ..signals import OnboardingSignals
from ..slots import SLOT_HOW_IT_WORKS, SLOT_TITLES
@@ -217,7 +218,7 @@ def _build(signals: OnboardingSignals) -> HowItWorksContext | None:
archetype=archetype,
archetype_evidence=evidence,
flows=flows,
- entry_points=list(getattr(signals.repo_structure, "entry_points", []))[:5],
+ entry_points=orientation_entry_points(signals.repo_structure, limit=5),
kg_tour_steps=kg_tour[:8],
)
diff --git a/tests/unit/generation/test_orientation_entry_points.py b/tests/unit/generation/test_orientation_entry_points.py
new file mode 100644
index 000000000..7ce591b8a
--- /dev/null
+++ b/tests/unit/generation/test_orientation_entry_points.py
@@ -0,0 +1,198 @@
+"""Every orientation surface names the same front door.
+
+``RepoStructure.entry_points`` arrives ``sorted()`` by path
+(``ingestion/traverser.py:470``): deterministic, and meaningless as an
+orientation order. The overview ranked it; the onboarding pages, the KG
+layer-naming prompt, the KG tour and the exported KG project block each took a
+raw prefix, so a truncated list showed whatever sorted first and the surfaces
+disagreed with each other about where the program starts.
+
+The order asserted here is ``orientation_entry_points``: a conventional entry
+name first, then shallower path, then a generic glue stem last. ``src/main.py``
+leads and ``src/features/api/index.ts`` (a glue stem, nested) comes last.
+"""
+
+from __future__ import annotations
+
+from dataclasses import replace
+
+import pytest
+
+from repowise.core.generation.entry_points import orientation_entry_points
+from repowise.core.ingestion.models import RepoStructure
+
+# Path-sorted, which is what ``traverser.py:470`` actually hands over: the
+# barrel sorts above the real entry because ``src/features`` precedes
+# ``src/main.py``, and ``packages/`` precedes both.
+RAW = [
+ "packages/svc/src/server.ts",
+ "src/features/api/index.ts",
+ "src/main.py",
+ "tools/scripts/run.py",
+]
+# Conventional entry name first (``main``, ``server``), then depth, with the
+# glue stem last. ``run`` is deliberately NOT in this bucket: it is in the
+# registry's ``entry_flag_stems`` (which is what made ``run.py`` a candidate at
+# all) but not in ``entry_filename_stems``, so ``packages/svc/src/server.ts``
+# outranks it despite being three levels deeper.
+RANKED = [
+ "src/main.py",
+ "packages/svc/src/server.ts",
+ "tools/scripts/run.py",
+ "src/features/api/index.ts",
+]
+
+
+def _structure(entry_points: list[str]) -> RepoStructure:
+ return RepoStructure(
+ is_monorepo=False,
+ packages=[],
+ root_language_distribution={"python": 1.0},
+ total_files=len(entry_points),
+ total_loc=100,
+ entry_points=list(entry_points),
+ )
+
+
+# ---------------------------------------------------------------------------
+# the helper
+# ---------------------------------------------------------------------------
+
+
+def test_ranks_a_conventional_entry_above_a_buried_barrel():
+ assert orientation_entry_points(_structure(RAW)) == RANKED
+
+
+def test_limit_keeps_the_best_not_the_first():
+ """The whole point of the truncation bug: ``[:1]`` on the raw list kept
+ the barrel and dropped ``main.py``."""
+ assert orientation_entry_points(_structure(RAW), limit=1) == ["src/main.py"]
+
+
+def test_glue_is_demoted_not_dropped():
+ """``packages/cli/src/index.ts`` is a genuine package front door in a
+ monorepo, so ranking must not lose it."""
+ ranked = orientation_entry_points(_structure(RAW))
+ assert set(ranked) == set(RAW)
+
+
+def test_no_repo_structure_is_an_empty_list():
+ assert orientation_entry_points(None) == []
+ assert orientation_entry_points(object()) == []
+
+
+def test_ordering_is_stable_for_an_already_ranked_list():
+ assert orientation_entry_points(_structure(RANKED)) == RANKED
+
+
+# ---------------------------------------------------------------------------
+# the surfaces
+# ---------------------------------------------------------------------------
+
+
+def test_repo_overview_entry_points_are_ranked(sample_config, sample_repo_structure):
+ """The overview sorted already, but not the same way.
+
+ ``sorted(entry_points, key=entry_point_rank_key)`` passes the key
+ positionally, so ``conventional_stems`` defaulted to empty and the overview
+ ranked on depth alone. This is red on origin/main, not a parity guard:
+ ``tools/scripts/run.py`` used to beat ``packages/svc/src/server.ts`` on
+ depth, and now loses to it on name.
+ """
+ from repowise.core.generation.context_assembler import ContextAssembler
+
+ ctx = ContextAssembler(sample_config).assemble_repo_overview(
+ replace(sample_repo_structure, entry_points=RAW), {}, [], {}
+ )
+ assert ctx.entry_points == RANKED
+
+
+def _onboarding_entry_points(slot: str) -> list[str]:
+ """Build one onboarding page context and read back its entry points."""
+ from types import SimpleNamespace
+
+ from repowise.core.generation import onboarding
+ from repowise.core.generation.onboarding.signals import OnboardingSignals
+ from repowise.core.generation.onboarding.slots import (
+ SLOT_GETTING_STARTED,
+ SLOT_HOW_IT_WORKS,
+ )
+
+ spec = onboarding.get_spec(
+ SLOT_HOW_IT_WORKS if slot == "how_it_works" else SLOT_GETTING_STARTED
+ )
+ assert spec is not None
+ signals = OnboardingSignals(
+ repo_name="testrepo",
+ repo_structure=_structure(RAW),
+ parsed_files=(),
+ source_map={},
+ graph_builder=SimpleNamespace(
+ community_info=lambda: {},
+ execution_flows=lambda: SimpleNamespace(flows=[]),
+ ),
+ pagerank={},
+ betweenness={},
+ community={},
+ sccs=(),
+ git_meta_map={},
+ dead_code_by_file={},
+ decisions_all=(),
+ # getting_started needs a manifest signal or it declines to build; the
+ # archetype gate on how_it_works is satisfied by the tour stops below.
+ external_systems=({"name": "fastapi", "ecosystem": "pypi", "is_dev_dep": False},),
+ completed_page_summaries={},
+ tour_stops=({"title": "Entry Point", "nodeIds": ["file:src/main.py"]},),
+ layer_order=("app",),
+ )
+ ctx = spec.build_context(signals)
+ assert ctx is not None, f"{slot} declined to build; the fixture no longer feeds its gate"
+ return list(ctx.entry_points)
+
+
[email protected](("slot", "limit"), [("how_it_works", 5), ("getting_started", 6)])
+def test_onboarding_pages_agree_with_the_overview(slot, limit):
+ """Both pages truncate, so an unranked list did not merely reorder them:
+ it decided which entry points a reader ever saw."""
+ assert _onboarding_entry_points(slot) == RANKED[:limit]
+
+
+def test_kg_project_block_is_ranked():
+ """``project.entry_points`` in the exported knowledge-graph.json. The
+ curator overwrites this when it runs, but curation is feature-flagged and
+ this is what a ``REPOWISE_KG_CURATION=0`` export carries."""
+ from types import SimpleNamespace
+
+ import networkx as nx
+
+ from repowise.core.analysis.knowledge_graph import build_knowledge_graph_skeleton
+
+ builder = SimpleNamespace(
+ graph=lambda: nx.DiGraph(),
+ pagerank=lambda: {},
+ betweenness_centrality=lambda: {},
+ community_detection=lambda: {},
+ community_info=lambda: {},
+ )
+ result = build_knowledge_graph_skeleton(
+ parsed_files=[],
+ graph_builder=builder,
+ repo_structure=_structure(RAW),
+ tech_stack=[],
+ external_systems=[],
+ )
+ assert result.project["entry_points"] == RANKED
+
+
+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
+ started the guided tour at a re-export barrel."""
+ from repowise.core.generation.knowledge_graph import build_deterministic_tour
+
+ layers = [{"name": "App", "nodeIds": [f"file:{p}" for p in RAW]}]
+ ranked = orientation_entry_points(_structure(RAW), limit=10)
+ stops = build_deterministic_tour({p: 0.1 for p in RAW}, ranked, layers)
+
+ assert stops
+ assert stops[0]["nodeIds"] == ["file:src/main.py"]