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
fix(health): stop get_health returning 4.7MB, and index the table it reads (#1337)
Raghav Chamadiya70d608543229
diff --git a/packages/core/alembic/versions/0045_health_findings_indexes.py b/packages/core/alembic/versions/0045_health_findings_indexes.pynew file mode 100644index 000000000..aa600af4e--- /dev/null+++ b/packages/core/alembic/versions/0045_health_findings_indexes.py@@ -0,0 +1,54 @@+"""Index ``health_findings`` — the table every health read full-scanned.++``health_findings`` carried no index beyond its primary key, so both of the+shapes ``get_health`` issues degraded to a full table scan plus a temp B-tree+sort. On a 3.2k-file repo that is ~10k rows; the cost is linear in finding+count, so it grows with the repo it is meant to describe.++Two indexes for two distinct reads:++``ix_health_findings_repo_status_path`` serves the file-scoped lookup —+``get_health(targets=[...])``, the call an agent makes to self-check a file+before and after editing it. Measured on the repowise index, one file went+from 8.8ms (SCAN) to 0.1ms (SEARCH).++``ix_health_findings_repo_status_impact`` serves the repo-wide ranked read,+letting the top-N walk the index in impact order instead of sorting every row+into a temp B-tree first.++Both are declared in ``HealthFinding.__table_args__`` too. Most local stores+are created by ``init_db`` and never see Alembic, so the model declaration+covers new stores and this migration covers existing ones; the two converge on+the same shape.++Revision ID: 0045+Revises: 0044+Create Date: 2026-08-07+"""++from __future__ import annotations++from collections.abc import Sequence++from alembic import op++# revision identifiers+revision: str = "0045"+down_revision: str | None = "0044"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++_INDEXES = (+ ("ix_health_findings_repo_status_path", ["repository_id", "status", "file_path"]),+ ("ix_health_findings_repo_status_impact", ["repository_id", "status", "health_impact"]),+)+++def upgrade() -> None:+ for name, columns in _INDEXES:+ op.create_index(name, "health_findings", columns, if_not_exists=True)+++def downgrade() -> None:+ for name, _columns in _INDEXES:+ op.drop_index(name, table_name="health_findings", if_exists=True)diff --git a/packages/core/src/repowise/core/exclusion.py b/packages/core/src/repowise/core/exclusion.pyindex 593b04e85..e4c83e972 100644--- a/packages/core/src/repowise/core/exclusion.py+++ b/packages/core/src/repowise/core/exclusion.py@@ -9,26 +9,67 @@ that logic; ``repowise.server.mcp_server._helpers`` delegates here.from __future__ import annotationsimport json+from functools import lru_cachefrom pathlib import Pathfrom typing import Any+# Per-spec memo ceiling. Comfortably above any real repo's distinct path count,+# low enough that 64 cached specs cannot pin unbounded memory.+_MEMO_MAX = 200_000-def build_exclude_spec(repo_path: Path | str) -> Any:- """Compile the repo's exclusion rules into a PathSpec, or ``None``.- Unions ``.repowise/config.yaml`` ``exclude_patterns`` with the repo's- gitignore stack (``.gitignore`` + ``.git/info/exclude``). Indexes built- before the traverser honoured ``info/exclude`` still contain rows for- local-only scratch dirs; filtering them at query time keeps those paths- out of generated output without forcing a reindex.+def _gitignore_files(root: Path) -> tuple[Path, ...]:+ """The gitignore-stack files unioned into the spec."""+ return (root / ".gitignore", root / ".git" / "info" / "exclude")+++def _rule_files(root: Path) -> tuple[Path, ...]:+ """Every file whose contents define the spec, config file included.++ Read from ``repo_config`` rather than spelled out again: a stamp that+ missed the config file would cache a spec across an ``exclude_patterns``+ edit and keep serving rows the user just excluded."""+ from repowise.core.repo_config import CONFIG_FILENAME, get_repowise_dir++ return (get_repowise_dir(root) / CONFIG_FILENAME, *_gitignore_files(root))+++def _rules_stamp(root: Path) -> tuple[tuple[int, int], ...]:+ """``(mtime_ns, size)`` per rule source, ``(0, 0)`` when absent.++ Size is in the key because mtime alone is not a reliable invalidator on+ Windows: measured on NTFS, 25 of 199 back-to-back writes shared an identical+ ``st_mtime_ns``. A rules edit that landed inside one timestamp tick would+ otherwise pin the stale spec for the life of the process, with no way to+ force a recompile short of restarting the server. A pattern edit essentially+ always changes the file size, and it rides the same ``stat`` call.+ """+ stamp = []+ for path in _rule_files(root):+ try:+ st = path.stat()+ stamp.append((st.st_mtime_ns, st.st_size))+ except OSError:+ stamp.append((0, 0))+ return tuple(stamp)+++# Sized for workspace mode, not for one repo. A workspace can register many+# repos, and an agent sweeping them round-robin past the cache size gets a 0%+# hit rate — which is worse than no cache, since a miss now also pays+# ``Path.resolve()`` and three ``stat`` calls. Specs are small; the mtime/size+# stamp in the key means stale entries are unreachable rather than merely old.+@lru_cache(maxsize=64)+def _compile_spec(root_key: str, _stamp: tuple[int, ...]) -> Any:+ """Compile and cache one repo's spec. Keyed by root + rule-file mtimes."""import pathspecfrom repowise.core.repo_config import load_repo_config- patterns = list(load_repo_config(repo_path).get("exclude_patterns") or [])- root = Path(repo_path)- for ignore_file in (root / ".gitignore", root / ".git" / "info" / "exclude"):+ root = Path(root_key)+ patterns = list(load_repo_config(root).get("exclude_patterns") or [])+ for ignore_file in _gitignore_files(root):try:if ignore_file.exists():patterns.extend(@@ -38,12 +79,54 @@ def build_exclude_spec(repo_path: Path | str) -> Any:continueif not patterns:return None- return pathspec.PathSpec.from_lines("gitwildmatch", patterns)+ spec = pathspec.PathSpec.from_lines("gitwildmatch", patterns)+ # Per-path decision memo, carried on the spec so it lives exactly as long as+ # the compiled spec does. ``match_file`` is a regex sweep over every pattern;+ # a repo-wide read filters the same few thousand paths over and over, both+ # within one call (findings outnumber files ~3:1) and across calls.+ spec._repowise_memo = {} # type: ignore[attr-defined]+ return spec+++def build_exclude_spec(repo_path: Path | str) -> Any:+ """Compile the repo's exclusion rules into a PathSpec, or ``None``.++ Unions ``.repowise/config.yaml`` ``exclude_patterns`` with the repo's+ gitignore stack (``.gitignore`` + ``.git/info/exclude``). Indexes built+ before the traverser honoured ``info/exclude`` still contain rows for+ local-only scratch dirs; filtering them at query time keeps those paths+ out of generated output without forcing a reindex.++ Cached per repo root and invalidated by the rule files' mtimes: every MCP+ tool builds this on each request, and compiling it is pure overhead when+ nothing changed.+ """+ root = Path(repo_path)+ try:+ root_key = str(root.resolve())+ except OSError:+ root_key = str(root)+ return _compile_spec(root_key, _rules_stamp(root))def is_excluded(path: str | None, spec: Any) -> bool:"""True if *path* matches *spec* (None spec or path -> not excluded)."""- return bool(spec is not None and path and spec.match_file(path))+ if spec is None or not path:+ return False+ memo = getattr(spec, "_repowise_memo", None)+ if memo is None:+ return bool(spec.match_file(path))+ cached = memo.get(path)+ if cached is None:+ if len(memo) >= _MEMO_MAX:+ # Bounded rather than merely finite. The natural ceiling is the+ # repo's distinct paths, but this is also fed symbol ids and+ # decision-anchored paths by other tools, so nothing guarantees+ # that. Dropping the whole memo costs one repopulation pass and+ # keeps a long-lived server from growing without limit.+ memo.clear()+ cached = memo[path] = bool(spec.match_file(path))+ return cacheddef decision_is_excluded(decision_row: Any, spec: Any) -> bool:diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.pyindex 7fa110072..39e5136d9 100644--- a/packages/core/src/repowise/core/persistence/crud/git.py+++ b/packages/core/src/repowise/core/persistence/crud/git.py@@ -81,13 +81,20 @@ async def get_git_metadata_bulk("""Return a dict of file_path → GitMetadata for the given paths."""if not file_paths:return {}- result = await session.execute(- select(GitMetadata).where(- GitMetadata.repository_id == repository_id,- GitMetadata.file_path.in_(file_paths),+ # Batched to stay under SQLite parameter limits (999 on SQLite < 3.32);+ # callers pass unbounded path sets.+ out: dict[str, GitMetadata] = {}+ unique_paths = list(dict.fromkeys(file_paths))+ for i in range(0, len(unique_paths), _BATCH_SIZE):+ result = await session.execute(+ select(GitMetadata).where(+ GitMetadata.repository_id == repository_id,+ GitMetadata.file_path.in_(unique_paths[i : i + _BATCH_SIZE]),+ ))- )- return {gm.file_path: gm for gm in result.scalars().all()}+ for gm in result.scalars().all():+ out[gm.file_path] = gm+ return outasync def get_all_git_metadata(session: AsyncSession, repository_id: str) -> dict[str, GitMetadata]:diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.pyindex a351472e5..727ab5af8 100644--- a/packages/core/src/repowise/core/persistence/crud/graph.py+++ b/packages/core/src/repowise/core/persistence/crud/graph.py@@ -638,3 +638,56 @@ async def get_node_degree_counts("in_degree": in_result.scalar() or 0,"out_degree": out_result.scalar() or 0,}+++async def get_node_degree_counts_bulk(+ session: AsyncSession,+ repository_id: str,+ node_ids: list[str],+) -> dict[str, dict[str, int]]:+ """Return ``node_id -> {in_degree, out_degree}`` for many nodes at once.++ Three queries total instead of three per node (existence, then one grouped+ count per direction). Callers that need degrees for a set of files were+ otherwise forced into an N+1.++ A node absent from the graph is absent from the result, mirroring+ ``get_graph_node`` returning ``None``: consumers distinguish "not a graph+ node" (no entry) from "a node with no edges" (``{0, 0}``), and collapsing+ the two would report isolated files as un-analyzed.+ """+ if not node_ids:+ return {}+ # Batched like ``get_graph_nodes_by_ids`` above: SQLITE_MAX_VARIABLE_NUMBER+ # is 999 on SQLite < 3.32, and the caller's input is unbounded by design (a+ # ``module:`` target expands to every file in the module).+ unique_ids = list(dict.fromkeys(node_ids))+ counts: dict[str, dict[str, int]] = {}+ for i in range(0, len(unique_ids), _BATCH_SIZE):+ existing = await session.execute(+ select(GraphNode.node_id).where(+ GraphNode.repository_id == repository_id,+ GraphNode.node_id.in_(unique_ids[i : i + _BATCH_SIZE]),+ )+ )+ for node_id in existing.scalars().all():+ counts[node_id] = {"in_degree": 0, "out_degree": 0}+ if not counts:+ return {}+ present = list(counts)+ for column, key in (+ (GraphEdge.target_node_id, "in_degree"),+ (GraphEdge.source_node_id, "out_degree"),+ ):+ for i in range(0, len(present), _BATCH_SIZE):+ rows = await session.execute(+ select(column, func.count())+ .where(+ GraphEdge.repository_id == repository_id,+ column.in_(present[i : i + _BATCH_SIZE]),+ )+ .group_by(column)+ )+ for node_id, count in rows.all():+ counts[node_id][key] = count or 0+ return countsdiff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 76b5f3bf0..57c6230c1 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -1126,6 +1126,17 @@ class HealthFinding(Base):DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc)+ # The table had no index at all, so every read full-scanned it. Two shapes+ # are served: a file-scoped lookup (``get_health`` with targets, the call an+ # agent makes to self-check a file before and after an edit) and a+ # repo-wide top-N ordered by impact. The first index turns the scan into a+ # seek; the second lets the ranked read stop early instead of sorting the+ # whole table into a temp B-tree.+ __table_args__ = (+ Index("ix_health_findings_repo_status_path", "repository_id", "status", "file_path"),+ Index("ix_health_findings_repo_status_impact", "repository_id", "status", "health_impact"),+ )+class RefactoringSuggestion(Base):"""One deterministic refactoring opportunity from the refactoring layer.diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex 4f7e5db6e..92ad10cd3 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport jsonfrom dataclasses import asdictfrom pathlib import Path+from time import perf_counterfrom typing import Anyfrom sqlalchemy import select@@ -21,9 +22,8 @@ from repowise.core.persistence.crud import (get_all_git_metadata,get_coverage_summary,get_file_language_map,- get_git_metadata,- get_graph_node,- get_node_degree_counts,+ get_git_metadata_bulk,+ get_node_degree_counts_bulk,get_refactoring_suggestions,list_health_snapshots,load_coverage_for_repo,@@ -95,6 +95,18 @@ def _serialize_refactoring(r: Any) -> dict[str, Any]:}+def _in_dimensions(row: Any, dimensions: set[str]) -> bool:+ """True when *row* belongs to one of *dimensions* (empty set -> everything).++ ``dimension`` is nullable and a NULL means ``defect``: the column was added+ without a backfill, so pre-existing rows stay NULL until the next index+ recomputes them. Reading it as anything else drops real defect findings.+ """+ if not dimensions:+ return True+ return (row.dimension or "defect") in dimensions++def _round_opt(v: Any) -> float | None:"""Round a nullable per-dimension score, preserving ``None`` (not measured)."""return round(v, 2) if v is not None else None@@ -440,8 +452,31 @@ async def get_health(limit: max rows in every ranked list (capped at 50); each carries a``*_total`` sibling so truncation is never silent."""+ started = perf_counter()limit = min(max(limit, 1), 50)include_set = set(include or [])+ only_set = set(only or [])++ def wants(block: str) -> bool:+ """True when ``block`` survives the ``only`` projection.++ ``only`` used to be applied to the finished response, so the cheapest+ documented call — ``only=["directive"]`` — still paid for every block it+ then discarded. Consulted before the expensive optional work so the+ projection gates the work as well as the payload.+ """+ return not only_set or block in only_set++ # Resolved before the reads, not after them. Applied to the finished+ # response, a dimension filter narrowed a list that had already been capped+ # by impact — and performance findings carry low impact by construction, so+ # ``include=["biomarkers", "performance"]`` filtered a defect-heavy head down+ # to nothing while the total still reported the whole repo. The filter now+ # decides which rows are eligible for the cap in the first place.+ dimension_filter = include_set & {"performance", "defect", "maintainability"}+ # The serialized-rows read is the expensive optional one; skip it when no+ # block that carries findings survives the projection.+ wants_findings = wants("findings") or wants("top_findings")# Split ``module:foo`` targets out of the path list. A target that# matches one or more modules is expanded into the set of files@@ -497,27 +532,127 @@ async def get_health(else:metric_rows = sorted(all_metrics, key=lambda r: r.score)- finding_q = select(HealthFinding).where(+ open_findings = (HealthFinding.repository_id == repository.id,HealthFinding.status == "open",)+ # Two row sets, deliberately split.+ #+ # ``finding_rows`` are the ones this response will serialize.+ # ``lead_rows`` is the wider set the per-file dominant-cause reduction+ # and the exact totals are computed from — it only ever needs four+ # columns.+ #+ # Targeted mode asks about a handful of files, so one full read serves+ # both. Dashboard mode does not: hydrating every open finding as a full+ # ORM object to emit ``limit`` of them measured 262ms on this repo, and+ # that cost is linear in finding count, so it grows with the repo the+ # dashboard is describing.if scoped:- finding_q = finding_q.where(HealthFinding.file_path.in_(effective_targets))- finding_q = finding_q.order_by(HealthFinding.health_impact.desc())- finding_rows = filter_rows_by_attr(- list((await session.execute(finding_q)).scalars().all()),- "file_path",- exclude_spec,- )+ finding_rows = filter_rows_by_attr(+ list(+ (+ await session.execute(+ select(HealthFinding)+ .where(*open_findings)+ .where(HealthFinding.file_path.in_(effective_targets))+ .order_by(HealthFinding.health_impact.desc())+ )+ )+ .scalars()+ .all()+ ),+ "file_path",+ exclude_spec,+ )+ lead_rows: list[Any] = finding_rows+ emitted = [f for f in finding_rows if _in_dimensions(f, dimension_filter)]+ finding_rows = emitted[:limit]+ else:+ # Narrow read over every open finding: the four attributes+ # ``_leads_by_file`` reads, plus ``dimension`` for the perf headline+ # and ``id`` to fetch the head. SQLAlchemy ``Row`` exposes these as+ # attributes, so the reduction and the exclude filter both run+ # against it unchanged.+ lite_rows = list(+ (+ await session.execute(+ select(+ HealthFinding.id,+ HealthFinding.file_path,+ HealthFinding.health_impact,+ HealthFinding.biomarker_type,+ HealthFinding.reason,+ HealthFinding.dimension,+ )+ .where(*open_findings)+ .order_by(HealthFinding.health_impact.desc())+ )+ ).all()+ )+ # ``lead_rows`` stays the unfiltered open set: it feeds the per-file+ # leads and the performance KPI, neither of which should change+ # because the caller asked to *see* one dimension.+ lead_rows = filter_rows_by_attr(lite_rows, "file_path", exclude_spec)+ emitted = [r for r in lead_rows if _in_dimensions(r, dimension_filter)]+ # Fetch the head by id rather than re-running the ranked query with+ # an over-fetch margin. The margin had to cover every exclusion in+ # the table, so a repo excluding a large subtree turned the "capped"+ # read back into a near-full one; by id it is exactly ``limit`` rows+ # whatever the exclude config or dimension filter say.+ head_ids = [r.id for r in emitted[:limit]]+ finding_rows = []+ if head_ids and wants_findings:+ by_id = {+ f.id: f+ for f in (+ await session.execute(+ select(HealthFinding).where(HealthFinding.id.in_(head_ids))+ )+ )+ .scalars()+ .all()+ }+ # Re-imposed from ``head_ids``; ``IN`` does not preserve order.+ finding_rows = [by_id[i] for i in head_ids if i in by_id]++ # Counts the rows this response is about: the post-exclusion open set,+ # narrowed to the requested dimensions when one was asked for. Reporting+ # the unfiltered total beside a filtered list is what made an empty+ # ``findings`` read as "nothing here" rather than "nothing shown".+ findings_total = len(emitted)# Dashboard perf headline: coverage (how much of the analyzed code the- # perf pass ran on) + open performance-finding count. finding_rows in- # dashboard mode is the complete open set, so the count is exact.- if not scoped:+ # perf pass ran on) + open performance-finding count. Both feed ``kpis``+ # alone, so a projection that drops kpis skips the language-map read.+ if not scoped and wants("kpis"):lang_by_path = await get_file_language_map(session, repository.id)perf_coverage = coverage_for_metrics(all_metrics, lang_by_path)perf_findings_count = sum(- 1 for f in finding_rows if (f.dimension or "defect") == "performance"+ 1 for f in lead_rows if (f.dimension or "defect") == "performance"+ )++ # ``accuracy`` scores the ranking against the whole repo rather than the+ # capped head, but it reads exactly one biomarker: ``compute_defect_accuracy``+ # ignores every finding whose type is not ``prior_defect``. Selecting+ # those directly keeps the honest denominator without re-reading the+ # ~10k rows the narrow pass above exists to avoid.+ accuracy_rows: list[Any] = []+ if "accuracy" in include_set and not scoped:+ accuracy_rows = filter_rows_by_attr(+ list(+ (+ await session.execute(+ select(HealthFinding)+ .where(*open_findings)+ .where(HealthFinding.biomarker_type == "prior_defect")+ )+ )+ .scalars()+ .all()+ ),+ "file_path",+ exclude_spec,)# Structured refactoring plans (Extract Class, ...) — loaded only when@@ -556,15 +691,21 @@ async def get_health(# before touching it. Targeted mode only; the target set is small.signals_by_path: dict[str, dict[str, Any]] = {}if "signals" in include_set and effective_targets:+ # Batched, not per-file. This loop used to issue three round-trips+ # per target (git metadata, graph node, degree counts) — the exact+ # cross-function N+1 the tool's own ``io_in_loop`` biomarker flags+ # here. ``module:`` targets expand to every file in the module, so+ # the target set is not always small.+ git_meta_by_path = await get_git_metadata_bulk(+ session, repository.id, list(effective_targets)+ )+ degrees_by_path = await get_node_degree_counts_bulk(+ session, repository.id, list(effective_targets)+ )for path in effective_targets:- git_meta = await get_git_metadata(session, repository.id, path)- node = await get_graph_node(session, repository.id, path)- degrees = (- await get_node_degree_counts(session, repository.id, path)- if node is not None- else None+ signals_by_path[path] = asdict(+ file_signals(git_meta_by_path.get(path), degrees_by_path.get(path)))- signals_by_path[path] = asdict(file_signals(git_meta, degrees))# Churn x complexity quadrant for the whole repo (dashboard mode). One# git-metadata query joined against the already-loaded metrics.@@ -587,9 +728,29 @@ async def get_health(performance_findings=perf_findings_count,coverage=perf_coverage,)- # Dominant-cause lead per file, from the findings already loaded (targeted- # findings are scoped to the targets; dashboard findings cover every file).- leads = _leads_by_file(finding_rows)+ # Dominant-cause lead per file. Targeted mode wants one per target, so the+ # reduction runs over the whole (small) scoped set. Dashboard mode only ever+ # prints a lead for the files it emits, so it reduces just those rows+ # instead of all ~10k — identical output, and ``_leads_by_file`` measured+ # ~148ms per call when handed the full set.+ if scoped:+ by_leverage: list[HealthFileMetric] = []+ lead_source: list[Any] = lead_rows+ else:+ # Leverage view: files ranked by NLOC-weighted deficit (how much each+ # drags the headline), not by raw score. Distinct from worst_files — a+ # big warning-band file outranks a tiny alert-band one here because+ # fixing it moves the average far more. Computed before the leads so the+ # set of printed files is known.+ by_leverage = sorted(+ (m for m in all_metrics if m.score < HEALTHY_MIN),+ key=lambda m: max(HEALTHY_MIN - m.score, 0.0) * max(m.nloc, 1),+ reverse=True,+ )+ printed = {m.file_path for m in metric_rows[:limit]}+ printed |= {m.file_path for m in by_leverage[:limit]}+ lead_source = [r for r in lead_rows if r.file_path in printed]+ leads = _leads_by_file(lead_source)if scoped:metric_payload: list[dict[str, Any]] = []@@ -605,7 +766,7 @@ async def get_health(# Capped like every other ranked list, with the total alongside so# the truncation is visible rather than inferred from the length."findings": [_serialize_finding(f) for f in finding_rows[:limit]],- "findings_total": len(finding_rows),+ "findings_total": findings_total,}unresolved = _unresolved_targets(file_targets=file_targets,@@ -645,17 +806,9 @@ async def get_health(else:# Dashboard mode — top-N worst files + headline findings + the# per-module rollup so the overview page doesn't need a second- # round-trip.- # Leverage view: files ranked by NLOC-weighted deficit (how much each- # drags the headline), not by raw score. Distinct from worst_files —- # a big warning-band file outranks a tiny alert-band one here because- # fixing it moves the average far more. Same serializer, so every row- # carries weighted_deficit for the caller to sort on further.- by_leverage = sorted(- (m for m in all_metrics if m.score < HEALTHY_MIN),- key=lambda m: max(HEALTHY_MIN - m.score, 0.0) * max(m.nloc, 1),- reverse=True,- )+ # 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)gap = _gap_analysis(all_metrics)result = {@@ -675,7 +828,7 @@ async def get_health(_serialize_metric(m, leads.get(m.file_path)) for m in by_leverage[:limit]],"top_findings": [_serialize_finding(f) for f in finding_rows[:limit]],- "top_findings_total": len(finding_rows),+ "top_findings_total": findings_total,# Worst-first, so the cap keeps the modules worth looking at. On a# monorepo the tail is dozens of single-file buckets."modules": all_modules[:limit],@@ -684,16 +837,24 @@ async def get_health(if "churn_complexity" in include_set:result["churn_complexity"] = churn_pointsif "accuracy" in include_set:- # Self-validation: does the score rank the buggy files first? Pure- # over the already-loaded metrics + findings (no extra query).+ # Self-validation: does the score rank the buggy files first?+ # Scored over the full open set (``accuracy_rows``), not the capped+ # head — ranking quality measured on the top 20 would be circular.# ``None`` when there isn't enough signal for an honest number.result["defect_accuracy"] = compute_defect_accuracy(all_metrics,- [_serialize_finding(f) for f in finding_rows],+ [_serialize_finding(f) for f in accuracy_rows],)if "biomarkers" in include_set and "findings" not in result:- result["findings"] = [_serialize_finding(f) for f in finding_rows]+ # Capped like every other ranked list. Uncapped, this was the one block+ # in the tool that could return the repo's entire open finding set: on a+ # 3.2k-file repo ``include=["biomarkers"]`` with no targets served 10.3k+ # rows / 4.7MB, which overflows an agent's context and returns nothing+ # usable. Findings arrive impact-ordered, so the cap keeps the ones+ # worth reading.+ result["findings"] = [_serialize_finding(f) for f in finding_rows[:limit]]+ result["findings_total"] = findings_totalif "refactoring" in include_set:# Structured refactoring plans (the concrete split groups / evidence /@@ -779,19 +940,10 @@ async def get_health("files": coverage_payload,}- # Dimension filter: ``include=["performance"]`` (or "defect" /- # "maintainability") narrows the returned findings to that pillar so an- # agent can ask "show me only the performance risk in this change". Applied- # after the biomarkers/refactoring includes so it filters whatever findings- # the response carries. Each finding's ``dimension`` is set at scoring time.- dimension_filter = include_set & {"performance", "defect", "maintainability"}- if dimension_filter:- for field in ("findings", "top_findings"):- rows = result.get(field)- if rows:- result[field] = [- r for r in rows if (r.get("dimension") or "defect") in dimension_filter- ]+ # (The dimension filter — ``include=["performance"]`` and friends, so an+ # agent can ask "show me only the performance risk in this change" — is+ # applied where the rows are selected, not here. Filtering the finished+ # response meant filtering a list already capped by impact.)# One entry per biomarker type actually present in the findings this# response carries. Built last so the dimension filter above has already@@ -831,4 +983,7 @@ async def get_health(analyzed = [m.updated_at for m in all_metrics if getattr(m, "updated_at", None)]if analyzed:result["_meta"]["health_analyzed_at"] = max(analyzed).isoformat()+ # Server-side wall clock, as ``get_context`` already reports. Without it a+ # regression in here is invisible until someone profiles it by hand.+ result["_meta"]["timing_ms"] = round((perf_counter() - started) * 1000, 2)return resultdiff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.pyindex cbe93102f..0278b0edc 100644--- a/tests/unit/server/mcp/test_health.py+++ b/tests/unit/server/mcp/test_health.py@@ -279,3 +279,101 @@ async def test_get_health_metric_carries_dominant_cause_and_magnitude(setup_mcp,worst = next(m for m in dash["worst_files"] if m["file_path"] == "src/auth/service.py")assert worst["primary_biomarker"] == "complex_method"assert worst["total_deduction"] == pytest.approx(3.9)+++async def test_get_health_biomarkers_block_is_capped(setup_mcp, health_data):+ """``include=["biomarkers"]`` respects ``limit`` and reports the true total.++ Regression: this was the one ranked list in the tool with no cap, so a+ dashboard-mode call returned every open finding in the repo — 10.3k rows /+ 4.7MB on repowise itself, which overflows an agent's context and yields+ nothing usable. Every other list caps and carries a ``*_total`` sibling.+ """+ from repowise.server.mcp_server import get_health++ result = await get_health(include=["biomarkers"], limit=2)+ assert len(result["findings"]) == 2+ # The cap is visible rather than inferred from the length.+ assert result["findings_total"] == 4+ # Impact-ordered, so the cap keeps the findings worth reading.+ impacts = [f["health_impact"] for f in result["findings"]]+ assert impacts == sorted(impacts, reverse=True)+++async def test_get_health_totals_survive_the_cap(setup_mcp, health_data):+ """Totals count the whole open set even when only ``limit`` rows ship.++ Dashboard mode no longer hydrates every finding to emit a handful, so the+ totals come from a separate narrow read; this pins them to the full set+ rather than the truncated head.+ """+ from repowise.server.mcp_server import get_health++ capped = await get_health(limit=1)+ assert len(capped["top_findings"]) == 1+ assert capped["top_findings_total"] == 4++ scoped = await get_health(targets=["src/auth/service.py"], limit=1)+ assert len(scoped["findings"]) == 1+ assert scoped["findings_total"] == 4+++async def test_get_health_only_projection_preserves_block_content(setup_mcp, health_data):+ """``only`` gates the work behind a block without changing what it holds.++ The projection now skips expensive optional work rather than computing and+ discarding it, so the surviving block must still be byte-identical to the+ one the full response carries.+ """+ from repowise.server.mcp_server import get_health++ full = await get_health()+ projected = await get_health(only=["kpis"])+ assert set(projected) == {"mode", "kpis", "_meta"}+ assert projected["kpis"] == full["kpis"]+++async def test_get_health_dimension_filter_is_not_defeated_by_the_cap(setup_mcp, health_data):+ """A dimension filter selects the rows, rather than trimming a capped head.++ Regression: the filter used to run over the finished response, so it+ narrowed a list already capped by ``health_impact``. Performance findings+ carry low impact by construction, so the head was defect-heavy and+ ``include=["biomarkers", "performance"]`` filtered down to nothing — while+ ``findings_total`` still reported the whole repo, which reads as "no+ performance risk here" rather than "none shown".+ """+ from repowise.server.mcp_server import get_health++ # limit=1 forces the cap to bite before the filter would have run.+ result = await get_health(include=["biomarkers", "performance"], limit=1)+ assert [f["dimension"] for f in result["findings"]] == ["performance"]+ # The total describes the filtered set, so an empty list is unambiguous.+ assert result["findings_total"] == 1++ maint = await get_health(include=["biomarkers", "maintainability"], limit=1)+ assert [f["dimension"] for f in maint["findings"]] == ["maintainability"]++ scoped = await get_health(+ targets=["src/auth/service.py"], include=["biomarkers", "performance"]+ )+ assert [f["dimension"] for f in scoped["findings"]] == ["performance"]+++async def test_get_health_dimension_filter_leaves_kpis_and_ranking_alone(setup_mcp, health_data):+ """Asking to *see* one dimension must not restate the repo's health.++ The leads and the performance KPI come from the unfiltered open set; only+ the emitted findings narrow.+ """+ from repowise.server.mcp_server import get_health++ full = await get_health()+ filtered = await get_health(include=["biomarkers", "maintainability"])+ assert filtered["kpis"]["performance_findings"] == full["kpis"]["performance_findings"]+ assert filtered["worst_files"] == full["worst_files"]