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.

feat(mcp): enrich get_health for pre-PR self-check (#571)

Raghav Chamadiya01195181f65a
diff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2
index a86281a92..4858cd510 100644
--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2
@@ -119,6 +119,7 @@ This repo has the Repowise MCP server configured. The tools below answer questio
| `search_codebase(query, mode?, kind?, symbol_kind?)` | Hybrid code search. `mode="auto"` (default) routes by query shape: an identifier → indexed symbol hits (`symbol_id`/`file`/line bounds — pipe into `get_symbol`), a path → file pages (pipe into `get_context`), prose → wiki-semantic search, mixed → hybrid (symbols first). Force a branch with `mode=symbol\|path\|concept\|hybrid`. Concept hits carry `search_method` (`embedding` vs `bm25` fallback); decision records rank below file pages unless the query is why-shaped. |
| `get_why(query, targets?)` | Architectural decision archaeology — *why* the code is shaped this way. Call before refactors or pattern divergences. Falls back to git archaeology when no ADRs exist for a file. |
| `get_risk(targets, changed_files?)` | What history says about touching these files: churn, owners, blast radius. Pass `changed_files` for PR mode → returns a `directive` (`will_break`, `missing_cochanges`, `missing_tests`). |
+| `get_health(targets?, include?)` | Code-health scores + biomarker findings (defect / maintainability / performance pillars). Self-check before a PR — read the same signals the merge-gate judges your change on. Default is lean; opt in with `include`: `["accuracy"]` (does the score rank the buggy files first — precision@K + `lift`), `["signals"]` (per-file prior-defects / churn / owners / degree, targeted mode), `["churn_complexity"]` (volatile-and-complex danger-zone files), `["biomarkers"]` (all findings), and a dimension name `["performance"]` / `["defect"]` / `["maintainability"]` to filter findings to one pillar. |
| `get_dead_code(...)` | Tiered unreachable / unused-export / zombie-package findings. Run before a cleanup sprint, not before a targeted fix. |
| `get_overview(repo?)` | Architecture map + `tool_guide` recipes. One-time orientation; skip on subsequent calls in the same session. |
diff --git a/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2 b/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2
index 2239abd0a..bbddcf2c9 100644
--- a/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2
@@ -65,6 +65,7 @@ These tools work across all repos in this workspace. Pass `repo="alias"` to scop
| `search_codebase(query, mode?, kind?, symbol_kind?)` | Hybrid code search. `mode="auto"` routes by query shape: identifier → indexed symbol hits (pipe `symbol_id` into `get_symbol`), path → file pages (`get_context`), prose → semantic search. Force with `mode=symbol\|path\|concept\|hybrid`. Concept hits tag `search_method` (`embedding` vs `bm25`). |
| `get_why(query, targets?)` | Architectural decision archaeology — *why* the code is shaped this way. Call before refactors. Falls back to git archaeology when no ADRs exist. |
| `get_risk(targets, changed_files?)` | What history says about touching these files. Pass `changed_files` for PR mode → returns a `directive` (`will_break`, `missing_cochanges`, `missing_tests`) plus cross-repo blast radius. |
+| `get_health(targets?, include?)` | Code-health scores + biomarker findings (defect / maintainability / performance). Self-check before a PR. Lean by default; opt in via `include`: `["accuracy"]` (precision@K + `lift`), `["signals"]` (per-file prior-defects / churn / owners / degree), `["churn_complexity"]` (danger-zone files), `["biomarkers"]` (all findings), or a dimension name `["performance"]` / `["defect"]` / `["maintainability"]` to filter findings to one pillar. |
| `get_dead_code(...)` | Tiered unreachable / unused-export / zombie-package findings; cross-repo consumer detection lowers confidence on shared exports. |
| `get_overview(repo?)` | Architecture map. `repo="all"` returns cross-repo topology (co-changes, package deps, API contracts). |
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 9e969609a..a948bf304 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py
@@ -3,16 +3,24 @@
from __future__ import annotations
import json
+from dataclasses import asdict
from typing import Any
from sqlalchemy import select
+from repowise.core.analysis.health.churn_complexity import churn_complexity_points
+from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracy
from repowise.core.analysis.health.grading import band_for
from repowise.core.analysis.health.grading import distribution as health_distribution
+from repowise.core.analysis.health.signals import file_signals
from repowise.core.analysis.health.suggestions import suggestion_for
from repowise.core.analysis.health.trends import diff_snapshots, file_trend, recent_kpis
from repowise.core.persistence.crud import (
+ get_all_git_metadata,
get_coverage_summary,
+ get_git_metadata,
+ get_graph_node,
+ get_node_degree_counts,
list_health_snapshots,
load_coverage_for_repo,
)
@@ -201,11 +209,30 @@ async def get_health(
resolved ``caller -> ... -> sink`` symbol chain). Performance is a static signal:
dynamic dispatch, ORM lazy-load, and unmodelled libraries are out of scope.
+ Self-check before a PR: an agent can read the same signals the code-health
+ merge-gate judges a change on. ``include=["accuracy"]`` returns
+ ``defect_accuracy`` (does the score actually rank the buggy files first —
+ precision@K of the least-healthy files vs the repo bug-fix base rate, with a
+ ``lift`` headline); ``include=["signals"]`` attaches per-file process / people
+ / topology ``signals`` (prior-defect count, churn, owners, in/out degree) to
+ each targeted metric; ``include=["churn_complexity"]`` returns the
+ churn x complexity quadrant points (volatile-and-complex files are where
+ defects concentrate); and a dimension name in ``include``
+ (``"performance"`` / ``"defect"`` / ``"maintainability"``) filters the
+ returned findings to that pillar.
+
Args:
- targets: List of file paths. Empty → dashboard mode.
- include: Optional flags. ``"biomarkers"`` always returns findings;
- ``"coverage"`` will surface coverage data when available
- (Phase 2).
+ targets: List of file paths (or ``module:<name>``). Empty → dashboard mode.
+ include: Optional opt-in flags (default response stays lean):
+ ``"biomarkers"`` returns findings in dashboard mode;
+ ``"refactoring"`` attaches a deterministic ``suggestion`` per finding;
+ ``"trend"`` adds the repo trend + alert block;
+ ``"coverage"`` surfaces coverage rows when ingested;
+ ``"accuracy"`` adds repo-level ``defect_accuracy`` (dashboard mode);
+ ``"signals"`` attaches per-file ``signals`` (targeted mode);
+ ``"churn_complexity"`` adds the churn x complexity points (dashboard);
+ ``"performance"`` / ``"defect"`` / ``"maintainability"`` filter
+ findings to that dimension.
repo: Repo alias / id / path.
limit: Max rows in the lowest-scoring file list (capped at 50).
"""
@@ -278,6 +305,32 @@ async def get_health(
# here; the per-file rows above are exclude-filtered.
coverage_summary = await get_coverage_summary(session, repository.id)
+ # Per-file process/people/topology signals for targeted files — the
+ # same join the file-detail drawer and REST breakdown use, so an agent
+ # can read why a file is risky (prior defects, churn, owners, degree)
+ # before touching it. Targeted mode only; the target set is small.
+ signals_by_path: dict[str, dict[str, Any]] = {}
+ if "signals" in include_set and effective_targets:
+ for path in effective_targets:
+ git_meta = await get_git_metadata(session, repository.id, path)
+ node = await get_graph_node(session, repository.id, path)
+ degrees = (
+ await get_node_degree_counts(session, repository.id, path)
+ if node is not None
+ else None
+ )
+ signals_by_path[path] = asdict(file_signals(git_meta, degrees))
+
+ # Churn x complexity quadrant for the whole repo (dashboard mode). One
+ # git-metadata query joined against the already-loaded metrics.
+ churn_points: list[dict[str, Any]] = []
+ if "churn_complexity" in include_set and not effective_targets:
+ 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]
+ ]
+
# 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).
@@ -288,10 +341,16 @@ async def get_health(
kpis = _compute_kpis(metric_rows if effective_targets else all_metrics)
if effective_targets:
+ metric_payload: list[dict[str, Any]] = []
+ for m in metric_rows:
+ row = _serialize_metric(m)
+ if m.file_path in signals_by_path:
+ row["signals"] = signals_by_path[m.file_path]
+ metric_payload.append(row)
result: dict[str, Any] = {
"mode": "targets",
"targets": raw_targets,
- "metrics": [_serialize_metric(m) for m in metric_rows],
+ "metrics": metric_payload,
"findings": [_serialize_finding(f) for f in finding_rows],
}
# Per-file score trajectory for each target — silent (omitted) when a
@@ -327,6 +386,16 @@ async def get_health(
"top_findings": [_serialize_finding(f) for f in finding_rows[:limit]],
"modules": _module_rollups(all_metrics),
}
+ if "churn_complexity" in include_set:
+ result["churn_complexity"] = churn_points
+ if "accuracy" in include_set:
+ # Self-validation: does the score rank the buggy files first? Pure
+ # over the already-loaded metrics + findings (no extra query).
+ # ``None`` when there isn't enough signal for an honest number.
+ result["defect_accuracy"] = compute_defect_accuracy(
+ all_metrics,
+ [_serialize_finding(f) for f in finding_rows],
+ )
if "biomarkers" in include_set and "findings" not in result:
result["findings"] = [_serialize_finding(f) for f in finding_rows]
@@ -395,5 +464,19 @@ async def get_health(
"files": coverage_payload,
}
+ # Dimension filter: ``include=["performance"]`` (or "defect" /
+ # "maintainability") narrows the returned findings to that pillar so an
+ # agent can ask "show me only the performance risk in this change". Applied
+ # after the biomarkers/refactoring includes so it filters whatever findings
+ # the response carries. Each finding's ``dimension`` is set at scoring time.
+ dimension_filter = include_set & {"performance", "defect", "maintainability"}
+ if dimension_filter:
+ for field in ("findings", "top_findings"):
+ rows = result.get(field)
+ if rows:
+ result[field] = [
+ r for r in rows if (r.get("dimension") or "defect") in dimension_filter
+ ]
+
result["_meta"] = _build_meta(repository=repository)
return result
diff --git a/tests/integration/test_mcp.py b/tests/integration/test_mcp.py
index 223d755d0..397c14107 100644
--- a/tests/integration/test_mcp.py
+++ b/tests/integration/test_mcp.py
@@ -425,3 +425,260 @@ async def test_mcp_search_flow(mcp_env):
result = await search_codebase("authentication login OAuth")
assert "results" in result
assert len(result["results"]) >= 1
+
+
+async def health_mcp_env():
+ """MCP environment populated with code-health metrics, findings, git
+ metadata, and graph topology so ``get_health`` enrichment can be exercised
+ end-to-end."""
+ from repowise.core.persistence.models import HealthFileMetric, HealthFinding
+
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ await init_db(engine)
+ factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
+
+ async with factory() as session:
+ session.add(
+ Repository(
+ id="health-repo",
+ name="health-project",
+ url="https://github.com/example/health",
+ local_path="/tmp/health-project",
+ default_branch="main",
+ settings_json="{}",
+ created_at=_NOW,
+ updated_at=_NOW,
+ )
+ )
+
+ # 30 files so the defect-accuracy guard (>= 25 files) is satisfied.
+ # Score ascending with the index, so f0..f5 (lowest health) are the
+ # files we tag as recently bug-fixed — precision@K should be high.
+ for i in range(30):
+ session.add(
+ HealthFileMetric(
+ id=f"hm{i}",
+ repository_id="health-repo",
+ file_path=f"src/mod/f{i}.py",
+ score=round(i * 0.3, 2),
+ max_ccn=10,
+ max_nesting=3,
+ nloc=100,
+ has_test_file=False,
+ module="src/mod",
+ defect_score=round(i * 0.3, 2),
+ maintainability_score=8.0,
+ performance_score=9.0,
+ updated_at=_NOW,
+ )
+ )
+
+ # prior_defect findings on the 6 least-healthy files (the positive
+ # class for defect_accuracy, >= 5 required).
+ for i in range(6):
+ session.add(
+ HealthFinding(
+ id=f"hfd{i}",
+ repository_id="health-repo",
+ file_path=f"src/mod/f{i}.py",
+ biomarker_type="prior_defect",
+ severity="medium",
+ details_json=json.dumps({"prior_defect_count": 2, "window_days": 180}),
+ health_impact=0.5,
+ reason="recently bug-fixed",
+ dimension="defect",
+ status="open",
+ created_at=_NOW,
+ updated_at=_NOW,
+ )
+ )
+
+ # One performance-pillar finding + one defect finding for the
+ # dimension filter test.
+ session.add(
+ HealthFinding(
+ id="hfp1",
+ repository_id="health-repo",
+ file_path="src/mod/f0.py",
+ biomarker_type="io_in_loop",
+ severity="high",
+ details_json=json.dumps({"boundary_kind": "db", "cross_function": False}),
+ health_impact=0.9,
+ reason="I/O inside a loop",
+ dimension="performance",
+ status="open",
+ created_at=_NOW,
+ updated_at=_NOW,
+ )
+ )
+ session.add(
+ HealthFinding(
+ id="hfc1",
+ repository_id="health-repo",
+ file_path="src/mod/f0.py",
+ biomarker_type="complex_method",
+ severity="high",
+ details_json="{}",
+ health_impact=0.8,
+ reason="too complex",
+ dimension="defect",
+ status="open",
+ created_at=_NOW,
+ updated_at=_NOW,
+ )
+ )
+
+ # Git metadata (churn + process/people signals) for the worst file.
+ session.add(
+ GitMetadata(
+ id="hgm0",
+ repository_id="health-repo",
+ file_path="src/mod/f0.py",
+ commit_count_total=40,
+ commit_count_90d=10,
+ commit_count_30d=4,
+ prior_defect_count=2,
+ change_entropy_pct=0.6,
+ lines_added_90d=200,
+ lines_deleted_90d=80,
+ primary_owner_name="Alice",
+ primary_owner_commit_pct=0.6,
+ recent_owner_name="Bob",
+ recent_owner_commit_pct=0.5,
+ is_hotspot=True,
+ churn_percentile=0.9,
+ age_days=300,
+ created_at=_NOW,
+ updated_at=_NOW,
+ )
+ )
+
+ # Graph node + edge so f0 has a non-zero out-degree for topology signals.
+ session.add(
+ GraphNode(
+ id="hgn0",
+ repository_id="health-repo",
+ node_id="src/mod/f0.py",
+ node_type="file",
+ language="python",
+ symbol_count=3,
+ created_at=_NOW,
+ )
+ )
+ session.add(
+ GraphNode(
+ id="hgn1",
+ repository_id="health-repo",
+ node_id="src/mod/f1.py",
+ node_type="file",
+ language="python",
+ symbol_count=2,
+ created_at=_NOW,
+ )
+ )
+ session.add(
+ GraphEdge(
+ id="hge0",
+ repository_id="health-repo",
+ source_node_id="src/mod/f0.py",
+ target_node_id="src/mod/f1.py",
+ imported_names_json="[]",
+ created_at=_NOW,
+ )
+ )
+
+ await session.commit()
+
+ import repowise.server.mcp_server as mcp_mod
+
+ mcp_mod._session_factory = factory
+ mcp_mod._repo_path = "/tmp/health-project"
+
+ yield
+
+ mcp_mod._session_factory = None
+ mcp_mod._repo_path = None
+ await engine.dispose()
+
+
+async def test_mcp_health_default_is_lean(health_mcp_env):
+ """The default dashboard response carries none of the opt-in enrichments."""
+ from repowise.server.mcp_server import get_health
+
+ res = await get_health()
+ assert res["mode"] == "dashboard"
+ assert res["kpis"]["file_count"] == 30
+ # Enrichment fields are gated behind include= and must be absent by default.
+ for absent in ("defect_accuracy", "churn_complexity"):
+ assert absent not in res
+
+
+async def test_mcp_health_accuracy(health_mcp_env):
+ """include=["accuracy"] surfaces the defect-accuracy self-validation stat."""
+ from repowise.server.mcp_server import get_health
+
+ res = await get_health(include=["accuracy"])
+ acc = res["defect_accuracy"]
+ assert acc is not None
+ assert acc["scored_files"] == 30
+ assert acc["defect_files"] == 6
+ # All 6 bug-fixed files are among the 20 least-healthy → precision is high.
+ assert acc["hits"] == 6
+ assert acc["lift"] is not None and acc["lift"] > 1.0
+
+
+async def test_mcp_health_churn_complexity(health_mcp_env):
+ """include=["churn_complexity"] returns the quadrant points for churned files."""
+ from repowise.server.mcp_server import get_health
+
+ res = await get_health(include=["churn_complexity"])
+ points = res["churn_complexity"]
+ # Only f0 has recent churn (commit_count_90d > 0).
+ assert len(points) == 1
+ p = points[0]
+ assert p["file_path"] == "src/mod/f0.py"
+ assert p["commit_count_90d"] == 10
+ assert p["max_ccn"] == 10
+
+
+async def test_mcp_health_signals_targeted(health_mcp_env):
+ """include=["signals"] attaches per-file process/people/topology signals."""
+ from repowise.server.mcp_server import get_health
+
+ res = await get_health(targets=["src/mod/f0.py", "src/mod/f7.py"], include=["signals"])
+ assert res["mode"] == "targets"
+ by_path = {m["file_path"]: m for m in res["metrics"]}
+
+ # f0 has full git history + a graph node → real signals.
+ sig = by_path["src/mod/f0.py"]["signals"]
+ assert sig["prior_defect_count"] == 2
+ assert sig["commit_count_90d"] == 10
+ assert sig["recent_owner_name"] == "Bob"
+ assert sig["out_degree"] == 1 # f0 -> f1
+
+ # f7 has neither git metadata nor a graph node → honest None everywhere,
+ # never an imputed zero (the signals.py honesty rule, surfaced through MCP).
+ sig7 = by_path["src/mod/f7.py"]["signals"]
+ assert all(v is None for v in sig7.values())
+
+
+async def test_mcp_health_performance_filter(health_mcp_env):
+ """A dimension name in include filters findings to that pillar."""
+ from repowise.server.mcp_server import get_health
+
+ # Pull all findings, then keep only the performance pillar.
+ res = await get_health(include=["biomarkers", "performance"])
+ findings = res["findings"]
+ assert findings # non-empty
+ assert all(f["dimension"] == "performance" for f in findings)
+ assert any(f["biomarker_type"] == "io_in_loop" for f in findings)