Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(health): production_average leaves out tooling, vendored and generated files on every surface (#4771)

Raghav Chamadiya4026e9b3e7bb
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 307647a0c..233291e3d 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -341,7 +341,7 @@ Code-health scores and findings from stored analysis, across defect risk, mainta
| `performance_confidence` | string | none | `high`, `medium`, `low` |
| `performance_actionability` | string | none | `plan_ready`, `advisory`, `investigate`, `expected` |
| `performance_sort` | string | `rank` | `rank`, `leverage`, `observations` |
-| `scope` | string | `"all"` | `production` drops test files from every figure |
+| `scope` | string | `"all"` | `production` drops test, tooling, vendored and generated files from every figure |
| `counts` | string | `"everything"` | `code_shape` drops the git-derived half of the score |
| `repo` | string | default repo | `"all"` not supported |
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.md
index 785d8365d..16bd608c2 100644
--- a/docs/layers/CODE_HEALTH.md
+++ b/docs/layers/CODE_HEALTH.md
@@ -77,7 +77,7 @@ not analysed, never scored as a 10.
| Control | Values | Effect |
|---|---|---|
-| `scope` | `all` (default), `production` | `production` drops test files, which lowers the headline because tests usually score higher |
+| `scope` | `all` (default), `production` | `production` drops test, tooling, vendored and generated files, which lowers the headline because tests usually score higher |
| `counts` | `everything` (default), `code_shape` | `code_shape` removes the git-history half of each deduction, to see whether code improved after a refactor raised churn |
Every response echoes both. `everything` is the calibrated number every accuracy claim
diff --git a/docs/reference/API_REFERENCE.md b/docs/reference/API_REFERENCE.md
index cba89efdc..290e355bf 100644
--- a/docs/reference/API_REFERENCE.md
+++ b/docs/reference/API_REFERENCE.md
@@ -414,7 +414,7 @@ empty. The route still declares only `application/json`.
Two query parameters repeat across the `code-health` tag, and both change the
numbers rather than the rows:
-- `scope=all` (default) or `production`. `production` drops test files, which
+- `scope=all` (default) or `production`. `production` drops test, tooling, vendored and generated files, which
lowers every figure without a defect having been found.
- `counts=everything` (default) or `code_shape`. `code_shape` removes the
git-derived half of the score, so the figure describes code shape rather than
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 8433127e7..990bff644 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -553,7 +553,7 @@ Groups changed files over index edges, co-change pairs and (for a range) shared
| `more`, `workspace` | Opt-in block names; workspace footer |
- **`dependencies`:** the ten heaviest package edges (`from`, `to`, `verb`, `weight`), `edges_total` when more; absent in a single-package repo.
-- **`code_health`:** `production_average` when tests are in the reading; `files_scored` when some files have no score.
+- **`code_health`:** `production_average` when tests, tooling, vendored or generated files are in the reading; `files_scored` when some files have no score.
- **`next_actions`:** `include=["actions"]` serves both horizons with `done_when` and `by_tier`; `get_health(fix_id="act_...")` opens one. `unavailable` names inputs the list was built without and `unavailable_reasons` gives each one's reason; both are absent when every input was read.
- **`repo="all"`:** each repo has `summary` (essay's first sentence), `code_files` (its `code_health.code_files`, or graph code files before health runs) and `symbol_count`; `total_code_files` sums them.
@@ -618,7 +618,7 @@ One ranked queue across refactoring, performance and code-shape work, the same o
| `top_findings` / `findings`, `test_findings` | Production and test; totals sum to the open set |
| metric row | One file's scores and deductions |
-- **`kpis`:** hotspot health, `average_health` (NLOC-weighted), `average_health_unweighted`, `average_health_weighting`, pillar averages, `production_average` (while tests are in the average), `worst_performer_path`, `worst_test_path`, `performance_causes` (`now`, `production`, `all`, `per_10k_loc`; see [PERFORMANCE.md](../layers/PERFORMANCE.md#the-default-queue)). `get_overview` reports bands the same way.
+- **`kpis`:** hotspot health, `average_health` (NLOC-weighted), `average_health_unweighted`, `average_health_weighting`, pillar averages, `production_average` (the files `worst_performer_path` is picked from, while tests, tooling, vendored or generated files are in the average), `worst_performer_path`, `worst_test_path`, `performance_causes` (`now`, `production`, `all`, `per_10k_loc`; see [PERFORMANCE.md](../layers/PERFORMANCE.md#the-default-queue)). `get_overview` reports bands the same way.
- **Metric row:** `score` (defect, headline), `maintainability_score`, `performance_score`, `weighted_deficit` = (8 - score) x NLOC, `is_test`, `has_test_file`, `primary_biomarker`, `total_deduction`, `structure_deduction`, `history_deduction`, `withheld_deduction`, `history: "short"` (under 5 commits, so most history markers cannot fire).
- Score = 10 minus structure and history deductions, floored at 1.0; history is 0.0 under `counts="code_shape"`. Deficit and gap fields share score points x NLOC and compare only with each other.
- `primary_biomarker` prefers a discrete finding over `coverage_gradient`. `details.actions` (agent prompt, silencing rule) appear only with `finding_id=...`.
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
index 9d130914b..7579e900b 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
@@ -38,7 +38,12 @@ from repowise.core.analysis.health.counts import (
from repowise.core.analysis.health.models import split_by_origin
from repowise.core.analysis.health.ranking import deduction_by_path
from repowise.core.analysis.health.rows import detail_map, split_unscored
-from repowise.core.analysis.health.scope import DEFAULT_SCOPE, SCOPES, parse_scope
+from repowise.core.analysis.health.scope import (
+ DEFAULT_SCOPE,
+ SCOPES,
+ parse_scope,
+ rows_in_scope,
+)
from repowise.core.analysis.health.scoring import ADVISORY_DIMENSION, compute_kpis
from repowise.core.analysis.health.signals import HISTORY_MIN_COMMITS
from repowise.core.persistence.crud.analysis.health import open_finding_count
@@ -178,8 +183,9 @@ class _HealthGroup(click.Group):
default=DEFAULT_SCOPE,
type=click.Choice(list(SCOPES)),
help=(
- "Which files to report on. Tests score higher than production code, "
- "so 'production' lowers every figure without a defect being found."
+ "Which files to report on. 'production' leaves out tests, tooling, "
+ "vendored and generated files, which tend to score higher, so it "
+ "lowers every figure without a defect being found."
),
)
@click.option(
@@ -455,7 +461,7 @@ def _scope_report(
metrics = [m for m in report.metrics if opts.keeps(m.file_path)]
narrowed = parse_scope(opts.scope) == "production"
if narrowed:
- metrics = [m for m in metrics if not m.is_test]
+ metrics = rows_in_scope(opts.scope, metrics)
# 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}
@@ -630,10 +636,11 @@ def _render_headline(kpis: dict[str, Any], code_shape: bool, unanalysed: int) ->
avg = kpis.get("average_health")
avg_band = headline_band(avg, share)
parts = [banded("Code health", avg, avg_band) + (f" {scope}" if scope else "")]
- # Production code beside the all-files figure, while tests are in it.
+ # Production code beside the all-files figure, while tests, tooling or
+ # other non-shipping code are in it.
production = kpis.get("production_average")
- has_tests = (kpis.get("production_file_count") or 0) < (kpis.get("file_count") or 0)
- if production is not None and has_tests:
+ narrowed = (kpis.get("production_file_count") or 0) < (kpis.get("file_count") or 0)
+ if production is not None and narrowed:
parts.append(banded("Production code", production, headline_band(production, share)))
# A repo with no recent churn has no hotspots, so no hotspot figure.
hotspot = kpis.get("hotspot_health")
diff --git a/packages/core/src/repowise/core/analysis/health/ranking.py b/packages/core/src/repowise/core/analysis/health/ranking.py
index 0ec1c17c2..5f0711e4f 100644
--- a/packages/core/src/repowise/core/analysis/health/ranking.py
+++ b/packages/core/src/repowise/core/analysis/health/ranking.py
@@ -23,6 +23,7 @@ __all__ = [
"deduction_by_path",
"scope_reason",
"sort_metrics_worst_first",
+ "split_in_scope",
"worst_first_key",
"worst_in_scope",
"worst_kpis",
@@ -106,6 +107,24 @@ def scope_reason(row: Any) -> str | None:
).reason
+def split_in_scope(rows: Iterable[Any]) -> tuple[list[Any], list[Any]]:
+ """``(production, tests)``: the rows in Fix first's scope and the test rows.
+
+ The one split behind ``worst_performer`` and ``production_average``, so
+ both leave out the same tooling, vendored, generated and docs example
+ files. A row in neither list is out of scope for another reason.
+ """
+ in_scope: list[Any] = []
+ tests: list[Any] = []
+ for row in rows:
+ reason = scope_reason(row)
+ if reason is None:
+ in_scope.append(row)
+ elif reason == "test":
+ tests.append(row)
+ return in_scope, tests
+
+
def worst_in_scope(
rows: Iterable[Any], deductions: Mapping[str, float]
) -> tuple[Any | None, Any | None]:
@@ -116,14 +135,7 @@ def worst_in_scope(
named. The worst test is the head of ``test_worst_files``. Either is
``None`` when its list is empty.
"""
- in_scope: list[Any] = []
- tests: list[Any] = []
- for row in scored_rows(rows):
- reason = scope_reason(row)
- if reason is None:
- in_scope.append(row)
- elif reason == "test":
- tests.append(row)
+ in_scope, tests = split_in_scope(scored_rows(rows))
def key(row: Any) -> tuple[float, float, str]:
return worst_first_key(row, deductions)
diff --git a/packages/core/src/repowise/core/analysis/health/scope.py b/packages/core/src/repowise/core/analysis/health/scope.py
index ddc02624a..01dd6ca03 100644
--- a/packages/core/src/repowise/core/analysis/health/scope.py
+++ b/packages/core/src/repowise/core/analysis/health/scope.py
@@ -1,13 +1,15 @@
"""What health scores, and the names of the halves it can report on.
-Production/test narrowing itself is a column read (``HealthFileMetric.is_test``,
-stamped from the shared path classifier), so only the vocabulary lives here.
+The ``production`` half is the file set ``production_average`` and
+``worst_performer`` read (``ranking.split_in_scope``), so a narrowed reading,
+its trend and the headline beside it agree.
"""
from __future__ import annotations
+from collections.abc import Iterable
from functools import cache
-from typing import Literal
+from typing import Any, Literal
HealthScope = Literal["all", "production"]
DEFAULT_SCOPE: HealthScope = "all"
@@ -48,3 +50,16 @@ def scores_language(language: str | None) -> bool:
def parse_scope(value: str | None) -> HealthScope:
"""Normalise a caller's scope, falling back to the default on anything else."""
return value if value in SCOPES else DEFAULT_SCOPE # type: ignore[return-value]
+
+
+def rows_in_scope(scope: str | None, rows: Iterable[Any]) -> list[Any]:
+ """*rows* kept by *scope*: all of them, or only production code for
+ ``production`` (no tests, tooling, build, vendored, generated or docs
+ example files). A row is judged by its path and origin, never its score:
+ an unscored production row stays, so a caller still counts it."""
+ if parse_scope(scope) != "production":
+ return list(rows)
+ # Deferred: ranking pulls in scoring and the queue, which this module stays out of.
+ from .ranking import split_in_scope
+
+ return split_in_scope(rows)[0]
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.py
index 19fd4d7e6..b855baf61 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -16,7 +16,7 @@ from typing import TYPE_CHECKING, Any
from .grading import analysed_share
from .models import HealthFileMetricData, HealthFindingData, Severity
-from .rows import field, scored_rows, split_tests, split_unscored
+from .rows import field, scored_rows, split_unscored
from .shape_curve import continuous_base, group_by_function, saturated
if TYPE_CHECKING:
@@ -1051,6 +1051,23 @@ def hotspot_health(
return round(nloc_weighted_score(rows), 2)
+def production_average(metrics: Iterable[Any]) -> tuple[float | None, int]:
+ """``(score, file count)`` over the scored production files in *metrics*.
+
+ The only implementation of ``production_average``. Production is the file
+ set ``worst_performer`` is picked from (``ranking.split_in_scope``), so
+ tests, tooling, build scripts, vendored, generated and docs example files
+ are all left out. The score is ``None`` when no production file is scored.
+ """
+ # Imported here: ``ranking`` reads this module's score ceiling.
+ from .ranking import split_in_scope
+
+ production, _ = split_in_scope(scored_rows(metrics))
+ if not production:
+ return None, 0
+ return round(nloc_weighted_score(production), 2), len(production)
+
+
def _empty_kpis(unanalysed: int) -> dict[str, object]:
"""KPIs with no scored file: the headline is ``None``, never 10.0.
@@ -1113,8 +1130,9 @@ def compute_kpis(
headline's two halves, in deduction points, so a surface can say which
one is holding the score down. They sum to ``SCORE_MAX`` minus the
matching headline (``headline_split``). ``None`` until files carry the split.
- - ``production_average``: ``average_health`` over non-test files, weighted
- identically, so a narrowed view and a narrowed trend agree.
+ - ``production_average``: ``average_health`` over production code, the
+ files ``worst_performer`` is picked from (``ranking.split_in_scope``):
+ no tests, tooling, build, vendored, generated or docs example files.
- ``unanalysed_file_count``: files stored with no score because health has
no dialect for their language. Every KPI above leaves them out; when no
file is scored at all, the two headline averages are ``None``.
@@ -1133,8 +1151,7 @@ def compute_kpis(
# Imported here: ``ranking`` reads this module's score ceiling.
from .ranking import worst_kpis
- # ``production_average`` keeps its own rule: every non-test file.
- production, _ = split_tests(metrics)
+ production, production_count = production_average(metrics)
maint_avg = nloc_weighted_attr(metrics, "maintainability_score")
maint_hotspot = nloc_weighted_attr(hotspots, "maintainability_score")
perf_avg = nloc_weighted_attr(metrics, "performance_score")
@@ -1152,10 +1169,8 @@ def compute_kpis(
"performance_average": round(perf_avg, 2) if perf_avg is not None else None,
"performance_hotspot": round(perf_hotspot, 2) if perf_hotspot is not None else None,
**{k: round(v, 2) if v is not None else None for k, v in splits.items()},
- "production_average": (
- round(nloc_weighted_score(production), 2) if production else None
- ),
- "production_file_count": len(production),
+ "production_average": production,
+ "production_file_count": production_count,
"unanalysed_file_count": unanalysed,
"analysed_share": analysed_share(len(metrics), unanalysed),
}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/population.py b/packages/server/src/repowise/server/mcp_server/tool_health/population.py
index 8168721cc..c89869c24 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/population.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/population.py
@@ -11,7 +11,7 @@ from repowise.core.analysis.health.counts import parse_counts
from repowise.core.analysis.health.counts import project as project_counts
from repowise.core.analysis.health.models import split_by_origin
from repowise.core.analysis.health.rows import scored_rows
-from repowise.core.analysis.health.scope import parse_scope
+from repowise.core.analysis.health.scope import parse_scope, rows_in_scope
from repowise.core.persistence.crud.analysis.health import health_exclude_spec
from repowise.core.persistence.crud.analysis.plain_rows import plain_rows
from repowise.core.persistence.models import HealthFileMetric
@@ -92,7 +92,7 @@ async def load_population(
reported_scope = parse_scope(req.scope)
scope_paths: set[str] | None = None
if reported_scope == "production":
- all_metrics = [m for m in all_metrics if not m.is_test]
+ all_metrics = rows_in_scope(reported_scope, all_metrics)
scope_paths = {m.file_path for m in all_metrics}
# Before ``counts``, so a file nobody measured is reported as that rather
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/summary.py b/packages/server/src/repowise/server/mcp_server/tool_health/summary.py
index 7b0defda3..c3bca3543 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/summary.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/summary.py
@@ -14,12 +14,11 @@ from repowise.core.analysis.health.grading import (
from repowise.core.analysis.health.models import primary_finding, split_by_origin
from repowise.core.analysis.health.perf.coverage import PerfCoverage
from repowise.core.analysis.health.ranking import worst_kpis
-from repowise.core.analysis.health.rows import split_tests
from repowise.core.analysis.health.scoring import (
headline_split,
hotspot_health,
nloc_weighted_attr,
- nloc_weighted_score,
+ production_average,
)
from repowise.core.persistence.crud.analysis.performance import PerformanceHeadline
from repowise.core.persistence.models import HealthFileMetric
@@ -201,15 +200,15 @@ def _compute_kpis(
total_nloc = sum(max(m.nloc, 1) for m in metrics)
avg = sum(m.score * max(m.nloc, 1) for m in metrics) / total_nloc
share = analysed_share(len(metrics), unanalysed)
- production, tests = split_tests(metrics)
+ production, production_count = production_average(metrics)
return {
"file_count": len(metrics),
"average_health": round(avg, 2),
- # Production code alone, weighted the same way; only said while tests
- # are in ``average_health``, so ``scope="production"`` omits it.
+ # Production code alone, weighted the same way; only said while
+ # ``average_health`` also holds tests, tooling or other non-shipping code.
**(
- {"production_average": round(nloc_weighted_score(production), 2)}
- if production and tests
+ {"production_average": production}
+ if production is not None and production_count < len(metrics)
else {}
),
# ``None`` with no hotspot files, not an empty set averaged to 10.0.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py b/packages/server/src/repowise/server/mcp_server/tool_health/tool.py
index bc70373af..367ab7590 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/tool.py
@@ -190,7 +190,7 @@ async def get_health(
performance_view/_context/_boundary/_confidence/_actionability/_sort:
queue filters.
scope / counts: default ``all``/``everything``. ``production`` drops
- test files; ``code_shape`` drops git-derived score and findings.
+ non-production code; ``code_shape``, git-based score+findings.
"""
started = perf_counter()
diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/health.py b/packages/server/src/repowise/server/mcp_server/tool_overview/health.py
index c7d2a9ee7..0611d1d16 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_overview/health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/health.py
@@ -9,8 +9,7 @@ from repowise.core.analysis.health.grading import (
distribution as health_distribution,
)
from repowise.core.analysis.health.grading import headline_band
-from repowise.core.analysis.health.rows import scored_rows, split_tests
-from repowise.core.analysis.health.scoring import hotspot_health, nloc_weighted_score
+from repowise.core.analysis.health.scoring import hotspot_health, production_average
from repowise.core.persistence.crud import (
get_health_metrics as _get_health_metrics,
)
@@ -20,13 +19,11 @@ from repowise.core.persistence.crud import (
from repowise.core.persistence.crud import get_hotspot_file_paths
-def _production_average(metrics_rows: list[Any]) -> float | None:
- """The headline over non-test files, as ``compute_kpis`` weighs it; ``None``
- when the reading holds no tests, since it would only repeat the headline."""
- production, tests = split_tests(scored_rows(metrics_rows))
- if not production or not tests:
- return None
- return round(nloc_weighted_score(production), 2)
+def _production_average(metrics_rows: list[Any], scored: int) -> float | None:
+ """``compute_kpis``'s ``production_average``; ``None`` when all *scored*
+ files are production code, since it would only repeat the headline."""
+ production, count = production_average(metrics_rows)
+ return production if count < scored else None
async def _build_code_health(session: Any, repository: Any) -> dict[str, Any]:
@@ -47,7 +44,7 @@ async def _build_code_health(session: Any, repository: Any) -> dict[str, Any]:
return {"analysis_status": NO_DIALECT_STATUS, "code_files": code_files}
# Hotspot health from its one owner, over the rows already loaded.
hotspot_paths = await get_hotspot_file_paths(session, repository.id)
- production = _production_average(metrics_rows)
+ production = _production_average(metrics_rows, scored)
bands = health_distribution(metrics_rows)["bands"]
return {
"average_health": health_summary["average_health"],
diff --git a/packages/server/src/repowise/server/routers/code_health/scope.py b/packages/server/src/repowise/server/routers/code_health/scope.py
index 40306ea9f..533220c16 100644
--- a/packages/server/src/repowise/server/routers/code_health/scope.py
+++ b/packages/server/src/repowise/server/routers/code_health/scope.py
@@ -6,13 +6,14 @@ from typing import Any
from fastapi import Query
-from repowise.core.analysis.health.scope import DEFAULT_SCOPE, SCOPES, parse_scope
+from repowise.core.analysis.health.scope import DEFAULT_SCOPE, SCOPES, parse_scope, rows_in_scope
ScopeQuery = Query(
DEFAULT_SCOPE,
description=(
- "Which files to report on: 'all' (production and tests) or 'production'. "
- "Tests score higher than production code, so narrowing lowers every figure "
+ "Which files to report on: 'all' or 'production' (no tests, tooling, "
+ "vendored or generated files). "
+ "Those score higher than production code, so narrowing lowers every figure "
"without a defect having been found."
),
pattern=f"^({'|'.join(SCOPES)})$",
@@ -24,11 +25,12 @@ def narrow(
) -> tuple[list[Any], ...]:
"""Filter *metrics* to *scope*, then everything else to the files it kept.
- Metric rows carry ``is_test``, so they answer the question directly.
- Findings and their kin only carry a path, so they follow the metrics.
+ Metric rows carry ``is_test`` and ``code_origin``, so they answer the
+ question directly. Findings and their kin only carry a path, so they
+ follow the metrics.
"""
if parse_scope(scope) != "production":
return (metrics, *keyed_by_path)
- kept = [m for m in metrics if not m.is_test]
+ kept = rows_in_scope(scope, metrics)
paths = {m.file_path for m in kept}
return (kept, *([r for r in rows if r.file_path in paths] for rows in keyed_by_path))
diff --git a/packages/server/src/repowise/server/routers/code_health/trends_routes.py b/packages/server/src/repowise/server/routers/code_health/trends_routes.py
index 73399cc4e..08d83849b 100644
--- a/packages/server/src/repowise/server/routers/code_health/trends_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/trends_routes.py
@@ -8,7 +8,7 @@ from typing import Any
from fastapi import Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.analysis.health.scope import parse_scope
+from repowise.core.analysis.health.scope import parse_scope, rows_in_scope
from repowise.core.analysis.health.trends import (
diff_snapshots,
drop_unscoped_fields,
@@ -95,8 +95,13 @@ async def health_trend(
)
summary = diff_snapshots(snapshots)
# Snapshots record per-file scores for the whole repository, so a narrowed
- # response has to drop the test files from the movement list too.
- test_paths = await crud.get_test_file_paths(session, repo_id) if narrowed else set()
+ # response has to drop the files the scope leaves out from the movement list too.
+ left_out: set[str] = set()
+ if narrowed:
+ metrics = await crud.get_health_metrics(session, repo_id)
+ kept = {m.file_path for m in rows_in_scope(scope, metrics)}
+ left_out = await crud.get_test_file_paths(session, repo_id)
+ left_out |= {m.file_path for m in metrics} - kept
# Per-file delta from the last two snapshots.
file_deltas: list[dict] = []
@@ -110,7 +115,7 @@ async def health_trend(
for p in all_paths:
before = prev.get(p)
after = cur.get(p)
- if before is None or after is None or p in test_paths:
+ if before is None or after is None or p in left_out:
continue
d = round(float(after) - float(before), 2)
if d == 0:
diff --git a/packages/server/src/repowise/server/services/health_map.py b/packages/server/src/repowise/server/services/health_map.py
index 272ef00ce..fa17ebc6b 100644
--- a/packages/server/src/repowise/server/services/health_map.py
+++ b/packages/server/src/repowise/server/services/health_map.py
@@ -32,7 +32,7 @@ from repowise.core.analysis.health.counts import DEFAULT_COUNTS
from repowise.core.analysis.health.counts import project as project_counts
from repowise.core.analysis.health.perf.coverage import supported_perf_languages
from repowise.core.analysis.health.perf.opportunity_rank import ACTIONABILITY_ORDER
-from repowise.core.analysis.health.scope import DEFAULT_SCOPE, parse_scope
+from repowise.core.analysis.health.scope import DEFAULT_SCOPE, parse_scope, rows_in_scope
from repowise.core.persistence import crud
__all__ = [
@@ -175,7 +175,7 @@ class HealthMapService:
scope_narrowed = parse_scope(scope) == "production"
if scope_narrowed:
- metrics = [m for m in metrics if not m.is_test]
+ metrics = rows_in_scope(scope, metrics)
kept = {m.file_path for m in metrics}
rollups = [r for r in rollups if r.file_path in kept]
diff --git a/tests/unit/cli/test_health_cmd_controls.py b/tests/unit/cli/test_health_cmd_controls.py
index 66166b60a..3b52ac2c8 100644
--- a/tests/unit/cli/test_health_cmd_controls.py
+++ b/tests/unit/cli/test_health_cmd_controls.py
@@ -44,6 +44,27 @@ def test_an_unknown_value_is_refused_rather_than_silently_defaulted() -> None:
assert "code-shape" in result.output
+def test_production_scope_leaves_out_tooling_vendored_and_generated_files() -> None:
+ """``--scope production`` reads the file set ``production_average`` does."""
+
+ def row(path: str, score: float, origin: str) -> SimpleNamespace:
+ return SimpleNamespace(
+ file_path=path, score=score, nloc=100, is_test=False, code_origin=origin
+ )
+
+ rows = [
+ row("src/a.py", 4.0, "production"),
+ row("scripts/release.py", 10.0, "tooling"),
+ row("vendor/lib.js", 10.0, "vendored"),
+ row("src/gen/api_pb2.py", 10.0, "generated"),
+ ]
+ report = SimpleNamespace(metrics=rows, findings=[], kpis={})
+ opts = SimpleNamespace(scope="production", counts=DEFAULT_COUNTS, keeps=lambda _p: True)
+ metrics, _, _ = health_module._scope_report(report, set(), opts)
+ assert [m.file_path for m in metrics] == ["src/a.py"]
+ assert report.kpis["average_health"] == report.kpis["production_average"] == 4.0
+
+
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
diff --git a/tests/unit/health/test_ranking_contract.py b/tests/unit/health/test_ranking_contract.py
index 56d0b5764..5ad0cd972 100644
--- a/tests/unit/health/test_ranking_contract.py
+++ b/tests/unit/health/test_ranking_contract.py
@@ -20,6 +20,7 @@ from repowise.core.analysis.health.ranking import (
worst_in_scope,
worst_metric,
)
+from repowise.core.analysis.health.scope import rows_in_scope
from repowise.core.analysis.health.scoring import SCORE_FLOOR, compute_kpis
@@ -183,6 +184,30 @@ def test_worst_in_scope_skips_files_fix_first_leaves_out() -> None:
assert worst_in_scope(rows[:2], {}) == (None, None)
+def test_production_average_covers_the_files_worst_performer_is_picked_from() -> None:
+ """Tooling, vendored, generated and test files stay in ``average_health``
+ and out of ``production_average``."""
+ rows = [
+ {**_dict("scripts/migrate.py", 10.0), "code_origin": "tooling"},
+ {**_dict("third_party/lib.js", 10.0), "code_origin": "vendored"},
+ {**_dict("src/gen/schema_pb2.py", 10.0), "code_origin": "generated"},
+ {**_dict("tests/test_app.py", 10.0), "is_test": True},
+ _dict("src/app.py", 4.0),
+ ]
+ kpis = compute_kpis(rows, set())
+ assert kpis["average_health"] == 8.8
+ assert (kpis["production_average"], kpis["production_file_count"]) == (4.0, 1)
+ assert [r["file_path"] for r in rows_in_scope("production", rows)] == ["src/app.py"]
+ assert rows_in_scope("all", rows) == rows
+ unscored = [{**_dict("src/b.py", 4.0), "score": None}, {**rows[0], "score": None}]
+ assert rows_in_scope("production", unscored) == unscored[:1]
+ no_production = compute_kpis(rows[:4], set())
+ assert (no_production["production_average"], no_production["production_file_count"]) == (
+ None,
+ 0,
+ )
+
+
def test_the_deduction_map_has_no_default() -> None:
"""Omitting it would silently tie the whole floor band on path."""
with pytest.raises(TypeError):
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index 7fcee3f4f..e0a44cf72 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -2213,6 +2213,34 @@ async def test_scope_narrows_every_figure_to_production(setup_mcp, session, popu
)
+async def test_production_scope_is_the_file_set_production_average_reads(
+ setup_mcp, session, populated_db
+):
+ """Tooling, vendored and generated files leave ``scope="production"`` as
+ they leave ``production_average``, so the narrowed headline equals it."""
+ from repowise.core.persistence.crud import save_health_metrics
+ from repowise.server.mcp_server import get_health
+
+ def row(path: str, score: float, origin: str) -> dict:
+ return {"file_path": path, "score": score, "nloc": 100, "code_origin": origin}
+
+ await save_health_metrics(
+ session,
+ populated_db,
+ [
+ row("src/auth/service.py", 4.0, "production"),
+ row("scripts/release.py", 10.0, "tooling"),
+ row("vendor/lib.js", 10.0, "vendored"),
+ row("src/gen/api_pb2.py", 10.0, "generated"),
+ ],
+ )
+ everything = (await get_health())["kpis"]
+ assert (everything["average_health"], everything["production_average"]) == (8.5, 4.0)
+ production = (await get_health(scope="production"))["kpis"]
+ assert (production["average_health"], production["file_count"]) == (4.0, 1)
+
+
@pytest.mark.asyncio
async def test_counts_reads_the_code_shape_half_across_the_response(
setup_mcp, session, populated_db
@@ -3019,6 +3047,31 @@ def test_kpis_name_production_code_beside_the_all_files_average() -> None:
assert "production_average" not in _compute_kpis([prod], deductions={})
+def test_production_average_agrees_on_every_surface() -> None:
+ """Tooling, vendored and generated files stay out of ``production_average``
+ on get_health, get_overview and ``compute_kpis`` alike."""
+ from repowise.core.analysis.health.scoring import compute_kpis
+ from repowise.core.persistence.models import HealthFileMetric
+ from repowise.server.mcp_server.tool_health.summary import _compute_kpis
+ from repowise.server.mcp_server.tool_overview.health import _production_average
+
+ def row(path: str, score: float, origin: str) -> HealthFileMetric:
+ return HealthFileMetric(
+ file_path=path, score=score, nloc=100, is_test=False, code_origin=origin
+ )
+
+ rows = [
+ row("src/a.py", 6.0, "production"),
+ row("scripts/release.py", 10.0, "tooling"),
+ row("vendor/lib.js", 10.0, "vendored"),
+ row("src/gen/api_pb2.py", 10.0, "generated"),
+ ]
+ mcp = _compute_kpis(rows, deductions={})
+ assert (mcp["average_health"], mcp["production_average"]) == (9.0, 6.0)
+ assert compute_kpis(rows, set())["production_average"] == 6.0
+ assert _production_average(rows, len(rows)) == 6.0
+
+
def test_kpis_scope_a_score_most_code_files_did_not_feed() -> None:
from repowise.core.persistence.models import HealthFileMetric
from repowise.server.mcp_server.tool_health.summary import _compute_kpis
diff --git a/tests/unit/server/mcp/test_tool_overview.py b/tests/unit/server/mcp/test_tool_overview.py
index 26695b879..9ddafdac1 100644
--- a/tests/unit/server/mcp/test_tool_overview.py
+++ b/tests/unit/server/mcp/test_tool_overview.py
@@ -321,12 +321,12 @@ async def test_key_decisions_survive_corrupt_affected_files(session, populated_d
assert block["recent_reversals"] == []
-def test_production_average_needs_tests_in_the_reading():
+def test_production_average_needs_non_production_files_in_the_reading():
from repowise.server.mcp_server.tool_overview.health import _production_average
prod = SimpleNamespace(file_path="a.py", score=6.0, nloc=10, is_test=False)
test = SimpleNamespace(file_path="t.py", score=10.0, nloc=10, is_test=True)
- assert _production_average([prod, test]) == 6.0
- # With no tests it would only repeat the headline.
- assert _production_average([prod]) is None
+ assert _production_average([prod, test], 2) == 6.0
+ # With only production files it would repeat the headline.
+ assert _production_average([prod], 1) is None
diff --git a/tests/unit/server/test_health_map_feed.py b/tests/unit/server/test_health_map_feed.py
index 0da23a590..1cf1868c4 100644
--- a/tests/unit/server/test_health_map_feed.py
+++ b/tests/unit/server/test_health_map_feed.py
@@ -355,6 +355,22 @@ async def test_production_code_is_admitted_before_tests_and_examples(app, client
assert feed["files"][0]["code_origin"] == "production"
+async def test_production_scope_draws_the_production_average_file_set(app, client):
+ repo_id = await _seed_rows(
+ app,
+ client,
+ [
+ _metric("src/a.py", 10, "src", origin="production"),
+ _metric("scripts/build.py", 700, "scripts", origin="tooling"),
+ _metric("tests/test_x.py", 800, "tests", origin="test"),
+ ],
+ )
+ narrowed = await _feed(client, repo_id, cap=100, scope="production")
+ assert [f["file_path"] for f in narrowed["files"]] == ["src/a.py"]
+ everything = await _feed(client, repo_id, cap=100, scope="all")
+ assert "scripts/build.py" in [f["file_path"] for f in everything["files"]]
+
+
async def test_an_unhealthy_file_outranks_a_bigger_clean_one(app, client):
repo_id = await _seed_rows(
app,