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(change-risk): stop an unreadable fix record from reading as a clean one (#2274)
Raghav Chamadiyac586807c979f
diff --git a/packages/core/src/repowise/core/analysis/change_review/service.py b/packages/core/src/repowise/core/analysis/change_review/service.pyindex e003a3aea..207c7dde2 100644--- a/packages/core/src/repowise/core/analysis/change_review/service.py+++ b/packages/core/src/repowise/core/analysis/change_review/service.py@@ -73,6 +73,11 @@ class ChangeReviewEvidence:#: A pre-scored change. Omitted, the service scores the change itself when#: it has a checkout to score from.risk: ChangeRiskResult | None = None+ #: An already-computed comparison. Omitted, the service runs one. A caller+ #: that runs the comparison concurrently with its other work -- which every+ #: real surface does, because it is the expensive half -- hands the result+ #: in here rather than losing that concurrency to a synchronous lane.+ health: ChangeHealthDelta | None = Nonecontracts: ContractInputs | None = None#: The result of ``analyze_test_impact``, uncapped, in its own shape.tests: Mapping[str, Any] | None = None@@ -165,20 +170,23 @@ class ChangeReviewService:evidence: ChangeReviewEvidence,lanes: dict[str, LaneState],) -> ChangeHealthDelta | None:- if "health" in evidence.skip:+ if evidence.health is not None:+ delta = evidence.health+ elif "health" in evidence.skip:lanes["health"] = LaneState("unsupported", "the caller skipped this lane")return None- service = self.delta_service or ChangeHealthDeltaService(- self.source, repo_path=self.repo_path- )- delta = service.compare(- DeltaRequest(- repo_path=self.repo_path or "",- revspec=request.revspec,- extensions=request.extensions,- exclude_patterns=request.exclude_patterns,+ else:+ service = self.delta_service or ChangeHealthDeltaService(+ self.source, repo_path=self.repo_path+ )+ delta = service.compare(+ DeltaRequest(+ repo_path=self.repo_path or "",+ revspec=request.revspec,+ extensions=request.extensions,+ exclude_patterns=request.exclude_patterns,+ ))- )# The delta's own status already says how complete the comparison was;# restating it in a second vocabulary is how the two drift apart.lanes["health"] = LaneState(diff --git a/packages/core/src/repowise/core/analysis/prior_fix_impact.py b/packages/core/src/repowise/core/analysis/prior_fix_impact.pynew file mode 100644index 000000000..3868d9b33--- /dev/null+++ b/packages/core/src/repowise/core/analysis/prior_fix_impact.py@@ -0,0 +1,230 @@+"""What the bug-fix record says about the ground a change stands on.++Aggregate only. No inducing commit is named: file-level SZZ measured 74.5%+precision against the frozen judgments, which is enough to count fixes and not+enough to accuse the commit that caused one.++Line overlap is the honest weak signal. A fix's stored ranges are line numbers+on *its own* 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, which is why the two are reported separately.++Collection is not here. A caller reads fix events from wherever it holds them --+SQL today, an artifact or an API elsewhere -- and hands them over as+:class:`FixRecord`s. This module only summarizes, so the summary cannot differ+between two callers that read the same events.+"""++from __future__ import annotations++import json+from collections.abc import Iterable, Mapping, Sequence+from dataclasses import dataclass+from datetime import UTC, datetime++from .review_directive import EvidenceState++#: Share of a change's counted lines above which one file is said to carry it.+#: A semantic threshold, not a display choice: below it, naming a single file+#: would imply a concentration the numbers do not show.+CONCENTRATION_SHARE = 0.5++#: What the line-overlap count is worth. Stated once, so no surface has to+#: remember to caveat it.+LINE_OVERLAP_BASIS = "approximate"+++@dataclass(frozen=True, slots=True)+class FixRecord:+ """One past bug fix's effect on one file, as the summary needs it."""++ fix_sha: str+ file_path: str+ #: Inclusive ``(start, end)`` spans on the fix's own parent commit. Empty+ #: for a pure insertion, which replaced nothing.+ old_ranges: tuple[tuple[int, int], ...] = ()+ committed_at: datetime | None = None+++@dataclass(frozen=True, slots=True)+class PriorFixFile:+ """One changed file's bug-fix past, and how much of the change it holds."""++ file_path: str+ #: Rows for this file, which is one per fixing commit.+ fix_count: int+ #: Changed lines falling inside a past fix's replaced ranges. Approximate;+ #: see :data:`LINE_OVERLAP_BASIS`.+ overlapping_lines: int+ changed_lines: int+ share_of_change: float+ last_fix_days_ago: int | None = None+++@dataclass(frozen=True, slots=True)+class PriorFixImpact:+ """The fix record over one change's files, uncapped.++ ``status`` is the point of this type. ``unavailable`` means the record could+ not be read, which must never render the same way as ``available`` with no+ files -- "we could not look" and "nothing has broken here" are opposite+ claims about the same change.+ """++ status: EvidenceState = "available"+ reason: str | None = None+ #: Ordered by overlap, then fix count, then path. Uncapped: a surface caps.+ files: tuple[PriorFixFile, ...] = ()+ #: Distinct fixing commits, not rows. One commit that fixed three of the+ #: changed files is one past fix, not three.+ total_fixes: int = 0+ line_overlap_basis: str = LINE_OVERLAP_BASIS++ @property+ def files_with_fixes(self) -> int:+ return len(self.files)++ @property+ def changed_lines_in_fixed_files(self) -> int:+ return sum(f.changed_lines for f in self.files)++ @property+ def is_empty(self) -> bool:+ return not self.files++ @property+ def dominant_file(self) -> PriorFixFile | None:+ """The fix-carrying file holding most of this change, if one does."""+ return dominant_file(self.files)+++def dominant_file(files: Sequence[PriorFixFile]) -> PriorFixFile | None:+ """The fix-carrying file holding most of a change, if one does.++ The score itself is whole-change, so this is the only thing here that says+ *where* the risk sits: the file with both the past and the churn. Exposed+ as a function as well as a property because a surface asks it of the capped+ list it is about to render, so that it never names a file the reader cannot+ find anywhere else in the block.+ """+ if not files:+ return None+ # Negated keys so ties break toward the first file the ordering shows.+ top = min(files, key=lambda f: (-f.share_of_change, -f.fix_count, f.file_path))+ return top if top.share_of_change >= CONCENTRATION_SHARE else None+++def unavailable_prior_fixes(reason: str) -> PriorFixImpact:+ """The record exists but could not be read. Not a clean bill."""+ return PriorFixImpact(status="unavailable", reason=reason)+++def unsupported_prior_fixes(reason: str) -> PriorFixImpact:+ """Nothing to read: no index, or an index built before fix events existed."""+ return PriorFixImpact(status="unsupported", reason=reason)+++def parse_old_ranges(raw: str | None) -> tuple[tuple[int, int], ...]:+ """Inclusive spans from a stored ``old_ranges_json`` value.++ Tolerant on purpose, and it lives here because the tolerance belongs with+ the knowledge of the format. This feeds advisory evidence: one malformed+ row must cost that row, never the whole analysis.+ """+ try:+ parsed = json.loads(raw or "[]")+ except (TypeError, ValueError):+ return ()+ if not isinstance(parsed, list):+ return ()+ return tuple(span for raw_span in parsed if (span := _span(raw_span)) is not None)+++def _span(raw: object) -> tuple[int, int] | None:+ """One stored span, or ``None`` if it is not a usable pair of line numbers.++ A reversed pair is dropped rather than turned the right way round. The+ writer emits ``[start, end]``, so ``[10, 4]`` is a corrupt row and not a+ backwards one -- reordering it would invent a ten-line range the fix may+ never have touched, and this evidence is advisory enough already.+ """+ if not isinstance(raw, (list, tuple)) or len(raw) != 2:+ return None+ try:+ lo, hi = int(raw[0]), int(raw[1])+ except (TypeError, ValueError):+ return None+ return (lo, hi) if lo <= hi else None+++def _overlap(changed_lines: set[int], ranges: Sequence[tuple[int, int]]) -> int:+ return sum(1 for line in changed_lines for lo, hi in ranges if lo <= line <= hi)+++def _days_ago(moment: datetime | None, now: datetime) -> int | None:+ if moment is None:+ return None+ # A naive timestamp is read as UTC rather than dropped: the column is+ # nullable and historically inconsistent, and "no date" is a weaker answer+ # than a date that is at worst a few hours out.+ aware = moment if moment.tzinfo else moment.replace(tzinfo=UTC)+ return max(0, (now - aware).days)+++def summarize_prior_fixes(+ events: Iterable[FixRecord],+ changed: Mapping[str, set[int]],+ *,+ now: datetime | None = None,+) -> PriorFixImpact:+ """Summarize *events* against the lines *changed* touches.++ *changed* maps a changed path to the line numbers this change touches there,+ and is the counted universe: an event for a path outside it is ignored+ rather than allowed to widen the change.++ An empty result with ``status="available"`` is a real answer -- these files+ have no fix record. Callers that could not read the record at all must say+ so through :func:`unavailable_prior_fixes` instead.+ """+ now = now or datetime.now(UTC)+ total_changed = sum(len(lines) for lines in changed.values())++ counts: dict[str, int] = {}+ overlaps: dict[str, int] = {}+ newest: dict[str, int] = {}+ shas: set[str] = set()+ for event in events:+ lines = changed.get(event.file_path)+ if lines is None:+ continue+ shas.add(event.fix_sha)+ counts[event.file_path] = counts.get(event.file_path, 0) + 1+ overlaps[event.file_path] = overlaps.get(event.file_path, 0) + _overlap(+ lines, event.old_ranges+ )+ days = _days_ago(event.committed_at, now)+ if days is not None:+ seen = newest.get(event.file_path)+ newest[event.file_path] = days if seen is None else min(seen, days)++ files = tuple(+ sorted(+ (+ PriorFixFile(+ file_path=path,+ fix_count=counts[path],+ overlapping_lines=overlaps[path],+ changed_lines=len(changed[path]),+ share_of_change=(+ round(len(changed[path]) / total_changed, 3) if total_changed else 0.0+ ),+ last_fix_days_ago=newest.get(path),+ )+ for path in counts+ ),+ key=lambda f: (-f.overlapping_lines, -f.fix_count, f.file_path),+ )+ )+ return PriorFixImpact(status="available", files=files, total_fixes=len(shas))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.pyindex 424765cd9..2a2138ec4 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,19 +3,17 @@from __future__ import annotationsimport asyncio-import jsonimport subprocessimport threadingimport timefrom collections import OrderedDict-from datetime import UTC, datetimefrom functools import partialfrom typing import Anyimport pathspecimport structlogfrom sqlalchemy import select-from sqlalchemy.exc import SQLAlchemyError+from sqlalchemy.exc import OperationalError, SQLAlchemyErrorfrom repowise.core.analysis.change_health.service import (ChangeHealthDeltaService,@@ -27,6 +25,16 @@ from repowise.core.analysis.change_risk import (score_live_change,)from repowise.core.analysis.pr_blast import rank_tests_by_reach+from repowise.core.analysis.prior_fix_impact import (+ FixRecord,+ PriorFixFile,+ PriorFixImpact,+ dominant_file,+ parse_old_ranges,+ summarize_prior_fixes,+ unavailable_prior_fixes,+ unsupported_prior_fixes,+)from repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server._budget import OmissionCollector, cap_collectionfrom repowise.server.mcp_server._budget.contracts import response_budget_shed_order@@ -775,14 +783,80 @@ async def _prior_fixes_block(ctx: Any, changed: dict[str, set[int]]) -> dict[strper-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.+ so a repo without the feature grows no noise block. A read that *failed* is+ not silent: it renders with ``status: "unavailable"``, because "we could not+ look" and "nothing has broken here" are opposite claims about the change.+ """+ impact = await _read_prior_fixes(ctx, changed)+ if impact.status == "unsupported" or (impact.status == "available" and impact.is_empty):+ return None+ if impact.status != "available":+ return {+ "status": impact.status,+ "reason": impact.reason,+ "summary": (+ "The bug-fix record for these files could not be read, so this "+ "change is not cleared of a fix-prone history."+ ),+ }++ shown = impact.files[:_PRIOR_FIXES_LIMIT]+ block = {+ "files": [_prior_fix_row(f) for f in shown],+ "truncated": len(impact.files) > _PRIOR_FIXES_LIMIT,+ "total_fixes": impact.total_fixes,+ "files_with_fixes": impact.files_with_fixes,+ "changed_lines_in_fixed_files": impact.changed_lines_in_fixed_files,+ "line_overlap": impact.line_overlap_basis,+ "summary": (+ f"{impact.total_fixes} past bug-fix commit(s) touched "+ f"{impact.files_with_fixes} of the changed file(s). "+ "Line overlap is approximate (past ranges are numbered on their own "+ "parent commit); the per-file counts are not."+ ),+ }+ # Only over the files actually returned, so the sentence never names a path+ # the reader cannot find anywhere else in the block.+ top = dominant_file(shown)+ if top is not None:+ block["concentration"] = (+ f"{top.file_path} carries {top.share_of_change:.0%} of the changed lines "+ f"and {top.fix_count} past bug fix(es)."+ )+ return block+++def _prior_fix_row(entry: PriorFixFile) -> dict[str, Any]:+ """One core row on the wire, keeping the historical key set and order."""+ row: dict[str, Any] = {+ "file_path": entry.file_path,+ "fix_count": entry.fix_count,+ "overlapping_lines": entry.overlapping_lines,+ "changed_lines": entry.changed_lines,+ "share_of_change": entry.share_of_change,+ }+ # Absent rather than null when no event carried a date, as before.+ if entry.last_fix_days_ago is not None:+ row["last_fix_days_ago"] = entry.last_fix_days_ago+ return row+++async def _read_prior_fixes(ctx: Any, changed: dict[str, set[int]]) -> PriorFixImpact:+ """Collect fix events from the index. Collection only; core summarizes.++ The four ways this can come back empty are not one state. An index that+ predates fix events has nothing to read (``unsupported``), while a query+ that failed means the record exists and was not read (``unavailable``).+ Collapsing those is how a failure reads as a clean bill."""from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import FixEventsession_factory = getattr(ctx, "session_factory", None)- if session_factory is None or not changed:- return None+ if session_factory is None:+ return unsupported_prior_fixes("this repository has no index to read a fix record from")+ if not changed:+ return unsupported_prior_fixes("no changed lines were counted for this change")try:async with get_session(session_factory) as session:@@ -796,70 +870,59 @@ async def _prior_fixes_block(ctx: Any, changed: dict[str, set[int]]) -> dict[str)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+ return unsupported_prior_fixes("this repository is not indexed")+ except OperationalError as exc:+ # An index built before fix events existed has no table to read. That is+ # silence, not an error the caller should have to handle -- but a locked+ # or unreadable database is a real failure and falls through below.+ if _is_missing_table(exc):+ return unsupported_prior_fixes("this index predates the bug-fix record")+ return unavailable_prior_fixes(_read_failure(exc))+ except SQLAlchemyError as exc:+ return unavailable_prior_fixes(_read_failure(exc))++ return summarize_prior_fixes(+ (+ FixRecord(+ fix_sha=event.fix_sha,+ file_path=event.file_path,+ old_ranges=parse_old_ranges(event.old_ranges_json),+ committed_at=event.committed_at,+ )+ for event in events+ ),+ changed,+ )- if not events:- return None- # Share of the change's own churn, so the fix counts below say where in this- # change the risk sits rather than only that some touched file has a past.- total_changed = sum(len(lines) for lines in changed.values())- 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,- "changed_lines": len(changed[event.file_path]),- "share_of_change": round(len(changed[event.file_path]) / total_changed, 3)- if total_changed- else 0.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})- block = {- "files": files[:_PRIOR_FIXES_LIMIT],- "truncated": len(files) > _PRIOR_FIXES_LIMIT,- "total_fixes": total,- "files_with_fixes": len(files),- "changed_lines_in_fixed_files": sum(f["changed_lines"] for f in per_file.values()),- "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."- ),- }- # Only over the files actually returned, so the sentence never names a path- # the reader cannot find anywhere else in the block.- concentration = _concentration(files[:_PRIOR_FIXES_LIMIT])- if concentration is not None:- block["concentration"] = concentration- return block+def _read_failure(exc: SQLAlchemyError) -> str:+ """Name the failure without quoting the driver.++ Driver text can carry connection-string fragments, and this string goes out+ on the wire. The class of failure is what a caller can act on; the detail+ belongs in the server log, where it already is.+ """+ log.warning("prior_fixes_read_failed", error=str(exc))+ return f"the fix record could not be read ({type(exc).__name__})"+++def _is_missing_table(exc: OperationalError) -> bool:+ """Whether *exc* is "that table is not there" rather than a real failure.++ Backend-specific wording, so this is a substring check and not a code. It+ fails toward ``unavailable``: mistaking a missing table for a failure costs+ a visible block that should have been silent, while the reverse would let a+ genuine failure render as a clean bill.++ Every clause is table-scoped for that reason. Postgres says "does not+ exist" for a missing column, database, function or role too, and each of+ those is real schema drift or misconfiguration -- swallowing them here+ would rebuild the exact silence this block exists to break.+ """+ text = str(getattr(exc, "orig", "") or exc).lower()+ if "no such table" in text or "undefined table" in text:+ return True+ return "does not exist" in text and ("relation" in text or "table" in text)async def _independent_changes_block(@@ -974,53 +1037,6 @@ async def _branch_overlap_block(return block-#: A file has to carry this much of the change's lines before the response will-#: say the risk sits there. Below it the change is spread out and naming one-#: file would be a stronger claim than the numbers support.-_CONCENTRATION_SHARE = 0.5---def _concentration(files: list[dict[str, Any]]) -> str | None:- """Name the fix-carrying file that holds most of this change, if one does.-- The score itself is whole-change, so this is the only place the response- says *where* the risk sits: the file with both the past and the churn.- """- if not files:- return None- # Negated path so ties break toward the first file the sorted list shows,- # matching the ascending file_path tiebreak the block is sorted by.- top = min(files, key=lambda f: (-f["share_of_change"], -f["fix_count"], f["file_path"]))- if top["share_of_change"] < _CONCENTRATION_SHARE:- return None- return (- f"{top['file_path']} carries {top['share_of_change']:.0%} of the changed lines "- f"and {top['fix_count']} past bug fix(es)."- )---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--def _cap_tests(tests: list[str], collector: OmissionCollector, label: str) -> list[str]:"""First _IMPACTED_TESTS_LIMIT ids; the tail goes to the omission store."""if len(tests) > _IMPACTED_TESTS_LIMIT:diff --git a/tests/unit/analysis/test_prior_fix_impact.py b/tests/unit/analysis/test_prior_fix_impact.pynew file mode 100644index 000000000..2aca027a7--- /dev/null+++ b/tests/unit/analysis/test_prior_fix_impact.py@@ -0,0 +1,240 @@+"""The fix record must not let a failed read look like a clean history.++The summary itself is arithmetic, but the states around it are the point: a+change whose fix record could not be read has not been cleared of one, and the+two must never render the same way. These assertions are about that difference+as much as about the counts.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta++import pytest++from repowise.core.analysis.prior_fix_impact import (+ CONCENTRATION_SHARE,+ FixRecord,+ PriorFixImpact,+ parse_old_ranges,+ summarize_prior_fixes,+ unavailable_prior_fixes,+ unsupported_prior_fixes,+)++NOW = datetime(2026, 9, 16, tzinfo=UTC)+++def _by_path(impact) -> dict:+ return {f.file_path: f for f in impact.files}+++def _fix(sha: str, path: str, ranges=(), *, days_ago: int | None = None) -> FixRecord:+ return FixRecord(+ fix_sha=sha,+ file_path=path,+ old_ranges=tuple(ranges),+ committed_at=None if days_ago is None else NOW - timedelta(days=days_ago),+ )+++# ---------------------------------------------------------------------------+# States+# ---------------------------------------------------------------------------+++def test_no_events_is_a_real_answer_not_a_missing_one():+ impact = summarize_prior_fixes([], {"a.py": {1, 2}}, now=NOW)++ assert impact.status == "available"+ assert impact.is_empty+ assert impact.reason is None+++def test_an_unread_record_is_not_a_clean_bill():+ impact = unavailable_prior_fixes("the fix record could not be read: disk I/O error")++ assert impact.status == "unavailable"+ assert impact.reason+ # Identical population to the known-empty case, which is exactly why the+ # status has to carry the difference.+ assert impact.is_empty+ assert impact.total_fixes == 0+++def test_nothing_to_read_is_distinct_from_a_failed_read():+ assert unsupported_prior_fixes("this index predates the bug-fix record").status == "unsupported"+ assert unavailable_prior_fixes("query failed").status == "unavailable"+++# ---------------------------------------------------------------------------+# Counting+# ---------------------------------------------------------------------------+++def test_one_commit_fixing_three_files_is_one_past_fix():+ """Summing per-file rows would report a single commit three times."""+ impact = summarize_prior_fixes(+ [_fix("abc", "a.py"), _fix("abc", "b.py"), _fix("abc", "c.py")],+ {"a.py": {1}, "b.py": {1}, "c.py": {1}},+ now=NOW,+ )++ assert impact.total_fixes == 1+ assert impact.files_with_fixes == 3+ assert [f.fix_count for f in impact.files] == [1, 1, 1]+++def test_per_file_counts_stay_per_file():+ impact = summarize_prior_fixes(+ [_fix("aaa", "a.py"), _fix("bbb", "a.py"), _fix("ccc", "b.py")],+ {"a.py": {1}, "b.py": {1}},+ now=NOW,+ )++ by_path = _by_path(impact)+ assert by_path["a.py"].fix_count == 2+ assert by_path["b.py"].fix_count == 1+ assert impact.total_fixes == 3+++def test_overlap_counts_changed_lines_inside_a_past_range():+ impact = summarize_prior_fixes(+ [_fix("aaa", "a.py", [(10, 20)])],+ {"a.py": {9, 10, 15, 20, 21}},+ now=NOW,+ )++ assert impact.files[0].overlapping_lines == 3 # 10, 15, 20+++def test_an_event_outside_the_counted_universe_is_ignored():+ """The fix record must not widen what the change is said to touch."""+ impact = summarize_prior_fixes(+ [_fix("aaa", "a.py"), _fix("bbb", "excluded.py")],+ {"a.py": {1}},+ now=NOW,+ )++ assert [f.file_path for f in impact.files] == ["a.py"]+ # The commit that only touched an uncounted file is not a past fix here.+ assert impact.total_fixes == 1+++def test_share_of_change_is_a_share_of_the_counted_lines():+ impact = summarize_prior_fixes(+ [_fix("aaa", "a.py"), _fix("bbb", "b.py")],+ {"a.py": {1, 2, 3}, "b.py": {4}},+ now=NOW,+ )++ by_path = _by_path(impact)+ assert by_path["a.py"].share_of_change == 0.75+ assert by_path["b.py"].share_of_change == 0.25+++def test_the_newest_fix_wins_the_age():+ impact = summarize_prior_fixes(+ [_fix("aaa", "a.py", days_ago=400), _fix("bbb", "a.py", days_ago=12)],+ {"a.py": {1}},+ now=NOW,+ )++ assert impact.files[0].last_fix_days_ago == 12+++def test_a_dateless_event_leaves_the_age_unknown():+ impact = summarize_prior_fixes([_fix("aaa", "a.py")], {"a.py": {1}}, now=NOW)++ assert impact.files[0].last_fix_days_ago is None+++def test_a_naive_timestamp_is_read_as_utc_rather_than_dropped():+ record = FixRecord(fix_sha="aaa", file_path="a.py", committed_at=datetime(2026, 9, 6))++ impact = summarize_prior_fixes([record], {"a.py": {1}}, now=NOW)++ assert impact.files[0].last_fix_days_ago == 10+++def test_a_future_timestamp_does_not_go_negative():+ impact = summarize_prior_fixes(+ [_fix("aaa", "a.py", days_ago=-5)], {"a.py": {1}}, now=NOW+ )++ assert impact.files[0].last_fix_days_ago == 0+++# ---------------------------------------------------------------------------+# Ordering and concentration+# ---------------------------------------------------------------------------+++def test_files_order_by_overlap_then_count_then_path():+ impact = summarize_prior_fixes(+ [+ _fix("aaa", "b.py"),+ _fix("bbb", "a.py"),+ _fix("ccc", "a.py"),+ _fix("ddd", "c.py", [(1, 5)]),+ ],+ {"a.py": {1}, "b.py": {1}, "c.py": {1}},+ now=NOW,+ )++ assert [f.file_path for f in impact.files] == ["c.py", "a.py", "b.py"]+++def test_a_file_carrying_most_of_the_change_is_named():+ impact = summarize_prior_fixes(+ [_fix("aaa", "big.py"), _fix("bbb", "small.py")],+ {"big.py": set(range(1, 10)), "small.py": {1}},+ now=NOW,+ )++ assert impact.dominant_file is not None+ assert impact.dominant_file.file_path == "big.py"+++def test_a_spread_out_change_names_no_file():+ impact = summarize_prior_fixes(+ [_fix("aaa", "a.py"), _fix("bbb", "b.py"), _fix("ccc", "c.py")],+ {"a.py": {1}, "b.py": {1}, "c.py": {1}},+ now=NOW,+ )++ # A third each is below the threshold; naming one would overclaim.+ assert max(f.share_of_change for f in impact.files) < CONCENTRATION_SHARE+ assert impact.dominant_file is None+++def test_no_files_names_no_dominant_file():+ assert PriorFixImpact().dominant_file is None+++# ---------------------------------------------------------------------------+# Stored range parsing+# ---------------------------------------------------------------------------+++ "raw,expected",+ [+ ("[[1, 4], [10, 12]]", ((1, 4), (10, 12))),+ ("[]", ()),+ ("", ()),+ (None, ()),+ ("not json", ()),+ ('{"a": 1}', ()), # not a list+ ("[[1]]", ()), # wrong arity+ ('[["x", "y"]]', ()), # not integers+ ("[[4, 1]]", ()), # a reversed span is corrupt, not backwards+ ],+)+def test_stored_ranges_parse_tolerantly(raw, expected):+ """One malformed row costs that row, never the whole analysis."""+ assert parse_old_ranges(raw) == expected+++def test_a_malformed_span_does_not_discard_its_good_neighbours():+ assert parse_old_ranges('[[1, 2], "junk", [5, 6]]') == ((1, 2), (5, 6))diff --git a/tests/unit/change_health/test_change_review_bundle.py b/tests/unit/change_health/test_change_review_bundle.pyindex 48e55d56c..2b4917d34 100644--- a/tests/unit/change_health/test_change_review_bundle.py+++ b/tests/unit/change_health/test_change_review_bundle.py@@ -16,7 +16,12 @@ import subprocessimport pytestfrom repowise.core.analysis.branch_overlap import BranchOverlap-from repowise.core.analysis.change_health import GitRevisionSource, MappingRevisionSource+from repowise.core.analysis.change_health import (+ ChangeHealthDeltaService,+ DeltaRequest,+ GitRevisionSource,+ MappingRevisionSource,+)from repowise.core.analysis.change_review import (CHANGE_REVIEW_CONTRACT_VERSION,LANES,@@ -28,6 +33,7 @@ from repowise.core.analysis.change_review import ()from repowise.core.analysis.change_risk import assess_change, features_from_file_changesfrom repowise.core.analysis.independent_changes import IndependentChangeEvidence+from repowise.core.analysis.review_directive import review_directivefrom .conftest import Repo, python_complex@@ -320,6 +326,41 @@ def test_no_coverage_map_and_no_candidates_asks_for_coverage(make_repo):assert "establish_test_coverage" in kinds+def test_a_supplied_delta_is_used_rather_than_recompared(make_repo):+ """A surface that runs the comparison concurrently keeps that concurrency."""+ repo = _two_commit_repo(make_repo)+ service = ChangeHealthDeltaService(GitRevisionSource(str(repo.path)), repo_path=str(repo.path))+ precomputed = service.compare(+ DeltaRequest(repo_path=str(repo.path), revspec="HEAD", extensions=(), exclude_patterns=())+ )++ bundle = _service(repo).review(+ ChangeReviewRequest(revspec="HEAD", baseline=0),+ evidence=ChangeReviewEvidence(health=precomputed),+ )++ assert bundle.health is precomputed+ assert bundle.lanes["health"].state in {"available", "partial"}+ # The directive is decided from the supplied delta, not from a second one.+ assert bundle.directive.status == review_directive(precomputed).status+++def test_a_supplied_delta_beats_a_skip(make_repo):+ """Handing the lane an answer is not the same as asking for it to be skipped."""+ repo = _two_commit_repo(make_repo)+ service = ChangeHealthDeltaService(GitRevisionSource(str(repo.path)), repo_path=str(repo.path))+ precomputed = service.compare(+ DeltaRequest(repo_path=str(repo.path), revspec="HEAD", extensions=(), exclude_patterns=())+ )++ bundle = _service(repo).review(+ ChangeReviewRequest(revspec="HEAD", baseline=0),+ evidence=ChangeReviewEvidence(health=precomputed, skip=frozenset({"health"})),+ )++ assert bundle.health is precomputed++def test_a_supplied_risk_result_is_used_rather_than_rescored(make_repo):"""A caller holding file stats from an API gets its own numbers back."""repo = _two_commit_repo(make_repo)diff --git a/tests/unit/server/mcp/test_change_risk_prior_fixes.py b/tests/unit/server/mcp/test_change_risk_prior_fixes.pynew file mode 100644index 000000000..d7b79d9ff--- /dev/null+++ b/tests/unit/server/mcp/test_change_risk_prior_fixes.py@@ -0,0 +1,181 @@+"""How the prior-fix block renders each state it can reach.++The block was silent for five different reasons, so an index read that failed+was indistinguishable on the wire from a change whose files have never been+patched. These tests pin which of those stay silent and which one must not.+"""++from __future__ import annotations++import pytest+from sqlalchemy.exc import OperationalError++from repowise.core.analysis.prior_fix_impact import (+ FixRecord,+ summarize_prior_fixes,+ unavailable_prior_fixes,+ unsupported_prior_fixes,+)+from repowise.server.mcp_server import tool_change_risk as tool+++async def _block(monkeypatch, impact, changed=None):+ async def _fake(ctx, changed_lines):+ return impact++ monkeypatch.setattr(tool, "_read_prior_fixes", _fake)+ return await tool._prior_fixes_block(object(), changed or {"a.py": {1}})+++# ---------------------------------------------------------------------------+# What stays silent+# ---------------------------------------------------------------------------+++async def test_an_index_without_fix_events_stays_silent(monkeypatch):+ """A repo without the feature must not grow a noise block."""+ block = await _block(monkeypatch, unsupported_prior_fixes("this index predates it"))++ assert block is None+++async def test_files_with_no_past_stay_silent(monkeypatch):+ block = await _block(monkeypatch, summarize_prior_fixes([], {"a.py": {1}}))++ assert block is None+++# ---------------------------------------------------------------------------+# What must not stay silent+# ---------------------------------------------------------------------------+++async def test_a_failed_read_renders_rather_than_vanishing(monkeypatch):+ block = await _block(monkeypatch, unavailable_prior_fixes("disk I/O error"))++ assert block is not None+ assert block["status"] == "unavailable"+ assert "disk I/O error" in block["reason"]+ # It must not carry the shape of an answer it does not have.+ assert "files" not in block+ assert "total_fixes" not in block+++async def test_a_failed_read_does_not_claim_the_change_is_clear(monkeypatch):+ block = await _block(monkeypatch, unavailable_prior_fixes("connection reset"))++ assert "not cleared" in block["summary"]+++# ---------------------------------------------------------------------------+# The populated block keeps its historical shape+# ---------------------------------------------------------------------------+++async def test_a_populated_block_keeps_its_keys(monkeypatch):+ impact = summarize_prior_fixes(+ [FixRecord(fix_sha="aaa", file_path="a.py", old_ranges=((1, 4),))],+ {"a.py": {1, 2}},+ )++ block = await _block(monkeypatch, impact, {"a.py": {1, 2}})++ assert set(block) >= {+ "files",+ "truncated",+ "total_fixes",+ "files_with_fixes",+ "changed_lines_in_fixed_files",+ "line_overlap",+ "summary",+ }+ assert block["line_overlap"] == "approximate"+ assert block["files"][0]["file_path"] == "a.py"+ assert block["files"][0]["overlapping_lines"] == 2+++async def test_a_dateless_fix_omits_the_age_key_rather_than_nulling_it(monkeypatch):+ impact = summarize_prior_fixes([FixRecord(fix_sha="aaa", file_path="a.py")], {"a.py": {1}})++ block = await _block(monkeypatch, impact)++ assert "last_fix_days_ago" not in block["files"][0]+++async def test_the_list_is_capped_and_says_so(monkeypatch):+ paths = [f"f{i}.py" for i in range(tool._PRIOR_FIXES_LIMIT + 3)]+ changed = {p: {1} for p in paths}+ impact = summarize_prior_fixes(+ [FixRecord(fix_sha=f"sha{i}", file_path=p) for i, p in enumerate(paths)], changed+ )++ block = await _block(monkeypatch, impact, changed)++ assert len(block["files"]) == tool._PRIOR_FIXES_LIMIT+ assert block["truncated"] is True+ # The counts describe the whole population, not the capped list.+ assert block["files_with_fixes"] == len(paths)+++async def test_concentration_only_names_a_file_the_block_shows(monkeypatch):+ changed = {"big.py": set(range(1, 20)), "small.py": {1}}+ impact = summarize_prior_fixes(+ [+ FixRecord(fix_sha="aaa", file_path="big.py"),+ FixRecord(fix_sha="bbb", file_path="small.py"),+ ],+ changed,+ )++ block = await _block(monkeypatch, impact, changed)++ assert "big.py" in block["concentration"]+++# ---------------------------------------------------------------------------+# Telling a missing table from a real failure+# ---------------------------------------------------------------------------+++ "message,missing",+ [+ ("no such table: fix_events", True),+ ('relation "fix_events" does not exist', True),+ ("Undefined table: 7 ERROR", True),+ ("database is locked", False),+ ("disk I/O error", False),+ ("connection reset by peer", False),+ # Postgres says "does not exist" for plenty that is not a missing+ # table, and every one of these is a real failure that must surface.+ ('column "fix_sha" does not exist', False),+ ('database "wiki" does not exist', False),+ ('role "repowise" does not exist', False),+ ("function now_utc() does not exist", False),+ ],+)+def test_a_missing_table_is_told_apart_from_a_broken_read(message, missing):+ exc = OperationalError("SELECT 1", {}, Exception(message))++ assert tool._is_missing_table(exc) is missing+++def test_the_failure_reason_names_the_class_without_quoting_the_driver():+ """Driver text can carry connection-string fragments, and this goes on the wire."""+ exc = OperationalError(+ "SELECT 1", {}, Exception("could not connect: host=db.internal user=admin password=hunter2")+ )++ reason = tool._read_failure(exc)++ assert "OperationalError" in reason+ assert "hunter2" not in reason+ assert "db.internal" not in reasondiff --git a/tests/unit/server/mcp/test_prior_fixes.py b/tests/unit/server/mcp/test_prior_fixes.pyindex 6d1e31dc7..84ca3c0c2 100644--- a/tests/unit/server/mcp/test_prior_fixes.py+++ b/tests/unit/server/mcp/test_prior_fixes.py@@ -17,25 +17,40 @@ from types import SimpleNamespacefrom sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine+from repowise.core.analysis.prior_fix_impact import (+ FixRecord,+ parse_old_ranges,+ summarize_prior_fixes,+)from repowise.core.persistence.database import init_dbfrom repowise.core.persistence.models import FixEvent, Repository, _new_uuid-from repowise.server.mcp_server.tool_change_risk import _overlap_count, _prior_fixes_block+from repowise.server.mcp_server.tool_change_risk import _prior_fixes_block+++def _overlap(changed: set[int], old_ranges_json: str) -> int:+ """Changed lines landing inside a stored fix's replaced ranges.++ Both halves now live in core -- the tolerant parse and the count -- so this+ asserts them together the way the block consumes them.+ """+ record = FixRecord(fix_sha="a", file_path="f", old_ranges=parse_old_ranges(old_ranges_json))+ return summarize_prior_fixes([record], {"f": changed}).files[0].overlapping_linesdef 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+ assert _overlap(changed, json.dumps([[4, 7]])) == 3+ assert _overlap(changed, json.dumps([[4, 7], [39, 41]])) == 4+ assert _overlap(changed, json.dumps([[100, 120]])) == 0def 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+ assert _overlap({1}, "[]") == 0+ assert _overlap({1}, "") == 0+ assert _overlap({1}, "not json") == 0+ assert _overlap({1}, json.dumps([[1]])) == 0+ assert _overlap({1}, json.dumps({"a": 1})) == 0async def test_block_is_silent_without_an_index():