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(files): mark which symbols in a file keep getting fixed (#968)
Raghav Chamadiyae85bf508930e
diff --git a/packages/server/src/repowise/server/routers/files.py b/packages/server/src/repowise/server/routers/files.pyindex 73718f07b..e3193a1ae 100644--- a/packages/server/src/repowise/server/routers/files.py+++ b/packages/server/src/repowise/server/routers/files.py@@ -245,6 +245,10 @@ async def file_detail(git["significant_commits"] = _json_or(git_meta.significant_commits_json, [])git["top_authors"] = _json_or(git_meta.top_authors_json, [])git["co_change_partners"] = _json_or(git_meta.co_change_partners_json, [])+ # symbol_id -> counted fixes that landed in it. Joined here rather than+ # onto HotspotResponse so the hotspots list does not carry a per-symbol+ # map on every row; only this page has symbols to spend it on.+ git["fix_symbol_counts"] = _json_or(git_meta.fix_symbol_counts_json, {})git["agent"] = {"agent_commit_count": git_meta.agent_commit_count or 0,"agent_authored_pct": git_meta.agent_authored_pct,diff --git a/packages/types/src/files.ts b/packages/types/src/files.tsindex 38c1944f6..1fb6b711b 100644--- a/packages/types/src/files.ts+++ b/packages/types/src/files.ts@@ -125,6 +125,12 @@ export interface FileDetailGit extends Hotspot {co_change_partners: CoChangePartner[];agent: FileAgentProvenance;first_commit_at: string | null;+ /** `symbol_id` -> counted fixes that landed in it, over the same window as+ * `prior_defect_count`. Approximate: symbol spans are current-tree while+ * each fix's line ranges are numbered on its own parent commit. A symbol+ * with no fixes is absent from the map; the whole map is empty on an index+ * that predates the fix rollup. */+ fix_symbol_counts?: Record<string, number>;}export interface FileDetailCoverage {diff --git a/packages/ui/__tests__/files/file-overview-tab.test.tsx b/packages/ui/__tests__/files/file-overview-tab.test.tsxnew file mode 100644index 000000000..6956a4747--- /dev/null+++ b/packages/ui/__tests__/files/file-overview-tab.test.tsx@@ -0,0 +1,158 @@+import { describe, it, expect } from "vitest";+import { render, screen } from "@testing-library/react";+import { FileOverviewTab } from "../../src/files/file-overview-tab.js";+import type {+ FileDetailGit,+ FileDetailResponse,+ FileSymbolSlim,+} from "@repowise-dev/types/files";++function symbol(name: string, complexity: number): FileSymbolSlim {+ return {+ symbol_id: `src/foo.ts::${name}`,+ name,+ kind: "function",+ signature: `${name}()`,+ start_line: 1,+ end_line: 10,+ visibility: "public",+ complexity_estimate: complexity,+ is_async: false,+ };+}++function makeGit(overrides: Partial<FileDetailGit> = {}): FileDetailGit {+ return {+ file_path: "src/foo.ts",+ commit_count_total: 40,+ commit_count_90d: 8,+ commit_count_30d: 2,+ churn_percentile: 92,+ primary_owner: "Ada",+ is_hotspot: true,+ is_stable: false,+ bus_factor: 2,+ contributor_count: 4,+ lines_added_90d: 100,+ lines_deleted_90d: 40,+ avg_commit_size: 30,+ commit_categories: {},+ significant_commits: [],+ top_authors: [],+ co_change_partners: [],+ agent: { agent_commit_count: 0, agent_authored_pct: null, tier_counts: {} },+ first_commit_at: null,+ ...overrides,+ };+}++function makeData(+ symbols: FileSymbolSlim[],+ git: FileDetailGit | null = null,+): FileDetailResponse {+ return {+ file_path: "src/foo.ts",+ wiki_page: null,+ health: { metric: null, breakdown: null, findings: [], trend: null, signals: null },+ git,+ coverage: null,+ graph: null,+ symbols,+ function_blame: [],+ governing_decisions: [],+ dead_code: [],+ } as unknown as FileDetailResponse;+}++const symbolHref = (id: string) => `/symbols/${id}`;+const fileHref = (p: string) => `/files/${p}`;++function renderTab(data: FileDetailResponse) {+ return render(<FileOverviewTab data={data} symbolHref={symbolHref} fileHref={fileHref} />);+}++describe("FileOverviewTab symbol fix counts", () => {+ it("marks only the symbols that were actually fixed", () => {+ renderTab(+ makeData(+ [symbol("run", 20), symbol("parse", 15)],+ makeGit({ fix_symbol_counts: { "src/foo.ts::run": 3 } }),+ ),+ );+ const run = screen.getByText("run").closest("a");+ const parse = screen.getByText("parse").closest("a");+ expect(run?.textContent).toContain("3");+ expect(parse?.textContent).not.toMatch(/\d/);+ });++ it("leaves the chip row untouched when the index carries no rollup", () => {+ renderTab(makeData([symbol("run", 20)], makeGit()));+ expect(screen.getByText("run").closest("a")?.textContent).toBe("runfunction");+ });++ it("adds nothing when the file has no git metadata at all", () => {+ renderTab(makeData([symbol("run", 20)], null));+ expect(screen.getByText("run").closest("a")?.textContent).toBe("runfunction");+ });++ it("reserves the last slot for the most-fixed symbol", () => {+ // Twenty symbols, eight chips. `edge` is the least complex, so complexity+ // alone would hide the one thing worth knowing about.+ const symbols = [+ ...Array.from({ length: 19 }, (_, i) => symbol(`big${i}`, 100 - i)),+ symbol("edge", 1),+ ];+ renderTab(makeData(symbols, makeGit({ fix_symbol_counts: { "src/foo.ts::edge": 5 } })));+ expect(screen.getByText("edge")).toBeTruthy();+ // It takes the last slot only, so the most complex symbols all survive.+ expect(screen.getByText("big0")).toBeTruthy();+ expect(screen.getByText("big6")).toBeTruthy();+ expect(screen.queryByText("big7")).toBeNull();+ });++ it("does not evict the file's most complex symbol for trivial fixed helpers", () => {+ // Ten one-fix helpers plus one very complex, never-fixed symbol. Sorting+ // the whole list on "was fixed" would drop `dispatch` off the panel.+ const symbols = [+ symbol("dispatch", 90),+ ...Array.from({ length: 10 }, (_, i) => symbol(`helper${i}`, i + 1)),+ ...Array.from({ length: 12 }, (_, i) => symbol(`filler${i}`, 50 + i)),+ ];+ const fix_symbol_counts = Object.fromEntries(+ Array.from({ length: 10 }, (_, i) => [`src/foo.ts::helper${i}`, 1]),+ );+ renderTab(makeData(symbols, makeGit({ fix_symbol_counts })));+ expect(screen.getByText("dispatch")).toBeTruthy();+ });++ it("keeps the most-fixed symbol ahead of a merely-fixed one", () => {+ const symbols = [+ symbol("parse", 3),+ ...Array.from({ length: 19 }, (_, i) => symbol(`big${i}`, 100 - i)),+ ];+ renderTab(+ makeData(+ symbols,+ makeGit({ fix_symbol_counts: { "src/foo.ts::parse": 12, "src/foo.ts::big0": 1 } }),+ ),+ );+ expect(screen.getByText("parse")).toBeTruthy();+ });++ it("stands down when a fix touched most of the file", () => {+ // One commit that fixed a bug and reformatted the file marks every symbol.+ // That map has no per-symbol signal, so marking all eight chips is noise.+ const symbols = Array.from({ length: 10 }, (_, i) => symbol(`s${i}`, 100 - i));+ const fix_symbol_counts = Object.fromEntries(+ symbols.map((s) => [s.symbol_id, 1]),+ );+ renderTab(makeData(symbols, makeGit({ fix_symbol_counts })));+ expect(screen.queryByTitle(/matched by line range/)).toBeNull();+ });++ it("still marks when the fixes are concentrated", () => {+ const symbols = Array.from({ length: 10 }, (_, i) => symbol(`s${i}`, 100 - i));+ renderTab(makeData(symbols, makeGit({ fix_symbol_counts: { "src/foo.ts::s0": 4 } })));+ expect(screen.getByText("s0").closest("a")?.textContent).toContain("4");+ });+});diff --git a/packages/ui/src/files/file-overview-tab.tsx b/packages/ui/src/files/file-overview-tab.tsxindex aa4228898..34664a017 100644--- a/packages/ui/src/files/file-overview-tab.tsx+++ b/packages/ui/src/files/file-overview-tab.tsx@@ -1,10 +1,11 @@-import { ArrowRight, Code2, Network } from "lucide-react";+import { ArrowRight, Bug, Code2, Network } from "lucide-react";import type { FileDetailResponse } from "@repowise-dev/types/files";import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";import { Badge } from "../ui/badge";import { StatGrid, StatTile } from "../shared/stat-grid";import { scoreTextColor } from "../health/tokens";import { truncatePath } from "../lib/format";+import { SYMBOL_FIX_TITLE } from "../git/fix-history-badge";interface FileOverviewTabProps {data: FileDetailResponse;@@ -22,9 +23,39 @@ interface FileOverviewTabProps {export function FileOverviewTab({ data, symbolHref, fileHref }: FileOverviewTabProps) {const score = data.health.metric?.score;const deadLines = data.dead_code.reduce((s, f) => s + f.lines, 0);- const keySymbols = [...data.symbols]- .sort((a, b) => b.complexity_estimate - a.complexity_estimate)- .slice(0, 8);+ // Keyed on the row's own symbol_id, not a rebuilt `${path}::${name}`: some+ // extractors mint ids from the qualified name, and those would never match.+ const rawFixCounts = data.git?.fix_symbol_counts ?? {};+ const fixedCount = Object.values(rawFixCounts).filter((n) => n > 0).length;+ // Attribution marks every symbol overlapping a fix's hunks, so one commit+ // that fixed a bug and reformatted the file lands on all of them. A map+ // covering most of the file says nothing about *which* symbol is the+ // problem, and painting every chip red is noise, so the markers stand down+ // and the file-level count on the History tab carries it instead.+ const perSymbolSignal =+ fixedCount > 0 && data.symbols.length > 0 && fixedCount * 2 <= data.symbols.length;+ const fixesIn = (symbolId: string) =>+ perSymbolSignal ? (rawFixCounts[symbolId] ?? 0) : 0;++ // Complexity picks the list, as it always has: biasing the whole sort on a+ // "was fixed" boolean would evict the file's most complex symbol in favour+ // of eight trivial helpers that took one fix each.+ const byComplexity = [...data.symbols].sort(+ (a, b) => b.complexity_estimate - a.complexity_estimate,+ );+ const keySymbols = byComplexity.slice(0, 8);+ // One reserved slot, so the symbol that keeps breaking cannot be hidden by+ // seven complicated neighbours. Only reachable when something was cut.+ if (byComplexity.length > keySymbols.length) {+ const worst = [...data.symbols].sort(+ (a, b) =>+ fixesIn(b.symbol_id) - fixesIn(a.symbol_id) ||+ b.complexity_estimate - a.complexity_estimate,+ )[0];+ if (worst && fixesIn(worst.symbol_id) > 0 && !keySymbols.includes(worst)) {+ keySymbols[keySymbols.length - 1] = worst;+ }+ }return (<div className="space-y-4">@@ -61,16 +92,28 @@ export function FileOverviewTab({ data, symbolHref, fileHref }: FileOverviewTabP</CardTitle></CardHeader><CardContent className="flex flex-wrap gap-1.5">- {keySymbols.map((s) => (- <a- key={s.symbol_id}- href={symbolHref(s.symbol_id)}- className="inline-flex items-center gap-1 rounded border border-[var(--color-border-default)] px-2 py-0.5 font-mono text-xs text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-accent-primary)] hover:text-[var(--color-accent-primary)]"- >- {s.name}- <span className="text-[10px] text-[var(--color-text-tertiary)]">{s.kind}</span>- </a>- ))}+ {keySymbols.map((s) => {+ const fixes = fixesIn(s.symbol_id);+ return (+ <a+ key={s.symbol_id}+ href={symbolHref(s.symbol_id)}+ className="inline-flex items-center gap-1 rounded border border-[var(--color-border-default)] px-2 py-0.5 font-mono text-xs text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-accent-primary)] hover:text-[var(--color-accent-primary)]"+ >+ {s.name}+ <span className="text-[10px] text-[var(--color-text-tertiary)]">{s.kind}</span>+ {fixes > 0 && (+ <span+ className="inline-flex items-center gap-0.5 text-[10px] tabular-nums text-[var(--color-error)]"+ title={SYMBOL_FIX_TITLE}+ >+ <Bug className="h-2.5 w-2.5" />+ {fixes}+ </span>+ )}+ </a>+ );+ })}</CardContent></Card>)}diff --git a/packages/web/src/components/docs/docs-viewer.tsx b/packages/web/src/components/docs/docs-viewer.tsxindex 62584b203..6fb4c4442 100644--- a/packages/web/src/components/docs/docs-viewer.tsx+++ b/packages/web/src/components/docs/docs-viewer.tsx@@ -245,6 +245,19 @@ function AtAGlance({ repoId, targetPath }: { repoId: string; targetPath: string</span></div>)}+ {data.original_path && (+ <div className="flex items-center justify-between gap-2">+ <span className="shrink-0 text-[var(--color-text-tertiary)]">Renamed from</span>+ <span className="truncate font-mono" title={data.original_path}>+ {data.original_path}+ </span>+ </div>+ )}+ {data.commit_count_capped && (+ <p className="text-[10px] text-[var(--color-text-tertiary)]">+ History capped during indexing, so older commits are not counted above.+ </p>+ )}</div></div>);diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.pyindex adcf9347c..6da4ec100 100644--- a/tests/unit/server/conftest.py+++ b/tests/unit/server/conftest.py@@ -33,6 +33,7 @@ def _create_test_app():dead_code,decisions,external_systems,+ files,git,graph,health,@@ -81,6 +82,7 @@ def _create_test_app():app.include_router(meta.router)app.include_router(webhooks.router)app.include_router(git.router)+ app.include_router(files.router)app.include_router(dead_code.router)app.include_router(owners.router)app.include_router(modules.router)diff --git a/tests/unit/server/test_git.py b/tests/unit/server/test_git.pyindex 9b7213dc9..ab9d70167 100644--- a/tests/unit/server/test_git.py+++ b/tests/unit/server/test_git.py@@ -45,6 +45,7 @@ async def _insert_git_metadata(session_factory, repo_id: str) -> None:temporal_hotspot_score=12.3,commit_count_capped=True,original_path="src/old_main.py",+ fix_symbol_counts_json=json.dumps({"src/main.py::run": 3}),)await crud.upsert_git_metadata(session,@@ -87,6 +88,29 @@ async def test_get_git_metadata(client: AsyncClient, app) -> None:assert data["original_path"] == "src/old_main.py"+async def test_file_detail_carries_symbol_fix_counts(client: AsyncClient, app) -> None:+ """The file page answers "which symbol keeps breaking" without a second call.++ The map is joined onto the file-detail git block rather than onto+ HotspotResponse, so the hotspots list is not made to carry a per-symbol+ dict on every row.+ """+ repo = await create_test_repo(client)+ await _insert_git_metadata(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/repos/{repo['id']}/files/src/main.py")+ assert resp.status_code == 200, resp.text+ git = resp.json()["git"]+ assert git["fix_symbol_counts"] == {"src/main.py::run": 3}++ # A file the rollup never touched reports an empty map, not a missing key,+ # so a consumer can index into it unconditionally.+ resp = await client.get(f"/api/repos/{repo['id']}/files/src/utils.py")+ assert resp.status_code == 200+ assert resp.json()["git"]["fix_symbol_counts"] == {}++@pytest.mark.asyncioasync def test_get_git_metadata_not_found(client: AsyncClient) -> None:repo = await create_test_repo(client)