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): one performance headline, led by the causes worth fixing now (#4231)

Raghav Chamadiya5bae0b401dcb
diff --git a/docs/layers/PERFORMANCE.md b/docs/layers/PERFORMANCE.md
index 7a1b7c55a..5a380b2c9 100644
--- a/docs/layers/PERFORMANCE.md
+++ b/docs/layers/PERFORMANCE.md
@@ -139,6 +139,14 @@ a `plan_ready` default-queue cause whose growth a loop outside a registry and a
Every other cause stays in the Performance view and is counted in Fix first as
`unconfirmed_cost`.
+Every headline counts causes the same way, in the three scopes of the Performance
+tab: `now` (the default queue, worth fixing now), `production` (every open
+production cause) and `all`, plus `per_10k_loc` (every cause per 10K lines a
+detector ran on). The generated CLAUDE.md and AGENTS.md, `get_health` `kpis`,
+`repowise health`, `repowise status`, the Overview card and the Code Health page
+lead with `now`. The map's performance lens colours a file by its causes in the
+default queue.
+
## Reading it
| Surface | How |
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 43f9ea14b..1dc86095f 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -376,7 +376,7 @@ Items are ordered by value first, then tier. History markers (churn, ownership,
| Field | Meaning |
|-------|---------|
-| `kpis` | Hotspot health, `average_health` (NLOC-weighted), `average_health_unweighted`, `average_health_weighting`, pillar averages, `production_average` (production code alone; only while tests are in `average_health`), `worst_performer_path`, `worst_test_path` |
+| `kpis` | Hotspot health, `average_health` (NLOC-weighted), `average_health_unweighted`, `average_health_weighting`, pillar averages, `production_average` (production code alone; only while tests are in `average_health`), `worst_performer_path`, `worst_test_path`, `performance_causes` (`now` in the default queue, `production`, `all`, and `per_10k_loc` over covered lines; see [PERFORMANCE.md](../layers/PERFORMANCE.md#the-default-queue)) |
| `unanalysed_file_count` | Files in a language health has no dialect for, stored with no score and left out of every figure; absent when there are none |
| `kpis.band`, `kpis.analysed_share` | The headline band is `null` when fewer than half the code files were analysed, since the average then speaks for a sample; `analysed_share` (scored over all code files) appears when some were left out. `get_overview` reports `code_health` the same way |
| `gap_analysis` | Weighted points the average must recover to reach 8.0, files below it, `files_to_reach_target`, `files_for_half_gap`, `weighted_gap_points`, `weighted_gross_gap_points` |
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 65d83dc3f..1ffff0c4b 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
@@ -46,6 +46,7 @@ from repowise.core.persistence.crud.analysis.health import open_finding_count
from .codegen import _generate_refactoring_code
from .persist import (
_load_fix_first,
+ _load_perf_causes,
_load_persisted_coverage_map,
_load_queue_counts,
_load_recommendations,
@@ -547,6 +548,7 @@ def _render_table(
) -> None:
"""The terminal report. *metrics* is ``(as scoped, sorted by score)``."""
from repowise.core.analysis.health.grading import distribution as health_distribution
+ from repowise.core.analysis.health.perf.coverage import coverage_for_metrics
scoped, metrics_sorted = metrics
# Lead with what to fix; a narrowed run is an inspection, not the worklist.
@@ -556,9 +558,13 @@ def _render_table(
_render_split_line(report.kpis)
_render_distribution_line(health_distribution(scoped))
_render_defect_accuracy_line(report)
- # Lead with the finding count, density and coverage, not the bounded /10
- # average. Metrics carry no language, so it comes with the report.
- _render_performance_section(report, findings, languages)
+ # Lead with the causes worth fixing now and coverage, not the bounded /10
+ # average. Metrics carry no language, so it comes with the report. The
+ # counts are the repository's, so a narrowed run leaves them out.
+ coverage = coverage_for_metrics(report.metrics, languages)
+ narrowed = bool(opts.file_filter or opts.module_filter)
+ causes = None if narrowed else _load_perf_causes(repo_path, coverage.covered_nloc)
+ _render_performance_section(report, coverage, causes)
_render_files_table(metrics_sorted, _load_short_history(repo_path))
_render_findings_table(findings)
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py b/packages/cli/src/repowise/cli/commands/health_cmd/persist.py
index bd43eaa19..503c1d24b 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/persist.py
@@ -78,6 +78,25 @@ def _load_fix_first(repo_path: object, *, limit: int) -> tuple[Any, Any] | None:
return None
+def _load_perf_causes(repo_path: object, covered_nloc: int) -> Any | None:
+ """The stored performance headline (``crud.performance_headline``), or
+ ``None`` when the store cannot answer."""
+ from repowise.cli.helpers import repo_index_session
+ from repowise.core.persistence.crud import performance_headline
+
+ async def _do() -> Any:
+ async with repo_index_session(Path(str(repo_path))) as opened:
+ if opened is None:
+ return None
+ session, repo_id = opened
+ return await performance_headline(session, repo_id, covered_nloc=covered_nloc)
+
+ try:
+ return run_async(_do())
+ except Exception:
+ return None
+
+
def _load_queue_counts(repo_path: object) -> dict[str, Any] | None:
"""Every queue unit's stored counts, by noun; ``None`` when the store cannot answer."""
from repowise.cli.helpers import repo_index_session
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/summary.py b/packages/cli/src/repowise/cli/commands/health_cmd/summary.py
index a264c5acd..1c6c566ea 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/summary.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/summary.py
@@ -41,35 +41,30 @@ def _render_fix_first(loaded: tuple[Any, Any] | None) -> None:
console.print(f" [dim]verify:[/dim] {escape(item.verify.command)}")
-def _render_performance_section(
- report: Any, findings: list[Any], lang_by_path: dict[str, str]
-) -> None:
- """Honest performance headline: risk count + density + coverage + scope.
+def _render_performance_section(report: Any, coverage: Any, causes: Any | None) -> None:
+ """Honest performance headline: the open causes + coverage + scope.
- Leads with the open-risk count and how much of the analyzed code a perf
+ Leads with the causes worth fixing now (``crud.performance_headline``, as
+ every surface counts them) and how much of the analyzed code a perf
detector actually ran on, so a mostly-unsupported-language repo reads a low
coverage % rather than a meaningless bounded 10/10. Silent when no code file
carries a supported language (nothing to say).
"""
- from repowise.core.analysis.health.perf.coverage import coverage_for_metrics
-
- coverage = coverage_for_metrics(report.metrics, lang_by_path)
if not coverage.analyzed_files:
return
- perf_findings = sum(
- 1 for f in findings if getattr(f, "dimension", "defect") == "performance"
- )
perf_avg = report.kpis.get("performance_average")
- parts = [f"[bold]{perf_findings}[/bold] risk{'s' if perf_findings != 1 else ''}"]
- if coverage.covered_nloc > 0:
- density = round(10000.0 * perf_findings / coverage.covered_nloc, 2)
- parts.append(f"{density}/10K covered LOC")
+ parts = []
+ if causes is not None:
+ parts.append(
+ f"[bold]{causes.now:,}[/bold] cause{'s' if causes.now != 1 else ''} worth "
+ f"fixing now · {causes.production:,} open in production code · {causes.all:,} overall"
+ )
+ if causes.per_10k_loc is not None:
+ parts.append(f"{causes.per_10k_loc}/10K covered LOC")
if isinstance(perf_avg, (int, float)):
parts.append(f"avg score {perf_avg:.1f}/10")
console.print(
- # "risk" sits on the count, where more is worse, not on a heading over
- # a score where more is better.
"\n[bold]Performance[/bold] "
"[dim](static, high-precision/low-recall)[/dim]: " + " · ".join(parts)
)
diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.py
index 412e64c38..e4ca70ba0 100644
--- a/packages/cli/src/repowise/cli/commands/status_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py
@@ -301,13 +301,14 @@ def _query_health_line(repo_path: Path) -> str | None:
# split has populated it (None on indexes that predate the relevant work).
maint = data.get("maintainability_average")
maint_part = f" · {format_score(maint)} (maintainability)" if maint is not None else ""
- # Performance leads with the finding COUNT (the honest signal); the bounded
- # /10 average trails in parens as a summary, never as a verification claim.
+ # Performance leads with the causes worth fixing now (the honest signal);
+ # the bounded /10 average trails in parens, never as a verification claim.
perf = data.get("performance_average")
- perf_findings = data.get("performance_findings", 0)
+ causes = data.get("performance_causes")
perf_part = (
- f" · {perf_findings} perf finding{'s' if perf_findings != 1 else ''} ({format_score(perf)})"
- if perf is not None
+ f" · {causes['now']} of {causes['production']} production perf causes "
+ f"worth fixing now ({format_score(perf)})"
+ if perf is not None and causes
else ""
)
# ``None`` when the repo has no hotspot files, so the segment is dropped
diff --git a/packages/core/src/repowise/core/generation/editor_files/data.py b/packages/core/src/repowise/core/generation/editor_files/data.py
index 252d10476..b02ac6e12 100644
--- a/packages/core/src/repowise/core/generation/editor_files/data.py
+++ b/packages/core/src/repowise/core/generation/editor_files/data.py
@@ -8,6 +8,10 @@ without any DB or filesystem dependency.
from __future__ import annotations
from dataclasses import dataclass, field
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from repowise.core.persistence.crud.analysis.performance import PerformanceHeadline
def _render_tool_table(*, keyless: bool = False) -> str:
@@ -85,14 +89,12 @@ class CodeHealthBlock:
# performance scores: static performance RISK). ``None`` when unmeasured, so
# the section omits the line rather than printing a misleading 10.0.
performance_average: float | None = None
- # Honest performance headline: the open finding count, its density per 10K
- # covered LOC, and how much of the analyzed code a perf detector actually ran
- # on. An agent reading a bare 9.9/10 should still see "N findings" and "perf
- # ran on X% of the code" so a mostly-unsupported-language repo never reads as
- # verified-fast. ``performance_coverage_pct`` is ``None`` when no code file
- # carries a supported language.
- performance_findings: int = 0
- performance_findings_density: float | None = None
+ # Honest performance headline: the open causes (worth fixing now, in
+ # production code, overall) and how much of the analyzed code a perf
+ # detector actually ran on, so a bare 9.9/10 on a mostly-unsupported-language
+ # repo never reads as verified-fast. ``performance_coverage_pct`` is ``None``
+ # when no code file carries a supported language.
+ performance_causes: PerformanceHeadline | None = None
performance_coverage_pct: float | None = None
performance_skipped_files: int = 0
performance_unsupported_languages: list[tuple[str, int]] = field(default_factory=list)
diff --git a/packages/core/src/repowise/core/generation/editor_files/fetcher.py b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
index 3200d366d..3505540ad 100644
--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py
+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
@@ -15,7 +15,6 @@ from pathlib import Path
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.analysis.finding_registry import excluded_types
from repowise.core.analysis.health.grading import (
BAND_LABEL,
analysed_note,
@@ -35,13 +34,11 @@ from repowise.core.generation.entry_points import (
from repowise.core.index_scope import load_index_scope, resolve_index_scope
from repowise.core.persistence import crud
from repowise.core.persistence.crud.analysis.fix_first import load_fix_first
-from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.models import (
DecisionRecord,
GitMetadata,
GraphNode,
HealthFileMetric,
- HealthFinding,
Page,
)
@@ -449,25 +446,10 @@ class EditorFileDataFetcher:
lang_by_path = await crud.get_file_language_map(self._session, self._repo_id)
perf_coverage = coverage_for_metrics(metric_rows, lang_by_path)
- # Open performance-finding count + density over covered LOC (the honest
- # headline the diluted /10 hides).
- performance_findings = (
- await self._session.execute(
- select(func.count()).where(
- HealthFinding.repository_id == self._repo_id,
- HealthFinding.status == "open",
- HealthFinding.dimension == "performance",
- HealthFinding.biomarker_type.not_in(excluded_types()),
- ungated("health", HealthFinding.file_path, HealthFinding.biomarker_type),
- )
- )
- ).scalar_one()
- performance_findings_density: float | None = None
- if perf_coverage.covered_nloc > 0:
- performance_findings_density = round(
- 10000.0 * performance_findings / perf_coverage.covered_nloc, 2
- )
-
+ # The causes worth fixing now lead; production and every cause are context.
+ performance_causes = await crud.performance_headline(
+ self._session, self._repo_id, covered_nloc=perf_coverage.covered_nloc
+ )
# The trend the snapshots record, or nothing: a repository indexed once
# has no trend, and the section used to print "stable" for it anyway.
@@ -490,8 +472,7 @@ class EditorFileDataFetcher:
performance_average=(
round(performance_average, 2) if performance_average is not None else None
),
- performance_findings=performance_findings,
- performance_findings_density=performance_findings_density,
+ performance_causes=performance_causes,
performance_coverage_pct=(
perf_coverage.pct_loc if perf_coverage.analyzed_files else None
),
diff --git a/packages/core/src/repowise/core/generation/templates/agents_md.j2 b/packages/core/src/repowise/core/generation/templates/agents_md.j2
index 528e49f26..3e30d9b31 100644
--- a/packages/core/src/repowise/core/generation/templates/agents_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/agents_md.j2
@@ -50,7 +50,7 @@ Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}
{% if data.code_health %}
### Code health
-Three co-equal signals: code health {{ data.code_health.average_health }}/10 avg{% if data.code_health.band or data.code_health.analysed_note %} ({{ [data.code_health.band, data.code_health.analysed_note] | select | join(', ') }}){% endif %}, hotspot health {{ data.code_health.hotspot_health }}/10{% if data.code_health.hotspot_trend %} ({{ data.code_health.hotspot_trend }}){% endif %}{% if data.code_health.worst_path %}, worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% endif %}{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% if data.code_health.performance_average is not none %} · performance risk {{ data.code_health.performance_findings }} open static performance finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% endif %}. Detail: `get_health()`.
+Three co-equal signals: code health {{ data.code_health.average_health }}/10 avg{% if data.code_health.band or data.code_health.analysed_note %} ({{ [data.code_health.band, data.code_health.analysed_note] | select | join(', ') }}){% endif %}, hotspot health {{ data.code_health.hotspot_health }}/10{% if data.code_health.hotspot_trend %} ({{ data.code_health.hotspot_trend }}){% endif %}{% if data.code_health.worst_path %}, worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% endif %}{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% set perf = data.code_health.performance_causes %}{% if data.code_health.performance_average is not none and perf %} · performance {{ perf.now }} cause{{ 's' if perf.now != 1 else '' }} worth fixing now ({{ perf.production }} open in production code, {{ perf.all }} overall){% endif %}. Detail: `get_health()`.
{% if data.code_health.fix_first %}
Fix first:
diff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2
index de72bda4e..879fe765e 100644
--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2
@@ -50,7 +50,7 @@ Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}
{% if data.code_health %}
### Code health
-Three co-equal signals: code health {{ data.code_health.average_health }}/10 avg{% if data.code_health.band or data.code_health.analysed_note %} ({{ [data.code_health.band, data.code_health.analysed_note] | select | join(', ') }}){% endif %}, hotspot health {{ data.code_health.hotspot_health }}/10{% if data.code_health.hotspot_trend %} ({{ data.code_health.hotspot_trend }}){% endif %}{% if data.code_health.worst_path %}, worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% endif %}{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% if data.code_health.performance_average is not none %} · performance risk {{ data.code_health.performance_findings }} open static performance finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% endif %}. Detail: `get_health()`.
+Three co-equal signals: code health {{ data.code_health.average_health }}/10 avg{% if data.code_health.band or data.code_health.analysed_note %} ({{ [data.code_health.band, data.code_health.analysed_note] | select | join(', ') }}){% endif %}, hotspot health {{ data.code_health.hotspot_health }}/10{% if data.code_health.hotspot_trend %} ({{ data.code_health.hotspot_trend }}){% endif %}{% if data.code_health.worst_path %}, worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% endif %}{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% set perf = data.code_health.performance_causes %}{% if data.code_health.performance_average is not none and perf %} · performance {{ perf.now }} cause{{ 's' if perf.now != 1 else '' }} worth fixing now ({{ perf.production }} open in production code, {{ perf.all }} overall){% endif %}. Detail: `get_health()`.
{% if data.code_health.fix_first %}
Fix first:
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
index f1d0c5a7f..bf129e6d0 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
@@ -112,6 +112,7 @@ from .performance import (
performance_area_counts,
performance_facet_counts,
performance_file_rollups,
+ performance_headline,
)
from .refactoring import (
count_refactoring_suggestions,
@@ -205,6 +206,7 @@ __all__ = [
"performance_area_counts",
"performance_facet_counts",
"performance_file_rollups",
+ "performance_headline",
"plan_payoff",
"prune_unscored_health_rows",
"ranked_refactoring_suggestions",
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health/summary.py b/packages/core/src/repowise/core/persistence/crud/analysis/health/summary.py
index 7ceba1e73..fbef333ae 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/health/summary.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health/summary.py
@@ -98,6 +98,7 @@ async def get_health_summary(
*,
metrics: list | None = None,
findings: list | None = None,
+ include_unverified: bool = False,
) -> dict:
"""Aggregate KPIs over the per-file metrics table.
@@ -112,6 +113,7 @@ async def get_health_summary(
``get_health_findings(repository_id)``, i.e. every open row for the repo,
post-exclusion. Handing over a *filtered* subset would silently skew
``open_findings`` and the per-dimension counts, which are repo headlines.
+ ``performance_causes`` counts language-gated causes only with *include_unverified*.
"""
if metrics is None:
metrics = await get_health_metrics(session, repository_id)
@@ -134,8 +136,7 @@ async def get_health_summary(
"structure_average": None,
"history_average": None,
"maintainability_findings": 0,
- "performance_findings": 0,
- "performance_findings_density": None,
+ "performance_causes": None,
"performance_coverage_pct": None,
"performance_covered_files": 0,
"performance_analyzed_files": 0,
@@ -180,18 +181,18 @@ async def get_health_summary(
# Perf coverage: honest denominator for the score. On a repo that is mostly a
# perf-unsupported language the aggregate perf average is meaningless, so we
- # surface how much of the analyzed code a detector actually ran on, plus a
- # findings-per-10K-LOC density over the *covered* lines (not the whole repo).
+ # surface how much of the analyzed code a detector actually ran on.
from .....analysis.health.perf.coverage import coverage_for_metrics
+ from ..performance import performance_headline
lang_by_path = await get_file_language_map(session, repository_id)
coverage = coverage_for_metrics(metrics, lang_by_path)
- performance_findings = by_dim.get("performance", 0)
- performance_findings_density: float | None = None
- if coverage.covered_nloc > 0:
- performance_findings_density = round(
- 10000.0 * performance_findings / coverage.covered_nloc, 2
- )
+ causes = await performance_headline(
+ session,
+ repository_id,
+ covered_nloc=coverage.covered_nloc,
+ include_unverified=include_unverified,
+ )
return {
"file_count": len(metrics),
"unanalysed_file_count": unanalysed,
@@ -207,8 +208,7 @@ async def get_health_summary(
"structure_average": _rounded(nloc_weighted_attr(metrics, "structure_deduction")),
"history_average": _rounded(nloc_weighted_attr(metrics, "history_deduction")),
"maintainability_findings": by_dim.get("maintainability", 0),
- "performance_findings": performance_findings,
- "performance_findings_density": performance_findings_density,
+ "performance_causes": causes.as_dict(),
"performance_coverage_pct": (coverage.pct_loc if coverage.analyzed_files else None),
"performance_covered_files": coverage.covered_files,
"performance_analyzed_files": coverage.analyzed_files,
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/performance.py b/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
index 0a4f29537..98ab631df 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
@@ -655,6 +655,51 @@ async def performance_facet_counts(
return [tuple(row) for row in result.all()]
+class PerformanceHeadline(NamedTuple):
+ """The performance headline every surface prints, in the Performance
+ view's three scopes: the default queue (worth fixing now) leads, and every
+ production cause and every cause give it context."""
+
+ now: int
+ production: int
+ all: int
+ per_10k_loc: float | None
+ """Every cause per 10K lines a performance detector ran on; ``None`` with none."""
+
+ def as_dict(self) -> dict[str, Any]:
+ return self._asdict()
+
+
+async def performance_headline(
+ session: AsyncSession,
+ repository_id: str,
+ *,
+ covered_nloc: int,
+ include_unverified: bool = False,
+) -> PerformanceHeadline:
+ """The one count of open performance causes, read by every surface.
+
+ The scope sizes the Performance view's scope control shows, from the same
+ grouped aggregate, so a headline never states a number that view
+ contradicts. *covered_nloc* is the caller's ``PerfCoverage.covered_nloc``.
+ """
+ from ....analysis.health.perf.serving import scope_counts
+ from .queue_counts import any_unjudged
+
+ groups = await performance_facet_counts(
+ session, repository_id, include_unverified=include_unverified, scoped=True
+ )
+ judged = not await any_unjudged(session, repository_id, "causes")
+ scopes = scope_counts(groups, judged=judged)
+ every = scopes["all"]
+ return PerformanceHeadline(
+ now=scopes["now"],
+ production=scopes["production"],
+ all=every,
+ per_10k_loc=round(10000.0 * every / covered_nloc, 2) if covered_nloc > 0 else None,
+ )
+
+
async def performance_area_counts(
session: AsyncSession,
repository_id: str,
@@ -692,6 +737,10 @@ class PerformanceFileRollup(NamedTuple):
expected: int
best_rank: int
"""Lowest ``rank_position`` on the file, so a map can rank files by cause."""
+ queued: int = 0
+ """Causes in the default queue: what a map colours, as the headline leads with them."""
+ queued_states: frozenset[str] = frozenset()
+ """The actionability states among those queued causes."""
async def gated_performance_counts(
@@ -709,39 +758,17 @@ async def gated_performance_counts(
)
-async def performance_file_rollups(
- session: AsyncSession,
- repository_id: str,
- *,
- file_paths: tuple[str, ...] | None = None,
-) -> list[PerformanceFileRollup]:
- """Per-file burden for every file carrying an open opportunity.
-
- One indexed aggregate over ``(repository_id, status, file_path)`` returning
- at most three rows per file rather than one per observation, so a caller
- that needs the whole repository still pays a grouped scan and not a
- per-file query. Ordered best-rank first, which is the order a bounded map
- feed admits files in.
- """
- where = _predicates(repository_id, file_paths=file_paths)
- result = await session.execute(
- select(
- PerformanceOpportunity.file_path,
- PerformanceOpportunity.actionability_state,
- func.count(),
- func.sum(PerformanceOpportunity.observations_total),
- func.min(PerformanceOpportunity.rank_position),
- )
- .where(*where)
- .group_by(
- PerformanceOpportunity.file_path,
- PerformanceOpportunity.actionability_state,
- )
- )
+def _fold_rollups(groups: Any) -> list[PerformanceFileRollup]:
+ """One rollup per file from the grouped ``performance_file_rollups`` rows."""
folded: dict[str, dict[str, int]] = {}
- for path, state, count, observations, best_rank in result.all():
+ queued_states: dict[str, set[str]] = {}
+ for path, state, count, observations, best_rank, eligible in groups:
if not path:
continue
+ # The stored verdict: a row stored before causes were judged counts as
+ # not queued until the next index judges it.
+ if eligible:
+ queued_states.setdefault(path, set()).add(state)
row = folded.setdefault(
path,
{
@@ -752,8 +779,10 @@ async def performance_file_rollups(
"investigate": 0,
"expected": 0,
"best_rank": best_rank or 0,
+ "queued": 0,
},
)
+ row["queued"] += int(count or 0) if eligible else 0
row["opportunities"] += int(count or 0)
row["observations"] += int(observations or 0)
if state in _ACTIONABILITY_STATES:
@@ -769,9 +798,46 @@ async def performance_file_rollups(
investigate=row["investigate"],
expected=row["expected"],
best_rank=row["best_rank"],
+ queued=row["queued"],
+ queued_states=frozenset(queued_states.get(path, ())),
)
for path, row in folded.items()
]
+ return rollups
+
+
+async def performance_file_rollups(
+ session: AsyncSession,
+ repository_id: str,
+ *,
+ file_paths: tuple[str, ...] | None = None,
+) -> list[PerformanceFileRollup]:
+ """Per-file burden for every file carrying an open opportunity.
+
+ One indexed aggregate over ``(repository_id, status, file_path)`` returning
+ a few rows per file rather than one per observation, so a caller
+ that needs the whole repository still pays a grouped scan and not a
+ per-file query. Ordered best-rank first, which is the order a bounded map
+ feed admits files in.
+ """
+ where = _predicates(repository_id, file_paths=file_paths)
+ result = await session.execute(
+ select(
+ PerformanceOpportunity.file_path,
+ PerformanceOpportunity.actionability_state,
+ func.count(),
+ func.sum(PerformanceOpportunity.observations_total),
+ func.min(PerformanceOpportunity.rank_position),
+ PerformanceOpportunity.queue_eligible,
+ )
+ .where(*where)
+ .group_by(
+ PerformanceOpportunity.file_path,
+ PerformanceOpportunity.actionability_state,
+ PerformanceOpportunity.queue_eligible,
+ )
+ )
+ rollups = _fold_rollups(result.all())
# Best rank first, then path, so the order a cap is applied against is
# total and does not move between two reads of the same store.
rollups.sort(key=lambda r: (r.best_rank, r.file_path))
@@ -916,6 +982,7 @@ async def get_health_finding_by_public_id(
__all__ = [
+ "PerformanceHeadline",
"finalize_performance_opportunities",
"gated_performance_counts",
"get_health_finding_by_public_id",
@@ -927,4 +994,5 @@ __all__ = [
"list_performance_opportunities",
"opportunity_details",
"performance_facet_counts",
+ "performance_headline",
]
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py b/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py
index 2ffd84c4c..8bb7cf87e 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py
@@ -82,7 +82,7 @@ def _dashboard_blocks(data: HealthData, req: HealthRequest, pager: Pager) -> dic
"kpis": lambda: _compute_kpis(
all_metrics,
hotspot_paths=data.hotspot_paths,
- performance_findings=data.perf_findings_count,
+ performance_causes=data.perf_causes,
coverage=data.perf_coverage,
unanalysed=len(pop.unanalysed_paths),
deductions=data.deductions,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
index 5437a3c5a..4741efd41 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
@@ -43,6 +43,10 @@ from repowise.core.persistence.crud import (
load_coverage_history,
)
from repowise.core.persistence.crud.analysis.fix_first import load_fix_first, queue_view
+from repowise.core.persistence.crud.analysis.performance import (
+ PerformanceHeadline,
+ performance_headline,
+)
from repowise.core.persistence.crud.analysis.queue_counts import unit_counts
from repowise.core.persistence.crud.analysis.refactoring import gated_plan_counts
from repowise.core.persistence.models import HealthFileMetric
@@ -88,7 +92,7 @@ class HealthData:
leads: dict[str, dict[str, Any]]
hotspot_paths: set[str] = field(default_factory=set)
perf_coverage: PerfCoverage | None = None
- perf_findings_count: int = 0
+ perf_causes: PerformanceHeadline | None = None
accuracy_rows: list[Any] = field(default_factory=list)
#: The queue's plans, read only when ``refactoring_plans`` is named.
refactoring_plans: RefactoringPlanPage | None = None
@@ -166,8 +170,8 @@ async def load_health_data(
),
)
data.hotspot_paths = await _read_hotspot_paths(session, repository, pop, req)
- data.perf_coverage, data.perf_findings_count = await _read_perf_headline(
- session, repository, pop, req, findings.lead_rows
+ data.perf_coverage, data.perf_causes = await _read_perf_headline(
+ session, repository, pop, req
)
data.accuracy_rows = await read_accuracy_rows(session, repository, pop, req)
data.refactoring_plans, data.refactoring_plans_ignored = await _read_refactoring_plans(
@@ -273,18 +277,22 @@ async def _read_hotspot_paths(
async def _read_perf_headline(
- session: Any, repository: Any, pop: Population, req: HealthRequest, lead_rows: list[Any]
-) -> tuple[PerfCoverage | None, int]:
+ session: Any, repository: Any, pop: Population, req: HealthRequest
+) -> tuple[PerfCoverage | None, PerformanceHeadline | None]:
"""Dashboard perf headline: coverage (how much of the analyzed code the
- perf pass ran on) + open performance-finding count. Both feed ``kpis``
- alone, so a projection that drops kpis skips the language-map read."""
+ perf pass ran on) + the open causes, as every surface counts them. Both
+ feed ``kpis`` alone, so a projection that drops kpis skips both reads."""
if pop.scoped or not req.wants("kpis"):
- return None, 0
+ return None, None
lang_by_path = await get_file_language_map(session, repository.id)
- return (
- coverage_for_metrics(pop.all_metrics, lang_by_path),
- sum(1 for f in lead_rows if (f.dimension or "defect") == "performance"),
+ coverage = coverage_for_metrics(pop.all_metrics, lang_by_path)
+ causes = await performance_headline(
+ session,
+ repository.id,
+ covered_nloc=coverage.covered_nloc,
+ include_unverified=req.include_unverified,
)
+ return coverage, causes
async def _read_refactoring_plans(
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 59950e3f9..ef5414a96 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
@@ -15,6 +15,7 @@ from repowise.core.analysis.health.scoring import (
nloc_weighted_attr,
nloc_weighted_score,
)
+from repowise.core.persistence.crud.analysis.performance import PerformanceHeadline
from repowise.core.persistence.models import HealthFileMetric
@@ -128,18 +129,16 @@ def _gap_analysis(metrics: list[HealthFileMetric]) -> dict[str, Any]:
}
-def _perf_kpis(performance_findings: int, coverage: PerfCoverage | None) -> dict[str, Any]:
- """The honest performance headline: finding count + density + coverage.
+def _perf_kpis(
+ causes: PerformanceHeadline | None, coverage: PerfCoverage | None
+) -> dict[str, Any]:
+ """The honest performance headline: the open causes + coverage.
Says how much of the code the perf pass ran on, so a bare
``performance_average`` near 10 is not read as "fast" on thin coverage.
"""
- density: float | None = None
- if coverage is not None and coverage.covered_nloc > 0:
- density = round(10000.0 * performance_findings / coverage.covered_nloc, 2)
return {
- "performance_findings": performance_findings,
- "performance_findings_density_per_10k_loc": density,
+ "performance_causes": causes.as_dict() if causes is not None else None,
"performance_coverage_pct": (
coverage.pct_loc if (coverage and coverage.analyzed_files) else None
),
@@ -160,7 +159,7 @@ def _compute_kpis(
metrics: list[HealthFileMetric],
*,
hotspot_paths: set[str] | None = None,
- performance_findings: int = 0,
+ performance_causes: PerformanceHeadline | None = None,
coverage: PerfCoverage | None = None,
unanalysed: int = 0,
deductions: dict[str, float],
@@ -184,7 +183,7 @@ def _compute_kpis(
"performance_average": None,
"structure_average": None,
"history_average": None,
- **_perf_kpis(0, None),
+ **_perf_kpis(None, None),
}
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
@@ -217,6 +216,6 @@ def _compute_kpis(
# The headline's code-shape and history halves, in deduction points.
"structure_average": _avg(metrics, "structure_deduction"),
"history_average": _avg(metrics, "history_deduction"),
- # Performance leads with count + density + coverage, not the diluted /10.
- **_perf_kpis(performance_findings, coverage),
+ # Performance leads with the causes worth fixing now and coverage, not the diluted /10.
+ **_perf_kpis(performance_causes, coverage),
}
diff --git a/packages/server/src/repowise/server/routers/code_health/files_routes.py b/packages/server/src/repowise/server/routers/code_health/files_routes.py
index 2b4a5078a..f089ba895 100644
--- a/packages/server/src/repowise/server/routers/code_health/files_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/files_routes.py
@@ -100,17 +100,13 @@ async def list_health_files(
total = len(filtered)
page = filtered[offset : offset + limit]
summary = fields == "summary"
- # Two reads, and ``summary`` needs only the narrow one. The full row's
- # dominant-cause lead is reduced from *every* open finding (this repo: 10,740
- # rows, 1.66 MB of ``details_json`` hydrated to reach four attributes), while
- # the performance lens needs only the perf dimension (697 rows). A caller
- # that does not print the lead should not pay for the wide read to compute
- # it — the map is exactly that caller, and it is the biggest request the
- # page makes.
+ # The full row's dominant-cause lead is reduced from *every* open finding
+ # (this repo: 10,740 rows, 1.66 MB of ``details_json`` hydrated to reach four
+ # attributes). A caller that does not print the lead should not pay for the
+ # wide read to compute it — the map is exactly that caller, and it is the
+ # biggest request the page makes.
leads: dict[str, dict] = {}
- if summary:
- findings = await crud.get_health_findings(session, repo_id, dimension="performance")
- else:
+ if not summary:
# History markers kept: a file's lead names what its score counted, so a
# history-only file scoring below 10 still has one.
findings = await crud.get_health_findings(session, repo_id, hold_history=False)
@@ -118,13 +114,10 @@ async def list_health_files(
# and the magnitude tiebreak without loading every finding for every row.
page_paths = {m.file_path for m in page}
leads = _leads_by_file([f for f in findings if f.file_path in page_paths])
- # Per-file performance signal for the map's performance lens: open perf-
- # finding counts + whether a perf detector ran on the file's language. Colors
- # the lens by findings/coverage instead of the narrow-band [8,10] score.
- perf_counts: dict[str, int] = {}
- for fnd in findings:
- if (getattr(fnd, "dimension", None) or "defect") == "performance":
- perf_counts[fnd.file_path] = perf_counts.get(fnd.file_path, 0) + 1
+ # Per-file performance signal for the map's performance lens: causes in the
+ # default queue (what the performance headline leads with) + whether a perf
+ # detector ran on the file's language, instead of the narrow-band score.
+ queued = {r.file_path: r.queued for r in await crud.performance_file_rollups(session, repo_id)}
lang_by_path = await crud.get_file_language_map(session, repo_id)
perf_langs = supported_perf_languages()
return {
@@ -136,7 +129,7 @@ async def list_health_files(
_metric_to_dict(
m,
leads.get(m.file_path),
- perf_findings=perf_counts.get(m.file_path, 0),
+ perf_opportunities=queued.get(m.file_path, 0),
perf_analyzed=lang_by_path.get(m.file_path) in perf_langs,
summary=summary,
),
diff --git a/packages/server/src/repowise/server/routers/code_health/overview_routes.py b/packages/server/src/repowise/server/routers/code_health/overview_routes.py
index 45f814626..37887e921 100644
--- a/packages/server/src/repowise/server/routers/code_health/overview_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/overview_routes.py
@@ -95,7 +95,11 @@ async def health_overview(
files=files,
)
summary = await crud.get_health_summary(
- session, repo_id, metrics=metrics, findings=kpi_findings
+ session,
+ repo_id,
+ metrics=metrics,
+ findings=kpi_findings,
+ include_unverified=include_unverified,
)
# Recomputed from the metrics already loaded rather than read off the latest
diff --git a/packages/server/src/repowise/server/routers/code_health/serializers.py b/packages/server/src/repowise/server/routers/code_health/serializers.py
index a34ef90ce..81a9edeaf 100644
--- a/packages/server/src/repowise/server/routers/code_health/serializers.py
+++ b/packages/server/src/repowise/server/routers/code_health/serializers.py
@@ -61,7 +61,7 @@ def _metric_to_dict(
m: Any,
lead: dict | None = None,
*,
- perf_findings: int = 0,
+ perf_opportunities: int = 0,
perf_analyzed: bool | None = None,
summary: bool = False,
) -> dict:
@@ -101,11 +101,11 @@ def _metric_to_dict(
# ``performance_score`` is computed but not yet surfaced as its own pillar.
out["maintainability_score"] = _round_opt(getattr(m, "maintainability_score", None))
out["performance_score"] = _round_opt(getattr(m, "performance_score", None))
- # Performance lens inputs for the code-health map: the open perf-finding
- # count colors the heat, and ``perf_analyzed`` (did a detector run on this
- # language?) separates green ("analyzed, none found") from grey ("never
+ # Performance lens inputs for the code-health map: the file's causes in the
+ # default queue color the heat, and ``perf_analyzed`` (did a detector run on
+ # this language?) separates green ("analyzed, none found") from grey ("never
# looked"). Presentation only — the score above is untouched.
- out["performance_findings"] = perf_findings
+ out["performance_opportunities"] = perf_opportunities
out["performance_analyzed"] = perf_analyzed
if not summary:
# The headline's two halves, and the score the file would carry without
diff --git a/packages/server/src/repowise/server/services/health_map.py b/packages/server/src/repowise/server/services/health_map.py
index 478f50e2e..272ef00ce 100644
--- a/packages/server/src/repowise/server/services/health_map.py
+++ b/packages/server/src/repowise/server/services/health_map.py
@@ -9,8 +9,8 @@ small file can hold the worst cause in the tree.
So the feed admits files in a fixed order - the caller's pinned paths first,
then a small floor per module so a little module never vanishes behind a big
one, then everything else by origin tier (production, tooling and build, test,
-docs examples), and inside a tier the files carrying open performance
-opportunities in rank order before a health-debt rank that puts unhealthy, large
+docs examples), and inside a tier the files carrying a performance cause in
+the default queue, in rank order, before a health-debt rank that puts unhealthy, large
files ahead of clean ones. Vendored and generated files are held out unless the
caller asks for them, because they are not the reader's to change. The response
states exactly what the cap and the hold pushed out. One response carries both
@@ -207,8 +207,9 @@ class HealthMapService:
eligible_paths = {m.file_path for m in eligible}
burden = {r.file_path: r for r in rollups}
- # A file whose only causes are ``expected`` has nothing to do; it earns no priority slot.
- open_rollups = [r for r in rollups if r.opportunities > r.expected]
+ # A file earns a priority slot with a cause in the default queue, the
+ # count the performance headline leads with; the rest wait in the queue view.
+ open_rollups = [r for r in rollups if r.queued]
perf_position = {
r.file_path: i for i, r in enumerate(open_rollups) if r.file_path in eligible_paths
}
@@ -277,7 +278,7 @@ class HealthMapService:
omitted = {
"files": len(eligible) - len(chosen),
"performance_files": len(undrawn_perf),
- "opportunities": sum(r.opportunities - r.expected for r in undrawn_perf),
+ "opportunities": sum(r.queued for r in undrawn_perf),
"observations": sum(r.observations for r in undrawn_perf),
# Drawable, and left out by the vendored/generated hold, not the cap.
"held": held_out,
@@ -364,8 +365,9 @@ class HealthMapService:
"has_test_file": metric.has_test_file,
"maintainability_score": metric.maintainability_score,
"performance_analyzed": languages.get(metric.file_path) in perf_languages,
- # What the default queue shows: ``expected`` causes have nothing to do.
- "performance_opportunities": rollup.opportunities - rollup.expected if rollup else 0,
+ # What the default queue shows, so the lens and the headline agree.
+ # Observations stay every open one on the file: evidence, not a count to act on.
+ "performance_opportunities": rollup.queued if rollup else 0,
"performance_observations": rollup.observations if rollup else 0,
"code_origin": metric.code_origin,
"is_hotspot": metric.file_path in hotspots,
@@ -400,7 +402,7 @@ class HealthMapService:
file_burden = burden.get(metric.file_path)
if file_burden is None:
continue
- row["opportunities"] += file_burden.opportunities
+ row["opportunities"] += file_burden.queued
row["observations"] += file_burden.observations
row["plan_ready"] += file_burden.plan_ready
best = row["best_rank"]
@@ -424,7 +426,8 @@ class HealthMapService:
``None`` means this index has never materialized the read model, which
is a different answer from "analyzed and nothing surfaced" and the lens
- must not render the two the same way.
+ must not render the two the same way. Its totals are the repository's
+ whole inventory, every context and state; the nodes count the queue.
"""
if summary is None and not rollups:
return None
@@ -476,9 +479,11 @@ def _leading_actionability(rollup: Any) -> str | None:
"""The best thing a reader could do about this file, or nothing.
Best rather than most common: a file with one stored plan and nine
- investigations is a file with a stored plan.
+ investigations is a file with a stored plan. Read over the queued causes,
+ the ones the lens counts.
"""
if rollup is None:
return None
# ``expected`` is never a lead: it has nothing to do.
- return next((s for s in ACTIONABILITY_ORDER if s != "expected" and getattr(rollup, s)), None)
+ states = rollup.queued_states
+ return next((s for s in ACTIONABILITY_ORDER if s != "expected" and s in states), None)
diff --git a/packages/server/src/repowise/server/services/overview_payload.py b/packages/server/src/repowise/server/services/overview_payload.py
index c3debace6..2b55fb2df 100644
--- a/packages/server/src/repowise/server/services/overview_payload.py
+++ b/packages/server/src/repowise/server/services/overview_payload.py
@@ -309,7 +309,8 @@ async def health_block(
# The two co-equal pillars surfaced alongside the defect headline.
"maintainability_average": summary.get("maintainability_average"),
"performance_average": summary.get("performance_average"),
- "performance_findings": summary.get("performance_findings", 0),
+ # Open causes: worth fixing now, in production code, overall.
+ "performance_causes": summary.get("performance_causes"),
"worst_performance_path": summary.get("worst_performance_path"),
"worst_performance_score": summary.get("worst_performance_score"),
"severity_breakdown": health_severity_breakdown(findings),
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index a49075ce4..ff8419754 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -296,13 +296,6 @@ export interface HealthFileMetric {
* before the column existed; absent on payloads that do not carry it.
*/
code_origin?: string | null;
- /**
- * Open performance-risk findings on this file. The performance lens on the
- * code-health map colors by this count (+ `performance_analyzed`), not by the
- * [9,10]-compressed `performance_score`, so a file with 40 N+1s reads
- * differently from one with 1. Absent on payloads predating the perf pass.
- */
- performance_findings?: number | null;
/**
* Whether a performance detector actually ran on this file (its language has a
* registered perf dialect). `false` = unsupported language, the perf pass never
@@ -803,6 +796,19 @@ export interface BiomarkerBreakdownRow {
* Overview
* ------------------------------------------------------------------ */
+/**
+ * The performance headline every surface prints, in the Performance view's
+ * three scopes: `now` (the default queue, worth fixing now) leads, and
+ * `production` and `all` open causes give it context.
+ */
+export interface PerformanceCauses {
+ now: number;
+ production: number;
+ all: number;
+ /** Every open cause per 10K lines a performance detector ran on. */
+ per_10k_loc: number | null;
+}
+
export interface HealthOverviewSummary {
file_count: number;
/** `null` when no file is scored: every file is in a language health has no
@@ -848,10 +854,11 @@ export interface HealthOverviewSummary {
*/
performance_average?: number | null;
performance_hotspot?: number | null;
- /** Open findings homing under the maintainability / performance pillars — the
- * per-pillar actionable counts. Absent on payloads predating the split. */
+ /** Open findings homing under the maintainability pillar. Absent on payloads
+ * predating the split. */
maintainability_findings?: number;
- performance_findings?: number;
+ /** Open performance causes, as every surface counts them; `null` with no files. */
+ performance_causes?: PerformanceCauses | null;
/** Lowest-scoring file by performance risk, surfaced only when score < 10
* (a clean repo returns `null` rather than a misleading "worst" at 10.0). */
worst_performance_path?: string | null;
diff --git a/packages/types/src/overview.ts b/packages/types/src/overview.ts
index cb633be73..61757128a 100644
--- a/packages/types/src/overview.ts
+++ b/packages/types/src/overview.ts
@@ -5,7 +5,12 @@
*/
import type { Hotspot } from "./git.js";
-import type { DefectAccuracy, HealthBand, HealthSeverity } from "./health.js";
+import type {
+ DefectAccuracy,
+ HealthBand,
+ HealthSeverity,
+ PerformanceCauses,
+} from "./health.js";
import type { QueueCounts } from "./queue.js";
export interface OverviewRepoMeta {
@@ -101,8 +106,8 @@ export interface OverviewHealth {
/** Co-equal performance pillar headline: static performance RISK (I/O-in-loop
* / N+1). `null` when not yet measured. */
performance_average?: number | null;
- /** Open findings homing under the performance pillar — the actionable count. */
- performance_findings?: number;
+ /** Open performance causes: worth fixing now, in production code, overall. */
+ performance_causes?: PerformanceCauses | null;
/** Lowest-scoring file by performance risk, surfaced only when score < 10. */
worst_performance_path?: string | null;
worst_performance_score?: number | null;
diff --git a/packages/ui/__tests__/dashboard/health-overview-card.test.tsx b/packages/ui/__tests__/dashboard/health-overview-card.test.tsx
index f2fb1ac95..b1420469c 100644
--- a/packages/ui/__tests__/dashboard/health-overview-card.test.tsx
+++ b/packages/ui/__tests__/dashboard/health-overview-card.test.tsx
@@ -29,3 +29,39 @@ describe("HealthOverviewCard band", () => {
expect(container.textContent).toContain("Excellent");
});
});
+
+describe("HealthOverviewCard performance", () => {
+ const perf = {
+ maintainability_average: 8.1,
+ performance_average: 9.76,
+ };
+
+ it("leads with the causes worth fixing now and keeps production as context", () => {
+ const { container } = render(
+ <HealthOverviewCard
+ data={data({
+ ...perf,
+ performance_causes: { now: 4, production: 415, all: 926, per_10k_loc: 9.03 },
+ })}
+ repoId="r"
+ />,
+ );
+ const text = container.textContent ?? "";
+ expect(text).toContain("4worth fixing now");
+ expect(text).toContain("415 in production");
+ expect(text).not.toContain("926");
+ });
+
+ it("is all clear only when no production cause is open", () => {
+ const waiting = render(
+ <HealthOverviewCard
+ data={data({
+ ...perf,
+ performance_causes: { now: 0, production: 12, all: 20, per_10k_loc: 1 },
+ })}
+ repoId="r"
+ />,
+ );
+ expect(waiting.container.textContent).toContain("0worth fixing now");
+ });
+});
diff --git a/packages/ui/__tests__/health/code-health-lede.test.tsx b/packages/ui/__tests__/health/code-health-lede.test.tsx
index 949507699..29adcef92 100644
--- a/packages/ui/__tests__/health/code-health-lede.test.tsx
+++ b/packages/ui/__tests__/health/code-health-lede.test.tsx
@@ -9,7 +9,7 @@ function summary(partial: Partial<HealthOverviewSummary> = {}): HealthOverviewSu
maintainability_average: 8.0,
hotspot_health: 4.5,
performance_average: 9.7,
- performance_findings: 942,
+ performance_causes: { now: 4, production: 415, all: 926, per_10k_loc: 9.03 },
file_count: 3787,
open_findings: 14755,
structure_average: 1.59,
@@ -55,11 +55,16 @@ describe("CodeHealthLede — how many scores the first screen carries", () => {
it("gives every figure an explainer a reader can open", () => {
render(<CodeHealthLede summary={summary()} />);
- for (const label of ["Code health", "Files", "Maintainability", "Performance risk", "Hotspot health"]) {
+ for (const label of ["Code health", "Files", "Maintainability", "Performance, fix now", "Hotspot health"]) {
expect(screen.getByLabelText(`What ${label} means`)).toBeTruthy();
}
});
+ it("leads performance with the causes worth fixing now", () => {
+ const { container } = render(<CodeHealthLede summary={summary()} />);
+ expect(container.textContent).toContain("Performance, fix now4");
+ });
+
it("says nothing when the split was never recorded", () => {
const { container } = render(
<CodeHealthLede summary={summary({ structure_average: null, history_average: null })} />,
diff --git a/packages/ui/__tests__/health/map-lens.test.tsx b/packages/ui/__tests__/health/map-lens.test.tsx
index 06733017e..69e6641f0 100644
--- a/packages/ui/__tests__/health/map-lens.test.tsx
+++ b/packages/ui/__tests__/health/map-lens.test.tsx
@@ -167,7 +167,7 @@ describe("scope disclosure", () => {
it("names the files with causes the cap pushed out", () => {
const { getByTestId } = render(<CodeHealthMap files={[f("a.py", 10, "core")]} scope={scope} />);
- expect(getByTestId("map-scope").textContent).toContain("3 files with open causes not drawn");
+ expect(getByTestId("map-scope").textContent).toContain("3 files with causes worth fixing now not drawn");
});
it("says so when the cap left no cause behind", () => {
@@ -178,7 +178,7 @@ describe("scope disclosure", () => {
/>,
);
expect(getByTestId("map-scope").textContent).toContain(
- "every file with an open cause is drawn",
+ "every file with a cause worth fixing now is drawn",
);
});
@@ -382,7 +382,7 @@ describe("the navigable list beside the field", () => {
<MapFieldList files={files} overlay="performance" onSelectFile={vi.fn()} scope={scope} />,
);
expect(getAllByRole("button")).toHaveLength(2);
- expect(getByText(/3 more carry causes outside the drawn field/)).toBeInTheDocument();
+ expect(getByText(/3 more carry causes worth fixing now outside the drawn field/)).toBeInTheDocument();
});
it("says plainly when the drawn field carries none", () => {
diff --git a/packages/ui/__tests__/health/triage-view-lead.test.tsx b/packages/ui/__tests__/health/triage-view-lead.test.tsx
index d52c6b538..25ba577b2 100644
--- a/packages/ui/__tests__/health/triage-view-lead.test.tsx
+++ b/packages/ui/__tests__/health/triage-view-lead.test.tsx
@@ -18,7 +18,7 @@ const overview = {
maintainability_average: 8.0,
hotspot_health: 4.5,
performance_average: 9.7,
- performance_findings: 942,
+ performance_causes: { now: 4, production: 415, all: 926, per_10k_loc: 9.03 },
file_count: 3787,
open_findings: 14755,
},
diff --git a/packages/ui/src/dashboard/health-overview-card.tsx b/packages/ui/src/dashboard/health-overview-card.tsx
index a86060c88..a15967f2d 100644
--- a/packages/ui/src/dashboard/health-overview-card.tsx
+++ b/packages/ui/src/dashboard/health-overview-card.tsx
@@ -15,7 +15,7 @@ import { AllClearStat } from "../shared/empty-state";
import { FilePath } from "../shared/file-path";
import { healthBand, SEVERITY_LABEL, SEVERITY_SEGMENT, type Severity } from "../health/tokens";
import { ProportionBar } from "../shared/proportion-bar";
-import { formatScore, type HealthBand } from "@repowise-dev/types/health";
+import { formatScore, type HealthBand, type PerformanceCauses } from "@repowise-dev/types/health";
import { Sparkline } from "../health/sparkline";
export interface HealthOverviewPoint {
@@ -42,8 +42,9 @@ export interface HealthOverviewData {
maintainability_average?: number | null;
/** Co-equal performance pillar headline (1–10, static risk), null until measured. */
performance_average?: number | null;
- /** Open findings homing under the performance pillar — the actionable count. */
- performance_findings?: number;
+ /** Open performance causes: worth fixing now (the default queue), in
+ * production code, and overall. */
+ performance_causes?: PerformanceCauses | null;
/** Snapshot history, oldest→newest, for the trend sparkline. */
history: HealthOverviewPoint[];
snapshot_count: number;
@@ -382,7 +383,7 @@ export function HealthOverviewCard({
<PerformancePillarStat
href={`${reportHref}?pillar=performance`}
score={data.performance_average ?? null}
- findings={data.performance_findings ?? 0}
+ causes={data.performance_causes ?? null}
/>
</div>
)}
@@ -435,18 +436,21 @@ function PillarStat({
);
}
-/** Performance is a risk pillar, so its cell leads with the count of open risks
- * (the actionable read) and keeps the /10 score as a quiet secondary line. */
+/** Performance is a risk pillar, so its cell leads with the causes worth fixing
+ * now (the default queue), then how many are open in production code, and
+ * keeps the /10 score as a quiet secondary line. */
function PerformancePillarStat({
href,
score,
- findings,
+ causes,
}: {
href: string;
score: number | null;
- findings: number;
+ causes: PerformanceCauses | null;
}) {
- const clear = score != null && findings === 0;
+ const now = causes?.now ?? 0;
+ const production = causes?.production ?? 0;
+ const clear = score != null && now === 0 && production === 0;
return (
<a
href={href}
@@ -463,13 +467,11 @@ function PerformancePillarStat({
) : (
<span className="flex items-baseline gap-1.5">
<span className="text-xl font-bold tabular-nums leading-none text-[var(--color-text-primary)]">
- {findings.toLocaleString()}
- </span>
- <span className="text-xs text-[var(--color-text-secondary)]">
- {findings === 1 ? "risk" : "risks"}
+ {now.toLocaleString()}
</span>
+ <span className="text-xs text-[var(--color-text-secondary)]">worth fixing now</span>
<span className="text-[10px] tabular-nums text-[var(--color-text-tertiary)]">
- · {formatScore(score)}/10
+ · {production.toLocaleString()} in production · {formatScore(score)}/10
</span>
</span>
)}
diff --git a/packages/ui/src/health/code-health-lede.tsx b/packages/ui/src/health/code-health-lede.tsx
index ea5d9f55e..7576f46f1 100644
--- a/packages/ui/src/health/code-health-lede.tsx
+++ b/packages/ui/src/health/code-health-lede.tsx
@@ -10,8 +10,8 @@
* place in the ribbon, beside the other cuts of the same scoring.
*
* Every figure carries an explainer. A number a reader cannot define is a
- * number they cannot act on, and "Performance risk 942" beside "Hotspot health
- * 4.5" reads as two scores when one is a count that only goes up.
+ * number they cannot act on, and "Performance, fix now 4" beside "Hotspot health
+ * 4.5" reads as two scores when one is a count.
*
* The prose is not decoration. "329 risks" reads as alarming on its own;
* "329 static performance risks, scored separately and never blended into the
@@ -27,6 +27,7 @@ import {
type DefectAccuracy,
type HealthDistribution,
type HealthOverviewSummary,
+ type PerformanceCauses,
} from "@repowise-dev/types/health";
import { PageLede } from "../shared/page-lede";
import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";
@@ -62,11 +63,20 @@ const MAINTAINABILITY_HINT =
"how hard the code is to work with rather than for bug risk. It counts no " +
"tests and no change history, so it is the figure a refactor moves.";
-const PERFORMANCE_HINT =
- "A count of open performance risks, not a score — it counts up as the analyzer " +
- "finds more and falls only when they are fixed. Each one is a database, " +
- "network, filesystem or subprocess call inside a loop, traced across function " +
- "boundaries. Never blended into the health score.";
+/** The performance stat's explainer, with the counts that give "now" its context. */
+function performanceHint(causes: PerformanceCauses | null | undefined): string {
+ const context = causes
+ ? ` Of ${formatNumber(causes.production)} open in production code, ` +
+ `${formatNumber(causes.all)} overall.`
+ : "";
+ return (
+ "Performance causes worth fixing now, a count rather than a score: the " +
+ "Performance view's default queue, where a database, network, filesystem or " +
+ "subprocess call inside a loop has a cost we can show." +
+ context +
+ " Never blended into the health score."
+ );
+}
const HOTSPOT_HINT =
"Code health averaged over the repo's churn hotspots — the files you change " +
@@ -144,7 +154,7 @@ export function CodeHealthLede({
if (health == null) return <UnanalysedLede action={action} />;
const maint = summary.maintainability_average;
const perf = summary.performance_average;
- const perfFindings = summary.performance_findings ?? 0;
+ const perfCauses = summary.performance_causes;
const hotspot = summary.hotspot_health;
const worstTestPath = summary.worst_test_path;
const worstTestScore = summary.worst_test_score;
@@ -192,9 +202,9 @@ export function CodeHealthLede({
highlighted: pillar === "maintainability",
},
{
- label: "Performance risk",
- value: perf == null ? "" : formatNumber(perfFindings),
- hint: PERFORMANCE_HINT,
+ label: "Performance, fix now",
+ value: perf == null ? "" : formatNumber(perfCauses?.now ?? 0),
+ hint: performanceHint(perfCauses),
},
{
label: "Hotspot health",
diff --git a/packages/ui/src/health/map/inspector.tsx b/packages/ui/src/health/map/inspector.tsx
index 68ee15bda..3eaf1588f 100644
--- a/packages/ui/src/health/map/inspector.tsx
+++ b/packages/ui/src/health/map/inspector.tsx
@@ -28,8 +28,8 @@ function causesOutside(scope: MapScope | undefined): string {
if (scope === undefined || omitted === null || omitted === undefined) {
return ". Whether more carry causes outside the drawn field is not reported here.";
}
- if (omitted === 0) return ". Every file with an open cause is drawn.";
- return `. ${omitted.toLocaleString()} more carry causes outside the drawn field.`;
+ if (omitted === 0) return ". Every file with a cause worth fixing now is drawn.";
+ return `. ${omitted.toLocaleString()} more carry causes worth fixing now outside the drawn field.`;
}
/** Worst-first for the active lens, so the list ranks what the field marks. */
@@ -153,7 +153,7 @@ export function MapFieldList({
<p className="text-xs text-[var(--color-text-tertiary)]">
<span className="tabular-nums">{rows.length}</span> of{" "}
<span className="tabular-nums">{ranked.length.toLocaleString()}</span>{" "}
- {overlay === "performance" ? "files with an open cause" : "drawn files"} listed
+ {overlay === "performance" ? "files with a cause worth fixing now" : "drawn files"} listed
{overlay === "performance" ? causesOutside(scope) : "."}
</p>
</div>
diff --git a/packages/ui/src/health/map/scope-note.tsx b/packages/ui/src/health/map/scope-note.tsx
index 3c6562d01..141d2304a 100644
--- a/packages/ui/src/health/map/scope-note.tsx
+++ b/packages/ui/src/health/map/scope-note.tsx
@@ -50,8 +50,8 @@ function Action({
function omittedText(scope: MapScope): string {
const causes = scope.omitted.performanceFiles;
if (causes == null) return `${scope.omitted.files.toLocaleString()} not drawn`;
- if (causes === 0) return "every file with an open cause is drawn";
- return `${causes.toLocaleString()} ${plural(causes, "file", "files")} with open causes not drawn`;
+ if (causes === 0) return "every file with a cause worth fixing now is drawn";
+ return `${causes.toLocaleString()} ${plural(causes, "file", "files")} with causes worth fixing now not drawn`;
}
function HeldToggle({
diff --git a/packages/vscode/webview/src/views/health/App.test.tsx b/packages/vscode/webview/src/views/health/App.test.tsx
index ad859849f..0f723932b 100644
--- a/packages/vscode/webview/src/views/health/App.test.tsx
+++ b/packages/vscode/webview/src/views/health/App.test.tsx
@@ -32,7 +32,7 @@ const overview: HealthOverviewResponse = {
maintainability_average: 8.2,
performance_average: 9.9,
maintainability_findings: 6,
- performance_findings: 0,
+ performance_causes: { now: 0, production: 0, all: 0, per_10k_loc: null },
},
distribution: {
total_files: 128,
diff --git a/tests/fixtures/mcp/tool_response_shapes.json b/tests/fixtures/mcp/tool_response_shapes.json
index 0b2c00437..33cde31ae 100644
--- a/tests/fixtures/mcp/tool_response_shapes.json
+++ b/tests/fixtures/mcp/tool_response_shapes.json
@@ -767,8 +767,12 @@
"performance_average": null,
"performance_coverage_pct": null,
"performance_covered_files": null,
- "performance_findings": null,
- "performance_findings_density_per_10k_loc": null,
+ "performance_causes": {
+ "all": null,
+ "now": null,
+ "per_10k_loc": null,
+ "production": null
+ },
"performance_skipped_files": null,
"performance_unsupported_languages": [
null
diff --git a/tests/unit/cli/test_health_cmd_controls.py b/tests/unit/cli/test_health_cmd_controls.py
index d1deccc68..eb609c5ff 100644
--- a/tests/unit/cli/test_health_cmd_controls.py
+++ b/tests/unit/cli/test_health_cmd_controls.py
@@ -196,3 +196,23 @@ def test_the_headline_names_production_code_while_tests_are_in_it() -> None:
# Narrowed to production, the two figures are one.
narrowed = headline(**base, production_file_count=2)
assert "Production code" not in narrowed and "Hotspot: ?/10" in narrowed
+
+
+def test_the_performance_line_leads_with_the_causes_worth_fixing_now() -> None:
+ """The stored headline every surface prints, not a raw finding count."""
+ from repowise.cli.commands.health_cmd.summary import _render_performance_section
+ from repowise.core.analysis.health.perf.coverage import PerfCoverage
+ from repowise.core.persistence.crud.analysis.performance import PerformanceHeadline
+
+ coverage = PerfCoverage(
+ analyzed_files=10, covered_files=9, covered_nloc=9000, total_nloc=10000
+ )
+ report = SimpleNamespace(kpis={"performance_average": 9.7})
+ console = Console(file=io.StringIO(), width=400, force_terminal=False)
+ with patch("repowise.cli.commands.health_cmd.summary.console", console):
+ _render_performance_section(report, coverage, PerformanceHeadline(4, 415, 926, 9.03))
+ out = console.file.getvalue()
+ assert (
+ "4 causes worth fixing now · 415 open in production code · 926 overall · "
+ "9.03/10K covered LOC · avg score 9.7/10" in out
+ )
diff --git a/tests/unit/cli/test_status_storage.py b/tests/unit/cli/test_status_storage.py
index 87b20e296..fb1ddc39a 100644
--- a/tests/unit/cli/test_status_storage.py
+++ b/tests/unit/cli/test_status_storage.py
@@ -141,3 +141,15 @@ def test_sync_state_totals_match_the_pages_table(tmp_path: Path, monkeypatch) ->
sync = result.output.split("Pages by Type")[0]
assert "│ 10 " in sync and "│ 12 " not in sync
assert "4,321" in sync
+
+
+def test_health_line_leads_performance_with_the_causes_worth_fixing_now(monkeypatch) -> None:
+ causes = {"now": 4, "production": 415, "all": 926, "per_10k_loc": 9.03}
+ monkeypatch.setattr(
+ status_cmd,
+ "_query_health",
+ lambda _path: _health(performance_average=9.76, performance_causes=causes),
+ )
+ line = status_cmd._query_health_line(Path("."))
+ assert line is not None
+ assert " · 4 of 415 production perf causes worth fixing now (9.7)" in line
diff --git a/tests/unit/generation/test_editor_file_base.py b/tests/unit/generation/test_editor_file_base.py
index f287d2610..39d5e6322 100644
--- a/tests/unit/generation/test_editor_file_base.py
+++ b/tests/unit/generation/test_editor_file_base.py
@@ -10,6 +10,7 @@ from repowise.core.generation.editor_files.data import (
EditorFileData,
HotspotFile,
)
+from repowise.core.persistence.crud.analysis.performance import PerformanceHeadline
# ---------------------------------------------------------------------------
# Minimal concrete subclass for testing
@@ -190,7 +191,7 @@ def test_stale_warning_guidance_points_at_served_files(any_gen):
def _health_block(
maintainability_average: float | None,
performance_average: float | None = None,
- performance_findings: int = 0,
+ performance_causes: PerformanceHeadline | None = None,
performance_coverage_pct: float | None = None,
band: str = "Good",
) -> CodeHealthBlock:
@@ -202,7 +203,7 @@ def _health_block(
worst_path="src/bad.py",
maintainability_average=maintainability_average,
performance_average=performance_average,
- performance_findings=performance_findings,
+ performance_causes=performance_causes,
performance_coverage_pct=performance_coverage_pct,
)
@@ -270,13 +271,18 @@ def test_render_surfaces_performance_when_present(gen):
data = dataclasses.replace(
_minimal_data(),
code_health=_health_block(
- 6.4, performance_average=9.2, performance_findings=7, performance_coverage_pct=88.0
+ 6.4,
+ performance_average=9.2,
+ performance_causes=PerformanceHeadline(1, 7, 12, 2.5),
+ performance_coverage_pct=88.0,
),
)
result = gen.render(data)
- # Leads with the finding COUNT; the bounded [9,10] average and coverage %
- # are deliberately not rendered (nothing an agent can act on there).
- assert "performance risk 7 open static performance findings" in result
+ # Leads with the causes worth fixing now, production and overall as context;
+ # the bounded [9,10] average and coverage % are deliberately not rendered.
+ assert (
+ "performance 1 cause worth fixing now (7 open in production code, 12 overall)" in result
+ )
assert "N+1" not in result
@@ -287,7 +293,7 @@ def test_render_omits_performance_when_unmeasured(gen):
result = gen.render(data)
# Maintainability still renders; the performance clause is suppressed.
assert "maintainability 6.4/10" in result
- assert "performance risk" not in result
+ assert "worth fixing now" not in result
def test_write_creates_new_file(gen, tmp_path):
diff --git a/tests/unit/persistence/test_health_overview_reads.py b/tests/unit/persistence/test_health_overview_reads.py
index ce1db4852..485361adc 100644
--- a/tests/unit/persistence/test_health_overview_reads.py
+++ b/tests/unit/persistence/test_health_overview_reads.py
@@ -107,7 +107,7 @@ async def test_findings_kwarg_is_actually_used_not_re_read(async_session, tmp_pa
summary = await get_health_summary(async_session, repo.id, findings=findings[:1])
assert summary["open_findings"] == 1
- assert summary["performance_findings"] == 0
+ assert summary["maintainability_findings"] == 0
async def test_snapshot_headline_reads_the_latest_and_counts_the_rest(
diff --git a/tests/unit/persistence/test_performance_headline.py b/tests/unit/persistence/test_performance_headline.py
new file mode 100644
index 000000000..6a555dedd
--- /dev/null
+++ b/tests/unit/persistence/test_performance_headline.py
@@ -0,0 +1,111 @@
+"""One performance headline, read the same way by every surface.
+
+The default queue leads, every production cause and every cause give it
+context, and the summary, the editor files and the CLI all print that one
+count rather than each summing raw findings over every context.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from sqlalchemy import update
+
+from repowise.core.analysis.health.models import HealthFindingData, Severity
+from repowise.core.analysis.health.perf.opportunities import link_performance_findings
+from repowise.core.generation.editor_files.fetcher import EditorFileDataFetcher
+from repowise.core.persistence.crud import (
+ finalize_performance_opportunities,
+ get_health_summary,
+ performance_headline,
+ save_health_findings,
+ save_health_metrics,
+ upsert_repository,
+)
+from repowise.core.persistence.models import PerformanceOpportunity
+
+
+def _metric(path: str) -> dict:
+ return {
+ "file_path": path,
+ "score": 8.0,
+ "max_ccn": 1,
+ "max_nesting": 1,
+ "nloc": 100,
+ "has_test_file": False,
+ "module": "src",
+ "performance_score": 9.5,
+ }
+
+
+def _perf_finding(path: str) -> HealthFindingData:
+ return HealthFindingData(
+ biomarker_type="io_in_loop",
+ severity=Severity.MEDIUM,
+ file_path=path,
+ function_name="run",
+ line_start=1,
+ line_end=1,
+ details={
+ "boundary_kind": "db",
+ "cross_function": True,
+ "path": [f"{path}::run", "src/db.py::fetch"],
+ "resolution_basis": "reliable-edge",
+ },
+ health_impact=0.0,
+ reason="Database work repeats for every loop iteration.",
+ dimension="performance",
+ )
+
+
+# (file, execution context, in the default queue)
+_CAUSES = (
+ ("src/queued.py", "production", True),
+ ("src/waiting.py", "production", False),
+ ("tests/test_loop.py", "test", False),
+)
+
+
+async def _seed(async_session, tmp_path):
+ repo = await upsert_repository(async_session, name="repo", local_path=str(tmp_path))
+ await save_health_metrics(async_session, repo.id, [_metric(p) for p, _, _ in _CAUSES])
+ findings = [_perf_finding(p) for p, _, _ in _CAUSES]
+ link_performance_findings(findings)
+ await save_health_findings(async_session, repo.id, findings)
+ await finalize_performance_opportunities(async_session, repo.id, analyzed_commit="a" * 40)
+ # The verdicts the finalizer stores, set directly so each scope holds a known row.
+ for path, context, queued in _CAUSES:
+ await async_session.execute(
+ update(PerformanceOpportunity)
+ .where(
+ PerformanceOpportunity.repository_id == repo.id,
+ PerformanceOpportunity.file_path == path,
+ )
+ .values(execution_context=context, queue_eligible=queued)
+ )
+ await async_session.flush()
+ return repo
+
+
+async def test_the_headline_leads_with_the_queue_and_keeps_the_rest_as_context(
+ async_session, tmp_path
+) -> None:
+ repo = await _seed(async_session, tmp_path)
+ causes = await performance_headline(async_session, repo.id, covered_nloc=30_000)
+ assert (causes.now, causes.production, causes.all) == (1, 2, 3)
+ # Density is every cause over the covered lines, computed once here.
+ assert causes.per_10k_loc == 1.0
+ assert (await performance_headline(async_session, repo.id, covered_nloc=0)).per_10k_loc is None
+
+
+async def test_the_summary_and_the_editor_files_print_the_same_headline(
+ async_session, tmp_path
+) -> None:
+ repo = await _seed(async_session, tmp_path)
+ summary = await get_health_summary(async_session, repo.id)
+ block = await EditorFileDataFetcher(async_session, repo.id, Path(tmp_path))._get_code_health()
+ assert block is not None
+ assert summary["performance_causes"] == block.performance_causes.as_dict()
+ assert (block.performance_causes.now, block.performance_causes.all) == (1, 3)
+ # Raw finding counts are gone from the summary, so no surface can lead with them.
+ assert "performance_findings" not in summary
diff --git a/tests/unit/server/golden/overview_summary.json b/tests/unit/server/golden/overview_summary.json
index 2a5cd5212..adb591792 100644
--- a/tests/unit/server/golden/overview_summary.json
+++ b/tests/unit/server/golden/overview_summary.json
@@ -50,7 +50,12 @@
"gated": {},
"maintainability_average": 5.5,
"performance_average": 9.5,
- "performance_findings": 0,
+ "performance_causes": {
+ "now": 0,
+ "production": 0,
+ "all": 0,
+ "per_10k_loc": 0.0
+ },
"worst_performance_path": "src/core.py",
"worst_performance_score": 9.5,
"severity_breakdown": {
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index f73aac6a4..9b07bdc4e 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -904,10 +904,33 @@ async def test_get_health_dimension_filter_leaves_kpis_and_ranking_alone(setup_m
filtered = await get_health(
include=["biomarkers", "maintainability"], only=["kpis", "worst_files"]
)
- assert filtered["kpis"]["performance_findings"] == full["kpis"]["performance_findings"]
+ assert filtered["kpis"]["performance_causes"] == full["kpis"]["performance_causes"]
assert filtered["worst_files"] == full["worst_files"]
+async def test_get_health_kpis_print_the_one_performance_headline(setup_mcp, health_data):
+ """The kpis carry the core headline every surface prints, never a raw finding count."""
+ from sqlalchemy import select
+
+ from repowise.core.persistence.crud import performance_headline
+ from repowise.core.persistence.models import Repository
+ from repowise.server.mcp_server import _session_factory, get_health
+
+ result = await get_health(only=["kpis"])
+ kpis = result["kpis"]
+ assert "performance_findings" not in kpis
+ async with _session_factory() as session:
+ repo = (await session.execute(select(Repository))).scalars().first()
+ causes = await performance_headline(session, repo.id, covered_nloc=1)
+ assert set(kpis["performance_causes"]) == {"now", "production", "all", "per_10k_loc"}
+ assert (
+ kpis["performance_causes"]["now"],
+ kpis["performance_causes"]["production"],
+ kpis["performance_causes"]["all"],
+ ) == (causes.now, causes.production, causes.all)
+
+
@pytest.fixture
async def floored_health_data(session, populated_db: str) -> str:
"""Four files clamped at the 1.0 score floor, worst one last by path.
diff --git a/tests/unit/server/test_health_excludes.py b/tests/unit/server/test_health_excludes.py
index a8fd02498..d33482f81 100644
--- a/tests/unit/server/test_health_excludes.py
+++ b/tests/unit/server/test_health_excludes.py
@@ -103,8 +103,7 @@ async def test_health_reads_honor_repo_settings_excludes(session, tmp_path) -> N
"structure_average": None,
"history_average": None,
"maintainability_findings": 0,
- "performance_findings": 0,
- "performance_findings_density": None,
+ "performance_causes": {"now": 0, "production": 0, "all": 0, "per_10k_loc": None},
"performance_coverage_pct": None,
"performance_covered_files": 0,
"performance_analyzed_files": 0,
diff --git a/tests/unit/server/test_health_files_summary.py b/tests/unit/server/test_health_files_summary.py
index 7c4eba367..685940c26 100644
--- a/tests/unit/server/test_health_files_summary.py
+++ b/tests/unit/server/test_health_files_summary.py
@@ -15,9 +15,13 @@ from __future__ import annotations
import pytest
from httpx import AsyncClient
+from sqlalchemy import update
+from repowise.core.analysis.health.models import HealthFindingData, Severity
+from repowise.core.analysis.health.perf.opportunities import link_performance_findings
from repowise.core.persistence import crud
from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import PerformanceOpportunity
from tests.unit.server.conftest import create_test_repo
_FULL_ONLY = {
@@ -60,18 +64,42 @@ def _finding(path: str, biomarker: str, dimension: str, impact: float) -> dict:
}
+def _perf_finding(path: str, line: int) -> HealthFindingData:
+ return HealthFindingData(
+ biomarker_type="io_in_loop",
+ severity=Severity.MEDIUM,
+ file_path=path,
+ function_name="run",
+ line_start=line,
+ line_end=line,
+ details={
+ "boundary_kind": "db",
+ "cross_function": True,
+ "path": [f"{path}::run", "src/db.py::fetch"],
+ "resolution_basis": "reliable-edge",
+ },
+ health_impact=0.0,
+ reason="Database work repeats for every loop iteration.",
+ dimension="performance",
+ )
+
+
async def _seed(app, repo_id: str) -> None:
+ perf = [_perf_finding("src/f00.py", 1), _perf_finding("src/f01.py", 1)]
+ link_performance_findings(perf)
async with get_session(app.state.session_factory) as session:
await crud.save_health_metrics(session, repo_id, [_metric(i) for i in range(3)])
await crud.save_health_findings(
session,
repo_id,
- [
- _finding("src/f00.py", "complex_method", "defect", 2.5),
- _finding("src/f00.py", "io_in_loop", "performance", 0.0),
- _finding("src/f01.py", "io_in_loop", "performance", 0.0),
- _finding("src/f01.py", "io_in_loop", "performance", 0.0),
- ],
+ [_finding("src/f00.py", "complex_method", "defect", 2.5), *perf],
+ )
+ await crud.finalize_performance_opportunities(session, repo_id, analyzed_commit="a" * 40)
+ # The verdict the finalizer stores for a production cause with a proven cost.
+ await session.execute(
+ update(PerformanceOpportunity)
+ .where(PerformanceOpportunity.repository_id == repo_id)
+ .values(queue_eligible=True)
)
@@ -113,10 +141,10 @@ async def test_summary_keeps_every_field_the_map_actually_colours_by(
) -> None:
"""The saving is only legitimate if the map can still draw itself.
- ``performance_findings`` is the one that makes this non-obvious: the
- narrowed read has to keep counting perf findings per file, and a summary
- mode that skipped the finding read entirely would grey out the performance
- lens while every other assertion here still passed.
+ ``performance_opportunities`` is the one that makes this non-obvious: the
+ narrowed read has to keep counting queued causes per file, and a summary
+ mode that skipped that read would grey out the performance lens while
+ every other assertion here still passed.
"""
repo = await create_test_repo(client)
await _seed(app, repo["id"])
@@ -135,7 +163,7 @@ async def test_summary_keeps_every_field_the_map_actually_colours_by(
"has_test_file",
"maintainability_score",
"performance_score",
- "performance_findings",
+ "performance_opportunities",
"performance_analyzed",
}
by_path_full = {f["file_path"]: f for f in full["files"]}
@@ -145,8 +173,9 @@ async def test_summary_keeps_every_field_the_map_actually_colours_by(
for key in map_fields:
assert row[key] == wide[key], f"{key} diverged on {row['file_path']}"
# And the counts are real, not a constant zero.
- assert by_path_full["src/f01.py"]["performance_findings"] == 2
- assert by_path_full["src/f00.py"]["performance_findings"] == 1
+ assert by_path_full["src/f01.py"]["performance_opportunities"] == 1
+ assert by_path_full["src/f00.py"]["performance_opportunities"] == 1
+ assert by_path_full["src/f02.py"]["performance_opportunities"] == 0
@pytest.mark.asyncio
diff --git a/tests/unit/server/test_health_map_feed.py b/tests/unit/server/test_health_map_feed.py
index 51decc22f..0da23a590 100644
--- a/tests/unit/server/test_health_map_feed.py
+++ b/tests/unit/server/test_health_map_feed.py
@@ -8,10 +8,12 @@ the rows it actually returned.
from __future__ import annotations
from httpx import AsyncClient
+from sqlalchemy import update
from repowise.core.analysis.health.models import HealthFindingData, Severity
from repowise.core.analysis.health.perf.opportunities import link_performance_findings
from repowise.core.persistence import crud
+from repowise.core.persistence.models import PerformanceOpportunity
from tests.unit.server.conftest import create_test_repo
@@ -58,11 +60,12 @@ def _perf_finding(path: str, line: int, path_nodes: list[str]) -> HealthFindingD
)
-async def _seed(app, client: AsyncClient) -> str:
+async def _seed(app, client: AsyncClient, *, queued: bool = True) -> str:
"""One big clean file, and one tiny file carrying the repository's cause.
The tiny file is the whole point: a size ranking puts it last, and it is
- where the work is.
+ where the work is. ``queued`` stores the cause as a default-queue member,
+ the verdict the finalizer writes for a production cause with a proven cost.
"""
repo = await create_test_repo(client)
repo_id = repo["id"]
@@ -79,6 +82,11 @@ async def _seed(app, client: AsyncClient) -> str:
await crud.finalize_performance_opportunities(
session, repo_id, analyzed_commit="a" * 40
)
+ await session.execute(
+ update(PerformanceOpportunity)
+ .where(PerformanceOpportunity.repository_id == repo_id)
+ .values(queue_eligible=queued)
+ )
await session.commit()
return repo_id
@@ -152,6 +160,19 @@ async def test_rows_carry_the_burden_the_lens_rings_by(app, client):
assert "performance_actionability" not in big
+async def test_a_cause_outside_the_default_queue_reads_clear_on_the_map(app, client):
+ """The lens colours what the performance headline leads with: the default queue."""
+ repo_id = await _seed(app, client, queued=False)
+ feed = await _feed(client, repo_id, cap=100)
+ tiny = next(f for f in feed["files"] if f["file_path"] == "src/tiny.py")
+ assert tiny["performance_opportunities"] == 0
+ assert "performance_actionability" not in tiny
+ # The repository block still counts every open cause.
+ assert feed["performance"]["opportunities_total"] >= 1
+ capped = await _feed(client, repo_id, cap=1)
+ assert capped["selection"]["performance_shown"] == 0
+
+
async def test_a_file_with_only_expected_causes_reads_clear_on_the_map(
app, client: AsyncClient
):