Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(health): a repo with no scored file has no score, not 10.0 (#3053)
Swati Ahuja48982825815d
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.pyindex 44de4e7da..2da91a22d 100644--- a/packages/core/src/repowise/core/analysis/health/scoring.py+++ b/packages/core/src/repowise/core/analysis/health/scoring.py@@ -935,13 +935,15 @@ def hotspot_health(def _empty_kpis(unanalysed: int) -> dict[str, object]:- """KPIs with no scored file. An empty repository keeps its historical 10.0- floors (the snapshot columns need a number); a repository whose files are- all unscored has no average to report, so its headline is ``None``."""- floor = None if unanalysed else SCORE_MAX+ """KPIs with no scored file: the headline is ``None``, never 10.0.++ Data, markup and config files never get a metric row (``scope.scores_language``),+ so a repository of only those arrives here with no rows at all, the same as+ an empty one. Neither has code to score. ``snapshot_fields`` writes no trend+ point for a ``None`` average, so no column needs a stand-in number."""return {- "hotspot_health": floor,- "average_health": floor,+ "hotspot_health": None,+ "average_health": None,"unanalysed_file_count": unanalysed,"worst_performer_path": None,"worst_performer_score": None,diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.pyindex ff79bff52..cf0eaadb5 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py@@ -745,7 +745,7 @@ async def get_health_summary(return {"file_count": 0,"unanalysed_file_count": unanalysed,- "average_health": None if unanalysed else 10.0,+ "average_health": None,"worst_performer_path": None,"worst_performer_score": None,"worst_test_path": None,diff --git a/packages/server/src/repowise/server/routers/code_health/badge.py b/packages/server/src/repowise/server/routers/code_health/badge.pyindex ceb1eef54..edd05022c 100644--- a/packages/server/src/repowise/server/routers/code_health/badge.py+++ b/packages/server/src/repowise/server/routers/code_health/badge.py@@ -83,15 +83,10 @@ async def _badge_average_health(session: AsyncSession, repo_id: str) -> float |repo = await crud.get_repository(session, repo_id)if repo is None:raise HTTPException(status_code=404, detail="Repository not found")- avg = await crud.get_average_health(session, repo_id)- if avg is not None:- return avg- # A repo with no metrics has always badged as a perfect 10.0 here, because- # ``get_health_summary`` returns 10.0 for an empty table. Preserved rather- # than quietly corrected: mapping "unmeasured" to 10.0 is this endpoint's- # existing contract. Rows with no score are another answer: every file is- # in a language health has no dialect for, and that badges "no data".- return None if await crud.get_scored_file_paths(session, repo_id) else 10.0+ # ``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)@router.get("/api/repos/{repo_id}/health/badge.json", response_model=HealthBadgeResponse)diff --git a/tests/unit/health/test_code_only_repo_score.py b/tests/unit/health/test_code_only_repo_score.pynew file mode 100644index 000000000..14cc8b143--- /dev/null+++ b/tests/unit/health/test_code_only_repo_score.py@@ -0,0 +1,84 @@+"""A repository's score counts code files only.++Data, markup and config files (JSON, YAML, Markdown and the rest the language+registry does not declare as code) get no metric row, so they cannot lift the+average. A big generated JSON spec used to sit in the average as a flat 10.0+weighted by its line count. And a repository with nothing but such files has+no code to score, so it reads "no score", never a perfect 10.0.+"""++from __future__ import annotations++from types import SimpleNamespace++import networkx as nx+import pytest++from repowise.core.analysis.health.engine import HealthAnalyzer+from repowise.core.analysis.health.scoring import compute_kpis+from repowise.core.analysis.health.trends import snapshot_fields++# A long, deeply nested function with many branches, so the file scores well+# below 10 and a 10.0 data file in the average would visibly lift it.+_BRANCHES = "\n".join(+ f" {'if' if i == 0 else 'elif'} x == {i}:\n"+ " for j in range(y):\n"+ " if j % 2:\n"+ " while z:\n"+ f" z -= {i}"+ for i in range(40)+)+_CODE = f"def tangled(x, y, z, a, b, c, d, e, f):\n total = 0\n if a:\n{_BRANCHES}\n return total\n"+++def _parsed(tmp_path, rel: str, language: str, body: str) -> SimpleNamespace:+ path = tmp_path / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(body)+ return SimpleNamespace(+ file_info=SimpleNamespace(path=rel, abs_path=str(path), language=language, is_test=False),+ symbols=[],+ )+++def _big_json(tmp_path) -> SimpleNamespace:+ entries = ",\n".join(f' "key_{i}": {{"value": {i}}}' for i in range(5_000))+ return _parsed(tmp_path, "swagger/swagger.json", "json", "{\n" + entries + "\n}\n")+++def _analyze(tmp_path, files: list[SimpleNamespace]):+ return HealthAnalyzer(graph=nx.DiGraph(), parsed_files=files, repo_root=tmp_path).analyze()+++def test_a_big_json_file_does_not_lift_the_code_files_score(tmp_path) -> None:+ code = _parsed(tmp_path, "src/tangled.py", "python", _CODE)+ report = _analyze(tmp_path, [_big_json(tmp_path), code])++ by_path = {m.file_path: m for m in report.metrics}+ if "src/tangled.py" not in by_path or by_path["src/tangled.py"].score is None:+ pytest.skip("python tree-sitter pack missing")+ assert "swagger/swagger.json" not in by_path+ assert report.kpis["average_health"] == by_path["src/tangled.py"].score+ assert report.kpis["average_health"] < 10.0+++def test_a_repository_of_only_data_files_has_no_score(tmp_path) -> None:+ files = [+ _big_json(tmp_path),+ _parsed(tmp_path, "README.md", "markdown", "# Title\n\nSome prose.\n"),+ _parsed(tmp_path, "config/app.yaml", "yaml", "name: app\nreplicas: 3\n"),+ ]+ report = _analyze(tmp_path, files)++ assert report.metrics == []+ assert report.kpis["average_health"] is None+ assert report.kpis["hotspot_health"] is None+ # No trend point for a number nobody measured.+ assert snapshot_fields(report.kpis, [], []) is None+++def test_no_scored_rows_means_no_score() -> None:+ kpis = compute_kpis([], set())+ assert kpis["average_health"] is None+ assert kpis["hotspot_health"] is None+ assert kpis["file_count"] == 0diff --git a/tests/unit/health/test_scoring.py b/tests/unit/health/test_scoring.pyindex 556992351..d89408432 100644--- a/tests/unit/health/test_scoring.py+++ b/tests/unit/health/test_scoring.py@@ -104,7 +104,7 @@ def test_compute_kpis_uses_nloc_weighting():def test_compute_kpis_empty_returns_defaults():kpis = compute_kpis([], hotspot_paths=set())- assert kpis["average_health"] == 10.0+ assert kpis["average_health"] is Noneassert kpis["file_count"] == 0assert kpis["maintainability_average"] is Noneassert kpis["performance_average"] is Nonediff --git a/tests/unit/health/test_unanalysed_languages.py b/tests/unit/health/test_unanalysed_languages.pyindex 8d7b58ffe..5a491b1f9 100644--- a/tests/unit/health/test_unanalysed_languages.py+++ b/tests/unit/health/test_unanalysed_languages.py@@ -116,11 +116,12 @@ def test_a_repository_of_only_unscored_files_has_no_average() -> None:assert snapshot_fields(kpis, [_metric("A.php", None)], []) is None-def test_an_empty_repository_keeps_its_old_kpis() -> None:- """Control: no rows at all is not the same answer as no scored rows."""+def test_an_empty_repository_has_no_average_either() -> None:+ """No rows at all is also no score: a repository of only data and config+ files arrives with no rows, since those files never get one."""kpis = compute_kpis([], set())- assert kpis["average_health"] == 10.0- assert snapshot_fields(kpis, [], []) is not None+ assert kpis["average_health"] is None+ assert snapshot_fields(kpis, [], []) is Nonedef test_unscored_files_are_never_the_worst_or_a_hotspot() -> None:diff --git a/tests/unit/persistence/test_average_health.py b/tests/unit/persistence/test_average_health.pyindex 831efabe7..f80bcaff0 100644--- a/tests/unit/persistence/test_average_health.py+++ b/tests/unit/persistence/test_average_health.py@@ -87,14 +87,12 @@ async def test_honors_the_exclusion_spec(async_session, tmp_path) -> None:async def test_unmeasured_repo_reports_none_rather_than_a_perfect_score(async_session, tmp_path) -> None:- """No rows is "not measured", not 10.0.+ """No rows is "not measured", not 10.0, in the summary and the badge alike.- ``get_health_summary`` returns 10.0 here, which the badge endpoint has- always rendered and still does — it maps ``None`` back to 10.0 itself. The- crud helper stays honest so a new caller is not handed a perfect score for- a repo nobody has analysed.+ A repository of only data and config files has no rows, since those files+ never get one, so a 10.0 here would badge it as perfect."""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_health_summary(async_session, repo.id))["average_health"] == 10.0+ assert (await get_health_summary(async_session, repo.id))["average_health"] is Nonediff --git a/tests/unit/persistence/test_health_metric_nullable_rebuild.py b/tests/unit/persistence/test_health_metric_nullable_rebuild.pyindex 76749c82f..e5ca29b43 100644--- a/tests/unit/persistence/test_health_metric_nullable_rebuild.py+++ b/tests/unit/persistence/test_health_metric_nullable_rebuild.py@@ -113,8 +113,8 @@ async def test_the_badge_says_no_data_when_no_file_is_scored(async_session):from repowise.server.routers.code_health.badge import _badge_average_healthrepo = await insert_repo(async_session)- # No rows at all keeps the endpoint's historical 10.0.- assert await _badge_average_health(async_session, repo.id) == 10.0+ # 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 Noneawait save_health_metrics(async_session, repo.id, [_row("Big.php", None)])assert await _badge_average_health(async_session, repo.id) is Noneawait save_health_metrics(async_session, repo.id, [_row("Big.php", None), _row("a.py", 8.0)])