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(cli): repowise health --format json keeps withheld finding types (#4111)
Raghav Chamadiyaff9100156eca
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.pyindex 1aa8760ef..33d5cfd60 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py@@ -26,7 +26,7 @@ from repowise.cli.helpers import (run_async,silence_logs_for_machine_output_until_close,)-from repowise.core.analysis.finding_registry import preview_lines+from repowise.core.analysis.finding_registry import excluded_types, is_served, preview_linesfrom repowise.core.analysis.health.counts import (COUNTS,DEFAULT_COUNTS,@@ -231,8 +231,12 @@ def health_command(returnreport, hotspots, languages = _load_report(repo_path, opts)- metrics, findings, unanalysed = _scope_report(report, hotspots, opts)+ metrics, scored, unanalysed = _scope_report(report, hotspots, opts)metrics_sorted = sorted(metrics, key=lambda m: m.score)+ # JSON explains the score with every finding it counted; the rest list+ # what MCP and the web UI list.+ excluded = excluded_types()+ findings = [f for f in scored if not _withheld(f, excluded)]if generate_code is not None:suggestions = _scoped_suggestions(report, opts)@@ -247,7 +251,7 @@ def health_command(elif badge_view:_render_badge(report.kpis.get("average_health"), report.kpis.get("analysed_share"))elif fmt == "json":- _render_json(repo_path, report, metrics_sorted, findings, opts)+ _render_json(repo_path, report, metrics_sorted, scored, opts)elif fmt == "md":_render_md(report, findings)else:@@ -256,6 +260,11 @@ def health_command()+def _withheld(finding: Any, excluded: frozenset[str]) -> bool:+ """A finding the registry or a language gate keeps off default surfaces."""+ return not is_served("health", finding.biomarker_type, finding.file_path, excluded)++@dataclass(frozen=True)class _Options:"""The options that pick a view and narrow the report."""@@ -421,6 +430,7 @@ def _scoped_suggestions(report: Any, opts: _Options) -> list[Any]:def _render_json(repo_path: Path, report: Any, metrics_sorted: list[Any], findings: list[Any], opts: _Options) -> None:+ excluded = excluded_types()click.echo(json.dumps({@@ -453,6 +463,7 @@ def _render_json("health_impact": f.health_impact,"details": detail_map(f),"reason": f.reason,+ **({"withheld": True} if _withheld(f, excluded) else {}),}for f in findings],@@ -496,7 +507,7 @@ def _render_table(_render_defect_accuracy_line(report)# Lead with the finding count, density and coverage, not the bounded /10# average. Metrics carry no language, so it comes with the report.- _render_performance_section(report, languages)+ _render_performance_section(report, findings, languages)_render_files_table(metrics_sorted)_render_findings_table(findings)diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py b/packages/cli/src/repowise/cli/commands/health_cmd/persist.pyindex e2c68db79..b9c76624b 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/persist.py@@ -131,8 +131,8 @@ def _load_stored_report(repo_path: object) -> tuple[Any, set[str], dict[str, strmetrics = await get_health_metrics(session, repo_id)if not metrics:return None- # KPIs count what the scores counted, file-held findings included.- findings = await get_health_findings(session, repo_id, file_holds=False)+ # Every row the scores counted, withheld types included.+ findings = await get_health_findings(session, repo_id, include_withheld=True)hotspots = await get_hotspot_file_paths(session, repo_id)languages = await get_file_language_map(session, repo_id)kpis = compute_kpis(metrics, hotspots, deductions=deduction_by_path(findings))diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/summary.py b/packages/cli/src/repowise/cli/commands/health_cmd/summary.pyindex bcb83454f..a264c5acd 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/summary.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/summary.py@@ -41,7 +41,9 @@ def _render_fix_first(loaded: tuple[Any, Any] | None) -> None:console.print(f" [dim]verify:[/dim] {escape(item.verify.command)}")-def _render_performance_section(report: Any, lang_by_path: dict[str, str]) -> None:+def _render_performance_section(+ report: Any, findings: list[Any], lang_by_path: dict[str, str]+) -> None:"""Honest performance headline: risk count + density + coverage + scope.Leads with the open-risk count and how much of the analyzed code a perf@@ -55,7 +57,7 @@ def _render_performance_section(report: Any, lang_by_path: dict[str, str]) -> Noif not coverage.analyzed_files:returnperf_findings = sum(- 1 for f in report.findings if getattr(f, "dimension", "defect") == "performance"+ 1 for f in findings if getattr(f, "dimension", "defect") == "performance")perf_avg = report.kpis.get("performance_average")diff --git a/tests/unit/cli/test_health_cmd_withheld.py b/tests/unit/cli/test_health_cmd_withheld.pynew file mode 100644index 000000000..2b7261a82--- /dev/null+++ b/tests/unit/cli/test_health_cmd_withheld.py@@ -0,0 +1,95 @@+"""``repowise health`` reads every stored finding the score counted, and lists+only what a default surface lists."""++from __future__ import annotations++import io+import json+from contextlib import asynccontextmanager+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++from click.testing import CliRunner+from rich.console import Console++from repowise.cli.commands.health_cmd import command as health_module+from repowise.cli.main import cli+from repowise.core.analysis.health.models import HealthFileMetricData+++def _finding(kind: str, impact: float) -> SimpleNamespace:+ return SimpleNamespace(+ biomarker_type=kind,+ severity="high",+ file_path="src/a.py",+ function_name="run",+ line_start=1,+ line_end=9,+ health_impact=impact,+ details_json=None,+ details={},+ reason=f"{kind} reason",+ dimension="defect",+ status="open",+ )+++def _run(monkeypatch, *args: str) -> tuple[str, str]:+ metric = HealthFileMetricData(+ file_path="src/a.py", score=7.0, max_ccn=12, max_nesting=2, nloc=40,+ has_test_file=False, defect_score=7.0,+ )+ stored = [_finding("complex_method", 2.0), _finding("dry_violation", 1.0)]++ @asynccontextmanager+ async def _session(_path):+ yield object(), "repo-1"++ async def _findings(_session, _repo_id, **kwargs):+ if kwargs.get("include_withheld"):+ return stored+ return [f for f in stored if f.biomarker_type != "dry_violation"]++ async def _empty(*_a, **_k):+ return {}++ async def _metrics(*_a, **_k):+ return [metric]++ monkeypatch.setattr("repowise.cli.helpers.repo_index_session", _session)+ monkeypatch.setattr("repowise.core.persistence.crud.get_health_findings", _findings)+ monkeypatch.setattr("repowise.core.persistence.crud.get_health_metrics", _metrics)+ monkeypatch.setattr("repowise.core.persistence.crud.get_hotspot_file_paths", _empty)+ monkeypatch.setattr("repowise.core.persistence.crud.get_file_language_map", _empty)+ 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_fix_first", return_value=None),+ patch.object(health_module, "_load_queue_counts", return_value=None),+ 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 result.stdout, console.file.getvalue()+++def test_json_keeps_withheld_findings_so_it_explains_its_score(monkeypatch) -> None:+ stdout, _ = _run(monkeypatch, "--format", "json")+ payload = json.loads(stdout[stdout.index("{"):])+ by_kind = {f["biomarker_type"]: f for f in payload["findings"]}+ assert set(by_kind) == {"complex_method", "dry_violation"}+ assert by_kind["dry_violation"]["withheld"] is True+ assert "withheld" not in by_kind["complex_method"]+++def test_table_lists_only_served_findings(monkeypatch) -> None:+ _, out = _run(monkeypatch)+ assert "complex_method" in out+ assert "dry_violation" not in out