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): stop alarming for a fall the code did not cause (#2171)

Raghav Chamadiyace350d1bb3a2
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index 948f18e57..da9ef64ac 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -537,8 +537,9 @@ KPI cards.
## 8. Trends (`trends.py`)
-State-free: callers pass an oldest-first list of snapshot rows. Two
-alerts:
+State-free: callers pass an oldest-first list of snapshot rows. Both alerts
+run over every metric in `_ALERT_METRICS` — hotspot health, the composite
+headline and maintainability — skipping any a snapshot never recorded:
- **Declining Health**: current is ≥ `DECLINE_THRESHOLD` (default 0.5)
below the snapshot `DECLINE_LOOKBACK` (5) positions back. Fires on the
@@ -547,6 +548,14 @@ alerts:
strictly below the one before. Magnitude is not required; direction is
the signal.
+Either can come back as a third `kind`, **`history_drag`**: a fall on the
+composite headline where `driver` is `history` and the structure half held or
+improved. It carries the same numbers and the opposite reading, because a
+decline the code shape did not contribute to has nothing to act on and
+reporting it in error red tells a reader their refactoring made things worse.
+Maintainability is code shape already, so it has no halves to split and never
+softens — it is the fall that always deserves the alarm.
+
`recent_kpis(history, limit=10)` returns a newest-first serialised view
for the CLI table and MCP `get_health(include=["trend"])` response.
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/trends.py b/packages/cli/src/repowise/cli/commands/health_cmd/trends.py
index 7f48fd77a..235792d74 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/trends.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/trends.py
@@ -9,6 +9,14 @@ from rich.table import Table
from repowise.cli.helpers import console, run_async
+# Rich style, mark and label per alert kind. ``history_drag`` is a fall the
+# code shape did not cause, so it reads as information rather than a warning.
+_ALERT_STYLE = {
+ "declining": ("red", "⚠", "declining"),
+ "predicted_decline": ("yellow", "⚠", "predicted decline"),
+ "history_drag": ("dim", "ℹ", "change history"),
+}
+
def _render_trend(repo_path: object, *, fmt: str) -> None:
"""Print the last 10 health snapshots straight from SQLite history.
@@ -62,6 +70,9 @@ def _render_trend(repo_path: object, *, fmt: str) -> None:
"baseline": a.baseline,
"delta": a.delta,
"message": a.message,
+ "driver": a.driver,
+ "structure_delta": a.structure_delta,
+ "history_delta": a.history_delta,
}
for a in (summary.alerts if summary else [])
],
@@ -90,5 +101,5 @@ def _render_trend(repo_path: object, *, fmt: str) -> None:
if summary and summary.alerts:
console.print()
for a in summary.alerts:
- color = "red" if a.kind == "declining" else "yellow"
- console.print(f"[{color}]⚠ {a.kind}[/{color}]: {a.message}")
+ style, mark, label = _ALERT_STYLE.get(a.kind, ("yellow", "⚠", a.kind))
+ console.print(f"[{style}]{mark} {label}[/{style}]: {a.message}")
diff --git a/packages/core/src/repowise/core/analysis/health/trends.py b/packages/core/src/repowise/core/analysis/health/trends.py
index acb9afde8..d0482eedd 100644
--- a/packages/core/src/repowise/core/analysis/health/trends.py
+++ b/packages/core/src/repowise/core/analysis/health/trends.py
@@ -7,14 +7,18 @@ Consumed by:
snapshots' KPIs side-by-side)
* the MCP ``get_health(include=["trend"])`` response
-Two alert kinds are emitted, matching plan §4 Phase 4 P4.1:
+Both detectors run over every metric in ``_ALERT_METRICS``, skipping any a
+snapshot never recorded. Three alert kinds come out:
- * ``declining`` — current ``hotspot_health`` is ≥ ``DECLINE_THRESHOLD``
- points (default 0.5) below the snapshot N-5 entries ago. This catches
- sustained drops, not single-snapshot noise.
+ * ``declining`` — the current reading is ≥ ``DECLINE_THRESHOLD`` points
+ (default 0.5) below the snapshot N-5 entries ago. This catches sustained
+ drops, not single-snapshot noise.
* ``predicted_decline`` — the three most recent snapshots are each
strictly below the one before them. Magnitude is not required —
direction is the signal.
+ * ``history_drag`` — either of the above on the composite headline, where
+ the only half that moved down was git history. Same numbers, opposite
+ reading: there is nothing in the code to act on.
The module is intentionally state-free. Callers pass in the snapshot
history (oldest → newest) and receive a list of alerts back. No DB
@@ -39,13 +43,28 @@ DECLINE_THRESHOLD: float = 0.5
DECLINE_LOOKBACK: int = 5 # compare current vs snapshot N positions back
PREDICTED_DECLINE_CONSECUTIVE: int = 3
+# Metrics a decline alert watches. ``maintainability_average`` is pure code
+# shape, so it is the one whose fall always answers to editing; it is absent
+# from snapshots taken before it was recorded and from narrowed ones, and a
+# metric a snapshot does not carry is skipped rather than read as zero.
+_ALERT_METRICS = ("hotspot_health", "average_health", "maintainability_average")
+
+_METRIC_LABEL = {
+ "hotspot_health": "Hotspot health",
+ "average_health": "Code health",
+ "maintainability_average": "Maintainability",
+}
+
@dataclass
class TrendAlert:
"""A single trend signal worth surfacing on the dashboard / CLI."""
- kind: str # "declining" | "predicted_decline"
- metric: str # "hotspot_health" | "average_health"
+ # ``history_drag`` is a decline whose whole cause is git history while the
+ # code shape held or improved. It carries the same numbers as ``declining``
+ # and the opposite reading, so a surface renders it as a watch item.
+ kind: str # "declining" | "predicted_decline" | "history_drag"
+ metric: str # one of _ALERT_METRICS
current: float
baseline: float | None
delta: float
@@ -231,82 +250,137 @@ def hotspot_trend(history: list[Any]) -> str | None:
return "stable"
+def _metric_value(snap: Any, metric: str) -> float | None:
+ """One metric off a snapshot, ``None`` when it was never recorded."""
+ value = getattr(snap, metric, None)
+ return None if value is None else float(value)
+
+
+def _build_alert(
+ *,
+ kind: str,
+ metric: str,
+ current: float,
+ baseline: float,
+ delta: float,
+ movement: str,
+ attribution: tuple[str | None, float | None, float | None],
+) -> TrendAlert:
+ """One alert, re-read as a watch item when only history moved.
+
+ *movement* names the fall and its window, e.g. "dropped 0.62 points vs.
+ snapshot 5 ago"; what follows depends on what drove it. A decline the code
+ shape did not contribute to is not something to fix, and reporting it in
+ the same red as a real regression tells a reader their refactoring made
+ things worse. Such a decline keeps every number and swaps the reading.
+ """
+ driver, structure, history_share = attribution
+ label = _METRIC_LABEL[metric]
+ window = f"({baseline:.2f} → {current:.2f})"
+ # Both halves are checked, not just the driver. ``driver`` names whichever
+ # moved further, which on a repo with floored files can be a half that
+ # moved *up*: the halves are deduction means and the score is a mean of
+ # clamped scores, so the two can disagree about direction. Claiming a cause
+ # is only honest when history is the one half that actually fell.
+ only_history_fell = (
+ structure is not None and structure >= 0 and history_share is not None and history_share < 0
+ )
+ if driver == "history" and only_history_fell:
+ shape = "held" if round(structure or 0.0, 2) == 0 else f"improved {structure:.2f}"
+ message = (
+ f"{label} {movement} {window}, and code shape {shape} over the same "
+ f"window. Change history is the only half that moved down, and no "
+ f"edit to these files settles it."
+ )
+ kind = "history_drag"
+ else:
+ message = f"{label} {movement} {window}.{_driver_sentence(driver, structure, history_share)}"
+ return TrendAlert(
+ kind=kind,
+ metric=metric,
+ current=round(current, 2),
+ baseline=round(baseline, 2),
+ delta=delta,
+ message=message,
+ driver=driver,
+ structure_delta=structure,
+ history_delta=history_share,
+ )
+
+
def _declining_alerts(history: list[Any]) -> list[TrendAlert]:
- """``Declining Health`` — current is ≥ threshold below snapshot N-5."""
+ """Current reading is at least the threshold below snapshot N-5."""
if len(history) <= DECLINE_LOOKBACK:
return []
current = history[-1]
baseline = history[-1 - DECLINE_LOOKBACK]
out: list[TrendAlert] = []
- for metric in ("hotspot_health", "average_health"):
- cur_val = float(getattr(current, metric))
- base_val = float(getattr(baseline, metric))
+ for metric in _ALERT_METRICS:
+ cur_val = _metric_value(current, metric)
+ base_val = _metric_value(baseline, metric)
+ if cur_val is None or base_val is None:
+ continue
delta = round(cur_val - base_val, 3)
- if delta <= -DECLINE_THRESHOLD:
- driver, structure, history = (
- _attribution(current, baseline)
- if metric == "average_health"
- else (None, None, None)
- )
- out.append(
- TrendAlert(
- kind="declining",
- metric=metric,
- current=round(cur_val, 2),
- baseline=round(base_val, 2),
- delta=delta,
- message=(
- f"{metric.replace('_', ' ').title()} dropped "
- f"{abs(delta):.2f} points vs. snapshot "
- f"{DECLINE_LOOKBACK} ago "
- f"({base_val:.2f} → {cur_val:.2f})."
- f"{_driver_sentence(driver, structure, history)}"
- ),
- driver=driver,
- structure_delta=structure,
- history_delta=history,
- )
+ if delta > -DECLINE_THRESHOLD:
+ continue
+ out.append(
+ _build_alert(
+ kind="declining",
+ metric=metric,
+ current=cur_val,
+ baseline=base_val,
+ delta=delta,
+ movement=f"dropped {abs(delta):.2f} points vs. snapshot {DECLINE_LOOKBACK} ago",
+ attribution=_attribution_for(metric, current, baseline),
)
+ )
return out
def _predicted_decline_alerts(history: list[Any]) -> list[TrendAlert]:
- """``Predicted Decline`` — N consecutive strict drops, any magnitude."""
+ """N consecutive strict drops, any magnitude."""
needed = PREDICTED_DECLINE_CONSECUTIVE + 1
if len(history) < needed:
return []
tail = history[-needed:]
out: list[TrendAlert] = []
- for metric in ("hotspot_health", "average_health"):
- vals = [float(getattr(s, metric)) for s in tail]
- if all(vals[i + 1] < vals[i] for i in range(len(vals) - 1)):
- delta = round(vals[-1] - vals[0], 3)
- driver, structure, history = (
- _attribution(tail[-1], tail[0])
- if metric == "average_health"
- else (None, None, None)
- )
- out.append(
- TrendAlert(
- kind="predicted_decline",
- metric=metric,
- current=round(vals[-1], 2),
- baseline=round(vals[0], 2),
- delta=delta,
- message=(
- f"{metric.replace('_', ' ').title()} declined for "
- f"{PREDICTED_DECLINE_CONSECUTIVE} consecutive snapshots "
- f"({vals[0]:.2f} → {vals[-1]:.2f})."
- f"{_driver_sentence(driver, structure, history)}"
- ),
- driver=driver,
- structure_delta=structure,
- history_delta=history,
- )
+ for metric in _ALERT_METRICS:
+ vals = [_metric_value(s, metric) for s in tail]
+ # One missing reading drops the metric rather than shortening the run:
+ # three drops either side of a gap are not three consecutive drops.
+ if any(v is None for v in vals):
+ continue
+ readings = [v for v in vals if v is not None] # narrows float | None
+ if not all(readings[i + 1] < readings[i] for i in range(len(readings) - 1)):
+ continue
+ delta = round(readings[-1] - readings[0], 3)
+ out.append(
+ _build_alert(
+ kind="predicted_decline",
+ metric=metric,
+ current=readings[-1],
+ baseline=readings[0],
+ delta=delta,
+ movement=f"declined for {PREDICTED_DECLINE_CONSECUTIVE} consecutive snapshots",
+ attribution=_attribution_for(metric, tail[-1], tail[0]),
)
+ )
return out
+def _attribution_for(
+ metric: str, current: Any, baseline: Any
+) -> tuple[str | None, float | None, float | None]:
+ """The structure / history split, which only the composite headline has.
+
+ Maintainability is already code shape alone and the hotspot figure never
+ had its halves snapshotted, so neither one splits.
+ """
+ if metric != "average_health":
+ return None, None, None
+ return _attribution(current, baseline)
+
+
def drop_unscoped_fields(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Blank the per-row figures a narrowed snapshot never recorded.
diff --git a/packages/server/src/repowise/server/schemas/code_health.py b/packages/server/src/repowise/server/schemas/code_health.py
index 4c31633c9..c6379340e 100644
--- a/packages/server/src/repowise/server/schemas/code_health.py
+++ b/packages/server/src/repowise/server/schemas/code_health.py
@@ -117,6 +117,8 @@ class HealthTrendSummary(BaseModel):
class HealthTrendAlert(BaseModel):
+ #: ``declining`` and ``predicted_decline`` are regressions; ``history_drag``
+ #: is a fall the code shape did not cause and there is nothing to act on.
kind: str
metric: str
current: float
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index 523c385b0..3fbb26b19 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -857,6 +857,11 @@ export interface HealthTrendResponse {
current_history_deduction?: number | null;
};
alerts: Array<{
+ /**
+ * `"declining"` and `"predicted_decline"` are regressions. `"history_drag"`
+ * is a fall whose whole cause is git history while the code shape held or
+ * improved: the same numbers with the opposite reading, and nothing to fix.
+ */
kind: string;
metric: string;
current: number;
diff --git a/packages/ui/__tests__/health/trend-view.test.tsx b/packages/ui/__tests__/health/trend-view.test.tsx
index bbcc8ef39..09e91236e 100644
--- a/packages/ui/__tests__/health/trend-view.test.tsx
+++ b/packages/ui/__tests__/health/trend-view.test.tsx
@@ -85,3 +85,57 @@ describe("TrendView — largest score changes", () => {
expect(screen.queryByText(/Showing the/)).not.toBeInTheDocument();
});
});
+
+describe("TrendView — how a decline is reported", () => {
+ // A fall the code shape did not cause is not the reader's doing. Reporting
+ // it in the same red as a regression is what told someone a week of
+ // refactoring had made things worse.
+
+ const alert = (kind: string) => ({
+ kind,
+ metric: "average_health",
+ current: 7,
+ baseline: 7.6,
+ delta: -0.6,
+ message: "Code health dropped 0.60 points.",
+ });
+
+ // Scoped to the lead element itself. Asserting over the whole tree would
+ // pass or fail on the KPI ribbon's colours, which have nothing to do with
+ // how an alert is reported.
+ const leadColour = (text: string) => screen.getByText(text).getAttribute("style") ?? "";
+
+ it("paints a history-driven fall neutrally, not in the error colour", () => {
+ render(
+ <TrendView data={response({ alerts: [alert("history_drag")] })} isLoading={false} error={null} />,
+ );
+ expect(leadColour("Change history, not code.")).toContain("var(--color-text-secondary)");
+ });
+
+ it("still paints a real regression in the error colour", () => {
+ render(
+ <TrendView data={response({ alerts: [alert("declining")] })} isLoading={false} error={null} />,
+ );
+ expect(leadColour("Declining.")).toContain("var(--color-error)");
+ });
+
+ it("does not name a figure the message contradicts", () => {
+ render(
+ <TrendView
+ data={response({
+ alerts: [{ ...alert("declining"), metric: "maintainability_average" }],
+ })}
+ isLoading={false}
+ error={null}
+ />,
+ );
+ expect(screen.queryByText("Declining health.")).toBeNull();
+ });
+
+ it("treats an unrecognised kind as a warning rather than dropping it", () => {
+ render(
+ <TrendView data={response({ alerts: [alert("something_new")] })} isLoading={false} error={null} />,
+ );
+ expect(screen.getByText("Predicted decline.")).toBeTruthy();
+ });
+});
diff --git a/packages/ui/src/health/trend-chart.tsx b/packages/ui/src/health/trend-chart.tsx
index c03255139..702e9c27f 100644
--- a/packages/ui/src/health/trend-chart.tsx
+++ b/packages/ui/src/health/trend-chart.tsx
@@ -84,6 +84,13 @@ export function TrendChart({ history, height = 220 }: TrendChartProps) {
};
const hasMaintainability = history.some((p) => p.maintainability_average != null);
+ // Maintainability leads wherever it was recorded. It is the series that
+ // answers "is my code getting better", and the composite it sits beside
+ // moves with git history too, so drawing the composite loudest emphasises
+ // the number that misleads. Without a maintainability series the composite
+ // is the only headline there is, and keeps the weight.
+ const leadWidth = 2.4;
+ const supportWidth = hasMaintainability ? 1.4 : 1.8;
// The band between the score history does not touch and the score itself:
// what git history costs, drawn where the lede says it in words. Only over
@@ -113,10 +120,10 @@ export function TrendChart({ history, height = 220 }: TrendChartProps) {
KPI trend
</h3>
<div className="flex flex-wrap items-center gap-3 text-xs text-[var(--color-text-tertiary)]">
- <Legend dot="bg-[var(--color-success)]" label="Code health" />
{hasMaintainability && (
<Legend dot="bg-[var(--color-accent-secondary)]" label="Maintainability" />
)}
+ <Legend dot="bg-[var(--color-success)]" label="Code health" />
{historyBands.length > 0 && (
<span className="inline-flex items-center gap-1">
<span className="inline-block h-2 w-2 rounded-[1px] bg-current opacity-25" />
@@ -137,38 +144,73 @@ export function TrendChart({ history, height = 220 }: TrendChartProps) {
</text>
</g>
))}
- {/* Under the lines: the band is context for them, not a mark of its own. */}
+ {/* Under the lines: the band is context for them, not a mark of its own.
+ Its edges are stroked in the code-health colour because the band
+ belongs to that line — it runs from the score up to where the score
+ would sit with no history against it. Unstroked, it read as bounding
+ whichever line happened to fall inside it. The lower edge lies on the
+ code-health line itself, so only the upper one shows. */}
{historyBands.map((d, i) => (
- <path key={i} d={d} fill="currentColor" fillOpacity={0.07} stroke="none" />
+ <path
+ key={i}
+ d={d}
+ fill="currentColor"
+ fillOpacity={0.07}
+ stroke="var(--color-success)"
+ strokeOpacity={0.35}
+ strokeWidth={1}
+ strokeDasharray="2 3"
+ />
))}
- <path d={path("average_health")} stroke="var(--color-success)" strokeWidth={1.8} fill="none" />
+ <path
+ d={path("average_health")}
+ stroke="var(--color-success)"
+ strokeWidth={supportWidth}
+ fill="none"
+ />
+ <path
+ d={path("hotspot_health")}
+ stroke="var(--color-warning)"
+ strokeWidth={supportWidth}
+ fill="none"
+ />
+ <path d={path("worst_performer_score")} stroke="var(--color-error)" strokeWidth={1.4} fill="none" strokeDasharray="3 3" />
+ {/* Last, so the lead series is never crossed out by a support line. */}
{hasMaintainability && (
<path
d={path("maintainability_average")}
stroke="var(--color-accent-secondary)"
- strokeWidth={1.8}
+ strokeWidth={leadWidth}
fill="none"
/>
)}
- <path d={path("hotspot_health")} stroke="var(--color-warning)" strokeWidth={1.8} fill="none" />
- <path d={path("worst_performer_score")} stroke="var(--color-error)" strokeWidth={1.4} fill="none" strokeDasharray="3 3" />
{history.map((p, i) => (
<g key={i}>
- <circle cx={xScale(i)} cy={yScale(p.average_health)} r={2.5} fill="var(--color-success)" />
- {p.maintainability_average != null ? (
+ <circle
+ cx={xScale(i)}
+ cy={yScale(p.average_health)}
+ r={hasMaintainability ? 2 : 2.5}
+ fill="var(--color-success)"
+ />
+ {p.hotspot_health != null ? (
<circle
cx={xScale(i)}
- cy={yScale(p.maintainability_average)}
- r={2.5}
- fill="var(--color-accent-secondary)"
+ cy={yScale(p.hotspot_health)}
+ r={hasMaintainability ? 2 : 2.5}
+ fill="var(--color-warning)"
/>
) : null}
- {p.hotspot_health != null ? (
- <circle cx={xScale(i)} cy={yScale(p.hotspot_health)} r={2.5} fill="var(--color-warning)" />
- ) : null}
{p.worst_performer_score != null ? (
<circle cx={xScale(i)} cy={yScale(p.worst_performer_score)} r={2} fill="var(--color-error)" />
) : null}
+ {p.maintainability_average != null ? (
+ <circle
+ cx={xScale(i)}
+ cy={yScale(p.maintainability_average)}
+ r={3}
+ fill="var(--color-accent-secondary)"
+ />
+ ) : null}
</g>
))}
{history.length > 1 ? (
diff --git a/packages/ui/src/health/trend-view.tsx b/packages/ui/src/health/trend-view.tsx
index 851d592ad..2e27899a1 100644
--- a/packages/ui/src/health/trend-view.tsx
+++ b/packages/ui/src/health/trend-view.tsx
@@ -18,7 +18,7 @@
* double-fetched alongside anything else on the page.
*/
-import { AlertTriangle } from "lucide-react";
+import { AlertTriangle, Info } from "lucide-react";
import type { HealthCounts, HealthTrendResponse } from "@repowise-dev/types/health";
import { Skeleton } from "../ui/skeleton";
@@ -35,6 +35,32 @@ import { deltaColor, formatDelta, scoreTextColor } from "./tokens";
*/
const SLOPE_MAX = 18;
+/**
+ * Colour, lead phrase and icon per alert kind.
+ *
+ * A `history_drag` fall is not the reader's doing and there is nothing to act
+ * on, so it takes the neutral treatment the drawer gives history findings
+ * rather than the error red. Painting it red is what told a reader their
+ * refactoring had made things worse. An unknown kind falls through to the
+ * warning treatment, which is the safe reading of a signal we cannot classify.
+ */
+function alertTreatment(kind: string): { color: string; label: string; watch: boolean } {
+ if (kind === "declining") {
+ // Not "Declining health.": three different figures raise this alert and the
+ // message names which one, so a lead that named a fourth thing contradicted it.
+ return { color: "var(--color-error)", label: "Declining.", watch: false };
+ }
+ if (kind === "history_drag") {
+ return {
+ color: "var(--color-text-secondary)",
+ label: "Change history, not code.",
+ watch: true,
+ };
+ }
+ return { color: "var(--color-warning)", label: "Predicted decline.", watch: false };
+}
+
+
export function TrendView({
data,
isLoading,
@@ -80,7 +106,7 @@ export function TrendView({
const stats: RibbonStat[] = [
{
- label: "Average health",
+ label: "Code health",
value: otherReading ? "—" : summary.current_average_health.toFixed(1),
...(otherReading
? { sub: "recorded on the full score" }
@@ -122,18 +148,14 @@ export function TrendView({
{data.alerts.length > 0 && (
<div className="flex flex-col gap-2">
{data.alerts.map((a, i) => {
- const color =
- a.kind === "declining" ? "var(--color-error)" : "var(--color-warning)";
+ const { color, label, watch } = alertTreatment(a.kind);
+ const Icon = watch ? Info : AlertTriangle;
return (
<p key={i} className="flex items-start gap-2 text-sm">
- <AlertTriangle
- className="mt-0.5 h-4 w-4 shrink-0"
- style={{ color }}
- aria-hidden
- />
+ <Icon className="mt-0.5 h-4 w-4 shrink-0" style={{ color }} aria-hidden />
<span>
<strong className="font-semibold" style={{ color }}>
- {a.kind === "declining" ? "Declining health." : "Predicted decline."}
+ {label}
</strong>{" "}
<span className="text-[var(--color-text-secondary)]">{a.message}</span>
</span>
diff --git a/tests/unit/health/test_trends.py b/tests/unit/health/test_trends.py
index 251b00aa0..602156ba8 100644
--- a/tests/unit/health/test_trends.py
+++ b/tests/unit/health/test_trends.py
@@ -92,6 +92,170 @@ def test_recent_kpis_orders_newest_first():
assert scores == [7.0, 6.0, 5.0]
+# --------------------------------------------------------------------------- #
+# Attribution: what a decline is blamed on
+# --------------------------------------------------------------------------- #
+
+
+@dataclass
+class _Split(_S):
+ """A snapshot carrying the two halves and the maintainability figure."""
+
+ structure_average: float | None = None
+ history_average: float | None = None
+ maintainability_average: float | None = None
+
+
+def _split_series(rows: list[tuple[float, float, float]]) -> list[_Split]:
+ """Snapshots from ``(average_health, structure_deduction, history_deduction)``."""
+ return [
+ _Split(
+ taken_at=_ts(i),
+ hotspot_health=10.0,
+ average_health=avg,
+ structure_average=structure,
+ history_average=history,
+ )
+ for i, (avg, structure, history) in enumerate(rows)
+ ]
+
+
+def test_a_decline_the_code_shape_did_not_cause_is_not_an_alarm():
+ """The founding case: history rises through a week of refactoring."""
+ flat = (8.0, 1.60, 1.20)
+ rows = [flat] * 6 + [(8.0 - DECLINE_THRESHOLD - 0.1, 1.30, 2.10)]
+ summary = diff_snapshots(_split_series(rows))
+ alerts = [a for a in summary.alerts if a.metric == "average_health"]
+ assert [a.kind for a in alerts] == ["history_drag"]
+ alert = alerts[0]
+ assert alert.driver == "history"
+ assert alert.structure_delta == 0.3
+ assert "code shape improved 0.30" in alert.message
+ assert "Change history is the only half that moved down" in alert.message
+ assert "dropped 0.60 points" in alert.message
+
+
+def test_a_decline_the_code_shape_shares_stays_an_alarm():
+ """History still leads, but structure fell too — that is a real regression."""
+ flat = (8.0, 1.60, 1.20)
+ rows = [flat] * 6 + [(8.0 - DECLINE_THRESHOLD - 0.1, 1.85, 2.10)]
+ summary = diff_snapshots(_split_series(rows))
+ alerts = [a for a in summary.alerts if a.metric == "average_health"]
+ assert [a.kind for a in alerts] == ["declining"]
+ assert alerts[0].driver == "history"
+
+
+def test_a_structure_led_decline_stays_an_alarm():
+ flat = (8.0, 1.60, 1.20)
+ rows = [flat] * 6 + [(8.0 - DECLINE_THRESHOLD - 0.1, 2.50, 1.20)]
+ summary = diff_snapshots(_split_series(rows))
+ alerts = [a for a in summary.alerts if a.metric == "average_health"]
+ assert [a.kind for a in alerts] == ["declining"]
+ assert alerts[0].driver == "structure"
+
+
+def test_code_shape_holding_still_reads_as_a_watch_item():
+ flat = (8.0, 1.60, 1.20)
+ rows = [flat] * 6 + [(8.0 - DECLINE_THRESHOLD - 0.1, 1.60, 2.10)]
+ alerts = [
+ a for a in diff_snapshots(_split_series(rows)).alerts if a.metric == "average_health"
+ ]
+ assert alerts[0].kind == "history_drag"
+ assert "code shape held" in alerts[0].message
+
+
+def test_a_fall_neither_half_explains_stays_an_alarm():
+ """Both halves improved while the clamped score fell.
+
+ ``driver`` names the half that moved furthest, which is not the same as the
+ half that moved down. Muting the alarm here would blame a fall on a half
+ that had just got better.
+ """
+ flat = (8.0, 1.60, 1.20)
+ rows = [flat] * 6 + [(8.0 - DECLINE_THRESHOLD - 0.1, 1.50, 0.70)]
+ alerts = [
+ a for a in diff_snapshots(_split_series(rows)).alerts if a.metric == "average_health"
+ ]
+ assert [a.kind for a in alerts] == ["declining"]
+ assert alerts[0].driver == "history"
+ assert alerts[0].history_delta == 0.5
+
+
+def test_a_shape_gain_too_small_to_show_reads_as_held():
+ """0.004 formats as 0.00, and "improved 0.00" is the held case mislabelled."""
+ flat = (8.0, 1.600, 1.200)
+ rows = [flat] * 6 + [(8.0 - DECLINE_THRESHOLD - 0.1, 1.596, 2.100)]
+ alert = next(
+ a for a in diff_snapshots(_split_series(rows)).alerts if a.metric == "average_health"
+ )
+ assert alert.kind == "history_drag"
+ assert "code shape held" in alert.message
+
+
+def test_a_predicted_decline_is_attributed_the_same_way():
+ rows = [(8.0, 1.60, 1.20), (7.9, 1.55, 1.35), (7.8, 1.50, 1.50), (7.7, 1.45, 1.65)]
+ alerts = [
+ a for a in diff_snapshots(_split_series(rows)).alerts if a.metric == "average_health"
+ ]
+ assert [a.kind for a in alerts] == ["history_drag"]
+
+
+def test_the_headline_is_named_code_health_not_average_health():
+ vals = [8.0] * 6 + [8.0 - DECLINE_THRESHOLD - 0.1]
+ alerts = diff_snapshots(_series(vals)).alerts
+ messages = {a.metric: a.message for a in alerts}
+ assert messages["average_health"].startswith("Code health dropped")
+ assert messages["hotspot_health"].startswith("Hotspot health dropped")
+
+
+# --------------------------------------------------------------------------- #
+# Maintainability
+# --------------------------------------------------------------------------- #
+
+
+def _maintainability_series(values: list[float]) -> list[_Split]:
+ return [
+ _Split(
+ taken_at=_ts(i),
+ hotspot_health=10.0,
+ average_health=10.0,
+ maintainability_average=v,
+ )
+ for i, v in enumerate(values)
+ ]
+
+
+def test_maintainability_declines_are_alerted():
+ """Nothing watched the one figure a refactor is supposed to move."""
+ vals = [8.5] * 6 + [8.5 - DECLINE_THRESHOLD - 0.1]
+ alerts = [
+ a
+ for a in diff_snapshots(_maintainability_series(vals)).alerts
+ if a.metric == "maintainability_average"
+ ]
+ assert [a.kind for a in alerts] == ["declining"]
+ assert alerts[0].message.startswith("Maintainability dropped 0.60 points")
+
+
+def test_a_maintainability_fall_is_never_blamed_on_history():
+ """It is code shape already, so it has no halves to split and never softens."""
+ vals = [8.5] * 6 + [8.5 - DECLINE_THRESHOLD - 0.1]
+ alert = next(
+ a
+ for a in diff_snapshots(_maintainability_series(vals)).alerts
+ if a.metric == "maintainability_average"
+ )
+ assert alert.driver is None
+ assert alert.structure_delta is None
+
+
+def test_snapshots_without_maintainability_raise_no_alert():
+ """Series predating the column must not read a missing figure as zero."""
+ vals = [8.0] * 6 + [8.0 - DECLINE_THRESHOLD - 0.1]
+ alerts = diff_snapshots(_series(vals)).alerts
+ assert not [a for a in alerts if a.metric == "maintainability_average"]
+
+
# --------------------------------------------------------------------------- #
# Per-file trajectory
# --------------------------------------------------------------------------- #