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(mcp): state get_risk's churn rank as a rank in risk_summary (#3560)

Pragalvaffdee1d90ebf
diff --git a/docs/reference/COMPUTED_GLOSSARY.md b/docs/reference/COMPUTED_GLOSSARY.md
index 1d7f74fda..d6e03329c 100644
--- a/docs/reference/COMPUTED_GLOSSARY.md
+++ b/docs/reference/COMPUTED_GLOSSARY.md
@@ -238,7 +238,7 @@ workspace overlays, MCP responses, and CLI output.
| Risk type | Human bucket for the kind of risk. | `tool_risk._classify_risk_type()` | `bug-prone`, `churn-heavy`, `bus-factor-risk`, `high-coupling`, `stable` |
| Change pattern | Human label from dominant commit category. | `tool_risk._derive_change_pattern()` | `feature-active`, `fix-heavy`, `dependency-churn`, `mixed-activity` |
| Impact surface | PageRank-ranked structural reverse-dependency reach within two hops. It preserves distance and does not claim runtime breakage. | `tool_risk._compute_impact_surface()` | `[{file_path: "src/api.py", distance: 2, claim: "structural_reach"}]` |
-| Risk summary | One-line synthesized risk sentence for MCP; its dependency count is direct-only. | `tool_risk._assess_one_target()` | `src/auth.py - hotspot score 88% (increasing), 6 direct dependents...` |
+| Risk summary | One-line synthesized risk sentence for MCP; its dependency count is direct-only. | `tool_risk._assess_one_target()` | `src/auth.py - churn hotspot, top 12% (increasing), 6 direct dependents...` |
| Top hotspots | Highest churn/hotspot files returned for context. | `get_risk()` | `[{file_path: "src/db.py", hotspot_score: 0.94}]` |
## Code Health And Defect-Score Benchmark Metrics
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
index 86c7e01ba..f8b71683f 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import asyncio
import contextlib
import json
+import math
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
@@ -349,6 +350,23 @@ def _fix_clause(profile: dict | None) -> str:
)
+def _churn_clause(churn_percentile: float, is_hotspot: bool, trend: str) -> str:
+ """Churn clause for ``risk_summary``, or empty when the file is not a hotspot.
+
+ ``churn_percentile`` is a rank (0 to 1), not a risk. Printed as a bare
+ percentage it read like "100% risk", and it was printed for files below the
+ hotspot cut too. So the clause states the rank as a rank ("top N%") and only
+ for files the stored ``is_hotspot`` flag marks; ``trend`` stays available as
+ its own field either way. Trailing separator included, as in ``_fix_clause``.
+ """
+ if not is_hotspot:
+ return ""
+ # Round before the ceiling: 1 - 0.86 is 0.14000000000000001 in floats, and
+ # that would otherwise print as top 15%.
+ top_pct = max(1, math.ceil(round((1.0 - churn_percentile) * 100, 6)))
+ return f"churn hotspot, top {top_pct}% ({trend}), "
+
+
def _defect_profile(meta: Any, now: datetime | None = None) -> dict | None:
"""What this file's counted bug fixes say about it, or ``None`` for silence.
@@ -745,10 +763,10 @@ async def _assess_one_target(
# on a churn percentile even where risk_type said "bug-prone", so the first
# thing an agent read disagreed with the classification beside it. Counted
# fixes are the better grounded defect signal, so they go first and churn
- # keeps its place as the next clause.
+ # keeps its place as the next clause, for files that are churn hotspots.
result_data["risk_summary"] = (
f"{target} — {_fix_clause(defect_profile)}"
- f"hotspot score {hotspot_score:.0%} ({trend}), "
+ f"{_churn_clause(hotspot_score, result_data['is_hotspot'], trend)}"
f"{dep_count} direct dependents, {risk_type}, {change_pattern}, "
f"{co_changes_total} co-change partners, {_owner_clause(owner, pct, line_pct)}"
f"{bus_note}{capped_note}"
diff --git a/tests/unit/cli/test_search_collapse.py b/tests/unit/cli/test_search_collapse.py
index 16c341ec2..d2e95e360 100644
--- a/tests/unit/cli/test_search_collapse.py
+++ b/tests/unit/cli/test_search_collapse.py
@@ -157,7 +157,7 @@ RISK_PAYLOAD = {
"commit_count_capped": False,
"episodes": 22,
"_base_dep_count": 52,
- "risk_summary": "persist.py — 22 bug fixes in 6mo, hotspot score 100% (increasing)",
+ "risk_summary": "persist.py — 22 bug fixes in 6mo, churn hotspot, top 1% (increasing)",
}
},
"global_hotspots": [
diff --git a/tests/unit/server/mcp/test_fix_history_coherence.py b/tests/unit/server/mcp/test_fix_history_coherence.py
index 336ca6965..5727a008c 100644
--- a/tests/unit/server/mcp/test_fix_history_coherence.py
+++ b/tests/unit/server/mcp/test_fix_history_coherence.py
@@ -116,8 +116,10 @@ async def test_risk_summary_leads_with_fix_history_when_present(setup_mcp, sessi
# The defect evidence comes before the churn number, and agrees with the
# risk_type printed further along the same line.
assert "4 bug fixes in 6mo, last 7d before the indexed commit (bug magnet)" in summary
- assert summary.index("bug fixes") < summary.index("hotspot score")
+ assert summary.index("bug fixes") < summary.index("direct dependents")
assert "bug-prone" in summary
+ # Not a churn hotspot (is_hotspot=False), so the summary makes no churn claim.
+ assert "hotspot" not in summary
@pytest.mark.asyncio
@@ -128,7 +130,43 @@ async def test_risk_summary_unchanged_without_fix_history(setup_mcp):
summary = result["targets"]["src/auth/service.py"]["risk_summary"]
assert "bug fix" not in summary
- assert summary.startswith("src/auth/service.py — hotspot score")
+ assert summary.startswith("src/auth/service.py — churn hotspot, top 8% (")
+
+
+async def test_risk_summary_drops_churn_clause_below_the_hotspot_cut(setup_mcp):
+ from repowise.server.mcp_server import get_risk
+
+ # models.py is in the fixture with churn_percentile=0.15 and is_hotspot=False.
+ result = await get_risk(["src/db/models.py"])
+ target = result["targets"]["src/db/models.py"]
+
+ assert target["is_hotspot"] is False
+ assert "hotspot" not in target["risk_summary"]
+ assert "15%" not in target["risk_summary"]
+ assert target["risk_summary"].startswith("src/db/models.py — 1 direct dependents")
+
+
+ ("percentile", "expected"),
+ [
+ (0.92, "churn hotspot, top 8% (stable), "),
+ (0.86, "churn hotspot, top 14% (stable), "), # 1 - 0.86 is not exactly 0.14
+ (0.9992, "churn hotspot, top 1% (stable), "), # rounded up, never "top 0%"
+ (1.0, "churn hotspot, top 1% (stable), "),
+ (0.75, "churn hotspot, top 25% (stable), "),
+ ],
+)
+def test_churn_clause_states_the_rank_as_top_n_percent(percentile, expected):
+ from repowise.server.mcp_server.tool_risk.assessment import _churn_clause
+
+ assert _churn_clause(percentile, True, "stable") == expected
+
+
+def test_churn_clause_is_empty_for_a_file_that_is_not_a_hotspot():
+ from repowise.server.mcp_server.tool_risk.assessment import _churn_clause
+
+ assert _churn_clause(0.9, False, "increasing") == ""
@pytest.mark.asyncio
diff --git a/tests/unit/server/mcp/test_risk.py b/tests/unit/server/mcp/test_risk.py
index 6eb023dd5..6236b4d51 100644
--- a/tests/unit/server/mcp/test_risk.py
+++ b/tests/unit/server/mcp/test_risk.py
@@ -26,7 +26,9 @@ async def test_get_risk_single_target(setup_mcp):
assert t["primary_owner"] == "Alice"
assert "owner_pct" not in t # detailed owner metrics require include=["owners"]
assert "risk_summary" in t
- assert "hotspot score" in t["risk_summary"]
+ # churn_percentile=0.92 and is_hotspot → named as a rank, not a bare percentage
+ assert "churn hotspot, top 8% (" in t["risk_summary"]
+ assert "hotspot score" not in t["risk_summary"]
# include=["owners"] opt-in adds owner_pct
owners_result = await get_risk(["src/auth/service.py"], include=["owners"])