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): name one worst file on every surface (#3653)
Swati Ahuja72e68e127fc2
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.pyindex 994714fdc..0f97e5a0c 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py@@ -34,6 +34,7 @@ from repowise.core.analysis.health.counts import (project as project_counts,)from repowise.core.analysis.health.models import split_by_origin+from repowise.core.analysis.health.ranking import deduction_by_pathfrom repowise.core.analysis.health.rows import detail_map, split_unscoredfrom repowise.core.analysis.health.scope import DEFAULT_SCOPE, SCOPES, parse_scopefrom repowise.core.analysis.health.scoring import compute_kpis@@ -311,7 +312,12 @@ def health_command(# Every figure the controls select for. Defect accuracy below is not# one of them: it scores the ranking against `prior_defect`, and# narrowing leaves it no labels to be accurate about.- report.kpis = compute_kpis(metrics, hotspots, unanalysed=unanalysed)+ report.kpis = compute_kpis(+ metrics,+ hotspots,+ unanalysed=unanalysed,+ deductions=deduction_by_path(report.findings),+ )metrics_sorted = sorted(metrics, key=lambda m: m.score)findings = report.findingsdiff --git a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py b/packages/cli/src/repowise/cli/commands/health_cmd/persist.pyindex f12c363a9..0f2e6b5ef 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/persist.py@@ -114,6 +114,7 @@ def _load_stored_report(repo_path: object) -> tuple[Any, set[str], dict[str, strfrom sqlalchemy.exc import SQLAlchemyErrorfrom repowise.cli.helpers import repo_index_session+ from repowise.core.analysis.health.ranking import deduction_by_pathfrom repowise.core.analysis.health.scoring import compute_kpisfrom repowise.core.persistence.crud import (get_file_language_map,@@ -133,7 +134,7 @@ def _load_stored_report(repo_path: object) -> tuple[Any, set[str], dict[str, strfindings = await get_health_findings(session, repo_id)hotspots = await get_hotspot_file_paths(session, repo_id)languages = await get_file_language_map(session, repo_id)- kpis = compute_kpis(metrics, hotspots)+ kpis = compute_kpis(metrics, hotspots, deductions=deduction_by_path(findings))return SimpleNamespace(metrics=metrics, findings=findings, kpis=kpis), hotspots, languagestry:diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex 4ed08d5d7..5ef073f83 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -73,6 +73,7 @@ from .perf import ()from .perf.lazy_load import collect_lazy_loadsfrom .perf.unbounded_reduction import collect_unbounded_reductions+from .ranking import deduction_by_pathfrom .refactoring import (PerformancePlanPolicy,RefactoringContext,@@ -1163,7 +1164,7 @@ class HealthAnalyzer:# KPIs are repo-wide; on an incremental run they would be biased# by the changed-files subset. Skip them in that case — the# ``persist`` step recomputes KPIs from the merged DB rows.- kpis = self._kpis(metrics) if changed_files is None else {}+ kpis = self._kpis(metrics, findings) if changed_files is None else {}with timed(timings, "analysis.health.finalize"):execution_roles = self._mark_perf_entry_reachability(findings)suggestions = self._with_performance_plans(run, findings, suggestions)@@ -1256,9 +1257,11 @@ class HealthAnalyzer:on_step(path)return metrics, findings, suggestions- def _kpis(self, metrics: list[HealthFileMetricData]) -> dict[str, Any]:+ def _kpis(+ self, metrics: list[HealthFileMetricData], findings: list[HealthFindingData]+ ) -> dict[str, Any]:hotspot_paths = {p for p, meta in self.git_meta_map.items() if self._is_hotspot(meta)}- return compute_kpis(metrics, hotspot_paths)+ return compute_kpis(metrics, hotspot_paths, deductions=deduction_by_path(findings))def _with_performance_plans(self,diff --git a/packages/core/src/repowise/core/analysis/health/ranking.py b/packages/core/src/repowise/core/analysis/health/ranking.pyindex de75c023a..0ec1c17c2 100644--- a/packages/core/src/repowise/core/analysis/health/ranking.py+++ b/packages/core/src/repowise/core/analysis/health/ranking.py@@ -21,8 +21,11 @@ from .scoring import SCORE_MAX__all__ = ["deduction_by_path",+ "scope_reason","sort_metrics_worst_first","worst_first_key",+ "worst_in_scope",+ "worst_kpis","worst_metric",]@@ -88,3 +91,51 @@ def worst_metric(rows: Iterable[Any], deductions: Mapping[str, float]) -> Any |return min(production or tests, key=lambda row: worst_first_key(row, deductions), default=None)+++def scope_reason(row: Any) -> str | None:+ """Why Fix first leaves *row*'s file out (``test``, ``tooling``, ``generated``...),+ ``None`` when it is in scope: Fix first's rule on the row's flag and stored origin."""+ # Deferred: the queue pulls in what this module keeps out (see the module docstring).+ from .queue.eligibility import path_verdict++ return path_verdict(+ str(field(row, "file_path", "") or ""),+ field(row, "is_test", False),+ origin=field(row, "code_origin", None),+ ).reason+++def worst_in_scope(+ rows: Iterable[Any], deductions: Mapping[str, float]+) -> tuple[Any | None, Any | None]:+ """``(worst file, worst test)`` every surface names, under the same key.++ The worst file is the head of the dashboard's ``worst_files``: in Fix+ first's scope, so a script, schema or generated file scoring lowest is not+ named. The worst test is the head of ``test_worst_files``. Either is+ ``None`` when its list is empty.+ """+ in_scope: list[Any] = []+ tests: list[Any] = []+ for row in scored_rows(rows):+ reason = scope_reason(row)+ if reason is None:+ in_scope.append(row)+ elif reason == "test":+ tests.append(row)++ def key(row: Any) -> tuple[float, float, str]:+ return worst_first_key(row, deductions)++ return min(in_scope, key=key, default=None), min(tests, key=key, default=None)+++def worst_kpis(rows: Iterable[Any], deductions: Mapping[str, float]) -> dict[str, Any]:+ """The four wire KPIs naming :func:`worst_in_scope`'s pair, ``None`` when absent."""+ out: dict[str, Any] = {}+ pair = worst_in_scope(rows, deductions)+ for prefix, row in zip(("worst_performer", "worst_test"), pair, strict=True):+ out[f"{prefix}_path"] = field(row, "file_path") if row is not None else None+ out[f"{prefix}_score"] = round(float(field(row, "score")), 2) if row is not None else None+ return outdiff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.pyindex f033722af..04ef1f20b 100644--- a/packages/core/src/repowise/core/analysis/health/scoring.py+++ b/packages/core/src/repowise/core/analysis/health/scoring.py@@ -19,7 +19,7 @@ empirical predictors are no longer suppressed by uniform severity values.from __future__ import annotations-from collections.abc import Callable, Iterable+from collections.abc import Callable, Iterable, Mappingfrom dataclasses import replacefrom typing import TYPE_CHECKING, Any@@ -974,13 +974,16 @@ def compute_kpis(hotspot_paths: set[str],*,unanalysed: int = 0,+ deductions: Mapping[str, float] | None = None,) -> dict[str, object]:"""Repo-level KPIs derived from per-file metrics.- ``hotspot_health``: NLOC-weighted average over files in *hotspot_paths*.- ``average_health``: NLOC-weighted average over all files.- - ``worst_performer``: lowest-scoring production file + score, and- ``worst_test_performer`` the same over test files, reported separately.+ - ``worst_performer``: the worst file in Fix first's scope + score, and+ ``worst_test_performer`` the worst test, as ``ranking.worst_in_scope``+ names them; *deductions* (``ranking.deduction_by_path``) breaks score+ ties the way every ranked list does.- ``maintainability_average`` / ``maintainability_hotspot``: the same twoNLOC-weighted averages over the per-file ``maintainability_score``, so themaintainability pillar surfaces a repo headline alongside the defect one.@@ -1009,10 +1012,11 @@ def compute_kpis(hotspots = [m for m in metrics if field(m, "file_path") in hotspot_paths]- production, tests = split_tests(metrics)- # Production first; a test file names the worst only in a tests-only repo.- worst = min(production or metrics, key=_row_score)- worst_test = min(tests, key=_row_score) if tests else None+ # Imported here: ``ranking`` reads this module's score ceiling.+ from .ranking import worst_kpis++ # ``production_average`` keeps its own rule: every non-test file.+ production, _ = split_tests(metrics)maint_avg = nloc_weighted_attr(metrics, "maintainability_score")maint_hotspot = nloc_weighted_attr(hotspots, "maintainability_score")perf_avg = nloc_weighted_attr(metrics, "performance_score")@@ -1031,10 +1035,7 @@ def compute_kpis(return {"hotspot_health": hotspot_kpi if hotspot_kpi is not None else 10.0,"average_health": round(nloc_weighted_score(metrics), 2),- "worst_performer_path": field(worst, "file_path"),- "worst_performer_score": round(_row_score(worst), 2),- "worst_test_path": field(worst_test, "file_path") if worst_test is not None else None,- "worst_test_score": round(_row_score(worst_test), 2) if worst_test is not None else None,+ **worst_kpis(metrics, deductions or {}),"file_count": len(metrics),"maintainability_average": round(maint_avg, 2) if maint_avg is not None else None,"maintainability_hotspot": round(maint_hotspot, 2) if maint_hotspot is not None else None,diff --git a/packages/core/src/repowise/core/generation/editor_files/data.py b/packages/core/src/repowise/core/generation/editor_files/data.pyindex 66e8002c1..252d10476 100644--- a/packages/core/src/repowise/core/generation/editor_files/data.py+++ b/packages/core/src/repowise/core/generation/editor_files/data.py@@ -67,8 +67,8 @@ class CodeHealthBlock:hotspot_health: floataverage_health: float- worst_score: float- worst_path: str+ worst_score: float | None+ worst_path: str | None# The band word for ``average_health``, so the line reads the same# direction as every other surface: a bare "6.9/10" beside a risk-shaped# label is the one reading that inverts.diff --git a/packages/core/src/repowise/core/generation/editor_files/fetcher.py b/packages/core/src/repowise/core/generation/editor_files/fetcher.pyindex 493bf1cad..56504316c 100644--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py@@ -23,7 +23,8 @@ from repowise.core.analysis.health.grading import (headline_band,)from repowise.core.analysis.health.perf.coverage import coverage_for_metrics-from repowise.core.analysis.health.rows import split_tests, split_unscored+from repowise.core.analysis.health.ranking import worst_in_scope+from repowise.core.analysis.health.rows import split_unscoredfrom repowise.core.analysis.health.scoring import hotspot_health, nloc_weighted_scorefrom repowise.core.analysis.health.trends import DECLINE_LOOKBACK, hotspot_trendfrom repowise.core.entry_candidacy import conventional_entry_stems@@ -388,10 +389,11 @@ class EditorFileDataFetcher:# zero-total-weight fallback to a plain mean. The empty case cannot# reach it — ``metric_rows`` is checked above.avg = nloc_weighted_score(metric_rows)- # The worst file names a production file: a test is not the file an- # agent should be told to handle with care.- production, tests = split_tests(metric_rows)- worst = min(production or tests, key=lambda m: m.score)+ # The worst file is the one ``get_overview`` and ``get_health`` name:+ # in Fix first's scope, so not a test, script or generated file.+ worst, _ = worst_in_scope(+ metric_rows, await crud.get_deduction_by_path(self._session, self._repo_id)+ )# Hotspot-flagged paths, and the hotspot KPI over them. Both come from# the shared owners now; this file used to re-derive the same weighted@@ -476,8 +478,8 @@ class EditorFileDataFetcher:average_health=round(avg, 2),band=BAND_LABEL[band] if band is not None else "",analysed_note=analysed_note(len(metric_rows), unanalysed),- worst_score=round(worst.score, 2),- worst_path=worst.file_path,+ worst_score=round(worst.score, 2) if worst is not None else None,+ worst_path=worst.file_path if worst is not None else None,hotspot_trend=hotspot_trend(history),maintainability_average=(round(maintainability_average, 2) if maintainability_average is not None else Nonediff --git a/packages/core/src/repowise/core/generation/templates/agents_md.j2 b/packages/core/src/repowise/core/generation/templates/agents_md.j2index 4ee2298ee..528e49f26 100644--- a/packages/core/src/repowise/core/generation/templates/agents_md.j2+++ b/packages/core/src/repowise/core/generation/templates/agents_md.j2@@ -50,7 +50,7 @@ Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}{% if data.code_health %}### Code health-Three co-equal signals: code health {{ data.code_health.average_health }}/10 avg{% if data.code_health.band or data.code_health.analysed_note %} ({{ [data.code_health.band, data.code_health.analysed_note] | select | join(', ') }}){% endif %}, hotspot health {{ data.code_health.hotspot_health }}/10{% if data.code_health.hotspot_trend %} ({{ data.code_health.hotspot_trend }}){% endif %}, worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% if data.code_health.performance_average is not none %} · performance risk {{ data.code_health.performance_findings }} open static performance finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% endif %}. Detail: `get_health()`.+Three co-equal signals: code health {{ data.code_health.average_health }}/10 avg{% if data.code_health.band or data.code_health.analysed_note %} ({{ [data.code_health.band, data.code_health.analysed_note] | select | join(', ') }}){% endif %}, hotspot health {{ data.code_health.hotspot_health }}/10{% if data.code_health.hotspot_trend %} ({{ data.code_health.hotspot_trend }}){% endif %}{% if data.code_health.worst_path %}, worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% endif %}{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% if data.code_health.performance_average is not none %} · performance risk {{ data.code_health.performance_findings }} open static performance finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% endif %}. Detail: `get_health()`.{% if data.code_health.fix_first %}Fix first:diff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2index 4b03d56b6..de72bda4e 100644--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2@@ -50,7 +50,7 @@ Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}{% if data.code_health %}### Code health-Three co-equal signals: code health {{ data.code_health.average_health }}/10 avg{% if data.code_health.band or data.code_health.analysed_note %} ({{ [data.code_health.band, data.code_health.analysed_note] | select | join(', ') }}){% endif %}, hotspot health {{ data.code_health.hotspot_health }}/10{% if data.code_health.hotspot_trend %} ({{ data.code_health.hotspot_trend }}){% endif %}, worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% if data.code_health.performance_average is not none %} · performance risk {{ data.code_health.performance_findings }} open static performance finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% endif %}. Detail: `get_health()`.+Three co-equal signals: code health {{ data.code_health.average_health }}/10 avg{% if data.code_health.band or data.code_health.analysed_note %} ({{ [data.code_health.band, data.code_health.analysed_note] | select | join(', ') }}){% endif %}, hotspot health {{ data.code_health.hotspot_health }}/10{% if data.code_health.hotspot_trend %} ({{ data.code_health.hotspot_trend }}){% endif %}{% if data.code_health.worst_path %}, worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% endif %}{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% if data.code_health.performance_average is not none %} · performance risk {{ data.code_health.performance_findings }} open static performance finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% endif %}. Detail: `get_health()`.{% if data.code_health.fix_first %}Fix first:diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.pyindex 9f867ddb6..62108986a 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py@@ -30,9 +30,9 @@ from ....analysis.health.grading import analysed_sharefrom ....analysis.health.ranking import (deduction_by_path,sort_metrics_worst_first,- worst_metric,+ worst_kpis,)-from ....analysis.health.rows import detail_map, split_tests, split_unscored+from ....analysis.health.rows import detail_map, split_unscoredfrom ....analysis.health.scope import scores_languagefrom ....analysis.health.scoring import ADVISORY_DIMENSION, SCORE_FIELDS, nloc_weighted_attrfrom ....analysis.health.worth import LowPriority, finding_priorities@@ -854,15 +854,10 @@ async def get_health_summary(findings = await _open_finding_totals_rows(session, repository_id)# Ranked with the same key as ``get_health_metrics``, off the findings this- # function already holds. Previously a plain ``min`` on the score, which- # agreed with the worst-files list only because every caller happened to- # pass an already-ranked list — a floor tie made the headline and the list- # under it disagree the moment one did not.- deductions = deduction_by_path(findings)- worst = worst_metric(metrics, deductions)- # The worst production file heads the page; the worst test file is named- # apart, under the same ranking, so a weak test is not lost behind it.- worst_test = worst_metric(split_tests(metrics)[1], deductions)+ # function already holds, and in Fix first's scope: the file ``get_health``+ # lists first, so a script or schema scoring lowest is not named. The worst+ # test is named apart, so a weak test is not lost behind it.+ worst = worst_kpis(metrics, deduction_by_path(findings))by_dim: dict[str, int] = {}for finding in findings:@@ -888,10 +883,7 @@ async def get_health_summary("unanalysed_file_count": unanalysed,"analysed_share": analysed_share(len(metrics), unanalysed),"average_health": _rounded(avg),- "worst_performer_path": worst.file_path,- "worst_performer_score": round(worst.score, 2),- "worst_test_path": worst_test.file_path if worst_test is not None else None,- "worst_test_score": round(worst_test.score, 2) if worst_test is not None else None,+ **worst,"open_findings": open_finding_count(findings),"maintainability_average": _rounded(maintainability_average),"performance_average": _rounded(performance_average),diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex ca44883c8..b0d16734f 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -2014,6 +2014,7 @@ async def snapshot_health_from_store(session: Any, repo_id: str) -> None:"""from sqlalchemy import select+ from repowise.core.analysis.health.ranking import deduction_by_pathfrom repowise.core.analysis.health.scoring import compute_kpisfrom repowise.core.analysis.health.trends import snapshot_fieldsfrom repowise.core.persistence.crud import get_hotspot_file_paths, save_health_snapshot@@ -2043,7 +2044,11 @@ async def snapshot_health_from_store(session: Any, repo_id: str) -> None:.scalars().all())- kpis = compute_kpis(metrics, await get_hotspot_file_paths(session, repo_id))+ kpis = compute_kpis(+ metrics,+ await get_hotspot_file_paths(session, repo_id),+ deductions=deduction_by_path(findings),+ )fields = snapshot_fields(kpis, metrics, findings)if fields is not None:await save_health_snapshot(session, repo_id, **fields)diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py b/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.pyindex d7ea536f6..42d5efb79 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py@@ -79,15 +79,13 @@ def _dashboard_blocks(data: HealthData, req: HealthRequest, pager: Pager) -> dic# KPIs keep test files unless ``scope`` narrows them. Tests score better# than production code, so narrowing lowers the number with no new defect# found: a caller should ask for it knowingly.- "kpis": lambda: _name_listed_worst(- _compute_kpis(- all_metrics,- hotspot_paths=data.hotspot_paths,- performance_findings=data.perf_findings_count,- coverage=data.perf_coverage,- unanalysed=len(pop.unanalysed_paths),- ),- data,+ "kpis": lambda: _compute_kpis(+ all_metrics,+ hotspot_paths=data.hotspot_paths,+ performance_findings=data.perf_findings_count,+ coverage=data.perf_coverage,+ unanalysed=len(pop.unanalysed_paths),+ deductions=data.deductions,),"distribution": lambda: health_distribution(all_metrics),# Where the gap to the target concentrates: a short list of files.@@ -171,18 +169,6 @@ def _finding_rows(data: HealthData, rows: list[Any]) -> list[dict[str, Any]]:return [_serialize_finding(f, data.reference_repository, labels.get(f.id)) for f in rows]-def _name_listed_worst(kpis: dict[str, Any], data: HealthData) -> dict[str, Any]:- """The worst file and worst test the KPIs name are the heads of the lists,- so a script left out of ``worst_files`` is not named worst either."""- if not kpis.get("file_count"):- return kpis- for prefix, rows in (("worst_performer", data.metric_rows), ("worst_test", data.test_metric_rows)):- head = rows[0] if rows else None- kpis[f"{prefix}_path"] = head.file_path if head else None- kpis[f"{prefix}_score"] = round(head.score, 2) if head else None- return kpis--def _metric_row(data: HealthData, m: Any) -> dict[str, Any]:return _serialize_metric(m, data.leads.get(m.file_path), is_test=m.file_path in data.test_paths)diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py b/packages/server/src/repowise/server/mcp_server/tool_health/loading.pyindex 4677d1cec..6d6a2ba8e 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py@@ -19,8 +19,11 @@ from repowise.core.analysis.health.churn_complexity import churn_complexity_poinfrom repowise.core.analysis.health.fix_first import FixFirstQueuefrom repowise.core.analysis.health.grading import TARGET_SCOREfrom repowise.core.analysis.health.perf.coverage import PerfCoverage, coverage_for_metrics-from repowise.core.analysis.health.queue.eligibility import path_verdict-from repowise.core.analysis.health.ranking import deduction_by_path, sort_metrics_worst_first+from repowise.core.analysis.health.ranking import (+ deduction_by_path,+ scope_reason,+ sort_metrics_worst_first,+)from repowise.core.analysis.health.refactoring.serving import parse_query as parse_refactoring_queryfrom repowise.core.analysis.health.signals import file_signalsfrom repowise.core.analysis.health.trends import project_scope@@ -214,10 +217,7 @@ def _scope_reasons(metrics: list[HealthFileMetric]) -> dict[str, str | None]:Ceiling: recomputed per process (about 0.3 s cold on 5k files, 1.2 s on 18k; 0.02 swarm). Upgrade path: persist the verdict per file when the health pass finalizes."""- return {- m.file_path: path_verdict(m.file_path, m.is_test, origin=m.code_origin).reason- for m in metrics- }+ return {m.file_path: scope_reason(m) for m in metrics}async def _read_test_paths(diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/summary.py b/packages/server/src/repowise/server/mcp_server/tool_health/summary.pyindex 6da5070b4..f7cc5741d 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/summary.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/summary.py@@ -8,7 +8,7 @@ from repowise.core.analysis.health.complexity.languages import NO_DIALECT_STATUSfrom repowise.core.analysis.health.grading import TARGET_SCORE, analysed_share, headline_bandfrom repowise.core.analysis.health.models import primary_finding, split_by_originfrom repowise.core.analysis.health.perf.coverage import PerfCoverage-from repowise.core.analysis.health.rows import split_tests+from repowise.core.analysis.health.ranking import worst_kpisfrom repowise.core.analysis.health.scoring import (hotspot_health,nloc_weighted_attr,@@ -142,9 +142,11 @@ def _compute_kpis(performance_findings: int = 0,coverage: PerfCoverage | None = None,unanalysed: int = 0,+ deductions: dict[str, float],) -> dict[str, Any]:"""*metrics* are scored rows; *unanalysed* counts the files left out of- them because health has no dialect for their language."""+ them because health has no dialect for their language. *deductions* is the+ worst-first tiebreak ``get_health_metrics`` ranks with."""if not metrics:return {"file_count": 0,@@ -165,10 +167,6 @@ def _compute_kpis(}total_nloc = sum(max(m.nloc, 1) for m in metrics)avg = sum(m.score * max(m.nloc, 1) for m in metrics) / total_nloc- # Production first; test files are ranked apart and named on their own.- production, tests = split_tests(metrics)- worst = min(production or metrics, key=lambda r: r.score)- worst_test = min(tests, key=lambda r: r.score) if tests else Noneshare = analysed_share(len(metrics), unanalysed)return {"file_count": len(metrics),@@ -182,10 +180,8 @@ def _compute_kpis("band": headline_band(round(avg, 2), share),# Only said when some files were left out, as ``unanalysed_file_count`` is.**({"analysed_share": share} if unanalysed else {}),- "worst_performer_path": worst.file_path,- "worst_performer_score": round(worst.score, 2),- "worst_test_path": worst_test.file_path if worst_test else None,- "worst_test_score": round(worst_test.score, 2) if worst_test else None,+ # The heads of ``worst_files`` and ``test_worst_files``, as REST names them.+ **worst_kpis(metrics, deductions),# ``None`` until the pillar is measured."maintainability_average": _avg(metrics, "maintainability_score"),"performance_average": _avg(metrics, "performance_score"),diff --git a/tests/unit/health/test_ranking_contract.py b/tests/unit/health/test_ranking_contract.pyindex 5c335d6e1..56d0b5764 100644--- a/tests/unit/health/test_ranking_contract.py+++ b/tests/unit/health/test_ranking_contract.py@@ -17,9 +17,10 @@ from repowise.core.analysis.health.ranking import (deduction_by_path,sort_metrics_worst_first,worst_first_key,+ worst_in_scope,worst_metric,)-from repowise.core.analysis.health.scoring import SCORE_FLOOR+from repowise.core.analysis.health.scoring import SCORE_FLOOR, compute_kpis@dataclass@@ -166,6 +167,22 @@ def test_worst_metric_is_none_for_no_rows() -> None:assert worst_metric([], {}) is None+def test_worst_in_scope_skips_files_fix_first_leaves_out() -> None:+ """A script or generated file scoring lowest is not named; KPIs agree."""+ rows = [+ {**_dict("scripts/migrate.py", 1.0), "code_origin": "tooling"},+ {**_dict("src/gen/schema_pb2.py", 1.0), "code_origin": "generated"},+ {**_dict("tests/test_app.py", 2.0), "is_test": True},+ _dict("src/app.py", 3.0),+ ]+ worst, worst_test = worst_in_scope(rows, {})+ assert (worst["file_path"], worst_test["file_path"]) == ("src/app.py", "tests/test_app.py")+ kpis = compute_kpis(rows, set())+ assert kpis["worst_performer_path"] == "src/app.py"+ assert kpis["worst_test_path"] == "tests/test_app.py"+ assert worst_in_scope(rows[:2], {}) == (None, None)++def test_the_deduction_map_has_no_default() -> None:"""Omitting it would silently tie the whole floor band on path."""with pytest.raises(TypeError):diff --git a/tests/unit/server/mcp/test_failing_types_surfaces.py b/tests/unit/server/mcp/test_failing_types_surfaces.pyindex 516c6fb66..543a2012e 100644--- a/tests/unit/server/mcp/test_failing_types_surfaces.py+++ b/tests/unit/server/mcp/test_failing_types_surfaces.py@@ -173,3 +173,40 @@ async def test_perf_text_has_no_n_plus_one_without_db(setup_mcp, failing_types_dfor f in perf:if f["details"].get("boundary_kind") != "db":assert "N+1" not in f["reason"]+++async def test_overview_and_health_name_one_worst_file(setup_mcp, session, failing_types_data):+ """A script and a generated schema scoring lowest are out of Fix first's+ scope, so get_overview, the REST summary and get_health all name the same+ production file as the worst."""+ from repowise.core.persistence.crud import get_health_summary+ from repowise.server.mcp_server import get_health, get_overview++ for path, origin in (("scripts/migrate.py", "tooling"), ("src/proto/schema_pb2.py", "generated")):+ session.add(+ HealthFileMetric(+ repository_id=failing_types_data,+ file_path=path,+ score=1.0,+ max_ccn=40,+ max_nesting=6,+ nloc=900,+ has_test_file=False,+ module=path.split("/")[0],+ is_test=False,+ code_origin=origin,+ )+ )+ await session.commit()++ summary = await get_health_summary(session, failing_types_data)+ overview = (await get_overview())["code_health"]+ kpis = (await get_health(only=["kpis", "worst_files"]))["kpis"]+ assert (+ summary["worst_performer_path"]+ == overview["worst_performer_path"]+ == kpis["worst_performer_path"]+ == "src/auth/service.py"+ )+ assert summary["worst_test_path"] == kpis["worst_test_path"] == "tests/test_service.py"diff --git a/tests/unit/server/test_health_worst_file_scope.py b/tests/unit/server/test_health_worst_file_scope.pynew file mode 100644index 000000000..e27f39c5c--- /dev/null+++ b/tests/unit/server/test_health_worst_file_scope.py@@ -0,0 +1,46 @@+"""The REST health summaries name the worst file in Fix first's scope.++A script or generated file scoring lowest is not the file to work on, so both+REST payloads name the production file ``get_health`` lists first.+"""++from __future__ import annotations++from repowise.core.analysis.health.models import HealthFileMetricData+from repowise.core.persistence.crud import save_health_metrics, upsert_repository++from .conftest import create_test_repo+++def _metric(path: str, score: float, origin: str | None = None) -> HealthFileMetricData:+ return HealthFileMetricData(+ file_path=path,+ score=score,+ max_ccn=1,+ max_nesting=1,+ nloc=100,+ has_test_file=False,+ defect_score=score,+ code_origin=origin,+ )+++async def test_rest_summaries_skip_out_of_scope_files(client, session, tmp_path) -> None:+ repo = await create_test_repo(client, tmp_path)+ await upsert_repository(session, name="r", local_path=repo["local_path"])+ await save_health_metrics(+ session,+ repo["id"],+ [+ _metric("scripts/migrate.py", 1.0, "tooling"),+ _metric("src/proto/schema_pb2.py", 1.5, "generated"),+ _metric("src/app/service.py", 4.0),+ _metric("src/app/models.py", 8.0),+ ],+ )+ await session.commit()++ health = (await client.get(f"/api/repos/{repo['id']}/health/overview")).json()+ overview = (await client.get(f"/api/repos/{repo['id']}/overview-summary")).json()+ assert health["summary"]["worst_performer_path"] == "src/app/service.py"+ assert overview["health"]["worst_performer_path"] == "src/app/service.py"