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.

fix(health): withhold the headline band when most code files are unanalysed (#3641)

Swati Ahuja30ebf189249a
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 2a48101db..554a85d7a 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -344,6 +344,7 @@ Items are ordered by value first, then tier. History markers (churn, ownership,
|-------|---------|
| `kpis` | Hotspot health, `average_health` (NLOC-weighted), `average_health_unweighted`, `average_health_weighting`, pillar averages, `worst_performer_path`, `worst_test_path`, `non_code_files`, `average_health_code_only` |
| `unanalysed_file_count` | Files in a language health has no dialect for, stored with no score and left out of every figure; absent when there are none |
+| `kpis.band`, `kpis.analysed_share` | The headline band is `null` when fewer than half the code files were analysed, since the average then speaks for a sample; `analysed_share` (scored over all code files) appears when some were left out. `get_overview` reports `code_health` the same way |
| `gap_analysis` | Weighted points the average must recover to reach 8.0, files below it, `files_to_reach_target`, `files_for_half_gap`, `weighted_gap_points`, `weighted_gross_gap_points` |
| `worst_files`, `test_worst_files` | Lowest raw scores, production and test |
| `high_leverage_files` | Ranked by `weighted_deficit`, with `share_of_repo_gap_pct` |
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
index a42042b83..994714fdc 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
@@ -311,7 +311,7 @@ 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)
+ report.kpis = compute_kpis(metrics, hotspots, unanalysed=unanalysed)
metrics_sorted = sorted(metrics, key=lambda m: m.score)
findings = report.findings
@@ -349,7 +349,7 @@ def health_command(
return
if badge_view:
- _render_badge(report.kpis.get("average_health"))
+ _render_badge(report.kpis.get("average_health"), report.kpis.get("analysed_share"))
return
if fmt == "json":
@@ -410,7 +410,9 @@ def health_command(
from repowise.core.analysis.health.grading import (
BAND_LABEL,
BAND_TERMINAL_COLOR,
+ analysed_note,
band_for,
+ headline_band,
)
from repowise.core.analysis.health.grading import (
distribution as health_distribution,
@@ -423,8 +425,8 @@ def health_command(
kpis = report.kpis
avg = kpis.get("average_health")
band_str = ""
- if isinstance(avg, (int, float)):
- band = band_for(float(avg))
+ band = headline_band(avg, kpis.get("analysed_share"))
+ if band is not None:
band_color = BAND_TERMINAL_COLOR[band]
band_str = f" [[{band_color}]{BAND_LABEL[band]}[/{band_color}]]"
console.print(
@@ -440,6 +442,10 @@ def health_command(
f"[dim]{unanalysed} file(s) not analysed: health does not support "
"their language yet.[/dim]"
)
+ # The share behind the headline, from the same counts as its band.
+ note = analysed_note(kpis.get("file_count") or 0, kpis.get("unanalysed_file_count") or 0)
+ if note:
+ console.print(f"[dim]Code health {note}.[/dim]")
_render_split_line(kpis)
_render_distribution_line(health_distribution(metrics))
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/summary.py b/packages/cli/src/repowise/cli/commands/health_cmd/summary.py
index 2d412c35d..bcb83454f 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/summary.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/summary.py
@@ -121,18 +121,25 @@ def _render_distribution_line(dist: dict) -> None:
console.print("[dim]Distribution (by code volume):[/dim] " + " · ".join(parts) + "\n")
-def _render_badge(average_health: object) -> None:
+def _render_badge(average_health: object, share: float | None = None) -> None:
"""Print ready-to-paste health-badge Markdown for a README.
Emits a static shields badge for the current score (immediately usable) and
documents the live endpoint form for a running Repowise server / hosted repo.
"""
- from repowise.core.analysis.health.grading import BAND_BADGE_COLOR, band_for, format_score
+ from repowise.core.analysis.health.grading import (
+ BADGE_UNKNOWN_COLOR,
+ BAND_BADGE_COLOR,
+ format_score,
+ headline_band,
+ )
if not isinstance(average_health, (int, float)):
console.print("[yellow]No health score yet — run `repowise init` first.[/yellow]")
return
- color = BAND_BADGE_COLOR[band_for(float(average_health))]
+ band = headline_band(float(average_health), share)
+ # Neutral, not green, when too little of the repo was analysed for a band.
+ color = BAND_BADGE_COLOR[band] if band is not None else BADGE_UNKNOWN_COLOR
msg = f"{format_score(float(average_health))}/10"
static = f"https://img.shields.io/badge/health-{msg.replace('/', '%2F')}-{color}"
console.print("[bold]Static badge (current score):[/bold]")
diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.py
index af6ee639d..cc80eba1a 100644
--- a/packages/cli/src/repowise/cli/commands/status_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py
@@ -282,14 +282,21 @@ def _query_health_line(repo_path: Path) -> str | None:
from repowise.core.analysis.health.grading import (
BAND_LABEL,
BAND_TERMINAL_COLOR,
- band_for,
+ analysed_note,
format_score,
+ headline_band,
)
worst_repr = format_score(worst_score) if worst_score is not None else "—"
- band = band_for(float(data["average_health"]))
- band_color = BAND_TERMINAL_COLOR[band]
+ band = headline_band(data["average_health"], data.get("analysed_share"))
+ if band is not None:
+ band_color = BAND_TERMINAL_COLOR[band]
+ band_part = f" [[{band_color}]{BAND_LABEL[band]}[/{band_color}]]"
+ else:
+ band_part = ""
+ note = analysed_note(data["file_count"], data.get("unanalysed_file_count") or 0)
+ note_part = f" · {note}" if note else ""
# Maintainability and performance are co-surfaced pillars; show each when the
# split has populated it (None on indexes that predate the relevant work).
maint = data.get("maintainability_average")
@@ -309,8 +316,8 @@ def _query_health_line(repo_path: Path) -> str | None:
hotspot = data.get("hotspot_health")
hotspot_part = f"{format_score(hotspot)} (hotspots) · " if hotspot is not None else ""
return (
- f"[bold]Health:[/bold] {format_score(data['average_health'])} (avg) "
- f"[[{band_color}]{BAND_LABEL[band]}[/{band_color}]] · "
+ f"[bold]Health:[/bold] {format_score(data['average_health'])} (avg)"
+ f"{band_part}{note_part} · "
f"{hotspot_part}"
f"{worst_repr} (worst: {worst_path})"
f"{maint_part}"
diff --git a/packages/core/src/repowise/core/analysis/health/grading.py b/packages/core/src/repowise/core/analysis/health/grading.py
index b02b01c11..bf2152089 100644
--- a/packages/core/src/repowise/core/analysis/health/grading.py
+++ b/packages/core/src/repowise/core/analysis/health/grading.py
@@ -83,6 +83,8 @@ BAND_BADGE_COLOR: dict[HealthBand, str] = {
"needs_work": "orange",
"at_risk": "red",
}
+# A badge with no band: no score, or too little analysed to grade.
+BADGE_UNKNOWN_COLOR = "lightgrey"
def band_for(score: float) -> HealthBand:
@@ -98,6 +100,42 @@ def band_for(score: float) -> HealthBand:
return "at_risk"
+# Below this share of code files scored, the repo average describes a sample,
+# not the repo, so no band is put on it. Presentation only, like the cutoffs.
+HEADLINE_MIN_ANALYSED_SHARE = 0.5
+
+
+def analysed_share(analysed: int, unanalysed: int) -> float | None:
+ """Share of code files health scored, or ``None`` with no code files.
+
+ Shortcut: file counts, not NLOC, because an unanalysed file has no NLOC.
+ A few large scored files beside many small unscored ones read low here;
+ counting unscored NLOC at ingest would weight it properly.
+ """
+ total = analysed + unanalysed
+ return round(analysed / total, 4) if total else None
+
+
+def headline_band(score: float | None, share: float | None) -> HealthBand | None:
+ """The band for a repo headline, withheld when too little was analysed.
+
+ A per-file score keeps :func:`band_for`; this is for repo averages only.
+ A ``share`` of ``None`` (not known) keeps the band.
+ """
+ if score is None:
+ return None
+ if share is not None and share < HEADLINE_MIN_ANALYSED_SHARE:
+ return None
+ return band_for(score)
+
+
+def analysed_note(analysed: int, unanalysed: int) -> str | None:
+ """``"analysed N of M code files"`` when some were left out, else ``None``."""
+ if unanalysed <= 0:
+ return None
+ return f"analysed {analysed} of {analysed + unanalysed} code files"
+
+
def format_score(score: float) -> str:
"""A 1-10 score at one decimal, rounded down, for display beside its band.
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.py
index 2da91a22d..f033722af 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -23,6 +23,7 @@ from collections.abc import Callable, Iterable
from dataclasses import replace
from typing import TYPE_CHECKING, Any
+from .grading import analysed_share
from .models import HealthFileMetricData, HealthFindingData, Severity
from .rows import field, scored_rows, split_tests, split_unscored
@@ -945,6 +946,7 @@ def _empty_kpis(unanalysed: int) -> dict[str, object]:
"hotspot_health": None,
"average_health": None,
"unanalysed_file_count": unanalysed,
+ "analysed_share": analysed_share(0, unanalysed),
"worst_performer_path": None,
"worst_performer_score": None,
"worst_test_path": None,
@@ -970,6 +972,8 @@ def _empty_kpis(unanalysed: int) -> dict[str, object]:
def compute_kpis(
metrics: list[HealthFileMetricData],
hotspot_paths: set[str],
+ *,
+ unanalysed: int = 0,
) -> dict[str, object]:
"""Repo-level KPIs derived from per-file metrics.
@@ -993,8 +997,13 @@ def compute_kpis(
- ``unanalysed_file_count``: files stored with no score because health has
no dialect for their language. Every KPI above leaves them out; when no
file is scored at all, the two headline averages are ``None``.
+ - ``analysed_share``: scored files over all code files (``grading.analysed_share``),
+ which decides whether the headline carries a band. *unanalysed* counts
+ unscored files a caller already took out of *metrics*, so a narrowed
+ recompute keeps the share of the population it narrowed.
"""
- metrics, unanalysed = split_unscored(metrics)
+ metrics, left_out = split_unscored(metrics)
+ unanalysed += left_out
if not metrics:
return _empty_kpis(unanalysed)
@@ -1037,4 +1046,5 @@ def compute_kpis(
),
"production_file_count": len(production),
"unanalysed_file_count": unanalysed,
+ "analysed_share": analysed_share(len(metrics), unanalysed),
}
diff --git a/packages/core/src/repowise/core/generation/editor_files/data.py b/packages/core/src/repowise/core/generation/editor_files/data.py
index 656b4f395..66e8002c1 100644
--- a/packages/core/src/repowise/core/generation/editor_files/data.py
+++ b/packages/core/src/repowise/core/generation/editor_files/data.py
@@ -73,6 +73,8 @@ class CodeHealthBlock:
# direction as every other surface: a bare "6.9/10" beside a risk-shaped
# label is the one reading that inverts.
band: str = ""
+ # "analysed N of M code files" when health left some out; ``None`` otherwise.
+ analysed_note: str | None = None
# ``None`` until two snapshots exist; the section then omits the label.
hotspot_trend: str | None = None
# Maintainability pillar headline (NLOC-weighted average over the per-file
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 c06b21299..493bf1cad 100644
--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py
+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
@@ -16,9 +16,14 @@ from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.finding_registry import excluded_types
-from repowise.core.analysis.health.grading import BAND_LABEL, band_for
+from repowise.core.analysis.health.grading import (
+ BAND_LABEL,
+ analysed_note,
+ analysed_share,
+ headline_band,
+)
from repowise.core.analysis.health.perf.coverage import coverage_for_metrics
-from repowise.core.analysis.health.rows import scored_rows, split_tests
+from repowise.core.analysis.health.rows import split_tests, split_unscored
from repowise.core.analysis.health.scoring import hotspot_health, nloc_weighted_score
from repowise.core.analysis.health.trends import DECLINE_LOOKBACK, hotspot_trend
from repowise.core.entry_candidacy import conventional_entry_stems
@@ -363,7 +368,8 @@ class EditorFileDataFetcher:
"""
# Scored rows only: a file in a language health has no dialect for
# carries no score, and a repository of nothing else has no block.
- metric_rows = scored_rows(
+ # The rest are counted, so the line can say how much was analysed.
+ metric_rows, unanalysed = split_unscored(
(
await self._session.execute(
select(HealthFileMetric).where(
@@ -464,10 +470,12 @@ class EditorFileDataFetcher:
self._session, self._repo_id, limit=DECLINE_LOOKBACK + 1
)
+ band = headline_band(round(avg, 2), analysed_share(len(metric_rows), unanalysed))
return CodeHealthBlock(
hotspot_health=round(hotspot_for_claude_md, 2),
average_health=round(avg, 2),
- band=BAND_LABEL[band_for(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,
hotspot_trend=hotspot_trend(history),
diff --git a/packages/core/src/repowise/core/generation/templates/agents_md.j2 b/packages/core/src/repowise/core/generation/templates/agents_md.j2
index f4219efee..4ee2298ee 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 %} ({{ data.code_health.band }}){% 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 %}, 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()`.
{% 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.j2
index 24c84b32e..4b03d56b6 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 %} ({{ data.code_health.band }}){% 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 %}, 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()`.
{% if data.code_health.fix_first %}
Fix first:
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
index f32f368eb..b8f43f470 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
@@ -75,9 +75,9 @@ from .health import (
backfill_is_test,
backfill_module_attribution,
clear_unanalysed_scores,
- get_average_health,
get_deduction_by_path,
get_file_language_map,
+ get_headline_health,
get_health_findings,
get_health_metrics,
get_health_snapshot_file_counts,
@@ -158,7 +158,6 @@ __all__ = [
"finalize_refactoring_suggestions",
"finding_data_from_row",
"gated_performance_counts",
- "get_average_health",
"get_coverage_summary",
"get_dead_code_findings",
"get_dead_code_summary",
@@ -167,6 +166,7 @@ __all__ = [
"get_doc_drift_references",
"get_file_language_map",
"get_function_facts",
+ "get_headline_health",
"get_health_finding_by_public_id",
"get_health_findings",
"get_health_metrics",
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
index 2644aa195..9f867ddb6 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
@@ -22,6 +22,7 @@ from ....analysis.health.finding_identity import (
legacy_finding_public_id,
)
from ....analysis.health.governance import GOVERNANCE_BIOMARKERS
+from ....analysis.health.grading import analysed_share
# The comparator is pure and lives with the health read models; only the SQL
# that feeds it belongs here. Re-imported rather than moved out of reach: the
@@ -687,8 +688,12 @@ async def get_health_metrics(
)
-async def get_average_health(session: AsyncSession, repository_id: str) -> float | None:
- """The repo's NLOC-weighted average health score, or ``None`` if unmeasured.
+async def get_headline_health(
+ session: AsyncSession, repository_id: str
+) -> tuple[float | None, float | None]:
+ """``(average health, analysed share)``: the badge's figure and its band gate.
+
+ The average is ``None`` if unmeasured; the share is ``analysed_share``.
Numerically identical to ``get_health_summary()["average_health"]`` — same
weighting, same ``max(nloc, 1)`` floor, same 2dp rounding — for callers that
@@ -720,7 +725,8 @@ async def get_average_health(session: AsyncSession, repository_id: str) -> float
)
# Files with no score (no health dialect for their language) are skipped,
# so a repository of nothing else reads unmeasured, never 10.0.
- return _rounded(nloc_weighted_attr(rows, "score"))
+ scored, unanalysed = split_unscored(rows)
+ return _rounded(nloc_weighted_attr(scored, "score")), analysed_share(len(scored), unanalysed)
async def get_file_language_map(session: AsyncSession, repository_id: str) -> dict[str, str]:
@@ -802,6 +808,7 @@ async def get_health_summary(
return {
"file_count": 0,
"unanalysed_file_count": unanalysed,
+ "analysed_share": analysed_share(0, unanalysed),
"average_health": None,
"worst_performer_path": None,
"worst_performer_score": None,
@@ -879,6 +886,7 @@ async def get_health_summary(
return {
"file_count": len(metrics),
"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),
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.py
index e5ddd7610..6da5070b4 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
@@ -5,7 +5,7 @@ from __future__ import annotations
from typing import Any
from repowise.core.analysis.health.complexity.languages import NO_DIALECT_STATUS
-from repowise.core.analysis.health.grading import TARGET_SCORE, band_for
+from repowise.core.analysis.health.grading import TARGET_SCORE, analysed_share, headline_band
from repowise.core.analysis.health.models import primary_finding, split_by_origin
from repowise.core.analysis.health.perf.coverage import PerfCoverage
from repowise.core.analysis.health.rows import split_tests
@@ -169,6 +169,7 @@ def _compute_kpis(
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 None
+ share = analysed_share(len(metrics), unanalysed)
return {
"file_count": len(metrics),
"average_health": round(avg, 2),
@@ -177,7 +178,10 @@ def _compute_kpis(
# Weighted vs plain mean: a gap means a few large files hold it down.
"average_health_weighting": "nloc",
"average_health_unweighted": round(sum(m.score for m in metrics) / len(metrics), 2),
- "band": band_for(round(avg, 2)),
+ # Withheld when too few code files were analysed to grade the repo.
+ "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,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/health.py b/packages/server/src/repowise/server/mcp_server/tool_overview/health.py
index ae094c5bd..bcc0d74f1 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_overview/health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/health.py
@@ -5,12 +5,10 @@ from __future__ import annotations
from typing import Any
from repowise.core.analysis.health.complexity.languages import NO_DIALECT_STATUS
-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.grading import headline_band
from repowise.core.analysis.health.scoring import hotspot_health
from repowise.core.persistence.crud import (
get_health_metrics as _get_health_metrics,
@@ -37,14 +35,27 @@ async def _build_code_health(session: Any, repository: Any) -> dict[str, Any]:
}
# Hotspot health from its one owner, over the rows already loaded.
hotspot_paths = await get_hotspot_file_paths(session, repository.id)
+ unanalysed = health_summary["unanalysed_file_count"]
return {
"average_health": health_summary["average_health"],
- "band": band_for(float(health_summary["average_health"])),
+ # ``None`` when too few code files were analysed to grade the repo.
+ "band": headline_band(
+ health_summary["average_health"], health_summary["analysed_share"]
+ ),
"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"],
"file_count": health_summary["file_count"],
+ # Only said when there are some, as the health dashboard does.
+ **(
+ {
+ "unanalysed_file_count": unanalysed,
+ "analysed_share": health_summary["analysed_share"],
+ }
+ if unanalysed
+ else {}
+ ),
"distribution": health_distribution(metrics_rows),
}
except Exception:
diff --git a/packages/server/src/repowise/server/routers/code_health/badge.py b/packages/server/src/repowise/server/routers/code_health/badge.py
index edd05022c..611c3c559 100644
--- a/packages/server/src/repowise/server/routers/code_health/badge.py
+++ b/packages/server/src/repowise/server/routers/code_health/badge.py
@@ -5,7 +5,12 @@ from __future__ import annotations
from fastapi import Depends, HTTPException, Response
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.analysis.health.grading import BAND_BADGE_COLOR, band_for, format_score
+from repowise.core.analysis.health.grading import (
+ BADGE_UNKNOWN_COLOR,
+ BAND_BADGE_COLOR,
+ format_score,
+ headline_band,
+)
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session
from repowise.server.schemas import HealthBadgeResponse
@@ -15,22 +20,29 @@ from ._router import router
# Hexes for the self-rendered SVG, so it matches the JSON endpoint's named
# colors without a round-trip to img.shields.io. The names themselves come
# from the shared band vocabulary.
-_UNKNOWN_COLOR = "lightgrey"
_BADGE_COLOR_HEX: dict[str, str] = {
"brightgreen": "#4c1",
"yellow": "#dfb317",
"orange": "#fe7d37",
"red": "#e05d44",
- "lightgrey": "#9f9f9f",
+ BADGE_UNKNOWN_COLOR: "#9f9f9f",
}
-def _badge_fields(average_health: float | None) -> tuple[str, str, str, str]:
- """Return ``(label, message, color_name, band)`` for the health badge."""
+def _badge_fields(
+ average_health: float | None, share: float | None = None
+) -> tuple[str, str, str, str]:
+ """Return ``(label, message, color_name, band)`` for the health badge.
+
+ Too little of the repo analysed for a band: the score stays, neutral grey.
+ """
if average_health is None:
- return "health", "no data", _UNKNOWN_COLOR, "unknown"
- band = band_for(float(average_health))
- return "health", f"{format_score(average_health)}/10", BAND_BADGE_COLOR[band], band
+ return "health", "no data", BADGE_UNKNOWN_COLOR, "unknown"
+ message = f"{format_score(average_health)}/10"
+ band = headline_band(float(average_health), share)
+ if band is None:
+ return "health", message, BADGE_UNKNOWN_COLOR, "unknown"
+ return "health", message, BAND_BADGE_COLOR[band], band
def _render_badge_svg(label: str, message: str, color_name: str) -> str:
@@ -69,16 +81,18 @@ def _render_badge_svg(label: str, message: str, color_name: str) -> str:
)
-async def _badge_average_health(session: AsyncSession, repo_id: str) -> float | None:
- """The one number these endpoints render.
+async def _badge_average_health(
+ session: AsyncSession, repo_id: str
+) -> tuple[float | None, float | None]:
+ """The one number these endpoints render, and the analysed share behind it.
These are README-embedded and public, so they get hit by anyone loading the
README — and they were reading the entire health dataset to print ``7.5/10``.
``get_health_summary`` hydrates every per-file metric row, runs the grouped
deduction aggregate for a ranking no badge shows, scans the whole findings
table for per-dimension counts, and loads the graph's language map, all to
- have one float taken off the result. ``get_average_health`` computes that
- float and nothing else, from the same rows with the same weighting.
+ have one float taken off the result. ``get_headline_health`` computes that
+ float and the share, from the same rows with the same weighting.
"""
repo = await crud.get_repository(session, repo_id)
if repo is None:
@@ -86,7 +100,7 @@ async def _badge_average_health(session: AsyncSession, repo_id: str) -> float |
# ``None`` badges "no data": no scored file, whether the repo is empty, holds
# only data and config files (which get no metric row), or only files in a
# language health has no dialect for.
- return await crud.get_average_health(session, repo_id)
+ return await crud.get_headline_health(session, repo_id)
@router.get("/api/repos/{repo_id}/health/badge.json", response_model=HealthBadgeResponse)
@@ -98,8 +112,8 @@ async def health_badge_json(
Embed via ``https://img.shields.io/endpoint?url=<this-url>``.
"""
- avg = await _badge_average_health(session, repo_id)
- label, message, color, band = _badge_fields(avg)
+ avg, share = await _badge_average_health(session, repo_id)
+ label, message, color, band = _badge_fields(avg, share)
return {
"schemaVersion": 1,
"label": label,
@@ -115,8 +129,8 @@ async def health_badge_svg(
session: AsyncSession = Depends(get_db_session),
) -> Response:
"""Self-rendered flat SVG health badge (no external service round-trip)."""
- avg = await _badge_average_health(session, repo_id)
- label, message, color, _band = _badge_fields(avg)
+ avg, share = await _badge_average_health(session, repo_id)
+ label, message, color, _band = _badge_fields(avg, share)
svg = _render_badge_svg(label, message, color)
return Response(
content=svg,
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 4a75cd267..3415cc802 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
@@ -14,8 +14,8 @@ from repowise.core.analysis.health.aggregation import (
severity_breakdown,
)
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.grading import headline_band
from repowise.core.analysis.health.ranking import deduction_by_path
from repowise.core.analysis.health.scoring import ZERO_IMPACT_DIMENSIONS, hotspot_health
from repowise.core.persistence import crud
@@ -113,7 +113,9 @@ async def health_overview(
# asked for; the two differ while a request is in flight.
"counts": counts,
"unscored_files": unscored,
- "band": band_for(float(avg)) if avg is not None else None,
+ # Withheld when too few code files were analysed for the average to
+ # speak for the repo; ``analysed_share`` rides in from the summary.
+ "band": headline_band(avg, summary.get("analysed_share")),
"gated": gated,
}
distribution = health_distribution(metric_dicts)
diff --git a/packages/server/src/repowise/server/routers/overview.py b/packages/server/src/repowise/server/routers/overview.py
index 00f6082e0..a6250ef5c 100644
--- a/packages/server/src/repowise/server/routers/overview.py
+++ b/packages/server/src/repowise/server/routers/overview.py
@@ -22,6 +22,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.aggregation import (
severity_breakdown as health_severity_breakdown,
)
+from repowise.core.analysis.health.grading import headline_band
from repowise.core.analysis.health.scoring import hotspot_health
from repowise.core.forges import read_remote_url, strip_credentials
from repowise.core.persistence import crud
@@ -511,6 +512,11 @@ async def overview_summary(
"average_health": health_summary.get("average_health"),
# Files in a language health has no dialect for: in no figure here.
"unanalysed_file_count": health_summary.get("unanalysed_file_count", 0),
+ "analysed_share": health_summary.get("analysed_share"),
+ # ``None`` when too few code files were analysed to grade the repo.
+ "band": headline_band(
+ health_summary.get("average_health"), health_summary.get("analysed_share")
+ ),
"hotspot_health": hotspot_health_value,
"worst_performer_path": health_summary.get("worst_performer_path"),
"worst_performer_score": health_summary.get("worst_performer_score"),
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index 306b2404b..354b90065 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -737,6 +737,9 @@ export interface HealthOverviewSummary {
/** Files left out of every figure here because health has no dialect for
* their language. Absent on an older server. */
unanalysed_file_count?: number;
+ /** Scored files over all code files, 0-1; `null` with no code files. Absent
+ * on an older server. */
+ analysed_share?: number | null;
hotspot_health?: number | null;
worst_performer_path: string | null;
worst_performer_score: number | null;
@@ -751,8 +754,10 @@ export interface HealthOverviewSummary {
medium: number;
low: number;
};
- /** Repo-level band derived from `average_health` (added in the band/distribution layer). */
- band?: HealthBand;
+ /** Repo-level band derived from `average_health` (added in the band/distribution layer).
+ * `null` when no file is scored or too few code files were analysed to grade
+ * the repo; absent on an older server. */
+ band?: HealthBand | null;
/**
* NLOC-weighted repo headline for the maintainability pillar (the second
* surfaced signal). `null`/absent when no file carries a maintainability
diff --git a/packages/types/src/overview.ts b/packages/types/src/overview.ts
index ae0891d56..ff9659a4c 100644
--- a/packages/types/src/overview.ts
+++ b/packages/types/src/overview.ts
@@ -5,7 +5,7 @@
*/
import type { Hotspot } from "./git.js";
-import type { DefectAccuracy, HealthSeverity } from "./health.js";
+import type { DefectAccuracy, HealthBand, HealthSeverity } from "./health.js";
import type { QueueCounts } from "./queue.js";
export interface OverviewRepoMeta {
@@ -77,6 +77,13 @@ export interface OverviewHealthHistoryPoint {
export interface OverviewHealth {
average_health: number | null;
+ /** Files health has no dialect for, left out of every figure. */
+ unanalysed_file_count?: number;
+ /** Scored files over all code files, 0-1; `null` with no code files. */
+ analysed_share?: number | null;
+ /** Band for `average_health`; `null` when too few code files were analysed
+ * to grade the repo. Absent on an older server. */
+ band?: HealthBand | null;
/** Backtested precision of the defect ranking — the "can you trust this
* score?" panel on the health card. Optional so an older server payload
* simply omits the panel. */
diff --git a/packages/ui/__tests__/dashboard/health-overview-card.test.tsx b/packages/ui/__tests__/dashboard/health-overview-card.test.tsx
new file mode 100644
index 000000000..f2fb1ac95
--- /dev/null
+++ b/packages/ui/__tests__/dashboard/health-overview-card.test.tsx
@@ -0,0 +1,31 @@
+import { describe, expect, it } from "vitest";
+import { render } from "@testing-library/react";
+import {
+ HealthOverviewCard,
+ type HealthOverviewData,
+} from "../../src/dashboard/health-overview-card";
+
+const data = (over: Partial<HealthOverviewData>): HealthOverviewData => ({
+ average_health: 10,
+ hotspot_health: null,
+ worst_performer_path: null,
+ worst_performer_score: null,
+ open_findings: 0,
+ severity_breakdown: {},
+ history: [],
+ snapshot_count: 1,
+ ...over,
+});
+
+describe("HealthOverviewCard band", () => {
+ it("shows no band the server withheld", () => {
+ const { container } = render(<HealthOverviewCard data={data({ band: null })} repoId="r" />);
+ expect(container.textContent).toContain("10.0");
+ expect(container.textContent).not.toContain("Excellent");
+ });
+
+ it("keeps the band from an older server that sends none", () => {
+ const { container } = render(<HealthOverviewCard data={data({})} repoId="r" />);
+ expect(container.textContent).toContain("Excellent");
+ });
+});
diff --git a/packages/ui/__tests__/health/unanalysed-files.test.tsx b/packages/ui/__tests__/health/unanalysed-files.test.tsx
index ef533becd..0425a43c8 100644
--- a/packages/ui/__tests__/health/unanalysed-files.test.tsx
+++ b/packages/ui/__tests__/health/unanalysed-files.test.tsx
@@ -138,4 +138,23 @@ describe("the code health lede", () => {
);
expect(container.textContent).toContain("1,650 more files are in a");
});
+
+ it("states the analysed share and withholds a band the server withheld", () => {
+ const { container } = render(
+ <CodeHealthLede
+ summary={
+ {
+ ...base,
+ file_count: 4,
+ average_health: 10,
+ unanalysed_file_count: 431,
+ analysed_share: 4 / 435,
+ band: null,
+ } as HealthOverviewSummary
+ }
+ />,
+ );
+ expect(container.textContent).toContain("4 of 435 code files");
+ expect(container.textContent).not.toContain("Excellent");
+ });
});
diff --git a/packages/ui/src/dashboard/health-overview-card.tsx b/packages/ui/src/dashboard/health-overview-card.tsx
index 7c565162a..e2268ddf8 100644
--- a/packages/ui/src/dashboard/health-overview-card.tsx
+++ b/packages/ui/src/dashboard/health-overview-card.tsx
@@ -15,7 +15,7 @@ import { AllClearStat } from "../shared/empty-state";
import { truncatePath } from "../lib/format";
import { healthBand, SEVERITY_LABEL, SEVERITY_SEGMENT, type Severity } from "../health/tokens";
import { ProportionBar } from "../shared/proportion-bar";
-import { formatScore } from "@repowise-dev/types/health";
+import { formatScore, type HealthBand } from "@repowise-dev/types/health";
import { Sparkline } from "../health/sparkline";
export interface HealthOverviewPoint {
@@ -27,6 +27,9 @@ export interface HealthOverviewPoint {
export interface HealthOverviewData {
/** Repo-wide biomarker health average, 1–10 (null until first health run). */
average_health: number | null;
+ /** Server-graded band for the average; `null` when it was withheld because
+ * too few code files were analysed. Absent on an older server. */
+ band?: HealthBand | null;
/** Health of the highest-churn files, 1–10. */
hotspot_health: number | null;
/** Lowest-scoring file and its score (1–10). */
@@ -301,7 +304,7 @@ export function HealthOverviewCard({
label="Average health"
value={avg}
delta={averageDelta}
- band={avg != null ? healthBand(avg) : null}
+ band={avg != null && data.band !== null ? healthBand(avg) : null}
sparkline={avgSeries}
/>
<MetricTile
diff --git a/packages/ui/src/health/code-health-lede.tsx b/packages/ui/src/health/code-health-lede.tsx
index 21ddc44f5..ea5d9f55e 100644
--- a/packages/ui/src/health/code-health-lede.tsx
+++ b/packages/ui/src/health/code-health-lede.tsx
@@ -168,7 +168,16 @@ export function CodeHealthLede({
// they are not a verdict this projection has earned: clamp(10 - structure)
// reads systematically higher, and almost every repo would print "Excellent"
// under it. The figure and the spread still say where the repo sits.
- const healthChip = codeShape ? undefined : healthBand(health);
+ // A `null` band means the server withheld it: too few code files were
+ // analysed for the average to speak for the repo. Absent on an older server.
+ const healthChip = codeShape || summary.band === null ? undefined : healthBand(health);
+ const unanalysed = summary.unanalysed_file_count ?? 0;
+ // The share is stated whenever files were left out, so a figure over a few
+ // files never reads as the whole repo.
+ const filesLabel =
+ unanalysed > 0
+ ? `${formatNumber(summary.file_count)} of ${formatNumber(summary.file_count + unanalysed)} code files`
+ : `${formatNumber(summary.file_count)} files`;
const stats: RibbonStat[] = [
{ label: "Files", value: formatNumber(summary.file_count), hint: FILES_HINT },
@@ -261,7 +270,7 @@ export function CodeHealthLede({
<p>
Across{" "}
<strong className="font-semibold text-[var(--color-text-primary)]">
- {formatNumber(summary.file_count)} files
+ {filesLabel}
</strong>
, weighted by lines of code.
{hotspot != null && (
@@ -309,7 +318,7 @@ export function CodeHealthLede({
<p>
Built from complexity, duplication, coverage
{codeShape ? "" : ", churn and ownership"}.
- <UnanalysedNote count={summary.unanalysed_file_count ?? 0} />
+ <UnanalysedNote count={unanalysed} />
</p>
{perf != null && (
// Not "performance risk": this is a score on the same ladder as
@@ -361,7 +370,7 @@ export function CodeHealthLede({
{formatScore(health)}
</span>
<span className="text-xs text-[var(--color-text-tertiary)]">
- out of 10 across {formatNumber(summary.file_count)} files
+ out of 10 across {filesLabel}
</span>
{healthChip ? (
<span className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">
diff --git a/tests/unit/cli/test_health_cmd_controls.py b/tests/unit/cli/test_health_cmd_controls.py
index 0eca4d365..e42f78f80 100644
--- a/tests/unit/cli/test_health_cmd_controls.py
+++ b/tests/unit/cli/test_health_cmd_controls.py
@@ -132,3 +132,53 @@ def test_the_report_leads_with_fix_first() -> None:
assert " 2. Start breaking up run (CCN 44, 50 lines): first lift lines 20-35 " in out
assert "src/core.py:20" in out
assert "verify: pytest tests/test_core_0.py" in out
+
+
+def _mostly_unanalysed_output(*args: str) -> str:
+ """``repowise health`` over 4 scored files beside 431 it cannot analyse."""
+ from repowise.core.analysis.health.models import HealthFileMetricData
+ from repowise.core.analysis.health.scoring import compute_kpis
+
+ def row(path: str, score: float | None) -> HealthFileMetricData:
+ return HealthFileMetricData(
+ file_path=path,
+ score=score,
+ max_ccn=None if score is None else 1,
+ max_nesting=None if score is None else 1,
+ nloc=10,
+ has_test_file=False,
+ defect_score=score,
+ )
+
+ metrics = [row(f"s{i}.swift", 10.0) for i in range(4)]
+ metrics += [row(f"u{i}.swift", None) for i in range(431)]
+ report = SimpleNamespace(metrics=metrics, findings=[], kpis=compute_kpis(metrics, set()))
+ console = Console(file=io.StringIO(), width=400, force_terminal=False)
+ runner = CliRunner()
+ with runner.isolated_filesystem():
+ Path(".repowise").mkdir()
+ with (
+ patch.object(health_module, "resolve_command_target") as resolve,
+ patch.object(health_module, "_load_stored_report", return_value=(report, set(), {})),
+ patch.object(health_module, "_load_fix_first", return_value=None),
+ patch.object(health_module, "_render_defect_accuracy_line"),
+ patch.object(health_module, "_render_performance_section"),
+ patch.object(health_module, "console", console),
+ ):
+ resolve.return_value = SimpleNamespace(
+ is_workspace=False,
+ repo_path=Path("."),
+ notice=lambda *a, **k: None,
+ )
+ result = runner.invoke(cli, ["health", *args])
+ assert result.exit_code == 0, result.output
+ return console.file.getvalue()
+
+
+def test_a_mostly_unanalysed_repo_gets_no_band_in_any_scope() -> None:
+ """A narrowed recompute keeps the unanalysed files in the share."""
+ for args in ((), ("--scope", "production")):
+ out = _mostly_unanalysed_output(*args)
+ assert "Code health: 10.0/10 ·" in out, args
+ assert "Excellent" not in out, args
+ assert "analysed 4 of 435 code files" in out, args
diff --git a/tests/unit/cli/test_status_storage.py b/tests/unit/cli/test_status_storage.py
index 31457b959..3aacfcb6a 100644
--- a/tests/unit/cli/test_status_storage.py
+++ b/tests/unit/cli/test_status_storage.py
@@ -35,6 +35,38 @@ def test_health_line_for_a_repo_with_no_scored_file(monkeypatch) -> None:
assert line is not None and "not analysed" in line and "2992" in line
+def _health(**over) -> dict:
+ return {
+ "average_health": 10.0,
+ "file_count": 4,
+ "unanalysed_file_count": 0,
+ "analysed_share": 1.0,
+ "worst_performer_path": "a.swift",
+ "worst_performer_score": 10.0,
+ **over,
+ }
+
+
+def test_health_line_withholds_the_band_on_a_mostly_unanalysed_repo(monkeypatch) -> None:
+ monkeypatch.setattr(
+ status_cmd,
+ "_query_health",
+ lambda _path: _health(unanalysed_file_count=431, analysed_share=4 / 435),
+ )
+ line = status_cmd._query_health_line(Path("."))
+ assert line is not None
+ assert "Excellent" not in line
+ assert "analysed 4 of 435 code files" in line
+
+
+def test_health_line_is_unchanged_when_fully_analysed(monkeypatch) -> None:
+ monkeypatch.setattr(status_cmd, "_query_health", lambda _path: _health())
+ line = status_cmd._query_health_line(Path("."))
+ assert line is not None
+ assert "(avg) [[green]Excellent[/green]] · " in line
+ assert "analysed" not in line
+
+
class TestStatusKeylessUpgradeNote:
"""``repowise status`` names the keyless upgrade commands, template-only (#3105)."""
diff --git a/tests/unit/generation/test_editor_file_base.py b/tests/unit/generation/test_editor_file_base.py
index 9a3d64c1b..0c6760ac2 100644
--- a/tests/unit/generation/test_editor_file_base.py
+++ b/tests/unit/generation/test_editor_file_base.py
@@ -231,6 +231,19 @@ def test_the_headline_drops_the_band_when_it_is_unknown(gen):
assert "avg ()" not in result
+def test_the_headline_states_the_analysed_share(gen):
+ import dataclasses
+
+ block = dataclasses.replace(
+ _health_block(6.4, band=""), analysed_note="analysed 4 of 435 code files"
+ )
+ result = gen.render(dataclasses.replace(_minimal_data(), code_health=block))
+ assert "code health 7.5/10 avg (analysed 4 of 435 code files)," in result
+ block = dataclasses.replace(block, band="Good")
+ result = gen.render(dataclasses.replace(_minimal_data(), code_health=block))
+ assert "avg (Good, analysed 4 of 435 code files)," in result
+
+
def test_render_surfaces_maintainability_when_present(gen):
import dataclasses
diff --git a/tests/unit/health/test_grading.py b/tests/unit/health/test_grading.py
index 9e0287516..e5f7eb88e 100644
--- a/tests/unit/health/test_grading.py
+++ b/tests/unit/health/test_grading.py
@@ -18,9 +18,12 @@ from repowise.core.analysis.health.grading import (
GOOD_MIN,
NEEDS_WORK_MIN,
TARGET_SCORE,
+ analysed_note,
+ analysed_share,
band_for,
distribution,
format_score,
+ headline_band,
)
@@ -159,3 +162,28 @@ def test_distribution_accepts_objects() -> None:
dist = distribution([_M("a.py", 9.0, 100), _M("b.py", 2.0, 100)])
assert dist["bands"]["excellent"]["pct"] == 50.0
assert dist["bands"]["at_risk"]["pct"] == 50.0
+
+
+def test_headline_band_is_withheld_when_few_files_were_analysed() -> None:
+ # 4 scored Swift files beside 431 the dialect cannot read.
+ share = analysed_share(4, 431)
+ assert share is not None and share < 0.5
+ assert headline_band(10.0, share) is None
+ # The per-file band is untouched.
+ assert band_for(10.0) == "excellent"
+
+
+def test_headline_band_matches_band_for_when_fully_analysed() -> None:
+ assert analysed_share(435, 0) == 1.0
+ for score in (9.0, 7.5, 6.0, 4.5, 2.0):
+ assert headline_band(score, 1.0) == band_for(score)
+ # Half is enough; an unknown share keeps the band; no score has none.
+ assert headline_band(9.0, analysed_share(1, 1)) == "excellent"
+ assert headline_band(9.0, None) == "excellent"
+ assert headline_band(None, 1.0) is None
+
+
+def test_analysed_note_only_when_files_were_left_out() -> None:
+ assert analysed_note(4, 431) == "analysed 4 of 435 code files"
+ assert analysed_note(435, 0) is None
+ assert analysed_share(0, 0) is None
diff --git a/tests/unit/health/test_unanalysed_languages.py b/tests/unit/health/test_unanalysed_languages.py
index 1fcea8a9b..8ec3a97bd 100644
--- a/tests/unit/health/test_unanalysed_languages.py
+++ b/tests/unit/health/test_unanalysed_languages.py
@@ -14,7 +14,7 @@ from repowise.core.analysis.health.complexity import FileComplexity, walk_file
from repowise.core.analysis.health.complexity.languages import has_health_dialect
from repowise.core.analysis.health.duplication import DuplicationReport
from repowise.core.analysis.health.engine import HealthAnalyzer
-from repowise.core.analysis.health.grading import distribution
+from repowise.core.analysis.health.grading import band_for, distribution, headline_band
from repowise.core.analysis.health.models import HealthFileMetricData
from repowise.core.analysis.health.ranking import worst_metric
from repowise.core.analysis.health.scoring import (
@@ -111,6 +111,22 @@ def test_kpis_leave_unscored_files_out() -> None:
assert kpis["worst_performer_path"] == "a.py"
+def test_a_mostly_unanalysed_repo_carries_its_share_and_no_band() -> None:
+ rows = [_metric(f"s{i}.swift", 10.0) for i in range(4)]
+ rows += [_metric(f"u{i}.swift", None) for i in range(431)]
+ kpis = compute_kpis(rows, set())
+ assert kpis["average_health"] == 10.0
+ assert kpis["analysed_share"] < 0.5
+ assert headline_band(kpis["average_health"], kpis["analysed_share"]) is None
+
+
+def test_a_fully_analysed_repo_keeps_its_band() -> None:
+ kpis = compute_kpis([_metric("a.py", 9.0), _metric("b.py", 8.0)], set())
+ assert kpis["analysed_share"] == 1.0
+ avg = kpis["average_health"]
+ assert headline_band(avg, kpis["analysed_share"]) == band_for(avg)
+
+
def test_a_repository_of_only_unscored_files_has_no_average() -> None:
kpis = compute_kpis([_metric("A.ex", None), _metric("B.ex", None)], {"A.ex"})
assert kpis["average_health"] is None
diff --git a/tests/unit/persistence/test_average_health.py b/tests/unit/persistence/test_average_health.py
index f80bcaff0..b3bc08684 100644
--- a/tests/unit/persistence/test_average_health.py
+++ b/tests/unit/persistence/test_average_health.py
@@ -1,4 +1,4 @@
-"""``get_average_health`` — the badge's one number, without the dataset.
+"""``get_headline_health``: the badge's one number, without the dataset.
The public badge endpoints render a single float and were reading the whole
health dataset to get it. The narrow read has to agree with
@@ -9,7 +9,7 @@ dashboard it links to.
from __future__ import annotations
from repowise.core.persistence.crud import (
- get_average_health,
+ get_headline_health,
get_health_summary,
save_health_metrics,
upsert_repository,
@@ -37,9 +37,10 @@ async def test_matches_the_summary_and_is_nloc_weighted(async_session, tmp_path)
[_metric("src/big.py", 1.0, 900), _metric("src/small.py", 10.0, 100)],
)
- avg = await get_average_health(async_session, repo.id)
+ avg, share = await get_headline_health(async_session, repo.id)
assert avg == 1.9 # (1.0*900 + 10.0*100) / 1000
+ assert share == 1.0
assert avg == (await get_health_summary(async_session, repo.id))["average_health"]
@@ -50,9 +51,9 @@ async def test_zero_nloc_rows_fall_back_to_a_plain_mean(async_session, tmp_path)
async_session, repo.id, [_metric("a.py", 2.0, 0), _metric("b.py", 8.0, 0)]
)
- assert await get_average_health(async_session, repo.id) == 5.0
+ assert (await get_headline_health(async_session, repo.id))[0] == 5.0
assert (
- await get_average_health(async_session, repo.id)
+ (await get_headline_health(async_session, repo.id))[0]
== (await get_health_summary(async_session, repo.id))["average_health"]
)
@@ -77,9 +78,9 @@ async def test_honors_the_exclusion_spec(async_session, tmp_path) -> None:
)
# Unfiltered this would be 1.7; the excluded file must not count at all.
- assert await get_average_health(async_session, repo.id) == 8.0
+ assert (await get_headline_health(async_session, repo.id))[0] == 8.0
assert (
- await get_average_health(async_session, repo.id)
+ (await get_headline_health(async_session, repo.id))[0]
== (await get_health_summary(async_session, repo.id))["average_health"]
)
@@ -94,5 +95,18 @@ async def test_unmeasured_repo_reports_none_rather_than_a_perfect_score(
"""
repo = await upsert_repository(async_session, name="repo", local_path=str(tmp_path))
- assert await get_average_health(async_session, repo.id) is None
+ assert (await get_headline_health(async_session, repo.id))[0] is None
assert (await get_health_summary(async_session, repo.id))["average_health"] is None
+
+
+async def test_share_counts_unscored_files_like_the_summary(async_session, tmp_path) -> None:
+ """The badge's band gate reads the same share the dashboard does."""
+ repo = await upsert_repository(async_session, name="repo", local_path=str(tmp_path))
+ unscored = [{**_metric(f"u{i}.swift", 0.0, 10), "score": None} for i in range(3)]
+ await save_health_metrics(async_session, repo.id, [_metric("a.py", 9.0, 10), *unscored])
+
+ avg, share = await get_headline_health(async_session, repo.id)
+
+ assert avg == 9.0
+ assert share == 0.25
+ assert share == (await get_health_summary(async_session, repo.id))["analysed_share"]
diff --git a/tests/unit/persistence/test_health_metric_nullable_rebuild.py b/tests/unit/persistence/test_health_metric_nullable_rebuild.py
index 55c6964d1..5b99ccc9c 100644
--- a/tests/unit/persistence/test_health_metric_nullable_rebuild.py
+++ b/tests/unit/persistence/test_health_metric_nullable_rebuild.py
@@ -114,8 +114,8 @@ async def test_the_badge_says_no_data_when_no_file_is_scored(async_session):
repo = await insert_repo(async_session)
# No rows at all is no data too: a repo of only data and config files has none.
- assert await _badge_average_health(async_session, repo.id) is None
+ assert await _badge_average_health(async_session, repo.id) == (None, None)
await save_health_metrics(async_session, repo.id, [_row("Big.ex", None)])
- assert await _badge_average_health(async_session, repo.id) is None
+ assert await _badge_average_health(async_session, repo.id) == (None, 0.0)
await save_health_metrics(async_session, repo.id, [_row("Big.ex", None), _row("a.py", 8.0)])
- assert await _badge_average_health(async_session, repo.id) == 8.0
+ assert await _badge_average_health(async_session, repo.id) == (8.0, 0.5)
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index 16e969f4c..f5aaca5cb 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -2707,3 +2707,37 @@ async def test_dashboard_unanalysed_file_count_name(setup_mcp, health_data, sess
only = await get_health(only=["unanalysed_file_count"])
assert only["unanalysed_file_count"] == 1
assert "unknown_only_keys" not in only
+
+
+async def test_overview_states_both_counts_and_withholds_the_band(setup_mcp, health_data, session):
+ """A few scored files beside many unanalysed ones: no band, both counts said."""
+ import uuid
+ from types import SimpleNamespace
+
+ from repowise.core.persistence.models import HealthFileMetric
+ from repowise.server.mcp_server.tool_overview.health import _build_code_health
+
+ repo = SimpleNamespace(id=health_data)
+ full = await _build_code_health(session, repo)
+ assert full["band"] is not None
+ assert "unanalysed_file_count" not in full
+ assert "analysed_share" not in full
+
+ for i in range(3):
+ session.add(
+ HealthFileMetric(
+ id=uuid.uuid4().hex,
+ repository_id=health_data,
+ file_path=f"Sources/View{i}.swift",
+ score=None,
+ nloc=10,
+ )
+ )
+ await session.flush()
+
+ partial = await _build_code_health(session, repo)
+ assert partial["file_count"] == 2
+ assert partial["unanalysed_file_count"] == 3
+ assert partial["analysed_share"] == 0.4
+ assert partial["band"] is None
diff --git a/tests/unit/server/test_health_badge.py b/tests/unit/server/test_health_badge.py
index 34814272c..802bb9937 100644
--- a/tests/unit/server/test_health_badge.py
+++ b/tests/unit/server/test_health_badge.py
@@ -25,6 +25,12 @@ def test_badge_fields_band_colors() -> None:
assert _badge_fields(6.98) == ("health", "6.9/10", "yellow", "fair")
+def test_badge_is_neutral_when_too_little_was_analysed() -> None:
+ # 4 of 435 files scored: the score stays, but not in green.
+ assert _badge_fields(10.0, 4 / 435) == ("health", "10.0/10", "lightgrey", "unknown")
+ assert _badge_fields(9.0, 1.0) == ("health", "9.0/10", "brightgreen", "excellent")
+
+
def test_every_band_colour_has_a_hex_for_the_self_rendered_svg() -> None:
# The JSON endpoint hands shields a colour name; the SVG endpoint has to
# resolve it here. A band colour without a hex renders grey.
diff --git a/tests/unit/server/test_health_excludes.py b/tests/unit/server/test_health_excludes.py
index 57af62829..a8fd02498 100644
--- a/tests/unit/server/test_health_excludes.py
+++ b/tests/unit/server/test_health_excludes.py
@@ -89,6 +89,7 @@ async def test_health_reads_honor_repo_settings_excludes(session, tmp_path) -> N
assert summary == {
"file_count": 1,
"unanalysed_file_count": 0,
+ "analysed_share": 1.0,
"average_health": 8.5,
"worst_performer_path": "src/app.py",
"worst_performer_score": 8.5,
diff --git a/tests/unit/server/test_overview_headline_band.py b/tests/unit/server/test_overview_headline_band.py
new file mode 100644
index 000000000..4fc0ac823
--- /dev/null
+++ b/tests/unit/server/test_overview_headline_band.py
@@ -0,0 +1,51 @@
+"""The REST overview grades the headline only when enough code was analysed."""
+
+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 | None) -> HealthFileMetricData:
+ return HealthFileMetricData(
+ file_path=path,
+ score=score,
+ max_ccn=None if score is None else 1,
+ max_nesting=None if score is None else 1,
+ nloc=10,
+ has_test_file=False,
+ defect_score=score,
+ )
+
+
+async def _repo(client, session, tmp_path, metrics) -> str:
+ 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"], metrics)
+ await session.commit()
+ return repo["id"]
+
+
+async def test_a_mostly_unanalysed_repo_has_no_band(client, session, tmp_path) -> None:
+ metrics = [_metric("a.swift", 10.0)] + [_metric(f"u{i}.swift", None) for i in range(3)]
+ repo_id = await _repo(client, session, tmp_path, metrics)
+
+ health = (await client.get(f"/api/repos/{repo_id}/overview-summary")).json()["health"]
+ assert health["average_health"] == 10.0
+ assert health["unanalysed_file_count"] == 3
+ assert health["analysed_share"] == 0.25
+ assert health["band"] is None
+
+ summary = (await client.get(f"/api/repos/{repo_id}/health/overview")).json()["summary"]
+ assert summary["analysed_share"] == 0.25
+ assert summary["band"] is None
+
+
+async def test_a_fully_analysed_repo_keeps_its_band(client, session, tmp_path) -> None:
+ repo_id = await _repo(client, session, tmp_path, [_metric("a.py", 9.0), _metric("b.py", 9.0)])
+
+ health = (await client.get(f"/api/repos/{repo_id}/overview-summary")).json()["health"]
+ assert health["analysed_share"] == 1.0
+ assert health["band"] == "excellent"