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.

feat(mcp): get_health include=["what_if"] names the points each fix recovers (#4130)

Raghav Chamadiya427beff9e7ad
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index e74116ff2..cc3aff7cd 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -328,7 +328,7 @@ Code-health scores and findings from the stored analysis, across defect risk, ma
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
| `targets` | list[string] | none (dashboard) | File paths or `module:<name>`. Misses are named in `unresolved` |
-| `include` | list[string] | none | Blocks: `biomarkers`, `refactoring`, `trend`, `coverage`, `accuracy`, `signals`, `churn_complexity`, `doc_drift`, `semantics`, `unverified`, `recipe` (with `plan_id`). Dimension filters: `performance`, `defect`, `maintainability`, `advisory` |
+| `include` | list[string] | none | Blocks: `biomarkers`, `refactoring`, `trend`, `coverage`, `accuracy`, `signals`, `churn_complexity`, `doc_drift`, `semantics`, `unverified`, `recipe` (with `plan_id`), `what_if`. Dimension filters: `performance`, `defect`, `maintainability`, `advisory` |
| `only` | list[string] | none | Keep just these top-level keys; identity, totals and recovery fields always survive. An unknown key is named in `unknown_only_keys` with `unknown_only_keys_hint` |
| `limit` | int | `20` | Max rows in every ranked list, capped at 50; `0` for none. `fix_first` shows five unless `limit` is passed with `only=["fix_first"]`, which pages up to 25; `refactoring_plans` up to 25 |
| `cursor` | int | `0` | Offset into a ranked list (and into `fix_first` when named in `only`); the `recovery` block names the next call |
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 948f4c5e3..46b67a9ca 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -402,6 +402,7 @@ On test files, history markers (ownership, churn, change entropy, co-change and
| `churn_complexity` | One point per recently changed file: commits, max CCN, NLOC, score, churn percentile |
| `doc_drift` | `findings` naming the document to edit, its line, the `target` it wrongly claims, `reason`, `kind`, `confidence`, optional `suggestion`; plus `findings_total`, `documents`, `basis`. A finding is evidence to check, not a proven defect |
| `semantics` | `_meta.health_semantics`: the legend for deficit points and percentiles |
+| `what_if` | Up to 10 worst files (or the targets), each with `ceiling` (the score with no structure deduction left, history's cap shrinking with it: the most an edit can reach), `target_out_of_reach` when that is below 8.0, `fix_all_structure` gains and its top 3 `findings`; `top_fixes` ranks single fixes across them. Each fix has `points` (its impact, an upper bound when its category is at its cap) and `gain`: `file`, `average` (headline points) and `hotspot` (when the file is a hotspot). `structure_deduction` can include withheld finding types no listed fix accounts for |
| `performance`, `defect`, `maintainability`, `advisory` | Filter findings to one dimension; `performance` also adds the performance queue |
`only` aliases: `biomarkers` -> `findings`, `accuracy` -> `defect_accuracy`, `refactoring` -> `refactoring_plans`. Dimension names have no single key and land in `unknown_only_keys`, beside `unknown_only_keys_hint`; for `signals` in targeted mode, name `metrics`.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/blocks.py b/packages/server/src/repowise/server/mcp_server/tool_health/blocks.py
index 7d8313dfe..fb6c1b705 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/blocks.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/blocks.py
@@ -26,6 +26,7 @@ from repowise.server.mcp_server.tool_health.pillars import (
from repowise.server.mcp_server.tool_health.plans import _render_plans
from repowise.server.mcp_server.tool_health.request import HealthRequest
from repowise.server.mcp_server.tool_health.serialize import _serialize_finding
+from repowise.server.mcp_server.tool_health.what_if import what_if_block
def add_optional_blocks(
@@ -55,6 +56,8 @@ def add_optional_blocks(
# rows are selected: filtering here would filter a list already capped.
if "refactoring" in include and req.wants("suggestion_legend"):
result["suggestion_legend"] = _suggestion_legend(data)
+ if "what_if" in include and req.wants("what_if"):
+ result["what_if"] = what_if_block(data, req)
def _add_biomarkers(result: dict[str, Any], data: HealthData, pager: Pager) -> None:
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 9515d95ce..5437a3c5a 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
@@ -265,10 +265,9 @@ async def _read_test_paths(
async def _read_hotspot_paths(
session: Any, repository: Any, pop: Population, req: HealthRequest
) -> set[str]:
- """Hotspot paths for the canonical hotspot-health KPI.
-
- Skipped in targeted mode, which builds no ``kpis`` block."""
- if pop.scoped or not req.wants("kpis"):
+ """Hotspot paths for the hotspot-health KPI and the what-if block's hotspot gains."""
+ what_if = "what_if" in req.include_set and req.wants("what_if")
+ if not what_if and (pop.scoped or not req.wants("kpis")):
return set()
return await get_hotspot_file_paths(session, repository.id)
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 51ba3f9d5..5fa0f9be6 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
@@ -62,6 +62,8 @@ _KNOWN_INCLUDES = frozenset(
"semantics",
# With ``plan_id``: the plan as preconditions, steps and postconditions.
"recipe",
+ # Points each fix would recover, per worst file and for the repo.
+ "what_if",
}
)
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 8b90a6490..22989a7f7 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
@@ -164,14 +164,14 @@ async def get_health(
No ``targets``: a dashboard led by ``fix_first``, what to fix first;
targets rank files and findings.
- Never recomputes health: commit, then run ``repowise update``.
+ Never recomputes: commit, then run ``repowise update``.
Every block and accepted value: docs/agent/MCP_TOOLS.md.
Args:
targets: file paths or ``module:<name>``; misses land in ``unresolved``.
include: ``biomarkers``|``refactoring``|``trend``|``coverage``|
``accuracy``|``signals``|``churn_complexity``|``doc_drift``|
- ``semantics``|``recipe``, or a dimension incl. ``advisory``;
+ ``semantics``|``recipe``|``what_if``, or a dimension incl. ``advisory``;
``performance`` and ``refactoring`` add queues.
only: keys to keep; identity, totals, recovery survive.
``biomarkers``/``accuracy``/``refactoring`` alias their block key;
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/what_if.py b/packages/server/src/repowise/server/mcp_server/tool_health/what_if.py
new file mode 100644
index 000000000..5e9729bcd
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/what_if.py
@@ -0,0 +1,158 @@
+"""``include=["what_if"]``: what fixing a finding would recover, per file and for the repo.
+
+A file's score is ``clamp(10 - structure - history)``, where history is capped by
+``history_cap(structure)``: removing structure also lowers what history may
+deduct. The stored history is already capped, so ``min(history, history_cap(s))``
+is exactly the history left at a lower structure ``s``. With no structure left
+that gives the file's ceiling, the most an edit can reach. A finding's ``points``
+are its ``health_impact``, an upper bound when its category sits at its cap
+(the others scale back up). Headline and hotspot gains weight the file gain by
+the file's nloc share of each average.
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from dataclasses import dataclass
+from typing import Any
+
+from repowise.core.analysis.health.grading import TARGET_SCORE
+from repowise.core.analysis.health.models import split_by_origin
+from repowise.core.analysis.health.scoring import (
+ ADVISORY_DIMENSION,
+ SCORE_FLOOR,
+ SCORE_MAX,
+ history_cap,
+)
+from repowise.server.mcp_server.tool_health.loading import HealthData
+from repowise.server.mcp_server.tool_health.request import HealthRequest
+
+#: Files and repo-level fixes the block lists, whatever ``limit`` is.
+WHAT_IF_CAP = 10
+
+#: Findings listed per file.
+FINDINGS_PER_FILE = 3
+
+#: Dimensions whose findings never move the score.
+_NO_SCORE = frozenset({"performance", ADVISORY_DIMENSION})
+
+
+@dataclass(frozen=True)
+class _Weights:
+ """Each average's total weight, to turn a file gain into a headline gain."""
+
+ average: float
+ hotspot: float
+ hotspots: frozenset[str]
+
+ def gains(self, path: str, nloc: int, file_gain: float) -> dict[str, float]:
+ weight = max(nloc, 1)
+ out = {"file": round(file_gain, 2), "average": _share(file_gain, weight, self.average)}
+ if path in self.hotspots:
+ out["hotspot"] = _share(file_gain, weight, self.hotspot)
+ return out
+
+
+@dataclass(frozen=True)
+class _FileScore:
+ """One file's two halves, and its score at any lower structure."""
+
+ structure: float
+ history: float
+
+ def at(self, structure: float) -> float:
+ history = min(self.history, history_cap(structure))
+ return _clamp(SCORE_MAX - structure - history)
+
+ @property
+ def now(self) -> float:
+ return self.at(self.structure)
+
+
+def what_if_block(data: HealthData, req: HealthRequest) -> dict[str, Any]:
+ """The worst files' recoverable points and the repo's best single fixes."""
+ weights = _weights(data)
+ by_file = _structure_findings(data.findings.lead_rows)
+ worst = data.metric_rows[: min(req.limit, WHAT_IF_CAP)]
+ files = [_file_row(m, by_file.get(m.file_path, []), weights) for m in worst]
+ fixes = sorted(
+ (fix for row in files for fix in row.pop("_fixes")),
+ key=lambda f: (-f["gain"]["average"], -f["gain"]["file"], f["file_path"]),
+ )
+ return {
+ "target_score": TARGET_SCORE,
+ "files": files,
+ "top_fixes": fixes[: min(req.limit, WHAT_IF_CAP)],
+ }
+
+
+def _weights(data: HealthData) -> _Weights:
+ """Over ``pop.all_metrics``, the rows ``kpis`` averages, tests included."""
+ scored = [m for m in data.pop.all_metrics if m.score is not None]
+ hotspots = frozenset(data.hotspot_paths)
+ return _Weights(
+ average=sum(max(m.nloc, 1) for m in scored),
+ hotspot=sum(max(m.nloc, 1) for m in scored if m.file_path in hotspots),
+ hotspots=hotspots,
+ )
+
+
+def _structure_findings(rows: list[Any]) -> dict[str, list[Any]]:
+ """Code-shape findings that move the score, by file, largest first."""
+ out: dict[str, list[Any]] = defaultdict(list)
+ for f in split_by_origin(rows)[0]:
+ if (f.health_impact or 0.0) > 0 and getattr(f, "dimension", None) not in _NO_SCORE:
+ out[f.file_path].append(f)
+ for findings in out.values():
+ findings.sort(key=lambda f: -f.health_impact)
+ return out
+
+
+def _file_row(m: Any, findings: list[Any], weights: _Weights) -> dict[str, Any]:
+ # A row written before the split was stored: its findings are the structure half.
+ stored = getattr(m, "structure_deduction", None)
+ halves = _FileScore(
+ structure=stored if stored is not None else sum(f.health_impact for f in findings),
+ history=getattr(m, "history_deduction", None) or 0.0,
+ )
+ ceiling = halves.at(0.0)
+ fixes = [_fix(m, f, halves, weights) for f in findings]
+ row: dict[str, Any] = {
+ "file_path": m.file_path,
+ "score": round(m.score, 2),
+ "is_hotspot": m.file_path in weights.hotspots,
+ "structure_deduction": round(halves.structure, 2),
+ "history_deduction": round(halves.history, 2),
+ "ceiling": round(ceiling, 2),
+ "fix_all_structure": weights.gains(m.file_path, m.nloc, ceiling - halves.now),
+ "findings": fixes[:FINDINGS_PER_FILE],
+ "_fixes": fixes,
+ }
+ if ceiling < TARGET_SCORE:
+ # History alone holds the file below target: no edit reaches it.
+ row["target_out_of_reach"] = True
+ return row
+
+
+def _fix(m: Any, f: Any, halves: _FileScore, weights: _Weights) -> dict[str, Any]:
+ points = min(f.health_impact, halves.structure)
+ file_gain = halves.at(halves.structure - points) - halves.now
+ fix: dict[str, Any] = {
+ "file_path": m.file_path,
+ "biomarker_type": f.biomarker_type,
+ "points": round(points, 2),
+ "gain": weights.gains(m.file_path, m.nloc, file_gain),
+ }
+ if f.function_name:
+ fix["function_name"] = f.function_name
+ if f.line_start is not None:
+ fix["line_start"] = f.line_start
+ return fix
+
+
+def _clamp(score: float) -> float:
+ return max(SCORE_FLOOR, min(SCORE_MAX, score))
+
+
+def _share(file_gain: float, weight: int, total: float) -> float:
+ return round(file_gain * weight / total, 3) if total else 0.0
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index e72fce769..b9b7c9498 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -2888,3 +2888,62 @@ async def test_overview_states_both_counts_and_withholds_the_band(setup_mcp, hea
assert partial["unanalysed_file_count"] == 3
assert partial["analysed_share"] == 0.4
assert partial["band"] is None
+
+
+async def test_what_if_names_the_points_a_fix_recovers(setup_mcp, session, populated_db):
+ """Per finding, per file and per headline, with the ceiling history leaves."""
+ from repowise.core.persistence.crud import save_health_findings, save_health_metrics
+ from repowise.server.mcp_server import get_health
+
+ await save_health_metrics(
+ session,
+ populated_db,
+ [
+ {
+ "file_path": "src/auth/service.py",
+ "score": 4.5,
+ "nloc": 200,
+ "is_test": False,
+ "structure_deduction": 3.0,
+ "history_deduction": 2.5,
+ },
+ {"file_path": "src/db/models.py", "score": 9.0, "nloc": 50, "is_test": False},
+ # Off the worst-files list, but inside the headline average.
+ {"file_path": "tests/test_auth.py", "score": 9.0, "nloc": 250, "is_test": True},
+ ],
+ )
+ finding = {
+ "file_path": "src/auth/service.py",
+ "severity": "high",
+ "line_start": 10,
+ "line_end": 80,
+ "details": {},
+ "reason": "r",
+ }
+ await save_health_findings(
+ session,
+ populated_db,
+ [
+ {**finding, "biomarker_type": "complex_method", "function_name": "a", "health_impact": 2.0},
+ {**finding, "biomarker_type": "nested_complexity", "function_name": "b", "health_impact": 1.0},
+ ],
+ )
+ await session.commit()
+
+ plain = await get_health()
+ assert "what_if" not in plain
+ assert plain["kpis"]["file_count"] == 3
+ block = (await get_health(include=["what_if"], only=["what_if"]))["what_if"]
+ row = block["files"][0]
+ assert row["file_path"] == "src/auth/service.py"
+ assert row["is_hotspot"] is True
+ # With no structure left, history may deduct at most 1.0: a 9.0 ceiling.
+ assert row["ceiling"] == 9.0
+ assert "target_out_of_reach" not in row
+ top = block["top_fixes"][0]
+ assert (top["biomarker_type"], top["points"]) == ("complex_method", 2.0)
+ # 2.0 structure points also lower history's cap from 2.5 to 2.0: 4.5 -> 7.0,
+ # on 200 of the headline's 500 nloc; the only hotspot carries all of it.
+ assert top["gain"] == {"file": 2.5, "average": 1.0, "hotspot": 2.5}
+ assert row["fix_all_structure"]["file"] == 4.5