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(mcp): rank get_risk's attention list and get_context's triage on fix history (#956)
Raghav Chamadiyafaa80420281d
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.pyindex f081ef363..53bd901c1 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/context.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/context.py@@ -56,6 +56,8 @@ async def get_context(Returns title, summary, signatures, hotspot bit, decision_record titles,and symbol_ids to pipe into get_symbol (cheaper than Read for bodies).+ fix_history appears only on files with counted bug fixes (count, age,+ bug_magnet); hotspot is churn. Either one is a cue to call get_risk.Batch targets in one call. File targets above ~80 lines default to askeleton (every signature + top-PageRank bodies, with a verified flag —a fraction of Read cost); ``mostly_full`` marks files where a directdiff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.pyindex 8675b5bfa..11ca97141 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py@@ -45,6 +45,7 @@ from repowise.server.mcp_server.tool_context.kg import (_find_layer_for_file,_find_tour_step_for_file,)+from repowise.server.mcp_server.tool_risk.assessment import fix_annotation# Skeleton-by-default threshold for file targets. Measured on this repo: a@@ -555,6 +556,12 @@ async def _resolve_one_target(# * ``hotspot``: lights the way to ``get_risk`` for files in the 95th+# churn percentile. Just the boolean — the full risk dossier stays# in ``get_risk`` so the triage card doesn't grow.+ # * ``fix_history``: the same pointer for the defect signal, and the+ # reason the card grew by one key. ``hotspot`` alone answers "is this+ # file busy", which is not the same question as "does this file break",+ # and get_risk already classifies targets bug-prone off these columns.+ # Count plus age plus the magnet flag, no symbols and no dossier;+ # omitted entirely on files with no counted fixes.# * ``decision_records``: titles only, no body. Lights the way to# ``get_why``. We deliberately don't inline the rationale here;# duplicating it across every ``get_context`` response bloats the@@ -565,14 +572,26 @@ async def _resolve_one_target(if target_type == "module" and page:triage_path = page.target_pathif triage_path:+ # Same single row, four columns instead of one: no extra round trip.triage_meta_res = await session.execute(- select(GitMetadata.is_hotspot).where(+ select(+ GitMetadata.is_hotspot,+ GitMetadata.prior_defect_count,+ GitMetadata.bug_magnet,+ GitMetadata.last_fix_at,+ ).where(GitMetadata.repository_id == repo_id,GitMetadata.file_path == triage_path,))- triage_meta = triage_meta_res.scalar_one_or_none()- result_data["hotspot"] = bool(triage_meta) if triage_meta is not None else False+ triage_meta = triage_meta_res.one_or_none()+ result_data["hotspot"] = bool(triage_meta.is_hotspot) if triage_meta is not None else False+ if triage_meta is not None:+ # Row exposes the selected columns as attributes, which is exactly+ # the shape fix_annotation reads off a full ORM row.+ fixes = fix_annotation(triage_meta)+ if fixes is not None:+ result_data["fix_history"] = fixes# Governing decisions — opt-in only (``include=["decisions"]``).# The default triage card omits them: the rich formdiff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.pyindex 25e636265..ce6623508 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@@ -262,6 +262,49 @@ def _build_co_changes(meta: Any, import_related: set[str], exclude_spec: Any) ->)+def fix_annotation(meta: Any) -> dict | None:+ """Counted fixes, their age, and the magnet flag, or ``None`` for silence.++ The compact form every fix-history surface shares, so the recency contract+ is enforced once: the ``bug_magnet`` flag rides on the age and is never+ emitted alone. ``bug_magnet`` is a claim about RECENT fix pressure, so with+ no timestamp to anchor it the same word would describe a file fixed four+ times last month and one fixed four times two years ago.++ Read off the ``GitMetadata`` row the caller already loaded: no query.+ """+ count = getattr(meta, "prior_defect_count", 0) or 0+ if count <= 0:+ return None++ out: dict[str, Any] = {"fix_count": count}+ last_fix_at = getattr(meta, "last_fix_at", None)+ if isinstance(last_fix_at, datetime):+ # Rows are stored naive-UTC; compare on the same footing.+ moment = last_fix_at if last_fix_at.tzinfo else last_fix_at.replace(tzinfo=UTC)+ out["last_fix_days_ago"] = max(0, (datetime.now(UTC) - moment).days)+ if getattr(meta, "bug_magnet", False):+ out["bug_magnet"] = True+ return out+++def _fix_clause(profile: dict | None) -> str:+ """Lead clause for ``risk_summary``, or empty when there is no fix history.++ Trailing separator included so the caller concatenates without a dangling+ comma on files that have never been fixed. Never renders a count without an+ age: an unanchored count reads as a claim about the distant past.+ """+ if not profile or "last_fix_days_ago" not in profile:+ return ""+ n = profile["fix_count"]+ magnet = " (bug magnet)" if profile.get("bug_magnet") else ""+ return (+ f"{n} bug fix{'es' if n != 1 else ''} in 6mo, "+ f"last {profile['last_fix_days_ago']}d ago{magnet}, "+ )++def _defect_profile(meta: Any) -> dict | None:"""What this file's counted bug fixes say about it, or ``None`` for silence.@@ -279,23 +322,10 @@ def _defect_profile(meta: Any) -> dict | None:string repeated once per target is exactly the per-file cost the lean-MCPwork went to some trouble to remove."""- count = getattr(meta, "prior_defect_count", 0) or 0- if count <= 0:+ profile = fix_annotation(meta)+ if profile is None:return None-- profile: dict[str, Any] = {"fix_count": count, "window": "6 months"}-- last_fix_at = getattr(meta, "last_fix_at", None)- if isinstance(last_fix_at, datetime):- # Rows are stored naive-UTC; compare on the same footing.- moment = last_fix_at if last_fix_at.tzinfo else last_fix_at.replace(tzinfo=UTC)- profile["last_fix_days_ago"] = max(0, (datetime.now(UTC) - moment).days)- # The flag rides on the age, never alone. bug_magnet is a claim about- # RECENT fix pressure, so without a timestamp to anchor it the same- # word would describe a file fixed four times last month and one fixed- # four times two years ago.- if getattr(meta, "bug_magnet", False):- profile["bug_magnet"] = True+ profile["window"] = "6 months"symbols = _top_fix_symbols(getattr(meta, "fix_symbol_counts_json", None))if symbols:@@ -449,8 +479,14 @@ async def _assess_one_target(# later by cross-repo enrichment. We store dep_count now and let the# outer function rebuild the summary after enrichment if needed.result_data["_base_dep_count"] = dep_count+ # Lead with the bug-fix history when there is any. The summary used to open+ # 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.result_data["risk_summary"] = (- f"{target} — hotspot score {hotspot_score:.0%} ({trend}), "+ f"{target} — {_fix_clause(defect_profile)}"+ f"hotspot score {hotspot_score:.0%} ({trend}), "f"{dep_count} dependents, {risk_type}, {change_pattern}, "f"{len(co_changes)} co-change partners, owned {pct:.0%} by {owner}"f"{bus_note}{capped_note}"diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.pyindex c9dcbbde5..f45de2c04 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py@@ -24,7 +24,7 @@ from repowise.server.mcp_server._helpers import ()from repowise.server.mcp_server._meta import build_meta as _build_meta-from .assessment import _assess_one_target, _get_active_contributor_count+from .assessment import _assess_one_target, _get_active_contributor_count, fix_annotationfrom .directives import _build_pr_directive, _governance_directivefrom .enrichment import _enrich_cross_repo, _enrich_health, _finalize_dep_summaries@@ -35,11 +35,11 @@ async def get_risk(repo: str | None = None,changed_files: list[str] | None = None,) -> dict:- """What history says about touching these files — churn, owners, blast radius.+ """What history says about touching these files — bug fixes, churn, owners.Fuses git temporal signals (churn percentile, trend, bus factor) withgraph topology (dependents, co-changes, impact surface) and security- findings. Consult before editing 95th+ churn-percentile files. Pass+ findings. Consult before editing a file that is bug-fixed or busy. Passchanged_files for PR mode: the response leads with a directive block(will_break, missing_cochanges, missing_tests, tests_to_run) — read itfirst. tests_to_run is coverage-backed: the tests the per-test map proves@@ -53,6 +53,7 @@ async def get_risk(are approximate, because symbol spans are current-tree while each fix's lineranges are numbered on its own parent commit, so read them as "mostly here"rather than exact. Nothing here names the commit that introduced a bug.+ global_hotspots ranks the same way: fix history first, churn as fallback.Args:targets: file paths to assess.@@ -115,27 +116,48 @@ async def get_risk(])- # Global hotspots (excluding requested targets)+ # Elsewhere-in-the-repo attention list (excluding requested targets).+ # Ranked on bug-fix history first, churn second. This list sits beside+ # per-target verdicts that already read "bug-prone" off counted fixes,+ # so ranking it purely on churn made the two halves of one response+ # disagree about what deserves attention. Admitting bug magnets matters+ # as much as the ordering: filtering on is_hotspot alone means a file+ # fixed four times last month that is not busy can never appear.+ # Churn stays the fallback, so a repo with no fix convention keeps+ # exactly the list it had. These are full ORM rows, so the fix columns+ # are already in memory and this adds no query.target_set = set(targets)res = await session.execute(select(GitMetadata).where(GitMetadata.repository_id == repo_id,- GitMetadata.is_hotspot == True, # noqa: E712+ (GitMetadata.is_hotspot == True) # noqa: E712+ | (GitMetadata.bug_magnet == True), # noqa: E712+ )+ .order_by(+ GitMetadata.bug_magnet.desc(),+ GitMetadata.fix_mass.desc(),+ GitMetadata.churn_percentile.desc(),)- .order_by(GitMetadata.churn_percentile.desc()).limit(len(targets) + 5))all_hotspots = filter_rows_by_attr(list(res.scalars().all()), "file_path", exclude_spec)- global_hotspots = [- {+ global_hotspots = []+ for h in all_hotspots:+ if h.file_path in target_set:+ continue+ entry = {"file_path": h.file_path,"hotspot_score": h.churn_percentile,"primary_owner": h.primary_owner_name,}- for h in all_hotspots- if h.file_path not in target_set- ][:5]+ # Silent on files with no counted fixes, so a repo without fix+ # history pays nothing for this.+ fixes = fix_annotation(h)+ if fixes is not None:+ entry.update(fixes)+ global_hotspots.append(entry)+ global_hotspots = global_hotspots[:5]# A. PR blast radius (only when caller passes changed_files)pr_blast_radius: dict | None = Nonediff --git a/tests/unit/server/mcp/test_defect_profile.py b/tests/unit/server/mcp/test_defect_profile.pyindex ed157636b..d300e2090 100644--- a/tests/unit/server/mcp/test_defect_profile.py+++ b/tests/unit/server/mcp/test_defect_profile.py@@ -18,7 +18,9 @@ import pytestfrom repowise.server.mcp_server.tool_risk.assessment import (_classify_risk_type,_defect_profile,+ _fix_clause,_top_fix_symbols,+ fix_annotation,)@@ -132,3 +134,64 @@ async def test_get_risk_omits_the_block_without_fix_data(setup_mcp):result = await get_risk(["src/auth/service.py"])assert "defect_profile" not in result["targets"]["src/auth/service.py"]+++# ---------------------------------------------------------------------------+# The shared fix annotation, and the risk_summary clause built on it+# ---------------------------------------------------------------------------+++def test_fix_annotation_is_silent_without_counted_fixes():+ assert fix_annotation(_meta()) is None+++def test_fix_annotation_withholds_the_magnet_flag_without_an_age():+ # bug_magnet is a claim about RECENT fix pressure. With no timestamp the+ # same word would describe a file fixed four times last month and one+ # fixed four times two years ago, so the flag drops rather than mislead.+ out = fix_annotation(_meta(prior_defect_count=9, bug_magnet=True, last_fix_at=None))+ assert out == {"fix_count": 9}+ assert "bug_magnet" not in out+++def test_fix_annotation_carries_count_age_and_flag():+ out = fix_annotation(+ _meta(+ prior_defect_count=5,+ bug_magnet=True,+ last_fix_at=datetime.now(UTC) - timedelta(days=14),+ )+ )+ assert out == {"fix_count": 5, "last_fix_days_ago": 14, "bug_magnet": True}+++def test_defect_profile_still_builds_on_the_shared_annotation():+ # The profile is the annotation plus a window and symbols, so the recency+ # contract is enforced in exactly one place.+ profile = _defect_profile(+ _meta(+ prior_defect_count=2,+ bug_magnet=True,+ last_fix_at=datetime.now(UTC) - timedelta(days=3),+ )+ )+ assert profile["fix_count"] == 2+ assert profile["last_fix_days_ago"] == 3+ assert profile["bug_magnet"] is True+ assert profile["window"] == "6 months"+++def test_risk_summary_clause_is_empty_without_fix_history():+ # Files that have never been fixed must not gain a dangling separator.+ assert _fix_clause(None) == ""+ assert _fix_clause({"fix_count": 4}) == "" # count with no age+++def test_risk_summary_clause_leads_with_fixes_and_closes_its_separator():+ clause = _fix_clause({"fix_count": 5, "last_fix_days_ago": 14, "bug_magnet": True})+ assert clause == "5 bug fixes in 6mo, last 14d ago (bug magnet), "+++def test_risk_summary_clause_singularizes_one_fix():+ clause = _fix_clause({"fix_count": 1, "last_fix_days_ago": 2})+ assert clause == "1 bug fix in 6mo, last 2d ago, "diff --git a/tests/unit/server/mcp/test_fix_history_coherence.py b/tests/unit/server/mcp/test_fix_history_coherence.pynew file mode 100644index 000000000..4bf147386--- /dev/null+++ b/tests/unit/server/mcp/test_fix_history_coherence.py@@ -0,0 +1,155 @@+"""get_risk and get_context rank and report on the same defect signal.++get_risk already classified a target ``bug-prone`` from counted fixes while the+attention list beside it ranked purely on churn, and get_context's triage card+carried the churn bit alone. Both now read the fix columns that were already on+the row, so the two halves of a response agree about what deserves attention.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta++import pytest+from sqlalchemy import select++from repowise.core.persistence.models import GitMetadata+++async def _add_bug_magnet(session, repo_id: str, path: str, *, fixes: int, days: int):+ """A file that is bug-fixed but NOT a churn hotspot.++ This is the population the old is_hotspot-only filter could never surface,+ which is the point of the test: no amount of re-sorting inside the churn set+ would reach it.++ Uses the fixture session rather than opening its own: the fixtures share one+ StaticPool connection and commit at teardown, so a second session that+ commits mid-test drops the seeded data out from under the tool call.+ """+ session.add(+ GitMetadata(+ id=f"gm-magnet-{path}",+ repository_id=repo_id,+ file_path=path,+ commit_count_total=6,+ commit_count_90d=1,+ commit_count_30d=0,+ churn_percentile=0.05,+ is_hotspot=False,+ bug_magnet=True,+ fix_mass=9.0,+ prior_defect_count=fixes,+ last_fix_at=datetime.now(UTC) - timedelta(days=days),+ primary_owner_name="Carol",+ )+ )+ await session.flush()+++async def test_global_hotspots_surfaces_a_bug_magnet_that_is_not_a_churn_hotspot(+ setup_mcp, session, repo_id+):+ from repowise.server.mcp_server import get_risk++ await _add_bug_magnet(session, repo_id, "src/quiet/breaks_a_lot.py", fixes=6, days=10)++ result = await get_risk(["src/auth/service.py"])+ listed = {h["file_path"]: h for h in result["global_hotspots"]}++ assert "src/quiet/breaks_a_lot.py" in listed+ entry = listed["src/quiet/breaks_a_lot.py"]+ assert entry["fix_count"] == 6+ assert entry["last_fix_days_ago"] == 10+ assert entry["bug_magnet"] is True+++async def test_global_hotspots_ranks_fix_history_ahead_of_churn(setup_mcp, session, repo_id):+ from repowise.server.mcp_server import get_risk++ await _add_bug_magnet(session, repo_id, "src/quiet/breaks_a_lot.py", fixes=6, days=10)++ # models.py is in the fixture with no fix history; target something else so+ # both candidates are eligible for the list.+ result = await get_risk(["src/auth/middleware.py"])+ paths = [h["file_path"] for h in result["global_hotspots"]]++ assert paths, "expected an attention list"+ assert paths[0] == "src/quiet/breaks_a_lot.py"+++async def test_global_hotspots_stays_silent_on_files_without_fix_history(setup_mcp):+ """A repo with no fix data pays nothing: no keys, not zeroed keys."""+ from repowise.server.mcp_server import get_risk++ result = await get_risk(["src/auth/middleware.py"])+ for entry in result["global_hotspots"]:+ assert "fix_count" not in entry+ assert "bug_magnet" not in entry+ assert "hotspot_score" in entry # churn ranking still intact+++async def test_risk_summary_leads_with_fix_history_when_present(setup_mcp, session, repo_id):+ from repowise.server.mcp_server import get_risk++ await _add_bug_magnet(session, repo_id, "src/quiet/breaks_a_lot.py", fixes=4, days=7)++ result = await get_risk(["src/quiet/breaks_a_lot.py"])+ summary = result["targets"]["src/quiet/breaks_a_lot.py"]["risk_summary"]++ # 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 ago (bug magnet)" in summary+ assert summary.index("bug fixes") < summary.index("hotspot score")+ assert "bug-prone" in summary+++async def test_risk_summary_unchanged_without_fix_history(setup_mcp):+ from repowise.server.mcp_server import get_risk++ result = await get_risk(["src/auth/service.py"])+ summary = result["targets"]["src/auth/service.py"]["risk_summary"]++ assert "bug fix" not in summary+ assert summary.startswith("src/auth/service.py — hotspot score")+++async def test_get_context_triage_reports_fix_history(setup_mcp, session, repo_id):+ from repowise.server.mcp_server import get_context++ # Update the file's existing row rather than inserting a second one: the+ # triage lookup expects at most one row per (repo, path).+ row = (+ await session.execute(+ select(GitMetadata).where(GitMetadata.file_path == "src/auth/service.py")+ )+ ).scalar_one()+ row.prior_defect_count = 5+ row.bug_magnet = True+ row.last_fix_at = datetime.now(UTC) - timedelta(days=3)+ await session.flush()++ result = await get_context(["src/auth/service.py"])+ t = result["targets"]["src/auth/service.py"]++ assert t["fix_history"]["fix_count"] == 5+ assert t["fix_history"]["last_fix_days_ago"] == 3+ assert t["fix_history"]["bug_magnet"] is True+++async def test_get_context_triage_omits_fix_history_when_there_is_none(setup_mcp):+ """The triage card must not grow a block of zeros on a clean file."""+ from repowise.server.mcp_server import get_context++ result = await get_context(["src/auth/service.py"])+ t = result["targets"]["src/auth/service.py"]++ assert "fix_history" not in t+ assert t["hotspot"] is True # churn bit still reported