Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(health): per-file score over time on the file page, drawer, and MCP (#489)
Raghav Chamadiyaf02a386c6d27
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.mdindex 05c906d16..bc317b5dd 100644--- a/docs/CODE_HEALTH.md+++ b/docs/CODE_HEALTH.md@@ -337,7 +337,10 @@ get_health(targets=["module:src.api"]) # everything in a module## TrendsEvery health run writes a `HealthSnapshot` row (rolling 50 entries per repo).-Two alerts run over the history:+Each snapshot stores the repo KPIs **and** a compact `{path: score}` map, so+the history doubles as a per-file record.++Two repo-level alerts run over the history:- **Declining Health** — current `hotspot_health` is ≥ 0.5 below thesnapshot 5 runs ago.@@ -356,6 +359,31 @@ Or from MCP:get_health(include=["trend"])```+### Per-file score over time++The same snapshots power a per-file trajectory — a file's score plotted+across runs (CodeScene's signature view). It surfaces on the file's Health+tab and in the health drawer as a sparkline, with a delta vs. the previous+run and a **Declining** flag (the per-file version of the alerts above:+≥ 0.5 below the run 5 snapshots back, or three consecutive drops).++A trend is **silent on thin history** — it needs at least two snapshots that+both carry the file, otherwise the UI shows "no score history yet" rather+than a misleading single dot. Gaps (a file absent from some snapshots) are+skipped, not zero-filled.++Fetch it directly:++```bash+# REST — one file's series + current delta + declining flag+GET /api/repos/{repo_id}/health/files/trend?file_path=path/to/file.py+```++```python+# MCP — targeted mode attaches a per-file `trends` block+get_health(targets=["path/to/file.py"])+```+## ConfigurationPer-file overrides live in `.repowise/health-rules.json`:diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.mdindex d66d3682a..3d6bbd92f 100644--- a/docs/architecture/code-health.md+++ b/docs/architecture/code-health.md@@ -65,7 +65,7 @@ analysis/health/├── scoring.py # weighted aggregation, category caps, KPIs├── grading.py # 3 defect-backed bands + NLOC-weighted distribution├── defect_accuracy.py # "does the score find the bugs?" self-validation-├── trends.py # snapshot diff, Declining/Predicted alerts+├── trends.py # snapshot diff, Declining/Predicted alerts, per-file score series├── suggestions.py # deterministic refactoring text per biomarker├── config.py # HealthConfig + .repowise/health-rules.json├── models.py # HealthFindingData, HealthFileMetricData, HealthReport@@ -177,6 +177,9 @@ packages/ui/src/health/ # shared React components (used by web + fut├── refactoring-target-list.tsx├── health-badge.tsx # score pill, colored by the 3 health bands├── health-distribution-bar.tsx # NLOC-weighted Alert/Warning/Healthy split+├── trend-chart.tsx # repo KPI history (3 series)+├── file-trend-chart.tsx # single file's score-over-time + delta + declining flag+├── sparkline.tsx # compact inline series (drawer trend)└── module-rollup-list.tsxpackages/web/src/app/repos/[id]/health/@@ -537,6 +540,26 @@ alerts:`recent_kpis(history, limit=10)` returns a newest-first serialised viewfor the CLI table and MCP `get_health(include=["trend"])` response.+### Per-file trajectory++Snapshots also store a compact `{path: score}` map (`per_file_scores_json`),+so the same window yields a single file's score-over-time series:++- `file_score_series(history, path)` — oldest-first `FileTrendPoint`s,+ skipping snapshots that don't carry the file. Returns `[]` below two+ points (silent on thin history). This is the exact function the PR bot+ reuses for its in-comment sparkline.+- `file_trend(history, path)` — wraps the series with `current` / `previous`+ / `delta` and a `declining` flag (the per-file mirror of the alerts above:+ ≥ `DECLINE_THRESHOLD` below the lookback point, or+ `PREDICTED_DECLINE_CONSECUTIVE` consecutive drops). `snapshot_count` is the+ full window size so a young repo is distinguishable from a file missing in+ older snapshots.++Both are state-free; the server serialises `FileTrend` via+`_file_trend_to_dict` and embeds it in the file-detail health block, the+health-breakdown response, and the standalone trend route (§13).+---## 9. Incremental analysis — the `repowise update` path@@ -665,8 +688,10 @@ Defined in `tool_health.py`. Modes:`worst_files` (top N lowest-scoring) + `top_findings` + a per-module`modules` rollup.- **Targeted mode** (`targets=[...]`) — returns full `metrics` +- `findings` for the listed paths. Targets prefixed `module:foo` expand- to the file set in that module.+ `findings` for the listed paths, plus a per-file `trends` block (compact+ score series + `current` + `delta` + `declining`) for any target with at+ least two snapshots of history. Targets prefixed `module:foo` expand to+ the file set in that module.`include` flags layer richer data:@@ -702,6 +727,9 @@ Every response carries the standard `_meta` envelope via `build_meta()`.| `GET /badge.svg` | self-rendered flat SVG health badge (color + `N.N/10`, no letter) || `GET /badge.json` | Shields.io endpoint-badge payload (`schemaVersion`/`label`/`message`/`color`/`band`) || `GET /files` | per-file metrics |+| `GET /files/breakdown` | one file's metric + score breakdown + findings + suggestions + per-file `trend` |+| `GET /files/trend` | one file's score-over-time series + current delta + `declining` flag (`?file_path=`) |+| `GET /trend` | repo KPI history + alerts + last-two-snapshot per-file deltas || `GET /findings` | findings list (filterable by biomarker_type, severity, file_path) || `GET /coverage` | coverage summary + per-file rows || `POST /coverage` | ingest a coverage report (used by some CI integrations) |@@ -813,7 +841,7 @@ Other perf notes:| `tests/unit/health/test_coverage_parsers.py` | LCOV / Cobertura / Clover / repowise-JSON happy paths + edge cases || `tests/unit/health/test_scoring.py` | Deduction caps, clamping, KPI math || `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 |+| `tests/unit/health/test_trends.py` | Declining + predicted alerts, ordering, per-file series + `file_trend` || `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.mdindex da3224807..dcc1edd37 100644--- a/packages/core/src/repowise/core/analysis/health/README.md+++ b/packages/core/src/repowise/core/analysis/health/README.md@@ -64,6 +64,14 @@ unchanged files keep their findings across incremental runs.Use `diff_snapshots(history)` for a `TrendSummary`, or `recent_kpis(history,limit=10)` for the CLI / dashboard table.+Per-file trajectory (same snapshots, the `{path: score}` map):++- `file_score_series(history, path)` — oldest-first `FileTrendPoint`s,+ skipping snapshots missing the file; `[]` below two points (silent on thin+ history). Reused verbatim by the PR bot's in-comment sparkline.+- `file_trend(history, path)` — wraps the series with `current` / `previous`+ / `delta` and a `declining` flag (per-file mirror of the alerts above).+## Refactoring suggestions`suggestions.suggestion_for(biomarker_type)` returns the canonical, staticdiff --git a/packages/core/src/repowise/core/analysis/health/trends.py b/packages/core/src/repowise/core/analysis/health/trends.pyindex 7dd63c406..8845dae4d 100644--- a/packages/core/src/repowise/core/analysis/health/trends.py+++ b/packages/core/src/repowise/core/analysis/health/trends.py@@ -24,6 +24,7 @@ or a session.from __future__ import annotations+import jsonfrom dataclasses import dataclass, fieldfrom datetime import datetimefrom typing import Any, Protocol@@ -41,6 +42,7 @@ class SnapshotLike(Protocol):average_health: floatworst_performer_path: str | Noneworst_performer_score: float | None+ per_file_scores_json: str@dataclass@@ -197,3 +199,147 @@ def recent_kpis(history: list[Any], limit: int = 10) -> list[dict[str, Any]]:})return rows+++# --------------------------------------------------------------------------- #+# Per-file trajectory+#+# The snapshot writer stores a compact ``{path: score}`` map per snapshot+# (``HealthSnapshot.per_file_scores_json``). These helpers turn that rolling+# window into a single file's score-over-time series — CodeScene's signature+# view. Like the repo-level helpers above they are intentionally state-free:+# callers pass the snapshot history (oldest → newest) and get plain data back,+# so the logic stays unit-testable without a DB and is reused verbatim by the+# PR bot's in-comment sparkline.+# --------------------------------------------------------------------------- #+++@dataclass+class FileTrendPoint:+ """One file's score at one snapshot."""++ taken_at: datetime | None+ score: float+++@dataclass+class FileTrend:+ """A file's score trajectory + the deltas worth surfacing.++ ``points`` is oldest-first and **empty when fewer than two snapshots+ carry the file** — a per-file trend is silent on thin history rather than+ drawing a misleading single dot (plan §2: "silent when < 2 real+ snapshots"). ``current`` / ``previous`` / ``delta`` and ``declining``+ are all ``None`` / ``False`` in that case.+ """++ file_path: str+ points: list[FileTrendPoint]+ current: float | None+ previous: float | None+ delta: float | None+ declining: bool+ snapshot_count: int+++def _score_in_snapshot(snap: Any, file_path: str) -> float | None:+ """Read ``file_path``'s score from a snapshot's compact JSON map.++ Returns ``None`` when the file is absent from that snapshot (it may have+ been added later, renamed, or filtered out of that run) or when the map+ can't be parsed — the series simply skips that snapshot.+ """+ raw = getattr(snap, "per_file_scores_json", None)+ if not raw:+ return None+ try:+ scores = json.loads(raw)+ except (ValueError, TypeError):+ return None+ val = scores.get(file_path) if isinstance(scores, dict) else None+ if val is None:+ return None+ try:+ return float(val)+ except (ValueError, TypeError):+ return None+++def file_score_series(history: list[Any], file_path: str) -> list[FileTrendPoint]:+ """A file's oldest-first score series across the snapshot window.++ Snapshots missing the file are skipped (gaps don't break the line).+ Returns ``[]`` when fewer than two points are available so consumers can+ render a "no history yet" state instead of a single misleading dot.++ *history* is expected oldest-first (the natural ``list_health_snapshots``+ order). This is the exact function the PR bot reuses for its in-comment+ sparkline, so it stays free of any persistence or presentation concern.+ """+ points: list[FileTrendPoint] = []+ for snap in history:+ score = _score_in_snapshot(snap, file_path)+ if score is None:+ continue+ points.append(FileTrendPoint(taken_at=getattr(snap, "taken_at", None), score=score))+ if len(points) < 2:+ return []+ return points+++def _file_declining(points: list[FileTrendPoint]) -> bool:+ """A sustained-decline heuristic for a single file's series.++ Mirrors the repo-level signals: fire when either the latest score is+ ``DECLINE_THRESHOLD`` below the point ``DECLINE_LOOKBACK`` back, or the+ tail is ``PREDICTED_DECLINE_CONSECUTIVE`` strict drops in a row. Single+ snapshot-to-snapshot noise is deliberately not enough.+ """+ if len(points) <= 1:+ return False+ scores = [p.score for p in points]++ if (+ len(scores) > DECLINE_LOOKBACK+ and scores[-1] <= scores[-1 - DECLINE_LOOKBACK] - DECLINE_THRESHOLD+ ):+ return True++ needed = PREDICTED_DECLINE_CONSECUTIVE + 1+ if len(scores) >= needed:+ tail = scores[-needed:]+ if all(tail[i + 1] < tail[i] for i in range(len(tail) - 1)):+ return True+ return False+++def file_trend(history: list[Any], file_path: str) -> FileTrend:+ """Assemble a file's :class:`FileTrend` from the snapshot history.++ Wraps :func:`file_score_series` with the current value, the prior value,+ their delta, and the declining flag. ``snapshot_count`` is the size of+ the whole repo window (not just the points carrying this file) so the UI+ can distinguish "young repo" from "file not in older snapshots".+ """+ points = file_score_series(history, file_path)+ if not points:+ return FileTrend(+ file_path=file_path,+ points=[],+ current=None,+ previous=None,+ delta=None,+ declining=False,+ snapshot_count=len(history),+ )+ current = round(points[-1].score, 2)+ previous = round(points[-2].score, 2)+ return FileTrend(+ file_path=file_path,+ points=points,+ current=current,+ previous=previous,+ delta=round(current - previous, 2),+ declining=_file_declining(points),+ snapshot_count=len(history),+ )diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex 2e1236094..35fc4f2e7 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -1,4 +1,4 @@-"""MCP tool: get_health — code-health biomarkers and per-file scores."""+"""MCP tool: get_health — code-health biomarkers and per-file scores."""from __future__ import annotations@@ -10,7 +10,7 @@ from sqlalchemy import selectfrom repowise.core.analysis.health.grading import band_forfrom repowise.core.analysis.health.grading import distribution as health_distributionfrom repowise.core.analysis.health.suggestions import suggestion_for-from repowise.core.analysis.health.trends import diff_snapshots, recent_kpis+from repowise.core.analysis.health.trends import diff_snapshots, file_trend, recent_kpisfrom repowise.core.persistence.crud import (get_coverage_summary,list_health_snapshots,@@ -225,8 +225,11 @@ async def get_health(# here; the per-file rows above are exclude-filtered.coverage_summary = await get_coverage_summary(session, repository.id)+ # Load the snapshot window for the repo-level trend block and/or the+ # per-file trajectory we attach in targeted mode ("should I touch this+ # file" context for agents).snapshots: list[Any] = []- if "trend" in include_set:+ if "trend" in include_set or effective_targets:snapshots = await list_health_snapshots(session, repository.id, limit=20)kpis = _compute_kpis(metric_rows if effective_targets else all_metrics)@@ -238,6 +241,24 @@ async def get_health("metrics": [_serialize_metric(m) for m in metric_rows],"findings": [_serialize_finding(f) for f in finding_rows],}+ # Per-file score trajectory for each target — silent (omitted) when a+ # file has < 2 snapshots of history rather than a misleading flat line.+ trends = []+ for m in metric_rows:+ t = file_trend(snapshots, m.file_path)+ if not t.points:+ continue+ trends.append(+ {+ "file_path": t.file_path,+ "series": [round(p.score, 2) for p in t.points],+ "current": t.current,+ "delta": t.delta,+ "declining": t.declining,+ }+ )+ if trends:+ result["trends"] = trendsif module_targets:scoped = [m for m in all_metrics if m.module in set(module_targets)]result["modules"] = _module_rollups(scoped)diff --git a/packages/server/src/repowise/server/routers/code_health.py b/packages/server/src/repowise/server/routers/code_health.pyindex 86b482f5c..00d3d9cd1 100644--- a/packages/server/src/repowise/server/routers/code_health.py+++ b/packages/server/src/repowise/server/routers/code_health.py@@ -27,7 +27,12 @@ from repowise.core.analysis.health.scoring import (severity_deduction,)from repowise.core.analysis.health.suggestions import suggestion_for as _suggestion_for-from repowise.core.analysis.health.trends import diff_snapshots, recent_kpis+from repowise.core.analysis.health.trends import (+ FileTrend,+ diff_snapshots,+ file_trend,+ recent_kpis,+)from repowise.core.persistence import crudfrom repowise.core.persistence.models import WikiSymbolfrom repowise.server.deps import get_db_session, verify_api_key@@ -75,6 +80,26 @@ def _metric_to_dict(m: Any) -> dict:}+def _file_trend_to_dict(t: FileTrend) -> dict:+ """Wire shape for ``FileHealthTrend`` (types/health.ts). ``points`` is+ empty on thin history so the UI shows a "no history yet" state."""+ return {+ "file_path": t.file_path,+ "points": [+ {+ "taken_at": p.taken_at.isoformat() if p.taken_at else None,+ "score": round(p.score, 2),+ }+ for p in t.points+ ],+ "current": t.current,+ "previous": t.previous,+ "delta": t.delta,+ "declining": t.declining,+ "snapshot_count": t.snapshot_count,+ }++async def _attach_symbol_ids(session: AsyncSession, repo_id: str, finding_dicts: list[dict]) -> list[dict]:@@ -90,22 +115,19 @@ async def _attach_symbol_ids(if not paths:return finding_dictsrows = (- (- await session.execute(- select(- WikiSymbol.symbol_id,- WikiSymbol.file_path,- WikiSymbol.name,- WikiSymbol.start_line,- WikiSymbol.end_line,- ).where(- WikiSymbol.repository_id == repo_id,- WikiSymbol.file_path.in_(paths),- )+ await session.execute(+ select(+ WikiSymbol.symbol_id,+ WikiSymbol.file_path,+ WikiSymbol.name,+ WikiSymbol.start_line,+ WikiSymbol.end_line,+ ).where(+ WikiSymbol.repository_id == repo_id,+ WikiSymbol.file_path.in_(paths),))- .all()- )+ ).all()by_name: dict[tuple[str, str], str] = {}by_file: dict[str, list[tuple[int, int, str]]] = {}for symbol_id, file_path, name, start_line, end_line in rows:@@ -394,7 +416,9 @@ async def list_health_findings(file_path=file_path,min_severity=min_severity,)- return await _attach_symbol_ids(session, repo_id, [_finding_to_dict(f) for f in findings[:limit]])+ return await _attach_symbol_ids(+ session, repo_id, [_finding_to_dict(f) for f in findings[:limit]]+ )_SORT_FIELDS = {@@ -576,15 +600,34 @@ async def file_score_breakdown(finding_dicts = await _attach_symbol_ids(session, repo_id, [_finding_to_dict(f) for f in findings])+ snapshots = await crud.list_health_snapshots(session, repo_id)return {"file_path": file_path,"metric": _metric_to_dict(metric) if metric else None,"breakdown": breakdown,"findings": finding_dicts,"suggestions": {b: _suggestion_for(b) for b in {f.biomarker_type for f in findings}},+ "trend": _file_trend_to_dict(file_trend(snapshots, file_path)),}[email protected]("/api/repos/{repo_id}/health/files/trend")+async def file_health_trend(+ repo_id: str,+ file_path: str = Query(..., description="File path to chart over time"),+ session: AsyncSession = Depends(get_db_session), # noqa: B008+) -> dict:+ """A single file's score-over-time series from the snapshot history.++ Silent (empty ``points``) when fewer than two snapshots carry the file.+ """+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")+ snapshots = await crud.list_health_snapshots(session, repo_id)+ return _file_trend_to_dict(file_trend(snapshots, file_path))++@router.get("/api/repos/{repo_id}/health/trend")async def health_trend(repo_id: str,diff --git a/packages/server/src/repowise/server/routers/files.py b/packages/server/src/repowise/server/routers/files.pyindex a54ff7a85..7490d3cdf 100644--- a/packages/server/src/repowise/server/routers/files.py+++ b/packages/server/src/repowise/server/routers/files.py@@ -17,12 +17,14 @@ from fastapi import APIRouter, Depends, HTTPExceptionfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.health.trends import file_trendfrom repowise.core.persistence import crudfrom repowise.core.persistence.decision_graph import get_governing_decisionsfrom repowise.core.persistence.models import DeadCodeFinding, Page, WikiSymbolfrom repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.mcp_server._graph_utils import parse_community_meta, percentile_rankfrom repowise.server.routers.code_health import (+ _file_trend_to_dict,_finding_to_dict,_metric_to_dict,_score_breakdown_from_findings,@@ -120,10 +122,12 @@ async def file_detail(# --- Health -----------------------------------------------------------findings = await crud.get_health_findings(session, repo_id, file_path=file_path)+ snapshots = await crud.list_health_snapshots(session, repo_id)health = {"metric": _metric_to_dict(metric) if metric else None,"breakdown": _score_breakdown_from_findings(findings) if findings else None,"findings": [_finding_to_dict(f) for f in findings],+ "trend": _file_trend_to_dict(file_trend(snapshots, file_path)),}# --- Git history ------------------------------------------------------diff --git a/packages/types/src/files.ts b/packages/types/src/files.tsindex 449d19158..91bb27c13 100644--- a/packages/types/src/files.ts+++ b/packages/types/src/files.ts@@ -5,6 +5,7 @@*/import type { CoChangePartner, FileAuthor, Hotspot, SignificantCommit } from "./git.js";+import type { FileHealthTrend } from "./health.js";export interface FileWikiPageRef {id: string;@@ -73,6 +74,8 @@ export interface FileDetailHealth {metric: FileHealthMetric | null;breakdown: FileScoreBreakdown | null;findings: FileHealthFinding[];+ /** Per-file score trajectory; `points` empty when history is thin. */+ trend: FileHealthTrend | null;}export interface FileAgentProvenance {diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsindex 5277dd0a1..53e74ba44 100644--- a/packages/types/src/health.ts+++ b/packages/types/src/health.ts@@ -241,6 +241,36 @@ export interface HealthFileBreakdownResponse {};findings: HealthFinding[];suggestions: Record<string, string>;+ /** Per-file score trajectory (silent when history is thin). */+ trend?: FileHealthTrend | null;+}++/* ------------------------------------------------------------------ *+ * Per-file trajectory+ * ------------------------------------------------------------------ */++/** One file's score at one snapshot. */+export interface FileTrendPoint {+ taken_at: string | null;+ score: number;+}++/**+ * A single file's score-over-time series plus the deltas worth surfacing.+ * `points` is oldest-first and **empty when fewer than two snapshots carry+ * the file** — consumers render a "no history yet" state rather than a+ * misleading single dot. `current`/`previous`/`delta`/`declining` are null/+ * false in that case. `snapshot_count` is the whole repo window size, so a+ * young repo is distinguishable from a file absent in older snapshots.+ */+export interface FileHealthTrend {+ file_path: string;+ points: FileTrendPoint[];+ current: number | null;+ previous: number | null;+ delta: number | null;+ declining: boolean;+ snapshot_count: number;}/* ------------------------------------------------------------------ *diff --git a/packages/ui/__tests__/health/file-trend-chart.test.tsx b/packages/ui/__tests__/health/file-trend-chart.test.tsxnew file mode 100644index 000000000..3e0084c0d--- /dev/null+++ b/packages/ui/__tests__/health/file-trend-chart.test.tsx@@ -0,0 +1,71 @@+import { describe, it, expect } from "vitest";+import { render, screen } from "@testing-library/react";+import type { FileHealthTrend } from "@repowise-dev/types/health";+import { FileTrendChart } from "../../src/health/file-trend-chart.js";++function trend(partial: Partial<FileHealthTrend>): FileHealthTrend {+ return {+ file_path: "a.py",+ points: [],+ current: null,+ previous: null,+ delta: null,+ declining: false,+ snapshot_count: 0,+ ...partial,+ };+}++describe("FileTrendChart", () => {+ it("renders the chart and delta when history is present", () => {+ render(+ <FileTrendChart+ trend={trend({+ points: [+ { taken_at: "2026-01-01T00:00:00Z", score: 8 },+ { taken_at: "2026-01-02T00:00:00Z", score: 6.5 },+ ],+ current: 6.5,+ previous: 8,+ delta: -1.5,+ snapshot_count: 2,+ })}+ />,+ );+ expect(screen.getByRole("img", { name: /score over time/i })).toBeInTheDocument();+ expect(screen.getByText(/-1\.50 vs\. previous/)).toBeInTheDocument();+ });++ it("flags a declining trajectory", () => {+ render(+ <FileTrendChart+ trend={trend({+ points: [+ { taken_at: null, score: 9 },+ { taken_at: null, score: 8 },+ { taken_at: null, score: 7 },+ ],+ current: 7,+ previous: 8,+ delta: -1,+ declining: true,+ snapshot_count: 3,+ })}+ />,+ );+ expect(screen.getByText("Declining")).toBeInTheDocument();+ });++ it("shows a 'no history yet' state below two points", () => {+ render(+ <FileTrendChart trend={trend({ points: [{ taken_at: null, score: 8 }], snapshot_count: 1 })} />,+ );+ expect(screen.getByText(/No score history yet/)).toBeInTheDocument();+ expect(screen.queryByRole("img")).not.toBeInTheDocument();+ });++ it("renders the empty state for a null trend", () => {+ render(<FileTrendChart trend={null} />);+ expect(screen.getByText(/No score history yet/)).toBeInTheDocument();+ });+});diff --git a/packages/ui/src/files/file-health-tab.tsx b/packages/ui/src/files/file-health-tab.tsxindex b0ea3f06d..bef203f64 100644--- a/packages/ui/src/files/file-health-tab.tsx+++ b/packages/ui/src/files/file-health-tab.tsx@@ -7,6 +7,7 @@ import { ScoreBreakdown, type ScoreBreakdownCategory } from "../health/score-breimport { BiomarkerDetails, type BiomarkerDetailsRecord } from "../health/biomarker-details";import { biomarkerInfo, biomarkerLabel, CATEGORY_LABEL } from "../health/biomarker-glossary";import { SEVERITY_CHIP, SEVERITY_LABEL, scoreBadgeClass, type Severity } from "../health/tokens";+import { FileTrendChart } from "../health/file-trend-chart";import type { FileDetailHealth, FunctionBlameRow } from "@repowise-dev/types/files";export type FindingStatus = "open" | "acknowledged" | "resolved" | "false_positive";@@ -45,7 +46,7 @@ export function FileHealthTab({}: FileHealthTabProps) {const [statusOverride, setStatusOverride] = useState<Record<string, FindingStatus>>({});const [savingId, setSavingId] = useState<string | null>(null);- const { metric, breakdown, findings } = health;+ const { metric, breakdown, findings, trend } = health;if (!metric && findings.length === 0) {return (@@ -107,6 +108,8 @@ export function FileHealthTab({</div>)}+ {trend && trend.points.length >= 2 && <FileTrendChart trend={trend} />}+{breakdown && (<section className="space-y-2"><h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">diff --git a/packages/ui/src/health/file-trend-chart.tsx b/packages/ui/src/health/file-trend-chart.tsxnew file mode 100644index 000000000..3b91fe151--- /dev/null+++ b/packages/ui/src/health/file-trend-chart.tsx@@ -0,0 +1,151 @@+"use client";++import { TrendingDown } from "lucide-react";+import type { FileHealthTrend } from "@repowise-dev/types/health";+import { deltaColor, formatDelta, scoreTextColor } from "./tokens";++export interface FileTrendChartProps {+ trend: FileHealthTrend | null | undefined;+ height?: number;+ /** Hide the bordered card chrome (e.g. when embedding inside another card). */+ bare?: boolean;+}++/**+ * A single file's score trajectory over the snapshot history — the per-file+ * counterpart to the repo-level `TrendChart`. Purpose-built for one 0-10+ * series (rather than overloading the 3-KPI chart): a fixed 0-10 Y axis, a+ * delta chip, and a declining flag. Silent ("no history yet") when the file+ * has fewer than two snapshots, matching the silent-on-thin-history contract.+ */+export function FileTrendChart({ trend, height = 140, bare = false }: FileTrendChartProps) {+ const points = trend?.points ?? [];++ const body =+ points.length < 2 ? (+ <div className="rounded-md border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4 text-center text-xs text-[var(--color-text-tertiary)]">+ No score history yet. Trends appear once this file has been scored in at+ least two <code>repowise</code> runs.+ </div>+ ) : (+ <Chart points={points} height={height} />+ );++ if (bare) return body;++ return (+ <section className="space-y-2">+ <div className="flex items-center justify-between gap-3">+ <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Score over time+ </h3>+ {points.length >= 2 && (+ <div className="flex items-center gap-2">+ {trend?.declining && (+ <span className="inline-flex items-center gap-1 rounded bg-[var(--color-error)]/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-[var(--color-error)]">+ <TrendingDown className="h-3 w-3" />+ Declining+ </span>+ )}+ {trend?.delta != null && trend.delta !== 0 && (+ <span className={`text-xs font-semibold tabular-nums ${deltaColor(trend.delta)}`}>+ {formatDelta(trend.delta)} vs. previous+ </span>+ )}+ </div>+ )}+ </div>+ {body}+ </section>+ );+}++function Chart({+ points,+ height,+}: {+ points: FileHealthTrend["points"];+ height: number;+}) {+ const W = 720;+ const H = height;+ const padL = 28;+ const padR = 12;+ const padT = 10;+ const padB = 22;+ const plotW = W - padL - padR;+ const plotH = H - padT - padB;++ const xScale = (i: number) =>+ points.length === 1 ? padL + plotW / 2 : padL + (i / (points.length - 1)) * plotW;+ const yScale = (v: number) => padT + ((10 - v) / 10) * plotH;++ const coords = points.map((p, i) => [xScale(i), yScale(p.score)] as const);+ const line = coords.map(([x, y], i) => (i === 0 ? `M${x},${y}` : `L${x},${y}`)).join(" ");++ const last = points[points.length - 1]!;+ const first = points[0]!;+ const endColor = scoreTextColor(last.score);++ const fmtDate = (iso: string | null) => (iso ? new Date(iso).toLocaleDateString() : "");++ return (+ <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-2">+ <svg+ viewBox={`0 0 ${W} ${H}`}+ width="100%"+ height={H}+ role="img"+ aria-label="File health score over time"+ >+ {[0, 5, 10].map((v) => (+ <g key={v}>+ <line+ x1={padL}+ x2={W - padR}+ y1={yScale(v)}+ y2={yScale(v)}+ stroke="currentColor"+ strokeOpacity={0.08}+ />+ <text+ x={padL - 5}+ y={yScale(v) + 3}+ fontSize={9}+ textAnchor="end"+ fill="currentColor"+ opacity={0.5}+ >+ {v}+ </text>+ </g>+ ))}+ <path d={line} stroke="var(--color-accent-primary)" strokeWidth={1.8} fill="none" />+ {coords.map(([x, y], i) => (+ <circle key={i} cx={x} cy={y} r={2.2} fill="var(--color-accent-primary)" />+ ))}+ {/* Emphasize the latest point, colored by its current band. */}+ <circle+ cx={coords[coords.length - 1]![0]}+ cy={coords[coords.length - 1]![1]}+ r={3.4}+ className={endColor}+ fill="currentColor"+ />+ <text x={padL} y={H - 6} fontSize={9} fill="currentColor" opacity={0.5}>+ {fmtDate(first.taken_at)}+ </text>+ <text+ x={W - padR}+ y={H - 6}+ fontSize={9}+ textAnchor="end"+ fill="currentColor"+ opacity={0.5}+ >+ {fmtDate(last.taken_at)}+ </text>+ </svg>+ </div>+ );+}diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsxindex cd2d02cb4..385078756 100644--- a/packages/ui/src/health/health-file-drawer.tsx+++ b/packages/ui/src/health/health-file-drawer.tsx@@ -7,12 +7,16 @@ import { InfoTip } from "../shared/info-tip";import { biomarkerLabel, biomarkerInfo, CATEGORY_LABEL } from "./biomarker-glossary";import { BiomarkerDetails, type BiomarkerDetailsRecord } from "./biomarker-details";import { ScoreBreakdown, type ScoreBreakdownCategory } from "./score-breakdown";+import { Sparkline } from "./sparkline";import {SEVERITY_CHIP,SEVERITY_LABEL,+ deltaColor,+ formatDelta,scoreBadgeClass,type Severity,} from "./tokens";+import type { FileHealthTrend } from "@repowise-dev/types/health";export interface HealthDrawerFinding {id: string;@@ -51,6 +55,8 @@ export interface HealthFileDrawerProps {} | null;findings?: HealthDrawerFinding[];suggestions?: Record<string, string>;+ /** Per-file score trajectory; renders a compact sparkline when populated. */+ trend?: FileHealthTrend | null;fileViewHref?: string;/** Build a per-line deep-link from the drawer's function:line span. */fileViewHrefFor?: ((lineStart: number) => string) | undefined;@@ -78,6 +84,7 @@ export function HealthFileDrawer({breakdown,findings = [],suggestions = {},+ trend,fileViewHref,fileViewHrefFor,permalinkHref,@@ -150,6 +157,31 @@ export function HealthFileDrawer({} /></div>+ {trend && trend.points.length >= 2 ? (+ <div className="flex items-center gap-3 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2">+ <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Trend+ </span>+ <Sparkline+ values={trend.points.map((p) => p.score)}+ domain={[0, 10]}+ width={120}+ height={28}+ stroke="var(--color-accent-primary)"+ />+ {trend.delta != null && trend.delta !== 0 ? (+ <span className={`text-xs font-semibold tabular-nums ${deltaColor(trend.delta)}`}>+ {formatDelta(trend.delta)}+ </span>+ ) : null}+ {trend.declining ? (+ <span className="text-[10px] font-semibold uppercase tracking-wider text-[var(--color-error)]">+ Declining+ </span>+ ) : null}+ </div>+ ) : null}+{fileViewHref ? (<ahref={fileViewHref}diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.tsindex a82ae6961..9bac89b35 100644--- a/packages/ui/src/health/index.ts+++ b/packages/ui/src/health/index.ts@@ -19,6 +19,7 @@ export * from "./sparkline";export * from "./health-tabs";export * from "./page-chrome";export * from "./trend-chart";+export * from "./file-trend-chart";export * from "./risk-coverage-scatter";export * from "./impact-effort-quadrant";export * from "./health-file-drawer";diff --git a/packages/web/src/components/health/health-file-drawer-host.tsx b/packages/web/src/components/health/health-file-drawer-host.tsxindex 459ec8123..0f6fc9879 100644--- a/packages/web/src/components/health/health-file-drawer-host.tsx+++ b/packages/web/src/components/health/health-file-drawer-host.tsx@@ -36,6 +36,7 @@ export function HealthFileDrawerHost({}findings={data?.findings ?? []}suggestions={data?.suggestions ?? {}}+ trend={data?.trend ?? null}permalinkHref={filePageHref ? `${filePageHref}?tab=health` : undefined}fileViewHref={filePageHref}fileViewHrefFor={diff --git a/tests/unit/health/test_trends.py b/tests/unit/health/test_trends.pyindex 3af4ddd7b..fade99c85 100644--- a/tests/unit/health/test_trends.py+++ b/tests/unit/health/test_trends.py@@ -2,6 +2,7 @@from __future__ import annotations+import jsonfrom dataclasses import dataclassfrom datetime import UTC, datetime, timedelta@@ -9,6 +10,8 @@ from repowise.core.analysis.health.trends import (DECLINE_LOOKBACK,DECLINE_THRESHOLD,diff_snapshots,+ file_score_series,+ file_trend,recent_kpis,)@@ -20,6 +23,7 @@ class _S:average_health: floatworst_performer_path: str | None = "x"worst_performer_score: float | None = 1.0+ per_file_scores_json: str = "{}"def _ts(n: int) -> datetime:@@ -80,3 +84,93 @@ def test_recent_kpis_orders_newest_first():rows = recent_kpis(_series([5.0, 6.0, 7.0]), limit=10)scores = [r["hotspot_health"] for r in rows]assert scores == [7.0, 6.0, 5.0]+++# --------------------------------------------------------------------------- #+# Per-file trajectory+# --------------------------------------------------------------------------- #+++def _file_series(per_file: list[dict[str, float]]) -> list[_S]:+ """Build snapshots whose only varying field is the per-file score map."""+ return [+ _S(+ taken_at=_ts(i),+ hotspot_health=10.0,+ average_health=10.0,+ per_file_scores_json=json.dumps(scores),+ )+ for i, scores in enumerate(per_file)+ ]+++def test_file_score_series_extracts_oldest_first():+ snaps = _file_series([{"a.py": 9.0}, {"a.py": 8.0}, {"a.py": 7.0}])+ pts = file_score_series(snaps, "a.py")+ assert [p.score for p in pts] == [9.0, 8.0, 7.0]+ # Ordering is preserved oldest -> newest.+ assert pts[0].taken_at == _ts(0)+ assert pts[-1].taken_at == _ts(2)+++def test_file_score_series_skips_snapshots_missing_the_file():+ # The file is absent from the middle snapshot — the gap is skipped, not+ # zero-filled, so the line connects the two real points.+ snaps = _file_series([{"a.py": 9.0}, {"b.py": 5.0}, {"a.py": 7.0}])+ pts = file_score_series(snaps, "a.py")+ assert [p.score for p in pts] == [9.0, 7.0]+++def test_file_score_series_silent_below_two_points():+ # One point is not a trend.+ snaps = _file_series([{"a.py": 9.0}, {"b.py": 5.0}])+ assert file_score_series(snaps, "a.py") == []+ # Zero points likewise.+ assert file_score_series(snaps, "missing.py") == []+++def test_file_score_series_tolerates_bad_json():+ snaps = _file_series([{"a.py": 9.0}, {"a.py": 8.0}])+ snaps.insert(1, _S(_ts(9), 10.0, 10.0, per_file_scores_json="not json"))+ pts = file_score_series(snaps, "a.py")+ assert [p.score for p in pts] == [9.0, 8.0]+++def test_file_trend_summary_delta():+ snaps = _file_series([{"a.py": 8.0}, {"a.py": 6.5}])+ t = file_trend(snaps, "a.py")+ assert t.current == 6.5+ assert t.previous == 8.0+ assert t.delta == -1.5+ assert t.snapshot_count == 2+++def test_file_trend_thin_history_is_neutral():+ snaps = _file_series([{"a.py": 8.0}])+ t = file_trend(snaps, "a.py")+ assert t.points == []+ assert t.current is None+ assert t.previous is None+ assert t.delta is None+ assert t.declining is False+ assert t.snapshot_count == 1+++def test_file_trend_declining_on_sustained_drop():+ # > DECLINE_LOOKBACK points, newest >= threshold below the lookback point.+ vals = [{"a.py": 8.0} for _ in range(DECLINE_LOOKBACK)]+ vals.append({"a.py": 8.0 - DECLINE_THRESHOLD - 0.1})+ t = file_trend(_file_series(vals), "a.py")+ assert t.declining is True+++def test_file_trend_declining_on_consecutive_drops():+ t = file_trend(+ _file_series([{"a.py": 9.0}, {"a.py": 8.8}, {"a.py": 8.6}, {"a.py": 8.4}]), "a.py"+ )+ assert t.declining is True+++def test_file_trend_not_declining_when_recovering():+ t = file_trend(_file_series([{"a.py": 7.0}, {"a.py": 8.0}, {"a.py": 9.0}]), "a.py")+ assert t.declining is Falsediff --git a/tests/unit/server/test_health_badge.py b/tests/unit/server/test_health_badge.pyindex 109d9486d..e134b9614 100644--- a/tests/unit/server/test_health_badge.py+++ b/tests/unit/server/test_health_badge.py@@ -1,8 +1,14 @@-"""Pure-function tests for the health badge fields + SVG rendering."""+"""Pure-function tests for the health badge fields + SVG rendering, plus the+per-file trend serializer's wire shape."""from __future__ import annotations-from repowise.server.routers.code_health import _badge_fields, _render_badge_svg+from repowise.core.analysis.health.trends import FileTrend, FileTrendPoint+from repowise.server.routers.code_health import (+ _badge_fields,+ _file_trend_to_dict,+ _render_badge_svg,+)def test_badge_fields_band_colors() -> None:@@ -24,4 +30,49 @@ def test_render_badge_svg_embeds_label_and_message() -> None:assert svg.endswith("</svg>")assert "7.4/10" in svgassert "#4c1" in svg # brightgreen hex- assert 'media' not in svg # sanity: it's markup, not a response wrapper+ assert "media" not in svg # sanity: it's markup, not a response wrapper+++def test_file_trend_to_dict_thin_history() -> None:+ t = FileTrend(+ file_path="a.py",+ points=[],+ current=None,+ previous=None,+ delta=None,+ declining=False,+ snapshot_count=1,+ )+ d = _file_trend_to_dict(t)+ assert d == {+ "file_path": "a.py",+ "points": [],+ "current": None,+ "previous": None,+ "delta": None,+ "declining": False,+ "snapshot_count": 1,+ }+++def test_file_trend_to_dict_serializes_points() -> None:+ from datetime import UTC, datetime++ t = FileTrend(+ file_path="a.py",+ points=[+ FileTrendPoint(taken_at=datetime(2026, 1, 1, tzinfo=UTC), score=8.0),+ FileTrendPoint(taken_at=None, score=6.5),+ ],+ current=6.5,+ previous=8.0,+ delta=-1.5,+ declining=True,+ snapshot_count=2,+ )+ d = _file_trend_to_dict(t)+ assert d["points"][0]["taken_at"] == "2026-01-01T00:00:00+00:00"+ assert d["points"][0]["score"] == 8.0+ assert d["points"][1]["taken_at"] is None+ assert d["delta"] == -1.5+ assert d["declining"] is True