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): count files and findings the same way on every surface (#3532)
Raghav Chamadiyaa2e08a6bbf60
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.pyindex 94c032338..1e3ff713d 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py@@ -37,6 +37,7 @@ from repowise.core.analysis.health.models import split_by_originfrom repowise.core.analysis.health.rows import detail_map, split_unscoredfrom repowise.core.analysis.health.scope import DEFAULT_SCOPE, SCOPES, parse_scopefrom repowise.core.analysis.health.scoring import compute_kpis+from repowise.core.persistence.crud.analysis.health import open_finding_countfrom .codegen import _generate_refactoring_codefrom .persist import (@@ -469,7 +470,8 @@ def health_command(console.print(table)if findings:- console.print(f"\n[bold]{len(findings)}[/bold] marker findings:")+ # The total get_overview prints; advisory rows are listed, not counted.+ console.print(f"\n[bold]{open_finding_count(findings)}[/bold] open findings:")f_table = Table()f_table.add_column("Severity", style="magenta")f_table.add_column("Marker", style="cyan")diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.pyindex e689a3eee..05503e269 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py@@ -4,7 +4,7 @@from __future__ import annotationsimport json-from collections.abc import Sequence+from collections.abc import Iterable, Sequencefrom datetime import datetimefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, NamedTuple@@ -415,7 +415,26 @@ async def backfill_module_attribution(return changed-async def _health_exclude_spec(session: AsyncSession, repository_id: str) -> Any:+def open_finding_count(findings: Iterable[Any]) -> int:+ """The open findings total every health headline prints.++ Advisory findings carry a zero health impact, so counting them would grow+ the headline without anything having got worse.+ """+ return sum(1 for f in findings if getattr(f, "dimension", None) != ADVISORY_DIMENSION)+++async def health_exclude_spec(+ session: AsyncSession, repository_id: str, repo_path: Path | str | None = None+) -> Any:+ """The exclude patterns every health surface narrows its files by.++ The repository's settings and ``exclude_patterns`` only. Not the gitignore+ stack: ingestion keeps a file git tracks even when an ignore rule matches+ it, so a stored row under such a rule is a real file of the repository.+ ``repo_path`` is where to read the config when the caller serves a+ checkout other than the stored ``local_path``.+ """repo = await session.get(Repository, repository_id)if repo is None:return None@@ -441,7 +460,7 @@ async def _health_exclude_spec(session: AsyncSession, repository_id: str) -> Anytry:from repowise.core.repo_config import load_repo_config- cfg = load_repo_config(Path(repo.local_path))+ cfg = load_repo_config(Path(repo_path or repo.local_path))if isinstance(cfg, dict):_add(cfg.get("exclude_patterns"))except Exception:@@ -544,7 +563,7 @@ async def get_health_findings(result = await session.execute(q)kept = _filter_excluded_paths(list(result.scalars().all()),- await _health_exclude_spec(session, repository_id),+ await health_exclude_spec(session, repository_id),)# A filter that drops some of a function's findings would misread its# shape, so the tier then reads every open finding on the kept files.@@ -638,7 +657,7 @@ async def get_health_metrics(result = await session.execute(q)rows = _filter_excluded_paths(list(result.scalars().all()),- await _health_exclude_spec(session, repository_id),+ await health_exclude_spec(session, repository_id),)if len(rows) < 2:# Nothing to order. Skips the aggregate for the single-file lookups@@ -684,7 +703,7 @@ async def get_average_health(session: AsyncSession, repository_id: str) -> float)).all()),- await _health_exclude_spec(session, repository_id),+ await health_exclude_spec(session, repository_id),)# Files with no score (no health dialect for their language) are skipped,# so a repository of nothing else reads unmeasured, never 10.0.@@ -736,7 +755,7 @@ async def _open_finding_totals_rows(session: AsyncSession, repository_id: str) -.order_by(HealthFinding.health_impact.desc(), HealthFinding.id))return _filter_excluded_paths(- plain_rows(rows), await _health_exclude_spec(session, repository_id)+ plain_rows(rows), await health_exclude_spec(session, repository_id))@@ -852,9 +871,7 @@ async def get_health_summary("worst_performer_score": round(worst.score, 2),"worst_test_path": worst_test.file_path if worst_test is not None else None,"worst_test_score": round(worst_test.score, 2) if worst_test is not None else None,- # Advisory findings carry a zero health impact, so counting them- # here would grow the headline without anything having got worse.- "open_findings": len(findings) - by_dim.get(ADVISORY_DIMENSION, 0),+ "open_findings": open_finding_count(findings),"maintainability_average": _rounded(maintainability_average),"performance_average": _rounded(performance_average),# The headline's two halves, in deduction points. Both come off columnsdiff --git a/packages/server/src/repowise/server/mcp_server/tool_health/population.py b/packages/server/src/repowise/server/mcp_server/tool_health/population.pyindex 02293fe1d..cae1c5da7 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/population.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/population.py@@ -12,9 +12,10 @@ from repowise.core.analysis.health.counts import project as project_countsfrom repowise.core.analysis.health.models import split_by_originfrom repowise.core.analysis.health.rows import scored_rowsfrom repowise.core.analysis.health.scope import parse_scope+from repowise.core.persistence.crud.analysis.health import health_exclude_specfrom repowise.core.persistence.crud.analysis.plain_rows import plain_rowsfrom repowise.core.persistence.models import HealthFileMetric-from repowise.server.mcp_server._helpers import _get_exclude_spec, filter_rows_by_attr+from repowise.server.mcp_server._helpers import filter_rows_by_attrfrom repowise.server.mcp_server.tool_health.request import HealthRequestfrom repowise.server.mcp_server.tool_health.targets import _expand_module_targets@@ -73,7 +74,10 @@ async def load_population(all_metrics_q = select(*HealthFileMetric.__table__.columns).where(HealthFileMetric.repository_id == repository.id)- exclude_spec = _get_exclude_spec(repo_path)+ # The rule the CLI, get_overview and status count files by. The MCP-wide+ # spec adds the gitignore stack, which hid a tracked file its pattern+ # matched and left get_health one file short of every other surface.+ exclude_spec = await health_exclude_spec(session, repository.id, repo_path)indexed_rows = plain_rows(await session.execute(all_metrics_q))all_metrics = filter_rows_by_attr(indexed_rows, "file_path", exclude_spec)# Lets an unresolved target report "excluded" rather than "no_such_path".diff --git a/tests/unit/server/mcp/test_mcp_exclude_filter.py b/tests/unit/server/mcp/test_mcp_exclude_filter.pyindex 059d05771..9844a215b 100644--- a/tests/unit/server/mcp/test_mcp_exclude_filter.py+++ b/tests/unit/server/mcp/test_mcp_exclude_filter.py@@ -147,6 +147,31 @@ async def test_get_health_excludes_configured_paths(setup_mcp, health_data, tmp_assert "src/auth/service.py" in paths+async def test_get_health_counts_a_file_an_ignore_rule_matches(+ setup_mcp, health_data, tmp_path, monkeypatch+):+ """Ingestion keeps a tracked file an ignore rule matches, and so do the CLI,+ get_overview and status. get_health dropped it and reported one file fewer."""+ import repowise.server.mcp_server as mcp_mod+ from repowise.server.mcp_server import get_health++ (tmp_path / ".gitignore").write_text("src/db/\n", encoding="utf-8")+ monkeypatch.setattr(mcp_mod._state, "_repo_path", str(tmp_path))++ result = await get_health(only=["worst_files"])+ assert "src/db/models.py" in {m["file_path"] for m in result.get("worst_files", [])}+++def test_open_finding_count_leaves_advisory_out() -> None:+ from types import SimpleNamespace++ from repowise.core.persistence.crud.analysis.health import open_finding_count++ rows = [SimpleNamespace(dimension=d) for d in ("defect", "advisory", None, "performance")]+ assert open_finding_count(rows) == 3++# ---------------------------------------------------------------------------# Targeted traversal-leak tests (edges / paths / co-change), not just helpers# ---------------------------------------------------------------------------