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 get_health cards, gap and count fields agree with the score (#3683)

Swati Ahuja24e3b3c1fd05
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 68791e222..e27cd2af0 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -337,6 +337,8 @@ One ranked queue across refactoring, performance and code-shape work, the same o
Findings, performance causes and refactoring plans carry the same count object when their list is named in `only`: `top_findings_counts`, `performance_opportunities_counts`, `refactoring_plans_counts`. The CLI and dashboard report the same numbers.
+`top_findings_counts` is the Fix first queue's judgement of the scoring findings (performance and zero-impact findings are not queue units), while `top_findings` ranks every open production finding by impact, so `top_findings_total` can exceed `in_scope` and its `shown` (rows listed) can exceed `eligible`.
+
Items are ordered by value first, then tier. History markers (churn, ownership, co-change, prior fixes) never create or lead an item; they ride on an item under `context`, and history-only files count under `counts.excluded.history_only`. `fix_first` always describes production code, whatever `scope` says; `limit` caps the items, never which leads.
### Dashboard and metric rows
@@ -350,11 +352,11 @@ Items are ordered by value first, then tier. History markers (churn, ownership,
| `worst_files`, `test_worst_files` | Lowest raw scores, production and test |
| `high_leverage_files` | Ranked by `weighted_deficit`, with `share_of_repo_gap_pct` |
| `top_findings` / `findings`, `test_findings` | Production and test findings; their totals sum to the whole open set |
-| metric row | `score` (defect dimension and headline), `maintainability_score`, `performance_score`, `weighted_deficit` = (8 - score) x NLOC, `is_test`, `has_test_file`, `primary_biomarker` |
+| metric row | `score` (defect dimension and headline), `maintainability_score`, `performance_score`, `weighted_deficit` = (8 - score) x NLOC, `is_test`, `has_test_file`, `primary_biomarker`, `total_deduction`, and `withheld_deduction` when part of it comes from a withheld finding type |
`weighted_deficit` and the gap fields share one unit, score points x NLOC; they compare only with each other. Non-code files score a mechanical 10.0 because no marker reads them; `average_health_code_only` shows the headline without them. `primary_biomarker` prefers a discrete finding over the continuous `coverage_gradient`. Each finding carries a `dimension`; `advisory` findings (`assertion_free_test`, `mock_saturated_test`) never deduct and appear only with `include=["advisory"]`.
-Provisional finding types appear only with `include=["unverified"]`, each marked `verification: "unverified"`. Targeted mode is never split into production and test.
+Provisional finding types appear only with `include=["unverified"]`, each marked `verification: "unverified"`. A withheld type never lists but still lowers the score it was counted in, so a file row reports it as `withheld_deduction` and `_meta.withheld` names the type, its count and why it is held back. Targeted mode is never split into production and test.
Health findings, refactoring plans and opportunities, and performance opportunities on Java, C#, C and C++ files are held back pending verification for those languages. They are still stored and a lookup by id still answers; `_meta.gated` counts them per layer and language, and `include=["unverified"]` shows them.
diff --git a/packages/core/src/repowise/core/ci/markdown.py b/packages/core/src/repowise/core/ci/markdown.py
index 484b2ea61..18b4f740d 100644
--- a/packages/core/src/repowise/core/ci/markdown.py
+++ b/packages/core/src/repowise/core/ci/markdown.py
@@ -24,7 +24,12 @@ def longest_backtick_run(text: str) -> int:
def code(text: str) -> str:
- """*text* as an inline code span that no backtick inside it can close early."""
+ """*text* as an inline code span that no backtick inside it can close early.
+
+ A snippet read from a CRLF file keeps its ``\\r``; prose drops it, so one
+ span reads the same on every checkout.
+ """
+ text = text.replace("\r\n", "\n")
fence = "`" * (longest_backtick_run(text) + 1)
pad = " " if text.startswith("`") or text.endswith("`") else ""
return f"{fence}{pad}{text}{pad}{fence}"
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/findings.py b/packages/server/src/repowise/server/mcp_server/tool_health/findings.py
index 2c8a37e45..7f1c3816c 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/findings.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/findings.py
@@ -244,6 +244,31 @@ async def _read_findings_by_id(session: Any, ids: list[str]) -> dict[str, Any]:
}
+async def read_withheld_rows(
+ session: Any, repository: Any, pop: Population, req: HealthRequest
+) -> list[Any]:
+ """Open findings of a type the registry withholds from this surface.
+
+ No list or total shows them, but the stored score counted them, so the
+ per-file leads report their deduction and ``_meta.withheld`` names them:
+ a score never drops for a reason the response hides.
+ """
+ if not req.withheld_types:
+ return []
+ query = select(
+ HealthFinding.file_path, HealthFinding.biomarker_type, HealthFinding.health_impact
+ ).where(
+ HealthFinding.repository_id == repository.id,
+ HealthFinding.status == "open",
+ # No language gate: a withheld type is withheld on every language, and
+ # ``gated_findings`` counts only shown types, so no row is named twice.
+ HealthFinding.biomarker_type.in_(req.withheld_types),
+ )
+ if pop.scoped:
+ query = query.where(HealthFinding.file_path.in_(pop.effective_targets))
+ return pop.in_counts_findings(pop.in_scope_rows(plain_rows(await session.execute(query))))
+
+
async def read_accuracy_rows(
session: Any, repository: Any, pop: Population, req: HealthRequest
) -> list[Any]:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
index b94d38de1..62cfed81e 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
@@ -52,6 +52,7 @@ from repowise.server.mcp_server.tool_health.findings import (
load_dashboard_findings,
load_targeted_findings,
read_accuracy_rows,
+ read_withheld_rows,
)
from repowise.server.mcp_server.tool_health.pillars import (
_performance_blocks,
@@ -111,6 +112,8 @@ class HealthData:
worst_files_hidden: dict[str, int] = field(default_factory=dict)
# What a language gate held back, ``{layer: {language: {count, ...}}}``.
gated: dict[str, dict] = field(default_factory=dict)
+ #: Open findings of a withheld type: never listed, but the score counted them.
+ withheld_rows: list[Any] = field(default_factory=list)
async def load_health_data(
@@ -179,8 +182,9 @@ async def load_health_data(
)
data.churn_points = await _read_churn_points(session, repository, pop, req)
data.snapshots = await _read_snapshots(session, repository, pop, req)
+ data.withheld_rows = await read_withheld_rows(session, repository, pop, req)
data.by_leverage, data.leads = _rank_leverage_and_leads(
- pop, metric_rows, findings, req, data.test_metric_rows
+ pop, metric_rows, findings, req, data.test_metric_rows, data.withheld_rows
)
data.fix_first, data.fix_first_full = await _read_fix_first(session, repository, pop, req)
if "top_findings" in req.only_set and not pop.nothing_resolved:
@@ -449,6 +453,7 @@ def _rank_leverage_and_leads(
findings: FindingSets,
req: HealthRequest,
test_metric_rows: list[HealthFileMetric],
+ withheld_rows: list[Any],
) -> tuple[list[HealthFileMetric], dict[str, dict[str, Any]]]:
"""Dominant-cause lead per file, and the leverage ranking it is printed beside.
@@ -456,7 +461,7 @@ def _rank_leverage_and_leads(
only the rows of files it prints: identical output at a fraction of the cost.
"""
if pop.scoped:
- return [], _leads_by_file(findings.lead_rows)
+ return [], _leads_by_file(findings.lead_rows, withheld_rows)
# Ranked by NLOC-weighted deficit, not raw score: a big mid-band file
# moves the average more than a tiny at-risk one.
by_leverage = sorted(
@@ -467,7 +472,10 @@ def _rank_leverage_and_leads(
printed = {m.file_path for m in metric_rows[: req.limit]}
printed |= {m.file_path for m in test_metric_rows[: req.limit]}
printed |= {m.file_path for m in by_leverage[: req.limit]}
- return by_leverage, _leads_by_file([r for r in findings.lead_rows if r.file_path in printed])
+ return by_leverage, _leads_by_file(
+ [r for r in findings.lead_rows if r.file_path in printed],
+ [r for r in withheld_rows if r.file_path in printed],
+ )
async def _read_fix_first(
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/request.py b/packages/server/src/repowise/server/mcp_server/tool_health/request.py
index 97b817bc9..51ba3f9d5 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/request.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/request.py
@@ -123,7 +123,8 @@ class HealthRequest:
# eligible for the impact cap rather than filtering an already-capped list.
self.dimension_filter = self.include_set & set(ALL_DIMENSIONS)
# Finding types the registry keeps off this surface, dropped at the read
- # so no list, lead or total counts one.
+ # so no list or total counts one; ``read_withheld_rows`` reads them back
+ # only for the deduction the score took from them.
self.include_unverified = "unverified" in self.include_set
self.withheld_types = excluded_types(include_provisional=self.include_unverified)
# Performance findings carry zero impact, so an impact-ranked list
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/serialize.py b/packages/server/src/repowise/server/mcp_server/tool_health/serialize.py
index b01980f21..dae04211f 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/serialize.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/serialize.py
@@ -189,4 +189,6 @@ def _serialize_metric(
"primary_biomarker": lead.get("primary_biomarker") if lead else None,
"primary_reason": lead.get("primary_reason") if lead else None,
"total_deduction": lead.get("total_deduction") if lead else None,
+ # Only when a type this surface withholds took points off the score.
+ **({"withheld_deduction": w} if lead and (w := lead.get("withheld_deduction")) else {}),
}
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 f7cc5741d..665e8dc29 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,20 +16,35 @@ from repowise.core.analysis.health.scoring import (
from repowise.core.persistence.models import HealthFileMetric
-def _leads_by_file(findings: list[Any]) -> dict[str, dict[str, Any]]:
+def _leads_by_file(
+ findings: list[Any], withheld: list[Any] | None = None
+) -> dict[str, dict[str, Any]]:
"""Reduce each file's findings to its dominant cause + pre-clamp magnitude.
``primary_*`` is the one reason to lead with; ``total_deduction`` (summed
``health_impact``) tells apart two files that both floor at 1.0. The
selection rule lives in ``analysis.health.models.primary_finding``.
+
+ *withheld* rows, of types the registry keeps off this surface, never lead.
+ The score counted them, so they add to ``total_deduction`` and show as
+ ``withheld_deduction``: the card always accounts for what lowered the score.
"""
by_file: dict[str, list[Any]] = {}
for f in findings:
by_file.setdefault(f.file_path, []).append(f)
+ hidden: dict[str, float] = {}
+ for f in withheld or ():
+ hidden[f.file_path] = hidden.get(f.file_path, 0.0) + float(f.health_impact or 0.0)
leads: dict[str, dict[str, Any]] = {}
- for path, fs in by_file.items():
+ for path in by_file.keys() | hidden.keys():
+ fs = by_file.get(path, [])
+ withheld_points = round(hidden.get(path, 0.0), 3)
+ total = round(sum(float(x.health_impact or 0.0) for x in fs) + withheld_points, 3)
+ extra = {"withheld_deduction": withheld_points} if withheld_points else {}
primary = primary_finding(fs)
if primary is None:
+ if withheld_points:
+ leads[path] = {"total_deduction": total, **extra}
continue
# No edit resolves a history marker, so ``actionable_*`` uses code shape
# alone and ``watch_*`` carries history as context.
@@ -43,7 +58,8 @@ def _leads_by_file(findings: list[Any]) -> dict[str, dict[str, Any]]:
"actionable_reason": actionable.reason if actionable else None,
"watch_biomarker": watch.biomarker_type if watch else None,
"watch_reason": watch.reason if watch else None,
- "total_deduction": round(sum(float(x.health_impact or 0.0) for x in fs), 3),
+ "total_deduction": total,
+ **extra,
}
return leads
@@ -87,6 +103,8 @@ def _gap_analysis(metrics: list[HealthFileMetric]) -> dict[str, Any]:
}
def _files_for(points: float) -> int:
+ if points <= 0:
+ return 0
acc = 0.0
for i, d in enumerate(below, 1):
acc += d
@@ -96,10 +114,11 @@ def _gap_analysis(metrics: list[HealthFileMetric]) -> dict[str, Any]:
# At or above target there is nothing to reach, but the gross gap still
# stands while any file is below target.
- reachable = max(net_gap, 0)
+ # Rounded first, so a gap reported as 0 never needs a file to close it.
+ reachable = round(max(net_gap, 0))
return {
"target_score": TARGET_SCORE,
- "weighted_gap_points": round(max(net_gap, 0)),
+ "weighted_gap_points": reachable,
"weighted_gross_gap_points": round(gross_gap),
"files_below_target": len(below),
"files_to_reach_target": _files_for(reachable),
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py b/packages/server/src/repowise/server/mcp_server/tool_health/tool.py
index 5817940b9..537680077 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/tool.py
@@ -9,9 +9,11 @@ accounting and projection passes (``paging`` / ``projection``).
from __future__ import annotations
import asyncio
+from collections import Counter
from time import perf_counter
from typing import Any
+from repowise.core.analysis.finding_registry import withheld_summary
from repowise.core.analysis.health.counts import DEFAULT_COUNTS
from repowise.core.analysis.health.refactoring.serving import (
DEFAULT_VIEW as _REFACTORING_VIEW_DEFAULT,
@@ -252,6 +254,7 @@ async def get_health(
else:
_attach_health_analysis_meta(result["_meta"], data.pop.all_metrics)
_attach_gated(result["_meta"], data)
+ _attach_withheld(result, data)
pager.report_omissions(result, omission_collector)
omission_collector.attach(result)
_attach_semantics(result, req)
@@ -267,6 +270,23 @@ def _attach_gated(meta: dict[str, Any], data: HealthData) -> None:
meta["gated"] = {**data.gated, "opt_in": {"include": ["unverified"]}}
+def _attach_withheld(result: dict[str, Any], data: HealthData) -> None:
+ """The withheld types behind the ``withheld_deduction`` of each emitted
+ file row, so none is unexplained. Absent when no emitted row carries one."""
+ paths = {
+ row["file_path"]
+ for rows in result.values()
+ if isinstance(rows, list)
+ for row in rows
+ if isinstance(row, dict) and "withheld_deduction" in row
+ }
+ counts = Counter(
+ r.biomarker_type for r in data.withheld_rows if r.health_impact and r.file_path in paths
+ )
+ if counts:
+ result["_meta"]["withheld"] = withheld_summary(counts, counts)
+
+
def _attach_semantics(result: dict[str, Any], req: HealthRequest) -> None:
"""The unit legend, on request: it is the same on every call."""
if "semantics" in req.include_set:
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index 9ddba2e86..b096c208c 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -189,6 +189,60 @@ async def test_get_health_dashboard_surfaces_leverage(setup_mcp, health_data):
assert gap["files_for_half_gap"] == 1
+def test_gap_analysis_needs_no_file_when_the_average_is_at_target():
+ """Above target on average, one file below it: nothing to reach, so no file
+ is needed, while the gross gap still names the below-target file."""
+ from types import SimpleNamespace
+
+ from repowise.server.mcp_server.tool_health.summary import _gap_analysis
+
+ gap = _gap_analysis(
+ [SimpleNamespace(score=7.0, nloc=10), SimpleNamespace(score=9.0, nloc=100)]
+ )
+ assert gap["weighted_gap_points"] == 0
+ assert gap["files_to_reach_target"] == 0
+ assert gap["files_for_half_gap"] == 0
+ assert gap["files_below_target"] == 1
+ assert gap["weighted_gross_gap_points"] == 10
+
+
+async def test_targeted_card_accounts_for_a_withheld_deduction(setup_mcp, health_data, session):
+ """A hidden finding type never lists, but the score counted it, so the card
+ reports its deduction and ``_meta.withheld`` names it."""
+ from repowise.server.mcp_server import get_health
+
+ session.add(
+ HealthFinding(
+ id="dry-models",
+ repository_id=health_data,
+ file_path="src/db/models.py",
+ biomarker_type="dry_violation",
+ severity="high",
+ details_json="{}",
+ health_impact=0.6,
+ reason="36% duplicated with src/db/other.py",
+ dimension="maintainability",
+ status="open",
+ )
+ )
+ await session.commit()
+
+ result = await get_health(targets=["src/db/models.py"])
+ card = result["metrics"][0]
+ assert card["total_deduction"] == 0.6
+ assert card["withheld_deduction"] == 0.6
+ assert card["primary_biomarker"] is None
+ assert all(f["biomarker_type"] != "dry_violation" for f in result["findings"])
+ assert result["_meta"]["withheld"]["dry_violation"]["count"] == 1
+ assert result["_meta"]["withheld"]["dry_violation"]["status"] == "hidden"
+
+ # A file with no withheld deduction carries neither field.
+ other = await get_health(targets=["src/auth/service.py"])
+ assert "withheld_deduction" not in other["metrics"][0]
+ assert "withheld" not in other["_meta"]
+
+
@pytest.mark.asyncio
async def test_get_health_refactoring_capped_and_leverage_ranked(setup_mcp, health_data):
"""refactoring_plans is bounded by limit and reports the honest total.
diff --git a/tests/unit/test_ci.py b/tests/unit/test_ci.py
index 5d905fa23..86d89077f 100644
--- a/tests/unit/test_ci.py
+++ b/tests/unit/test_ci.py
@@ -8,7 +8,7 @@ import pytest
from repowise.core.ci import github
from repowise.core.ci.base import BaseNotFoundError, default_revspec
-from repowise.core.ci.markdown import cell, details, more_line, plural
+from repowise.core.ci.markdown import cell, code, details, more_line, plural
def test_annotation_escapes_properties_and_message() -> None:
@@ -43,6 +43,11 @@ def test_markdown_pieces() -> None:
assert details("S", []) == []
+def test_code_span_reads_the_same_on_a_crlf_checkout() -> None:
+ # A plan anchor keeps the file's CRLF; the sentence quoting it must not.
+ assert code("if (\r\n x") == code("if (\n x") == "`if (\n x`"
+
+
def _git(cwd, *args: str) -> None:
subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)