Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(mcp): clarify health semantics and recipes (#1934)

Raghav Chamadiyae485fb6a790a
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 2014cedf7..1ecb08981 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -679,8 +679,21 @@ get_dead_code(kind="unused_export", group_by="owner")
Code-health marker scores: the same deterministic markers the
`repowise health` CLI computes, across three signals (defect risk,
maintainability, performance), exposed for agentic workflows. Zero LLM calls.
-Use it to **self-check a change before opening a PR**: the same signals a
-code-health merge-gate judges it on.
+Use it to inspect stored health analysis before a change and after committing
+health-relevant changes and running `repowise update`: neither re-calling
+`get_health` nor updating an uncommitted working tree recomputes those metrics.
+
+**Safe recipes:**
+
+```text
+get_health(only=["directive"])
+get_health(targets=["path"], include=["refactoring"])
+get_health(targets=["module:path"], only=["modules","metrics"])
+get_health(include=["trend"], only=["trend"])
+get_health(include=["accuracy"], only=["accuracy"])
+get_health(include=["coverage"], only=["coverage"])
+get_health(include=["performance","refactoring"], only=["performance_opportunities","refactoring_plans"])
+```
**Parameters:**
@@ -702,7 +715,8 @@ per-dimension scores, and the score breakdown. Each finding carries a `dimension
(`defect` / `maintainability` / `performance`).
**Lead with `directive`.** Dashboard mode opens with the single file to fix
-first, its dominant finding, `recovers_points` / `share_of_repo_gap_pct` (what
+first, its dominant finding, `recovers_weighted_deficit_points` /
+`share_of_repo_gap_pct` (what
fixing it buys the headline; the share is bounded by 100% and sums to 100%
across `high_leverage_files` — the gross deficit of below-target files is the
denominator, not the net gap, so a single file cannot read as closing more than
@@ -710,10 +724,14 @@ the whole remaining gap), and `then`, the next two by leverage. Every other
block ranks and describes; this one recommends. Same role as `get_risk`'s
`directive`. Rank by `weighted_deficit`, not `score` — the score floors at 1.0.
+`recovers_points` remains an exact deprecated alias during the compatibility
+window; `recovers_points_compatibility` names its replacement.
+
**Nothing is dropped silently.** Any `targets` entry that matched nothing is
named in `unresolved` with a reason (`not_indexed` → run `repowise update`,
`no_such_path`, `excluded`, `no_such_module`; a missed module name also returns
-`known_modules`), so an empty `findings` list means healthy and nothing else. A
+`known_modules`). Missing stored analysis is explicitly unavailable rather than
+fabricated as a healthy score. A
target set that resolves to nothing still answers in targeted mode rather than
falling back to the repo dashboard. Every capped list carries a `*_total`
sibling — including under `only`, which retains it automatically. `unresolved`
@@ -721,7 +739,10 @@ and `known_modules` survive any `only` projection too, for the same reason
`mode` does: a caller who has to ask for the error report in order to see it
does not have an error report.
-`_meta.health_analyzed_at` dates the health pass, which is separate from
+`_meta.health_analysis` explicitly labels the result as stored analysis,
+states that the call did not recompute it, distinguishes index/live-Git facts
+from source-byte verification, and gives the exact commit-then-update refresh
+precondition. `_meta.health_analyzed_at` dates the health pass, which is separate from
indexing and can lag it, and `_meta.health_analyzed_commit` says which commit
those scores were computed against. The incremental update path rescores only
the files that changed, so the metrics table can hold rows from several passes
@@ -767,7 +788,7 @@ make that actionable rather than a mystery:
(dashboard mode) is the top-N ranked by it, distinct from `worst_files`, which
sorts by raw score and ranks a 30-line file at 1.0 equal to a 1,200-line file at
1.0 that moves the average ~40x more.
-- `weighted_deficit`, `directive.recovers_points` and
+- `weighted_deficit`, `directive.recovers_weighted_deficit_points` and
`gap_analysis.weighted_gap_points` share one unit — *score-points x NLOC* —
which compares against itself and nothing else. Every `high_leverage_files`
row and the `directive` also carry `share_of_repo_gap_pct`, the same quantity
@@ -775,6 +796,10 @@ make that actionable rather than a mystery:
(`gap_analysis.weighted_gross_gap_points`), so the shares are bounded by 100%
and sum to 100% by construction; that plus
`gap_analysis.files_to_reach_target` is what answers "is this worth doing".
+- `_meta.health_semantics` gives the numerator, gross-deficit denominator,
+ nonnegative unbounded scale and direction. These are deterministic heuristic
+ triage points, not probabilities, normalized score points, percentages or
+ guaranteed improvement.
- `kpis.non_code_files` and `kpis.average_health_code_only` say how much of the
headline is markdown/JSON/YAML. No biomarker walks those files, so they score
a mechanical 10.0 meaning "nothing looked at this" — on this repo, 233 of
@@ -819,6 +844,14 @@ The opt-in enrichments:
plans on the files that move the headline surface first; `refactoring_plans_total`
reports the full count behind the cap. Each plan echoes its
`file_weighted_deficit`. Full shapes in [`docs/layers/REFACTORING.md`](../layers/REFACTORING.md).
+- A requested empty plan list includes `refactoring_plans_status.reason`:
+ `no_applicable_findings`, `plan_analysis_indeterminate`,
+ `no_eligible_targets`, or `analysis_unavailable`. The structured-analysis
+ fallback includes a concrete `get_symbol` or `get_context` source call and
+ explicitly names the two facts the stored data cannot distinguish: no
+ supported transformation vs a disabled or failed detector.
+ Projection exclusion emits no plan warning; a zero-row cursor window is
+ reported separately as `request_window_empty`.
- **dimension filter** narrows the returned findings to one pillar, e.g.
`include=["biomarkers", "performance"]`.
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/change_entropy.py b/packages/core/src/repowise/core/analysis/health/biomarkers/change_entropy.py
index 9e2996e01..10f9951fb 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/change_entropy.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/change_entropy.py
@@ -25,6 +25,7 @@ from __future__ import annotations
from typing import Any
from ..models import Severity
+from ..semantics import format_top_percentile
from .base import BiomarkerResult, FileContext
_MIN_PERCENTILE = 0.80
@@ -91,7 +92,7 @@ class ChangeEntropyDetector:
},
reason=(
f"changes are scattered across noisy commits "
- f"(top {(1 - percentile) * 100:.0f}% change entropy); "
+ f"({format_top_percentile(percentile, 'files eligible for change-entropy ranking')}); "
"a strong history-based fault predictor"
),
)
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/churn_risk.py b/packages/core/src/repowise/core/analysis/health/biomarkers/churn_risk.py
index 114f85afa..64c08dd82 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/churn_risk.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/churn_risk.py
@@ -25,6 +25,7 @@ absent/zero and the detector emits nothing.
from __future__ import annotations
from ..models import Severity
+from ..semantics import format_top_percentile
from .base import BiomarkerResult, FileContext
_MIN_COMMITS_90D = 5
@@ -105,7 +106,7 @@ class ChurnRiskDetector:
reason=(
f"90-day churn rewrote {churn_text} "
f"({added + deleted} lines over {ctx.nloc} NLOC, "
- f"top {(1 - churn_pct):.0%} of repo churn)"
+ f"{format_top_percentile(churn_pct, 'repository files eligible for churn ranking')})"
),
)
]
diff --git a/packages/core/src/repowise/core/analysis/health/semantics.py b/packages/core/src/repowise/core/analysis/health/semantics.py
new file mode 100644
index 000000000..451324216
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/semantics.py
@@ -0,0 +1,66 @@
+"""Public interpretation helpers for health output."""
+
+from __future__ import annotations
+
+from typing import Any
+
+
+def weighted_deficit_contract() -> dict[str, Any]:
+ """Describe the uncalibrated weighted-deficit unit without changing it."""
+ return {
+ "unit": "health_score_points_x_nloc",
+ "numerator": "max(8.0 - file_score, 0.0) * max(nloc, 1)",
+ "denominator": "gap_analysis.weighted_gross_gap_points",
+ "scale": {"minimum": 0, "maximum": None, "normalized": False},
+ "direction": (
+ "higher means the file contributes more to the eligible population's "
+ "gross deficit from the Healthy threshold"
+ ),
+ "interpretation": (
+ "a deterministic triage weight, not a probability, percentage, "
+ "normalized score, or guaranteed improvement"
+ ),
+ }
+
+
+def percentile_contract() -> dict[str, Any]:
+ """Describe the common stored and public health-percentile scales."""
+ return {
+ "stored_scale": "ratio_0_to_1",
+ "public_raw_scale": "percentile_rank_0_to_100",
+ "direction": "higher means ranked above more files in the eligible stored population",
+ "population": (
+ "the eligible repository files used by the stored analysis for that signal"
+ ),
+ "freshness": "stored analysis; not recomputed by get_health",
+ }
+
+
+def format_top_percentile(percentile: float, population: str) -> str:
+ """Render a stored 0-1 rank without ever claiming ``top 0%``."""
+ bounded = min(max(float(percentile), 0.0), 1.0)
+ upper_tail = (1.0 - bounded) * 100.0
+ if upper_tail < 0.1:
+ rank = "top <0.1%"
+ elif upper_tail < 10.0:
+ rendered = f"{upper_tail:.1f}".rstrip("0").rstrip(".")
+ rank = f"top {rendered}%"
+ else:
+ rank = f"top {upper_tail:.0f}%"
+ return f"{rank} among {population}"
+
+
+def health_semantics_contract() -> dict[str, Any]:
+ """Compact shared legend retained by every health recipe."""
+ return {
+ "weighted_deficit_points": weighted_deficit_contract(),
+ "percentiles": percentile_contract(),
+ }
+
+
+__all__ = [
+ "format_top_percentile",
+ "health_semantics_contract",
+ "percentile_contract",
+ "weighted_deficit_contract",
+]
diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
index 9103aa356..ab82505f0 100644
--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
@@ -306,6 +306,23 @@ def _emergency_fit(
return
+def _reconcile_health_plan_status(result: dict[str, Any]) -> None:
+ """Keep plan availability honest after the final budget mutates collections."""
+ status = result.get("refactoring_plans_status")
+ plans = result.get("refactoring_plans")
+ if not isinstance(status, dict) or status.get("state") != "available":
+ return
+ if plans is not None and (not isinstance(plans, list) or plans):
+ return
+ if not result.get("refactoring_plans_total", 0):
+ return
+ status.update(
+ state="available_not_emitted",
+ reason="response_budget",
+ message="Plans exist but were removed by the final response budget.",
+ )
+
+
def enforce_response_budget(
tool: str,
result: Any,
@@ -380,6 +397,9 @@ def enforce_response_budget(
_emergency_fit(result, contract, emergency, working_limit)
emergency.attach(result)
+ if tool == "get_health":
+ _reconcile_health_plan_status(result)
+
if result.get("truncated"):
result.setdefault("_meta", {}).setdefault("state", {})["truncated"] = True
_stamp_accounting(result, limit=limit, tier=tier)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.py
index 5236e4229..15381ef96 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py
@@ -26,6 +26,7 @@ from repowise.core.analysis.health.refactoring.recommendations import (
hydrate_recommendations,
)
from repowise.core.analysis.health.scoring import hotspot_health
+from repowise.core.analysis.health.semantics import health_semantics_contract
from repowise.core.analysis.health.signals import file_signals
from repowise.core.analysis.health.suggestions import suggestion_for
from repowise.core.analysis.health.trends import diff_snapshots, file_trend, recent_kpis
@@ -49,6 +50,7 @@ from repowise.core.persistence.models import (
HealthFinding,
RefactoringSuggestion,
)
+from repowise.core.registry import ToolRecipe
from repowise.core.registry import mcp_tool_registry as mcp
from repowise.server.mcp_server._budget import OmissionCollector
from repowise.server.mcp_server._helpers import (
@@ -664,7 +666,13 @@ def _directive(
# is the *gross* deficit of all below-target files (not the net gap,
# which healthy files cushion): per-file shares are then bounded by
# 100% and sum to 100% by construction (issue #1437).
+ "recovers_weighted_deficit_points": recovers,
"recovers_points": recovers,
+ "recovers_points_compatibility": {
+ "deprecated": True,
+ "replacement": "recovers_weighted_deficit_points",
+ "equivalent_value": True,
+ },
"share_of_repo_gap_pct": (round(100.0 * recovers / gap_points, 1) if gap_points else None),
"then": [m.file_path for m in by_leverage[1:3]],
# Projected, not bare. ``include`` adds a block without subtracting the
@@ -713,6 +721,127 @@ def _directive(
return out
+def _finding_next_action(finding: Any, repo: str | None) -> dict[str, Any]:
+ """Return one concrete source call for a finding without a stored plan."""
+ path = str(getattr(finding, "file_path", ""))
+ line_start = getattr(finding, "line_start", None)
+ line_end = getattr(finding, "line_end", None)
+ if path and line_start and line_end:
+ arguments: dict[str, Any] = {"symbol_id": f"{path}:{line_start}-{line_end}"}
+ if repo:
+ arguments["repo"] = repo
+ return {"tool": "get_symbol", "arguments": arguments}
+ arguments = {"targets": [path], "include": ["skeleton"]}
+ if repo:
+ arguments["repo"] = repo
+ return {"tool": "get_context", "arguments": arguments}
+
+
+def _refactoring_plans_status(
+ *,
+ available_plans_total: int,
+ plans_emitted: int,
+ scoped: bool,
+ has_eligible_metrics: bool,
+ finding: Any | None,
+ repo: str | None,
+) -> dict[str, Any]:
+ """Explain an explicitly requested plan projection deterministically."""
+ if plans_emitted:
+ return {"state": "available", "reason": None}
+ if available_plans_total:
+ return {
+ "state": "available_not_emitted",
+ "reason": "request_window_empty",
+ "message": "Plans exist but the requested limit/cursor window emitted none.",
+ }
+ if scoped and not has_eligible_metrics:
+ return {
+ "state": "unavailable",
+ "reason": "no_eligible_targets",
+ "message": "No requested target resolved to an eligible stored health row.",
+ }
+ if not has_eligible_metrics:
+ return {
+ "state": "unavailable",
+ "reason": "analysis_unavailable",
+ "message": "No stored health analysis is available for this population.",
+ "next_action": {
+ "command": "repowise update",
+ "reason": "run health analysis before interpreting scores or plans",
+ },
+ }
+ if finding is None:
+ return {
+ "state": "empty",
+ "reason": "no_applicable_findings",
+ "message": "The eligible population has no applicable open findings.",
+ }
+ return {
+ "state": "indeterminate",
+ "reason": "plan_analysis_indeterminate",
+ "message": "Findings exist, but stored plan evidence is absent.",
+ "possible_causes": [
+ "no_supported_structured_transformation",
+ "refactoring_detector_disabled_or_failed",
+ ],
+ "next_action": _finding_next_action(finding, repo),
+ }
+
+
+def _attach_health_analysis_meta(
+ meta: dict[str, Any], metrics: list[HealthFileMetric]
+) -> None:
+ """Keep stored analysis distinct from index/live Git verification."""
+ meta["health_semantics"] = health_semantics_contract()
+ analyzed = [m for m in metrics if getattr(m, "updated_at", None)]
+ commits = {c for m in analyzed if (c := getattr(m, "analyzed_commit", None))}
+ latest = max(analyzed, key=lambda m: m.updated_at) if analyzed else None
+ latest_commit = getattr(latest, "analyzed_commit", None) if latest else None
+ status = "available" if latest_commit else "degraded" if metrics else "unavailable"
+ analysis: dict[str, Any] = {
+ "status": status,
+ "source": "stored_health_analysis",
+ "recomputed_this_call": False,
+ "live_verification": {
+ "basis": (
+ "index_commit_and_live_git_head"
+ if meta.get("indexed_commit") and meta.get("live_head")
+ else "unavailable"
+ ),
+ "source_bytes_verified": False,
+ },
+ "refresh": {
+ "command": "repowise update",
+ "precondition": "commit health-relevant working-tree changes first",
+ "required_before_comparison": True,
+ },
+ }
+ if not metrics:
+ analysis["reason"] = "no_stored_health_metrics"
+ if analyzed:
+ assert latest is not None
+ analyzed_at = latest.updated_at.isoformat()
+ analysis["analyzed_at"] = analyzed_at
+ meta["health_analyzed_at"] = analyzed_at
+ if latest_commit:
+ analyzed_commit = latest_commit[:12]
+ analysis["analyzed_commit"] = analyzed_commit
+ meta["health_analyzed_commit"] = analyzed_commit
+ if len(commits) > 1:
+ analysis["analyzed_commits_distinct"] = len(commits)
+ meta["health_analyzed_commits_distinct"] = len(commits)
+ if not latest_commit:
+ analysis["reason"] = "analysis_commit_not_recorded"
+ analysis["analyzed_commit"] = None
+ else:
+ analysis["recorded_at"] = None
+ analysis["recorded_commit"] = None
+ if metrics:
+ analysis["reason"] = "analysis_timestamp_not_recorded"
+ meta["health_analysis"] = analysis
+
+
def _dimension_average(metrics: list[HealthFileMetric], attr: str) -> float | None:
"""NLOC-weighted headline over a per-dimension score attribute.
@@ -851,7 +980,9 @@ def _compute_kpis(
if not metrics:
return {
"file_count": 0,
- "average_health": 10.0,
+ "average_health": None,
+ "band": None,
+ "analysis_status": "unavailable",
"hotspot_health": None,
"worst_performer_path": None,
"worst_performer_score": None,
@@ -910,7 +1041,47 @@ def _compute_kpis(
}
[email protected](surface_order=90)
+ surface_order=90,
+ recipes=(
+ ToolRecipe(
+ "health_directive",
+ 'get_health(only=["directive"])',
+ ("get_health",),
+ ),
+ ToolRecipe(
+ "health_file_self_check",
+ 'get_health(targets=["path"], include=["refactoring"])',
+ ("get_health",),
+ ),
+ ToolRecipe(
+ "health_module_triage",
+ 'get_health(targets=["module:path"], only=["modules","metrics"])',
+ ("get_health",),
+ ),
+ ToolRecipe(
+ "health_trend",
+ 'get_health(include=["trend"], only=["trend"])',
+ ("get_health",),
+ ),
+ ToolRecipe(
+ "health_accuracy",
+ 'get_health(include=["accuracy"], only=["accuracy"])',
+ ("get_health",),
+ ),
+ ToolRecipe(
+ "health_coverage",
+ 'get_health(include=["coverage"], only=["coverage"])',
+ ("get_health",),
+ ),
+ ToolRecipe(
+ "health_performance_refactoring",
+ 'get_health(include=["performance","refactoring"], '
+ 'only=["performance_opportunities","refactoring_plans"])',
+ ("get_health",),
+ ),
+ ),
+)
async def get_health(
targets: list[str] | None = None,
include: list[str] | None = None,
@@ -922,10 +1093,11 @@ async def get_health(
finding_id: str | None = None,
plan_id: str | None = None,
) -> dict:
- """Code-health scores and findings — self-check a file before/after editing.
+ """Code-health scores and findings from stored analysis.
- No ``targets`` returns a directive-led dashboard; targets return ranked
- per-file scores and findings using ``weighted_deficit``.
+ No ``targets`` returns a dashboard; targets return ranked files and findings.
+ This verifies Git/index facts but never recomputes health. For comparisons,
+ commit health changes then run ``repowise update``; it ignores uncommitted edits.
Args:
targets: file paths or ``module:<name>``. Empty → dashboard. Unmatched
@@ -1065,6 +1237,8 @@ async def get_health(
next_limit,
len(rows) - tail_start,
)
+ elif rows and start >= len(rows):
+ page_recoveries[label] = (0, min(len(rows), max(row_cap, 1), 50), len(rows))
else:
semantic_omissions[label] = rows[row_cap:]
return kept
@@ -1099,7 +1273,7 @@ async def get_health(
),
None,
)
- return {
+ result = {
"mode": "finding",
"finding_id": finding_id,
"finding": (
@@ -1111,6 +1285,22 @@ async def get_health(
targets=[match.file_path] if match else None,
),
}
+ metric_rows = (
+ list(
+ (
+ await session.execute(
+ select(HealthFileMetric).where(
+ HealthFileMetric.repository_id == repository.id,
+ HealthFileMetric.file_path == match.file_path,
+ )
+ )
+ ).scalars()
+ )
+ if match
+ else []
+ )
+ _attach_health_analysis_meta(result["_meta"], metric_rows)
+ return result
if plan_id:
plan_rows = await get_refactoring_suggestions(session, repository.id)
@@ -1126,7 +1316,7 @@ async def get_health(
),
None,
)
- return {
+ result = {
"mode": "refactoring_plan",
"plan_id": plan_id,
"plan": (
@@ -1140,6 +1330,22 @@ async def get_health(
targets=[match.suggestion.file_path] if match else None,
),
}
+ metric_rows = (
+ list(
+ (
+ await session.execute(
+ select(HealthFileMetric).where(
+ HealthFileMetric.repository_id == repository.id,
+ HealthFileMetric.file_path == match.suggestion.file_path,
+ )
+ )
+ ).scalars()
+ )
+ if match
+ else []
+ )
+ _attach_health_analysis_meta(result["_meta"], metric_rows)
+ return result
all_metrics_q = select(HealthFileMetric).where(
HealthFileMetric.repository_id == repository.id
@@ -1328,6 +1534,7 @@ async def get_health(
test_finding_rows = [by_id[i] for i in test_head_ids if i in by_id]
test_findings_total = len(test_emitted)
+ action_finding_rows = emitted
# 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
@@ -1850,6 +2057,16 @@ async def get_health(
reason="profile_cap",
)
result["refactoring_plans_total"] = len(refactoring_rows)
+ if wants("refactoring_plans"):
+ finding_for_action = next(iter(action_finding_rows), None)
+ result["refactoring_plans_status"] = _refactoring_plans_status(
+ available_plans_total=len(refactoring_recommendations),
+ plans_emitted=len(plan_payload),
+ scoped=scoped,
+ has_eligible_metrics=bool(metric_rows if scoped else all_metrics),
+ finding=finding_for_action,
+ repo=repo,
+ )
# The deterministic prose suggestion is the fallback for biomarkers
# that have no structured detector yet. It is emitted once per
# biomarker type as ``suggestion_legend`` (built below, after the
@@ -2125,6 +2342,7 @@ async def get_health(
)
if "refactoring_plans" in only_set:
keep |= {
+ "refactoring_plans_status",
"validation_profiles",
"validation_profiles_total",
"validation_profiles_emitted",
@@ -2165,25 +2383,8 @@ async def get_health(
# Targeted mode scopes the stale signal to the asked-about files; the
# dashboard (no targets) keeps the repo-level warning.
result["_meta"] = _build_meta(repository=repository, targets=targets if targets else None)
- # 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_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()
- # The commit the health rows were scored against. Distinct from
- # ``indexed_commit``: the incremental path upserts only the files that
- # changed (``upsert_health_metrics``), so the table can legitimately hold
- # rows from several passes, and reporting one SHA for all of them would
- # be a claim this read cannot support. Report the newest pass's commit,
- # and say how many others are still represented.
- commits = {c for m in analyzed if (c := getattr(m, "analyzed_commit", None))}
- if latest_commit := getattr(latest, "analyzed_commit", None):
- result["_meta"]["health_analyzed_commit"] = latest_commit[:12]
- if len(commits) > 1:
- result["_meta"]["health_analyzed_commits_distinct"] = len(commits)
+ _attach_health_analysis_meta(result["_meta"], analyzed_source)
# 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():
diff --git a/packages/ui/src/health/biomarker-details.tsx b/packages/ui/src/health/biomarker-details.tsx
index eeb8ea1b0..82b879d05 100644
--- a/packages/ui/src/health/biomarker-details.tsx
+++ b/packages/ui/src/health/biomarker-details.tsx
@@ -3,6 +3,7 @@
import { ArrowLeftRight } from "lucide-react";
import { PERF_BOUNDARY_LABEL } from "@repowise-dev/types/health";
import type { C4IoKind } from "@repowise-dev/types/external-systems";
+import { formatTopPercentile } from "../lib/format";
export type BiomarkerDetailsRecord = Record<string, unknown>;
@@ -451,7 +452,7 @@ export function BiomarkerDetails({
case "change_entropy": {
const p = num(details.change_entropy_pct);
line = joinStats(
- p != null ? `top ${Math.max(0, Math.round((1 - p) * 100))}% entropy` : null,
+ p != null ? `${formatTopPercentile(p)} entropy` : null,
num(details.commit_count_90d) != null
? `${num(details.commit_count_90d)} commits/90d`
: null,
diff --git a/packages/ui/src/lib/format.test.ts b/packages/ui/src/lib/format.test.ts
new file mode 100644
index 000000000..83ea7462a
--- /dev/null
+++ b/packages/ui/src/lib/format.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+
+import { formatTopPercentile } from "./format";
+
+describe("formatTopPercentile", () => {
+ it.each([
+ [100, "top <0.1%"],
+ [99.9, "top 0.1%"],
+ [98.9, "top 1.1%"],
+ [90, "top 10%"],
+ [0, "top 100%"],
+ ])("renders %s honestly", (percentile, expected) => {
+ expect(formatTopPercentile(percentile)).toBe(expected);
+ expect(expected).not.toBe("top 0%");
+ });
+
+ it("bounds values outside the public 0-100 scale", () => {
+ expect(formatTopPercentile(101)).toBe("top <0.1%");
+ expect(formatTopPercentile(-1)).toBe("top 100%");
+ });
+});
diff --git a/packages/ui/src/lib/format.ts b/packages/ui/src/lib/format.ts
index 8648747ce..99e9ebcb9 100644
--- a/packages/ui/src/lib/format.ts
+++ b/packages/ui/src/lib/format.ts
@@ -187,6 +187,15 @@ export function formatPercent(ratio: number, decimals = 0): string {
return `${pct.toFixed(decimals)}%`;
}
+/** Render a surfaced 0-100 percentile as an honest upper-tail rank. */
+export function formatTopPercentile(percentile: number): string {
+ const bounded = Math.min(Math.max(percentile, 0), 100);
+ const upperTail = Math.round((100 - bounded) * 1e10) / 1e10;
+ if (upperTail < 0.1) return "top <0.1%";
+ if (upperTail < 10) return `top ${upperTail.toFixed(1).replace(/\.0$/, "")}%`;
+ return `top ${Math.round(upperTail)}%`;
+}
+
/** Format byte counts: 1536 → "1.5 KB", 1048576 → "1.0 MB" */
export function formatBytes(bytes: number): string {
if (!Number.isFinite(bytes) || bytes < 0) return "—";
diff --git a/packages/ui/src/symbols/symbol-detail-body.tsx b/packages/ui/src/symbols/symbol-detail-body.tsx
index 1bb138faf..c2318c291 100644
--- a/packages/ui/src/symbols/symbol-detail-body.tsx
+++ b/packages/ui/src/symbols/symbol-detail-body.tsx
@@ -15,7 +15,7 @@ import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { StatGrid, StatTile } from "../shared/stat-grid";
import { scoreBadgeClass } from "../health/tokens";
-import { formatRelativeTimeOrNull, truncatePath } from "../lib/format";
+import { formatRelativeTimeOrNull, formatTopPercentile, truncatePath } from "../lib/format";
import { cn } from "../lib/cn";
import { SymbolCallGraph } from "./symbol-call-graph";
@@ -280,7 +280,7 @@ export function SymbolDetailBody({
{git.contributor_count != null && <span>{git.contributor_count} contributors</span>}
{git.commit_count_90d != null && <span>{git.commit_count_90d} commits / 90d</span>}
{git.churn_percentile != null && (
- <span>churn top {100 - Math.round(git.churn_percentile)}%</span>
+ <span>churn {formatTopPercentile(git.churn_percentile)}</span>
)}
{git.is_hotspot && (
<span className="inline-flex items-center gap-0.5 rounded bg-[var(--color-error)]/15 px-1.5 py-0.5 text-[var(--color-error)]">
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index 2c32749ce..43f046e32 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -81,6 +81,23 @@ async def test_dashboard_zero_limit_has_exact_ranked_page_recovery(setup_mcp, he
assert recovered["high_leverage_files"][0]["file_path"] == "src/auth/service.py"
+async def test_cursor_beyond_end_offers_one_call_reset(setup_mcp, health_data):
+ from repowise.server.mcp_server import get_health
+
+ result = await get_health(
+ targets=["module:auth"], only=["metrics"], limit=1, cursor=99
+ )
+
+ assert result["metrics"] == []
+ assert result["metrics_total"] == 1
+ recovery = result["recovery"]["metrics"]
+ assert recovery["remaining"] == 1
+ assert "only=['metrics']" in recovery["call"]
+ assert "cursor=0" in recovery["call"]
+ assert "limit=1" in recovery["call"]
+
+
@pytest.mark.asyncio
async def test_get_health_dashboard_surfaces_maintainability(setup_mcp, health_data):
"""The maintainability pillar is surfaced as a co-equal second signal."""
@@ -198,6 +215,44 @@ async def _seed_plans(session, rid, plans):
await session.commit()
+async def test_entity_recovery_retains_health_semantics_and_freshness(
+ setup_mcp, health_data, session
+):
+ from repowise.server.mcp_server import get_health
+
+ finding = (await get_health(only=["top_findings"], limit=1))["top_findings"][0]
+ finding_detail = await get_health(finding_id=finding["id"])
+ assert finding_detail["finding"] == finding
+ assert finding_detail["_meta"]["health_semantics"]
+ assert finding_detail["_meta"]["health_analysis"]["recomputed_this_call"] is False
+
+ await _seed_plans(
+ session,
+ health_data,
+ [
+ {
+ "file_path": "src/auth/service.py",
+ "impact_delta": 1.2,
+ "source_biomarker": "complex_method",
+ }
+ ],
+ )
+ plan = (
+ await get_health(
+ targets=["src/auth/service.py"],
+ include=["refactoring"],
+ only=["refactoring_plans"],
+ limit=1,
+ )
+ )["refactoring_plans"][0]
+ plan_detail = await get_health(plan_id=plan["id"])
+ assert plan_detail["plan"]["id"] == plan["id"]
+ assert plan_detail["plan"]["file_path"] == plan["file_path"]
+ assert plan_detail["_meta"]["health_semantics"]
+ assert plan_detail["_meta"]["health_analysis"]["recomputed_this_call"] is False
+
+
def test_validation_profiles_deduplicate_without_dropping_commands_or_target_tests():
from repowise.server.mcp_server.tool_health import _validation_profile
@@ -519,6 +574,12 @@ async def test_get_health_dashboard_leads_with_a_directive(setup_mcp, health_dat
assert d["fix_first"] == "src/auth/service.py"
assert d["reason"] == "authenticate has cyclomatic complexity 15"
assert d["recovers_points"] == 700 # (8.0 - 4.5) * 200
+ assert d["recovers_weighted_deficit_points"] == d["recovers_points"]
+ assert d["recovers_points_compatibility"] == {
+ "deprecated": True,
+ "replacement": "recovers_weighted_deficit_points",
+ "equivalent_value": True,
+ }
# The only below-target file holds the whole gross deficit (700/700), so
# the share is 100% by construction — the net gap (675) is not the
# denominator, since healthy files would cushion it (issue #1437).
@@ -1095,6 +1156,7 @@ async def test_include_names_work_as_only_aliases(setup_mcp, health_data, alias,
}
if resolved == "refactoring_plans":
allowed |= {
+ "refactoring_plans_status",
"validation_profiles",
"validation_profiles_total",
"validation_profiles_emitted",
@@ -1930,6 +1992,106 @@ async def test_meta_omits_the_commit_when_no_row_records_one(setup_mcp, health_d
meta = (await get_health())["_meta"]
assert "health_analyzed_commit" not in meta
assert isinstance(meta["health_analyzed_at"], str)
+ assert meta["health_analysis"]["source"] == "stored_health_analysis"
+ assert meta["health_analysis"]["recomputed_this_call"] is False
+ assert meta["health_analysis"]["live_verification"] == {
+ "basis": "unavailable",
+ "source_bytes_verified": False,
+ }
+ analysis = meta["health_analysis"]
+ assert analysis["status"] == "degraded"
+ assert analysis["reason"] == "analysis_commit_not_recorded"
+ assert analysis["refresh"] == {
+ "command": "repowise update",
+ "precondition": "commit health-relevant working-tree changes first",
+ "required_before_comparison": True,
+ }
+
+
+async def test_health_semantics_survive_narrow_projection(setup_mcp, health_data):
+ from repowise.server.mcp_server import get_health
+
+ broad = await get_health()
+ narrow = await get_health(only=["directive"])
+ assert narrow["directive"] == broad["directive"]
+ assert narrow["_meta"]["health_semantics"] == broad["_meta"]["health_semantics"]
+ contract = narrow["_meta"]["health_semantics"]["weighted_deficit_points"]
+ assert contract["unit"] == "health_score_points_x_nloc"
+ assert contract["denominator"] == "gap_analysis.weighted_gross_gap_points"
+ assert contract["scale"] == {"minimum": 0, "maximum": None, "normalized": False}
+ assert "not a probability" in contract["interpretation"]
+
+
+async def test_requested_empty_plans_explain_real_pipeline_state(setup_mcp, health_data):
+ from repowise.server.mcp_server import get_health
+
+ healthy = await get_health(
+ targets=["src/db/models.py"],
+ include=["refactoring"],
+ only=["metrics", "findings", "refactoring_plans"],
+ )
+ assert healthy["findings_total"] == 0
+ assert healthy["refactoring_plans"] == []
+ assert healthy["refactoring_plans_status"]["reason"] == "no_applicable_findings"
+
+ unsupported = await get_health(
+ targets=["src/auth/service.py"],
+ include=["refactoring"],
+ only=["findings", "refactoring_plans"],
+ )
+ assert unsupported["findings_total"] > 0
+ assert unsupported["refactoring_plans"] == []
+ status = unsupported["refactoring_plans_status"]
+ assert status["state"] == "indeterminate"
+ assert status["reason"] == "plan_analysis_indeterminate"
+ assert status["possible_causes"] == [
+ "no_supported_structured_transformation",
+ "refactoring_detector_disabled_or_failed",
+ ]
+ assert status["next_action"] == {
+ "tool": "get_symbol",
+ "arguments": {"symbol_id": "src/auth/service.py:10-80"},
+ }
+
+
+async def test_plan_status_is_omitted_when_projection_did_not_request_plans(
+ setup_mcp, health_data
+):
+ from repowise.server.mcp_server import get_health
+
+ result = await get_health(include=["refactoring"], only=["suggestion_legend"])
+ assert "refactoring_plans" not in result
+ assert "refactoring_plans_status" not in result
+
+
+async def test_unresolved_and_missing_analysis_never_read_as_healthy(
+ setup_mcp, populated_db
+):
+ from repowise.server.mcp_server import get_health
+
+ unresolved = await get_health(
+ targets=["does/not/exist.py"],
+ include=["refactoring"],
+ only=["metrics", "refactoring_plans"],
+ )
+ assert unresolved["unresolved"] == [
+ {"target": "does/not/exist.py", "reason": "no_such_path"}
+ ]
+ assert unresolved["refactoring_plans_status"]["reason"] == "no_eligible_targets"
+
+ missing = await get_health(
+ include=["refactoring"],
+ only=["directive", "kpis", "refactoring_plans"],
+ )
+ assert missing["directive"] is None
+ assert missing["kpis"]["average_health"] is None
+ assert missing["kpis"]["analysis_status"] == "unavailable"
+ assert missing["refactoring_plans_status"]["reason"] == "analysis_unavailable"
+ assert missing["_meta"]["health_analysis"]["status"] == "unavailable"
def test_only_docstring_does_not_overclaim_the_aliases():
diff --git a/tests/unit/server/mcp/test_health_semantics_matrix.py b/tests/unit/server/mcp/test_health_semantics_matrix.py
new file mode 100644
index 000000000..948e8c7bc
--- /dev/null
+++ b/tests/unit/server/mcp/test_health_semantics_matrix.py
@@ -0,0 +1,570 @@
+"""Sealed semantic oracles for the public ``get_health`` recipes.
+
+The table is intentionally data-only: implementation tests consume these exact
+calls and expectations without changing the oracle when a behavior fails.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+from types import MappingProxyType
+from typing import Any, Literal
+
+import pytest
+
+PlanReason = Literal[
+ "no_applicable_findings",
+ "plan_analysis_indeterminate",
+ "no_eligible_targets",
+ "analysis_unavailable",
+]
+
+
+@dataclass(frozen=True)
+class HealthSemanticsCase:
+ """One independently measured health call and its semantic comparison."""
+
+ name: str
+ call: str
+ kwargs: MappingProxyType[str, Any]
+ comparison: str
+ comparison_kwargs: MappingProxyType[str, Any]
+ plans_requested: bool
+ expected_plan_count: int | None
+ expected_empty_reason: PlanReason | None
+ next_action: str | None
+ recovery: Literal["none", "cursor", "omission_ref"]
+ invariant_paths: tuple[str, ...]
+
+
+def _frozen(**kwargs: Any) -> MappingProxyType[str, Any]:
+ return MappingProxyType(kwargs)
+
+
+SEALED_HEALTH_SEMANTICS: tuple[HealthSemanticsCase, ...] = (
+ HealthSemanticsCase(
+ name="repository directive",
+ call='get_health(only=["directive"], limit=0)',
+ kwargs=_frozen(only=("directive",), limit=0),
+ comparison="default dashboard and limit=50",
+ comparison_kwargs=_frozen(limit=50),
+ plans_requested=False,
+ expected_plan_count=None,
+ expected_empty_reason=None,
+ next_action=None,
+ recovery="none",
+ invariant_paths=("directive", "_meta.health_analysis", "_meta.health_semantics"),
+ ),
+ HealthSemanticsCase(
+ name="healthy file self-check",
+ call=(
+ 'get_health(targets=["src/db/models.py"], include=["refactoring"], '
+ 'only=["metrics", "findings", "refactoring_plans"])'
+ ),
+ kwargs=_frozen(
+ targets=("src/db/models.py",),
+ include=("refactoring",),
+ only=("metrics", "findings", "refactoring_plans"),
+ ),
+ comparison="broad healthy-file refactoring call",
+ comparison_kwargs=_frozen(
+ targets=("src/db/models.py",), include=("refactoring",)
+ ),
+ plans_requested=True,
+ expected_plan_count=0,
+ expected_empty_reason="no_applicable_findings",
+ next_action=None,
+ recovery="none",
+ invariant_paths=(
+ "metrics",
+ "findings",
+ "refactoring_plans",
+ "_meta.health_analysis",
+ "_meta.health_semantics",
+ ),
+ ),
+ HealthSemanticsCase(
+ name="unhealthy file self-check",
+ call=(
+ 'get_health(targets=["src/auth/service.py"], include=["refactoring"], '
+ 'only=["metrics", "findings", "refactoring_plans"])'
+ ),
+ kwargs=_frozen(
+ targets=("src/auth/service.py",),
+ include=("refactoring",),
+ only=("metrics", "findings", "refactoring_plans"),
+ ),
+ comparison="broad unhealthy-file refactoring call and repeated ID resolution",
+ comparison_kwargs=_frozen(
+ targets=("src/auth/service.py",), include=("refactoring",)
+ ),
+ plans_requested=True,
+ expected_plan_count=1,
+ expected_empty_reason=None,
+ next_action=None,
+ recovery="none",
+ invariant_paths=(
+ "metrics",
+ "findings",
+ "refactoring_plans",
+ "_meta.health_analysis",
+ "_meta.health_semantics",
+ ),
+ ),
+ HealthSemanticsCase(
+ name="module triage",
+ call=(
+ 'get_health(targets=["module:auth", "module:db"], '
+ 'only=["modules", "metrics"], limit=1)'
+ ),
+ kwargs=_frozen(
+ targets=("module:auth", "module:db"),
+ only=("modules", "metrics"),
+ limit=1,
+ ),
+ comparison="same module with limit=3",
+ comparison_kwargs=_frozen(
+ targets=("module:auth", "module:db"),
+ only=("modules", "metrics"),
+ limit=3,
+ ),
+ plans_requested=False,
+ expected_plan_count=None,
+ expected_empty_reason=None,
+ next_action=None,
+ recovery="cursor",
+ invariant_paths=(
+ "modules",
+ "modules_total",
+ "metrics_total",
+ "_meta.health_analysis",
+ "_meta.health_semantics",
+ ),
+ ),
+ HealthSemanticsCase(
+ name="trend",
+ call='get_health(include=["trend"], only=["trend"])',
+ kwargs=_frozen(include=("trend",), only=("trend",)),
+ comparison="broad trend expansion",
+ comparison_kwargs=_frozen(include=("trend",)),
+ plans_requested=False,
+ expected_plan_count=None,
+ expected_empty_reason=None,
+ next_action=None,
+ recovery="none",
+ invariant_paths=("trend", "_meta.health_analysis", "_meta.health_semantics"),
+ ),
+ HealthSemanticsCase(
+ name="accuracy",
+ call='get_health(include=["accuracy"], only=["accuracy"])',
+ kwargs=_frozen(include=("accuracy",), only=("accuracy",)),
+ comparison="broad accuracy expansion",
+ comparison_kwargs=_frozen(include=("accuracy",)),
+ plans_requested=False,
+ expected_plan_count=None,
+ expected_empty_reason=None,
+ next_action=None,
+ recovery="none",
+ invariant_paths=(
+ "defect_accuracy",
+ "_meta.health_analysis",
+ "_meta.health_semantics",
+ ),
+ ),
+ HealthSemanticsCase(
+ name="coverage",
+ call='get_health(include=["coverage"], only=["coverage"], limit=1)',
+ kwargs=_frozen(include=("coverage",), only=("coverage",), limit=1),
+ comparison="coverage expansion with a larger page",
+ comparison_kwargs=_frozen(
+ include=("coverage",), only=("coverage",), limit=20
+ ),
+ plans_requested=False,
+ expected_plan_count=None,
+ expected_empty_reason=None,
+ next_action=None,
+ recovery="cursor",
+ invariant_paths=(
+ "coverage.summary",
+ "coverage.files_total",
+ "_meta.health_analysis",
+ "_meta.health_semantics",
+ ),
+ ),
+ HealthSemanticsCase(
+ name="performance plus refactoring",
+ call=(
+ 'get_health(include=["performance", "refactoring"], '
+ 'only=["performance_opportunities", "refactoring_plans"], limit=1)'
+ ),
+ kwargs=_frozen(
+ include=("performance", "refactoring"),
+ only=("performance_opportunities", "refactoring_plans"),
+ limit=1,
+ ),
+ comparison="independent performance and refactoring projections",
+ comparison_kwargs=_frozen(
+ include=("performance", "refactoring"), limit=1
+ ),
+ plans_requested=True,
+ expected_plan_count=1,
+ expected_empty_reason=None,
+ next_action=None,
+ recovery="cursor",
+ invariant_paths=(
+ "performance_opportunities",
+ "performance_opportunities_total",
+ "refactoring_plans",
+ "refactoring_plans_total",
+ "_meta.health_analysis",
+ "_meta.health_semantics",
+ ),
+ ),
+ HealthSemanticsCase(
+ name="findings without supported plan",
+ call=(
+ 'get_health(targets=["src/auth/service.py"], include=["refactoring"], '
+ 'only=["findings", "refactoring_plans"])'
+ ),
+ kwargs=_frozen(
+ targets=("src/auth/service.py",),
+ include=("refactoring",),
+ only=("findings", "refactoring_plans"),
+ ),
+ comparison="same source population through the broad target call",
+ comparison_kwargs=_frozen(
+ targets=("src/auth/service.py",), include=("refactoring",)
+ ),
+ plans_requested=True,
+ expected_plan_count=0,
+ expected_empty_reason="plan_analysis_indeterminate",
+ next_action="get_symbol",
+ recovery="none",
+ invariant_paths=(
+ "findings",
+ "refactoring_plans",
+ "_meta.health_analysis",
+ "_meta.health_semantics",
+ ),
+ ),
+ HealthSemanticsCase(
+ name="unresolved target",
+ call='get_health(targets=["does/not/exist.py"], only=["metrics"])',
+ kwargs=_frozen(targets=("does/not/exist.py",), only=("metrics",)),
+ comparison="broad unresolved-target call",
+ comparison_kwargs=_frozen(targets=("does/not/exist.py",)),
+ plans_requested=False,
+ expected_plan_count=None,
+ expected_empty_reason=None,
+ next_action=None,
+ recovery="none",
+ invariant_paths=("targets", "unresolved", "_meta.health_semantics"),
+ ),
+ HealthSemanticsCase(
+ name="stale indexed analysis with live source",
+ call='get_health(targets=["src/auth/service.py"], only=["metrics"])',
+ kwargs=_frozen(targets=("src/auth/service.py",), only=("metrics",)),
+ comparison="broad target call over the same stale stored row",
+ comparison_kwargs=_frozen(targets=("src/auth/service.py",)),
+ plans_requested=False,
+ expected_plan_count=None,
+ expected_empty_reason=None,
+ next_action="repowise update",
+ recovery="none",
+ invariant_paths=("metrics", "_meta.health_analysis", "_meta.health_semantics"),
+ ),
+ HealthSemanticsCase(
+ name="degraded or missing analysis",
+ call=(
+ 'get_health(include=["refactoring"], '
+ 'only=["directive", "kpis", "refactoring_plans"])'
+ ),
+ kwargs=_frozen(
+ include=("refactoring",),
+ only=("directive", "kpis", "refactoring_plans"),
+ ),
+ comparison="missing-analysis narrow projection",
+ comparison_kwargs=_frozen(only=("directive", "kpis")),
+ plans_requested=True,
+ expected_plan_count=0,
+ expected_empty_reason="analysis_unavailable",
+ next_action="repowise update",
+ recovery="none",
+ invariant_paths=("directive", "kpis", "_meta.health_analysis", "_meta.health_semantics"),
+ ),
+)
+
+
+def test_sealed_health_semantics_matrix_has_every_independent_oracle() -> None:
+ assert tuple(case.name for case in SEALED_HEALTH_SEMANTICS) == (
+ "repository directive",
+ "healthy file self-check",
+ "unhealthy file self-check",
+ "module triage",
+ "trend",
+ "accuracy",
+ "coverage",
+ "performance plus refactoring",
+ "findings without supported plan",
+ "unresolved target",
+ "stale indexed analysis with live source",
+ "degraded or missing analysis",
+ )
+
+
+def test_sealed_health_semantics_matrix_records_required_measurements() -> None:
+ for case in SEALED_HEALTH_SEMANTICS:
+ assert case.call.startswith("get_health(")
+ assert case.comparison
+ assert case.invariant_paths
+ if case.expected_empty_reason is not None:
+ assert case.plans_requested
+ assert case.expected_plan_count == 0
+ if not case.plans_requested:
+ assert case.expected_plan_count is None
+ assert case.expected_empty_reason is None
+
+
+def _assert_counted(result: dict[str, Any], key: str) -> None:
+ rows = result[key]
+ assert result[f"{key}_total"] >= result[f"{key}_emitted"] == len(rows)
+
+
+def _mutable_kwargs(values: MappingProxyType[str, Any]) -> dict[str, Any]:
+ return {key: list(value) if isinstance(value, tuple) else value for key, value in values.items()}
+
+
+def _path(result: dict[str, Any], dotted: str) -> Any:
+ value: Any = result
+ for part in dotted.split("."):
+ value = value[part]
+ return value
+
+
+async def _seed_case_evidence(case: HealthSemanticsCase, session, repository_id: str) -> None:
+ from repowise.core.persistence.crud import (
+ save_coverage_files,
+ save_health_findings,
+ save_health_snapshot,
+ save_refactoring_suggestions,
+ )
+
+ if case.name == "coverage":
+ await save_coverage_files(
+ session,
+ repository_id,
+ [
+ {
+ "file_path": path,
+ "line_coverage_pct": pct,
+ "covered_lines": [1],
+ "total_coverable_lines": 10,
+ "branch_coverage_pct": pct,
+ }
+ for path, pct in (("src/auth/service.py", 20.0), ("src/db/models.py", 90.0))
+ ],
+ source_format="lcov",
+ )
+ if case.name == "trend":
+ base = datetime(2026, 1, 1, tzinfo=UTC)
+ for day, scores in (
+ (0, {"src/auth/service.py": 4.0}),
+ (1, {"src/auth/service.py": 4.5}),
+ ):
+ await save_health_snapshot(
+ session,
+ repository_id,
+ hotspot_health=4.5,
+ average_health=5.3,
+ worst_performer_path="src/auth/service.py",
+ worst_performer_score=4.5,
+ per_file_scores=scores,
+ taken_at=base + timedelta(days=day),
+ )
+ if case.expected_plan_count:
+ plans = [
+ {
+ "refactoring_type": "extract_method",
+ "file_path": "src/auth/service.py",
+ "target_symbol": "authenticate",
+ "line_start": 10,
+ "line_end": 80,
+ "plan": {"groups": []},
+ "evidence": {},
+ "impact_delta": 1.2,
+ "effort_bucket": "S",
+ "blast_radius": {"dependents_count": 0},
+ "confidence": "high",
+ "source_biomarker": "complex_method",
+ }
+ ]
+ if case.name == "performance plus refactoring":
+ await save_health_findings(
+ session,
+ repository_id,
+ [
+ {
+ "file_path": "src/db/models.py",
+ "biomarker_type": "io_in_loop",
+ "severity": "medium",
+ "function_name": "load_rows",
+ "line_start": 10,
+ "line_end": 10,
+ "details": {"boundary_kind": "db"},
+ "health_impact": 0.5,
+ "reason": "database call inside a loop",
+ "dimension": "performance",
+ }
+ ],
+ )
+ plans.append({**plans[0], "file_path": "src/db/models.py", "target_symbol": "load_rows"})
+ await save_refactoring_suggestions(session, repository_id, plans)
+ await session.commit()
+
+
+ "case",
+ [case for case in SEALED_HEALTH_SEMANTICS if case.name != "degraded or missing analysis"],
+ ids=lambda case: case.name,
+)
+async def test_each_sealed_row_executes_its_call_and_comparison(
+ case, setup_mcp, health_data, session
+):
+ from repowise.server.mcp_server import get_health, tool_middleware
+
+ await _seed_case_evidence(case, session, health_data)
+ call = tool_middleware(get_health)
+ result = await call(**_mutable_kwargs(case.kwargs))
+ comparison = await call(**_mutable_kwargs(case.comparison_kwargs))
+
+ assert result["_meta"]["response_budget"]["serialized_chars"] == len(
+ json.dumps(result, separators=(",", ":"), default=str)
+ )
+ assert result["_meta"]["health_analysis"]["recomputed_this_call"] is False
+ assert result["_meta"]["health_analysis"]["live_verification"][
+ "source_bytes_verified"
+ ] is False
+ for dotted in case.invariant_paths:
+ if dotted == "metrics" and case.name == "module triage":
+ assert _path(result, dotted) == _path(comparison, dotted)[:1]
+ else:
+ assert _path(result, dotted) == _path(comparison, dotted)
+ if case.plans_requested:
+ assert len(result["refactoring_plans"]) == case.expected_plan_count
+ reason = result["refactoring_plans_status"]["reason"]
+ assert reason == case.expected_empty_reason
+ if case.recovery == "cursor":
+ assert result["recovery"]
+
+
+async def test_sealed_missing_analysis_row_executes_without_fabricating_health(
+ setup_mcp, populated_db
+):
+ from repowise.server.mcp_server import get_health, tool_middleware
+
+ case = SEALED_HEALTH_SEMANTICS[-1]
+ call = tool_middleware(get_health)
+ result = await call(**_mutable_kwargs(case.kwargs))
+ comparison = await call(**_mutable_kwargs(case.comparison_kwargs))
+
+ assert result["directive"] is None
+ assert result["kpis"]["average_health"] is None
+ assert result["kpis"]["analysis_status"] == "unavailable"
+ assert result["refactoring_plans"] == []
+ assert result["refactoring_plans_status"]["reason"] == case.expected_empty_reason
+ assert result["_meta"]["health_analysis"]["status"] == "unavailable"
+ assert comparison["_meta"]["health_analysis"] == result["_meta"]["health_analysis"]
+ assert result["_meta"]["response_budget"]["serialized_chars"] == len(
+ json.dumps(result, separators=(",", ":"), default=str)
+ )
+
+
+
+async def test_sealed_projection_invariance_uses_independent_calls(setup_mcp, health_data):
+ from repowise.server.mcp_server import get_health
+
+ dashboard = await get_health()
+ directive = await get_health(only=["directive"], limit=0)
+ assert directive["directive"] == dashboard["directive"]
+ assert directive["_meta"]["health_semantics"] == dashboard["_meta"]["health_semantics"]
+ assert directive["_meta"]["health_analysis"] == dashboard["_meta"]["health_analysis"]
+
+ broad = await get_health(
+ targets=["src/auth/service.py"], include=["refactoring"], limit=2
+ )
+ narrow = await get_health(
+ targets=["src/auth/service.py"],
+ include=["refactoring"],
+ only=["metrics", "findings", "refactoring_plans"],
+ limit=2,
+ )
+ for key in ("metrics", "findings", "refactoring_plans"):
+ assert narrow[key] == broad[key]
+ assert narrow[f"{key}_total"] == broad[f"{key}_total"]
+ assert narrow[f"{key}_emitted"] == broad[f"{key}_emitted"]
+ _assert_counted(narrow, key)
+ assert narrow["refactoring_plans_status"] == broad["refactoring_plans_status"]
+ assert narrow.get("unresolved", []) == []
+ assert narrow["_meta"]["health_analysis"] == broad["_meta"]["health_analysis"]
+
+
+async def test_module_limit_changes_page_not_rollup_or_row_meaning(setup_mcp, health_data):
+ from repowise.server.mcp_server import get_health
+
+ short = await get_health(
+ targets=["module:auth", "module:db"],
+ only=["modules", "metrics"],
+ limit=1,
+ )
+ long = await get_health(
+ targets=["module:auth", "module:db"],
+ only=["modules", "metrics"],
+ limit=3,
+ )
+ assert short["modules"] == long["modules"]
+ assert short["modules_total"] == long["modules_total"] == 2
+ assert short["metrics_total"] == long["metrics_total"] == 2
+ assert short["metrics"] == long["metrics"][:1]
+ assert [row["file_path"] for row in short["metrics"]] == ["src/auth/service.py"]
+ assert short["_meta"]["health_analysis"] == long["_meta"]["health_analysis"]
+
+
+async def test_seven_registry_health_recipes_are_bounded_and_self_describing(
+ setup_mcp, health_data
+):
+ from repowise.server.mcp_server import get_health, tool_middleware
+
+ call = tool_middleware(get_health)
+ recipes = (
+ ({"only": ["directive"]}, "directive"),
+ ({"targets": ["src/auth/service.py"], "include": ["refactoring"]}, "metrics"),
+ (
+ {"targets": ["module:auth"], "only": ["modules", "metrics"]},
+ "modules",
+ ),
+ ({"include": ["trend"], "only": ["trend"]}, "trend"),
+ ({"include": ["accuracy"], "only": ["accuracy"]}, "defect_accuracy"),
+ ({"include": ["coverage"], "only": ["coverage"]}, "coverage"),
+ (
+ {
+ "include": ["performance", "refactoring"],
+ "only": ["performance_opportunities", "refactoring_plans"],
+ },
+ "performance_opportunities",
+ ),
+ )
+ for kwargs, answer_key in recipes:
+ result = await call(**kwargs)
+ assert answer_key in result
+ assert result["_meta"]["health_semantics"]
+ assert result["_meta"]["health_analysis"]
+ size = len(json.dumps(result, separators=(",", ":"), default=str))
+ budget = 32_000 if kwargs.get("include") else 24_000
+ assert size <= budget
diff --git a/tests/unit/server/mcp/test_number_precision.py b/tests/unit/server/mcp/test_number_precision.py
index e80d3ea86..0c1fcb03b 100644
--- a/tests/unit/server/mcp/test_number_precision.py
+++ b/tests/unit/server/mcp/test_number_precision.py
@@ -288,6 +288,51 @@ def test_churn_risk_biomarker_emits_percentile_on_the_zero_to_one_hundred_scale(
assert results[0].details["churn_percentile"] == 98.9
+ ("stored", "expected"),
+ [
+ (0.973, "top 2.7% among eligible files"),
+ (0.99, "top 1% among eligible files"),
+ (0.999, "top 0.1% among eligible files"),
+ (0.9995, "top <0.1% among eligible files"),
+ (1.0, "top <0.1% among eligible files"),
+ ],
+)
+def test_health_percentile_formatter_is_bounded_and_preserves_precision(stored, expected):
+ from repowise.core.analysis.health.semantics import format_top_percentile
+
+ assert format_top_percentile(stored, "eligible files") == expected
+ assert "top 0%" not in expected
+
+
+def test_health_biomarkers_share_honest_extreme_percentile_wording():
+ from repowise.core.analysis.health.biomarkers.change_entropy import (
+ BIOMARKER as ENTROPY_BIOMARKER,
+ )
+ from repowise.core.analysis.health.biomarkers.churn_risk import (
+ BIOMARKER as CHURN_BIOMARKER,
+ )
+
+ entropy = ENTROPY_BIOMARKER.detect(
+ _file_context(change_entropy=4.0, change_entropy_pct=1.0, commit_count_90d=10)
+ )[0]
+ churn = CHURN_BIOMARKER.detect(
+ _file_context(
+ churn_percentile=1.0,
+ lines_added_90d=10,
+ lines_deleted_90d=0,
+ commit_count_90d=5,
+ is_hotspot=True,
+ )
+ )[0]
+ assert "top <0.1%" in entropy.reason
+ assert "top <0.1%" in churn.reason
+ assert "top 0%" not in entropy.reason
+ assert "top 0%" not in churn.reason
+ assert entropy.details["change_entropy_pct"] == 100.0
+ assert churn.details["churn_percentile"] == 100.0
+
+
# ---------------------------------------------------------------------------
# NaN at the source, not stripped per-boundary
# ---------------------------------------------------------------------------
diff --git a/tests/unit/server/mcp/test_overview_surface.py b/tests/unit/server/mcp/test_overview_surface.py
index fafa18eba..7d674885b 100644
--- a/tests/unit/server/mcp/test_overview_surface.py
+++ b/tests/unit/server/mcp/test_overview_surface.py
@@ -188,3 +188,25 @@ async def test_live_registry_recipe_calls_bind_to_current_tool_signatures(setup_
assert recipe_requirements[recipe["name"]] <= set(
result["tool_surface"]["enabled"]
)
+
+ health_recipes = {
+ recipe["name"]: recipe["call"]
+ for recipe in result["tool_surface"]["recipes"]
+ if recipe["name"].startswith("health_")
+ }
+ assert health_recipes == {
+ "health_directive": 'get_health(only=["directive"])',
+ "health_file_self_check": (
+ 'get_health(targets=["path"], include=["refactoring"])'
+ ),
+ "health_module_triage": (
+ 'get_health(targets=["module:path"], only=["modules","metrics"])'
+ ),
+ "health_trend": 'get_health(include=["trend"], only=["trend"])',
+ "health_accuracy": 'get_health(include=["accuracy"], only=["accuracy"])',
+ "health_coverage": 'get_health(include=["coverage"], only=["coverage"])',
+ "health_performance_refactoring": (
+ 'get_health(include=["performance","refactoring"], '
+ 'only=["performance_opportunities","refactoring_plans"])'
+ ),
+ }
diff --git a/tests/unit/server/mcp/test_response_budget_contracts.py b/tests/unit/server/mcp/test_response_budget_contracts.py
index c9f829df2..1c6c6017b 100644
--- a/tests/unit/server/mcp/test_response_budget_contracts.py
+++ b/tests/unit/server/mcp/test_response_budget_contracts.py
@@ -121,6 +121,25 @@ def _enforce(tool: str, payload: dict[str, Any], include: list[str] | None = Non
)
+def test_health_plan_status_tracks_final_budget_removal(setup_mcp: str) -> None:
+ payload = {
+ "mode": "dashboard",
+ "directive": None,
+ "kpis": {"average_health": 7.0},
+ "refactoring_plans": [{"id": "plan_1", "evidence": "x" * 30_000}],
+ "refactoring_plans_total": 1,
+ "refactoring_plans_status": {"state": "available", "reason": None},
+ "_meta": {"contract_version": 1},
+ }
+
+ result = _enforce("get_health", payload)
+
+ assert result.get("refactoring_plans", []) == []
+ assert result["refactoring_plans_total"] == 1
+ assert result["refactoring_plans_status"]["state"] == "available_not_emitted"
+ assert result["refactoring_plans_status"]["reason"] == "response_budget"
+
+
@pytest.mark.parametrize(
("tool", "required"),
[