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): make the headline split add up and mark advisory rows in the CLI findings table (#4770)

Raghav Chamadiya03fc147a14bc
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 6dcde9a5f..9d130914b 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
@@ -39,7 +39,7 @@ from repowise.core.analysis.health.models import split_by_origin
from repowise.core.analysis.health.ranking import deduction_by_path
from repowise.core.analysis.health.rows import detail_map, split_unscored
from repowise.core.analysis.health.scope import DEFAULT_SCOPE, SCOPES, parse_scope
-from repowise.core.analysis.health.scoring import compute_kpis
+from repowise.core.analysis.health.scoring import ADVISORY_DIMENSION, compute_kpis
from repowise.core.analysis.health.signals import HISTORY_MIN_COMMITS
from repowise.core.persistence.crud.analysis.health import open_finding_count
@@ -688,27 +688,38 @@ def _render_files_table(metrics_sorted: list[Any], short_history: set[str]) -> N
)
+def _is_advisory(finding: Any) -> bool:
+ return getattr(finding, "dimension", None) == ADVISORY_DIMENSION
+
+
def _render_findings_table(findings: list[Any]) -> None:
if not findings:
return
- # The total get_overview prints; advisory rows are listed, not counted.
- console.print(f"\n[bold]{open_finding_count(findings)}[/bold] open findings:")
+ # The total get_overview prints. Advisory rows deduct nothing, so they are
+ # listed after the counted ones and marked, never counted.
+ counted = open_finding_count(findings)
+ advisory = len(findings) - counted
+ header = f"\n[bold]{counted}[/bold] open findings"
+ if advisory:
+ header += f" [dim](+{advisory} advisory, not scored)[/dim]"
+ console.print(header + ":")
+ listed = sorted(findings, key=_is_advisory)[:30]
f_table = Table()
f_table.add_column("Severity", style="magenta")
f_table.add_column("Marker", style="cyan")
f_table.add_column("File")
f_table.add_column("Function")
f_table.add_column("Impact", justify="right")
- for f in findings[:30]:
+ for f in listed:
f_table.add_row(
str(f.severity),
f.biomarker_type,
f.file_path,
f.function_name or "-",
- f"-{f.health_impact:.2f}",
+ "[dim]advisory[/dim]" if _is_advisory(f) else f"-{f.health_impact:.2f}",
)
console.print(f_table)
- for line in preview_lines("health", findings[:30], kind="biomarker_type"):
+ for line in preview_lines("health", listed, kind="biomarker_type"):
console.print(f"[dim]{line}[/dim]")
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.py
index 74689e989..19fd4d7e6 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -977,6 +977,32 @@ def nloc_weighted_attr(rows: list[HealthFileMetricData], attr: str) -> float | N
return sum(float(field(r, attr)) * _weight(r) for r in scored) / total_w
+def headline_split(rows: Sequence[Any]) -> tuple[float | None, float | None]:
+ """NLOC-weighted ``(structure, history)`` halves of the headline deduction.
+
+ The stored halves are unclamped, so a file under the floor holds more
+ points than its score lost. Each file's halves are scaled to its floored
+ deficit (``SCORE_MAX - score``) so the two always add up to ``SCORE_MAX``
+ minus the headline. ``(None, None)`` until every scored file carries the
+ split: halves over a subset would not add up to the headline.
+ """
+ split = scored_rows(rows)
+ if not split or any(
+ field(r, "structure_deduction", None) is None and field(r, "history_deduction", None) is None
+ for r in split
+ ):
+ return None, None
+ structure = history = 0.0
+ for r in split:
+ s = float(field(r, "structure_deduction", 0.0) or 0.0)
+ h = float(field(r, "history_deduction", 0.0) or 0.0)
+ scale = (SCORE_MAX - _row_score(r)) / (s + h) if s + h > 0 else 0.0
+ structure += s * scale * _weight(r)
+ history += h * scale * _weight(r)
+ total_w = sum(_weight(r) for r in split)
+ return structure / total_w, history / total_w
+
+
def nloc_weighted_score(rows: list[HealthFileMetricData]) -> float:
"""NLOC-weighted mean of ``score``, weighting each file by ``max(nloc, 1)``.
@@ -1085,7 +1111,8 @@ def compute_kpis(
``None`` when no file carries a performance score.
- ``structure_average`` / ``history_average`` and their hotspot pair: the
headline's two halves, in deduction points, so a surface can say which
- one is holding the score down. ``None`` until files carry the split.
+ one is holding the score down. They sum to ``SCORE_MAX`` minus the
+ matching headline (``headline_split``). ``None`` until files carry the split.
- ``production_average``: ``average_health`` over non-test files, weighted
identically, so a narrowed view and a narrowed trend agree.
- ``unanalysed_file_count``: files stored with no score because health has
@@ -1112,11 +1139,9 @@ def compute_kpis(
maint_hotspot = nloc_weighted_attr(hotspots, "maintainability_score")
perf_avg = nloc_weighted_attr(metrics, "performance_score")
perf_hotspot = nloc_weighted_attr(hotspots, "performance_score")
- splits = {
- f"{half}_{scope}": nloc_weighted_attr(rows, f"{half}_deduction")
- for half in ("structure", "history")
- for scope, rows in (("average", metrics), ("hotspot", hotspots))
- }
+ splits: dict[str, float | None] = {}
+ for scope, rows in (("average", metrics), ("hotspot", hotspots)):
+ splits[f"structure_{scope}"], splits[f"history_{scope}"] = headline_split(rows)
return {
"hotspot_health": hotspot_health(metrics, hotspot_paths),
"average_health": round(nloc_weighted_score(metrics), 2),
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health/summary.py b/packages/core/src/repowise/core/persistence/crud/analysis/health/summary.py
index fbef333ae..5db50a6e6 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/health/summary.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health/summary.py
@@ -10,7 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from .....analysis.health.grading import analysed_share
from .....analysis.health.ranking import deduction_by_path, worst_kpis
from .....analysis.health.rows import split_unscored
-from .....analysis.health.scoring import nloc_weighted_attr
+from .....analysis.health.scoring import headline_split, nloc_weighted_attr
from ....models import HealthFileMetric, HealthFinding
from ..plain_rows import plain_rows
from ..shown import shown
@@ -146,6 +146,7 @@ async def get_health_summary(
"worst_performance_score": None,
}
avg = nloc_weighted_attr(metrics, "score")
+ structure_average, history_average = headline_split(metrics)
# The two co-surfaced pillars: the same NLOC weighting over their own
# columns, ``None`` when no row carries one so a surface reads "not
@@ -205,8 +206,8 @@ async def get_health_summary(
# The headline's two halves, in deduction points. Both come off columns
# already on the rows in hand, so this costs no query — and without them
# the page can show a score falling without saying which half moved.
- "structure_average": _rounded(nloc_weighted_attr(metrics, "structure_deduction")),
- "history_average": _rounded(nloc_weighted_attr(metrics, "history_deduction")),
+ "structure_average": _rounded(structure_average),
+ "history_average": _rounded(history_average),
"maintainability_findings": by_dim.get("maintainability", 0),
"performance_causes": causes.as_dict(),
"performance_coverage_pct": (coverage.pct_loc if coverage.analyzed_files else None),
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 710bfe834..7b0defda3 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
@@ -16,6 +16,7 @@ from repowise.core.analysis.health.perf.coverage import PerfCoverage
from repowise.core.analysis.health.ranking import worst_kpis
from repowise.core.analysis.health.rows import split_tests
from repowise.core.analysis.health.scoring import (
+ headline_split,
hotspot_health,
nloc_weighted_attr,
nloc_weighted_score,
@@ -160,6 +161,13 @@ def _avg(metrics: list[HealthFileMetric], attr: str) -> float | None:
return round(value, 2) if value is not None else None
+def _split_kpis(metrics: list[HealthFileMetric]) -> dict[str, float | None]:
+ """The headline's code-shape and history halves, in deduction points."""
+ halves = headline_split(metrics)
+ keys = ("structure_average", "history_average")
+ return {k: round(v, 2) if v is not None else None for k, v in zip(keys, halves, strict=True)}
+
+
def _compute_kpis(
metrics: list[HealthFileMetric],
*,
@@ -224,9 +232,7 @@ def _compute_kpis(
# ``None`` until the pillar is measured.
"maintainability_average": _avg(metrics, "maintainability_score"),
"performance_average": _avg(metrics, "performance_score"),
- # The headline's code-shape and history halves, in deduction points.
- "structure_average": _avg(metrics, "structure_deduction"),
- "history_average": _avg(metrics, "history_deduction"),
+ **_split_kpis(metrics),
# Performance leads with the causes worth fixing now and coverage, not the diluted /10.
**_perf_kpis(performance_causes, coverage),
}
diff --git a/tests/unit/cli/test_health_cmd_findings_table.py b/tests/unit/cli/test_health_cmd_findings_table.py
new file mode 100644
index 000000000..7e50963cd
--- /dev/null
+++ b/tests/unit/cli/test_health_cmd_findings_table.py
@@ -0,0 +1,53 @@
+"""``repowise health`` lists advisory findings apart from the counted ones."""
+
+from __future__ import annotations
+
+import io
+from unittest.mock import patch
+
+from rich.console import Console
+
+from repowise.cli.commands.health_cmd import command as health_module
+from repowise.core.analysis.health.models import HealthFindingData, Severity
+
+
+def _finding(marker: str, impact: float, dimension: str) -> HealthFindingData:
+ return HealthFindingData(
+ biomarker_type=marker,
+ severity=Severity.MEDIUM,
+ file_path="src/app.py",
+ function_name="run",
+ line_start=1,
+ line_end=9,
+ details={},
+ health_impact=impact,
+ dimension=dimension,
+ )
+
+
+def test_header_counts_the_scored_rows_and_advisory_rows_are_marked_last() -> None:
+ findings = [
+ _finding("brain_method", 0.0, "advisory"),
+ _finding("complex_method", 1.2, "defect"),
+ _finding("hidden_coupling", 0.0, "advisory"),
+ _finding("large_method", 0.4, "defect"),
+ ]
+ console = Console(file=io.StringIO(), width=400, force_terminal=False)
+ with patch.object(health_module, "console", console):
+ health_module._render_findings_table(findings)
+ out = console.file.getvalue()
+
+ assert "2 open findings (+2 advisory, not scored):" in out
+ rows = [line for line in out.splitlines() if "src/app.py" in line]
+ order = ["complex_method", "large_method", "brain_method", "hidden_coupling"]
+ assert all(marker in row for marker, row in zip(order, rows, strict=True))
+ assert all("advisory" in r and "-0.00" not in r for r in rows[2:])
+ assert "-1.20" in rows[0] and "advisory" not in rows[0]
+
+
+def test_no_advisory_note_without_advisory_rows() -> None:
+ console = Console(file=io.StringIO(), width=400, force_terminal=False)
+ with patch.object(health_module, "console", console):
+ health_module._render_findings_table([_finding("complex_method", 1.2, "defect")])
+ out = console.file.getvalue()
+ assert "1 open findings:" in out and "advisory" not in out
diff --git a/tests/unit/health/golden/health_engine.json b/tests/unit/health/golden/health_engine.json
index 3c67af2e9..77f866356 100644
--- a/tests/unit/health/golden/health_engine.json
+++ b/tests/unit/health/golden/health_engine.json
@@ -136,8 +136,8 @@
"performance_average": 10.0,
"performance_hotspot": null,
"structure_average": 0.0,
- "structure_hotspot": null,
"history_average": 0.0,
+ "structure_hotspot": null,
"history_hotspot": null,
"production_average": 10.0,
"production_file_count": 1,
@@ -195,8 +195,8 @@
"performance_average": 10.0,
"performance_hotspot": null,
"structure_average": 0.0,
- "structure_hotspot": null,
"history_average": 0.0,
+ "structure_hotspot": null,
"history_hotspot": null,
"production_average": 10.0,
"production_file_count": 1,
@@ -405,8 +405,8 @@
"performance_average": 10.0,
"performance_hotspot": null,
"structure_average": 1.51,
- "structure_hotspot": null,
"history_average": 0.0,
+ "structure_hotspot": null,
"history_hotspot": null,
"production_average": 8.49,
"production_file_count": 3,
@@ -793,9 +793,9 @@
"maintainability_hotspot": null,
"performance_average": 10.0,
"performance_hotspot": null,
- "structure_average": 3.08,
- "structure_hotspot": null,
+ "structure_average": 3.09,
"history_average": 0.0,
+ "structure_hotspot": null,
"history_hotspot": null,
"production_average": 6.91,
"production_file_count": 1,
@@ -5306,8 +5306,8 @@
"performance_average": 9.48,
"performance_hotspot": null,
"structure_average": 0.35,
- "structure_hotspot": null,
"history_average": 0.0,
+ "structure_hotspot": null,
"history_hotspot": null,
"production_average": 9.64,
"production_file_count": 69,
diff --git a/tests/unit/health/test_scope_and_split.py b/tests/unit/health/test_scope_and_split.py
index 665270196..8715c487d 100644
--- a/tests/unit/health/test_scope_and_split.py
+++ b/tests/unit/health/test_scope_and_split.py
@@ -7,12 +7,18 @@ import pytest
from repowise.core.analysis.health.biomarkers.base import BiomarkerResult, FileContext
from repowise.core.analysis.health.biomarkers.hidden_coupling import HiddenCouplingDetector
from repowise.core.analysis.health.biomarkers.untested_hotspot import UntestedHotspotDetector
-from repowise.core.analysis.health.models import Severity, split_by_origin
+from repowise.core.analysis.health.models import (
+ HealthFileMetricData,
+ Severity,
+ split_by_origin,
+)
from repowise.core.analysis.health.scope import parse_scope, scores_language
from repowise.core.analysis.health.scoring import (
SCORE_MAX,
attach_impacts,
+ compute_kpis,
deduction_split,
+ headline_split,
score_file,
unclamped_score,
)
@@ -126,6 +132,47 @@ def test_history_alone_can_hold_a_score_down() -> None:
assert history > 0
+def _row(path: str, score: float, structure: float, history: float, nloc: int = 100):
+ return HealthFileMetricData(
+ file_path=path,
+ score=score,
+ max_ccn=1,
+ max_nesting=1,
+ nloc=nloc,
+ has_test_file=False,
+ structure_deduction=structure,
+ history_deduction=history,
+ )
+
+
+def test_a_floored_file_splits_only_the_points_it_lost() -> None:
+ """Unclamped 12.71 = 9.21 + 3.5, floored at 1.0: the halves share 9.0."""
+ structure, history = headline_split([_row("a.py", 1.0, 9.21, 3.5)])
+ assert structure is not None and history is not None
+ assert round(structure + history, 6) == SCORE_MAX - 1.0
+ assert round(structure / history, 6) == round(9.21 / 3.5, 6)
+
+
+def test_the_headline_halves_add_up_to_its_deficit() -> None:
+ rows = [
+ _row("floored.py", 1.0, 9.21, 3.5, nloc=300),
+ _row("fine.py", 8.5, 1.0, 0.5, nloc=200),
+ _row("clean.py", 10.0, 0.0, 0.0, nloc=50),
+ ]
+ kpis = compute_kpis(rows, {"floored.py"})
+ for scope, headline in (("average", "average_health"), ("hotspot", "hotspot_health")):
+ halves = kpis[f"structure_{scope}"] + kpis[f"history_{scope}"]
+ assert abs(halves - (SCORE_MAX - kpis[headline])) <= 0.011
+
+
+def test_the_split_is_unknown_before_files_carry_it() -> None:
+ legacy = HealthFileMetricData(
+ file_path="a.py", score=5.0, max_ccn=1, max_nesting=1, nloc=10, has_test_file=False
+ )
+ assert headline_split([legacy]) == (None, None)
+ assert headline_split([legacy, _row("b.py", 8.0, 1.5, 0.5)]) == (None, None)
+
+
def test_a_floored_file_still_shows_its_depth() -> None:
"""Two files pinned at 1.0 are not equally deep, and the score cannot say so."""
shallow = unclamped_score(6.0, 4.0)