Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(health): show per-file bug-fix history in the drawer, panel and hover (#948)

Raghav Chamadiya967dc2d4f2e2
diff --git a/packages/core/src/repowise/core/analysis/health/signals.py b/packages/core/src/repowise/core/analysis/health/signals.py
index d934a374e..4c8484b94 100644
--- a/packages/core/src/repowise/core/analysis/health/signals.py
+++ b/packages/core/src/repowise/core/analysis/health/signals.py
@@ -21,7 +21,7 @@ from __future__ import annotations
import json
from dataclasses import asdict, dataclass
-from datetime import datetime
+from datetime import UTC, datetime
from typing import Protocol
# How many symbols the per-file fix breakdown carries. Enough to say "mostly
@@ -107,8 +107,20 @@ 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 iso_utc(value: datetime | None) -> str | None:
+ """ISO-8601 with an explicit UTC offset, always.
+
+ SQLite's DATETIME bind processor drops ``tzinfo``, so these columns come
+ back naive even though they were written aware-UTC. A bare
+ ``2026-07-19T10:00:00`` is parsed as LOCAL time by every JS consumer, which
+ on a UTC-8 viewer reads a two-hour-old fix as six hours in the future, trips
+ ``formatRelativeTimeOrNull``'s future-guard, and makes the age silently
+ vanish from the copy that is required to carry it. Re-attach UTC here, once,
+ rather than in each of the four surfaces that render this.
+ """
+ if not isinstance(value, datetime):
+ return None
+ return (value if value.tzinfo else value.replace(tzinfo=UTC)).isoformat()
def _top_fix_symbols(raw: str | None) -> dict[str, int] | None:
@@ -161,7 +173,7 @@ def file_signals(
# 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,
+ last_fix_at=iso_utc(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/ui/__tests__/health/file-signals-panel.test.tsx b/packages/ui/__tests__/health/file-signals-panel.test.tsx
index 8eb3b95eb..1760714f1 100644
--- a/packages/ui/__tests__/health/file-signals-panel.test.tsx
+++ b/packages/ui/__tests__/health/file-signals-panel.test.tsx
@@ -87,3 +87,61 @@ describe("FileSignalsPanel", () => {
expect(container).toBeEmptyDOMElement();
});
});
+
+describe("FileSignalsPanel bug history", () => {
+ it("shows the magnet badge only alongside the last-fix age", () => {
+ // The contract in types/health.ts is explicit: `bug_magnet` is a claim
+ // about RECENT fix pressure, so it never renders without recency beside
+ // it. A file fixed four times two years ago must not read like one fixed
+ // four times this month.
+ const twoWeeksAgo = new Date(Date.now() - 14 * 86400_000).toISOString();
+ render(
+ <FileSignalsPanel
+ signals={sig({ prior_defect_count: 5, bug_magnet: true, last_fix_at: twoWeeksAgo })}
+ />,
+ );
+
+ expect(screen.getByText("5 bug-fixes")).toBeInTheDocument();
+ expect(screen.getByText("Bug magnet")).toBeInTheDocument();
+ expect(screen.getByText(/last 2w ago/)).toBeInTheDocument();
+ });
+
+ it("omits the badge when the file is not a magnet", () => {
+ render(<FileSignalsPanel signals={sig({ prior_defect_count: 2, bug_magnet: false })} />);
+
+ expect(screen.getByText("2 bug-fixes")).toBeInTheDocument();
+ expect(screen.queryByText("Bug magnet")).not.toBeInTheDocument();
+ });
+
+ it("falls back to the plain caption when the last fix is unknown", () => {
+ render(<FileSignalsPanel signals={sig({ prior_defect_count: 3 })} />);
+
+ expect(screen.getByText("bug-fix commits in the last 6 months")).toBeInTheDocument();
+ });
+});
+
+describe("FileSignalsPanel magnet recency guard", () => {
+ it("drops the badge when there is no last-fix age to anchor it", () => {
+ // The badge claims RECENT fix pressure. With no timestamp the row would
+ // read identically for a file fixed four times last month and one fixed
+ // four times two years ago, so the flag goes quiet and the windowed count
+ // stands on its own.
+ render(
+ <FileSignalsPanel
+ signals={sig({ prior_defect_count: 5, bug_magnet: true, last_fix_at: null })}
+ />,
+ );
+
+ expect(screen.getByText("5 bug-fixes")).toBeInTheDocument();
+ expect(screen.queryByText("Bug magnet")).not.toBeInTheDocument();
+ });
+
+ it("drops the badge on a file with no counted fixes", () => {
+ render(
+ <FileSignalsPanel signals={sig({ prior_defect_count: 0, bug_magnet: true })} />,
+ );
+
+ expect(screen.getByText("No bug-fixes")).toBeInTheDocument();
+ expect(screen.queryByText("Bug magnet")).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/__tests__/health/health-file-drawer.test.tsx b/packages/ui/__tests__/health/health-file-drawer.test.tsx
index 62bd868df..8cb0c92ab 100644
--- a/packages/ui/__tests__/health/health-file-drawer.test.tsx
+++ b/packages/ui/__tests__/health/health-file-drawer.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { render, screen, within } from "@testing-library/react";
+import { fireEvent, render, screen, within } from "@testing-library/react";
import {
HealthFileDrawer,
type HealthDrawerFinding,
@@ -95,3 +95,64 @@ describe("HealthFileDrawer metric cards", () => {
expect(screen.getByText("12")).toBeInTheDocument();
});
});
+
+describe("HealthFileDrawer bug history", () => {
+ const signals = {
+ prior_defect_count: 8,
+ change_entropy_pct: null,
+ lines_added_90d: null,
+ lines_deleted_90d: null,
+ commit_count_90d: null,
+ age_days: null,
+ primary_owner_name: null,
+ primary_owner_commit_pct: null,
+ recent_owner_name: null,
+ recent_owner_commit_pct: null,
+ in_degree: null,
+ out_degree: null,
+ bug_magnet: true,
+ last_fix_at: new Date(Date.now() - 3 * 86400_000).toISOString(),
+ fix_symbol_counts: { "pipeline.py::run_update": 4, "pipeline.py::persist": 2 },
+ };
+
+ it("hides per-symbol counts behind a disclosure that names the last fix", () => {
+ render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric()}
+ findings={[]}
+ signals={signals}
+ />,
+ );
+
+ const toggle = screen.getByRole("button", { name: /Bug history/ });
+ // Recency rides on the toggle itself: the counts are collapsed, the "is
+ // this still happening?" answer is not.
+ expect(toggle).toHaveTextContent(/last fix 3d ago/);
+ // Collapsed by default, because "where do the bugs cluster" is not a question
+ // every reader of the drawer has.
+ expect(screen.queryByText("run_update")).not.toBeInTheDocument();
+
+ fireEvent.click(toggle);
+ expect(screen.getByText("run_update")).toBeInTheDocument();
+ expect(screen.getByText("4 fixes")).toBeInTheDocument();
+ expect(screen.getByText("2 fixes")).toBeInTheDocument();
+ // The line-range mapping is approximate and says so, rather than letting
+ // the counts read as exact.
+ expect(screen.getByText(/lines move/)).toBeInTheDocument();
+ });
+
+ it("stays silent without per-symbol data", () => {
+ render(
+ <HealthFileDrawer
+ open
+ onClose={() => {}}
+ metric={metric()}
+ findings={[]}
+ signals={{ ...signals, fix_symbol_counts: null }}
+ />,
+ );
+ expect(screen.queryByRole("button", { name: /Bug history/ })).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/src/health/file-signals-panel.tsx b/packages/ui/src/health/file-signals-panel.tsx
index f14be41c1..113138422 100644
--- a/packages/ui/src/health/file-signals-panel.tsx
+++ b/packages/ui/src/health/file-signals-panel.tsx
@@ -1,6 +1,7 @@
"use client";
import type { FileSignals } from "@repowise-dev/types/health";
+import { formatRelativeTimeOrNull } from "../lib/format";
export interface FileSignalsPanelProps {
signals: FileSignals | null | undefined;
@@ -36,8 +37,9 @@ export function FileSignalsPanel({ signals, hideHeading = false }: FileSignalsPa
<Group label="Process">
<Row
value={priorDefectValue(signals.prior_defect_count)}
- caption="bug-fix commits in the last 6 months"
+ caption={defectCaption(signals)}
present={signals.prior_defect_count != null}
+ badge={magnetBadge(signals)}
/>
<Row
value={
@@ -123,6 +125,27 @@ function priorDefectValue(n: number | null): string | null {
return n === 0 ? "No bug-fixes" : `${n} bug-fix${n === 1 ? "" : "es"}`;
}
+/** The bug-fix caption, with recency folded in when we know it. */
+function defectCaption(s: FileSignals): string {
+ const base = "bug-fix commits in the last 6 months";
+ const last = formatRelativeTimeOrNull(s.last_fix_at, "");
+ return last ? `${base}, last ${last}` : base;
+}
+
+/**
+ * The magnet pill, and only when the caption can carry an age beside it.
+ *
+ * `bug_magnet` is a claim about *recent* fix pressure, so the contract requires
+ * any copy showing it to show `last_fix_at` too: a file fixed four times two
+ * years ago must not read like one fixed four times this month. Without a
+ * timestamp the badge would say exactly that, so it goes quiet instead. The
+ * count beside it is windowed and stands on its own.
+ */
+function magnetBadge(s: FileSignals): string | undefined {
+ if (!s.bug_magnet || !s.prior_defect_count) return undefined;
+ return formatRelativeTimeOrNull(s.last_fix_at, "") ? "Bug magnet" : undefined;
+}
+
function velocityValue(s: FileSignals): string | null {
if (s.commit_count_90d == null) return null;
const added = s.lines_added_90d ?? 0;
@@ -164,16 +187,19 @@ function Row({
caption,
present,
emphasize = false,
+ badge,
}: {
value: string | null;
caption: string;
present: boolean;
emphasize?: boolean;
+ /** Optional pill beside the value (e.g. "Bug magnet"). */
+ badge?: string | undefined;
}) {
return (
<div>
<p
- className={`text-xs font-semibold tabular-nums ${
+ className={`flex items-center gap-1.5 text-xs font-semibold tabular-nums ${
present
? emphasize
? "text-[var(--color-accent-primary)]"
@@ -182,6 +208,11 @@ function Row({
}`}
>
{present ? value : "No signal"}
+ {present && badge != null && (
+ <span className="rounded-full border border-[var(--color-accent-muted)] bg-[var(--color-accent-muted)] px-1.5 py-px text-[9px] font-medium uppercase tracking-wide text-[var(--color-accent-primary)]">
+ {badge}
+ </span>
+ )}
</p>
<p className="text-[10px] leading-tight text-[var(--color-text-tertiary)]">{caption}</p>
</div>
diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsx
index 365d83a19..f75eb81c2 100644
--- a/packages/ui/src/health/health-file-drawer.tsx
+++ b/packages/ui/src/health/health-file-drawer.tsx
@@ -16,6 +16,8 @@ import {
import { BiomarkerDetails, type BiomarkerDetailsRecord } from "./biomarker-details";
import { ScoreBreakdown, type ScoreBreakdownCategory } from "./score-breakdown";
import { FileSignalsPanel } from "./file-signals-panel";
+import { CollapsibleSection } from "../shared/collapsible-section";
+import { formatRelativeTimeOrNull } from "../lib/format";
import { Sparkline } from "./sparkline";
import {
SEVERITY_CHIP,
@@ -380,6 +382,8 @@ export function HealthFileDrawer({
<FileSignalsPanel signals={signals} />
+ <BugHistorySection signals={signals} />
+
{fileViewHref ? (
<a
href={fileViewHref}
@@ -442,6 +446,56 @@ export function HealthFileDrawer({
* row, not seven — the P2 "looks padded" fix. Single-finding groups render
* expanded; the caller expands the highest-impact group by default.
*/
+/**
+ * Which symbols this file's recent bug fixes landed in, behind a disclosure.
+ *
+ * Collapsed by default and silent without per-symbol data: the counts are a
+ * "where do the bugs cluster" question, not something every reader of the
+ * drawer needs answered. Two honesty rules show up in the copy. The heading
+ * carries the last-fix age because a fix count without recency reads the same
+ * at two weeks and two years. And the counts are labelled approximate, because
+ * symbol spans are current-tree while each fix's line ranges are numbered on
+ * its own parent commit, so a file that has moved since is matched on lines
+ * that shifted.
+ *
+ * No commit is named here. File-level SZZ ran at 74.5% precision against the
+ * frozen judgments, which is enough to count fixes and not enough to say which
+ * commit caused one.
+ */
+function BugHistorySection({ signals }: { signals: FileSignals | null | undefined }) {
+ const counts = signals?.fix_symbol_counts;
+ if (!counts || Object.keys(counts).length === 0) return null;
+
+ const lastFix = formatRelativeTimeOrNull(signals?.last_fix_at ?? null, "");
+ const entries = Object.entries(counts).sort((a, b) => b[1] - a[1]);
+
+ return (
+ <CollapsibleSection
+ title="Bug history"
+ hint={lastFix ? `last fix ${lastFix}` : "last fix unknown"}
+ >
+ <ul className="space-y-1">
+ {entries.map(([symbolId, count]) => (
+ <li
+ key={symbolId}
+ className="flex items-baseline gap-2 text-xs text-[var(--color-text-secondary)]"
+ >
+ <code className="font-mono text-[var(--color-text-primary)]">
+ {symbolId.split("::").pop()}
+ </code>
+ <span className="ml-auto tabular-nums text-[var(--color-text-tertiary)]">
+ {count} {count === 1 ? "fix" : "fixes"}
+ </span>
+ </li>
+ ))}
+ </ul>
+ <p className="text-[10px] leading-tight text-[var(--color-text-tertiary)]">
+ Approximate: fixes are matched to symbols by line range, and lines move.
+ </p>
+ </CollapsibleSection>
+ );
+}
+
function FunctionFindingsGroup({
isFile,
functionName,
diff --git a/packages/vscode/src/features/hovers.ts b/packages/vscode/src/features/hovers.ts
index 1e0bf4a0f..baaa0770a 100644
--- a/packages/vscode/src/features/hovers.ts
+++ b/packages/vscode/src/features/hovers.ts
@@ -5,7 +5,9 @@ import { listDecisions } from "@repowise-dev/api-client/decisions";
import { getSymbolDetail, listSymbols } from "@repowise-dev/api-client/symbols";
import type { RepowiseContext } from "../core/context";
import { getFileFindings, repoRelativePath } from "../core/fileSignals";
+import { formatRelativeTimeOrNull } from "@repowise-dev/ui/lib/format";
import type {
+ FileSignals,
HealthFileBreakdownResponse,
HealthFinding,
} from "@repowise-dev/types/health";
@@ -72,6 +74,23 @@ export function registerHovers(ctx: RepowiseContext): vscode.Disposable {
}
}
+ /**
+ * One line of counted bug-fix history, or nothing.
+ *
+ * Recency is not optional in this copy: `bug_magnet` is a claim about recent
+ * fix pressure, so it is dropped rather than shown without the age beside it.
+ * Silent when the file has no counted fixes, so a clean file's hover is
+ * unchanged. Aggregate only, and no commit is named here or anywhere else.
+ */
+ function fixHistoryLine(signals: FileSignals | null | undefined): string | null {
+ const count = signals?.prior_defect_count;
+ if (count == null || count <= 0) return null;
+ const last = formatRelativeTimeOrNull(signals?.last_fix_at ?? null, "");
+ if (!last) return `Bug fixes: ${count} in 6 months`;
+ const magnet = signals?.bug_magnet ? " **bug magnet**" : "";
+ return `Bug fixes: ${count} in 6 months, last ${last}${magnet}`;
+ }
+
async function fileHover(
relPath: string,
): Promise<vscode.Hover | undefined> {
@@ -111,6 +130,11 @@ export function registerHovers(ctx: RepowiseContext): vscode.Disposable {
);
}
+ const bugHistory = fixHistoryLine(breakdown?.signals);
+ if (bugHistory) {
+ md.appendMarkdown(`${bugHistory}\n\n`);
+ }
+
if (governing.length > 0) {
md.appendMarkdown("Decisions:\n\n");
for (const decision of governing) {
diff --git a/tests/unit/health/test_signals.py b/tests/unit/health/test_signals.py
index de7166d40..d55e89236 100644
--- a/tests/unit/health/test_signals.py
+++ b/tests/unit/health/test_signals.py
@@ -147,3 +147,23 @@ def test_fix_symbol_counts_are_capped_and_bad_json_is_silent():
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 None
+
+
+def test_naive_timestamps_are_serialized_with_an_explicit_utc_offset():
+ """The stored column is naive, and a naive ISO string is a real bug on the wire.
+
+ SQLite's DATETIME bind processor drops tzinfo, so `last_fix_at` reads back
+ naive even though the rollup wrote it aware-UTC. JS parses a date-time with
+ no offset as LOCAL time, so west of UTC a fresh fix lands in the future,
+ trips `formatRelativeTimeOrNull`'s future-guard, and the age disappears from
+ copy that is contractually required to carry it. Worst for the newest fixes,
+ which are the ones worth showing.
+ """
+ from datetime import datetime
+
+ @dataclass
+ class _GitNaive(_Git):
+ last_fix_at: datetime | None = datetime(2026, 6, 2, 10, 30)
+
+ s = file_signals(_GitNaive(prior_defect_count=1), None)
+ assert s.last_fix_at == "2026-06-02T10:30:00+00:00"