Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(change-risk): harden get_change_risk subprocess handling and align with MCP tool conventions (#899)
Raghav Chamadiyaffd2797ecedd
diff --git a/packages/core/src/repowise/core/analysis/change_risk/baseline.py b/packages/core/src/repowise/core/analysis/change_risk/baseline.pyindex 9c43441b4..6a2830092 100644--- a/packages/core/src/repowise/core/analysis/change_risk/baseline.py+++ b/packages/core/src/repowise/core/analysis/change_risk/baseline.py@@ -12,7 +12,7 @@ import subprocessimport pathspec-from .features import features_from_file_changes+from .features import GIT_TIMEOUT_SECONDS, features_from_file_changesfrom .model import score_change@@ -35,6 +35,10 @@ def baseline_scores(*exclude_patterns* use gitignore syntax and are applied to every sampledcommit, matching the target change's filtering."""+ # stdin=DEVNULL + timeout: a stuck git must not hang the caller (on MCP+ # stdio transport an inherited pipe handle can wedge the whole session).+ # No returncode check: the anchor was already validated by the feature+ # extraction, and a failed sample degrades honestly to "no percentile".out = subprocess.run(["git", "log", f"-n{limit}", "--no-merges", "--format=%x1e%H", "--numstat", anchor],cwd=repo_path,@@ -42,6 +46,8 @@ def baseline_scores(text=True,encoding="utf-8",errors="replace",+ stdin=subprocess.DEVNULL,+ timeout=GIT_TIMEOUT_SECONDS,).stdoutscores: list[float] = []diff --git a/packages/core/src/repowise/core/analysis/change_risk/features.py b/packages/core/src/repowise/core/analysis/change_risk/features.pyindex cd1ab6689..c3f7fa504 100644--- a/packages/core/src/repowise/core/analysis/change_risk/features.py+++ b/packages/core/src/repowise/core/analysis/change_risk/features.py@@ -47,15 +47,32 @@ class ChangeFeatures:ref: str = "" # the commit sha or "base..head" range scored-def _git(args: list[str], cwd: str) -> str:- return subprocess.run(+# Generous ceiling: even a 200-commit numstat walk finishes in seconds. The+# point is that a stuck git (lock contention, network filesystem) must fail+# loud instead of hanging the caller's thread forever.+GIT_TIMEOUT_SECONDS = 60+++def _git(args: list[str], cwd: str, *, check: bool = True) -> str:+ # stdin=DEVNULL: on MCP stdio transport a child that inherits the JSON-RPC+ # pipe handles can wedge the session (same failure mode _meta.py guards+ # against). check=True so a bad revspec raises instead of yielding empty+ # stdout, which used to score as a zero-feature "low risk" change.+ proc = subprocess.run(["git", *args],cwd=cwd,capture_output=True,text=True,encoding="utf-8",errors="replace",- ).stdout+ stdin=subprocess.DEVNULL,+ timeout=GIT_TIMEOUT_SECONDS,+ )+ if check and proc.returncode != 0:+ raise subprocess.CalledProcessError(+ proc.returncode, proc.args, output=proc.stdout, stderr=proc.stderr+ )+ return proc.stdoutdef _accumulate_numstat(@@ -103,9 +120,12 @@ def _author_experience(repo_path: str, author: str, upto_ref: str) -> int:"""Author's prior commit count reachable from *upto_ref* (one cheap call)."""if not author:return 0+ # check=False: --author is a regex, so a name with metacharacters can make+ # git error; unknown experience degrades to 0 rather than failing the score.out = _git(["rev-list", "--count", "--author", author, "--no-merges", upto_ref],repo_path,+ check=False,).strip()try:return int(out)@@ -178,7 +198,10 @@ def extract_commit_features(author, _, subject = meta.partition("\x00")numstat = _git(["show", sha, "--numstat", "--format="], repo_path)la, ld, nf, dirs, subs, per_file = _accumulate_numstat(numstat, extensions, exclude_patterns)- parent = _git(["rev-parse", "--verify", "--quiet", f"{sha}^"], repo_path).strip()+ # check=False: a root commit has no parent and that is not an error.+ parent = _git(+ ["rev-parse", "--verify", "--quiet", f"{sha}^"], repo_path, check=False+ ).strip()exp = _author_experience(repo_path, author, parent or sha)return ChangeFeatures(la=la,diff --git a/packages/core/src/repowise/core/analysis/change_risk/service.py b/packages/core/src/repowise/core/analysis/change_risk/service.pyindex 48821b6af..3d9e4a4cc 100644--- a/packages/core/src/repowise/core/analysis/change_risk/service.py+++ b/packages/core/src/repowise/core/analysis/change_risk/service.py@@ -7,7 +7,12 @@ from dataclasses import dataclass, replacefrom pathlib import Pathfrom .baseline import baseline_scores-from .features import ChangeFeatures, extract_commit_features, extract_range_features+from .features import (+ GIT_TIMEOUT_SECONDS,+ ChangeFeatures,+ extract_commit_features,+ extract_range_features,+)from .model import ChangeRisk, score_changefrom .normalize import RiskNormalizer, review_priority_classification@@ -34,6 +39,8 @@ def riskignore_patterns(repo_path: str) -> tuple[str, ...]:capture_output=True,text=True,encoding="utf-8",+ stdin=subprocess.DEVNULL,+ timeout=GIT_TIMEOUT_SECONDS,)if proc.returncode != 0:return ()diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.pyindex e2720fb81..50b7d58de 100644--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py@@ -4,10 +4,12 @@ from __future__ import annotationsimport asyncioimport subprocess+import timefrom repowise.core.analysis.change_risk import change_risk_payload, score_live_changefrom repowise.core.registry import mcp_tool_registry as mcp-from repowise.server.mcp_server._helpers import _resolve_repo_context+from repowise.server.mcp_server._helpers import _resolve_repo_context, _unsupported_repo_all+from repowise.server.mcp_server._meta import build_meta as _build_meta@mcp.tool()@@ -41,7 +43,10 @@ async def get_change_risk(exclude_patterns: Gitignore-style paths to omit, for example ``["tests/", "*.md"]``.baseline: Recent commits to sample for percentile ranking; 0 disables it."""+ if repo == "all":+ return _unsupported_repo_all("get_change_risk")ctx = await _resolve_repo_context(repo)+ started = time.perf_counter()try:result = await asyncio.to_thread(score_live_change,@@ -54,5 +59,20 @@ async def get_change_risk(except ValueError as exc:return {"error": str(exc)}except subprocess.CalledProcessError as exc:- return {"error": f"Could not read change {revspec!r}: {exc.stderr or exc}"}- return change_risk_payload(result)+ detail = (exc.stderr or "").strip() or str(exc)+ return {"error": f"Could not read change {revspec!r}: {detail}"}+ except subprocess.TimeoutExpired:+ return {"error": f"git timed out reading change {revspec!r}."}+ payload = change_risk_payload(result)+ if result.features.nf == 0:+ payload["warning"] = (+ f"No counted file changes in {revspec!r} "+ "(check the revspec, extensions, or exclusion filters)."+ )+ # source: live_git marks that this response is computed from the working+ # checkout's git, not the index, so index freshness does not apply to it.+ payload["_meta"] = _build_meta(+ timing_ms=(time.perf_counter() - started) * 1000,+ extra={"source": "live_git"},+ )+ return payloaddiff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.pyindex cbc2ec699..996e1eeb5 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py@@ -44,6 +44,8 @@ async def get_risk((will_break, missing_cochanges, missing_tests, tests_to_run) — read itfirst. tests_to_run is coverage-backed: the tests the per-test map provesexercise the changed files, empty when no coverage map is ingested.+ To score a live commit or ``base..head`` diff by revspec instead of file+ paths, use ``get_change_risk``.Args:targets: file paths to assess.diff --git a/tests/unit/analysis/test_change_risk.py b/tests/unit/analysis/test_change_risk.pyindex a941092de..24166087b 100644--- a/tests/unit/analysis/test_change_risk.py+++ b/tests/unit/analysis/test_change_risk.py@@ -16,6 +16,7 @@ from repowise.core.analysis.change_risk import (extract_range_features,features_from_file_changes,score_change,+ score_live_change,)from repowise.core.analysis.change_risk.model import _CONSTANTS, _sigmoid@@ -278,3 +279,42 @@ def test_score_change_on_real_commit(git_repo: Path) -> None:assert 0.0 <= risk.score <= 10.0assert risk.features is fassert not math.isnan(risk.probability)+++def test_extract_commit_features_bad_revspec_raises(git_repo: Path) -> None:+ # A bogus revspec must raise (git returns nonzero), not silently produce an+ # all-zero feature vector that scores as a low-risk change.+ with pytest.raises(subprocess.CalledProcessError):+ extract_commit_features(str(git_repo), "no-such-ref")+++def test_score_live_change_bad_revspec_raises(git_repo: Path) -> None:+ with pytest.raises(subprocess.CalledProcessError):+ score_live_change(str(git_repo), "no-such-ref", baseline=0)+++def test_score_live_change_rejects_negative_baseline(git_repo: Path) -> None:+ with pytest.raises(ValueError, match="baseline"):+ score_live_change(str(git_repo), "HEAD", baseline=-1)+++def test_score_live_change_three_dot_range_is_valid(git_repo: Path) -> None:+ base = subprocess.run(+ ["git", "rev-parse", "HEAD"], cwd=git_repo, check=True, capture_output=True, text=True+ ).stdout.strip()+ _commit(git_repo, {"r/a.py": "a=1\n"}, "feat: a", author="Dev")+ # Three-dot syntax (base...HEAD) must degrade to a valid anchor rather than+ # leaving a leading dot that git rejects as a ref.+ result = score_live_change(str(git_repo), f"{base}...HEAD", baseline=0)+ assert result.features.nf == 1+ assert result.features.ref == f"{base}..HEAD"+++def test_score_live_change_below_min_baseline_yields_no_percentile(git_repo: Path) -> None:+ # A shallow repo (fewer than the 8-commit floor) can't produce a+ # representative percentile, so it degrades to no ranking, not a wrong one.+ _commit(git_repo, {"a.py": "a=1\n"}, "feat: a", author="Dev")+ result = score_live_change(str(git_repo), "HEAD", baseline=200)+ assert result.baseline_sample_size < 8+ assert result.percentile is None+ assert result.priority is Nonediff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.pyindex 77d8b02bf..ffda42c71 100644--- a/tests/unit/server/mcp/test_change_risk.py+++ b/tests/unit/server/mcp/test_change_risk.py@@ -64,3 +64,58 @@ async def test_get_change_risk_honors_riskignore_and_request_filters(tmp_path, massert result["review_priority"] is Noneassert result["classification"] is Noneassert result["baseline_sample_size"] == 0+ # Live-git responses carry a _meta envelope flagged as index-independent.+ assert result["_meta"]["source"] == "live_git"+ assert "warning" not in result+++async def test_get_change_risk_bad_revspec_returns_error(tmp_path, monkeypatch) -> None:+ repo = tmp_path / "repo"+ repo.mkdir()+ _git(["init", "-q"], repo)+ _commit(repo, {"README.md": "# seed\n"}, "chore: seed")++ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")++ async def _context(_: str | None) -> SimpleNamespace:+ return SimpleNamespace(path=str(repo))++ monkeypatch.setattr(module, "_resolve_repo_context", _context)+ result = await module.get_change_risk(revspec="does-not-exist", baseline=0)++ # A bogus revspec must surface an error, not a silent zero-risk score.+ assert "error" in result+ assert "does-not-exist" in result["error"]+ assert "score" not in result+++async def test_get_change_risk_empty_diff_warns(tmp_path, monkeypatch) -> None:+ repo = tmp_path / "repo"+ repo.mkdir()+ _git(["init", "-q"], repo)+ _commit(repo, {"README.md": "# seed\n"}, "chore: seed")+ _commit(repo, {"app.py": "value = 1\n"}, "feat: app")++ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")++ async def _context(_: str | None) -> SimpleNamespace:+ return SimpleNamespace(path=str(repo))++ monkeypatch.setattr(module, "_resolve_repo_context", _context)+ # Only a .py change exists; restricting to .md counts zero files.+ result = await module.get_change_risk(extensions=["md"], baseline=0)++ assert result["features"]["nf"] == 0+ assert "warning" in result+ assert "no counted file changes" in result["warning"].lower()+++async def test_get_change_risk_rejects_repo_all() -> None:+ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")+ result = await module.get_change_risk(repo="all")++ assert "error" in result+ assert "get_change_risk" in result["error"]