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): health bands, repo distribution, and README badge (#485)
Raghav Chamadiya01978e7bf1f0
diff --git a/README.md b/README.mdindex e18a6c163..9bec3ba96 100644--- a/README.md+++ b/README.md@@ -14,6 +14,7 @@<p align="center"><a href="https://pypi.org/project/repowise/"><img src="https://img.shields.io/pypi/v/repowise?style=for-the-badge&color=1E293B&labelColor=0A0A0A&logo=pypi&logoColor=white" alt="PyPI version" /></a>+ <a href="https://www.repowise.dev"><img src="https://img.shields.io/badge/code_health-tracked-1E293B?style=for-the-badge&labelColor=0A0A0A" alt="Code health tracked on repowise.dev" /></a><a href="https://www.gnu.org/licenses/agpl-3.0"><img src="https://img.shields.io/badge/License-AGPL--v3-059669?style=for-the-badge&labelColor=0A0A0A" alt="License: AGPL v3" /></a><a href="https://pypi.org/project/repowise/"><img src="https://img.shields.io/badge/Python-3.11%2B-1E293B?style=for-the-badge&labelColor=0A0A0A&logo=python&logoColor=white" alt="Python 3.11+" /></a><a href="https://modelcontextprotocol.io"><img src="https://img.shields.io/badge/MCP-compatible-1E293B?style=for-the-badge&labelColor=0A0A0A" alt="MCP compatible" /></a>diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.mdindex 28afd28a4..05c906d16 100644--- a/docs/CODE_HEALTH.md+++ b/docs/CODE_HEALTH.md@@ -69,6 +69,51 @@ The final score is clamped to `[1.0, 10.0]`. The three repo-level KPIs:- **Average Health** — NLOC-weighted average over all files.- **Worst Performer** — single lowest-scoring file.+## Bands and distribution++On top of the 1–10 number, every score falls into one of three **bands**. These+are the single categorical scheme repowise surfaces (there is deliberately no+letter grade — a letter on top of the number would be a third overlapping scale+with arbitrary cliffs):++| Band | Score | Meaning |+|------|-------|---------|+| **Healthy** | `≥ 8.0` | Low-risk, maintainable. |+| **Warning** | `4.0 – 8.0` | Worth watching; rising complexity or process risk. |+| **Alert** | `< 4.0` | High-risk; concentrates defects. |++The cutoffs are not arbitrary. On our calibration corpus, **Alert files carry+roughly 17× the per-file defect rate of Healthy files**, so the band boundaries+are empirically defensible. They are defined once in core+(`analysis/health/grading.py`) and mirrored in `@repowise-dev/types` for the UI;+a parity test on each side locks the values.++The **health distribution** is the NLOC-weighted split of the repo across the+three bands — what share of your code (by volume, not file count) is Healthy vs+Warning vs Alert. `repowise health` prints it as a one-line summary; the+dashboard renders it as a bar.++```text+Distribution (by code volume): 8% alert (12 files) · 21% warning (88 files) · 71% healthy (410 files)+```++## Badge++`repowise health --badge` prints ready-to-paste Markdown for a README health+badge (a Shields-style **color + `N.N/10`** badge — no letter). A running+Repowise server (or the hosted app) also serves the badge directly:++```text+GET /api/repos/{repo_id}/health/badge.svg # self-rendered flat SVG+GET /api/repos/{repo_id}/health/badge.json # Shields endpoint payload+```++Embed the dynamic form via Shields:++```markdown++```+## Does the score find the bugs?The score is only worth anything if the files it flags are the files thatdiff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.mdindex 6faca45b7..d66d3682a 100644--- a/docs/architecture/code-health.md+++ b/docs/architecture/code-health.md@@ -63,6 +63,8 @@ analysis/health/├── __init__.py # public API: HealthAnalyzer, HealthReport├── engine.py # orchestrator: walker → biomarkers → scorer├── 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├── suggestions.py # deterministic refactoring text per biomarker├── config.py # HealthConfig + .repowise/health-rules.json@@ -173,7 +175,8 @@ packages/ui/src/health/ # shared React components (used by web + fut├── untested-hotspot-warning.tsx├── refactoring-card.tsx├── refactoring-target-list.tsx-├── health-badge.tsx+├── health-badge.tsx # score pill, colored by the 3 health bands+├── health-distribution-bar.tsx # NLOC-weighted Alert/Warning/Healthy split└── module-rollup-list.tsxpackages/web/src/app/repos/[id]/health/@@ -657,7 +660,8 @@ silently re-scored for changed files only.Defined in `tool_health.py`. Modes:-- **Dashboard mode** (`targets=None`) — returns repo-level KPIs ++- **Dashboard mode** (`targets=None`) — returns repo-level KPIs (with the+ repo `band`) + the NLOC-weighted `distribution` across the 3 bands +`worst_files` (top N lowest-scoring) + `top_findings` + a per-module`modules` rollup.- **Targeted mode** (`targets=[...]`) — returns full `metrics` +@@ -680,8 +684,8 @@ Defined in `tool_health.py`. Modes:- `get_context(targets, include=["health"])` — per-file `score`,`max_ccn`, `max_nesting`, `nloc`, `module`, `duplication_pct`, top2 biomarkers (each with a `suggestion` string), and coverage block.-- `get_overview()` — adds a `code_health` block: avg, hotspot, worst- performer, open finding count.+- `get_overview()` — adds a `code_health` block: avg, repo `band`, hotspot,+ worst performer, open finding count, and the NLOC-weighted `distribution`.Every response carries the standard `_meta` envelope via `build_meta()`.@@ -694,7 +698,9 @@ Every response carries the standard `_meta` envelope via `build_meta()`.| Route | Returns ||---|---|-| `GET /overview` | summary + lowest-scoring files + top findings + module rollup |+| `GET /overview` | summary (with repo `band`) + `distribution` + lowest-scoring files + top findings + module rollup |+| `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 /findings` | findings list (filterable by biomarker_type, severity, file_path) || `GET /coverage` | coverage summary + per-file rows |@@ -872,6 +878,13 @@ phases may revisit; the constraints kept v1 shippable.shipped surface: the `analysis/change_risk/` package behind`repowise risk` scores a commit or base..head range with a calibratedlogistic model.)+- **No letter grade.** The 1–10 score is the single number. The only+ categorical layer is the 3 defect-backed bands (Healthy/Warning/Alert,+ `grading.py`); a letter on top would be a third overlapping scale with+ arbitrary cliffs. The legacy 4-step `scoreBand` in `ui/health/tokens.ts`+ is retained only as a finer color ramp for file-table pills, not a+ labeling scheme — surfaced band labels and the distribution use the 3+ bands.---diff --git a/packages/cli/src/repowise/cli/commands/health_cmd.py b/packages/cli/src/repowise/cli/commands/health_cmd.pyindex b1aac3578..9f0705af1 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd.py@@ -91,6 +91,13 @@ from repowise.cli.helpers import (default=False,help="Print the last 10 health snapshots from the SQLite history.",)+ "--badge",+ "badge_view",+ is_flag=True,+ default=False,+ help="Print a ready-to-paste health badge (Markdown) for this repo's README.",+)def health_command(path: str | None,file_filter: str | None,@@ -103,6 +110,7 @@ def health_command(refactoring_targets: bool,module_filter: str | None,trend_view: bool,+ badge_view: bool,) -> None:"""Compute code-health scores from biomarkers (CCN, nesting, brain-method).@@ -281,6 +289,10 @@ def health_command(_render_refactoring_targets(metrics_sorted, findings, fmt=fmt)return+ if badge_view:+ _render_badge(report.kpis.get("average_health"))+ return+if fmt == "json":click.echo(json.dumps(@@ -331,13 +343,28 @@ def health_command(return# Table format+ from repowise.core.analysis.health.grading import (+ BAND_LABEL,+ band_for,+ )+ from repowise.core.analysis.health.grading import (+ distribution as health_distribution,+ )+kpis = report.kpis+ avg = kpis.get("average_health")+ band_str = ""+ if isinstance(avg, (int, float)):+ band = band_for(float(avg))+ band_color = {"healthy": "green", "warning": "yellow", "alert": "red"}[band]+ band_str = f" [[{band_color}]{BAND_LABEL[band]}[/{band_color}]]"console.print(f"\nHotspot: [bold]{kpis.get('hotspot_health', '?')}[/bold]/10 · "- f"Average: [bold]{kpis.get('average_health', '?')}[/bold]/10 · "+ f"Average: [bold]{avg if avg is not None else '?'}[/bold]/10{band_str} · "f"Worst: [bold]{kpis.get('worst_performer_score', '?')}[/bold]/10 "- f"({kpis.get('worst_performer_path', 'n/a')})\n"+ f"({kpis.get('worst_performer_path', 'n/a')})")+ _render_distribution_line(health_distribution(report.metrics))_render_defect_accuracy_line(report)@@ -379,6 +406,45 @@ def health_command(console.print(f_table)+def _render_distribution_line(dist: dict) -> None:+ """One compact line: the NLOC-weighted file split across the 3 bands."""+ bands = dist.get("bands") or {}+ if not dist.get("total_files"):+ return+ parts = []+ for band, color in (("healthy", "green"), ("warning", "yellow"), ("alert", "red")):+ share = bands.get(band) or {}+ parts.append(+ f"[{color}]{share.get('pct', 0)}%[/{color}] {band} "+ f"([dim]{share.get('files', 0)} files[/dim])"+ )+ console.print("[dim]Distribution (by code volume):[/dim] " + " · ".join(parts) + "\n")+++def _render_badge(average_health: object) -> None:+ """Print ready-to-paste health-badge Markdown for a README.++ Emits a static shields badge for the current score (immediately usable) and+ documents the live endpoint form for a running Repowise server / hosted repo.+ """+ from repowise.core.analysis.health.grading import band_for++ if not isinstance(average_health, (int, float)):+ console.print("[yellow]No health score yet — run `repowise health` first.[/yellow]")+ return+ band = band_for(float(average_health))+ color = {"healthy": "brightgreen", "warning": "yellow", "alert": "red"}[band]+ msg = f"{float(average_health):.1f}/10"+ static = f"https://img.shields.io/badge/health-{msg.replace('/', '%2F')}-{color}"+ console.print("[bold]Static badge (current score):[/bold]")+ console.print(f" ")+ console.print("\n[bold]Live badge[/bold] [dim](running Repowise server or hosted repo):[/dim]")+ console.print(+ " "+ )++def _render_defect_accuracy_line(report: Any) -> None:"""One-line "does the score find the bugs?" validation, or nothing.diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.pyindex f5cf88899..dc546039b 100644--- a/packages/cli/src/repowise/cli/commands/status_cmd.py+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py@@ -187,8 +187,13 @@ def _query_health_line(repo_path: Path) -> str | None:worst_path = data["worst_performer_path"] or "n/a"worst_score = data["worst_performer_score"]worst_repr = f"{worst_score:.1f}" if worst_score is not None else "—"+ from repowise.core.analysis.health.grading import BAND_LABEL, band_for++ band = band_for(float(data["average_health"]))+ band_color = {"healthy": "green", "warning": "yellow", "alert": "red"}[band]return (- f"[bold]Health:[/bold] {data['average_health']:.1f} (avg) · "+ f"[bold]Health:[/bold] {data['average_health']:.1f} (avg) "+ f"[[{band_color}]{BAND_LABEL[band]}[/{band_color}]] · "f"{data['hotspot_health']:.1f} (hotspots) · "f"{worst_repr} (worst: {worst_path})")diff --git a/packages/core/src/repowise/core/analysis/health/README.md b/packages/core/src/repowise/core/analysis/health/README.mdindex 593e0f186..da3224807 100644--- a/packages/core/src/repowise/core/analysis/health/README.md+++ b/packages/core/src/repowise/core/analysis/health/README.md@@ -90,6 +90,11 @@ expose NLOC-weighted module aggregates and accept `module:foo` targets.Protocol from `biomarkers/base.py`. Twenty-six registered (see`biomarkers/registry.py` and `biomarkers/README.md` for the full list),plus three governance findings written by a separate additive pass.+- `grading.py` — the presentation "currency" layer over the score: the 3+ defect-backed bands (`band_for` — Alert `<4` / Warning `4–8` / Healthy `≥8`)+ and the NLOC-weighted `distribution`. Single source of truth for the cutoffs+ (mirrored in `@repowise-dev/types/health`). No letter grade — see+ `docs/architecture/code-health.md` §20.Each sub-package has its own `README.md` covering inputs, outputs, andextension points.diff --git a/packages/core/src/repowise/core/analysis/health/grading.py b/packages/core/src/repowise/core/analysis/health/grading.pynew file mode 100644index 000000000..8413f8158--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/grading.py@@ -0,0 +1,93 @@+"""Health bands + repo distribution — the "currency" layer over the score.++The 1-10 health score is the single number we surface. On top of it we put ONE+categorical scheme: the 3 defect-backed buckets **Healthy / Warning / Alert**.+Their cutoffs are not arbitrary - on our calibration corpus Alert files carry+roughly 17x the per-file defect rate of Healthy files, so the boundaries are+empirically defensible (see ``docs/CODE_HEALTH.md``).++This module is the SINGLE SOURCE OF TRUTH for the cutoffs. The TypeScript+mirror lives in ``packages/types/src/health.ts`` (``ALERT_MAX`` / ``HEALTHY_MIN``+/ ``bandForScore``) and a parity test on each side locks the values. We+deliberately ship NO letter grade - a letter on top of the number plus the band+would be a third overlapping scale with arbitrary cliffs.++Inputs are duck-typed (mapping ``m["score"]`` or object ``m.score``) so the same+functions serve the server (dict rows), the CLI (``HealthFileMetricData``), and+the hosted backend (``health.json`` dicts) without per-call-site adapters - the+same convention as ``defect_accuracy.py``.+"""++from __future__ import annotations++from typing import Any, Literal++HealthBand = Literal["healthy", "warning", "alert"]++# Canonical band cutoffs. Frozen (scoring is frozen; this is presentation).+# Score >= HEALTHY_MIN -> Healthy; score < ALERT_MAX -> Alert; between -> Warning.+HEALTHY_MIN = 8.0+ALERT_MAX = 4.0++BAND_LABEL: dict[HealthBand, str] = {+ "healthy": "Healthy",+ "warning": "Warning",+ "alert": "Alert",+}++# Ordered worst-first, matching how the surface lists files.+BAND_ORDER: tuple[HealthBand, ...] = ("alert", "warning", "healthy")+++def band_for(score: float) -> HealthBand:+ """Map a 1-10 score to its defect-backed band."""+ if score < ALERT_MAX:+ return "alert"+ if score < HEALTHY_MIN:+ return "warning"+ return "healthy"+++def _get(obj: Any, key: str, default: Any = None) -> Any:+ """Read ``key`` from a mapping or an attribute-bearing object."""+ if isinstance(obj, dict):+ return obj.get(key, default)+ return getattr(obj, key, default)+++def distribution(metrics: list[Any]) -> dict[str, Any]:+ """NLOC-weighted file distribution across the 3 bands.++ Returns the wire shape consumed by ``HealthDistribution`` in+ ``packages/types``: per-band file count, summed NLOC, and the NLOC-weighted+ percentage (0-100, rounded to 1 dp). NLOC is floored at 1 per file so a+ zero-NLOC file still counts once - mirroring the KPI weighting in+ ``scoring.compute_kpis``. An empty repo yields all-zero bands.+ """+ bands: dict[str, dict[str, float]] = {+ b: {"files": 0, "nloc": 0} for b in ("healthy", "warning", "alert")+ }+ total_files = 0+ total_weight = 0+ for m in metrics:+ if _get(m, "file_path") is None:+ continue+ score = float(_get(m, "score", 10.0))+ weight = max(int(_get(m, "nloc", 0) or 0), 1)+ band = band_for(score)+ bands[band]["files"] += 1+ bands[band]["nloc"] += weight+ total_files += 1+ total_weight += weight++ out_bands: dict[str, dict[str, Any]] = {}+ for b in ("healthy", "warning", "alert"):+ nloc = int(bands[b]["nloc"])+ pct = round(100.0 * nloc / total_weight, 1) if total_weight else 0.0+ out_bands[b] = {"files": int(bands[b]["files"]), "nloc": nloc, "pct": pct}++ return {+ "total_files": total_files,+ "total_nloc": total_weight,+ "bands": out_bands,+ }diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex 71fe1db33..2e1236094 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -7,6 +7,8 @@ from typing import Anyfrom sqlalchemy import select+from repowise.core.analysis.health.grading import band_for+from repowise.core.analysis.health.grading import distribution as health_distributionfrom repowise.core.analysis.health.suggestions import suggestion_forfrom repowise.core.analysis.health.trends import diff_snapshots, recent_kpisfrom repowise.core.persistence.crud import (@@ -16,6 +18,7 @@ from repowise.core.persistence.crud import ()from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import HealthFileMetric, HealthFinding+from repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server._helpers import (_get_exclude_spec,_get_repo,@@ -23,7 +26,6 @@ from repowise.server.mcp_server._helpers import (filter_rows_by_attr,)from repowise.server.mcp_server._meta import build_meta as _build_meta-from repowise.core.registry import mcp_tool_registry as mcpdef _serialize_finding(f: HealthFinding) -> dict[str, Any]:@@ -123,6 +125,7 @@ def _compute_kpis(metrics: list[HealthFileMetric]) -> dict[str, Any]:return {"file_count": len(metrics),"average_health": round(avg, 2),+ "band": band_for(round(avg, 2)),"worst_performer_path": worst.file_path,"worst_performer_score": round(worst.score, 2),}@@ -245,6 +248,7 @@ async def get_health(result = {"mode": "dashboard","kpis": kpis,+ "distribution": health_distribution(all_metrics),"worst_files": [_serialize_metric(m) for m in metric_rows[:limit]],"top_findings": [_serialize_finding(f) for f in finding_rows[:limit]],"modules": _module_rollups(all_metrics),diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.pyindex f8b62d5ca..993dadcca 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py@@ -10,6 +10,12 @@ from typing import Anyfrom sqlalchemy import func as sa_funcfrom sqlalchemy import select+from repowise.core.analysis.health.grading import (+ band_for,+)+from repowise.core.analysis.health.grading import (+ distribution as health_distribution,+)from repowise.core.generation.onboarding.slots import (ONBOARDING_ORDER,PROMOTED_SLOTS,@@ -557,11 +563,13 @@ async def get_overview(repo: str | None = None) -> dict:hotspot_avg = sum(m.score * max(m.nloc, 1) for m in top_q) / tot if tot else 10.0code_health = {"average_health": health_summary["average_health"],+ "band": band_for(float(health_summary["average_health"])),"hotspot_health": round(hotspot_avg, 2),"worst_performer_path": health_summary["worst_performer_path"],"worst_performer_score": health_summary["worst_performer_score"],"open_findings": health_summary["open_findings"],"file_count": health_summary["file_count"],+ "distribution": health_distribution(metrics_rows),}except Exception:code_health = {}diff --git a/packages/server/src/repowise/server/routers/code_health.py b/packages/server/src/repowise/server/routers/code_health.pyindex 110e77956..86b482f5c 100644--- a/packages/server/src/repowise/server/routers/code_health.py+++ b/packages/server/src/repowise/server/routers/code_health.py@@ -11,12 +11,14 @@ import jsonimport refrom typing import Any-from fastapi import APIRouter, Depends, HTTPException, Query+from fastapi import APIRouter, Depends, HTTPException, Query, Responsefrom pydantic import BaseModel, Fieldfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom 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_distributionfrom repowise.core.analysis.health.models import Severityfrom repowise.core.analysis.health.scoring import (CATEGORY_CAPS,@@ -216,11 +218,18 @@ async def health_overview(hotspot_health = round(float(latest.hotspot_health), 2)last_indexed_at = latest.taken_at.isoformat() if latest.taken_at else None+ metric_dicts = [_metric_to_dict(m) for m in metrics]++ # Repo-level band (from the NLOC-weighted average) + the per-band file+ # distribution. Both derive purely from the existing score — no new data.+ avg = summary.get("average_health")summary = {**summary,"hotspot_health": hotspot_health,"severity_breakdown": _severity_breakdown(findings),+ "band": band_for(float(avg)) if avg is not None else None,}+ distribution = health_distribution(metric_dicts)# "Does the score find the bugs?" self-validation, derived from the same# metrics + findings (prior_defect biomarker) already loaded above. ``None``@@ -236,8 +245,9 @@ async def health_overview(return {"summary": summary,+ "distribution": distribution,"defect_accuracy": defect_accuracy,- "files": [_metric_to_dict(m) for m in metrics[:limit]],+ "files": metric_dicts[:limit],"top_findings": top_findings,"modules": _module_rollups(metrics),"biomarkers": _biomarker_breakdown(findings),@@ -249,6 +259,112 @@ async def health_overview(}+# Shields-compatible band colors. Named colors for the JSON endpoint (shields+# resolves them) + hexes for the self-rendered SVG so it matches without a+# round-trip to img.shields.io.+_BADGE_COLOR_NAME: dict[str, str] = {+ "healthy": "brightgreen",+ "warning": "yellow",+ "alert": "red",+ "unknown": "lightgrey",+}+_BADGE_COLOR_HEX: dict[str, str] = {+ "brightgreen": "#4c1",+ "yellow": "#dfb317",+ "red": "#e05d44",+ "lightgrey": "#9f9f9f",+}+++def _badge_fields(average_health: float | None) -> tuple[str, str, str, str]:+ """Return ``(label, message, color_name, band)`` for the health badge."""+ if average_health is None:+ return "health", "no data", _BADGE_COLOR_NAME["unknown"], "unknown"+ band = band_for(float(average_health))+ return "health", f"{average_health:.1f}/10", _BADGE_COLOR_NAME[band], band+++def _render_badge_svg(label: str, message: str, color_name: str) -> str:+ """Render a flat shields-style SVG so the badge needs no external service.++ Char-width estimate matches shields' Verdana ~7px/char heuristic; exact+ pixel fidelity isn't needed for a README badge.+ """+ hex_color = _BADGE_COLOR_HEX.get(color_name, "#9f9f9f")+ lw = len(label) * 7 + 10+ mw = len(message) * 7 + 10+ total = lw + mw+ lx = lw * 10 // 2+ mx = (lw + mw // 2) * 10+ return (+ f'<svg xmlns="http://www.w3.org/2000/svg" width="{total}" height="20" '+ f'role="img" aria-label="{label}: {message}">'+ f"<title>{label}: {message}</title>"+ f'<linearGradient id="s" x2="0" y2="100%">'+ f'<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>'+ f'<stop offset="1" stop-opacity=".1"/></linearGradient>'+ f'<clipPath id="r"><rect width="{total}" height="20" rx="3" fill="#fff"/></clipPath>'+ f'<g clip-path="url(#r)">'+ f'<rect width="{lw}" height="20" fill="#555"/>'+ f'<rect x="{lw}" width="{mw}" height="20" fill="{hex_color}"/>'+ f'<rect width="{total}" height="20" fill="url(#s)"/></g>'+ f'<g fill="#fff" text-anchor="middle" '+ f'font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="110">'+ f'<text x="{lx}" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" '+ f'textLength="{(lw - 10) * 10}">{label}</text>'+ f'<text x="{lx}" y="140" transform="scale(.1)" textLength="{(lw - 10) * 10}">{label}</text>'+ f'<text x="{mx}" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" '+ f'textLength="{(mw - 10) * 10}">{message}</text>'+ f'<text x="{mx}" y="140" transform="scale(.1)" textLength="{(mw - 10) * 10}">{message}</text>'+ f"</g></svg>"+ )+++async def _badge_average_health(session: AsyncSession, repo_id: str) -> float | None:+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")+ summary = await crud.get_health_summary(session, repo_id)+ avg = summary.get("average_health")+ return float(avg) if avg is not None else None++[email protected]("/api/repos/{repo_id}/health/badge.json")+async def health_badge_json(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session), # noqa: B008+) -> dict:+ """Shields.io endpoint-badge payload (color + ``N.N/10`` score, no letter).++ Embed via ``https://img.shields.io/endpoint?url=<this-url>``.+ """+ avg = await _badge_average_health(session, repo_id)+ label, message, color, band = _badge_fields(avg)+ return {+ "schemaVersion": 1,+ "label": label,+ "message": message,+ "color": color,+ "band": band,+ }++[email protected]("/api/repos/{repo_id}/health/badge.svg")+async def health_badge_svg(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session), # noqa: B008+) -> Response:+ """Self-rendered flat SVG health badge (no external service round-trip)."""+ avg = await _badge_average_health(session, repo_id)+ label, message, color, _band = _badge_fields(avg)+ svg = _render_badge_svg(label, message, color)+ return Response(+ content=svg,+ media_type="image/svg+xml",+ headers={"Cache-Control": "max-age=300, public"},+ )++@router.get("/api/repos/{repo_id}/health/modules")async def health_modules(repo_id: str,diff --git a/packages/types/__tests__/health.test.ts b/packages/types/__tests__/health.test.tsnew file mode 100644index 000000000..509c9faa7--- /dev/null+++ b/packages/types/__tests__/health.test.ts@@ -0,0 +1,31 @@+/**+ * Runtime tests locking the health band cutoffs + the pure band mapping.+ *+ * These are the TypeScript half of the cross-language parity guard: the same+ * cutoffs are asserted in core (`tests/unit/health/test_grading.py`). If a+ * silent retune changes one side without the other, one of the two snapshots+ * fails CI. The 3 buckets are defect-backed (Alert ~17x the defect rate of+ * Healthy) so the boundaries are intentionally frozen.+ */++import { describe, expect, it } from "vitest";+import { ALERT_MAX, HEALTHY_MIN, bandForScore } from "../src/health.js";++describe("health band cutoffs", () => {+ it("are the frozen defect-backed values", () => {+ expect(ALERT_MAX).toBe(4.0);+ expect(HEALTHY_MIN).toBe(8.0);+ });+});++describe("bandForScore", () => {+ it("maps each band including boundaries", () => {+ expect(bandForScore(1.0)).toBe("alert");+ expect(bandForScore(3.99)).toBe("alert");+ expect(bandForScore(4.0)).toBe("warning"); // ALERT_MAX is inclusive of warning+ expect(bandForScore(6.0)).toBe("warning");+ expect(bandForScore(7.99)).toBe("warning");+ expect(bandForScore(8.0)).toBe("healthy"); // HEALTHY_MIN is inclusive of healthy+ expect(bandForScore(10.0)).toBe("healthy");+ });+});diff --git a/packages/types/package.json b/packages/types/package.jsonindex 4684bd510..a1871bcf5 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -25,7 +25,8 @@"./modules": "./src/modules.ts","./overview": "./src/overview.ts","./files": "./src/files.ts",- "./external-systems": "./src/external-systems.ts"+ "./external-systems": "./src/external-systems.ts",+ "./health": "./src/health.ts"},"publishConfig": {"registry": "https://npm.pkg.github.com",diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsnew file mode 100644index 000000000..5277dd0a1--- /dev/null+++ b/packages/types/src/health.ts@@ -0,0 +1,365 @@+/**+ * Canonical code-health wire contract — shared by the web dashboard+ * (`packages/web`), the shared UI (`packages/ui`), the hosted frontend, and+ * the bot. Mirrors the server's `routers/code_health.py` response shapes plus+ * the band/distribution "currency" layer.+ *+ * Before this module the health types lived web-locally in+ * `packages/web/src/lib/api/code-health.ts`; they were migrated here so every+ * consumer reads one contract.+ *+ * Band cutoffs are the SINGLE TypeScript mirror of the canonical Python source+ * in `packages/core/src/repowise/core/analysis/health/grading.py`. The two are+ * kept in sync by a parity test (`__tests__/health/band-cutoffs.test.ts` here,+ * `tests/unit/health/test_grading.py` in core). Do not hardcode `4`/`8` band+ * cutoffs anywhere else — derive from these consts or read the API `band`.+ */++/** Finding severity used across the health surface. */+export type HealthSeverity = "low" | "medium" | "high" | "critical";++/* ------------------------------------------------------------------ *+ * Band "currency" layer+ * ------------------------------------------------------------------ */++/**+ * The 3 defect-backed health buckets. Alert files carry roughly 17x the+ * defect rate of Healthy files on our calibration corpus, so the boundaries+ * are empirically defensible rather than arbitrary. This replaces the legacy+ * ad-hoc 4-band labeling (`critical/poor/fair/good`).+ */+export type HealthBand = "healthy" | "warning" | "alert";++/** Score at or above this is Healthy. */+export const HEALTHY_MIN = 8.0;+/** Score below this is Alert; `[ALERT_MAX, HEALTHY_MIN)` is Warning. */+export const ALERT_MAX = 4.0;++export const HEALTH_BAND_LABEL: Record<HealthBand, string> = {+ healthy: "Healthy",+ warning: "Warning",+ alert: "Alert",+};++/**+ * Pure score -> band mapping. Mirror of `grading.band_for` in core. Prefer the+ * API-provided `band` where available; use this only when deriving locally.+ */+export function bandForScore(score: number): HealthBand {+ if (score < ALERT_MAX) return "alert";+ if (score < HEALTHY_MIN) return "warning";+ return "healthy";+}++export interface HealthBandShare {+ /** Number of files in this band. */+ files: number;+ /** Sum of NLOC across the files in this band. */+ nloc: number;+ /** NLOC-weighted share of the repo in this band, 0-100. */+ pct: number;+}++/**+ * NLOC-weighted distribution of files across the 3 bands. The repo-level+ * "health distribution" surfaced on the dashboard + badge.+ */+export interface HealthDistribution {+ total_files: number;+ total_nloc: number;+ bands: Record<HealthBand, HealthBandShare>;+}++/* ------------------------------------------------------------------ *+ * Defect-accuracy ("does the score find the bugs?") — migrated from+ * packages/ui so the overview response can reference it without ui depending+ * back into web. `packages/ui` re-exports these for component prop typing.+ * ------------------------------------------------------------------ */++export interface DefectAccuracyFile {+ file_path: string;+ score: number;+ recent_fixes: number;+}++export interface DefectAccuracyPoint {+ k: number;+ hits: number;+}++export interface DefectAccuracy {+ k: number;+ hits: number;+ precision: number;+ base_rate: number;+ lift: number | null;+ window_days: number;+ scored_files: number;+ defect_files: number;+ concentration_file_fraction: number;+ concentration_defect_share: number;+ precision_table: DefectAccuracyPoint[];+ flagged_files: DefectAccuracyFile[];+}++/* ------------------------------------------------------------------ *+ * Core file/finding/module rows+ * ------------------------------------------------------------------ */++export interface HealthFileMetric {+ file_path: string;+ score: number;+ max_ccn: number;+ max_nesting: number;+ nloc: number;+ has_test_file: boolean;+ line_coverage_pct: number | null;+ module: string | null;+ duplication_pct?: number | null;+}++export interface HealthFinding {+ id: string;+ file_path: string;+ biomarker_type: string;+ severity: HealthSeverity;+ function_name: string | null;+ line_start: number | null;+ line_end: number | null;+ health_impact: number;+ reason: string;+ details: Record<string, unknown>;+ status: string;+ /** Matching symbol id when the finding names a function; links to the symbol page. */+ symbol_id?: string | null;+}++export interface HealthModuleRow {+ module: string;+ file_count: number;+ nloc: number;+ average_health: number;+ worst_performer_path: string;+ worst_performer_score: number;+}++export interface BiomarkerBreakdownRow {+ biomarker_type: string;+ critical: number;+ high: number;+ medium: number;+ low: number;+ total: number;+}++/* ------------------------------------------------------------------ *+ * Overview+ * ------------------------------------------------------------------ */++export interface HealthOverviewSummary {+ file_count: number;+ average_health: number;+ hotspot_health?: number | null;+ worst_performer_path: string | null;+ worst_performer_score: number | null;+ open_findings: number;+ severity_breakdown?: { critical: number; high: number; medium: number; low: number };+ /** Repo-level band derived from `average_health` (added in the band/distribution layer). */+ band?: HealthBand;+}++export interface HealthOverviewResponse {+ summary: HealthOverviewSummary;+ /** NLOC-weighted file distribution across the 3 bands. */+ distribution?: HealthDistribution | null;+ defect_accuracy?: DefectAccuracy | null;+ files: HealthFileMetric[];+ top_findings: HealthFinding[];+ modules?: HealthModuleRow[];+ biomarkers?: BiomarkerBreakdownRow[];+ meta?: {+ last_indexed_at: string | null;+ head_commit: string | null;+ snapshot_count: number;+ };+}++/* ------------------------------------------------------------------ *+ * Files list+ * ------------------------------------------------------------------ */++export interface HealthFilesResponse {+ total: number;+ offset: number;+ limit: number;+ files: HealthFileMetric[];+}++export interface HealthFilesQuery {+ limit?: number;+ offset?: number;+ sort?: string;+ order?: "asc" | "desc";+ search?: string;+ module?: string;+ only_hotspots?: boolean;+ only_untested?: boolean;+ only_failing?: boolean;+}++/* ------------------------------------------------------------------ *+ * File breakdown (score drill-down)+ * ------------------------------------------------------------------ */++export interface FileBreakdownFinding {+ id: string;+ biomarker_type: string;+ severity: HealthSeverity;+ raw_impact: number;+ applied_impact: number;+ function_name: string | null;+ reason: string;+}++export interface FileBreakdownCategory {+ category: string;+ cap: number;+ raw_deduction: number;+ applied_deduction: number;+ capped: boolean;+ finding_count: number;+ findings: FileBreakdownFinding[];+}++export interface HealthFileBreakdownResponse {+ file_path: string;+ metric: HealthFileMetric | null;+ breakdown: {+ score: number;+ total_deduction: number;+ categories: FileBreakdownCategory[];+ };+ findings: HealthFinding[];+ suggestions: Record<string, string>;+}++/* ------------------------------------------------------------------ *+ * Trend+ * ------------------------------------------------------------------ */++export interface HealthTrendResponse {+ history: Array<{+ taken_at: string | null;+ hotspot_health: number;+ average_health: number;+ worst_performer_path: string | null;+ worst_performer_score: number | null;+ }>;+ summary: {+ current_hotspot_health: number;+ current_average_health: number;+ previous_hotspot_health: number | null;+ previous_average_health: number | null;+ hotspot_delta: number | null;+ average_delta: number | null;+ };+ alerts: Array<{+ kind: string;+ metric: string;+ current: number;+ baseline: number | null;+ delta: number;+ message: string;+ }>;+ file_deltas: Array<{ file_path: string; before: number; after: number; delta: number }>;+ snapshot_count: number;+}++/* ------------------------------------------------------------------ *+ * Coverage+ * ------------------------------------------------------------------ */++export interface CoverageFileRow {+ file_path: string;+ source_format: string;+ line_coverage_pct: number;+ branch_coverage_pct: number | null;+ total_coverable_lines: number;+ ingested_at: string | null;+ ingested_commit_sha: string | null;+ covered_lines?: number[];+ health_score?: number;+ nloc?: number;+}++export interface ModuleCoverageRow {+ module: string;+ files: number;+ covered_lines: number;+ total_lines: number;+ line_coverage_pct: number;+}++export interface CoverageSummary {+ file_count: number;+ covered_lines: number;+ total_lines: number;+ line_coverage_pct: number | null;+ branch_coverage_pct: number | null;+ source_format: string | null;+ ingested_at: string | null;+ ingested_commit_sha: string | null;+}++export interface HealthCoverageResponse {+ summary: CoverageSummary;+ files: CoverageFileRow[];+ modules: ModuleCoverageRow[];+}++/* ------------------------------------------------------------------ *+ * Refactoring targets+ * ------------------------------------------------------------------ */++export interface RefactoringTarget {+ file_path: string;+ score: number;+ nloc: number;+ module?: string | null;+ primary_biomarker: string;+ primary_severity: HealthSeverity;+ primary_reason: string;+ primary_function: string | null;+ primary_line_start: number | null;+ primary_line_end: number | null;+ primary_suggestion?: string;+ primary_finding_id?: string;+ total_impact: number;+ finding_count: number;+ biomarkers: string[];+ effort_bucket: "S" | "M" | "L" | "XL";+ impact_per_effort: number;+ all_findings?: Array<{+ id: string;+ biomarker_type: string;+ severity: HealthSeverity;+ function_name: string | null;+ health_impact: number;+ reason: string;+ status?: string;+ }>;+}++export interface RefactoringTargetsResponse {+ targets: RefactoringTarget[];+ total: number;+}++export interface RefactoringQuery {+ limit?: number;+ module?: string;+ biomarker?: string;+ min_severity?: string;+ max_effort?: string;+ sort?: "impact_per_effort" | "total_impact" | "score" | "finding_count";+}diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 7befaeb20..3dbdf470a 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -25,3 +25,4 @@ export * from "./modules.js";export * from "./overview.js";export * from "./files.js";export * from "./external-systems.js";+export * from "./health.js";diff --git a/packages/ui/README.md b/packages/ui/README.mdindex 7f028a12a..572183d32 100644--- a/packages/ui/README.md+++ b/packages/ui/README.md@@ -80,10 +80,14 @@ the root of the app:fallback is `ApiError` with a reset retry.- **`EmptyState`** — the only sanctioned empty-state rendering. No raw`<p>` placeholders.-- Score colors come from ONE band helper in `health/tokens.ts`- (`scoreBand` / `scoreBadgeClass` / `scoreSoftBadgeClass` /- `scoreTextColor`): <4 critical, <6 poor, <8 fair, ≥8 good, mapped to- the semantic tokens (`--color-error/warning/caution/success`).+- Score colors come from `health/tokens.ts`. The canonical health *buckets*+ are the 3 defect-backed bands in `@repowise-dev/types/health`+ (`HealthBand` — Alert/Warning/Healthy at `<4 / 4–8 / ≥8`); use+ `healthBandSoftBadgeClass` / `healthBandTextColor` for band colors. The+ `scoreBand` / `scoreBadgeClass` / `scoreSoftBadgeClass` / `scoreTextColor`+ helpers are an internal 4-step color ramp (`<4 / <6 / <8 / ≥8`) for+ file-table pills only — not a labeling scheme — mapped to the semantic+ tokens (`--color-error/warning/caution/success`).## Peer depsdiff --git a/packages/ui/__tests__/health/distribution-badge.test.tsx b/packages/ui/__tests__/health/distribution-badge.test.tsxnew file mode 100644index 000000000..d749700ed--- /dev/null+++ b/packages/ui/__tests__/health/distribution-badge.test.tsx@@ -0,0 +1,53 @@+import { describe, it, expect } from "vitest";+import { render, screen } from "@testing-library/react";+import type { HealthDistribution } from "@repowise-dev/types/health";+import { HealthDistributionBar } from "../../src/health/health-distribution-bar.js";+import { HealthBadge } from "../../src/health/health-badge.js";++const DIST: HealthDistribution = {+ total_files: 10,+ total_nloc: 1000,+ bands: {+ healthy: { files: 6, nloc: 700, pct: 70 },+ warning: { files: 3, nloc: 200, pct: 20 },+ alert: { files: 1, nloc: 100, pct: 10 },+ },+};++describe("HealthDistributionBar", () => {+ it("renders the NLOC-weighted per-band shares", () => {+ render(<HealthDistributionBar distribution={DIST} />);+ expect(screen.getByText(/70% healthy/)).toBeInTheDocument();+ expect(screen.getByText(/20% warning/)).toBeInTheDocument();+ expect(screen.getByText(/10% alert/)).toBeInTheDocument();+ });++ it("shows an empty state when no files are analyzed", () => {+ const empty: HealthDistribution = {+ total_files: 0,+ total_nloc: 0,+ bands: {+ healthy: { files: 0, nloc: 0, pct: 0 },+ warning: { files: 0, nloc: 0, pct: 0 },+ alert: { files: 0, nloc: 0, pct: 0 },+ },+ };+ render(<HealthDistributionBar distribution={empty} />);+ expect(screen.getByText("No files analyzed.")).toBeInTheDocument();+ });+});++describe("HealthBadge", () => {+ it("renders the score and derives the band when none is passed", () => {+ render(<HealthBadge score={2.5} />);+ const el = screen.getByText("2.5");+ expect(el).toBeInTheDocument();+ // Alert band → error color class.+ expect(el.className).toContain("color-error");+ });++ it("renders nothing for a missing score", () => {+ const { container } = render(<HealthBadge score={null} />);+ expect(container).toBeEmptyDOMElement();+ });+});diff --git a/packages/ui/src/health/defect-accuracy-card.tsx b/packages/ui/src/health/defect-accuracy-card.tsxindex dd15fbb4e..2831b6fbd 100644--- a/packages/ui/src/health/defect-accuracy-card.tsx+++ b/packages/ui/src/health/defect-accuracy-card.tsx@@ -2,33 +2,16 @@import { useState } from "react";import { Check, ChevronDown, ChevronRight, Minus, Target, HelpCircle } from "lucide-react";+import type {+ DefectAccuracy,+ DefectAccuracyFile,+ DefectAccuracyPoint,+} from "@repowise-dev/types/health";import { Card } from "../ui/card";-export interface DefectAccuracyFile {- file_path: string;- score: number;- recent_fixes: number;-}--export interface DefectAccuracyPoint {- k: number;- hits: number;-}--export interface DefectAccuracy {- k: number;- hits: number;- precision: number;- base_rate: number;- lift: number | null;- window_days: number;- scored_files: number;- defect_files: number;- concentration_file_fraction: number;- concentration_defect_share: number;- precision_table: DefectAccuracyPoint[];- flagged_files: DefectAccuracyFile[];-}+// Canonical definitions now live in @repowise-dev/types; re-exported here so+// existing `@repowise-dev/ui/health` consumers keep working unchanged.+export type { DefectAccuracy, DefectAccuracyFile, DefectAccuracyPoint };/*** "Does the score actually find the buggy files?" card.diff --git a/packages/ui/src/health/health-badge.tsx b/packages/ui/src/health/health-badge.tsxindex 598766d5c..6195521da 100644--- a/packages/ui/src/health/health-badge.tsx+++ b/packages/ui/src/health/health-badge.tsx@@ -1,17 +1,23 @@-import { scoreSoftBadgeClass } from "./tokens";+import { bandForScore } from "@repowise-dev/types";+import type { HealthBand } from "@repowise-dev/types/health";+import { healthBandSoftBadgeClass } from "./tokens";export interface HealthBadgeProps {score: number | null | undefined;+ /** Explicit band from the API; when omitted it is derived from `score`+ * via the shared `bandForScore` mirror (no hardcoded cutoffs). */+ band?: HealthBand;size?: "xs" | "sm";}/** Compact health-score pill, designed to inline next to a file path* on Hotspot / Ownership / Graph rows without changing those shared* components' shapes. Renders nothing when the score is missing.- * Colors come from the shared score-band helper in tokens.ts. */-export function HealthBadge({ score, size = "xs" }: HealthBadgeProps) {+ * Colored by the 3 defect-backed health bands. */+export function HealthBadge({ score, band, size = "xs" }: HealthBadgeProps) {if (score == null) return null;- const cls = scoreSoftBadgeClass(score);+ const resolved = band ?? bandForScore(score);+ const cls = healthBandSoftBadgeClass(resolved);const sizing =size === "xs"? "text-[10px] px-1.5 py-0.5"diff --git a/packages/ui/src/health/health-distribution-bar.tsx b/packages/ui/src/health/health-distribution-bar.tsxnew file mode 100644index 000000000..59920b0fa--- /dev/null+++ b/packages/ui/src/health/health-distribution-bar.tsx@@ -0,0 +1,82 @@+import type { HealthBand, HealthDistribution } from "@repowise-dev/types/health";++/** Worst-first, matching how the surface lists files. */+const ORDER: HealthBand[] = ["alert", "warning", "healthy"];++const BAND_LABEL: Record<HealthBand, string> = {+ healthy: "Healthy",+ warning: "Warning",+ alert: "Alert",+};++/* Literal class strings so Tailwind's static scanner keeps them. */+const BAND_BAR: Record<HealthBand, string> = {+ healthy: "bg-[var(--color-success)]",+ warning: "bg-[var(--color-caution)]",+ alert: "bg-[var(--color-error)]",+};++const BAND_DOT: Record<HealthBand, string> = BAND_BAR;++export interface HealthDistributionBarProps {+ distribution: HealthDistribution;+ /** When true (default), render the per-band legend under the bar. */+ showCounts?: boolean;+ height?: "sm" | "md";+}++/**+ * NLOC-weighted distribution of files across the 3 defect-backed bands+ * (Alert / Warning / Healthy). Mirrors the `SeverityDistribution` idiom so the+ * health surface reads consistently. Widths are by code volume (NLOC), not file+ * count, so a single large unhealthy file isn't hidden behind many tiny ones.+ */+export function HealthDistributionBar({+ distribution,+ showCounts = true,+ height = "sm",+}: HealthDistributionBarProps) {+ const total = distribution.total_nloc;+ if (!distribution.total_files || total === 0) {+ return (+ <p className="text-xs text-[var(--color-text-tertiary)]">No files analyzed.</p>+ );+ }+ const h = height === "sm" ? "h-1.5" : "h-2";+ return (+ <div className="space-y-1.5">+ <div+ className={`flex w-full ${h} overflow-hidden rounded-full bg-[var(--color-bg-muted)]`}+ title={ORDER.map(+ (b) => `${BAND_LABEL[b]} ${distribution.bands[b].pct}%`,+ ).join(" · ")}+ >+ {ORDER.map((b) => {+ const pct = distribution.bands[b].pct;+ if (pct === 0) return null;+ return (+ <div+ key={b}+ className={BAND_BAR[b]}+ style={{ width: `${pct}%` }}+ aria-label={`${BAND_LABEL[b]} ${pct}%`}+ />+ );+ })}+ </div>+ {showCounts && (+ <div className="flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] text-[var(--color-text-tertiary)]">+ {ORDER.map((b) => (+ <span key={b} className="inline-flex items-center gap-1 tabular-nums">+ <span className={`inline-block h-1.5 w-1.5 rounded-full ${BAND_DOT[b]}`} />+ {distribution.bands[b].pct}% {BAND_LABEL[b].toLowerCase()}+ <span className="text-[var(--color-text-tertiary)]/70">+ ({distribution.bands[b].files})+ </span>+ </span>+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.tsindex 1523cd01b..a82ae6961 100644--- a/packages/ui/src/health/index.ts+++ b/packages/ui/src/health/index.ts@@ -13,6 +13,7 @@ export * from "./refactoring-target-list";export * from "./health-badge";export * from "./module-rollup-list";export * from "./severity-distribution";+export * from "./health-distribution-bar";export * from "./score-breakdown";export * from "./sparkline";export * from "./health-tabs";diff --git a/packages/ui/src/health/kpi-cards.tsx b/packages/ui/src/health/kpi-cards.tsxindex 97f70ee09..0ce7ea5f2 100644--- a/packages/ui/src/health/kpi-cards.tsx+++ b/packages/ui/src/health/kpi-cards.tsx@@ -1,8 +1,11 @@+import type { HealthBand, HealthDistribution } from "@repowise-dev/types/health";+import { bandForScore, HEALTH_BAND_LABEL } from "@repowise-dev/types";import { formatNumber } from "../lib/format";import { InfoTip } from "../shared/info-tip";-import { scoreTextColor, formatDelta, deltaColor } from "./tokens";+import { scoreTextColor, healthBandTextColor, formatDelta, deltaColor } from "./tokens";import { Sparkline } from "./sparkline";import { SeverityDistribution, type SeverityBreakdown } from "./severity-distribution";+import { HealthDistributionBar } from "./health-distribution-bar";export interface HealthSummary {file_count: number;@@ -12,10 +15,14 @@ export interface HealthSummary {worst_performer_score: number | null;open_findings: number;severity_breakdown?: SeverityBreakdown;+ /** Repo-level band from the API; derived from average_health when absent. */+ band?: HealthBand;}export interface HealthKpiCardsProps {summary: HealthSummary;+ /** NLOC-weighted file distribution across the 3 bands. */+ distribution?: HealthDistribution | null;/** Optional series for sparklines, newest-last. */averageHistory?: number[];hotspotHistory?: number[];@@ -26,12 +33,14 @@ export interface HealthKpiCardsProps {export function HealthKpiCards({summary,+ distribution,averageHistory,hotspotHistory,worstHistory,averageDelta,hotspotDelta,}: HealthKpiCardsProps) {+ const band = summary.band ?? bandForScore(summary.average_health);return (<div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-5"><Card label="Files Analyzed">@@ -41,11 +50,21 @@ export function HealthKpiCards({</Card><Card label="Average Health" sparkline={averageHistory} delta={averageDelta}><p- className={`text-2xl font-bold tabular-nums ${scoreTextColor(summary.average_health)}`}+ className={`flex items-baseline gap-2 text-2xl font-bold tabular-nums ${scoreTextColor(summary.average_health)}`}>- {summary.average_health.toFixed(1)}- <span className="text-base font-normal text-[var(--color-text-secondary)]">/10</span>+ <span>+ {summary.average_health.toFixed(1)}+ <span className="text-base font-normal text-[var(--color-text-secondary)]">/10</span>+ </span>+ <span className={`text-xs font-semibold uppercase tracking-wide ${healthBandTextColor(band)}`}>+ {HEALTH_BAND_LABEL[band]}+ </span></p>+ {distribution ? (+ <div className="mt-2">+ <HealthDistributionBar distribution={distribution} showCounts={false} height="sm" />+ </div>+ ) : null}</Card><Cardlabel="Hotspot Health"diff --git a/packages/ui/src/health/tokens.ts b/packages/ui/src/health/tokens.tsindex 7b8eb81b3..bbc2d3da5 100644--- a/packages/ui/src/health/tokens.ts+++ b/packages/ui/src/health/tokens.ts@@ -7,6 +7,8 @@* caution/success) so the surface themes correctly in both modes.*/+import type { HealthBand } from "@repowise-dev/types/health";+export type Severity = "critical" | "high" | "medium" | "low";export const SEVERITY_ORDER: Record<Severity, number> = {@@ -40,8 +42,12 @@ export const SEVERITY_BAR: Record<Severity, string> = {};/**- * The ONE score→band mapping. Every score color in the app derives from- * this: <4 critical, <6 poor, <8 fair, >=8 good.+ * Internal 4-step COLOR RAMP for score pills. This is presentation granularity+ * only — NOT a labeling scheme. The canonical, defect-backed health *buckets*+ * are the 3 `HealthBand` values (Healthy/Warning/Alert) defined once in+ * `@repowise-dev/types/health` (mirroring core `grading.py`); use those for any+ * surfaced band label or count. `scoreBand` keeps an extra step (poor vs fair+ * inside the Warning band) purely so the file-table pills read on a finer ramp.*/export type ScoreBand = "critical" | "poor" | "fair" | "good";@@ -52,13 +58,30 @@ export function scoreBand(score: number): ScoreBand {return "good";}-export const SCORE_BAND_LABEL: Record<ScoreBand, string> = {- critical: "Critical",- poor: "Poor",- fair: "Fair",- good: "Good",+/* Color classes for the 3 canonical health bands (Alert/Warning/Healthy).+ * Literal strings so Tailwind's static scanner keeps them. */+const HEALTH_BAND_TEXT: Record<HealthBand, string> = {+ alert: "text-[var(--color-error)]",+ warning: "text-[var(--color-caution)]",+ healthy: "text-[var(--color-success)]",+};++const HEALTH_BAND_BADGE_SOFT: Record<HealthBand, string> = {+ alert: "bg-[var(--color-error)]/15 text-[var(--color-error)]",+ warning: "bg-[var(--color-caution)]/15 text-[var(--color-caution)]",+ healthy: "bg-[var(--color-success)]/15 text-[var(--color-success)]",};+/** Band → soft badge class. Pass the API-provided band where available; falls+ * back to deriving it from a score via the shared `bandForScore` mirror. */+export function healthBandSoftBadgeClass(band: HealthBand): string {+ return HEALTH_BAND_BADGE_SOFT[band];+}++export function healthBandTextColor(band: HealthBand): string {+ return HEALTH_BAND_TEXT[band];+}+/* Literal class strings per band so Tailwind's static scanner sees them. */const BAND_TEXT: Record<ScoreBand, string> = {critical: "text-[var(--color-error)]",diff --git a/packages/ui/vitest.config.ts b/packages/ui/vitest.config.tsindex ab7cde6b3..b23df65ee 100644--- a/packages/ui/vitest.config.ts+++ b/packages/ui/vitest.config.ts@@ -24,6 +24,7 @@ export default defineConfig({"@repowise-dev/types/blast-radius": path.resolve(__dirname, "../types/src/blast-radius.ts"),"@repowise-dev/types/jobs": path.resolve(__dirname, "../types/src/jobs.ts"),"@repowise-dev/types/settings": path.resolve(__dirname, "../types/src/settings.ts"),+ "@repowise-dev/types/health": path.resolve(__dirname, "../types/src/health.ts"),},},});diff --git a/packages/web/src/components/code-health/triage-tab.tsx b/packages/web/src/components/code-health/triage-tab.tsxindex 1a83d04a9..eb69d39eb 100644--- a/packages/web/src/components/code-health/triage-tab.tsx+++ b/packages/web/src/components/code-health/triage-tab.tsx@@ -256,6 +256,7 @@ export function TriageTab({ repoId: id }: { repoId: string }) {<RecalibrationBanner repoId={id} /><HealthKpiCardssummary={overview.summary}+ distribution={overview.distribution}averageHistory={avgSeries}hotspotHistory={hotspotSeries}worstHistory={worstSeries}diff --git a/packages/web/src/lib/api/code-health.ts b/packages/web/src/lib/api/code-health.tsindex 26464ea8e..bebadeb38 100644--- a/packages/web/src/lib/api/code-health.ts+++ b/packages/web/src/lib/api/code-health.ts@@ -1,75 +1,45 @@-import type { DefectAccuracy } from "@repowise-dev/ui/health";+/**+ * Code-health API client. The response/query *types* now live in the shared+ * `@repowise-dev/types/health` contract (migrated out of this web-local file so+ * the hosted frontend and the bot read the same shapes); this module re-exports+ * them for back-compat and keeps only the fetch functions.+ */+import type {+ HealthFilesQuery,+ HealthFilesResponse,+ HealthFinding,+ HealthCoverageResponse,+ HealthFileBreakdownResponse,+ HealthOverviewResponse,+ HealthTrendResponse,+ RefactoringQuery,+ RefactoringTargetsResponse,+} from "@repowise-dev/types/health";import { apiGet, apiPatch } from "./client";-export type { DefectAccuracy } from "@repowise-dev/ui/health";--export interface HealthFileMetric {- file_path: string;- score: number;- max_ccn: number;- max_nesting: number;- nloc: number;- has_test_file: boolean;- line_coverage_pct: number | null;- module: string | null;- duplication_pct?: number | null;-}--export interface HealthFinding {- id: string;- file_path: string;- biomarker_type: string;- severity: "low" | "medium" | "high" | "critical";- function_name: string | null;- line_start: number | null;- line_end: number | null;- health_impact: number;- reason: string;- details: Record<string, unknown>;- status: string;- /** Matching symbol id when the finding names a function; links to the symbol page. */- symbol_id?: string | null;-}--export interface HealthModuleRow {- module: string;- file_count: number;- nloc: number;- average_health: number;- worst_performer_path: string;- worst_performer_score: number;-}--export interface BiomarkerBreakdownRow {- biomarker_type: string;- critical: number;- high: number;- medium: number;- low: number;- total: number;-}--export interface HealthOverviewResponse {- summary: {- file_count: number;- average_health: number;- hotspot_health?: number | null;- worst_performer_path: string | null;- worst_performer_score: number | null;- open_findings: number;- severity_breakdown?: { critical: number; high: number; medium: number; low: number };- };- defect_accuracy?: DefectAccuracy | null;- files: HealthFileMetric[];- top_findings: HealthFinding[];- modules?: HealthModuleRow[];- biomarkers?: BiomarkerBreakdownRow[];- meta?: {- last_indexed_at: string | null;- head_commit: string | null;- snapshot_count: number;- };-}+export type {+ BiomarkerBreakdownRow,+ CoverageFileRow,+ CoverageSummary,+ DefectAccuracy,+ FileBreakdownCategory,+ FileBreakdownFinding,+ HealthBand,+ HealthCoverageResponse,+ HealthDistribution,+ HealthFileBreakdownResponse,+ HealthFileMetric,+ HealthFilesQuery,+ HealthFilesResponse,+ HealthFinding,+ HealthModuleRow,+ HealthOverviewResponse,+ HealthTrendResponse,+ ModuleCoverageRow,+ RefactoringQuery,+ RefactoringTarget,+ RefactoringTargetsResponse,+} from "@repowise-dev/types/health";export async function getHealthOverview(repoId: string,@@ -93,25 +63,6 @@ export async function listHealthFindings(return apiGet<HealthFinding[]>(`/api/repos/${repoId}/health/findings`, opts);}-export interface HealthFilesResponse {- total: number;- offset: number;- limit: number;- files: HealthFileMetric[];-}--export interface HealthFilesQuery {- limit?: number;- offset?: number;- sort?: string;- order?: "asc" | "desc";- search?: string;- module?: string;- only_hotspots?: boolean;- only_untested?: boolean;- only_failing?: boolean;-}-export async function listHealthFiles(repoId: string,opts?: HealthFilesQuery,@@ -122,38 +73,6 @@ export async function listHealthFiles();}-export interface FileBreakdownFinding {- id: string;- biomarker_type: string;- severity: "low" | "medium" | "high" | "critical";- raw_impact: number;- applied_impact: number;- function_name: string | null;- reason: string;-}--export interface FileBreakdownCategory {- category: string;- cap: number;- raw_deduction: number;- applied_deduction: number;- capped: boolean;- finding_count: number;- findings: FileBreakdownFinding[];-}--export interface HealthFileBreakdownResponse {- file_path: string;- metric: HealthFileMetric | null;- breakdown: {- score: number;- total_deduction: number;- categories: FileBreakdownCategory[];- };- findings: HealthFinding[];- suggestions: Record<string, string>;-}-export async function getHealthFileBreakdown(repoId: string,filePath: string,@@ -164,34 +83,6 @@ export async function getHealthFileBreakdown();}-export interface HealthTrendResponse {- history: Array<{- taken_at: string | null;- hotspot_health: number;- average_health: number;- worst_performer_path: string | null;- worst_performer_score: number | null;- }>;- summary: {- current_hotspot_health: number;- current_average_health: number;- previous_hotspot_health: number | null;- previous_average_health: number | null;- hotspot_delta: number | null;- average_delta: number | null;- };- alerts: Array<{- kind: string;- metric: string;- current: number;- baseline: number | null;- delta: number;- message: string;- }>;- file_deltas: Array<{ file_path: string; before: number; after: number; delta: number }>;- snapshot_count: number;-}-export async function getHealthTrend(repoId: string, limit = 20): Promise<HealthTrendResponse> {return apiGet<HealthTrendResponse>(`/api/repos/${repoId}/health/trend`, { limit });}@@ -207,44 +98,6 @@ export async function updateFindingStatus();}-export interface CoverageFileRow {- file_path: string;- source_format: string;- line_coverage_pct: number;- branch_coverage_pct: number | null;- total_coverable_lines: number;- ingested_at: string | null;- ingested_commit_sha: string | null;- covered_lines?: number[];- health_score?: number;- nloc?: number;-}--export interface ModuleCoverageRow {- module: string;- files: number;- covered_lines: number;- total_lines: number;- line_coverage_pct: number;-}--export interface CoverageSummary {- file_count: number;- covered_lines: number;- total_lines: number;- line_coverage_pct: number | null;- branch_coverage_pct: number | null;- source_format: string | null;- ingested_at: string | null;- ingested_commit_sha: string | null;-}--export interface HealthCoverageResponse {- summary: CoverageSummary;- files: CoverageFileRow[];- modules: ModuleCoverageRow[];-}-export async function getHealthCoverage(repoId: string,opts?: { file_path?: string; limit?: number },@@ -255,49 +108,6 @@ export async function getHealthCoverage();}-export interface RefactoringTarget {- file_path: string;- score: number;- nloc: number;- module?: string | null;- primary_biomarker: string;- primary_severity: "low" | "medium" | "high" | "critical";- primary_reason: string;- primary_function: string | null;- primary_line_start: number | null;- primary_line_end: number | null;- primary_suggestion?: string;- primary_finding_id?: string;- total_impact: number;- finding_count: number;- biomarkers: string[];- effort_bucket: "S" | "M" | "L" | "XL";- impact_per_effort: number;- all_findings?: Array<{- id: string;- biomarker_type: string;- severity: "low" | "medium" | "high" | "critical";- function_name: string | null;- health_impact: number;- reason: string;- status?: string;- }>;-}--export interface RefactoringTargetsResponse {- targets: RefactoringTarget[];- total: number;-}--export interface RefactoringQuery {- limit?: number;- module?: string;- biomarker?: string;- min_severity?: string;- max_effort?: string;- sort?: "impact_per_effort" | "total_impact" | "score" | "finding_count";-}-export async function getRefactoringTargets(repoId: string,opts?: RefactoringQuery,diff --git a/tests/unit/health/test_grading.py b/tests/unit/health/test_grading.pynew file mode 100644index 000000000..2200cd71d--- /dev/null+++ b/tests/unit/health/test_grading.py@@ -0,0 +1,79 @@+"""Tests for the health band + distribution "currency" layer.++The cutoffs are frozen (D6: scoring/presentation is frozen) and mirrored in+``packages/types/src/health.ts``; the boundary assertions here are the Python+half of the cross-language parity guard.+"""++from __future__ import annotations++from repowise.core.analysis.health.grading import (+ ALERT_MAX,+ HEALTHY_MIN,+ band_for,+ distribution,+)+++def test_cutoffs_are_frozen_defect_backed_values() -> None:+ # If these change, the TS mirror (band-cutoffs test) must change too.+ assert ALERT_MAX == 4.0+ assert HEALTHY_MIN == 8.0+++def test_band_for_boundaries() -> None:+ assert band_for(1.0) == "alert"+ assert band_for(3.99) == "alert"+ assert band_for(4.0) == "warning" # ALERT_MAX inclusive of warning+ assert band_for(6.0) == "warning"+ assert band_for(7.99) == "warning"+ assert band_for(8.0) == "healthy" # HEALTHY_MIN inclusive of healthy+ assert band_for(10.0) == "healthy"+++def test_distribution_empty_repo() -> None:+ dist = distribution([])+ assert dist["total_files"] == 0+ assert dist["total_nloc"] == 0+ for band in ("healthy", "warning", "alert"):+ assert dist["bands"][band] == {"files": 0, "nloc": 0, "pct": 0.0}+++def test_distribution_nloc_weighted() -> None:+ # One healthy file with lots of NLOC vs many tiny alert files: the+ # percentage is NLOC-weighted, not file-count-weighted.+ metrics = [+ {"file_path": "big_healthy.py", "score": 9.0, "nloc": 900},+ {"file_path": "a.py", "score": 2.0, "nloc": 50},+ {"file_path": "b.py", "score": 3.0, "nloc": 50},+ ]+ dist = distribution(metrics)+ assert dist["total_files"] == 3+ assert dist["total_nloc"] == 1000+ assert dist["bands"]["healthy"] == {"files": 1, "nloc": 900, "pct": 90.0}+ assert dist["bands"]["alert"] == {"files": 2, "nloc": 100, "pct": 10.0}+ assert dist["bands"]["warning"] == {"files": 0, "nloc": 0, "pct": 0.0}+++def test_distribution_floors_zero_nloc_at_one() -> None:+ # A zero-NLOC file still counts once toward its band's weight.+ metrics = [+ {"file_path": "z.py", "score": 9.0, "nloc": 0},+ {"file_path": "w.py", "score": 5.0, "nloc": 0},+ ]+ dist = distribution(metrics)+ assert dist["total_nloc"] == 2+ assert dist["bands"]["healthy"]["nloc"] == 1+ assert dist["bands"]["warning"]["nloc"] == 1+++def test_distribution_accepts_objects() -> None:+ class _M:+ def __init__(self, path: str, score: float, nloc: int) -> None:+ self.file_path = path+ self.score = score+ self.nloc = nloc++ dist = distribution([_M("a.py", 9.0, 100), _M("b.py", 2.0, 100)])+ assert dist["bands"]["healthy"]["pct"] == 50.0+ assert dist["bands"]["alert"]["pct"] == 50.0diff --git a/tests/unit/server/test_health_badge.py b/tests/unit/server/test_health_badge.pynew file mode 100644index 000000000..109d9486d--- /dev/null+++ b/tests/unit/server/test_health_badge.py@@ -0,0 +1,27 @@+"""Pure-function tests for the health badge fields + SVG rendering."""++from __future__ import annotations++from repowise.server.routers.code_health import _badge_fields, _render_badge_svg+++def test_badge_fields_band_colors() -> None:+ assert _badge_fields(9.0) == ("health", "9.0/10", "brightgreen", "healthy")+ assert _badge_fields(6.0) == ("health", "6.0/10", "yellow", "warning")+ assert _badge_fields(2.0) == ("health", "2.0/10", "red", "alert")+++def test_badge_fields_no_data() -> None:+ _label, message, color, band = _badge_fields(None)+ assert message == "no data"+ assert band == "unknown"+ assert color == "lightgrey"+++def test_render_badge_svg_embeds_label_and_message() -> None:+ svg = _render_badge_svg("health", "7.4/10", "brightgreen")+ assert svg.startswith("<svg")+ assert svg.endswith("</svg>")+ assert "7.4/10" in svg+ assert "#4c1" in svg # brightgreen hex+ assert 'media' not in svg # sanity: it's markup, not a response wrapper