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.

refactor(risk): score the range endpoint through the shared facade (#2268)

Raghav Chamadiya591a67e46545
diff --git a/packages/core/src/repowise/core/analysis/change_risk/__init__.py b/packages/core/src/repowise/core/analysis/change_risk/__init__.py
index d4da46037..ecf79e45c 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/__init__.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/__init__.py
@@ -32,6 +32,7 @@ from .model import SCORE_MEASURES, SCORE_UNIT, ChangeRisk, RiskDriver, score_cha
from .normalize import RiskNormalizer, review_priority_classification
from .service import (
ChangeRiskResult,
+ assess_change,
change_risk_payload,
normalize_extensions,
range_anchor,
@@ -50,6 +51,7 @@ __all__ = [
"FixHistoryUnavailableError",
"RiskDriver",
"RiskNormalizer",
+ "assess_change",
"baseline_samples",
"change_features_from_stored",
"change_fix_density",
diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.py
index e17f695c3..288be7298 100644
--- a/packages/server/src/repowise/server/routers/git.py
+++ b/packages/server/src/repowise/server/routers/git.py
@@ -6,7 +6,6 @@ import json
import os
import subprocess
from collections import Counter
-from dataclasses import replace
from datetime import datetime, timedelta
from fastapi import APIRouter, Depends, HTTPException, Query
@@ -16,17 +15,14 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.change_risk import (
SCORE_MEASURES,
SCORE_UNIT,
- BaselineSample,
FixHistoryUnavailableError,
RiskNormalizer,
+ assess_change,
baseline_samples,
change_features_from_stored,
- change_fix_density,
densities_excluding,
extract_range_features,
- fix_density_percentile,
fix_pressure,
- hot_files,
range_anchor,
review_priority_classification,
score_change,
@@ -68,10 +64,6 @@ from repowise.server.schemas import (
from repowise.server.services.module_health import top_level_module
from repowise.server.services.reviewer_suggestions import suggest_reviewers
-# Below this many sampled commits a percentile isn't worth showing; mirrors
-# the CLI's ``repowise risk`` threshold so the two surfaces agree.
-_MIN_BASELINE = 8
-
router = APIRouter(
prefix="/api/repos",
tags=["git"],
@@ -701,43 +693,34 @@ def get_risk_range(
status_code=400, detail=f"Could not read range {base!r}..{head!r}: {exc}"
) from exc
- risk = score_change(features)
-
- percentile: float | None = None
- priority: str | None = None
- samples: list[BaselineSample] = []
- if baseline:
- # Same anchor rule as the CLI/MCP scorer, so both surfaces rank a range
- # against the history it forked from rather than against its own commits.
- samples = baseline_samples(local_path, range_anchor(local_path, base, head), baseline, ())
- scores = scores_excluding(samples, "")
- if len(scores) >= _MIN_BASELINE:
- normalizer = RiskNormalizer.from_scores(scores)
- # Rank with experience unknown, matching the baseline (diff-shape
- # percentile within the repo), keeping the comparison like-with-like.
- rank_score = score_change(replace(features, exp=None)).score
- percentile = normalizer.percentile(rank_score)
- priority = normalizer.priority(rank_score)
-
- # Read at the fork point, matching the CLI/MCP scorer: the record predates
- # the change rather than counting fixes the range itself brought in.
+ # The fork point anchors both the baseline cohort and the fix record, so a
+ # range is ranked against the history it forked from and is never credited
+ # with fixes it brought in itself.
+ anchor = range_anchor(local_path, base, head)
+ samples = baseline_samples(local_path, anchor, baseline, ()) if baseline else []
try:
- pressure = fix_pressure(local_path, range_anchor(local_path, base, head))
- fix_available = True
+ pressure: dict[str, float] | None = fix_pressure(local_path, anchor)
except FixHistoryUnavailableError:
- pressure, fix_available = {}, False
- density = change_fix_density(pressure, features.file_churn)
+ pressure = None
+
+ assessed = assess_change(
+ features,
+ fix_pressure=pressure,
+ baseline_scores=scores_excluding(samples, ""),
+ baseline_fix_densities=densities_excluding(samples, "", pressure or {}),
+ )
+ risk, percentile, priority = assessed.risk, assessed.percentile, assessed.priority
return RiskRangeResponse(
base=base,
head=head,
fix_history=FixHistoryResponse(
- available=fix_available,
- density=round(density, 3),
- percentile=fix_density_percentile(densities_excluding(samples, "", pressure), density),
+ available=assessed.fix_history_available,
+ density=assessed.fix_density,
+ percentile=assessed.fix_percentile,
files=[
FixHistoryFileResponse(path=path, churn=churn, fix_pressure=p)
- for path, churn, p in hot_files(pressure, features.file_churn)
+ for path, churn, p in assessed.hot_files
],
),
risk_authority=change_risk_authority(),
diff --git a/packages/types/src/blast-radius.ts b/packages/types/src/blast-radius.ts
index 7acb237f0..1507690c0 100644
--- a/packages/types/src/blast-radius.ts
+++ b/packages/types/src/blast-radius.ts
@@ -74,7 +74,11 @@ export interface TestImpactResponse {
recommendations_by_primary_basis: Record<TestRecommendationBasis, number>;
files: Array<{
source_file: string;
- status: "measured" | "inferred" | "unknown";
+ status: "measured" | "inferred" | "unknown" | "deleted";
+ /** The path's transition, when the caller supplied one. */
+ change_status?: string | null;
+ /** False for a path the change deletes: it has no head side to cover. */
+ head_present?: boolean;
measured_tests: string[];
measured_tests_total: number;
inferred_tests: string[];
@@ -83,6 +87,8 @@ export interface TestImpactResponse {
files_total: number;
files_without_measured_tests: string[];
unknown_files: string[];
+ /** Changed paths the change deletes. Not a coverage gap. */
+ deleted_files?: string[];
coverage: {
status: "available" | "partial" | "unavailable" | "degraded";
reason: string | null;
diff --git a/tests/unit/server/test_risk_range.py b/tests/unit/server/test_risk_range.py
index 3134e6e1a..81a618279 100644
--- a/tests/unit/server/test_risk_range.py
+++ b/tests/unit/server/test_risk_range.py
@@ -179,3 +179,49 @@ def test_scores_excluding_omits_target_ref(git_repo: Path) -> None:
assert len(scores_excluding(samples, head)) == 1
assert len(scores_excluding(samples, head[:7])) == 1
assert len(scores_excluding(samples, "")) == 2
+
+
+async def test_route_scores_through_the_shared_facade(
+ client: AsyncClient, git_repo: Path, tmp_path: Path
+) -> None:
+ """The route must not carry its own copy of the scoring composition.
+
+ It once repeated the features -> score -> fix-history -> baseline sequence
+ inline, with comments saying it matched the other surfaces. Two copies that
+ agree only by comment drift the first time one is edited, so this pins the
+ route's numbers to the facade every other surface uses.
+ """
+ from repowise.core.analysis.change_risk import (
+ assess_change,
+ extract_range_features,
+ fix_pressure,
+ range_anchor,
+ )
+
+ repo = await create_test_repo(client, tmp_path)
+ _commit(git_repo, {"src/f.py": "a = 1\nb = 2\n"}, "feat: f")
+ _commit(git_repo, {"src/g.py": "c = 3\n"}, "fix: crash")
+
+ response = await client.get(
+ f"/api/repos/{repo['id']}/risk/range",
+ params={"base": "HEAD~2", "head": "HEAD"},
+ )
+ assert response.status_code == 200
+ body = response.json()
+
+ anchor = range_anchor(str(git_repo), "HEAD~2", "HEAD")
+ samples = baseline_samples(str(git_repo), anchor, 200, ())
+ pressure = fix_pressure(str(git_repo), anchor)
+ expected = assess_change(
+ extract_range_features(str(git_repo), "HEAD~2", "HEAD"),
+ fix_pressure=pressure,
+ baseline_scores=scores_excluding(samples, ""),
+ baseline_fix_densities=densities_excluding(samples, "", pressure),
+ )
+
+ assert body["score"] == expected.risk.score
+ assert body["risk_percentile"] == expected.percentile
+ assert body["review_priority"] == expected.priority
+ assert body["fix_history"]["density"] == expected.fix_density
+ assert body["fix_history"]["percentile"] == expected.fix_percentile
+ assert body["fix_history"]["available"] == expected.fix_history_available