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): anchor fix history recency to indexed commit instead of wall clock (#3145)
Rishabh Mishrafe038272169b
diff --git a/docs/layers/BUG_HISTORY.md b/docs/layers/BUG_HISTORY.mdindex 18f14cf17..fa94bd898 100644--- a/docs/layers/BUG_HISTORY.md+++ b/docs/layers/BUG_HISTORY.md@@ -44,7 +44,7 @@ In the dashboard, look at the health drawer's **Bug history** section and the| Field | Meaning ||---|---|| `fix_count` | Counted bug-fix commits that touched the file in the last 180 days |-| `last_fix_days_ago` / `last_fix_at` | Age of the most recent counted fix |+| `last_fix_days_ago` / `last_fix_at` | Age of the most recent counted fix, measured to the indexed commit || `bug_magnet` | The decayed fix mass is 3.0 or more. Present only when true || `top_symbols` | Up to three functions or classes that absorbed the most fixes. Approximate |diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex e65e236bc..96032ac71 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -147,7 +147,7 @@ Per target, under `targets`:|-------|---------|| title, summary, symbols | Docs summary and the symbols defined, with signatures and line numbers. Compact cards list the top 15 (types, then functions and methods, then the rest, by centrality) with `symbols_truncated` `{shown, total, hint}` and `symbols_total`; a budget trim below that keeps symbols by kind and name match, not centrality; `include=["symbols"]` lists all. A row without `symbol_id` is `path::name` || `hotspot` | Churn flag |-| `fix_history` | Only on files with counted bug fixes: count, age, `bug_magnet`. A cue to call `get_risk` |+| `fix_history` | Only on files with counted bug fixes: count, age (measured to the indexed commit), `bug_magnet`. A cue to call `get_risk` || `episodes` | Count of dated records bound to the target; `get_why` serves their bodies || decisions | Titles by default. With `include=["decisions"]`, three lanes: `decisions` (accepted, governing), `candidates` (proposed, at most 3), `history` (accepted then withdrawn, at most 2) || `file_preview` | For a file with no indexed symbols: `lines`, `chars`, and for a markdown or reST document `heading_count` with the first three `headings`; otherwise the first three non-empty lines as `head` |@@ -206,6 +206,7 @@ Per file:| Field | Meaning ||-------|---------|+| `defect_profile` | Only on files with counted bug fixes: `fix_count` (in 6-month window), `last_fix_days_ago` (measured to the indexed commit), `bug_magnet`, `top_symbols` || `hotspot_score` | 0 to 1 churn percentile || `health_score` | 0 to 10 || `dependents_count` | Direct directed structural dependents; a floor over the indexed graph |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 f7d0e5c38..ef89a1de3 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@@ -47,7 +47,10 @@ import asyncioimport loggingfrom typing import Any+from sqlalchemy import func, select+from repowise.core.persistence.database import get_session+from repowise.core.persistence.models import GitMetadatafrom repowise.core.registry import ToolRecipefrom repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server import _state@@ -174,6 +177,13 @@ async def get_context(_t0 = _time.perf_counter()async with get_session(ctx.session_factory) as session:repository = await _get_repo(session)+ as_of_ts = (+ await session.execute(+ select(func.max(GitMetadata.last_commit_at)).where(+ GitMetadata.repository_id == repository.id+ )+ )+ ).scalar()# return_exceptions=True isolates a single target's failure: one# target raising (e.g. a malformed lookup) must not sink the whole@@ -191,6 +201,7 @@ async def get_context(exclude_spec=exclude_spec,repo_root=ctx.path,collector=collector,+ as_of_ts=as_of_ts,)for t in targets],diff --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 32626c029..ae08a6d75 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@@ -11,6 +11,7 @@ from __future__ import annotationsimport contextlibimport jsonimport re+from datetime import datetimefrom pathlib import Pathfrom typing import Any@@ -381,6 +382,7 @@ async def _resolve_one_target(exclude_spec: Any = None,repo_root: Any = None,collector: OmissionCollector | None = None,+ as_of_ts: datetime | None = None,) -> dict:"""Resolve a single target and return its full context."""repo_id = repository.id@@ -610,6 +612,7 @@ async def _resolve_one_target(exclude_spec=exclude_spec,repo_root=repo_root,collector=collector,+ as_of_ts=as_of_ts,)if "error" not in card:card["target"] = target@@ -1019,7 +1022,7 @@ async def _resolve_one_target(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)+ fixes = fix_annotation(triage_meta, now=as_of_ts)if fixes is not None:result_data["fix_history"] = fixesdiff --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 66fadc53f..3b4da5635 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@@ -373,10 +373,10 @@ def _build_co_changes(return population, len(population)-def fix_annotation(meta: Any) -> dict | None:- """Counted fixes, their age, and the magnet flag, or ``None`` for silence.+def fix_annotation(meta: Any, now: datetime | None = None) -> dict | None:+ """The shared count/age/magnet fix block used by context and risk.- The compact form every fix-history surface shares, so the recency contract+ Centralized so the two tools agree on the wire format and the age contractis enforced once: the ``bug_magnet`` flag rides on the age and is neveremitted alone. ``bug_magnet`` is a claim about RECENT fix pressure, so withno timestamp to anchor it the same word would describe a file fixed four@@ -392,8 +392,13 @@ def fix_annotation(meta: Any) -> dict | None: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.+ ref = (+ datetime.now(UTC)+ if now is None+ else (now if now.tzinfo else now.replace(tzinfo=UTC))+ )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)+ out["last_fix_days_ago"] = max(0, (ref - moment).days)if getattr(meta, "bug_magnet", False):out["bug_magnet"] = Truereturn out@@ -412,11 +417,11 @@ def _fix_clause(profile: dict | None) -> str: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}, "+ f"last {profile['last_fix_days_ago']}d before the indexed commit{magnet}, ")-def _defect_profile(meta: Any) -> dict | None:+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.Built from the fix-event rollup already loaded on the ``GitMetadata`` row,@@ -433,7 +438,7 @@ 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."""- profile = fix_annotation(meta)+ profile = fix_annotation(meta, now=now)if profile is None:return Noneprofile["window"] = "6 months"@@ -506,6 +511,7 @@ async def _assess_one_target(team_size: int | None = None,collector: OmissionCollector | None = None,include_graph: bool = False,+ as_of_ts: datetime | None = None,) -> dict:"""Assess risk for a single target file.@@ -737,7 +743,7 @@ async def _assess_one_target(if merge_commit_count > 0:result_data["merge_commit_count_90d"] = merge_commit_count- defect_profile = _defect_profile(meta)+ defect_profile = _defect_profile(meta, now=as_of_ts)if defect_profile is not None:result_data["defect_profile"] = defect_profilediff --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 6df7119e4..3a2bf03d6 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@@ -6,7 +6,7 @@ import asynciofrom dataclasses import dataclassfrom typing import Any, NamedTuple-from sqlalchemy import select+from sqlalchemy import func, selectfrom repowise.core.analysis.risk_semantics import file_risk_scalesfrom repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPES@@ -187,21 +187,25 @@ async def _load_dependency_graph(session: Any, repo_id: str, roots: set[str]) ->return _DependencyGraph(node_meta, import_links, reverse_deps, dep_counts)-def _hotspot_entry(meta: GitMetadata) -> dict:+def _hotspot_entry(meta: GitMetadata, as_of_ts: Any = None) -> dict:entry = {"file_path": meta.file_path,"hotspot_score": meta.churn_percentile,"is_hotspot": True,"primary_owner": meta.primary_owner_name,}- fixes = fix_annotation(meta)+ fixes = fix_annotation(meta, now=as_of_ts)if fixes is not None:entry.update(fixes)return entryasync def _global_hotspots(- session: Any, repo_id: str, targets: list[str], exclude_spec: Any+ session: Any,+ repo_id: str,+ targets: list[str],+ exclude_spec: Any,+ as_of_ts: Any = None,) -> list[dict]:"""Hotspots outside ``targets``, ranked on bug-fix history, then churn.@@ -224,7 +228,11 @@ async def _global_hotspots()all_hotspots = filter_rows_by_attr(list(res.scalars().all()), "file_path", exclude_spec)target_set = set(targets)- return [_hotspot_entry(h) for h in all_hotspots if h.file_path not in target_set]+ return [+ _hotspot_entry(h, as_of_ts=as_of_ts)+ for h in all_hotspots+ if h.file_path not in target_set+ ]async def _pr_blast_radius(@@ -254,6 +262,13 @@ async def _gather_evidence(# Repo-wide, so computed once for every target's bus-factor calibration.team_size = await _get_active_contributor_count(session, repo_id)+ as_of_ts = (+ await session.execute(+ select(func.max(GitMetadata.last_commit_at)).where(+ GitMetadata.repository_id == repo_id+ )+ )+ ).scalar()results = await asyncio.gather(*[@@ -269,13 +284,16 @@ async def _gather_evidence(team_size,collector,include_graph,+ as_of_ts=as_of_ts,)for t in targets])global_hotspots = []if len(targets) > 1 and not changed_files:- global_hotspots = await _global_hotspots(session, repo_id, targets, exclude_spec)+ global_hotspots = await _global_hotspots(+ session, repo_id, targets, exclude_spec, as_of_ts=as_of_ts+ )pr_blast_radius = None# Only the PR directive reads this, and only for affected file paths.test_paths: set[str] = set()diff --git a/tests/unit/server/mcp/test_defect_profile.py b/tests/unit/server/mcp/test_defect_profile.pyindex d300e2090..16786c34b 100644--- a/tests/unit/server/mcp/test_defect_profile.py+++ b/tests/unit/server/mcp/test_defect_profile.py@@ -165,6 +165,16 @@ def test_fix_annotation_carries_count_age_and_flag():assert out == {"fix_count": 5, "last_fix_days_ago": 14, "bug_magnet": True}+def test_fix_annotation_anchors_to_passed_reference_time():+ last_fix = datetime(2022, 8, 4, 14, 24, 20, tzinfo=UTC)+ now = last_fix + timedelta(days=41)+ out = fix_annotation(+ _meta(prior_defect_count=1, last_fix_at=last_fix),+ now=now,+ )+ assert out == {"fix_count": 1, "last_fix_days_ago": 41}++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.@@ -189,9 +199,9 @@ def test_risk_summary_clause_is_empty_without_fix_history():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), "+ assert clause == "5 bug fixes in 6mo, last 14d before the indexed commit (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, "+ assert clause == "1 bug fix in 6mo, last 2d before the indexed commit, "diff --git a/tests/unit/server/mcp/test_fix_history_coherence.py b/tests/unit/server/mcp/test_fix_history_coherence.pyindex d535ef55d..336ca6965 100644--- a/tests/unit/server/mcp/test_fix_history_coherence.py+++ b/tests/unit/server/mcp/test_fix_history_coherence.py@@ -11,7 +11,7 @@ from __future__ import annotationsfrom datetime import UTC, datetime, timedeltaimport pytest-from sqlalchemy import select+from sqlalchemy import func, selectfrom repowise.core.persistence.models import GitMetadata@@ -27,6 +27,18 @@ async def _add_bug_magnet(session, repo_id: str, path: str, *, fixes: int, days:StaticPool connection and commit at teardown, so a second session thatcommits mid-test drops the seeded data out from under the tool call."""+ anchor = (+ await session.execute(+ select(func.max(GitMetadata.last_commit_at)).where(+ GitMetadata.repository_id == repo_id+ )+ )+ ).scalar_one_or_none()+ if anchor is None:+ anchor = datetime.now(UTC)+ elif anchor.tzinfo is None:+ anchor = anchor.replace(tzinfo=UTC)+session.add(GitMetadata(id=f"gm-magnet-{path}",@@ -40,7 +52,7 @@ async def _add_bug_magnet(session, repo_id: str, path: str, *, fixes: int, days:bug_magnet=True,fix_mass=9.0,prior_defect_count=fixes,- last_fix_at=datetime.now(UTC) - timedelta(days=days),+ last_fix_at=anchor - timedelta(days=days),primary_owner_name="Carol",))@@ -103,7 +115,7 @@ 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 ago (bug magnet)" in summary+ assert "4 bug fixes in 6mo, last 7d before the indexed commit (bug magnet)" in summaryassert summary.index("bug fixes") < summary.index("hotspot score")assert "bug-prone" in summary@@ -132,7 +144,10 @@ async def test_get_context_triage_reports_fix_history(setup_mcp, session, repo_i).scalar_one()row.prior_defect_count = 5row.bug_magnet = True- row.last_fix_at = datetime.now(UTC) - timedelta(days=3)+ anchor = row.last_commit_at or datetime.now(UTC)+ if anchor.tzinfo is None:+ anchor = anchor.replace(tzinfo=UTC)+ row.last_fix_at = anchor - timedelta(days=3)await session.flush()result = await get_context(["src/auth/service.py"])@@ -153,3 +168,60 @@ async def test_get_context_triage_omits_fix_history_when_there_is_none(setup_mcpassert "fix_history" not in tassert t["hotspot"] is True # churn bit still reported+++async def test_fix_history_anchors_to_historical_commit_two_years_ago(+ setup_mcp, session, repo_id+):+ """A repository last committed two years ago measures fix age from HEAD, not today."""+ from repowise.server.mcp_server import get_context, get_risk++ # Move all existing rows back to 2 years ago+ two_years_ago = datetime.now(UTC) - timedelta(days=730)+ rows = (+ await session.execute(+ select(GitMetadata).where(GitMetadata.repository_id == repo_id)+ )+ ).scalars().all()+ for r in rows:+ r.last_commit_at = two_years_ago+ await session.flush()++ # Add a file with one fix 30 days before that anchor+ session.add(+ GitMetadata(+ id="gm-old-fix",+ repository_id=repo_id,+ file_path="src/old/fixed.py",+ commit_count_total=5,+ commit_count_90d=1,+ commit_count_30d=0,+ churn_percentile=0.1,+ is_hotspot=False,+ bug_magnet=True,+ prior_defect_count=1,+ last_fix_at=two_years_ago - timedelta(days=30),+ primary_owner_name="Dave",+ )+ )+ await session.flush()++ # get_risk: risk_summary, defect_profile+ risk_res = await get_risk(["src/old/fixed.py"])+ target_risk = risk_res["targets"]["src/old/fixed.py"]+ assert "1 bug fix in 6mo, last 30d before the indexed commit" in target_risk["risk_summary"]+ assert target_risk["defect_profile"]["last_fix_days_ago"] == 30+ assert target_risk["defect_profile"]["fix_count"] == 1++ # global_hotspots (target other files so src/old/fixed.py is surfaced in attention list)+ hotspots_res = await get_risk(["src/auth/service.py", "src/db/models.py"])+ listed = {h["file_path"]: h for h in hotspots_res["global_hotspots"]}+ assert "src/old/fixed.py" in listed+ assert listed["src/old/fixed.py"]["last_fix_days_ago"] == 30++ # get_context: fix_history+ context_res = await get_context(["src/old/fixed.py"])+ target_ctx = context_res["targets"]["src/old/fixed.py"]+ assert target_ctx["fix_history"]["last_fix_days_ago"] == 30+ assert target_ctx["fix_history"]["fix_count"] == 1