Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(health): hotspots counted, searched and paged over the whole set (#4162)
Raghav Chamadiyad7b9ecebc3ee
diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.mdindex 009108ac5..2c5235cc2 100644--- a/docs/architecture/ARCHITECTURE.md+++ b/docs/architecture/ARCHITECTURE.md@@ -1144,7 +1144,7 @@ Key routers:- `/api/webhooks/gitlab`: GitLab webhook handler- `/api/webhooks/gitea`: Gitea and Forgejo webhook handler with HMAC verification- `/api/repos/{id}/git-metadata`: per-file git metadata-- `/api/repos/{id}/hotspots`: high-churn + high-complexity files+- `/api/repos/{id}/hotspots`: hotspots ranked by temporal hotspot score; `q`, `filter`, `sort`/`order`, offset paging, `hold`/`include` (map scope) and `facets` counts over the searched set- `/api/repos/{id}/ownership`: ownership breakdown (file/module/package granularity)- `/api/repos/{id}/co-changes`: co-change partners for a file- `/api/repos/{id}/git-summary`: aggregate git health signals for dashboarddiff --git a/packages/api-client/src/git.ts b/packages/api-client/src/git.tsindex 27ce6d62b..60b5a6de4 100644--- a/packages/api-client/src/git.ts+++ b/packages/api-client/src/git.ts@@ -1,3 +1,4 @@+import { holdParams } from "./areas";import { apiGet } from "./client";import type {AgentTrend,@@ -12,6 +13,13 @@ import type {Paginated,ReviewerSuggestionsResponse,} from "./types";+import type { MapHoldQuery } from "@repowise-dev/types/areas";+import type {+ HotspotFacets,+ HotspotFilter,+ HotspotOrder,+ HotspotSort,+} from "@repowise-dev/types/git";import type {HistoryFilters,PeriodHealthSummaryResponse,@@ -26,21 +34,39 @@ export async function getGitMetadata(});}+/** One page of the hotspot list plus counts over the whole searched set. */+export interface HotspotPage extends Paginated<HotspotResponse> {+ facets: HotspotFacets;+}++export interface HotspotPageQuery extends MapHoldQuery {+ limit?: number;+ offset?: number;+ /** Path or owner substring. */+ q?: string;+ filter?: HotspotFilter;+ sort?: HotspotSort;+ order?: HotspotOrder;+}+/**- * 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).+ * One page of hotspots ranked by temporal hotspot score. `total` counts what+ * the filter and search match; `facets` count every filter over the search.+ * Defaults (no search, no filter, every origin) list the whole hotspot set.*/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`, {+ options: HotspotPageQuery = {},+): Promise<HotspotPage> {+ const { limit = 50, offset = 0, q, filter, sort, order } = options;+ return apiGet<HotspotPage>(`/api/repos/${repoId}/hotspots`, {limit,offset,+ q: q || undefined,+ filter: filter && filter !== "all" ? filter : undefined,+ sort,+ order,+ ...holdParams(options),});}diff --git a/packages/api-client/src/types/git.ts b/packages/api-client/src/types/git.tsindex f005b5604..d68d2bb8a 100644--- a/packages/api-client/src/types/git.ts+++ b/packages/api-client/src/types/git.ts@@ -84,6 +84,10 @@ export interface HotspotResponse {bug_magnet?: boolean;last_fix_at?: string | null;original_path?: string | null;+ /** Faster over the last 30 days than over the last 90, on a file older than that window. */+ accelerating?: boolean;+ /** Place by hotspot score within the listed scope; set by the hotspot list only. */+ rank?: number | null;}export interface OwnershipEntry {diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.pyindex 18b7946ff..2934ab8ba 100644--- a/packages/server/src/repowise/server/routers/git.py+++ b/packages/server/src/repowise/server/routers/git.py@@ -54,6 +54,7 @@ from repowise.server.routers._local_git import (resolve_local_repo,revision_exists,)+from repowise.server.routers.held_origins import HOLD_QUERY, INCLUDE_QUERYfrom repowise.server.schemas import (AgentTrendBucket,AgentTrendResponse,@@ -79,7 +80,9 @@ from repowise.server.schemas import (RiskHistogramBucket,RiskRangeResponse,)+from repowise.server.schemas.git import HotspotFacets, HotspotPagefrom repowise.server.schemas.history import PeriodHealthSummaryResponse+from repowise.server.services.areas import held_originsfrom repowise.server.services.history.commits import (CommitHistory,commit_history,@@ -90,6 +93,9 @@ from repowise.server.services.history.health import (finding_fields,period_response,)+from repowise.server.services.hotspots import FILTERS as HOTSPOT_FILTERS+from repowise.server.services.hotspots import SORTS as HOTSPOT_SORTS+from repowise.server.services.hotspots import HotspotQuery, is_accelerating, list_hotspotsfrom repowise.server.services.module_health import top_level_modulefrom repowise.server.services.reviewer_suggestions import suggest_reviewers@@ -142,6 +148,7 @@ def _hotspot_from_row(r: GitMetadata) -> HotspotResponse:bug_magnet=bool(r.bug_magnet),last_fix_at=r.last_fix_at,original_path=r.original_path,+ accelerating=is_accelerating(r.commit_count_30d, r.commit_count_90d, r.age_days),)@@ -680,43 +687,49 @@ async def get_git_metadata(return response[email protected]("/{repo_id}/hotspots", response_model=Paginated[HotspotResponse])-async def get_hotspots(- repo_id: str,+def _hotspot_query(limit: int = Query(50, ge=1, le=500),offset: int = Query(0, ge=0),- session: AsyncSession = Depends(get_db_session),-) -> Paginated[HotspotResponse]:- """Return the highest-churn files (hotspots), paginated.+ q: str = Query("", max_length=200, description="Path or owner substring, case-insensitive."),+ filter: str = Query("all", pattern=f"^({'|'.join(HOTSPOT_FILTERS)})$"),+ sort: str = Query("score", pattern=f"^({'|'.join(HOTSPOT_SORTS)})$"),+ order: str = Query("desc", pattern="^(asc|desc)$"),+ hold: str = HOLD_QUERY,+ include: str = INCLUDE_QUERY,+) -> HotspotQuery:+ return HotspotQuery(+ limit=limit,+ offset=offset,+ q=q,+ filter=filter,+ sort=sort,+ descending=order == "desc",+ held=held_origins(hold, include),+ )- 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[email protected]("/{repo_id}/hotspots", response_model=HotspotPage)+async def get_hotspots(+ repo_id: str,+ query: HotspotQuery = Depends(_hotspot_query),+ session: AsyncSession = Depends(get_db_session),+) -> HotspotPage:+ """Hotspots ranked by temporal hotspot score, one page at a time.- 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](+ ``total`` counts the rows this filter and search match; ``facets`` count+ every filter over the searched set, so a chip can say "N of total". Each+ row's ``rank`` is its place by score in the scope, whatever the sort.+ """+ listing = await list_hotspots(session, repo_id, query)+ items = [_hotspot_from_row(r).model_copy(update={"rank": rank}) for r, rank in listing.rows]+ end = query.offset + query.limit+ next_offset = end if end < listing.total else None+ return HotspotPage(items=items,- total=total,+ total=listing.total,has_more=next_offset is not None,next_offset=next_offset,+ facets=HotspotFacets(**listing.facets),)diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.pyindex 722ab5e05..9511a9698 100644--- a/packages/server/src/repowise/server/schemas/git.py+++ b/packages/server/src/repowise/server/schemas/git.py@@ -11,6 +11,7 @@ from pydantic import BaseModelfrom repowise.core.attribution import file_sharefrom repowise.core.co_change import parse_partnersfrom repowise.server.schemas.history import HealthDeltaSummaryResponse+from repowise.server.schemas.pagination import Paginatedfrom repowise.server.schemas.risk_semantics import RiskAuthority@@ -175,6 +176,26 @@ class HotspotResponse(BaseModel):bug_magnet: bool = Falselast_fix_at: datetime | None = Noneoriginal_path: str | None = None+ #: Changing faster over the last 30 days than over the last 90, on a file+ #: older than that window (see ``services.hotspots.is_accelerating``).+ accelerating: bool = False+ #: Place by hotspot score within the listed scope; set by the hotspot list only.+ rank: int | None = None+++class HotspotFacets(BaseModel):+ """Counts over every hotspot the search matches, whatever the filter."""++ total: int+ bus_factor_1: int+ accelerating: int+ bug_magnet: int+ #: Hotspots with any recorded fix, so a client knows fix data exists past its page.+ with_fixes: int = 0+++class HotspotPage(Paginated[HotspotResponse]):+ facets: HotspotFacetsclass OwnershipEntry(BaseModel):diff --git a/packages/server/src/repowise/server/services/hotspots.py b/packages/server/src/repowise/server/services/hotspots.pynew file mode 100644index 000000000..dd78ff1c5--- /dev/null+++ b/packages/server/src/repowise/server/services/hotspots.py@@ -0,0 +1,203 @@+"""The hotspot list: one ranked, searchable, filterable page plus its facets.++Rank is the file's place by temporal hotspot score within the scope (the held+origins left out), so it stays the same whatever the reader filters, searches or+sorts by. The facets count the whole searched set in one aggregate and are kept+per index state, so a page turn costs the page query alone.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Literal++from sqlalchemy import Integer, and_, case, func, or_, select+from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.sql import ColumnElement, Select++from repowise.core.persistence.index_cache import IndexStampCache+from repowise.core.persistence.models import GitMetadata, HealthFileMetric++__all__ = [+ "FILTERS",+ "SORTS",+ "HotspotListing",+ "HotspotQuery",+ "accelerating_clause",+ "clear_hotspot_cache",+ "is_accelerating",+ "list_hotspots",+ "origin_clause",+]++HotspotFilter = Literal["all", "bus_factor_1", "accelerating", "bug_magnet"]+FILTERS: tuple[str, ...] = ("all", "bus_factor_1", "accelerating", "bug_magnet")+SORTS: tuple[str, ...] = ("score", "commits", "fixes", "churn")++#: The trailing window the commit counts describe, and its recent slice.+WINDOW_DAYS = 90+RECENT_DAYS = 30++#: Facets per (database, repository, index stamp, held set, search).+_facets = IndexStampCache(64)+++def clear_hotspot_cache() -> None:+ _facets.clear()+++def is_accelerating(commits_30d: int | None, commits_90d: int | None, age_days: int | None) -> bool:+ """A file changing faster in the last 30 days than over its last 90.++ Only a file older than the window has a pace to speed up from: a file+ created this quarter has all its commits recent by construction, which is+ newness, not acceleration. :func:`accelerating_clause` is the same rule in SQL.+ """+ if (age_days or 0) <= WINDOW_DAYS:+ return False+ return (commits_30d or 0) * (WINDOW_DAYS // RECENT_DAYS) > (commits_90d or 0)+++def accelerating_clause(g: Any = GitMetadata) -> ColumnElement[bool]:+ """:func:`is_accelerating` as a ``where`` clause over git rows."""+ return and_(+ func.coalesce(g.age_days, 0) > WINDOW_DAYS,+ func.coalesce(g.commit_count_30d, 0) * (WINDOW_DAYS // RECENT_DAYS)+ > func.coalesce(g.commit_count_90d, 0),+ )+++def _bug_magnet_clause(g: Any = GitMetadata) -> ColumnElement[bool]:+ # The flag only counts with an age beside it (consumers drop it otherwise).+ return and_(+ g.bug_magnet.is_(True),+ g.last_fix_at.is_not(None),+ func.coalesce(g.prior_defect_count, 0) > 0,+ )+++def _bus_factor_1_clause(g: Any = GitMetadata) -> ColumnElement[bool]:+ # Exactly one: zero means the file has no attributable history, not one owner.+ return g.bus_factor == 1+++_FILTER_CLAUSES = {+ "bus_factor_1": _bus_factor_1_clause,+ "accelerating": accelerating_clause,+ "bug_magnet": _bug_magnet_clause,+}+++def origin_clause(h: Any = HealthFileMetric) -> ColumnElement[str]:+ """:func:`repowise.core.analysis.finding_registry.stored_origin` in SQL, over+ an outer-joined health row (a file with no health row reads ``production``)."""+ return case(+ (and_(h.code_origin.is_not(None), h.code_origin != ""), h.code_origin),+ (h.is_test.is_(True), "test"),+ else_="production",+ )+++def _sort_columns(g: Any) -> dict[str, ColumnElement[Any]]:+ return {+ "score": g.temporal_hotspot_score,+ "commits": g.commit_count_90d,+ "fixes": g.prior_defect_count,+ "churn": g.churn_percentile,+ }+++def _scope(repo_id: str, held: frozenset[str]) -> Select[Any]:+ """Hotspot rows outside the held origins, each with its rank by score."""+ g = GitMetadata+ rank = func.row_number().over(+ order_by=(g.temporal_hotspot_score.desc().nulls_last(), g.churn_percentile.desc(), g.file_path)+ )+ stmt = select(g.id.label("id"), rank.label("rank")).where(+ g.repository_id == repo_id, g.is_hotspot.is_(True)+ )+ if held:+ h = HealthFileMetric+ stmt = stmt.outerjoin(+ h, and_(h.repository_id == g.repository_id, h.file_path == g.file_path)+ ).where(origin_clause(h).not_in(sorted(held)))+ return stmt+++def _search_clause(q: str) -> ColumnElement[bool]:+ needle = q.lower()+ return or_(+ func.lower(GitMetadata.file_path).contains(needle, autoescape=True),+ func.lower(func.coalesce(GitMetadata.primary_owner_name, "")).contains(needle, autoescape=True),+ )+++async def _git_stamp(session: AsyncSession, repo_id: str) -> tuple[Any, ...]:+ """What moves when git rows are re-mined without a health pass: the index+ stamp watches health rows, and the facets read git rows."""+ g = GitMetadata+ stmt = select(func.count(), func.max(g.updated_at)).where(g.repository_id == repo_id)+ return tuple((await session.execute(stmt)).one())+++@dataclass(frozen=True)+class HotspotQuery:+ """One page of the list: which rows (scope, search, filter), in what order."""++ limit: int = 50+ offset: int = 0+ q: str = ""+ filter: str = "all"+ sort: str = "score"+ descending: bool = True+ held: frozenset[str] = frozenset()+++@dataclass+class HotspotListing:+ rows: list[tuple[GitMetadata, int]]+ total: int+ facets: dict[str, int]+++async def _count_facets(session: AsyncSession, base: Select[Any]) -> dict[str, int]:+ """Every facet over the searched set in one aggregate."""++ def count_of(clause: ColumnElement[bool]) -> Any:+ return func.coalesce(func.sum(case((clause, 1), else_=0)), 0).cast(Integer)++ row = (+ await session.execute(+ base.with_only_columns(+ func.count(),+ count_of(_bus_factor_1_clause()),+ count_of(accelerating_clause()),+ count_of(_bug_magnet_clause()),+ count_of(func.coalesce(GitMetadata.prior_defect_count, 0) > 0),+ ).order_by(None)+ )+ ).one()+ keys = ("total", "bus_factor_1", "accelerating", "bug_magnet", "with_fixes")+ return dict(zip(keys, map(int, row), strict=True))+++async def list_hotspots(session: AsyncSession, repo_id: str, query: HotspotQuery) -> HotspotListing:+ scope = _scope(repo_id, query.held).subquery()+ g = GitMetadata+ base = select(g, scope.c.rank).join(scope, scope.c.id == g.id)+ q = query.q.strip()+ if q:+ base = base.where(_search_clause(q))++ stamp = await _git_stamp(session, repo_id)+ key = await _facets.key(session, repo_id, stamp, tuple(sorted(query.held)), q)+ facets = _facets.get(key) if key in _facets else _facets.remember(key, await _count_facets(session, base))++ narrow = _FILTER_CLAUSES.get(query.filter)+ listing = base if narrow is None else base.where(narrow())+ column = _sort_columns(g)[query.sort]+ ordered = column.desc() if query.descending else column.asc()+ page = listing.order_by(ordered.nulls_last(), scope.c.rank).limit(query.limit).offset(query.offset)+ rows = [(r[0], int(r[1])) for r in (await session.execute(page)).all()]+ total = facets["total"] if narrow is None else facets[query.filter]+ return HotspotListing(rows=rows, total=total, facets=facets)diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex d2929f5e6..fb137217e 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -2638,6 +2638,23 @@ export interface HotFilesNodeResponse {commit_count: number;}+/** Counts over every hotspot the search matches, whatever the filter. */+export interface HotspotFacets {+ total: number;+ bus_factor_1: number;+ accelerating: number;+ bug_magnet: number;+ with_fixes?: number;+}++export interface HotspotPage {+ items: HotspotResponse[];+ total: number;+ has_more: boolean;+ next_offset?: number | null;+ facets: HotspotFacets;+}+export interface HotspotResponse {file_path: string;commit_count_total?: number;@@ -2667,6 +2684,8 @@ export interface HotspotResponse {bug_magnet?: boolean;last_fix_at?: string | null;original_path?: string | null;+ accelerating?: boolean;+ rank?: number | null;}export interface IdentityResponse {@@ -3154,13 +3173,6 @@ export interface Paginated_CommitResponse_ {next_offset?: number | null;}-export interface Paginated_HotspotResponse_ {- items: HotspotResponse[];- total: number;- has_more: boolean;- next_offset?: number | null;-}-export interface Paginated_ModuleHealthSummary_ {items: ModuleHealthSummary[];total: number;diff --git a/packages/types/src/git.ts b/packages/types/src/git.tsindex d21b01b43..e6c8f4dfe 100644--- a/packages/types/src/git.ts+++ b/packages/types/src/git.ts@@ -121,6 +121,26 @@ export interface Hotspot {last_fix_at?: string | null;/** The file's path before its most recent rename, if any. */original_path?: string | null;+ /** Faster over the last 30 days than over the last 90, on a file older than that window. */+ accelerating?: boolean;+ /** Place by hotspot score within the listed scope; set by the hotspot list only. */+ rank?: number | null;+}++/** The hotspot list's filters; `all` lists every hotspot in scope. */+export type HotspotFilter = "all" | "bus_factor_1" | "accelerating" | "bug_magnet";+/** The hotspot list's sortable columns; `score` is the temporal hotspot score. */+export type HotspotSort = "score" | "commits" | "fixes" | "churn";+export type HotspotOrder = "asc" | "desc";++/** Counts over every hotspot the search matches, whatever the filter. */+export interface HotspotFacets {+ total: number;+ bus_factor_1: number;+ accelerating: number;+ bug_magnet: number;+ /** Hotspots with any recorded fix, across the whole searched set. */+ with_fixes?: number;}/** Repo-relative tercile of the diff-size percentile within its own repo;diff --git a/packages/ui/COMPONENT_CONTRACTS.md b/packages/ui/COMPONENT_CONTRACTS.mdindex 6393a40e8..7a2b8693c 100644--- a/packages/ui/COMPONENT_CONTRACTS.md+++ b/packages/ui/COMPONENT_CONTRACTS.md@@ -407,13 +407,19 @@ contributors only.### `git/hotspot-table` — `HotspotTable`-Searchable, filterable, sortable table of hotspots. Filter chips:-`all` / `hot` / `risk` / `accelerating`. Sortable columns:-`commits` / `churn` / `trend`. UI-local state — no fetch coupling.+Server-driven table of hotspots: the host owns search, filter, sort and+paging (the table debounces the search box and reports settled values).+Chips (`all` / `bus_factor_1` / `accelerating` / `bug_magnet`) show the+server's `facets` as "N of total"; sortable columns (`score` / `commits` /+`fixes` / `churn`) render only with `onSortChange`. One quiet per-row agent+prompt and a header "Copy prompt for these N".| Prop | Type | Required ||------|------|----------|| `hotspots` | `Hotspot[]` (`@repowise-dev/types/git`) | yes |+| `total`, `facets` | `number`, `HotspotFacets` | no |+| `query` / `filter` / `sort` and their `on*Change` | controlled state | no |+| `onGeneratePrompt`, `onGenerateBatchPrompt` | callbacks | no |### `git/ownership-table` — `OwnershipTable`diff --git a/packages/ui/__tests__/git/hotspot-table.test.tsx b/packages/ui/__tests__/git/hotspot-table.test.tsxindex 9625bf714..96c13059c 100644--- a/packages/ui/__tests__/git/hotspot-table.test.tsx+++ b/packages/ui/__tests__/git/hotspot-table.test.tsx@@ -1,7 +1,7 @@-import { describe, it, expect } from "vitest";-import { render, screen, fireEvent } from "@testing-library/react";+import { describe, it, expect, vi, afterEach } from "vitest";+import { render, screen, fireEvent, act } from "@testing-library/react";import { HotspotTable } from "../../src/git/hotspot-table.js";-import type { Hotspot } from "@repowise-dev/types/git";+import type { Hotspot, HotspotFacets } from "@repowise-dev/types/git";const hotspot = (overrides: Partial<Hotspot> = {}): Hotspot => ({file_path: "src/foo.ts",@@ -21,52 +21,121 @@ const hotspot = (overrides: Partial<Hotspot> = {}): Hotspot => ({...overrides,});-// Small dataset (< 60 rows) so the shared virtualizer renders every row-// unwindowed — assertions stay deterministic under jsdom.const rows: Hotspot[] = Array.from({ length: 10 }, (_, i) =>hotspot({- file_path: `src/file-${i}.ts`,+ file_path: `src/dir/file-${i}.ts`,commit_count_90d: 20 - i,- is_hotspot: i % 2 === 0,bus_factor: i % 3,+ rank: i + 41,+ accelerating: i === 0,}),);-describe("HotspotTable virtualization", () => {- it("renders every row in a small dataset", () => {+const facets: HotspotFacets = { total: 672, bus_factor_1: 378, accelerating: 253, bug_magnet: 0 };++afterEach(() => vi.useRealTimers());++describe("HotspotTable", () => {+ it("shows the server's facet counts as N of total, with no Hot chip", () => {+ render(<HotspotTable hotspots={rows} total={672} facets={facets} onFilterChange={() => {}} />);+ expect(screen.getByRole("button", { name: /^All 672$/ })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: /^Bus factor 1 378 of 672$/ })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: /^Accelerating 253 of 672$/ })).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: /^Hot/ })).not.toBeInTheDocument();+ // A filter with nothing in it is not offered.+ expect(screen.queryByRole("button", { name: /^Bug magnet/ })).not.toBeInTheDocument();+ });++ it("asks the host to filter rather than filtering the loaded page", () => {+ const onFilterChange = vi.fn();+ render(<HotspotTable hotspots={rows} facets={facets} onFilterChange={onFilterChange} />);+ fireEvent.click(screen.getByRole("button", { name: /^Accelerating/ }));+ expect(onFilterChange).toHaveBeenCalledWith("accelerating");+ expect(screen.getByText("file-9.ts")).toBeInTheDocument();+ });++ it("shows the server rank and the name before its folder", () => {render(<HotspotTable hotspots={rows} />);- for (const h of rows) {- expect(screen.getByText(h.file_path)).toBeInTheDocument();- }+ expect(screen.getByText("41")).toBeInTheDocument();+ expect(screen.getByText("file-0.ts")).toBeInTheDocument();+ expect(screen.getAllByText("src/dir")).toHaveLength(10);});- it("memoized filter chips show correct counts", () => {+ it("marks only accelerating rows", () => {render(<HotspotTable hotspots={rows} />);- // All = 10, Hot = 5 (even indices). The filter chips are <button>s whose- // accessible name folds in the count span ("All (10)", "Hot (5)").- expect(screen.getByRole("button", { name: /^All \(10\)$/ })).toBeInTheDocument();- expect(screen.getByRole("button", { name: /^Hot \(5\)$/ })).toBeInTheDocument();+ expect(screen.getAllByLabelText("Accelerating")).toHaveLength(1);+ });++ it("sorts through the host, flipping the order on the active column", () => {+ const onSortChange = vi.fn();+ render(+ <HotspotTable hotspots={rows} sort={{ key: "commits", order: "desc" }} onSortChange={onSortChange} />,+ );+ fireEvent.click(screen.getByRole("button", { name: /^Commits 90d/ }));+ expect(onSortChange).toHaveBeenLastCalledWith({ key: "commits", order: "asc" });+ fireEvent.click(screen.getByRole("button", { name: /^Score/ }));+ expect(onSortChange).toHaveBeenLastCalledWith({ key: "score", order: "desc" });+ });++ it("reports a settled search, not each keystroke", () => {+ vi.useFakeTimers();+ const onQueryChange = vi.fn();+ render(<HotspotTable hotspots={rows} onQueryChange={onQueryChange} />);+ const box = screen.getByRole("searchbox", { name: /Search hotspots/ });+ fireEvent.change(box, { target: { value: "co" } });+ fireEvent.change(box, { target: { value: "core" } });+ act(() => {+ vi.advanceTimersByTime(300);+ });+ expect(onQueryChange).toHaveBeenCalledTimes(1);+ expect(onQueryChange).toHaveBeenCalledWith("core");+ });++ it("keeps what was typed when the URL echoes an earlier search", () => {+ vi.useFakeTimers();+ const tree = (query: string) => <HotspotTable hotspots={rows} query={query} onQueryChange={() => {}} />;+ const { rerender } = render(tree(""));+ const box = screen.getByRole("searchbox");+ fireEvent.change(box, { target: { value: "co" } });+ act(() => {+ vi.advanceTimersByTime(300);+ });+ fireEvent.change(box, { target: { value: "core" } });+ rerender(tree("co"));+ expect(box).toHaveValue("core");+ // A change from outside (back button, link) still resets the box.+ rerender(tree("api"));+ expect(box).toHaveValue("api");});- it("expands a row to reveal its detail content", () => {+ it("keeps the active chip when its count drops to zero", () => {+ render(+ <HotspotTable hotspots={[]} query="x" facets={facets} filter="bug_magnet" onFilterChange={() => {}} />,+ );+ expect(screen.getByRole("button", { name: /^Bug magnet 0 of 672$/ })).toHaveAttribute("aria-pressed", "true");+ });++ it("offers one prompt per row and one for every listed row", () => {+ const onGeneratePrompt = vi.fn();+ const onGenerateBatchPrompt = vi.fn();render(<HotspotTablehotspots={rows}- renderExpandedRow={(h) => <div>detail for {h.file_path}</div>}+ total={672}+ onGeneratePrompt={onGeneratePrompt}+ onGenerateBatchPrompt={onGenerateBatchPrompt}/>,);- expect(screen.queryByText("detail for src/file-0.ts")).not.toBeInTheDocument();- const toggle = screen.getAllByRole("button", { name: "Expand symbols" })[0]!;- fireEvent.click(toggle);- expect(screen.getByText("detail for src/file-0.ts")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Copy prompt for these 672" }));+ expect(onGenerateBatchPrompt).toHaveBeenCalledWith(rows);+ fireEvent.click(screen.getByRole("button", { name: /: src\/dir\/file-3\.ts$/ }));+ expect(onGeneratePrompt).toHaveBeenCalledWith(rows[3]);});- it("filters rows by the active filter chip", () => {- render(<HotspotTable hotspots={rows} />);- fireEvent.click(screen.getByRole("button", { name: /^Hot \(5\)$/ }));- // Only the 5 hot files (even indices) should remain.- expect(screen.getByText("src/file-0.ts")).toBeInTheDocument();- expect(screen.queryByText("src/file-1.ts")).not.toBeInTheDocument();+ it("keeps the toolbar when a search matches nothing", () => {+ render(<HotspotTable hotspots={[]} query="zzz" onQueryChange={() => {}} />);+ expect(screen.getByText("No matches")).toBeInTheDocument();+ expect(screen.getByRole("searchbox")).toHaveValue("zzz");});it("renders the empty state when there are no hotspots", () => {@@ -75,42 +144,32 @@ describe("HotspotTable virtualization", () => {});});-const daysAgo = (n: number) =>- new Date(Date.now() - n * 86_400_000).toISOString();+const daysAgo = (n: number) => new Date(Date.now() - n * 86_400_000).toISOString();describe("HotspotTable fix history", () => {it("hides the Fixes column entirely when no row has counted fixes", () => {render(<HotspotTable hotspots={rows} />);- expect(screen.queryByRole("button", { name: /^Fixes/ })).not.toBeInTheDocument();- expect(screen.queryByRole("button", { name: /Bug magnet/ })).not.toBeInTheDocument();+ expect(screen.queryByRole("columnheader", { name: /^Fixes/ })).not.toBeInTheDocument();+ });++ it("shows the Fixes column when fixes sit only past the loaded page", () => {+ render(<HotspotTable hotspots={rows} facets={{ ...facets, with_fixes: 4 }} onSortChange={() => {}} />);+ expect(screen.getByRole("columnheader", { name: /^Fixes/ })).toBeInTheDocument();});it("shows the Fixes column once the index carries fix data", () => {const withFixes = [hotspot({ file_path: "src/a.ts", prior_defect_count: 7, last_fix_at: daysAgo(3) }),- hotspot({ file_path: "src/b.ts", prior_defect_count: 0 }),+ hotspot({ file_path: "src/b.ts", prior_defect_count: 0, primary_owner: "Bo" }),];render(<HotspotTable hotspots={withFixes} />);- expect(screen.getByRole("button", { name: /^Fixes/ })).toBeInTheDocument();+ expect(screen.getByRole("columnheader", { name: /^Fixes/ })).toBeInTheDocument();expect(screen.getByText("7")).toBeInTheDocument();// The file with no fixes shows a dash, not a misleading zero.expect(screen.getByText("—")).toBeInTheDocument();});- it("sorts on fix count, independently of churn", () => {- const withFixes = [- hotspot({ file_path: "src/low-fix.ts", commit_count_90d: 99, prior_defect_count: 1, last_fix_at: daysAgo(2) }),- hotspot({ file_path: "src/high-fix.ts", commit_count_90d: 1, prior_defect_count: 9, last_fix_at: daysAgo(2) }),- ];- render(<HotspotTable hotspots={withFixes} />);- fireEvent.click(screen.getByRole("button", { name: /^Fixes/ }));- const paths = screen- .getAllByTitle(/^src\//)- .map((el) => el.textContent);- expect(paths[0]).toBe("src/high-fix.ts");- });-- it("offers a Bug magnet chip only for magnets that carry a timestamp", () => {+ it("marks a magnet only when it carries a timestamp", () => {const anchored = hotspot({file_path: "src/magnet.ts",prior_defect_count: 5,@@ -124,9 +183,6 @@ describe("HotspotTable fix history", () => {last_fix_at: null,});render(<HotspotTable hotspots={[anchored, unanchored]} />);- // One of the two claims a magnet; the timestamp-less one is not counted.- fireEvent.click(screen.getByRole("button", { name: /^Bug magnet \(1\)$/ }));- expect(screen.getByText("src/magnet.ts")).toBeInTheDocument();- expect(screen.queryByText("src/unanchored.ts")).not.toBeInTheDocument();+ expect(screen.getAllByTitle(/^Bug magnet:/)).toHaveLength(1);});});diff --git a/packages/ui/__tests__/health/batch-prompts.test.ts b/packages/ui/__tests__/health/batch-prompts.test.tsindex cc9027c11..81b981efd 100644--- a/packages/ui/__tests__/health/batch-prompts.test.ts+++ b/packages/ui/__tests__/health/batch-prompts.test.ts@@ -3,6 +3,8 @@ import { describe, it, expect } from "vitest";import {buildCoverageAiPrompt,buildCoverageBatchAiPrompt,+ buildHotspotAiPrompt,+ buildHotspotBatchAiPrompt,buildSecurityAiPrompt,buildSecurityBatchAiPrompt,} from "../../src/health/ai-prompt-builder";@@ -42,4 +44,13 @@ describe("batch prompts", () => {});expect(prompt).toContain("**rotated**");});++ it("hotspot batch lists the loaded rows and counts the rest of the filtered total", () => {+ const hot = (i: number) => ({ file_path: `src/h${i}.ts`, commit_count_90d: 9, bus_factor: 1 });+ expect(buildHotspotBatchAiPrompt({ rows: [hot(1)] })).toBe(buildHotspotAiPrompt({ hotspot: hot(1) }));+ const prompt = buildHotspotBatchAiPrompt({ rows: Array.from({ length: 30 }, (_, i) => hot(i)), total: 672 });+ expect(prompt).toContain("`src/h24.ts` — 9 commits in 90 days, one person holds the knowledge");+ expect(prompt).not.toContain("`src/h25.ts`");+ expect(prompt).toContain("…and 647 more");+ });});diff --git a/packages/ui/src/git/hotspot-row.tsx b/packages/ui/src/git/hotspot-row.tsxnew file mode 100644index 000000000..cdf717023--- /dev/null+++ b/packages/ui/src/git/hotspot-row.tsx@@ -0,0 +1,143 @@+"use client";++import { memo } from "react";+import { Bug, Flame, TrendingUp } from "lucide-react";+import type { Hotspot } from "@repowise-dev/types/git";+import { Badge } from "../ui/badge";+import { ChurnBar } from "./churn-bar";+import { formatLOC } from "../lib/format";+import { summarizeFixHistory } from "../lib/fix-history";+import { cn } from "../lib/cn";+import { clickableRowProps, CLICKABLE_ROW_CLS } from "../shared/responsive-table";+import { RowPromptAction } from "../health/row-prompt-action";++/** A row's fix history, or null when it has none. */+export const fixOf = (h: Hotspot) =>+ summarizeFixHistory(h.prior_defect_count, h.last_fix_at, h.bug_magnet);++/**+ * Name first, folder after it in the quiet tone.+ * TODO(eux): swap for the shared FilePath from `@repowise-dev/ui/shared/file-path`+ * once PR 4161 lands on this base; this is the same name-first reading.+ */+function NameFirstPath({ path }: { path: string }) {+ const name = path.split("/").pop() ?? path;+ const dir = path.slice(0, path.length - name.length).replace(/\/$/, "");+ return (+ <span className="flex min-w-0 items-baseline gap-2 font-mono text-xs" title={path}>+ <span className="shrink-0 text-[var(--color-text-primary)] underline-offset-2 group-hover/row:underline">+ {name}+ </span>+ {dir && <span className="min-w-0 truncate text-[var(--color-text-tertiary)]">{dir}</span>}+ </span>+ );+}++const TD = "px-3 py-2.5";++export const HotspotRow = memo(function HotspotRow({+ hotspot: h,+ rank,+ showFixes,+ onSelect,+ onGeneratePrompt,+}: {+ hotspot: Hotspot;+ rank: number;+ showFixes: boolean;+ onSelect?: ((h: Hotspot) => void) | undefined;+ onGeneratePrompt?: ((h: Hotspot) => void) | undefined;+}) {+ const fix = fixOf(h);+ const score = h.temporal_hotspot_score;+ return (+ <tr+ {...(onSelect ? clickableRowProps(() => onSelect(h)) : {})}+ className={cn(+ "group/row border-b border-[var(--color-table-divider)] hover:bg-[var(--color-bg-elevated)] transition-colors",+ onSelect && CLICKABLE_ROW_CLS,+ )}+ >+ <td className={cn(TD, "text-[var(--color-text-tertiary)] tabular-nums text-xs")}>{rank}</td>+ <td className={cn(TD, "min-w-[200px] max-w-[440px]")}>+ <NameFirstPath path={h.file_path} />+ </td>+ <td className={cn(TD, "tabular-nums text-xs text-right")}>+ <span className="inline-flex items-center justify-end gap-1 text-[var(--color-text-secondary)]">+ {h.commit_count_90d}+ {/* Marked only where true: a column of arrows would mark the default. */}+ {h.accelerating && (+ <TrendingUp+ className="h-3 w-3 text-[var(--color-warning)]"+ aria-label="Accelerating"+ />+ )}+ </span>+ </td>+ {showFixes && (+ <td className={cn(TD, "tabular-nums text-xs text-right")}>+ {fix ? (+ <span+ className={cn(+ "inline-flex items-center justify-end gap-1",+ fix.magnet ? "text-[var(--color-error)]" : "text-[var(--color-text-secondary)]",+ )}+ title={fix.magnet ? `Bug magnet: ${fix.label}` : `Bug fixes: ${fix.label}`}+ >+ {fix.magnet && <Bug className="h-3 w-3 shrink-0" />}+ {fix.count}+ {/* The magnet emphasis never travels without its age. */}+ {fix.magnet && <span className="text-[10px] font-normal">{fix.age}</span>}+ </span>+ ) : (+ <span className="text-[var(--color-text-tertiary)]">—</span>+ )}+ </td>+ )}+ <td className={cn(TD, "hidden lg:table-cell")}>+ <div className="flex items-center gap-2">+ <ChurnBar percentile={h.churn_percentile} className="w-16" tone="neutral" />+ <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums w-8">+ {Math.round(h.churn_percentile)}%+ </span>+ </div>+ </td>+ <td className={cn(TD, "tabular-nums text-xs text-right")}>+ {score != null ? (+ <span className="inline-flex items-center justify-end gap-1 text-[var(--color-text-secondary)]">+ <Flame className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />+ {score.toFixed(2)}+ </span>+ ) : (+ <span className="text-[var(--color-text-tertiary)]">—</span>+ )}+ </td>+ <td className={cn(TD, "hidden md:table-cell")}>+ {/* Only a sole owner is marked; zero means no attributable history. */}+ <span+ className={cn(+ "text-xs tabular-nums",+ h.bus_factor === 1 ? "text-[var(--color-warning)]" : "text-[var(--color-text-secondary)]",+ )}+ >+ {h.bus_factor}+ </span>+ </td>+ <td className={cn(TD, "text-xs tabular-nums hidden lg:table-cell")}>+ <span className="text-[var(--color-success)]">+{formatLOC(h.lines_added_90d)}</span>{" "}+ <span className="text-[var(--color-error)]">-{formatLOC(h.lines_deleted_90d)}</span>+ </td>+ <td className={cn(TD, "text-xs text-[var(--color-text-secondary)] hidden md:table-cell")}>+ {h.primary_owner ?? "—"}+ </td>+ <td className={cn(TD, "text-right")} onClick={(e) => e.stopPropagation()}>+ <div className="flex items-center justify-end gap-1">+ {h.is_stable && <Badge variant="fresh">Stable</Badge>}+ {onGeneratePrompt && (+ <RowPromptAction subject={h.file_path} onClick={() => onGeneratePrompt(h)} />+ )}+ </div>+ </td>+ </tr>+ );+});diff --git a/packages/ui/src/git/hotspot-table.tsx b/packages/ui/src/git/hotspot-table.tsxindex 21d5292d4..23400643a 100644--- a/packages/ui/src/git/hotspot-table.tsx+++ b/packages/ui/src/git/hotspot-table.tsx@@ -1,245 +1,169 @@"use client";import * as React from "react";-import { useState, useMemo } from "react";-import { TrendingUp, TrendingDown, Search, Flame, Bug, ArrowUpDown, ArrowUp, ArrowDown, ChevronRight, ChevronDown } from "lucide-react";-import { Badge } from "../ui/badge";-import { Input } from "../ui/input";+import { useMemo } from "react";+import { ArrowDown, ArrowUp, ArrowUpDown } from "lucide-react";+import type {+ Hotspot,+ HotspotFacets,+ HotspotFilter,+ HotspotOrder,+ HotspotSort,+} from "@repowise-dev/types/git";import { EmptyState } from "../shared/empty-state";import { ResultsFooter } from "../shared/results-footer";-import { AiPromptButton } from "../health/ai-prompt-button";-import { ChurnBar } from "./churn-bar";-import { formatLOC } from "../lib/format";-import { summarizeFixHistory } from "../lib/fix-history";-import { cn } from "../lib/cn";import { useVirtualRows } from "../shared/virtualized-table";-import { clickableRowProps, CLICKABLE_ROW_CLS } from "../shared/responsive-table";-import type { Hotspot } from "@repowise-dev/types/git";+import { HotspotRow } from "./hotspot-row";+import { HotspotToolbar } from "./hotspot-toolbar";-/**- * Collapsed main-row height (px), used as the initial virtualization estimate.- * Real heights — including expanded detail rows — are measured at runtime via- * `measureElement`, so this only affects the first paint and off-screen spacers.- */-const ESTIMATED_ROW_HEIGHT = 44;+/** Row height (px); rows are one line, so the estimate is the height. */+const ROW_HEIGHT = 44;++export interface HotspotSortState {+ key: HotspotSort;+ order: HotspotOrder;+}++export const DEFAULT_HOTSPOT_SORT: HotspotSortState = { key: "score", order: "desc" };interface HotspotTableProps {+ /** The loaded rows, in the server's order. */hotspots: Hotspot[];- /**- * Kept for callers that still pass them. The rows carried a Graph / Docs /- * Blast Radius menu built from these; a table already sorted by risk did not- * need three links per row competing with the row's own click, so it is- * gone and these no longer do anything.- */- repoId?: string;- linkPrefix?: string;- /**- * Optional row-click handler. When set, the entire row becomes clickable and- * the host can render a FileCardDialog (or similar) populated from the- * passed Hotspot. The action buttons in the rightmost column are still- * 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.- */+ /** Rows the current filter and search match (server count). */total?: number;+ /** Server counts per filter over the searched set; chips show only with these. */+ facets?: HotspotFacets;+ query?: string;+ /** Called with the settled search (debounced here); the host fetches. */+ onQueryChange?: (q: string) => void;+ filter?: HotspotFilter;+ onFilterChange?: (filter: HotspotFilter) => void;+ sort?: HotspotSortState;+ /** Sortable headers render only when the host can sort on the server. */+ onSortChange?: (sort: HotspotSortState) => void;hasMore?: boolean;loadingMore?: boolean;onLoadMore?: () => void;+ /** Row click: the host opens its file card. */+ onSelect?: (hotspot: Hotspot) => void;+ /** The row's agent prompt (quiet, on hover/focus). */+ onGeneratePrompt?: (hotspot: Hotspot) => void;+ /** One prompt over the listed rows ("Copy prompt for these N"). */+ onGenerateBatchPrompt?: (rows: Hotspot[]) => void;+ /** The header prompt's label; English "Copy prompt for these N" by default. */+ batchPromptLabel?: (count: number) => string;/**- * When provided, each row shows a chevron toggle that expands an inline- * panel below it — used for hotspot → "top symbols in this file" drill-down.- * The host owns data-fetching and renders the panel body.+ * Accepted and ignored, for callers that still pass them: the row's own+ * click opens the file card, which already lists the file's top symbols and+ * links, so a per-row menu and an inline symbols expand were competing+ * actions. Remove from hosts when they next port.*/+ repoId?: string;+ linkPrefix?: string;renderExpandedRow?: (hotspot: Hotspot) => React.ReactNode;- /** When set, each row shows an "AI stabilize" action that calls this. */- onGeneratePrompt?: (hotspot: Hotspot) => void;}-type Filter = "all" | "hot" | "risk" | "accelerating" | "magnet";-type SortKey = "trend" | "churn" | "commits" | "fixes";-type SortDir = "asc" | "desc";--/** A row's fix history, or null when it has none. */-const fixOf = (h: Hotspot) =>- summarizeFixHistory(h.prior_defect_count, h.last_fix_at, h.bug_magnet);--function SortIcon({ column, sortKey, sortDir }: { column: SortKey; sortKey: SortKey; sortDir: SortDir }) {- if (column !== sortKey) return <ArrowUpDown className="inline h-3 w-3 ml-1 opacity-60" />;- return sortDir === "desc"- ? <ArrowDown className="inline h-3 w-3 ml-1" />- : <ArrowUp className="inline h-3 w-3 ml-1" />;+function SortHeader({+ column,+ label,+ title,+ sort,+ onSortChange,+ align = "right",+ className,+}: {+ column: HotspotSort;+ label: string;+ title?: string;+ sort: HotspotSortState;+ onSortChange?: ((s: HotspotSortState) => void) | undefined;+ align?: "left" | "right";+ className?: string;+}) {+ const active = sort.key === column;+ const ariaSort = active ? (sort.order === "asc" ? "ascending" : "descending") : "none";+ const Icon = !active ? ArrowUpDown : sort.order === "desc" ? ArrowDown : ArrowUp;+ return (+ <th+ scope="col"+ aria-sort={onSortChange ? ariaSort : undefined}+ title={title}+ className={`px-3 py-2.5 ${align === "left" ? "text-left" : "text-right"} text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider ${className ?? ""}`}+ >+ {onSortChange ? (+ <button+ type="button"+ className="cursor-pointer select-none uppercase tracking-wider font-medium hover:text-[var(--color-text-secondary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] rounded"+ onClick={() =>+ onSortChange({+ key: column,+ order: active && sort.order === "desc" ? "asc" : "desc",+ })+ }+ >+ {label}+ <Icon className={`inline h-3 w-3 ml-1 ${active ? "" : "opacity-60"}`} />+ </button>+ ) : (+ label+ )}+ </th>+ );}-function ariaSortFor(column: SortKey, sortKey: SortKey, sortDir: SortDir): "none" | "ascending" | "descending" {- if (column !== sortKey) return "none";- return sortDir === "asc" ? "ascending" : "descending";-}+const TH = "px-3 py-2.5 text-left text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider";export function HotspotTable({hotspots,- onSelect,total,+ facets,+ query = "",+ onQueryChange,+ filter = "all",+ onFilterChange,+ sort = DEFAULT_HOTSPOT_SORT,+ onSortChange,hasMore,loadingMore,onLoadMore,- renderExpandedRow,+ onSelect,onGeneratePrompt,+ onGenerateBatchPrompt,+ batchPromptLabel,}: HotspotTableProps) {- const expandable = !!renderExpandedRow;- const [expanded, setExpanded] = useState<Set<string>>(() => new Set());- const toggleExpand = (filePath: string) => {- setExpanded((prev) => {- const next = new Set(prev);- if (next.has(filePath)) next.delete(filePath);- else next.add(filePath);- return next;- });- };- const [search, setSearch] = useState("");- const [filter, setFilter] = useState<Filter>("all");- const [sortKey, setSortKey] = useState<SortKey>("trend");- const [sortDir, setSortDir] = useState<SortDir>("desc");-- function handleSort(key: SortKey) {- if (key === sortKey) {- setSortDir((d) => (d === "desc" ? "asc" : "desc"));- } else {- setSortKey(key);- setSortDir("desc");- }- }-- const filtered = useMemo(() => {- let items = hotspots;-- if (search) {- const q = search.toLowerCase();- items = items.filter(- (h) =>- h.file_path.toLowerCase().includes(q) ||- (h.primary_owner ?? "").toLowerCase().includes(q),- );- }-- switch (filter) {- case "hot":- items = items.filter((h) => h.is_hotspot);- break;- case "risk":- items = items.filter((h) => h.bus_factor <= 1);- break;- case "accelerating":- items = items.filter((h) => h.commit_count_30d * 3 > h.commit_count_90d);- break;- case "magnet":- items = items.filter((h) => fixOf(h)?.magnet);- break;- }-- const sign = sortDir === "desc" ? -1 : 1;- items = [...items].sort((a, b) => {- if (sortKey === "trend") {- const av = a.temporal_hotspot_score ?? -1;- const bv = b.temporal_hotspot_score ?? -1;- return sign * (av - bv);- }- if (sortKey === "churn") return sign * (a.churn_percentile - b.churn_percentile);- if (sortKey === "commits") return sign * (a.commit_count_90d - b.commit_count_90d);- if (sortKey === "fixes")- return sign * ((a.prior_defect_count ?? 0) - (b.prior_defect_count ?? 0));- return 0;- });-- return items;- }, [hotspots, search, filter, sortKey, sortDir]);-- // Memoize the filter chips' counts so the three full `hotspots` scans only- // run when the dataset changes, not on every keystroke / sort / expand.- const filters: { key: Filter; label: string; count: number }[] = useMemo(() => {- const base: { key: Filter; label: string; count: number }[] = [- { key: "all", label: "All", count: hotspots.length },- { key: "hot", label: "Hot", count: hotspots.filter((h) => h.is_hotspot).length },- { key: "risk", label: "Bus factor risk", count: hotspots.filter((h) => h.bus_factor <= 1).length },- { key: "accelerating", label: "Accelerating", count: hotspots.filter((h) => h.commit_count_30d * 3 > h.commit_count_90d).length },- ];- // A repo with no counted magnets gets no chip at all rather than a zero.- const magnets = hotspots.filter((h) => fixOf(h)?.magnet).length;- if (magnets > 0) base.push({ key: "magnet", label: "Bug magnet", count: magnets });- return base;- }, [hotspots]);-+ const listed = total ?? hotspots.length;// Churn and bug-fix history are different claims, so the Fixes column only- // appears once the index actually carries fix data for this set of files.- const hasFixData = useMemo(- () => hotspots.some((h) => (h.prior_defect_count ?? 0) > 0),- [hotspots],+ // appears once the index carries fix data for this set of files: anywhere in+ // the searched set (the facet), not only on the loaded page.+ const showFixes = useMemo(+ () => (facets?.with_fixes ?? 0) > 0 || hotspots.some((h) => (h.prior_defect_count ?? 0) > 0),+ [facets, hotspots],);-- // Window the tbody rows. Rows are variable-height (an expanded row adds a- // second <tr>), so we drive the windowing with the lower-level hook and let- // it MEASURE real heights via `measureElement`. To capture the *combined*- // height of a logical row (main <tr> + optional expanded <tr>) within valid- // table semantics, each logical row is rendered as its own <tbody> — a- // <table> may contain multiple <tbody>s — and the measured/`data-index`d- // element is that <tbody>, so an expanded row's full height is tracked.- const {- scrollRef,- virtualRows,- paddingTop,- paddingBottom,- measureElement,- } = useVirtualRows({- count: filtered.length,- estimateSize: ESTIMATED_ROW_HEIGHT,+ const { scrollRef, virtualRows, paddingTop, paddingBottom } = useVirtualRows({+ count: hotspots.length,+ estimateSize: ROW_HEIGHT,});- if (hotspots.length === 0) {- return (- <EmptyState- title="No hotspots found"- description="All files look stable — great work!"- />- );+ const narrowed = query !== "" || filter !== "all";+ if (hotspots.length === 0 && !narrowed) {+ return <EmptyState title="No hotspots found" description="No file stands out for recent change." />;}return (<div className="space-y-3">- <div className="flex flex-wrap items-center gap-2">- <div className="relative">- <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />- <Input- placeholder="Search files or owners…"- value={search}- onChange={(e) => setSearch(e.target.value)}- className="pl-8 h-8 w-full sm:w-56 text-xs"- />- </div>- <div className="flex flex-wrap rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">- {filters.map((f) => (- <button- key={f.key}- onClick={() => setFilter(f.key)}- className={cn(- "px-2.5 py-1.5 font-medium transition-colors",- filter === f.key- ? "bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"- : "bg-transparent text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]",- )}- >- {f.label}- <span className="ml-1 text-[10px] opacity-70">({f.count})</span>- </button>- ))}- </div>- </div>+ <HotspotToolbar+ query={query}+ onQueryChange={onQueryChange}+ filter={filter}+ onFilterChange={onFilterChange}+ facets={facets}+ total={listed}+ onPromptForRows={onGenerateBatchPrompt ? () => onGenerateBatchPrompt(hotspots) : undefined}+ batchPromptLabel={batchPromptLabel}+ />- {filtered.length === 0 ? (- <EmptyState title="No matches" description="Try adjusting your search or filters." />+ {hotspots.length === 0 ? (+ <EmptyState title="No matches" description="Try another search or filter." />) : (<divref={scrollRef}@@ -249,264 +173,88 @@ export function HotspotTable({<table className="w-full min-w-[760px] text-sm"><thead className="sticky top-0 z-10 bg-[var(--color-bg-surface)]"><tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">- {expandable && <th className="w-6 px-1" aria-hidden="true" />}- <th className="px-3 py-2.5 text-left text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-8">+ <th scope="col" className={`${TH} w-10`} title="Place by hotspot score">#</th>- <th className="px-3 py-2.5 text-left text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ <th scope="col" className={TH}>File</th>- <th- scope="col"- aria-sort={ariaSortFor("commits", sortKey, sortDir)}- className="px-3 py-2.5 text-right text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-24"- >- <button- type="button"- className="cursor-pointer select-none uppercase tracking-wider font-medium hover:text-[var(--color-text-secondary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] rounded"- onClick={() => handleSort("commits")}- >- Commits 90d<SortIcon column="commits" sortKey={sortKey} sortDir={sortDir} />- </button>- </th>- {hasFixData && (- <th- scope="col"- aria-sort={ariaSortFor("fixes", sortKey, sortDir)}- className="px-3 py-2.5 text-right text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-24"- >- <button- type="button"- className="cursor-pointer select-none uppercase tracking-wider font-medium hover:text-[var(--color-text-secondary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] rounded"- onClick={() => handleSort("fixes")}- title="Bug-fix commits that touched this file in the trailing defect window. Churn counts every change; this counts only the ones that fixed something."- >- Fixes<SortIcon column="fixes" sortKey={sortKey} sortDir={sortDir} />- </button>- </th>+ <SortHeader column="commits" label="Commits 90d" sort={sort} onSortChange={onSortChange} className="w-28" />+ {showFixes && (+ <SortHeader+ column="fixes"+ label="Fixes"+ title="Bug-fix commits that touched this file in the trailing defect window. Churn counts every change; this counts only the ones that fixed something."+ sort={sort}+ onSortChange={onSortChange}+ className="w-24"+ />)}- <th- scope="col"- aria-sort={ariaSortFor("churn", sortKey, sortDir)}- className="px-3 py-2.5 text-left text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-32 hidden lg:table-cell"- >- <button- type="button"- className="cursor-pointer select-none uppercase tracking-wider font-medium hover:text-[var(--color-text-secondary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] rounded"- onClick={() => handleSort("churn")}- >- Churn<SortIcon column="churn" sortKey={sortKey} sortDir={sortDir} />- </button>+ <SortHeader+ column="churn"+ label="Churn"+ align="left"+ sort={sort}+ onSortChange={onSortChange}+ className="w-32 hidden lg:table-cell"+ />+ <SortHeader+ column="score"+ label="Score"+ title="Hotspot score: commits weighted by recency (180-day half-life). The ranking."+ sort={sort}+ onSortChange={onSortChange}+ className="w-24"+ />+ <th scope="col" className={`${TH} w-20 hidden md:table-cell`}>+ Bus factor</th>- <th- scope="col"- aria-sort={ariaSortFor("trend", sortKey, sortDir)}- className="px-3 py-2.5 text-right text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-24"- >- <button- type="button"- className="cursor-pointer select-none uppercase tracking-wider font-medium hover:text-[var(--color-text-secondary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] rounded"- onClick={() => handleSort("trend")}- title="Exponential decay score weighting recent commits more heavily (180-day half-life)"- >- Trend<SortIcon column="trend" sortKey={sortKey} sortDir={sortDir} />- </button>- </th>- <th className="px-3 py-2.5 text-left text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-20 hidden md:table-cell">- Bus Factor- </th>- <th className="px-3 py-2.5 text-left text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-24 hidden lg:table-cell">+ <th scope="col" className={`${TH} w-24 hidden lg:table-cell`}>Lines ±90d</th>- <th className="px-3 py-2.5 text-left text-[11px] font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider hidden md:table-cell">+ <th scope="col" className={`${TH} hidden md:table-cell`}>Owner</th>- <th className="px-3 py-2.5 w-20" />+ <th scope="col" className="px-3 py-2.5 w-0">+ <span className="sr-only">Actions</span>+ </th></tr></thead>- {paddingTop > 0 && (- <tbody aria-hidden>- <tr>+ <tbody>+ {paddingTop > 0 && (+ <tr aria-hidden><td style={{ height: paddingTop, padding: 0, border: 0 }} /></tr>- </tbody>- )}- {virtualRows.map((vr) => {- const h = filtered[vr.index];- if (h === undefined) return null;- const i = vr.index;- const accelerating = h.commit_count_30d * 3 > h.commit_count_90d;- const fix = fixOf(h);- const trendScore = h.temporal_hotspot_score;- const isExpanded = expanded.has(h.file_path);- return (- <tbody key={h.file_path} ref={measureElement} data-index={i}>- <tr- {...(onSelect ? clickableRowProps(() => onSelect(h)) : {})}- className={cn(- "border-b border-[var(--color-table-divider)] hover:bg-[var(--color-bg-elevated)] transition-colors group",- !isExpanded && "last:border-0",- onSelect && CLICKABLE_ROW_CLS,- )}- >- {expandable && (- <td- className="px-1 py-2.5 align-middle"- onClick={(e) => {- e.stopPropagation();- toggleExpand(h.file_path);- }}- >- <button- type="button"- aria-label={isExpanded ? "Collapse symbols" : "Expand symbols"}- aria-expanded={isExpanded}- className="flex h-5 w-5 items-center justify-center rounded text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"- >- {isExpanded ? (- <ChevronDown className="h-3.5 w-3.5" />- ) : (- <ChevronRight className="h-3.5 w-3.5" />- )}- </button>- </td>- )}- <td className="px-3 py-2.5 text-[var(--color-text-tertiary)] tabular-nums text-xs">- {i + 1}- </td>- <td className="px-3 py-2.5 font-mono text-xs text-[var(--color-text-primary)] min-w-[180px] max-w-[420px]">- <span className="block truncate group-hover:underline underline-offset-2" title={h.file_path}>{h.file_path}</span>- </td>- <td className="px-3 py-2.5 tabular-nums text-xs text-right">- <span className="inline-flex items-center justify-end gap-1">- <span className="text-[var(--color-text-secondary)]">- {h.commit_count_90d}- </span>- {accelerating ? (- <TrendingUp className="h-3 w-3 text-[var(--color-error)]" />- ) : (- <TrendingDown className="h-3 w-3 text-[var(--color-success)]" />- )}- </span>- </td>- {hasFixData && (- <td className="px-3 py-2.5 tabular-nums text-xs text-right">- {fix ? (- <span- className={cn(- "inline-flex items-center justify-end gap-1",- fix.magnet- ? "text-[var(--color-error)]"- : "text-[var(--color-text-secondary)]",- )}- title={- fix.magnet- ? `Bug magnet: ${fix.label}`- : `Bug fixes: ${fix.label}`- }- >- <Bug className="h-3 w-3 shrink-0" />- {fix.count}- {/* The magnet emphasis never travels without its age. */}- {fix.magnet && (- <span className="text-[10px] font-normal">{fix.age}</span>- )}- </span>- ) : (- <span className="text-[var(--color-text-tertiary)]">—</span>- )}- </td>- )}- <td className="px-3 py-2.5 hidden lg:table-cell">- <div className="flex items-center gap-2">- <ChurnBar percentile={h.churn_percentile} className="w-16" tone="neutral" />- <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums w-8">- {Math.round(h.churn_percentile)}%- </span>- </div>- </td>- <td className="px-3 py-2.5 tabular-nums text-xs text-right">- <span className="inline-flex items-center justify-end gap-1">- {trendScore != null ? (- <>- <Flame className={cn("h-3 w-3 shrink-0", trendScore >= 5 ? "text-[var(--color-error)]" : trendScore >= 2 ? "text-[var(--color-warning)]" : "text-[var(--color-text-tertiary)]")} />- <span className="text-[var(--color-text-secondary)]">- {trendScore.toFixed(2)}- </span>- </>- ) : (- <span className="text-[var(--color-text-tertiary)]">—</span>- )}- </span>- </td>- <td className="px-3 py-2.5 hidden md:table-cell">- {/* A number, not a badge. A tinted pill on every row- made a column of ordinary counts look like a column- of alerts; only a sole owner is worth marking, and- the colour alone says it. */}- <span- className={`text-xs tabular-nums ${- h.bus_factor <= 1- ? "text-[var(--color-warning)]"- : "text-[var(--color-text-secondary)]"- }`}- >- {h.bus_factor}- </span>- </td>- <td className="px-3 py-2.5 text-xs tabular-nums hidden lg:table-cell">- <span className="text-[var(--color-success)]">+{formatLOC(h.lines_added_90d)}</span>- {" "}- <span className="text-[var(--color-error)]">-{formatLOC(h.lines_deleted_90d)}</span>- </td>- <td className="px-3 py-2.5 text-xs text-[var(--color-text-secondary)] hidden md:table-cell">- {h.primary_owner ?? "—"}- </td>- <td className="px-3 py-2.5" onClick={(e) => e.stopPropagation()}>- <div className="flex items-center gap-1">- {/* No "Hot" badge: every row in a hotspot table is- one, so it labelled nothing. "Stable" still earns- its place — it is the row that is not. */}- {h.is_stable && <Badge variant="fresh">Stable</Badge>}- {onGeneratePrompt && (- <AiPromptButton- variant="icon"- label="AI stabilization prompt"- onClick={() => onGeneratePrompt(h)}- />- )}- </div>- </td>- </tr>- {expandable && isExpanded && (- <tr className="border-b border-[var(--color-table-divider)] bg-[var(--color-bg-wash)] last:border-0">- <td className="px-1" />- <td colSpan={hasFixData ? 10 : 9} className="px-3 py-3">- {renderExpandedRow!(h)}- </td>- </tr>- )}- </tbody>- );- })}- {paddingBottom > 0 && (- <tbody aria-hidden>- <tr>+ )}+ {virtualRows.map((vr) => {+ const h = hotspots[vr.index];+ if (h === undefined) return null;+ return (+ <HotspotRow+ key={h.file_path}+ hotspot={h}+ rank={h.rank ?? vr.index + 1}+ showFixes={showFixes}+ onSelect={onSelect}+ onGeneratePrompt={onGeneratePrompt}+ />+ );+ })}+ {paddingBottom > 0 && (+ <tr aria-hidden><td style={{ height: paddingBottom, padding: 0, border: 0 }} /></tr>- </tbody>- )}+ )}+ </tbody></table>- {total != null && (- <ResultsFooter- shown={filtered.length}- total={total}- hasMore={!!hasMore}- loading={loadingMore}- onLoadMore={onLoadMore}- noun="hotspots"- />- )}+ <ResultsFooter+ shown={hotspots.length}+ total={listed}+ hasMore={!!hasMore}+ loading={loadingMore}+ onLoadMore={onLoadMore}+ noun="hotspots"+ /></div>)}</div>diff --git a/packages/ui/src/git/hotspot-toolbar.tsx b/packages/ui/src/git/hotspot-toolbar.tsxnew file mode 100644index 000000000..020488d20--- /dev/null+++ b/packages/ui/src/git/hotspot-toolbar.tsx@@ -0,0 +1,136 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { Search } from "lucide-react";+import type { HotspotFacets, HotspotFilter } from "@repowise-dev/types/git";+import { Input } from "../ui/input";+import { cn } from "../lib/cn";+import { useDebounce } from "../hooks/use-debounce";+import { PromptForRowsButton } from "../health/row-prompt-action";++/** Wait after the last keystroke before the search goes to the server. */+const SEARCH_DEBOUNCE_MS = 250;++const CHIPS: { key: HotspotFilter; label: string; title?: string }[] = [+ { key: "all", label: "All" },+ {+ key: "bus_factor_1",+ label: "Bus factor 1",+ title: "One person holds the knowledge. Files with no attributable history are not counted.",+ },+ {+ key: "accelerating",+ label: "Accelerating",+ title: "More commits in the last 30 days than its 90-day pace, on files older than 90 days.",+ },+ { key: "bug_magnet", label: "Bug magnet", title: "Repeated recent bug fixes." },+];++/** The chips a facet set offers: a filter with nothing in it is not offered,+ * unless it is the active one (the reader needs it to see what is applied). */+export function hotspotChips(facets: HotspotFacets, active: HotspotFilter = "all") {+ return CHIPS.filter((c) => c.key === "all" || c.key === active || facets[c.key] > 0).map((c) => ({+ ...c,+ count: c.key === "all" ? facets.total : facets[c.key],+ }));+}++/** Search box that reports a settled query, and follows the URL when it changes. */+function SearchBox({ query, onChange }: { query: string; onChange: (q: string) => void }) {+ const [draft, setDraft] = useState(query);+ const settled = useDebounce(draft, SEARCH_DEBOUNCE_MS);+ // The last value sent up: its echo back through the URL must not overwrite+ // what the reader has typed since. Only an outside change resets the box.+ const sent = useRef(query);+ useEffect(() => {+ if (query !== sent.current) {+ sent.current = query;+ setDraft(query);+ }+ }, [query]);+ useEffect(() => {+ if (settled === sent.current) return;+ sent.current = settled;+ onChange(settled);+ // Keyed on the settled value alone; `onChange` is the host's latest setter.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [settled]);+ return (+ <div className="relative">+ <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />+ <Input+ type="search"+ aria-label="Search hotspots by file or owner"+ placeholder="Search files or owners…"+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ className="pl-8 h-8 w-full sm:w-56 text-xs"+ />+ </div>+ );+}++export function HotspotToolbar({+ query,+ onQueryChange,+ filter,+ onFilterChange,+ facets,+ total,+ onPromptForRows,+ batchPromptLabel,+}: {+ query: string;+ onQueryChange?: ((q: string) => void) | undefined;+ filter: HotspotFilter;+ onFilterChange?: ((f: HotspotFilter) => void) | undefined;+ facets?: HotspotFacets | undefined;+ /** Rows the current filter and search match. */+ total: number;+ onPromptForRows?: (() => void) | undefined;+ batchPromptLabel?: ((count: number) => string) | undefined;+}) {+ return (+ <div className="flex flex-wrap items-center gap-2">+ {onQueryChange && <SearchBox query={query} onChange={onQueryChange} />}+ {facets && onFilterChange && (+ <div+ role="group"+ aria-label="Filter hotspots"+ className="flex flex-wrap rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs"+ >+ {hotspotChips(facets, filter).map((c) => (+ <button+ key={c.key}+ type="button"+ aria-pressed={filter === c.key}+ title={c.title}+ onClick={() => onFilterChange(c.key)}+ className={cn(+ "px-2.5 py-1.5 font-medium transition-colors",+ filter === c.key+ ? "bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"+ : "bg-transparent text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]",+ )}+ >+ {c.label}+ <span className="ml-1.5 tabular-nums text-[10px] opacity-70">+ {c.key === "all"+ ? c.count.toLocaleString()+ : `${c.count.toLocaleString()} of ${facets.total.toLocaleString()}`}+ </span>+ </button>+ ))}+ </div>+ )}+ {onPromptForRows && (+ <PromptForRowsButton+ count={total}+ onClick={onPromptForRows}+ {...(batchPromptLabel ? { label: batchPromptLabel } : {})}+ className="sm:ml-auto"+ />+ )}+ </div>+ );+}diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.tsindex c5f71924d..9396ab8a1 100644--- a/packages/ui/src/health/ai-prompt-builder.ts+++ b/packages/ui/src/health/ai-prompt-builder.ts@@ -53,6 +53,8 @@ export {} from "./ai-prompts/security-prompt";export {buildHotspotAiPrompt,+ buildHotspotBatchAiPrompt,+ type BuildHotspotBatchPromptOptions,type BuildHotspotPromptOptions,type HotspotPromptInput,} from "./ai-prompts/hotspot-prompt";diff --git a/packages/ui/src/health/ai-prompts/hotspot-prompt.ts b/packages/ui/src/health/ai-prompts/hotspot-prompt.tsindex e039023e0..c15276191 100644--- a/packages/ui/src/health/ai-prompts/hotspot-prompt.ts+++ b/packages/ui/src/health/ai-prompts/hotspot-prompt.ts@@ -100,3 +100,55 @@ export function buildHotspotAiPrompt({explorationCloser(flavor, h.file_path, "hotspot"),]);}++/** Files listed in a batch prompt; the rest are counted, not dropped silently. */+const MAX_BATCH_FILES = 25;++export interface BuildHotspotBatchPromptOptions {+ rows: HotspotPromptInput[];+ /** Every row the filters match, when more exist than were loaded. */+ total?: number;+ flavor?: AiPromptFlavor;+ repoName?: string;+}++/** One prompt over several hotspots, e.g. every row the current filters show. */+export function buildHotspotBatchAiPrompt({+ rows,+ total = rows.length,+ flavor = "generic",+ repoName,+}: BuildHotspotBatchPromptOptions): string {+ const only = rows.length === 1 && total === 1 ? rows[0] : undefined;+ if (only) return buildHotspotAiPrompt({ hotspot: only, flavor, ...(repoName ? { repoName } : {}) });+ const shown = rows.slice(0, MAX_BATCH_FILES);+ const hidden = total - shown.length;++ return joinSections([+ FLAVOR_PREAMBLE[flavor],+ "",+ `## Hotspots to stabilize${repoSuffix(repoName)}`,+ "",+ "Ranked by hotspot score (recent change weighted most), highest first.",+ "",+ bulletList(+ shown.map(+ (h) =>+ `\`${h.file_path}\` — ${h.commit_count_90d ?? 0} commits in 90 days${+ h.bus_factor === 1 ? ", one person holds the knowledge" : ""+ }${h.prior_defect_count ? `, ${h.prior_defect_count} prior bug fixes` : ""}`,+ ),+ ),+ hidden > 0 ? `…and ${hidden} more in the same list (open Code Health in repowise for all of them).` : "",+ "",+ "## Your task",+ "",+ bulletList([+ "Work one file at a time, highest first, and finish each before starting the next.",+ "For each: find why it keeps changing, then make the smallest behaviour-preserving change that makes the next change cheaper, with tests that protect it.",+ "Stop and report after each file with what you changed and what you would do next.",+ ]),+ "",+ explorationCloser(flavor, shown[0]?.file_path ?? "", "hotspot"),+ ]);+}diff --git a/packages/web/messages/en.json b/packages/web/messages/en.jsonindex 59fd47d71..221da4693 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -1259,11 +1259,14 @@"codeHealth": {"hotspots": {"title": "Hotspots",- "description": "Ranked by change frequency and prior bug fixes, mined from full git history. The danger is not churn on its own. It is a file that changes constantly and only one person understands.",+ "description": "Ranked by hotspot score: every commit counts, recent ones most (180-day half-life). Same scope as the map above. The danger is not churn on its own. It is a file that changes constantly and only one person understands.","commitHistory": "Commit history","loadFailed": "Couldn't load hotspots. Run a sync to mine git history for this repo.","promptTitle": "AI stabilization prompt",- "promptDescription": "A ready-to-paste prompt that has your AI agent diagnose why this file churns and propose changes that make it cheaper to maintain."+ "promptDescription": "A ready-to-paste prompt that has your AI agent diagnose why this file churns and propose changes that make it cheaper to maintain.",+ "batchPromptAction": "Copy prompt for these {count}",+ "batchPromptTitle": "Prompt for {count, plural, one {# hotspot} other {# hotspots}}",+ "batchPromptDescription": "One prompt that has your agent work through these hotspots one at a time, highest score first."}},"commits": {diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex 1688a1b74..fd021ac38 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -1259,11 +1259,14 @@"codeHealth": {"hotspots": {"title": "热点",- "description": "按变更频率与历史缺陷修复排序,从完整 git 历史中挖掘。危险的不只是频繁变更,而是那种频繁改动却只有一个人看得懂的文件。",+ "description": "按热点分数排序:每次提交都计入,越近的权重越高(半衰期 180 天)。范围与上方地图一致。危险的不只是频繁变更,而是那种频繁改动却只有一个人看得懂的文件。","commitHistory": "提交历史","loadFailed": "无法加载热点。请运行一次同步,为该代码仓库挖掘 git 历史。","promptTitle": "AI 稳定化提示词",- "promptDescription": "一段可直接粘贴的提示词,让 AI 智能体诊断该文件为何频繁变更,并提出降低维护成本的改动建议。"+ "promptDescription": "一段可直接粘贴的提示词,让 AI 智能体诊断该文件为何频繁变更,并提出降低维护成本的改动建议。",+ "batchPromptAction": "为这 {count} 项复制提示词",+ "batchPromptTitle": "{count} 个热点的提示词",+ "batchPromptDescription": "一段提示词,让智能体按分数从高到低逐个处理这些热点。"}},"commits": {diff --git a/packages/web/src/components/code-health/hotspots-section.tsx b/packages/web/src/components/code-health/hotspots-section.tsxindex a805570b4..6c055bbe5 100644--- a/packages/web/src/components/code-health/hotspots-section.tsx+++ b/packages/web/src/components/code-health/hotspots-section.tsx@@ -3,69 +3,83 @@/*** Hotspots, as a section under the Code Health map rather than a tab of its own.*- * The tab it replaces rendered a *second* galaxy map — same component, churn- * lens, 420px — directly beneath the page's 720px one, plus five bordered chart- * cards at identical weight. Churn is now a lens on the single map, which is- * where it always belonged, so what survives here is only what the lens cannot- * say: which hot files have a single owner, and the ranked table itself.- *- * Four charts did not survive. The commit-category donut spent four unrelated- * hues on four categories, which is the exact pattern the colour rule exists to- * stop. The churn histogram, the risk-distribution chart and the churn-vs-bus-- * factor scatter all restate columns the table below them already shows, in a- * form you cannot sort.- *- * The scatter was the close call, and it lost on its own data. Its whole point- * is a top-right danger zone — changes constantly, only one person understands- * it — but on a real repo almost every hotspot sits at bus factor 1 and the- * 100th churn percentile, so the danger zone is the entire plot and the shape- * carries nothing. The table says it better: a `BUS FACTOR` column you can sort- * and a "Bus factor risk" filter chip that names the set outright.+ * Churn is a lens on the map; what this section adds is the ranked list itself,+ * in the map's scope (tests, docs examples, build, vendored and generated files+ * held out unless `?include=` brings them back). The server searches, filters,+ * sorts and counts, so every chip and total describes the whole list, not the+ * page that happens to be loaded. Search, filter and sort live in the URL.*/-import { useState } from "react";-import useSWR from "swr";+import { useCallback } from "react";+import { useTranslations } from "next-intl";+import Link from "next/link";import { OverviewSection, SectionLink } from "@repowise-dev/ui/overview";import { HotspotTable } from "@repowise-dev/ui/git/hotspot-table";-import { AiPromptModal, buildHotspotAiPrompt, fileChatContext } from "@repowise-dev/ui/health";+import {+ buildHotspotAiPrompt,+ buildHotspotBatchAiPrompt,+ fileChatContext,+ useAiPromptAction,+ type HotspotPromptInput,+} from "@repowise-dev/ui/health";import { Skeleton } from "@repowise-dev/ui/ui/skeleton";-import { useTranslations } from "next-intl";import { hotspotToFileCard } from "@repowise-dev/ui/shared/file-card";import type { Hotspot } from "@repowise-dev/types/git";-import Link from "next/link";import { useFileCardHost } from "@/components/shared/file-card-host";-import { HotspotTopSymbolsHost } from "@/components/symbols/hotspot-top-symbols-host";-import { SymbolDrawerWrapper } from "@/components/symbols/symbol-drawer-wrapper";-import { getHotspotsPage } from "@/lib/api/git";-import type { Paginated, SymbolResponse, HotspotResponse } from "@/lib/api/types";+import { useHotspotList } from "./use-hotspot-list";-const PAGE_SIZE = 100;-const PAGE_MAX = 500;+/** The fields the hotspot prompt reads; the row carries more than it needs. */+function promptInput(h: Hotspot): HotspotPromptInput {+ return {+ file_path: h.file_path,+ churn_percentile: h.churn_percentile,+ commit_count_90d: h.commit_count_90d,+ commit_count_30d: h.commit_count_30d,+ bus_factor: h.bus_factor,+ contributor_count: h.contributor_count,+ primary_owner: h.primary_owner,+ lines_added_90d: h.lines_added_90d,+ lines_deleted_90d: h.lines_deleted_90d,+ temporal_hotspot_score: h.temporal_hotspot_score ?? null,+ change_entropy_pct: h.change_entropy_pct ?? null,+ prior_defect_count: h.prior_defect_count ?? null,+ };+}export function HotspotsSection({ repoId }: { repoId: string }) {const t = useTranslations("codeHealth");const { showFile, dialog } = useFileCardHost(repoId);- const [pageLimit, setPageLimit] = useState(PAGE_SIZE);- const [drawerSymbol, setDrawerSymbol] = useState<SymbolResponse | null>(null);- const [promptHotspot, setPromptHotspot] = useState<Hotspot | null>(null);+ const { openPrompt, promptModal } = useAiPromptAction();+ const list = useHotspotList(repoId);- const {- data: page,- isLoading,- isValidating,- error,- } = useSWR<Paginated<HotspotResponse>>(- `risk-hotspots:${repoId}:${pageLimit}`,- () => getHotspotsPage(repoId, { limit: pageLimit }),- { revalidateOnFocus: false, keepPreviousData: true },+ const promptFor = useCallback(+ (h: Hotspot) =>+ openPrompt({+ title: t("hotspots.promptTitle"),+ description: t("hotspots.promptDescription"),+ filePath: h.file_path,+ getPrompt: (flavor) => buildHotspotAiPrompt({ hotspot: promptInput(h), flavor }),+ chatContext: fileChatContext(h.file_path),+ }),+ [openPrompt, t],);+ const { total } = list;+ const promptForRows = useCallback(+ (rows: Hotspot[]) =>+ openPrompt({+ title: t("hotspots.batchPromptTitle", { count: total }),+ description: t("hotspots.batchPromptDescription"),+ getPrompt: (flavor) =>+ buildHotspotBatchAiPrompt({ rows: rows.map(promptInput), total, flavor }),+ }),+ [openPrompt, t, total],+ );+ const select = useCallback((h: Hotspot) => showFile(hotspotToFileCard(h)), [showFile]);- const list = page?.items ?? [];- const total = page?.total ?? list.length;-- // The section renders nothing at all when a repo has no git history to mine,- // rather than an empty state explaining an absence the reader cannot act on.- if (!isLoading && !error && list.length === 0) return null;+ const narrowed = list.query !== "" || list.filter !== "all";+ // A repo with no git history to mine shows no section, rather than an empty+ // state explaining an absence the reader cannot act on.+ if (!list.isLoading && !list.error && list.items.length === 0 && !narrowed) return null;return (<OverviewSection@@ -77,68 +91,32 @@ export function HotspotsSection({ repoId }: { repoId: string }) {</SectionLink>}>- {error && list.length === 0 ? (- <p className="text-sm text-[var(--color-text-secondary)]">- {t("hotspots.loadFailed")}- </p>- ) : isLoading && list.length === 0 ? (+ {list.error && list.items.length === 0 ? (+ <p className="text-sm text-[var(--color-text-secondary)]">{t("hotspots.loadFailed")}</p>+ ) : list.isLoading && list.items.length === 0 ? (<Skeleton className="h-72 w-full rounded-xl" />) : (<HotspotTable- hotspots={list}- repoId={repoId}- onSelect={(h) => showFile(hotspotToFileCard(h))}- onGeneratePrompt={setPromptHotspot}- total={total}- hasMore={page?.has_more ?? false}- loadingMore={isValidating && !isLoading}- onLoadMore={() => setPageLimit((n) => Math.min(n + PAGE_SIZE, PAGE_MAX))}- renderExpandedRow={(h) => (- <HotspotTopSymbolsHost- repoId={repoId}- filePath={h.file_path}- onSelectSymbol={setDrawerSymbol}- />- )}+ hotspots={list.items}+ total={list.total}+ {...(list.facets ? { facets: list.facets } : {})}+ query={list.query}+ onQueryChange={list.setQuery}+ filter={list.filter}+ onFilterChange={list.setFilter}+ sort={list.sort}+ onSortChange={list.setSort}+ hasMore={list.hasMore}+ loadingMore={list.loadingMore}+ onLoadMore={list.loadMore}+ onSelect={select}+ onGeneratePrompt={promptFor}+ onGenerateBatchPrompt={promptForRows}+ batchPromptLabel={(count) => t("hotspots.batchPromptAction", { count })}/>)}-{dialog}- <SymbolDrawerWrapper- symbol={drawerSymbol}- repoId={repoId}- onClose={() => setDrawerSymbol(null)}- />- <AiPromptModal- open={promptHotspot !== null}- onOpenChange={(o) => !o && setPromptHotspot(null)}- getPrompt={- promptHotspot- ? (flavor) =>- buildHotspotAiPrompt({- hotspot: {- file_path: promptHotspot.file_path,- churn_percentile: promptHotspot.churn_percentile,- commit_count_90d: promptHotspot.commit_count_90d,- commit_count_30d: promptHotspot.commit_count_30d,- bus_factor: promptHotspot.bus_factor,- contributor_count: promptHotspot.contributor_count,- primary_owner: promptHotspot.primary_owner,- lines_added_90d: promptHotspot.lines_added_90d,- lines_deleted_90d: promptHotspot.lines_deleted_90d,- temporal_hotspot_score: promptHotspot.temporal_hotspot_score,- change_entropy_pct: promptHotspot.change_entropy_pct,- prior_defect_count: promptHotspot.prior_defect_count,- },- flavor,- })- : null- }- filePath={promptHotspot?.file_path}- chatContext={fileChatContext(promptHotspot?.file_path)}- title={t("hotspots.promptTitle")}- description={t("hotspots.promptDescription")}- />+ {promptModal}</OverviewSection>);}diff --git a/packages/web/src/components/code-health/triage-tab.tsx b/packages/web/src/components/code-health/triage-tab.tsxindex 3c315075e..8106cd6b3 100644--- a/packages/web/src/components/code-health/triage-tab.tsx+++ b/packages/web/src/components/code-health/triage-tab.tsx@@ -38,6 +38,7 @@ import type { HealthCounts, HealthScope } from "@repowise-dev/types/health";import { HealthFileDrawerHost } from "@/components/health/health-file-drawer-host";import { FixFirstSection } from "@/components/code-health/fix-first-section";import { useAreaRailLabels } from "./area-rail-labels";+import { useIncludeParam } from "./use-include-param";/*** Churn points pulled for the churn lens, joined onto the area-loaded rows by@@ -69,33 +70,6 @@ function useAreaParam() {return [area, setArea] as const;}-/**- * Held-out groups brought back into the map, in `?include=` (e.g.- * `test,build`). Replaced rather than pushed: it is a view setting, not a- * place to go back to.- */-function useIncludeParam() {- const router = useRouter();- const pathname = usePathname();- const searchParams = useSearchParams();- const raw = searchParams.get("include") ?? "";- const include = useMemo(- () => raw.split(",").map((o) => o.trim().toLowerCase()).filter(Boolean),- [raw],- );- const setInclude = useCallback(- (next: string[]) => {- const sp = new URLSearchParams(searchParams.toString());- if (next.length) sp.set("include", next.join(","));- else sp.delete("include");- const qs = sp.toString();- router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });- },- [router, pathname, searchParams],- );- return [include, setInclude] as const;-}-/** Churn percentiles by path, fetched only while the churn lens is on. */function useChurnExtras(repoId: string, wanted: boolean) {const { data, isLoading } = useSWR<ChurnComplexityResponse>(diff --git a/packages/web/src/components/code-health/use-hotspot-list.test.ts b/packages/web/src/components/code-health/use-hotspot-list.test.tsnew file mode 100644index 000000000..6ec89a0fe--- /dev/null+++ b/packages/web/src/components/code-health/use-hotspot-list.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from "vitest";+import type { HotspotPage } from "@/lib/api/git";+import { summarizePages } from "./use-hotspot-list";++const facets = { total: 3, bus_factor_1: 1, accelerating: 1, bug_magnet: 0 };+const page = (paths: string[], has_more: boolean): HotspotPage =>+ ({+ items: paths.map((file_path) => ({ file_path })),+ total: 3,+ has_more,+ next_offset: null,+ facets,+ }) as unknown as HotspotPage;++describe("summarizePages", () => {+ it("appends rows and reads counts from the first page, more from the last", () => {+ const s = summarizePages([page(["a", "b"], true), page(["c"], false)]);+ expect(s.items.map((h) => h.file_path)).toEqual(["a", "b", "c"]);+ expect(s).toMatchObject({ total: 3, facets, hasMore: false, loaded: 2 });+ });++ it("is empty before the first page lands", () => {+ expect(summarizePages(undefined)).toEqual({+ items: [],+ total: 0,+ facets: undefined,+ hasMore: false,+ loaded: 0,+ });+ });+});diff --git a/packages/web/src/components/code-health/use-hotspot-list.ts b/packages/web/src/components/code-health/use-hotspot-list.tsnew file mode 100644index 000000000..4698c3232--- /dev/null+++ b/packages/web/src/components/code-health/use-hotspot-list.ts@@ -0,0 +1,95 @@+"use client";++import { useCallback, useMemo } from "react";+import useSWRInfinite from "swr/infinite";+import { parseAsString, parseAsStringLiteral, useQueryStates } from "nuqs";+import type { HotspotFilter, HotspotOrder, HotspotSort } from "@repowise-dev/types/git";+import { getHotspotsPage, type HotspotPage } from "@/lib/api/git";+import { useIncludeParam } from "./use-include-param";++/** Rows per page; "Load more" appends the next offset, with no ceiling. */+export const HOTSPOT_PAGE_SIZE = 100;++const FILTERS = ["all", "bus_factor_1", "accelerating", "bug_magnet"] as const satisfies readonly HotspotFilter[];+const SORTS = ["score", "commits", "fixes", "churn"] as const satisfies readonly HotspotSort[];+const ORDERS = ["desc", "asc"] as const satisfies readonly HotspotOrder[];++/** Search, filter and sort live in the URL (`hq`, `hfilter`, `hsort`, `horder`). */+function useHotspotParams() {+ return useQueryStates(+ {+ hq: parseAsString.withDefault(""),+ hfilter: parseAsStringLiteral(FILTERS).withDefault("all"),+ hsort: parseAsStringLiteral(SORTS).withDefault("score"),+ horder: parseAsStringLiteral(ORDERS).withDefault("desc"),+ },+ { history: "replace", scroll: false },+ );+}++/** The loaded pages as one list: rows appended, counts from the first page. */+export function summarizePages(data: HotspotPage[] | undefined) {+ const pages = data ?? [];+ const first = pages[0];+ return {+ items: pages.flatMap((p) => p.items),+ total: first ? first.total : 0,+ facets: first?.facets,+ hasMore: pages.length > 0 && pages[pages.length - 1]!.has_more,+ loaded: pages.length,+ };+}++/**+ * The hotspot list in the map's scope (`hold=map` plus `?include=`), paged by+ * offset. The server searches, filters, sorts and counts; this only appends.+ */+export function useHotspotList(repoId: string) {+ const [params, setParams] = useHotspotParams();+ const [include] = useIncludeParam();+ const query = useMemo(+ () => ({+ q: params.hq,+ filter: params.hfilter,+ sort: params.hsort,+ order: params.horder,+ hold: "map" as const,+ include,+ }),+ [params, include],+ );+ const keyBase = JSON.stringify(query);++ const { data, error, size, setSize, isLoading, isValidating } = useSWRInfinite<HotspotPage>(+ (pageIndex, previous: HotspotPage | null) =>+ previous && !previous.has_more ? null : ["hotspots", repoId, keyBase, pageIndex],+ ([, , , pageIndex]: [string, string, string, number]) =>+ getHotspotsPage(repoId, {+ ...query,+ limit: HOTSPOT_PAGE_SIZE,+ offset: pageIndex * HOTSPOT_PAGE_SIZE,+ }),+ { revalidateOnFocus: false, revalidateFirstPage: false, keepPreviousData: true },+ );++ const pages = useMemo(() => summarizePages(data), [data]);+ const loadMore = useCallback(() => setSize(size + 1), [setSize, size]);++ return {+ ...pages,+ isLoading,+ loadingMore: isValidating && !isLoading && size > pages.loaded,+ error,+ query: params.hq,+ filter: params.hfilter,+ sort: { key: params.hsort, order: params.horder },+ setQuery: (hq: string) => setParams({ hq: hq || null }),+ setFilter: (f: HotspotFilter) => setParams({ hfilter: f === "all" ? null : f }),+ setSort: (s: { key: HotspotSort; order: HotspotOrder }) =>+ setParams({+ hsort: s.key === "score" ? null : s.key,+ horder: s.order === "desc" ? null : s.order,+ }),+ loadMore,+ };+}diff --git a/packages/web/src/components/code-health/use-include-param.ts b/packages/web/src/components/code-health/use-include-param.tsnew file mode 100644index 000000000..11d5e67f9--- /dev/null+++ b/packages/web/src/components/code-health/use-include-param.ts@@ -0,0 +1,31 @@+"use client";++import { useCallback, useMemo } from "react";+import { usePathname, useRouter, useSearchParams } from "next/navigation";++/**+ * Held-out groups brought back into the map, in `?include=` (e.g.+ * `test,build`). Replaced rather than pushed: it is a view setting, not a+ * place to go back to. Every section under the map reads the same scope.+ */+export function useIncludeParam() {+ const router = useRouter();+ const pathname = usePathname();+ const searchParams = useSearchParams();+ const raw = searchParams.get("include") ?? "";+ const include = useMemo(+ () => raw.split(",").map((o) => o.trim().toLowerCase()).filter(Boolean),+ [raw],+ );+ const setInclude = useCallback(+ (next: string[]) => {+ const sp = new URLSearchParams(searchParams.toString());+ if (next.length) sp.set("include", next.join(","));+ else sp.delete("include");+ const qs = sp.toString();+ router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });+ },+ [router, pathname, searchParams],+ );+ return [include, setInclude] as const;+}diff --git a/packages/web/src/components/symbols/hotspot-top-symbols-host.tsx b/packages/web/src/components/symbols/hotspot-top-symbols-host.tsxdeleted file mode 100644index 397d6e3be..000000000--- a/packages/web/src/components/symbols/hotspot-top-symbols-host.tsx+++ /dev/null@@ -1,45 +0,0 @@-"use client";--import useSWR from "swr";-import { TopSymbolsRow } from "@repowise-dev/ui/symbols/top-symbols-row";-import { listSymbolsPage } from "@/lib/api/symbols";-import type { SymbolResponse } from "@/lib/api/types";-import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";--interface Props {- repoId: string;- filePath: string;- /** Opens the universal SymbolDrawer from the host page. */- onSelectSymbol: (symbol: SymbolResponse) => void;-}--/**- * SWR host for the hotspot-row → top-symbols inline expand. Pulls the top 10- * importance-ranked symbols in the given file, then defers rendering to the- * shared TopSymbolsRow.- */-export function HotspotTopSymbolsHost({ repoId, filePath, onSelectSymbol }: Props) {- const { data, error, isLoading } = useSWR(- `top-symbols-in-file:${repoId}:${filePath}`,- () =>- listSymbolsPage({- repo_id: repoId,- file_path: filePath,- sort: "importance",- limit: 10,- }),- { revalidateOnFocus: false },- );-- const seeAllHref = `/repos/${repoId}/architecture?view=symbols&q=${encodeURIComponent(filePath)}`;-- return (- <TopSymbolsRow- symbols={data?.items}- loading={isLoading}- error={error ? toFriendlyMessage(error) : undefined}- onSelect={onSelectSymbol}- seeAllHref={seeAllHref}- />- );-}diff --git a/tests/unit/server/golden/overview_summary.json b/tests/unit/server/golden/overview_summary.jsonindex 072e376da..67e08c1d8 100644--- a/tests/unit/server/golden/overview_summary.json+++ b/tests/unit/server/golden/overview_summary.json@@ -399,7 +399,9 @@"prior_defect_count": 0,"bug_magnet": false,"last_fix_at": null,- "original_path": null+ "original_path": null,+ "accelerating": false,+ "rank": null},{"file_path": "web/app.ts",@@ -429,7 +431,9 @@"prior_defect_count": 0,"bug_magnet": false,"last_fix_at": null,- "original_path": null+ "original_path": null,+ "accelerating": false,+ "rank": null}],"recent_decisions": [diff --git a/tests/unit/server/test_hotspots_list.py b/tests/unit/server/test_hotspots_list.pynew file mode 100644index 000000000..bb5e4607c--- /dev/null+++ b/tests/unit/server/test_hotspots_list.py@@ -0,0 +1,225 @@+"""The hotspot list: scope, search, filters, sort, rank and facets."""++from __future__ import annotations++from datetime import UTC, datetime++import pytest+from httpx import AsyncClient++from repowise.core.analysis.finding_registry import stored_origin+from repowise.core.persistence import crud+from repowise.core.persistence.database import get_session+from repowise.core.persistence.models import HealthFileMetric+from repowise.server.services.hotspots import (+ accelerating_clause,+ is_accelerating,+ origin_clause,+)+from tests.unit.server.conftest import create_test_repo++_FIXED = datetime(2026, 9, 1, tzinfo=UTC)++# path, score, commits 90d/30d, age, bus factor, owner, magnet, origin+_ROWS = [+ ("src/core.py", 9.0, 30, 20, 400, 1, "Ada", True, "production"),+ ("src/api.py", 7.0, 20, 2, 400, 2, "Grace", False, "production"),+ ("src/new.py", 6.0, 10, 10, 20, 1, "Ada", False, "production"), # new, not accelerating+ ("tests/test_core.py", 8.0, 25, 15, 400, 0, "Linus", True, "test"),+ ("build/gen.py", 5.0, 5, 1, 400, 1, "Ada", False, "build"),+ ("src/legacy.py", 4.0, 4, 3, 900, 3, None, False, None), # no health row+]+++async def _seed(session_factory, repo_id: str) -> None:+ async with get_session(session_factory) as session:+ for path, score, c90, c30, age, bf, owner, magnet, origin in _ROWS:+ await crud.upsert_git_metadata(+ session,+ repository_id=repo_id,+ file_path=path,+ commit_count_total=c90 * 2,+ commit_count_90d=c90,+ commit_count_30d=c30,+ age_days=age,+ bus_factor=bf,+ primary_owner_name=owner,+ is_hotspot=True,+ is_stable=False,+ churn_percentile=score / 10,+ temporal_hotspot_score=score,+ prior_defect_count=3 if magnet else 0,+ bug_magnet=magnet,+ last_fix_at=_FIXED if magnet else None,+ )+ if origin is not None:+ session.add(+ HealthFileMetric(+ repository_id=repo_id, file_path=path, nloc=10, code_origin=origin+ )+ )+ # A file that is not a hotspot never lists.+ await crud.upsert_git_metadata(+ session, repository_id=repo_id, file_path="src/calm.py", is_hotspot=False+ )+++async def _list(client: AsyncClient, repo_id: str, **params) -> dict:+ resp = await client.get(f"/api/repos/{repo_id}/hotspots", params=params)+ assert resp.status_code == 200, resp.text+ return resp.json()+++def _paths(payload: dict) -> list[str]:+ return [r["file_path"] for r in payload["items"]]+++async def test_default_lists_every_hotspot_by_score(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ page = await _list(client, repo["id"])+ assert _paths(page) == [+ "src/core.py",+ "tests/test_core.py",+ "src/api.py",+ "src/new.py",+ "build/gen.py",+ "src/legacy.py",+ ]+ assert [r["rank"] for r in page["items"]] == [1, 2, 3, 4, 5, 6]+ assert page["total"] == 6+ # Bus factor 0 is "no history", not one owner; the new file is not accelerating.+ assert page["facets"] == {+ "total": 6,+ "bus_factor_1": 3,+ "accelerating": 3,+ "bug_magnet": 2,+ "with_fixes": 2,+ }+++async def test_hold_map_leaves_out_held_origins_and_ranks_within_scope(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ page = await _list(client, repo["id"], hold="map")+ assert _paths(page) == ["src/core.py", "src/api.py", "src/new.py", "src/legacy.py"]+ assert [r["rank"] for r in page["items"]] == [1, 2, 3, 4]++ back = await _list(client, repo["id"], hold="map", include="TEST")+ assert "tests/test_core.py" in _paths(back)+ assert "build/gen.py" not in _paths(back)+++async def test_facets_sum_and_match_each_filters_total(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ base = await _list(client, repo["id"], hold="map", limit=500)+ facets = base["facets"]+ assert facets["total"] == base["total"] == len(base["items"])+ for name in ("bus_factor_1", "accelerating", "bug_magnet"):+ page = await _list(client, repo["id"], hold="map", filter=name, limit=500)+ assert page["total"] == facets[name] == len(page["items"])+ # The facets describe the searched set, not the filtered page.+ assert page["facets"] == facets+ flags = {r["file_path"]: r["accelerating"] for r in base["items"]}+ assert flags == {+ "src/core.py": True,+ "src/api.py": False,+ "src/new.py": False,+ "src/legacy.py": True,+ }+++async def test_search_matches_path_or_owner_and_keeps_global_rank(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ by_owner = await _list(client, repo["id"], q="grace")+ assert _paths(by_owner) == ["src/api.py"]+ assert by_owner["items"][0]["rank"] == 3+ assert by_owner["facets"]["total"] == 1++ by_path = await _list(client, repo["id"], q="LEGACY")+ assert _paths(by_path) == ["src/legacy.py"]++ # LIKE wildcards are literal.+ assert (await _list(client, repo["id"], q="%"))["total"] == 0+++async def test_sort_and_offset_page_through_the_whole_set(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ asc = await _list(client, repo["id"], sort="commits", order="asc")+ assert _paths(asc)[0] == "src/legacy.py"+ assert asc["items"][0]["rank"] == 6++ first = await _list(client, repo["id"], limit=4)+ rest = await _list(client, repo["id"], limit=4, offset=4)+ assert first["has_more"] is True and first["next_offset"] == 4+ assert rest["has_more"] is False and rest["next_offset"] is None+ assert len(set(_paths(first)) | set(_paths(rest))) == 6+++async def test_facets_follow_a_git_only_remine(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])+ assert (await _list(client, repo["id"]))["facets"]["total"] == 6++ async with get_session(app.state.session_factory) as session:+ await crud.upsert_git_metadata(+ session, repository_id=repo["id"], file_path="src/late.py", is_hotspot=True,+ commit_count_90d=1, commit_count_30d=0, churn_percentile=0.1,+ )+ page = await _list(client, repo["id"])+ assert page["facets"]["total"] == page["total"] == 7+++async def test_rejects_unknown_filter_and_sort(client: AsyncClient) -> None:+ repo = await create_test_repo(client)+ for params in ({"filter": "hot"}, {"sort": "trend"}, {"order": "up"}):+ resp = await client.get(f"/api/repos/{repo['id']}/hotspots", params=params)+ assert resp.status_code == 422+++def test_accelerating_needs_a_prior_window() -> None:+ assert is_accelerating(5, 10, 400)+ assert not is_accelerating(3, 10, 400)+ assert not is_accelerating(10, 10, 30)+ assert not is_accelerating(None, None, None)+ assert accelerating_clause() is not None+++ ("code_origin", "is_test"),+ [(None, None), (None, True), ("", True), ("", False), ("build", True), ("production", None)],+)+async def test_origin_clause_matches_stored_origin(app, code_origin, is_test) -> None:+ from sqlalchemy import select++ async with get_session(app.state.session_factory) as session:+ row = HealthFileMetric(+ repository_id="r", file_path="x.py", nloc=1, code_origin=code_origin, is_test=is_test+ )+ session.add(row)+ await session.flush()+ got = await session.scalar(+ select(origin_clause()).where(HealthFileMetric.id == row.id)+ )+ await session.rollback()+ assert got == stored_origin(code_origin, is_test)