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
fix(health): rank the worst-files lists by deduction, not by a score that clamps at 1.0 (#1342)
Raghav Chamadiya5222e0a03947
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.pyindex b97ed713a..7a8eb1da4 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py@@ -30,6 +30,7 @@ from .dead_code import ()from .health import (HEALTH_SNAPSHOT_RETENTION,+ get_deduction_by_path,get_file_language_map,get_health_findings,get_health_metrics,@@ -40,6 +41,7 @@ from .health import (save_health_findings,save_health_metrics,save_health_snapshot,+ sort_metrics_worst_first,update_health_finding_status,upsert_health_findings,upsert_health_metrics,@@ -58,6 +60,7 @@ __all__ = ["get_coverage_summary","get_dead_code_findings","get_dead_code_summary",+ "get_deduction_by_path","get_file_language_map","get_health_findings","get_health_metrics",@@ -76,6 +79,7 @@ __all__ = ["save_health_snapshot","save_refactoring_suggestions","save_test_coverage",+ "sort_metrics_worst_first","tests_covering","update_dead_code_status","update_health_finding_status",diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.pyindex 47ada9c1f..bf3726c5a 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py@@ -8,7 +8,7 @@ from datetime import datetimefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any-from sqlalchemy import or_, select+from sqlalchemy import func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSessionif TYPE_CHECKING:@@ -310,21 +310,103 @@ async def get_health_findings()+async def get_deduction_by_path(+ session: AsyncSession,+ repository_id: str,+ *,+ file_paths: list[str] | None = None,+ status: str = "open",+) -> dict[str, float]:+ """``{file_path: summed health_impact}`` over the repo's findings.++ The pre-clamp deduction magnitude, aggregated in SQL rather than by+ hydrating every finding. Each stored ``health_impact`` is already the+ applied (capped) value, so the sum equals the breakdown endpoint's+ ``total_deduction``.++ Files with no findings are simply absent — a caller reading this as a+ ranking key should treat a miss as 0.0 (a clean file has no magnitude).+ """+ totals: dict[str, float] = {}+ base = select(+ HealthFinding.file_path,+ func.sum(HealthFinding.health_impact),+ ).where(+ HealthFinding.repository_id == repository_id,+ HealthFinding.status == status,+ )+ # Batched like the other ``IN`` lookups here: SQLITE_MAX_VARIABLE_NUMBER is+ # 999 before SQLite 3.32 and a module-scoped caller expands without bound.+ chunks: list[list[str] | None] = (+ [file_paths[i : i + _BATCH_SIZE] for i in range(0, len(file_paths), _BATCH_SIZE)]+ if file_paths is not None+ else [None]+ )+ for chunk in chunks:+ q = base if chunk is None else base.where(HealthFinding.file_path.in_(chunk))+ for path, total in (await session.execute(q.group_by(HealthFinding.file_path))).all():+ totals[path] = float(total or 0.0)+ return totals+++def sort_metrics_worst_first(+ rows: list[Any], deduction_by_path: dict[str, float]+) -> list[Any]:+ """Order per-file metrics worst-first: ``(score asc, deduction desc, path)``.++ ``score`` alone cannot rank the band that matters. It clamps at 1.0, so on+ a real repo dozens of files tie there and any list sorted on score alone+ comes back in whatever order the DB happened to return — path order, in+ practice. That put this repo's single worst file (12.9 points of deduction)+ at position 27 of a list capped at 20.++ ``total_deduction`` is the pre-clamp magnitude, so it keeps ranking below+ the floor: a -25 file sorts above a -9 file that prints the same 1.0. The+ trailing ``file_path`` makes the order total, so a page boundary is stable+ across requests instead of shuffling two equal rows.++ Shared with the MCP ``get_health`` tool, which builds its own deduction map+ from findings it has already loaded rather than re-querying. One comparator+ so REST, MCP and hosted cannot drift into three different "worst files".+ """+ return sorted(+ rows,+ key=lambda m: (m.score, -deduction_by_path.get(m.file_path, 0.0), m.file_path),+ )++async def get_health_metrics(session: AsyncSession,repository_id: str,*,file_paths: list[str] | None = None,) -> list[HealthFileMetric]:+ """Per-file health metrics, ordered worst-first.++ See :func:`sort_metrics_worst_first` for why the order is not a plain+ ``ORDER BY score``.+ """q = select(HealthFileMetric).where(HealthFileMetric.repository_id == repository_id)if file_paths is not None:q = q.where(HealthFileMetric.file_path.in_(file_paths))- q = q.order_by(HealthFileMetric.score.asc())result = await session.execute(q)- return _filter_excluded_paths(+ rows = _filter_excluded_paths(list(result.scalars().all()),await _health_exclude_spec(session, repository_id),)+ if len(rows) < 2:+ # Nothing to order. Skips the aggregate for the single-file lookups+ # (symbol drawer, file detail, one-plan refactoring view), which are+ # per-request reads that would otherwise pay for a ranking they cannot+ # use.+ return rows+ # Scoped to the caller's paths, not to ``rows``: a repo-wide read wants the+ # single grouped scan, and the extra keys an exclude config leaves in the+ # map are never looked up.+ return sort_metrics_worst_first(+ rows,+ await get_deduction_by_path(session, repository_id, file_paths=file_paths),+ )async def get_file_language_map(session: AsyncSession, repository_id: str) -> dict[str, str]:diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex 92ad10cd3..25b810a61 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -27,6 +27,7 @@ from repowise.core.persistence.crud import (get_refactoring_suggestions,list_health_snapshots,load_coverage_for_repo,+ sort_metrics_worst_first,)from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import HealthFileMetric, HealthFinding@@ -523,15 +524,6 @@ async def get_health(effective_targets = file_targets if scoped else []nothing_resolved = scoped and not effective_targets- if scoped:- metric_rows = [- m- for m in sorted(all_metrics, key=lambda r: r.score)- if m.file_path in set(effective_targets)- ]- else:- metric_rows = sorted(all_metrics, key=lambda r: r.score)-open_findings = (HealthFinding.repository_id == repository.id,HealthFinding.status == "open",@@ -622,6 +614,34 @@ async def get_health(# ``findings`` read as "nothing here" rather than "nothing shown".findings_total = len(emitted)+ # Worst-first order, placed here because ranking needs the summed+ # deduction per file and ``lead_rows`` is the first point that carries+ # every open finding this response is entitled to see. Same comparator+ # the crud layer applies to ``get_health_metrics``, so the REST+ # dashboard and this tool cannot disagree about which file is worst —+ # but fed from rows already in memory, so it costs no extra query.+ #+ # Deliberately ``lead_rows`` (the unfiltered open set) rather than+ # ``emitted``: asking to *see* one dimension must not restate which+ # files the repo's worst are.+ deduction_by_path: dict[str, float] = {}+ for f in lead_rows:+ deduction_by_path[f.file_path] = deduction_by_path.get(f.file_path, 0.0) + float(+ f.health_impact or 0.0+ )+ # Rebound rather than kept beside a sorted copy, and above every reader.+ # ``kpis``, the module rollup, the leverage view and the churn quadrant+ # all reduce with ``min()`` or a stable sort, which resolve ties by+ # *input* order — so leaving them on the raw list would have one+ # response name one file as the worst performer while the+ # ``worst_files`` list printed below it led with another.+ all_metrics = sort_metrics_worst_first(all_metrics, deduction_by_path)+ metric_rows = (+ [m for m in all_metrics if m.file_path in set(effective_targets)]+ if scoped+ else all_metrics+ )+# Dashboard perf headline: coverage (how much of the analyzed code the# perf pass ran on) + open performance-finding count. Both feed ``kpis``# alone, so a projection that drops kpis skips the language-map read.diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.pyindex 035ea5ed2..0271e02a4 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py@@ -718,10 +718,14 @@ def _resolve_title(overview_page: Page | None, repository: Any) -> str:async def _build_code_health(session: Any, repository: Any) -> dict[str, Any]:"""Headline code-health KPIs; empty when health hasn't been run on this repo."""try:- health_summary = await _get_health_summary(session, repository.id)+ # Metrics first, handed to the summary: it reads the same table, and+ # that read now also aggregates the per-file deduction used to rank+ # floored files, so letting it load its own copy pays for the ranking+ # twice.metrics_rows = await _get_health_metrics(session, repository.id)if not metrics_rows:return {}+ health_summary = await _get_health_summary(session, repository.id, metrics=metrics_rows)# Hotspot health: NLOC-weighted avg over the top-25% files by NLOC,# matching the dashboard KPI definition.sorted_by_nloc = sorted(metrics_rows, key=lambda m: m.nloc or 0, reverse=True)diff --git a/packages/server/src/repowise/server/routers/code_health/__init__.py b/packages/server/src/repowise/server/routers/code_health/__init__.pyindex e2c4ec5cf..ade1f8145 100644--- a/packages/server/src/repowise/server/routers/code_health/__init__.py+++ b/packages/server/src/repowise/server/routers/code_health/__init__.py@@ -28,6 +28,7 @@ from ._router import routerfrom .badge import _badge_fields, _render_badge_svg # noqa: F401from .breakdown import _finding_base_deduction, _score_breakdown_from_findings # noqa: F401from .overview_routes import _resolve_last_indexed_at # noqa: F401+from .refactoring_routes import _SORT_KEYS # noqa: F401# re-export helpers imported by routers/files.py + tests (keep old import path working)from .serializers import ( # noqa: F401diff --git a/packages/server/src/repowise/server/routers/code_health/churn_routes.py b/packages/server/src/repowise/server/routers/code_health/churn_routes.pyindex 0e3381c84..5212e55f9 100644--- a/packages/server/src/repowise/server/routers/code_health/churn_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/churn_routes.py@@ -16,7 +16,12 @@ from .serializers import _churn_complexity_to_dict@router.get("/api/repos/{repo_id}/health/churn-complexity")async def churn_complexity(repo_id: str,- limit: int = Query(300, ge=1, le=1000),+ # The ceiling has to clear the code-health map's file window (2,000), not+ # match it. The map ranks by NLOC and this list ranks by the danger product,+ # so a top-2,000 churn window covers only part of a top-2,000-by-NLOC map —+ # measured 1,490 of the 1,935 mapped files that have churn data. Every node+ # it misses renders as the legend's "no data" swatch for data that exists.+ limit: int = Query(300, ge=1, le=5000),session: AsyncSession = Depends(get_db_session),) -> dict:"""Churn x complexity scatter points -- the "hotspot anatomy" danger-zone view.diff --git a/packages/server/src/repowise/server/routers/code_health/overview_routes.py b/packages/server/src/repowise/server/routers/code_health/overview_routes.pyindex 42eb0f1e8..0bbaabff7 100644--- a/packages/server/src/repowise/server/routers/code_health/overview_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/overview_routes.py@@ -49,8 +49,12 @@ async def health_overview(repo = await crud.get_repository(session, repo_id)if repo is None:raise HTTPException(status_code=404, detail="Repository not found")- summary = await crud.get_health_summary(session, repo_id)+ # ``metrics=`` exists for exactly this caller (see the parameter's+ # docstring): without it the summary pulls the whole metrics table a second+ # time, and since that read now also aggregates the deduction column it+ # would pay for the ranking twice.metrics = await crud.get_health_metrics(session, repo_id)+ summary = await crud.get_health_summary(session, repo_id, metrics=metrics)findings = await crud.get_health_findings(session, repo_id)snapshots = await crud.list_health_snapshots(session, repo_id)diff --git a/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py b/packages/server/src/repowise/server/routers/code_health/refactoring_routes.pyindex caa2e913e..77a625ef0 100644--- a/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py@@ -24,6 +24,22 @@ _EFFORT_BUCKETS: tuple[tuple[int, str], ...] = ()+_SORT_KEYS = {+ "impact_per_effort": lambda t: (-t["impact_per_effort"], -t["total_impact"]),+ "total_impact": lambda t: -t["total_impact"],+ # ``score`` clamps at 1.0, so on a real repo dozens of targets tie at the+ # top and sorting on it alone returns them in dict-insertion order.+ # ``total_impact`` is the same pre-clamp deduction magnitude the crud layer+ # ranks metrics by — but summed over the findings that survived this+ # request's ``biomarker`` / ``min_severity`` filters, so under a filter this+ # ranks by the filtered depth rather than the file's full depth. That is+ # what a filtered queue should do; it just means the order is not expected+ # to match /health/files once a filter is on.+ "score": lambda t: (t["score"], -t["total_impact"], t["file_path"]),+ "finding_count": lambda t: -t["finding_count"],+}++def _effort_for_nloc(nloc: int) -> str:for ceiling, label in _EFFORT_BUCKETS:if nloc <= ceiling:@@ -103,11 +119,5 @@ async def refactoring_targets(})- sort_key_map = {- "impact_per_effort": lambda t: (-t["impact_per_effort"], -t["total_impact"]),- "total_impact": lambda t: -t["total_impact"],- "score": lambda t: t["score"],- "finding_count": lambda t: -t["finding_count"],- }- targets.sort(key=sort_key_map[sort])+ targets.sort(key=_SORT_KEYS[sort])return {"targets": targets[:limit], "total": len(targets)}diff --git a/packages/ui/src/health/file-table.tsx b/packages/ui/src/health/file-table.tsxindex ba2734f9d..9d8bd6c14 100644--- a/packages/ui/src/health/file-table.tsx+++ b/packages/ui/src/health/file-table.tsx@@ -63,9 +63,15 @@ export function HealthFileTable({selectedPath,emptyMessage,}: HealthFileTableProps) {- // When sorting by score, two floored files both read 1.0; break that tie by- // deduction magnitude so the deeper problem sorts first (server sorts by- // score only, so this is a within-page refinement — P1).+ // Two floored files both read 1.0; break that tie by deduction magnitude so+ // the deeper problem sorts first. The OSS server now does this in the crud+ // layer, which makes this a no-op there — but this component is published and+ // the hosted backend still sorts on score alone, so it stays as that+ // deployment's only tiebreak until the same ordering lands there.+ //+ // It can only ever refine the page it was handed. Recovering a file the+ // server left *off* the page needs the server-side sort; that is why this is+ // a fallback and not the fix.const rows = useMemo(() => {if (sortField !== "score") return files;const dir = sortOrder === "desc" ? -1 : 1;diff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsxindex 6bb3f8bff..3006c7a94 100644--- a/packages/web/src/app/repos/[id]/code-health/page.tsx+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx@@ -85,6 +85,25 @@ const TAB_ALIASES: Record<string, TabId> = {*/const OVERLAYS: CodeHealthOverlay[] = ["health", "maintainability", "performance", "churn"];+/** Files pulled for the map: biggest first, capped so the galaxy stays legible. */+const MAP_FILE_LIMIT = 2000;+/**+ * Churn points pulled for the churn lens. Deliberately larger than+ * `MAP_FILE_LIMIT`: the map ranks by NLOC and churn-complexity ranks by+ * `commit_count × max_ccn`, so the two windows do not contain the same files.+ * At the old default of 300 this repo joined churn onto 296 of the 1,935 mapped+ * files that have it, and the other ~1,700 nodes rendered as the legend's+ * "no data" swatch for data that exists. Matching the map's 2,000 would still+ * miss 445. 5,000 covers every churned file here with headroom; a repo that+ * exceeds it degrades back to the same partial join rather than breaking.+ *+ * Costs ~469 KB uncompressed on this repo (3,011 points), on a request that+ * only fires once the churn lens is selected. The hosted route still caps at+ * 1,000, so porting this page there needs that ceiling raised first or the+ * request 422s.+ */+const CHURN_POINT_LIMIT = 5000;+export default function CodeHealthPage() {const params = useParams<{ id: string }>();const router = useRouter();@@ -140,7 +159,7 @@ export default function CodeHealthPage() {// so switching the lens never refetches.const { data: mapFiles } = useSWR<HealthFilesResponse>(`code-health-map-files:${repoId}`,- () => listHealthFiles(repoId, { limit: 2000, sort: "nloc", order: "desc" }),+ () => listHealthFiles(repoId, { limit: MAP_FILE_LIMIT, sort: "nloc", order: "desc" }),{ revalidateOnFocus: false },);@@ -150,7 +169,7 @@ export default function CodeHealthPage() {const churnWanted = overlay === "churn";const { data: churn, isLoading: churnLoading } = useSWR<ChurnComplexityResponse>(churnWanted ? `health-churn-complexity:${repoId}` : null,- () => getChurnComplexity(repoId),+ () => getChurnComplexity(repoId, { limit: CHURN_POINT_LIMIT }),{ revalidateOnFocus: false, keepPreviousData: true },);diff --git a/tests/unit/persistence/test_health_ranking.py b/tests/unit/persistence/test_health_ranking.pynew file mode 100644index 000000000..7f778a1ca--- /dev/null+++ b/tests/unit/persistence/test_health_ranking.py@@ -0,0 +1,159 @@+"""Worst-first ordering of per-file health metrics.++The score clamps at 1.0, so on a real repo dozens of files tie there and a list+sorted on score alone comes back in DB order. Measured on this repo's own+index: 30 files at exactly 1.0, and the file carrying the largest deduction+(12.9) landed at position 27 of a list capped at 20.+"""++from __future__ import annotations++from repowise.core.persistence.crud import (+ get_deduction_by_path,+ get_health_metrics,+ save_health_findings,+ save_health_metrics,+ sort_metrics_worst_first,+ upsert_repository,+)+++def _metric(path: str, score: float) -> dict:+ return {+ "file_path": path,+ "score": score,+ "max_ccn": 1,+ "max_nesting": 1,+ "nloc": 10,+ "has_test_file": False,+ "module": "src",+ }+++def _finding(path: str, impact: float, name: str = "f") -> dict:+ return {+ "file_path": path,+ "biomarker_type": "complex_method",+ "severity": "high",+ "function_name": name,+ "line_start": 1,+ "line_end": 2,+ "details": {},+ "health_impact": impact,+ "reason": "reason",+ }+++async def _seed(async_session, tmp_path, metrics: list[dict], findings: list[dict]):+ repo = await upsert_repository(async_session, name="repo", local_path=str(tmp_path))+ await save_health_metrics(async_session, repo.id, metrics)+ await save_health_findings(async_session, repo.id, findings)+ return repo+++async def test_floored_files_rank_by_deduction_not_path(async_session, tmp_path) -> None:+ """The deepest floored file leads, even when its path sorts last."""+ repo = await _seed(+ async_session,+ tmp_path,+ [_metric("a.py", 1.0), _metric("m.py", 1.0), _metric("z.py", 1.0)],+ # Deliberately inverse to path order: sorting on score alone would+ # return a, m, z and bury the worst file.+ [_finding("a.py", 2.0), _finding("m.py", 5.0), _finding("z.py", 9.0)],+ )++ rows = await get_health_metrics(async_session, repo.id)++ assert [m.file_path for m in rows] == ["z.py", "m.py", "a.py"]+++async def test_deduction_ties_break_on_path_so_paging_is_stable(async_session, tmp_path) -> None:+ """Equal score and equal deduction still produce one total order.++ Without the trailing key two equal rows could swap between requests, which+ a caller paging by offset reads as a row appearing twice or not at all.+ """+ repo = await _seed(+ async_session,+ tmp_path,+ [_metric("b.py", 1.0), _metric("a.py", 1.0)],+ [_finding("a.py", 3.0), _finding("b.py", 3.0)],+ )++ rows = await get_health_metrics(async_session, repo.id)+ assert [m.file_path for m in rows] == ["a.py", "b.py"]+++async def test_file_with_no_findings_sorts_after_a_tied_file_that_has_them(+ async_session, tmp_path+) -> None:+ """A miss in the deduction map is 0.0: a clean file has no magnitude."""+ repo = await _seed(+ async_session,+ tmp_path,+ [_metric("clean.py", 1.0), _metric("deep.py", 1.0)],+ [_finding("deep.py", 4.0)],+ )++ assert [m.file_path for m in await get_health_metrics(async_session, repo.id)] == [+ "deep.py",+ "clean.py",+ ]+++async def test_score_still_outranks_deduction(async_session, tmp_path) -> None:+ """Deduction is the tiebreak, not the sort. A worse score always leads."""+ repo = await _seed(+ async_session,+ tmp_path,+ [_metric("low.py", 1.0), _metric("high.py", 6.0)],+ [_finding("low.py", 1.0), _finding("high.py", 40.0)],+ )++ assert [m.file_path for m in await get_health_metrics(async_session, repo.id)] == [+ "low.py",+ "high.py",+ ]+++async def test_scoped_read_ranks_and_sums_only_the_requested_paths(+ async_session, tmp_path+) -> None:+ repo = await _seed(+ async_session,+ tmp_path,+ [_metric("a.py", 1.0), _metric("b.py", 1.0), _metric("c.py", 1.0)],+ [_finding("a.py", 2.0), _finding("b.py", 7.0), _finding("c.py", 99.0)],+ )++ rows = await get_health_metrics(async_session, repo.id, file_paths=["a.py", "b.py"])+ assert [m.file_path for m in rows] == ["b.py", "a.py"]++ scoped = await get_deduction_by_path(async_session, repo.id, file_paths=["a.py", "b.py"])+ assert scoped == {"a.py": 2.0, "b.py": 7.0}+++async def test_deduction_sums_every_finding_on_a_file(async_session, tmp_path) -> None:+ repo = await _seed(+ async_session,+ tmp_path,+ [_metric("a.py", 1.0)],+ [_finding("a.py", 1.5, "one"), _finding("a.py", 2.25, "two")],+ )++ assert await get_deduction_by_path(async_session, repo.id) == {"a.py": 3.75}+++def test_sort_helper_is_pure_and_leaves_its_input_alone() -> None:+ """The MCP tool feeds this rows it also serializes from, unsorted."""++ class _Row:+ def __init__(self, path: str, score: float) -> None:+ self.file_path = path+ self.score = score++ rows = [_Row("a.py", 1.0), _Row("b.py", 1.0)]+ ordered = sort_metrics_worst_first(rows, {"b.py": 5.0})++ assert [r.file_path for r in ordered] == ["b.py", "a.py"]+ assert [r.file_path for r in rows] == ["a.py", "b.py"]diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.pyindex 0278b0edc..330e2c03a 100644--- a/tests/unit/server/mcp/test_health.py+++ b/tests/unit/server/mcp/test_health.py@@ -377,3 +377,119 @@ async def test_get_health_dimension_filter_leaves_kpis_and_ranking_alone(setup_mfiltered = await get_health(include=["biomarkers", "maintainability"])assert filtered["kpis"]["performance_findings"] == full["kpis"]["performance_findings"]assert filtered["worst_files"] == full["worst_files"]+++async def floored_health_data(session, populated_db: str) -> str:+ """Four files clamped at the 1.0 score floor, worst one last by path.++ Mirrors the shape of a real repo, where 30 files sit at exactly 1.0 and the+ deepest of them sorts last alphabetically.+ """+ from repowise.core.persistence.crud import save_health_findings, save_health_metrics++ rid = populated_db+ paths = ["src/a.py", "src/b.py", "src/c.py", "src/z.py"]+ await save_health_metrics(+ session,+ rid,+ [+ {+ "file_path": p,+ "score": 1.0,+ "max_ccn": 20,+ "max_nesting": 5,+ "nloc": 100,+ "has_test_file": False,+ "module": "src",+ }+ for p in paths+ ],+ )+ # z.py is the deepest by a wide margin and would be invisible under a+ # score-only sort at any limit below 4.+ impacts = {"src/a.py": 2.0, "src/b.py": 3.0, "src/c.py": 4.0, "src/z.py": 9.0}+ await save_health_findings(+ session,+ rid,+ [+ {+ "file_path": p,+ "biomarker_type": "complex_method",+ "severity": "high",+ "function_name": "run",+ "line_start": 1,+ "line_end": 20,+ "details": {},+ "health_impact": impact,+ "reason": f"{p} is complex",+ }+ for p, impact in impacts.items()+ ],+ )+ return rid+++async def test_worst_files_ranks_floored_ties_by_deduction(setup_mcp, floored_health_data):+ """The headline "worst files" list contains the actual worst file.++ Regression: the list sorted on ``score`` alone. The score clamps at 1.0, so+ ties broke by DB order — path order in practice — and on this repo the file+ carrying the largest deduction landed at position 27 of a list capped at 20.+ """+ from repowise.server.mcp_server import get_health++ result = await get_health()+ assert [m["file_path"] for m in result["worst_files"]] == [+ "src/z.py",+ "src/c.py",+ "src/b.py",+ "src/a.py",+ ]++ # The cap is where the old order actually hurt: under a score-only sort the+ # worst file falls off the page entirely.+ capped = await get_health(limit=1)+ assert [m["file_path"] for m in capped["worst_files"]] == ["src/z.py"]+++async def test_worst_files_order_survives_every_dimension_filter(setup_mcp, floored_health_data):+ """Ranking reads the unfiltered open set, whatever the caller asked to see.++ The combination is the point: a cap and a filter interacting is where this+ tool has broken twice. Narrowing the *findings* to one dimension must not+ silently re-rank which files the repo's worst are.+ """+ from repowise.server.mcp_server import get_health++ baseline = [m["file_path"] for m in (await get_health(limit=2))["worst_files"]]+ assert baseline == ["src/z.py", "src/c.py"]++ for include in (["defect"], ["maintainability"], ["performance"], ["biomarkers", "defect"]):+ result = await get_health(include=include, limit=2)+ assert [m["file_path"] for m in result["worst_files"]] == baseline, include+++async def test_one_response_agrees_with_itself_about_the_worst_file(+ setup_mcp, floored_health_data+):+ """``kpis`` and ``worst_files`` must name the same file.++ Regression: ``_compute_kpis`` reduces with ``min()``, which returns the+ *first* minimum, so it answered from whatever order it was handed. Ranking+ ``worst_files`` without also ranking the list behind the KPIs produced a+ payload whose headline named one file as the worst performer while the+ list printed directly beneath it led with another.+ """+ from repowise.server.mcp_server import get_health++ result = await get_health()+ assert result["kpis"]["worst_performer_path"] == result["worst_files"][0]["file_path"]+ assert result["kpis"]["worst_performer_path"] == "src/z.py"++ # Same reduction, same tie, one level down: the module rollup's worst+ # performer is picked with ``min()`` over the same rows.+ assert [m["worst_performer_path"] for m in result["modules"]] == ["src/z.py"]diff --git a/tests/unit/server/test_health_breakdown.py b/tests/unit/server/test_health_breakdown.pyindex f9fbfdb3e..c16876ab5 100644--- a/tests/unit/server/test_health_breakdown.py+++ b/tests/unit/server/test_health_breakdown.py@@ -13,6 +13,7 @@ from types import SimpleNamespacefrom repowise.core.analysis.health.models import Severityfrom repowise.core.analysis.health.scoring import biomarker_weight, severity_deductionfrom repowise.server.routers.code_health import (+ _SORT_KEYS,_finding_base_deduction,_leads_by_file,_primary_and_magnitude,@@ -20,6 +21,41 @@ from repowise.server.routers.code_health import ()+def _target(path, score, total_impact):+ return {+ "file_path": path,+ "score": score,+ "total_impact": total_impact,+ "impact_per_effort": total_impact,+ "finding_count": 1,+ }+++def test_worst_score_sort_breaks_floored_ties_by_impact() -> None:+ """``sort=score`` on the refactoring queue ranks the depth behind the floor.++ The score clamps at 1.0, so sorting on it alone left the top of the "Worst+ score" list in dict-insertion order, which is whatever order the findings+ happened to group in.+ """+ targets = [+ _target("a.py", 1.0, 2.0),+ _target("z.py", 1.0, 9.0),+ _target("m.py", 1.0, 5.0),+ _target("ok.py", 6.0, 40.0),+ ]+ targets.sort(key=_SORT_KEYS["score"])+ assert [t["file_path"] for t in targets] == ["z.py", "m.py", "a.py", "ok.py"]+++def test_worst_score_sort_is_a_total_order() -> None:+ """Equal score and equal impact still order deterministically, so a+ ``limit`` boundary does not shuffle between requests."""+ targets = [_target("b.py", 1.0, 3.0), _target("a.py", 1.0, 3.0)]+ targets.sort(key=_SORT_KEYS["score"])+ assert [t["file_path"] for t in targets] == ["a.py", "b.py"]++def _finding(biomarker_type, severity, health_impact, *, details=None, fid="x", reason="", file_path="f.py"):