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): surface counted bug-fix history on get_risk and get_change_risk (#946)

Raghav Chamadiya87e65d23d7e6
diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.md
index 3e484d8ad..ae620892a 100644
--- a/docs/MCP_TOOLS.md
+++ b/docs/MCP_TOOLS.md
@@ -367,6 +367,23 @@ execute the change's changed *lines* (line-precise, so a narrower set than
suite"), never as untested. Build the map with `coverage run --contexts=test`
followed by `repowise coverage add`.
+When the changed files carry counted bug fixes, the response also holds
+`prior_fixes`: per file, how many past bug-fix commits touched it
+(`fix_count`), how many of the change's lines fall inside the ranges one of
+those fixes replaced (`overlapping_lines`), and how long ago the most recent
+was (`last_fix_days_ago`). `total_fixes` counts distinct commits, not rows,
+and `files` is capped at ten with `truncated` reporting overflow.
+
+`overlapping_lines` is labelled `approximate` in the payload, and that label is
+load-bearing: a past fix's ranges are numbered against its own parent commit,
+so anything that moved lines in between shifts them. Read it as "this
+neighbourhood has been patched before", not "this exact line". The per-file
+`fix_count` beside it carries no such caveat. The whole block is aggregate and
+never names the commit that introduced a bug: file-level SZZ measured 74.5%
+precision on this repo's frozen judgments, which is enough to count fixes and
+not enough to accuse one commit of causing them. The block is absent entirely
+on an index with no fix history.
+
**When to use:** Before merging a commit or PR range, especially when you need
to assess the diff itself rather than the risk of an already-indexed file.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
index da8bc2af4..4103f86e7 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
@@ -3,11 +3,15 @@
from __future__ import annotations
import asyncio
+import json
import subprocess
import time
+from datetime import UTC, datetime
from typing import Any
import pathspec
+from sqlalchemy import select
+from sqlalchemy.exc import SQLAlchemyError
from repowise.core.analysis.change_risk import (
change_risk_payload,
@@ -27,6 +31,10 @@ from repowise.server.mcp_server._meta import build_meta as _build_meta
#: ``truncated`` report the overflow rather than silently dropping it.
_IMPACTED_TESTS_LIMIT = 10
+#: Cap on the per-file prior-fix list, matching ``_IMPACTED_TESTS_LIMIT`` so both
+#: per-file blocks in this response stay the same size.
+_PRIOR_FIXES_LIMIT = 10
+
@mcp.tool()
async def get_change_risk(
@@ -55,6 +63,9 @@ async def get_change_risk(
lines no test covers. Its ``status`` is ``no_map`` (unknown, run the full
suite), never "untested", when no map is ingested.
+ ``prior_fixes`` appears only when the changed files carry counted bug fixes:
+ per-file counts, never a commit name.
+
Args:
revspec: Commit or ``base..head`` range to score. Defaults to ``HEAD``.
repo: Repository alias in workspace mode; omit for the default repository.
@@ -88,16 +99,25 @@ async def get_change_risk(
f"No counted file changes in {revspec!r} "
"(check the revspec, extensions, or exclusion filters)."
)
- # Line-precise impacted tests over the SAME file universe the score counted
- # (its extensions + riskignore + request excludes), so the two never
- # disagree about which files the change touches.
- payload["impacted_tests"] = await _impacted_tests_block(
- ctx,
- str(ctx.path),
- revspec,
- normalize_extensions(tuple(extensions or ())),
- result.riskignore_excludes + result.request_excludes,
- )
+ # Changed lines over the SAME file universe the score counted (its
+ # extensions + riskignore + request excludes), so nothing downstream
+ # disagrees with the score about which files the change touches. Read once
+ # and shared: both blocks below need it and git is the expensive part.
+ # Skipped entirely without an index, because neither block can say anything
+ # then and the git call is the expensive half of this response.
+ changed: dict[str, set[int]] = {}
+ changed_error: tuple[str, str] | None = None
+ if getattr(ctx, "session_factory", None) is not None:
+ changed, changed_error = await _changed_in_scope(
+ str(ctx.path),
+ revspec,
+ normalize_extensions(tuple(extensions or ())),
+ result.riskignore_excludes + result.request_excludes,
+ )
+ payload["impacted_tests"] = await _impacted_tests_block(ctx, changed, changed_error)
+ prior_fixes = await _prior_fixes_block(ctx, changed)
+ if prior_fixes is not None:
+ payload["prior_fixes"] = prior_fixes
# source: live_git marks that this response is computed from the working
# checkout's git, not the index, so index freshness does not apply to it.
payload["_meta"] = _build_meta(
@@ -187,12 +207,144 @@ def _serialize_missing(report: Any) -> dict[str, Any]:
}
-async def _impacted_tests_block(
- ctx: Any,
+async def _changed_in_scope(
repo_path: str,
revspec: str,
extensions: tuple[str, ...],
exclude_patterns: tuple[str, ...],
+) -> tuple[dict[str, set[int]], tuple[str, str] | None]:
+ """The change's changed lines, restricted to the score's counted universe.
+
+ Returns ``(changed, error)`` where *error* is a ``(status, summary)`` pair
+ for the degraded paths, so the callers below can report the same reason
+ without each re-reading git. Shared because ``changed_lines`` shells out and
+ two blocks want the same answer.
+ """
+ from repowise.core.analysis.changed_lines import changed_lines
+
+ try:
+ changed, _label = await asyncio.to_thread(
+ changed_lines, repo_path, _normalize_revspec(revspec)
+ )
+ except ValueError as exc:
+ return {}, ("unknown", f"Could not read changed lines: {exc}")
+ except (subprocess.SubprocessError, OSError):
+ return {}, ("unknown", "Could not read changed lines from git.")
+
+ changed = _filter_changed(changed, extensions, exclude_patterns)
+ if not changed:
+ return {}, ("no_source_line_changes", "No changed source lines to map to tests.")
+ return changed, None
+
+
+async def _prior_fixes_block(ctx: Any, changed: dict[str, set[int]]) -> dict[str, Any] | None:
+ """Past bug fixes that landed on the lines this change touches, or ``None``.
+
+ Aggregate only. No inducing commit is named: file-level SZZ measured 74.5%
+ precision against the frozen judgments, enough to count fixes and not enough
+ to accuse the commit that caused one.
+
+ ``overlapping_lines`` is the honest weak signal and is labelled as such. A
+ fix's stored ranges are line numbers on ITS parent commit while the change's
+ are line numbers now, so any commit in between shifts them; the count says
+ "this neighbourhood has been patched before", never "this exact line". The
+ per-file fix count beside it carries no such caveat.
+
+ Silent (``None``) when the index has no fix events for these files at all,
+ so a repo without the feature grows no noise block.
+ """
+ from repowise.core.persistence.database import get_session
+ from repowise.core.persistence.models import FixEvent
+
+ session_factory = getattr(ctx, "session_factory", None)
+ if session_factory is None or not changed:
+ return None
+
+ try:
+ async with get_session(session_factory) as session:
+ repo_id = (await _get_repo(session)).id
+ res = await session.execute(
+ select(FixEvent).where(
+ FixEvent.repository_id == repo_id,
+ FixEvent.file_path.in_(list(changed)),
+ FixEvent.shape_kind == "code_fix",
+ )
+ )
+ events = list(res.scalars().all())
+ except LookupError:
+ return None
+ except SQLAlchemyError:
+ # A pre-fix-events index has no table to read; that is silence, not an
+ # error the caller should have to handle.
+ return None
+
+ if not events:
+ return None
+
+ per_file: dict[str, dict[str, Any]] = {}
+ for event in events:
+ entry = per_file.setdefault(
+ event.file_path, {"file_path": event.file_path, "fix_count": 0, "overlapping_lines": 0}
+ )
+ entry["fix_count"] += 1
+ entry["overlapping_lines"] += _overlap_count(
+ changed[event.file_path], event.old_ranges_json
+ )
+ committed_at = event.committed_at
+ if isinstance(committed_at, datetime):
+ moment = committed_at if committed_at.tzinfo else committed_at.replace(tzinfo=UTC)
+ days = max(0, (datetime.now(UTC) - moment).days)
+ entry["last_fix_days_ago"] = min(entry.get("last_fix_days_ago", days), days)
+
+ files = sorted(
+ per_file.values(),
+ key=lambda f: (-f["overlapping_lines"], -f["fix_count"], f["file_path"]),
+ )
+ # Distinct commits, not rows. There is one row per (fix_sha, file_path), so
+ # summing per-file counts would report one commit that fixed three of the
+ # changed files as "3 past bug fixes". The per-file counts are per-file and
+ # stay as they are.
+ total = len({event.fix_sha for event in events})
+ return {
+ "files": files[:_PRIOR_FIXES_LIMIT],
+ "truncated": len(files) > _PRIOR_FIXES_LIMIT,
+ "total_fixes": total,
+ "files_with_fixes": len(files),
+ "line_overlap": "approximate",
+ "summary": (
+ f"{total} past bug-fix commit(s) touched {len(files)} of the changed file(s). "
+ "Line overlap is approximate (past ranges are numbered on their own "
+ "parent commit); the per-file counts are not."
+ ),
+ }
+
+
+def _overlap_count(changed_lines_now: set[int], old_ranges_json: str) -> int:
+ """How many of the change's lines fall inside a past fix's replaced ranges."""
+ try:
+ ranges = json.loads(old_ranges_json or "[]")
+ except (TypeError, ValueError):
+ return 0
+ if not isinstance(ranges, list):
+ return 0
+ hits = 0
+ for span in ranges:
+ if not isinstance(span, (list, tuple)) or len(span) != 2:
+ continue
+ try:
+ lo, hi = int(span[0]), int(span[1])
+ except (TypeError, ValueError):
+ # Same defensiveness as the json.loads above: a malformed range must
+ # not take down the whole get_change_risk call.
+ continue
+ hits += sum(1 for line in changed_lines_now if lo <= line <= hi)
+ return hits
+
+
+async def _impacted_tests_block(
+ ctx: Any,
+ changed: dict[str, set[int]],
+ changed_error: tuple[str, str] | None,
) -> dict[str, Any]:
"""Line-precise impacted tests + honest missing-test buckets for the change.
@@ -204,29 +356,17 @@ async def _impacted_tests_block(
honestly as "unknown, run the suite". Degrades to a ``status`` string rather
than raising, so it never fails the surrounding score.
"""
- from repowise.core.analysis.changed_lines import changed_lines
from repowise.core.analysis.missing_test_signal import detect_missing_tests
from repowise.core.persistence.crud import tests_covering
from repowise.core.persistence.database import get_session
session_factory = getattr(ctx, "session_factory", None)
if session_factory is None:
- return _empty_impacted("no_index", "No index; run `repowise init` to enable impacted tests.")
-
- try:
- changed, _label = await asyncio.to_thread(
- changed_lines, repo_path, _normalize_revspec(revspec)
- )
- except ValueError as exc:
- return _empty_impacted("unknown", f"Could not read changed lines: {exc}")
- except (subprocess.SubprocessError, OSError):
- return _empty_impacted("unknown", "Could not read changed lines from git.")
-
- changed = _filter_changed(changed, extensions, exclude_patterns)
- if not changed:
return _empty_impacted(
- "no_source_line_changes", "No changed source lines to map to tests."
+ "no_index", "No index; run `repowise init` to enable impacted tests."
)
+ if changed_error is not None:
+ return _empty_impacted(*changed_error)
try:
async with get_session(session_factory) as session:
@@ -256,11 +396,7 @@ async def _impacted_tests_block(
"missing_tests": _serialize_missing(report),
"summary": (
f"{total} test(s) cover the changed lines"
- + (
- f"; showing first {_IMPACTED_TESTS_LIMIT}"
- if total > _IMPACTED_TESTS_LIMIT
- else ""
- )
+ + (f"; showing first {_IMPACTED_TESTS_LIMIT}" if total > _IMPACTED_TESTS_LIMIT else "")
+ "."
),
}
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 f995febf3..25e636265 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
@@ -4,7 +4,7 @@ from __future__ import annotations
import contextlib
import json
-import re
+from datetime import UTC, datetime
from typing import Any
from sqlalchemy import select, text
@@ -19,10 +19,13 @@ from repowise.server.mcp_server._helpers import (
filter_dicts_by_key,
)
-_FIX_PATTERN = re.compile(
- r"\b(fix|bug|patch|hotfix|revert|regression|broken|crash|error)\b",
- re.IGNORECASE,
-)
+#: A file carrying this many counted bug fixes reads as bug-prone. Same trigger
+#: the PR bot uses for prior defects, so the two surfaces agree on "a lot".
+_BUG_PRONE_FIXES = 3
+
+#: How many attributed symbols the defect profile names. Enough to say "mostly
+#: these", short enough to keep the block inside the per-file token budget.
+_TOP_FIX_SYMBOLS = 3
def _derive_change_pattern(categories: dict[str, int]) -> str:
@@ -74,21 +77,26 @@ def _classify_risk_type(meta: Any, dep_count: int, team_size: int | None = None)
expected operating model, so ``bus-factor-risk`` is reserved for
hotspot-active files there (issue #361). ``None`` = unknown → keep
the historical behaviour.
+
+ ``bug-prone`` reads the counted fix history rather than the old keyword
+ scan over ``significant_commits``: that scan matched "fix" anywhere in a
+ subject, counted doc and test commits, and had no recency at all, while
+ ``prior_defect_count`` is the shape-filtered windowed count and
+ ``bug_magnet`` is its decayed form. An index that predates the fix-event
+ rollup reports 0/None here and simply falls through to the next rule,
+ the same way every other backfilled column behaves until the next update.
"""
from repowise.core.analysis.health.biomarkers.base import SMALL_TEAM_MAX_CONTRIBUTORS
- # Count bug-fix commits from significant_commits messages
- commits = json.loads(meta.significant_commits_json) if meta.significant_commits_json else []
- fix_count = sum(1 for c in commits if _FIX_PATTERN.search(c.get("message", "")))
-
churn_score = meta.churn_percentile or 0.0
bus_factor = getattr(meta, "bus_factor", 0) or 0
total_commits = meta.commit_count_total or 0
small_team = team_size is not None and team_size <= SMALL_TEAM_MAX_CONTRIBUTORS
- # Bug-prone takes priority if fix ratio is high
- if commits and fix_count / len(commits) >= 0.4:
+ # Bug-prone takes priority: real counted fixes, decayed or plain.
+ prior_defects = getattr(meta, "prior_defect_count", 0) or 0
+ if getattr(meta, "bug_magnet", False) or prior_defects >= _BUG_PRONE_FIXES:
return "bug-prone"
if churn_score >= 0.7:
return "churn-heavy"
@@ -254,6 +262,65 @@ def _build_co_changes(meta: Any, import_related: set[str], exclude_spec: Any) ->
)
+def _defect_profile(meta: Any) -> dict | None:
+ """What this file's counted bug fixes say about it, or ``None`` for silence.
+
+ Built from the fix-event rollup already loaded on the ``GitMetadata`` row,
+ so there is no second query. Silent when the file has no counted fixes, so a
+ clean file and a repo with no fix history both add nothing to the response
+ (the FileSignalsPanel convention).
+
+ Every field is aggregate. No inducing commit is named here or anywhere else:
+ file-level SZZ ran at 74.5% precision against the frozen judgments, which is
+ fine for counting and too thin to accuse a commit.
+
+ The approximation caveat on ``top_symbols`` lives in ``get_risk``'s docstring
+ rather than in each row. It is the same sentence every time, and a constant
+ string repeated once per target is exactly the per-file cost the lean-MCP
+ work went to some trouble to remove.
+ """
+ count = getattr(meta, "prior_defect_count", 0) or 0
+ if count <= 0:
+ 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
+
+ symbols = _top_fix_symbols(getattr(meta, "fix_symbol_counts_json", None))
+ if symbols:
+ profile["top_symbols"] = symbols
+ return profile
+
+
+def _top_fix_symbols(raw: str | None) -> dict[str, int]:
+ """Top few ``symbol -> fix count`` pairs, with the redundant path stripped.
+
+ Stored keys are ``path/to/file.py::Name`` and the caller already knows the
+ path, so the prefix is pure token cost in an MCP response. The stored map is
+ written in descending-count order, so "top few" is a slice.
+ """
+ if not raw:
+ return {}
+ try:
+ counts = json.loads(raw)
+ except (TypeError, ValueError):
+ return {}
+ if not isinstance(counts, dict):
+ return {}
+ return {str(k).rsplit("::", 1)[-1]: int(v) for k, v in list(counts.items())[:_TOP_FIX_SYMBOLS]}
+
+
def _load_commit_categories(meta: Any) -> dict:
"""Parse the persisted commit-category counts, tolerating malformed JSON."""
categories: dict = {}
@@ -362,6 +429,10 @@ async def _assess_one_target(
if merge_commit_count > 0:
result_data["merge_commit_count_90d"] = merge_commit_count
+ defect_profile = _defect_profile(meta)
+ if defect_profile is not None:
+ result_data["defect_profile"] = defect_profile
+
# C. Test gaps + security signals
result_data["test_gap"] = await _check_test_gap(session, repo_id, target)
result_data["security_signals"] = await _get_security_signals(session, repo_id, target)
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.py
index 996e1eeb5..c9dcbbde5 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
@@ -47,6 +47,13 @@ async def get_risk(
To score a live commit or ``base..head`` diff by revspec instead of file
paths, use ``get_change_risk``.
+ defect_profile appears only on files with counted bug fixes: how many landed
+ in the trailing 6 months, how long ago the last one was, a bug_magnet flag
+ for sustained recent fix pressure, and top_symbols. Those per-symbol counts
+ are approximate, because symbol spans are current-tree while each fix's line
+ ranges 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.
+
Args:
targets: file paths to assess.
repo: usually omitted.
diff --git a/tests/unit/server/mcp/test_defect_profile.py b/tests/unit/server/mcp/test_defect_profile.py
new file mode 100644
index 000000000..ed157636b
--- /dev/null
+++ b/tests/unit/server/mcp/test_defect_profile.py
@@ -0,0 +1,134 @@
+"""get_risk's defect_profile and the fix-history it replaces the keyword scan with.
+
+Two contracts here. The block is silent when a file has no counted fixes, so an
+index without the fix-event rollup grows no noise (the FileSignalsPanel
+convention every surface in this feature follows). And nothing in it names a
+commit: file-level SZZ measured 74.5% precision against the frozen judgments,
+which counts fixes honestly and accuses one dishonestly.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
+
+import pytest
+
+from repowise.server.mcp_server.tool_risk.assessment import (
+ _classify_risk_type,
+ _defect_profile,
+ _top_fix_symbols,
+)
+
+
+def _meta(**overrides) -> SimpleNamespace:
+ base = {
+ "prior_defect_count": 0,
+ "bug_magnet": False,
+ "last_fix_at": None,
+ "fix_symbol_counts_json": None,
+ "churn_percentile": 0.1,
+ "bus_factor": 3,
+ "commit_count_total": 10,
+ "is_hotspot": False,
+ }
+ base.update(overrides)
+ return SimpleNamespace(**base)
+
+
+def test_no_fix_history_is_silent():
+ """A clean file adds nothing to the response, rather than a block of zeros."""
+ assert _defect_profile(_meta()) is None
+
+
+def test_counted_fixes_render_with_recency_and_symbols():
+ profile = _defect_profile(
+ _meta(
+ prior_defect_count=5,
+ bug_magnet=True,
+ last_fix_at=datetime.now(UTC) - timedelta(days=14),
+ fix_symbol_counts_json=json.dumps(
+ {
+ "src/pipeline.py::run": 4,
+ "src/pipeline.py::load": 2,
+ "src/pipeline.py::save": 1,
+ "src/pipeline.py::drop": 1,
+ }
+ ),
+ )
+ )
+
+ assert profile is not None
+ assert profile["fix_count"] == 5
+ assert profile["window"] == "6 months"
+ assert profile["last_fix_days_ago"] == 14
+ assert profile["bug_magnet"] is True
+ # Capped, path stripped (the caller already knows it), hedged.
+ assert profile["top_symbols"] == {"run": 4, "load": 2, "save": 1}
+ # The approximation caveat is in the tool docstring, not repeated per row:
+ # a constant string once per target is pure per-file token cost.
+ assert "symbols_note" not in profile
+
+
+def test_bug_magnet_omitted_rather_than_reported_false():
+ """Absent means "not a magnet": a false flag is not worth the tokens."""
+ profile = _defect_profile(_meta(prior_defect_count=3))
+ assert profile is not None
+ assert "bug_magnet" not in profile
+
+
+def test_naive_timestamps_are_treated_as_utc():
+ """The column round-trips naive; comparing it to an aware now must not raise."""
+ profile = _defect_profile(
+ _meta(prior_defect_count=1, last_fix_at=datetime.now(UTC).replace(tzinfo=None))
+ )
+ assert profile is not None
+ assert profile["last_fix_days_ago"] == 0
+
+
+def test_top_fix_symbols_tolerates_junk():
+ assert _top_fix_symbols(None) == {}
+ assert _top_fix_symbols("not json") == {}
+ assert _top_fix_symbols("[1, 2]") == {}
+
+
+ ("meta", "expected"),
+ [
+ # The real counted history, decayed or plain, wins.
+ (_meta(bug_magnet=True), "bug-prone"),
+ (_meta(prior_defect_count=3), "bug-prone"),
+ # Under the trigger, the file falls through to the next rule rather
+ # than being called bug-prone on a keyword match.
+ (_meta(prior_defect_count=2, churn_percentile=0.9), "churn-heavy"),
+ # A pre-rollup index reports nothing here and classifies as before.
+ (_meta(churn_percentile=0.9), "churn-heavy"),
+ ],
+)
+def test_bug_prone_reads_counted_fixes_not_commit_subjects(meta, expected):
+ assert _classify_risk_type(meta, dep_count=0, team_size=10) == expected
+
+
+def test_fix_keywords_in_subjects_no_longer_classify():
+ """The retired scan called a file bug-prone off "fix" in a commit subject.
+
+ That matched doc and test commits, ignored recency entirely, and disagreed
+ with the count the rest of the surfaces show. A file whose every commit says
+ "fix" but which has no counted production fix is now simply stable.
+ """
+ meta = _meta(
+ significant_commits_json=json.dumps(
+ [{"message": "fix typo in README"}, {"message": "fix flaky test"}]
+ )
+ )
+ assert _classify_risk_type(meta, dep_count=0, team_size=10) == "stable"
+
+
+async def test_get_risk_omits_the_block_without_fix_data(setup_mcp):
+ """End to end: the fixture repo has no counted fixes, so no block appears."""
+ from repowise.server.mcp_server import get_risk
+
+ result = await get_risk(["src/auth/service.py"])
+ assert "defect_profile" not in result["targets"]["src/auth/service.py"]
diff --git a/tests/unit/server/mcp/test_prior_fixes.py b/tests/unit/server/mcp/test_prior_fixes.py
new file mode 100644
index 000000000..6d1e31dc7
--- /dev/null
+++ b/tests/unit/server/mcp/test_prior_fixes.py
@@ -0,0 +1,131 @@
+"""get_change_risk's prior_fixes block: past fixes on the lines a change touches.
+
+The block is aggregate by construction. It reports how many fixes each changed
+file has carried and how many changed lines land inside a past fix's replaced
+ranges, and it never names the commit that introduced a bug — file-level SZZ ran
+at 74.5% precision, enough to count and not enough to accuse.
+
+It is also silent unless there is something to say, so a repo indexed before the
+fix-event table existed sees no new block at all.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
+
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+from repowise.core.persistence.database import init_db
+from repowise.core.persistence.models import FixEvent, Repository, _new_uuid
+from repowise.server.mcp_server.tool_change_risk import _overlap_count, _prior_fixes_block
+
+
+def test_overlap_counts_only_lines_inside_a_replaced_range():
+ changed = {5, 6, 7, 40}
+ assert _overlap_count(changed, json.dumps([[4, 7]])) == 3
+ assert _overlap_count(changed, json.dumps([[4, 7], [39, 41]])) == 4
+ assert _overlap_count(changed, json.dumps([[100, 120]])) == 0
+
+
+def test_overlap_tolerates_missing_and_malformed_ranges():
+ """A pure insertion stores an empty range list; that is 0, not a crash."""
+ assert _overlap_count({1}, "[]") == 0
+ assert _overlap_count({1}, "") == 0
+ assert _overlap_count({1}, "not json") == 0
+ assert _overlap_count({1}, json.dumps([[1]])) == 0
+ assert _overlap_count({1}, json.dumps({"a": 1})) == 0
+
+
+async def test_block_is_silent_without_an_index():
+ ctx = SimpleNamespace(path="/repo")
+ assert await _prior_fixes_block(ctx, {"a.py": {1}}) is None
+
+
+async def test_block_is_silent_with_no_changed_lines():
+ ctx = SimpleNamespace(path="/repo", session_factory=object())
+ assert await _prior_fixes_block(ctx, {}) is None
+
+
+_REPO_ID = "repo1"
+
+
+async def _ctx_with_events(
+ tmp_path, events: list[tuple[str, list, int]], *, shape_kind: str = "code_fix"
+) -> SimpleNamespace:
+ """A context over a real wiki.db seeded with ``(path, old_ranges, age_days)``."""
+ tmp_path.mkdir(parents=True, exist_ok=True)
+ db_path = tmp_path / "wiki.db"
+ engine = create_async_engine(f"sqlite+aiosqlite:///{db_path.as_posix()}")
+ await init_db(engine)
+ factory = async_sessionmaker(engine, expire_on_commit=False)
+ async with factory() as session:
+ session.add(Repository(id=_REPO_ID, name="repo", local_path=str(tmp_path)))
+ for i, (path, old_ranges, age_days) in enumerate(events):
+ session.add(
+ FixEvent(
+ id=_new_uuid(),
+ repository_id=_REPO_ID,
+ fix_sha=f"{i:040x}",
+ file_path=path,
+ shape_kind=shape_kind,
+ old_ranges_json=json.dumps(old_ranges),
+ committed_at=datetime.now(UTC).replace(tzinfo=None) - timedelta(days=age_days),
+ )
+ )
+ await session.commit()
+ return SimpleNamespace(path=str(tmp_path), session_factory=factory)
+
+
+async def test_block_aggregates_per_file_and_ranks_by_overlap(tmp_path):
+ """The whole point of the block: which changed files have been patched here before."""
+ ctx = await _ctx_with_events(
+ tmp_path,
+ [
+ # app.py: two past fixes, one of which covers the lines being changed.
+ ("src/app.py", [[10, 20]], 30),
+ ("src/app.py", [[500, 510]], 5),
+ # util.py: one past fix, nowhere near the changed lines.
+ ("src/util.py", [[900, 910]], 100),
+ ],
+ )
+
+ block = await _prior_fixes_block(ctx, {"src/app.py": {12, 13, 14}, "src/util.py": {1, 2}})
+
+ assert block is not None
+ assert block["total_fixes"] == 3
+ assert block["files_with_fixes"] == 2
+ # Ranked by overlap first, so the file whose changed lines sit on old fix
+ # ground leads even though both files have fix history.
+ assert [f["file_path"] for f in block["files"]] == ["src/app.py", "src/util.py"]
+
+ app, util = block["files"]
+ assert app["fix_count"] == 2
+ assert app["overlapping_lines"] == 3
+ # The MOST RECENT fix wins the age, not the last row the query happened to
+ # return: "has this been a problem lately" is the question being answered.
+ assert app["last_fix_days_ago"] == 5
+ assert util["fix_count"] == 1
+ assert util["overlapping_lines"] == 0
+
+ # The overlap is hedged and the counts beside it are not, because only one
+ # of the two is affected by lines having moved since the fix.
+ assert block["line_overlap"] == "approximate"
+ assert "approximate" in block["summary"]
+
+
+async def test_block_ignores_files_the_change_does_not_touch(tmp_path):
+ ctx = await _ctx_with_events(tmp_path, [("src/other.py", [[1, 5]], 10)])
+ assert await _prior_fixes_block(ctx, {"src/app.py": {1}}) is None
+
+
+async def test_non_code_fixes_are_not_counted(tmp_path):
+ """A doc-only or test-only commit is not a bug fix in this file.
+
+ The shape filter runs at index time for `prior_defect_count`; this block
+ reads the raw events, so it has to apply the same rule or it would report a
+ higher number than every other surface shows for the same file.
+ """
+ ctx = await _ctx_with_events(tmp_path, [("src/app.py", [[1, 5]], 10)], shape_kind="doc_only")
+ assert await _prior_fixes_block(ctx, {"src/app.py": {1, 2, 3}}) is None