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
perf(mcp): compact health responses with recoverable pagination (#1924)
Raghav Chamadiya18f9a532fc7d
diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.pyindex bb6a2b4d1..dbdd25959 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py@@ -108,6 +108,37 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {),protected=("title", "architecture", "entry_points"),),+ "get_health": ResponseBudgetContract(+ "blocks",+ (+ "suggestion_legend",+ "coverage.files[]",+ "trend.recent[]",+ "trend.alerts[]",+ "churn_complexity[]",+ "test_findings[]",+ "top_findings[]",+ "findings[]",+ "worst_files[]",+ "modules[]",+ "trends[]",+ "metrics[]",+ "refactoring_plans[]",+ "performance_opportunities[]",+ "high_leverage_files[]",+ "secondary_rankings",+ ),+ protected=(+ "mode",+ "directive",+ "targets",+ "unresolved",+ "known_modules",+ "kpis",+ "distribution",+ "gap_analysis",+ ),+ ),}@@ -305,6 +336,27 @@ def enforce_response_budget(headroom=0,record_counts=True,)+ if tool == "get_health":+ plans = result.get("refactoring_plans")+ profiles = result.get("validation_profiles")+ if isinstance(plans, list) and isinstance(profiles, list):+ referenced = {+ plan.get("validation_profile_id")+ for plan in plans+ if isinstance(plan, dict) and plan.get("validation_profile_id")+ }+ kept_profiles = [+ profile+ for profile in profiles+ if isinstance(profile, dict) and profile.get("id") in referenced+ ]+ dropped_profiles = [profile for profile in profiles if profile not in kept_profiles]+ if dropped_profiles:+ collector.add("validation_profiles no longer referenced after response budgeting", dropped_profiles)+ result["validation_profiles"] = kept_profiles+ result["validation_profiles_emitted"] = len(kept_profiles)+ result["validation_profiles_reduced_reason"] = "response_budget"+ result["truncated"] = Truecollector.attach(result)if response_chars(result) > limit:diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex 906ab3425..51ea08a96 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -2,6 +2,7 @@from __future__ import annotations+import hashlibimport jsonfrom dataclasses import asdictfrom pathlib import Path@@ -49,7 +50,7 @@ from repowise.core.persistence.models import (RefactoringSuggestion,)from repowise.core.registry import mcp_tool_registry as mcp-from repowise.server.mcp_server._budget import effective_char_budget+from repowise.server.mcp_server._budget import OmissionCollectorfrom repowise.server.mcp_server._helpers import (_get_exclude_spec,_get_repo,@@ -251,106 +252,71 @@ _ONLY_ALIASES = {_DIRECTIVE_CANDIDATES = 3-# Deliberately not ``CHAR_BUDGET`` (8000 tokens). That ceiling is for tools that-# *summarize*; the dashboard is a ranked report and already measures ~44k chars-# at the documented default ``limit=20``, so budgeting it there would silently-# halve every list on a call that has never failed. The ceiling that matters here-# is the one whose breach is an isError: pass an effectively-unbounded-# ``configured`` so ``effective_char_budget`` returns the host-derived cap alone-# (25000 tokens x 0.6 x 4 chars = 60,000), and follows a narrowed-# ``MAX_MCP_OUTPUT_TOKENS`` down.-_HOST_CEILING = 1 << 30--# Room for what the guard adds *after* it measures: ``truncated_to_fit``, the-# recovery sentence and ``timing_ms``. Without it the report of the trim pushed-# the response back over the ceiling the trim existed to respect — the marker-# has to be inside the budget, not on top of it. Same shape as ``tool_why``'s-# ``_COLLECTOR_HEADROOM_CHARS``, and generous: over-reserving costs a row.-_TRUNCATION_MARKER_HEADROOM = 400--# Every list this response can carry that grows with the repo, trimmed-# longest-first when the whole payload would overflow the host's tool-result cap.-# Named rather than derived from "every value that is a list" so trimming can-# never eat a small structural list (``kpis.performance_unsupported_languages``,-# ``unresolved``) to save bytes a growable list is responsible for.-#-# **This list must stay exhaustive, and the first version of it was not.** It-# held only the eight dashboard blocks that carry a ``limit`` cap, which are the-# lists least able to overflow — while the three genuinely unbounded ones were-# invisible to the guard. ``metrics`` and ``trends`` are built per *target* with-# no cap at all (a ``module:`` target expands to every file in the module), and-# targeted ``coverage.files`` serializes the per-line ``covered_lines`` arrays-# that dashboard mode declines to read precisely because they measured 466,874 B.-# A guard that misses those does something worse than nothing: it trims a small-# capped list to zero, still overflows, and stamps ``truncated_to_fit`` claiming-# it handled the problem. **When adding a list to this response, add it here.**-#-# Dotted entries address one level of nesting; the flat ``result.get(k)`` scan-# would never have found them.-_TRIMMABLE_LISTS = (- "performance_opportunities",- "refactoring_plans",- "high_leverage_files",- "worst_files",- "test_findings",- "top_findings",- "findings",- "churn_complexity",- "modules",- "metrics",- "trends",- "coverage.files",- "trend.recent",-)+def _stamp_collection(+ result: dict[str, Any],+ key: str,+ *,+ total: int | None = None,+ reason: str = "limit",+) -> None:+ """Attach complete-population accounting to one emitted collection."""+ rows = result.get(key)+ if not isinstance(rows, list):+ return+ eligible = len(rows) if total is None else total+ emitted = len(rows)+ result[f"{key}_total"] = eligible+ result[f"{key}_emitted"] = emitted+ if emitted < eligible:+ result[f"{key}_reduced_reason"] = reason+++def _validation_profile(validation: dict[str, Any]) -> tuple[str, dict[str, Any]]:+ """Deduplicate a plan's repeated tests, targets, and command material."""+ encoded = json.dumps(validation, sort_keys=True, separators=(",", ":"), default=str)+ profile_id = "validation_" + hashlib.sha256(encoded.encode()).hexdigest()[:16]+ tests = list(validation.get("tests") or [])+ targets = list(validation.get("targets") or [])+ profile = {+ key: value+ for key, value in validation.items()+ if key not in {"tests", "targets", "commands", "truncated"}+ }+ profile.update(+ {+ "id": profile_id,+ "tests": tests,+ "tests_total": int(validation.get("total") or len(tests)),+ "tests_emitted": len(tests),+ "targets": targets,+ "commands": list(validation.get("commands") or []),+ "commands_total": len(validation.get("commands") or []),+ "commands_emitted": len(validation.get("commands") or []),+ }+ )+ if profile["tests_emitted"] < profile["tests_total"]:+ profile["tests_reduced_reason"] = "analysis_source_cap"+ return profile_id, profile-def _resolve_list(result: dict[str, Any], path: str) -> list[Any] | None:- """The list at a ``_TRIMMABLE_LISTS`` path, or ``None`` when absent."""- node: Any = result- for part in path.split("."):- if not isinstance(node, dict):- return None- node = node.get(part)- return node if isinstance(node, list) and node else None---def _fit_to_budget(result: dict[str, Any], budget: int) -> dict[str, int]:- """Trim ranked lists until *result* fits *budget* chars. Returns what it cut.-- ``include`` only ever adds a block, and the dashboard's ranked lists compose:- measured on this repo, bare ``include=['refactoring']`` returns ~59k chars- with no single list at fault (refactoring_plans 34%, high_leverage_files 16%,- worst_files 16%, test_findings 13%, top_findings 13%). Past the host's- ``MAX_MCP_OUTPUT_TOKENS`` the result is *rejected* with an isError — the- agent loses the whole answer — so a per-list cap that is individually- reasonable is not enough; something has to bound the sum.-- Trims the currently-longest list, so the cut lands on whichever block is- actually responsible rather than on a fixed victim. Every trimmed list keeps- its ``*_total`` sibling, and the cut is reported in- ``_meta.truncated_to_fit`` — the recovery path is ``only=[...]``, which gates- the work as well as the payload.- """- dropped: dict[str, int] = {}- size = len(json.dumps(result, default=str))- while size > budget:- candidates = {k: rs for k in _TRIMMABLE_LISTS if (rs := _resolve_list(result, k))}- longest = max(candidates, key=lambda k: len(candidates[k]), default=None)- if longest is None:- # Nothing left to give. Better an oversized response the host may- # reject than a silently empty one — and _meta says what happened.- break- rows = candidates[longest]- # Estimate how many rows the overflow is worth from this list's own mean- # row size, so a 200-row overflow is not 200 whole-response- # re-serializations. Never more than half the list per pass: the estimate- # is a mean over uneven rows, and over-trimming cannot be undone.- per_row = max(1, len(json.dumps(rows, default=str)) // len(rows))- take = max(1, min(len(rows), (size - budget) // per_row, max(1, len(rows) // 2)))- del rows[len(rows) - take :]- dropped[longest] = dropped.get(longest, 0) + take- size = len(json.dumps(result, default=str))- return dropped+def _stamp_nested_collections(value: Any) -> None:+ """Give every nested list an emitted count and an honest eligible total."""+ if isinstance(value, list):+ for item in value:+ _stamp_nested_collections(item)+ return+ if not isinstance(value, dict):+ return+ for key, child in list(value.items()):+ if isinstance(child, list):+ total_key = f"{key}_total"+ emitted_key = f"{key}_emitted"+ total = int(value.get(total_key, len(child)) or 0)+ value.setdefault(total_key, total)+ value.setdefault(emitted_key, len(child))+ if len(child) < total:+ value.setdefault(f"{key}_reduced_reason", "limit")+ _stamp_nested_collections(child)def _in_dimensions(row: Any, dimensions: set[str]) -> bool:@@ -897,17 +863,12 @@ async def get_health(limit: int = 20,only: list[str] | None = None,refactoring_view: str = "canonical",+ cursor: int = 0,) -> dict:"""Code-health scores and findings — self-check a file before/after editing.- No ``targets`` → dashboard led by a ``directive`` naming the first file to- fix. With ``targets`` → per-file scores and findings. Rank by- ``weighted_deficit`` (score-points x NLOC), not ``score``;- ``share_of_repo_gap_pct`` expresses the same quantity as a percentage.-- Per file: ``score`` is defect risk *and* the headline — there is no- ``defect_score`` — beside ``maintainability_score`` / ``performance_score``- (never blended in).+ No ``targets`` returns a directive-led dashboard; targets return ranked+ per-file scores and findings using ``weighted_deficit``.Args:targets: file paths or ``module:<name>``. Empty → dashboard. Unmatched@@ -917,25 +878,44 @@ async def get_health(``performance``/``defect``/``maintainability`` (dimension).``performance`` adds causal ``performance_opportunities``; with``refactoring``, a compact ``recommendation_lede``. Only adds- blocks; pair with ``only``. Over cap sets ``_meta.truncated_to_fit``.- only: top-level keys to keep; ``["directive"]`` is cheapest and- ``*_total`` siblings survive. Only ``biomarkers``, ``accuracy``- and ``refactoring`` alias; ``performance``, ``defect``,- ``maintainability`` and ``signals`` do not and land in- ``unknown_only_keys``.+ blocks; pair with ``only``. Final response budgeting and omission+ recovery use the shared MCP delivery contract.+ only: top-level keys to keep; identity, counts, unresolved targets,+ and recovery metadata survive. ``biomarkers``, ``accuracy``, and+ ``refactoring`` alias; ``performance``, ``defect``, and+ ``maintainability`` do not.repo: usually omitted.- limit: max rows per ranked list (max 50, ``0`` for none).+ limit: max rows per ranked list (``0`` for none). Performance+ opportunities and refactoring plans have independent caps of 6;+ performance evidence is capped at 3 rows per opportunity.refactoring_view: ``canonical`` (default) or diversified``file_spread``.+ cursor: zero-based offset for top-level ranked collections. Reduced+ pages carry an exact next-page call; nested evidence uses omission+ references instead."""started = perf_counter()# ``0`` means none, matching the ``module_limit`` convention on the REST# coverage route. It used to clamp up to 1, so the documented way to ask for# "the totals, none of the rows" silently returned a row.- limit = min(max(limit, 0), 50)+ limit = max(limit, 0)+ cursor = max(cursor, 0)if refactoring_view not in {"canonical", "file_spread"}:refactoring_view = "canonical"include_set = set(include or [])+ known_includes = {+ "biomarkers",+ "refactoring",+ "trend",+ "coverage",+ "accuracy",+ "signals",+ "churn_complexity",+ "performance",+ "defect",+ "maintainability",+ }+ unknown_include_keys = sorted(include_set - known_includes)only_list = [_ONLY_ALIASES.get(k, k) for k in (only or [])]only_set = set(only_list)@@ -993,6 +973,46 @@ async def get_health(file_targets = [t.replace("\\", "/") for t in raw_targets if not t.startswith("module:")]ctx = await _resolve_repo_context(repo)+ omission_collector = OmissionCollector("get_health", repo_root=ctx.path)+ semantic_omissions: dict[str, list[Any]] = {}+ page_recoveries: dict[str, tuple[int, int, int]] = {}+ paged_collections = {+ "metrics",+ "findings",+ "trends",+ "worst_files",+ "high_leverage_files",+ "top_findings",+ "test_findings",+ "modules",+ "churn_complexity",+ "coverage.files",+ "refactoring_plans",+ "performance_opportunities",+ }++ def bounded(rows: list[Any], label: str, *, cap: int | None = None) -> list[Any]:+ """Bound one collection and retain its exact tail in shared omission storage."""+ row_cap = limit if cap is None else cap+ start = cursor if label in paged_collections else 0+ kept = rows[start : start + row_cap]+ if len(kept) < len(rows):+ tail_start = start + len(kept)+ if label in paged_collections:+ if tail_start < len(rows):+ next_limit = (+ min(row_cap or 6, 6)+ if label in {"refactoring_plans", "performance_opportunities"}+ else min(len(rows) - tail_start, 50)+ )+ page_recoveries[label] = (+ tail_start,+ next_limit,+ len(rows) - tail_start,+ )+ else:+ semantic_omissions[label] = rows[row_cap:]+ return kept# Performance headline inputs (dashboard mode): filled inside the session.perf_coverage: PerfCoverage | None = Noneperf_findings_count = 0@@ -1091,7 +1111,7 @@ async def get_health(emitted = _rank_emitted([f for f in finding_rows if _in_dimensions(f, dimension_filter)])- finding_rows = emitted[:limit]+ finding_rows = emittedlegend_rows: list[Any] = finding_rowselse:# Narrow read over every open finding: the four attributes@@ -1354,15 +1374,13 @@ async def get_health(churn_points: list[dict[str, Any]] = []if "churn_complexity" in include_set and not scoped:git_meta_by_path = await get_all_git_metadata(session, repository.id)- churn_points = [- asdict(p) for p in churn_complexity_points(all_metrics, git_meta_by_path)[:limit]- ]+ churn_points = [asdict(p) for p in churn_complexity_points(all_metrics, git_meta_by_path)]# Load the snapshot window for the repo-level trend block and/or the# per-file trajectory we attach in targeted mode ("should I touch this# file" context for agents).snapshots: list[Any] = []- if "trend" in include_set or scoped:+ if "trend" in include_set or (scoped and wants("trends")):snapshots = await list_health_snapshots(session, repository.id, limit=20)# Dominant-cause lead per file. Targeted mode wants one per target, so@@ -1463,6 +1481,9 @@ async def get_health(if m.file_path in signals_by_path: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)]+ )result: dict[str, Any] = {"mode": "targets","targets": raw_targets,@@ -1473,11 +1494,14 @@ async def get_health(# visible — a ``module:`` target expands to every file in the module,# so this is the one growable list whose length the caller cannot# infer from what they passed.- "metrics": metric_payload,+ **({"modules": module_rollup} if module_targets else {}),+ "metrics": bounded(metric_payload, "metrics"),"metrics_total": len(metric_payload),# 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": bounded(+ [_serialize_finding(f) for f in finding_rows], "findings"+ ),"findings_total": findings_total,}unresolved = _unresolved_targets(@@ -1520,10 +1544,27 @@ async def get_health(entry["unclamped_delta"] = t.unclamped_deltatrends.append(entry)if trends:- result["trends"] = trends- if module_targets:- in_modules = [m for m in all_metrics if m.module in set(module_targets)]- result["modules"] = _module_rollups(in_modules)+ result["trends"] = bounded(trends, "trends")+ if module_targets and not only and not include_set:+ result["secondary_rankings"] = {+ "findings": {+ "total": findings_total,+ "call": (+ f"get_health(targets={raw_targets!r}, only=['findings'], "+ f"repo={repo!r}, limit=50, refactoring_view='{refactoring_view}')"+ ),+ },+ "trends": {+ "total": len(trends),+ "call": (+ f"get_health(targets={raw_targets!r}, only=['trends'], "+ f"repo={repo!r}, limit=50, refactoring_view='{refactoring_view}')"+ ),+ },+ }+ for block in ("findings", "trends"):+ result.pop(block, None)+ result.pop(f"{block}_total", None)else:# Dashboard mode — top-N worst files + headline findings + the# per-module rollup so the overview page doesn't need a second@@ -1533,7 +1574,6 @@ async def get_health(all_modules = _module_rollups(all_metrics)gap = _gap_analysis(all_metrics)result = {- "mode": "dashboard",# Lead with the call, not the data. Every block below ranks and# describes; this one recommends."directive": _directive(@@ -1543,15 +1583,16 @@ async def get_health(plan_biomarkers_by_path,plan_count_by_path,),+ "mode": "dashboard","kpis": kpis,"distribution": health_distribution(all_metrics),# Where the gap to Healthy concentrates — the "few files, not the# long tail" reframe that turns a repo-wide number into a short list."gap_analysis": gap,- "worst_files": [+ "worst_files": bounded([_serialize_metric(m, leads.get(m.file_path), is_test=m.file_path in test_paths)- for m in metric_rows[:limit]- ],+ for m in metric_rows+ ], "worst_files"),# Both ranked file lists deliberately keep test files in place, and# both now say which rows are tests. Measured on this repo, 0 of the# top 25 by the worst-first comparator are test material, so there@@ -1568,7 +1609,7 @@ async def get_health(# share is bounded by 100% and the rows sum to 100% by construction# — the net gap would let healthy files cushion the total and push a# single large file over 100% (issue #1437).- "high_leverage_files": [+ "high_leverage_files": bounded([{**_serialize_metric(m, leads.get(m.file_path), is_test=m.file_path in test_paths@@ -1585,23 +1626,49 @@ async def get_health(else None),}- for m in by_leverage[:limit]- ],+ for m in by_leverage+ ], "high_leverage_files"),"high_leverage_files_total": len(by_leverage),- "top_findings": [_serialize_finding(f) for f in finding_rows[:limit]],+ "top_findings": bounded(+ [_serialize_finding(f) for f in finding_rows], "top_findings"+ ),"top_findings_total": findings_total,# The test half of the same ranked set, in its own bucket so a# thrashing test suite stays visible without competing with# production defect risk for the most-read list.- "test_findings": [_serialize_finding(f) for f in test_finding_rows[:limit]],+ "test_findings": bounded(+ [_serialize_finding(f) for f in test_finding_rows], "test_findings"+ ),"test_findings_total": test_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],+ "modules": bounded(all_modules, "modules"),"modules_total": len(all_modules),}+ if not only:+ result["secondary_rankings"] = {+ "worst_files": {+ "total": len(metric_rows),+ "call": f"get_health(repo={repo!r}, only=['worst_files'], limit=50)",+ },+ "top_findings": {+ "total": findings_total,+ "call": f"get_health(repo={repo!r}, only=['top_findings'], limit=50)",+ },+ "test_findings": {+ "total": test_findings_total,+ "call": f"get_health(repo={repo!r}, only=['test_findings'], limit=50)",+ },+ "modules": {+ "total": len(all_modules),+ "call": f"get_health(repo={repo!r}, only=['modules'], limit=50)",+ },+ }+ for block in ("worst_files", "top_findings", "test_findings", "modules"):+ result.pop(block, None)+ result.pop(f"{block}_total", None)if "churn_complexity" in include_set:- result["churn_complexity"] = churn_points+ result["churn_complexity"] = bounded(churn_points, "churn_complexity")if "accuracy" in include_set:# Self-validation: does the score rank the buggy files first?# Scored over the full open set (``accuracy_rows``), not the capped@@ -1619,20 +1686,45 @@ async def get_health(# 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"] = bounded(+ [_serialize_finding(f) for f in finding_rows], "findings"+ )result["findings_total"] = findings_total# Same production/test split as ``top_findings``: this block only ever# fires in dashboard mode (targeted mode set ``findings`` above), so it# is describing the repo, not a file the caller named.- result["test_findings"] = [_serialize_finding(f) for f in test_finding_rows[:limit]]+ result["test_findings"] = bounded(+ [_serialize_finding(f) for f in test_finding_rows], "test_findings"+ )result["test_findings_total"] = test_findings_totalif "refactoring" in include_set:# Canonical is the shared REST/MCP/CLI order. File diversity remains# available only through the explicitly named ``file_spread`` view.- result["refactoring_plans"] = [- recommendation.as_dict() for recommendation in refactoring_recommendations[:limit]- ]+ validation_profiles: dict[str, dict[str, Any]] = {}+ plan_payload = []+ selected_recommendations = bounded(+ refactoring_recommendations,+ "refactoring_plans",+ cap=min(limit, 6),+ )+ for recommendation in selected_recommendations:+ payload = recommendation.as_dict()+ validation = payload.pop("validation", None)+ if validation:+ profile_id, profile = _validation_profile(validation)+ validation_profiles.setdefault(profile_id, profile)+ payload["validation_profile_id"] = profile_id+ plan_payload.append(payload)+ result["refactoring_plans"] = plan_payload+ if validation_profiles:+ result["validation_profiles"] = list(validation_profiles.values())+ _stamp_collection(+ result,+ "validation_profiles",+ total=len(validation_profiles),+ reason="profile_cap",+ )result["refactoring_plans_total"] = len(refactoring_rows)# The deterministic prose suggestion is the fallback for biomarkers# that have no structured detector yet. It is emitted once per@@ -1647,6 +1739,18 @@ async def get_health(if "trend" in include_set:summary = diff_snapshots(snapshots)+ recent = recent_kpis(snapshots, limit=10)+ alerts = [+ {+ "kind": a.kind,+ "metric": a.metric,+ "current": a.current,+ "baseline": a.baseline,+ "delta": a.delta,+ "message": a.message,+ }+ for a in summary.alerts+ ]result["trend"] = {"current_hotspot_health": summary.current_hotspot_health,"current_average_health": summary.current_average_health,@@ -1654,29 +1758,45 @@ async def get_health("previous_average_health": summary.previous_average_health,"hotspot_delta": summary.hotspot_delta,"average_delta": summary.average_delta,- "alerts": [- {- "kind": a.kind,- "metric": a.metric,- "current": a.current,- "baseline": a.baseline,- "delta": a.delta,- "message": a.message,- }- for a in summary.alerts- ],- "recent": recent_kpis(snapshots, limit=10),+ "alerts": bounded(alerts, "trend.alerts"),+ "alerts_total": len(alerts),+ "alerts_emitted": min(len(alerts), limit),+ "recent": bounded(recent, "trend.recent"),+ "recent_total": len(recent),+ "recent_emitted": min(len(recent), limit),}+ if len(alerts) > limit:+ result["trend"]["alerts_reduced_reason"] = "limit"+ if len(recent) > limit:+ result["trend"]["recent_reduced_reason"] = "limit"opportunities = []if "performance" in include_set and wants_performance_opportunities:+ performance_rows = [row for row in lead_rows if _in_dimensions(row, {"performance"})]opportunities = build_performance_opportunities(- [row for row in lead_rows if _in_dimensions(row, {"performance"})],- evidence_limit=8,+ performance_rows,+ evidence_limit=max(len(performance_rows), 3),)- result["performance_opportunities"] = [- opportunity.as_dict() for opportunity in opportunities[:limit]- ]+ opportunity_payload = []+ selected_opportunities = bounded(+ opportunities,+ "performance_opportunities",+ cap=min(limit, 6),+ )+ for opportunity in selected_opportunities:+ payload = opportunity.as_dict()+ evidence = list(payload.get("evidence", []))+ payload["evidence"] = bounded(+ evidence,+ f"performance_opportunities.{opportunity.opportunity_id}.evidence",+ cap=3,+ )+ payload["evidence_total"] = payload.get("observations_total", len(evidence))+ payload["evidence_emitted"] = len(payload["evidence"])+ if payload["evidence_emitted"] < payload["evidence_total"]:+ payload["evidence_reduced_reason"] = "evidence_cap"+ opportunity_payload.append(payload)+ result["performance_opportunities"] = opportunity_payloadresult["performance_opportunities_total"] = len(opportunities)if {"performance", "refactoring"} <= include_set and wants("recommendation_lede"):@@ -1724,7 +1844,6 @@ async def get_health("cost","risk","rank_score",- "validation",)}if lead_payload@@ -1732,8 +1851,10 @@ async def get_health(),"performance_plan_id": matching.id if matching else None,"next_call": (- "get_health(include=['performance','refactoring'], limit=3, "- "only=['performance_opportunities','refactoring_plans'])"+ f"get_health(targets={raw_targets!r}, repo={repo!r}, "+ "include=['performance','refactoring'], limit=3, "+ "only=['performance_opportunities','refactoring_plans'], "+ f"refactoring_view='{refactoring_view}')"),}@@ -1741,14 +1862,16 @@ async def get_health(# Drop the bulky covered-lines arrays from dashboard mode; full# detail is available in targeted mode.if scoped:- coverage_payload = [_serialize_coverage_row(r) for r in coverage_rows]- _attach_coverage_decay(coverage_payload, coverage_rows, str(ctx.path))+ selected_coverage = bounded(coverage_rows, "coverage.files")+ coverage_payload = [_serialize_coverage_row(r) for r in selected_coverage]+ _attach_coverage_decay(coverage_payload, selected_coverage, str(ctx.path))else:# Built narrow, not built wide and subtracted from. These rows came# back without the column at all (see the read above).- coverage_payload = [- _serialize_coverage_row(r, covered_lines=False) for r in coverage_rows[:limit]+ full_coverage_payload = [+ _serialize_coverage_row(r, covered_lines=False) for r in coverage_rows]+ coverage_payload = bounded(full_coverage_payload, "coverage.files")# ``ingested_at`` is a datetime on the summary too — coerce.if coverage_summary.get("ingested_at") is not None:coverage_summary = {@@ -1758,7 +1881,11 @@ async def get_health(result["coverage"] = {"summary": coverage_summary,"files": coverage_payload,+ "files_total": len(coverage_rows),+ "files_emitted": len(coverage_payload),}+ if len(coverage_payload) < len(coverage_rows):+ result["coverage"]["files_reduced_reason"] = "limit"# (The dimension filter — ``include=["performance"]`` and friends, so an# agent can ask "show me only the performance risk in this change" — is@@ -1790,6 +1917,35 @@ async def get_health(bt: suggestion_for(bt) for bt in sorted(t for t in present_types if t)}+ collection_totals = {+ "targets": len(raw_targets),+ "metrics": len(metric_payload) if scoped else None,+ "findings": findings_total,+ "trends": len(trends) if scoped else None,+ "modules": len(module_rollup) if scoped else len(all_modules),+ "worst_files": len(metric_rows),+ "high_leverage_files": len(by_leverage),+ "top_findings": findings_total,+ "test_findings": test_findings_total,+ "churn_complexity": len(churn_points),+ "refactoring_plans": len(refactoring_recommendations),+ "performance_opportunities": len(opportunities),+ }+ for key, total in collection_totals.items():+ if total is None:+ continue+ cap_reason = (+ "collection_cap"+ if key in {"refactoring_plans", "performance_opportunities"}+ and limit > 6+ and len(result.get(key, [])) == 6+ else "limit"+ )+ _stamp_collection(result, key, total=total, reason=cap_reason)+ if unknown_include_keys:+ result["unknown_include_keys"] = unknown_include_keys+ _stamp_nested_collections(result)+# Projection. ``include`` could only ever add blocks, so asking for one# extra block re-shipped the whole dashboard with it; ``only`` is the# subtract half. Applied last so it can drop anything above, and ``mode`` /@@ -1811,9 +1967,39 @@ async def get_health(# error report.keep = (set(only_list)- | {"mode", "unresolved", "known_modules"}- | {f"{k}_total" for k in only_list}+ | {+ "mode",+ "targets",+ "targets_total",+ "targets_emitted",+ "unresolved",+ "unresolved_total",+ "unresolved_emitted",+ "known_modules",+ "known_modules_total",+ "known_modules_emitted",+ "unknown_include_keys",+ "unknown_include_keys_total",+ "unknown_include_keys_emitted",+ "recovery",+ }+ | {+ suffix+ for k in only_list+ for suffix in (+ f"{k}_total",+ f"{k}_emitted",+ f"{k}_reduced_reason",+ )+ })+ if "refactoring_plans" in only_set:+ keep |= {+ "validation_profiles",+ "validation_profiles_total",+ "validation_profiles_emitted",+ "validation_profiles_reduced_reason",+ }# A key that does not exist in this response is named rather than# quietly yielding an empty one — same rule as ``unresolved`` above.# A misspelled projection is otherwise indistinguishable from a block@@ -1825,6 +2011,26 @@ async def get_health(result = {k: v for k, v in result.items() if k in keep}if unknown:result["unknown_only_keys"] = unknown+ _stamp_collection(result, "unknown_only_keys", total=len(unknown))++ visible_recoveries = {+ label: values+ for label, values in page_recoveries.items()+ if label.split(".", 1)[0] in result+ }+ if visible_recoveries:+ recovery: dict[str, dict[str, Any]] = {}+ for label, (next_cursor, next_limit, remaining) in visible_recoveries.items():+ root = label.split(".", 1)[0]+ recovery[label] = {+ "remaining": remaining,+ "call": (+ f"get_health(targets={raw_targets!r}, include={list(include or [])!r}, "+ f"repo={repo!r}, limit={next_limit}, only={[root]!r}, "+ f"refactoring_view='{refactoring_view}', cursor={next_cursor})"+ ),+ }+ result["recovery"] = recovery# Targeted mode scopes the stale signal to the asked-about files; the# dashboard (no targets) keeps the repo-level warning.@@ -1832,7 +2038,8 @@ async def get_health(# When the health pass last ran, which is a separate pass from indexing and# can lag it. ``_build_meta``'s fields all describe the *index*, so a stale# health row was previously invisible.- analyzed = [m for m in all_metrics if getattr(m, "updated_at", None)]+ analyzed_source = metric_rows if scoped else all_metrics+ analyzed = [m for m in analyzed_source if getattr(m, "updated_at", None)]if analyzed:latest = max(analyzed, key=lambda m: m.updated_at)result["_meta"]["health_analyzed_at"] = latest.updated_at.isoformat()@@ -1847,18 +2054,15 @@ async def get_health(result["_meta"]["health_analyzed_commit"] = latest_commit[:12]if len(commits) > 1:result["_meta"]["health_analyzed_commits_distinct"] = len(commits)- # Keep the whole response under the host's tool-result cap. Applied after the- # projection (so ``only`` is credited for what it saved) and after ``_meta``- # (which the host tokenizes too), but before ``timing_ms`` so the reported- # time covers the trim.- if dropped := _fit_to_budget(- result, effective_char_budget(_HOST_CEILING) - _TRUNCATION_MARKER_HEADROOM- ):- result["_meta"]["truncated_to_fit"] = dropped- result["_meta"]["truncated_recovery"] = (- "Over MCP result cap. Re-request only=[...] — each list's *_total says what was there."- )# Server-side wall clock, as ``get_context`` already reports. Without it a# regression in here is invisible until someone profiles it by hand.+ for label, dropped in semantic_omissions.items():+ root = label.split(".", 1)[0]+ if root in result:+ omission_collector.add(+ f"{label} beyond emitted cap ({len(dropped)} dropped)",+ [row.as_dict() if hasattr(row, "as_dict") else row for row in dropped],+ )+ omission_collector.attach(result)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 b1b03913b..fb17b16d1 100644--- a/tests/unit/server/mcp/test_health.py+++ b/tests/unit/server/mcp/test_health.py@@ -19,9 +19,26 @@ async def test_get_health_dashboard(setup_mcp, health_data):assert result["mode"] == "dashboard"assert result["kpis"]["file_count"] == 2assert result["kpis"]["worst_performer_path"] == "src/auth/service.py"- assert len(result["worst_files"]) == 2- assert result["worst_files"][0]["file_path"] == "src/auth/service.py"- assert len(result["top_findings"]) == 4+ assert list(result)[:2] == ["directive", "mode"]+ assert "high_leverage_files" in result+ assert "worst_files" not in result+ assert result["secondary_rankings"]["worst_files"]["total"] == 2+ assert result["secondary_rankings"]["top_findings"]["total"] == 4+ assert "omitted" not in result["_meta"]+++async def test_dashboard_zero_limit_has_exact_ranked_page_recovery(setup_mcp, health_data):+ from repowise.server.mcp_server import get_health++ result = await get_health(limit=0)+ recovery = result["recovery"]["high_leverage_files"]+ assert "only=['high_leverage_files']" in recovery["call"]+ assert "cursor=0" in recovery["call"]+ assert "limit=1" in recovery["call"]+ recovered = await get_health(only=["high_leverage_files"], limit=1, cursor=0)+ assert len(recovered["high_leverage_files"]) == 1+ assert recovered["high_leverage_files"][0]["file_path"] == "src/auth/service.py"@pytest.mark.asyncio@@ -29,7 +46,7 @@ async def test_get_health_dashboard_surfaces_maintainability(setup_mcp, health_d"""The maintainability pillar is surfaced as a co-equal second signal."""from repowise.server.mcp_server import get_health- result = await get_health()+ result = await get_health(only=["kpis", "worst_files", "top_findings"])# Repo-level KPI headline for the maintainability pillar.# NLOC-weighted: (6.0*200 + 9.0*50) / 250 = 6.6.assert result["kpis"]["maintainability_average"] == 6.6@@ -49,7 +66,7 @@ async def test_get_health_dashboard_surfaces_performance(setup_mcp, health_data)"""The performance pillar is surfaced as a co-equal third signal."""from repowise.server.mcp_server import get_health- result = await get_health()+ result = await get_health(only=["kpis", "top_findings"])# Repo-level KPI headline for the performance pillar.# NLOC-weighted: (9.0*200 + 10.0*50) / 250 = 9.2.assert result["kpis"]["performance_average"] == 9.2@@ -70,7 +87,9 @@ async def test_get_health_dashboard_surfaces_leverage(setup_mcp, health_data):"""Leverage view: which files move the NLOC-weighted headline, not just which score low."""from repowise.server.mcp_server import get_health- result = await get_health()+ result = await get_health(+ only=["kpis", "gap_analysis", "worst_files", "high_leverage_files"]+ )kpis = result["kpis"]# Weighted (4.5*200 + 8.5*50)/250 = 5.3 vs plain mean (4.5 + 8.5)/2 = 6.5:# the divergence is the "a big low file holds the headline down" signal.@@ -139,6 +158,61 @@ async def _seed_plans(session, rid, plans):await session.commit()+def test_validation_profiles_deduplicate_without_dropping_commands_or_target_tests():+ from repowise.server.mcp_server.tool_health import _validation_profile++ validation = {+ "tests": ["tests/test_service.py::test_auth"],+ "total": 1,+ "commands": ["pytest tests/test_service.py::test_auth"],+ "targets": [+ {+ "file_path": "src/auth/service.py",+ "tests": ["tests/test_service.py::test_auth"],+ "total": 1,+ }+ ],+ }+ _profile_id, profile = _validation_profile(validation)++ assert profile["commands"] == validation["commands"]+ assert profile["commands_total"] == profile["commands_emitted"] == 1+ assert profile["targets"][0]["tests"] == validation["targets"][0]["tests"]+++async def test_target_freshness_uses_only_the_requested_health_rows(+ setup_mcp, health_data, session+):+ from datetime import UTC, datetime++ from sqlalchemy import select++ from repowise.core.persistence.models import HealthFileMetric+ from repowise.server.mcp_server import get_health++ rows = list(+ (+ await session.execute(+ select(HealthFileMetric).where(HealthFileMetric.repository_id == health_data)+ )+ )+ .scalars()+ .all()+ )+ by_path = {row.file_path: row for row in rows}+ by_path["src/auth/service.py"].updated_at = datetime(2025, 1, 1, tzinfo=UTC)+ by_path["src/auth/service.py"].analyzed_commit = "a" * 40+ by_path["src/db/models.py"].updated_at = datetime(2026, 1, 1, tzinfo=UTC)+ by_path["src/db/models.py"].analyzed_commit = "b" * 40+ await session.flush()++ result = await get_health(targets=["src/auth/service.py"], only=["metrics"])+ assert result["_meta"]["health_analyzed_at"].startswith("2025-01-01")+ assert result["_meta"]["health_analyzed_commit"] == "a" * 12+ assert "health_analyzed_commits_distinct" not in result["_meta"]++@pytest.mark.asyncioasync def test_directive_admits_when_the_file_has_no_plans_at_all(setup_mcp, health_data):"""``plan_via`` promised a fix for ``reason``; with no plans it cannot deliver one."""@@ -225,7 +299,8 @@ async def test_combined_recommendation_lede_is_compact_and_self_directing(assert lede["performance_opportunities_total"] == 1assert lede["refactoring_plans_total"] == 1assert lede["performance_lead"]["boundary_kind"] == "db"- assert {"benefit", "leverage", "cost", "risk", "validation"} <= set(lede["recommendation_lead"])+ assert {"benefit", "leverage", "cost", "risk"} <= set(lede["recommendation_lead"])+ assert "validation" not in lede["recommendation_lead"]assert "only=['performance_opportunities','refactoring_plans']" in lede["next_call"]@@ -339,7 +414,7 @@ async def test_get_health_unmatched_module_stays_scoped(setup_mcp, health_data):result = await get_health(targets=["module:nope"])assert result["mode"] == "targets"assert result["metrics"] == []- assert result["findings"] == []+ assert "findings" not in resultassert result["unresolved"] == [{"target": "module:nope", "reason": "no_such_module"}]# None of the repo-wide blocks leak into a scoped answer.assert not {"kpis", "worst_files", "gap_analysis", "distribution"} & set(result)@@ -363,7 +438,7 @@ async def test_get_health_findings_capped_with_honest_total(setup_mcp, health_daassert len(result["findings"]) == 2assert result["findings_total"] == 4- dash = await get_health(limit=2)+ dash = await get_health(only=["top_findings"], limit=2)assert len(dash["top_findings"]) == 2assert dash["top_findings_total"] == 4@@ -372,7 +447,7 @@ async def test_get_health_findings_capped_with_honest_total(setup_mcp, health_daasync def test_get_health_modules_capped_with_honest_total(setup_mcp, health_data):from repowise.server.mcp_server import get_health- result = await get_health(limit=1)+ result = await get_health(only=["modules"], limit=1)assert len(result["modules"]) == 1assert result["modules_total"] == 2@@ -382,7 +457,9 @@ async def test_get_health_suggestion_text_emitted_once_as_legend(setup_mcp, heal"""Suggestion prose is keyed by biomarker type, so it ships once, not per row."""from repowise.server.mcp_server import get_health- result = await get_health(include=["refactoring"])+ result = await get_health(+ include=["refactoring"], only=["top_findings", "suggestion_legend"]+ )rows = result["top_findings"]assert rows, "fixture should produce findings"assert not any("suggestion" in r for r in rows)@@ -616,9 +693,21 @@ async def test_get_health_only_names_unknown_keys(setup_mcp, health_data):result = await get_health(only=["directive", "kpiz"])assert result["unknown_only_keys"] == ["kpiz"]+ assert result["unknown_only_keys_total"] == 1+ assert result["unknown_only_keys_emitted"] == 1assert "directive" in result+async def test_get_health_include_names_unknown_keys(setup_mcp, health_data):+ from repowise.server.mcp_server import get_health++ result = await get_health(include=["trend", "typo"])+ assert result["unknown_include_keys"] == ["typo"]+ assert result["unknown_include_keys_total"] == 1+ assert result["unknown_include_keys_emitted"] == 1++@pytest.mark.asyncioasync def test_get_health_meta_stamps_when_health_last_ran(setup_mcp, health_data):"""Health is a separate pass from indexing and can lag it."""@@ -651,7 +740,7 @@ async def test_get_health_metric_carries_dominant_cause_and_magnitude(setup_mcp,# Σ health_impact = 1.2 + 0.7 + 1.0 + 1.0 — the depth behind a floored score.assert metric["total_deduction"] == pytest.approx(3.9)# Same lead reaches dashboard worst_files.- dash = await get_health()+ dash = await get_health(only=["worst_files"])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)@@ -687,7 +776,7 @@ async def test_get_health_totals_survive_the_cap(setup_mcp, health_data):"""from repowise.server.mcp_server import get_health- capped = await get_health(limit=1)+ capped = await get_health(only=["top_findings"], limit=1)assert len(capped["top_findings"]) == 1assert capped["top_findings_total"] == 4@@ -749,8 +838,10 @@ async def test_get_health_dimension_filter_leaves_kpis_and_ranking_alone(setup_m"""from repowise.server.mcp_server import get_health- full = await get_health()- filtered = await get_health(include=["biomarkers", "maintainability"])+ full = await get_health(only=["kpis", "worst_files"])+ filtered = await get_health(+ include=["biomarkers", "maintainability"], only=["kpis", "worst_files"]+ )assert filtered["kpis"]["performance_findings"] == full["kpis"]["performance_findings"]assert filtered["worst_files"] == full["worst_files"]@@ -816,7 +907,7 @@ async def test_worst_files_ranks_floored_ties_by_deduction(setup_mcp, floored_he"""from repowise.server.mcp_server import get_health- result = await get_health()+ result = await get_health(only=["worst_files"])assert [m["file_path"] for m in result["worst_files"]] == ["src/z.py","src/c.py",@@ -826,7 +917,7 @@ async def test_worst_files_ranks_floored_ties_by_deduction(setup_mcp, floored_he# The cap is where the old order actually hurt: under a score-only sort the# worst file falls off the page entirely.- capped = await get_health(limit=1)+ capped = await get_health(only=["worst_files"], limit=1)assert [m["file_path"] for m in capped["worst_files"]] == ["src/z.py"]@@ -840,11 +931,14 @@ async def test_worst_files_order_survives_every_dimension_filter(setup_mcp, floo"""from repowise.server.mcp_server import get_health- baseline = [m["file_path"] for m in (await get_health(limit=2))["worst_files"]]+ baseline = [+ m["file_path"]+ for m in (await get_health(only=["worst_files"], limit=2))["worst_files"]+ ]assert baseline == ["src/z.py", "src/c.py"]for include in (["defect"], ["maintainability"], ["performance"], ["biomarkers", "defect"]):- result = await get_health(include=include, limit=2)+ result = await get_health(include=include, only=["worst_files"], limit=2)assert [m["file_path"] for m in result["worst_files"]] == baseline, include@@ -860,7 +954,7 @@ async def test_one_response_agrees_with_itself_about_the_worst_file(setup_mcp, f"""from repowise.server.mcp_server import get_health- result = await get_health()+ result = await get_health(only=["kpis", "worst_files", "modules"])assert result["kpis"]["worst_performer_path"] == result["worst_files"][0]["file_path"]assert result["kpis"]["worst_performer_path"] == "src/z.py"@@ -908,7 +1002,7 @@ async def test_only_retains_the_total_for_every_capped_list(setup_mcp, health_daassert key in result, result.get("unknown_only_keys")assert f"{key}_total" in result, f"{key} lost its total under a projection"# And it is the real count, not the length of the capped list.- full = await get_health(include=include, limit=1)+ full = await get_health(include=include, only=[key], limit=1)assert result[f"{key}_total"] == full[f"{key}_total"]@@ -922,7 +1016,7 @@ async def test_worst_files_and_high_leverage_files_report_totals(setup_mcp, heal"""from repowise.server.mcp_server import get_health- result = await get_health(limit=1)+ result = await get_health(only=["worst_files", "high_leverage_files"], limit=1)assert len(result["worst_files"]) == 1assert result["worst_files_total"] == 2assert len(result["high_leverage_files"]) == 1@@ -953,7 +1047,20 @@ async def test_include_names_work_as_only_aliases(setup_mcp, health_data, alias,assert resolved in result# An alias that resolves is not "unknown".assert "unknown_only_keys" not in result- assert set(result) - {"mode", "_meta"} <= {resolved, f"{resolved}_total"}+ allowed = {+ resolved,+ f"{resolved}_total",+ f"{resolved}_emitted",+ f"{resolved}_reduced_reason",+ }+ if resolved == "refactoring_plans":+ allowed |= {+ "validation_profiles",+ "validation_profiles_total",+ "validation_profiles_emitted",+ "validation_profiles_reduced_reason",+ }+ assert set(result) - {"mode", "targets", "_meta"} <= allowed@pytest.mark.asyncio@@ -989,7 +1096,10 @@ async def test_suggestion_legend_survives_a_projection(setup_mcp, health_data_wi"""from repowise.server.mcp_server import get_health- full = await get_health(include=["refactoring"])+ full = await get_health(+ include=["refactoring"],+ only=["refactoring_plans", "suggestion_legend", "top_findings", "test_findings"],+ )assert full["suggestion_legend"], "fixture should produce legend entries"without_findings = await get_health(@@ -1017,11 +1127,13 @@ async def test_limit_zero_means_no_rows_not_one_row(setup_mcp, health_data):from repowise.server.mcp_server import get_healthresult = await get_health(limit=0)- for key in ("worst_files", "high_leverage_files", "top_findings", "test_findings", "modules"):- assert result[key] == [], key- # Totals are unaffected: the cap is a display decision, not a filter.- assert result["worst_files_total"] == 2- assert result["top_findings_total"] == (await get_health())["top_findings_total"]+ assert result["high_leverage_files"] == []+ assert result["high_leverage_files_total"] == 1+ for key in ("worst_files", "top_findings", "test_findings", "modules"):+ projected = await get_health(only=[key], limit=0)+ assert projected[key] == [], key+ assert projected[f"{key}_emitted"] == 0+ assert projected[f"{key}_total"] >= 0@pytest.mark.asyncio@@ -1123,7 +1235,7 @@ async def test_test_findings_get_their_own_bucket(setup_mcp, health_data_with_te"""from repowise.server.mcp_server import get_health- result = await get_health()+ result = await get_health(only=["top_findings", "test_findings"])# Unsplit, the two highest-impact findings in the fixture are both tests.assert [f["file_path"] for f in result["test_findings"]] == [@@ -1150,7 +1262,7 @@ async def test_each_bucket_is_capped_against_its_own_population(setup_mcp, healt"""from repowise.server.mcp_server import get_health- result = await get_health(limit=2)+ result = await get_health(only=["top_findings", "test_findings"], limit=2)assert len(result["top_findings"]) == 2assert len(result["test_findings"]) == 2assert result["top_findings_total"] == 4@@ -1166,7 +1278,7 @@ async def test_metric_rows_say_whether_a_file_is_test_material(setup_mcp, health"""from repowise.server.mcp_server import get_health- result = await get_health()+ result = await get_health(only=["worst_files", "high_leverage_files"])by_path = {m["file_path"]: m for m in result["worst_files"]}assert by_path["tests/test_service.py"]["is_test"] is Trueassert by_path["src/auth/service.py"]["is_test"] is False@@ -1223,7 +1335,7 @@ async def test_targeted_mode_asks_only_about_the_files_it_was_given(assert targeted["metrics"][0]["is_test"] is Trueasked.clear()- dashboard = await get_health()+ dashboard = await get_health(only=["test_findings"])assert asked == [None], "the dashboard split needs the repo-wide answer"assert dashboard["test_findings"], "scoping the dashboard would empty this"@@ -1240,7 +1352,7 @@ async def test_kpis_still_include_test_files(setup_mcp, health_data_with_tests):"""from repowise.server.mcp_server import get_health- result = await get_health()+ result = await get_health(only=["kpis", "worst_files"])assert result["kpis"]["file_count"] == 3assert any(m["file_path"] == "tests/test_service.py" for m in result["worst_files"])@@ -1253,8 +1365,11 @@ async def test_the_split_survives_a_dimension_filter(setup_mcp, health_data_with"""from repowise.server.mcp_server import get_health- unfiltered = await get_health()- filtered = await get_health(include=["biomarkers", "defect"])+ unfiltered = await get_health(only=["top_findings", "test_findings"])+ filtered = await get_health(+ include=["biomarkers", "defect"],+ only=["findings", "test_findings"],+ )assert all(f["dimension"] == "defect" for f in filtered["findings"])assert all(f["dimension"] == "defect" for f in filtered["test_findings"])assert (@@ -1458,7 +1573,8 @@ async def test_metric_rows_drop_the_duplicated_defect_score(setup_mcp, health_daassert row["maintainability_score"] == 6.0assert row["performance_score"] == 9.0for block in ("worst_files", "high_leverage_files"):- assert all("defect_score" not in m for m in (await get_health())[block])+ projected = await get_health(only=[block])+ assert all("defect_score" not in m for m in projected[block])@pytest.mark.asyncio@@ -1562,7 +1678,7 @@ async def test_primary_biomarker_prefers_a_discrete_cause(setup_mcp, gradient_heassert row["primary_reason"] == "run nests 4 levels deep"# The gradient is still the larger deduction and is still summed in.assert row["total_deduction"] == pytest.approx(3.9)- dash = await get_health()+ dash = await get_health(only=["worst_files"])worst = next(m for m in dash["worst_files"] if m["file_path"] == "src/wide.py")assert worst["primary_biomarker"] == "nested_complexity"@@ -1647,7 +1763,9 @@ async def test_non_code_split_is_gated_on_the_language_read(setup_mcp, health_da@pytest.mark.asyncio-async def test_response_is_trimmed_under_the_host_result_cap(setup_mcp, health_data, monkeypatch):+async def test_default_dashboard_is_compact_before_final_delivery(+ setup_mcp, health_data, monkeypatch+):"""Five ranked lists at the default limit compose past the host's cap.Past ``MAX_MCP_OUTPUT_TOKENS`` the host *rejects* the whole result with an@@ -1658,23 +1776,10 @@ async def test_response_is_trimmed_under_the_host_result_cap(setup_mcp, health_d"""from repowise.server.mcp_server import get_health- baseline = len(json.dumps(await get_health(), default=str))- monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "900") # 900 * 0.6 * 4 = 2160 charsresult = await get_health()- assert len(json.dumps(result, default=str)) <= 2160 < baseline- dropped = result["_meta"]["truncated_to_fit"]- assert dropped, "the guard must say what it cut"- assert set(dropped) <= {- "refactoring_plans",- "high_leverage_files",- "worst_files",- "test_findings",- "top_findings",- "findings",- "churn_complexity",- "modules",- }- assert "truncated_recovery" in result["_meta"]+ assert len(json.dumps(result, separators=(",", ":"), default=str)) <= 24_000+ assert "truncated_to_fit" not in result["_meta"]+ assert result["directive"]["fix_first"]@pytest.mark.asyncio@@ -1688,18 +1793,16 @@ async def test_a_response_that_fits_is_not_trimmed(setup_mcp, health_data):@pytest.mark.asyncio-async def test_trimming_never_eats_the_directive_or_the_totals(setup_mcp, health_data, monkeypatch):+async def test_tool_local_budget_does_not_preempt_final_delivery(+ setup_mcp, health_data, monkeypatch+):"""The blocks that let a caller recover must survive the cut that caused it."""from repowise.server.mcp_server import get_health- # Small enough that the guard exhausts every trimmable list and stops.monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "400")result = await get_health()- assert all(result[k] == [] for k in ("worst_files", "top_findings", "high_leverage_files"))assert result["directive"]["fix_first"]- # Totals describe what was there before the trim, so the loss stays visible.- assert result["worst_files_total"] == 2- assert result["mode"] == "dashboard"+ assert "truncated_to_fit" not in result["_meta"]@pytest.mark.asyncio@@ -1810,79 +1913,127 @@ def test_only_docstring_does_not_overclaim_the_aliases():@pytest.mark.asyncio-async def test_trimming_takes_from_the_longest_list_first(setup_mcp, health_data, monkeypatch):- """The cut has to land on whichever block is actually responsible.+async def test_module_metrics_obey_limit_and_lead_with_rollup(+ setup_mcp, health_data, monkeypatch+):+ from repowise.server.mcp_server import get_health- Trimming a fixed victim would hold the payload down just as well and be- wrong about *why* it was over: on this fixture ``top_findings`` (4 rows) is- twice ``worst_files`` (2) and four times ``high_leverage_files`` (1), so a- small overflow must come out of ``top_findings`` and leave the one-row list- whole. (Found by mutation testing — the first version of this guard passed- every test with a fixed trim order.)- """+ result = await get_health(targets=["module:auth", "module:db"], limit=1)+ assert list(result)[:3] == ["mode", "targets", "modules"]+ assert result["modules_total"] == 2+ assert result["modules_emitted"] == 2+ assert result["metrics_total"] == 2+ assert result["metrics_emitted"] == 1+ assert result["metrics_reduced_reason"] == "limit"+++async def test_module_metrics_limit_zero_returns_rollup_and_totals(+ setup_mcp, health_data, monkeypatch+):from repowise.server.mcp_server import get_health- baseline = await get_health()- size = len(json.dumps(baseline, default=str))- assert len(baseline["top_findings"]) == 4- # Budget = current size minus roughly one finding, plus the marker headroom- # the guard reserves, so exactly a row or two has to go.- per_row = len(json.dumps(baseline["top_findings"], default=str)) // 4- monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", str(int((size - per_row + 400) / 4 / 0.6)))- result = await get_health()- dropped = result["_meta"]["truncated_to_fit"]- assert set(dropped) == {"top_findings"}- assert len(result["high_leverage_files"]) == 1- assert len(result["worst_files"]) == 2+ result = await get_health(targets=["module:auth", "module:db"], limit=0)+ assert result["metrics"] == []+ assert result["metrics_total"] == 2+ assert result["metrics_emitted"] == 0+ assert len(result["modules"]) == 2+ assert result["modules_total"] == 2+ assert result["modules_emitted"] == 2+ assert "modules_reduced_reason" not in result@pytest.mark.asyncio-async def test_guard_trims_the_uncapped_targeted_lists(setup_mcp, health_data, monkeypatch):- """The three lists that can actually run away are ``limit``-free.+async def test_shared_budget_contract_owns_get_health_final_delivery(+ setup_mcp, health_data, monkeypatch+):+ """``coverage.files`` is not a top-level key; a flat scan never finds it."""+ from repowise.server.mcp_server import get_health+ from repowise.server.mcp_server._budget import budgeted_tool_names- Found in adversarial review, and it is the defect the guard was most likely- to have: the first ``_TRIMMABLE_LISTS`` held only the eight *capped*- dashboard blocks — the ones least able to overflow — while ``metrics``,- ``trends`` and ``coverage.files`` were invisible to it. Those three are- built per target with no cap (a ``module:`` target expands to every file in- the module) and targeted ``coverage.files`` carries the per-line- ``covered_lines`` arrays dashboard mode declines to read. A guard that- misses them is worse than none: it trims a small capped list to empty, still- overflows, and stamps ``truncated_to_fit`` claiming it handled it.- """+ assert "get_health" in budgeted_tool_names()+ result = await get_health(include=["coverage"], targets=["src/auth/service.py"], limit=0)+ assert result["coverage"]["files"] == []+ assert result["coverage"]["files_total"] == 0+ assert result["coverage"]["files_emitted"] == 0+ assert "files_reduced_reason" not in result["coverage"]+++async def test_large_module_metrics_obey_every_limit(+ setup_mcp, health_data, session+):+ import uuid++ from repowise.core.persistence.models import HealthFileMetricfrom repowise.server.mcp_server import get_health- targets = ["src/auth/service.py", "src/db/models.py"]- baseline = await get_health(targets=targets)- assert len(baseline["metrics"]) == 2- assert baseline["metrics_total"] == 2+ for index in range(60):+ session.add(+ HealthFileMetric(+ id=str(uuid.uuid4()),+ repository_id=health_data,+ file_path=f"src/large/file_{index:02d}.py",+ module="large",+ score=1.0 + index / 100,+ max_ccn=10 + index,+ max_nesting=2,+ nloc=100 + index,+ has_test_file=False,+ )+ )+ await session.flush()- monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "400")- result = await get_health(targets=targets)- assert result["_meta"]["truncated_to_fit"].get("metrics"), (- "metrics is uncapped by limit, so the size guard is the only thing "- "bounding it — it must be reachable"- )- assert len(result["metrics"]) < 2- # The total still describes what was there, so the trim stays visible.- assert result["metrics_total"] == 2+ for limit in (0, 1, 20, 50):+ result = await get_health(targets=["module:large"], only=["metrics"], limit=limit)+ assert result["metrics_total"] == 60+ assert result["metrics_emitted"] == limit+ assert len(result["metrics"]) == limit+ assert result["metrics_reduced_reason"] == "limit"+ recovery = result["recovery"]["metrics"]+ assert f"cursor={limit}" in recovery["call"]+ first_page_limit = min(60 - limit, 50)+ assert f"limit={first_page_limit}" in recovery["call"]+ dropped_paths = {f"src/large/file_{index:02d}.py" for index in range(limit, 60)}+ emitted_paths = {row["file_path"] for row in result["metrics"]}+ recovered_paths = set()+ next_cursor = limit+ while next_cursor < 60:+ page_limit = min(60 - next_cursor, 50)+ recovered = await get_health(+ targets=["module:large"],+ only=["metrics"],+ cursor=next_cursor,+ limit=page_limit,+ )+ page_paths = {row["file_path"] for row in recovered["metrics"]}+ assert len(page_paths) == page_limit+ recovered_paths |= page_paths+ next_cursor += page_limit+ assert recovered_paths == dropped_paths+ assert recovered_paths.isdisjoint(emitted_paths)@pytest.mark.asyncio-async def test_guard_reaches_a_list_nested_one_level_down(setup_mcp, health_data, monkeypatch):- """``coverage.files`` is not a top-level key; a flat scan never finds it."""+async def test_every_growing_collection_has_total_and_emitted_counts(+ setup_mcp, health_data+):from repowise.server.mcp_server import get_health- monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "400")- result = await get_health(include=["coverage"])- # Whatever else it cut, it must not have stopped at the top level while a- # nested list still held rows.- assert result["_meta"]["truncated_to_fit"]- from repowise.server.mcp_server.tool_health import _TRIMMABLE_LISTS, _resolve_list-- assert "coverage.files" in _TRIMMABLE_LISTS- assert "trends" in _TRIMMABLE_LISTS- assert _resolve_list({"coverage": {"files": [1, 2]}}, "coverage.files") == [1, 2]- assert _resolve_list({"coverage": {"files": []}}, "coverage.files") is None- assert _resolve_list({}, "coverage.files") is None- assert _resolve_list({"coverage": None}, "coverage.files") is None+ result = await get_health(include=["performance", "refactoring"], limit=2)++ def assert_counted(value):+ if isinstance(value, list):+ for item in value:+ assert_counted(item)+ return+ if not isinstance(value, dict):+ return+ for key, child in value.items():+ if isinstance(child, list):+ assert f"{key}_total" in value, key+ assert f"{key}_emitted" in value, key+ assert value[f"{key}_total"] >= value[f"{key}_emitted"] == len(child)+ assert_counted(child)++ assert_counted(result)diff --git a/tests/unit/server/mcp/test_mcp_exclude_filter.py b/tests/unit/server/mcp/test_mcp_exclude_filter.pyindex f7e660245..554a452e2 100644--- a/tests/unit/server/mcp/test_mcp_exclude_filter.py+++ b/tests/unit/server/mcp/test_mcp_exclude_filter.py@@ -141,7 +141,7 @@ async def test_get_health_excludes_configured_paths(setup_mcp, health_data, tmp_(rw / "config.yaml").write_text("exclude_patterns:\n - src/db/\n", encoding="utf-8")monkeypatch.setattr(mcp_mod._state, "_repo_path", str(tmp_path))- result = await get_health()+ result = await get_health(only=["worst_files"])paths = {m["file_path"] for m in result.get("worst_files", [])}assert "src/db/models.py" not in pathsassert "src/auth/service.py" in pathsdiff --git a/tests/unit/server/mcp/test_perf_rank.py b/tests/unit/server/mcp/test_perf_rank.pyindex a2da3967a..2d8185d66 100644--- a/tests/unit/server/mcp/test_perf_rank.py+++ b/tests/unit/server/mcp/test_perf_rank.py@@ -256,14 +256,21 @@ async def test_perf_rank_is_absent_from_every_other_dimension(setup_mcp, perf_fi@pytest.mark.asyncioasync def test_narrow_projection_leads_with_one_shared_causal_opportunity(- setup_mcp, perf_findings, session+ setup_mcp, perf_findings, session, monkeypatch, tmp_path):import json+ from repowise.core.distill.store import OmissionStorefrom repowise.core.persistence.models import HealthFindingfrom repowise.server.mcp_server import get_health+ from repowise.server.mcp_server._budget import collector as collector_module- for index, caller in enumerate(("src/a.py", "src/b.py"), start=10):+ store_path = tmp_path / "omissions.db"+ monkeypatch.setattr(collector_module, "default_store_path", lambda _root: store_path)++ for index, caller in enumerate(+ ("src/a.py", "src/b.py", "src/c.py", "src/d.py", "src/e.py"), start=10+ ):session.add(HealthFinding(id=str(uuid.uuid4()),@@ -298,10 +305,23 @@ async def test_narrow_projection_leads_with_one_shared_causal_opportunity(]assert len(shared) == 1assert shared[0]["intervention_symbol"] == "src/shared.py::load"- assert shared[0]["affected_call_sites_total"] == 2- assert shared[0]["observations_total"] == 2- assert {item["line_start"] for item in shared[0]["evidence"]} == {10, 11}+ assert shared[0]["affected_call_sites_total"] == 5+ assert shared[0]["observations_total"] == 5+ assert {item["line_start"] for item in shared[0]["evidence"]} == {10, 11, 12}assert {item["function_name"] for item in shared[0]["evidence"]} == {"run"}+ assert shared[0]["evidence_total"] == 5+ assert shared[0]["evidence_emitted"] == 3+ assert shared[0]["evidence_reduced_reason"] == "evidence_cap"+ refs = result["_meta"]["omitted"]["refs"]+ assert len(refs) == 1+ store = OmissionStore(store_path)+ try:+ omitted = store.get(refs[0]) or ""+ finally:+ store.close()+ assert '"line_start": 13' in omitted+ assert '"line_start": 14' in omitted+ assert '"line_start": 10' not in omittedassert result["performance_opportunities_total"] >= 1assert "top_findings" not in resultdiff --git a/tests/unit/server/mcp/test_response_budget_contracts.py b/tests/unit/server/mcp/test_response_budget_contracts.pyindex 56fbc48e5..cd987454e 100644--- a/tests/unit/server/mcp/test_response_budget_contracts.py+++ b/tests/unit/server/mcp/test_response_budget_contracts.py@@ -1,4 +1,4 @@-"""Golden contracts for the five shared-budget canonical MCP tools."""+"""Golden contracts for the shared-budget canonical MCP tools."""from __future__ import annotations@@ -20,6 +20,8 @@ from repowise.server.mcp_server._budget import (def _payload(tool: str, pad: int) -> dict[str, Any]:+ if tool == "get_health":+ pad = min(pad, 10_000)rows = [{"id": i, "evidence": f"EVIDENCE_{tool}_{i}_" + "x" * pad} for i in range(3)]meta = {"contract_version": 1, "indexed_commit": "a" * 12}if tool == "get_context":@@ -56,6 +58,16 @@ def _payload(tool: str, pad: int) -> dict[str, Any]:"retrieval": rows,"_meta": meta,}+ if tool == "get_health":+ return {+ "mode": "dashboard",+ "directive": {"fix_first": "src/large.py", "reason": "highest leverage"},+ "kpis": {"average_health": 4.2, "file_count": 3},+ "high_leverage_files": rows,+ "high_leverage_files_total": len(rows),+ "high_leverage_files_emitted": len(rows),+ "_meta": meta,+ }return {"title": "Large repository","architecture": {"layers": [{"name": "Service", "file_count": 10}]},@@ -91,6 +103,7 @@ def _enforce(tool: str, payload: dict[str, Any], include: list[str] | None = Non("get_change_risk", "classification"),("get_answer", "answer"),("get_overview", "title"),+ ("get_health", "directive"),],)@pytest.mark.parametrize(("case", "pad"), [("minimum", 0), ("typical", 600)])@@ -128,6 +141,7 @@ def test_default_payload_goldens_keep_action_fields_and_exact_accounting(("get_change_risk", "classification"),("get_answer", "answer"),("get_overview", "title"),+ ("get_health", "directive"),],)def test_adversarial_payload_goldens_fit_and_recover_in_one_lookup(@@ -153,6 +167,8 @@ def test_adversarial_payload_goldens_fit_and_recover_in_one_lookup(assert result["truncated"] is Truerefs = result["_meta"]["omitted"]["refs"]assert refs+ if tool == "get_health":+ assert len(refs) == 1if tool == "get_risk":reductions = result["_meta"].get("reductions", [])assert reductions and all(@@ -163,6 +179,10 @@ def test_adversarial_payload_goldens_fit_and_recover_in_one_lookup(assert result["prior_fixes_total"] == 3assert result["prior_fixes_emitted"] == 0assert result["prior_fixes_reduced_reason"] == "response_budget"+ elif tool == "get_health":+ assert result["high_leverage_files_total"] == 3+ assert result["high_leverage_files_emitted"] < 3+ assert result["high_leverage_files_reduced_reason"] == "response_budget"store = OmissionStore(default_store_path(repo))try:@@ -170,6 +190,50 @@ def test_adversarial_payload_goldens_fit_and_recover_in_one_lookup(finally:store.close()assert any(value is not None and f"EVIDENCE_{tool}" in value for value in recovered)+ if tool == "get_health":+ joined = recovered[0] or ""+ emitted_ids = {row["id"] for row in result["high_leverage_files"]}+ for row_id in set(range(3)) - emitted_ids:+ assert f'"id": {row_id}' in joined+ for row_id in emitted_ids:+ assert f'"id": {row_id}' not in joined+++def test_health_budget_prunes_profiles_for_removed_plans(+ setup_mcp: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ import repowise.server.mcp_server as mcp_mod++ (tmp_path / ".repowise").mkdir()+ monkeypatch.setattr(mcp_mod, "_repo_path", str(tmp_path))+ plans = [+ {"id": f"plan-{index}", "validation_profile_id": f"profile-{index}"}+ for index in range(8)+ ]+ profiles = [+ {+ "id": f"profile-{index}",+ "commands": [f"pytest tests/test_{index}.py " + "x" * 6_000],+ }+ for index in range(8)+ ]+ payload = {+ "mode": "targets",+ "targets": ["src/large.py"],+ "refactoring_plans": plans,+ "refactoring_plans_total": len(plans),+ "validation_profiles": profiles,+ "validation_profiles_total": len(profiles),+ "_meta": {"contract_version": 1},+ }++ result = _enforce("get_health", payload, ["refactoring"])+ referenced = {plan["validation_profile_id"] for plan in result["refactoring_plans"]}+ retained = {profile["id"] for profile in result["validation_profiles"]}+ assert retained == referenced+ assert result["validation_profiles_emitted"] == len(retained)+ assert result["validation_profiles_reduced_reason"] == "response_budget"+ assert result["_meta"]["response_budget"]["serialized_chars"] <= EXPANDED_RESPONSE_CHARSdef test_explicit_include_uses_the_expansion_tier(