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): churn x complexity quadrant on the hotspots tab (#491)

Raghav Chamadiya9b0dd5ede80b
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.md
index 42ec7e1d8..33f8c3482 100644
--- a/docs/CODE_HEALTH.md
+++ b/docs/CODE_HEALTH.md
@@ -416,6 +416,39 @@ GET /api/repos/{repo_id}/health/files/breakdown?file_path=path/to/file.py
get_context(targets=["path/to/file.py"], include=["health"])
```
+## Hotspot anatomy
+
+Two views dissect *where* risk concentrates, both plotted from data already on
+disk (churn from the git indexer, complexity from the walker, blame at function
+granularity).
+
+### Churn × complexity
+
+One dot per recently-changed file: the x-axis is its 90-day commit count
+(churn), the y-axis is its max cyclomatic complexity, dot size is NLOC, and dot
+color is the health band. Dashed guides sit at the repo's median churn and
+median complexity, so the tinted top-right corner reads "busier **and** more
+complex than a typical file here" — the refactor zone, where volatility and
+tangle collide and defects concentrate. It lives on the **Hotspots & churn**
+dashboard tab, toggleable with the churn × bus-factor view.
+
+```bash
+# REST — repo-level point list (one point per churned file)
+GET /api/repos/{repo_id}/health/churn-complexity
+```
+
+Files with no recent churn are omitted (they have nothing to say on the churn
+axis); complexity is never used to filter, so a high-churn, low-complexity file
+still shows in the bottom-right ("changes constantly but stays simple").
+
+### Functions by churn
+
+The file's Health tab lists its functions ranked by modification count, with
+the 90-day recent-mod count, median age, and blame owner per function — the
+same `git_function_blame` rollup the symbol page uses. It promotes per-function
+ownership and volatility out of the buried biomarker cards into a first-class
+table, so "which function in this file is the actual hotspot" is one glance away.
+
## Configuration
Per-file overrides live in `.repowise/health-rules.json`:
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index 3d7408b25..bbed9b8c1 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -67,6 +67,7 @@ analysis/health/
├── defect_accuracy.py # "does the score find the bugs?" self-validation
├── trends.py # snapshot diff, Declining/Predicted alerts, per-file score series
├── signals.py # per-file process/people/topology join (surfacing-only)
+├── churn_complexity.py # churn × complexity scatter points (surfacing-only)
├── suggestions.py # deterministic refactoring text per biomarker
├── config.py # HealthConfig + .repowise/health-rules.json
├── models.py # HealthFindingData, HealthFileMetricData, HealthReport
@@ -209,6 +210,7 @@ tests/unit/health/ # 99+ tests
├── test_health_config.py # .repowise/health-rules.json
├── test_trends.py # diff_snapshots, declining/predicted alerts
├── test_signals.py # file_signals join + no-signal/normalization
+├── test_churn_complexity.py # churn × complexity point shaping + sort + filtering
└── test_suggestions.py
tests/integration/
@@ -756,6 +758,7 @@ Every response carries the standard `_meta` envelope via `build_meta()`.
| `GET /coverage` | coverage summary + per-file rows |
| `POST /coverage` | ingest a coverage report (used by some CI integrations) |
| `GET /refactoring-targets` | ranked by `total_impact / effort_bucket` |
+| `GET /churn-complexity` | churn × complexity scatter points (one per churned file: `commit_count_90d`, `max_ccn`, `nloc`, `score`, `churn_percentile`) |
| `GET /modules` | NLOC-weighted module rollup table |
Auth is the standard `verify_api_key` dependency from
@@ -775,7 +778,10 @@ Three routes under `/repos/[id]/health/`:
Plus a sidecar `HealthRisksPanel` on the Hotspots, Ownership, and Graph
pages — surfaces the lowest-scoring files inline without touching the
-shared table/graph components.
+shared table/graph components. The **Hotspots & churn** tab carries the
+`ChurnComplexityQuadrant` (fed by `GET /churn-complexity`), toggleable in
+place with the existing churn × bus-factor scatter; the file Health tab
+carries the per-function "Functions by churn" blame table.
All visual primitives live in `packages/ui/src/health/` so the hosted
`frontend/` repo (separate git checkout) can reuse them — port is mostly
@@ -865,6 +871,7 @@ Other perf notes:
| `tests/unit/health/test_scoring_snapshot.py` | **Stability guard** — caps, severity table, biomarker→category mapping, two known fixture scores |
| `tests/unit/health/test_trends.py` | Declining + predicted alerts, ordering, per-file series + `file_trend` |
| `tests/unit/health/test_signals.py` | `file_signals` join — no-signal vs real-zero, entropy 0-1→0-100, owner handoff |
+| `tests/unit/health/test_churn_complexity.py` | `churn_complexity_points` — no-churn omission, complexity never filters, danger-product sort, percentile scaling |
| `tests/unit/health/test_suggestions.py` | Suggestion strings keyed correctly |
| `tests/unit/health/test_health_config.py` | `.repowise/health-rules.json` parsing + glob matching |
| `tests/integration/test_health_coverage_integration.py` | End-to-end LCOV → analyzer → coverage_gap fires |
diff --git a/packages/core/src/repowise/core/analysis/health/README.md b/packages/core/src/repowise/core/analysis/health/README.md
index 5e0917bd1..1a90a4b02 100644
--- a/packages/core/src/repowise/core/analysis/health/README.md
+++ b/packages/core/src/repowise/core/analysis/health/README.md
@@ -92,6 +92,24 @@ Mirrored as `FileSignals` in `@repowise-dev/types/health`; surfaced in the
dashboard drawer, the file-page Health tab, the `/health/files/breakdown` +
`files/{path}` endpoints, and the MCP `get_context(include=["health"])` block.
+## Churn × complexity
+
+`churn_complexity.py` is the same pure, state-free join in service of the
+"hotspot anatomy" scatter:
+
+- `churn_complexity_points(metrics, git_meta_by_path)` returns one
+ `ChurnComplexityPoint` per recently-changed file — `commit_count_90d` (churn
+ axis), `max_ccn` (complexity axis), `nloc` (dot size), `score` (dot color via
+ band), `churn_percentile` (tooltip context) — sorted by the churn × complexity
+ "danger product" so a capped caller keeps the worst offenders.
+- Honesty rule: a file is omitted when it has no recent churn (nothing to plot
+ on the x-axis); complexity is **never** a filter, so a high-churn, simple file
+ is kept as a valid bottom-right signal.
+
+Mirrored as `ChurnComplexityPoint` in `@repowise-dev/types/health`; served by
+`GET /health/churn-complexity` and rendered by `ChurnComplexityQuadrant` on the
+Hotspots & churn dashboard tab.
+
## Refactoring suggestions
`suggestions.suggestion_for(biomarker_type)` returns the canonical, static
diff --git a/packages/core/src/repowise/core/analysis/health/churn_complexity.py b/packages/core/src/repowise/core/analysis/health/churn_complexity.py
new file mode 100644
index 000000000..9ccdbe70f
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/churn_complexity.py
@@ -0,0 +1,112 @@
+"""Churn x complexity scatter points (the "hotspot anatomy" view).
+
+Phase 4 of health surfacing: plot every recently-changed file by how often it
+changes (churn) against how tangled it is (complexity). The top-right corner is
+the danger zone -- files that are both volatile and complex are where defects
+concentrate and where refactoring pays off most. Pure surfacing: every input
+is already computed and persisted (churn from the git indexer, complexity from
+the walker, score from the health engine); no recompute, no new measurement,
+no LLM.
+
+State-free like :mod:`signals.py` and :mod:`trends.py` so the join logic stays
+unit-testable without a DB -- callers pass already-loaded rows and get plain
+dataclasses back. The same :func:`churn_complexity_points` assembler backs the
+REST endpoint today and any future export.
+
+Honesty rule: a file only earns a point when it has *recent churn* to speak of
+(``commit_count_90d > 0``). A file with no recent commits has nothing to say on
+the churn axis -- plotting it on the y-axis would imply a story that isn't
+there -- so it is omitted rather than pinned to zero. Complexity is never used
+to filter: a high-churn, low-complexity file is a real and useful bottom-right
+signal ("changes constantly but stays simple").
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Protocol
+
+
+class MetricLike(Protocol):
+ """The health-metric fields the quadrant reads (duck-typed).
+
+ Matches ``persistence.models.HealthFileMetric``; a Protocol so the
+ assembler stays free of any ORM import and tests can pass a stub.
+ """
+
+ file_path: str
+ score: float
+ max_ccn: int
+ nloc: int
+
+
+class GitMetaLike(Protocol):
+ """The churn fields the quadrant reads (duck-typed)."""
+
+ commit_count_90d: int | None
+ churn_percentile: float | None
+
+
+@dataclass
+class ChurnComplexityPoint:
+ """One file positioned in the churn x complexity plane.
+
+ ``commit_count_90d`` is the x (churn) axis, ``max_ccn`` the y (complexity)
+ axis, ``nloc`` encodes dot size, and ``score`` drives dot color via the
+ health band. ``churn_percentile`` (0-100) is repo-relative context shown in
+ the tooltip so a raw count is interpretable across repos of any size.
+ """
+
+ file_path: str
+ commit_count_90d: int
+ max_ccn: int
+ nloc: int
+ score: float
+ churn_percentile: float
+
+
+def _churn_pct(raw: float | None) -> float:
+ """Normalize the stored churn percentile to a 0-100 scale.
+
+ The column is stored 0-1; tolerate a 0-100 caller defensively (mirrors
+ ``churn-vs-bus-factor-scatter`` on the UI side). Absent -> 0.0 (the file is
+ simply un-ranked, not "no signal" -- the count axis carries the real data).
+ """
+ if raw is None:
+ return 0.0
+ return round(raw * 100.0, 1) if raw <= 1 else round(raw, 1)
+
+
+def churn_complexity_points(
+ metrics: list[MetricLike],
+ git_meta_by_path: dict[str, GitMetaLike],
+) -> list[ChurnComplexityPoint]:
+ """Assemble churn x complexity points from already-loaded rows.
+
+ *metrics* are the repo's ``HealthFileMetric`` rows; *git_meta_by_path* maps
+ ``file_path`` to its ``GitMetadata`` row (from ``get_all_git_metadata``).
+ No DB access and no recompute -- a plain join keyed on ``file_path``.
+
+ Returns the points sorted by the "danger product" (churn x complexity)
+ descending so a caller that caps the list keeps the most consequential
+ files. Files with no recent churn are omitted (see module docstring).
+ """
+ points: list[ChurnComplexityPoint] = []
+ for m in metrics:
+ g = git_meta_by_path.get(m.file_path)
+ commit_count = (g.commit_count_90d or 0) if g else 0
+ if commit_count <= 0:
+ continue
+ max_ccn = m.max_ccn or 0
+ points.append(
+ ChurnComplexityPoint(
+ file_path=m.file_path,
+ commit_count_90d=commit_count,
+ max_ccn=max_ccn,
+ nloc=m.nloc or 0,
+ score=round(m.score, 2),
+ churn_percentile=_churn_pct(g.churn_percentile if g else None),
+ )
+ )
+ points.sort(key=lambda p: (p.commit_count_90d * p.max_ccn, p.commit_count_90d), reverse=True)
+ return points
diff --git a/packages/server/src/repowise/server/routers/code_health.py b/packages/server/src/repowise/server/routers/code_health.py
index 8fee0ccc9..82f4d264c 100644
--- a/packages/server/src/repowise/server/routers/code_health.py
+++ b/packages/server/src/repowise/server/routers/code_health.py
@@ -16,6 +16,7 @@ from pydantic import BaseModel, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.health.churn_complexity import churn_complexity_points
from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracy
from repowise.core.analysis.health.grading import band_for
from repowise.core.analysis.health.grading import distribution as health_distribution
@@ -930,3 +931,40 @@ async def refactoring_targets(
}
targets.sort(key=sort_key_map[sort])
return {"targets": targets[:limit], "total": len(targets)}
+
+
+def _churn_complexity_to_dict(p: Any) -> dict:
+ return {
+ "file_path": p.file_path,
+ "commit_count_90d": p.commit_count_90d,
+ "max_ccn": p.max_ccn,
+ "nloc": p.nloc,
+ "score": p.score,
+ "churn_percentile": p.churn_percentile,
+ }
+
+
[email protected]("/api/repos/{repo_id}/health/churn-complexity")
+async def churn_complexity(
+ repo_id: str,
+ limit: int = Query(300, ge=1, le=1000),
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> dict:
+ """Churn x complexity scatter points -- the "hotspot anatomy" danger-zone view.
+
+ One point per recently-changed file: x = 90-day commit count (churn),
+ y = max cyclomatic complexity, dot size = NLOC, color = health band. The
+ top-right corner is where churn and complexity collide -- the highest-value
+ refactoring targets, plotted instead of listed.
+ """
+ repo = await crud.get_repository(session, repo_id)
+ if repo is None:
+ raise HTTPException(status_code=404, detail="Repository not found")
+
+ metrics = await crud.get_health_metrics(session, repo_id)
+ git_meta = await crud.get_all_git_metadata(session, repo_id)
+ points = churn_complexity_points(metrics, git_meta)
+ return {
+ "points": [_churn_complexity_to_dict(p) for p in points[:limit]],
+ "total": len(points),
+ }
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index a035307bc..d20312600 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -426,3 +426,28 @@ export interface RefactoringQuery {
max_effort?: string;
sort?: "impact_per_effort" | "total_impact" | "score" | "finding_count";
}
+
+/* ------------------------------------------------------------------ *
+ * Churn x complexity quadrant (the "hotspot anatomy" view)
+ * ------------------------------------------------------------------ */
+
+/**
+ * One file in the churn x complexity plane. `commit_count_90d` is the churn
+ * (x) axis, `max_ccn` the complexity (y) axis, `nloc` encodes dot size, and
+ * `score` drives dot color via the health band. `churn_percentile` (0-100) is
+ * repo-relative tooltip context so a raw count reads sensibly across repos of
+ * any size. Only files with recent churn (`commit_count_90d > 0`) are plotted.
+ */
+export interface ChurnComplexityPoint {
+ file_path: string;
+ commit_count_90d: number;
+ max_ccn: number;
+ nloc: number;
+ score: number;
+ churn_percentile: number;
+}
+
+export interface ChurnComplexityResponse {
+ points: ChurnComplexityPoint[];
+ total: number;
+}
diff --git a/packages/ui/__tests__/health/churn-complexity-quadrant.test.tsx b/packages/ui/__tests__/health/churn-complexity-quadrant.test.tsx
new file mode 100644
index 000000000..ac6883980
--- /dev/null
+++ b/packages/ui/__tests__/health/churn-complexity-quadrant.test.tsx
@@ -0,0 +1,55 @@
+import { describe, it, expect, vi } from "vitest";
+import { render, screen, fireEvent } from "@testing-library/react";
+import type { ChurnComplexityPoint } from "@repowise-dev/types/health";
+import { ChurnComplexityQuadrant } from "../../src/health/churn-complexity-quadrant.js";
+
+function pt(partial: Partial<ChurnComplexityPoint> & { file_path: string }): ChurnComplexityPoint {
+ return {
+ commit_count_90d: 5,
+ max_ccn: 8,
+ nloc: 100,
+ score: 7,
+ churn_percentile: 50,
+ ...partial,
+ };
+}
+
+describe("ChurnComplexityQuadrant", () => {
+ it("renders the empty state when there are no points", () => {
+ render(<ChurnComplexityQuadrant points={[]} />);
+ expect(screen.getByText(/needs git history/i)).toBeInTheDocument();
+ });
+
+ it("filters out files with no recent churn", () => {
+ render(<ChurnComplexityQuadrant points={[pt({ file_path: "a.py", commit_count_90d: 0 })]} />);
+ // Only the zero-churn file was passed → degenerates to the empty state.
+ expect(screen.getByText(/needs git history/i)).toBeInTheDocument();
+ });
+
+ it("plots points and labels the refactor (danger) zone", () => {
+ render(
+ <ChurnComplexityQuadrant
+ points={[
+ pt({ file_path: "hot.py", commit_count_90d: 30, max_ccn: 40, score: 3 }),
+ pt({ file_path: "calm.py", commit_count_90d: 2, max_ccn: 2, score: 9 }),
+ ]}
+ />,
+ );
+ expect(screen.getByText("Refactor zone")).toBeInTheDocument();
+ expect(screen.getByText(/2 files/)).toBeInTheDocument();
+ });
+
+ it("invokes onSelect when a dot is clicked", () => {
+ const onSelect = vi.fn();
+ const { container } = render(
+ <ChurnComplexityQuadrant
+ points={[pt({ file_path: "hot.py", commit_count_90d: 30, max_ccn: 40 })]}
+ onSelect={onSelect}
+ />,
+ );
+ const circle = container.querySelector("circle");
+ expect(circle).not.toBeNull();
+ fireEvent.click(circle!);
+ expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ file_path: "hot.py" }));
+ });
+});
diff --git a/packages/ui/src/health/churn-complexity-quadrant.tsx b/packages/ui/src/health/churn-complexity-quadrant.tsx
new file mode 100644
index 000000000..d1e3c8c3c
--- /dev/null
+++ b/packages/ui/src/health/churn-complexity-quadrant.tsx
@@ -0,0 +1,174 @@
+"use client";
+
+import { useMemo, useState } from "react";
+// Value imports must come from the package root, not the `/health` subpath:
+// the vite/rollup base alias clobbers subpath value resolution. Type-only
+// subpath imports are fine (erased before resolution).
+import { bandForScore } from "@repowise-dev/types";
+import type { ChurnComplexityPoint, HealthBand } from "@repowise-dev/types/health";
+
+export interface ChurnComplexityQuadrantProps {
+ points: ChurnComplexityPoint[];
+ onSelect?: (point: ChurnComplexityPoint) => void;
+ height?: number;
+}
+
+/* SVG fill class per canonical health band (the 3-bucket currency). Literal
+ * strings so Tailwind's static scanner keeps them. */
+const BAND_FILL: Record<HealthBand, string> = {
+ alert: "fill-[var(--color-error)]",
+ warning: "fill-[var(--color-caution)]",
+ healthy: "fill-[var(--color-success)]",
+};
+
+/** Median of a numeric list (the data-driven quadrant split). */
+function median(values: number[]): number {
+ if (values.length === 0) return 0;
+ const sorted = [...values].sort((a, b) => a - b);
+ const mid = Math.floor(sorted.length / 2);
+ return sorted.length % 2 === 0 ? (sorted[mid - 1]! + sorted[mid]!) / 2 : sorted[mid]!;
+}
+
+/**
+ * Churn x complexity quadrant -- the "hotspot anatomy" view. X = 90-day commit
+ * count (how often the file changes), Y = max cyclomatic complexity (how
+ * tangled it is). Dot size encodes NLOC; dot color is the health band. The
+ * dashed guides sit at the repo's median churn and median complexity, so the
+ * top-right tinted corner reads "busier AND more complex than a typical file
+ * here" -- the danger zone where defects concentrate and refactoring pays off.
+ *
+ * Inline SVG (no chart dep) so it stays cheap and reusable, matching the other
+ * health scatters.
+ */
+export function ChurnComplexityQuadrant({
+ points,
+ onSelect,
+ height = 320,
+}: ChurnComplexityQuadrantProps) {
+ const [hovered, setHovered] = useState<ChurnComplexityPoint | null>(null);
+ const data = useMemo(
+ () => points.filter((p) => p.commit_count_90d > 0 && Number.isFinite(p.max_ccn)),
+ [points],
+ );
+
+ const layout = useMemo(() => {
+ const maxCommits = Math.max(...data.map((d) => d.commit_count_90d), 1);
+ const maxCcn = Math.max(...data.map((d) => d.max_ccn), 1);
+ const maxNloc = Math.max(...data.map((d) => d.nloc), 1);
+ return {
+ maxCommits,
+ maxCcn,
+ maxNloc,
+ medCommits: median(data.map((d) => d.commit_count_90d)),
+ medCcn: median(data.map((d) => d.max_ccn)),
+ };
+ }, [data]);
+
+ if (data.length === 0) {
+ return (
+ <div
+ className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-sm text-[var(--color-text-tertiary)] text-center"
+ style={{ minHeight: height }}
+ >
+ No recently-changed files to plot yet. Churn x complexity needs git history.
+ </div>
+ );
+ }
+
+ const W = 640;
+ const H = height;
+ const padL = 44;
+ const padR = 12;
+ const padT = 24;
+ const padB = 34;
+ const plotW = W - padL - padR;
+ const plotH = H - padT - padB;
+
+ // 5% headroom so points never sit on the frame.
+ const xMax = layout.maxCommits * 1.05;
+ const yMax = layout.maxCcn * 1.05;
+ const xScale = (commits: number) => padL + (commits / xMax) * plotW;
+ const yScale = (ccn: number) => padT + ((yMax - ccn) / yMax) * plotH;
+ const r = (nloc: number) => 2 + Math.min(7, Math.sqrt(nloc / layout.maxNloc) * 7);
+
+ const midX = xScale(layout.medCommits);
+ const midY = yScale(layout.medCcn);
+
+ return (
+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">
+ <div className="mb-2 flex items-baseline gap-2">
+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">
+ Churn x complexity
+ </h3>
+ <span className="text-xs text-[var(--color-text-tertiary)]">
+ {data.length} files · dot size = NLOC · color = health
+ </span>
+ </div>
+ <div className="relative">
+ <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} role="img" aria-label="Churn vs complexity scatter plot">
+ {/* Danger-zone tint — top-right (high churn, high complexity) */}
+ <rect x={midX} y={padT} width={W - padR - midX} height={midY - padT} fill="currentColor" className="text-[var(--color-error)]/8" />
+
+ {/* Axes */}
+ <line x1={padL} y1={padT} x2={padL} y2={H - padB} stroke="currentColor" strokeOpacity={0.2} />
+ <line x1={padL} y1={H - padB} x2={W - padR} y2={H - padB} stroke="currentColor" strokeOpacity={0.2} />
+ {/* Median guide lines */}
+ <line x1={midX} y1={padT} x2={midX} y2={H - padB} stroke="currentColor" strokeOpacity={0.12} strokeDasharray="3 3" />
+ <line x1={padL} y1={midY} x2={W - padR} y2={midY} stroke="currentColor" strokeOpacity={0.12} strokeDasharray="3 3" />
+
+ {/* Axis labels */}
+ <text x={W / 2} y={H - 4} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6}>
+ Commits (90 days) →
+ </text>
+ <text x={12} y={H / 2} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6} transform={`rotate(-90 12 ${H / 2})`}>
+ Complexity (max CCN) →
+ </text>
+ <text x={midX} y={H - padB + 14} fontSize={9} textAnchor="middle" fill="currentColor" opacity={0.4}>
+ median
+ </text>
+
+ {/* Quadrant captions */}
+ <text x={W - padR - 6} y={padT + 13} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.6} className="font-medium">
+ Refactor zone
+ </text>
+ <text x={padL + 6} y={padT + 13} fontSize={10} fill="currentColor" opacity={0.45}>Complex, but stable</text>
+ <text x={W - padR - 6} y={H - padB - 6} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.45}>Churns, but simple</text>
+ <text x={padL + 6} y={H - padB - 6} fontSize={10} fill="currentColor" opacity={0.4}>Calm &amp; simple</text>
+
+ {/* Points */}
+ {data.map((p) => {
+ const cx = xScale(p.commit_count_90d);
+ const cy = yScale(p.max_ccn);
+ const isHovered = hovered?.file_path === p.file_path;
+ const fillCls = BAND_FILL[bandForScore(p.score)];
+ return (
+ <circle
+ key={p.file_path}
+ cx={cx}
+ cy={cy}
+ r={r(p.nloc) * (isHovered ? 1.4 : 1)}
+ className={`${fillCls} ${onSelect ? "cursor-pointer" : ""}`}
+ fillOpacity={0.7}
+ stroke={isHovered ? "white" : "none"}
+ strokeWidth={1.5}
+ onMouseEnter={() => setHovered(p)}
+ onMouseLeave={() => setHovered(null)}
+ onClick={onSelect ? () => onSelect(p) : undefined}
+ >
+ <title>{`${p.file_path}\n${p.commit_count_90d} commits/90d (${Math.round(p.churn_percentile)}th pct) · CCN ${p.max_ccn} · NLOC ${p.nloc} · score ${p.score.toFixed(1)}`}</title>
+ </circle>
+ );
+ })}
+ </svg>
+ {hovered ? (
+ <div className="pointer-events-none absolute bottom-2 left-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-[11px] shadow-md">
+ <span className="font-mono text-[var(--color-text-primary)]">{hovered.file_path}</span>
+ <span className="ml-2 text-[var(--color-text-tertiary)]">
+ {hovered.commit_count_90d} commits · CCN {hovered.max_ccn} · {hovered.score.toFixed(1)}
+ </span>
+ </div>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.ts
index f0c81e660..276eacb2d 100644
--- a/packages/ui/src/health/index.ts
+++ b/packages/ui/src/health/index.ts
@@ -23,6 +23,7 @@ export * from "./file-trend-chart";
export * from "./file-signals-panel";
export * from "./risk-coverage-scatter";
export * from "./impact-effort-quadrant";
+export * from "./churn-complexity-quadrant";
export * from "./health-file-drawer";
export * from "./ai-prompt-builder";
export * from "./ai-prompt-modal";
diff --git a/packages/web/src/components/risk/hotspots-tab.tsx b/packages/web/src/components/risk/hotspots-tab.tsx
index 8cf391fa7..3b794d559 100644
--- a/packages/web/src/components/risk/hotspots-tab.tsx
+++ b/packages/web/src/components/risk/hotspots-tab.tsx
@@ -13,11 +13,16 @@ import { ChurnHistogram } from "@repowise-dev/ui/git/churn-histogram";
import { CommitCategoryDonut } from "@repowise-dev/ui/git/commit-category-donut";
import { RiskDistributionChart } from "@repowise-dev/ui/git/risk-distribution-chart";
import { ChurnVsBusFactorScatter } from "@repowise-dev/ui/git/churn-vs-bus-factor-scatter";
+import { ChurnComplexityQuadrant } from "@repowise-dev/ui/health/churn-complexity-quadrant";
import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
import { getHotspotsPage } from "@/lib/api/git";
+import { getChurnComplexity } from "@/lib/api/code-health";
+import type { ChurnComplexityResponse } from "@/lib/api/code-health";
import type { HotspotResponse } from "@/lib/api/types";
+type ChurnView = "complexity" | "bus-factor";
+
const PAGE_SIZE = 100;
function hotspotToFileCard(h: HotspotRowType): FileCardData {
@@ -40,6 +45,14 @@ export function HotspotsTab({ repoId }: { repoId: string }) {
const { showFile, dialog } = useFileCardHost(repoId);
const [pageLimit, setPageLimit] = useState(PAGE_SIZE);
const [drawerSymbol, setDrawerSymbol] = useState<SymbolResponse | null>(null);
+ // Default to churn x complexity: complexity is more universally legible than
+ // bus factor, so it makes the friendlier first read of the danger zone.
+ const [churnView, setChurnView] = useState<ChurnView>("complexity");
+ const { data: churnComplexity } = useSWR<ChurnComplexityResponse>(
+ `health-churn-complexity:${repoId}`,
+ () => getChurnComplexity(repoId),
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
const {
data: hotspotsPage,
isLoading: loadingHotspots,
@@ -118,20 +131,62 @@ export function HotspotsTab({ repoId }: { repoId: string }) {
<Card>
<CardHeader className="pb-2">
- <CardTitle className="text-sm">Churn × bus factor</CardTitle>
+ <div className="flex items-center justify-between gap-2">
+ <CardTitle className="text-sm">
+ {churnView === "complexity" ? "Churn × complexity" : "Churn × bus factor"}
+ </CardTitle>
+ <div
+ className="inline-flex shrink-0 rounded-md border border-[var(--color-border-default)] p-0.5 text-xs"
+ role="tablist"
+ aria-label="Churn scatter view"
+ >
+ {(
+ [
+ ["complexity", "Complexity"],
+ ["bus-factor", "Bus factor"],
+ ] as [ChurnView, string][]
+ ).map(([value, label]) => (
+ <button
+ key={value}
+ type="button"
+ role="tab"
+ aria-selected={churnView === value}
+ onClick={() => setChurnView(value)}
+ className={`rounded px-2 py-0.5 transition-colors ${
+ churnView === value
+ ? "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]"
+ : "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
+ }`}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ </div>
<p className="text-xs text-[var(--color-text-tertiary)]">
- Top-right is the danger zone: high churn and a single owner. Bubble size
- reflects 90-day commit count.
+ {churnView === "complexity"
+ ? "Top-right is the refactor zone: files that change often AND are complex. Dot size is NLOC, color is health."
+ : "Top-right is the danger zone: high churn and a single owner. Bubble size reflects 90-day commit count."}
</p>
</CardHeader>
<CardContent className="pt-0">
- <ChurnVsBusFactorScatter
- hotspots={list}
- onSelect={(path) => {
- const hit = list.find((h) => h.file_path === path);
- if (hit) showFile(hotspotToFileCard(hit));
- }}
- />
+ {churnView === "complexity" ? (
+ <ChurnComplexityQuadrant
+ points={churnComplexity?.points ?? []}
+ onSelect={(p) => {
+ const hit = list.find((h) => h.file_path === p.file_path);
+ showFile(hit ? hotspotToFileCard(hit) : { file_path: p.file_path });
+ }}
+ />
+ ) : (
+ <ChurnVsBusFactorScatter
+ hotspots={list}
+ onSelect={(path) => {
+ const hit = list.find((h) => h.file_path === path);
+ if (hit) showFile(hotspotToFileCard(hit));
+ }}
+ />
+ )}
</CardContent>
</Card>
</div>
diff --git a/packages/web/src/lib/api/code-health.ts b/packages/web/src/lib/api/code-health.ts
index bebadeb38..aadb343c1 100644
--- a/packages/web/src/lib/api/code-health.ts
+++ b/packages/web/src/lib/api/code-health.ts
@@ -5,6 +5,7 @@
* them for back-compat and keeps only the fetch functions.
*/
import type {
+ ChurnComplexityResponse,
HealthFilesQuery,
HealthFilesResponse,
HealthFinding,
@@ -19,6 +20,8 @@ import { apiGet, apiPatch } from "./client";
export type {
BiomarkerBreakdownRow,
+ ChurnComplexityPoint,
+ ChurnComplexityResponse,
CoverageFileRow,
CoverageSummary,
DefectAccuracy,
@@ -117,3 +120,13 @@ export async function getRefactoringTargets(
opts as Record<string, string | number | boolean | undefined>,
);
}
+
+export async function getChurnComplexity(
+ repoId: string,
+ opts?: { limit?: number },
+): Promise<ChurnComplexityResponse> {
+ return apiGet<ChurnComplexityResponse>(
+ `/api/repos/${repoId}/health/churn-complexity`,
+ opts,
+ );
+}
diff --git a/tests/unit/health/test_churn_complexity.py b/tests/unit/health/test_churn_complexity.py
new file mode 100644
index 000000000..89b625221
--- /dev/null
+++ b/tests/unit/health/test_churn_complexity.py
@@ -0,0 +1,103 @@
+"""Tests for ``health/churn_complexity.py`` -- the churn x complexity join.
+
+The assembler is a pure surfacing layer: it plots only files with recent churn,
+never filters on complexity, normalizes the churn percentile to 0-100, and
+sorts by the danger product so a capped caller keeps the worst offenders.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from repowise.core.analysis.health.churn_complexity import (
+ ChurnComplexityPoint,
+ churn_complexity_points,
+)
+
+
+@dataclass
+class _Metric:
+ """Stub mirroring the HealthFileMetric fields the quadrant reads."""
+
+ file_path: str
+ score: float = 8.0
+ max_ccn: int = 5
+ nloc: int = 100
+
+
+@dataclass
+class _Git:
+ """Stub mirroring the GitMetadata fields the quadrant reads."""
+
+ commit_count_90d: int | None = 0
+ churn_percentile: float | None = None
+
+
+def test_empty_inputs_yield_no_points():
+ assert churn_complexity_points([], {}) == []
+
+
+def test_file_with_no_recent_churn_is_omitted():
+ # commit_count_90d == 0 -> nothing to say on the churn axis -> dropped.
+ metrics = [_Metric("a.py")]
+ points = churn_complexity_points(metrics, {"a.py": _Git(commit_count_90d=0)})
+ assert points == []
+
+
+def test_file_with_no_git_meta_is_omitted():
+ points = churn_complexity_points([_Metric("a.py")], {})
+ assert points == []
+
+
+def test_point_carries_all_axes():
+ metrics = [_Metric("a.py", score=3.4, max_ccn=22, nloc=420)]
+ git = {"a.py": _Git(commit_count_90d=14, churn_percentile=0.92)}
+ points = churn_complexity_points(metrics, git)
+ assert len(points) == 1
+ p = points[0]
+ assert isinstance(p, ChurnComplexityPoint)
+ assert p.file_path == "a.py"
+ assert p.commit_count_90d == 14
+ assert p.max_ccn == 22
+ assert p.nloc == 420
+ assert p.score == 3.4
+ assert p.churn_percentile == 92.0 # 0-1 stored -> 0-100 surfaced
+
+
+def test_low_complexity_high_churn_file_is_kept():
+ # Complexity is never a filter: a churny-but-simple file is a valid
+ # bottom-right signal, not noise.
+ metrics = [_Metric("simple.py", max_ccn=1)]
+ git = {"simple.py": _Git(commit_count_90d=30)}
+ points = churn_complexity_points(metrics, git)
+ assert len(points) == 1
+ assert points[0].max_ccn == 1
+
+
+def test_sorted_by_danger_product_descending():
+ metrics = [
+ _Metric("low.py", max_ccn=2),
+ _Metric("hot.py", max_ccn=40),
+ _Metric("mid.py", max_ccn=10),
+ ]
+ git = {
+ "low.py": _Git(commit_count_90d=3), # 6
+ "hot.py": _Git(commit_count_90d=20), # 800
+ "mid.py": _Git(commit_count_90d=10), # 100
+ }
+ points = churn_complexity_points(metrics, git)
+ assert [p.file_path for p in points] == ["hot.py", "mid.py", "low.py"]
+
+
+def test_churn_percentile_tolerates_already_scaled_value():
+ metrics = [_Metric("a.py")]
+ git = {"a.py": _Git(commit_count_90d=5, churn_percentile=87.0)}
+ points = churn_complexity_points(metrics, git)
+ assert points[0].churn_percentile == 87.0
+
+
+def test_missing_churn_percentile_defaults_to_zero():
+ metrics = [_Metric("a.py")]
+ git = {"a.py": _Git(commit_count_90d=5, churn_percentile=None)}
+ points = churn_complexity_points(metrics, git)
+ assert points[0].churn_percentile == 0.0
diff --git a/tests/unit/server/test_health_badge.py b/tests/unit/server/test_health_badge.py
index 2e150ca0e..7b7a785f1 100644
--- a/tests/unit/server/test_health_badge.py
+++ b/tests/unit/server/test_health_badge.py
@@ -3,10 +3,12 @@ per-file trend serializer's wire shape."""
from __future__ import annotations
+from repowise.core.analysis.health.churn_complexity import ChurnComplexityPoint
from repowise.core.analysis.health.signals import file_signals
from repowise.core.analysis.health.trends import FileTrend, FileTrendPoint
from repowise.server.routers.code_health import (
_badge_fields,
+ _churn_complexity_to_dict,
_file_signals_to_dict,
_file_trend_to_dict,
_render_badge_svg,
@@ -126,3 +128,23 @@ def test_file_signals_to_dict_populated_and_normalized() -> None:
assert d["primary_owner_name"] == "Ada"
assert d["in_degree"] == 9
assert d["out_degree"] == 4
+
+
+def test_churn_complexity_to_dict_wire_shape() -> None:
+ p = ChurnComplexityPoint(
+ file_path="a.py",
+ commit_count_90d=14,
+ max_ccn=22,
+ nloc=420,
+ score=3.4,
+ churn_percentile=92.0,
+ )
+ d = _churn_complexity_to_dict(p)
+ assert d == {
+ "file_path": "a.py",
+ "commit_count_90d": 14,
+ "max_ccn": 22,
+ "nloc": 420,
+ "score": 3.4,
+ "churn_percentile": 92.0,
+ }