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): wire dead perf markers and surface honest perf coverage (#711)

Raghav Chamadiya13f4566e5973
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd.py b/packages/cli/src/repowise/cli/commands/health_cmd.py
index 69d8152e6..ddf8d017e 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd.py
@@ -394,6 +394,14 @@ def health_command(
_render_defect_accuracy_line(report)
+ # Performance pillar section: lead with the finding COUNT + density +
+ # coverage (the honest signal), not the bounded /10 average. Language comes
+ # from the parsed files (the in-memory metrics don't carry it).
+ _render_performance_section(
+ report,
+ {pf.file_info.path: pf.file_info.language for pf in parsed_files},
+ )
+
table = Table(title=f"Lowest-scoring files ({min(len(metrics_sorted), 20)})")
table.add_column("File", style="cyan")
table.add_column("Score", justify="right")
@@ -432,6 +440,49 @@ def health_command(
console.print(f_table)
+def _render_performance_section(report: Any, lang_by_path: dict[str, str]) -> None:
+ """Honest performance headline: finding count + density + coverage + scope.
+
+ Leads with the open-finding count 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 report.findings if getattr(f, "dimension", "defect") == "performance"
+ )
+ perf_avg = report.kpis.get("performance_average")
+
+ parts = [f"[bold]{perf_findings}[/bold] finding{'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")
+ if isinstance(perf_avg, (int, float)):
+ parts.append(f"avg {perf_avg:.1f}/10")
+ console.print(
+ "\n[bold]Performance risk[/bold] "
+ "[dim](static, high-precision/low-recall)[/dim]: " + " · ".join(parts)
+ )
+
+ cov_line = (
+ f"[dim]Coverage:[/dim] perf ran on {coverage.pct_loc}% of analyzed code lines "
+ f"({coverage.covered_files}/{coverage.analyzed_files} files)"
+ )
+ if coverage.skipped_files:
+ langs = ", ".join(f"{lang} x{n}" for lang, n in coverage.unsupported_languages[:3])
+ cov_line += f"; {coverage.skipped_files} skipped in unsupported languages ({langs})"
+ console.print(cov_line)
+ console.print(
+ "[dim]Scope: I/O-in-loop / N+1, resource/regex/defer-in-loop, blocking-in-async. "
+ "Not covered: algorithmic blowups, GC pressure, ORM lazy-load N+1.[/dim]"
+ )
+
+
def _render_distribution_line(dist: dict) -> None:
"""One compact line: the NLOC-weighted file split across the 3 bands."""
bands = dist.get("bands") or {}
diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.py
index 5385e407a..79d9e247f 100644
--- a/packages/cli/src/repowise/cli/commands/status_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py
@@ -209,8 +209,15 @@ 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" · {maint:.1f} (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.
perf = data.get("performance_average")
- perf_part = f" · {perf:.1f} (performance)" if perf is not None else ""
+ perf_findings = data.get("performance_findings", 0)
+ perf_part = (
+ f" · {perf_findings} perf finding{'s' if perf_findings != 1 else ''} ({perf:.1f})"
+ if perf is not None
+ else ""
+ )
return (
f"[bold]Health:[/bold] {data['average_health']:.1f} (avg) "
f"[[{band_color}]{BAND_LABEL[band]}[/{band_color}]] · "
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/defer_in_loop.py b/packages/core/src/repowise/core/analysis/health/biomarkers/defer_in_loop.py
new file mode 100644
index 000000000..a5b7a9b29
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/defer_in_loop.py
@@ -0,0 +1,52 @@
+"""Defer-in-loop — a Go ``defer`` accumulated on every loop iteration.
+
+A ``defer`` inside a ``for`` loop does not run at the end of the iteration; it
+runs when the *enclosing function* returns. Each iteration pushes another
+deferred call onto the stack, so a file/handle/row opened-and-deferred in a loop
+stays open until the whole function exits — the classic Go resource leak (open
+files, unclosed ``*sql.Rows``, held mutexes). ``go vet`` and ``gocritic`` ship
+the same check. A ``performance`` dimension signal (Go only).
+
+High-precision by construction: it is a pure syntactic shape (a ``defer``
+statement whose nearest enclosing loop is inside the same function), gated in the
+Go dialect's ``loop_stmt_marker``. This detector lifts the pre-collected hits
+into findings.
+"""
+
+from __future__ import annotations
+
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+_KIND = "defer_in_loop"
+
+
+class DeferInLoopDetector:
+ name = _KIND
+ category = "performance"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ out: list[BiomarkerResult] = []
+ for hit in ctx.perf_hits:
+ if hit.kind != _KIND:
+ continue
+ out.append(
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=Severity.MEDIUM,
+ function_name=hit.function,
+ line_start=hit.line,
+ line_end=hit.line,
+ details={},
+ reason=(
+ "a deferred call inside a loop runs only when the "
+ "enclosing function returns, so the resource stays held "
+ "across every iteration; close it in the loop body (or "
+ "wrap the body in a function) instead"
+ ),
+ )
+ )
+ return out
+
+
+BIOMARKER = DeferInLoopDetector()
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/regex_compile_in_loop.py b/packages/core/src/repowise/core/analysis/health/biomarkers/regex_compile_in_loop.py
new file mode 100644
index 000000000..4ae1ee81b
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/regex_compile_in_loop.py
@@ -0,0 +1,51 @@
+"""Regex-compile-in-loop — a regex recompiled on every loop iteration.
+
+Compiling a regular expression (``Pattern.compile`` / ``regexp.MustCompile`` /
+``regexp.Compile`` / ``Regex::new``) inside a loop rebuilds the same automaton
+every iteration instead of hoisting it once. Compilation dominates matching, so
+a static pattern recompiled per iteration is pure wasted work. A ``performance``
+dimension signal.
+
+Valid only where the language does NOT cache compiled patterns: Java, Go, and
+Rust. Python's ``re`` module and .NET both cache internally, so the pattern is a
+no-op there and the marker is intentionally absent from those dialects. Each
+emitting dialect further gates on a *static literal* pattern (a dynamic
+``MustCompile(pat)`` may legitimately vary each iteration and cannot be lifted).
+This detector lifts the pre-collected, pre-gated hits into findings.
+"""
+
+from __future__ import annotations
+
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+_KIND = "regex_compile_in_loop"
+
+
+class RegexCompileInLoopDetector:
+ name = _KIND
+ category = "performance"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ out: list[BiomarkerResult] = []
+ for hit in ctx.perf_hits:
+ if hit.kind != _KIND:
+ continue
+ out.append(
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=Severity.MEDIUM,
+ function_name=hit.function,
+ line_start=hit.line,
+ line_end=hit.line,
+ details={},
+ reason=(
+ "a regex with a static pattern is recompiled every loop "
+ "iteration; compile it once outside the loop and reuse it"
+ ),
+ )
+ )
+ return out
+
+
+BIOMARKER = RegexCompileInLoopDetector()
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
index 0cd41a489..2a2a250d6 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
@@ -25,6 +25,7 @@ from .complex_conditional import ComplexConditionalDetector
from .complex_method import ComplexMethodDetector
from .coverage_gap import CoverageGapDetector
from .coverage_gradient import CoverageGradientDetector
+from .defer_in_loop import DeferInLoopDetector
from .developer_congestion import DeveloperCongestionDetector
from .dry_violation import DryViolationDetector
from .duplicated_assertion_block import DuplicatedAssertionBlockDetector
@@ -51,6 +52,7 @@ from .pandas_iterrows_in_loop import PandasIterrowsInLoopDetector
from .pd_concat_in_loop import PdConcatInLoopDetector
from .primitive_obsession import PrimitiveObsessionDetector
from .prior_defect import PriorDefectDetector
+from .regex_compile_in_loop import RegexCompileInLoopDetector
from .resource_construction_in_loop import ResourceConstructionInLoopDetector
from .serial_await_in_loop import SerialAwaitInLoopDetector
from .sql_cartesian_join import SqlCartesianJoinDetector
@@ -91,6 +93,10 @@ _DETECTOR_FACTORIES: list[type[Biomarker]] = [
IoInLoopDetector, # type: ignore[list-item]
StringConcatInLoopDetector, # type: ignore[list-item]
BlockingSyncInAsyncDetector, # type: ignore[list-item]
+ # Phase 6 dialect markers — emitted by the Java/Go/Rust dialects but
+ # previously unwired (no lifter), so recall-zero until now.
+ RegexCompileInLoopDetector, # type: ignore[list-item]
+ DeferInLoopDetector, # type: ignore[list-item]
# Phase 7a — cheap, high-precision loop markers.
ResourceConstructionInLoopDetector, # type: ignore[list-item]
LockInLoopDetector, # type: ignore[list-item]
diff --git a/packages/core/src/repowise/core/analysis/health/perf/coverage.py b/packages/core/src/repowise/core/analysis/health/perf/coverage.py
new file mode 100644
index 000000000..66856c655
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/perf/coverage.py
@@ -0,0 +1,130 @@
+"""Performance-coverage accounting — how much of a repo the perf pass actually ran on.
+
+The performance pillar is silent for any language with no registered
+``PerfDialect`` (Kotlin, C++, Ruby, PHP, Swift, Scala, C, plain SQL). Such a file
+still gets a complexity/NLOC score, so it counts toward the health headline, but
+**no perf detector ever runs on it** — the score is a mechanical 10.0 that means
+"we never looked," not "your code is fast." On a repo that is mostly an
+unsupported language the aggregate perf score is therefore meaningless.
+
+This module turns that blind spot into an honest, surfaced number: given the
+analyzed code files and their languages, it reports what fraction of files / LOC
+a perf detector was actually *able* to run on, and which unsupported languages
+account for the gap. Pure and dependency-free (a language string set in, a
+:class:`PerfCoverage` out) so it is trivially unit-testable; the DB loader that
+feeds it lives in the persistence layer.
+"""
+
+from __future__ import annotations
+
+from collections import Counter
+from collections.abc import Iterable
+from dataclasses import dataclass, field
+from typing import Protocol
+
+from ..complexity.languages import LANGUAGE_MAPS
+from .dialects import PERF_DIALECTS
+
+
+def supported_perf_languages() -> frozenset[str]:
+ """The ``LanguageTag`` set the perf pass has a dialect for (its full scope)."""
+ return frozenset(PERF_DIALECTS)
+
+
+class _FileMetricRow(Protocol):
+ """The two fields coverage needs off a per-file metric row (duck-typed)."""
+
+ file_path: str
+ nloc: int
+
+
+@dataclass(frozen=True)
+class PerfCoverage:
+ """What fraction of the analyzed code the performance pass covered.
+
+ ``covered`` = files in a language with a registered perf dialect; ``skipped``
+ = analyzed code files in an unsupported language (a silent 10.0). ``pct_loc``
+ is the honest headline: perf ran on this share of the analyzed lines.
+ """
+
+ analyzed_files: int
+ covered_files: int
+ covered_nloc: int
+ total_nloc: int
+ # Unsupported (language, file_count) pairs, most files first.
+ unsupported_languages: list[tuple[str, int]] = field(default_factory=list)
+
+ @property
+ def skipped_files(self) -> int:
+ return self.analyzed_files - self.covered_files
+
+ @property
+ def pct_loc(self) -> float:
+ """Percent of analyzed NLOC a perf detector ran on (0-100)."""
+ if self.total_nloc <= 0:
+ return 100.0 if self.analyzed_files == 0 else 0.0
+ return round(100.0 * self.covered_nloc / self.total_nloc, 1)
+
+ @property
+ def is_partial(self) -> bool:
+ """True when some analyzed code was skipped — the score is incomplete."""
+ return self.skipped_files > 0
+
+
+def compute_perf_coverage(
+ files: Iterable[tuple[str, int]],
+ *,
+ supported: frozenset[str] | None = None,
+) -> PerfCoverage:
+ """Bucket analyzed code files into perf-covered vs skipped.
+
+ *files* is an iterable of ``(language_tag, nloc)`` for every analyzed code
+ file (one row per file). *supported* defaults to the registered dialect set;
+ pass an explicit set only in tests. Non-code artifacts (markdown, json, …)
+ must be filtered out by the caller — this counts every row it is given as an
+ analyzed code file.
+ """
+ tags = supported if supported is not None else supported_perf_languages()
+ analyzed = 0
+ covered = 0
+ covered_nloc = 0
+ total_nloc = 0
+ unsupported: Counter[str] = Counter()
+ for language, nloc in files:
+ analyzed += 1
+ weight = max(int(nloc), 0)
+ total_nloc += weight
+ if language in tags:
+ covered += 1
+ covered_nloc += weight
+ else:
+ unsupported[language or "unknown"] += 1
+ return PerfCoverage(
+ analyzed_files=analyzed,
+ covered_files=covered,
+ covered_nloc=covered_nloc,
+ total_nloc=total_nloc,
+ unsupported_languages=unsupported.most_common(),
+ )
+
+
+def coverage_for_metrics(
+ metrics: Iterable[_FileMetricRow],
+ lang_by_path: dict[str, str],
+ *,
+ supported: frozenset[str] | None = None,
+) -> PerfCoverage:
+ """Perf coverage over per-file metric rows, restricted to real code.
+
+ The denominator is every metric row whose language the complexity walker
+ actually walks (``LANGUAGE_MAPS`` — real code, including the perf-unsupported
+ Kotlin/C++), so docs/config rows (markdown/json/yaml) in the metrics table
+ never dilute the coverage math. *lang_by_path* maps ``file_path`` → language
+ tag (from the graph's file nodes).
+ """
+ code_rows = [
+ (lang_by_path.get(m.file_path, ""), m.nloc)
+ for m in metrics
+ if lang_by_path.get(m.file_path, "") in LANGUAGE_MAPS
+ ]
+ return compute_perf_coverage(code_rows, supported=supported)
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.py
index 3d44ceac1..406e037e1 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -213,6 +213,9 @@ _BIOMARKER_DIMENSIONS: dict[str, set[str]] = {
"io_in_loop": {"performance"},
"string_concat_in_loop": {"performance"},
"blocking_sync_in_async": {"performance"},
+ # Phase 6 dialect markers (Java/Go/Rust) - performance-only.
+ "regex_compile_in_loop": {"performance"},
+ "defer_in_loop": {"performance"},
# Phase 7a loop markers - performance-only, same as the originals.
"resource_construction_in_loop": {"performance"},
"lock_in_loop": {"performance"},
@@ -333,6 +336,12 @@ _PERFORMANCE_WEIGHT_MULTIPLIER: dict[str, float] = {
# (MARKER_BACKLOG.md); promote to full weight where corpus precision >= 70%.
# resource_construction is the highest-confidence (classified constructor),
# serial_await the lowest (cannot prove iteration independence).
+ # Phase 6 dialect markers. Both are high-precision syntactic shapes (Go
+ # `go vet`/`gocritic` ship defer-in-loop; the regex marker gates on a static
+ # literal pattern in Java/Go/Rust). Ship advisory pending this session's
+ # test-repo gate; bounded by the 1.0 perf cap either way.
+ "regex_compile_in_loop": 0.6,
+ "defer_in_loop": 0.6,
"resource_construction_in_loop": 0.7,
"lock_in_loop": 0.5,
# PROMOTED 0.5 -> 0.7 (Phase-7c): 100% precision across corpora (7a 22/22 +
@@ -372,6 +381,8 @@ _PERFORMANCE_CATEGORY: dict[str, str] = {
"io_in_loop": "performance",
"string_concat_in_loop": "performance",
"blocking_sync_in_async": "performance",
+ "regex_compile_in_loop": "performance",
+ "defer_in_loop": "performance",
"resource_construction_in_loop": "performance",
"lock_in_loop": "performance",
"serial_await_in_loop": "performance",
@@ -400,6 +411,8 @@ _PERFORMANCE_HOME: frozenset[str] = frozenset(
"io_in_loop",
"string_concat_in_loop",
"blocking_sync_in_async",
+ "regex_compile_in_loop",
+ "defer_in_loop",
"resource_construction_in_loop",
"lock_in_loop",
"serial_await_in_loop",
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 150ca4997..9f707fdcd 100644
--- a/packages/core/src/repowise/core/generation/editor_files/data.py
+++ b/packages/core/src/repowise/core/generation/editor_files/data.py
@@ -58,6 +58,17 @@ 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
+ performance_coverage_pct: float | None = None
+ performance_skipped_files: int = 0
+ performance_unsupported_languages: list[tuple[str, int]] = field(default_factory=list)
critical_biomarkers: list[dict] = field(default_factory=list)
untested_hotspots: list[dict] = 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 e06ebefab..b129ebd57 100644
--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py
+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
@@ -15,6 +15,7 @@ from pathlib import Path
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.health.perf.coverage import coverage_for_metrics
from repowise.core.persistence import crud
from repowise.core.persistence.models import (
DecisionRecord,
@@ -277,9 +278,7 @@ class EditorFileDataFetcher:
if hotspot_metrics:
h_nloc = sum(max(m.nloc, 1) for m in hotspot_metrics)
hotspot_health = (
- sum(m.score * max(m.nloc, 1) for m in hotspot_metrics) / h_nloc
- if h_nloc
- else avg
+ sum(m.score * max(m.nloc, 1) for m in hotspot_metrics) / h_nloc if h_nloc else avg
)
else:
hotspot_health = avg
@@ -287,7 +286,9 @@ class EditorFileDataFetcher:
# Maintainability pillar headline: NLOC-weighted over the per-file
# maintainability scores, skipping rows that predate the split. ``None``
# when unmeasured so the section omits the line rather than printing 10.0.
- maint_rows = [m for m in metric_rows if getattr(m, "maintainability_score", None) is not None]
+ maint_rows = [
+ m for m in metric_rows if getattr(m, "maintainability_score", None) is not None
+ ]
maintainability_average: float | None = None
if maint_rows:
m_nloc = sum(max(m.nloc, 1) for m in maint_rows)
@@ -310,6 +311,12 @@ class EditorFileDataFetcher:
else sum(m.performance_score for m in perf_rows) / len(perf_rows)
)
+ # Honest performance headline: how much of the analyzed code a perf
+ # detector actually ran on. Restricted to real code (LANGUAGE_MAPS), so a
+ # mostly-C++/Kotlin repo reads a low coverage %, never a bare 10/10.
+ lang_by_path = await crud.get_file_language_map(self._session, self._repo_id)
+ perf_coverage = coverage_for_metrics(metric_rows, lang_by_path)
+
# Critical biomarkers: brain methods, or critical-severity findings
# in hotspot files. Cap at 5 to keep CLAUDE.md tight.
f_res = await self._session.execute(
@@ -321,6 +328,18 @@ class EditorFileDataFetcher:
.order_by(HealthFinding.health_impact.desc())
)
all_findings = list(f_res.scalars().all())
+
+ # Open performance-finding count + density over covered LOC (the honest
+ # headline the diluted /10 hides).
+ performance_findings = sum(
+ 1 for f in all_findings if (f.dimension or "defect") == "performance"
+ )
+ 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
+ )
+
critical = []
for f in all_findings:
if len(critical) >= 5:
@@ -328,14 +347,16 @@ class EditorFileDataFetcher:
if f.biomarker_type == "brain_method" or (
f.severity == "critical" and f.file_path in hotspot_paths
):
- critical.append({
- "path": f.file_path,
- "summary": (
- f"{f.biomarker_type.replace('_', ' ')}"
- + (f" ({f.function_name})" if f.function_name else "")
- + f" — impact −{f.health_impact:.1f}"
- ),
- })
+ critical.append(
+ {
+ "path": f.file_path,
+ "summary": (
+ f"{f.biomarker_type.replace('_', ' ')}"
+ + (f" ({f.function_name})" if f.function_name else "")
+ + f" — impact −{f.health_impact:.1f}"
+ ),
+ }
+ )
return CodeHealthBlock(
hotspot_health=round(hotspot_health, 2),
@@ -349,6 +370,13 @@ 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_coverage_pct=(
+ perf_coverage.pct_loc if perf_coverage.analyzed_files else None
+ ),
+ performance_skipped_files=perf_coverage.skipped_files,
+ performance_unsupported_languages=perf_coverage.unsupported_languages,
critical_biomarkers=critical,
untested_hotspots=[], # Phase 2 fills this from coverage data
)
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 4a8746eaa..3ea64229e 100644
--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2
@@ -87,7 +87,11 @@ Worst: {{ data.code_health.worst_score }}/10 (`{{ data.code_health.worst_path }}
Maintainability, Average: {{ data.code_health.maintainability_average }}/10
{% endif %}
{% if data.code_health.performance_average is not none %}
-Performance risk, Average: {{ data.code_health.performance_average }}/10
+Performance risk: {{ data.code_health.performance_findings }} open finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% if data.code_health.performance_findings_density is not none %} ({{ data.code_health.performance_findings_density }} per 10K covered LOC){% endif %} · Average: {{ data.code_health.performance_average }}/10 (a bounded [9,10] summary of the findings, not a verification claim)
+{% if data.code_health.performance_coverage_pct is not none %}
+Performance coverage: perf detectors ran on {{ data.code_health.performance_coverage_pct }}% of analyzed code lines{% if data.code_health.performance_skipped_files %}; {{ data.code_health.performance_skipped_files }} file(s) skipped in unsupported languages ({% for lang, n in data.code_health.performance_unsupported_languages[:3] %}{{ lang }}×{{ n }}{% if not loop.last %}, {% endif %}{% endfor %}){% endif %}
+{% endif %}
+Performance scope: static RISK detection (I/O-in-loop / N+1, resource-in-loop, regex/defer-in-loop, blocking-in-async); high-precision, low-recall. Does NOT cover algorithmic blowups, GC/memory pressure, or ORM lazy-load N+1. Full list: `get_health(include=["biomarkers","performance"])`.
{% endif %}
{% if data.code_health.critical_biomarkers %}
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis.py b/packages/core/src/repowise/core/persistence/crud/analysis.py
index 53e8998e9..8804a52b4 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis.py
@@ -9,16 +9,20 @@ from __future__ import annotations
import json
from datetime import datetime
from pathlib import Path
-from typing import Any
+from typing import TYPE_CHECKING, Any
from sqlalchemy import or_, select
from sqlalchemy.ext.asyncio import AsyncSession
+if TYPE_CHECKING:
+ from ...analysis.health.perf.coverage import PerfCoverage
+
from repowise.core.analysis.dead_code.risk_factors import effective_safe_to_delete
from ..models import (
CoverageFile,
DeadCodeFinding,
+ GraphNode,
HealthFileMetric,
HealthFinding,
HealthSnapshot,
@@ -529,6 +533,26 @@ async def get_health_metrics(
)
+async def get_file_language_map(session: AsyncSession, repository_id: str) -> dict[str, str]:
+ """``{file_path: language_tag}`` for every file node in the graph."""
+ q = select(GraphNode.node_id, GraphNode.language).where(
+ GraphNode.repository_id == repository_id,
+ GraphNode.node_type == "file",
+ )
+ return {node_id: language for node_id, language in (await session.execute(q)).all()}
+
+
+async def get_perf_coverage(session: AsyncSession, repository_id: str) -> PerfCoverage:
+ """How much of the analyzed code the performance pass was able to run on."""
+ # Imported lazily to keep the persistence layer free of an analysis-layer
+ # import at module load (and to avoid a circular import).
+ from ...analysis.health.perf.coverage import coverage_for_metrics
+
+ metrics = await get_health_metrics(session, repository_id)
+ lang_by_path = await get_file_language_map(session, repository_id)
+ return coverage_for_metrics(metrics, lang_by_path)
+
+
async def get_health_summary(session: AsyncSession, repository_id: str) -> dict:
"""Aggregate KPIs over the per-file metrics table."""
metrics = await get_health_metrics(session, repository_id)
@@ -543,6 +567,12 @@ async def get_health_summary(session: AsyncSession, repository_id: str) -> dict:
"performance_average": None,
"maintainability_findings": 0,
"performance_findings": 0,
+ "performance_findings_density": None,
+ "performance_coverage_pct": None,
+ "performance_covered_files": 0,
+ "performance_analyzed_files": 0,
+ "performance_skipped_files": 0,
+ "performance_unsupported_languages": [],
"worst_performance_path": None,
"worst_performance_score": None,
}
@@ -600,6 +630,21 @@ async def get_health_summary(session: AsyncSession, repository_id: str) -> dict:
for finding in findings:
dim = finding.dimension or "defect"
by_dim[dim] = by_dim.get(dim, 0) + 1
+
+ # 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).
+ from ...analysis.health.perf.coverage import coverage_for_metrics
+
+ 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
+ )
return {
"file_count": len(metrics),
"average_health": round(avg, 2),
@@ -613,7 +658,13 @@ async def get_health_summary(session: AsyncSession, repository_id: str) -> dict:
round(performance_average, 2) if performance_average is not None else None
),
"maintainability_findings": by_dim.get("maintainability", 0),
- "performance_findings": by_dim.get("performance", 0),
+ "performance_findings": performance_findings,
+ "performance_findings_density": performance_findings_density,
+ "performance_coverage_pct": (coverage.pct_loc if coverage.analyzed_files else None),
+ "performance_covered_files": coverage.covered_files,
+ "performance_analyzed_files": coverage.analyzed_files,
+ "performance_skipped_files": coverage.skipped_files,
+ "performance_unsupported_languages": coverage.unsupported_languages,
"worst_performance_path": worst_performance_path,
"worst_performance_score": worst_performance_score,
}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.py
index 22b4de9e4..d1a2077e1 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py
@@ -12,12 +12,14 @@ from repowise.core.analysis.health.churn_complexity import churn_complexity_poin
from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracy
from repowise.core.analysis.health.grading import band_for
from repowise.core.analysis.health.grading import distribution as health_distribution
+from repowise.core.analysis.health.perf.coverage import PerfCoverage, coverage_for_metrics
from repowise.core.analysis.health.signals import file_signals
from repowise.core.analysis.health.suggestions import suggestion_for
from repowise.core.analysis.health.trends import diff_snapshots, file_trend, recent_kpis
from repowise.core.persistence.crud import (
get_all_git_metadata,
get_coverage_summary,
+ get_file_language_map,
get_git_metadata,
get_graph_node,
get_node_degree_counts,
@@ -210,7 +212,35 @@ def _dimension_average(metrics: list[HealthFileMetric], attr: str) -> float | No
return round(sum(getattr(m, attr) * max(m.nloc, 1) for m in scored) / total_nloc, 2)
-def _compute_kpis(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.
+
+ Leads with *how many* findings and over *how much* of the code the perf pass
+ ran, so an agent never reads a bare ``performance_average`` of ~10 as "fast"
+ when the real story is "we could only analyze 3% of this repo".
+ """
+ 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_coverage_pct": (
+ coverage.pct_loc if (coverage and coverage.analyzed_files) else None
+ ),
+ "performance_covered_files": coverage.covered_files if coverage else 0,
+ "performance_analyzed_files": coverage.analyzed_files if coverage else 0,
+ "performance_skipped_files": coverage.skipped_files if coverage else 0,
+ "performance_unsupported_languages": (coverage.unsupported_languages if coverage else []),
+ }
+
+
+def _compute_kpis(
+ metrics: list[HealthFileMetric],
+ *,
+ performance_findings: int = 0,
+ coverage: PerfCoverage | None = None,
+) -> dict[str, Any]:
if not metrics:
return {
"file_count": 0,
@@ -219,6 +249,7 @@ def _compute_kpis(metrics: list[HealthFileMetric]) -> dict[str, Any]:
"worst_performer_score": None,
"maintainability_average": None,
"performance_average": None,
+ **_perf_kpis(0, 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
@@ -233,6 +264,8 @@ def _compute_kpis(metrics: list[HealthFileMetric]) -> dict[str, Any]:
# defect-backed average. Each is ``None`` until its pillar is measured.
"maintainability_average": _dimension_average(metrics, "maintainability_score"),
"performance_average": _dimension_average(metrics, "performance_score"),
+ # Performance leads with count + density + coverage, not the diluted /10.
+ **_perf_kpis(performance_findings, coverage),
}
@@ -308,6 +341,9 @@ async def get_health(
file_targets = [t for t in raw_targets if not t.startswith("module:")]
ctx = await _resolve_repo_context(repo)
+ # Performance headline inputs (dashboard mode): filled inside the session.
+ perf_coverage: PerfCoverage | None = None
+ perf_findings_count = 0
async with get_session(ctx.session_factory) as session:
repository = await _get_repo(session, repo)
@@ -352,6 +388,16 @@ async def get_health(
exclude_spec,
)
+ # Dashboard perf headline: coverage (how much of the analyzed code the
+ # perf pass ran on) + open performance-finding count. finding_rows in
+ # dashboard mode is the complete open set, so the count is exact.
+ if not effective_targets:
+ lang_by_path = await get_file_language_map(session, repository.id)
+ perf_coverage = coverage_for_metrics(all_metrics, lang_by_path)
+ perf_findings_count = sum(
+ 1 for f in finding_rows if (f.dimension or "defect") == "performance"
+ )
+
# Structured refactoring plans (Extract Class, ...) — loaded only when
# asked for, scoped to the same targets, exclude-filtered like findings.
refactoring_rows: list[Any] = []
@@ -412,7 +458,11 @@ async def get_health(
if "trend" in include_set or effective_targets:
snapshots = await list_health_snapshots(session, repository.id, limit=20)
- kpis = _compute_kpis(metric_rows if effective_targets else all_metrics)
+ kpis = _compute_kpis(
+ metric_rows if effective_targets else all_metrics,
+ performance_findings=perf_findings_count,
+ coverage=perf_coverage,
+ )
# Dominant-cause lead per file, from the findings already loaded (targeted
# findings are scoped to the targets; dashboard findings cover every file).
leads = _leads_by_file(finding_rows)
@@ -459,7 +509,9 @@ async def get_health(
"mode": "dashboard",
"kpis": kpis,
"distribution": health_distribution(all_metrics),
- "worst_files": [_serialize_metric(m, leads.get(m.file_path)) for m in metric_rows[:limit]],
+ "worst_files": [
+ _serialize_metric(m, leads.get(m.file_path)) for m in metric_rows[:limit]
+ ],
"top_findings": [_serialize_finding(f) for f in finding_rows[:limit]],
"modules": _module_rollups(all_metrics),
}
diff --git a/packages/ui/src/health/biomarker-glossary.ts b/packages/ui/src/health/biomarker-glossary.ts
index 2009562bd..856eae6a0 100644
--- a/packages/ui/src/health/biomarker-glossary.ts
+++ b/packages/ui/src/health/biomarker-glossary.ts
@@ -249,6 +249,18 @@ export const BIOMARKER_GLOSSARY: Record<string, BiomarkerInfo> = {
description:
"A synchronous blocking call (time.sleep, requests.get, subprocess.run) inside an async function blocks the whole event loop, stalling every other coroutine. Mirrors ruff's ASYNC210/230/251.",
},
+ regex_compile_in_loop: {
+ label: "Regex compiled in loop",
+ category: "performance",
+ description:
+ "A regex with a static pattern compiled every loop iteration (Pattern.compile, regexp.MustCompile, Regex::new) instead of once. Compilation dominates matching, so recompiling a constant pattern is wasted work. Fires only where the language does not cache compiled patterns (Java, Go, Rust). Hoist the compile outside the loop.",
+ },
+ defer_in_loop: {
+ label: "Defer in loop",
+ category: "performance",
+ description:
+ "A Go `defer` inside a loop runs when the enclosing function returns, not at the end of the iteration, so a resource opened-and-deferred each iteration stays held until the function exits — the classic file-handle / *sql.Rows leak. Close it in the loop body, or wrap the body in its own function so the defer fires per iteration.",
+ },
resource_construction_in_loop: {
label: "Resource built in loop",
category: "performance",
@@ -376,6 +388,8 @@ export const PERFORMANCE_HOME_BIOMARKERS: ReadonlySet<string> = new Set([
"io_in_loop",
"string_concat_in_loop",
"blocking_sync_in_async",
+ "regex_compile_in_loop",
+ "defer_in_loop",
"resource_construction_in_loop",
"lock_in_loop",
"serial_await_in_loop",
diff --git a/tests/unit/generation/test_editor_file_base.py b/tests/unit/generation/test_editor_file_base.py
index b301ba234..12256f9dd 100644
--- a/tests/unit/generation/test_editor_file_base.py
+++ b/tests/unit/generation/test_editor_file_base.py
@@ -54,6 +54,8 @@ def test_render_contains_repo_name(gen):
def _health_block(
maintainability_average: float | None,
performance_average: float | None = None,
+ performance_findings: int = 0,
+ performance_coverage_pct: float | None = None,
) -> CodeHealthBlock:
return CodeHealthBlock(
hotspot_health=5.0,
@@ -62,6 +64,8 @@ def _health_block(
worst_path="src/bad.py",
maintainability_average=maintainability_average,
performance_average=performance_average,
+ performance_findings=performance_findings,
+ performance_coverage_pct=performance_coverage_pct,
)
@@ -87,10 +91,16 @@ def test_render_surfaces_performance_when_present(gen):
import dataclasses
data = dataclasses.replace(
- _minimal_data(), code_health=_health_block(6.4, performance_average=9.2)
+ _minimal_data(),
+ code_health=_health_block(
+ 6.4, performance_average=9.2, performance_findings=7, performance_coverage_pct=88.0
+ ),
)
result = gen.render(data)
- assert "Performance risk, Average: 9.2/10" in result
+ # Leads with the finding COUNT + coverage, not the bounded /10.
+ assert "Performance risk: 7 open findings" in result
+ assert "Average: 9.2/10" in result
+ assert "perf detectors ran on 88.0% of analyzed code lines" in result
def test_render_omits_performance_when_unmeasured(gen):
@@ -100,7 +110,7 @@ def test_render_omits_performance_when_unmeasured(gen):
result = gen.render(data)
# Maintainability still renders; the performance line is suppressed.
assert "Maintainability, Average: 6.4/10" in result
- assert "Performance risk, Average" not in result
+ assert "Performance risk:" not in result
def test_write_creates_new_file(gen, tmp_path):
diff --git a/tests/unit/server/test_health_excludes.py b/tests/unit/server/test_health_excludes.py
index 64a8abed5..7cedb401c 100644
--- a/tests/unit/server/test_health_excludes.py
+++ b/tests/unit/server/test_health_excludes.py
@@ -96,6 +96,12 @@ async def test_health_reads_honor_repo_settings_excludes(session, tmp_path) -> N
"performance_average": None,
"maintainability_findings": 0,
"performance_findings": 0,
+ "performance_findings_density": None,
+ "performance_coverage_pct": None,
+ "performance_covered_files": 0,
+ "performance_analyzed_files": 0,
+ "performance_skipped_files": 0,
+ "performance_unsupported_languages": [],
"worst_performance_path": None,
"worst_performance_score": None,
}