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): one band vocabulary, and counts for the CLI and MCP (#2180)
Raghav Chamadiyae88db81d7878
diff --git a/docs/BENCHMARKS.md b/docs/BENCHMARKS.mdindex c3318756b..aeb86ae6f 100644--- a/docs/BENCHMARKS.md+++ b/docs/BENCHMARKS.md@@ -514,7 +514,7 @@ this category with a published empirical defect study. Both tools scored the sam|---|---:|---:|---|| Recall at a 20%-of-lines review budget | **0.173** | 0.074 | p = 0.003 || Effort-aware ranking (Popt) | **0.607** | 0.462 | p = 0.003 |-| Defect density, size-normalized (Alert:Healthy) | **2.18x** | 0.56x | p = 0.003 |+| Defect density, size-normalized (below 4.0 : 8.0 and above) | **2.18x** | 0.56x | p = 0.003 || Discrimination (ROC AUC) | 0.731 | 0.705 | p = 0.054, marginal || Precision at a 20%-of-lines review budget | 0.580 | **0.636** | p = 0.64, a tie |diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex d81f83a06..38ad21766 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -195,8 +195,20 @@ and `search_codebase` (`kind`).`get_dead_code`'s `min_confidence` additionally accepts the tier names theresponse is organised by — `"high"` (0.8), `"medium"` (0.5), `"low"` (0.0) — as-well as a float. `get_health` reports the same thing under its own older name,-`unknown_only_keys`, for the `only` projection.+well as a float.++`get_health` is the exception to the shape. It reports a misspelled `only` key+under its own older name, `unknown_only_keys`, and everything else —+`refactoring_*` and `performance_*` filters, `scope`, `counts` — in+`ignored_arguments` as a flat map of argument to the value that was dropped:++```jsonc+"ignored_arguments": { "counts": "code-shape", "refactoring_effort": "tiny" }+```++A detail lookup (`finding_id`, `plan_id`, `opportunity_id`) reports `scope` and+`counts` there too: it answers about one stored row, so a population control has+nothing to act on.---@@ -881,6 +893,12 @@ representations of the same work in one response. The `include` **dimension** na| `performance_boundary` | string | No | `db` / `network` / `filesystem` / `subprocess` / `lock` / `none`. || `performance_confidence` | string | No | Evidence confidence: `high` / `medium` / `low`. Fix safety and actionability are separate facets. || `performance_sort` | string | No | `rank` (default) / `leverage` / `observations`. |+| `scope` | string | No | Which files every figure describes: `all` (default) or `production`. Narrowing drops test files from the headline, the distribution and every ranked list. Tests score higher than production code, so `production` lowers the number without a defect having been found. |+| `counts` | string | No | What the score counts: `everything` (default, the calibrated number) or `code_shape`, which removes the git-derived half. Change history rises as a file is worked on, so it answers what a repository has been through rather than what its code is like — `code_shape` is the reading that answers "is this code getting better". Files with no stored split are reported in `unscored_files` rather than counted. Findings from history are dropped, not re-scored. |++An unrecognized `scope` or `counts` falls back to the default and is named in+`ignored_arguments`, so a misspelling never answers a different question under+the name you asked for. Both are echoed on the response.**Returns:** Dashboard mode (no `targets`) returns a `directive`, repo-level KPIs(hotspot health, average health, worst performer, maintainability / performance@@ -904,7 +922,8 @@ window; `recovers_points_compatibility` names its replacement.**Nothing is dropped silently.** Any `targets` entry that matched nothing isnamed in `unresolved` with a reason (`not_indexed` → run `repowise update`,-`no_such_path`, `excluded`, `no_such_module`; a missed module name also returns+`no_such_path`, `excluded`, `not_measured` → indexed, but carrying no stored+split for the reading `counts` asked for, `no_such_module`; a missed module name also returns`known_modules`). Missing stored analysis is explicitly unavailable rather thanfabricated as a healthy score. Atarget set that resolves to nothing still answers in targeted mode rather than@@ -959,7 +978,7 @@ make that actionable rather than a mystery:`kpis.average_health_weighting` is `"nloc"`. When the weighted and unweightednumbers diverge, the gap is telling you to chase *big* files, not the long tail.- `gap_analysis` (dashboard mode) reports the net weighted points the average must- recover to reach the Healthy floor (8.0), how many files sit below it, and how+ recover to reach the target score (8.0), how many files sit below it, and howfew of them carry the whole gap (`files_to_reach_target`) or half of it(`files_for_half_gap`). This reframes a repo-wide number as a short worklist.- Every metric row carries `weighted_deficit = (8 - score) x nloc`: how much thediff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.mdindex da9ef64ac..16c204635 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├── ranking.py # canonical worst-first key + deduction fold├── aggregation.py # module rollups, severity/biomarker/score breakdowns-├── grading.py # 3 defect-backed bands + NLOC-weighted distribution+├── grading.py # the five absolute bands + NLOC-weighted distribution├── defect_accuracy.py # "does the score find the bugs?" self-validation├── trends.py # snapshot diff, Declining/Predicted alerts, per-file score series├── signals.py # per-file process/people/topology join (surfacing-only)@@ -178,8 +178,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 # score pill, colored by the 3 health bands-├── health-distribution-bar.tsx # NLOC-weighted Alert/Warning/Healthy split+├── health-badge.tsx # score pill, colored by the health band+├── health-distribution-bar.tsx # NLOC-weighted split across the five bands├── 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)@@ -724,7 +724,7 @@ silently re-scored for changed files only.Defined in `tool_health.py`. Modes:- **Dashboard mode** (`targets=None`): returns repo-level KPIs (with the- repo `band`) + the NLOC-weighted `distribution` across the 3 bands ++ repo `band`) + the NLOC-weighted `distribution` across the bands +`worst_files` (top N lowest-scoring) + `top_findings` + a per-module`modules` rollup.- **Targeted mode** (`targets=[...]`): returns full `metrics` +@@ -939,12 +939,11 @@ phases may revisit; the constraints kept v1 shippable.`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.+ categorical layer is the five absolute bands (Excellent / Good / Fair /+ Needs work / At risk, `grading.py`); a letter on top would be a third+ overlapping scale with arbitrary cliffs. Every surface that shows a band+ word or a band colour reads that one vocabulary — there is no second+ ramp.---diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex 82cc3c74f..460f2945f 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -153,18 +153,30 @@ files), and **Worst Performer**.### Bands-| Band | Score | Meaning |-|---|---|---|-| **Healthy** | `≥ 8.0` | Low-risk, maintainable |-| **Warning** | `4.0 – 8.0` | Rising complexity or process risk |-| **Alert** | `< 4.0` | High-risk; concentrates defects |--The cutoffs are empirical, not arbitrary. On the 2,770-file measured corpus,-Alert files carry **16.9× the per-file defect rate of Healthy files**-(95% CI 8.6–29.0), and **2.18×** the defects-per-KLOC once file size is-normalized out (95% CI 1.00–3.58). Both numbers belong together: the raw ratio-is the headline, and the size-normalized one is the proof it is not simply an-artifact of large files being large.+| Band | Score | Colour | Meaning |+|---|---|---|---|+| **Excellent** | `≥ 8.5` | green | Low-risk, maintainable |+| **Good** | `7.0 – 8.5` | green | Sound; nothing demanding attention |+| **Fair** | `5.5 – 7.0` | gold | Rising complexity or process risk |+| **Needs work** | `4.0 – 5.5` | amber | Worth scheduling |+| **At risk** | `< 4.0` | red | High-risk; concentrates defects |++The bands are **absolute, not percentile**, so a score means the same thing+behind a firewall as it does against a public corpus. Excellent and Good share+one green and are told apart by the word; green starts at 7.0 because a 7 is+not a warning.++The `4.0` cutoff is the empirical one and it has never moved. On the 2,770-file+measured corpus, files below it carry **16.9× the per-file defect rate of files+at 8.0 and above** (95% CI 8.6–29.0), and **2.18×** the defects-per-KLOC once+file size is normalized out (95% CI 1.00–3.58). Both numbers belong together:+the raw ratio is the headline, and the size-normalized one is the proof it is+not simply an artifact of large files being large. The boundaries above 4.0 are+reading points on that same scale rather than separate defect-rate claims.++`8.0` survives as `TARGET_SCORE`, the score a refactoring's leverage is+measured against. It is deliberately not a band edge — moving it would reorder+every recommendation.The bands are defined once in core (`analysis/health/grading.py`) and mirroredin `@repowise-dev/types`, with a parity test on each side.@@ -308,8 +320,8 @@ losses:- **AUC is not a win.** p = 0.054 is above 0.05. The correct statement is "atleast as good, consistent small edge," not "significantly better."-- **CodeScene's precision lead is a real design choice.** It flags **27** Alert- files where we flag **132**. That is a deliberately more conservative+- **CodeScene's precision lead is a real design choice.** It flags **27** files+ at its most severe level where we flag **132** At risk. That is a deliberately more conservativeoperating point: a short list a team will actually work through, tradedagainst recall. If you want a handful of files to fix this quarter rather thanthe ranking that catches the most defects, that operating point is better, anddiff --git a/docs/start/DASHBOARD.md b/docs/start/DASHBOARD.mdindex 004270469..c75167666 100644--- a/docs/start/DASHBOARD.md+++ b/docs/start/DASHBOARD.md@@ -45,7 +45,7 @@ scratch.The landing view. Repo KPIs (files, symbols, entry points, dead exports, healthaverages), an attention panel that promotes whatever currently deserves it-(declining health, a stale doc set, an alert-band file), a decisions timeline,+(declining health, a stale doc set, an at-risk file), a decisions timeline,quick actions, and a live banner while an index or generation job is running.If a job is in flight, the progress and log stream here.@@ -149,7 +149,7 @@ zoomed on one node. The older `/c4` and `/zoom` URLs redirect here.**Answers:** which files have the strongest defect indicators, and why?-<img src="../../.github/assets/dashboard/code-health.png" alt="Repowise code health: the three co-equal pillars, the alert/warning/healthy band distribution, KPI cards and the code health map" width="100%" />+<img src="../../.github/assets/dashboard/code-health.png" alt="Repowise code health: the three co-equal pillars, the health band distribution, KPI cards and the code health map" width="100%" />Tabs behind `?tab=`:diff --git a/packages/api-client/src/__fixtures__/hosted/file-detail.json b/packages/api-client/src/__fixtures__/hosted/file-detail.jsonindex 55c98c35c..269816248 100644--- a/packages/api-client/src/__fixtures__/hosted/file-detail.json+++ b/packages/api-client/src/__fixtures__/hosted/file-detail.json@@ -5,7 +5,7 @@"metric": {"file_path": ".pre-commit-config.yaml","score": 10,- "band": "healthy",+ "band": "excellent","max_ccn": 1,"max_nesting": 0,"nloc": 23,diff --git a/packages/api-client/src/__fixtures__/hosted/health-files.json b/packages/api-client/src/__fixtures__/hosted/health-files.jsonindex 49a51fdbb..dc405f3b1 100644--- a/packages/api-client/src/__fixtures__/hosted/health-files.json+++ b/packages/api-client/src/__fixtures__/hosted/health-files.json@@ -2,7 +2,7 @@{"file_path": "src/flask/app.py","score": 1.07,- "band": "alert",+ "band": "at_risk","max_ccn": 16,"max_nesting": 5,"nloc": 1235,@@ -63,7 +63,7 @@{"file_path": "src/flask/sansio/app.py","score": 1.35,- "band": "alert",+ "band": "at_risk","max_ccn": 12,"max_nesting": 4,"nloc": 678,@@ -124,7 +124,7 @@{"file_path": "src/flask/cli.py","score": 2.05,- "band": "alert",+ "band": "at_risk","max_ccn": 13,"max_nesting": 5,"nloc": 822,diff --git a/packages/api-client/src/__fixtures__/hosted/health-overview.json b/packages/api-client/src/__fixtures__/hosted/health-overview.jsonindex 045370abb..f2bff2bf3 100644--- a/packages/api-client/src/__fixtures__/hosted/health-overview.json+++ b/packages/api-client/src/__fixtures__/hosted/health-overview.json@@ -14,7 +14,7 @@{"file_path": "src/flask/app.py","score": 1.07,- "band": "alert",+ "band": "at_risk","max_ccn": 16,"max_nesting": 5,"nloc": 1235,@@ -75,7 +75,7 @@{"file_path": "src/flask/sansio/app.py","score": 1.35,- "band": "alert",+ "band": "at_risk","max_ccn": 12,"max_nesting": 4,"nloc": 678,@@ -136,7 +136,7 @@{"file_path": "src/flask/cli.py","score": 2.05,- "band": "alert",+ "band": "at_risk","max_ccn": 13,"max_nesting": 5,"nloc": 822,@@ -194,7 +194,7 @@{"file_path": "src/flask/sansio/blueprints.py","score": 3.53,- "band": "alert",+ "band": "at_risk","max_ccn": 22,"max_nesting": 3,"nloc": 557,@@ -254,7 +254,7 @@{"file_path": "src/flask/config.py","score": 5.15,- "band": "warning",+ "band": "needs_work","max_ccn": 7,"max_nesting": 3,"nloc": 282,diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.pyindex 57b9d7a4b..c9e4b43eb 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py@@ -23,6 +23,15 @@ from repowise.cli.helpers import (run_async,silence_logs_for_machine_output,)+from repowise.core.analysis.health.counts import (+ COUNTS,+ DEFAULT_COUNTS,+ parse_counts,+)+from repowise.core.analysis.health.counts import (+ project as project_counts,+)+from repowise.core.analysis.health.models import split_by_originfrom repowise.core.analysis.health.scope import DEFAULT_SCOPE, SCOPES, parse_scopefrom repowise.core.analysis.health.scoring import compute_kpis@@ -99,6 +108,15 @@ from .trends import _render_trend"so 'production' lowers every figure without a defect being found."),)+ "--counts",+ default=DEFAULT_COUNTS,+ type=click.Choice(list(COUNTS)),+ help=(+ "What the score counts. 'code_shape' removes the git-derived half, "+ "which rises as a file is worked on rather than describing its code."+ ),+)@click.option("--trend","trend_view",@@ -130,6 +148,7 @@ def health_command(generate_code: str | None,module_filter: str | None,scope: str,+ counts: str,trend_view: bool,badge_view: bool,verbose: bool,@@ -180,6 +199,14 @@ def health_command(status.print(f"[bold]repowise health[/bold] — {repo_path}")if trend_view:+ # The trend reads stored snapshots, which carry the calibrated score+ # only. Saying so beats printing a projected headline's flag over an+ # unprojected line.+ if parse_scope(scope) != DEFAULT_SCOPE or parse_counts(counts) != DEFAULT_COUNTS:+ status.print(+ "[dim]The trend reads stored snapshots, so --scope and --counts "+ "do not apply to it.[/dim]"+ )_render_trend(repo_path, fmt=fmt)return@@ -279,24 +306,37 @@ def health_command(metrics = [m for m in metrics if m.file_path == file_filter]if module_filter:metrics = [m for m in metrics if m.file_path.startswith(module_filter)]- if parse_scope(scope) == "production":+ narrowed = parse_scope(scope) == "production"+ if narrowed:metrics = [m for m in metrics if not m.is_test]- # Every figure, not just the table: the flag says production, so the- # headline, the hotspot number, the worst performer and the- # distribution all have to describe that population too.+ # Taken before the projection, so a row the projection cannot read still+ # keeps its findings rather than reading as a file that left the repo.+ scoped_paths = {m.file_path for m in metrics}+ code_shape = parse_counts(counts) == "code_shape"+ if code_shape:+ # No `unscored` counterpart to the API's: this command scores live, so+ # every row carries the split the projection reads.+ metrics, _ = project_counts(counts, metrics)+ if narrowed or code_shape:+ # Every figure the controls select for. Defect accuracy below is not+ # one of them: it scores the ranking against `prior_defect`, and+ # narrowing leaves it no labels to be accurate about.report.kpis = compute_kpis(metrics, {p for p, m in git_meta_map.items() if m.get("is_hotspot")})metrics_sorted = sorted(metrics, key=lambda m: m.score)- scoped_paths = {m.file_path for m in metrics}findings = report.findingsif file_filter:findings = [f for f in findings if f.file_path == file_filter]if module_filter:findings = [f for f in findings if f.file_path.startswith(module_filter)]- if parse_scope(scope) == "production":+ if narrowed:findings = [f for f in findings if f.file_path in scoped_paths]+ if code_shape:+ # A history finding cannot explain a score the history half was taken+ # out of, so it is not part of this reading.+ findings = split_by_origin(findings)[0]if generate_code is not None:suggestions = getattr(report, "refactoring_suggestions", None) or []@@ -329,6 +369,8 @@ def health_command(json.dumps({"kpis": report.kpis,+ "scope": parse_scope(scope),+ "counts": parse_counts(counts),"metrics": [{"file_path": m.file_path,@@ -376,6 +418,7 @@ def health_command(# Table formatfrom repowise.core.analysis.health.grading import (BAND_LABEL,+ BAND_TERMINAL_COLOR,band_for,)from repowise.core.analysis.health.grading import (@@ -387,7 +430,7 @@ def health_command(band_str = ""if isinstance(avg, (int, float)):band = band_for(float(avg))- band_color = {"healthy": "green", "warning": "yellow", "alert": "red"}[band]+ band_color = BAND_TERMINAL_COLOR[band]band_str = f" [[{band_color}]{BAND_LABEL[band]}[/{band_color}]]"console.print(f"\nCode health: [bold]{avg if avg is not None else '?'}[/bold]/10{band_str} · "@@ -395,6 +438,8 @@ def health_command(f"Worst: [bold]{kpis.get('worst_performer_score', '?')}[/bold]/10 "f"({kpis.get('worst_performer_path', 'n/a')})")+ if code_shape:+ console.print("[dim]Counting code shape only — change history is left out.[/dim]")_render_split_line(kpis)_render_distribution_line(health_distribution(metrics))@@ -416,7 +461,7 @@ def health_command(table.add_column("NLOC", justify="right")table.add_column("Test?", justify="center")for m in metrics_sorted[:20]:- score_color = "red" if m.score < 4 else "yellow" if m.score < 7 else "green"+ score_color = BAND_TERMINAL_COLOR[band_for(m.score)]table.add_row(m.file_path,f"[{score_color}]{m.score:.1f}[/{score_color}]",diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/summary.py b/packages/cli/src/repowise/cli/commands/health_cmd/summary.pyindex a333303b4..3b06ce464 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/summary.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/summary.py@@ -67,15 +67,22 @@ def _render_split_line(kpis: dict) -> None:def _render_distribution_line(dist: dict) -> None:- """One compact line: the NLOC-weighted file split across the 3 bands."""+ """One compact line: the NLOC-weighted file split across the bands."""+ from repowise.core.analysis.health.grading import (+ BAND_LABEL,+ BAND_ORDER,+ BAND_TERMINAL_COLOR,+ )+bands = dist.get("bands") or {}if not dist.get("total_files"):returnparts = []- for band, color in (("healthy", "green"), ("warning", "yellow"), ("alert", "red")):+ for band in BAND_ORDER:+ color = BAND_TERMINAL_COLOR[band]share = bands.get(band) or {}parts.append(- f"[{color}]{share.get('pct', 0)}%[/{color}] {band} "+ f"[{color}]{share.get('pct', 0)}%[/{color}] {BAND_LABEL[band].lower()} "f"([dim]{share.get('files', 0)} files[/dim])")console.print("[dim]Distribution (by code volume):[/dim] " + " · ".join(parts) + "\n")@@ -87,13 +94,12 @@ def _render_badge(average_health: object) -> None:Emits a static shields badge for the current score (immediately usable) anddocuments the live endpoint form for a running Repowise server / hosted repo."""- from repowise.core.analysis.health.grading import band_for+ from repowise.core.analysis.health.grading import BAND_BADGE_COLOR, band_forif 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]+ color = BAND_BADGE_COLOR[band_for(float(average_health))]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]")diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.pyindex 43ad4ef58..25332789c 100644--- a/packages/cli/src/repowise/cli/commands/status_cmd.py+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py@@ -271,10 +271,14 @@ 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+ from repowise.core.analysis.health.grading import (+ BAND_LABEL,+ BAND_TERMINAL_COLOR,+ band_for,+ )band = band_for(float(data["average_health"]))- band_color = {"healthy": "green", "warning": "yellow", "alert": "red"}[band]+ band_color = BAND_TERMINAL_COLOR[band]# Maintainability and performance are co-surfaced pillars; show each when the# split has populated it (None on indexes that predate the relevant work).maint = data.get("maintainability_average")diff --git a/packages/core/src/repowise/core/analysis/health/README.md b/packages/core/src/repowise/core/analysis/health/README.mdindex 61964f38d..5405baddf 100644--- a/packages/core/src/repowise/core/analysis/health/README.md+++ b/packages/core/src/repowise/core/analysis/health/README.md@@ -157,9 +157,11 @@ orchestrator (falls back to the top-level directory). The MCP toolProtocol 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+- `grading.py` — the presentation "currency" layer over the score: the five+ absolute bands (`band_for` — Excellent `≥8.5` / Good `≥7.0` / Fair `≥5.5` /+ Needs work `≥4.0` / At risk below) and the NLOC-weighted `distribution`.+ It also owns `TARGET_SCORE`, the refactoring deficit target, which is+ deliberately not a band edge. Single source of truth for the cutoffs(mirrored in `@repowise-dev/types/health`). No letter grade — see`docs/architecture/code-health.md` §20.diff --git a/packages/core/src/repowise/core/analysis/health/counts.py b/packages/core/src/repowise/core/analysis/health/counts.pyindex f4c52765c..12ff8bf43 100644--- a/packages/core/src/repowise/core/analysis/health/counts.py+++ b/packages/core/src/repowise/core/analysis/health/counts.py@@ -50,13 +50,12 @@ class CodeShapeMetric:write the projection back to the store on the next flush."""- # ``score`` is the surfaced number every aggregate weights and- # ``defect_score`` mirrors it on the wire; both move or the page disagrees- # with itself. ``history_deduction`` reads 0.0 because that is what this- # reading counts, which keeps every figure derived from the two halves —- # the wire row's ``unclamped_score``, the summary's history average — in- # step with the score beside it rather than describing the other reading.- # Everything else falls through to the row.+ # ``score`` is the surfaced number every aggregate weights, and+ # ``defect_score`` mirrors it for the REST serializer, which emits both.+ # ``history_deduction`` reads 0.0 because that is what this reading counts,+ # which keeps the figures derived from the two halves — the REST row's+ # ``unclamped_score``, the summary's history average — in step with the+ # score beside them. Everything else falls through to the row.__slots__ = ("_row", "defect_score", "history_deduction", "score")def __init__(self, row: Any, score: float) -> None:diff --git a/packages/core/src/repowise/core/analysis/health/grading.py b/packages/core/src/repowise/core/analysis/health/grading.pyindex d44e69667..b7835f47f 100644--- a/packages/core/src/repowise/core/analysis/health/grading.py+++ b/packages/core/src/repowise/core/analysis/health/grading.py@@ -1,16 +1,15 @@"""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/layers/CODE_HEALTH.md``).+categorical scheme: five absolute bands, **Excellent / Good / Fair / Needs work+/ At risk**. Absolute rather than percentile, so a score means the same thing+behind a firewall as it does against a public corpus. Excellent and Good share+one green and are told apart by the word.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.+mirror lives in ``packages/types/src/health.ts`` 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 samefunctions serve the server (dict rows), the CLI (``HealthFileMetricData``), and@@ -24,34 +23,83 @@ from typing import Any, Literalfrom .rows import field-HealthBand = Literal["healthy", "warning", "alert"]+HealthBand = Literal["excellent", "good", "fair", "needs_work", "at_risk"]-# 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+# Absolute band cutoffs. Frozen (scoring is frozen; this is presentation).+# Green starts at 7.0 because a 7 is not a warning; 4.0 is the long-standing+# most-severe cutoff, so the worst classification keeps its meaning.+EXCELLENT_MIN = 8.5+GOOD_MIN = 7.0+FAIR_MIN = 5.5+NEEDS_WORK_MIN = 4.0++# The score a refactoring is measured against. Deliberately not a band edge:+# it is the deficit target behind refactoring leverage, and moving it would+# reorder every recommendation.+TARGET_SCORE = 8.0BAND_LABEL: dict[HealthBand, str] = {- "healthy": "Healthy",- "warning": "Warning",- "alert": "Alert",+ "excellent": "Excellent",+ "good": "Good",+ "fair": "Fair",+ "needs_work": "Needs work",+ "at_risk": "At risk",+}++# The range each band covers, for keys and legends that show the boundaries.+BAND_RANGE_LABEL: dict[HealthBand, str] = {+ "excellent": "8.5+",+ "good": "7.0 to 8.5",+ "fair": "5.5 to 7.0",+ "needs_work": "4.0 to 5.5",+ "at_risk": "under 4.0",}# Ordered worst-first, matching how the surface lists files.-BAND_ORDER: tuple[HealthBand, ...] = ("alert", "warning", "healthy")+BAND_ORDER: tuple[HealthBand, ...] = (+ "at_risk",+ "needs_work",+ "fair",+ "good",+ "excellent",+)++# Terminal colours for the CLI. Fair and Needs work are distinct steps down+# from green, so they do not share a hue.+BAND_TERMINAL_COLOR: dict[HealthBand, str] = {+ "excellent": "green",+ "good": "green",+ "fair": "yellow",+ "needs_work": "dark_orange",+ "at_risk": "red",+}++# shields.io colour names for the health badge. Excellent and Good share the+# one green, as they do on every other surface.+BAND_BADGE_COLOR: dict[HealthBand, str] = {+ "excellent": "brightgreen",+ "good": "brightgreen",+ "fair": "yellow",+ "needs_work": "orange",+ "at_risk": "red",+}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"+ """Map a 1-10 score to its band."""+ if score >= EXCELLENT_MIN:+ return "excellent"+ if score >= GOOD_MIN:+ return "good"+ if score >= FAIR_MIN:+ return "fair"+ if score >= NEEDS_WORK_MIN:+ return "needs_work"+ return "at_risk"def distribution(metrics: list[Any]) -> dict[str, Any]:- """NLOC-weighted file distribution across the 3 bands.+ """NLOC-weighted file distribution across the bands.Returns the wire shape consumed by ``HealthDistribution`` in``packages/types``: per-band file count, summed NLOC, and the NLOC-weighted@@ -59,9 +107,7 @@ def distribution(metrics: list[Any]) -> dict[str, Any]: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")- }+ bands: dict[str, dict[str, float]] = {b: {"files": 0, "nloc": 0} for b in BAND_ORDER}total_files = 0total_weight = 0for m in metrics:@@ -76,7 +122,7 @@ def distribution(metrics: list[Any]) -> dict[str, Any]:total_weight += weightout_bands: dict[str, dict[str, Any]] = {}- for b in ("healthy", "warning", "alert"):+ for b in BAND_ORDER:nloc = int(bands[b]["nloc"])pct = round(100.0 * nloc / total_weight, 1) if total_weight else 0.0out_bands[b] = {"files": int(bands[b]["files"]), "nloc": nloc, "pct": pct}diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.pyindex cbdfd8a62..2a822e2cb 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py@@ -16,7 +16,7 @@ from typing import Any, Literalfrom sqlalchemy.ext.asyncio import AsyncSession-from repowise.core.analysis.health.grading import HEALTHY_MIN+from repowise.core.analysis.health.grading import TARGET_SCOREfrom repowise.core.analysis.test_reachability import ReachedBy, tests_reaching_by_tierfrom .models import RefactoringSuggestion@@ -494,7 +494,7 @@ def _priority_components(dependents: int,validation: ValidationPlan,) -> tuple[float, float, float, float, float, int]:- weighted_deficit = round(max(HEALTHY_MIN - health_score, 0.0) * max(nloc, 1))+ weighted_deficit = round(max(TARGET_SCORE - health_score, 0.0) * max(nloc, 1))benefit = detector_native_benefit(suggestion)entry_bonus = 0.5 if (suggestion.evidence or {}).get("reliable_entry_reachability") else 0.0leverage = 0.5 * math.log1p(weighted_deficit) + math.log1p(max(0, dependents)) + entry_bonus@@ -542,8 +542,8 @@ def build_recommendations(enrich_blast_radius(suggestion, centrality)metric = metrics.get(suggestion.file_path)nloc = int(_attr(metric, "nloc", 0) or 0)- raw_health_score = _attr(metric, "score", HEALTHY_MIN)- health_score = float(HEALTHY_MIN if raw_health_score is None else raw_health_score)+ raw_health_score = _attr(metric, "score", TARGET_SCORE)+ health_score = float(TARGET_SCORE if raw_health_score is None else raw_health_score)dependents = int(float(centrality.get(suggestion.file_path, 0.0) or 0.0))validation = validations.get(index) or build_validation_plan(suggestion, {}, {})benefit, leverage, cost, risk, rank_score, deficit = _priority_components(diff --git a/packages/core/src/repowise/core/analysis/health/semantics.py b/packages/core/src/repowise/core/analysis/health/semantics.pyindex 451324216..d045fac68 100644--- a/packages/core/src/repowise/core/analysis/health/semantics.py+++ b/packages/core/src/repowise/core/analysis/health/semantics.py@@ -14,7 +14,7 @@ def weighted_deficit_contract() -> dict[str, Any]:"scale": {"minimum": 0, "maximum": None, "normalized": False},"direction": ("higher means the file contributes more to the eligible population's "- "gross deficit from the Healthy threshold"+ "gross deficit from the refactoring target score"),"interpretation": ("a deterministic triage weight, not a probability, percentage, "diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex 8c5e99b30..e7e1cdfaa 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -13,10 +13,17 @@ from sqlalchemy import func, selectfrom repowise.core.analysis.health.aggregation import module_rollups as _module_rollupsfrom repowise.core.analysis.health.churn_complexity import churn_complexity_points+from repowise.core.analysis.health.counts import (+ DEFAULT_COUNTS,+ parse_counts,+)+from repowise.core.analysis.health.counts import (+ project as project_counts,+)from repowise.core.analysis.health.coverage import decay_since, measurement_reffrom repowise.core.analysis.health.defect_accuracy import compute_defect_accuracyfrom repowise.core.analysis.health.finding_identity import finding_public_id-from repowise.core.analysis.health.grading import HEALTHY_MIN, band_for+from repowise.core.analysis.health.grading import TARGET_SCORE, band_forfrom repowise.core.analysis.health.grading import distribution as health_distributionfrom repowise.core.analysis.health.models import primary_finding, split_by_originfrom repowise.core.analysis.health.perf.coverage import PerfCoverage, coverage_for_metrics@@ -142,6 +149,28 @@ def _selector_conflict(**selectors: str | None) -> dict[str, Any] | None:}+def _note_inapplicable_controls(+ result: dict[str, Any], scope: str, counts: str+) -> dict[str, Any]:+ """Name ``scope`` / ``counts`` when a detail lookup cannot honour them.++ These select a population; a lookup by id answers about one stored row and+ is always the calibrated reading. Silently accepting the control returned+ that row to a caller who believes they asked for a different one.+ """+ inapplicable = {+ name: value+ for name, value, default in (+ ("scope", scope, DEFAULT_SCOPE),+ ("counts", counts, DEFAULT_COUNTS),+ )+ if value is not None and value != default+ }+ if inapplicable:+ result["ignored_arguments"] = {**result.get("ignored_arguments", {}), **inapplicable}+ return result++@dataclass(frozen=True, slots=True)class _PerformanceBlocks:"""Everything the performance pillar contributes to one response."""@@ -753,16 +782,17 @@ def _serialize_metric("line_coverage_pct": m.line_coverage_pct,"branch_coverage_pct": m.branch_coverage_pct,"module": m.module,- # Leverage: NLOC-weighted points this file drags below the Healthy band- # (``(8.0 - score) * nloc``, 0 once healthy). This is how much the repo- # headline recovers if the file reaches 8.0, so ranking by it — not by- # raw score — points at the files that actually move the average. A tiny- # 1.0 file and a 1200-line 1.0 file score the same but differ 40x here.+ # Leverage: NLOC-weighted points this file drags below the target score+ # (``(8.0 - score) * nloc``, 0 once the file is at target). This is+ # how much the repo headline recovers if the file reaches 8.0, so+ # ranking by it — not by raw score — points at the files that actually+ # move the average. A tiny 1.0 file and a 1200-line 1.0 file score the+ # same but differ 40x here.# The unit is score-points x NLOC, which is meaningless on its own — the# docstring and ``gap_analysis.weighted_gap_points`` give it a# denominator, and every ``high_leverage_files`` row carries the same# quantity as ``share_of_repo_gap_pct``.- "weighted_deficit": round(max(HEALTHY_MIN - m.score, 0.0) * max(m.nloc, 1)),+ "weighted_deficit": round(max(TARGET_SCORE - m.score, 0.0) * max(m.nloc, 1)),# Per-dimension scores from the three-signal split. ``defect_score`` is# deliberately absent: ``engine.py`` sets it and ``score`` from the same# ``scores["defect"]`` value, so it was pure duplication on every row of@@ -868,6 +898,7 @@ def _unresolved_targets(matched_modules: set[str],resolved_paths: set[str],excluded_paths: set[str],+ unscored_paths: set[str],repo_root: Any,) -> list[dict[str, str]]:"""Name every requested target that produced no rows, with a reason.@@ -876,7 +907,12 @@ def _unresolved_targets(empty ``findings`` list reads as "this file is healthy", which is the mostdamaging default this tool can have. The reason is the actionable part —``not_indexed`` means run ``repowise update``, ``no_such_path`` means the- target was a typo, ``excluded`` means the repo config drops it on purpose.+ target was a typo, ``excluded`` means the repo config drops it on purpose,+ and ``not_measured`` means the row is indexed but carries no stored split+ for the reading ``counts`` asked for. That last one is why the projection+ is passed in rather than inferred: an indexed file it could not answer for+ would otherwise read as ``not_indexed`` and send the caller to run an+ update that changes nothing."""out: list[dict[str, str]] = []for t in file_targets:@@ -884,6 +920,8 @@ def _unresolved_targets(continueif t in excluded_paths:reason = "excluded"+ elif t in unscored_paths:+ reason = "not_measured"else:try:on_disk = (Path(repo_root) / t).exists()@@ -927,7 +965,7 @@ def _directive((m for m in by_leverage if (leads.get(m.file_path) or {}).get("actionable_biomarker")),by_leverage[0],)- recovers = round(max(HEALTHY_MIN - top.score, 0.0) * max(top.nloc, 1))+ recovers = round(max(TARGET_SCORE - top.score, 0.0) * max(top.nloc, 1))lead = leads.get(top.file_path) or {}# Does anything behind ``plan_via`` actually address the cause named in# ``reason``? Plans carry the biomarker that produced them, and several@@ -943,11 +981,11 @@ def _directive(out = {"fix_first": top.file_path,"reason": lead.get("actionable_reason") or f"scores {round(top.score, 2)}",- # Points the repo headline recovers if this one file reaches Healthy,+ # Points the repo headline recovers if this one file reaches the target,# and what share of the total gap that is — the "few files, not the# long tail" argument made concrete for a single file. The denominator# is the *gross* deficit of all below-target files (not the net gap,- # which healthy files cushion): per-file shares are then bounded by+ # which above-target files cushion): per-file shares are then bounded by# 100% and sum to 100% by construction (issue #1437)."recovers_weighted_deficit_points": recovers,"recovers_points": recovers,@@ -1267,38 +1305,38 @@ def _gap_analysis(metrics: list[HealthFileMetric]) -> dict[str, Any]:kept deliberately distinct:- ``weighted_gap_points`` — the **net** points the average needs- (``8.0 * total_nloc - Σ score*nloc``). Healthy files already sit above 8.0- and cushion it, so this is smaller than the gross all-files-healthy+ (``8.0 * total_nloc - Σ score*nloc``). Files already above the target+ cushion it, so this is smaller than the gross every-file-at-targetdeficit and is the number that matches the goal "move the average".``files_to_reach_target`` is the punchline: lift the worst-deficit N filesto 8.0 and the headline crosses 8.0. This can be 0 or negative on a- mostly-healthy repo (the average is already above 8.0).+ repo that is mostly at target (the average is already above 8.0).- ``weighted_gross_gap_points`` — the **gross** deficit,``Σ max(8.0 - score, 0) * nloc`` over files below 8.0. This is thedenominator ``share_of_repo_gap_pct`` uses: it is positive whenever anyfile is below target (unlike the net gap), so a share is meaningful even- when the average is already healthy, and per-file shares sum to exactly+ when the average is already at target, and per-file shares sum to exactly100% by construction. The net gap is not used there precisely because- healthy files cushion it — one large low file could then read as closing+ above-target files cushion it — one large low file could then read as closingmore than the whole remaining gap (issue #1437).Pure over the metrics in hand."""total_nloc = sum(max(m.nloc, 1) for m in metrics)weighted_sum = sum(m.score * max(m.nloc, 1) for m in metrics)- net_gap = HEALTHY_MIN * total_nloc - weighted_sum+ net_gap = TARGET_SCORE * total_nloc - weighted_sumbelow = sorted((- max(HEALTHY_MIN - m.score, 0.0) * max(m.nloc, 1)+ max(TARGET_SCORE - m.score, 0.0) * max(m.nloc, 1)for m in metrics- if m.score < HEALTHY_MIN+ if m.score < TARGET_SCORE),reverse=True,)gross_gap = sum(below)if not below:return {- "target_score": HEALTHY_MIN,+ "target_score": TARGET_SCORE,"weighted_gap_points": 0,"weighted_gross_gap_points": 0,"files_below_target": 0,@@ -1315,12 +1353,12 @@ def _gap_analysis(metrics: list[HealthFileMetric]) -> dict[str, Any]:return len(below)# ``files_to_reach_target`` needs the net gap to mean "the headline crosses- # 8.0". When the net gap is <= 0 (average already healthy) there is nothing+ # 8.0". When the net gap is <= 0 (average already at target) there is nothing# to reach, so those fields are 0 — but the gross gap is still reported# because per-file shares are meaningful whenever any file is below target.reachable = max(net_gap, 0)return {- "target_score": HEALTHY_MIN,+ "target_score": TARGET_SCORE,# Net weighted points the average must recover to reach 8.0."weighted_gap_points": round(max(net_gap, 0)),# Gross deficit of all below-target files: the share_of_repo_gap_pct@@ -1498,35 +1536,37 @@ async def get_health(performance_confidence: str | None = None,performance_sort: str | None = None,scope: str = DEFAULT_SCOPE,+ counts: str = DEFAULT_COUNTS,) -> dict:"""Code-health scores and findings from stored analysis.No ``targets`` returns a dashboard; targets return ranked files and findings.- Never recomputes health: commit changes, then run ``repowise update``.+ Never recomputes health: commit, then run ``repowise update``.Every block and accepted value: docs/agent/MCP_TOOLS.md.Args:- targets: file paths or ``module:<name>``. Empty means dashboard;+ targets: file paths or ``module:<name>``; empty means dashboard,unmatched ones land in ``unresolved``.- include: ``biomarkers`` | ``refactoring`` | ``trend`` | ``coverage`` |- ``accuracy`` | ``signals`` | ``churn_complexity``, or a dimension.+ include: ``biomarkers``|``refactoring``|``trend``|``coverage``|+ ``accuracy``|``signals``|``churn_complexity``, or a dimension;``performance`` and ``refactoring`` add their queues.- only: keys to keep; identity, counts and recovery survive.- ``biomarkers``, ``accuracy`` and ``refactoring`` alias their block- key. ``performance``, ``defect`` and ``maintainability`` do not:- they filter rows and land in ``unknown_only_keys``.+ only: keys to keep; identity, totals and recovery survive.+ ``biomarkers``/``accuracy``/``refactoring`` alias their block key;+ ``performance``/``defect``/``maintainability`` do not: they filter+ rows and land in ``unknown_only_keys``.repo: usually omitted.limit: max rows per ranked list, ``0`` for none.cursor: zero-based offset into a ranked list.- finding_id / plan_id: stable ``id`` from a finding or a plan.- opportunity_id: ``perf...`` or ``refop...`` id: the unit, its steps or- plan, and evidence paged by ``only=["*_evidence"]``.- refactoring_view: ``diversified`` (default) | ``canonical`` |- ``file_spread``; _type / _confidence / _effort filter.- performance_view / _context / _boundary / _confidence / _sort: queue+ finding_id/plan_id: stable ``id`` from a finding or plan.+ opportunity_id: ``perf...``/``refop...``: the unit, its steps or+ plan, evidence paged by ``only=["*_evidence"]``.+ refactoring_view: ``diversified`` (default)|``canonical``|+ ``file_spread``; _type/_confidence/_effort filter.+ performance_view/_context/_boundary/_confidence/_sort: queueprojection and filters; the facets list them.- scope: ``all`` (default) | ``production``. Narrowing drops test files- from every figure; tests score higher, so it lowers them.+ scope / counts: default ``all``/``everything``. ``production`` drops+ test files, which score higher; ``code_shape`` drops the+ git-derived half of the score and its findings."""started = perf_counter()@@ -1534,7 +1574,7 @@ async def get_health(finding_id=finding_id, plan_id=plan_id, opportunity_id=opportunity_id)if conflict is not None:- return conflict+ return _note_inapplicable_controls(conflict, scope, counts)# ``0`` means none, matching the ``module_limit`` convention on the REST# coverage route. It used to clamp up to 1, so the documented way to ask for# "the totals, none of the rows" silently returned a row.@@ -1703,28 +1743,36 @@ async def get_health(),}await _attach_repository_analysis_meta(session, repository, result["_meta"])- return result+ return _note_inapplicable_controls(result, scope, counts)if opportunity_id and opportunity_id.startswith(_REFACTORING_OPPORTUNITY_PREFIX):- return await _refactoring_detail_response(- session,- repository,- reference_repository,- opportunity_id,- evidence_only=only_set == {"refactoring_evidence"},- limit=limit,- cursor=cursor,+ return _note_inapplicable_controls(+ await _refactoring_detail_response(+ session,+ repository,+ reference_repository,+ opportunity_id,+ evidence_only=only_set == {"refactoring_evidence"},+ limit=limit,+ cursor=cursor,+ ),+ scope,+ counts,)if opportunity_id:- return await _performance_detail_response(- session,- repository,- reference_repository,- opportunity_id,- evidence_only=only_set == {"performance_evidence"},- limit=limit,- cursor=cursor,+ return _note_inapplicable_controls(+ await _performance_detail_response(+ session,+ repository,+ reference_repository,+ opportunity_id,+ evidence_only=only_set == {"performance_evidence"},+ limit=limit,+ cursor=cursor,+ ),+ scope,+ counts,)if plan_id:@@ -1757,7 +1805,7 @@ async def get_health("opportunity; a demoted clone is supporting evidence, not work.")await _attach_repository_analysis_meta(session, repository, result["_meta"])- return result+ return _note_inapplicable_controls(result, scope, counts)all_metrics_q = select(HealthFileMetric).where(HealthFileMetric.repository_id == repository.id@@ -1782,11 +1830,28 @@ async def get_health(all_metrics = [m for m in all_metrics if not m.is_test]scope_paths = {m.file_path for m in all_metrics}+ # Composes with the scope: a re-read off the stored structure/history+ # split, not a rescore. Findings narrow by origin, not by path, so a row+ # it cannot read lands in ``unscored_files`` with its findings intact.+ reported_counts = parse_counts(counts)+ code_shape = reported_counts == "code_shape"+ unscored_files = 0+ unscored_paths: set[str] = set()+ if code_shape:+ before = {m.file_path for m in all_metrics}+ all_metrics, unscored_files = project_counts(counts, all_metrics)+ unscored_paths = before - {m.file_path for m in all_metrics}+def in_scope_rows(rows: list, attr: str = "file_path") -> list:rows = filter_rows_by_attr(rows, attr, exclude_spec)if scope_paths is None:return rowsreturn [r for r in rows if getattr(r, attr, None) in scope_paths]++ def in_counts_findings(rows: list) -> list:+ """A history finding cannot explain a score its half was taken out+ of, so it is not part of the code-shape reading."""+ return split_by_origin(rows)[0] if code_shape else rowsmatched_modules: set[str] = set()if module_targets:module_set = set(module_targets)@@ -1845,7 +1910,7 @@ async def get_health(test_finding_rows: list[Any] = []test_findings_total = 0if scoped:- finding_rows = in_scope_rows(+ finding_rows = in_counts_findings(in_scope_rows(list((await session.execute(@@ -1859,7 +1924,7 @@ async def get_health(.all()),"file_path",- )+ ))lead_rows: list[Any] = finding_rowsemitted = _rank_emitted([f for f in finding_rows if _in_dimensions(f, ranked_dimensions)]@@ -1911,7 +1976,7 @@ async def get_health(# ``lead_rows`` stays the unfiltered open set: it feeds the per-file# leads and the performance KPI, neither of which should change# because the caller asked to *see* one dimension.- lead_rows = in_scope_rows(lite_rows)+ lead_rows = in_counts_findings(in_scope_rows(lite_rows))emitted = _rank_emitted([r for r in lead_rows if _in_dimensions(r, ranked_dimensions)])@@ -2025,6 +2090,10 @@ async def get_health(# ignores every finding whose type is not ``prior_defect``. Selecting# those directly keeps the honest denominator without re-reading the# ~10k rows the narrow pass above exists to avoid.+ # Not routed through ``in_counts_findings``: ``prior_defect`` is the+ # ground truth this block scores the number against, not a deduction+ # the reading includes. Dropping it under ``code_shape`` would leave+ # the accuracy block with no labels to be accurate about.accuracy_rows: list[Any] = []if "accuracy" in include_set and not scoped:accuracy_rows = in_scope_rows(@@ -2197,12 +2266,12 @@ async def get_health(else:# Leverage view: files ranked by NLOC-weighted deficit (how much# each drags the headline), not by raw score. Distinct from- # worst_files — a big warning-band file outranks a tiny alert-band+ # worst_files — a big mid-band file outranks a tiny at-risk# one here because fixing it moves the average far more. Computed# before the leads so the set of printed files is known.by_leverage = sorted(- (m for m in all_metrics if m.score < HEALTHY_MIN),- key=lambda m: max(HEALTHY_MIN - m.score, 0.0) * max(m.nloc, 1),+ (m for m in all_metrics if m.score < TARGET_SCORE),+ key=lambda m: max(TARGET_SCORE - m.score, 0.0) * max(m.nloc, 1),reverse=True,)printed = {m.file_path for m in metric_rows[:limit]}@@ -2301,6 +2370,11 @@ async def get_health("findings",),"findings_total": findings_total,+ # Which reading these scores are on, last so the identity keys keep+ # the head of the payload. Without it a projected score is+ # indistinguishable from the calibrated one.+ "scope": reported_scope,+ "counts": reported_counts,}unresolved = _unresolved_targets(file_targets=file_targets,@@ -2308,6 +2382,7 @@ async def get_health(matched_modules=matched_modules,resolved_paths={m.file_path for m in metric_rows},excluded_paths=excluded_paths,+ unscored_paths=unscored_paths,repo_root=ctx.path,)if unresolved:@@ -2401,9 +2476,11 @@ async def get_health(),"mode": "dashboard","scope": reported_scope,+ "counts": reported_counts,+ "unscored_files": unscored_files,"kpis": kpis,"distribution": health_distribution(all_metrics),- # Where the gap to Healthy concentrates — the "few files, not the+ # Where the gap to the target concentrates — the "few files, not the# long tail" reframe that turns a repo-wide number into a short list."gap_analysis": gap,"worst_files": bounded([@@ -2424,7 +2501,7 @@ async def get_health(# gap does, and it is the unit ``directive`` already speaks. The# denominator is the gross deficit of all below-target files, so a# share is bounded by 100% and the rows sum to 100% by construction- # — the net gap would let healthy files cushion the total and push a+ # — the net gap would let above-target files cushion the total and push a# single large file over 100% (issue #1437)."high_leverage_files": bounded([{@@ -2434,7 +2511,7 @@ async def get_health("share_of_repo_gap_pct": (round(100.0- * max(HEALTHY_MIN - m.score, 0.0)+ * max(TARGET_SCORE - m.score, 0.0)* max(m.nloc, 1)/ gap["weighted_gross_gap_points"],1,@@ -2828,6 +2905,32 @@ async def get_health(result["unknown_include_keys"] = unknown_include_keys_stamp_nested_collections(result)+ # A misspelled control falls back to the default, answering a different+ # question under the name the caller asked for. The routes and the CLI+ # reject outright; MCP cannot, so it names the value it dropped.+ rejected = {+ name: raw+ for name, raw, resolved in (+ ("scope", scope, reported_scope),+ ("counts", counts, reported_counts),+ )+ if raw is not None and raw != resolved+ }+ if rejected:+ result["ignored_arguments"] = {**result.get("ignored_arguments", {}), **rejected}++ # Snapshots and the two ranked queues have no stored split to re-read, so+ # they stay calibrated. Named, or a projected headline reads as if+ # everything beside it were projected too.+ if reported_counts == "code_shape":+ unprojected = [+ key+ for key in ("trend", "trends", "refactoring_opportunities", "performance_opportunities")+ if key in result+ ]+ if unprojected:+ result["counts_not_applied_to"] = unprojected+# Projection. ``include`` could only ever add blocks, so asking for one# extra block re-shipped the whole dashboard with it; ``only`` is the# subtract half. Applied last so it can drop anything above, and ``mode`` /@@ -2878,6 +2981,13 @@ async def get_health()})+ # Which reading the kept numbers are on, but only once it is not the+ # default: unconditionally would add three empty keys to every other+ # projection.+ if reported_scope != DEFAULT_SCOPE:+ keep |= {"scope"}+ if reported_counts != DEFAULT_COUNTS:+ keep |= {"counts", "unscored_files", "counts_not_applied_to"}if "refactoring_plans" in only_set:keep |= {"refactoring_plans_status",diff --git a/packages/server/src/repowise/server/routers/code_health/badge.py b/packages/server/src/repowise/server/routers/code_health/badge.pyindex 13ea25aed..ee8d79e96 100644--- a/packages/server/src/repowise/server/routers/code_health/badge.py+++ b/packages/server/src/repowise/server/routers/code_health/badge.py@@ -5,25 +5,21 @@ from __future__ import annotationsfrom fastapi import Depends, HTTPException, Responsefrom sqlalchemy.ext.asyncio import AsyncSession-from repowise.core.analysis.health.grading import band_for+from repowise.core.analysis.health.grading import BAND_BADGE_COLOR, band_forfrom repowise.core.persistence import crudfrom repowise.server.deps import get_db_sessionfrom repowise.server.schemas import HealthBadgeResponsefrom ._router import router-# 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",-}+# Hexes for the self-rendered SVG, so it matches the JSON endpoint's named+# colors without a round-trip to img.shields.io. The names themselves come+# from the shared band vocabulary.+_UNKNOWN_COLOR = "lightgrey"_BADGE_COLOR_HEX: dict[str, str] = {"brightgreen": "#4c1","yellow": "#dfb317",+ "orange": "#fe7d37","red": "#e05d44","lightgrey": "#9f9f9f",}@@ -32,9 +28,9 @@ _BADGE_COLOR_HEX: dict[str, str] = {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"+ return "health", "no data", _UNKNOWN_COLOR, "unknown"band = band_for(float(average_health))- return "health", f"{average_health:.1f}/10", _BADGE_COLOR_NAME[band], band+ return "health", f"{average_health:.1f}/10", BAND_BADGE_COLOR[band], banddef _render_badge_svg(label: str, message: str, color_name: str) -> str:diff --git a/packages/types/__tests__/health.test.ts b/packages/types/__tests__/health.test.tsindex 54ff5c53f..691d5f38b 100644--- a/packages/types/__tests__/health.test.ts+++ b/packages/types/__tests__/health.test.ts@@ -4,24 +4,39 @@* 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.+ * fails CI. The bands are absolute, so a score means the same thing behind a+ * firewall as it does against a public corpus.*/import { describe, expect, it } from "vitest";import {- ALERT_MAX,- HEALTHY_MIN,+ EXCELLENT_MIN,+ FAIR_MIN,+ GOOD_MIN,+ HEALTH_BAND_LABEL,+ HEALTH_BAND_ORDER,+ HEALTH_BAND_RANGE_LABEL,HEALTH_DIMENSIONS,+ NEEDS_WORK_MIN,PERF_BOUNDARY_LABEL,bandForScore,} from "../src/health.js";import { C4_IO_KINDS } from "../src/external-systems.js";describe("health band cutoffs", () => {- it("are the frozen defect-backed values", () => {- expect(ALERT_MAX).toBe(4.0);- expect(HEALTHY_MIN).toBe(8.0);+ it("are the frozen values core mirrors", () => {+ expect(EXCELLENT_MIN).toBe(8.5);+ expect(GOOD_MIN).toBe(7.0);+ expect(FAIR_MIN).toBe(5.5);+ expect(NEEDS_WORK_MIN).toBe(4.0);+ });++ it("give every band a label and a range, worst-first", () => {+ expect(HEALTH_BAND_ORDER).toEqual(["at_risk", "needs_work", "fair", "good", "excellent"]);+ for (const band of HEALTH_BAND_ORDER) {+ expect(HEALTH_BAND_LABEL[band]).toBeTruthy();+ expect(HEALTH_BAND_RANGE_LABEL[band]).toBeTruthy();+ }});});@@ -44,12 +59,15 @@ describe("health dimensions", () => {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");+ expect(bandForScore(10.0)).toBe("excellent");+ expect(bandForScore(8.5)).toBe("excellent"); // each cutoff belongs to the band above+ expect(bandForScore(8.49)).toBe("good");+ expect(bandForScore(7.0)).toBe("good");+ expect(bandForScore(6.99)).toBe("fair");+ expect(bandForScore(5.5)).toBe("fair");+ expect(bandForScore(5.49)).toBe("needs_work");+ expect(bandForScore(4.0)).toBe("needs_work");+ expect(bandForScore(3.99)).toBe("at_risk");+ expect(bandForScore(1.0)).toBe("at_risk");});});diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsindex 3fbb26b19..d53328bc0 100644--- a/packages/types/src/health.ts+++ b/packages/types/src/health.ts@@ -10,9 +10,9 @@** 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`.+ * kept in sync by a parity test (`__tests__/health.test.ts` here,+ * `tests/unit/health/test_grading.py` in core). Do not hardcode band cutoffs+ * anywhere else — derive from these consts or read the API `band`.*/import type { C4IoKind } from "./external-systems.js";@@ -93,22 +93,41 @@ export const PERF_BOUNDARY_LABEL: Record<C4IoKind, string> = {* ------------------------------------------------------------------ *//**- * 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`).+ * The five absolute health bands: a score means the same thing behind a+ * firewall as against a public corpus. Excellent and Good share one green and+ * are told apart by the word. Mirror of `grading.py`, parity-tested both ways.*/-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 type HealthBand = "excellent" | "good" | "fair" | "needs_work" | "at_risk";++export const EXCELLENT_MIN = 8.5;+export const GOOD_MIN = 7.0;+export const FAIR_MIN = 5.5;+export const NEEDS_WORK_MIN = 4.0;++/** Worst-first, matching how the surfaces list files. */+export const HEALTH_BAND_ORDER: readonly HealthBand[] = [+ "at_risk",+ "needs_work",+ "fair",+ "good",+ "excellent",+] as const;export const HEALTH_BAND_LABEL: Record<HealthBand, string> = {- healthy: "Healthy",- warning: "Warning",- alert: "Alert",+ excellent: "Excellent",+ good: "Good",+ fair: "Fair",+ needs_work: "Needs work",+ at_risk: "At risk",+};++/** The range each band covers, for keys and legends that show the boundaries. */+export const HEALTH_BAND_RANGE_LABEL: Record<HealthBand, string> = {+ excellent: "8.5+",+ good: "7.0 to 8.5",+ fair: "5.5 to 7.0",+ needs_work: "4.0 to 5.5",+ at_risk: "under 4.0",};/**@@ -116,9 +135,11 @@ export const HEALTH_BAND_LABEL: Record<HealthBand, string> = {* 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";+ if (score >= EXCELLENT_MIN) return "excellent";+ if (score >= GOOD_MIN) return "good";+ if (score >= FAIR_MIN) return "fair";+ if (score >= NEEDS_WORK_MIN) return "needs_work";+ return "at_risk";}export interface HealthBandShare {@@ -131,7 +152,7 @@ export interface HealthBandShare {}/**- * NLOC-weighted distribution of files across the 3 bands. The repo-level+ * NLOC-weighted distribution of files across the bands. The repo-level* "health distribution" surfaced on the dashboard + badge.*/export interface HealthDistribution {@@ -561,7 +582,7 @@ export interface HealthOverviewSummary {export interface HealthOverviewResponse {summary: HealthOverviewSummary;- /** NLOC-weighted file distribution across the 3 bands. */+ /** NLOC-weighted file distribution across the health bands. */distribution?: HealthDistribution | null;defect_accuracy?: DefectAccuracy | null;files: HealthFileMetric[];diff --git a/packages/ui/COMPONENT_CONTRACTS.md b/packages/ui/COMPONENT_CONTRACTS.mdindex 9b32a9653..ff2032c24 100644--- a/packages/ui/COMPONENT_CONTRACTS.md+++ b/packages/ui/COMPONENT_CONTRACTS.md@@ -925,10 +925,9 @@ Two consequences a host must honour:click. A tab with nothing behind it is left out of that list ratherthan buying a trip to be shown the same empty state.-Bands come from `bandForScore` (`@repowise-dev/types/health`), never from-`scoreBadgeClass` — that is a four-step presentation ramp and this page-sits one click from the treemap and the health map, which both paint the-canonical three.+Bands come from `bandForScore` (`@repowise-dev/types/health`), never from a+threshold of the page's own — this page sits one click from the treemap and+the health map, and all three paint the same five bands.**The doors, and who owns each end.** The page had thirty surfaces linkinginto it and almost nothing linking out, and the docs surface — the one thatdiff --git a/packages/ui/README.md b/packages/ui/README.mdindex 2ab6a4161..7fe9f6edf 100644--- a/packages/ui/README.md+++ b/packages/ui/README.md@@ -80,14 +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 `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`).+- Score colors come from `health/tokens.ts`, on the one band vocabulary in+ `@repowise-dev/types/health` (`HealthBand` — Excellent `≥8.5` / Good+ `≥7.0` / Fair `≥5.5` / Needs work `≥4.0` / At risk below). Excellent and+ Good share the green; the word carries the difference. Use+ `healthBandSoftBadgeClass` / `healthBandTextColor` when you already have a+ band, and `scoreBadgeClass` / `scoreTextColor` / `healthInk` when you have+ a score. All of them resolve to the semantic tokens+ (`--color-error/warning/caution/success`).## Peer depsdiff --git a/packages/ui/__tests__/c4/export.test.ts b/packages/ui/__tests__/c4/export.test.tsindex 2c8c5af2f..733cc3394 100644--- a/packages/ui/__tests__/c4/export.test.ts+++ b/packages/ui/__tests__/c4/export.test.ts@@ -29,7 +29,7 @@ function makeArchFileNode(id: string, nodeType: string, overrides?: Partial<Node};}-function makeLayerClusterNode(id: string): Node {+function makeLayerClusterNode(id: string, healthScore = 85): Node {return {id,type: "layerCluster",@@ -39,7 +39,7 @@ function makeLayerClusterNode(id: string): Node {name: "API Layer",description: "Handles requests",file_count: 10,- health_score: 85,+ health_score: healthScore,},},};@@ -195,6 +195,15 @@ describe("SVG export - new node types", () => {expect(svg).toContain('stroke-dasharray="8 5"'); // dashed ghost boundary});+ it("paints a layer's health on the same bands the canvas does", () => {+ // The exporter used to collapse everything between At risk and Good onto+ // one amber, so a Fair layer left the screen gold and arrived amber in the+ // SVG of that screen. 62 is Fair; 88 and 30 bracket it.+ expect(buildC4Svg([makeLayerClusterNode("fair", 62)], [])).toContain("#a8821f");+ expect(buildC4Svg([makeLayerClusterNode("good", 88)], [])).toContain("#1d8155");+ expect(buildC4Svg([makeLayerClusterNode("bad", 30)], [])).toContain("#b23a2e");+ });+it("test_svg_export_entry_accent: entry points render the ember gradient", () => {const entry = makeArchFileNode("e1", "file");(entry.data as { node: { is_entry_point: boolean } }).node.is_entry_point = true;diff --git a/packages/ui/__tests__/files/file-page-header.test.tsx b/packages/ui/__tests__/files/file-page-header.test.tsxindex 687f82ffe..f9ff74d0a 100644--- a/packages/ui/__tests__/files/file-page-header.test.tsx+++ b/packages/ui/__tests__/files/file-page-header.test.tsx@@ -35,10 +35,9 @@ function metric(score: number) {}describe("FilePageHeader health band", () => {- it("bands a 6.9 as Warning, the way every other surface does", () => {- // The trap this replaced: `scoreBadgeClass` is a four-step presentation- // ramp that calls 6.9 "fair" and paints it caution, while the treemap and- // the map that link here paint `bandForScore`. Same file, two readings.+ it("bands a 6.9 as Fair, the way every other surface does", () => {+ // The trap this replaced: a presentation ramp of its own, so the same file+ // read one way here and another on the treemap that links to it.render(<FilePageHeaderdata={makeData({ health: { ...makeData().health, metric: metric(6.9) } })}@@ -46,17 +45,17 @@ describe("FilePageHeader health band", () => {/>,);expect(screen.getByText("6.9")).toBeTruthy();- expect(screen.getByText("Warning")).toBeTruthy();+ expect(screen.getByText("Fair")).toBeTruthy();});- it("bands an 8.0 as Healthy", () => {+ it("bands an 8.0 as Good", () => {render(<FilePageHeaderdata={makeData({ health: { ...makeData().health, metric: metric(8.0) } })}linkPrefix="/repos/r1"/>,);- expect(screen.getByText("Healthy")).toBeTruthy();+ expect(screen.getByText("Good")).toBeTruthy();});it("renders the path without truncating it", () => {diff --git a/packages/ui/__tests__/files/files-index.test.tsx b/packages/ui/__tests__/files/files-index.test.tsxindex 49326fd99..e48c32b21 100644--- a/packages/ui/__tests__/files/files-index.test.tsx+++ b/packages/ui/__tests__/files/files-index.test.tsx@@ -87,18 +87,21 @@ describe("FilesIndex", () => {expect(headings.map((h) => h.textContent)).toEqual(["Repository map", "Every file"]);});- it("reports the healthy share against the number that carries a score", () => {+ it("reports the good-or-better share against the number that carries a score", () => {renderIndex([row({ file_path: "a.ts", defect_score: 9 }),row({ file_path: "b.ts", defect_score: 7.5 }),+ row({ file_path: "d.ts", defect_score: 6.9 }),row({ file_path: "c.ts", defect_score: null }),]);- // 2 of 3 files are scored, and only the 9 is Healthy — 7.5 sits in the- // Warning band. A local `>= 7` threshold would call this 100%, disagreeing- // with the amber tile the map paints for the same file.- expect(screen.getByText(/50%/)).toBeInTheDocument();- expect(screen.getByText(/carrying a health score are healthy/)).toBeInTheDocument();+ // 3 of 4 files are scored and 2 of those are Good or better. The 6.9 is the+ // row that discriminates: it is Fair, and any surface bucketing it as good+ // would print 100% here while the map paints its tile gold.+ expect(screen.getByText(/67%/)).toBeInTheDocument();+ expect(+ screen.getByText(/carrying a health score are Good or better/),+ ).toBeInTheDocument();});it("names the active sort rather than claiming a fixed order", () => {@@ -144,14 +147,14 @@ describe("FilesTreemap key row", () => {it("names every health band, and the thresholds that define them", () => {renderIndex([row({ defect_score: 9 })]);- // All three even though this level only carries one: a fixed scale showing- // two steps reads as a scale that has two.- for (const band of ["Healthy", "Warning", "Alert"]) {+ // All of them even though this level only carries one: a fixed scale+ // showing two steps reads as a scale that has two.+ for (const band of ["Excellent", "Good", "Fair", "Needs work", "At risk"]) {expect(screen.getByText(band)).toBeInTheDocument();}- expect(screen.getByText("8+")).toBeInTheDocument();- expect(screen.getByText("4–8")).toBeInTheDocument();- expect(screen.getByText("< 4")).toBeInTheDocument();+ expect(screen.getByText("8.5+")).toBeInTheDocument();+ expect(screen.getByText("7.0 to 8.5")).toBeInTheDocument();+ expect(screen.getByText("under 4.0")).toBeInTheDocument();});it("marks unscored tiles only when there are some", () => {@@ -175,7 +178,7 @@ describe("FilesTreemap key row", () => {expect(within(key).getByText("typescript")).toBeInTheDocument();expect(within(key).getByText("python")).toBeInTheDocument();// Health bands belong to the other mode and must not linger.- expect(within(key).queryByText("Healthy")).not.toBeInTheDocument();+ expect(within(key).queryByText("Excellent")).not.toBeInTheDocument();});it("says what area means, and it follows the control", () => {diff --git a/packages/ui/__tests__/graph/graph-community-panel.test.tsx b/packages/ui/__tests__/graph/graph-community-panel.test.tsxindex bdac5ceb0..b2a746183 100644--- a/packages/ui/__tests__/graph/graph-community-panel.test.tsx+++ b/packages/ui/__tests__/graph/graph-community-panel.test.tsx@@ -156,9 +156,8 @@ describe("GraphCommunityPanel state", () => {/>,);expect(screen.getByText("5.2")).toBeTruthy();- // Five-band vocabulary, shared with the Code Health lede and the file- // health drawer, so one score never gets two sets of words.- expect(screen.getByText("Fair")).toBeTruthy();+ // The shared band vocabulary, so one score never gets two sets of words.+ expect(screen.getByText("Needs work")).toBeTruthy();// The mean is over the scored members, and says so rather than implying it// measured all three.expect(screen.getByText(/2 of 3 files that are\s+scored/)).toBeTruthy();diff --git a/packages/ui/__tests__/health/code-health-map.test.tsx b/packages/ui/__tests__/health/code-health-map.test.tsxindex 6ebaf5adc..ee849c727 100644--- a/packages/ui/__tests__/health/code-health-map.test.tsx+++ b/packages/ui/__tests__/health/code-health-map.test.tsx@@ -138,10 +138,10 @@ describe("CodeHealthMap", () => {const { getByText } = render(<CodeHealthMap files={[f("a.py", 30, "core")]} />);expect(getByText("Code health")).toBeInTheDocument();expect(getByText(/galaxy = module/i)).toBeInTheDocument();- // The four-step ramp names score ranges. Band words would claim a- // vocabulary the three-band scale beside it does not share.- expect(getByText("8 and above")).toBeInTheDocument();- expect(getByText("4 to 6")).toBeInTheDocument();+ // The legend names the band and the range it covers, on the same+ // vocabulary every other mark on the page uses.+ expect(getByText("Excellent · 8.5+")).toBeInTheDocument();+ expect(getByText("Needs work · 4.0 to 5.5")).toBeInTheDocument();});it("renders the coverage legend under the coverage lens", () => {@@ -183,7 +183,7 @@ describe("CodeHealthMap", () => {const { container } = render(<CodeHealthMap files={files} overlay="performance" />);const fillOf = (p: string) =>container.querySelector(`circle[data-path="${p}"]`)?.getAttribute("fill");- expect(fillOf("core/planned.py")).toBe("var(--color-node-critical)");+ expect(fillOf("core/planned.py")).toBe("var(--color-node-at-risk)");expect(fillOf("core/one.py")).toBe("var(--color-node-fair)");expect(fillOf("core/clean.py")).toBe(NEUTRAL_FILL);// Stored plan earns no mark of its own. It is said in words instead.diff --git a/packages/ui/__tests__/health/distribution-badge.test.tsx b/packages/ui/__tests__/health/distribution-badge.test.tsxindex d749700ed..c19375a75 100644--- a/packages/ui/__tests__/health/distribution-badge.test.tsx+++ b/packages/ui/__tests__/health/distribution-badge.test.tsx@@ -8,18 +8,22 @@ 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 },+ excellent: { files: 4, nloc: 500, pct: 50 },+ good: { files: 2, nloc: 200, pct: 20 },+ fair: { files: 2, nloc: 150, pct: 15 },+ needs_work: { files: 1, nloc: 50, pct: 5 },+ at_risk: { 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();+ expect(screen.getByText(/50% excellent/)).toBeInTheDocument();+ expect(screen.getByText(/20% good/)).toBeInTheDocument();+ expect(screen.getByText(/15% fair/)).toBeInTheDocument();+ expect(screen.getByText(/5% needs work/)).toBeInTheDocument();+ expect(screen.getByText(/10% at risk/)).toBeInTheDocument();});it("shows an empty state when no files are analyzed", () => {@@ -27,14 +31,47 @@ describe("HealthDistributionBar", () => {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 },+ excellent: { files: 0, nloc: 0, pct: 0 },+ good: { files: 0, nloc: 0, pct: 0 },+ fair: { files: 0, nloc: 0, pct: 0 },+ needs_work: { files: 0, nloc: 0, pct: 0 },+ at_risk: { files: 0, nloc: 0, pct: 0 },},};render(<HealthDistributionBar distribution={empty} />);expect(screen.getByText("No files analyzed.")).toBeInTheDocument();});++ it("renders what a server predating the five bands sends, rather than throwing", () => {+ // The CLI/server and the app that reads it upgrade independently, so a+ // three-band payload is reachable. A missing band reads as absent.+ const partial = {+ total_files: 10,+ total_nloc: 1000,+ bands: { excellent: { files: 6, nloc: 700, pct: 70 } },+ } as unknown as HealthDistribution;+ render(<HealthDistributionBar distribution={partial} />);+ expect(screen.getByText(/70% excellent/)).toBeInTheDocument();+ expect(screen.getByText(/0% at risk/)).toBeInTheDocument();+ });++ it("does not report a repo with a three-band payload as empty in every band", () => {+ // A server predating the five bands sends correct totals under band names+ // this build does not know. Rendering that as five zeroes is a confident+ // false statement — "we analysed 128 files and none is in any band".+ const legacy = {+ total_files: 128,+ total_nloc: 9000,+ bands: {+ healthy: { files: 100, nloc: 7000, pct: 78 },+ warning: { files: 20, nloc: 1500, pct: 17 },+ alert: { files: 8, nloc: 500, pct: 5 },+ },+ } as unknown as HealthDistribution;+ render(<HealthDistributionBar distribution={legacy} />);+ expect(screen.getByText("No files analyzed.")).toBeInTheDocument();+ expect(screen.queryByText(/0% at risk/)).not.toBeInTheDocument();+ });});describe("HealthBadge", () => {@@ -42,7 +79,7 @@ describe("HealthBadge", () => {render(<HealthBadge score={2.5} />);const el = screen.getByText("2.5");expect(el).toBeInTheDocument();- // Alert band → error color class.+ // At risk band -> error color class.expect(el.className).toContain("color-error");});@@ -50,4 +87,13 @@ describe("HealthBadge", () => {const { container } = render(<HealthBadge score={null} />);expect(container).toBeEmptyDOMElement();});++ it("falls back to the score when the API sends a band this build does not know", () => {+ // A server predating the five bands sends "healthy". Indexing the colour+ // table with it yields undefined, and the pill renders unstyled.+ render(<HealthBadge score={2.5} band={"healthy" as never} />);+ const el = screen.getByText("2.5");+ expect(el.className).toContain("color-error");+ expect(el.className).not.toContain("undefined");+ });});diff --git a/packages/ui/__tests__/health/health-file-drawer.test.tsx b/packages/ui/__tests__/health/health-file-drawer.test.tsxindex 6e6bf786e..d53142251 100644--- a/packages/ui/__tests__/health/health-file-drawer.test.tsx+++ b/packages/ui/__tests__/health/health-file-drawer.test.tsx@@ -375,9 +375,9 @@ describe("HealthFileDrawer metrics", () => {it("leads with the file's own score and a canonical band", () => {render(<HealthFileDrawer open onClose={() => {}} metric={metric({ score: 1.0 })} />);expect(screen.getByText("1.0")).toBeInTheDocument();- // One of the three canonical bands, never a five-step word: this pill sits- // beside marks that all derive from `bandForScore`.- expect(screen.getByText("Alert")).toBeInTheDocument();+ // The shared band word, never a local one: this pill sits beside marks+ // that all derive from `bandForScore`.+ expect(screen.getByText("At risk")).toBeInTheDocument();});it("offers one link to the full page", () => {diff --git a/packages/ui/__tests__/health/map-lens.test.tsx b/packages/ui/__tests__/health/map-lens.test.tsxindex d7e35b59e..a09557561 100644--- a/packages/ui/__tests__/health/map-lens.test.tsx+++ b/packages/ui/__tests__/health/map-lens.test.tsx@@ -92,20 +92,22 @@ describe("burden encoding", () => {// own tones toward the page, putting colours on this field that exist// nowhere else in the product and going muddy against a dark root.const health = (score: number) => OVERLAY_SPECS.health.fill({ ...f("s.py", 1, null), score });- expect(at(1)).toBe(health(7)); // the ramp's fair step- expect(at(3)).toBe(health(5)); // poor- expect(at(9)).toBe(health(1)); // critical+ expect(at(1)).toBe(health(6)); // fair+ expect(at(3)).toBe(health(4.5)); // needs work+ expect(at(9)).toBe(health(1)); // at risk});- it("never paints a file the healthy green, whatever its state", () => {- // Green means healthy on this map and no performance verdict is that: a- // cleared file is one with no supported pattern in it, not one measured to- // be fast. So the lens uses three of the ramp's four bands.- const green = OVERLAY_SPECS.health.fill({ ...f("s.py", 1, null), score: 9 });+ it("never paints a file a green, whatever its state", () => {+ // Green means the code is fine on this map and no performance verdict is+ // that: a cleared file is one with no supported pattern in it, not one+ // measured to be fast. So the lens uses only the bands below green.+ const greens = [7, 9].map((score) =>+ OVERLAY_SPECS.health.fill({ ...f("s.py", 1, null), score }),+ );const fills = [0, 1, 3, 9, 40].map((n) =>performanceFill(f("a.py", 10, "core", { performance_opportunities: n })),);- expect(fills).not.toContain(green);+ for (const green of greens) expect(fills).not.toContain(green);});it("gives every file with no open cause the one neutral", () => {diff --git a/packages/ui/__tests__/overview/repo-rows.test.tsx b/packages/ui/__tests__/overview/repo-rows.test.tsxindex 8253f144a..9b8f49a50 100644--- a/packages/ui/__tests__/overview/repo-rows.test.tsx+++ b/packages/ui/__tests__/overview/repo-rows.test.tsx@@ -63,14 +63,14 @@ describe("RepoRows", () => {expect(screen.getByText("—")).toBeTruthy();});- it("bands the score on the same five-step ladder the repo pages use", () => {+ it("bands the score on the same ladder the repo pages use", () => {render(<RepoRowsrepos={[row({ id: "a", name: "alpha", health: 9.1 }),row({ id: "b", name: "beta", health: 7.4 }),- row({ id: "c", name: "gamma", health: 5.0 }),- row({ id: "d", name: "delta", health: 3.6 }),+ row({ id: "c", name: "gamma", health: 6.0 }),+ row({ id: "d", name: "delta", health: 4.5 }),row({ id: "e", name: "epsilon", health: 3.0 }),]}/>,@@ -80,16 +80,16 @@ describe("RepoRows", () => {expect(screen.getByText("Good")).toBeTruthy();expect(screen.getByText("Fair")).toBeTruthy();expect(screen.getByText("Needs work")).toBeTruthy();- expect(screen.getByText("Critical")).toBeTruthy();+ expect(screen.getByText("At risk")).toBeTruthy();});- // The bug this guards: 7.4 read amber "Warning" in the workspace list and- // green "Good" the moment you opened the same repo.+ // The bug this guards: 7.4 read amber in the workspace list and green the+ // moment you opened the same repo.it("reads a mid-seven score green, as the repo overview does", () => {render(<RepoRows repos={[row({ health: 7.4 })]} />);expect(screen.getByText("Good")).toBeTruthy();- expect(screen.queryByText("Warning")).toBeNull();+ expect(screen.queryByText("Fair")).toBeNull();});it("does not quote figures for a repo that was never indexed", () => {diff --git a/packages/ui/__tests__/zoom/node-signals.test.ts b/packages/ui/__tests__/zoom/node-signals.test.tsindex b99889c0d..d259584b8 100644--- a/packages/ui/__tests__/zoom/node-signals.test.ts+++ b/packages/ui/__tests__/zoom/node-signals.test.ts@@ -80,13 +80,11 @@ describe("healthBandLabel", () => {expect(healthBandLabel(null)).toBeNull();});- it("uses the canonical 3-band scale the card's dot paints on", () => {- expect(healthBandLabel(8.0)).toBe("Healthy");- expect(healthBandLabel(4.0)).toBe("Warning");- expect(healthBandLabel(3.9)).toBe("Alert");- });-- it("does not report a 6.9 as 'Good' while the dot beside it paints amber", () => {- expect(healthBandLabel(6.9)).toBe("Warning");+ it("uses the one band scale the card's dot paints on", () => {+ expect(healthBandLabel(9.0)).toBe("Excellent");+ expect(healthBandLabel(7.4)).toBe("Good");+ expect(healthBandLabel(6.0)).toBe("Fair");+ expect(healthBandLabel(4.0)).toBe("Needs work");+ expect(healthBandLabel(3.9)).toBe("At risk");});});diff --git a/packages/ui/src/c4/export/svg-exporter.ts b/packages/ui/src/c4/export/svg-exporter.tsindex d2b5c9175..56b3f0073 100644--- a/packages/ui/src/c4/export/svg-exporter.ts+++ b/packages/ui/src/c4/export/svg-exporter.ts@@ -10,6 +10,7 @@ import type { Edge, Node } from "@xyflow/react";import type { C4EdgeData, C4NodeData } from "../types";import { TONE_STYLES, type ToneName } from "../../graph-primitives/tone-styles";import { resolveToken } from "../../shared/use-theme-tokens";+import type { HealthBand } from "@repowise-dev/types/health";import { healthBand100 } from "../../health/tokens";/**@@ -35,12 +36,24 @@ function resolveInkPalette() {textPrimary: resolveToken("--color-text-primary", "#241b2c"),textSecondary: resolveToken("--color-text-secondary", "#5e5360"),success: resolveToken("--color-success", "#1d8155"),+ caution: resolveToken("--color-caution", "#a8821f"),warning: resolveToken("--color-warning", "#9a6614"),error: resolveToken("--color-error", "#b23a2e"),};}type InkPalette = ReturnType<typeof resolveInkPalette>;+/** The band inks of `THEME.health`, resolved for a standalone SVG. */+function bandInk(pal: InkPalette): Record<HealthBand, string> {+ return {+ excellent: pal.success,+ good: pal.success,+ fair: pal.caution,+ needs_work: pal.warning,+ at_risk: pal.error,+ };+}+interface ArchFileNodeData {node: {node_type: string;@@ -265,9 +278,7 @@ function renderArchNode(n: Node, pal: InkPalette): string {parts.push(`<text x="14" y="44" font-family="${FONT_FAMILY}" font-size="11" fill="${pal.inkText}" opacity="0.72">${subtitle}</text>`);parts.push(`<text x="14" y="${h - 12}" font-family="${MONO_FONT}" font-size="9" font-weight="600" letter-spacing="1" fill="${pal.inkText}" opacity="0.6">${isGroup ? "GROUP" : "LAYER"} · ${layer.file_count} FILES</text>`);if (layer.health_score !== null) {- const healthBand = healthBand100(layer.health_score);- const healthColor =- healthBand === "healthy" ? pal.success : healthBand === "warning" ? pal.warning : pal.error;+ const healthColor = bandInk(pal)[healthBand100(layer.health_score)];parts.push(`<text x="${w - 14}" y="${h - 12}" font-family="${FONT_FAMILY}" font-size="12" font-weight="600" fill="${healthColor}" text-anchor="end">${Math.round(layer.health_score)}</text>`);}parts.push(`</g>`);diff --git a/packages/ui/src/c4/health-score-ring.tsx b/packages/ui/src/c4/health-score-ring.tsxindex 9ca44ace9..49ea17ba0 100644--- a/packages/ui/src/c4/health-score-ring.tsx+++ b/packages/ui/src/c4/health-score-ring.tsx@@ -3,7 +3,8 @@import { useEffect, useState } from "react";import { motion } from "framer-motion";import { HelpCircle } from "lucide-react";-import { healthInk100 } from "../health/tokens";+import { HEALTH_BAND_LABEL } from "@repowise-dev/types/health";+import { healthBand100, healthInk100 } from "../health/tokens";export interface HealthScoreComponent {key: string;@@ -27,11 +28,7 @@ interface HealthScoreRingProps {}function getScoreLabel(score: number): string {- if (score >= 80) return "Excellent";- if (score >= 65) return "Good";- if (score >= 50) return "Fair";- if (score >= 30) return "Needs Work";- return "Critical";+ return HEALTH_BAND_LABEL[healthBand100(score)];}export function HealthScoreRing({ score, size = 160, components, note }: HealthScoreRingProps) {diff --git a/packages/ui/src/c4/nodes/LayerClusterNode.tsx b/packages/ui/src/c4/nodes/LayerClusterNode.tsxindex 8e10126ff..9a67db0b3 100644--- a/packages/ui/src/c4/nodes/LayerClusterNode.tsx+++ b/packages/ui/src/c4/nodes/LayerClusterNode.tsx@@ -2,6 +2,7 @@import { memo, useState } from "react";import type { NodeProps } from "@xyflow/react";+import { healthBand100 } from "../../health/tokens";import { InkNodeShell, type InkRole } from "./ink-node-shell";import { getKindIcon } from "./kind-icons";import { useArchitectureStore } from "../store/use-architecture-store";@@ -87,7 +88,7 @@ function LayerClusterNodeImpl(props: NodeProps) {style={{fontSize: 12,fontWeight: 600,- color: layer.health_score >= 80 ? THEME.health.good : layer.health_score >= 60 ? THEME.health.fair : THEME.health.poor,+ color: THEME.health[healthBand100(layer.health_score)],}}>{Math.round(layer.health_score)}diff --git a/packages/ui/src/c4/theme/theme-variables.ts b/packages/ui/src/c4/theme/theme-variables.tsindex b8ae041e6..b359390e8 100644--- a/packages/ui/src/c4/theme/theme-variables.ts+++ b/packages/ui/src/c4/theme/theme-variables.ts@@ -1,3 +1,5 @@+import type { HealthBand } from "@repowise-dev/types/health";+export const THEME = {canvas: {bg: "var(--color-bg-canvas)",@@ -48,12 +50,14 @@ export const THEME = {dead: "var(--color-text-muted)",},- /** Health-score buckets (≥80 / ≥60 / below). */+ /** Health band inks, on the shared 1-10 bands read at 0-100. */health: {+ excellent: "var(--color-success)",good: "var(--color-success)",- fair: "var(--color-warning)",- poor: "var(--color-error)",- },+ fair: "var(--color-caution)",+ needs_work: "var(--color-warning)",+ at_risk: "var(--color-error)",+ } satisfies Record<HealthBand, string>,edge: {imports: "var(--color-edge-imports)",diff --git a/packages/ui/src/coupling/coupling-graph.tsx b/packages/ui/src/coupling/coupling-graph.tsxindex 4833602e8..edf11c3a0 100644--- a/packages/ui/src/coupling/coupling-graph.tsx+++ b/packages/ui/src/coupling/coupling-graph.tsx@@ -6,9 +6,13 @@ import { curveBundle, lineRadial } from "d3-shape";// Value imports must come from the package root, not the `/coupling` subpath:// the vite/rollup base alias clobbers subpath value resolution. Type-only// subpath imports are fine (erased before resolution).-import { bandForScore } from "@repowise-dev/types";import type { CouplingEdge, CouplingNode } from "@repowise-dev/types/coupling";-import type { HealthBand } from "@repowise-dev/types/health";+import {+ HEALTH_BAND_LABEL,+ HEALTH_BAND_ORDER,+ HEALTH_BAND_RANGE_LABEL,+} from "@repowise-dev/types/health";+import { healthBandNodeFill, healthNodeFill } from "../health/tokens";import { disambiguateBasenames } from "../lib/format";import { isSamePair, pairHas, type CouplingPair } from "./claim";@@ -48,17 +52,12 @@ export interface CouplingGraphProps {size?: number;}-/* CSS-var ink per canonical health band (the 3-bucket currency). A file with- * no health metric resolves to neutral. SVG stroke/fill accept `var()`. */+/* A file with no health metric resolves to neutral. SVG stroke/fill accept+ * `var()`, so the band ink goes in raw. */const NEUTRAL_INK = "var(--color-text-tertiary)";-const BAND_INK: Record<HealthBand, string> = {- alert: "var(--color-error)",- warning: "var(--color-caution)",- healthy: "var(--color-success)",-};function inkFor(score: number | null): string {- return score == null ? NEUTRAL_INK : BAND_INK[bandForScore(score)];+ return score == null ? NEUTRAL_INK : healthNodeFill(score);}/** Shared empty neighbor set so the no-focus path allocates nothing. */@@ -478,15 +477,16 @@ export function CouplingGraph({{/* Legend */}<div className="mt-1 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-[var(--color-text-tertiary)]">- <span className="inline-flex items-center gap-1.5">- <span className="h-2 w-2 rounded-full bg-[var(--color-success)]" /> healthy- </span>- <span className="inline-flex items-center gap-1.5">- <span className="h-2 w-2 rounded-full bg-[var(--color-caution)]" /> warning- </span>- <span className="inline-flex items-center gap-1.5">- <span className="h-2 w-2 rounded-full bg-[var(--color-error)]" /> alert- </span>+ {HEALTH_BAND_ORDER.map((band) => (+ <span key={band} className="inline-flex items-center gap-1.5">+ <span+ className="h-2 w-2 rounded-full"+ style={{ backgroundColor: healthBandNodeFill(band) }}+ />{" "}+ {HEALTH_BAND_LABEL[band]}{" "}+ <span className="tabular-nums opacity-70">{HEALTH_BAND_RANGE_LABEL[band]}</span>+ </span>+ ))}{/* `min-w-0` so this can shrink and wrap rather than force the rowwider than the viewport; right-aligned only once there is room. */}<span className="min-w-0 basis-full sm:basis-auto sm:ml-auto">diff --git a/packages/ui/src/dashboard/health-overview-card.tsx b/packages/ui/src/dashboard/health-overview-card.tsxindex 400af6cff..0be9dff8b 100644--- a/packages/ui/src/dashboard/health-overview-card.tsx+++ b/packages/ui/src/dashboard/health-overview-card.tsx@@ -12,6 +12,7 @@ import {import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";import { fileEntityPath } from "../shared/entity/routes";import { truncatePath } from "../lib/format";+import { healthBand } from "../health/tokens";import { Sparkline } from "../health/sparkline";export interface HealthOverviewPoint {@@ -72,16 +73,6 @@ interface HealthOverviewCardProps {className?: string;}-/* 1–10 health bands — the moat metric, distinct from the 0–100 composite- shown in the header badge. */-function band(v: number): { color: string; label: string } {- if (v >= 8) return { color: "var(--color-success)", label: "Excellent" };- if (v >= 6.5) return { color: "var(--color-success)", label: "Good" };- if (v >= 5) return { color: "var(--color-caution)", label: "Fair" };- if (v >= 3.5) return { color: "var(--color-warning)", label: "Needs work" };- return { color: "var(--color-error)", label: "Critical" };-}-const SEVERITY_ORDER = ["critical", "high", "medium", "low"] as const;const SEVERITY_COLOR: Record<string, string> = {critical: "var(--color-error)",@@ -314,7 +305,7 @@ export function HealthOverviewCard({label="Average health"value={avg}delta={averageDelta}- band={avg != null ? band(avg) : null}+ band={avg != null ? healthBand(avg) : null}sparkline={avgSeries}/><MetricTile@@ -322,7 +313,7 @@ export function HealthOverviewCard({label="Hotspot health"value={hot}delta={hotspotDelta}- band={hot != null ? band(hot) : null}+ band={hot != null ? healthBand(hot) : null}sparkline={hotSeries}/></div>@@ -367,7 +358,7 @@ export function HealthOverviewCard({</span><spanclassName="shrink-0 text-xs font-bold tabular-nums"- style={{ color: band(data.worst_performer_score).color }}+ style={{ color: healthBand(data.worst_performer_score).color }}>{data.worst_performer_score.toFixed(1)}/10</span>@@ -412,7 +403,7 @@ function PillarStat({label: string;score: number | null;}) {- const b = score != null ? band(score) : null;+ const b = score != null ? healthBand(score) : null;return (<ahref={href}diff --git a/packages/ui/src/decisions/decision-status-mark.tsx b/packages/ui/src/decisions/decision-status-mark.tsxindex 648707dd1..d95fc018a 100644--- a/packages/ui/src/decisions/decision-status-mark.tsx+++ b/packages/ui/src/decisions/decision-status-mark.tsx@@ -16,7 +16,7 @@ const STATUS_COLOR: Record<DecisionStatus, string> = {/*** The status colour, for a bare dot in a list too narrow to carry the word.*- * Exported for the same reason `healthBandInk` is: a second surface that keeps+ * Exported for the same reason `healthBandColor` is: a second surface that keeps* its own copy of this table is a surface that can drift from it, and this one* already had — a local map in the VS Code decisions panel painted `proposed`* `--color-info` while this one painted it accent, so one status word had twodiff --git a/packages/ui/src/files/file-health-tab.tsx b/packages/ui/src/files/file-health-tab.tsxindex 0d6b015ac..bd7864876 100644--- a/packages/ui/src/files/file-health-tab.tsx+++ b/packages/ui/src/files/file-health-tab.tsx@@ -173,7 +173,7 @@ export function FileHealthTab({<>Code health is the calibrated number in the header. Maintainability and performanceare co-equal signals rather than a blend of it, and they are banded the same way —- healthy at 8 and above, alert below 4.{" "}+ Good from 7.0, at risk below 4.0.{" "}{metric.has_test_file? "This file has a paired test file.": "No paired test file was found for it."}diff --git a/packages/ui/src/files/file-page-header.tsx b/packages/ui/src/files/file-page-header.tsxindex ea0e7a99a..caddf83b1 100644--- a/packages/ui/src/files/file-page-header.tsx+++ b/packages/ui/src/files/file-page-header.tsx@@ -3,7 +3,7 @@ import { bandForScore, HEALTH_BAND_LABEL } from "@repowise-dev/types/health";import type { FileDetailResponse } from "@repowise-dev/types/files";import { PageLede } from "../shared/page-lede";import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";-import { healthBandInk, coverageTextColor } from "../health/tokens";+import { healthBandColor, coverageTextColor } from "../health/tokens";import { formatLOC, formatNumber } from "../lib/format";import { FileMarks } from "./file-marks";@@ -41,12 +41,6 @@ export interface FilePageHeaderProps {* the house `font-mono text-[10px] uppercase tracking-[0.12em]`, and whose* identity ran `text-lg` against `RepoIdentityHeader`'s `text-xl sm:text-2xl` —* a different face and two different sizes from every other surface.- *- * The score is banded by `bandForScore`, not `scoreBadgeClass`. The latter is a- * four-step presentation ramp whose own docstring says it is not a labelling- * scheme, and it disagrees with the bands the Files index, the treemap and the- * health map all paint: a 6.9 read one way here and another 200px away on the- * map that links to this page.*/export function FilePageHeader({data,@@ -93,11 +87,11 @@ export function FilePageHeader({<PageLedelabel="Code health"value={score.toFixed(1)}- valueColor={healthBandInk(bandForScore(score))}+ valueColor={healthBandColor(bandForScore(score))}unit="out of 10"band={{label: HEALTH_BAND_LABEL[bandForScore(score)],- color: healthBandInk(bandForScore(score)),+ color: healthBandColor(bandForScore(score)),}}layout="beside">diff --git a/packages/ui/src/files/files-index.tsx b/packages/ui/src/files/files-index.tsxindex 18b47d2db..f57140637 100644--- a/packages/ui/src/files/files-index.tsx+++ b/packages/ui/src/files/files-index.tsx@@ -105,16 +105,15 @@ export function FilesIndex({ files, languages, fileHref }: FilesIndexProps) {const kpis = useMemo(() => {let loc = 0;let scored = 0;- let healthy = 0;+ let good = 0;for (const f of files) {loc += f.loc ?? 0;if (f.defect_score != null) {scored++;- // `bandForScore`, not a local `>= 7`. The threshold here was 7 while- // every band this page paints starts Healthy at 8, so the strip was- // reporting a share of files as healthy that the map beside it was- // colouring amber.- if (bandForScore(f.defect_score) === "healthy") healthy++;+ // `bandForScore`, not a local threshold, so the strip and the map+ // beside it cannot report different shares of the same files.+ const band = bandForScore(f.defect_score);+ if (band === "good" || band === "excellent") good++;}}return {@@ -122,7 +121,7 @@ export function FilesIndex({ files, languages, fileHref }: FilesIndexProps) {loc,langCount: languages.length,scored,- healthyPct: scored > 0 ? Math.round((healthy / scored) * 100) : null,+ goodPct: scored > 0 ? Math.round((good / scored) * 100) : null,};}, [files, languages]);@@ -201,10 +200,10 @@ export function FilesIndex({ files, languages, fileHref }: FilesIndexProps) {<Fig>{formatNumber(kpis.total)}</Fig> files across <Fig>{formatLOC(kpis.loc)}</Fig>{" "}lines in <Fig>{kpis.langCount}</Fig> {kpis.langCount === 1 ? "language" : "languages"}.{" "}- {kpis.healthyPct != null ? (+ {kpis.goodPct != null ? (<>- <Fig>{kpis.healthyPct}%</Fig> of the <Fig>{formatNumber(kpis.scored)}</Fig>{" "}- carrying a health score are healthy.+ <Fig>{kpis.goodPct}%</Fig> of the <Fig>{formatNumber(kpis.scored)}</Fig>{" "}+ carrying a health score are Good or better.</>) : ("None carry a health score yet."diff --git a/packages/ui/src/files/files-table.tsx b/packages/ui/src/files/files-table.tsxindex 8d5830c42..e224c2ae6 100644--- a/packages/ui/src/files/files-table.tsx+++ b/packages/ui/src/files/files-table.tsx@@ -27,15 +27,7 @@ interface FilesTableProps {const ROW_HEIGHT = 44;const OVERSCAN = 8;-/**- * The health figure's colour, from the same function the treemap tiles use.- *- * This banded at 7 while `healthInk` bands at 8, so the 7.x files — and there- * are a lot of them — read green in this column, green in the map's tooltip and- * amber on the tile the tooltip was attached to. Three vocabularies for one- * number on one page. Match the mark you sit next to; every other mark on this- * page is on the canonical bands.- */+/** The health figure's colour, from the same function the treemap tiles use. */function scoreInk(score: number | null): string {return score == null ? "var(--color-text-tertiary)" : healthInk(score);}diff --git a/packages/ui/src/files/files-treemap.tsx b/packages/ui/src/files/files-treemap.tsxindex 13ae4e6cd..49b0c6465 100644--- a/packages/ui/src/files/files-treemap.tsx+++ b/packages/ui/src/files/files-treemap.tsx@@ -4,14 +4,13 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { hierarchy, treemap, treemapSquarify, type HierarchyRectangularNode } from "d3-hierarchy";import type { FileRow } from "@repowise-dev/types/files";import {- ALERT_MAX,bandForScore,HEALTH_BAND_LABEL,- HEALTHY_MIN,- type HealthBand,+ HEALTH_BAND_ORDER,+ HEALTH_BAND_RANGE_LABEL,} from "@repowise-dev/types/health";import { ChevronRight, FolderOpen } from "lucide-react";-import { healthBandInk, healthInk } from "../health/tokens";+import { healthBandNodeFill, healthNodeFill } from "../health/tokens";/*** `dependents` is the PageRank percentile over the import graph. It is named@@ -88,10 +87,10 @@ function langInk(rank: number | undefined): string {return `color-mix(in srgb, var(--color-accent-fill) ${Math.max(12, 70 - rank * 16)}%, var(--color-bg-inset))`;}-/** Health score (0-10) → the canonical band ink. Null reads neutral. */+/** Health score (0-10) → the canvas band fill. Null reads neutral. */function healthColor(score: number | null): string {if (score == null) return NO_SCORE_INK;- return healthInk(score);+ return healthNodeFill(score);}function sizeValue(row: FileRow, sizeBy: TreemapSize): number {@@ -201,18 +200,13 @@ function KeyRow({}) {const swatches = useMemo<KeySwatch[]>(() => {if (colorBy === "health") {- // All three bands always, even where one is absent from this level: a- // fixed scale showing two steps reads as a scale that has two.- const out: KeySwatch[] = (["healthy", "warning", "alert"] as HealthBand[]).map((band) => ({+ // Every band always, even where one is absent from this level: a fixed+ // scale showing two steps reads as a scale that has two.+ const out: KeySwatch[] = HEALTH_BAND_ORDER.map((band) => ({key: band,label: HEALTH_BAND_LABEL[band],- hint:- band === "healthy"- ? `${HEALTHY_MIN}+`- : band === "alert"- ? `< ${ALERT_MAX}`- : `${ALERT_MAX}–${HEALTHY_MIN}`,- ink: healthBandInk(band),+ hint: HEALTH_BAND_RANGE_LABEL[band],+ ink: healthBandNodeFill(band),}));if (level.some((c) => c.avgScore == null)) {out.push({@@ -474,9 +468,7 @@ export function FilesTreemap({<pclassName="mt-0.5 font-medium tabular-nums"// Painted by the same function as the tile underneath the- // pointer. It was not: this line banded at 7 while `healthInk`- // bands at 8, so every file scoring 7.x was an amber tile with- // a green score written on top of it.+ // pointer, so the word and the tile cannot disagree.style={{ color: healthColor(tip.child.avgScore) }}>{HEALTH_BAND_LABEL[bandForScore(tip.child.avgScore)]} ·{" "}diff --git a/packages/ui/src/graph/graph-community-panel.tsx b/packages/ui/src/graph/graph-community-panel.tsxindex b0c32bef0..39a96f591 100644--- a/packages/ui/src/graph/graph-community-panel.tsx+++ b/packages/ui/src/graph/graph-community-panel.tsx@@ -10,7 +10,8 @@ import { InfoTip } from "../shared/info-tip";import { truncatePath } from "../lib/format";// Shared band function, never a local threshold: two surfaces disagreeing// about where "Good" starts is worse than the import.-import { healthBand } from "../overview/health-lede";+import { bandForScore, type HealthBand } from "@repowise-dev/types/health";+import { healthBand } from "../health/tokens";import type { CommunityDetail } from "@repowise-dev/types/graph";/**@@ -27,16 +28,16 @@ import type { CommunityDetail } from "@repowise-dev/types/graph";* bad file inside a healthy group is exactly the file such a sentence would* tell the reader to skip.*- * Keyed on `healthBand`'s label, the same five bands the Code Health lede and- * the file health drawer show, so one score never gets two vocabularies.+ * Keyed on the band itself rather than its label, so a wording change to the+ * band cannot silently drop a reading.*/-const HEALTH_READING: Record<string, string> = {- Excellent:+const HEALTH_READING: Record<HealthBand, string> = {+ excellent:"On average this area scores well. A mean hides its worst file, so check the flags below.",- Good: "On average this area scores well. A mean hides its worst file, so check the flags below.",- Fair: "This area averages into the middle; some files here carry real defect risk.",- "Needs work": "This area averages low. Read it before you change it.",- Critical: "This area averages into the worst band. Read it before you change it.",+ good: "On average this area scores well. A mean hides its worst file, so check the flags below.",+ fair: "This area averages into the middle; some files here carry real defect risk.",+ needs_work: "This area averages low. Read it before you change it.",+ at_risk: "This area averages into the worst band. Read it before you change it.",};export interface GraphCommunityPanelProps {@@ -270,7 +271,7 @@ function HealthLede({</span></div><p className="mt-1.5 text-[11px] leading-relaxed text-[var(--color-text-secondary)]">- {HEALTH_READING[band.label]}{" "}+ {HEALTH_READING[bandForScore(score)]}{" "}{/* The mean is over the files that have a score, which is rarely all ofthem. Saying how many stops the figure from claiming more coveragethan it has. */}diff --git a/packages/ui/src/health/churn-complexity-quadrant.tsx b/packages/ui/src/health/churn-complexity-quadrant.tsxindex d73f149fe..59b7c31ed 100644--- a/packages/ui/src/health/churn-complexity-quadrant.tsx+++ b/packages/ui/src/health/churn-complexity-quadrant.tsx@@ -5,7 +5,8 @@ import { useMemo, useState } from "react";// the vite/rollup base alias clobbers subpath value resolution. Type-only// subpath imports are fine (erased before resolution).import { bandForScore } from "@repowise-dev/types";-import type { ChurnComplexityPoint, HealthBand } from "@repowise-dev/types/health";+import type { ChurnComplexityPoint } from "@repowise-dev/types/health";+import { HEALTH_BAND_FILL } from "./tokens";export interface ChurnComplexityQuadrantProps {points: ChurnComplexityPoint[];@@ -13,14 +14,6 @@ export interface ChurnComplexityQuadrantProps {height?: number;}-/* SVG fill class per canonical health band (the 3-bucket currency). Literal- * strings so Tailwind's static scanner keeps them. */-const BAND_FILL: Record<HealthBand, string> = {- alert: "fill-[var(--color-error)]",- warning: "fill-[var(--color-caution)]",- healthy: "fill-[var(--color-success)]",-};-/** Median of a numeric list (the data-driven quadrant split). */function median(values: number[]): number {if (values.length === 0) return 0;@@ -140,7 +133,7 @@ export function ChurnComplexityQuadrant({const cx = xScale(p.commit_count_90d);const cy = yScale(p.max_ccn);const isHovered = hovered?.file_path === p.file_path;- const fillCls = BAND_FILL[bandForScore(p.score)];+ const fillCls = HEALTH_BAND_FILL[bandForScore(p.score)];return (<circlekey={p.file_path}diff --git a/packages/ui/src/health/code-health-lede.tsx b/packages/ui/src/health/code-health-lede.tsxindex 59b72a82f..3cd7acd9e 100644--- a/packages/ui/src/health/code-health-lede.tsx+++ b/packages/ui/src/health/code-health-lede.tsx@@ -23,7 +23,6 @@import {bandForScore,- HEALTH_BAND_LABEL,type DefectAccuracy,type HealthDistribution,type HealthOverviewSummary,@@ -31,7 +30,7 @@ import {import { PageLede } from "../shared/page-lede";import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";import { formatNumber } from "../lib/format";-import { healthBandColor, scoreTextColor } from "./tokens";+import { healthBand, healthBandColor, scoreTextColor } from "./tokens";import { HealthDistributionBar } from "./health-distribution-bar";const HEALTH_HINT =@@ -97,12 +96,6 @@ function windowLabel(days: number): string {return months === 1 ? "month" : `${months} months`;}-/** A score as a canonical three-band chip. */-function bandChip(score: number): { label: string; color: string } {- const band = bandForScore(score);- return { label: HEALTH_BAND_LABEL[band], color: healthBandColor(band) };-}-export function CodeHealthLede({summary,accuracy,@@ -133,9 +126,9 @@ export function CodeHealthLede({: Math.round((historyDeduction / deduction) * 100);// The band words were fitted against the full, bug-predicting score, so// they are not a verdict this projection has earned: clamp(10 - structure)- // reads systematically higher, and almost every repo would print "Healthy"+ // reads systematically higher, and almost every repo would print "Excellent"// under it. The figure and the spread still say where the repo sits.- const healthChip = codeShape ? undefined : bandChip(health);+ const healthChip = codeShape ? undefined : healthBand(health);const stats: RibbonStat[] = [{ label: "Files", value: formatNumber(summary.file_count), hint: FILES_HINT },@@ -220,7 +213,7 @@ export function CodeHealthLede({for code health, weighted by lines of code and built from complexity,duplication, coverage{codeShape ? "" : ", churn and ownership"}.- {healthChip ? <> We rate that {healthChip.label.toLowerCase()}.</> : null}+ {healthChip ? <> That puts it in the {healthChip.label} band.</> : null}{perf != null && (<>{" "}diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsxindex 665af4e03..501c2f9fc 100644--- a/packages/ui/src/health/coverage-view.tsx+++ b/packages/ui/src/health/coverage-view.tsx@@ -21,6 +21,7 @@import { useMemo, useState } from "react";import { ArrowUpRight, Sparkles } from "lucide-react";import useSWR from "swr";+import { GOOD_MIN } from "@repowise-dev/types/health";import type {CoverageFileRow,HealthCoverageResponse,@@ -190,7 +191,7 @@ function CoverageBody({f.total_coverable_lines > 0 &&f.line_coverage_pct != null &&f.line_coverage_pct < 30 &&- (f.health_score == null || f.health_score < 6),+ (f.health_score == null || f.health_score < GOOD_MIN),).slice(0, 10).map((f) => {diff --git a/packages/ui/src/health/health-badge.tsx b/packages/ui/src/health/health-badge.tsxindex 6195521da..5bb1cdad4 100644--- a/packages/ui/src/health/health-badge.tsx+++ b/packages/ui/src/health/health-badge.tsx@@ -1,10 +1,11 @@import { bandForScore } from "@repowise-dev/types";-import type { HealthBand } from "@repowise-dev/types/health";+import { HEALTH_BAND_ORDER, 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`+ /** Explicit band from the API; when omitted, or when a server predating the+ * five bands sends one this build does not know, it is derived from `score`* via the shared `bandForScore` mirror (no hardcoded cutoffs). */band?: HealthBand;size?: "xs" | "sm";@@ -12,12 +13,12 @@ export interface HealthBadgeProps {/** 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.- * Colored by the 3 defect-backed health bands. */+ * components' shapes. Renders nothing when the score is missing. */export function HealthBadge({ score, band, size = "xs" }: HealthBadgeProps) {if (score == null) return null;- const resolved = band ?? bandForScore(score);- const cls = healthBandSoftBadgeClass(resolved);+ const cls = healthBandSoftBadgeClass(+ band && HEALTH_BAND_ORDER.includes(band) ? band : bandForScore(score),+ );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.tsxindex 9cf4215a8..c64c5b6d3 100644--- a/packages/ui/src/health/health-distribution-bar.tsx+++ b/packages/ui/src/health/health-distribution-bar.tsx@@ -1,22 +1,11 @@-import type { HealthBand, HealthDistribution } from "@repowise-dev/types/health";+import {+ HEALTH_BAND_LABEL,+ HEALTH_BAND_ORDER,+ type HealthBand,+ type 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;+import { HEALTH_BAND_BAR } from "./tokens";export interface HealthDistributionBarProps {distribution: HealthDistribution;@@ -26,18 +15,26 @@ export interface HealthDistributionBarProps {}/**- * 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.+ * NLOC-weighted distribution of files across the five health bands. Widths are+ * by code volume (NLOC), not file count, so a single large at-risk file isn't+ * hidden behind many tiny ones.*/export function HealthDistributionBar({distribution,showCounts = true,height = "sm",}: HealthDistributionBarProps) {+ // A server that predates the five bands still serves the three-band shape,+ // and the extension and the web app upgrade independently of it. A missing+ // band reads as absent, not as a crash.+ const share = (b: HealthBand) => distribution.bands[b]?.pct ?? 0;+ const files = (b: HealthBand) => distribution.bands[b]?.files ?? 0;const total = distribution.total_nloc;- if (!distribution.total_files || total === 0) {+ // A server predating the five bands serves the three-band shape with correct+ // totals, which would otherwise render as "we analysed 128 files and none of+ // them is in any band". No band accounted for is an unknown shape, not zero.+ const accounted = HEALTH_BAND_ORDER.some((b) => share(b) > 0);+ if (!distribution.total_files || total === 0 || !accounted) {return (<p className="text-xs text-[var(--color-text-tertiary)]">No files analyzed.</p>);@@ -47,31 +44,31 @@ export function HealthDistributionBar({<div className="space-y-1.5"><divclassName={`flex w-full ${h} overflow-hidden rounded-full bg-[var(--color-bg-inset)]`}- title={ORDER.map(- (b) => `${BAND_LABEL[b]} ${distribution.bands[b].pct}%`,+ title={HEALTH_BAND_ORDER.map(+ (b) => `${HEALTH_BAND_LABEL[b]} ${share(b)}%`,).join(" · ")}>- {ORDER.map((b) => {- const pct = distribution.bands[b].pct;+ {HEALTH_BAND_ORDER.map((b) => {+ const pct = share(b);if (pct === 0) return null;return (<divkey={b}- className={BAND_BAR[b]}+ className={HEALTH_BAND_BAR[b]}style={{ width: `${pct}%` }}- aria-label={`${BAND_LABEL[b]} ${pct}%`}+ aria-label={`${HEALTH_BAND_LABEL[b]} ${pct}%`}/>);})}</div>{showCounts && (<div className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-[var(--color-text-tertiary)]">- {ORDER.map((b) => (+ {HEALTH_BAND_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={`inline-block h-1.5 w-1.5 rounded-full ${HEALTH_BAND_BAR[b]}`} />+ {share(b)}% {HEALTH_BAND_LABEL[b].toLowerCase()}<span className="text-[var(--color-text-tertiary)]/70">- ({distribution.bands[b].files})+ ({files(b)})</span></span>))}diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsxindex d3ec343d4..6b338c522 100644--- a/packages/ui/src/health/health-file-drawer.tsx+++ b/packages/ui/src/health/health-file-drawer.tsx@@ -36,9 +36,9 @@ import {healthBandColor,type Severity,} from "./tokens";-// The canonical three bands, never a local threshold: this pill sits beside-// marks that all derive from `bandForScore`, and two of them disagreeing about-// where a band starts describes one file two ways in one viewport.+// The shared bands, never a local threshold: this pill sits beside marks that+// all derive from `bandForScore`, and two of them disagreeing about where a+// band starts describes one file two ways in one viewport.import { bandForScore, HEALTH_BAND_LABEL } from "@repowise-dev/types/health";import type {FileHealthTrend,diff --git a/packages/ui/src/health/impact-effort-quadrant.tsx b/packages/ui/src/health/impact-effort-quadrant.tsxindex 36be1a55a..fc9e95348 100644--- a/packages/ui/src/health/impact-effort-quadrant.tsx+++ b/packages/ui/src/health/impact-effort-quadrant.tsx@@ -1,6 +1,8 @@"use client";import { useMemo, useState } from "react";+import { bandForScore } from "@repowise-dev/types/health";+import { HEALTH_BAND_FILL } from "./tokens";import type { EffortBucket } from "./refactoring-card";export interface ImpactEffortPoint {@@ -109,14 +111,7 @@ export function ImpactEffortQuadrant({const cx = baseX + jitter(p.file_path);const cy = yScale(p.total_impact);const isHovered = hovered?.file_path === p.file_path;- const fillCls =- p.score < 4- ? "fill-[var(--color-error)]"- : p.score < 6- ? "fill-[var(--color-warning)]"- : p.score < 8- ? "fill-[var(--color-caution)]"- : "fill-[var(--color-success)]";+ const fillCls = HEALTH_BAND_FILL[bandForScore(p.score)];return (<circlekey={p.file_path}diff --git a/packages/ui/src/health/map/lens.ts b/packages/ui/src/health/map/lens.tsindex cd89b5c11..17c32eb64 100644--- a/packages/ui/src/health/map/lens.ts+++ b/packages/ui/src/health/map/lens.ts@@ -5,39 +5,19 @@* cannot drift: both call the same spec.*/-import { scoreBand, type ScoreBand } from "../tokens";+import {+ HEALTH_BAND_LABEL,+ HEALTH_BAND_ORDER,+ HEALTH_BAND_RANGE_LABEL,+} from "@repowise-dev/types/health";+import { healthBandNodeFill, healthNodeFill } from "../tokens";import type { CodeHealthMapFile, CodeHealthOverlay, PerformanceActionability } from "./types";-/**- * Band -> SVG fill var().- *- * The canvas ramp, not the semantic ink the score pills use. Those are tuned- * to be read as small coloured type against the page; this field is thousands- * of overlapping filled discs, which is a different job in both themes. The- * two ramps are the same four severity steps in the same hue family and are- * deliberately not the same values. See `--color-node-*` in globals.css.- */-const BAND_FILL: Record<ScoreBand, string> = {- critical: "var(--color-node-critical)",- poor: "var(--color-node-poor)",- fair: "var(--color-node-fair)",- good: "var(--color-node-good)",-};--/**- * The ramp names its score ranges rather than borrowing band words.- *- * It has four steps and the canonical band scale has three, so reusing the- * words made "Warning" mean 4 to 6 here and 4 to 8 on every other mark on the- * page, and invented a fourth band, "Fair", that the product never returns. A- * range is unambiguous and needs no glossary.- */-const BAND_LABEL: { band: ScoreBand; label: string }[] = [- { band: "critical", label: "Below 4" },- { band: "poor", label: "4 to 6" },- { band: "fair", label: "6 to 8" },- { band: "good", label: "8 and above" },-];+/** Worst-first legend rows, each naming its band and the range it covers. */+const BAND_LEGEND = HEALTH_BAND_ORDER.map((band) => ({+ fill: healthBandNodeFill(band),+ label: `${HEALTH_BAND_LABEL[band]} · ${HEALTH_BAND_RANGE_LABEL[band]}`,+}));/*** Neutral fill for nodes a lens has no signal for.@@ -72,7 +52,7 @@ export interface OverlaySpec {/** Score band: the health ramp, quiet grey when the pillar is unscored. */function scoreFill(score: number | null | undefined): string {if (score == null) return NEUTRAL_FILL;- return BAND_FILL[scoreBand(score)];+ return healthNodeFill(score);}/** Coverage band: green = well covered, red = uncovered, grey = no data. */@@ -99,10 +79,10 @@ function churnFill(pctile: number | null | undefined): string {* The health ramp with its top step removed.** This lens is a sibling of the health lens, not a different chart, so it- * paints with the same four-band ramp, at the same flat opacity, over the same- * geometry. It uses three of the four bands. A file a detector cleared is a+ * paints with the same band ramp, at the same flat opacity, over the same+ * geometry. It uses only the bands below green. A file a detector cleared is a* file with no supported pattern in it, not a file measured to be fast, and on- * this map green means healthy; so performance has no green, and that single+ * this map green means the code is fine; so performance has no green, and that* rule is the whole difference between the two lenses.** An earlier cut said the same thing with its own palette and its own opacity@@ -205,16 +185,16 @@ export function burdenBand(count: number): 0 | 1 | 2 | 3 {}/**- * The three steps, borrowed whole from the health ramp.+ * The three steps, borrowed from the health ramp.** Same tokens the score pills and the health lens use, so a colour means the- * same severity wherever it appears on this surface. `BAND_FILL.good` is- * deliberately absent: it is the only band that would claim a file is fine.+ * same severity wherever it appears on this surface. The two greens are+ * deliberately absent: they are the bands that would claim a file is fine.*/const BURDEN_FILL: Record<1 | 2 | 3, string> = {- 1: BAND_FILL.fair,- 2: BAND_FILL.poor,- 3: BAND_FILL.critical,+ 1: healthBandNodeFill("fair"),+ 2: healthBandNodeFill("needs_work"),+ 3: healthBandNodeFill("at_risk"),};export const PERFORMANCE_STATE_LABEL: Record<PerformanceNodeState, string> = {@@ -240,15 +220,15 @@ export const OVERLAY_SPECS: Record<CodeHealthOverlay, OverlaySpec> = {health: {label: "Code health",caption: "galaxy = module · size = lines of code",- fill: (f) => BAND_FILL[scoreBand(f.score)],- legend: BAND_LABEL.map((b) => ({ fill: BAND_FILL[b.band], label: b.label })),+ fill: (f) => healthNodeFill(f.score),+ legend: BAND_LEGEND,},maintainability: {label: "Maintainability",caption: "color = maintainability score · grey = not measured",fill: (f) => scoreFill(f.maintainability_score),legend: [- ...BAND_LABEL.map((b) => ({ fill: BAND_FILL[b.band], label: b.label })),+ ...BAND_LEGEND,{ fill: NEUTRAL_FILL, label: "not measured" },],},diff --git a/packages/ui/src/health/risk-coverage-scatter.tsx b/packages/ui/src/health/risk-coverage-scatter.tsxindex 56a8f399b..4119ba6fa 100644--- a/packages/ui/src/health/risk-coverage-scatter.tsx+++ b/packages/ui/src/health/risk-coverage-scatter.tsx@@ -1,7 +1,8 @@"use client";import { useEffect, useMemo, useRef, useState } from "react";-import type { CoverageBasis } from "@repowise-dev/types/health";+import { GOOD_MIN, bandForScore, type CoverageBasis } from "@repowise-dev/types/health";+import { HEALTH_BAND_FILL } from "./tokens";export interface RiskCoveragePoint {file_path: string;@@ -144,7 +145,7 @@ export function RiskCoverageScatter({// 60% coverage and a 7.0 score are the quadrant thresholds. On the// inferred basis the vertical one is the column divider instead.midX: inferred ? padL + plotW * 0.5 : xScale(60),- midY: yScale(7),+ midY: yScale(GOOD_MIN),};}, [width, height, data, inferred]);@@ -348,12 +349,9 @@ function reachedFill(reached: boolean | undefined): string {return reached ? "var(--color-accent-fill)" : "var(--color-accent-secondary)";}-/** Fill by health band. The bands are the same ones the rest of health uses. */+/** Fill by health band. */function bandFill(score: number): string {- if (score < 4) return "fill-[var(--color-error)]";- if (score < 6) return "fill-[var(--color-warning)]";- if (score < 8) return "fill-[var(--color-caution)]";- return "fill-[var(--color-success)]";+ return HEALTH_BAND_FILL[bandForScore(score)];}/**diff --git a/packages/ui/src/health/tokens.ts b/packages/ui/src/health/tokens.tsindex bff90d4fc..1eac7abfd 100644--- a/packages/ui/src/health/tokens.ts+++ b/packages/ui/src/health/tokens.ts@@ -7,7 +7,11 @@* caution/success) so the surface themes correctly in both modes.*/-import { bandForScore, type HealthBand } from "@repowise-dev/types/health";+import {+ bandForScore,+ HEALTH_BAND_LABEL,+ type HealthBand,+} from "@repowise-dev/types/health";export type Severity = "critical" | "high" | "medium" | "low";@@ -49,148 +53,138 @@ export const SEVERITY_BAR: Record<Severity, string> = {};/**- * 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.+ * The one health band -> colour vocabulary. Excellent and Good share the+ * green; the band word carries the difference. Every table below is written+ * out in full because Tailwind only sees class names it can read literally.*/-export type ScoreBand = "critical" | "poor" | "fair" | "good";--export function scoreBand(score: number): ScoreBand {- if (score < 4) return "critical";- if (score < 6) return "poor";- if (score < 8) return "fair";- return "good";-}+const HEALTH_BAND_VAR: Record<HealthBand, string> = {+ excellent: "var(--color-success)",+ good: "var(--color-success)",+ fair: "var(--color-caution)",+ needs_work: "var(--color-warning)",+ at_risk: "var(--color-error)",+};-/* Color classes for the 3 canonical health bands (Alert/Warning/Healthy).- * Literal strings so Tailwind's static scanner keeps them.- *- * These MUST use the same tokens as `HEALTH_BAND_INK` below. They did not:- * the Warning band read `--color-caution` here and `--color-warning` there,- * so a 6.9 was one amber as a label and a different amber as a fill —- * the treemap tile and the file page's score, or the zoom map's dot and its- * detail panel, describing one file in one viewport. Two marks on one object- * may not disagree about a colour they both derive from `bandForScore`.- * `--color-caution` stays where it belongs: the four-step severity/presentation- * ramp below, which is not a band. */const HEALTH_BAND_TEXT: Record<HealthBand, string> = {- alert: "text-[var(--color-error)]",- warning: "text-[var(--color-warning)]",- healthy: "text-[var(--color-success)]",+ excellent: "text-[var(--color-success)]",+ good: "text-[var(--color-success)]",+ fair: "text-[var(--color-caution)]",+ needs_work: "text-[var(--color-warning)]",+ at_risk: "text-[var(--color-error)]",+};++const HEALTH_BAND_BADGE: Record<HealthBand, string> = {+ excellent:+ "bg-[var(--color-success)]/15 text-[var(--color-success)] border border-[var(--color-success)]/30",+ good: "bg-[var(--color-success)]/15 text-[var(--color-success)] border border-[var(--color-success)]/30",+ fair: "bg-[var(--color-caution)]/15 text-[var(--color-caution)] border border-[var(--color-caution)]/30",+ needs_work:+ "bg-[var(--color-warning)]/15 text-[var(--color-warning)] border border-[var(--color-warning)]/30",+ at_risk:+ "bg-[var(--color-error)]/15 text-[var(--color-error)] border border-[var(--color-error)]/30",};const HEALTH_BAND_BADGE_SOFT: Record<HealthBand, string> = {- alert: "bg-[var(--color-error)]/15 text-[var(--color-error)]",- warning: "bg-[var(--color-warning)]/15 text-[var(--color-warning)]",- healthy: "bg-[var(--color-success)]/15 text-[var(--color-success)]",+ excellent: "bg-[var(--color-success)]/15 text-[var(--color-success)]",+ good: "bg-[var(--color-success)]/15 text-[var(--color-success)]",+ fair: "bg-[var(--color-caution)]/15 text-[var(--color-caution)]",+ needs_work: "bg-[var(--color-warning)]/15 text-[var(--color-warning)]",+ at_risk: "bg-[var(--color-error)]/15 text-[var(--color-error)]",};-/** 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];-}+/** SVG `fill-` classes, for the marks the scatter charts draw. */+export const HEALTH_BAND_FILL: Record<HealthBand, string> = {+ excellent: "fill-[var(--color-success)]",+ good: "fill-[var(--color-success)]",+ fair: "fill-[var(--color-caution)]",+ needs_work: "fill-[var(--color-warning)]",+ at_risk: "fill-[var(--color-error)]",+};-export function healthBandTextColor(band: HealthBand): string {- return HEALTH_BAND_TEXT[band];-}+/**+ * Bar fills for the distribution. Good is the same green stepped down in+ * opacity, so it stays legible where it sits next to Excellent.+ */+export const HEALTH_BAND_BAR: Record<HealthBand, string> = {+ excellent: "bg-[var(--color-success)]",+ good: "bg-[var(--color-success)]/55",+ fair: "bg-[var(--color-caution)]",+ needs_work: "bg-[var(--color-warning)]",+ at_risk: "bg-[var(--color-error)]",+};-/* The same three colours as raw CSS values, for the places that cannot take a- * class: an inline `style`, an SVG stroke. Kept beside HEALTH_BAND_TEXT so the- * two cannot drift the way the ink and text tables once did. */-const HEALTH_BAND_COLOR: Record<HealthBand, string> = {- alert: "var(--color-error)",- warning: "var(--color-warning)",- healthy: "var(--color-success)",+/**+ * The canvas ramp. Dense filled shapes carry no band word, so Excellent and+ * Good separate by value here rather than sharing the one green.+ */+const HEALTH_BAND_NODE_FILL: Record<HealthBand, string> = {+ excellent: "var(--color-node-excellent)",+ good: "var(--color-node-good)",+ fair: "var(--color-node-fair)",+ needs_work: "var(--color-node-needs-work)",+ at_risk: "var(--color-node-at-risk)",};-export function healthBandColor(band: HealthBand): string {- return HEALTH_BAND_COLOR[band];+export function healthBandNodeFill(band: HealthBand): string {+ return HEALTH_BAND_NODE_FILL[band];}-/* Literal class strings per band so Tailwind's static scanner sees them. */-const BAND_TEXT: Record<ScoreBand, string> = {- critical: "text-[var(--color-error)]",- poor: "text-[var(--color-warning)]",- fair: "text-[var(--color-caution)]",- good: "text-[var(--color-success)]",-};+/** The canvas ramp for a 1-10 score. */+export function healthNodeFill(score: number): string {+ return HEALTH_BAND_NODE_FILL[bandForScore(score)];+}-const BAND_BADGE: Record<ScoreBand, string> = {- critical:- "bg-[var(--color-error)]/15 text-[var(--color-error)] border border-[var(--color-error)]/30",- poor: "bg-[var(--color-warning)]/15 text-[var(--color-warning)] border border-[var(--color-warning)]/30",- fair: "bg-[var(--color-caution)]/15 text-[var(--color-caution)] border border-[var(--color-caution)]/30",- good: "bg-[var(--color-success)]/15 text-[var(--color-success)] border border-[var(--color-success)]/30",-};+export function healthBandColor(band: HealthBand): string {+ return HEALTH_BAND_VAR[band];+}-const BAND_BADGE_SOFT: Record<ScoreBand, string> = {- critical: "bg-[var(--color-error)]/15 text-[var(--color-error)]",- poor: "bg-[var(--color-warning)]/15 text-[var(--color-warning)]",- fair: "bg-[var(--color-caution)]/15 text-[var(--color-caution)]",- good: "bg-[var(--color-success)]/15 text-[var(--color-success)]",-};+export function healthBandTextColor(band: HealthBand): string {+ return HEALTH_BAND_TEXT[band];+}+export function healthBandSoftBadgeClass(band: HealthBand): string {+ return HEALTH_BAND_BADGE_SOFT[band];+}++/** Tailwind text colour for a 1-10 score. */export function scoreTextColor(score: number | null | undefined): string {if (score == null) return "text-[var(--color-text-primary)]";- return BAND_TEXT[scoreBand(score)];+ return HEALTH_BAND_TEXT[bandForScore(score)];}-/** Bordered score pill (file table, KPI badges). */+/** Bordered score pill, for a figure sitting in a table row. */export function scoreBadgeClass(score: number): string {- return BAND_BADGE[scoreBand(score)];+ return HEALTH_BAND_BADGE[bandForScore(score)];}-/** Borderless compact variant (inline HealthBadge next to file paths). */+/** Borderless score pill, for a figure sitting inline in prose. */export function scoreSoftBadgeClass(score: number): string {- return BAND_BADGE_SOFT[scoreBand(score)];-}--/* Raw CSS custom-property references per canonical band, for SVG/canvas- * fills and inline styles where a class string cannot be used. */-const HEALTH_BAND_INK: Record<HealthBand, string> = {- alert: "var(--color-error)",- warning: "var(--color-warning)",- healthy: "var(--color-success)",-};--/**- * A canonical band as an ink color, for a key or legend that has a band but no- * score to derive it from. Exported so an off-canvas key paints from the same- * table the fills do — a legend with its own copy of the colours is a legend- * that can describe a canvas it no longer matches.- */-export function healthBandInk(band: HealthBand): string {- return HEALTH_BAND_INK[band];+ return HEALTH_BAND_BADGE_SOFT[bandForScore(score)];}-/**- * Canonical banding for a higher-is-better health score on the 0-10 scale,- * as an ink color usable in `style`/SVG attributes. Thresholds come from the- * shared `bandForScore` mirror so every surface agrees on what counts as red.- */+/** Raw colour for a 1-10 score, for canvas ink and inline styles. */export function healthInk(score10: number): string {- return healthBandInk(bandForScore(score10));+ return HEALTH_BAND_VAR[bandForScore(score10)];}-/** `healthInk` for scores expressed on a 0-100 scale. */+/** The same, for the surfaces that carry health on a 0-100 scale. */export function healthInk100(score100: number): string {return healthInk(score100 / 10);}-/** `bandForScore` for scores expressed on a 0-100 scale. */export function healthBand100(score100: number): HealthBand {return bandForScore(score100 / 10);}/**- * Banding for a higher-is-worse risk value on the 0-1 scale, as an ink- * color. Matches the impact-graph node banding (>=0.66 alert, >=0.33- * warning) so risk reads the same across tables, charts, and graphs.+ * A 1-10 score as the colour and the word together, so a lede printing the+ * label and the figure beside it taking the colour cannot disagree.*/+export function healthBand(score: number): { color: string; label: string } {+ const band = bandForScore(score);+ return { color: HEALTH_BAND_VAR[band], label: HEALTH_BAND_LABEL[band] };+}+export function riskInk(risk01: number): string {if (risk01 >= 0.66) return "var(--color-error)";if (risk01 >= 0.33) return "var(--color-warning)";diff --git a/packages/ui/src/health/trend-slope-chart.tsx b/packages/ui/src/health/trend-slope-chart.tsxindex a032d847a..84d76502c 100644--- a/packages/ui/src/health/trend-slope-chart.tsx+++ b/packages/ui/src/health/trend-slope-chart.tsx@@ -1,7 +1,7 @@"use client";import { useMemo, useState } from "react";-import { scoreBand } from "./tokens";+import { healthInk } from "./tokens";export interface TrendSlopePoint {file_path: string;@@ -17,13 +17,6 @@ export interface TrendSlopeChartProps {max?: number;}-const BAND_STROKE: Record<string, string> = {- critical: "var(--color-error)",- poor: "var(--color-warning)",- fair: "var(--color-caution)",- good: "var(--color-success)",-};-/*** Slope chart for "largest score changes" — each file is a line from its* before-score to its after-score across two snapshot columns. Declines drop,@@ -77,7 +70,7 @@ export function TrendSlopeChart({ points, height = 320, max = 18 }: TrendSlopeCh{data.map((p) => {const y1 = yScale(p.before);const y2 = yScale(p.after);- const stroke = BAND_STROKE[scoreBand(p.after)] ?? "var(--color-caution)";+ const stroke = healthInk(p.after);const isHovered = hovered?.file_path === p.file_path;const name = p.file_path.split("/").pop() ?? p.file_path;return (diff --git a/packages/ui/src/modules/module-helpers.tsx b/packages/ui/src/modules/module-helpers.tsxindex 0366bfa28..17eddf458 100644--- a/packages/ui/src/modules/module-helpers.tsx+++ b/packages/ui/src/modules/module-helpers.tsx@@ -13,11 +13,13 @@ import { healthBand100 } from "../health/tokens";/* Literal class strings per band so Tailwind's static scanner keeps them. */const BAND_CHIP: Record<HealthBand, string> = {- healthy:+ excellent:"text-[var(--color-success)] bg-[var(--color-success)]/10 border-[var(--color-success)]/40",- warning:- "text-[var(--color-caution)] bg-[var(--color-caution)]/10 border-[var(--color-caution)]/40",- alert: "text-[var(--color-error)] bg-[var(--color-error)]/10 border-[var(--color-error)]/40",+ good: "text-[var(--color-success)] bg-[var(--color-success)]/10 border-[var(--color-success)]/40",+ fair: "text-[var(--color-caution)] bg-[var(--color-caution)]/10 border-[var(--color-caution)]/40",+ needs_work:+ "text-[var(--color-warning)] bg-[var(--color-warning)]/10 border-[var(--color-warning)]/40",+ at_risk: "text-[var(--color-error)] bg-[var(--color-error)]/10 border-[var(--color-error)]/40",};/** Colour classes for a 0–100 module health score. */diff --git a/packages/ui/src/overview/health-lede.tsx b/packages/ui/src/overview/health-lede.tsxindex 9be9c823f..aca8ec967 100644--- a/packages/ui/src/overview/health-lede.tsx+++ b/packages/ui/src/overview/health-lede.tsx@@ -1,4 +1,5 @@import * as React from "react";+import { healthBand } from "../health/tokens";import { LedeLink, PageLede } from "../shared/page-lede";export interface HealthLedeProps {@@ -16,16 +17,6 @@ export interface HealthLedeProps {LinkComponent?: React.ElementType;}-/** 1–10 bands. Shared with HealthOverviewCard's thresholds on purpose: two- * surfaces disagreeing about what "Good" means is worse than duplication. */-export function healthBand(v: number): { color: string; label: string } {- if (v >= 8) return { color: "var(--color-success)", label: "Excellent" };- if (v >= 6.5) return { color: "var(--color-success)", label: "Good" };- if (v >= 5) return { color: "var(--color-caution)", label: "Fair" };- if (v >= 3.5) return { color: "var(--color-warning)", label: "Needs work" };- return { color: "var(--color-error)", label: "Critical" };-}-/*** Code health as a headline number and a plain sentence, not a card of tiles.*diff --git a/packages/ui/src/overview/index.ts b/packages/ui/src/overview/index.tsindex e564e1fe8..3fb498e16 100644--- a/packages/ui/src/overview/index.ts+++ b/packages/ui/src/overview/index.ts@@ -22,7 +22,7 @@ export type { RepoAvatarProps } from "./repo-avatar";export { RepoRows } from "./repo-rows";export type { RepoRow, RepoRowsProps } from "./repo-rows";-export { HealthLede, healthBand } from "./health-lede";+export { HealthLede } from "./health-lede";export type { HealthLedeProps } from "./health-lede";export { ReadsColumn } from "./reads-column";diff --git a/packages/ui/src/overview/repo-rows.tsx b/packages/ui/src/overview/repo-rows.tsxindex 4796af752..cbee0a97e 100644--- a/packages/ui/src/overview/repo-rows.tsx+++ b/packages/ui/src/overview/repo-rows.tsx@@ -1,7 +1,7 @@import * as React from "react";import type { RepoIndexStatus } from "@repowise-dev/types/repos";import { formatNumber, formatRelativeTime } from "../lib/format";-import { healthBand } from "./health-lede";+import { healthBand } from "../health/tokens";import { RepoAvatar } from "./repo-avatar";export interface RepoRow {@@ -100,11 +100,8 @@ function figuresFor(repo: RepoRow): string[] {* the ribbon above it.** Health leads the right-hand column because it is the figure that decides- * which repo you open. It is painted on the five-step `healthBand`, the same- * reading the repo overview and the code health page use, so the number that- * sends you into a repo means there what it meant here. This row previously- * used the three-band `bandForScore`, which made one repo read amber in the- * list and green the moment you opened it.+ * which repo you open. It is painted on the shared `healthBand`, so the number+ * that sends you into a repo means there what it meant here.*/export function RepoRows({ repos, LinkComponent, actionsFor }: RepoRowsProps) {const A = LinkComponent ?? "a";diff --git a/packages/ui/src/zoom/node-signals.ts b/packages/ui/src/zoom/node-signals.tsindex 1325e2cd2..e9eac8beb 100644--- a/packages/ui/src/zoom/node-signals.ts+++ b/packages/ui/src/zoom/node-signals.ts@@ -1,17 +1,12 @@/*** What a card says about itself, in words. Pure, browser-free.*- * A card carries two dots and nothing on the surface named either. Worse, they- * shared a palette: the role dot painted `--color-success` for "has an entry- * point" while the health dot painted the same token for "healthy", so a reader- * who worked out one dot would misread the other. Colour bands belong to health- * (one accent, two semantics), so the role dot is now a single accent dot- * meaning "there is something here" and this module supplies the words that say- * what.+ * A card carries two dots and nothing on its surface names either, so the role+ * dot is a single accent dot meaning "there is something here" and the band+ * colours are left to health. These are the words that say which roles.*- * Naming all applicable roles also fixes a silent drop: the old dot ran a- * priority cascade (entry > hotspot > dead > on-flow) and drew only the winner,- * so a box that was both an entry point and a hotspot reported only "entry".+ * Every applicable role is named, not the winner of a priority cascade: a box+ * that is both an entry point and a hotspot is both.*/import { bandForScore, HEALTH_BAND_LABEL } from "@repowise-dev/types/health";@@ -55,11 +50,8 @@ export function hasRole(node: ZoomNode): boolean {}/**- * The health dot's band as a word, from the canonical 3-band scale in- * `@repowise-dev/types/health` — the same `bandForScore` the dot itself paints- * on. Not the 5-step Excellent/Good/Fair ladder the scan surfaces use: a 6.9- * reads "Good" there and paints amber here, and a label that contradicts the- * dot it sits beside is worse than no label.+ * The health dot's band as a word, on the same `bandForScore` the dot itself+ * paints on, so the label never contradicts the mark it sits beside.*/export function healthBandLabel(score: number | null): string | null {if (score === null) return null;diff --git a/packages/ui/src/zoom/nodes.ts b/packages/ui/src/zoom/nodes.tsindex 813fe7b14..27e3670a2 100644--- a/packages/ui/src/zoom/nodes.ts+++ b/packages/ui/src/zoom/nodes.ts@@ -14,7 +14,7 @@* single neutral hue, thin, faded behind the cards.*/-import { ALERT_MAX, HEALTHY_MIN } from "@repowise-dev/types/health";+import { bandForScore, type HealthBand } from "@repowise-dev/types/health";import type { Rect } from "./camera";import { hasRole, KIND_LABEL } from "./node-signals";@@ -120,16 +120,23 @@ function primaryMetric(node: ZoomNode): string {return n > 0 ? `${n} ${n === 1 ? "file" : "files"}` : "";}+/** Excellent and Good share the green; the word beside the dot separates them. */+const HEALTH_SLOT: Record<HealthBand, keyof ZoomPalette> = {+ excellent: "healthGood",+ good: "healthGood",+ fair: "healthFair",+ needs_work: "healthNeedsWork",+ at_risk: "healthAtRisk",+};+/**- * Traffic-light ink for a node's code-health score, on the same 0-10 bands the- * /files treemap uses (`bandForScore`: <4 alert, <8 warning, else healthy) so a- * card and a treemap tile never disagree. Null (unscored, sparse) reads neutral.+ * Ink for a node's code-health score, on the shared bands, so a card, the+ * detail panel and a treemap tile never disagree. Null (unscored) reads+ * neutral.*/function healthColor(score: number | null, palette: ZoomPalette): string {if (score === null) return palette.healthNeutral;- if (score < ALERT_MAX) return palette.healthAlert;- if (score < HEALTHY_MIN) return palette.healthWarning;- return palette.healthHealthy;+ return palette[HEALTH_SLOT[bandForScore(score)]];}/**@@ -168,16 +175,13 @@ function drawPaperTexture(/*** The role dot's colour, or null when a node carries no role.*- * One hue, deliberately. This used to return a different colour per role from- * `palette.entry` / `.hotspot` / `.dead` / `.flow`, which collided head-on with- * the health dot in the footer: `palette.entry` and `palette.healthHealthy` are- * both `--color-success`, so a green dot meant "has an entry point" in the- * top-right corner and "healthy" in the bottom-left one, forty pixels apart on- * the same card. Green/amber/red carry a band and belong to health.+ * One hue, deliberately. A per-role palette collides with the health dot in the+ * footer — `palette.entry` and `palette.healthGood` are both `--color-success`,+ * so one green would mean "has an entry point" and another "Good", forty pixels+ * apart on the same card. The band colours belong to health.*- * The role dot now says only "there is something here"; `nodeRoles` in- * `node-signals.ts` says what, in words, on hover and in the detail panel —- * where it can name every applicable role rather than a cascade's winner.+ * The role dot says only "there is something here"; `nodeRoles` in+ * `node-signals.ts` names every applicable role in words.*/function roleColor(node: ZoomNode, palette: ZoomPalette): string | null {return hasRole(node) ? palette.accent : null;diff --git a/packages/ui/src/zoom/theme.ts b/packages/ui/src/zoom/theme.tsindex 2f8c1ff0e..4baa1d0b8 100644--- a/packages/ui/src/zoom/theme.ts+++ b/packages/ui/src/zoom/theme.ts@@ -47,10 +47,11 @@ export interface ZoomPalette {dead: string;entry: string;flow: string;- /** Code-health traffic-light inks, matching the /files treemap bands. */- healthAlert: string;- healthWarning: string;- healthHealthy: string;+ /** Code-health band inks. Excellent and Good share the one green. */+ healthAtRisk: string;+ healthNeedsWork: string;+ healthFair: string;+ healthGood: string;/** Neutral ink for an unscored file/subtree (health is sparse). */healthNeutral: string;}@@ -78,11 +79,12 @@ const TOKEN_SPEC: Record<keyof ZoomPalette, string> = {dead: "--color-stale",entry: "--color-success",flow: "--color-accent-secondary",- // Same tokens the health tokens.ts `healthInk` maps to, so a zoom card and the- // /files treemap tile agree on what counts as red/amber/green.- healthAlert: "--color-error",- healthWarning: "--color-warning",- healthHealthy: "--color-success",+ // Same tokens `healthInk` maps to, so a zoom card, the detail panel beside+ // it and a /files treemap tile agree on the colour of one band.+ healthAtRisk: "--color-error",+ healthNeedsWork: "--color-warning",+ healthFair: "--color-caution",+ healthGood: "--color-success",healthNeutral: "--color-text-tertiary",};@@ -107,9 +109,10 @@ const FALLBACK: ZoomPalette = {dead: "gray",entry: "green",flow: "teal",- healthAlert: "crimson",- healthWarning: "orange",- healthHealthy: "green",+ healthAtRisk: "crimson",+ healthNeedsWork: "orange",+ healthFair: "goldenrod",+ healthGood: "green",healthNeutral: "gray",};diff --git a/packages/ui/styles/globals.css b/packages/ui/styles/globals.cssindex 39d6eeacd..cf787b7b5 100644--- a/packages/ui/styles/globals.css+++ b/packages/ui/styles/globals.css@@ -160,11 +160,14 @@Same red / amber / gold / green family, chroma and value pulled backtogether, and the amber and gold steps separated by hue as well aslightness. Fill only: pills, badges and text keep the ink vars, so the- map's red is deliberately not byte-identical to the pill's. */- --color-node-critical: #9e3226;- --color-node-poor: #ad5a19;+ map's red is deliberately not byte-identical to the pill's. Excellent+ and Good separate here by value, because on a canvas two thousand+ tiles of one green cannot be told apart by a word. */+ --color-node-at-risk: #9e3226;+ --color-node-needs-work: #ad5a19;--color-node-fair: #b3872a;--color-node-good: #2a7a54;+ --color-node-excellent: #17603f;/* No signal under the active lens. This was mixed a third of the way towardthe root, which recedes correctly against near-black and washes out to aghost against cream. One value cannot serve both directions. */@@ -495,10 +498,11 @@/* Canvas node ramp (dark) — see the light block for why this is not the ink.Deeper and less saturated than the semantic vars so a field of thousandsreads as pigment rather than as light. */- --color-node-critical: #b0544b;- --color-node-poor: #bd7c42;+ --color-node-at-risk: #b0544b;+ --color-node-needs-work: #bd7c42;--color-node-fair: #a89453;--color-node-good: #42906f;+ --color-node-excellent: #5cb389;--color-node-neutral: #333336;/* Refactoring type accents — qualitative palette (dark theme, brighter). */diff --git a/packages/vscode/webview/src/views/health/App.test.tsx b/packages/vscode/webview/src/views/health/App.test.tsxindex 6fc6ed5a5..7be56bf8c 100644--- a/packages/vscode/webview/src/views/health/App.test.tsx+++ b/packages/vscode/webview/src/views/health/App.test.tsx@@ -6,8 +6,9 @@ import type {HealthOverviewResponse,HealthTrendResponse,} from "@repowise-dev/types/health";+import { bandForScore } from "@repowise-dev/types/health";import { OVERLAY_SPECS } from "@repowise-dev/ui/health/code-health-map";-import { scoreBand, scoreTextColor } from "@repowise-dev/ui/health/tokens";+import { scoreTextColor } from "@repowise-dev/ui/health/tokens";import type { WebviewHost } from "../../runtime/rpc";import { App } from "./App";@@ -27,7 +28,7 @@ const overview: HealthOverviewResponse = {worst_performer_path: "src/worst.py",worst_performer_score: 2.3,open_findings: 42,- band: "warning",+ band: "good",maintainability_average: 8.2,performance_average: 9.9,maintainability_findings: 6,@@ -37,9 +38,11 @@ const overview: HealthOverviewResponse = {total_files: 128,total_nloc: 10000,bands: {- healthy: { files: 80, nloc: 6000, pct: 60 },- warning: { files: 40, nloc: 3000, pct: 30 },- alert: { files: 8, nloc: 1000, pct: 10 },+ excellent: { files: 50, nloc: 4000, pct: 40 },+ good: { files: 30, nloc: 2000, pct: 20 },+ fair: { files: 40, nloc: 3000, pct: 30 },+ needs_work: { files: 0, nloc: 0, pct: 0 },+ at_risk: { files: 8, nloc: 1000, pct: 10 },},},files: [],@@ -202,9 +205,8 @@ describe("Health dashboard", () => {// differ is the band beneath both, which is what this pins: the map fills// the node token for this file's band, and the figure carries the ink that// the same band function gives the same score.- const band = scoreBand(file.score);- expect(band).toBe("fair");- expect(OVERLAY_SPECS.health.fill(file)).toBe(`var(--color-node-${band})`);+ expect(bandForScore(file.score)).toBe("good");+ expect(OVERLAY_SPECS.health.fill(file)).toBe("var(--color-node-good)");expect(figure.className).toContain(scoreTextColor(file.score));});diff --git a/packages/vscode/webview/src/views/home/App.test.tsx b/packages/vscode/webview/src/views/home/App.test.tsxindex cb97ea9ae..1d620aa7c 100644--- a/packages/vscode/webview/src/views/home/App.test.tsx+++ b/packages/vscode/webview/src/views/home/App.test.tsx@@ -10,7 +10,7 @@ const SUMMARY: HomeSummary = {average: 7.4,fileCount: 1280,openFindings: 42,- band: "warning",+ band: "good",hotspotDelta: 0.3,history: [4.8, 4.9, 5.0, 5.1],},diff --git a/packages/vscode/webview/src/views/home/App.tsx b/packages/vscode/webview/src/views/home/App.tsxindex 32004cb99..f05dfec32 100644--- a/packages/vscode/webview/src/views/home/App.tsx+++ b/packages/vscode/webview/src/views/home/App.tsx@@ -47,11 +47,8 @@ import {import owlDarkTheme from "../../assets/owl-dark-theme.png";import owlLightTheme from "../../assets/owl-light-theme.png";-/**- * The shared score ramp, as a text class. This file used to carry its own- * thresholds — healthy at 7.5 — which disagreed with every other surface in the- * product and, more visibly, with the health dashboard this hero launches.- */+/** The shared band ramp as a text class, so this hero and the health dashboard+ * it launches read a score the same way. */function scoreTone(score: number | null): string {return score == null ? "text-[var(--color-text-tertiary)]" : scoreTextColor(score);}diff --git a/packages/web/src/components/zoom/zoom-detail-panel.tsx b/packages/web/src/components/zoom/zoom-detail-panel.tsxindex 67dfacb5f..1b886a87e 100644--- a/packages/web/src/components/zoom/zoom-detail-panel.tsx+++ b/packages/web/src/components/zoom/zoom-detail-panel.tsx@@ -100,9 +100,7 @@ export function ZoomDetailPanel({}: ZoomDetailPanelProps) {const m = node.metrics;const isFile = node.kind === "file";- // The canonical 3-band scale, so the panel agrees with the dot on the card- // beside it. The 5-step Excellent/Good ladder the scan surfaces use would- // call a 6.9 "Good" while the card paints it amber.+ // The shared bands, so the panel agrees with the dot on the card beside it.const band = healthBandLabel(node.health_score);const bandClass =node.health_score === null ? "" : healthBandTextColor(bandForScore(node.health_score));diff --git a/packages/web/src/components/zoom/zoom-map-key.tsx b/packages/web/src/components/zoom/zoom-map-key.tsxindex 6082dcfe7..d1962eb69 100644--- a/packages/web/src/components/zoom/zoom-map-key.tsx+++ b/packages/web/src/components/zoom/zoom-map-key.tsx@@ -30,7 +30,12 @@import { FilterChip } from "@repowise-dev/ui/health";import { type VerbCount, toggleVerb } from "@repowise-dev/ui/zoom";-import { HEALTH_BAND_LABEL } from "@repowise-dev/types/health";+import {+ FAIR_MIN,+ GOOD_MIN,+ HEALTH_BAND_LABEL,+ NEEDS_WORK_MIN,+} from "@repowise-dev/types/health";interface ZoomMapKeyProps {/** Every verb present in the loaded map, descending by count. */@@ -126,12 +131,15 @@ export function ZoomMapKey({</div><div className="flex items-center gap-1.5"><Dot className="bg-[var(--color-success)]" />+ <Dot className="bg-[var(--color-caution)]" /><Dot className="bg-[var(--color-warning)]" /><Dot className="bg-[var(--color-error)]" /><dt className="sr-only">Footer dot</dt><dd>- Code health: {HEALTH_BAND_LABEL.healthy} 8+, {HEALTH_BAND_LABEL.warning} 4 to 8,{" "}- {HEALTH_BAND_LABEL.alert} under 4.+ Code health: {HEALTH_BAND_LABEL.good} from {GOOD_MIN.toFixed(1)},{" "}+ {HEALTH_BAND_LABEL.fair} from {FAIR_MIN.toFixed(1)},{" "}+ {HEALTH_BAND_LABEL.needs_work} from {NEEDS_WORK_MIN.toFixed(1)},{" "}+ {HEALTH_BAND_LABEL.at_risk} below that.</dd></div></dl>diff --git a/tests/fixtures/mcp/tool_response_shapes.json b/tests/fixtures/mcp/tool_response_shapes.jsonindex c0af018d6..7bc8ad69a 100644--- a/tests/fixtures/mcp/tool_response_shapes.json+++ b/tests/fixtures/mcp/tool_response_shapes.json@@ -652,17 +652,27 @@},"distribution": {"bands": {- "alert": {+ "at_risk": {"files": null,"nloc": null,"pct": null},- "healthy": {+ "excellent": {"files": null,"nloc": null,"pct": null},- "warning": {+ "fair": {+ "files": null,+ "nloc": null,+ "pct": null+ },+ "good": {+ "files": null,+ "nloc": null,+ "pct": null+ },+ "needs_work": {"files": null,"nloc": null,"pct": null@@ -1305,17 +1315,27 @@"band": null,"distribution": {"bands": {- "alert": {+ "at_risk": {+ "files": null,+ "nloc": null,+ "pct": null+ },+ "excellent": {+ "files": null,+ "nloc": null,+ "pct": null+ },+ "fair": {"files": null,"nloc": null,"pct": null},- "healthy": {+ "good": {"files": null,"nloc": null,"pct": null},- "warning": {+ "needs_work": {"files": null,"nloc": null,"pct": nulldiff --git a/tests/unit/cli/test_health_cmd_controls.py b/tests/unit/cli/test_health_cmd_controls.pynew file mode 100644index 000000000..b6aac3f05--- /dev/null+++ b/tests/unit/cli/test_health_cmd_controls.py@@ -0,0 +1,101 @@+"""``repowise health`` offers the same two controls the API and MCP do.++An agent or a script that can ask "is this repo's code getting better" through+one surface and not another gets a different answer depending on where it+asked, which is the drift these two options exist to remove.+"""++from __future__ import annotations++import io+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++from click.testing import CliRunner+from rich.console import Console++from repowise.cli.commands.health_cmd import command as health_module+from repowise.cli.commands.health_cmd.command import health_command+from repowise.cli.main import cli+from repowise.core.analysis.health.counts import COUNTS, DEFAULT_COUNTS+from repowise.core.analysis.health.scope import DEFAULT_SCOPE, SCOPES+++def _option(name: str):+ return next(p for p in health_command.params if p.name == name)+++def test_both_controls_offer_the_shared_vocabulary() -> None:+ scope, counts = _option("scope"), _option("counts")+ assert tuple(scope.type.choices) == SCOPES+ assert scope.default == DEFAULT_SCOPE+ assert tuple(counts.type.choices) == COUNTS+ assert counts.default == DEFAULT_COUNTS+++def test_an_unknown_value_is_refused_rather_than_silently_defaulted() -> None:+ # Falling back to the default would report the calibrated number under a+ # flag that asked for the other one. Assert on click's rejection and not+ # just a non-zero exit: a missing index exits non-zero too.+ result = CliRunner().invoke(cli, ["health", "--counts", "code-shape"])+ assert result.exit_code != 0+ assert "Invalid value for '--counts'" in result.output+ assert "code-shape" in result.output+++def test_the_distribution_line_names_every_band() -> None:+ """Three segments on a five-band scale reads as a scale that has three."""+ import re++ from repowise.cli.commands.health_cmd.summary import _render_distribution_line+ from repowise.core.analysis.health.grading import BAND_LABEL, BAND_ORDER++ console = Console(file=io.StringIO(), width=400, force_terminal=False)+ with patch("repowise.cli.commands.health_cmd.summary.console", console):+ _render_distribution_line(+ {+ "total_files": 5,+ "total_nloc": 500,+ "bands": {b: {"files": 1, "nloc": 100, "pct": 20.0} for b in BAND_ORDER},+ }+ )+ out = re.sub(r"\s+", " ", console.file.getvalue())+ for band in BAND_ORDER:+ assert f"{BAND_LABEL[band].lower()} (1 files)" in out+++def test_the_trend_says_the_controls_do_not_reach_it() -> None:+ """The trend reads calibrated snapshots, so a flag on it would be a lie."""+ runner = CliRunner()+ with runner.isolated_filesystem():+ Path(".repowise").mkdir()+ with (+ patch.object(health_module, "_render_trend") as render,+ patch.object(health_module, "resolve_command_target") as resolve,+ ):+ resolve.return_value = SimpleNamespace(+ is_workspace=False,+ repo_path=Path("."),+ notice=lambda *a, **k: None,+ )+ result = runner.invoke(cli, ["health", "--trend", "--counts", "code_shape"])+ render.assert_called_once()+ assert "do not apply to it" in result.output+++def test_the_trend_stays_quiet_when_no_control_was_passed() -> None:+ runner = CliRunner()+ with runner.isolated_filesystem():+ Path(".repowise").mkdir()+ with (+ patch.object(health_module, "_render_trend"),+ patch.object(health_module, "resolve_command_target") as resolve,+ ):+ resolve.return_value = SimpleNamespace(+ is_workspace=False,+ repo_path=Path("."),+ notice=lambda *a, **k: None,+ )+ result = runner.invoke(cli, ["health", "--trend"])+ assert "do not apply to it" not in result.outputdiff --git a/tests/unit/health/test_grading.py b/tests/unit/health/test_grading.pyindex 2200cd71d..12b78ef0f 100644--- a/tests/unit/health/test_grading.py+++ b/tests/unit/health/test_grading.py@@ -1,46 +1,117 @@"""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.+The cutoffs are absolute 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 annotationsfrom repowise.core.analysis.health.grading import (- ALERT_MAX,- HEALTHY_MIN,+ BAND_BADGE_COLOR,+ BAND_LABEL,+ BAND_ORDER,+ BAND_RANGE_LABEL,+ BAND_TERMINAL_COLOR,+ EXCELLENT_MIN,+ FAIR_MIN,+ GOOD_MIN,+ NEEDS_WORK_MIN,+ TARGET_SCORE,band_for,distribution,)-def test_cutoffs_are_frozen_defect_backed_values() -> None:+def test_cutoffs_are_frozen() -> None:# If these change, the TS mirror (band-cutoffs test) must change too.- assert ALERT_MAX == 4.0- assert HEALTHY_MIN == 8.0+ assert EXCELLENT_MIN == 8.5+ assert GOOD_MIN == 7.0+ assert FAIR_MIN == 5.5+ assert NEEDS_WORK_MIN == 4.0+++def test_the_refactoring_target_is_not_a_band_edge() -> None:+ # Bands are presentation; this is the number refactoring leverage is+ # measured against. Moving it would reorder every recommendation, so it+ # stays where it was when the bands moved around it.+ assert TARGET_SCORE == 8.0+ assert TARGET_SCORE not in {EXCELLENT_MIN, GOOD_MIN, FAIR_MIN, NEEDS_WORK_MIN}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"+ assert band_for(10.0) == "excellent"+ assert band_for(8.5) == "excellent"+ assert band_for(8.49) == "good"+ assert band_for(7.0) == "good"+ assert band_for(6.99) == "fair"+ assert band_for(5.5) == "fair"+ assert band_for(5.49) == "needs_work"+ assert band_for(4.0) == "needs_work"+ assert band_for(3.99) == "at_risk"+ assert band_for(1.0) == "at_risk"+++def test_every_band_has_a_label_a_range_and_a_colour() -> None:+ bands = set(BAND_ORDER)+ assert bands == {"at_risk", "needs_work", "fair", "good", "excellent"}+ for table in (BAND_LABEL, BAND_RANGE_LABEL, BAND_TERMINAL_COLOR, BAND_BADGE_COLOR):+ assert set(table) == bands+++def test_range_labels_state_the_real_cutoffs() -> None:+ # These strings are what legends and keys print. Pinned to the constants+ # they describe, so moving a cutoff cannot leave a legend telling the user+ # a boundary that is no longer there.+ expected = {+ "excellent": f"{EXCELLENT_MIN}+",+ "good": f"{GOOD_MIN} to {EXCELLENT_MIN}",+ "fair": f"{FAIR_MIN} to {GOOD_MIN}",+ "needs_work": f"{NEEDS_WORK_MIN} to {FAIR_MIN}",+ "at_risk": f"under {NEEDS_WORK_MIN}",+ }+ assert dict(BAND_RANGE_LABEL) == expected+++def test_terminal_and_badge_colours_are_named_and_ordered() -> None:+ # A typo reaches a user as a rich markup error or a grey shields badge, and+ # neither surface is covered by a rendering test.+ assert dict(BAND_TERMINAL_COLOR) == {+ "excellent": "green",+ "good": "green",+ "fair": "yellow",+ "needs_work": "dark_orange",+ "at_risk": "red",+ }+ assert dict(BAND_BADGE_COLOR) == {+ "excellent": "brightgreen",+ "good": "brightgreen",+ "fair": "yellow",+ "needs_work": "orange",+ "at_risk": "red",+ }+++def test_band_order_runs_worst_first() -> None:+ assert BAND_ORDER == ("at_risk", "needs_work", "fair", "good", "excellent")+++def test_excellent_and_good_share_one_green() -> None:+ # They are told apart by the word, not by the colour.+ assert BAND_TERMINAL_COLOR["excellent"] == BAND_TERMINAL_COLOR["good"]+ assert BAND_BADGE_COLOR["excellent"] == BAND_BADGE_COLOR["good"]def test_distribution_empty_repo() -> None:dist = distribution([])assert dist["total_files"] == 0assert dist["total_nloc"] == 0- for band in ("healthy", "warning", "alert"):+ for band in BAND_ORDER: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+ # One excellent file with lots of NLOC vs many tiny at-risk files: the# percentage is NLOC-weighted, not file-count-weighted.metrics = [{"file_path": "big_healthy.py", "score": 9.0, "nloc": 900},@@ -50,9 +121,9 @@ def test_distribution_nloc_weighted() -> None:dist = distribution(metrics)assert dist["total_files"] == 3assert 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}+ assert dist["bands"]["excellent"] == {"files": 1, "nloc": 900, "pct": 90.0}+ assert dist["bands"]["at_risk"] == {"files": 2, "nloc": 100, "pct": 10.0}+ assert dist["bands"]["fair"] == {"files": 0, "nloc": 0, "pct": 0.0}def test_distribution_floors_zero_nloc_at_one() -> None:@@ -63,8 +134,8 @@ def test_distribution_floors_zero_nloc_at_one() -> None:]dist = distribution(metrics)assert dist["total_nloc"] == 2- assert dist["bands"]["healthy"]["nloc"] == 1- assert dist["bands"]["warning"]["nloc"] == 1+ assert dist["bands"]["excellent"]["nloc"] == 1+ assert dist["bands"]["needs_work"]["nloc"] == 1def test_distribution_accepts_objects() -> None:@@ -75,5 +146,5 @@ def test_distribution_accepts_objects() -> None:self.nloc = nlocdist = 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.0+ assert dist["bands"]["excellent"]["pct"] == 50.0+ assert dist["bands"]["at_risk"]["pct"] == 50.0diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.pyindex be8e28389..def81b2e7 100644--- a/tests/unit/server/mcp/test_health.py+++ b/tests/unit/server/mcp/test_health.py@@ -1921,6 +1921,166 @@ async def test_scope_narrows_every_figure_to_production(setup_mcp, session, popu)+async def test_counts_reads_the_code_shape_half_across_the_response(+ setup_mcp, session, populated_db+):+ """``counts`` is the same shape of control as ``scope``: one projection+ over the whole response, off the stored split rather than a rescore."""+ from repowise.core.persistence.crud import save_health_metrics+ from repowise.server.mcp_server import get_health++ await save_health_metrics(+ session,+ populated_db,+ [+ {+ "file_path": "src/auth/service.py",+ "score": 3.0,+ "nloc": 100,+ "is_test": False,+ "structure_deduction": 1.0,+ "history_deduction": 6.0,+ },+ ],+ )+ everything = await get_health()+ assert everything["counts"] == "everything"+ assert everything["kpis"]["average_health"] == 3.0+ assert everything["unscored_files"] == 0++ shaped = await get_health(counts="code_shape")+ assert shaped["counts"] == "code_shape"+ # 10 - structure, with the history half left out. The score is re-read,+ # never recomputed.+ assert shaped["kpis"]["average_health"] == 9.0+ assert shaped["unscored_files"] == 0+++async def test_a_row_the_projection_cannot_read_is_not_reported_as_unindexed(+ setup_mcp, session, populated_db, tmp_path+):+ """``not_indexed`` sends the caller to run an update. An update writes no+ split for a row that predates it, so that would be a wasted trip."""+ from repowise.core.persistence.crud import save_health_metrics+ from repowise.server.mcp_server import get_health++ await save_health_metrics(+ session,+ populated_db,+ [{"file_path": "src/auth/service.py", "score": 3.0, "nloc": 100, "is_test": False}],+ )+ result = await get_health(targets=["src/auth/service.py"], counts="code_shape")+ reasons = {row["target"]: row["reason"] for row in result.get("unresolved", [])}+ assert reasons.get("src/auth/service.py") == "not_measured"+++async def test_counts_and_scope_compose(setup_mcp, session, populated_db):+ """Both controls narrow the one population, rather than fighting over it."""+ from repowise.core.persistence.crud import save_health_metrics+ from repowise.server.mcp_server import get_health++ await save_health_metrics(+ session,+ populated_db,+ [+ {+ "file_path": "src/auth/service.py",+ "score": 3.0,+ "nloc": 100,+ "is_test": False,+ "structure_deduction": 1.0,+ "history_deduction": 6.0,+ },+ {+ "file_path": "tests/test_auth.py",+ "score": 5.0,+ "nloc": 100,+ "is_test": True,+ "structure_deduction": 3.0,+ "history_deduction": 2.0,+ },+ ],+ )+ result = await get_health(scope="production", counts="code_shape")+ assert result["scope"] == "production"+ assert result["counts"] == "code_shape"+ assert result["kpis"]["file_count"] == 1+ assert result["kpis"]["average_health"] == 9.0+++async def test_the_reading_survives_an_only_projection(setup_mcp, session, populated_db):+ """A projected score with nothing saying so is the failure the echo prevents.++ ``only`` used to drop ``scope`` and ``counts``, so the narrowest useful+ call — ask for the KPIs and nothing else — returned the code-shape number+ indistinguishable from the calibrated one.+ """+ from repowise.core.persistence.crud import save_health_metrics+ from repowise.server.mcp_server import get_health++ await save_health_metrics(+ session,+ populated_db,+ [+ {+ "file_path": "src/auth/service.py",+ "score": 3.0,+ "nloc": 100,+ "is_test": False,+ "structure_deduction": 1.0,+ "history_deduction": 6.0,+ }+ ],+ )+ result = await get_health(counts="code_shape", scope="production", only=["kpis"])+ assert result["counts"] == "code_shape"+ assert result["scope"] == "production"+ assert result["kpis"]["average_health"] == 9.0+++async def test_a_detail_lookup_says_the_controls_do_not_apply(setup_mcp, session, populated_db):+ """A lookup by id answers about one stored row, always calibrated.++ Accepting the control silently returned that row to a caller who believed+ they had asked for the other reading.+ """+ from repowise.server.mcp_server import get_health++ result = await get_health(plan_id="does-not-exist", counts="code_shape")+ assert result["ignored_arguments"] == {"counts": "code_shape"}+++async def test_a_misspelled_control_is_named_rather_than_silently_defaulted(+ setup_mcp, session, populated_db+):+ """The routes reject an unknown value and the CLI refuses to run.++ MCP falls back to the default, so the only honest equivalent is to say+ which value was dropped: without it a caller who asked for code shape gets+ the churn-contaminated number under the name they asked for.+ """+ from repowise.server.mcp_server import get_health++ result = await get_health(counts="code-shape", scope="prod")+ assert result["counts"] == "everything"+ assert result["scope"] == "all"+ assert result["ignored_arguments"] == {"counts": "code-shape", "scope": "prod"}+++async def test_a_valid_control_is_not_reported_as_ignored(setup_mcp, session, populated_db):+ from repowise.server.mcp_server import get_health++ result = await get_health(counts="code_shape", scope="production")+ assert "ignored_arguments" not in result++@pytest.mark.asyncioasync def test_a_narrowed_target_is_not_reported_as_config_excluded(setup_mcp, session, populated_db@@ -2210,7 +2370,7 @@ def test_only_docstring_does_not_overclaim_the_aliases():from repowise.server.mcp_server.tool_health import _ONLY_ALIASES, get_healthdoc = get_health.__doc__ or ""- only_section = doc.split("only:", 1)[1].split("repo:", 1)[0]+ only_section = doc.split("only:", 1)[1].split("limit:", 1)[0]assert set(_ONLY_ALIASES) == {"biomarkers", "accuracy", "refactoring"}for name in _ONLY_ALIASES:assert name in only_sectiondiff --git a/tests/unit/server/test_health_badge.py b/tests/unit/server/test_health_badge.pyindex 69f8ad79f..a158a44a7 100644--- a/tests/unit/server/test_health_badge.py+++ b/tests/unit/server/test_health_badge.py@@ -16,9 +16,20 @@ from repowise.server.routers.code_health import (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")+ assert _badge_fields(9.0) == ("health", "9.0/10", "brightgreen", "excellent")+ assert _badge_fields(7.5) == ("health", "7.5/10", "brightgreen", "good")+ assert _badge_fields(6.0) == ("health", "6.0/10", "yellow", "fair")+ assert _badge_fields(4.5) == ("health", "4.5/10", "orange", "needs_work")+ assert _badge_fields(2.0) == ("health", "2.0/10", "red", "at_risk")+++def test_every_band_colour_has_a_hex_for_the_self_rendered_svg() -> None:+ # The JSON endpoint hands shields a colour name; the SVG endpoint has to+ # resolve it here. A band colour without a hex renders grey.+ from repowise.core.analysis.health.grading import BAND_BADGE_COLOR+ from repowise.server.routers.code_health.badge import _BADGE_COLOR_HEX++ assert set(BAND_BADGE_COLOR.values()) <= set(_BADGE_COLOR_HEX)def test_badge_fields_no_data() -> None:diff --git a/tests/unit/server/test_health_counts_route.py b/tests/unit/server/test_health_counts_route.pyindex 03397a975..1b03296ec 100644--- a/tests/unit/server/test_health_counts_route.py+++ b/tests/unit/server/test_health_counts_route.py@@ -67,8 +67,8 @@ async def test_the_distribution_is_recomputed_not_carried_over(client, session,await client.get(f"/api/repos/{repo_id}/health/overview?counts=code_shape")).json()bands = shaped["distribution"]["bands"]- assert bands["healthy"]["files"] == 1- assert bands["alert"]["files"] == 0+ assert bands["excellent"]["files"] == 1+ assert bands["at_risk"]["files"] == 0async def test_rows_without_a_split_are_reported_not_scored_ten(client, session, tmp_path) -> None:diff --git a/website/cli-reference.md b/website/cli-reference.mdindex f522f1776..5cf4e019c 100644--- a/website/cli-reference.md+++ b/website/cli-reference.md@@ -518,6 +518,8 @@ repowise health [PATH] [OPTIONS]|------|------|---------|-------------|| `--file` | string | — | Deep-dive a single file (relative path) || `--module` | string | — | Restrict to files whose path starts with this prefix |+| `--scope` | choice | all | `all` or `production`. Tests score higher than production code, so narrowing lowers every figure without a defect being found |+| `--counts` | choice | everything | `everything` or `code_shape`. `code_shape` removes the git-derived half of the score, which rises as a file is worked on || `--refactoring-targets` | flag | false | Ranked refactoring candidates by impact/effort || `--trend` | flag | false | Last health snapshots + declining alerts || `--badge` | flag | false | Ready-to-paste health badge Markdown |