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.

Risk + symbols + git UI: truthful pagination, importance ranking, scatter fix (#187)

Raghav Chamadiyaf4360389d5db
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer.py
index a2021d2a2..e90f91dc9 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer.py
@@ -79,6 +79,13 @@ _MIN_MESSAGE_LEN = 12
# Default per-file commit history depth.
_DEFAULT_COMMIT_LIMIT: int = 500
+# Per-file persisted contributor / commit fan-out. Previously hard-coded
+# to 5 / 10 inline, which silently hid co-owners and meaningful history on
+# multi-team modules. 50 is generous enough that any realistic UI surface
+# can render the full list while keeping the JSON blob bounded.
+_MAX_TOP_AUTHORS: int = 50
+_MAX_SIGNIFICANT_COMMITS: int = 50
+
# Co-change pair extraction widens the window because individual files
# may only co-change a handful of times in 500 commits — well below the
# ``min_count`` threshold. On low-churn repos the 500-commit window
@@ -714,9 +721,11 @@ class GitIndexer:
break
meta["bus_factor"] = bus
- # Top authors
+ # Top authors — keep a generous slice (50) so the API can show
+ # the full contributor surface for a file; the old top-5 cap
+ # silently hid co-owners on multi-team modules.
top_authors = []
- for name, count in author_counts.most_common(5):
+ for name, count in author_counts.most_common(_MAX_TOP_AUTHORS):
top_authors.append(
{
"name": name,
@@ -775,7 +784,7 @@ class GitIndexer:
pr_num = pr_match.group(1) or pr_match.group(2) or pr_match.group(3)
entry["pr_number"] = int(pr_num)
sig_commits.append(entry)
- if len(sig_commits) >= 10:
+ if len(sig_commits) >= _MAX_SIGNIFICANT_COMMITS:
sig_full = True
# Classify ALL commits for accurate category ratios
for cat, pattern in _COMMIT_CATEGORIES.items():
diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.py
index 1d3cdd4b4..52bf8ff5f 100644
--- a/packages/server/src/repowise/server/routers/git.py
+++ b/packages/server/src/repowise/server/routers/git.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import json
-from sqlalchemy import select
+from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import APIRouter, Depends, HTTPException, Query
@@ -17,6 +17,7 @@ from repowise.server.schemas import (
GitSummaryResponse,
HotspotResponse,
OwnershipEntry,
+ Paginated,
)
router = APIRouter(
@@ -26,6 +27,44 @@ router = APIRouter(
)
+# ---------------------------------------------------------------------------
+# Row mappers — kept out of the route bodies so they're trivial to test and
+# can be reused by future endpoints (owner profile, module health, etc.).
+# ---------------------------------------------------------------------------
+
+
+def _hotspot_from_row(r: GitMetadata) -> HotspotResponse:
+ # churn_percentile is stored on a 0–1 scale (rank / total) but every UI
+ # consumer treats it as a percentile rank in 0–100. Normalize here so
+ # the API contract is unambiguous and the dashboard ChurnBar / scatter
+ # / hotspots-mini render correctly without per-component hacks.
+ churn_pct = (r.churn_percentile or 0.0) * 100.0
+ return HotspotResponse(
+ file_path=r.file_path,
+ commit_count_total=r.commit_count_total or 0,
+ commit_count_90d=r.commit_count_90d,
+ commit_count_30d=r.commit_count_30d,
+ churn_percentile=churn_pct,
+ temporal_hotspot_score=r.temporal_hotspot_score,
+ primary_owner=r.primary_owner_name,
+ primary_owner_commit_pct=r.primary_owner_commit_pct,
+ recent_owner_name=r.recent_owner_name,
+ recent_owner_commit_pct=r.recent_owner_commit_pct,
+ is_hotspot=r.is_hotspot,
+ is_stable=r.is_stable,
+ bus_factor=r.bus_factor or 0,
+ contributor_count=r.contributor_count or 0,
+ lines_added_90d=r.lines_added_90d or 0,
+ lines_deleted_90d=r.lines_deleted_90d or 0,
+ avg_commit_size=r.avg_commit_size or 0.0,
+ commit_categories=json.loads(r.commit_categories_json) if r.commit_categories_json else {},
+ merge_commit_count_90d=r.merge_commit_count_90d or 0,
+ commit_count_capped=bool(r.commit_count_capped),
+ age_days=r.age_days or 0,
+ last_commit_at=r.last_commit_at,
+ )
+
+
@router.get("/{repo_id}/git-metadata", response_model=GitMetadataResponse)
async def get_git_metadata(
repo_id: str,
@@ -41,61 +80,61 @@ async def get_git_metadata(
return response
[email protected]("/{repo_id}/hotspots", response_model=list[HotspotResponse])
[email protected]("/{repo_id}/hotspots", response_model=Paginated[HotspotResponse])
async def get_hotspots(
repo_id: str,
- limit: int = Query(20, ge=1, le=100),
+ limit: int = Query(50, ge=1, le=500),
+ offset: int = Query(0, ge=0),
session: AsyncSession = Depends(get_db_session), # noqa: B008
-) -> list[HotspotResponse]:
- """Get the highest-churn files (hotspots) for a repository."""
- result = await session.execute(
- select(GitMetadata)
- .where(
- GitMetadata.repository_id == repo_id,
- GitMetadata.is_hotspot.is_(True),
- )
- .order_by(
- GitMetadata.temporal_hotspot_score.desc().nulls_last(),
- GitMetadata.churn_percentile.desc(),
- )
- .limit(limit)
+) -> Paginated[HotspotResponse]:
+ """Return the highest-churn files (hotspots), paginated.
+
+ The previous response shape was a bare list capped at 100 rows — large
+ repos with thousands of hotspots silently lost the long tail. Callers
+ should treat the envelope's ``total`` as authoritative and request
+ further pages via ``offset``.
+ """
+
+ base = select(GitMetadata).where(
+ GitMetadata.repository_id == repo_id,
+ GitMetadata.is_hotspot.is_(True),
+ )
+ total = await session.scalar(select(func.count()).select_from(base.subquery())) or 0
+
+ paged = base.order_by(
+ GitMetadata.temporal_hotspot_score.desc().nulls_last(),
+ GitMetadata.churn_percentile.desc(),
+ ).limit(limit).offset(offset)
+ rows = (await session.execute(paged)).scalars().all()
+ items = [_hotspot_from_row(r) for r in rows]
+ next_offset = offset + limit if offset + limit < total else None
+ return Paginated[HotspotResponse](
+ items=items,
+ total=total,
+ has_more=next_offset is not None,
+ next_offset=next_offset,
)
- rows = result.scalars().all()
- return [
- HotspotResponse(
- file_path=r.file_path,
- commit_count_90d=r.commit_count_90d,
- commit_count_30d=r.commit_count_30d,
- churn_percentile=r.churn_percentile,
- temporal_hotspot_score=r.temporal_hotspot_score,
- primary_owner=r.primary_owner_name,
- is_hotspot=r.is_hotspot,
- is_stable=r.is_stable,
- bus_factor=r.bus_factor or 0,
- contributor_count=r.contributor_count or 0,
- lines_added_90d=r.lines_added_90d or 0,
- lines_deleted_90d=r.lines_deleted_90d or 0,
- avg_commit_size=r.avg_commit_size or 0.0,
- commit_categories=json.loads(r.commit_categories_json)
- if r.commit_categories_json
- else {},
- )
- for r in rows
- ]
-
-
[email protected]("/{repo_id}/ownership", response_model=list[OwnershipEntry])
+
+
[email protected]("/{repo_id}/ownership", response_model=Paginated[OwnershipEntry])
async def get_ownership(
repo_id: str,
granularity: str = Query("module", description="file or module"),
+ limit: int = Query(500, ge=1, le=5000),
+ offset: int = Query(0, ge=0),
session: AsyncSession = Depends(get_db_session), # noqa: B008
-) -> list[OwnershipEntry]:
- """Get ownership breakdown for a repository."""
+) -> Paginated[OwnershipEntry]:
+ """Ownership breakdown for a repository, paginated.
+
+ ``granularity=module`` groups by top-level directory; ``file`` returns
+ one entry per tracked file.
+ """
+
result = await session.execute(select(GitMetadata).where(GitMetadata.repository_id == repo_id))
all_meta = result.scalars().all()
if granularity == "file":
- return [
+ entries = [
OwnershipEntry(
module_path=m.file_path,
primary_owner=m.primary_owner_name,
@@ -105,38 +144,45 @@ async def get_ownership(
)
for m in all_meta
]
-
- # Group by top-level directory (module)
- modules: dict[str, list] = {}
- for m in all_meta:
- parts = m.file_path.split("/")
- module = parts[0] if len(parts) > 1 else "root"
- modules.setdefault(module, []).append(m)
-
- entries = []
- for module_path, files in sorted(modules.items()):
- # Find the most common owner in this module
- owners: dict[str, int] = {}
- for f in files:
- if f.primary_owner_name:
- owners[f.primary_owner_name] = owners.get(f.primary_owner_name, 0) + 1
- if owners:
- top_owner = max(owners, key=owners.get) # type: ignore[arg-type]
- owner_pct = owners[top_owner] / len(files)
- else:
- top_owner = None
- owner_pct = 0.0
-
- entries.append(
- OwnershipEntry(
- module_path=module_path,
- primary_owner=top_owner,
- owner_pct=owner_pct,
- file_count=len(files),
- is_silo=owner_pct > 0.8,
+ else:
+ modules: dict[str, list] = {}
+ for m in all_meta:
+ parts = m.file_path.split("/")
+ module = parts[0] if len(parts) > 1 else "root"
+ modules.setdefault(module, []).append(m)
+
+ entries = []
+ for module_path, files in sorted(modules.items()):
+ owners: dict[str, int] = {}
+ for f in files:
+ if f.primary_owner_name:
+ owners[f.primary_owner_name] = owners.get(f.primary_owner_name, 0) + 1
+ if owners:
+ top_owner = max(owners, key=owners.get) # type: ignore[arg-type]
+ owner_pct = owners[top_owner] / len(files)
+ else:
+ top_owner = None
+ owner_pct = 0.0
+
+ entries.append(
+ OwnershipEntry(
+ module_path=module_path,
+ primary_owner=top_owner,
+ owner_pct=owner_pct,
+ file_count=len(files),
+ is_silo=owner_pct > 0.8,
+ )
)
- )
- return entries
+
+ total = len(entries)
+ page = entries[offset : offset + limit]
+ next_offset = offset + limit if offset + limit < total else None
+ return Paginated[OwnershipEntry](
+ items=page,
+ total=total,
+ has_more=next_offset is not None,
+ next_offset=next_offset,
+ )
@router.get("/{repo_id}/co-changes")
@@ -157,23 +203,35 @@ async def get_co_changes(
return {
"file_path": file_path,
"co_change_partners": filtered,
+ "total": len(filtered),
}
@router.get("/{repo_id}/git-summary", response_model=GitSummaryResponse)
async def get_git_summary(
repo_id: str,
+ top_owners_limit: int = Query(25, ge=1, le=200),
session: AsyncSession = Depends(get_db_session), # noqa: B008
) -> GitSummaryResponse:
- """Get aggregate git health signals for a repository."""
+ """Aggregate git health signals for a repository.
+
+ ``top_owners_limit`` controls how many contributors are returned in
+ descending order of file count. Defaults to 25 (vs. the old hardcoded
+ 10) so an engineering leader can see the broader contributor surface.
+ """
+
result = await session.execute(select(GitMetadata).where(GitMetadata.repository_id == repo_id))
all_meta = list(result.scalars().all())
hotspot_count = sum(1 for m in all_meta if m.is_hotspot)
stable_count = sum(1 for m in all_meta if m.is_stable)
- avg_churn = sum(m.churn_percentile for m in all_meta) / len(all_meta) if all_meta else 0.0
+ # Normalize to 0–100 to match the rest of the HTTP API contract.
+ avg_churn = (
+ sum(m.churn_percentile for m in all_meta) / len(all_meta) * 100.0
+ if all_meta
+ else 0.0
+ )
- # Top owners by file count
owners: dict[str, int] = {}
for m in all_meta:
if m.primary_owner_name:
@@ -183,7 +241,7 @@ async def get_git_summary(
[{"name": k, "file_count": v, "pct": v / total} for k, v in owners.items()],
key=lambda x: x["file_count"],
reverse=True,
- )[:10]
+ )[:top_owners_limit]
return GitSummaryResponse(
total_files=len(all_meta),
diff --git a/packages/server/src/repowise/server/routers/symbols.py b/packages/server/src/repowise/server/routers/symbols.py
index aef662824..974ac4b87 100644
--- a/packages/server/src/repowise/server/routers/symbols.py
+++ b/packages/server/src/repowise/server/routers/symbols.py
@@ -2,13 +2,19 @@
from __future__ import annotations
-from sqlalchemy import select
+from typing import Literal
+
+from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import APIRouter, Depends, HTTPException, Query
-from repowise.core.persistence.models import WikiSymbol
+from repowise.core.persistence.models import GitMetadata, GraphNode, WikiSymbol
from repowise.server.deps import get_db_session, verify_api_key
-from repowise.server.schemas import SymbolResponse
+from repowise.server.schemas import Paginated, SymbolImportanceComponents, SymbolResponse
+from repowise.server.services.symbol_ranking import (
+ compute_components,
+ rank_symbols,
+)
router = APIRouter(
prefix="/api/symbols",
@@ -17,31 +23,201 @@ router = APIRouter(
)
[email protected]("", response_model=list[SymbolResponse])
+SortKey = Literal["importance", "name", "complexity", "kind"]
+
+
+def _attach_signals(
+ response: SymbolResponse,
+ *,
+ pagerank: float,
+ is_entry_point: bool,
+ churn_percentile: float | None,
+ is_hotspot: bool | None,
+ components,
+ score: float,
+) -> SymbolResponse:
+ response.importance_score = round(score, 6)
+ response.importance_components = SymbolImportanceComponents(
+ file_pagerank=components.file_pagerank,
+ visibility_factor=components.visibility_factor,
+ complexity_norm=components.complexity_norm,
+ kind_boost=components.kind_boost,
+ is_entry_point=components.is_entry_point,
+ )
+ response.file_pagerank = pagerank
+ response.is_entry_point = is_entry_point
+ response.file_churn_percentile = churn_percentile
+ response.file_is_hotspot = is_hotspot
+ return response
+
+
+async def _file_signals(
+ session: AsyncSession, repo_id: str, paths: set[str]
+) -> tuple[dict[str, tuple[float, bool]], dict[str, tuple[float | None, bool | None]]]:
+ """Fetch file-level signals (pagerank + entry-point, churn + hotspot) for
+ the given file paths in a single round trip each."""
+
+ if not paths:
+ return {}, {}
+
+ pagerank_rows = await session.execute(
+ select(GraphNode.node_id, GraphNode.pagerank, GraphNode.is_entry_point).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_type == "file",
+ GraphNode.node_id.in_(paths),
+ )
+ )
+ pagerank_map: dict[str, tuple[float, bool]] = {
+ row.node_id: (float(row.pagerank or 0.0), bool(row.is_entry_point))
+ for row in pagerank_rows
+ }
+
+ churn_rows = await session.execute(
+ select(GitMetadata.file_path, GitMetadata.churn_percentile, GitMetadata.is_hotspot).where(
+ GitMetadata.repository_id == repo_id,
+ GitMetadata.file_path.in_(paths),
+ )
+ )
+ churn_map: dict[str, tuple[float | None, bool | None]] = {
+ # 0–1 stored → 0–100 exposed (matches HotspotResponse contract).
+ row.file_path: (
+ float(row.churn_percentile) * 100.0 if row.churn_percentile is not None else None,
+ bool(row.is_hotspot),
+ )
+ for row in churn_rows
+ }
+ return pagerank_map, churn_map
+
+
[email protected]("", response_model=Paginated[SymbolResponse])
async def search_symbols(
repo_id: str = Query(..., description="Repository ID"),
q: str = Query("", description="Search query (substring match on name)"),
kind: str | None = Query(None, description="Filter by symbol kind"),
language: str | None = Query(None, description="Filter by language"),
+ visibility: str | None = Query(None, description="Filter by visibility"),
+ in_hot_files: bool = Query(False, description="Only symbols whose file is a hotspot"),
+ in_entry_points: bool = Query(False, description="Only symbols in entry-point files"),
+ sort: SortKey = Query("importance", description="Sort key"),
limit: int = Query(50, ge=1, le=500),
offset: int = Query(0, ge=0),
session: AsyncSession = Depends(get_db_session), # noqa: B008
-) -> list[SymbolResponse]:
- """Search symbols by name, kind, or language."""
- query = select(WikiSymbol).where(WikiSymbol.repository_id == repo_id)
+) -> Paginated[SymbolResponse]:
+ """Search symbols by name/kind/language with importance-aware ranking.
+ Importance sort is stable across pages: the server scores every symbol
+ that matches the filters, sorts in Python (composite score is cheap),
+ and returns the requested page. For very large symbol tables (>50k) the
+ score should be persisted at index time — tracked as Phase 3 work.
+ """
+
+ base = select(WikiSymbol).where(WikiSymbol.repository_id == repo_id)
if q:
- query = query.where(WikiSymbol.name.ilike(f"%{q}%"))
+ base = base.where(WikiSymbol.name.ilike(f"%{q}%"))
if kind:
- query = query.where(WikiSymbol.kind == kind)
+ base = base.where(WikiSymbol.kind == kind)
if language:
- query = query.where(WikiSymbol.language == language)
+ base = base.where(WikiSymbol.language == language)
+ if visibility:
+ base = base.where(WikiSymbol.visibility == visibility)
+
+ # Optional file-level filters require resolving file paths up front.
+ if in_hot_files or in_entry_points:
+ file_query = select(GraphNode.node_id if in_entry_points else GitMetadata.file_path)
+ if in_entry_points:
+ file_query = file_query.where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_type == "file",
+ GraphNode.is_entry_point.is_(True),
+ )
+ if in_hot_files:
+ hot_paths = await session.execute(
+ select(GitMetadata.file_path).where(
+ GitMetadata.repository_id == repo_id,
+ GitMetadata.is_hotspot.is_(True),
+ )
+ )
+ hot_set = {r.file_path for r in hot_paths}
+ base = base.where(WikiSymbol.file_path.in_(hot_set or {""}))
+ if in_entry_points:
+ ep_paths = await session.execute(
+ select(GraphNode.node_id).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_type == "file",
+ GraphNode.is_entry_point.is_(True),
+ )
+ )
+ ep_set = {r.node_id for r in ep_paths}
+ base = base.where(WikiSymbol.file_path.in_(ep_set or {""}))
+
+ total = await session.scalar(select(func.count()).select_from(base.subquery())) or 0
- query = query.order_by(WikiSymbol.name).limit(limit).offset(offset)
+ if sort == "importance":
+ # Need the full filtered set to score then page; for non-importance
+ # sorts SQL ORDER BY is faster and equally stable.
+ all_rows = (await session.execute(base)).scalars().all()
+ paths = {s.file_path for s in all_rows}
+ pagerank_map, churn_map = await _file_signals(session, repo_id, paths)
+ ranked = rank_symbols(list(all_rows), pagerank_map)
+ page = ranked[offset : offset + limit]
+ items: list[SymbolResponse] = []
+ for r in page:
+ response = SymbolResponse.from_orm(r.symbol)
+ churn, hot = churn_map.get(getattr(r.symbol, "file_path", "") or "", (None, None))
+ items.append(
+ _attach_signals(
+ response,
+ pagerank=r.file_pagerank,
+ is_entry_point=r.is_entry_point,
+ churn_percentile=churn,
+ is_hotspot=hot,
+ components=r.components,
+ score=r.score,
+ )
+ )
+ else:
+ if sort == "name":
+ base = base.order_by(WikiSymbol.name)
+ elif sort == "complexity":
+ base = base.order_by(WikiSymbol.complexity_estimate.desc(), WikiSymbol.name)
+ elif sort == "kind":
+ base = base.order_by(WikiSymbol.kind, WikiSymbol.name)
+ rows = (
+ await session.execute(base.limit(limit).offset(offset))
+ ).scalars().all()
+ paths = {s.file_path for s in rows}
+ pagerank_map, churn_map = await _file_signals(session, repo_id, paths)
+ items = []
+ for sym in rows:
+ response = SymbolResponse.from_orm(sym)
+ pr, ep = pagerank_map.get(sym.file_path, (0.0, False))
+ churn, hot = churn_map.get(sym.file_path, (None, None))
+ components = compute_components(
+ file_pagerank=pr,
+ visibility=sym.visibility,
+ complexity=sym.complexity_estimate,
+ kind=sym.kind,
+ is_entry_point=ep,
+ )
+ items.append(
+ _attach_signals(
+ response,
+ pagerank=pr,
+ is_entry_point=ep,
+ churn_percentile=churn,
+ is_hotspot=hot,
+ components=components,
+ score=components.score(),
+ )
+ )
- result = await session.execute(query)
- symbols = result.scalars().all()
- return [SymbolResponse.from_orm(s) for s in symbols]
+ next_offset = offset + limit if offset + limit < total else None
+ return Paginated[SymbolResponse](
+ items=items,
+ total=total,
+ has_more=next_offset is not None,
+ next_offset=next_offset,
+ )
@router.get("/by-name/{name}", response_model=list[SymbolResponse])
@@ -54,7 +230,7 @@ async def lookup_by_name(
Returns exact matches first, then LIKE matches, up to 10 results.
"""
- # Try exact match first
+
result = await session.execute(
select(WikiSymbol).where(
WikiSymbol.repository_id == repo_id,
@@ -65,7 +241,6 @@ async def lookup_by_name(
if exact:
return [SymbolResponse.from_orm(s) for s in exact]
- # Fall back to LIKE match
result = await session.execute(
select(WikiSymbol)
.where(
@@ -84,6 +259,7 @@ async def get_symbol(
session: AsyncSession = Depends(get_db_session), # noqa: B008
) -> SymbolResponse:
"""Get a single symbol by its database ID."""
+
sym = await session.get(WikiSymbol, symbol_db_id)
if sym is None:
raise HTTPException(status_code=404, detail="Symbol not found")
diff --git a/packages/server/src/repowise/server/schemas.py b/packages/server/src/repowise/server/schemas.py
index 30b16867a..4b71adb15 100644
--- a/packages/server/src/repowise/server/schemas.py
+++ b/packages/server/src/repowise/server/schemas.py
@@ -5,9 +5,30 @@ from __future__ import annotations
import json
from datetime import datetime
from pathlib import Path
+from typing import Generic, TypeVar
from pydantic import BaseModel, Field, field_validator
+# ---------------------------------------------------------------------------
+# Pagination envelope — shared across list endpoints (git, symbols, etc.)
+# ---------------------------------------------------------------------------
+
+T = TypeVar("T")
+
+
+class Paginated(BaseModel, Generic[T]):
+ """Stable envelope for paginated list endpoints.
+
+ Lets the UI show "Showing N of M / Load more" without guessing whether
+ a list was truncated by the server. `next_offset` is null when there
+ are no further pages.
+ """
+
+ items: list[T]
+ total: int
+ has_more: bool
+ next_offset: int | None = None
+
# ---------------------------------------------------------------------------
# Repository
# ---------------------------------------------------------------------------
@@ -232,6 +253,18 @@ class SearchResultResponse(BaseModel):
# ---------------------------------------------------------------------------
+class SymbolImportanceComponents(BaseModel):
+ """Transparent breakdown of the composite importance score so the UI can
+ explain *why* a symbol ranks where it does. All fields are normalized to
+ [0, 1] except booleans."""
+
+ file_pagerank: float = 0.0
+ visibility_factor: float = 0.5
+ complexity_norm: float = 0.0
+ kind_boost: float = 1.0
+ is_entry_point: bool = False
+
+
class SymbolResponse(BaseModel):
id: str
repository_id: str
@@ -249,6 +282,14 @@ class SymbolResponse(BaseModel):
complexity_estimate: int
language: str
parent_name: str | None
+ # Importance signals (populated when the list endpoint joins GraphNode /
+ # GitMetadata; nullable so single-symbol lookups remain lightweight).
+ importance_score: float | None = None
+ importance_components: SymbolImportanceComponents | None = None
+ file_pagerank: float | None = None
+ is_entry_point: bool | None = None
+ file_churn_percentile: float | None = None
+ file_is_hotspot: bool | None = None
@classmethod
def from_orm(cls, obj: object) -> SymbolResponse:
@@ -400,7 +441,8 @@ class GitMetadataResponse(BaseModel):
co_change_partners=json.loads(obj.co_change_partners_json), # type: ignore[attr-defined]
is_hotspot=obj.is_hotspot, # type: ignore[attr-defined]
is_stable=obj.is_stable, # type: ignore[attr-defined]
- churn_percentile=obj.churn_percentile, # type: ignore[attr-defined]
+ # Normalize 0–1 → 0–100 to match the rest of the HTTP API.
+ churn_percentile=(obj.churn_percentile or 0.0) * 100.0, # type: ignore[attr-defined]
age_days=obj.age_days, # type: ignore[attr-defined]
bus_factor=obj.bus_factor or 0, # type: ignore[attr-defined]
contributor_count=obj.contributor_count or 0, # type: ignore[attr-defined]
@@ -416,11 +458,15 @@ class GitMetadataResponse(BaseModel):
class HotspotResponse(BaseModel):
file_path: str
+ commit_count_total: int = 0
commit_count_90d: int
commit_count_30d: int
churn_percentile: float
temporal_hotspot_score: float | None = None
primary_owner: str | None
+ primary_owner_commit_pct: float | None = None
+ recent_owner_name: str | None = None
+ recent_owner_commit_pct: float | None = None
is_hotspot: bool
is_stable: bool
bus_factor: int
@@ -429,6 +475,10 @@ class HotspotResponse(BaseModel):
lines_deleted_90d: int
avg_commit_size: float
commit_categories: dict
+ merge_commit_count_90d: int = 0
+ commit_count_capped: bool = False
+ age_days: int = 0
+ last_commit_at: datetime | None = None
class OwnershipEntry(BaseModel):
diff --git a/packages/server/src/repowise/server/services/symbol_ranking.py b/packages/server/src/repowise/server/services/symbol_ranking.py
new file mode 100644
index 000000000..189b4058f
--- /dev/null
+++ b/packages/server/src/repowise/server/services/symbol_ranking.py
@@ -0,0 +1,154 @@
+"""Composite importance scoring for code symbols.
+
+Symbols are ranked by a blend of architectural and structural signals that
+already live in the database — no new ingestion pass required. The formula
+favours symbols that sit at the centre of the dependency graph, are
+externally visible, are non-trivial in size, and are flagged as entry
+points.
+
+The score is monotonic and bounded in [0, 1] per term, so it's safe to
+compute server-side as a SQL expression for ORDER BY without materializing
+the full list.
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass
+
+# Weights — kept in one place so future tuning has a single touch-point.
+W_PAGERANK = 0.40
+W_VISIBILITY = 0.25
+W_COMPLEXITY = 0.20
+W_KIND = 0.10
+W_ENTRY_POINT = 0.05
+
+# Complexity is log-normalized against this ceiling so that a 30-branch
+# function reaches the max signal — anything beyond is squashed.
+_COMPLEXITY_CAP = 30.0
+_COMPLEXITY_LOG_CEILING = math.log(_COMPLEXITY_CAP + 1.0)
+
+# Symbol-kind multiplier. Classes and interfaces tend to carry more
+# architectural weight than free functions; variables and constants less.
+_KIND_BOOST: dict[str, float] = {
+ "class": 1.2,
+ "interface": 1.15,
+ "trait": 1.15,
+ "struct": 1.1,
+ "enum": 1.05,
+ "module": 1.05,
+ "function": 1.0,
+ "method": 1.0,
+ "type": 0.9,
+ "variable": 0.7,
+ "constant": 0.7,
+}
+_DEFAULT_KIND_BOOST = 1.0
+
+
+@dataclass(frozen=True)
+class ImportanceComponents:
+ file_pagerank: float
+ visibility_factor: float
+ complexity_norm: float
+ kind_boost: float
+ is_entry_point: bool
+
+ def score(self) -> float:
+ return (
+ W_PAGERANK * self.file_pagerank
+ + W_VISIBILITY * self.visibility_factor
+ + W_COMPLEXITY * self.complexity_norm
+ + W_KIND * (self.kind_boost / 1.2) # normalize to [0, 1]
+ + W_ENTRY_POINT * (1.0 if self.is_entry_point else 0.0)
+ )
+
+
+def _visibility_factor(visibility: str | None) -> float:
+ if not visibility:
+ return 0.5
+ v = visibility.lower()
+ if v == "public":
+ return 1.0
+ if v == "protected":
+ return 0.75
+ return 0.4
+
+
+def _complexity_norm(complexity: int | None) -> float:
+ if not complexity or complexity <= 0:
+ return 0.0
+ return min(1.0, math.log(complexity + 1.0) / _COMPLEXITY_LOG_CEILING)
+
+
+def _kind_boost(kind: str | None) -> float:
+ if not kind:
+ return _DEFAULT_KIND_BOOST
+ return _KIND_BOOST.get(kind.lower(), _DEFAULT_KIND_BOOST)
+
+
+def compute_components(
+ *,
+ file_pagerank: float | None,
+ visibility: str | None,
+ complexity: int | None,
+ kind: str | None,
+ is_entry_point: bool | None,
+) -> ImportanceComponents:
+ """Pure-Python score components — used to enrich already-fetched rows."""
+
+ return ImportanceComponents(
+ file_pagerank=float(file_pagerank or 0.0),
+ visibility_factor=_visibility_factor(visibility),
+ complexity_norm=_complexity_norm(complexity),
+ kind_boost=_kind_boost(kind),
+ is_entry_point=bool(is_entry_point),
+ )
+
+
+@dataclass(frozen=True)
+class RankedSymbol:
+ """A WikiSymbol paired with the components/score used to rank it."""
+
+ symbol: object # WikiSymbol — kept loose so this module doesn't pull SQLAlchemy types
+ components: ImportanceComponents
+ file_pagerank: float
+ is_entry_point: bool
+ score: float
+
+
+def rank_symbols(
+ symbols: list[object],
+ file_signals: dict[str, tuple[float, bool]],
+) -> list[RankedSymbol]:
+ """Annotate symbols with importance components and return them ordered by
+ descending score (with name as the tiebreaker for stable pagination).
+
+ ``file_signals`` maps ``file_path`` → ``(pagerank, is_entry_point)`` so
+ callers can fetch the GraphNode rows once and reuse them.
+ """
+
+ ranked: list[RankedSymbol] = []
+ for sym in symbols:
+ path = getattr(sym, "file_path", None)
+ pagerank, entry = file_signals.get(path or "", (0.0, False))
+ components = compute_components(
+ file_pagerank=pagerank,
+ visibility=getattr(sym, "visibility", None),
+ complexity=getattr(sym, "complexity_estimate", 0),
+ kind=getattr(sym, "kind", None),
+ is_entry_point=entry,
+ )
+ ranked.append(
+ RankedSymbol(
+ symbol=sym,
+ components=components,
+ file_pagerank=pagerank,
+ is_entry_point=entry,
+ score=components.score(),
+ )
+ )
+
+ # Stable tiebreaker on name keeps pagination deterministic across pages.
+ ranked.sort(key=lambda r: (-r.score, getattr(r.symbol, "name", "")))
+ return ranked
diff --git a/packages/types/src/git.ts b/packages/types/src/git.ts
index 13d89d1b1..812fa2831 100644
--- a/packages/types/src/git.ts
+++ b/packages/types/src/git.ts
@@ -59,11 +59,17 @@ export interface GitMetadata {
export interface Hotspot {
file_path: string;
+ commit_count_total?: number;
commit_count_90d: number;
commit_count_30d: number;
churn_percentile: number;
temporal_hotspot_score?: number | null;
primary_owner: string | null;
+ /** Share of all-time commits attributable to the primary owner, 0–1. */
+ primary_owner_commit_pct?: number | null;
+ /** Top author in the last 90 days; may differ from primary_owner on legacy code. */
+ recent_owner_name?: string | null;
+ recent_owner_commit_pct?: number | null;
is_hotspot: boolean;
is_stable: boolean;
bus_factor: number;
@@ -72,6 +78,11 @@ export interface Hotspot {
lines_deleted_90d: number;
avg_commit_size: number;
commit_categories: Record<string, number>;
+ merge_commit_count_90d?: number;
+ /** True when the per-file commit-history cap was hit during indexing — i.e. older history exists but was not analysed. */
+ commit_count_capped?: boolean;
+ age_days?: number;
+ last_commit_at?: string | null;
}
export interface OwnershipEntry {
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index c62611ae9..b03a0975a 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -7,6 +7,7 @@
* are also supported via the `exports` map in package.json.
*/
+export * from "./pagination.js";
export * from "./graph.js";
export * from "./git.js";
export * from "./docs.js";
diff --git a/packages/types/src/pagination.ts b/packages/types/src/pagination.ts
new file mode 100644
index 000000000..264410fe2
--- /dev/null
+++ b/packages/types/src/pagination.ts
@@ -0,0 +1,14 @@
+/**
+ * Canonical pagination envelope used by all list endpoints (git, symbols,
+ * dead-code, etc.). Mirrors `repowise.server.schemas.Paginated[T]`.
+ *
+ * Clients should read `total` as authoritative ("there are N matching rows
+ * server-side") and use `next_offset` to fetch further pages. When
+ * `has_more` is false, the list is complete.
+ */
+export interface Paginated<T> {
+ items: T[];
+ total: number;
+ has_more: boolean;
+ next_offset: number | null;
+}
diff --git a/packages/types/src/symbols.ts b/packages/types/src/symbols.ts
index 761478537..6ccf121db 100644
--- a/packages/types/src/symbols.ts
+++ b/packages/types/src/symbols.ts
@@ -21,6 +21,19 @@ export type SymbolKind =
export type SymbolVisibility = "public" | "private" | "protected" | (string & {});
+/**
+ * Transparent breakdown of the composite importance score. Mirrors the
+ * server's ``SymbolImportanceComponents``; lets the UI explain *why* a
+ * symbol ranks where it does (tooltip on the score chip).
+ */
+export interface SymbolImportanceComponents {
+ file_pagerank: number;
+ visibility_factor: number;
+ complexity_norm: number;
+ kind_boost: number;
+ is_entry_point: boolean;
+}
+
/** Renamed `CodeSymbol` to avoid shadowing the global `Symbol`. */
export interface CodeSymbol {
id: string;
@@ -39,6 +52,14 @@ export interface CodeSymbol {
complexity_estimate: number;
language: string;
parent_name: string | null;
+ /** Composite importance score (0–1ish). Populated by the list endpoint. */
+ importance_score?: number | null;
+ importance_components?: SymbolImportanceComponents | null;
+ /** File-level signals — populated by the list endpoint via JOINs. */
+ file_pagerank?: number | null;
+ is_entry_point?: boolean | null;
+ file_churn_percentile?: number | null;
+ file_is_hotspot?: boolean | null;
}
export interface SymbolList {
diff --git a/packages/ui/__tests__/symbols/symbol-table.test.tsx b/packages/ui/__tests__/symbols/symbol-table.test.tsx
index 286f2e87f..c56d124f8 100644
--- a/packages/ui/__tests__/symbols/symbol-table.test.tsx
+++ b/packages/ui/__tests__/symbols/symbol-table.test.tsx
@@ -1,6 +1,6 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
-import { SymbolTable } from "../../src/symbols/symbol-table.js";
+import { SymbolTable, type SymbolFilters } from "../../src/symbols/symbol-table.js";
import type { CodeSymbol } from "@repowise-dev/types/symbols";
const sym = (overrides: Partial<CodeSymbol> = {}): CodeSymbol => ({
@@ -20,24 +20,31 @@ const sym = (overrides: Partial<CodeSymbol> = {}): CodeSymbol => ({
complexity_estimate: 3,
language: "typescript",
parent_name: null,
+ importance_score: 0.9,
...overrides,
});
+const defaultFilters: SymbolFilters = {
+ q: "",
+ kind: "all",
+ language: "all",
+ visibility: "all",
+ inHotFiles: false,
+ inEntryPoints: false,
+ sort: "importance",
+};
+
describe("SymbolTable", () => {
it("renders the empty state when no items", () => {
render(
<SymbolTable
items={[]}
- importanceScores={new Map()}
isLoading={false}
isValidating={false}
hasMore={false}
- q=""
- onQChange={vi.fn()}
- kind="all"
- onKindChange={vi.fn()}
- language="all"
- onLanguageChange={vi.fn()}
+ total={0}
+ filters={defaultFilters}
+ onFiltersChange={vi.fn()}
onLoadMore={vi.fn()}
onSelect={vi.fn()}
/>,
@@ -48,23 +55,20 @@ describe("SymbolTable", () => {
it("renders rows for loaded symbols", () => {
render(
<SymbolTable
- items={[sym(), sym({ id: "s2", name: "baz", file_path: "src/baz.ts" })]}
- importanceScores={new Map([["s1", 0.9], ["s2", 0.3]])}
+ items={[sym(), sym({ id: "s2", name: "baz", file_path: "src/baz.ts", importance_score: 0.3 })]}
isLoading={false}
isValidating={false}
hasMore={false}
- q=""
- onQChange={vi.fn()}
- kind="all"
- onKindChange={vi.fn()}
- language="all"
- onLanguageChange={vi.fn()}
+ total={2}
+ filters={defaultFilters}
+ onFiltersChange={vi.fn()}
onLoadMore={vi.fn()}
onSelect={vi.fn()}
/>,
);
expect(screen.getByText("bar")).toBeTruthy();
expect(screen.getByText("baz")).toBeTruthy();
- expect(screen.getByText("2 symbols")).toBeTruthy();
+ // ResultsFooter renders "Showing 2 of 2 symbols"
+ expect(screen.getByText(/Showing/)).toBeTruthy();
});
});
diff --git a/packages/ui/src/dashboard/attention-panel.tsx b/packages/ui/src/dashboard/attention-panel.tsx
index 64c95df02..970f31902 100644
--- a/packages/ui/src/dashboard/attention-panel.tsx
+++ b/packages/ui/src/dashboard/attention-panel.tsx
@@ -1,3 +1,4 @@
+import { useState } from "react";
import {
AlertTriangle,
Trash2,
@@ -50,6 +51,8 @@ interface AttentionPanelProps {
items: AttentionItem[];
repoId: string;
linkPrefix?: string;
+ /** Initial preview window; expanding the panel reveals all items. */
+ previewCount?: number;
}
function getDefaultHref(item: AttentionItem, prefix: string): string {
@@ -68,8 +71,15 @@ function getDefaultHref(item: AttentionItem, prefix: string): string {
}
}
-export function AttentionPanel({ items, repoId, linkPrefix }: AttentionPanelProps) {
+export function AttentionPanel({
+ items,
+ repoId,
+ linkPrefix,
+ previewCount = 8,
+}: AttentionPanelProps) {
const prefix = linkPrefix ?? `/repos/${repoId}`;
+ const [expanded, setExpanded] = useState(false);
+ const visible = expanded ? items : items.slice(0, previewCount);
if (items.length === 0) {
return (
<Card>
@@ -97,7 +107,7 @@ export function AttentionPanel({ items, repoId, linkPrefix }: AttentionPanelProp
</CardHeader>
<CardContent className="pt-0">
<div className="space-y-1">
- {items.slice(0, 8).map((item) => {
+ {visible.map((item) => {
const Icon = ICON_MAP[item.type];
const href = item.href ?? getDefaultHref(item, prefix);
return (
@@ -125,10 +135,16 @@ export function AttentionPanel({ items, repoId, linkPrefix }: AttentionPanelProp
</a>
);
})}
- {items.length > 8 && (
- <p className="text-[11px] text-[var(--color-text-tertiary)] text-center pt-1">
- +{items.length - 8} more items
- </p>
+ {items.length > previewCount && (
+ <button
+ type="button"
+ onClick={() => setExpanded((v) => !v)}
+ className="block w-full text-[11px] text-[var(--color-accent-primary)] hover:underline text-center pt-1"
+ >
+ {expanded
+ ? "Show fewer"
+ : `+${items.length - previewCount} more items — show all`}
+ </button>
)}
</div>
</CardContent>
diff --git a/packages/ui/src/dashboard/hotspots-mini.tsx b/packages/ui/src/dashboard/hotspots-mini.tsx
index 996a462ea..0c45771bf 100644
--- a/packages/ui/src/dashboard/hotspots-mini.tsx
+++ b/packages/ui/src/dashboard/hotspots-mini.tsx
@@ -8,6 +8,15 @@ interface HotspotsMiniProps {
hotspots: Hotspot[];
repoId: string;
linkPrefix?: string;
+ /**
+ * Total hotspot count (from the paginated envelope). When provided the
+ * header shows "Top 5 of N" so the user understands the mini card is a
+ * preview, not the full set. Without this, the "View all" link is the
+ * only signal that more exists.
+ */
+ total?: number;
+ /** Preview window — defaults to 5; cap at 10 for a glance card. */
+ previewCount?: number;
}
function getChurnColor(percentile: number): string {
@@ -16,9 +25,19 @@ function getChurnColor(percentile: number): string {
return "var(--color-accent-primary)";
}
-export function HotspotsMini({ hotspots, repoId, linkPrefix }: HotspotsMiniProps) {
+export function HotspotsMini({
+ hotspots,
+ repoId,
+ linkPrefix,
+ total,
+ previewCount = 5,
+}: HotspotsMiniProps) {
const prefix = linkPrefix ?? `/repos/${repoId}`;
- const top = hotspots.slice(0, 5);
+ const top = hotspots.slice(0, Math.min(previewCount, 10));
+ // Authoritative total is the server-reported figure when present; fall
+ // back to the array length so this widget still works when callers
+ // haven't migrated to the paginated fetch yet.
+ const fullCount = total ?? hotspots.length;
if (top.length === 0) {
return (
@@ -41,6 +60,9 @@ export function HotspotsMini({ hotspots, repoId, linkPrefix }: HotspotsMiniProps
<span className="flex items-center gap-2">
<Flame className="h-4 w-4 text-red-500" />
Top Hotspots
+ <span className="text-[10px] font-normal text-[var(--color-text-tertiary)] tabular-nums">
+ {top.length} of {fullCount.toLocaleString()}
+ </span>
</span>
<a
href={`${prefix}/hotspots`}
diff --git a/packages/ui/src/dead-code/safe-to-delete-pile.tsx b/packages/ui/src/dead-code/safe-to-delete-pile.tsx
index 7b4fdee89..4ed13785b 100644
--- a/packages/ui/src/dead-code/safe-to-delete-pile.tsx
+++ b/packages/ui/src/dead-code/safe-to-delete-pile.tsx
@@ -42,10 +42,39 @@ export function SafeToDeletePile({
findings.reduce((sum, f) => sum + (Number.isFinite(f.lines) ? f.lines : 0), 0);
const files = new Set(findings.map((f) => f.file_path)).size;
- const top = React.useMemo(
- () => [...findings].sort((a, b) => b.lines - a.lines).slice(0, 5),
- [findings],
- );
+ // Roll findings up by file so the preview list shows distinct files
+ // instead of repeating the same path once per finding. Each group keeps
+ // a pointer back to its largest finding so onSelect still opens
+ // something meaningful in the context drawer.
+ type FileGroup = {
+ file_path: string;
+ lines: number;
+ finding_count: number;
+ representative: SafeToDeletePileFinding;
+ };
+ const groups: FileGroup[] = React.useMemo(() => {
+ const byFile = new Map<string, FileGroup>();
+ for (const f of findings) {
+ const existing = byFile.get(f.file_path);
+ if (existing) {
+ existing.lines += Number.isFinite(f.lines) ? f.lines : 0;
+ existing.finding_count += 1;
+ if ((f.lines ?? 0) > (existing.representative.lines ?? 0)) {
+ existing.representative = f;
+ }
+ } else {
+ byFile.set(f.file_path, {
+ file_path: f.file_path,
+ lines: Number.isFinite(f.lines) ? f.lines : 0,
+ finding_count: 1,
+ representative: f,
+ });
+ }
+ }
+ return [...byFile.values()].sort((a, b) => b.lines - a.lines);
+ }, [findings]);
+ const top = groups.slice(0, 5);
+ const moreFiles = Math.max(0, groups.length - top.length);
return (
<div
@@ -88,13 +117,13 @@ export function SafeToDeletePile({
{top.length > 0 && (
<ul className="mt-4 grid gap-1.5">
- {top.map((f) => {
+ {top.map((g) => {
const Tag = onSelect ? "button" : "div";
return (
- <li key={f.id}>
+ <li key={g.file_path}>
<Tag
type={onSelect ? "button" : undefined}
- onClick={onSelect ? () => onSelect(f) : undefined}
+ onClick={onSelect ? () => onSelect(g.representative) : undefined}
className={cn(
"flex w-full items-center justify-between gap-3 rounded-md border border-transparent px-2 py-1.5",
"text-left text-xs transition",
@@ -103,21 +132,29 @@ export function SafeToDeletePile({
>
<span
className="font-mono text-[11px] text-[var(--color-text-secondary)] truncate"
- title={f.symbol_name ? `${f.file_path} :: ${f.symbol_name}` : f.file_path}
+ title={g.file_path}
>
- {f.file_path}
- {f.symbol_name ? (
- <span className="text-[var(--color-text-tertiary)]"> :: {f.symbol_name}</span>
- ) : null}
+ {g.file_path}
+ {g.finding_count > 1 && (
+ <span className="ml-1.5 text-[var(--color-text-tertiary)]">
+ ({g.finding_count} findings)
+ </span>
+ )}
</span>
<span className="shrink-0 font-mono tabular-nums text-[var(--color-text-tertiary)]">
- {f.lines.toLocaleString()} lines
+ {g.lines.toLocaleString()} lines
{onSelect && <ArrowRight className="ml-1 inline h-3 w-3" />}
</span>
</Tag>
</li>
);
})}
+ {moreFiles > 0 && (
+ <li className="px-2 pt-0.5 text-[11px] text-[var(--color-text-tertiary)]">
+ +{moreFiles.toLocaleString()} more file{moreFiles === 1 ? "" : "s"} —
+ {" "}see findings table below.
+ </li>
+ )}
</ul>
)}
</div>
diff --git a/packages/ui/src/git/bus-factor-panel.tsx b/packages/ui/src/git/bus-factor-panel.tsx
index 2c2fdb54c..309bf5b9e 100644
--- a/packages/ui/src/git/bus-factor-panel.tsx
+++ b/packages/ui/src/git/bus-factor-panel.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useState } from "react";
import {
BarChart,
Bar,
@@ -14,9 +15,12 @@ import type { Hotspot } from "@repowise-dev/types/git";
interface BusFactorPanelProps {
hotspots: Hotspot[];
+ /** Number of risk files shown before the "show more" toggle. */
+ riskPreviewCount?: number;
}
-export function BusFactorPanel({ hotspots }: BusFactorPanelProps) {
+export function BusFactorPanel({ hotspots, riskPreviewCount = 5 }: BusFactorPanelProps) {
+ const [showAllRisk, setShowAllRisk] = useState(false);
if (!hotspots || hotspots.length === 0) {
return (
<EmptyState
@@ -34,10 +38,13 @@ export function BusFactorPanel({ hotspots }: BusFactorPanelProps) {
const data = [{ high, medium, low }];
- const riskFiles = hotspots
+ const allRiskFiles = hotspots
.filter((h) => h.bus_factor <= 1)
- .sort((a, b) => b.commit_count_90d - a.commit_count_90d)
- .slice(0, 5);
+ .sort((a, b) => b.commit_count_90d - a.commit_count_90d);
+ const riskFiles = showAllRisk
+ ? allRiskFiles
+ : allRiskFiles.slice(0, riskPreviewCount);
+ const hiddenRisk = allRiskFiles.length - riskFiles.length;
return (
<div className="space-y-4">
@@ -84,8 +91,11 @@ export function BusFactorPanel({ hotspots }: BusFactorPanelProps) {
{riskFiles.length > 0 && (
<div>
- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">
- Highest Risk Files
+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2 flex items-center justify-between">
+ <span>Highest Risk Files</span>
+ <span className="font-normal normal-case tracking-normal text-[10px]">
+ {riskFiles.length} of {allRiskFiles.length}
+ </span>
</p>
<div className="space-y-1.5">
{riskFiles.map((f) => (
@@ -102,6 +112,15 @@ export function BusFactorPanel({ hotspots }: BusFactorPanelProps) {
</div>
))}
</div>
+ {(hiddenRisk > 0 || showAllRisk) && (
+ <button
+ type="button"
+ onClick={() => setShowAllRisk((v) => !v)}
+ className="mt-2 text-[10px] text-[var(--color-accent-primary)] hover:underline"
+ >
+ {showAllRisk ? "Show fewer" : `Show ${hiddenRisk} more`}
+ </button>
+ )}
</div>
)}
</div>
diff --git a/packages/ui/src/git/churn-vs-bus-factor-scatter.tsx b/packages/ui/src/git/churn-vs-bus-factor-scatter.tsx
index 511bcd0c3..7d2358b15 100644
--- a/packages/ui/src/git/churn-vs-bus-factor-scatter.tsx
+++ b/packages/ui/src/git/churn-vs-bus-factor-scatter.tsx
@@ -5,6 +5,7 @@ import { cn } from "../lib/cn";
export interface ScatterHotspot {
file_path: string;
+ /** 0–100 percentile rank (post-normalisation in the HTTP layer). */
churn_percentile: number;
commit_count_90d: number;
bus_factor: number;
@@ -16,6 +17,11 @@ interface ChurnVsBusFactorScatterProps {
className?: string;
onSelect?: (filePath: string) => void;
height?: number;
+ /**
+ * Maximum filename labels rendered on the danger-zone points. Keeps the
+ * chart legible while still telling the user *which* files are fragile.
+ */
+ maxDangerLabels?: number;
}
/**
@@ -30,7 +36,8 @@ export function ChurnVsBusFactorScatter({
hotspots,
className,
onSelect,
- height = 220,
+ height = 240,
+ maxDangerLabels = 5,
}: ChurnVsBusFactorScatterProps) {
const padding = { top: 12, right: 12, bottom: 28, left: 36 };
const width = 480;
@@ -39,16 +46,31 @@ export function ChurnVsBusFactorScatter({
const points = React.useMemo(() => {
return hotspots.map((h) => {
- const x = Math.max(0, Math.min(100, h.churn_percentile));
+ // Defensive coverage: tolerate either 0–1 (legacy) or 0–100 callers.
+ const raw = h.churn_percentile ?? 0;
+ const churn = raw <= 1 ? raw * 100 : raw;
+ const x = Math.max(0, Math.min(100, churn));
// bus_factor of 1 → top of chart (riskiest); cap at 8 for visual scale.
const busClamped = Math.max(1, Math.min(8, h.bus_factor || 1));
const y = ((8 - busClamped) / 7) * 100;
// Bubble size by commit_count_90d (sqrt for area-ish scaling).
const r = 4 + Math.min(14, Math.sqrt(h.commit_count_90d ?? 0));
- return { ...h, _x: x, _y: y, _r: r };
+ const inDanger = x >= 50 && y >= 50;
+ return { ...h, _x: x, _y: y, _r: r, _danger: inDanger };
});
}, [hotspots]);
+ const dangerPoints = React.useMemo(
+ () =>
+ points
+ .filter((p) => p._danger)
+ .sort((a, b) => b._x + b._y - (a._x + a._y))
+ .slice(0, maxDangerLabels),
+ [points, maxDangerLabels],
+ );
+ const dangerCount = points.filter((p) => p._danger).length;
+ const allChurnZero = points.every((p) => p._x === 0);
+
if (points.length === 0) {
return (
<div
@@ -62,8 +84,47 @@ export function ChurnVsBusFactorScatter({
);
}
+ // When every file has churn=0, the scatter degenerates to a vertical line
+ // and conveys nothing — give the user something useful instead.
+ if (allChurnZero) {
+ return (
+ <div
+ className={cn(
+ "rounded-md border border-dashed border-[var(--color-border-default)] p-4 text-xs text-[var(--color-text-tertiary)] space-y-1",
+ className,
+ )}
+ >
+ <p className="font-medium text-[var(--color-text-secondary)]">
+ Not enough churn variation to plot.
+ </p>
+ <p>
+ The repo&apos;s churn percentile is uniform — likely a fresh clone,
+ shallow history, or a repository where all tracked files have the
+ same recent commit pattern. Try re-indexing once more history is
+ available.
+ </p>
+ </div>
+ );
+ }
+
return (
- <div className={cn("w-full", className)}>
+ <div className={cn("w-full space-y-2", className)}>
+ <div className="flex items-center justify-between text-[11px] text-[var(--color-text-tertiary)]">
+ <span>
+ {points.length} files plotted
+ </span>
+ <span
+ className={cn(
+ "inline-flex items-center gap-1 rounded px-1.5 py-0.5 tabular-nums",
+ dangerCount > 0
+ ? "bg-red-500/15 text-red-400"
+ : "bg-green-500/15 text-green-400",
+ )}
+ >
+ <span className="font-medium">{dangerCount}</span>
+ in danger zone
+ </span>
+ </div>
<svg
viewBox={`0 0 ${width} ${height}`}
preserveAspectRatio="xMidYMid meet"
@@ -152,10 +213,9 @@ export function ChurnVsBusFactorScatter({
{points.map((p) => {
const cx = padding.left + (p._x / 100) * innerW;
const cy = padding.top + innerH - (p._y / 100) * innerH;
- const fill =
- p._x >= 50 && p._y >= 50
- ? "rgba(244,63,94,0.6)"
- : "rgba(245,158,11,0.5)";
+ const fill = p._danger
+ ? "rgba(244,63,94,0.7)"
+ : "rgba(245,158,11,0.45)";
return (
<g key={p.file_path}>
<circle
@@ -163,21 +223,52 @@ export function ChurnVsBusFactorScatter({
cy={cy}
r={p._r}
fill={fill}
- stroke="rgba(0,0,0,0.2)"
- strokeWidth={0.5}
+ stroke={p._danger ? "rgba(244,63,94,0.9)" : "rgba(0,0,0,0.2)"}
+ strokeWidth={p._danger ? 1 : 0.5}
onClick={onSelect ? () => onSelect(p.file_path) : undefined}
style={{ cursor: onSelect ? "pointer" : "default" }}
>
<title>
{p.file_path}
- {"\n"}churn: {Math.round(p.churn_percentile)}th, bus factor: {p.bus_factor}
+ {"\n"}churn: {Math.round(p._x)}th, bus factor: {p.bus_factor}
{", "}commits 90d: {p.commit_count_90d}
+ {p.primary_owner ? `\nowner: ${p.primary_owner}` : ""}
</title>
</circle>
</g>
);
})}
+
+ {/* The danger-zone files are listed in the legend below — drawing
+ them inline collides whenever multiple points cluster in the
+ same quadrant. */}
</svg>
+ {dangerPoints.length > 0 && (
+ <ul className="space-y-0.5 text-[11px]">
+ {dangerPoints.map((p) => (
+ <li
+ key={`legend-${p.file_path}`}
+ className="flex items-center justify-between gap-2"
+ >
+ <button
+ type="button"
+ onClick={onSelect ? () => onSelect(p.file_path) : undefined}
+ disabled={!onSelect}
+ className={cn(
+ "truncate text-left font-mono text-[var(--color-text-secondary)]",
+ onSelect && "hover:text-[var(--color-accent-primary)] cursor-pointer",
+ )}
+ title={p.file_path}
+ >
+ {p.file_path}
+ </button>
+ <span className="shrink-0 tabular-nums text-[var(--color-text-tertiary)]">
+ bus {p.bus_factor} · churn {Math.round(p._x)}th
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
</div>
);
}
diff --git a/packages/ui/src/git/co-change-list.tsx b/packages/ui/src/git/co-change-list.tsx
index 9a0402492..c9bc630ca 100644
--- a/packages/ui/src/git/co-change-list.tsx
+++ b/packages/ui/src/git/co-change-list.tsx
@@ -1,17 +1,27 @@
+import { useState } from "react";
import { truncatePath } from "../lib/format";
interface CoChangeListProps {
partners: Array<{ file_path: string; co_change_count: number }>;
+ /**
+ * Number of rows rendered when collapsed. The control toggles to the
+ * full list — partners are already trimmed server-side by ``min_count``
+ * so the full set is bounded.
+ */
+ previewCount?: number;
}
-export function CoChangeList({ partners }: CoChangeListProps) {
+export function CoChangeList({ partners, previewCount = 5 }: CoChangeListProps) {
+ const [expanded, setExpanded] = useState(false);
if (partners.length === 0) return null;
const maxCount = Math.max(...partners.map((p) => p.co_change_count));
+ const visible = expanded ? partners : partners.slice(0, previewCount);
+ const hidden = partners.length - visible.length;
return (
<div className="space-y-1.5">
- {partners.slice(0, 5).map((p) => (
+ {visible.map((p) => (
<div key={p.file_path} className="space-y-0.5">
<div className="flex items-center justify-between text-xs">
<span className="font-mono text-[var(--color-text-secondary)] truncate flex-1 min-w-0" title={p.file_path}>
@@ -31,6 +41,15 @@ export function CoChangeList({ partners }: CoChangeListProps) {
</div>
</div>
))}
+ {(hidden > 0 || expanded) && (
+ <button
+ type="button"
+ onClick={() => setExpanded((v) => !v)}
+ className="text-[10px] text-[var(--color-accent-primary)] hover:underline"
+ >
+ {expanded ? "Show fewer" : `Show ${hidden} more`}
+ </button>
+ )}
</div>
);
}
diff --git a/packages/ui/src/git/hotspot-table.tsx b/packages/ui/src/git/hotspot-table.tsx
index 002fd0b95..92dcc87e3 100644
--- a/packages/ui/src/git/hotspot-table.tsx
+++ b/packages/ui/src/git/hotspot-table.tsx
@@ -5,6 +5,7 @@ import { TrendingUp, TrendingDown, Search, Flame, ArrowUpDown, ArrowUp, ArrowDow
import { Badge } from "../ui/badge";
import { Input } from "../ui/input";
import { EmptyState } from "../shared/empty-state";
+import { ResultsFooter } from "../shared/results-footer";
import { RowActions } from "../shared/row-actions";
import { ChurnBar } from "./churn-bar";
import { formatLOC } from "../lib/format";
@@ -22,6 +23,16 @@ interface HotspotTableProps {
* clickable independently — they stop propagation.
*/
onSelect?: (hotspot: Hotspot) => void;
+ /**
+ * Pagination signals. When `total` is provided, the table renders a
+ * "Showing N of M / Load more" footer so the user can see whether the
+ * data was truncated. `onLoadMore` is wired to the parent's fetch — the
+ * table itself stays presentational.
+ */
+ total?: number;
+ hasMore?: boolean;
+ loadingMore?: boolean;
+ onLoadMore?: () => void;
}
type Filter = "all" | "hot" | "risk" | "accelerating";
@@ -40,7 +51,16 @@ function ariaSortFor(column: SortKey, sortKey: SortKey, sortDir: SortDir): "none
return sortDir === "asc" ? "ascending" : "descending";
}
-export function HotspotTable({ hotspots, repoId, linkPrefix, onSelect }: HotspotTableProps) {
+export function HotspotTable({
+ hotspots,
+ repoId,
+ linkPrefix,
+ onSelect,
+ total,
+ hasMore,
+ loadingMore,
+ onLoadMore,
+}: HotspotTableProps) {
const prefix = linkPrefix ?? (repoId ? `/repos/${repoId}` : undefined);
const [search, setSearch] = useState("");
const [filter, setFilter] = useState<Filter>("all");
@@ -286,6 +306,16 @@ export function HotspotTable({ hotspots, repoId, linkPrefix, onSelect }: Hotspot
})}
</tbody>
</table>
+ {total != null && (
+ <ResultsFooter
+ shown={filtered.length}
+ total={total}
+ hasMore={!!hasMore}
+ loading={loadingMore}
+ onLoadMore={onLoadMore}
+ noun="hotspots"
+ />
+ )}
</div>
)}
</div>
diff --git a/packages/ui/src/git/risk-distribution-chart.tsx b/packages/ui/src/git/risk-distribution-chart.tsx
index e0b30da07..eabcdd5ee 100644
--- a/packages/ui/src/git/risk-distribution-chart.tsx
+++ b/packages/ui/src/git/risk-distribution-chart.tsx
@@ -15,6 +15,12 @@ import type { Hotspot } from "@repowise-dev/types/git";
interface RiskDistributionChartProps {
hotspots: Hotspot[];
+ /**
+ * Maximum bars to render before the chart becomes illegible. The count
+ * is surfaced to the user via the caller — this prop only controls the
+ * visual cap, not what data the parent fetched.
+ */
+ maxBars?: number;
}
function computeRiskScore(h: Hotspot): number {
@@ -31,7 +37,7 @@ function riskColor(score: number): string {
return "#22c55e";
}
-export function RiskDistributionChart({ hotspots }: RiskDistributionChartProps) {
+export function RiskDistributionChart({ hotspots, maxBars = 30 }: RiskDistributionChartProps) {
const data = useMemo(() => {
return hotspots
.map((h) => ({
@@ -42,15 +48,21 @@ export function RiskDistributionChart({ hotspots }: RiskDistributionChartProps)
busFactor: h.bus_factor,
}))
.sort((a, b) => b.risk - a.risk)
- .slice(0, 30);
- }, [hotspots]);
+ .slice(0, maxBars);
+ }, [hotspots, maxBars]);
if (data.length === 0) return null;
const avgRisk = Math.round(data.reduce((s, d) => s + d.risk, 0) / data.length);
+ const truncated = hotspots.length > data.length;
return (
<div className="w-full">
+ {truncated && (
+ <p className="text-[10px] text-[var(--color-text-tertiary)] mb-1 text-right tabular-nums">
+ Showing top {data.length} of {hotspots.length.toLocaleString()} by risk score
+ </p>
+ )}
<ResponsiveContainer width="100%" height={Math.max(200, data.length * 22 + 40)}>
<BarChart
data={data}
diff --git a/packages/ui/src/shared/index.ts b/packages/ui/src/shared/index.ts
index 2e7336df9..a7b3dedeb 100644
--- a/packages/ui/src/shared/index.ts
+++ b/packages/ui/src/shared/index.ts
@@ -2,5 +2,6 @@ export * from "./api-error.js";
export * from "./breadcrumb.js";
export * from "./empty-state.js";
export * from "./stat-card.js";
+export * from "./results-footer.js";
export { RowActions, type RowAction } from "./row-actions";
export * from "./entity";
diff --git a/packages/ui/src/shared/results-footer.tsx b/packages/ui/src/shared/results-footer.tsx
new file mode 100644
index 000000000..7a732eeb9
--- /dev/null
+++ b/packages/ui/src/shared/results-footer.tsx
@@ -0,0 +1,60 @@
+import * as React from "react";
+import { Button } from "../ui/button";
+import { cn } from "../lib/cn";
+
+interface ResultsFooterProps {
+ /** Number of items currently rendered in the parent component. */
+ shown: number;
+ /** Authoritative total reported by the server. */
+ total: number;
+ /** True when more pages are available. */
+ hasMore: boolean;
+ /** Disables the load-more button while the next page is in flight. */
+ loading?: boolean;
+ /**
+ * Called when the user requests more rows. The parent decides the page
+ * size; this primitive only owns the affordance and the count surface.
+ */
+ onLoadMore?: () => void;
+ /** Optional label tweak — defaults to "results". */
+ noun?: string;
+ className?: string;
+}
+
+/**
+ * Footer for any list that pages through a {@link Paginated} envelope. The
+ * goal is to never let the UI silently hide data: the count makes the
+ * "shown N of M" contract explicit even when the list happens to fit on
+ * one page.
+ */
+export function ResultsFooter({
+ shown,
+ total,
+ hasMore,
+ loading = false,
+ onLoadMore,
+ noun = "results",
+ className,
+}: ResultsFooterProps) {
+ if (total === 0) return null;
+ return (
+ <div
+ className={cn(
+ "flex items-center justify-between gap-3 border-t border-[var(--color-border)] px-3 py-2 text-xs text-[var(--color-text-secondary)]",
+ className,
+ )}
+ >
+ <span className="tabular-nums">
+ Showing <span className="font-medium text-[var(--color-text-primary)]">{shown.toLocaleString()}</span>
+ {" "}of{" "}
+ <span className="font-medium text-[var(--color-text-primary)]">{total.toLocaleString()}</span>
+ {" "}{noun}
+ </span>
+ {hasMore && onLoadMore && (
+ <Button size="sm" variant="outline" onClick={onLoadMore} disabled={loading}>
+ {loading ? "Loading…" : "Load more"}
+ </Button>
+ )}
+ </div>
+ );
+}
diff --git a/packages/ui/src/symbols/hot-symbols-board.tsx b/packages/ui/src/symbols/hot-symbols-board.tsx
index 3c8b540cf..276d9ba17 100644
--- a/packages/ui/src/symbols/hot-symbols-board.tsx
+++ b/packages/ui/src/symbols/hot-symbols-board.tsx
@@ -1,6 +1,7 @@
"use client";
-import { Flame, ArrowRight } from "lucide-react";
+import { useState } from "react";
+import { ArrowRight, ChevronDown, ChevronRight, Flame } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { Badge } from "../ui/badge";
import { cn } from "../lib/cn";
@@ -19,9 +20,23 @@ export interface HotSymbolsBoardProps {
limit?: number;
onSelect?: (sym: CodeSymbol) => void;
className?: string;
+ /**
+ * When true (default) the board starts collapsed — header only, content
+ * hidden behind an expand toggle. The table below it is the primary
+ * surface; this board is a secondary preview, so keeping it folded by
+ * default avoids stealing top-of-page real estate.
+ */
+ defaultCollapsed?: boolean;
}
-export function HotSymbolsBoard({ items, limit = 8, onSelect, className }: HotSymbolsBoardProps) {
+export function HotSymbolsBoard({
+ items,
+ limit = 8,
+ onSelect,
+ className,
+ defaultCollapsed = true,
+}: HotSymbolsBoardProps) {
+ const [open, setOpen] = useState(!defaultCollapsed);
const top = items.slice(0, limit);
if (top.length === 0) {
return null;
@@ -31,14 +46,30 @@ export function HotSymbolsBoard({ items, limit = 8, onSelect, className }: HotSy
return (
<Card className={className}>
<CardHeader className="pb-2">
- <CardTitle className="text-sm flex items-center gap-2">
- <Flame className="h-4 w-4 text-orange-500" />
- Hot symbols
- <span className="text-[10px] font-normal text-[var(--color-text-tertiary)] uppercase tracking-wider">
- churn × centrality × complexity
- </span>
- </CardTitle>
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ className="w-full text-left -my-1 -mx-1 rounded px-1 py-1 hover:bg-[var(--color-bg-elevated)] transition-colors"
+ >
+ <CardTitle className="text-sm flex items-center gap-2">
+ {open ? (
+ <ChevronDown className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ ) : (
+ <ChevronRight className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ )}
+ <Flame className="h-4 w-4 text-orange-500" />
+ Hot symbols
+ <span className="text-[10px] font-normal text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ churn × centrality × complexity
+ </span>
+ <span className="ml-auto text-[10px] font-normal text-[var(--color-text-tertiary)] tabular-nums">
+ {top.length}
+ </span>
+ </CardTitle>
+ </button>
</CardHeader>
+ {open && (
<CardContent className="pt-0">
<div className="grid grid-cols-1 md:grid-cols-2 gap-2">
{top.map(({ symbol, score }) => {
@@ -84,6 +115,7 @@ export function HotSymbolsBoard({ items, limit = 8, onSelect, className }: HotSy
})}
</div>
</CardContent>
+ )}
</Card>
);
}
diff --git a/packages/ui/src/symbols/index.ts b/packages/ui/src/symbols/index.ts
index 0f2d52494..77ea3673c 100644
--- a/packages/ui/src/symbols/index.ts
+++ b/packages/ui/src/symbols/index.ts
@@ -1,4 +1,5 @@
export * from "./symbol-table.js";
export * from "./symbol-drawer.js";
export * from "./symbol-graph-panel.js";
+export * from "./symbol-git-panel.js";
export * from "./hot-symbols-board.js";
diff --git a/packages/ui/src/symbols/symbol-drawer.tsx b/packages/ui/src/symbols/symbol-drawer.tsx
index 920da7eac..059361fb8 100644
--- a/packages/ui/src/symbols/symbol-drawer.tsx
+++ b/packages/ui/src/symbols/symbol-drawer.tsx
@@ -21,9 +21,15 @@ interface SymbolDrawerProps {
* `<SymbolGraphPanelWrapper>` here; pass `null` to hide the column.
*/
graphPanel?: ReactNode;
+ /**
+ * Additional right-column slot for file-level git context (owner, bus
+ * factor, co-changes, overlapping dead code). Rendered below the graph
+ * panel when both are present.
+ */
+ gitPanel?: ReactNode;
}
-export function SymbolDrawer({ symbol, onClose, graphPanel }: SymbolDrawerProps) {
+export function SymbolDrawer({ symbol, onClose, graphPanel, gitPanel }: SymbolDrawerProps) {
return (
<Dialog open={symbol !== null} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-[95vw] w-[1000px] max-h-[88vh] overflow-hidden p-0">
@@ -79,9 +85,13 @@ export function SymbolDrawer({ symbol, onClose, graphPanel }: SymbolDrawerProps)
</div>
</ScrollArea>
- {graphPanel && (
+ {(graphPanel || gitPanel) && (
<div className="hidden md:flex flex-col border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-[340px] shrink-0 overflow-hidden">
- {graphPanel}
+ <ScrollArea className="flex-1 min-h-0">
+ {graphPanel}
+ {graphPanel && gitPanel && <Separator />}
+ {gitPanel}
+ </ScrollArea>
</div>
)}
</div>
diff --git a/packages/ui/src/symbols/symbol-git-panel.tsx b/packages/ui/src/symbols/symbol-git-panel.tsx
new file mode 100644
index 000000000..11a9889d8
--- /dev/null
+++ b/packages/ui/src/symbols/symbol-git-panel.tsx
@@ -0,0 +1,207 @@
+"use client";
+
+import {
+ AlertTriangle,
+ Flame,
+ GitBranch,
+ Radius,
+ Skull,
+ Users,
+} from "lucide-react";
+import { Button } from "../ui/button";
+import { truncatePath } from "../lib/format";
+import { cn } from "../lib/cn";
+
+export interface SymbolGitPanelOwner {
+ name: string;
+ email?: string;
+ commit_count?: number;
+ pct?: number;
+}
+
+export interface SymbolGitPanelCoChange {
+ file_path: string;
+ co_change_count: number;
+}
+
+export interface SymbolGitPanelDeadFinding {
+ id: string;
+ kind: string;
+ reason: string;
+ confidence: number;
+ lines: number;
+ safe_to_delete: boolean;
+}
+
+export interface SymbolGitPanelProps {
+ filePath: string;
+ loading?: boolean;
+ /** Git metadata bundle — null when the file has no git history. */
+ git?: {
+ primary_owner_name: string | null;
+ primary_owner_commit_pct: number | null;
+ recent_owner_name?: string | null;
+ recent_owner_commit_pct?: number | null;
+ bus_factor: number;
+ contributor_count: number;
+ commit_count_90d: number;
+ is_hotspot: boolean;
+ churn_percentile: number;
+ top_authors?: SymbolGitPanelOwner[];
+ } | null;
+ coChanges?: SymbolGitPanelCoChange[];
+ /** Dead-code findings whose line range overlaps the symbol. */
+ deadCode?: SymbolGitPanelDeadFinding[];
+ /** Optional callback for the "View blast radius" CTA. */
+ onOpenBlastRadius?: () => void;
+}
+
+/**
+ * Side-panel that overlays file-level git intelligence onto a symbol.
+ * Lives in shared `packages/ui/` so the hosted frontend can re-use it
+ * without re-implementing the layout. All data fetching stays in the
+ * web-side wrapper; this component is purely presentational.
+ */
+export function SymbolGitPanel({
+ filePath,
+ loading,
+ git,
+ coChanges,
+ deadCode,
+ onOpenBlastRadius,
+}: SymbolGitPanelProps) {
+ const hasDead = (deadCode?.length ?? 0) > 0;
+ const visibleCoChanges = (coChanges ?? []).slice(0, 6);
+ const moreCoChanges = (coChanges?.length ?? 0) - visibleCoChanges.length;
+
+ return (
+ <div className="px-4 py-3 space-y-4 text-xs">
+ <p className="text-[10px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ File context
+ </p>
+
+ {loading && (
+ <div className="space-y-2">
+ <div className="h-3 w-24 rounded bg-[var(--color-bg-elevated)] animate-pulse" />
+ <div className="h-3 w-32 rounded bg-[var(--color-bg-elevated)] animate-pulse" />
+ </div>
+ )}
+
+ {!loading && !git && (
+ <p className="text-[var(--color-text-tertiary)]">No git history for this file.</p>
+ )}
+
+ {git && (
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <Users className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ <span className="text-[var(--color-text-secondary)]">
+ {git.primary_owner_name ?? "—"}
+ {git.primary_owner_commit_pct != null && (
+ <span className="ml-1 text-[var(--color-text-tertiary)] tabular-nums">
+ ({Math.round(git.primary_owner_commit_pct * 100)}%)
+ </span>
+ )}
+ </span>
+ </div>
+ {git.recent_owner_name && git.recent_owner_name !== git.primary_owner_name && (
+ <p className="text-[var(--color-text-tertiary)] pl-5">
+ Recent owner (90d): {git.recent_owner_name}
+ </p>
+ )}
+ <div className="flex flex-wrap items-center gap-2 text-[var(--color-text-tertiary)]">
+ <span
+ className={cn(
+ "inline-flex items-center rounded px-1.5 py-0.5 tabular-nums",
+ git.bus_factor <= 1
+ ? "bg-red-500/15 text-red-400"
+ : git.bus_factor === 2
+ ? "bg-yellow-500/15 text-yellow-400"
+ : "bg-green-500/15 text-green-400",
+ )}
+ title="Bus factor"
+ >
+ bus {git.bus_factor}
+ </span>
+ <span>{git.contributor_count} contributors</span>
+ <span>{git.commit_count_90d} commits / 90d</span>
+ {git.is_hotspot && (
+ <span className="inline-flex items-center gap-0.5 rounded bg-red-500/15 px-1.5 py-0.5 text-red-400">
+ <Flame className="h-3 w-3" />
+ hotspot
+ </span>
+ )}
+ </div>
+ </div>
+ )}
+
+ {visibleCoChanges.length > 0 && (
+ <div className="space-y-1.5">
+ <p className="text-[10px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider flex items-center gap-1">
+ <GitBranch className="h-3 w-3" />
+ Co-changes
+ </p>
+ <ul className="space-y-1">
+ {visibleCoChanges.map((p) => (
+ <li
+ key={p.file_path}
+ className="flex items-center justify-between gap-2 font-mono text-[11px]"
+ >
+ <span className="truncate text-[var(--color-text-secondary)]" title={p.file_path}>
+ {truncatePath(p.file_path, 36)}
+ </span>
+ <span className="tabular-nums text-[var(--color-text-tertiary)]">
+ {p.co_change_count}&times;
+ </span>
+ </li>
+ ))}
+ </ul>
+ {moreCoChanges > 0 && (
+ <p className="text-[10px] text-[var(--color-text-tertiary)]">
+ +{moreCoChanges} more
+ </p>
+ )}
+ </div>
+ )}
+
+ {hasDead && (
+ <div className="space-y-1.5">
+ <p className="text-[10px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider flex items-center gap-1">
+ <Skull className="h-3 w-3" />
+ Dead code in scope
+ </p>
+ <ul className="space-y-1">
+ {deadCode!.map((f) => (
+ <li key={f.id} className="flex items-start gap-2 text-[11px]">
+ <AlertTriangle
+ className={cn(
+ "h-3 w-3 mt-0.5 shrink-0",
+ f.safe_to_delete ? "text-red-400" : "text-yellow-400",
+ )}
+ />
+ <span className="text-[var(--color-text-secondary)]">
+ <span className="font-medium">{f.kind}</span>{" "}
+ <span className="text-[var(--color-text-tertiary)]">
+ — {f.reason} ({f.lines} lines)
+ </span>
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ {onOpenBlastRadius && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="w-full"
+ onClick={onOpenBlastRadius}
+ >
+ <Radius className="h-3.5 w-3.5 mr-1.5" />
+ View blast radius for {truncatePath(filePath, 24)}
+ </Button>
+ )}
+ </div>
+ );
+}
diff --git a/packages/ui/src/symbols/symbol-table.tsx b/packages/ui/src/symbols/symbol-table.tsx
index 61ccd7d4c..498709176 100644
--- a/packages/ui/src/symbols/symbol-table.tsx
+++ b/packages/ui/src/symbols/symbol-table.tsx
@@ -1,59 +1,72 @@
"use client";
-import { useState, useCallback, useMemo, type ReactNode } from "react";
-import { ChevronUp, ChevronDown, ChevronsUpDown, TrendingUp, GitBranch, BookOpen } from "lucide-react";
+import { type ReactNode } from "react";
+import {
+ BookOpen,
+ Flame,
+ GitBranch,
+ Globe2,
+ Lock,
+ Rocket,
+ Sparkles,
+ TrendingUp,
+} from "lucide-react";
import { Input } from "../ui/input";
-import { Button } from "../ui/button";
import { Badge } from "../ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
import { Skeleton } from "../ui/skeleton";
import { EmptyState } from "../shared/empty-state";
+import { ResultsFooter } from "../shared/results-footer";
import { RowActions } from "../shared/row-actions";
import { truncatePath } from "../lib/format";
import { cn } from "../lib/cn";
import type { CodeSymbol } from "@repowise-dev/types/symbols";
-export type SortCol = "importance" | "name" | "kind" | "language" | "complexity_estimate" | "start_line";
-export type SortDir = "asc" | "desc";
-
const KINDS = ["function", "class", "method", "interface", "variable", "module"];
const LANGUAGES = ["python", "typescript", "javascript", "go", "rust", "java", "cpp", "c"];
+const VISIBILITIES = ["public", "protected", "private"];
+
+export type SymbolSortKey = "importance" | "name" | "complexity" | "kind";
+
+/**
+ * The full filter set the server understands. Kept as a value object so
+ * the wrapper owns a single piece of state and there's no chance of the
+ * fetch key drifting from the rendered controls.
+ */
+export interface SymbolFilters {
+ q: string;
+ kind: string;
+ language: string;
+ visibility: string;
+ inHotFiles: boolean;
+ inEntryPoints: boolean;
+ sort: SymbolSortKey;
+}
export interface SymbolTableProps {
- /** Loaded symbols (already paginated and filtered server-side). */
items: CodeSymbol[];
- /** Map of symbol.id → normalized importance score (0–1). */
- importanceScores: Map<string, number>;
isLoading: boolean;
isValidating: boolean;
hasMore: boolean;
- /** Server-driven filters — these affect the fetch key, so they live in the wrapper. */
- q: string;
- onQChange: (v: string) => void;
- kind: string;
- onKindChange: (v: string) => void;
- language: string;
- onLanguageChange: (v: string) => void;
+ /** Authoritative count from the server's paginated envelope. */
+ total: number;
+ filters: SymbolFilters;
+ onFiltersChange: (next: SymbolFilters) => void;
onLoadMore: () => void;
onSelect: (sym: CodeSymbol) => void;
repoId?: string;
linkPrefix?: string;
- /** Drawer slot for the selected row. Wrapper passes a `<SymbolDrawer>` mounted with its own data. */
drawer?: ReactNode;
}
-function SortIcon({ col, sortCol, sortDir }: { col: SortCol; sortCol: SortCol; sortDir: SortDir }) {
- if (col !== sortCol) return <ChevronsUpDown className="h-3 w-3 opacity-40" />;
- return sortDir === "asc" ? (
- <ChevronUp className="h-3 w-3" />
- ) : (
- <ChevronDown className="h-3 w-3" />
- );
-}
-
-function ImportanceBar({ score }: { score: number }) {
- const pct = Math.min(100, Math.round(score * 100));
- const color = pct >= 70 ? "bg-[var(--color-accent-primary)]" : pct >= 40 ? "bg-yellow-500" : "bg-[var(--color-text-tertiary)]";
+function ImportanceBar({ score }: { score: number | null | undefined }) {
+ const pct = Math.min(100, Math.max(0, Math.round((score ?? 0) * 100)));
+ const color =
+ pct >= 70
+ ? "bg-[var(--color-accent-primary)]"
+ : pct >= 40
+ ? "bg-yellow-500"
+ : "bg-[var(--color-text-tertiary)]";
return (
<div className="flex items-center gap-1.5">
<div className="h-1.5 w-16 rounded-full bg-[var(--color-bg-inset)] overflow-hidden">
@@ -64,18 +77,102 @@ function ImportanceBar({ score }: { score: number }) {
);
}
+/**
+ * Compact signal chips that summarise the row's most important non-name
+ * properties at a glance. Kept terse so the table stays scannable.
+ */
+function SignalChips({ sym }: { sym: CodeSymbol }) {
+ const isPublic = sym.visibility === "public";
+ const isPrivate = sym.visibility === "private";
+ const complex = (sym.complexity_estimate ?? 0) >= 15;
+ return (
+ <span className="inline-flex flex-wrap items-center gap-1">
+ <span
+ className={cn(
+ "inline-flex items-center gap-0.5 rounded px-1 py-0.5 text-[10px] font-medium",
+ isPublic
+ ? "bg-emerald-500/15 text-emerald-400"
+ : isPrivate
+ ? "bg-slate-500/15 text-slate-400"
+ : "bg-amber-500/15 text-amber-400",
+ )}
+ title={`Visibility: ${sym.visibility}`}
+ >
+ {isPublic ? <Globe2 className="h-2.5 w-2.5" /> : isPrivate ? <Lock className="h-2.5 w-2.5" /> : null}
+ {sym.visibility}
+ </span>
+ {sym.is_entry_point && (
+ <span
+ className="inline-flex items-center gap-0.5 rounded bg-blue-500/15 px-1 py-0.5 text-[10px] font-medium text-blue-400"
+ title="Lives in an entry-point file"
+ >
+ <Rocket className="h-2.5 w-2.5" />
+ entry
+ </span>
+ )}
+ {sym.file_is_hotspot && (
+ <span
+ className="inline-flex items-center gap-0.5 rounded bg-red-500/15 px-1 py-0.5 text-[10px] font-medium text-red-400"
+ title="File is a churn hotspot"
+ >
+ <Flame className="h-2.5 w-2.5" />
+ hot
+ </span>
+ )}
+ {complex && (
+ <span
+ className="inline-flex items-center gap-0.5 rounded bg-yellow-500/15 px-1 py-0.5 text-[10px] font-medium text-yellow-400"
+ title="High complexity"
+ >
+ <Sparkles className="h-2.5 w-2.5" />
+ complex
+ </span>
+ )}
+ </span>
+ );
+}
+
+/**
+ * Toggle pill — used for boolean filter facets ("in hot files",
+ * "entry points only"). Lifted into a tiny helper so the toolbar reads
+ * declaratively.
+ */
+function FacetToggle({
+ active,
+ onClick,
+ label,
+ icon,
+}: {
+ active: boolean;
+ onClick: () => void;
+ label: string;
+ icon: ReactNode;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={cn(
+ "inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs transition-colors",
+ active
+ ? "border-[var(--color-accent-primary)] bg-[var(--color-accent-primary)]/15 text-[var(--color-accent-primary)]"
+ : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]",
+ )}
+ >
+ {icon}
+ {label}
+ </button>
+ );
+}
+
export function SymbolTable({
items,
- importanceScores,
isLoading,
isValidating,
hasMore,
- q,
- onQChange,
- kind,
- onKindChange,
- language,
- onLanguageChange,
+ total,
+ filters,
+ onFiltersChange,
onLoadMore,
onSelect,
repoId,
@@ -83,54 +180,21 @@ export function SymbolTable({
drawer,
}: SymbolTableProps) {
const prefix = linkPrefix ?? (repoId ? `/repos/${repoId}` : undefined);
- const [sortCol, setSortCol] = useState<SortCol>("importance");
- const [sortDir, setSortDir] = useState<SortDir>("desc");
- const handleSort = useCallback(
- (col: SortCol) => {
- if (col === sortCol) {
- setSortDir((d) => (d === "asc" ? "desc" : "asc"));
- } else {
- setSortCol(col);
- setSortDir(col === "importance" ? "desc" : "asc");
- }
- },
- [sortCol],
- );
-
- const sorted = useMemo(() => {
- return [...items].sort((a, b) => {
- if (sortCol === "importance") {
- const ia = importanceScores.get(a.id) ?? 0;
- const ib = importanceScores.get(b.id) ?? 0;
- return sortDir === "asc" ? ia - ib : ib - ia;
- }
- const va = (a as unknown as Record<string, unknown>)[sortCol] ?? "";
- const vb = (b as unknown as Record<string, unknown>)[sortCol] ?? "";
- const cmp = String(va).localeCompare(String(vb), undefined, { numeric: true });
- return sortDir === "asc" ? cmp : -cmp;
- });
- }, [items, sortCol, sortDir, importanceScores]);
-
- const columns: Array<{ col: SortCol; label: string; hideOnMobile?: boolean }> = [
- { col: "importance", label: "Importance" },
- { col: "name", label: "Name" },
- { col: "kind", label: "Kind" },
- { col: "language", label: "Language", hideOnMobile: true },
- { col: "start_line", label: "File", hideOnMobile: true },
- { col: "complexity_estimate", label: "Complexity", hideOnMobile: true },
- ];
+ function patch(p: Partial<SymbolFilters>) {
+ onFiltersChange({ ...filters, ...p });
+ }
return (
<div className="space-y-4">
- <div className="flex flex-wrap gap-2">
+ <div className="flex flex-wrap items-center gap-2">
<Input
placeholder="Search symbols…"
- value={q}
- onChange={(e) => onQChange(e.target.value)}
+ value={filters.q}
+ onChange={(e) => patch({ q: e.target.value })}
className="max-w-xs"
/>
- <Select value={kind} onValueChange={onKindChange}>
+ <Select value={filters.kind} onValueChange={(v) => patch({ kind: v })}>
<SelectTrigger className="w-36">
<SelectValue placeholder="Kind" />
</SelectTrigger>
@@ -143,7 +207,7 @@ export function SymbolTable({
))}
</SelectContent>
</Select>
- <Select value={language} onValueChange={onLanguageChange}>
+ <Select value={filters.language} onValueChange={(v) => patch({ language: v })}>
<SelectTrigger className="w-36">
<SelectValue placeholder="Language" />
</SelectTrigger>
@@ -156,11 +220,42 @@ export function SymbolTable({
))}
</SelectContent>
</Select>
- {items.length > 0 && (
- <span className="self-center text-xs text-[var(--color-text-tertiary)]">
- {items.length} symbols
- </span>
- )}
+ <Select value={filters.visibility} onValueChange={(v) => patch({ visibility: v })}>
+ <SelectTrigger className="w-36">
+ <SelectValue placeholder="Visibility" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">All visibilities</SelectItem>
+ {VISIBILITIES.map((v) => (
+ <SelectItem key={v} value={v}>
+ {v}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FacetToggle
+ active={filters.inHotFiles}
+ onClick={() => patch({ inHotFiles: !filters.inHotFiles })}
+ label="In hot files"
+ icon={<Flame className="h-3 w-3" />}
+ />
+ <FacetToggle
+ active={filters.inEntryPoints}
+ onClick={() => patch({ inEntryPoints: !filters.inEntryPoints })}
+ label="Entry points"
+ icon={<Rocket className="h-3 w-3" />}
+ />
+ <Select value={filters.sort} onValueChange={(v) => patch({ sort: v as SymbolSortKey })}>
+ <SelectTrigger className="w-40">
+ <SelectValue placeholder="Sort" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="importance">Importance</SelectItem>
+ <SelectItem value="name">Name (A→Z)</SelectItem>
+ <SelectItem value="complexity">Complexity</SelectItem>
+ <SelectItem value="kind">Kind</SelectItem>
+ </SelectContent>
+ </Select>
</div>
{isLoading && items.length === 0 ? (
@@ -169,42 +264,40 @@ export function SymbolTable({
<Skeleton key={i} className="h-10 w-full" />
))}
</div>
- ) : sorted.length === 0 ? (
+ ) : items.length === 0 ? (
<EmptyState title="No symbols found" description="Try adjusting your filters." />
) : (
- <>
- <div className="rounded-lg border border-[var(--color-border-default)] overflow-x-auto">
+ <div className="rounded-lg border border-[var(--color-border-default)] overflow-hidden">
+ <div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="sticky top-0 z-10">
<tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">
- {columns.map(({ col, label, hideOnMobile }) => (
- <th
- key={col}
- scope="col"
- aria-sort={
- sortCol === col
- ? sortDir === "asc"
- ? "ascending"
- : "descending"
- : "none"
- }
- className={cn(
- "px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider cursor-pointer select-none hover:text-[var(--color-text-primary)] transition-colors bg-[var(--color-bg-elevated)]",
- hideOnMobile && "hidden sm:table-cell",
- )}
- onClick={() => handleSort(col)}
- >
- <span className="inline-flex items-center gap-1">
- {col === "importance" && <TrendingUp className="h-3 w-3" />}
- {label}
- <SortIcon col={col} sortCol={sortCol} sortDir={sortDir} />
- </span>
- </th>
- ))}
+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-32">
+ <span className="inline-flex items-center gap-1">
+ <TrendingUp className="h-3 w-3" />
+ Importance
+ </span>
+ </th>
+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ Name
+ </th>
+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ Signals
+ </th>
+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider hidden sm:table-cell">
+ Kind
+ </th>
+ <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider hidden sm:table-cell">
+ File
+ </th>
+ <th className="px-4 py-2.5 text-right text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider hidden md:table-cell">
+ Complexity
+ </th>
+ {prefix && <th className="px-2 py-2.5 w-12" />}
</tr>
</thead>
<tbody>
- {sorted.map((sym) => (
+ {items.map((sym) => (
<tr
key={sym.id}
className="border-b border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)] transition-colors last:border-0 cursor-pointer focus:outline-none focus:bg-[var(--color-bg-elevated)]"
@@ -220,26 +313,33 @@ export function SymbolTable({
}}
>
<td className="px-4 py-2.5">
- <ImportanceBar score={importanceScores.get(sym.id) ?? 0} />
+ <ImportanceBar score={sym.importance_score} />
</td>
<td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-primary)] min-w-[200px] max-w-[420px]">
- <span className="truncate block" title={sym.qualified_name || sym.name}>{sym.name}</span>
+ <span className="truncate block" title={sym.qualified_name || sym.name}>
+ {sym.name}
+ </span>
{sym.parent_name && (
- <span className="block truncate text-[var(--color-text-tertiary)]" title={sym.parent_name}>.{sym.parent_name}</span>
+ <span
+ className="block truncate text-[var(--color-text-tertiary)]"
+ title={sym.parent_name}
+ >
+ .{sym.parent_name}
+ </span>
)}
</td>
<td className="px-4 py-2.5">
- <Badge variant={sym.kind === "class" ? "accent" : "default"}>{sym.kind}</Badge>
+ <SignalChips sym={sym} />
</td>
- <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)] hidden sm:table-cell">
- {sym.language}
+ <td className="px-4 py-2.5 hidden sm:table-cell">
+ <Badge variant={sym.kind === "class" ? "accent" : "default"}>{sym.kind}</Badge>
</td>
<td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-tertiary)] min-w-[200px] max-w-[420px] hidden sm:table-cell">
<span className="block truncate" title={`${sym.file_path}:${sym.start_line}`}>
{truncatePath(sym.file_path)}:{sym.start_line}
</span>
</td>
- <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)] tabular-nums hidden sm:table-cell text-right">
+ <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)] tabular-nums hidden md:table-cell text-right">
<span
className={cn(
sym.complexity_estimate > 15
@@ -256,8 +356,16 @@ export function SymbolTable({
<td className="px-2 py-2.5" onClick={(e) => e.stopPropagation()}>
<RowActions
actions={[
- { icon: GitBranch, label: "Graph", href: `${prefix}/graph?node=${encodeURIComponent(sym.file_path)}` },
- { icon: BookOpen, label: "Docs", href: `${prefix}/docs?file=${encodeURIComponent(sym.file_path)}` },
+ {
+ icon: GitBranch,
+ label: "Graph",
+ href: `${prefix}/graph?node=${encodeURIComponent(sym.file_path)}`,
+ },
+ {
+ icon: BookOpen,
+ label: "Docs",
+ href: `${prefix}/docs?file=${encodeURIComponent(sym.file_path)}`,
+ },
]}
/>
</td>
@@ -267,20 +375,15 @@ export function SymbolTable({
</tbody>
</table>
</div>
-
- {hasMore && (
- <div className="flex justify-center">
- <Button
- variant="outline"
- size="sm"
- onClick={onLoadMore}
- disabled={isValidating}
- >
- {isValidating ? "Loading…" : "Load more"}
- </Button>
- </div>
- )}
- </>
+ <ResultsFooter
+ shown={items.length}
+ total={total}
+ hasMore={hasMore}
+ loading={isValidating}
+ onLoadMore={onLoadMore}
+ noun="symbols"
+ />
+ </div>
)}
{drawer}
diff --git a/packages/web/src/components/risk/hotspots-tab.tsx b/packages/web/src/components/risk/hotspots-tab.tsx
index 134b7bdeb..380545bba 100644
--- a/packages/web/src/components/risk/hotspots-tab.tsx
+++ b/packages/web/src/components/risk/hotspots-tab.tsx
@@ -1,20 +1,21 @@
"use client";
+import { useState } from "react";
import useSWR from "swr";
import { useFileCardHost } from "@/components/shared/file-card-host";
-import type { HotspotResponse as HotspotRowType } from "@/lib/api/types";
+import type { HotspotResponse as HotspotRowType, Paginated } from "@/lib/api/types";
import type { FileCardData } from "@repowise-dev/ui/shared/file-card";
import { HotspotTable } from "@repowise-dev/ui/git/hotspot-table";
-import { ContributorBar } from "@repowise-dev/ui/git/contributor-bar";
import { ChurnHistogram } from "@repowise-dev/ui/git/churn-histogram";
import { CommitCategoryDonut } from "@repowise-dev/ui/git/commit-category-donut";
import { RiskDistributionChart } from "@repowise-dev/ui/git/risk-distribution-chart";
import { ChurnVsBusFactorScatter } from "@repowise-dev/ui/git/churn-vs-bus-factor-scatter";
import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import { getHotspots, getGitSummary } from "@/lib/api/git";
-import { formatNumber } from "@repowise-dev/ui/lib/format";
-import type { GitSummaryResponse, HotspotResponse } from "@/lib/api/types";
+import { getHotspotsPage } from "@/lib/api/git";
+import type { HotspotResponse } from "@/lib/api/types";
+
+const PAGE_SIZE = 100;
function hotspotToFileCard(h: HotspotRowType): FileCardData {
return {
@@ -34,18 +35,20 @@ function hotspotToFileCard(h: HotspotRowType): FileCardData {
export function HotspotsTab({ repoId }: { repoId: string }) {
const { showFile, dialog } = useFileCardHost(repoId);
- const { data: hotspots, isLoading: loadingHotspots, error: hotspotsError } = useSWR<HotspotResponse[]>(
- `risk-hotspots:${repoId}`,
- () => getHotspots(repoId, 100),
- { revalidateOnFocus: false },
- );
- const { data: summary } = useSWR<GitSummaryResponse>(
- `git-summary:${repoId}`,
- () => getGitSummary(repoId),
- { revalidateOnFocus: false },
+ const [pageLimit, setPageLimit] = useState(PAGE_SIZE);
+ const {
+ data: hotspotsPage,
+ isLoading: loadingHotspots,
+ isValidating: validatingHotspots,
+ error: hotspotsError,
+ } = useSWR<Paginated<HotspotResponse>>(
+ `risk-hotspots:${repoId}:${pageLimit}`,
+ () => getHotspotsPage(repoId, { limit: pageLimit }),
+ { revalidateOnFocus: false, keepPreviousData: true },
);
-
- const list = hotspots ?? [];
+ const list = hotspotsPage?.items ?? [];
+ const total = hotspotsPage?.total ?? list.length;
+ const hasMore = hotspotsPage?.has_more ?? false;
const aggregatedCategories: Record<string, number> = {};
for (const h of list) {
for (const [cat, count] of Object.entries(h.commit_categories || {})) {
@@ -118,43 +121,28 @@ export function HotspotsTab({ repoId }: { repoId: string }) {
</p>
</CardHeader>
<CardContent className="pt-0">
- <ChurnVsBusFactorScatter hotspots={list} />
+ <ChurnVsBusFactorScatter
+ hotspots={list}
+ onSelect={(path) => {
+ const hit = list.find((h) => h.file_path === path);
+ if (hit) showFile(hotspotToFileCard(hit));
+ }}
+ />
</CardContent>
</Card>
</div>
)}
- <div className="grid grid-cols-1 gap-6 xl:grid-cols-4">
- <div className="xl:col-span-3">
- <HotspotTable hotspots={list} repoId={repoId} onSelect={(h) => showFile(hotspotToFileCard(h))} />
- </div>
-
- {summary && summary.top_owners.length > 0 && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Top Owners</CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- <ContributorBar owners={summary.top_owners} />
- <div className="mt-3 space-y-1.5">
- {summary.top_owners.slice(0, 5).map((o, i) => (
- <div key={o.email || `owner-${i}`} className="flex items-center justify-between text-xs">
- <span
- className="text-[var(--color-text-secondary)] truncate"
- title={o.email ? `${o.name} <${o.email}>` : o.name}
- >
- {o.name}
- </span>
- <span className="text-[var(--color-text-tertiary)] tabular-nums ml-2">
- {formatNumber(o.file_count)} files ({Math.round(o.pct * 100)}%)
- </span>
- </div>
- ))}
- </div>
- </CardContent>
- </Card>
- )}
- </div>
+ {/* Top contributors lives on the Heatmap tab; not duplicated here. */}
+ <HotspotTable
+ hotspots={list}
+ repoId={repoId}
+ onSelect={(h) => showFile(hotspotToFileCard(h))}
+ total={total}
+ hasMore={hasMore}
+ loadingMore={validatingHotspots && !loadingHotspots}
+ onLoadMore={() => setPageLimit((n) => Math.min(n + PAGE_SIZE, 500))}
+ />
{dialog}
</div>
);
diff --git a/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx b/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx
index c20ab9be8..400d7cdc8 100644
--- a/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx
+++ b/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx
@@ -2,6 +2,7 @@
import { SymbolDrawer } from "@repowise-dev/ui/symbols/symbol-drawer";
import { SymbolGraphPanelWrapper } from "./symbol-graph-panel-wrapper";
+import { SymbolGitPanelWrapper } from "./symbol-git-panel-wrapper";
import type { SymbolResponse } from "@/lib/api/types";
interface Props {
@@ -16,6 +17,7 @@ export function SymbolDrawerWrapper({ symbol, repoId, onClose }: Props) {
symbol={symbol}
onClose={onClose}
graphPanel={symbol ? <SymbolGraphPanelWrapper repoId={repoId} symbol={symbol} /> : null}
+ gitPanel={symbol ? <SymbolGitPanelWrapper repoId={repoId} symbol={symbol} /> : null}
/>
);
}
diff --git a/packages/web/src/components/symbols/symbol-git-panel-wrapper.tsx b/packages/web/src/components/symbols/symbol-git-panel-wrapper.tsx
new file mode 100644
index 000000000..6ed449311
--- /dev/null
+++ b/packages/web/src/components/symbols/symbol-git-panel-wrapper.tsx
@@ -0,0 +1,98 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useMemo } from "react";
+import useSWR from "swr";
+import { SymbolGitPanel } from "@repowise-dev/ui/symbols/symbol-git-panel";
+import { getCoChanges, getGitMetadata } from "@/lib/api/git";
+import { listDeadCode } from "@/lib/api/dead-code";
+import type { SymbolResponse } from "@/lib/api/types";
+
+interface Props {
+ symbol: SymbolResponse;
+ repoId: string;
+}
+
+/**
+ * Data-coupled wrapper around {@link SymbolGitPanel}. Fetches per-file
+ * git metadata, co-changes, and any dead-code findings whose line range
+ * overlaps the symbol — composed from existing endpoints so this panel
+ * is purely additive (no ingestion changes required).
+ */
+export function SymbolGitPanelWrapper({ symbol, repoId }: Props) {
+ const router = useRouter();
+ const filePath = symbol.file_path;
+
+ const { data: git, isLoading: gitLoading } = useSWR(
+ `git-meta:${repoId}:${filePath}`,
+ () =>
+ getGitMetadata(repoId, filePath).catch((err) => {
+ // 404 is expected for files outside the indexed history (vendored,
+ // generated, etc.) — fall back to null so the panel hides itself.
+ if (err?.status === 404) return null;
+ throw err;
+ }),
+ { revalidateOnFocus: false },
+ );
+
+ const { data: coChangePayload } = useSWR(
+ git ? `co-changes:${repoId}:${filePath}` : null,
+ () => getCoChanges(repoId, filePath, 2),
+ { revalidateOnFocus: false },
+ );
+
+ const { data: deadFindings } = useSWR(
+ `dead-code:${repoId}`,
+ () => listDeadCode(repoId, { limit: 500 }),
+ { revalidateOnFocus: false },
+ );
+
+ const overlappingDead = useMemo(() => {
+ if (!deadFindings) return [];
+ return deadFindings.filter((f) => {
+ if (f.file_path !== filePath) return false;
+ // The dead-code finding doesn't carry line ranges in this shape, so
+ // we conservatively match by file + symbol name when available.
+ if (!f.symbol_name) return false;
+ return (
+ f.symbol_name === symbol.name ||
+ f.symbol_name === symbol.qualified_name
+ );
+ });
+ }, [deadFindings, filePath, symbol.name, symbol.qualified_name]);
+
+ return (
+ <SymbolGitPanel
+ filePath={filePath}
+ loading={gitLoading}
+ git={
+ git
+ ? {
+ primary_owner_name: git.primary_owner_name,
+ primary_owner_commit_pct: git.primary_owner_commit_pct,
+ recent_owner_name: git.recent_owner_name,
+ recent_owner_commit_pct: git.recent_owner_commit_pct,
+ bus_factor: git.bus_factor,
+ contributor_count: git.contributor_count,
+ commit_count_90d: git.commit_count_90d,
+ is_hotspot: git.is_hotspot,
+ churn_percentile: git.churn_percentile,
+ top_authors: git.top_authors,
+ }
+ : null
+ }
+ coChanges={coChangePayload?.co_change_partners ?? []}
+ deadCode={overlappingDead.map((f) => ({
+ id: f.id,
+ kind: f.kind,
+ reason: f.reason,
+ confidence: f.confidence,
+ lines: f.lines,
+ safe_to_delete: f.safe_to_delete,
+ }))}
+ onOpenBlastRadius={() =>
+ router.push(`/repos/${repoId}/blast-radius?file=${encodeURIComponent(filePath)}`)
+ }
+ />
+ );
+}
diff --git a/packages/web/src/components/symbols/symbol-table-wrapper.tsx b/packages/web/src/components/symbols/symbol-table-wrapper.tsx
index 9ce873212..9e2ed0c49 100644
--- a/packages/web/src/components/symbols/symbol-table-wrapper.tsx
+++ b/packages/web/src/components/symbols/symbol-table-wrapper.tsx
@@ -1,15 +1,13 @@
"use client";
-import { useState, useMemo } from "react";
-import useSWR from "swr";
+import { useMemo, useState } from "react";
import useSWRInfinite from "swr/infinite";
-import { SymbolTable } from "@repowise-dev/ui/symbols/symbol-table";
+import { SymbolTable, type SymbolFilters } from "@repowise-dev/ui/symbols/symbol-table";
import { HotSymbolsBoard, type HotSymbol } from "@repowise-dev/ui/symbols/hot-symbols-board";
import { SymbolDrawerWrapper } from "./symbol-drawer-wrapper";
-import { listSymbols } from "@/lib/api/symbols";
-import { getGraph } from "@/lib/api/graph";
+import { listSymbolsPage, type SymbolSortKey } from "@/lib/api/symbols";
import { useDebounce } from "@/lib/hooks/use-debounce";
-import type { SymbolResponse, GraphExportResponse } from "@/lib/api/types";
+import type { Paginated, SymbolResponse } from "@/lib/api/types";
const LIMIT = 50;
@@ -18,37 +16,44 @@ interface Props {
}
export function SymbolTableWrapper({ repoId }: Props) {
- const [q, setQ] = useState("");
- const debouncedQ = useDebounce(q, 300);
- const [kind, setKind] = useState("all");
- const [language, setLanguage] = useState("all");
+ const [filters, setFilters] = useState<SymbolFilters>({
+ q: "",
+ kind: "all",
+ language: "all",
+ visibility: "all",
+ inHotFiles: false,
+ inEntryPoints: false,
+ sort: "importance",
+ });
+ const debouncedQ = useDebounce(filters.q, 300);
const [selected, setSelected] = useState<SymbolResponse | null>(null);
- const { data: graphData } = useSWR<GraphExportResponse>(
- `graph:${repoId}`,
- () => getGraph(repoId),
- { revalidateOnFocus: false, revalidateOnReconnect: false },
+ // The fetch key changes whenever any filter does — SWR will fall back to
+ // page 0 cleanly without us having to reset infinite state by hand.
+ const keyPayload = useMemo(
+ () => ({ ...filters, q: debouncedQ }),
+ [filters, debouncedQ],
);
- const pagerankMap = useMemo(() => {
- if (!graphData) return new Map<string, number>();
- const m = new Map<string, number>();
- for (const n of graphData.nodes) m.set(n.node_id, n.pagerank);
- return m;
- }, [graphData]);
-
- const { data, size, setSize, isLoading, isValidating } = useSWRInfinite<SymbolResponse[]>(
+ const { data, size, setSize, isLoading, isValidating } = useSWRInfinite<
+ Paginated<SymbolResponse>
+ >(
(pageIndex, previousPageData) => {
- if (previousPageData && previousPageData.length < LIMIT) return null;
- return `symbols:${repoId}:${debouncedQ}:${kind}:${language}:${pageIndex}`;
+ if (previousPageData && !previousPageData.has_more) return null;
+ return `symbols:${repoId}:${JSON.stringify(keyPayload)}:${pageIndex}`;
},
(key) => {
const pageIndex = parseInt(key.split(":").pop()!, 10);
- return listSymbols({
+ return listSymbolsPage({
repo_id: repoId,
- q: debouncedQ || undefined,
- kind: kind !== "all" ? kind : undefined,
- language: language !== "all" ? language : undefined,
+ q: keyPayload.q || undefined,
+ kind: keyPayload.kind !== "all" ? keyPayload.kind : undefined,
+ language: keyPayload.language !== "all" ? keyPayload.language : undefined,
+ visibility:
+ keyPayload.visibility !== "all" ? keyPayload.visibility : undefined,
+ in_hot_files: keyPayload.inHotFiles || undefined,
+ in_entry_points: keyPayload.inEntryPoints || undefined,
+ sort: keyPayload.sort,
limit: LIMIT,
offset: pageIndex * LIMIT,
});
@@ -56,34 +61,26 @@ export function SymbolTableWrapper({ repoId }: Props) {
{ revalidateOnFocus: false, revalidateFirstPage: false },
);
- const items = useMemo(() => (data ? data.flat() : []), [data]);
-
- const importanceScores = useMemo(() => {
- const scores = new Map<string, number>();
- for (const sym of items) {
- const fileRank = pagerankMap.get(sym.file_path) ?? 0;
- const complexity = Math.max(1, sym.complexity_estimate);
- scores.set(sym.id, fileRank * (1 + Math.log(complexity)));
- }
- const max = Math.max(...scores.values(), 0.0001);
- for (const [k, v] of scores) scores.set(k, v / max);
- return scores;
- }, [items, pagerankMap]);
-
- const lastPage = data ? data[data.length - 1] : undefined;
- const hasMore = lastPage?.length === LIMIT;
+ const items = useMemo(
+ () => (data ? data.flatMap((p) => p.items) : []),
+ [data],
+ );
+ const total = data && data.length > 0 ? data[0].total : 0;
+ const hasMore = data ? data[data.length - 1].has_more : false;
+ // Hot symbols board — uses the same server-ranked stream so it matches
+ // the table's order. We just take the top of the first page.
const hotSymbols: HotSymbol[] = useMemo(() => {
- return [...items]
- .map((s) => {
- const pr = pagerankMap.get(s.file_path) ?? 0;
- const cx = Math.max(1, s.complexity_estimate);
- return { symbol: s, score: pr * (1 + Math.log(cx)), pagerank: pr };
- })
- .sort((a, b) => b.score - a.score)
- .filter((h) => h.score > 0)
- .slice(0, 8);
- }, [items, pagerankMap]);
+ const firstPage = data && data.length > 0 ? data[0].items : [];
+ return firstPage
+ .filter((s) => (s.importance_score ?? 0) > 0)
+ .slice(0, 8)
+ .map((s) => ({
+ symbol: s,
+ score: s.importance_score ?? 0,
+ pagerank: s.file_pagerank ?? 0,
+ }));
+ }, [data]);
return (
<div className="space-y-6">
@@ -91,28 +88,24 @@ export function SymbolTableWrapper({ repoId }: Props) {
<HotSymbolsBoard items={hotSymbols} onSelect={setSelected} />
)}
<SymbolTable
- items={items}
- importanceScores={importanceScores}
- repoId={repoId}
- isLoading={isLoading}
- isValidating={isValidating}
- hasMore={hasMore}
- q={q}
- onQChange={setQ}
- kind={kind}
- onKindChange={setKind}
- language={language}
- onLanguageChange={setLanguage}
- onLoadMore={() => setSize(size + 1)}
- onSelect={setSelected}
- drawer={
- <SymbolDrawerWrapper
- symbol={selected}
- repoId={repoId}
- onClose={() => setSelected(null)}
- />
- }
- />
+ items={items}
+ repoId={repoId}
+ isLoading={isLoading}
+ isValidating={isValidating}
+ hasMore={hasMore}
+ total={total}
+ filters={filters}
+ onFiltersChange={setFilters}
+ onLoadMore={() => setSize(size + 1)}
+ onSelect={setSelected}
+ drawer={
+ <SymbolDrawerWrapper
+ symbol={selected}
+ repoId={repoId}
+ onClose={() => setSelected(null)}
+ />
+ }
+ />
</div>
);
}
diff --git a/packages/web/src/lib/api/git.ts b/packages/web/src/lib/api/git.ts
index d3aba0708..68ac7948f 100644
--- a/packages/web/src/lib/api/git.ts
+++ b/packages/web/src/lib/api/git.ts
@@ -1,9 +1,10 @@
import { apiGet } from "./client";
import type {
GitMetadataResponse,
+ GitSummaryResponse,
HotspotResponse,
OwnershipEntry,
- GitSummaryResponse,
+ Paginated,
} from "./types";
export async function getGitMetadata(
@@ -15,31 +16,76 @@ export async function getGitMetadata(
});
}
+/**
+ * Paginated hotspot fetch — returns the full envelope so the UI can render
+ * "Showing N of M / Load more". New callers should prefer this over
+ * {@link getHotspots}, which is kept for back-compat (returns just the
+ * items list, but no longer hides the long tail since the server cap is
+ * 500 rather than the old 100).
+ */
+export async function getHotspotsPage(
+ repoId: string,
+ options: { limit?: number; offset?: number } = {},
+): Promise<Paginated<HotspotResponse>> {
+ const { limit = 50, offset = 0 } = options;
+ return apiGet<Paginated<HotspotResponse>>(`/api/repos/${repoId}/hotspots`, {
+ limit,
+ offset,
+ });
+}
+
+/**
+ * Back-compat helper — keeps the legacy `(repoId, limit) → list` signature
+ * used by widgets that don't (yet) render a "load more" affordance.
+ */
export async function getHotspots(
repoId: string,
- limit = 20,
+ limit = 50,
): Promise<HotspotResponse[]> {
- return apiGet<HotspotResponse[]>(`/api/repos/${repoId}/hotspots`, { limit });
+ const page = await getHotspotsPage(repoId, { limit });
+ return page.items;
+}
+
+export async function getOwnershipPage(
+ repoId: string,
+ granularity: "file" | "module" = "module",
+ options: { limit?: number; offset?: number } = {},
+): Promise<Paginated<OwnershipEntry>> {
+ const { limit = 500, offset = 0 } = options;
+ return apiGet<Paginated<OwnershipEntry>>(`/api/repos/${repoId}/ownership`, {
+ granularity,
+ limit,
+ offset,
+ });
}
export async function getOwnership(
repoId: string,
granularity: "file" | "module" = "module",
): Promise<OwnershipEntry[]> {
- return apiGet<OwnershipEntry[]>(`/api/repos/${repoId}/ownership`, { granularity });
+ const page = await getOwnershipPage(repoId, granularity, { limit: 5000 });
+ return page.items;
}
export async function getCoChanges(
repoId: string,
filePath: string,
minCount = 3,
-): Promise<{ file_path: string; co_change_partners: Array<{ file_path: string; co_change_count: number }> }> {
+): Promise<{
+ file_path: string;
+ co_change_partners: Array<{ file_path: string; co_change_count: number }>;
+ total?: number;
+}> {
return apiGet(`/api/repos/${repoId}/co-changes`, {
file_path: filePath,
min_count: minCount,
});
}
-export async function getGitSummary(repoId: string): Promise<GitSummaryResponse> {
- return apiGet<GitSummaryResponse>(`/api/repos/${repoId}/git-summary`);
+export async function getGitSummary(
+ repoId: string,
+ topOwnersLimit?: number,
+): Promise<GitSummaryResponse> {
+ const params = topOwnersLimit ? { top_owners_limit: topOwnersLimit } : undefined;
+ return apiGet<GitSummaryResponse>(`/api/repos/${repoId}/git-summary`, params);
}
diff --git a/packages/web/src/lib/api/symbols.ts b/packages/web/src/lib/api/symbols.ts
index cae363981..e998f1d23 100644
--- a/packages/web/src/lib/api/symbols.ts
+++ b/packages/web/src/lib/api/symbols.ts
@@ -1,18 +1,37 @@
import { apiGet } from "./client";
-import type { SymbolResponse } from "./types";
+import type { Paginated, SymbolResponse } from "./types";
+
+export type SymbolSortKey = "importance" | "name" | "complexity" | "kind";
export interface SymbolListParams {
repo_id: string;
q?: string;
kind?: string;
language?: string;
+ visibility?: string;
+ in_hot_files?: boolean;
+ in_entry_points?: boolean;
+ sort?: SymbolSortKey;
limit?: number;
offset?: number;
}
-export async function listSymbols(params: SymbolListParams): Promise<SymbolResponse[]> {
+/** Paginated symbol search — preferred entry point. */
+export async function listSymbolsPage(
+ params: SymbolListParams,
+): Promise<Paginated<SymbolResponse>> {
const p: Record<string, string | number | boolean | undefined> = { ...params };
- return apiGet<SymbolResponse[]>("/api/symbols", p);
+ return apiGet<Paginated<SymbolResponse>>("/api/symbols", p);
+}
+
+/**
+ * Back-compat: returns just the items array. Existing callers that don't
+ * (yet) render pagination keep working but get importance-ranked output
+ * by default.
+ */
+export async function listSymbols(params: SymbolListParams): Promise<SymbolResponse[]> {
+ const page = await listSymbolsPage(params);
+ return page.items;
}
export async function lookupSymbolByName(
diff --git a/packages/web/src/lib/api/types.ts b/packages/web/src/lib/api/types.ts
index 7c94fecc1..41bca28ac 100644
--- a/packages/web/src/lib/api/types.ts
+++ b/packages/web/src/lib/api/types.ts
@@ -3,6 +3,17 @@
* Source of truth: packages/server/src/repowise/server/schemas.py
*/
+/**
+ * Pagination envelope returned by list endpoints. Mirrors
+ * ``repowise.server.schemas.Paginated[T]``.
+ */
+export interface Paginated<T> {
+ items: T[];
+ total: number;
+ has_more: boolean;
+ next_offset: number | null;
+}
+
// ---------------------------------------------------------------------------
// Repository
// ---------------------------------------------------------------------------
@@ -153,6 +164,14 @@ export interface SearchResultResponse {
// Symbols
// ---------------------------------------------------------------------------
+export interface SymbolImportanceComponents {
+ file_pagerank: number;
+ visibility_factor: number;
+ complexity_norm: number;
+ kind_boost: number;
+ is_entry_point: boolean;
+}
+
export interface SymbolResponse {
id: string;
repository_id: string;
@@ -170,6 +189,12 @@ export interface SymbolResponse {
complexity_estimate: number;
language: string;
parent_name: string | null;
+ importance_score?: number | null;
+ importance_components?: SymbolImportanceComponents | null;
+ file_pagerank?: number | null;
+ is_entry_point?: boolean | null;
+ file_churn_percentile?: number | null;
+ file_is_hotspot?: boolean | null;
}
// ---------------------------------------------------------------------------
@@ -454,11 +479,15 @@ export interface GitMetadataResponse {
export interface HotspotResponse {
file_path: string;
+ commit_count_total?: number;
commit_count_90d: number;
commit_count_30d: number;
churn_percentile: number;
temporal_hotspot_score?: number | null;
primary_owner: string | null;
+ primary_owner_commit_pct?: number | null;
+ recent_owner_name?: string | null;
+ recent_owner_commit_pct?: number | null;
is_hotspot: boolean;
is_stable: boolean;
bus_factor: number;
@@ -467,6 +496,10 @@ export interface HotspotResponse {
lines_deleted_90d: number;
avg_commit_size: number;
commit_categories: Record<string, number>;
+ merge_commit_count_90d?: number;
+ commit_count_capped?: boolean;
+ age_days?: number;
+ last_commit_at?: string | null;
}
export interface OwnershipEntry {
diff --git a/tests/unit/server/test_git.py b/tests/unit/server/test_git.py
index 53f21eb8b..7667a1089 100644
--- a/tests/unit/server/test_git.py
+++ b/tests/unit/server/test_git.py
@@ -86,8 +86,11 @@ async def test_get_hotspots(client: AsyncClient, app) -> None:
resp = await client.get(f"/api/repos/{repo['id']}/hotspots")
assert resp.status_code == 200
- data = resp.json()
- assert len(data) == 1 # Only main.py is a hotspot
+ payload = resp.json()
+ assert payload["total"] == 1 # Only main.py is a hotspot
+ assert payload["has_more"] is False
+ data = payload["items"]
+ assert len(data) == 1
assert data[0]["file_path"] == "src/main.py"
assert data[0]["is_hotspot"] is True
@@ -99,7 +102,9 @@ async def test_get_ownership(client: AsyncClient, app) -> None:
resp = await client.get(f"/api/repos/{repo['id']}/ownership")
assert resp.status_code == 200
- data = resp.json()
+ payload = resp.json()
+ data = payload["items"]
+ assert payload["total"] == len(data)
assert len(data) >= 1
# Both files are under "src" module
src_entry = next((e for e in data if e["module_path"] == "src"), None)
diff --git a/tests/unit/server/test_symbols.py b/tests/unit/server/test_symbols.py
index 36bbc9baa..c6ab73c65 100644
--- a/tests/unit/server/test_symbols.py
+++ b/tests/unit/server/test_symbols.py
@@ -40,7 +40,10 @@ async def test_search_symbols_empty(client: AsyncClient) -> None:
repo = await create_test_repo(client)
resp = await client.get("/api/symbols", params={"repo_id": repo["id"]})
assert resp.status_code == 200
- assert resp.json() == []
+ payload = resp.json()
+ assert payload["total"] == 0
+ assert payload["items"] == []
+ assert payload["has_more"] is False
@pytest.mark.asyncio
@@ -50,10 +53,15 @@ async def test_search_symbols_by_name(client: AsyncClient, app) -> None:
resp = await client.get("/api/symbols", params={"repo_id": repo["id"], "q": "main"})
assert resp.status_code == 200
- data = resp.json()
+ payload = resp.json()
+ assert payload["total"] == 1
+ data = payload["items"]
assert len(data) == 1
assert data[0]["name"] == "main"
assert data[0]["kind"] == "function"
+ # New importance enrichment fields should be populated.
+ assert data[0]["importance_score"] is not None
+ assert data[0]["importance_components"] is not None
@pytest.mark.asyncio
@@ -69,7 +77,7 @@ async def test_search_symbols_by_kind(client: AsyncClient, app) -> None:
resp = await client.get("/api/symbols", params={"repo_id": repo["id"], "kind": "class"})
assert resp.status_code == 200
- data = resp.json()
+ data = resp.json()["items"]
assert len(data) == 1
assert data[0]["kind"] == "class"