Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
refactor(health): one owner for the code-health read models (#2046)
Raghav Chamadiyaf5a5f15bdc03
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.mdindex ad8bc01a0..61fcaee28 100644--- a/docs/architecture/code-health.md+++ b/docs/architecture/code-health.md@@ -63,6 +63,8 @@ analysis/health/├── __init__.py # public API: HealthAnalyzer, HealthReport├── engine.py # orchestrator: walker → biomarkers → scorer├── scoring.py # weighted aggregation, category caps, KPIs+├── ranking.py # canonical worst-first key + deduction fold+├── aggregation.py # module rollups, severity/biomarker/score breakdowns├── grading.py # 3 defect-backed bands + NLOC-weighted distribution├── defect_accuracy.py # "does the score find the bugs?" self-validation├── trends.py # snapshot diff, Declining/Predicted alerts, per-file score seriesdiff --git a/packages/cli/src/repowise/cli/commands/health_cmd/summary.py b/packages/cli/src/repowise/cli/commands/health_cmd/summary.pyindex a145e43fc..516197ed3 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/summary.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/summary.py@@ -101,8 +101,13 @@ def _render_defect_accuracy_line(report: Any) -> None:"""try:from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracy+ from repowise.core.analysis.health.ranking import deduction_by_path- stat = compute_defect_accuracy(report.metrics, report.findings)+ stat = compute_defect_accuracy(+ report.metrics,+ report.findings,+ deductions=deduction_by_path(report.findings),+ )except Exception:returnif not stat:diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py b/packages/cli/src/repowise/cli/commands/init_cmd/reporting.pyindex 73e0ff5a0..d65a082ed 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py@@ -90,8 +90,13 @@ def _render_defect_accuracy(result: Any) -> None:returntry:from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracy+ from repowise.core.analysis.health.ranking import deduction_by_path- stat = compute_defect_accuracy(report.metrics, report.findings)+ stat = compute_defect_accuracy(+ report.metrics,+ report.findings,+ deductions=deduction_by_path(report.findings),+ )except Exception:returnif not stat:diff --git a/packages/core/src/repowise/core/analysis/health/README.md b/packages/core/src/repowise/core/analysis/health/README.mdindex dbc6b93e8..61964f38d 100644--- a/packages/core/src/repowise/core/analysis/health/README.md+++ b/packages/core/src/repowise/core/analysis/health/README.md@@ -127,12 +127,23 @@ text used by both the MCP `get_health(include=["refactoring"])` response andthe dashboard's `RefactoringCard`. Templates live in `suggestions.py` —adding a new marker means adding a new `_TEMPLATES` entry.-## Module rollups+## Ranking and aggregation++`ranking.py` and `aggregation.py` are the one owner for the arithmetic that+used to be reimplemented per caller: worst-first ordering+(`sort_metrics_worst_first`, `worst_metric`), module rollups+(`module_rollups`), and the severity / biomarker / score breakdowns+(`severity_breakdown`, `biomarker_breakdown`, `score_breakdown`). Both are+pure folds over rows a caller has already loaded, read through+`rows.field`/`rows.detail_map` so a mapping, an analyzer dataclass and an ORM+row rank and roll up identically. Neither imports persistence, a session, or+the analyzer engine.`HealthFileMetric.module` is populated from graph community labels by theorchestrator (falls back to the top-level directory). The MCP tool-(`tool_health.py`) and the API endpoint (`routers/code_health.py`) both-expose NLOC-weighted module aggregates and accept `module:foo` targets.+(`tool_health.py`) and the API endpoint (`routers/code_health/`) both call+`aggregation.module_rollups` for NLOC-weighted module aggregates and accept+`module:foo` targets.## Sub-packagesdiff --git a/packages/core/src/repowise/core/analysis/health/__init__.py b/packages/core/src/repowise/core/analysis/health/__init__.pyindex 1bdb2b4db..5555e9b7a 100644--- a/packages/core/src/repowise/core/analysis/health/__init__.py+++ b/packages/core/src/repowise/core/analysis/health/__init__.py@@ -3,11 +3,25 @@Public surface kept minimal. Engine + report types only — sub-packagesare accessed directly by their owners (pipeline orchestrator, MCP tool,tests).++The engine is bound on first attribute access rather than at import. Importing+it eagerly loaded ingestion, git blame and, through them, persistence — for+*any* import under this package, including the record adapters in ``rows`` and+the pure folds in ``ranking``, ``aggregation`` and ``trends``. Persistence+importing one of those back then closed a real cycle, which is why the crud+layer had to defer its own import of ``rows``. ``from ... import+HealthAnalyzer`` still works and still loads the engine; only the cost of *not*+asking for it went away.++Half the job: ``scoring`` keeps its one biomarker import behind ``TYPE_CHECKING``+for the same reason. Undoing either brings the whole tail back, and+``tests/unit/health/test_lightweight_health_imports.py`` fails if one is."""from __future__ import annotations-from .engine import HEALTH_ANALYZER_VERSION, HealthAnalyzer+from typing import TYPE_CHECKING, Any+from .models import (HealthFileMetricData,HealthFindingData,@@ -15,6 +29,11 @@ from .models import (Severity,)+if TYPE_CHECKING:+ from .engine import HEALTH_ANALYZER_VERSION, HealthAnalyzer++_ENGINE_EXPORTS = frozenset({"HEALTH_ANALYZER_VERSION", "HealthAnalyzer"})+__all__ = ["HEALTH_ANALYZER_VERSION","HealthAnalyzer",@@ -23,3 +42,16 @@ __all__ = ["HealthReport","Severity",]+++def __getattr__(name: str) -> Any:+ if name in _ENGINE_EXPORTS:+ from . import engine++ return getattr(engine, name)+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+++def __dir__() -> list[str]:+ """Everything really bound, plus the two names that bind on access."""+ return sorted(set(globals()) | _ENGINE_EXPORTS)diff --git a/packages/core/src/repowise/core/analysis/health/aggregation.py b/packages/core/src/repowise/core/analysis/health/aggregation.pynew file mode 100644index 000000000..fee1305e3--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/aggregation.py@@ -0,0 +1,245 @@+"""Folds over already-loaded health metrics and findings.++Every function here is pure: it takes rows a caller has already read and gives+back plain data. Rows are read through :func:`..rows.field` / :func:`..rows.detail_map`,+so a mapping, an analyzer dataclass and an ORM row all fold identically.++This module owns the arithmetic that REST and the MCP tool used to hold one copy+of each. Response composition, pagination and wire naming stay with the callers.+"""++from __future__ import annotations++from collections.abc import Iterable, Mapping, Sequence+from typing import Any++from .models import Severity+from .ranking import worst_metric+from .rows import detail_map, field+from .scoring import (+ CATEGORY_CAPS,+ SCORE_FLOOR,+ SCORE_MAX,+ biomarker_category,+ biomarker_weight,+ severity_deduction,+)++__all__ = [+ "MODULE_ROOT_LABEL",+ "SEVERITY_ORDER",+ "biomarker_breakdown",+ "finding_base_deduction",+ "module_label",+ "module_rollups",+ "score_breakdown",+ "severity_breakdown",+]++#: Label for a file that sits directly in the repository root.+MODULE_ROOT_LABEL = "root"++#: The buckets a severity breakdown always declares, worst first. Fixed rather+#: than derived from the data so an absent severity reads as 0, not as missing.+SEVERITY_ORDER: tuple[str, ...] = ("critical", "high", "medium", "low")+++def module_label(file_path: str | None) -> str:+ """The top-level directory of *file_path*, or :data:`MODULE_ROOT_LABEL`.++ Only the first segment: ``a/b/c.py`` is ``a`` at any depth. A path with no+ separator has no directory to name, so it rolls up under the root label+ rather than under itself — otherwise every root-level file would be its own+ single-file module.++ Distinct from ``HealthFileMetric.module``, which is the resolved package+ boundary. The two answer different questions and are not interchangeable.+ """+ head, separator, _ = (file_path or "").partition("/")+ return head if separator else MODULE_ROOT_LABEL+++def _nloc(row: Any) -> int:+ """A row's NLOC as a non-negative int; a missing or null value is 0."""+ try:+ return max(int(field(row, "nloc", 0) or 0), 0)+ except (TypeError, ValueError):+ return 0+++def _score(row: Any) -> float:+ """A row's score; an unmeasured one reads as perfect, not as the worst.++ Tested for ``None`` rather than falsiness: a real ``0.0`` is a score, and+ ``or`` would turn the worst possible file into the best. Unreachable while+ the floor clamps at 1.0, and wrong the moment a legacy row does not.+ """+ score = field(row, "score", SCORE_MAX)+ return float(SCORE_MAX if score is None else score)+++def _severity_key(value: Any) -> Any:+ """A severity in the form the scoring tables are keyed on.++ ``Severity`` is a ``StrEnum``, so a member and its lowercase value are the+ same key. A legacy row carrying an unknown or differently-cased string is+ normalized rather than rejected: the lookup tables already default, and a+ malformed stored severity must not turn a read into an error.+ """+ if isinstance(value, Severity):+ return value+ return str(value or "").lower()+++def module_rollups(+ metrics: Iterable[Any],+ deductions: Mapping[str, float] | None = None,+) -> list[dict[str, Any]]:+ """NLOC-weighted rollups keyed on each row's ``module``.++ Rows without a module are dropped — an unresolved package boundary is not a+ module named ``None``. Worst modules first; ties break on the module name so+ a page boundary is stable across requests.++ *deductions* feeds each module's worst performer the same key the repo-wide+ ranking uses. Passing it is what makes that choice deduction-aware in its own+ right: without it the pick still comes out of the score, but a module whose+ files are all held at the floor resolves on the path instead of on depth.+ """+ buckets: dict[str, list[Any]] = {}+ for row in metrics:+ module = field(row, "module", None)+ if module:+ buckets.setdefault(str(module), []).append(row)++ rows: list[dict[str, Any]] = []+ for name, group in buckets.items():+ # Weight floors at 1 per file, so a non-empty group always has weight+ # and the average never divides by zero.+ total_weight = sum(max(_nloc(row), 1) for row in group)+ average = sum(_score(row) * max(_nloc(row), 1) for row in group) / total_weight+ worst = worst_metric(group, deductions or {})+ rows.append(+ {+ "module": name,+ "file_count": len(group),+ "nloc": sum(_nloc(row) for row in group),+ "average_health": round(average, 2),+ "worst_performer_path": field(worst, "file_path", None),+ "worst_performer_score": round(_score(worst), 2),+ }+ )+ rows.sort(key=lambda row: (row["average_health"], row["module"]))+ return rows+++def severity_breakdown(findings: Iterable[Any]) -> dict[str, int]:+ """Counts per declared severity. Unrecognized severities are not counted.++ A ``Severity`` member and its lowercase string are the same dict key, and+ ``dict`` keeps the key it was built with — so the returned keys stay plain+ strings even when every finding carried an enum. Do not "fix" that by+ coercing: the wire shape depends on it.+ """+ out = dict.fromkeys(SEVERITY_ORDER, 0)+ for finding in findings:+ severity = _severity_key(field(finding, "severity", None))+ if severity in out:+ out[severity] += 1+ return out+++def biomarker_breakdown(findings: Iterable[Any]) -> list[dict[str, Any]]:+ """Per-biomarker counts split by severity, busiest first.++ ``total`` counts every finding of that biomarker, including one whose+ severity matched no bucket, so it is the honest count and can exceed the+ sum of the four columns. Ties break on the biomarker name.+ """+ by_type: dict[str, dict[str, int]] = {}+ for finding in findings:+ name = field(finding, "biomarker_type", None)+ severity = _severity_key(field(finding, "severity", None))+ bucket = by_type.setdefault(name, {**dict.fromkeys(SEVERITY_ORDER, 0), "total": 0})+ if severity in bucket:+ bucket[severity] += 1+ bucket["total"] += 1+ rows = [{"biomarker_type": name, **counts} for name, counts in by_type.items()]+ rows.sort(key=lambda row: (-row["total"], str(row["biomarker_type"])))+ return rows+++def finding_base_deduction(finding: Any) -> float:+ """The pre-cap, pre-weight base deduction for one finding.++ Mirrors ``scoring.score_file``: a continuous ``deduction`` recorded in the+ finding's details (the coverage gradient scales with the uncovered fraction)+ takes the place of the discrete severity table. Reading the override here is+ what lets a breakdown show the continuous signal rather than a band proxy.+ """+ override = detail_map(finding).get("deduction")+ if isinstance(override, (int, float)):+ return float(override)+ return severity_deduction(_severity_key(field(finding, "severity", None)))+++def score_breakdown(findings: Sequence[Any]) -> dict[str, Any]:+ """Reconstruct one file's per-category deductions from its open findings.++ The applied impact is the **stored** ``health_impact`` — the exact+ already-weighted-and-capped value the scorer produced at index time — so the+ breakdown reproduces the file's score instead of re-deriving it. Only the+ raw (pre-cap) figure is reconstructed, with the same ``base x weight``+ formula, so a capped category is honest about how much it shed.++ Categories are emitted in :data:`CATEGORY_CAPS` order and a category with no+ findings is omitted, not zero-filled.+ """+ per_category: dict[str, list[Any]] = {}+ for finding in findings:+ category = biomarker_category(field(finding, "biomarker_type", None))+ per_category.setdefault(category, []).append(finding)++ categories: list[dict[str, Any]] = []+ total_deduction = 0.0+ for category, cap in CATEGORY_CAPS.items():+ entries = per_category.get(category, [])+ if not entries:+ continue+ raw_each = [+ finding_base_deduction(f) * biomarker_weight(field(f, "biomarker_type", None))+ for f in entries+ ]+ applied_each = [float(field(f, "health_impact", 0.0) or 0.0) for f in entries]+ raw_sum = sum(raw_each)+ applied_sum = sum(applied_each)+ categories.append(+ {+ "category": category,+ "cap": round(cap, 2),+ "raw_deduction": round(raw_sum, 3),+ "applied_deduction": round(applied_sum, 3),+ # Category shed weight iff its applied total is held at the cap.+ "capped": applied_sum < raw_sum - 1e-6,+ "finding_count": len(entries),+ "findings": [+ {+ "id": field(f, "id", None),+ "biomarker_type": field(f, "biomarker_type", None),+ "severity": field(f, "severity", None),+ "raw_impact": round(raw, 3),+ "applied_impact": round(applied, 3),+ "function_name": field(f, "function_name", None),+ "reason": field(f, "reason", None),+ }+ for f, raw, applied in zip(entries, raw_each, applied_each, strict=True)+ ],+ }+ )+ total_deduction += applied_sum+ score = max(SCORE_FLOOR, min(SCORE_MAX, SCORE_MAX - total_deduction))+ return {+ "score": round(score, 2),+ "total_deduction": round(total_deduction, 3),+ "categories": categories,+ }diff --git a/packages/core/src/repowise/core/analysis/health/defect_accuracy.py b/packages/core/src/repowise/core/analysis/health/defect_accuracy.pyindex 3d138b9f8..c7e9f735f 100644--- a/packages/core/src/repowise/core/analysis/health/defect_accuracy.py+++ b/packages/core/src/repowise/core/analysis/health/defect_accuracy.py@@ -20,30 +20,27 @@ hosted backend (``health.json`` dicts) without per-call-site adapters.from __future__ import annotations+from collections.abc import Mappingfrom typing import Any+from .ranking import sort_metrics_worst_first+from .rows import detail_map, field+_DEFAULT_K = 20_MIN_FILES = 25 # below this a precision@K headline is noise_MIN_DEFECT_FILES = 5 # need a real positive class to divide by_DEFAULT_WINDOW_DAYS = 180-def _get(obj: Any, key: str, default: Any = None) -> Any:- """Read ``key`` from a mapping or an attribute-bearing object."""- if isinstance(obj, dict):- return obj.get(key, default)- return getattr(obj, key, default)--def _recent_fix_counts(findings: list[Any]) -> tuple[dict[str, int], int]:"""Map file_path -> recent bug-fix count, plus the window in days."""counts: dict[str, int] = {}window_days = _DEFAULT_WINDOW_DAYSfor f in findings:- if _get(f, "biomarker_type") != "prior_defect":+ if field(f, "biomarker_type") != "prior_defect":continue- details = _get(f, "details") or {}- path = _get(f, "file_path", "")+ details = detail_map(f)+ path = field(f, "file_path", "")counts[path] = int(details.get("prior_defect_count", 1) or 1)window_days = int(details.get("window_days", window_days) or window_days)counts.pop("", None)@@ -55,23 +52,37 @@ def compute_defect_accuracy(findings: list[Any],*,k: int = _DEFAULT_K,+ deductions: Mapping[str, float] | None = None,) -> dict[str, Any] | None:"""Precision-style accuracy summary, or ``None`` when there isn't enough- signal to show an honest number (too few files / too few defects)."""- scored = [m for m in metrics if _get(m, "file_path")]+ signal to show an honest number (too few files / too few defects).++ *deductions* is ``{file_path: summed health_impact}`` over the repo's whole+ open finding set — :func:`..ranking.deduction_by_path` builds it. It is a+ parameter rather than a fold over *findings* because callers pass only the+ ``prior_defect`` rows this stat reads, and a map summed from that slice+ would rank on a fraction of each file's real depth. Without it the ranking+ is still total and deterministic, but the floor-tied band is ordered by path+ and so need not match the worst-files list this stat validates.+ """+ scored = [m for m in metrics if field(m, "file_path")]n = len(scored)fix_counts, window_days = _recent_fix_counts(findings)- total_defect_files = sum(- 1 for m in scored if fix_counts.get(_get(m, "file_path"), 0) > 0- )+ total_defect_files = sum(1 for m in scored if fix_counts.get(field(m, "file_path"), 0) > 0)if n < _MIN_FILES or total_defect_files < _MIN_DEFECT_FILES:return None- ranked = sorted(scored, key=lambda m: float(_get(m, "score", 10.0)))+ # The canonical worst-first order, not a plain score sort. The score clamps+ # at the floor, so a score-only sort left the tied band in whatever order it+ # arrived in, and this stat then measured a different top-K than the+ # worst-files list it exists to validate. ``flagged_files``, precision@K and+ # the concentration share all slice this one list, so they cannot disagree+ # about membership.+ ranked = sort_metrics_worst_first(scored, deductions or {})def hits_in(top: list[Any]) -> int:- return sum(1 for m in top if fix_counts.get(_get(m, "file_path"), 0) > 0)+ return sum(1 for m in top if fix_counts.get(field(m, "file_path"), 0) > 0)kk = min(k, n)hits = hits_in(ranked[:kk])@@ -93,9 +104,9 @@ def compute_defect_accuracy(# The flagged files themselves, for a bulletproof drill-down.sample = [{- "file_path": _get(m, "file_path"),- "score": round(float(_get(m, "score", 10.0)), 2),- "recent_fixes": fix_counts.get(_get(m, "file_path"), 0),+ "file_path": field(m, "file_path"),+ "score": round(float(field(m, "score", 10.0)), 2),+ "recent_fixes": fix_counts.get(field(m, "file_path"), 0),}for m in ranked[:kk]]diff --git a/packages/core/src/repowise/core/analysis/health/grading.py b/packages/core/src/repowise/core/analysis/health/grading.pyindex 13d34bbde..d44e69667 100644--- a/packages/core/src/repowise/core/analysis/health/grading.py+++ b/packages/core/src/repowise/core/analysis/health/grading.py@@ -22,6 +22,8 @@ from __future__ import annotationsfrom typing import Any, Literal+from .rows import field+HealthBand = Literal["healthy", "warning", "alert"]# Canonical band cutoffs. Frozen (scoring is frozen; this is presentation).@@ -48,13 +50,6 @@ def band_for(score: float) -> HealthBand:return "healthy"-def _get(obj: Any, key: str, default: Any = None) -> Any:- """Read ``key`` from a mapping or an attribute-bearing object."""- if isinstance(obj, dict):- return obj.get(key, default)- return getattr(obj, key, default)--def distribution(metrics: list[Any]) -> dict[str, Any]:"""NLOC-weighted file distribution across the 3 bands.@@ -70,10 +65,10 @@ def distribution(metrics: list[Any]) -> dict[str, Any]:total_files = 0total_weight = 0for m in metrics:- if _get(m, "file_path") is None:+ if field(m, "file_path") is None:continue- score = float(_get(m, "score", 10.0))- weight = max(int(_get(m, "nloc", 0) or 0), 1)+ score = float(field(m, "score", 10.0))+ weight = max(int(field(m, "nloc", 0) or 0), 1)band = band_for(score)bands[band]["files"] += 1bands[band]["nloc"] += weightdiff --git a/packages/core/src/repowise/core/analysis/health/perf/coverage.py b/packages/core/src/repowise/core/analysis/health/perf/coverage.pyindex 66856c655..dbc096c2b 100644--- a/packages/core/src/repowise/core/analysis/health/perf/coverage.py+++ b/packages/core/src/repowise/core/analysis/health/perf/coverage.py@@ -18,11 +18,12 @@ feeds it lives in the persistence layer.from __future__ import annotationsfrom collections import Counter-from collections.abc import Iterable+from collections.abc import Iterable, Mappingfrom dataclasses import dataclass, field-from typing import Protocol+from typing import Any, Protocolfrom ..complexity.languages import LANGUAGE_MAPS+from ..rows import field as _row_field # aliased: ``field`` here is dataclasses'from .dialects import PERF_DIALECTS@@ -32,7 +33,10 @@ def supported_perf_languages() -> frozenset[str]:class _FileMetricRow(Protocol):- """The two fields coverage needs off a per-file metric row (duck-typed)."""+ """The two fields coverage needs off a per-file metric row (duck-typed).++ A mapping carrying the same two keys is read identically.+ """file_path: strnloc: int@@ -109,7 +113,7 @@ def compute_perf_coverage(def coverage_for_metrics(- metrics: Iterable[_FileMetricRow],+ metrics: Iterable[_FileMetricRow | Mapping[str, Any]],lang_by_path: dict[str, str],*,supported: frozenset[str] | None = None,@@ -122,9 +126,12 @@ def coverage_for_metrics(never dilute the coverage math. *lang_by_path* maps ``file_path`` → languagetag (from the graph's file nodes)."""+ # One language lookup per row rather than one per row per clause: this runs+ # over the whole metrics table on every read that reports coverage.+ tagged = ((lang_by_path.get(_row_field(m, "file_path"), ""), m) for m in metrics)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+ (language, int(_row_field(row, "nloc", 0) or 0))+ for language, row in tagged+ if language in LANGUAGE_MAPS]return compute_perf_coverage(code_rows, supported=supported)diff --git a/packages/core/src/repowise/core/analysis/health/ranking.py b/packages/core/src/repowise/core/analysis/health/ranking.pynew file mode 100644index 000000000..a73aaf35f--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/ranking.py@@ -0,0 +1,84 @@+"""Worst-first ordering of per-file health metrics.++One comparator, so no two surfaces can disagree about which file is worst.+``score`` alone cannot rank the band that matters: it clamps at+:data:`~repowise.core.analysis.health.scoring.SCORE_FLOOR`, so on a real repo+dozens of files tie there and a list sorted on score alone comes back in+whatever order its source happened to produce.++Every function here reads its rows through :func:`..rows.field`, so a mapping,+an analyzer dataclass and an ORM row all rank identically. Nothing here loads+persistence, a session, or the analyzer engine.+"""++from __future__ import annotations++from collections.abc import Iterable, Mapping, Sequence+from typing import Any++from .rows import field+from .scoring import SCORE_MAX++__all__ = [+ "deduction_by_path",+ "sort_metrics_worst_first",+ "worst_first_key",+ "worst_metric",+]+++def deduction_by_path(findings: Iterable[Any]) -> dict[str, float]:+ """``{file_path: summed health_impact}`` over already-loaded findings.++ The in-memory twin of the persistence layer's grouped ``SUM`` aggregate, for+ callers that hold the findings anyway and must not pay a second query.+ ``health_impact`` is the applied (category-capped) contribution the scorer+ used, so the sum equals the breakdown endpoint's ``total_deduction``.++ Findings are summed as given: filtering to a status is the caller's, since+ a caller that already narrowed its rows must not be narrowed again.+ """+ totals: dict[str, float] = {}+ for finding in findings:+ path = field(finding, "file_path", None)+ if not path:+ continue+ totals[path] = totals.get(path, 0.0) + float(field(finding, "health_impact", 0.0) or 0.0)+ return totals+++def worst_first_key(row: Any, deductions: Mapping[str, float]) -> tuple[float, float, str]:+ """The canonical ranking key: ``(score asc, deduction desc, path asc)``.++ ``deduction`` is the pre-clamp magnitude, so it keeps ranking below the+ floor: a -25 file sorts above a -9 file that prints the same 1.0. A file+ absent from the map has no findings and so no magnitude, which is 0.0. The+ trailing path makes the order total, so a page boundary is stable across+ requests instead of shuffling two otherwise equal rows.++ *deductions* has no default. A caller that omits it does not get a slightly+ worse order, it gets the floor band tied on path — the exact bug this key+ exists to fix — and would get it silently. Pass ``{}`` to say out loud that+ there is no magnitude to rank on.+ """+ path = str(field(row, "file_path", "") or "")+ magnitude = float(deductions.get(path, 0.0))+ # An unscored row reads as a perfect score rather than the worst one: a+ # missing measurement is not evidence of a problem.+ score = field(row, "score", SCORE_MAX)+ return (float(SCORE_MAX if score is None else score), -magnitude, path)+++def sort_metrics_worst_first(rows: Sequence[Any], deductions: Mapping[str, float]) -> list[Any]:+ """Order per-file metrics worst-first. Pure: the input list is untouched."""+ return sorted(rows, key=lambda row: worst_first_key(row, deductions))+++def worst_metric(rows: Iterable[Any], deductions: Mapping[str, float]) -> Any | None:+ """The single worst row under the same key, or ``None`` for no rows.++ Identical to ``sort_metrics_worst_first(rows, deductions)[0]`` without+ sorting the tail. Sharing the key is what keeps a repo's headline "worst+ performer" from naming a different file than the worst-files list under it.+ """+ return min(rows, key=lambda row: worst_first_key(row, deductions), default=None)diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/identity.py b/packages/core/src/repowise/core/analysis/health/refactoring/identity.pyindex 6acc61b16..56d723f4c 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/identity.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/identity.py@@ -22,6 +22,8 @@ import jsonimport refrom typing import Any+from ..rows import field+REFACTORING_MODEL_VERSION = 2"""Version of the identity semantics. v1 was the fresh-UUID-per-index era.@@ -70,16 +72,10 @@ def _evidence_of(suggestion: Any) -> dict:return evidence if isinstance(evidence, dict) else {}-def _field(suggestion: Any, name: str, default: Any = None) -> Any:- if isinstance(suggestion, dict):- return suggestion.get(name, default)- return getattr(suggestion, name, default)--def _span_length(suggestion: Any) -> int | None:"""Span size, which survives the whole block moving down the file."""- start = _field(suggestion, "line_start")- end = _field(suggestion, "line_end")+ start = field(suggestion, "line_start")+ end = field(suggestion, "line_end")if isinstance(start, int) and isinstance(end, int):return end - startreturn None@@ -152,7 +148,7 @@ def _extract_class_kernel(suggestion: Any, file_path: str) -> RefactoringKernel:return ("extract_class",file_path,- _field(suggestion, "target_symbol") or "",+ field(suggestion, "target_symbol") or "",tuple(membership),)@@ -180,7 +176,7 @@ def _extract_method_kernel(suggestion: Any, file_path: str) -> RefactoringKernelreturn ("extract_method",file_path,- _field(suggestion, "target_symbol") or "",+ field(suggestion, "target_symbol") or "",tuple(str(name) for name in (plan.get("params") or [])),tuple(str(name) for name in (plan.get("returns") or [])),_span_length(suggestion),@@ -208,7 +204,7 @@ def _generic_kernel(kind: str, suggestion: Any, file_path: str) -> RefactoringKereturn (kind,file_path,- _field(suggestion, "target_symbol") or "",+ field(suggestion, "target_symbol") or "",_span_length(suggestion),)@@ -219,9 +215,9 @@ def refactoring_kernel(suggestion: Any) -> RefactoringKernel:Accepts a detector dataclass, a plain dict, or a persisted ORM row: thethree describe the same plan and must reach the same string."""- kind = str(_field(suggestion, "refactoring_type") or "")- file_path = str(_field(suggestion, "file_path") or "")- biomarker = str(_field(suggestion, "source_biomarker") or "")+ kind = str(field(suggestion, "refactoring_type") or "")+ file_path = str(field(suggestion, "file_path") or "")+ biomarker = str(field(suggestion, "source_biomarker") or "")if kind == "performance_fix":# The performance layer already owns a versioned causal id for this@@ -291,9 +287,9 @@ def assign_public_ids(suggestions: list[Any]) -> list[str]:ordered = sorted(members,key=lambda index: (- str(_field(suggestions[index], "file_path") or ""),- _field(suggestions[index], "line_start") or 0,- str(_field(suggestions[index], "target_symbol") or ""),+ str(field(suggestions[index], "file_path") or ""),+ field(suggestions[index], "line_start") or 0,+ str(field(suggestions[index], "target_symbol") or ""),),)for ordinal, index in enumerate(ordered):diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.pyindex 8e3cce832..cb7f3c66f 100644--- a/packages/core/src/repowise/core/analysis/health/scoring.py+++ b/packages/core/src/repowise/core/analysis/health/scoring.py@@ -21,9 +21,17 @@ from __future__ import annotationsfrom collections.abc import Callable, Iterablefrom dataclasses import replace+from typing import TYPE_CHECKING, Any-from .biomarkers.base import BiomarkerResultfrom .models import HealthFileMetricData, HealthFindingData, Severity+from .rows import field++if TYPE_CHECKING:+ # Annotation-only, and deliberately not imported at runtime: the biomarker+ # package reaches ingestion and the tree-sitter grammars, which the scoring+ # tables, the ranking key and the read-model folds have no use for. Keeping+ # it behind the type gate is what makes those importable on their own.+ from .biomarkers.base import BiomarkerResult# The band every dimension's score is clamped into. Named because the floor is# lossy — a file 12.9 points deep and one 9.1 points deep both print 1.0 — and@@ -657,6 +665,15 @@ def attach_impacts(return out+def _weight(row: Any) -> int:+ """One row's NLOC weight, floored at 1 so no file weighs nothing."""+ return max(int(field(row, "nloc", 0) or 0), 1)+++def _row_score(row: Any) -> float:+ return float(field(row, "score", SCORE_MAX))++def _wavg_attr(rows: list[HealthFileMetricData], attr: str) -> float | None:"""NLOC-weighted average of one metric attribute, skipping ``None`` values.@@ -664,13 +681,13 @@ def _wavg_attr(rows: list[HealthFileMetricData], attr: str) -> float | None:``maintainability_score`` predates the split) so the KPI reads "not measured"rather than a misleading perfect 10.0."""- scored = [r for r in rows if getattr(r, attr, None) is not None]+ scored = [r for r in rows if field(r, attr, None) is not None]if not scored:return None- total_w = sum(max(r.nloc, 1) for r in scored)+ total_w = sum(_weight(r) for r in scored)if total_w == 0:- return sum(getattr(r, attr) for r in scored) / len(scored)- return sum(getattr(r, attr) * max(r.nloc, 1) for r in scored) / total_w+ return sum(float(field(r, attr)) for r in scored) / len(scored)+ return sum(float(field(r, attr)) * _weight(r) for r in scored) / total_wdef nloc_weighted_score(rows: list[HealthFileMetricData]) -> float:@@ -682,10 +699,10 @@ def nloc_weighted_score(rows: list[HealthFileMetricData]) -> float:"""if not rows:return 10.0- total_w = sum(max(r.nloc, 1) for r in rows)+ total_w = sum(_weight(r) for r in rows)if total_w == 0:- return sum(r.score for r in rows) / len(rows)- return sum(r.score * max(r.nloc, 1) for r in rows) / total_w+ return sum(_row_score(r) for r in rows) / len(rows)+ return sum(_row_score(r) * _weight(r) for r in rows) / total_wdef hotspot_health(@@ -713,7 +730,7 @@ def hotspot_health(when they have none. :func:`compute_kpis` still floors it to 10.0 for thepersisted KPI, and says why there."""- rows = [m for m in metrics if m.file_path in hotspot_paths]+ rows = [m for m in metrics if field(m, "file_path") in hotspot_paths]if not rows:return Nonereturn round(nloc_weighted_score(rows), 2)@@ -750,8 +767,8 @@ def compute_kpis("performance_hotspot": None,}- hotspots = [m for m in metrics if m.file_path in hotspot_paths]- worst = min(metrics, key=lambda m: m.score)+ hotspots = [m for m in metrics if field(m, "file_path") in hotspot_paths]+ worst = min(metrics, key=_row_score)maint_avg = _wavg_attr(metrics, "maintainability_score")maint_hotspot = _wavg_attr(hotspots, "maintainability_score")perf_avg = _wavg_attr(metrics, "performance_score")@@ -765,8 +782,8 @@ def compute_kpis(return {"hotspot_health": hotspot_kpi if hotspot_kpi is not None else 10.0,"average_health": round(nloc_weighted_score(metrics), 2),- "worst_performer_path": worst.file_path,- "worst_performer_score": round(worst.score, 2),+ "worst_performer_path": field(worst, "file_path"),+ "worst_performer_score": round(_row_score(worst), 2),"file_count": len(metrics),"maintainability_average": round(maint_avg, 2) if maint_avg is not None else None,"maintainability_hotspot": round(maint_hotspot, 2) if maint_hotspot is not None else None,diff --git a/packages/core/src/repowise/core/analysis/health/trends.py b/packages/core/src/repowise/core/analysis/health/trends.pyindex 9a7e63aac..145bc64c2 100644--- a/packages/core/src/repowise/core/analysis/health/trends.py+++ b/packages/core/src/repowise/core/analysis/health/trends.py@@ -27,10 +27,11 @@ cache with no observable effect on any return value.from __future__ import annotationsimport json+from collections.abc import Sequencefrom dataclasses import dataclass, fieldfrom datetime import datetimefrom functools import lru_cache-from typing import Any+from typing import Any, TypeAliasfrom .scoring import SCORE_FLOOR, SCORE_MAX@@ -257,6 +258,15 @@ def snapshot_file_maps(return per_file_scores, per_file_deductions+#: One normalized snapshot reading for a single file: when it was taken, the+#: clamped score, and the recorded pre-clamp deduction where the reading+#: captured one. The storage-neutral input to :func:`build_file_points`.+FileScoreReading: TypeAlias = tuple[datetime | None, float, float | None]++#: Readings needed before a per-file series is worth drawing.+MIN_TREND_POINTS: int = 2++@dataclassclass FileTrendPoint:"""One file's score at one snapshot.@@ -353,13 +363,13 @@ def _score_in_snapshot(snap: Any, file_path: str) -> float | None:return _value_in_snapshot(snap, "per_file_scores_json", file_path)-def _unclamped_in_snapshot(snap: Any, file_path: str, score: float) -> float | None:- """``file_path``'s score with the floor undone, as far as *snap* knows.+def _unclamped_score(score: float, deduction: float | None) -> float | None:+ """One reading's score with the floor undone, as far as it is known.Three cases, and the third is the one that matters:- * A recorded deduction means the clamp bit and this snapshot kept the- depth. The honest value is ``SCORE_MAX - deduction``, below the floor and+ * A recorded deduction means the clamp bit and the reading kept the depth.+ The honest value is ``SCORE_MAX - deduction``, below the floor andpossibly negative.* No deduction and a score above the floor: the clamp did not bite, so thescore already *is* the unclamped value.@@ -368,58 +378,79 @@ def _unclamped_in_snapshot(snap: Any, file_path: str, score: float) -> float | N``None`` — not ``score``, which would assert a depth of exactly 9.0 thatwas never measured."""- deduction = _value_in_snapshot(snap, "per_file_deductions_json", file_path)if deduction is not None:return round(SCORE_MAX - deduction, 2)return score if score > SCORE_FLOOR else None-def file_score_series(history: list[Any], file_path: str) -> list[FileTrendPoint]:- """A file's oldest-first score series across the snapshot window.-- Snapshots missing the file are skipped (gaps don't break the line).- Returns ``[]`` when fewer than two points are available so consumers can- render a "no history yet" state instead of a single misleading dot.+def build_file_points(+ readings: Sequence[FileScoreReading],+ *,+ min_points: int = MIN_TREND_POINTS,+) -> list[FileTrendPoint]:+ """Turn normalized readings into a file's oldest-first trend series.++ The correctness half of a per-file trend, over storage-neutral readings, so+ that where the numbers came from — a snapshot row here, something else+ elsewhere — stays entirely inside the adapter that produced them.++ Returns ``[]`` below *min_points*, so a consumer renders a "no history yet"+ state instead of a single misleading dot. The threshold is a parameter+ rather than a constant because it is a presentation floor, not a+ correctness one: two is right for a chart, and a consumer that can surface a+ lone reading honestly may ask for one.++ ``unclamped_score`` diverges from ``score`` only when **every** reading has+ a known depth. A series that mixes measured depth with readings that never+ recorded it is the dangerous case, not the harmless one: the unmeasured+ points read as ``1.0`` and the measured ones as their real depth, so the+ first index after depth capture is switched on draws a cliff on a file that+ did not change. Measured against the live index — fifteen snapshots without+ capture plus one with, and nothing altered — that flipped **21 of 32**+ floored files to ``declining`` with drops up to 3.9 points. Waiting for the+ window to fill costs a slow start; not waiting reports a collapse that+ never happened.+ """+ if len(readings) < min_points:+ return []+ depths = [_unclamped_score(score, deduction) for _, score, deduction in readings]+ depth_known = all(depth is not None for depth in depths)+ return [+ FileTrendPoint(+ taken_at=taken_at,+ score=score,+ unclamped_score=depth if depth_known and depth is not None else score,+ )+ for (taken_at, score, _), depth in zip(readings, depths, strict=True)+ ]- *history* is expected oldest-first (the natural ``list_health_snapshots``- order). This is the exact function the PR bot reuses for its in-comment- sparkline, so it stays free of any persistence or presentation concern.- ``unclamped_score`` diverges from ``score`` only when **every** point in- the series has a known depth. A series that mixes measured depth with- snapshots that never recorded it is the dangerous case, not the harmless- one: the unmeasured points read as ``1.0`` and the measured ones as their- real depth, so the first index after depth capture is switched on draws a- cliff on a file that did not change. Measured against the live index —- fifteen snapshots without capture plus one with, and nothing altered —- that flipped **21 of 32** floored files to ``declining`` with drops up to- 3.9 points. Waiting for the window to fill costs a slow start; not waiting- reports a collapse that never happened.- """- raw: list[tuple[Any, float, float | None]] = []+def _snapshot_readings(history: list[Any], file_path: str) -> list[FileScoreReading]:+ """Normalize one file out of the snapshot window. The storage adapter."""+ readings: list[FileScoreReading] = []for snap in history:score = _score_in_snapshot(snap, file_path)if score is None:continue- raw.append(+ readings.append((getattr(snap, "taken_at", None),score,- _unclamped_in_snapshot(snap, file_path, score),+ _value_in_snapshot(snap, "per_file_deductions_json", file_path),))- depth_known = all(unclamped is not None for _, _, unclamped in raw)- points = [- FileTrendPoint(- taken_at=taken_at,- score=score,- unclamped_score=unclamped if depth_known else score,- )- for taken_at, score, unclamped in raw- ]- if len(points) < 2:- return []- return points+ return readings+++def file_score_series(history: list[Any], file_path: str) -> list[FileTrendPoint]:+ """A file's oldest-first score series across the snapshot window.++ Snapshots missing the file are skipped (gaps don't break the line).+ *history* is expected oldest-first (the natural ``list_health_snapshots``+ order). This is the exact function the PR bot reuses for its in-comment+ sparkline, so it stays free of any persistence or presentation concern.+ """+ return build_file_points(_snapshot_readings(history, file_path))def _file_declining(points: list[FileTrendPoint]) -> bool:@@ -458,15 +489,24 @@ def _file_declining(points: list[FileTrendPoint]) -> bool:return False-def file_trend(history: list[Any], file_path: str) -> FileTrend:- """Assemble a file's :class:`FileTrend` from the snapshot history.+def file_trend_from_points(+ file_path: str,+ readings: Sequence[FileScoreReading],+ *,+ snapshot_count: int,+ min_points: int = MIN_TREND_POINTS,+) -> FileTrend:+ """Assemble a :class:`FileTrend` from normalized readings.++ The whole per-file trend contract with no storage in it. *snapshot_count*+ is the size of the caller's whole window rather than of *readings*, so a+ consumer can tell "young repo" from "file absent from older snapshots".- Wraps :func:`file_score_series` with the current value, the prior value,- their delta, and the declining flag. ``snapshot_count`` is the size of- the whole repo window (not just the points carrying this file) so the UI- can distinguish "young repo" from "file not in older snapshots".+ ``previous``, ``delta`` and ``unclamped_delta`` need two points and stay+ ``None`` on a series shorter than that — which only a caller passing+ ``min_points=1`` can see."""- points = file_score_series(history, file_path)+ points = build_file_points(readings, min_points=min_points)if not points:return FileTrend(file_path=file_path,@@ -475,9 +515,19 @@ def file_trend(history: list[Any], file_path: str) -> FileTrend:previous=None,delta=None,declining=False,- snapshot_count=len(history),+ snapshot_count=snapshot_count,)current = round(points[-1].score, 2)+ if len(points) < 2:+ return FileTrend(+ file_path=file_path,+ points=points,+ current=current,+ previous=None,+ delta=None,+ declining=False,+ snapshot_count=snapshot_count,+ )previous = round(points[-2].score, 2)return FileTrend(file_path=file_path,@@ -487,5 +537,17 @@ def file_trend(history: list[Any], file_path: str) -> FileTrend:delta=round(current - previous, 2),unclamped_delta=round(points[-1].unclamped_score - points[-2].unclamped_score, 2),declining=_file_declining(points),+ snapshot_count=snapshot_count,+ )+++def file_trend(history: list[Any], file_path: str) -> FileTrend:+ """A file's :class:`FileTrend` over the snapshot window.++ The snapshot adapter over :func:`file_trend_from_points`.+ """+ return file_trend_from_points(+ file_path,+ _snapshot_readings(history, file_path),snapshot_count=len(history),)diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.pyindex 060c291e5..265729399 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py@@ -14,6 +14,17 @@ from sqlalchemy.ext.asyncio import AsyncSessionif TYPE_CHECKING:from ....analysis.health.perf.coverage import PerfCoverage+from ....analysis.health.finding_identity import finding_public_id++# The comparator is pure and lives with the health read models; only the SQL+# that feeds it belongs here. Re-imported rather than moved out of reach: the+# crud surface is where the MCP tool and the tests already read it from.+from ....analysis.health.ranking import (+ deduction_by_path,+ sort_metrics_worst_first,+ worst_metric,+)+from ....analysis.health.rows import detail_mapfrom ...models import (GraphNode,HealthFileMetric,@@ -33,14 +44,6 @@ def _health_finding_row_kwargs(finding: Any, repository_id: str) -> dict:every path or by none. ``public_id`` is stamped here because this is theone place every persisted finding passes through."""- # Deferred: the analysis package imports persistence, so a module-level- # import here would close the cycle.-- # Deferred: the analysis package imports persistence, so importing it at- # module level here would close the cycle.- from ....analysis.health.finding_identity import finding_public_id- from ....analysis.health.rows import detail_map-if hasattr(finding, "biomarker_type"):severity = finding.severitydata = {@@ -401,30 +404,6 @@ async def get_deduction_by_path(return totals-def sort_metrics_worst_first(rows: list[Any], deduction_by_path: dict[str, float]) -> list[Any]:- """Order per-file metrics worst-first: ``(score asc, deduction desc, path)``.-- ``score`` alone cannot rank the band that matters. It clamps at 1.0, so on- a real repo dozens of files tie there and any list sorted on score alone- comes back in whatever order the DB happened to return — path order, in- practice. That put this repo's single worst file (12.9 points of deduction)- at position 27 of a list capped at 20.-- ``total_deduction`` is the pre-clamp magnitude, so it keeps ranking below- the floor: a -25 file sorts above a -9 file that prints the same 1.0. The- trailing ``file_path`` makes the order total, so a page boundary is stable- across requests instead of shuffling two equal rows.-- Shared with the MCP ``get_health`` tool, which builds its own deduction map- from findings it has already loaded rather than re-querying. One comparator- so REST, MCP and hosted cannot drift into three different "worst files".- """- return sorted(- rows,- key=lambda m: (m.score, -deduction_by_path.get(m.file_path, 0.0), m.file_path),- )--async def get_health_metrics(session: AsyncSession,repository_id: str,@@ -568,7 +547,6 @@ async def get_health_summary(avg = sum(m.score * max(m.nloc, 1) for m in metrics) / total_nlocelse:avg = sum(m.score for m in metrics) / len(metrics)- worst = min(metrics, key=lambda r: r.score)# Maintainability headline: NLOC-weighted average over the per-file# maintainability scores (skipping rows that predate the split / lack one).@@ -614,6 +592,14 @@ async def get_health_summary(if findings is None:findings = await get_health_findings(session, repository_id)++ # Ranked with the same key as ``get_health_metrics``, off the findings this+ # function already holds. Previously a plain ``min`` on the score, which+ # agreed with the worst-files list only because every caller happened to+ # pass an already-ranked list — a floor tie made the headline and the list+ # under it disagree the moment one did not.+ worst = worst_metric(metrics, deduction_by_path(findings))+by_dim: dict[str, int] = {}for finding in findings:dim = finding.dimension or "defect"diff --git a/packages/core/src/repowise/core/persistence/crud/external_systems.py b/packages/core/src/repowise/core/persistence/crud/external_systems.pyindex d3ace4805..de76f2bdf 100644--- a/packages/core/src/repowise/core/persistence/crud/external_systems.py+++ b/packages/core/src/repowise/core/persistence/crud/external_systems.py@@ -11,6 +11,10 @@ from typing import Anyfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from ...analysis.external_systems.links import (+ EXTERNAL_NODE_PREFIX,+ declaration_name_candidates,+)from ..models import (ExternalSystem,GraphNode,@@ -115,14 +119,6 @@ async def link_graph_nodes_to_external_systems(if not name_to_id:return 0- # Imported inside the function, not at module scope: the matcher's package- # reaches this module back through ``analysis.health``, which loads the- # analyzer engine on import.- from repowise.core.analysis.external_systems.links import (- EXTERNAL_NODE_PREFIX,- declaration_name_candidates,- )-prefix = EXTERNAL_NODE_PREFIXresult = await session.execute(select(GraphNode).where(diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex 98d2ed6f5..e08eff78f 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -11,6 +11,7 @@ from typing import Anyfrom sqlalchemy import func, select+from repowise.core.analysis.health.aggregation import module_rollups as _module_rollupsfrom repowise.core.analysis.health.churn_complexity import churn_complexity_pointsfrom repowise.core.analysis.health.complexity.languages import LANGUAGE_MAPSfrom repowise.core.analysis.health.coverage import decay_since, measurement_ref@@ -21,6 +22,7 @@ from repowise.core.analysis.health.grading import distribution as health_distribfrom repowise.core.analysis.health.models import primary_findingfrom repowise.core.analysis.health.perf.coverage import PerfCoverage, coverage_for_metricsfrom repowise.core.analysis.health.perf.opportunity_rank import observation_rank+from repowise.core.analysis.health.ranking import deduction_by_path, sort_metrics_worst_firstfrom repowise.core.analysis.health.refactoring.recommendations import (Recommendation,build_recommendations,@@ -44,7 +46,6 @@ from repowise.core.persistence.crud import (get_test_file_paths,list_health_snapshots,load_coverage_for_repo,- sort_metrics_worst_first,)from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import (@@ -840,39 +841,6 @@ def _serialize_coverage_row(row: Any, *, covered_lines: bool = True) -> dict[strreturn out-def _module_rollups(metrics: list[HealthFileMetric]) -> list[dict[str, Any]]:- """NLOC-weighted module rollups derived from ``HealthFileMetric.module``.-- One row per module; ``None`` modules are dropped. Sorted by health- ascending so the worst modules surface first — matches the per-file- ordering and what the dashboard already expects.- """- buckets: dict[str, list[HealthFileMetric]] = {}- for m in metrics:- if m.module:- buckets.setdefault(m.module, []).append(m)- out: list[dict[str, Any]] = []- for name, rows in buckets.items():- total_nloc = sum(max(r.nloc, 1) for r in rows)- if total_nloc:- avg = sum(r.score * max(r.nloc, 1) for r in rows) / total_nloc- else:- avg = sum(r.score for r in rows) / len(rows)- worst = min(rows, key=lambda r: r.score)- out.append(- {- "module": name,- "file_count": len(rows),- "nloc": sum(r.nloc for r in rows),- "average_health": round(avg, 2),- "worst_performer_path": worst.file_path,- "worst_performer_score": round(worst.score, 2),- }- )- out.sort(key=lambda r: r["average_health"])- return out--def _unresolved_targets(*,file_targets: list[str],@@ -1936,18 +1904,14 @@ async def get_health(# Deliberately ``lead_rows`` (the unfiltered open set) rather than# ``emitted``: asking to *see* one dimension must not restate which# files the repo's worst are.- deduction_by_path: dict[str, float] = {}- for f in lead_rows:- deduction_by_path[f.file_path] = deduction_by_path.get(f.file_path, 0.0) + float(- f.health_impact or 0.0- )+ deductions = deduction_by_path(lead_rows)# Rebound rather than kept beside a sorted copy, and above every reader.- # ``kpis``, the module rollup, the leverage view and the churn quadrant- # all reduce with ``min()`` or a stable sort, which resolve ties by- # *input* order — so leaving them on the raw list would have one- # response name one file as the worst performer while the- # ``worst_files`` list printed below it led with another.- all_metrics = sort_metrics_worst_first(all_metrics, deduction_by_path)+ # ``kpis``, the leverage view and the churn quadrant all reduce with+ # ``min()`` or a stable sort, which resolve ties by *input* order — so+ # leaving them on the raw list would have one response name one file as+ # the worst performer while the ``worst_files`` list printed below it+ # led with another. The module rollup takes the map itself.+ all_metrics = sort_metrics_worst_first(all_metrics, deductions)metric_rows = ([m for m in all_metrics if m.file_path in set(effective_targets)]if scoped@@ -2231,7 +2195,7 @@ async def get_health(row["signals"] = signals_by_path[m.file_path]metric_payload.append(row)module_rollup = _module_rollups(- [m for m in all_metrics if m.module in set(module_targets)]+ [m for m in all_metrics if m.module in set(module_targets)], deductions)result: dict[str, Any] = {"mode": "targets",@@ -2321,7 +2285,7 @@ async def get_health(# round-trip. ``by_leverage`` is built above, before the leads.# Same serializer as worst_files, so every row carries# weighted_deficit for the caller to sort on further.- all_modules = _module_rollups(all_metrics)+ all_modules = _module_rollups(all_metrics, deductions)gap = _gap_analysis(all_metrics)result = {# Lead with the call, not the data. Every block below ranks and@@ -2447,6 +2411,9 @@ async def get_health(result["defect_accuracy"] = compute_defect_accuracy(all_metrics,[_serialize_finding(f, reference_repository) for f in accuracy_rows],+ # The same map ``all_metrics`` was ranked with, so the stat+ # measures exactly the ``worst_files`` this response printed.+ deductions=deductions,)if "biomarkers" in include_set and "findings" not in result:diff --git a/packages/server/src/repowise/server/routers/code_health/aggregation.py b/packages/server/src/repowise/server/routers/code_health/aggregation.pydeleted file mode 100644index 813097d38..000000000--- a/packages/server/src/repowise/server/routers/code_health/aggregation.py+++ /dev/null@@ -1,56 +0,0 @@-"""Module rollups + severity / biomarker breakdowns over finding lists."""--from __future__ import annotations--from typing import Any---def _module_rollups(metrics: list[Any]) -> list[dict]:- """NLOC-weighted module rollups derived from ``HealthFileMetric.module``."""- buckets: dict[str, list[Any]] = {}- for m in metrics:- if m.module:- buckets.setdefault(m.module, []).append(m)- rows: list[dict] = []- for name, group in buckets.items():- total_nloc = sum(max(r.nloc, 1) for r in group)- avg = sum(r.score * max(r.nloc, 1) for r in group) / total_nloc if total_nloc else 10.0- worst = min(group, key=lambda r: r.score)- rows.append(- {- "module": name,- "file_count": len(group),- "nloc": sum(r.nloc for r in group),- "average_health": round(avg, 2),- "worst_performer_path": worst.file_path,- "worst_performer_score": round(worst.score, 2),- }- )- rows.sort(key=lambda r: r["average_health"])- return rows---def _severity_breakdown(findings: list[Any]) -> dict[str, int]:- out = {"critical": 0, "high": 0, "medium": 0, "low": 0}- for f in findings:- s = (f.severity or "").lower()- if s in out:- out[s] += 1- return out---def _biomarker_breakdown(findings: list[Any]) -> list[dict]:- """Per-biomarker counts split by severity, sorted by total."""- by_type: dict[str, dict[str, int]] = {}- for f in findings:- b = f.biomarker_type- sev = (f.severity or "").lower()- bucket = by_type.setdefault(- b, {"critical": 0, "high": 0, "medium": 0, "low": 0, "total": 0}- )- if sev in bucket:- bucket[sev] += 1- bucket["total"] += 1- rows = [{"biomarker_type": b, **counts} for b, counts in by_type.items()]- rows.sort(key=lambda r: r["total"], reverse=True)- return rowsdiff --git a/packages/server/src/repowise/server/routers/code_health/breakdown.py b/packages/server/src/repowise/server/routers/code_health/breakdown.pyindex b81153f6d..ea7cc6f6d 100644--- a/packages/server/src/repowise/server/routers/code_health/breakdown.py+++ b/packages/server/src/repowise/server/routers/code_health/breakdown.py@@ -1,110 +1,16 @@-"""Reconstruct per-category score breakdowns from stored findings."""+"""Reconstruct per-category score breakdowns from stored findings.-from __future__ import annotations+The reconstruction lives in ``repowise.core.analysis.health.aggregation``; this+keeps the private import path the routes and tests already use.+"""-import json-from typing import Any+from __future__ import annotations-from repowise.core.analysis.health.models import Severity-from repowise.core.analysis.health.scoring import (- CATEGORY_CAPS,- SCORE_FLOOR,- SCORE_MAX,- biomarker_category,- biomarker_weight,- severity_deduction,+from repowise.core.analysis.health.aggregation import (+ finding_base_deduction as _finding_base_deduction,+)+from repowise.core.analysis.health.aggregation import (+ score_breakdown as _score_breakdown_from_findings,)--def _finding_details(f: Any) -> dict:- """Return a finding's details as a dict, from either a live ``details``- attr (tests) or the stored ``details_json`` column (the ORM row)."""- d = getattr(f, "details", None)- if isinstance(d, dict):- return d- raw = getattr(f, "details_json", None)- if raw:- try:- parsed = json.loads(raw)- return parsed if isinstance(parsed, dict) else {}- except Exception:- return {}- return {}---def _finding_base_deduction(f: Any) -> float:- """The pre-cap, pre-weight base deduction for one stored finding.-- Mirrors ``scoring.score_file``: a continuous ``deduction`` override (e.g.- coverage scaled by the uncovered fraction, recorded in the finding's- ``details``) takes the place of the discrete severity table. Reading the- override here — instead of always recomputing from the severity band — is- what lets the breakdown show the continuous coverage gradient rather than a- band proxy.- """- override = _finding_details(f).get("deduction")- if isinstance(override, (int, float)):- return float(override)- sev = Severity(f.severity) if not isinstance(f.severity, Severity) else f.severity- return severity_deduction(sev)---def _score_breakdown_from_findings(findings: list[Any]) -> dict:- """Reconstruct per-category deductions from open findings of one file.-- The applied per-finding impact is read from the **stored**- ``health_impact`` (the exact, already-weighted-and-capped value computed by- ``scoring.score_file`` at index time), so the breakdown reproduces the- file's score and surfaces continuous signals (the coverage gradient) instead- of a severity-band proxy. The raw (pre-cap) figure is reconstructed with the- same ``base x weight`` formula scoring uses, so a capped category is honest- about how much it shed.- """- per_cat: dict[str, list[Any]] = {}- for f in findings:- per_cat.setdefault(biomarker_category(f.biomarker_type), []).append(f)-- categories: list[dict] = []- total_deduction = 0.0- for cat, cap in CATEGORY_CAPS.items():- entries = per_cat.get(cat, [])- if not entries:- continue- raw_per_finding = [- _finding_base_deduction(f) * biomarker_weight(f.biomarker_type) for f in entries- ]- applied_per_finding = [float(f.health_impact or 0.0) for f in entries]- raw_sum = sum(raw_per_finding)- applied_sum = sum(applied_per_finding)- categories.append(- {- "category": cat,- "cap": round(cap, 2),- "raw_deduction": round(raw_sum, 3),- "applied_deduction": round(applied_sum, 3),- # Category shed weight iff its applied total is held at the cap.- "capped": applied_sum < raw_sum - 1e-6,- "finding_count": len(entries),- "findings": [- {- "id": f.id,- "biomarker_type": f.biomarker_type,- "severity": f.severity,- "raw_impact": round(raw, 3),- "applied_impact": round(applied, 3),- "function_name": f.function_name,- "reason": f.reason,- }- for f, raw, applied in zip(- entries, raw_per_finding, applied_per_finding, strict=True- )- ],- }- )- total_deduction += applied_sum- score = max(SCORE_FLOOR, min(SCORE_MAX, SCORE_MAX - total_deduction))- return {- "score": round(score, 2),- "total_deduction": round(total_deduction, 3),- "categories": categories,- }+__all__ = ["_finding_base_deduction", "_score_breakdown_from_findings"]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.pyindex f2507d2ce..43d889866 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@@ -7,16 +7,21 @@ from datetime import datetimefrom fastapi import Depends, HTTPException, Queryfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.health.aggregation import (+ biomarker_breakdown,+ module_rollups,+ severity_breakdown,+)from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracyfrom repowise.core.analysis.health.grading import band_forfrom repowise.core.analysis.health.grading import distribution as health_distribution+from repowise.core.analysis.health.ranking import deduction_by_pathfrom repowise.core.analysis.health.scoring import hotspot_healthfrom repowise.core.persistence import crudfrom repowise.server.deps import get_db_sessionfrom repowise.server.mcp_server._meta import resolve_indexed_commitfrom ._router import router-from .aggregation import _biomarker_breakdown, _module_rollups, _severity_breakdownfrom .loaders import _attach_symbol_idsfrom .serializers import _finding_to_dict, _leads_by_file, _metric_to_dict@@ -88,7 +93,7 @@ async def health_overview(summary = {**summary,"hotspot_health": hotspot_health_value,- "severity_breakdown": _severity_breakdown(findings),+ "severity_breakdown": severity_breakdown(findings),"band": band_for(float(avg)) if avg is not None else None,}distribution = health_distribution(metric_dicts)@@ -101,9 +106,15 @@ async def health_overview(# metrics — so ``metric_dicts`` above serves, no second conversion — and# only the ``prior_defect`` findings, so converting the other ~90% (which# means a ``json.loads`` of every ``details_json``) was pure waste.+ # Summed over every open finding, not the ``prior_defect`` slice below: a+ # ranking needs each file's whole depth, or the floor-tied band comes out in+ # a different order than the worst-files list beside it. Folded once and+ # shared with the module rollup.+ deductions = deduction_by_path(findings)defect_accuracy = compute_defect_accuracy(metric_dicts,[_finding_to_dict(f) for f in findings if f.biomarker_type == "prior_defect"],+ deductions=deductions,)# Ranked by health impact, so performance is out: its findings score zero@@ -122,8 +133,8 @@ async def health_overview("defect_accuracy": defect_accuracy,"files": metric_dicts[:limit],"top_findings": top_findings,- "modules": _module_rollups(metrics),- "biomarkers": _biomarker_breakdown(findings),+ "modules": module_rollups(metrics, deductions),+ "biomarkers": biomarker_breakdown(findings),"meta": {"last_indexed_at": last_indexed_at,# Prefer state.json's last_sync_commit over a possibly-stale DB row@@ -145,4 +156,8 @@ async def health_modules(if repo is None:raise HTTPException(status_code=404, detail="Repository not found")metrics = await crud.get_health_metrics(session, repo_id)- return {"modules": _module_rollups(metrics)}+ # One grouped aggregate, the same one the ranking above it runs. Without it+ # a module whose files all sit at the score floor would name its worst+ # performer by path rather than by how deep each file actually is.+ deductions = await crud.get_deduction_by_path(session, repo_id)+ return {"modules": module_rollups(metrics, deductions)}diff --git a/packages/server/src/repowise/server/routers/overview.py b/packages/server/src/repowise/server/routers/overview.pyindex 0ff6a8a78..fe3847145 100644--- a/packages/server/src/repowise/server/routers/overview.py+++ b/packages/server/src/repowise/server/routers/overview.py@@ -20,6 +20,9 @@ from fastapi import APIRouter, Depends, HTTPExceptionfrom sqlalchemy import func, selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.health.aggregation import (+ severity_breakdown as health_severity_breakdown,+)from repowise.core.analysis.health.scoring import hotspot_healthfrom repowise.core.persistence import crudfrom repowise.core.persistence.models import (@@ -415,11 +418,7 @@ async def overview_summary(if len(file_counts) == 2 and all(file_counts):deltas["file_count"] = file_counts[1] - file_counts[0]- severity_breakdown = {"critical": 0, "high": 0, "medium": 0, "low": 0}- for f in findings:- s = (f.severity or "").lower()- if s in severity_breakdown:- severity_breakdown[s] += 1+ severity_breakdown = health_severity_breakdown(findings)# "Can you trust this score?" — the backtested precision of the defect# ranking, shown on the health card. Sourced here rather than from the stats@@ -453,6 +452,7 @@ async def overview_summary(defect_accuracy = Nonetry:from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracy+ from repowise.core.analysis.health.ranking import deduction_by_pathdefect_accuracy = compute_defect_accuracy([@@ -466,6 +466,7 @@ async def overview_summary(for m in health_metrics],prior_defect_rows,+ deductions=deduction_by_path(findings),)except Exception:# Best-effort: the card omits the panel rather than failing the page.diff --git a/packages/server/src/repowise/server/services/module_health.py b/packages/server/src/repowise/server/services/module_health.pyindex cd5c5cdc6..280243604 100644--- a/packages/server/src/repowise/server/services/module_health.py+++ b/packages/server/src/repowise/server/services/module_health.py@@ -24,6 +24,7 @@ from sqlalchemy import func as sa_funcfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.health.aggregation import module_labelfrom repowise.core.persistence.models import (DeadCodeFinding,DecisionRecord,@@ -32,15 +33,9 @@ from repowise.core.persistence.models import (WikiSymbol,)--def top_level_module(file_path: str) -> str:- """The top-level directory of *file_path*, or ``"root"`` for a root file.-- The one definition behind every ownership rollup. Not a package boundary --- see the module docstring.- """- parts = file_path.split("/", 1)- return parts[0] if len(parts) > 1 else "root"+#: The one definition behind every ownership rollup. Not a package boundary --+#: see the module docstring.+top_level_module = module_labeldef _compute_health_score(diff --git a/tests/unit/health/test_aggregation_contract.py b/tests/unit/health/test_aggregation_contract.pynew file mode 100644index 000000000..1c9ab6fe6--- /dev/null+++ b/tests/unit/health/test_aggregation_contract.py@@ -0,0 +1,292 @@+"""Module rollups, breakdowns and category caps, over every record shape.++These folds were held in two copies each — one in the REST router package, one+in the MCP tool — over rows that arrive as ORM objects, analyzer dataclasses or+plain dicts depending on the caller. The copies are gone; this pins what the+one implementation must do, including the cases the copies never agreed on:+floor ties, malformed legacy severity, absent categories, and stored applied+impact taking precedence over anything recomputed.+"""++from __future__ import annotations++from dataclasses import dataclass+from dataclasses import field as dc_field++import pytest++from repowise.core.analysis.health.aggregation import (+ MODULE_ROOT_LABEL,+ biomarker_breakdown,+ finding_base_deduction,+ module_label,+ module_rollups,+ score_breakdown,+ severity_breakdown,+)+from repowise.core.analysis.health.models import Severity+from repowise.core.analysis.health.scoring import (+ CATEGORY_CAPS,+ SCORE_FLOOR,+ SCORE_MAX,+ biomarker_category,+)+++@dataclass+class _Finding:+ biomarker_type: str+ severity: str = "high"+ health_impact: float = 0.0+ details: dict = dc_field(default_factory=dict)+ id: str = "f1"+ function_name: str | None = None+ reason: str = ""+++class _MetricRow:+ def __init__(self, file_path: str, score: float, nloc: int, module: str | None) -> None:+ self.file_path = file_path+ self.score = score+ self.nloc = nloc+ self.module = module+++def _metric_dict(file_path: str, score: float, nloc: int, module: str | None) -> dict:+ return {"file_path": file_path, "score": score, "nloc": nloc, "module": module}+++# --------------------------------------------------------------------------- #+# Module label policy+# --------------------------------------------------------------------------- #+++ "path,expected",+ [+ ("packages/core/src/a.py", "packages"),+ ("packages/a.py", "packages"),+ ("README.md", MODULE_ROOT_LABEL),+ ("", MODULE_ROOT_LABEL),+ (None, MODULE_ROOT_LABEL),+ ("src/", "src"),+ ],+)+def test_module_label_takes_the_first_segment_or_the_root_label(path, expected) -> None:+ assert module_label(path) == expected+++# --------------------------------------------------------------------------- #+# Module rollups+# --------------------------------------------------------------------------- #+++def test_module_rollups_are_identical_for_dicts_and_attribute_rows() -> None:+ rows = [+ ("api/a.py", 4.0, 100, "api"),+ ("api/b.py", 8.0, 300, "api"),+ ("web/c.py", 6.0, 50, "web"),+ ]+ as_dicts = module_rollups([_metric_dict(*r) for r in rows])+ as_objects = module_rollups([_MetricRow(*r) for r in rows])+ assert as_dicts == as_objects+ assert [r["module"] for r in as_dicts] == ["web", "api"] # worst average first+ api = as_dicts[1]+ assert api["file_count"] == 2+ assert api["nloc"] == 400+ # NLOC-weighted: (4*100 + 8*300) / 400.+ assert api["average_health"] == 7.0+ assert api["worst_performer_path"] == "api/a.py"+ assert api["worst_performer_score"] == 4.0+++def test_rows_without_a_module_are_dropped_not_bucketed_under_none() -> None:+ rollups = module_rollups(+ [_metric_dict("a.py", 3.0, 10, None), _metric_dict("api/b.py", 9.0, 10, "api")]+ )+ assert [r["module"] for r in rollups] == ["api"]+++def test_module_rollup_order_is_total_across_equal_averages() -> None:+ rows = [+ _metric_dict("b/x.py", 5.0, 10, "b"),+ _metric_dict("a/x.py", 5.0, 10, "a"),+ _metric_dict("c/x.py", 1.0, 10, "c"),+ ]+ assert [r["module"] for r in module_rollups(rows)] == ["c", "a", "b"]+++def test_a_module_worst_performer_uses_depth_when_the_scores_tie() -> None:+ rows = [+ _metric_dict("api/z.py", SCORE_FLOOR, 10, "api"),+ _metric_dict("api/a.py", SCORE_FLOOR, 10, "api"),+ ]+ deepest = module_rollups(rows, {"api/z.py": 12.0, "api/a.py": 3.0})+ assert deepest[0]["worst_performer_path"] == "api/z.py"+++def test_without_depth_a_tied_module_worst_performer_falls_to_the_path() -> None:+ rows = [+ _metric_dict("api/z.py", SCORE_FLOOR, 10, "api"),+ _metric_dict("api/a.py", SCORE_FLOOR, 10, "api"),+ ]+ assert module_rollups(rows)[0]["worst_performer_path"] == "api/a.py"+++def test_a_zero_score_is_a_score_not_a_missing_measurement() -> None:+ """``or SCORE_MAX`` here would rank the worst possible file as the best."""+ rows = [+ _metric_dict("api/a.py", 0.0, 10, "api"),+ _metric_dict("api/b.py", 10.0, 10, "api"),+ ]+ rollup = module_rollups(rows)[0]+ assert rollup["average_health"] == 5.0+ assert rollup["worst_performer_score"] == 0.0+ assert rollup["worst_performer_path"] == "api/a.py"+++def test_a_missing_nloc_weighs_one_rather_than_dividing_by_zero() -> None:+ rows = [+ {"file_path": "api/a.py", "score": 2.0, "module": "api"},+ {"file_path": "api/b.py", "score": 8.0, "module": "api"},+ ]+ rollup = module_rollups(rows)[0]+ assert rollup["nloc"] == 0+ assert rollup["average_health"] == 5.0+++# --------------------------------------------------------------------------- #+# Severity + biomarker breakdowns+# --------------------------------------------------------------------------- #+++def test_severity_breakdown_always_declares_every_bucket() -> None:+ assert severity_breakdown([]) == {"critical": 0, "high": 0, "medium": 0, "low": 0}+++def test_severity_breakdown_reads_enums_strings_and_casing_alike() -> None:+ findings = [+ _Finding("a", severity=Severity.HIGH),+ {"biomarker_type": "b", "severity": "high"},+ _Finding("c", severity="HIGH"),+ ]+ assert severity_breakdown(findings)["high"] == 3+++def test_malformed_legacy_severity_is_dropped_not_raised() -> None:+ findings = [_Finding("a", severity="informational"), _Finding("b", severity=None)]+ assert severity_breakdown(findings) == {"critical": 0, "high": 0, "medium": 0, "low": 0}+++def test_biomarker_totals_count_a_malformed_severity_the_buckets_cannot() -> None:+ rows = biomarker_breakdown([_Finding("god_class", severity="informational")])+ assert rows == [+ {+ "biomarker_type": "god_class",+ "critical": 0,+ "high": 0,+ "medium": 0,+ "low": 0,+ "total": 1,+ }+ ]+++def test_biomarker_breakdown_is_busiest_first_with_a_total_order() -> None:+ findings = [+ _Finding("zeta"),+ _Finding("alpha"),+ _Finding("busy"),+ _Finding("busy"),+ ]+ assert [r["biomarker_type"] for r in biomarker_breakdown(findings)] == [+ "busy",+ "alpha",+ "zeta",+ ]+++# --------------------------------------------------------------------------- #+# Score / category breakdown+# --------------------------------------------------------------------------- #+++def _category_biomarker(category: str) -> str:+ """A biomarker name the scorer files under *category*."""+ for name in ("god_class", "complex_method", "coverage_gap", "dry_violation", "error_handling"):+ if biomarker_category(name) == category:+ return name+ raise AssertionError(f"no biomarker maps to {category}")+++def test_a_continuous_deduction_override_replaces_the_severity_band() -> None:+ finding = _Finding("coverage_gradient", severity="low", details={"deduction": 3.25})+ assert finding_base_deduction(finding) == 3.25+++def test_the_override_is_read_from_stored_details_json_too() -> None:+ stored = {+ "biomarker_type": "coverage_gradient",+ "severity": "low",+ "details_json": '{"deduction": 2.5}',+ }+ assert finding_base_deduction(stored) == 2.5+++def test_a_malformed_severity_falls_back_instead_of_raising() -> None:+ assert finding_base_deduction(_Finding("god_class", severity="informational")) == 0.5+++def test_the_breakdown_reproduces_the_score_from_stored_impact() -> None:+ biomarker = _category_biomarker("structural_complexity")+ findings = [_Finding(biomarker, health_impact=1.5), _Finding(biomarker, health_impact=0.75)]+ out = score_breakdown(findings)+ assert out["total_deduction"] == 2.25+ assert out["score"] == round(SCORE_MAX - 2.25, 2)+ assert out["categories"][0]["applied_deduction"] == 2.25+++def test_a_capped_category_is_flagged_and_holds_its_applied_total() -> None:+ biomarker = _category_biomarker("structural_complexity")+ cap = CATEGORY_CAPS["structural_complexity"]+ findings = [_Finding(biomarker, severity="critical", health_impact=cap / 4) for _ in range(4)]+ category = score_breakdown(findings)["categories"][0]+ assert category["applied_deduction"] == pytest.approx(cap)+ assert category["raw_deduction"] > cap+ assert category["capped"] is True+++def test_a_category_with_no_findings_is_absent_rather_than_zero_filled() -> None:+ biomarker = _category_biomarker("structural_complexity")+ out = score_breakdown([_Finding(biomarker, health_impact=1.0)])+ assert [c["category"] for c in out["categories"]] == ["structural_complexity"]+++def test_the_breakdown_never_reports_below_the_floor() -> None:+ biomarker = _category_biomarker("structural_complexity")+ findings = [_Finding(biomarker, health_impact=50.0)]+ assert score_breakdown(findings)["score"] == SCORE_FLOOR+++def test_the_breakdown_is_identical_for_dataclasses_and_stored_rows() -> None:+ biomarker = _category_biomarker("structural_complexity")+ as_objects = [_Finding(biomarker, severity="high", health_impact=1.5, id="x")]+ as_dicts = [+ {+ "biomarker_type": biomarker,+ "severity": "high",+ "health_impact": 1.5,+ "details_json": "{}",+ "id": "x",+ "function_name": None,+ "reason": "",+ }+ ]+ assert score_breakdown(as_objects) == score_breakdown(as_dicts)+++def test_a_null_health_impact_counts_as_no_deduction() -> None:+ biomarker = _category_biomarker("structural_complexity")+ out = score_breakdown([{"biomarker_type": biomarker, "severity": "high", "health_impact": None}])+ assert out["total_deduction"] == 0.0+ assert out["score"] == SCORE_MAXdiff --git a/tests/unit/health/test_defect_accuracy_membership.py b/tests/unit/health/test_defect_accuracy_membership.pynew file mode 100644index 000000000..5ba07635c--- /dev/null+++ b/tests/unit/health/test_defect_accuracy_membership.py@@ -0,0 +1,126 @@+"""Defect accuracy measures the list it validates, not a different one.++The stat ranks files worst-first and asks how many of the top K were recently+bug-fixed. It used to sort on the clamped score alone. The score floors, so the+tied band came out in whatever order the rows arrived in, and the top K it+scored could name different files than the ``worst_files`` list published+beside it — a self-validation of a ranking nobody was shown.+"""++from __future__ import annotations++from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracy+from repowise.core.analysis.health.ranking import deduction_by_path, sort_metrics_worst_first+from repowise.core.analysis.health.scoring import SCORE_FLOOR++_K = 5+_FLOORED = 12 # enough tied files that a score-only sort cannot resolve them+++def _metrics() -> list[dict]:+ """25 scored files: a floor-tied band, then healthy filler."""+ floored = [+ {"file_path": f"floor_{i:02d}.py", "score": SCORE_FLOOR, "nloc": 100}+ for i in range(_FLOORED)+ ]+ filler = [+ {"file_path": f"ok_{i:02d}.py", "score": 9.0, "nloc": 100} for i in range(25 - _FLOORED)+ ]+ return floored + filler+++def _findings() -> list[dict]:+ """Depth findings for the tied band, plus the bug-fix labels.++ Depth runs *opposite* to path order, so a comparator that ignores it and+ falls back to the path picks the shallowest files, and one that honours it+ picks the deepest. The bug-fixed files are the deep ones.+ """+ rows: list[dict] = []+ for i in range(_FLOORED):+ rows.append(+ {+ "file_path": f"floor_{i:02d}.py",+ "biomarker_type": "god_class",+ "health_impact": 9.0 + i,+ }+ )+ for i in range(_FLOORED - 5, _FLOORED):+ rows.append(+ {+ "file_path": f"floor_{i:02d}.py",+ "biomarker_type": "prior_defect",+ "health_impact": 0.1,+ "details": {"prior_defect_count": 3, "window_days": 90},+ }+ )+ return rows+++def _stat() -> dict:+ findings = _findings()+ stat = compute_defect_accuracy(+ _metrics(),+ [f for f in findings if f["biomarker_type"] == "prior_defect"],+ k=_K,+ deductions=deduction_by_path(findings),+ )+ assert stat is not None+ return stat+++def test_flagged_files_are_the_canonical_worst_files() -> None:+ findings = _findings()+ canonical = sort_metrics_worst_first(_metrics(), deduction_by_path(findings))+ flagged = [row["file_path"] for row in _stat()["flagged_files"]]+ assert flagged == [row["file_path"] for row in canonical[:_K]]+++def test_precision_counts_hits_in_that_same_membership() -> None:+ stat = _stat()+ hits = sum(1 for row in stat["flagged_files"] if row["recent_fixes"] > 0)+ assert stat["hits"] == hits+ assert stat["precision"] == round(hits / stat["k"], 4)+++def test_depth_decides_the_floor_tied_band_not_path_order() -> None:+ """Every flagged file is one of the deepest, which is where the fixes are."""+ flagged = {row["file_path"] for row in _stat()["flagged_files"]}+ deepest = {f"floor_{i:02d}.py" for i in range(_FLOORED - _K, _FLOORED)}+ assert flagged == deepest+ assert _stat()["hits"] == _K+++def test_concentration_shares_the_same_ranking() -> None:+ stat = _stat()+ # 20% of 25 files is the worst five, which is exactly K here, so the+ # concentration hit count and the precision hit count come from one list.+ assert stat["concentration_file_fraction"] == 0.20+ assert stat["concentration_defect_share"] == round(stat["hits"] / stat["defect_files"], 4)+++def test_the_ranking_is_independent_of_the_order_rows_arrive_in() -> None:+ findings = _findings()+ deductions = deduction_by_path(findings)+ labels = [f for f in findings if f["biomarker_type"] == "prior_defect"]+ forward = compute_defect_accuracy(_metrics(), labels, k=_K, deductions=deductions)+ reversed_rows = compute_defect_accuracy(+ list(reversed(_metrics())), labels, k=_K, deductions=deductions+ )+ assert forward == reversed_rows+++def test_window_and_counts_still_come_from_stored_details_json() -> None:+ """The label rows reach the server as ORM rows carrying ``details_json``."""+ labels = [+ {+ "file_path": f"floor_{i:02d}.py",+ "biomarker_type": "prior_defect",+ "details_json": '{"prior_defect_count": 4, "window_days": 45}',+ }+ for i in range(_FLOORED - 5, _FLOORED)+ ]+ stat = compute_defect_accuracy(_metrics(), labels, k=_K)+ assert stat is not None+ assert stat["window_days"] == 45+ assert all(row["recent_fixes"] in (0, 4) for row in stat["flagged_files"])diff --git a/tests/unit/health/test_lightweight_health_imports.py b/tests/unit/health/test_lightweight_health_imports.pynew file mode 100644index 000000000..5f3dfc1fa--- /dev/null+++ b/tests/unit/health/test_lightweight_health_imports.py@@ -0,0 +1,96 @@+"""The portable health read models stay cheap to import.++``analysis/health/__init__`` used to bind the analyzer engine eagerly, so an+import of the record adapters or of any pure fold under this package dragged in+ingestion, git blame and, through them, persistence — which is why the crud+layer had to defer its own imports back out of ``analysis.health`` to keep the+cycle from closing.++The engine now binds on first attribute access, and ``scoring`` keeps its one+biomarker import behind a ``TYPE_CHECKING`` gate. A consumer that only wants the+ranking, the folds or the trend arithmetic pays for none of it: the seven modules+below reach fewer than ten repowise modules between them, against the 419 and a+full set of tree-sitter grammars before. This is a guard, not a benchmark: it+fails when someone reintroduces an eager import, and says nothing about speed.+"""++from __future__ import annotations++import subprocess+import sys+import textwrap++import pytest++_LIGHTWEIGHT = (+ "repowise.core.analysis.health.rows",+ "repowise.core.analysis.health.ranking",+ "repowise.core.analysis.health.aggregation",+ "repowise.core.analysis.health.trends",+ "repowise.core.analysis.health.grading",+ "repowise.core.analysis.health.suggestions",+ "repowise.core.analysis.health.defect_accuracy",+)++# Loading any of these means the seam stopped being portable: a downstream+# consumer holding plain records would be made to install a web framework, a+# database driver, a parser toolchain, or the whole analyzer to read a number.+#+# ``tree_sitter`` and the ingestion package are on the list because they are the+# heaviest tail and the easiest to reintroduce by accident: one runtime import+# of a biomarker type for an annotation pulls in every grammar. That is exactly+# what a `TYPE_CHECKING` gate in ``scoring`` currently prevents, and removing it+# has to fail here rather than in a downstream consumer's install.+_FORBIDDEN = ("fastapi", "sqlalchemy", "pydantic", "tree_sitter")+_FORBIDDEN_REPOWISE = (+ "repowise.core.persistence",+ "repowise.core.ingestion",+ "repowise.core.analysis.health.biomarkers",+ "repowise.core.analysis.health.engine",+ "repowise.server",+)+++def _loaded_after_importing(module: str) -> set[str]:+ """Module names present in a fresh interpreter after importing *module*."""+ script = textwrap.dedent(+ f"""+ import importlib, sys+ importlib.import_module({module!r})+ print("\\n".join(sorted(sys.modules)))+ """+ )+ done = subprocess.run(+ [sys.executable, "-c", script],+ capture_output=True,+ text=True,+ check=False,+ )+ assert done.returncode == 0, done.stderr+ return set(done.stdout.split())++[email protected]("module", _LIGHTWEIGHT)+def test_the_read_models_import_without_the_heavy_layers(module: str) -> None:+ loaded = _loaded_after_importing(module)+ offenders = sorted(+ name+ for name in loaded+ if name in _FORBIDDEN or name.startswith(_FORBIDDEN_REPOWISE)+ )+ assert offenders == [], f"{module} pulled in {offenders}"+++def test_the_engine_is_still_reachable_from_the_package() -> None:+ """Deferring the import must not remove the export."""+ from repowise.core.analysis.health import HEALTH_ANALYZER_VERSION, HealthAnalyzer++ assert HealthAnalyzer.__name__ == "HealthAnalyzer"+ assert isinstance(HEALTH_ANALYZER_VERSION, int)+++def test_an_unknown_package_attribute_still_raises_attribute_error() -> None:+ import repowise.core.analysis.health as health++ with pytest.raises(AttributeError):+ _ = health.NotAThingdiff --git a/tests/unit/health/test_ranking_contract.py b/tests/unit/health/test_ranking_contract.pynew file mode 100644index 000000000..5c335d6e1--- /dev/null+++ b/tests/unit/health/test_ranking_contract.py@@ -0,0 +1,172 @@+"""The worst-first comparator, over every record shape that reaches it.++A health row arrives as an analyzer dataclass before persistence, as an ORM row+after it, and as a plain dict in tests, fixtures and any consumer reading a+serialized report. The ranking is a wire-visible ordering, so all three must+produce the same list — otherwise "the worst files" depends on which surface+asked.+"""++from __future__ import annotations++from dataclasses import dataclass++import pytest++from repowise.core.analysis.health.ranking import (+ deduction_by_path,+ sort_metrics_worst_first,+ worst_first_key,+ worst_metric,+)+from repowise.core.analysis.health.scoring import SCORE_FLOOR+++@dataclass+class _MetricData:+ """Stands in for the analyzer's ``HealthFileMetricData``."""++ file_path: str+ score: float+ nloc: int = 10+++class _Row:+ """Stands in for an ORM row: plain attributes, not a dataclass."""++ def __init__(self, file_path: str, score: float, nloc: int = 10) -> None:+ self.file_path = file_path+ self.score = score+ self.nloc = nloc+++def _dict(file_path: str, score: float, nloc: int = 10) -> dict:+ return {"file_path": file_path, "score": score, "nloc": nloc}+++def _shapes(rows: list[tuple[str, float]]) -> list[list]:+ """The same rows as dicts, dataclasses and attribute rows."""+ return [+ [_dict(path, score) for path, score in rows],+ [_MetricData(path, score) for path, score in rows],+ [_Row(path, score) for path, score in rows],+ ]+++def _paths(ordered: list) -> list[str]:+ return [+ row["file_path"] if isinstance(row, dict) else row.file_path for row in ordered+ ]+++# --------------------------------------------------------------------------- #+# Record-shape equivalence+# --------------------------------------------------------------------------- #+++ "rows,deductions,expected",+ [+ # Score decides first.+ ([("a.py", 8.0), ("b.py", 2.0), ("c.py", 5.0)], {}, ["b.py", "c.py", "a.py"]),+ # Floor ties fall to deduction, deepest first.+ (+ [("a.py", SCORE_FLOOR), ("b.py", SCORE_FLOOR), ("c.py", SCORE_FLOOR)],+ {"a.py": 3.0, "b.py": 12.9, "c.py": 9.0},+ ["b.py", "c.py", "a.py"],+ ),+ # A file with no findings has no magnitude, so it sorts last in the band.+ (+ [("z.py", SCORE_FLOOR), ("a.py", SCORE_FLOOR)],+ {"z.py": 4.0},+ ["z.py", "a.py"],+ ),+ # Equal score and equal deduction: path breaks the tie, so paging is stable.+ (+ [("b.py", SCORE_FLOOR), ("a.py", SCORE_FLOOR)],+ {"a.py": 5.0, "b.py": 5.0},+ ["a.py", "b.py"],+ ),+ # Score still outranks depth: a 2.0 file precedes a deeper floored one.+ (+ [("deep.py", SCORE_FLOOR), ("mid.py", 2.0)],+ {"deep.py": 25.0},+ ["deep.py", "mid.py"],+ ),+ ],+)+def test_every_record_shape_ranks_identically(rows, deductions, expected) -> None:+ for shape in _shapes(rows):+ assert _paths(sort_metrics_worst_first(shape, deductions)) == expected+++def test_the_key_itself_is_identical_across_shapes() -> None:+ deductions = {"a.py": 4.5}+ keys = {+ worst_first_key(row, deductions) for shape in _shapes([("a.py", 1.0)]) for row in shape+ }+ assert keys == {(1.0, -4.5, "a.py")}+++def test_sorting_leaves_its_input_alone() -> None:+ rows = [_dict("a.py", 1.0), _dict("b.py", 1.0)]+ assert _paths(sort_metrics_worst_first(rows, {"b.py": 5.0})) == ["b.py", "a.py"]+ assert _paths(rows) == ["a.py", "b.py"]+++def test_an_unscored_row_is_not_treated_as_the_worst() -> None:+ """A missing measurement is not evidence of a problem."""+ rows = [{"file_path": "unmeasured.py"}, _dict("bad.py", 1.0)]+ assert _paths(sort_metrics_worst_first(rows, {})) == ["bad.py", "unmeasured.py"]+++# --------------------------------------------------------------------------- #+# deduction_by_path+# --------------------------------------------------------------------------- #+++def test_deductions_sum_every_finding_on_a_file_across_shapes() -> None:+ @dataclass+ class _Finding:+ file_path: str+ health_impact: float++ dicts = [+ {"file_path": "a.py", "health_impact": 1.25},+ {"file_path": "a.py", "health_impact": 2.5},+ {"file_path": "b.py", "health_impact": 0.5},+ ]+ objects = [_Finding(f["file_path"], f["health_impact"]) for f in dicts]+ expected = {"a.py": 3.75, "b.py": 0.5}+ assert deduction_by_path(dicts) == expected+ assert deduction_by_path(objects) == expected+++def test_pathless_and_null_impact_findings_do_not_corrupt_the_map() -> None:+ rows = [+ {"file_path": "", "health_impact": 9.0},+ {"file_path": None, "health_impact": 9.0},+ {"file_path": "a.py", "health_impact": None},+ ]+ assert deduction_by_path(rows) == {"a.py": 0.0}+++# --------------------------------------------------------------------------- #+# worst_metric+# --------------------------------------------------------------------------- #+++def test_worst_metric_agrees_with_the_head_of_the_sorted_list() -> None:+ rows = [_dict("a.py", 1.0), _dict("b.py", 1.0), _dict("c.py", 4.0)]+ deductions = {"a.py": 2.0, "b.py": 7.0}+ assert worst_metric(rows, deductions) is sort_metrics_worst_first(rows, deductions)[0]+++def test_worst_metric_is_none_for_no_rows() -> None:+ assert worst_metric([], {}) is None+++def test_the_deduction_map_has_no_default() -> None:+ """Omitting it would silently tie the whole floor band on path."""+ with pytest.raises(TypeError):+ sort_metrics_worst_first([_dict("a.py", 1.0)]) # type: ignore[call-arg]diff --git a/tests/unit/health/test_trend_points_contract.py b/tests/unit/health/test_trend_points_contract.pynew file mode 100644index 000000000..14aa06392--- /dev/null+++ b/tests/unit/health/test_trend_points_contract.py@@ -0,0 +1,182 @@+"""Per-file trend correctness over normalized readings.++``build_file_points`` / ``file_trend_from_points`` are the storage-free half of+the per-file trend: a reading is ``(taken_at, clamped score, recorded+deduction)`` and nothing about where it was read from survives into them. The+snapshot-shaped path is a thin adapter over these, and is covered by+``test_trends.py``; this pins the contract a second reader has to satisfy.+"""++from __future__ import annotations++from datetime import UTC, datetime++import pytest++from repowise.core.analysis.health.scoring import SCORE_FLOOR, SCORE_MAX+from repowise.core.analysis.health.trends import (+ MIN_TREND_POINTS,+ build_file_points,+ file_trend_from_points,+)+++def _at(day: int) -> datetime:+ return datetime(2026, 1, day, tzinfo=UTC)+++def _readings(*rows: tuple[float, float | None]) -> list:+ return [(_at(i + 1), score, deduction) for i, (score, deduction) in enumerate(rows)]+++# --------------------------------------------------------------------------- #+# Minimum points+# --------------------------------------------------------------------------- #+++def test_the_default_minimum_is_two_so_a_lone_reading_draws_nothing() -> None:+ assert MIN_TREND_POINTS == 2+ assert build_file_points(_readings((7.0, None))) == []+ assert len(build_file_points(_readings((7.0, None), (6.0, None)))) == 2+++def test_no_readings_is_empty_at_any_minimum() -> None:+ assert build_file_points([], min_points=1) == []+++def test_a_consumer_may_lower_the_minimum_to_one() -> None:+ points = build_file_points(_readings((7.0, None)), min_points=1)+ assert [p.score for p in points] == [7.0]+++def test_a_single_point_trend_reports_a_current_and_no_movement() -> None:+ trend = file_trend_from_points(+ "a.py", _readings((7.0, None)), snapshot_count=1, min_points=1+ )+ assert trend.current == 7.0+ assert trend.previous is None+ assert trend.delta is None+ assert trend.unclamped_delta is None+ assert trend.declining is False+++def test_below_the_minimum_the_trend_is_wholly_neutral() -> None:+ trend = file_trend_from_points("a.py", _readings((7.0, None)), snapshot_count=9)+ assert trend.points == []+ assert (trend.current, trend.previous, trend.delta) == (None, None, None)+ assert trend.declining is False+ # The window size is the caller's, not the number of readings carrying the file.+ assert trend.snapshot_count == 9+++# --------------------------------------------------------------------------- #+# Depth-known / all-points rule+# --------------------------------------------------------------------------- #+++def test_an_unfloored_series_is_its_own_unclamped_series() -> None:+ points = build_file_points(_readings((8.0, None), (6.5, None)))+ assert [p.unclamped_score for p in points] == [8.0, 6.5]+++def test_a_recorded_deduction_undoes_the_floor() -> None:+ points = build_file_points(_readings((SCORE_FLOOR, 12.0), (SCORE_FLOOR, 13.5)))+ assert [p.unclamped_score for p in points] == [+ round(SCORE_MAX - 12.0, 2),+ round(SCORE_MAX - 13.5, 2),+ ]+++def test_one_reading_without_depth_flattens_the_whole_series() -> None:+ """Mixing measured depth with unmeasured draws a cliff that never happened."""+ points = build_file_points(_readings((SCORE_FLOOR, None), (SCORE_FLOOR, 13.5)))+ assert [p.unclamped_score for p in points] == [SCORE_FLOOR, SCORE_FLOOR]+++def test_depth_appears_only_once_every_reading_carries_it() -> None:+ with_depth = build_file_points(_readings((SCORE_FLOOR, 11.0), (SCORE_FLOOR, 12.0)))+ assert [p.unclamped_score for p in with_depth] == [-1.0, -2.0]+++def test_an_above_floor_reading_needs_no_recorded_deduction() -> None:+ """Its score already is the unclamped value, so the series stays known."""+ points = build_file_points(_readings((4.0, None), (SCORE_FLOOR, 12.0)))+ assert [p.unclamped_score for p in points] == [4.0, -2.0]+++# --------------------------------------------------------------------------- #+# Decline rules+# --------------------------------------------------------------------------- #+++def test_a_single_drop_is_noise_not_a_decline() -> None:+ trend = file_trend_from_points(+ "a.py", _readings((9.0, None), (5.0, None)), snapshot_count=2+ )+ assert trend.delta == -4.0+ assert trend.declining is False+++def test_three_consecutive_drops_declare_a_decline() -> None:+ trend = file_trend_from_points(+ "a.py",+ _readings((9.0, None), (8.9, None), (8.8, None), (8.7, None)),+ snapshot_count=4,+ )+ assert trend.declining is True+++def test_a_recovering_series_is_not_declining() -> None:+ trend = file_trend_from_points(+ "a.py",+ _readings((9.0, None), (8.0, None), (7.0, None), (8.5, None)),+ snapshot_count=4,+ )+ assert trend.declining is False+++def test_a_sustained_drop_over_the_lookback_declares_a_decline() -> None:+ trend = file_trend_from_points(+ "a.py",+ _readings(*[(9.0, None)] * 5, (8.0, None), (8.4, None)),+ snapshot_count=7,+ )+ assert trend.declining is True+++def test_a_floored_file_getting_worse_below_the_floor_still_declines() -> None:+ """The clamped line is flat; the recorded depth is what moves."""+ trend = file_trend_from_points(+ "a.py",+ _readings(+ (SCORE_FLOOR, 9.0),+ (SCORE_FLOOR, 10.0),+ (SCORE_FLOOR, 11.0),+ (SCORE_FLOOR, 12.0),+ ),+ snapshot_count=4,+ )+ assert [p.score for p in trend.points] == [SCORE_FLOOR] * 4+ assert trend.delta == 0.0+ assert trend.unclamped_delta == -1.0+ assert trend.declining is True+++# --------------------------------------------------------------------------- #+# Summary fields+# --------------------------------------------------------------------------- #+++def test_current_previous_and_delta_stay_on_the_clamped_score() -> None:+ trend = file_trend_from_points(+ "a.py", _readings((6.0, None), (4.5, None)), snapshot_count=2+ )+ assert (trend.current, trend.previous, trend.delta) == (4.5, 6.0, -1.5)+ assert trend.unclamped_delta == -1.5++[email protected]("min_points", [1, 2, 3])+def test_points_are_returned_oldest_first_at_any_minimum(min_points) -> None:+ readings = _readings((9.0, None), (8.0, None), (7.0, None))+ points = build_file_points(readings, min_points=min_points)+ assert [p.taken_at for p in points] == [_at(1), _at(2), _at(3)]diff --git a/tests/unit/server/test_health_aggregation_delegation.py b/tests/unit/server/test_health_aggregation_delegation.pynew file mode 100644index 000000000..e0169eedb--- /dev/null+++ b/tests/unit/server/test_health_aggregation_delegation.py@@ -0,0 +1,102 @@+"""REST and MCP read the health folds from one owner, and the wire is unchanged.++Both surfaces used to carry their own copy of the module rollup, and the REST+package its own copy of the breakdown, the record adapter and — in a second+router — the severity fold. The copies drifted in ways nothing could see: the+two rollups disagreed on what to do with a zero-weight bucket, and neither broke+a tie the same way twice.++The key sets below are the pre-existing payload contract. They are asserted+literally because a delegating alias makes a dropped or renamed key invisible at+the call site — the route builds a plain dict, so nothing else would catch it.+"""++from __future__ import annotations++from repowise.core.analysis.health import aggregation as core+from repowise.server.mcp_server.tool_health import _module_rollups as mcp_module_rollups+from repowise.server.routers.code_health import (+ _finding_base_deduction,+ _score_breakdown_from_findings,+)+from repowise.server.routers.code_health.overview_routes import (+ biomarker_breakdown as _biomarker_breakdown,+)+from repowise.server.routers.code_health.overview_routes import (+ module_rollups as _module_rollups,+)+from repowise.server.routers.code_health.overview_routes import (+ severity_breakdown as _severity_breakdown,+)++_METRICS = [+ {"file_path": "api/a.py", "score": 3.0, "nloc": 100, "module": "api"},+ {"file_path": "api/b.py", "score": 7.0, "nloc": 100, "module": "api"},+ {"file_path": "web/c.py", "score": 9.0, "nloc": 40, "module": "web"},+]+_FINDINGS = [+ {"biomarker_type": "god_class", "severity": "critical", "health_impact": 1.5, "details": {}},+ {"biomarker_type": "god_class", "severity": "low", "health_impact": 0.5, "details": {}},+]+++def test_the_repo_overview_shares_the_severity_fold_too() -> None:+ """A fourth copy of this lived in ``routers/overview.py``."""+ from repowise.server.routers.overview import health_severity_breakdown++ assert health_severity_breakdown is core.severity_breakdown+++def test_both_surfaces_resolve_to_the_one_owner() -> None:+ assert _module_rollups is mcp_module_rollups is core.module_rollups+ assert _severity_breakdown is core.severity_breakdown+ assert _biomarker_breakdown is core.biomarker_breakdown+ assert _score_breakdown_from_findings is core.score_breakdown+ assert _finding_base_deduction is core.finding_base_deduction+++def test_the_module_rollup_row_keys_are_unchanged() -> None:+ rows = _module_rollups(_METRICS)+ assert [set(row) for row in rows] == [+ {+ "module",+ "file_count",+ "nloc",+ "average_health",+ "worst_performer_path",+ "worst_performer_score",+ }+ ] * len(rows)+++def test_the_severity_breakdown_keys_are_unchanged() -> None:+ assert set(_severity_breakdown(_FINDINGS)) == {"critical", "high", "medium", "low"}+++def test_the_biomarker_breakdown_row_keys_are_unchanged() -> None:+ row = _biomarker_breakdown(_FINDINGS)[0]+ assert set(row) == {"biomarker_type", "critical", "high", "medium", "low", "total"}+++def test_the_score_breakdown_keys_are_unchanged() -> None:+ out = _score_breakdown_from_findings(_FINDINGS)+ assert set(out) == {"score", "total_deduction", "categories"}+ category = out["categories"][0]+ assert set(category) == {+ "category",+ "cap",+ "raw_deduction",+ "applied_deduction",+ "capped",+ "finding_count",+ "findings",+ }+ assert set(category["findings"][0]) == {+ "id",+ "biomarker_type",+ "severity",+ "raw_impact",+ "applied_impact",+ "function_name",+ "reason",+ }