Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

refactor(health): give hotspot health one owner, computed live (#1552)

Swati Ahuja1014764ce471
diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.py
index d13a075fa..2d9c34287 100644
--- a/packages/cli/src/repowise/cli/commands/status_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py
@@ -190,6 +190,7 @@ def _query_health(repo_path: Path) -> dict | None:
return None
async def _q() -> dict | None:
+ from repowise.core.analysis.health.scoring import hotspot_health
from repowise.core.persistence import (
create_engine,
create_session_factory,
@@ -198,6 +199,7 @@ def _query_health(repo_path: Path) -> dict | None:
from repowise.core.persistence.crud import (
get_health_metrics,
get_health_summary,
+ get_hotspot_file_paths,
get_repository_by_path,
)
@@ -210,23 +212,21 @@ def _query_health(repo_path: Path) -> dict | None:
repo = await get_repository_by_path(session, str(repo_path))
if repo is None:
return None
- summary = await get_health_summary(session, repo.id)
+ # Load the metrics once and hand them to the summary. Without
+ # the ``metrics=`` handoff the summary reads the whole table
+ # itself, so this function used to read it twice per
+ # ``repowise status`` (and recompute the findings aggregate and
+ # the worst-first sort twice with it).
+ metrics = await get_health_metrics(session, repo.id)
+ summary = await get_health_summary(session, repo.id, metrics=metrics)
if summary["file_count"] == 0:
return None
- metrics = await get_health_metrics(session, repo.id)
- # Hotspot health: NLOC-weighted avg of top-25% files by NLOC.
- if metrics:
- by_nloc = sorted(metrics, key=lambda m: m.nloc or 0, reverse=True)
- top = by_nloc[: max(1, len(by_nloc) // 4)]
- tot = sum(max(m.nloc, 1) for m in top)
- hotspot = (
- sum(m.score * max(m.nloc, 1) for m in top) / tot
- if tot
- else summary["average_health"]
- )
- else:
- hotspot = summary["average_health"]
- return {**summary, "hotspot_health": round(hotspot, 2)}
+ # Hotspot health from the one owner. This used to average the
+ # top 25% of files by NLOC, which ranks size rather than churn;
+ # it is the same wrong definition ``get_overview`` carried, so
+ # the two agreed with each other and with no other surface.
+ hotspot_paths = await get_hotspot_file_paths(session, repo.id)
+ return {**summary, "hotspot_health": hotspot_health(metrics, hotspot_paths)}
finally:
await engine.dispose()
@@ -267,10 +267,15 @@ def _query_health_line(repo_path: Path) -> str | None:
if perf is not None
else ""
)
+ # ``None`` when the repo has no hotspot files, so the segment is dropped
+ # rather than printing a 10.0 that would read as "your hotspots are
+ # perfect" when there are none to score.
+ hotspot = data.get("hotspot_health")
+ hotspot_part = f"{hotspot:.1f} (hotspots) · " if hotspot is not None else ""
return (
f"[bold]Health:[/bold] {data['average_health']:.1f} (avg) "
f"[[{band_color}]{BAND_LABEL[band]}[/{band_color}]] · "
- f"{data['hotspot_health']:.1f} (hotspots) · "
+ f"{hotspot_part}"
f"{worst_repr} (worst: {worst_path})"
f"{maint_part}"
f"{perf_part}"
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.py
index cd924e93f..8e3cce832 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -673,6 +673,52 @@ def _wavg_attr(rows: list[HealthFileMetricData], attr: str) -> float | None:
return sum(getattr(r, attr) * max(r.nloc, 1) for r in scored) / total_w
+def nloc_weighted_score(rows: list[HealthFileMetricData]) -> float:
+ """NLOC-weighted mean of ``score``, weighting each file by ``max(nloc, 1)``.
+
+ Returns 10.0 for an empty input. Callers that can distinguish "nothing to
+ average" from "averaged to a perfect score" should check emptiness first —
+ :func:`hotspot_health` does exactly that.
+ """
+ if not rows:
+ return 10.0
+ total_w = sum(max(r.nloc, 1) for r in rows)
+ if total_w == 0:
+ return sum(r.score for r in rows) / len(rows)
+ return sum(r.score * max(r.nloc, 1) for r in rows) / total_w
+
+
+def hotspot_health(
+ metrics: list[HealthFileMetricData],
+ hotspot_paths: set[str],
+) -> float | None:
+ """The repo's hotspot health: NLOC-weighted score over its hotspot files.
+
+ **This is the only implementation of that question.** Four places computed
+ it and two more read a persisted copy. Of the four, two averaged the top 25%
+ of files *by NLOC*, which ranks size rather than churn and so answers a
+ different question: measured against this definition across 42 local
+ indexes they differed on all 42, median 2.67 points of 10, worst 6.46, and
+ read *higher* on 31 — the wrong definition was also the flattering one. The
+ other two agreed here and differed only over what to say when a repo has no
+ hotspot files. Anything that wants this number calls here.
+
+ *hotspot_paths* is the set git flagged ``is_hotspot``: top-quartile churn
+ **and** the absolute activity floors from issue #361.
+
+ ``None`` means the repo has no hotspot files at all, which is a real answer
+ and not a failure — a repo with no recent churn has nothing to be a hotspot.
+ It is kept distinct from a low score on purpose: averaging an empty set
+ yields 10.0, and reporting that would tell a user their hotspots are perfect
+ when they have none. :func:`compute_kpis` still floors it to 10.0 for the
+ persisted KPI, and says why there.
+ """
+ rows = [m for m in metrics if m.file_path in hotspot_paths]
+ if not rows:
+ return None
+ return round(nloc_weighted_score(rows), 2)
+
+
def compute_kpis(
metrics: list[HealthFileMetricData],
hotspot_paths: set[str],
@@ -704,23 +750,21 @@ def compute_kpis(
"performance_hotspot": None,
}
- def _wavg(rows: list[HealthFileMetricData]) -> float:
- if not rows:
- return 10.0
- total_w = sum(max(r.nloc, 1) for r in rows)
- if total_w == 0:
- return sum(r.score for r in rows) / len(rows)
- return sum(r.score * max(r.nloc, 1) for r in rows) / total_w
-
hotspots = [m for m in metrics if m.file_path in hotspot_paths]
worst = min(metrics, key=lambda m: m.score)
maint_avg = _wavg_attr(metrics, "maintainability_score")
maint_hotspot = _wavg_attr(hotspots, "maintainability_score")
perf_avg = _wavg_attr(metrics, "performance_score")
perf_hotspot = _wavg_attr(hotspots, "performance_score")
+ # Floored to 10.0 when the repo has no hotspot files, because this dict is
+ # what ``save_health_snapshot`` persists into a non-nullable column and what
+ # the trend alerts diff against. The floor lives here, at the one point that
+ # needs it, rather than inside the arithmetic — surfaces that can say "no
+ # hotspots" out loud read ``hotspot_health()`` and get ``None``.
+ hotspot_kpi = hotspot_health(metrics, hotspot_paths)
return {
- "hotspot_health": round(_wavg(hotspots), 2),
- "average_health": round(_wavg(metrics), 2),
+ "hotspot_health": hotspot_kpi if hotspot_kpi is not None else 10.0,
+ "average_health": round(nloc_weighted_score(metrics), 2),
"worst_performer_path": worst.file_path,
"worst_performer_score": round(worst.score, 2),
"file_count": len(metrics),
diff --git a/packages/core/src/repowise/core/generation/editor_files/fetcher.py b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
index 3383b3eb9..d8749d86c 100644
--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py
+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
@@ -16,6 +16,7 @@ from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.perf.coverage import coverage_for_metrics
+from repowise.core.analysis.health.scoring import hotspot_health, nloc_weighted_score
from repowise.core.persistence import crud
from repowise.core.persistence.models import (
DecisionRecord,
@@ -303,32 +304,29 @@ class EditorFileDataFetcher:
if not metric_rows:
return None
- # KPIs.
- total_nloc = sum(max(m.nloc, 1) for m in metric_rows)
- avg = (
- sum(m.score * max(m.nloc, 1) for m in metric_rows) / total_nloc
- if total_nloc
- else sum(m.score for m in metric_rows) / len(metric_rows)
- )
+ # KPIs. The weighting is the shared one rather than a fourth copy of it:
+ # this reimplemented ``nloc_weighted_score`` exactly, including the
+ # 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)
worst = min(metric_rows, key=lambda m: m.score)
- # Hotspot-flagged paths.
- hotspot_paths_res = await self._session.execute(
- select(GitMetadata.file_path).where(
- GitMetadata.repository_id == self._repo_id,
- GitMetadata.is_hotspot == True, # noqa: E712
- )
- )
- hotspot_paths = {row[0] for row in hotspot_paths_res.all()}
-
- hotspot_metrics = [m for m in metric_rows if m.file_path in hotspot_paths]
- if hotspot_metrics:
- h_nloc = sum(max(m.nloc, 1) for m in hotspot_metrics)
- hotspot_health = (
- sum(m.score * max(m.nloc, 1) for m in hotspot_metrics) / h_nloc if h_nloc else avg
- )
- else:
- hotspot_health = avg
+ # 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
+ # average inline and the same path query inline, and agreed with the
+ # canonical KPI only by coincidence.
+ hotspot_paths = await crud.get_hotspot_file_paths(self._session, self._repo_id)
+ hotspot_kpi = hotspot_health(metric_rows, hotspot_paths)
+
+ # CEILING: when the repo has no hotspot files the honest answer is "no
+ # hotspots", and every other surface now says so by omitting the number.
+ # This one still substitutes the repo average, because saying nothing
+ # means making the figure optional in ``claude_md.j2`` / ``agents_md.j2``
+ # — and that same template line is the subject of issue #1490, which an
+ # outside contributor has claimed. UPGRADE PATH: once #1490 lands and the
+ # line renders conditionally, drop this fallback and pass ``hotspot_kpi``
+ # straight through. Affects only repos with no recent churn at all.
+ hotspot_for_claude_md = hotspot_kpi if hotspot_kpi is not None else avg
# Maintainability pillar headline: NLOC-weighted over the per-file
# maintainability scores, skipping rows that predate the split. ``None``
@@ -406,7 +404,7 @@ class EditorFileDataFetcher:
)
return CodeHealthBlock(
- hotspot_health=round(hotspot_health, 2),
+ hotspot_health=round(hotspot_for_claude_md, 2),
average_health=round(avg, 2),
worst_score=round(worst.score, 2),
worst_path=worst.file_path,
diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.py
index 670a8e623..8d36881c9 100644
--- a/packages/core/src/repowise/core/persistence/crud/git.py
+++ b/packages/core/src/repowise/core/persistence/crud/git.py
@@ -105,6 +105,25 @@ async def get_all_git_metadata(session: AsyncSession, repository_id: str) -> dic
return {gm.file_path: gm for gm in result.scalars().all()}
+async def get_hotspot_file_paths(session: AsyncSession, repository_id: str) -> set[str]:
+ """The file paths git flagged ``is_hotspot``, as a set.
+
+ One scalar column, no entity hydration: every caller wants membership, and
+ :func:`get_all_git_metadata` would load each row's full ORM object to answer
+ it. Shared rather than inlined because the hotspot set defines what
+ ``hotspot_health`` averages over, and a surface that scopes it differently
+ silently answers a different question — which is how the KPI came to have
+ four implementations.
+ """
+ result = await session.execute(
+ select(GitMetadata.file_path).where(
+ GitMetadata.repository_id == repository_id,
+ GitMetadata.is_hotspot.is_(True),
+ )
+ )
+ return {row[0] for row in result.all() if row[0] is not None}
+
+
#: The only git fields dead-code confidence is scored from
#: (``analyzer._make_unreachable_finding`` and its sibling detectors).
_DEAD_CODE_GIT_FIELDS = (
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.py
index 33f6ffcca..0b4f74936 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py
@@ -17,6 +17,7 @@ from repowise.core.analysis.health.defect_accuracy import compute_defect_accurac
from repowise.core.analysis.health.grading import HEALTHY_MIN, band_for
from repowise.core.analysis.health.grading import distribution as health_distribution
from repowise.core.analysis.health.perf.coverage import PerfCoverage, coverage_for_metrics
+from repowise.core.analysis.health.scoring import hotspot_health
from repowise.core.analysis.health.signals import file_signals
from repowise.core.analysis.health.suggestions import suggestion_for
from repowise.core.analysis.health.trends import diff_snapshots, file_trend, recent_kpis
@@ -26,6 +27,7 @@ from repowise.core.persistence.crud import (
get_coverage_summary,
get_file_language_map,
get_git_metadata_bulk,
+ get_hotspot_file_paths,
get_node_degree_counts_bulk,
get_refactoring_suggestions,
get_test_file_paths,
@@ -756,6 +758,7 @@ def _code_only(
def _compute_kpis(
metrics: list[HealthFileMetric],
*,
+ hotspot_paths: set[str] | None = None,
performance_findings: int = 0,
coverage: PerfCoverage | None = None,
lang_by_path: dict[str, str] | None = None,
@@ -764,6 +767,7 @@ def _compute_kpis(
return {
"file_count": 0,
"average_health": 10.0,
+ "hotspot_health": None,
"worst_performer_path": None,
"worst_performer_score": None,
"maintainability_average": None,
@@ -797,6 +801,11 @@ def _compute_kpis(
return {
"file_count": len(metrics),
"average_health": round(avg, 2),
+ # ``None`` when the repo has no hotspot files, which is a real answer:
+ # the alternative is averaging an empty set to a perfect 10.0 and
+ # reporting it as a score, the same fabricated-10.0 problem the comment
+ # above objects to for non-code rows.
+ "hotspot_health": hotspot_health(metrics, hotspot_paths or set()),
**code_kpis,
# NLOC-weighted (``average_health``) vs plain file mean. When these
# diverge, a few large low-scoring files are holding the headline down —
@@ -1141,6 +1150,15 @@ async def get_health(
else all_metrics
)
+ # Hotspot health was the one repo KPI this tool never returned, while
+ # ``get_overview`` invented its own definition for it — so the canonical
+ # persisted number was surfaced by neither. One scalar column, gated the
+ # same way as the language map below: ``targets`` mode builds no ``kpis``
+ # block at all, so scoping the call must not pay for this read.
+ hotspot_paths: set[str] = set()
+ if not scoped and wants("kpis"):
+ hotspot_paths = await get_hotspot_file_paths(session, repository.id)
+
# 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.
@@ -1341,6 +1359,7 @@ async def get_health(
# findings compete for a ranked list, not about what the score means.
kpis = _compute_kpis(
metric_rows if scoped else all_metrics,
+ hotspot_paths=hotspot_paths,
performance_findings=perf_findings_count,
coverage=perf_coverage,
lang_by_path=lang_by_path,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.py
index d575df859..472f7407e 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py
@@ -16,6 +16,7 @@ from repowise.core.analysis.health.grading import (
from repowise.core.analysis.health.grading import (
distribution as health_distribution,
)
+from repowise.core.analysis.health.scoring import hotspot_health
from repowise.core.generation.onboarding.slots import (
ONBOARDING_ORDER,
PROMOTED_SLOTS,
@@ -26,6 +27,9 @@ from repowise.core.persistence.crud import (
from repowise.core.persistence.crud import (
get_health_summary as _get_health_summary,
)
+from repowise.core.persistence.crud import (
+ get_hotspot_file_paths,
+)
from repowise.core.persistence.crud import (
get_kg_layers as _get_kg_layers,
)
@@ -726,16 +730,17 @@ async def _build_code_health(session: Any, repository: Any) -> dict[str, Any]:
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)
- top_q = sorted_by_nloc[: max(1, len(sorted_by_nloc) // 4)]
- tot = sum(max(m.nloc, 1) for m in top_q)
- hotspot_avg = sum(m.score * max(m.nloc, 1) for m in top_q) / tot if tot else 10.0
+ # Hotspot health from the one owner, over the rows already loaded above.
+ # This used to average the top 25% of files *by NLOC* under a comment
+ # claiming it matched the dashboard; it never did. That ranks size, not
+ # churn, and it disagreed with the persisted KPI on all 42 local indexes
+ # (median 2.67 of 10, worst 6.46), reading higher on 31 of them. It also
+ # sorted every file row to produce one float.
+ hotspot_paths = await get_hotspot_file_paths(session, repository.id)
return {
"average_health": health_summary["average_health"],
"band": band_for(float(health_summary["average_health"])),
- "hotspot_health": round(hotspot_avg, 2),
+ "hotspot_health": hotspot_health(metrics_rows, hotspot_paths),
"worst_performer_path": health_summary["worst_performer_path"],
"worst_performer_score": health_summary["worst_performer_score"],
"open_findings": health_summary["open_findings"],
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.py
index 9b7ffab1b..2ce44fef3 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
@@ -10,6 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracy
from repowise.core.analysis.health.grading import band_for
from repowise.core.analysis.health.grading import distribution as health_distribution
+from repowise.core.analysis.health.scoring import hotspot_health
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session
from repowise.server.mcp_server._meta import resolve_indexed_commit
@@ -60,14 +61,21 @@ async def health_overview(
session, repo_id, metrics=metrics, findings=findings
)
- # Pull hotspot_health from the latest snapshot (KPIs aren't recomputed
- # on every overview hit — the snapshot is authoritative). Scalars only:
- # a full snapshot entity drags its per-file score map, and this route reads
- # none of it.
+ # Hotspot health is recomputed from the metrics already loaded above rather
+ # than read off the latest snapshot. The snapshot was described here as
+ # authoritative, and it is not: ``repowise update`` re-scores health and
+ # calls ``save_health_metrics`` without ``save_health_snapshot``
+ # (``update_cmd/persistence.py``), so after any update this route served a
+ # figure from the previous full index while every other number on the page
+ # came from the fresh rows. Measured stale on 3 of 42 local indexes, this
+ # repo among them (4.62 against 5.08 live) — a lower bound, since a corpus
+ # of frozen clones mostly has nothing to have gone stale against.
+ #
+ # It costs no query: ``metrics`` is already in hand, and the hotspot path
+ # set is one scalar column. The snapshot is still read, for ``taken_at``.
snapshot = await crud.get_health_snapshot_headline(session, repo_id)
- hotspot_health = (
- round(snapshot.hotspot_health, 2) if snapshot.hotspot_health is not None else None
- )
+ hotspot_paths = await crud.get_hotspot_file_paths(session, repo_id)
+ hotspot_health_value = hotspot_health(metrics, hotspot_paths)
last_indexed_at = _resolve_last_indexed_at(snapshot.taken_at, repo.updated_at)
@@ -79,7 +87,7 @@ async def health_overview(
avg = summary.get("average_health")
summary = {
**summary,
- "hotspot_health": hotspot_health,
+ "hotspot_health": hotspot_health_value,
"severity_breakdown": _severity_breakdown(findings),
"band": band_for(float(avg)) if avg is not None else None,
}
diff --git a/packages/server/src/repowise/server/routers/overview.py b/packages/server/src/repowise/server/routers/overview.py
index 86ce0535b..9cdbcd2ed 100644
--- a/packages/server/src/repowise/server/routers/overview.py
+++ b/packages/server/src/repowise/server/routers/overview.py
@@ -20,6 +20,7 @@ from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.health.scoring import hotspot_health
from repowise.core.persistence import crud
from repowise.core.persistence.models import (
DeadCodeFinding,
@@ -388,7 +389,16 @@ async def overview_summary(
snapshot = await crud.get_health_snapshot_headline(
session, repo_id, recent=HEALTH_HISTORY_POINTS
)
- hotspot_health: float | None = None
+ # The headline is the *current* number, so it comes from the metrics loaded
+ # above rather than off the newest snapshot: ``repowise update`` re-scores
+ # health without writing a snapshot, so the stored value can lag the rows
+ # every other figure on this page is built from. Costs no extra query.
+ #
+ # ``history`` and ``deltas`` below stay snapshot-derived on purpose. They
+ # are a series of recorded runs, and there is no live value for "the run
+ # before this one", so the delta means "since the last recorded snapshot".
+ hotspot_paths = await crud.get_hotspot_file_paths(session, repo_id)
+ hotspot_health_value = hotspot_health(health_metrics, hotspot_paths)
last_indexed_at: str | None = None
deltas: dict[str, float | None] = {
"average_health": None,
@@ -396,7 +406,6 @@ async def overview_summary(
"file_count": None,
}
if snapshot.snapshot_count:
- hotspot_health = round(float(snapshot.hotspot_health), 2)
last_indexed_at = snapshot.taken_at.isoformat() if snapshot.taken_at else None
if len(snapshot.recent) >= 2:
prev, cur = snapshot.recent[-2], snapshot.recent[-1]
@@ -580,7 +589,7 @@ async def overview_summary(
},
"health": {
"average_health": health_summary.get("average_health"),
- "hotspot_health": hotspot_health,
+ "hotspot_health": hotspot_health_value,
"worst_performer_path": health_summary.get("worst_performer_path"),
"worst_performer_score": health_summary.get("worst_performer_score"),
"open_findings": health_summary.get("open_findings", 0),
diff --git a/tests/unit/health/test_hotspot_health.py b/tests/unit/health/test_hotspot_health.py
new file mode 100644
index 000000000..cee040d05
--- /dev/null
+++ b/tests/unit/health/test_hotspot_health.py
@@ -0,0 +1,135 @@
+"""The hotspot-health KPI has one definition (P10).
+
+Four implementations of this number shipped at once and disagreed on all 42
+local indexes. Nothing pinned the arithmetic: ``test_scoring.py`` exercised
+``compute_kpis`` but never asserted ``kpis["hotspot_health"]``, and the two
+surfaces carrying the wrong definition had no tests at all, so swapping them
+would have been green.
+
+These tests pin the number itself. ``test_no_hotspot_health_copies.py`` is the
+other half — it fails when a *second* implementation appears.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from repowise.core.analysis.health.scoring import (
+ compute_kpis,
+ hotspot_health,
+ nloc_weighted_score,
+)
+
+
+@dataclass
+class _Metric:
+ """The three attributes the KPI reads off a per-file metric row."""
+
+ file_path: str
+ score: float
+ nloc: int
+ maintainability_score: float | None = None
+ performance_score: float | None = None
+
+
+def test_hotspot_health_weights_by_nloc_not_by_file() -> None:
+ """A big bad file outweighs a small good one; a plain mean would not."""
+ rows = [
+ _Metric("big.py", 2.0, 900),
+ _Metric("small.py", 9.0, 100),
+ ]
+ got = hotspot_health(rows, {"big.py", "small.py"})
+ # NLOC-weighted: (2.0*900 + 9.0*100) / 1000 == 2.7. The unweighted mean is
+ # 5.5, so this assertion fails if the weighting is ever dropped.
+ assert got == 2.7
+
+
+def test_hotspot_health_averages_only_the_hotspot_files() -> None:
+ """Files outside the hotspot set contribute nothing, whatever their size."""
+ rows = [
+ _Metric("hot.py", 3.0, 100),
+ _Metric("cold.py", 10.0, 10_000),
+ ]
+ assert hotspot_health(rows, {"hot.py"}) == 3.0
+
+
+def test_hotspot_health_is_none_when_the_repo_has_no_hotspots() -> None:
+ """No hotspots is a real answer, and it is not a perfect score.
+
+ Averaging an empty set yields 10.0, which would tell a user their hotspots
+ are in perfect health when they have none. 11 of 42 local indexes are in
+ this state.
+ """
+ rows = [_Metric("a.py", 4.0, 100)]
+ assert hotspot_health(rows, set()) is None
+
+
+def test_hotspot_health_ignores_hotspot_paths_with_no_metric_row() -> None:
+ """A git hotspot that health never scored cannot drag the average."""
+ rows = [_Metric("scored.py", 6.0, 100)]
+ assert hotspot_health(rows, {"scored.py", "never-scored.py"}) == 6.0
+
+
+def test_nloc_floor_keeps_a_zero_nloc_file_from_vanishing() -> None:
+ """``max(nloc, 1)`` — a 0-NLOC row still counts, at weight 1."""
+ rows = [_Metric("empty.py", 0.0, 0), _Metric("real.py", 10.0, 1)]
+ assert hotspot_health(rows, {"empty.py", "real.py"}) == 5.0
+
+
+def test_compute_kpis_floors_the_persisted_kpi_to_ten() -> None:
+ """The persisted contract is unchanged: a float, 10.0 when no hotspots.
+
+ ``save_health_snapshot`` writes this into a non-nullable column and the
+ trend alerts diff against it, so ``None`` must not reach it. The honest
+ ``None`` is what ``hotspot_health`` returns to surfaces that can render it.
+ """
+ rows = [_Metric("a.py", 4.0, 100)]
+ kpis = compute_kpis(rows, set())
+ assert kpis["hotspot_health"] == 10.0
+ assert hotspot_health(rows, set()) is None
+
+
+def test_compute_kpis_hotspot_health_matches_the_shared_owner() -> None:
+ """The persisted KPI and the surfaces cannot drift apart."""
+ rows = [
+ _Metric("hot.py", 3.0, 200),
+ _Metric("cold.py", 9.0, 100),
+ ]
+ hotspots = {"hot.py"}
+ assert compute_kpis(rows, hotspots)["hotspot_health"] == hotspot_health(rows, hotspots)
+
+
+def test_hotspot_health_is_not_the_top_quartile_by_nloc() -> None:
+ """The definition two surfaces shipped, named so it cannot come back.
+
+ ``get_overview`` and ``repowise status`` both averaged the top 25% of files
+ *by NLOC* under a comment claiming it matched the dashboard. That ranks size
+ rather than churn, so it answers a different question and read *higher* than
+ the real KPI on 31 of 42 local indexes.
+
+ Here the biggest file is not a hotspot and the one hotspot is tiny, so the
+ two definitions land far apart: quartile 2.0, owner 9.0.
+ """
+ rows = [
+ _Metric("big-but-calm.py", 2.0, 1000),
+ _Metric("small-but-churny.py", 9.0, 10),
+ ]
+
+ # What the retired implementation computed, spelled out rather than
+ # imported, so deleting it cannot make this test vacuous.
+ by_nloc = sorted(rows, key=lambda m: m.nloc, reverse=True)
+ top_q = by_nloc[: max(1, len(by_nloc) // 4)]
+ quartile = sum(m.score * max(m.nloc, 1) for m in top_q) / sum(
+ max(m.nloc, 1) for m in top_q
+ )
+ assert quartile == 2.0
+
+ assert hotspot_health(rows, {"small-but-churny.py"}) == 9.0
+
+
+def test_nloc_weighted_score_is_the_one_weighting_helper() -> None:
+ """``average_health`` and ``hotspot_health`` share their arithmetic."""
+ rows = [_Metric("a.py", 2.0, 300), _Metric("b.py", 6.0, 100)]
+ assert nloc_weighted_score(rows) == 3.0
+ # The same helper, restricted to a subset, is what hotspot health is.
+ assert hotspot_health(rows, {"a.py", "b.py"}) == round(nloc_weighted_score(rows), 2)
diff --git a/tests/unit/server/mcp/test_hotspot_health_surfaces.py b/tests/unit/server/mcp/test_hotspot_health_surfaces.py
new file mode 100644
index 000000000..a773a10b5
--- /dev/null
+++ b/tests/unit/server/mcp/test_hotspot_health_surfaces.py
@@ -0,0 +1,126 @@
+"""The MCP surfaces report the owner's hotspot health (P10).
+
+``_build_code_health`` (``get_overview``) had no test at all: nothing called it
+with health metrics seeded, so it short-circuited on the empty guard in every
+run. It shipped a top-25%-by-NLOC average under a comment claiming it matched
+the dashboard, and swapping that for the real KPI broke nothing.
+
+``get_health`` did not return the number at all, so the canonical persisted KPI
+was surfaced by neither tool while the two disagreed with each other.
+
+The seeded repo (see ``conftest.health_data``) is two files:
+ src/auth/service.py score 4.5 nloc 200
+ src/db/models.py score 8.5 nloc 50
+"""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy import update
+
+from repowise.core.persistence.models import GitMetadata
+
+
+async def _set_hotspots(session, repo_id: str, paths: set[str]) -> None:
+ """Make *paths* exactly the repo's hotspot set.
+
+ Every flag is cleared first. The fixture already flags ``service.py``, so a
+ test that only adds a flag inherits a set it did not choose — which is how
+ the first cut of these tests asserted the wrong numbers against correct
+ code.
+ """
+ await session.execute(
+ update(GitMetadata)
+ .where(GitMetadata.repository_id == repo_id)
+ .values(is_hotspot=False)
+ )
+ if paths:
+ await session.execute(
+ update(GitMetadata)
+ .where(
+ GitMetadata.repository_id == repo_id,
+ GitMetadata.file_path.in_(paths),
+ )
+ .values(is_hotspot=True)
+ )
+ await session.flush()
+
+
+async def test_get_overview_code_health_uses_the_hotspot_files(
+ session, setup_mcp, health_data
+):
+ """The KPI averages the flagged file, not the biggest one.
+
+ This is the whole disagreement in one assertion. The retired definition
+ took the top 25% by NLOC, which here is ``service.py`` (200 NLOC) and would
+ coincidentally also give 4.5 — so the flagged file is the *small* one, to
+ make the two answers differ: owner 8.5, retired 4.5.
+ """
+ from repowise.core.persistence import crud
+ from repowise.server.mcp_server.tool_overview import _build_code_health
+
+ repo_id = health_data
+ await _set_hotspots(session, repo_id, {"src/db/models.py"})
+ repository = await crud.get_repository(session, repo_id)
+
+ block = await _build_code_health(session, repository)
+
+ assert block["hotspot_health"] == 8.5
+ # The average is unchanged: (4.5*200 + 8.5*50) / 250 == 5.3.
+ assert block["average_health"] == 5.3
+
+
+async def test_get_overview_hotspot_health_is_none_without_hotspots(
+ session, setup_mcp, health_data
+):
+ """No flagged file means no hotspot health, not a perfect 10.0."""
+ from repowise.core.persistence import crud
+ from repowise.server.mcp_server.tool_overview import _build_code_health
+
+ await _set_hotspots(session, health_data, set())
+ repository = await crud.get_repository(session, health_data)
+ block = await _build_code_health(session, repository)
+
+ assert block["hotspot_health"] is None
+
+
+async def test_get_health_returns_hotspot_health(session, setup_mcp, health_data):
+ """The KPI ``get_health`` never returned (D2)."""
+ from repowise.server.mcp_server import get_health
+
+ await _set_hotspots(session, health_data, {"src/auth/service.py"})
+
+ result = await get_health()
+
+ assert "hotspot_health" in result["kpis"]
+ assert result["kpis"]["hotspot_health"] == 4.5
+
+
+async def test_get_health_and_get_overview_agree(session, setup_mcp, health_data):
+ """The two tools that disagreed on 42 of 42 indexes now cannot.
+
+ Asserting agreement rather than two literals is deliberate: a future change
+ to the definition should move both or fail here, which is exactly what did
+ not happen when one of them drifted.
+
+ The hotspot is ``models.py``, the *small* file, on purpose. Flagging the
+ big one makes the retired quartile definition agree with the owner by
+ coincidence, and a version of this test that did so passed against the very
+ code it was meant to outlaw.
+ """
+ from repowise.core.persistence import crud
+ from repowise.server.mcp_server import get_health
+ from repowise.server.mcp_server.tool_overview import _build_code_health
+
+ await _set_hotspots(session, health_data, {"src/db/models.py"})
+ repository = await crud.get_repository(session, health_data)
+
+ overview_block = await _build_code_health(session, repository)
+ health_result = await get_health()
+
+ assert overview_block["hotspot_health"] == health_result["kpis"]["hotspot_health"]
+ assert overview_block["hotspot_health"] == 8.5
diff --git a/tests/unit/test_no_hotspot_health_copies.py b/tests/unit/test_no_hotspot_health_copies.py
new file mode 100644
index 000000000..707c5a991
--- /dev/null
+++ b/tests/unit/test_no_hotspot_health_copies.py
@@ -0,0 +1,158 @@
+"""No seventh answer to "what is this repo's hotspot health" (P10).
+
+An architecture check rather than a behaviour one. Six implementations shipped
+at once: the owner in :mod:`repowise.core.analysis.health.scoring`, a top-25%-
+by-NLOC average in ``get_overview``, the same wrong average again in
+``repowise status``, an inline re-derivation in the CLAUDE.md fetcher, a
+snapshot read on each of two dashboard routes, and ``get_health`` omitting the
+number entirely while ``get_overview`` invented one. They disagreed on all 42
+local indexes, median 2.67 points of 10.
+
+Nothing caught that, because nothing tested it: ``compute_kpis`` had tests that
+never asserted ``hotspot_health``, and the two surfaces carrying the wrong
+definition had no tests at all. A reviewer noticing the seventh copy is not a
+plan, so this fails when one appears.
+
+Ceiling: this matches on module contents, not on semantics. A module that
+computes hotspot health under names none of the lists below know stays
+invisible. It catches the shape that actually recurred here — a surface
+deriving the number itself instead of calling the owner.
+``tests/unit/health/test_hotspot_health.py`` is what catches a *wrong* answer;
+this only catches a second implementation of the question.
+"""
+
+from __future__ import annotations
+
+import pathlib
+import re
+
+import pytest
+
+_OWNER_MODULE = "repowise/core/analysis/health/scoring.py"
+_OWNER_MODULE_FROM_SRC = "core/src/repowise/core/analysis/health/scoring.py"
+_OWNER_IMPORT = "from repowise.core.analysis.health.scoring import"
+
+_PACKAGES = pathlib.Path(__file__).resolve().parents[2] / "packages"
+
+# Modules that legitimately mention ``hotspot_health`` without computing it.
+# Each entry says why. The list only ever shrinks: a new surface that renders
+# this number belongs in the "imports the owner" set, not here.
+_PLUMBING: dict[str, str] = {
+ # --- storage and schema: the value arrives already computed --------------
+ "repowise/core/persistence/models.py": "the column",
+ "repowise/core/persistence/crud/analysis/health.py": "writes/reads the column",
+ "repowise/core/persistence/crud/git.py": "supplies the hotspot path set, not the score",
+ "repowise/core/persistence/stores/_sql_analysis.py": "passthrough to the crud writer",
+ "repowise/core/persistence/_interfaces/_analysis.py": "the store ABC's parameter name",
+ "alembic/versions/0019_code_health.py": "the migration that adds the column",
+ # --- writers: hand ``compute_kpis`` output to the snapshot ---------------
+ "repowise/core/pipeline/persist.py": "persists the KPI dict from the health report",
+ "repowise/cli/commands/health_cmd/persist.py": "same, for `repowise health`",
+ "repowise/cli/commands/upgrade_flow.py": "same, for `repowise upgrade`",
+ # --- trend surfaces: diff recorded snapshots, no current value -----------
+ "repowise/core/analysis/health/trends.py": "diffs snapshots; owns no current value",
+ "repowise/server/routers/code_health/trends_routes.py": "serves the snapshot series",
+ "repowise/cli/commands/health_cmd/trends.py": "prints the snapshot series",
+ # --- pure renderers: read a value someone else computed ------------------
+ "repowise/cli/commands/health_cmd/command.py": "prints the KPI dict it was handed",
+ "repowise/core/generation/editor_files/data.py": "the CodeHealthBlock field",
+}
+
+
+def _modules_mentioning_hotspot_health() -> list[pathlib.Path]:
+ out = []
+ for path in sorted(_PACKAGES.rglob("*.py")):
+ try:
+ text = path.read_text(encoding="utf-8")
+ except (UnicodeDecodeError, OSError): # pragma: no cover - defensive
+ continue
+ if "hotspot_health" in text:
+ out.append(path)
+ return out
+
+
+def _relative(path: pathlib.Path) -> str:
+ """``packages/<pkg>/src/`` and ``packages/core/`` stripped to a stable key."""
+ parts = path.as_posix().split("/")
+ if "src" in parts:
+ return "/".join(parts[parts.index("src") + 1 :])
+ # packages/core/alembic/versions/... -> alembic/versions/...
+ return "/".join(parts[parts.index("packages") + 2 :])
+
+
+def test_the_owner_module_is_where_the_arithmetic_lives() -> None:
+ """Guards the constant this whole test file is keyed on."""
+ owner = _PACKAGES / _OWNER_MODULE_FROM_SRC
+ assert owner.is_file(), f"the owner moved; update _OWNER_MODULE ({_OWNER_MODULE})"
+ text = owner.read_text(encoding="utf-8")
+ assert "def hotspot_health(" in text
+
+
+def test_every_surface_gets_hotspot_health_from_the_one_owner() -> None:
+ """A module that mentions the KPI either imports it, stores it, or renders it.
+
+ Anything else is a seventh implementation.
+ """
+ offenders: list[str] = []
+ for path in _modules_mentioning_hotspot_health():
+ rel = _relative(path)
+ if rel == _OWNER_MODULE:
+ continue
+ if rel in _PLUMBING:
+ continue
+ text = path.read_text(encoding="utf-8")
+ if _OWNER_IMPORT in text:
+ continue
+ offenders.append(rel)
+
+ assert not offenders, (
+ "these modules reference hotspot_health without importing the shared "
+ f"owner and without a recorded reason: {offenders}. Call "
+ "`repowise.core.analysis.health.scoring.hotspot_health`, or add an "
+ "entry to _PLUMBING saying why this module only stores or renders it."
+ )
+
+
[email protected]("rel", sorted(_PLUMBING))
+def test_the_plumbing_allowlist_has_no_dead_entries(rel: str) -> None:
+ """An allowlist entry for a module that no longer mentions the KPI is rot.
+
+ Without this the list silently grows into a place where a real copy can
+ hide behind a stale name.
+ """
+ known = {_relative(p) for p in _modules_mentioning_hotspot_health()}
+ assert rel in known, (
+ f"_PLUMBING lists {rel!r}, which no longer mentions hotspot_health. "
+ "Remove the entry."
+ )
+
+
+def test_the_retired_top_quartile_definition_is_gone() -> None:
+ """The exact shape that shipped twice must not reappear.
+
+ Both wrong sites sorted every metric row by NLOC and sliced ``// 4``. This
+ catches a paste of that idiom anywhere under ``packages/``.
+
+ The pattern deliberately tolerates the closing paren: the shipped code read
+ ``[: max(1, len(by_nloc) // 4)]``, and a first cut of this test matched only
+ ``// 4]``, so it stayed green against the very code it was written to
+ outlaw. Verified by probe against the real shape, not the remembered one.
+ """
+ quartile_slice = re.compile(r"//\s*4\s*\)?\s*\]")
+ offenders: list[str] = []
+ for path in sorted(_PACKAGES.rglob("*.py")):
+ try:
+ text = path.read_text(encoding="utf-8")
+ except (UnicodeDecodeError, OSError): # pragma: no cover - defensive
+ continue
+ if not quartile_slice.search(text):
+ continue
+ if "nloc" not in text.lower():
+ continue
+ offenders.append(_relative(path))
+
+ assert not offenders, (
+ "the top-quartile-by-NLOC hotspot definition is back in "
+ f"{offenders}. It ranks file size, not churn, and it read higher than "
+ "the real KPI on 31 of 42 measured repos."
+ )