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(claude-md): rank the generated attention list by bug-fix history, not churn (#954)
Raghav Chamadiya0d28880fbea1
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.pyindex 74e5962ce..cc7965d73 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/decision_inject.py@@ -552,7 +552,15 @@ _FIX_NOTICE_MIN_COUNT = 3def _humanize_age(days: int) -> str:- """Render an age as "2 weeks ago" / "3 months ago", never as a bare count."""+ """Render an age as "2 weeks ago" / "3 months ago", never as a bare count.++ Deliberately duplicated by ``editor_files/fetcher.py``, which renders the+ same recency phrasing into CLAUDE.md. Sharing it would mean this hook+ importing ``repowise.core``, and the cheapest module that could host it+ costs ~660ms to import (``analysis.health.__init__`` builds the whole+ HealthAnalyzer) against this module's sub-100ms budget. Ten lines of copy+ is the cheaper trade; keep the two phrasings in step by hand.+ """if days <= 1:return "today" if days <= 0 else "yesterday"if days < 14:diff --git a/packages/core/src/repowise/core/generation/editor_files/data.py b/packages/core/src/repowise/core/generation/editor_files/data.pyindex 754190cfd..1a21bc1c4 100644--- a/packages/core/src/repowise/core/generation/editor_files/data.py+++ b/packages/core/src/repowise/core/generation/editor_files/data.py@@ -40,6 +40,14 @@ class HotspotFile:churn_percentile: floatcommit_count_90d: intowner: str | None+ # Bug-fix history for the same file. ``fix_count`` is the windowed+ # production-code fix count (``GitMetadata.prior_defect_count``), and+ # ``last_fix_age`` is pre-rendered ("2 weeks ago") because a count with no+ # recency reads as an accusation about 2019. ``bug_magnet`` is only ever set+ # alongside an age, per the recency contract in ``types/health.ts``.+ fix_count: int = 0+ bug_magnet: bool = False+ last_fix_age: str | None = None@dataclass(frozen=True)@@ -79,7 +87,6 @@ class CodeHealthBlock:performance_skipped_files: int = 0performance_unsupported_languages: list[tuple[str, int]] = field(default_factory=list)critical_biomarkers: list[dict] = field(default_factory=list)- untested_hotspots: list[dict] = field(default_factory=list)@dataclass(frozen=True)diff --git a/packages/core/src/repowise/core/generation/editor_files/fetcher.py b/packages/core/src/repowise/core/generation/editor_files/fetcher.pyindex a58f6591f..bc30ac12a 100644--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py@@ -172,33 +172,69 @@ class EditorFileDataFetcher:return [row[0] for row in result.all()]async def _get_hotspots(self) -> list[HotspotFile]:- """Top hotspot files by churn_percentile with owner info."""+ """Top attention-worthy files: bug-fix history first, churn as fallback.++ Two populations, deliberately unioned rather than re-sorted. Ranking by+ fix mass inside ``is_hotspot`` alone would still be churn-gated: a file+ fixed four times last month that simply is not busy could never appear.+ So the filter admits bug magnets too, and the order puts fix evidence+ ahead of commit counts, because the section's own instruction is to call+ ``get_risk`` (a defect tool) before editing.++ Churn stays the fallback and the tie-break. A repo whose commit messages+ do not follow a fix convention has zero fix mass everywhere, and this+ degrades to exactly the churn ordering it had before rather than to an+ empty section.++ The fix columns come from the same row the churn columns already did, so+ this is the same single query it was.+ """result = await self._session.execute(select(GitMetadata.file_path,GitMetadata.churn_percentile,GitMetadata.commit_count_90d,GitMetadata.primary_owner_name,+ GitMetadata.prior_defect_count,+ GitMetadata.bug_magnet,+ GitMetadata.last_fix_at,).where(GitMetadata.repository_id == self._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(),GitMetadata.file_path.asc(), # deterministic tie-break).limit(_MAX_HOTSPOTS))- return [- HotspotFile(- path=row[0],- churn_percentile=round(row[1] * 100, 1), # stored as 0.0-1.0- commit_count_90d=row[2],- owner=row[3],+ now = datetime.now(UTC)+ hotspots: list[HotspotFile] = []+ for row in result.all():+ last_fix_at = row[6]+ age: str | None = None+ if isinstance(last_fix_at, datetime):+ # SQLite hands these back naive; re-attach UTC before subtracting+ # or the delta is wrong by the local offset (see signals.iso_utc).+ moment = last_fix_at if last_fix_at.tzinfo else last_fix_at.replace(tzinfo=UTC)+ age = _humanize_age(max(0, (now - moment).days))+ hotspots.append(+ HotspotFile(+ path=row[0],+ churn_percentile=round(row[1] * 100, 1), # stored as 0.0-1.0+ commit_count_90d=row[2],+ owner=row[3],+ fix_count=row[4] or 0,+ # Never claim "bug magnet" without an age to anchor it.+ bug_magnet=bool(row[5]) and age is not None,+ last_fix_age=age,+ ))- for row in result.all()- ]+ return hotspotsasync def _get_decisions(self) -> list[DecisionSummary]:"""Active decision records, least-stale first."""@@ -387,7 +423,6 @@ class EditorFileDataFetcher:performance_skipped_files=perf_coverage.skipped_files,performance_unsupported_languages=perf_coverage.unsupported_languages,critical_biomarkers=critical,- untested_hotspots=[], # Phase 2 fills this from coverage data)async def _get_kg_data(@@ -483,6 +518,24 @@ def _get_head_short_sha(repo_path: Path) -> str:return ""+def _humanize_age(days: int) -> str:+ """Render an age as "2 weeks ago" / "3 months ago", never as a bare count.++ Twin of the pre-edit hook's ``decision_inject._humanize_age``, which states+ why the two are not shared: that module is on a sub-100ms budget and cannot+ afford to import ``repowise.core``. Keep the phrasing in step by hand.+ """+ if days <= 1:+ return "today" if days <= 0 else "yesterday"+ if days < 14:+ return f"{days} days ago"+ if days < 60:+ weeks = round(days / 7)+ return f"{weeks} week{'' if weeks == 1 else 's'} ago"+ months = round(days / 30)+ return f"{months} month{'' if months == 1 else 's'} ago"++def _extract_sentences(text: str, max_sentences: int) -> str:"""Return up to *max_sentences* prose sentences from the start of *text*.diff --git a/packages/core/src/repowise/core/generation/templates/agents_md.j2 b/packages/core/src/repowise/core/generation/templates/agents_md.j2index 34f91b6d4..be3efa45f 100644--- a/packages/core/src/repowise/core/generation/templates/agents_md.j2+++ b/packages/core/src/repowise/core/generation/templates/agents_md.j2@@ -45,9 +45,9 @@ The MCP tools below serve pre-verified docs, symbols, history, and health from t{% endif %}{% if data.hotspots %}-### Hotspots (high churn — check `get_risk` before editing)+### Files that need care (bug-fix history first, then churn — check `get_risk` before editing){% for h in data.hotspots %}-- `{{ h.path }}` — {{ h.commit_count_90d }} commits/90d ({{ h.churn_percentile }}th %ile)+- `{{ h.path }}` — {% if h.fix_count and h.last_fix_age %}{{ h.fix_count }} bug fix{{ 'es' if h.fix_count != 1 else '' }}, last fix {{ h.last_fix_age }}{% if h.bug_magnet %} (bug magnet){% endif %}; {% endif %}{{ h.commit_count_90d }} commits/90d{% endfor %}{% endif %}{% if data.code_health %}@@ -61,13 +61,6 @@ Critical files:- `{{ b.path }}` — {{ b.summary }}{% endfor %}{% endif %}-{% if data.code_health.untested_hotspots %}--Untested hotspots:-{% for h in data.code_health.untested_hotspots %}-- `{{ h.path }}` — {{ h.dependents }} dependents, {{ h.coverage_pct }}% coverage, {{ h.commits_90d }} commits/90d-{% endfor %}-{% endif %}{% endif %}{% if data.decisions %}diff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2index 75909c529..bd8bc86fd 100644--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2@@ -45,9 +45,9 @@ The MCP tools below serve pre-verified docs, symbols, history, and health from t{% endif %}{% if data.hotspots %}-### Hotspots (high churn — check `get_risk` before editing)+### Files that need care (bug-fix history first, then churn — check `get_risk` before editing){% for h in data.hotspots %}-- `{{ h.path }}` — {{ h.commit_count_90d }} commits/90d ({{ h.churn_percentile }}th %ile)+- `{{ h.path }}` — {% if h.fix_count and h.last_fix_age %}{{ h.fix_count }} bug fix{{ 'es' if h.fix_count != 1 else '' }}, last fix {{ h.last_fix_age }}{% if h.bug_magnet %} (bug magnet){% endif %}; {% endif %}{{ h.commit_count_90d }} commits/90d{% endfor %}{% endif %}{% if data.code_health %}@@ -61,13 +61,6 @@ Critical files:- `{{ b.path }}` — {{ b.summary }}{% endfor %}{% endif %}-{% if data.code_health.untested_hotspots %}--Untested hotspots:-{% for h in data.code_health.untested_hotspots %}-- `{{ h.path }}` — {{ h.dependents }} dependents, {{ h.coverage_pct }}% coverage, {{ h.commits_90d }} commits/90d-{% endfor %}-{% endif %}{% endif %}{% if data.decisions %}diff --git a/tests/unit/generation/test_editor_file_base.py b/tests/unit/generation/test_editor_file_base.pyindex f0842abb8..1563df12c 100644--- a/tests/unit/generation/test_editor_file_base.py+++ b/tests/unit/generation/test_editor_file_base.py@@ -5,7 +5,11 @@ from __future__ import annotationsimport pytestfrom repowise.core.generation.editor_files.base import BaseEditorFileGenerator-from repowise.core.generation.editor_files.data import CodeHealthBlock, EditorFileData+from repowise.core.generation.editor_files.data import (+ CodeHealthBlock,+ EditorFileData,+ HotspotFile,+)# ---------------------------------------------------------------------------# Minimal concrete subclass for testing@@ -230,3 +234,73 @@ def test_render_full_matches_write_output(gen, tmp_path):gen.write(tmp_path, data)written = (tmp_path / "TEST.md").read_text(encoding="utf-8")assert preview == written+++# ---------------------------------------------------------------------------+# Attention-list section: fix history leads, churn is the fallback+# ---------------------------------------------------------------------------+++def _hotspot(path: str, **kw) -> HotspotFile:+ base = {"churn_percentile": 99.0, "commit_count_90d": 28, "owner": None}+ return HotspotFile(path=path, **{**base, **kw})+++def test_render_hotspot_section_no_longer_claims_to_rank_by_churn(gen):+ # The header used to read "high churn" while telling the agent to call+ # get_risk, a defect tool. The list and its own instruction disagreed.+ import dataclasses++ data = dataclasses.replace(_minimal_data(), hotspots=[_hotspot("src/a.py")])+ result = gen.render(data)+ assert "high churn" not in result+ assert "get_risk" in result+++def test_render_hotspot_row_leads_with_fix_history(gen):+ import dataclasses++ data = dataclasses.replace(+ _minimal_data(),+ hotspots=[_hotspot("src/a.py", fix_count=5, bug_magnet=True, last_fix_age="2 weeks ago")],+ )+ result = gen.render(data)+ assert "5 bug fixes, last fix 2 weeks ago (bug magnet); 28 commits/90d" in result+++def test_render_hotspot_row_singularizes_one_fix(gen):+ import dataclasses++ data = dataclasses.replace(+ _minimal_data(),+ hotspots=[_hotspot("src/a.py", fix_count=1, last_fix_age="yesterday")],+ )+ result = gen.render(data)+ assert "1 bug fix, last fix yesterday" in result+ assert "1 bug fixes" not in result+++def test_render_hotspot_row_falls_back_to_churn_without_fix_history(gen):+ # A repo whose commit messages carry no fix convention has zero fix mass+ # everywhere. The section must still render, on churn alone.+ import dataclasses++ data = dataclasses.replace(_minimal_data(), hotspots=[_hotspot("src/a.py")])+ result = gen.render(data)+ assert "- `src/a.py` — 28 commits/90d" in result+ assert "bug fix" not in result+++def test_render_never_shows_a_fix_count_without_its_age(gen):+ # The recency contract: a count with no timestamp reads as an accusation+ # about 2019, so an unanchored count degrades to the churn row.+ import dataclasses++ data = dataclasses.replace(+ _minimal_data(),+ hotspots=[_hotspot("src/a.py", fix_count=9, bug_magnet=True, last_fix_age=None)],+ )+ result = gen.render(data)+ assert "9 bug fixes" not in result+ assert "bug magnet" not in result+ assert "28 commits/90d" in resultdiff --git a/tests/unit/generation/test_editor_file_fetcher.py b/tests/unit/generation/test_editor_file_fetcher.pyindex 3a03adc7a..8b79836d9 100644--- a/tests/unit/generation/test_editor_file_fetcher.py+++ b/tests/unit/generation/test_editor_file_fetcher.py@@ -2,7 +2,7 @@from __future__ import annotations-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltaimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine@@ -100,7 +100,17 @@ async def _add_page(session, repo_id, page_id, page_type, target_path, content):async def _add_git_meta(- session, repo_id, file_path, *, is_hotspot=False, churn_pct=0.5, owner=None+ session,+ repo_id,+ file_path,+ *,+ is_hotspot=False,+ churn_pct=0.5,+ owner=None,+ prior_defect_count=0,+ fix_mass=0.0,+ bug_magnet=False,+ last_fix_at=None,):gm = GitMetadata(repository_id=repo_id,@@ -109,6 +119,10 @@ async def _add_git_meta(churn_percentile=churn_pct,commit_count_90d=10,primary_owner_name=owner,+ prior_defect_count=prior_defect_count,+ fix_mass=fix_mass,+ bug_magnet=bug_magnet,+ last_fix_at=last_fix_at,)session.add(gm)await session.flush()@@ -237,6 +251,68 @@ async def test_fetch_hotspots(session, repo, tmp_path):assert data.hotspots[0].churn_percentile == 95.0 # stored 0.95 → displayed 95.0+async def test_fetch_hotspots_admits_bug_magnets_that_are_not_churn_hotspots(+ session, repo, tmp_path+):+ # The filter used to be is_hotspot-only, so a file fixed four times last+ # month that simply is not busy could never appear no matter how it ranked.+ await _add_git_meta(session, repo.id, "src/busy.py", is_hotspot=True, churn_pct=0.99)+ await _add_git_meta(+ session,+ repo.id,+ "src/broken.py",+ is_hotspot=False,+ churn_pct=0.10,+ bug_magnet=True,+ fix_mass=9.0,+ prior_defect_count=4,+ last_fix_at=datetime.now(UTC) - timedelta(days=14),+ )+ await session.commit()++ data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()++ paths = [h.path for h in data.hotspots]+ assert paths == ["src/broken.py", "src/busy.py"] # fix evidence leads+ assert data.hotspots[0].fix_count == 4+ assert data.hotspots[0].bug_magnet is True+ assert data.hotspots[0].last_fix_age == "2 weeks ago"+++async def test_fetch_hotspots_falls_back_to_churn_order_without_fix_data(session, repo, tmp_path):+ # A repo with no fix convention has zero fix mass everywhere; the ordering+ # must degrade to exactly the churn ranking it had before, not to nothing.+ await _add_git_meta(session, repo.id, "src/low.py", is_hotspot=True, churn_pct=0.20)+ await _add_git_meta(session, repo.id, "src/high.py", is_hotspot=True, churn_pct=0.90)+ await session.commit()++ data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()++ assert [h.path for h in data.hotspots] == ["src/high.py", "src/low.py"]+ assert all(h.fix_count == 0 and h.last_fix_age is None for h in data.hotspots)+++async def test_fetch_hotspots_drops_the_magnet_flag_when_recency_is_unknown(+ session, repo, tmp_path+):+ # bug_magnet with a NULL last_fix_at would render an unanchored accusation.+ await _add_git_meta(+ session,+ repo.id,+ "src/a.py",+ is_hotspot=True,+ bug_magnet=True,+ prior_defect_count=9,+ last_fix_at=None,+ )+ await session.commit()++ data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()++ assert data.hotspots[0].bug_magnet is False+ assert data.hotspots[0].last_fix_age is None++async def test_fetch_active_decisions_only(session, repo, tmp_path):await _add_decision(session, repo.id, "Use JWT", status="active")await _add_decision(session, repo.id, "Old choice", status="deprecated")