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
feat(health): attribute bug fixes to symbols and flag bug magnets (#940)
Raghav Chamadiyaad0a32fe065f
diff --git a/packages/core/src/repowise/core/analysis/health/fix_attribution.py b/packages/core/src/repowise/core/analysis/health/fix_attribution.pynew file mode 100644index 000000000..b6652598c--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/fix_attribution.py@@ -0,0 +1,194 @@+"""Which symbols a bug fix landed in, and how much of a file's fix mass is recent.++``fix_events`` records the old-side line ranges each fix replaced;+``wiki_symbols`` records where every symbol starts and ends. Intersecting the+two turns "this file was fixed 5 times" into "``persist_graph_edges`` was fixed+5 times", which is the granularity an agent about to edit that function can act+on.++State-free on purpose, like :mod:`signals` and :mod:`trends`: callers pass rows+they already loaded and get plain values back, so the join logic is unit-testable+without a database.++Two honesty rules run through this module.++**Line numbers drift.** Symbol ranges are current-tree; the fix's ranges are from+its own parent commit. Any commit to the file in between can shift them, so an+attribution is only ``exact`` when nothing has touched the file since the fix.+Everything else is ``approximate`` and the surfaces are expected to hedge. This+will be most rows on an active file, which is the truth rather than a defect: the+alternative is re-parsing every historical revision.++**Recency is applied here, not at write time.** Rows are stored undecayed with+their ``committed_at`` (see :class:`~persistence.models.FixEvent`), so the+half-life below is a read-time constant. Changing it re-runs the rollup, never a+reindex.+"""++from __future__ import annotations++from dataclasses import dataclass+from datetime import datetime++__all__ = [+ "BUG_MAGNET_MASS",+ "FIX_HALF_LIFE_DAYS",+ "FixRollup",+ "SymbolSpan",+ "attribute_ranges",+ "decayed_mass",+ "roll_up_file",+]++# G1.4 swept 60 / 90 / 180-day half-lives against the 21-repo calibration corpus.+# Decay was the only lever that moved the ``prior_defect`` coefficient at all+# (0.15 undecayed -> 0.23), and 90d and 180d tied inside noise; 90d is the+# plan's candidate and the tighter of the two, so a file fixed three times last+# month outranks one fixed three times six months ago by ~4x rather than ~2x.+FIX_HALF_LIFE_DAYS = 90.0++# "Bug magnet" means the file carries at least the weight of three fixes landed+# today. Three is the same trigger the PR bot already uses for prior defects, so+# the two surfaces agree on what counts as a lot; decay is what stops a file+# whose fixes all sit at the window's trailing edge from flagging identically to+# one fixed three times this month.+#+# Read the threshold with the decay in mind: because only a same-day fix is+# worth a full 1.0, three real fixes spread over a couple of weeks land near+# 2.9 and do NOT flag. In practice the flag needs four recent fixes, or three+# very recent ones. That is deliberately the conservative end — the flag exists+# to interrupt someone mid-edit, so it should be rare enough to be worth reading.+BUG_MAGNET_MASS = 3.0++_DAY_SECONDS = 86400.0+++@dataclass(frozen=True)+class SymbolSpan:+ """A symbol's current line span. Mirrors the ``wiki_symbols`` columns used."""++ symbol_id: str+ start_line: int+ end_line: int+++@dataclass(frozen=True)+class FixRollup:+ """A file's fix history collapsed to what the surfaces read.++ ``fix_mass`` is carried alongside ``bug_magnet`` so the flag is auditable:+ a bare boolean cannot be argued with, and the number behind it is one float.+ """++ fix_count: int+ fix_mass: float+ bug_magnet: bool+ last_fix_at: datetime | None+ symbol_counts: dict[str, int]+++def attribute_ranges(+ old_ranges: list[tuple[int, int]] | list[list[int]],+ symbols: list[SymbolSpan],+) -> list[str]:+ """Symbol ids whose current span overlaps any of *old_ranges*.++ A range that cuts across a class and two of its methods attributes to the+ methods only: any selected symbol that strictly contains another selected+ symbol is dropped. That keeps per-symbol counts from double-counting one+ fix at every level of nesting, and it is language-agnostic in a way that+ filtering on ``kind`` would not be.++ Returns ids in file order. Empty when the fix was a pure insertion (no old+ side to intersect) or the file has no parsed symbols.+ """+ if not old_ranges or not symbols:+ return []++ hits: list[SymbolSpan] = []+ for sym in symbols:+ if sym.start_line <= 0 or sym.end_line < sym.start_line:+ continue+ if any(sym.start_line <= int(hi) and int(lo) <= sym.end_line for lo, hi in old_ranges):+ hits.append(sym)++ leaves = [+ sym+ for sym in hits+ if not any(+ other is not sym+ and sym.start_line <= other.start_line+ and other.end_line <= sym.end_line+ and (other.end_line - other.start_line) < (sym.end_line - sym.start_line)+ for other in hits+ )+ ]+ leaves.sort(key=lambda s: (s.start_line, s.end_line))+ return [s.symbol_id for s in leaves]+++def attribution_kind(+ symbol_ids: list[str],+ fixed_at: datetime | None,+ file_last_commit_at: datetime | None,+) -> str:+ """``exact`` | ``approximate`` | ``none`` for one attributed event.++ ``exact`` requires that nothing has touched the file since the fix, which is+ the only case where the current symbol spans are the spans the fix saw. On a+ file that has changed since, the attribution is still the best available+ (symbols rarely move far relative to their own size) but it is reported as+ ``approximate`` so nothing downstream states it as fact.+ """+ if not symbol_ids:+ return "none"+ if fixed_at is None or file_last_commit_at is None:+ return "approximate"+ return "exact" if fixed_at >= file_last_commit_at else "approximate"+++def decayed_mass(fixed_at: datetime | None, as_of: datetime) -> float:+ """Weight of one fix at *as_of*: 1.0 the day it landed, 0.5 a half-life later.++ A fix dated after *as_of* (clock skew in the committer's timezone) is worth+ a fresh fix, never more.+ """+ if fixed_at is None:+ return 0.0+ age_days = (as_of - fixed_at).total_seconds() / _DAY_SECONDS+ if age_days <= 0:+ return 1.0+ return 0.5 ** (age_days / FIX_HALF_LIFE_DAYS)+++def roll_up_file(+ events: list[tuple[datetime | None, list[str]]],+ as_of: datetime,+) -> FixRollup:+ """Collapse one file's fix events into its :class:`FixRollup`.++ *events* is ``(committed_at, symbol_ids)`` per event, already filtered to the+ fixes that count (production-code fixes inside the defect window). Callers+ do the filtering because the same rollup shape should not have to know the+ shape vocabulary.+ """+ mass = 0.0+ last: datetime | None = None+ counts: dict[str, int] = {}++ for fixed_at, symbol_ids in events:+ mass += decayed_mass(fixed_at, as_of)+ if fixed_at is not None and (last is None or fixed_at > last):+ last = fixed_at+ for symbol_id in symbol_ids:+ counts[symbol_id] = counts.get(symbol_id, 0) + 1++ return FixRollup(+ fix_count=len(events),+ fix_mass=round(mass, 4),+ bug_magnet=mass >= BUG_MAGNET_MASS,+ last_fix_at=last,+ # Descending count, then symbol id, so the stored order is stable across+ # runs and a surface that shows "top 3" always shows the same three.+ symbol_counts=dict(sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))),+ )diff --git a/packages/core/src/repowise/core/analysis/health/signals.py b/packages/core/src/repowise/core/analysis/health/signals.pyindex b8cb8e25b..d934a374e 100644--- a/packages/core/src/repowise/core/analysis/health/signals.py+++ b/packages/core/src/repowise/core/analysis/health/signals.py@@ -19,9 +19,15 @@ graph node.from __future__ import annotations+import jsonfrom dataclasses import asdict, dataclass+from datetime import datetimefrom typing import Protocol+# How many symbols the per-file fix breakdown carries. Enough to say "mostly+# these", short enough to sit inside an MCP response without a budget argument.+_TOP_FIX_SYMBOLS = 5+class GitMetaLike(Protocol):"""The git-metadata fields the signals view reads (duck-typed).@@ -40,6 +46,9 @@ class GitMetaLike(Protocol):primary_owner_commit_pct: float | Nonerecent_owner_name: str | Nonerecent_owner_commit_pct: float | None+ bug_magnet: bool | None+ last_fix_at: datetime | None+ fix_symbol_counts_json: str | None@dataclass@@ -67,6 +76,14 @@ class FileSignals:# Topology — how connected it is in the dependency graph.in_degree: int | Noneout_degree: int | None+ # Defect history — how often it gets bug-fixed, and where in the file.+ # ``bug_magnet`` is the decayed fix mass past its trigger, ``last_fix_at``+ # the recency that must accompany it in any copy, and ``fix_symbol_counts``+ # the top few symbols the fixes landed in. See+ # :mod:`~analysis.health.fix_attribution`.+ bug_magnet: bool | None+ last_fix_at: str | None+ fix_symbol_counts: dict[str, int] | None@propertydef has_any(self) -> bool:@@ -90,6 +107,30 @@ def _entropy_pct(raw: float | None) -> float | None:return round(raw * 100.0, 1)+def _iso(value: datetime | None) -> str | None:+ return value.isoformat() if isinstance(value, datetime) else None+++def _top_fix_symbols(raw: str | None) -> dict[str, int] | None:+ """Parse the stored symbol->fix-count map, keeping only the top few.++ The stored map is written in descending-count order, so "top few" is a+ slice. Capping here rather than at the call sites keeps every consumer —+ drawer, file page, MCP — on the same budget: this rides inside MCP+ responses, and a 40-symbol file would otherwise spend a response on a tail+ nobody reads.+ """+ if not raw:+ return None+ try:+ counts = json.loads(raw)+ except (TypeError, ValueError):+ return None+ if not isinstance(counts, dict) or not counts:+ return None+ return {str(k): int(v) for k, v in list(counts.items())[:_TOP_FIX_SYMBOLS]}++def file_signals(git_meta: GitMetaLike | None,degrees: dict[str, int] | None,@@ -116,4 +157,12 @@ def file_signals(recent_owner_commit_pct=g.recent_owner_commit_pct if g else None,in_degree=degrees["in_degree"] if degrees else None,out_degree=degrees["out_degree"] if degrees else None,+ bug_magnet=getattr(g, "bug_magnet", None) if g else None,+ # ISO string, not a datetime: this dataclass goes through ``asdict`` into+ # MCP responses, which have to be JSON-serializable without a custom+ # encoder.+ last_fix_at=_iso(getattr(g, "last_fix_at", None)) if g else None,+ fix_symbol_counts=_top_fix_symbols(getattr(g, "fix_symbol_counts_json", None))+ if g+ else None,)diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 40105e15c..e5156b00b 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -451,6 +451,19 @@ class GitMetadata(Base):prior_defect_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)prior_defect_raw_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ # Bug-magnet rollup over this file's ``fix_events``, recomputed after every+ # index and update. ``fix_mass`` is ``prior_defect_count`` with a 90-day+ # half-life applied (analysis.health.fix_attribution), so a file whose fixes+ # all sit at the window's trailing edge stops looking like one fixed three+ # times this month; ``bug_magnet`` is that mass past the three-fresh-fixes+ # trigger. ``fix_symbol_counts_json`` maps ``WikiSymbol.symbol_id`` to how+ # many of those fixes landed in it. The mass is stored beside the flag on+ # purpose: a bare boolean cannot be argued with.+ fix_mass: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+ bug_magnet: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ last_fix_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ fix_symbol_counts_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")+# Temporal hotspot score: exponentially time-decayed churn signaltemporal_hotspot_score: Mapped[float | None] = mapped_column(Float, nullable=True, default=0.0)@@ -620,6 +633,16 @@ class FixEvent(Base):# Per-bucket changed-line counts from the fix taxonomy. Empty until Phase 5.taxonomy_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")+ # ``WikiSymbol.symbol_id``s whose CURRENT line span overlaps this row's+ # ``old_ranges_json``, so a file-level fix history can be read per symbol.+ # ``attribution`` says how much to trust the join: ``exact`` only when+ # nothing has touched the file since the fix (so the current spans are the+ # spans the fix saw), ``approximate`` when lines may have shifted underneath,+ # ``none`` when there was nothing to attribute — a pure insertion, an+ # unparsed file. See analysis.health.fix_attribution.+ symbol_ids_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ attribution: Mapped[str] = mapped_column(String(16), nullable=False, default="none")+committed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)created_at: Mapped[datetime] = mapped_column(diff --git a/packages/core/src/repowise/core/pipeline/fix_rollups.py b/packages/core/src/repowise/core/pipeline/fix_rollups.pynew file mode 100644index 000000000..67cee98da--- /dev/null+++ b/packages/core/src/repowise/core/pipeline/fix_rollups.py@@ -0,0 +1,158 @@+"""Attribute persisted fix events to symbols and roll them up onto git metadata.++The one impure half of the fix-history feature: :mod:`analysis.health.fix_attribution`+does the arithmetic, this module does the reads and writes. It runs after both+``fix_events`` and ``wiki_symbols`` are persisted — a full index (end of+``persist_git``) and an update (end of ``persist_incremental_fix_events``) — and+recomputes the whole repo's rollups from the stored rows each time.++Recomputing everything rather than patching the files an update touched is+deliberate. Decay means a rollup goes stale on its own with nothing changing in+the file, so "only files this update touched" would leave the rest of the repo+frozen at whatever mass it had when it was last edited. The pass is two indexed+queries and some arithmetic over a windowed table (~1k rows on this repo), which+is far cheaper than the drift would be to explain.+"""++from __future__ import annotations++import json+from collections import defaultdict+from datetime import UTC, datetime+from typing import Any++import structlog++from repowise.core.analysis.health.fix_attribution import (+ SymbolSpan,+ attribute_ranges,+ attribution_kind,+ roll_up_file,+)++logger = structlog.get_logger(__name__)++__all__ = ["apply_fix_rollups"]++# Only fixes that changed production code count toward the magnet signal, the+# same filter #931 put on ``prior_defect_count`` — so the two numbers can never+# disagree about what a bug fix is.+_COUNTED_SHAPE = "code_fix"+++async def apply_fix_rollups(session: Any, repo_id: str) -> int:+ """Recompute symbol attribution + ``GitMetadata`` fix rollups for *repo_id*.++ Returns the number of files whose rollup was written. Failure-isolated by+ the caller, like every other post-persist refresh: a rollup this run could+ not compute leaves the previous values in place rather than zeroing a+ surface.+ """+ from sqlalchemy import select++ from repowise.core.persistence.models import FixEvent, GitMetadata, WikiSymbol++ events = (+ (await session.execute(select(FixEvent).where(FixEvent.repository_id == repo_id)))+ .scalars()+ .all()+ )+ if not events:+ return 0++ paths = {e.file_path for e in events}++ symbols_by_path: dict[str, list[SymbolSpan]] = defaultdict(list)+ for symbol_id, file_path, start_line, end_line in (+ await session.execute(+ select(+ WikiSymbol.symbol_id,+ WikiSymbol.file_path,+ WikiSymbol.start_line,+ WikiSymbol.end_line,+ ).where(WikiSymbol.repository_id == repo_id, WikiSymbol.file_path.in_(paths))+ )+ ).all():+ symbols_by_path[file_path].append(+ SymbolSpan(symbol_id=symbol_id, start_line=start_line or 0, end_line=end_line or 0)+ )++ meta_rows = (+ (+ await session.execute(+ select(GitMetadata).where(+ GitMetadata.repository_id == repo_id, GitMetadata.file_path.in_(paths)+ )+ )+ )+ .scalars()+ .all()+ )+ meta_by_path = {m.file_path: m for m in meta_rows}++ as_of = _as_of(events, meta_rows)++ # Pass 1: attribute each event to symbols, on the row itself.+ counted: dict[str, list[tuple[datetime | None, list[str]]]] = defaultdict(list)+ for event in events:+ symbol_ids = attribute_ranges(_old_ranges(event), symbols_by_path.get(event.file_path, []))+ meta = meta_by_path.get(event.file_path)+ event.symbol_ids_json = json.dumps(symbol_ids)+ event.attribution = attribution_kind(+ symbol_ids,+ _aware(event.committed_at),+ _aware(getattr(meta, "last_commit_at", None)),+ )+ if event.shape_kind == _COUNTED_SHAPE:+ counted[event.file_path].append((_aware(event.committed_at), symbol_ids))++ # Pass 2: roll the counted events up onto git metadata. Files with events but+ # no metadata row are skipped rather than created: git_metadata's key set is+ # owned by the git indexer.+ written = 0+ for file_path, meta in meta_by_path.items():+ rollup = roll_up_file(counted.get(file_path, []), as_of)+ meta.fix_mass = rollup.fix_mass+ meta.bug_magnet = rollup.bug_magnet+ meta.last_fix_at = rollup.last_fix_at+ meta.fix_symbol_counts_json = json.dumps(rollup.symbol_counts)+ written += 1++ await session.flush()+ logger.debug(+ "fix_rollups_applied",+ repo_id=repo_id,+ events=len(events),+ files=written,+ magnets=sum(1 for m in meta_by_path.values() if m.bug_magnet),+ )+ return written+++def _old_ranges(event: Any) -> list[list[int]]:+ try:+ return json.loads(event.old_ranges_json or "[]")+ except (TypeError, ValueError):+ return []+++def _aware(value: datetime | None) -> datetime | None:+ """SQLite hands back naive datetimes; the arithmetic needs them comparable."""+ if value is None:+ return None+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)+++def _as_of(events: list[Any], meta_rows: list[Any]) -> datetime:+ """The "now" decay is measured from: the repo's newest commit.++ Not wall-clock time. Anchoring to the repo means two indexes of the same+ checkout produce the same rollups, which is what the update-parity check+ asserts, and it keeps a dormant repo's mass decaying rather than freezing at+ whatever it was when work stopped — the newest commit is genuinely how old+ that repo's newest code is.+ """+ stamps = [_aware(m.last_commit_at) for m in meta_rows]+ stamps += [_aware(e.committed_at) for e in events]+ known = [s for s in stamps if s is not None]+ return max(known) if known else datetime.now(UTC)diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex 069c1fc42..ae21149e8 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -625,6 +625,15 @@ async def persist_incremental_fix_events(session: Any, repo_id: str, indexer: Anif tracked:await prune_fix_events_for_missing_paths(session, repo_id, tracked)+ # Recompute over the whole stored window, not just the rows this update+ # appended: decay ages every file's mass whether or not the file changed.+ try:+ from repowise.core.pipeline.fix_rollups import apply_fix_rollups++ await apply_fix_rollups(session, repo_id)+ except Exception as exc:+ logger.debug("fix_rollups_failed", error=str(exc))+async def refresh_external_systems(session: Any,diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex c7c375497..4bd2320b7 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -699,6 +699,16 @@ async def persist_git(result: Any, session: Any, repo_id: str) -> None:await prune_fix_events_before(session, repo_id, datetime.fromtimestamp(oldest_ts, tz=UTC))+ # Symbol attribution + bug-magnet rollups, over the rows just written.+ # Failure-isolated: a rollup that cannot be computed leaves the previous+ # values in place rather than blanking a surface mid-index.+ try:+ from repowise.core.pipeline.fix_rollups import apply_fix_rollups++ await apply_fix_rollups(session, repo_id)+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("fix_rollups_failed", repo_id=repo_id, error=str(exc))+# Whole-history totals (true age / commit / contributor counts) also ride on# the summary — stamp them on the Repository row so the stats page reads them# instead of deriving them from the bounded ``git_commits`` sample (#730).diff --git a/packages/server/src/repowise/server/routers/code_health/serializers.py b/packages/server/src/repowise/server/routers/code_health/serializers.pyindex 06d114ec5..929ddd9d8 100644--- a/packages/server/src/repowise/server/routers/code_health/serializers.py+++ b/packages/server/src/repowise/server/routers/code_health/serializers.py@@ -145,6 +145,9 @@ def _file_signals_to_dict(s: FileSignals) -> dict:"recent_owner_commit_pct": s.recent_owner_commit_pct,"in_degree": s.in_degree,"out_degree": s.out_degree,+ "bug_magnet": s.bug_magnet,+ "last_fix_at": s.last_fix_at,+ "fix_symbol_counts": s.fix_symbol_counts,}diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsindex ebadaa938..6e2896a71 100644--- a/packages/types/src/health.ts+++ b/packages/types/src/health.ts@@ -397,6 +397,14 @@ export interface FileSignals {// Topology — how connected it is in the dependency graph.in_degree: number | null;out_degree: number | null;+ // Defect history — how often this file gets bug-fixed, and where in it.+ // `bug_magnet` is the decayed fix mass past its trigger, so it is a recency+ // claim: any copy that shows it must show `last_fix_at` too.+ // `fix_symbol_counts` maps symbol_id to how many recent fixes landed in it,+ // top few only, already sorted by count.+ bug_magnet: boolean | null;+ last_fix_at: string | null;+ fix_symbol_counts: Record<string, number> | null;}/* ------------------------------------------------------------------ *diff --git a/packages/ui/__tests__/health/file-signals-panel.test.tsx b/packages/ui/__tests__/health/file-signals-panel.test.tsxindex 52be8f732..8eb3b95eb 100644--- a/packages/ui/__tests__/health/file-signals-panel.test.tsx+++ b/packages/ui/__tests__/health/file-signals-panel.test.tsx@@ -17,6 +17,9 @@ function sig(partial: Partial<FileSignals>): FileSignals {recent_owner_commit_pct: null,in_degree: null,out_degree: null,+ bug_magnet: null,+ last_fix_at: null,+ fix_symbol_counts: null,...partial,};}diff --git a/tests/unit/health/test_fix_attribution.py b/tests/unit/health/test_fix_attribution.pynew file mode 100644index 000000000..8e6f0f72b--- /dev/null+++ b/tests/unit/health/test_fix_attribution.py@@ -0,0 +1,122 @@+"""Tests for ``health/fix_attribution.py`` — symbols per fix, and decayed mass.++The two claims this module makes to the surfaces are that a fix lands in the+narrowest symbol it touched, and that a file's "bug magnet" flag is about recent+fixes rather than a lifetime tally. Both are asserted here; both are the reason+the surfaces are allowed to say "mostly this function" and "last fixed N weeks+ago" at all.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta++from repowise.core.analysis.health.fix_attribution import (+ BUG_MAGNET_MASS,+ FIX_HALF_LIFE_DAYS,+ SymbolSpan,+ attribute_ranges,+ attribution_kind,+ decayed_mass,+ roll_up_file,+)++NOW = datetime(2026, 7, 1, tzinfo=UTC)+++def _spans() -> list[SymbolSpan]:+ return [+ SymbolSpan("m.py::Store", 1, 60),+ SymbolSpan("m.py::Store.save", 10, 25),+ SymbolSpan("m.py::Store.load", 30, 45),+ SymbolSpan("m.py::helper", 70, 80),+ ]+++def test_range_attributes_to_the_narrowest_containing_symbol():+ # Lines 12-14 sit inside both the class and one of its methods.+ assert attribute_ranges([(12, 14)], _spans()) == ["m.py::Store.save"]+++def test_range_spanning_two_methods_attributes_to_both_not_the_class():+ assert attribute_ranges([(20, 35)], _spans()) == [+ "m.py::Store.save",+ "m.py::Store.load",+ ]+++def test_range_in_class_body_outside_any_method_keeps_the_class():+ assert attribute_ranges([(2, 5)], _spans()) == ["m.py::Store"]+++def test_disjoint_ranges_union_their_symbols_in_file_order():+ assert attribute_ranges([(75, 76), (11, 12)], _spans()) == [+ "m.py::Store.save",+ "m.py::helper",+ ]+++def test_pure_insertion_and_unparsed_file_attribute_to_nothing():+ assert attribute_ranges([], _spans()) == []+ assert attribute_ranges([(1, 5)], []) == []+++def test_range_between_symbols_attributes_to_nothing():+ assert attribute_ranges([(62, 66)], _spans()) == []+++def test_degenerate_symbol_spans_are_skipped():+ bad = [SymbolSpan("m.py::a", 0, 0), SymbolSpan("m.py::b", 9, 3)]+ assert attribute_ranges([(1, 100)], bad) == []+++def test_attribution_is_exact_only_when_nothing_touched_the_file_since():+ fixed = datetime(2026, 6, 1, tzinfo=UTC)+ assert attribution_kind(["s"], fixed, fixed) == "exact"+ assert attribution_kind(["s"], fixed, fixed + timedelta(days=1)) == "approximate"+ # No symbols is "none" regardless of how fresh the row is.+ assert attribution_kind([], fixed, fixed) == "none"+ # An unreadable timestamp cannot prove exactness, so it does not claim it.+ assert attribution_kind(["s"], None, fixed) == "approximate"+ assert attribution_kind(["s"], fixed, None) == "approximate"+++def test_decay_halves_over_one_half_life():+ assert decayed_mass(NOW, NOW) == 1.0+ older = NOW - timedelta(days=FIX_HALF_LIFE_DAYS)+ assert round(decayed_mass(older, NOW), 6) == 0.5+ assert round(decayed_mass(NOW - timedelta(days=2 * FIX_HALF_LIFE_DAYS), NOW), 6) == 0.25+ # Committer clock skew must not mint mass above a fresh fix.+ assert decayed_mass(NOW + timedelta(days=3), NOW) == 1.0+ assert decayed_mass(None, NOW) == 0.0+++def test_three_fresh_fixes_flag_a_magnet_and_three_stale_ones_do_not():+ fresh = [(NOW, ["m.py::f"]) for _ in range(3)]+ assert roll_up_file(fresh, NOW).bug_magnet is True++ stale_at = NOW - timedelta(days=FIX_HALF_LIFE_DAYS)+ stale = [(stale_at, ["m.py::f"]) for _ in range(3)]+ rollup = roll_up_file(stale, NOW)+ assert rollup.bug_magnet is False+ assert rollup.fix_count == 3 # the count is undecayed; only the mass ages+ assert round(rollup.fix_mass, 2) == 1.5+++def test_rollup_reports_last_fix_and_symbol_counts_by_descending_count():+ events = [+ (NOW - timedelta(days=40), ["m.py::a"]),+ (NOW - timedelta(days=5), ["m.py::a", "m.py::b"]),+ (NOW - timedelta(days=90), ["m.py::b"]),+ ]+ rollup = roll_up_file(events, NOW)+ assert rollup.last_fix_at == NOW - timedelta(days=5)+ assert list(rollup.symbol_counts.items()) == [("m.py::a", 2), ("m.py::b", 2)]+ assert rollup.fix_mass < BUG_MAGNET_MASS+++def test_empty_history_rolls_up_to_a_clean_zero():+ rollup = roll_up_file([], NOW)+ assert rollup == type(rollup)(+ fix_count=0, fix_mass=0.0, bug_magnet=False, last_fix_at=None, symbol_counts={}+ )diff --git a/tests/unit/health/test_signals.py b/tests/unit/health/test_signals.pyindex 88405874f..de7166d40 100644--- a/tests/unit/health/test_signals.py+++ b/tests/unit/health/test_signals.py@@ -96,3 +96,54 @@ def test_degrees_surfaced_when_node_present():assert s.prior_defect_count is Noneassert s.primary_owner_name is Noneassert s.has_any is True+++def test_old_callers_see_unchanged_fields_when_defect_columns_are_absent():+ """A ``GitMetadata`` stub predating the fix-history columns still works.++ The Protocol is duck-typed and both the MCP and REST paths pass live ORM+ rows, but a pre-upgrade row (or an old stub like ``_Git`` above) simply has+ no ``bug_magnet``. That must read as "no signal", not raise, and must leave+ every field the caller already relied on untouched.+ """+ s = file_signals(_Git(prior_defect_count=4, commit_count_90d=9), None)+ assert s.prior_defect_count == 4+ assert s.commit_count_90d == 9+ assert s.bug_magnet is None+ assert s.last_fix_at is None+ assert s.fix_symbol_counts is None+++def test_defect_history_surfaced_when_columns_are_present():+ from datetime import UTC, datetime++ @dataclass+ class _GitWithFixes(_Git):+ bug_magnet: bool = True+ last_fix_at: datetime | None = datetime(2026, 6, 2, tzinfo=UTC)+ fix_symbol_counts_json: str = '{"m.py::save": 4, "m.py::load": 1}'++ s = file_signals(_GitWithFixes(prior_defect_count=5), None)+ assert s.bug_magnet is True+ # Serialized as a string: this dataclass goes through asdict() into MCP+ # responses, which have no datetime encoder.+ assert s.last_fix_at == "2026-06-02T00:00:00+00:00"+ assert s.fix_symbol_counts == {"m.py::save": 4, "m.py::load": 1}+++def test_fix_symbol_counts_are_capped_and_bad_json_is_silent():+ from repowise.core.analysis.health.signals import _TOP_FIX_SYMBOLS++ @dataclass+ class _GitJson(_Git):+ fix_symbol_counts_json: str = ""++ many = {f"m.py::s{i}": 20 - i for i in range(12)}+ import json as _json++ s = file_signals(_GitJson(fix_symbol_counts_json=_json.dumps(many)), None)+ assert len(s.fix_symbol_counts) == _TOP_FIX_SYMBOLS+ assert list(s.fix_symbol_counts) == [f"m.py::s{i}" for i in range(_TOP_FIX_SYMBOLS)]++ assert file_signals(_GitJson(fix_symbol_counts_json="not json"), None).fix_symbol_counts is None+ assert file_signals(_GitJson(fix_symbol_counts_json="{}"), None).fix_symbol_counts is Nonediff --git a/tests/unit/persistence/test_fix_rollups.py b/tests/unit/persistence/test_fix_rollups.pynew file mode 100644index 000000000..ea22c44f0--- /dev/null+++ b/tests/unit/persistence/test_fix_rollups.py@@ -0,0 +1,212 @@+"""Round-trip tests for the fix-event rollup pass (``pipeline/fix_rollups.py``).++Covers the parts the pure-function tests can't: that attribution is written back+onto the event rows, that only production-code fixes reach the magnet count,+that decay is anchored to the repo rather than wall-clock time, and that+re-running the pass on unchanged data is a no-op.+"""++from __future__ import annotations++import json+from datetime import UTC, datetime, timedelta++import pytest+from sqlalchemy import select++from repowise.core.persistence.models import FixEvent, GitMetadata, WikiSymbol+from repowise.core.pipeline.fix_rollups import apply_fix_rollups+from tests.unit.persistence.helpers import insert_repo++HEAD = datetime(2026, 7, 1, tzinfo=UTC)+PATH = "src/store.py"+++async def _seed(session, repo_id: str, *, events: list[dict], last_commit_at=HEAD) -> None:+ session.add(+ GitMetadata(+ repository_id=repo_id,+ file_path=PATH,+ last_commit_at=last_commit_at,+ prior_defect_count=len(events),+ )+ )+ for symbol_id, start, end in (+ (f"{PATH}::Store", 1, 60),+ (f"{PATH}::Store.save", 10, 25),+ (f"{PATH}::Store.load", 30, 45),+ ):+ session.add(+ WikiSymbol(+ repository_id=repo_id,+ file_path=PATH,+ symbol_id=symbol_id,+ name=symbol_id.split("::")[-1],+ qualified_name=symbol_id,+ kind="function",+ start_line=start,+ end_line=end,+ )+ )+ for i, ev in enumerate(events):+ session.add(+ FixEvent(+ repository_id=repo_id,+ fix_sha=ev.get("sha", f"{i:040d}"),+ file_path=PATH,+ shape_kind=ev.get("shape_kind", "code_fix"),+ old_ranges_json=json.dumps(ev.get("ranges", [[12, 14]])),+ committed_at=ev["at"],+ )+ )+ await session.flush()+++async def _meta(session, repo_id: str) -> GitMetadata:+ return (+ await session.execute(+ select(GitMetadata).where(+ GitMetadata.repository_id == repo_id, GitMetadata.file_path == PATH+ )+ )+ ).scalar_one()+++async def test_attribution_and_rollup_written_for_a_magnet_file(async_session) -> None:+ repo = await insert_repo(async_session)+ await _seed(+ async_session,+ repo.id,+ events=[+ {"at": HEAD, "ranges": [[12, 14]]},+ {"at": HEAD - timedelta(days=3), "ranges": [[12, 20]]},+ {"at": HEAD - timedelta(days=10), "ranges": [[31, 33]]},+ {"at": HEAD - timedelta(days=25), "ranges": [[12, 13]]},+ ],+ )++ written = await apply_fix_rollups(async_session, repo.id)+ assert written == 1++ meta = await _meta(async_session, repo.id)+ assert meta.bug_magnet is True+ assert meta.fix_mass > 3.0+ assert meta.last_fix_at.replace(tzinfo=UTC) == HEAD+ assert json.loads(meta.fix_symbol_counts_json) == {+ f"{PATH}::Store.save": 3,+ f"{PATH}::Store.load": 1,+ }++ rows = (+ (await async_session.execute(select(FixEvent).where(FixEvent.repository_id == repo.id)))+ .scalars()+ .all()+ )+ assert {json.loads(r.symbol_ids_json)[0] for r in rows} == {+ f"{PATH}::Store.save",+ f"{PATH}::Store.load",+ }+ # The newest fix is the file's last commit, so nothing moved under it.+ newest = max(rows, key=lambda r: r.committed_at)+ assert newest.attribution == "exact"+ assert all(r.attribution in ("exact", "approximate") for r in rows)+++async def test_only_production_code_fixes_reach_the_magnet_count(async_session) -> None:+ """The magnet flag uses the same filter #931 put on ``prior_defect_count``."""+ repo = await insert_repo(async_session)+ await _seed(+ async_session,+ repo.id,+ events=[+ {"at": HEAD, "shape_kind": "code_fix"},+ {"at": HEAD, "shape_kind": "test_only"},+ {"at": HEAD, "shape_kind": "doc_only"},+ {"at": HEAD, "shape_kind": "config_other"},+ ],+ )+ await apply_fix_rollups(async_session, repo.id)++ meta = await _meta(async_session, repo.id)+ assert meta.fix_mass == 1.0+ assert meta.bug_magnet is False+ assert json.loads(meta.fix_symbol_counts_json) == {f"{PATH}::Store.save": 1}++ # Non-code rows are still attributed — the ranges are true either way, they+ # simply do not count as defects.+ rows = (+ (await async_session.execute(select(FixEvent).where(FixEvent.repository_id == repo.id)))+ .scalars()+ .all()+ )+ assert all(json.loads(r.symbol_ids_json) for r in rows)+++async def test_pure_insertions_attribute_to_nothing(async_session) -> None:+ repo = await insert_repo(async_session)+ await _seed(async_session, repo.id, events=[{"at": HEAD, "ranges": []}])+ await apply_fix_rollups(async_session, repo.id)++ row = (+ await async_session.execute(select(FixEvent).where(FixEvent.repository_id == repo.id))+ ).scalar_one()+ assert row.attribution == "none"+ assert json.loads(row.symbol_ids_json) == []+ # It is still a fix: the file-level mass counts it, only the symbol map cannot.+ meta = await _meta(async_session, repo.id)+ assert meta.fix_mass == 1.0+ assert json.loads(meta.fix_symbol_counts_json) == {}+++async def test_decay_is_anchored_to_the_repo_not_to_wall_clock(async_session) -> None:+ """A dormant repo's fixes are fresh relative to its own newest commit.++ Anchoring to wall-clock time would make every rollup drift between two+ indexes of the same checkout, which is exactly what the update-parity check+ forbids.+ """+ repo = await insert_repo(async_session)+ old = datetime(2024, 1, 1, tzinfo=UTC)+ await _seed(+ async_session,+ repo.id,+ events=[{"at": old, "sha": f"a{i:039d}"} for i in range(3)],+ last_commit_at=old,+ )+ await apply_fix_rollups(async_session, repo.id)++ meta = await _meta(async_session, repo.id)+ assert meta.fix_mass == 3.0+ assert meta.bug_magnet is True+++async def test_rerunning_the_pass_is_idempotent(async_session) -> None:+ repo = await insert_repo(async_session)+ await _seed(async_session, repo.id, events=[{"at": HEAD}, {"at": HEAD - timedelta(days=20)}])++ def _snapshot(m: GitMetadata) -> tuple:+ # SQLite hands datetimes back naive, so compare the instant, not the+ # tzinfo the value happened to be carrying when it was written.+ return (+ m.fix_mass,+ m.bug_magnet,+ m.fix_symbol_counts_json,+ m.last_fix_at.replace(tzinfo=None),+ )++ await apply_fix_rollups(async_session, repo.id)+ first = _snapshot(await _meta(async_session, repo.id))++ await apply_fix_rollups(async_session, repo.id)+ assert _snapshot(await _meta(async_session, repo.id)) == first+++async def test_no_fix_events_is_a_no_op(async_session) -> None:+ repo = await insert_repo(async_session)+ assert await apply_fix_rollups(async_session, repo.id) == 0diff --git a/tests/unit/server/test_health_badge.py b/tests/unit/server/test_health_badge.pyindex 7b7a785f1..f3b8845ea 100644--- a/tests/unit/server/test_health_badge.py+++ b/tests/unit/server/test_health_badge.py@@ -117,6 +117,9 @@ def test_file_signals_to_dict_no_data_all_null() -> None:"recent_owner_commit_pct": None,"in_degree": None,"out_degree": None,+ "bug_magnet": None,+ "last_fix_at": None,+ "fix_symbol_counts": None,}