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(health): add just-in-time change-risk scoring + `repowise risk` (#315)

Raghav Chamadiya4086fba66b0b
diff --git a/docs/CHANGE_RISK.md b/docs/CHANGE_RISK.md
new file mode 100644
index 000000000..d9a0a6ec9
--- /dev/null
+++ b/docs/CHANGE_RISK.md
@@ -0,0 +1,52 @@
+# Change risk (`repowise risk`)
+
+`repowise risk` scores a **change** — a commit or a `base..head` range — for
+defect risk from the shape of its diff, not the health of any file. It is a
+just-in-time / pre-merge signal: complementary to `repowise health` (which
+scores files), and useful as a PR gate because it fires on risky *small* changes
+a file-level delta misses.
+
+```bash
+repowise risk # score HEAD
+repowise risk abc123 # score a single commit
+repowise risk main..HEAD # score a branch / PR range as one change
+repowise risk main..HEAD --ext .py # count only .py files
+repowise risk --format json # machine-readable
+```
+
+It runs in-process: pure `git` + learned constants. **No LLM, no network, and no
+blame at runtime** — SZZ labelling lives entirely in the offline calibration.
+
+## What it measures
+
+The model uses Kamei-style *change* metrics (Kamei et al., "A large-scale
+empirical study of just-in-time quality assurance"):
+
+| Feature | Meaning |
+|---------|---------|
+| `la`, `ld` | lines added / deleted |
+| `nf` | files touched |
+| `nd`, `ns` | distinct directories / top-level subsystems touched |
+| `entropy` | Shannon entropy of the per-file churn distribution (diffusion) |
+| `exp` | author's prior commit count (experience); unknown → scored neutrally |
+
+These are properties of the *diff*, so the score is a change-level signal rather
+than a file-size proxy. The risk is a plain L2-logistic over standardized,
+log-compressed features — `logit = intercept + Σ coefᵢ·zᵢ` — so every feature's
+push on the risk is exact and reported as an attributable driver (the same
+linear / per-finding-attributable contract the file health score holds).
+
+## Calibration & accuracy
+
+Constants are learned offline against the defect corpus (AG-SZZ bug-inducing
+commits as labels, time-ordered evaluation with a right-censoring gap, and a
+leave-one-repo-out comparison to the churn-only baseline). On a 7-repo,
+5-language slice the pooled leave-one-repo-out AUC is **0.772 vs 0.766 for
+churn-only** (Δ +0.0068, 95% CI [-0.0003, +0.0131]) — competitive with churn
+across the corpus and stronger on some repos (clap +0.053 on a time-ordered
+split). Diff size dominates the fit, with change entropy risky and author
+experience protective, both literature-consistent. Only the learned constants
+ship; the runtime stays deterministic and zero-LLM.
+
+Recalibrate via `repowise-bench/health-defect/jit_calibration.py`; the constants
+live in `packages/core/src/repowise/core/analysis/change_risk/model.py`.
diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.py
new file mode 100644
index 000000000..7cbc7e514
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py
@@ -0,0 +1,138 @@
+"""``repowise risk`` — just-in-time change-risk for a commit or diff range.
+
+Scores a *change* (not a file) from its diff shape — size, diffusion, author
+familiarity — and prints a 0-10 risk with an attributable breakdown. Runs
+in-process: pure git + learned constants, no LLM, no network. A natural
+pre-merge / PR gate, complementary to ``repowise health`` (which scores files).
+
+Examples:
+ repowise risk # score HEAD
+ repowise risk abc123 # score a single commit
+ repowise risk main..HEAD # score a branch / PR range as one change
+"""
+
+from __future__ import annotations
+
+import json
+
+import click
+from rich.table import Table
+
+from repowise.cli.helpers import console, err_console
+
+
[email protected]("revspec", required=False, default="HEAD")
+ "--path",
+ "repo_path",
+ default=".",
+ type=click.Path(exists=True, file_okay=False),
+ help="Path to the git repository (default: current directory).",
+)
+ "--ext",
+ "ext",
+ default=None,
+ help="Comma-separated file suffixes to count (e.g. '.py' or '.ts,.tsx'). "
+ "Default: count every changed file.",
+)
+ "--format",
+ "fmt",
+ default="table",
+ type=click.Choice(["table", "json"]),
+ help="Output format.",
+)
+def risk_command(revspec: str, repo_path: str, ext: str | None, fmt: str) -> None:
+ """Score the defect risk of a change (commit or ``base..head`` range)."""
+ from repowise.core.analysis.change_risk import (
+ extract_commit_features,
+ extract_range_features,
+ score_change,
+ )
+
+ extensions = tuple(e if e.startswith(".") else f".{e}" for e in ext.split(",")) if ext else ()
+ status = err_console if fmt != "table" else console
+
+ try:
+ if ".." in revspec:
+ base, _, head = revspec.partition("..")
+ head = head or "HEAD"
+ features = extract_range_features(repo_path, base, head, extensions=extensions)
+ else:
+ features = extract_commit_features(repo_path, revspec, extensions=extensions)
+ except Exception as exc:
+ # Surface git errors (bad revspec, not a repo) as a clean CLI message.
+ raise click.ClickException(
+ f"Could not read change {revspec!r} in {repo_path}: {exc}"
+ ) from exc
+
+ if features.nf == 0:
+ status.print(
+ f"[yellow]No counted file changes in {revspec!r} "
+ f"(check the revspec or --ext filter).[/yellow]"
+ )
+
+ risk = score_change(features)
+
+ if fmt == "json":
+ click.echo(
+ json.dumps(
+ {
+ "ref": features.ref,
+ "score": risk.score,
+ "probability": round(risk.probability, 4),
+ "level": risk.level,
+ "is_fix": features.is_fix,
+ "features": {
+ "la": features.la,
+ "ld": features.ld,
+ "nf": features.nf,
+ "nd": features.nd,
+ "ns": features.ns,
+ "entropy": round(features.entropy, 4),
+ "exp": features.exp,
+ },
+ "drivers": [
+ {
+ "feature": d.feature,
+ "value": d.value,
+ "contribution": round(d.contribution, 4),
+ "label": d.label,
+ }
+ for d in risk.top_drivers
+ ],
+ },
+ indent=2,
+ )
+ )
+ return
+
+ color = {"high": "red", "moderate": "yellow", "low": "green"}[risk.level]
+ console.print(
+ f"\n[bold]Change risk[/bold] for [cyan]{features.ref}[/cyan]: "
+ f"[{color}]{risk.score:.1f}/10[/{color}] ({risk.level})"
+ )
+ if features.subject:
+ console.print(f" [dim]{features.subject}[/dim]")
+ console.print(
+ f" +{features.la} / -{features.ld} lines · {features.nf} files · "
+ f"{features.nd} dirs · {features.ns} subsystems · "
+ f"entropy {features.entropy:.2f} · author exp {features.exp}"
+ + (" [magenta](fix)[/magenta]" if features.is_fix else "")
+ )
+
+ table = Table(title="Risk drivers (signed contribution to the change-risk)")
+ table.add_column("Driver")
+ table.add_column("Value", justify="right")
+ table.add_column("Push", justify="right")
+ for d in risk.top_drivers:
+ push_color = "red" if d.contribution > 0 else "green"
+ sign = "+" if d.contribution >= 0 else ""
+ table.add_row(
+ d.label,
+ f"{d.value:g}",
+ f"[{push_color}]{sign}{d.contribution:.2f}[/{push_color}]",
+ )
+ console.print(table)
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index 5e99f8a9d..1c7bea599 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -18,6 +18,7 @@ from repowise.cli.commands.hook_cmd import hook_group
from repowise.cli.commands.init_cmd import init_command
from repowise.cli.commands.mcp_cmd import mcp_command
from repowise.cli.commands.reindex_cmd import reindex_command
+from repowise.cli.commands.risk_cmd import risk_command
from repowise.cli.commands.search_cmd import search_command
from repowise.cli.commands.serve_cmd import serve_command
from repowise.cli.commands.status_cmd import status_command
@@ -57,6 +58,7 @@ register_command(costs_command)
register_command(update_command)
register_command(dead_code_command)
register_command(health_command)
+register_command(risk_command)
register_command(decision_group)
register_command(search_command)
register_command(export_command)
diff --git a/packages/core/src/repowise/core/analysis/change_risk/__init__.py b/packages/core/src/repowise/core/analysis/change_risk/__init__.py
new file mode 100644
index 000000000..792a0fa02
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/change_risk/__init__.py
@@ -0,0 +1,28 @@
+"""Just-in-time change-risk scoring.
+
+Scores a *change* (a commit or a ``base..head`` range) for defect risk from its
+diff shape — size, diffusion, authorship — using a linear, interpretable model
+with offline-calibrated constants. Complements the file-level health score: it
+is not size-dominated, so it flags risky *small* changes the file delta misses,
+and is a natural pre-merge / PR gate.
+"""
+
+from __future__ import annotations
+
+from .features import (
+ ChangeFeatures,
+ extract_commit_features,
+ extract_range_features,
+ features_from_file_changes,
+)
+from .model import ChangeRisk, RiskDriver, score_change
+
+__all__ = [
+ "ChangeFeatures",
+ "ChangeRisk",
+ "RiskDriver",
+ "extract_commit_features",
+ "extract_range_features",
+ "features_from_file_changes",
+ "score_change",
+]
diff --git a/packages/core/src/repowise/core/analysis/change_risk/features.py b/packages/core/src/repowise/core/analysis/change_risk/features.py
new file mode 100644
index 000000000..b9cd3b760
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/change_risk/features.py
@@ -0,0 +1,224 @@
+"""Change-feature extraction for just-in-time (commit/PR-level) risk.
+
+Computes Kamei-style change metrics from a git diff — the size, diffusion and
+authorship of a *change*, not the size of any one file — so the resulting risk
+signal sidesteps the file-size confound that dominates the file-level health
+score and is directly useful as a pre-merge gate.
+
+Pure ``git`` subprocess walking (no new dependency, deterministic). The runtime
+scores a *live* diff and never blames: SZZ labelling lives entirely in the
+offline calibration. Two entry points:
+
+* :func:`extract_commit_features` — features of a single commit.
+* :func:`extract_range_features` — features of a ``base..head`` range scored as
+ one cumulative change (the "score this PR" case).
+"""
+
+from __future__ import annotations
+
+import math
+import subprocess
+from collections.abc import Iterable
+from dataclasses import dataclass
+
+from ...ingestion.git_indexer._constants import is_fix_commit
+
+
+@dataclass
+class ChangeFeatures:
+ """Kamei change metrics for one change (a commit or a base..head range)."""
+
+ la: int # lines added
+ ld: int # lines deleted
+ nf: int # files touched
+ nd: int # distinct directories touched
+ ns: int # distinct top-level subsystems touched
+ entropy: float # Shannon entropy of the per-file churn distribution
+ # Author's prior commit count (experience). ``None`` = unknown (e.g. a
+ # diff-only caller with no git history); the scorer treats unknown as a
+ # neutral, no-push feature rather than imputing inexperience.
+ exp: int | None
+ # Informational only (NOT model features) — surfaced in the breakdown.
+ is_fix: bool = False
+ author: str = ""
+ subject: str = ""
+ ref: str = "" # the commit sha or "base..head" range scored
+
+
+def _git(args: list[str], cwd: str) -> str:
+ return subprocess.run(
+ ["git", *args],
+ cwd=cwd,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ ).stdout
+
+
+def _accumulate_numstat(
+ numstat: str, extensions: tuple[str, ...]
+) -> tuple[int, int, int, set[str], set[str], list[int]]:
+ la = ld = nf = 0
+ dirs: set[str] = set()
+ subs: set[str] = set()
+ per_file: list[int] = []
+ for row in numstat.strip().split("\n"):
+ if not row:
+ continue
+ parts = row.split("\t")
+ if len(parts) != 3:
+ continue
+ a_raw, d_raw, path = parts
+ if extensions and not path.endswith(extensions):
+ continue
+ a = int(a_raw) if a_raw.isdigit() else 0
+ d = int(d_raw) if d_raw.isdigit() else 0
+ la += a
+ ld += d
+ nf += 1
+ churn = a + d
+ if churn:
+ per_file.append(churn)
+ segs = path.split("/")
+ dirs.add("/".join(segs[:-1]))
+ subs.add(segs[0])
+ return la, ld, nf, dirs, subs, per_file
+
+
+def _entropy(per_file: list[int]) -> float:
+ """Shannon entropy of the per-file churn distribution (diffusion)."""
+ total = sum(per_file)
+ if total <= 0 or len(per_file) < 2:
+ return 0.0
+ return -sum((p / total) * math.log2(p / total) for p in per_file if p > 0)
+
+
+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
+ out = _git(
+ ["rev-list", "--count", "--author", author, "--no-merges", upto_ref],
+ repo_path,
+ ).strip()
+ try:
+ return int(out)
+ except ValueError:
+ return 0
+
+
+def features_from_file_changes(
+ changes: Iterable[tuple[str, int, int]],
+ *,
+ exp: int | None = None,
+ is_fix: bool = False,
+ author: str = "",
+ subject: str = "",
+ ref: str = "",
+) -> ChangeFeatures:
+ """Build :class:`ChangeFeatures` from a list of ``(path, additions, deletions)``.
+
+ The diff-only entry point — for callers that already have a change's file
+ list (e.g. a GitHub PR's ``files`` payload) and no local git checkout to
+ walk. *exp* (author experience) cannot be derived from a diff, so the caller
+ supplies it; leave it ``None`` when unknown (the scorer then treats it as a
+ neutral feature rather than imputing inexperience).
+ """
+ la = ld = nf = 0
+ dirs: set[str] = set()
+ subs: set[str] = set()
+ per_file: list[int] = []
+ for path, additions, deletions in changes:
+ a = max(int(additions or 0), 0)
+ d = max(int(deletions or 0), 0)
+ la += a
+ ld += d
+ nf += 1
+ churn = a + d
+ if churn:
+ per_file.append(churn)
+ segs = path.split("/")
+ dirs.add("/".join(segs[:-1]))
+ subs.add(segs[0])
+ return ChangeFeatures(
+ la=la,
+ ld=ld,
+ nf=nf,
+ nd=len(dirs),
+ ns=len(subs),
+ entropy=_entropy(per_file),
+ exp=exp,
+ is_fix=is_fix,
+ author=author,
+ subject=subject,
+ ref=ref,
+ )
+
+
+def extract_commit_features(
+ repo_path: str,
+ sha: str,
+ *,
+ extensions: tuple[str, ...] = (),
+) -> ChangeFeatures:
+ """Extract change features for a single commit.
+
+ *extensions* optionally restricts the counted files to a set of suffixes
+ (e.g. ``(".py",)``); empty means count every changed file.
+ """
+ meta = _git(["show", "-s", "--format=%an%x00%s", sha], repo_path).strip("\n")
+ author, _, subject = meta.partition("\x00")
+ numstat = _git(["show", sha, "--numstat", "--format="], repo_path)
+ la, ld, nf, dirs, subs, per_file = _accumulate_numstat(numstat, extensions)
+ parent = _git(["rev-parse", "--verify", "--quiet", f"{sha}^"], repo_path).strip()
+ exp = _author_experience(repo_path, author, parent or sha)
+ return ChangeFeatures(
+ la=la,
+ ld=ld,
+ nf=nf,
+ nd=len(dirs),
+ ns=len(subs),
+ entropy=_entropy(per_file),
+ exp=exp,
+ is_fix=is_fix_commit(subject),
+ author=author,
+ subject=subject,
+ ref=sha,
+ )
+
+
+def extract_range_features(
+ repo_path: str,
+ base: str,
+ head: str,
+ *,
+ extensions: tuple[str, ...] = (),
+) -> ChangeFeatures:
+ """Extract features for a ``base..head`` range scored as one change.
+
+ Diff size/diffusion come from the cumulative ``base..head`` diff; author and
+ fix-flag come from the head commit; experience is the head author's prior
+ commit count at *base*.
+ """
+ numstat = _git(["diff", "--numstat", f"{base}..{head}"], repo_path)
+ la, ld, nf, dirs, subs, per_file = _accumulate_numstat(numstat, extensions)
+ meta = _git(["show", "-s", "--format=%an%x00%s", head], repo_path).strip("\n")
+ author, _, subject = meta.partition("\x00")
+ # Any fix commit in the range marks the change as a fix (informational).
+ range_subjects = _git(["log", "--format=%s", f"{base}..{head}"], repo_path)
+ is_fix = any(is_fix_commit(s) for s in range_subjects.split("\n") if s)
+ exp = _author_experience(repo_path, author, base)
+ return ChangeFeatures(
+ la=la,
+ ld=ld,
+ nf=nf,
+ nd=len(dirs),
+ ns=len(subs),
+ entropy=_entropy(per_file),
+ exp=exp,
+ is_fix=is_fix,
+ author=author,
+ subject=subject,
+ ref=f"{base}..{head}",
+ )
diff --git a/packages/core/src/repowise/core/analysis/change_risk/model.py b/packages/core/src/repowise/core/analysis/change_risk/model.py
new file mode 100644
index 000000000..921c6399f
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/change_risk/model.py
@@ -0,0 +1,157 @@
+"""Linear, interpretable change-risk model.
+
+Scores a :class:`ChangeFeatures` vector to a 0-10 change-risk plus a fully
+attributable per-feature breakdown. The model is a plain L2-logistic over
+standardized, log-compressed change features — the same per-finding-attributable
+contract the file health score holds: the logit is a linear sum of per-feature
+contributions, so each feature's push on the risk is exact and explainable. No
+LLM, no network, no blame at runtime — only learned constants ship.
+
+Constants are calibrated offline (``repowise-bench/health-defect/
+jit_calibration.py``: AG-SZZ bug-inducing commits as labels, time-ordered
+evaluation, right-censoring gap, leave-one-repo-out vs the churn-only baseline)
+and pasted into ``_CONSTANTS`` below. Regenerate them there if the corpus moves.
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass, field
+
+from .features import ChangeFeatures
+
+# Calibrated offline (2026-05-30) on a 7-repo, 5-language slice of the corpus
+# (clap, pydantic, fd, gin, fastify, bat, chi; AG-SZZ bug-inducing commits as
+# labels, gap_days=120 right-censoring, pooled L2-logistic over the genuinely
+# runtime-available features — age_days is excluded as a label-availability
+# artifact). Generated by repowise-bench/health-defect/jit_calibration.py.
+# Generalization (leave-one-repo-out pooled OOF, n=4102, 662 inducing): model
+# AUC 0.772 vs churn-only baseline 0.766 (Δ +0.0068 [95% CI -0.0003, +0.0131]) —
+# competitive with churn corpus-wide and stronger on some repos (clap +0.053
+# time-split). Diff size (la) dominates, with entropy risky (+) and author
+# experience protective (-), both literature-consistent; the small negative
+# nf/nd/ns coefficients are collinearity with la (size), kept as fit. Order
+# matters: features / log1p / mean / std / coef are parallel arrays.
+_CONSTANTS: dict[str, object] = {
+ "features": ["la", "ld", "nf", "nd", "ns", "entropy", "exp"],
+ "log1p": [True, True, True, True, True, False, True],
+ "mean": [2.443, 1.723, 1.006, 0.795, 0.806, 0.537, 3.011],
+ "std": [1.414, 1.380, 0.465, 0.237, 0.285, 0.776, 2.270],
+ "coef": [1.1241, 0.0151, -0.1103, -0.0310, -0.0672, 0.1483, -0.0702],
+ "intercept": -0.3797,
+}
+
+# Human-readable driver labels, keyed by whether the feature is ABOVE its
+# typical value — (above-typical phrase, below-typical phrase). The label
+# describes the change's shape (a fact); the signed contribution + colour convey
+# whether that pushed risk up or down, so a collinear coefficient sign never
+# mislabels the feature itself.
+_FEATURE_LABELS: dict[str, tuple[str, str]] = {
+ "la": ("large diff (many lines added)", "small diff"),
+ "ld": ("many lines deleted", "few deletions"),
+ "nf": ("touches many files", "narrow file footprint"),
+ "nd": ("spread across many directories", "localized to few directories"),
+ "ns": ("spans multiple subsystems", "single subsystem"),
+ "entropy": ("scattered, high-entropy change", "focused change"),
+ "exp": ("experienced author", "low author familiarity with the code"),
+}
+
+
+@dataclass
+class RiskDriver:
+ """One feature's contribution to the change-risk logit."""
+
+ feature: str
+ value: float # raw feature value
+ contribution: float # signed push on the logit (coef * standardized value)
+ label: str # human-readable explanation
+
+
+@dataclass
+class ChangeRisk:
+ """Result of scoring a change."""
+
+ score: float # 0-10 (10 * predicted probability)
+ probability: float # calibrated logistic probability
+ level: str # "low" | "moderate" | "high"
+ drivers: list[RiskDriver] = field(default_factory=list)
+ features: ChangeFeatures | None = None
+
+ @property
+ def top_drivers(self) -> list[RiskDriver]:
+ """Drivers sorted by absolute contribution (strongest first)."""
+ return sorted(self.drivers, key=lambda d: -abs(d.contribution))
+
+
+def _sigmoid(z: float) -> float:
+ if z >= 0:
+ return 1.0 / (1.0 + math.exp(-z))
+ e = math.exp(z)
+ return e / (1.0 + e)
+
+
+def _level(score: float) -> str:
+ if score >= 7.0:
+ return "high"
+ if score >= 4.0:
+ return "moderate"
+ return "low"
+
+
+def score_change(features: ChangeFeatures) -> ChangeRisk:
+ """Score a :class:`ChangeFeatures` vector → :class:`ChangeRisk`.
+
+ Linear and attributable: ``logit = intercept + Σ coef_i · z_i`` where
+ ``z_i`` is the standardized (optionally log1p'd) feature, and each
+ ``coef_i · z_i`` is reported as a :class:`RiskDriver`.
+ """
+ cols: list[str] = _CONSTANTS["features"] # type: ignore[assignment]
+ log1p: list[bool] = _CONSTANTS["log1p"] # type: ignore[assignment]
+ mean: list[float] = _CONSTANTS["mean"] # type: ignore[assignment]
+ std: list[float] = _CONSTANTS["std"] # type: ignore[assignment]
+ coef: list[float] = _CONSTANTS["coef"] # type: ignore[assignment]
+ intercept: float = float(_CONSTANTS["intercept"]) # type: ignore[arg-type]
+
+ logit = intercept
+ drivers: list[RiskDriver] = []
+ for i, name in enumerate(cols):
+ raw = getattr(features, name)
+ if raw is None:
+ # Unknown feature (e.g. author experience on a diff-only caller):
+ # contribute nothing rather than impute, and say so.
+ drivers.append(
+ RiskDriver(
+ feature=name,
+ value=float("nan"),
+ contribution=0.0,
+ label=f"{name} (unknown)",
+ )
+ )
+ continue
+ raw = float(raw)
+ x = math.log1p(raw) if log1p[i] else raw
+ s = std[i] if std[i] else 1.0
+ z = (x - mean[i]) / s
+ contribution = coef[i] * z
+ logit += contribution
+ above, below = _FEATURE_LABELS.get(name, (name, name))
+ # Label describes the feature's STATE (above/below typical); the signed
+ # contribution carries the risk direction.
+ drivers.append(
+ RiskDriver(
+ feature=name,
+ value=raw,
+ contribution=contribution,
+ label=above if x >= mean[i] else below,
+ )
+ )
+
+ prob = _sigmoid(logit)
+ score = round(10.0 * prob, 1)
+ return ChangeRisk(
+ score=score,
+ probability=prob,
+ level=_level(score),
+ drivers=drivers,
+ features=features,
+ )
diff --git a/tests/unit/analysis/test_change_risk.py b/tests/unit/analysis/test_change_risk.py
new file mode 100644
index 000000000..f1d1f002e
--- /dev/null
+++ b/tests/unit/analysis/test_change_risk.py
@@ -0,0 +1,213 @@
+"""Unit tests for the just-in-time change-risk model + feature extraction."""
+
+from __future__ import annotations
+
+import math
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.change_risk import (
+ ChangeFeatures,
+ extract_commit_features,
+ extract_range_features,
+ features_from_file_changes,
+ score_change,
+)
+from repowise.core.analysis.change_risk.model import _CONSTANTS, _sigmoid
+
+
+def _feat(**kw) -> ChangeFeatures:
+ base = dict(la=0, ld=0, nf=0, nd=0, ns=0, entropy=0.0, exp=0)
+ base.update(kw)
+ return ChangeFeatures(**base)
+
+
+# ---------------------------------------------------------------------------
+# Model mechanics — linear, attributable, bounded.
+# ---------------------------------------------------------------------------
+
+
+def test_score_is_bounded_and_levelled() -> None:
+ risk = score_change(_feat(la=200, ld=120, nf=30, nd=12, ns=6, entropy=4.0, exp=0))
+ assert 0.0 <= risk.probability <= 1.0
+ assert 0.0 <= risk.score <= 10.0
+ assert risk.level in {"low", "moderate", "high"}
+
+
+def test_logit_is_exact_sum_of_driver_contributions() -> None:
+ """The reported per-driver contributions must reconstruct the probability
+ exactly — the attribution is the model, not a post-hoc approximation."""
+ f = _feat(la=50, ld=10, nf=5, nd=3, ns=2, entropy=2.0, exp=8)
+ risk = score_change(f)
+ logit = float(_CONSTANTS["intercept"]) + sum(d.contribution for d in risk.drivers)
+ assert risk.probability == pytest.approx(_sigmoid(logit))
+ assert risk.score == pytest.approx(round(10.0 * _sigmoid(logit), 1))
+
+
+def test_larger_diff_scores_higher() -> None:
+ small = score_change(_feat(la=5, ld=1, nf=1, nd=1, ns=1, entropy=0.0, exp=50))
+ large = score_change(_feat(la=400, ld=200, nf=25, nd=10, ns=5, entropy=4.0, exp=50))
+ assert large.score > small.score
+
+
+def test_author_experience_is_protective() -> None:
+ """Holding the diff fixed, a more experienced author is lower risk (the
+ calibrated `exp` coefficient is negative — literature-consistent)."""
+ base = dict(la=80, ld=40, nf=8, nd=4, ns=2, entropy=3.0)
+ newcomer = score_change(_feat(**base, exp=0))
+ veteran = score_change(_feat(**base, exp=2000))
+ assert veteran.score <= newcomer.score
+ exp_driver = next(d for d in veteran.drivers if d.feature == "exp")
+ assert exp_driver.contribution < 0 # protective push
+
+
+def test_unknown_experience_is_neutral() -> None:
+ """exp=None (diff-only caller) contributes zero — no imputed inexperience."""
+ base = dict(la=80, ld=40, nf=8, nd=4, ns=2, entropy=3.0)
+ risk = score_change(_feat(**base, exp=None))
+ exp_driver = next(d for d in risk.drivers if d.feature == "exp")
+ assert exp_driver.contribution == 0.0
+ # Identical to scoring with exp omitted from the logit entirely.
+ from repowise.core.analysis.change_risk.model import _CONSTANTS, _sigmoid
+
+ logit = float(_CONSTANTS["intercept"]) + sum(
+ d.contribution for d in risk.drivers if d.feature != "exp"
+ )
+ assert risk.probability == pytest.approx(_sigmoid(logit))
+
+
+def test_top_drivers_sorted_by_magnitude() -> None:
+ risk = score_change(_feat(la=300, ld=5, nf=2, nd=1, ns=1, entropy=0.5, exp=100))
+ contribs = [abs(d.contribution) for d in risk.top_drivers]
+ assert contribs == sorted(contribs, reverse=True)
+
+
+# ---------------------------------------------------------------------------
+# Diff-only feature builder (no git repo — the bot's PR-API path).
+# ---------------------------------------------------------------------------
+
+
+def test_features_from_file_changes_aggregates_diffusion() -> None:
+ f = features_from_file_changes(
+ [
+ ("src/a.py", 10, 2),
+ ("src/sub/b.py", 4, 0),
+ ("pkg/c.py", 1, 1),
+ ],
+ exp=42,
+ is_fix=True,
+ ref="pr-123",
+ )
+ assert f.la == 15
+ assert f.ld == 3
+ assert f.nf == 3
+ assert f.ns == 2 # src, pkg
+ assert f.nd == 3 # src, src/sub, pkg
+ assert f.exp == 42
+ assert f.is_fix is True
+ assert f.entropy > 0.0
+ # The diff-only builder must score identically to the git path for the
+ # same underlying counts.
+ assert score_change(f).score == score_change(
+ ChangeFeatures(la=15, ld=3, nf=3, nd=3, ns=2, entropy=f.entropy, exp=42)
+ ).score
+
+
+# ---------------------------------------------------------------------------
+# Feature extraction from a real (tiny) git repo.
+# ---------------------------------------------------------------------------
+
+
+def _git(args: list[str], cwd: Path) -> None:
+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)
+
+
+def _commit(repo: Path, files: dict[str, str], message: str, author: str = "Tester") -> str:
+ for rel, content in files.items():
+ p = repo / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(content, encoding="utf-8")
+ _git(["add", rel], repo)
+ _git(["-c", f"user.name={author}", "-c", "[email protected]", "commit", "-m", message], repo)
+ return subprocess.run(
+ ["git", "rev-parse", "HEAD"], cwd=repo, check=True, capture_output=True, text=True
+ ).stdout.strip()
+
+
+def git_repo(tmp_path: Path) -> Path:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(["init", "-q"], repo)
+ _git(["config", "user.name", "Seed"], repo)
+ _git(["config", "user.email", "[email protected]"], repo)
+ _commit(repo, {"README.md": "# seed\n"}, "chore: seed", author="Seed")
+ return repo
+
+
+def test_extract_commit_features_counts_diffusion(git_repo: Path) -> None:
+ _commit(
+ git_repo,
+ {
+ "src/a.py": "x = 1\ny = 2\nz = 3\n",
+ "src/sub/b.py": "def f():\n return 1\n",
+ "pkg/c.py": "C = 1\n",
+ },
+ "fix: handle null input crash",
+ author="Dev",
+ )
+ f = extract_commit_features(str(git_repo), "HEAD", extensions=(".py",))
+ assert f.nf == 3
+ assert f.la == 6 # 3 + 2 + 1 added lines
+ assert f.ld == 0
+ assert f.ns == 2 # src, pkg
+ assert f.nd == 3 # src, src/sub, pkg
+ assert f.is_fix is True
+ assert f.entropy > 0.0 # churn spread across files
+
+
+def test_extract_filters_by_extension(git_repo: Path) -> None:
+ _commit(
+ git_repo,
+ {"keep.py": "a = 1\n", "skip.md": "doc\nmore\n"},
+ "feat: add thing",
+ author="Dev",
+ )
+ f = extract_commit_features(str(git_repo), "HEAD", extensions=(".py",))
+ assert f.nf == 1
+ assert f.la == 1
+ assert f.is_fix is False
+
+
+def test_author_experience_accrues(git_repo: Path) -> None:
+ _commit(git_repo, {"f1.py": "a=1\n"}, "feat: one", author="Repeat")
+ _commit(git_repo, {"f2.py": "b=2\n"}, "feat: two", author="Repeat")
+ head = _commit(git_repo, {"f3.py": "c=3\n"}, "feat: three", author="Repeat")
+ f = extract_commit_features(str(git_repo), head, extensions=(".py",))
+ # Two prior "Repeat" commits exist before HEAD.
+ assert f.exp == 2
+
+
+def test_extract_range_features_aggregates(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")
+ _commit(git_repo, {"r/b.py": "b=2\nc=3\n"}, "fix: b crash", author="Dev")
+ f = extract_range_features(str(git_repo), base, "HEAD", extensions=(".py",))
+ assert f.nf == 2
+ assert f.la == 3
+ assert f.is_fix is True # a fix commit is in the range
+ assert f.ref == f"{base}..HEAD"
+
+
+def test_score_change_on_real_commit(git_repo: Path) -> None:
+ _commit(git_repo, {"big.py": "\n".join(f"line{i} = {i}" for i in range(120)) + "\n"},
+ "feat: big drop", author="New")
+ f = extract_commit_features(str(git_repo), "HEAD", extensions=(".py",))
+ risk = score_change(f)
+ assert 0.0 <= risk.score <= 10.0
+ assert risk.features is f
+ assert not math.isnan(risk.probability)