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(risk): make every number change risk reports mean what it says (#1583)
Raghav Chamadiyad51c37708f91
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 2b8ac2f66..486a0f85a 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -426,18 +426,20 @@ shape of the live diff and needs no index refresh.| Parameter | Type | Required | Description ||-----------|------|----------|-------------|-| `revspec` | string | No | Commit or `base..head` range to score (default `"HEAD"`) |+| `revspec` | string | No | Commit or `base..head` range to score. Omit it to score uncommitted work, or pass `HEAD` when the tree is clean || `repo` | string | No | *(workspace only)* Target repo alias || `extensions` | list[string] | No | File suffixes to count, such as `[".py", ".ts"]` || `exclude_patterns` | list[string] | No | Gitignore-style paths to omit; combined with root `.riskignore` rules || `baseline` | int | No | Recent commits to sample for percentile ranking (default `200`; `0` disables percentile ranking) |-**Returns:** The corpus-calibrated `score`, `probability`, and `level`, plus a-repo-relative `risk_percentile`, `review_priority`, and `classification`.-`baseline_sample_size` reports how many filtered commits informed the percentile;-`features`, `drivers`, and combined `exclude_patterns` make the result auditable.-Use the percentile and review priority for triage; the raw score is secondary-context when no repository baseline is available.+**Returns:** A repo-relative `risk_percentile`, `review_priority`, and+`classification` — triage on these — plus the raw `score` and the `score_unit`+it is calibrated on (a single commit, so a PR-sized range reads high by+construction). `fallback_band` carries the absolute band and appears only when+no baseline was available. `working_tree` says whether uncommitted work was the+subject. `baseline_sample_size` reports how many filtered commits informed the+percentile; `features`, `drivers`, and combined `exclude_patterns` make the+result auditable.It also returns `impacted_tests`: the tests the per-test coverage map provesexecute the change's changed *lines* (line-precise, so a narrower set thandiff --git a/docs/layers/CHANGE_RISK.md b/docs/layers/CHANGE_RISK.mdindex 0e0ae8e50..da8cba80e 100644--- a/docs/layers/CHANGE_RISK.md+++ b/docs/layers/CHANGE_RISK.md@@ -7,7 +7,8 @@ scores files), and useful as a PR gate because it fires on risky *small* changesa file-level delta misses.```bash-repowise risk # score HEAD+repowise risk # score uncommitted work, else HEAD+repowise risk HEAD # score the last commitrepowise risk abc123 # score a single commitrepowise risk main..HEAD # score a branch / PR range as one changerepowise risk main..HEAD --ext .py # count only .py files@@ -18,6 +19,16 @@ repowise risk --format json # machine-readableIt runs in-process: pure `git` + learned constants. **No LLM, no network, and noblame at runtime**: SZZ labelling lives entirely in the offline calibration.+## What gets scored++With **no revspec** the subject is the change in front of you: your uncommitted+work (staged, unstaged and untracked) if the tree is dirty, otherwise `HEAD`.+The payload sets `working_tree: true` when it took that path, and the CLI says+so. Naming a revspec — `HEAD` included — always means committed refs.++A **merge commit** is scored for the diff it brought onto its first parent, so a+merged PR reads as its own content rather than as an empty change.+## Excluding pathsUse repeatable `--exclude` / `-x` flags with gitignore-style patterns to omit@@ -39,7 +50,13 @@ empirical study of just-in-time quality assurance"):| `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 is scored neutrally |+| `exp` | author's prior commit count (experience) |++`exp` is genuinely optional: when the author cannot be resolved — a diff-only+caller with no local history, or a name whose regex breaks the `git rev-list`+lookup — it is reported as `null` and contributes exactly zero to the logit.+Nothing is imputed, because `0` is a real value meaning "first ever commit" and+the model reads it as a risk-raising signal.These are properties of the *diff*, so the score is a change-level signal ratherthan a file-size proxy. The risk is a plain L2-logistic over standardized,@@ -49,20 +66,27 @@ linear / per-finding-attributable contract the file health score holds).## How to read the result-The headline signal is **repo-relative**. The raw 0–10 logistic probability is-anchored to the offline calibration corpus, so on a repo whose typical commit is-large the diff-size term dominates and the absolute band skews high: two-thirds-of commits can read "high" while ranking perfectly normally for *that* repo. The-*ranking* is sound; the absolute band is not portable.+The headline signal is **repo-relative**. The raw 0–10 score is anchored to the+offline calibration corpus, and that corpus is **individual commits** (baseline:+10.5 lines added, 1.7 files). A squash-merged PR, a `base..head` range, or any+repo whose typical commit is large is several commits' worth of diff read+against a one-commit scale, so the absolute band skews high: two-thirds of+commits can read "high" while ranking perfectly normally for *that* repo. The+*ranking* is sound; the absolute band is not portable. The payload states the+assumption in `score_unit`.So the surfaces lead with where the change sits in its **own repo's**distribution:-- **Review priority**: `Below typical` / `Typical` / `Elevated` (terciles of- the repo's own commit-risk distribution). This is the signal to triage on.+- **Review priority** / **classification**: `Below typical` / `Typical` /+ `Elevated` (terciles of the repo's own commit-risk distribution). This is the+ signal to triage on.- **Percentile**: "riskier than N% of this repo's commits".- **Raw model score** (0–10): kept for transparency but shown as a secondary,clearly corpus-anchored number, not the thing to act on.+- **`fallback_band`**: the absolute `low` / `moderate` / `high` band. Present+ *only* when there was no baseline to rank against (a shallow repo, or+ `--baseline 0`), which is why it is not a peer of the review priority.Each **driver** is reported relative to *the model's baseline commit* (thecalibration-corpus mean), not this repo, so a `+19 / −1` change can legitimately@@ -71,6 +95,13 @@ repo of large commits. The signed contribution and colour (red raised the rawscore, green lowered it) carry the direction; the label only states thefeature's standing, never an absolute verdict.+`nf`, `nd` and `ns` enter the logit exactly as fit but are **not reported as+drivers**. Their coefficients are small and negative — collinearity with `la`+(size), not a finding that touching more files is safer — so as an explanation+they contradict themselves: the label reads "more directories than baseline"+while the contribution is protective. Hiding an explanation we cannot stand+behind is the honest interim; a refit is the real fix.+The `repowise risk` CLI samples the repo's recent commits live (`--baseline`,default 200) to compute this percentile; in the web UI it is precomputed from theindexed commit history.diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 76ea04eee..b67f1053a 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -730,8 +730,9 @@ repowise dead-code --repo backend # workspace, single repoJust-in-time change-risk scoring for a commit or diff range. Scores the defectrisk of a change from the same calibrated signals the code-health layer uses -no LLM calls, and it works without `repowise init` (pure git + learned-constants). `REVSPEC` defaults to `HEAD`; pass a `base..head` range to score a-whole branch / PR as one change.+constants). With no `REVSPEC` it scores your uncommitted work, falling back to+`HEAD` when the tree is clean; pass `HEAD` to always mean the last commit, or a+`base..head` range to score a whole branch / PR as one change.The headline is **repo-relative**: the change's percentile and review priority(`Below typical` / `Typical` / `Elevated`) within the repo's own recent commits,@@ -754,7 +755,8 @@ to the model's baseline commit, not this repo.| `--full` | With `--target`: emit the complete tool payload as JSON (implies `--format json`) |```bash-repowise risk # score HEAD+repowise risk # score uncommitted work, else HEAD+repowise risk HEAD # score the last commitrepowise risk main..HEAD # score a branch / PR range as one changerepowise risk --ext .ts,.tsx # restrict to specific suffixesrepowise risk main..HEAD -x 'tests/' -x '*.spec.ts' # omit tests from scoringdiff --git a/examples/risk/README.md b/examples/risk/README.mdindex 3b796e5e9..d0837fe47 100644--- a/examples/risk/README.md+++ b/examples/risk/README.md@@ -14,10 +14,11 @@ Works without `repowise init` (index is optional).cd /path/to/your-repo```-## 1. Score HEAD or a range+## 1. Score your current change, a commit, or a range```bash-repowise risk # score HEAD+repowise risk # score uncommitted work, else HEAD+repowise risk HEAD # score the last commitrepowise risk main..HEAD # whole branch / PR as one changerepowise risk HEAD~5..HEAD # recent local work```diff --git a/packages/api-client/src/risk.ts b/packages/api-client/src/risk.tsindex f4f8e95d9..b71fe3f74 100644--- a/packages/api-client/src/risk.ts+++ b/packages/api-client/src/risk.ts@@ -22,10 +22,13 @@ export interface RiskRangeResponse {base: string;head: string;score: number;- probability: number;- level: string;+ /** The unit `score` is calibrated on: a single commit, not a whole range. */+ score_unit: string;risk_percentile: number | null;review_priority: string | null;+ classification: string | null;+ /** Absolute band, present only when there was no baseline to rank against. */+ fallback_band: string | null;is_fix: boolean;features: Record<string, number | null>;drivers: RiskDriverResponse[];diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.pyindex 67542eca8..38e59caa0 100644--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py@@ -15,7 +15,8 @@ same seam ``ask`` / ``context`` / ``symbol`` / ``why`` use. It reads the indexrather than git, so the repo must be indexed.Examples:- repowise risk # score HEAD+ repowise risk # score uncommitted work, else HEAD+ repowise risk HEAD # score the last commitrepowise risk abc123 # score a single commitrepowise risk main..HEAD # score a branch / PR range as one changerepowise risk --target a.py -t b.py # what history says about those files@@ -372,7 +373,7 @@ def _ordinal(n: int) -> str:@click.command("risk")[email protected]("revspec", required=False, default="HEAD")[email protected]("revspec", required=False, default=None)@click.option("--path","repo_path",@@ -423,7 +424,7 @@ def _ordinal(n: int) -> str:@format_option()@full_option()def risk_command(- revspec: str,+ revspec: str | None,repo_path: str,ext: str | None,baseline: int,@@ -436,8 +437,9 @@ def risk_command("""Score the defect risk of a change, or of touching some files.With no --target this scores REVSPEC (a commit, or a ``base..head``- range) from its diff. With --target it reports what the repo's history- says about the named files, the same as the get_risk MCP tool.+ range) from its diff. Omit REVSPEC to score your uncommitted work, or+ HEAD when the tree is clean. With --target it reports what the repo's+ history says about the named files, the same as the get_risk MCP tool."""if targets:_target_risk(repo_path, targets, changed_files, fmt, full)@@ -465,7 +467,7 @@ def risk_command(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}"+ f"Could not read change {revspec or 'HEAD'!r} in {repo_path}: {exc}") from excfeatures = result.features@@ -476,7 +478,7 @@ def risk_command(if features.nf == 0:status.print(- f"[yellow]No counted file changes in {revspec!r} "+ f"[yellow]No counted file changes in {features.ref!r} "f"(check the revspec, --ext, or exclusion filters).[/yellow]")@@ -497,8 +499,11 @@ def risk_command(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.level}[/{color}] (absolute band — no repo baseline to rank against)"+ f"[{color}]{risk.level}[/{color}] (absolute per-commit band — "+ "no repo baseline to rank against)")+ if result.working_tree:+ console.print(" [dim]Scoring your uncommitted changes, not the last commit.[/dim]")if features.subject:console.print(f" [dim]{features.subject}[/dim]")if request_excludes:@@ -506,16 +511,20 @@ def risk_command(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}"+ f"entropy {features.entropy:.2f} · author exp "+ f"{'unknown' if features.exp is None else features.exp}"+ (" [magenta](fix)[/magenta]" if features.is_fix else ""))if percentile is not None and priority is not None:console.print(f" [dim]{_PRIORITY_LEAD[priority]} ({_ordinal(round(percentile))} percentile).[/dim]")- # Raw score kept as a clearly-secondary, clearly-labelled number.+ # Raw score kept as a clearly-secondary, clearly-labelled number. The unit+ # matters: the corpus is single commits, so a PR-sized range reads high. The+ # band is deliberately absent here — it is printed above when, and only+ # when, there is no percentile to prefer over it.console.print(- f" [dim]Raw model score: {risk.score:.1f}/10 — corpus-anchored ({risk.level}); "+ f" [dim]Raw model score: {risk.score:.1f}/10 — corpus-anchored to a single commit; "f"prefer the percentile for review order.[/dim]")diff --git a/packages/core/src/repowise/core/analysis/change_risk/__init__.py b/packages/core/src/repowise/core/analysis/change_risk/__init__.pyindex c48d05990..82b42da3b 100644--- a/packages/core/src/repowise/core/analysis/change_risk/__init__.py+++ b/packages/core/src/repowise/core/analysis/change_risk/__init__.py@@ -11,13 +11,16 @@ from __future__ import annotationsfrom .baseline import baseline_scoresfrom .features import (+ WORKING_TREE_REF,ChangeFeatures,change_features_from_stored,extract_commit_features,extract_range_features,+ extract_worktree_features,features_from_file_changes,+ working_tree_is_dirty,)-from .model import ChangeRisk, RiskDriver, score_change+from .model import SCORE_UNIT, ChangeRisk, RiskDriver, score_changefrom .normalize import RiskNormalizer, review_priority_classificationfrom .service import (ChangeRiskResult,@@ -28,6 +31,8 @@ from .service import ()__all__ = [+ "SCORE_UNIT",+ "WORKING_TREE_REF","ChangeFeatures","ChangeRisk","ChangeRiskResult",@@ -38,10 +43,12 @@ __all__ = ["change_risk_payload","extract_commit_features","extract_range_features",+ "extract_worktree_features","features_from_file_changes","normalize_extensions","review_priority_classification","riskignore_patterns","score_change","score_live_change",+ "working_tree_is_dirty",]diff --git a/packages/core/src/repowise/core/analysis/change_risk/features.py b/packages/core/src/repowise/core/analysis/change_risk/features.pyindex 4a05b3e34..73cf1ca26 100644--- a/packages/core/src/repowise/core/analysis/change_risk/features.py+++ b/packages/core/src/repowise/core/analysis/change_risk/features.py@@ -20,11 +20,16 @@ import mathimport subprocessfrom collections.abc import Iterablefrom dataclasses import dataclass+from pathlib import Pathimport pathspecfrom ...ingestion.git_indexer._constants import is_fix_commit+#: ``ChangeFeatures.ref`` for a score of the uncommitted change. Not a revspec —+#: it names the unit scored, in the same slot a sha or ``base..head`` occupies.+WORKING_TREE_REF = "working tree"+@dataclassclass ChangeFeatures:@@ -116,12 +121,18 @@ def _entropy(per_file: list[int]) -> float: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)."""+def _author_experience(repo_path: str, author: str, upto_ref: str) -> int | None:+ """Author's prior commit count reachable from *upto_ref*, or ``None``.++ ``None`` means *unknown*, which the scorer treats as a neutral no-push+ feature. Never ``0`` on failure: a real zero is a first-ever commit and the+ model reads it as a risk-raising signal, so imputing it for a lookup that+ merely failed would silently penalize the change.+ """if not author:- return 0+ return None# 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.+ # git error.out = _git(["rev-list", "--count", "--author", author, "--no-merges", upto_ref],repo_path,@@ -130,7 +141,7 @@ def _author_experience(repo_path: str, author: str, upto_ref: str) -> int:try:return int(out)except ValueError:- return 0+ return Nonedef features_from_file_changes(@@ -219,6 +230,82 @@ def change_features_from_stored()+def working_tree_is_dirty(repo_path: str) -> bool:+ """Whether the checkout holds staged, unstaged or untracked changes."""+ # check=False so a non-repo path answers "not dirty" rather than raising:+ # the caller falls back to scoring a committed ref, which then reports the+ # real git error with its own revspec in the message.+ return bool(_git(["status", "--porcelain"], repo_path, check=False).strip())+++#: Untracked files above this are counted as a touched file with zero added+#: lines rather than read into memory to be counted. A multi-megabyte untracked+#: blob is a build artifact, not authored code, and its exact line count would+#: not change the risk band.+_UNTRACKED_READ_LIMIT = 2_000_000+++def _untracked_additions(repo_path: str, path: str) -> int:+ """Line count of an untracked file, matching what git would call additions."""+ target = Path(repo_path) / path+ try:+ if target.stat().st_size > _UNTRACKED_READ_LIMIT:+ return 0+ data = target.read_bytes()+ except OSError:+ return 0+ if b"\x00" in data:+ return 0 # binary: git reports "-" in numstat, which we count as 0+ if not data:+ return 0+ return data.count(b"\n") + (0 if data.endswith(b"\n") else 1)+++def extract_worktree_features(+ repo_path: str,+ *,+ extensions: tuple[str, ...] = (),+ exclude_patterns: tuple[str, ...] = (),+) -> ChangeFeatures:+ """Extract features for the uncommitted change: the diff against ``HEAD``.++ Covers staged and unstaged edits to tracked files plus untracked files,+ which is what a caller who just wrote code and asked "how risky is this?"+ means by "this". Untracked files are invisible to ``git diff HEAD``, so they+ are folded in as pure additions.++ Experience is the configured author's prior commit count at ``HEAD``, and+ ``is_fix`` is always false — an uncommitted change has no subject to read.+ """+ # Both walks run from the repo root: ``git diff`` reports root-relative+ # paths whatever the cwd, but ``ls-files --others`` is scoped to the cwd and+ # reports relative to it, so from a subdirectory the two halves would use+ # different path roots and only half would match a root-anchored exclude.+ root = _git(["rev-parse", "--show-toplevel"], repo_path, check=False).strip() or repo_path+ numstat = _git(["diff", "--numstat", "HEAD"], root, check=False)+ untracked = _git(["ls-files", "--others", "--exclude-standard"], root, check=False)+ rows = [+ f"{_untracked_additions(root, path)}\t0\t{path}" for path in untracked.splitlines() if path+ ]+ if rows:+ numstat = numstat.rstrip("\n") + "\n" + "\n".join(rows)+ la, ld, nf, dirs, subs, per_file = _accumulate_numstat(numstat, extensions, exclude_patterns)+ author = _git(["config", "user.name"], root, check=False).strip()+ return ChangeFeatures(+ la=la,+ ld=ld,+ nf=nf,+ nd=len(dirs),+ ns=len(subs),+ entropy=_entropy(per_file),+ exp=_author_experience(root, author, "HEAD"),+ is_fix=False,+ author=author,+ subject="",+ ref=WORKING_TREE_REF,+ )++def extract_commit_features(repo_path: str,sha: str,@@ -234,7 +321,11 @@ def extract_commit_features("""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)+ # -m --first-parent: on a merge, score the diff the merge brought onto the+ # first parent — the PR's content. Without it the answer depends on git's+ # combined-diff defaults, which can drop every file that matches a parent.+ # No effect on a non-merge commit.+ numstat = _git(["show", sha, "--numstat", "--format=", "-m", "--first-parent"], repo_path)la, ld, nf, dirs, subs, per_file = _accumulate_numstat(numstat, extensions, exclude_patterns)# 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()diff --git a/packages/core/src/repowise/core/analysis/change_risk/model.py b/packages/core/src/repowise/core/analysis/change_risk/model.pyindex 4525e3d38..386353ba5 100644--- a/packages/core/src/repowise/core/analysis/change_risk/model.py+++ b/packages/core/src/repowise/core/analysis/change_risk/model.py@@ -71,20 +71,37 @@ class RiskDriver:label: str # human-readable explanation+#: Features whose contribution is real but whose *explanation* is not.+#:+#: ``nf``/``nd``/``ns`` carry small negative coefficients that are collinearity+#: with ``la`` (size), not a finding that touching more files is safer. Reported+#: as drivers they contradict themselves: the label says "more directories than+#: baseline" while the colour says protective. They still enter the logit+#: exactly as fit — this hides an explanation we cannot stand behind, not a+#: number. A refit is the real fix.+_UNREPORTABLE_DRIVERS = frozenset({"nf", "nd", "ns"})++@dataclassclass ChangeRisk:"""Result of scoring a change."""score: float # 0-10 (10 * predicted probability)- probability: float # calibrated logistic probability- level: str # "low" | "moderate" | "high"+ level: str # absolute band; see _leveldrivers: list[RiskDriver] = field(default_factory=list)features: ChangeFeatures | None = None@propertydef top_drivers(self) -> list[RiskDriver]:- """Drivers sorted by absolute contribution (strongest first)."""- return sorted(self.drivers, key=lambda d: -abs(d.contribution))+ """Reportable drivers, sorted by absolute contribution (strongest first).++ ``drivers`` holds the full attribution and always sums to the logit;+ this is the display subset, minus ``_UNREPORTABLE_DRIVERS``.+ """+ return sorted(+ (d for d in self.drivers if d.feature not in _UNREPORTABLE_DRIVERS),+ key=lambda d: -abs(d.contribution),+ )def _sigmoid(z: float) -> float:@@ -94,7 +111,23 @@ def _sigmoid(z: float) -> float:return e / (1.0 + e)+#: The unit the absolute band assumes, stated wherever the band is emitted.+#:+#: The constants were fit on *individual commits* (corpus baseline: 10.5 lines+#: added, 1.7 files), so a squash-merged PR or a multi-commit range is several+#: commits' worth of diff read against a one-commit scale and lands high by+#: construction. The repo-relative percentile is immune to this; the band is not.+SCORE_UNIT = "per-commit"++def _level(score: float) -> str:+ """Absolute calibrated band — the fallback when no percentile is available.++ Portable only across repos whose typical commit resembles the calibration+ corpus (see :data:`SCORE_UNIT`). Surfaces lead with the repo-relative+ review priority and fall back to this only when the baseline sample is+ empty or too small to rank against.+ """if score >= 7.0:return "high"if score >= 4.0:@@ -150,12 +183,5 @@ def score_change(features: ChangeFeatures) -> ChangeRisk:))- prob = _sigmoid(logit)- score = round(10.0 * prob, 1)- return ChangeRisk(- score=score,- probability=prob,- level=_level(score),- drivers=drivers,- features=features,- )+ score = round(10.0 * _sigmoid(logit), 1)+ return ChangeRisk(score=score, level=_level(score), drivers=drivers, features=features)diff --git a/packages/core/src/repowise/core/analysis/change_risk/service.py b/packages/core/src/repowise/core/analysis/change_risk/service.pyindex ad248a05a..4cff479ea 100644--- a/packages/core/src/repowise/core/analysis/change_risk/service.py+++ b/packages/core/src/repowise/core/analysis/change_risk/service.py@@ -12,8 +12,10 @@ from .features import (ChangeFeatures,extract_commit_features,extract_range_features,+ extract_worktree_features,+ working_tree_is_dirty,)-from .model import ChangeRisk, score_change+from .model import SCORE_UNIT, ChangeRisk, score_changefrom .normalize import RiskNormalizer, review_priority_classification_MIN_BASELINE = 8@@ -30,6 +32,7 @@ class ChangeRiskResult:baseline_sample_size: intriskignore_excludes: tuple[str, ...]request_excludes: tuple[str, ...]+ working_tree: bool = False # scored the uncommitted change, not a commitdef riskignore_patterns(repo_path: str) -> tuple[str, ...]:@@ -61,21 +64,42 @@ def normalize_extensions(extensions: tuple[str, ...]) -> tuple[str, ...]:def score_live_change(repo_path: str,- revspec: str = "HEAD",+ revspec: str | None = None,*,extensions: tuple[str, ...] = (),exclude_patterns: tuple[str, ...] = (),baseline: int = 200,) -> ChangeRiskResult:- """Score a commit or ``base..head`` range with optional live filters."""+ """Score a commit or ``base..head`` range with optional live filters.++ With no *revspec* the subject is "the change in front of me": the+ uncommitted work if the tree is dirty, otherwise ``HEAD``. A caller that+ just wrote code and asked for a score means the code it wrote, and the+ previous commit is the one answer that is certainly wrong. An explicit+ *revspec* — ``"HEAD"`` included — always means committed refs.+ """if baseline < 0:raise ValueError("baseline must be non-negative")extensions = normalize_extensions(extensions)from_riskignore = riskignore_patterns(repo_path)effective_excludes = from_riskignore + exclude_patterns- if ".." in revspec:- base, _, head = revspec.partition("..")+ target = revspec or "HEAD"+ uncommitted = (+ extract_worktree_features(+ repo_path, extensions=extensions, exclude_patterns=effective_excludes+ )+ if revspec is None and working_tree_is_dirty(repo_path)+ else None+ )+ # A tree dirty only in paths the filters drop is not a change this command+ # can score, so fall through to HEAD rather than answer "empty change".+ working_tree = uncommitted is not None and uncommitted.nf > 0+ if working_tree:+ features = uncommitted+ anchor, excluded_ref = "HEAD", ""+ elif ".." in target:+ base, _, head = target.partition("..")# Strip leading dot(s) so three-dot syntax (main...HEAD) gives a valid anchor ref.head = head.lstrip(".") or "HEAD"features = extract_range_features(@@ -84,9 +108,9 @@ def score_live_change(anchor, excluded_ref = head, ""else:features = extract_commit_features(- repo_path, revspec, extensions=extensions, exclude_patterns=effective_excludes+ repo_path, target, extensions=extensions, exclude_patterns=effective_excludes)- anchor, excluded_ref = revspec, features.ref+ anchor, excluded_ref = target, features.refrisk = score_change(features)percentile: float | None = None@@ -116,20 +140,27 @@ def score_live_change(baseline_sample_size=baseline_sample_size,riskignore_excludes=from_riskignore,request_excludes=exclude_patterns,+ working_tree=working_tree,)def change_risk_payload(result: ChangeRiskResult) -> dict:- """Render the machine-readable response shared by the CLI and MCP tool."""+ """Render the machine-readable response shared by the CLI and MCP tool.++ ``fallback_band`` is the absolute calibrated band, non-null only when there+ was no baseline to rank against — which is why it is not a peer of+ ``review_priority``. ``score_unit`` names the unit that band assumes.+ """features, risk = result.features, result.riskreturn {"ref": features.ref,+ "working_tree": result.working_tree,"score": risk.score,- "probability": round(risk.probability, 4),- "level": risk.level,+ "score_unit": SCORE_UNIT,"risk_percentile": round(result.percentile, 1) if result.percentile is not None else None,"review_priority": result.priority,"classification": review_priority_classification(result.priority),+ "fallback_band": risk.level if result.priority is None else None,"baseline_sample_size": result.baseline_sample_size,"exclude_patterns": list(result.riskignore_excludes + result.request_excludes),"is_fix": features.is_fix,diff --git a/packages/core/src/repowise/core/analysis/changed_lines.py b/packages/core/src/repowise/core/analysis/changed_lines.pyindex 4fe1b85b0..d3287624e 100644--- a/packages/core/src/repowise/core/analysis/changed_lines.py+++ b/packages/core/src/repowise/core/analysis/changed_lines.py@@ -139,16 +139,25 @@ def changed_lines(revspec: str | None = None,*,staged: bool = False,+ working_tree: bool = False,) -> tuple[dict[str, set[int]], str]:"""Return ``({file: changed_lines}, label)`` for a change.*revspec* mirrors ``repowise risk``: ``base..head`` is a range, a bare refis a single commit. With no *revspec* (or *staged*), the staged diff- (``git diff --cached``) is used - the "what will I commit" case. *label*+ (``git diff --cached``) is used - the "what will I commit" case.+ *working_tree* widens that to everything ``HEAD`` does not have, staged or+ not, matching what change risk counts for an uncommitted change. *label*is a human string naming what was diffed. Raises ``ValueError`` on anunknown revision so the caller can fail loudly rather than silentlyreporting "no changes"."""+ if working_tree:+ # Untracked files are absent by design: they are new, so neither caller+ # (prior fixes, per-test coverage) has a row to find for them anyway.+ diff = _git(["diff", "--unified=0", "HEAD"], repo_path)+ return _parse_unified_diff(diff), "working tree"+if staged or not revspec:diff = _git(["diff", "--cached", "--unified=0"], repo_path)return _parse_unified_diff(diff), "staged changes"@@ -163,5 +172,7 @@ def changed_lines(_verify_ref(repo_path, revspec)# --format= drops the commit message so only the diff body is parsed.- diff = _git(["show", "--unified=0", "--format=", revspec], repo_path)+ # -m --first-parent matches what change risk counts on a merge; without it+ # git's combined diff emits nothing at all and a merged PR reads as empty.+ diff = _git(["show", "--unified=0", "--format=", "-m", "--first-parent", revspec], repo_path)return _parse_unified_diff(diff), revspecdiff --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 7585f9275..734f02a7e 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@@ -7,6 +7,7 @@ import jsonimport subprocessimport timefrom datetime import UTC, datetime+from functools import partialfrom typing import Anyimport pathspec@@ -38,23 +39,23 @@ _PRIOR_FIXES_LIMIT = 10@mcp.tool()async def get_change_risk(- revspec: str = "HEAD",+ revspec: str | None = None,repo: str | None = None,extensions: list[str] | None = None,exclude_patterns: list[str] | None = None,baseline: int = 200,) -> dict:- """Score a live commit or ``base..head`` range from its diff shape.+ """Score a live commit, ``base..head`` range, or uncommitted work.Use this for a pre-merge score of a commit or PR range. It is distinct from``get_risk``, which assesses indexed files and PR blast radius. Both filtersbelow also apply to the baseline used for the repository percentile.- Prefer ``risk_percentile`` as the indicator of change risk: it ranks this- change against sampled recent commits in the same repository. Summarize it- with ``review_priority`` and ``classification``. ``score``, ``probability``,- and ``level`` are secondary corpus-calibrated context, the fallback only- when ``risk_percentile`` is unavailable.+ Lead with ``risk_percentile``, summarized by ``review_priority`` and+ ``classification``: it ranks this change against sampled recent commits in+ the same repository. ``score`` is calibrated per single commit, so a PR-sized+ change reads high by construction; ``fallback_band`` appears only when there+ was no baseline to rank against.``impacted_tests`` names the tests the per-test coverage map proves executethe change's changed *lines* (line-precise, narrower than get_risk's@@ -66,7 +67,8 @@ async def get_change_risk(per-file counts, never a commit name.Args:- revspec: Commit or ``base..head`` range to score. Defaults to ``HEAD``.+ revspec: Commit or ``base..head`` range to score. Omit it to score the+ uncommitted change, or ``HEAD`` when the working tree is clean.repo: Repository alias in workspace mode; omit for the default repository.extensions: File suffixes to count, for example ``[".py", ".ts"]``.exclude_patterns: Gitignore-style paths to omit, for example ``["tests/", "*.md"]``.@@ -89,13 +91,13 @@ async def get_change_risk(return {"error": str(exc)}except subprocess.CalledProcessError as exc:detail = (exc.stderr or "").strip() or str(exc)- return {"error": f"Could not read change {revspec!r}: {detail}"}+ return {"error": f"Could not read change {revspec or 'HEAD'!r}: {detail}"}except subprocess.TimeoutExpired:- return {"error": f"git timed out reading change {revspec!r}."}+ return {"error": f"git timed out reading change {revspec or 'HEAD'!r}."}payload = change_risk_payload(result)if result.features.nf == 0:payload["warning"] = (- f"No counted file changes in {revspec!r} "+ f"No counted file changes in {payload['ref']!r} ""(check the revspec, extensions, or exclusion filters).")# Changed lines over the SAME file universe the score counted (its@@ -112,6 +114,7 @@ async def get_change_risk(revspec,normalize_extensions(tuple(extensions or ())),result.riskignore_excludes + result.request_excludes,+ working_tree=result.working_tree,)payload["impacted_tests"] = await _impacted_tests_block(ctx, changed, changed_error)prior_fixes = await _prior_fixes_block(ctx, changed)@@ -126,13 +129,15 @@ async def get_change_risk(return payload-def _normalize_revspec(revspec: str) -> str:+def _normalize_revspec(revspec: str | None) -> str:"""Mirror ``score_live_change``'s three-dot handling for ``changed_lines``.``changed_lines`` verifies each side of a ``base..head`` range as a ref, so athree-dot ``base...head`` (whose head parses as ``.head``) would fail itsref check. Strip the extra dot to the two-dot form the scorer already uses."""+ if revspec is None:+ return "HEAD"if ".." in revspec:base, _, head = revspec.partition("..")head = head.lstrip(".") or "HEAD"@@ -208,9 +213,11 @@ def _serialize_missing(report: Any) -> dict[str, Any]:async def _changed_in_scope(repo_path: str,- revspec: str,+ revspec: str | None,extensions: tuple[str, ...],exclude_patterns: tuple[str, ...],+ *,+ working_tree: bool = False,) -> tuple[dict[str, set[int]], tuple[str, str] | None]:"""The change's changed lines, restricted to the score's counted universe.@@ -223,7 +230,12 @@ async def _changed_in_scope(try:changed, _label = await asyncio.to_thread(- changed_lines, repo_path, _normalize_revspec(revspec)+ partial(+ changed_lines,+ repo_path,+ _normalize_revspec(revspec),+ working_tree=working_tree,+ ))except ValueError as exc:return {}, ("unknown", f"Could not read changed lines: {exc}")diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.pyindex aa1054885..d97786573 100644--- a/packages/server/src/repowise/server/routers/git.py+++ b/packages/server/src/repowise/server/routers/git.py@@ -14,10 +14,12 @@ from sqlalchemy import case, func, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.change_risk import (+ SCORE_UNIT,RiskNormalizer,baseline_scores,change_features_from_stored,extract_range_features,+ review_priority_classification,score_change,)from repowise.core.ingestion.git_indexer._constants import (@@ -699,10 +701,11 @@ def get_risk_range(base=base,head=head,score=risk.score,- probability=risk.probability,- level=risk.level,+ score_unit=SCORE_UNIT,risk_percentile=percentile,review_priority=priority,+ classification=review_priority_classification(priority),+ fallback_band=risk.level if priority is None else None,is_fix=features.is_fix,features=ChangeFeaturesResponse(la=features.la,diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.pyindex 660391344..7f84d04dd 100644--- a/packages/server/src/repowise/server/schemas/git.py+++ b/packages/server/src/repowise/server/schemas/git.py@@ -298,10 +298,15 @@ class RiskRangeResponse(BaseModel):base: strhead: strscore: float- probability: float- level: str+ #: The unit ``score`` is calibrated on. A range is several commits' worth+ #: of diff, so it reads high against a single-commit scale.+ score_unit: strrisk_percentile: float | Nonereview_priority: str | None+ classification: str | None+ #: Absolute calibrated band, present only when there was no baseline to+ #: rank against — so it is not a peer of ``review_priority``.+ fallback_band: str | Noneis_fix: boolfeatures: ChangeFeaturesResponsedrivers: list[RiskDriverResponse]diff --git a/packages/ui/src/commits/commit-detail-card.tsx b/packages/ui/src/commits/commit-detail-card.tsxindex d915604e4..27e0557e4 100644--- a/packages/ui/src/commits/commit-detail-card.tsx+++ b/packages/ui/src/commits/commit-detail-card.tsx@@ -101,7 +101,7 @@ export function CommitDetailCard({ commit, reviewCut, className }: CommitDetailC<OverviewSectionclassName="mt-7"title="What changed, and what it cost"- description="Every measurement the model reads, and the exact signed points each one moved the raw score by. Red raised it, green lowered it, both against the model's baseline commit."+ description="The measurements that explain the score, and the exact signed points each one moved it by. Red raised it, green lowered it, both against the model's baseline commit. File, directory and subsystem counts are left out: they enter the score, but their fitted signs are collinearity with diff size rather than a finding."><RiskDriverBreakdown drivers={c.drivers} /></OverviewSection>diff --git a/packages/vscode/src/features/lmTools.ts b/packages/vscode/src/features/lmTools.tsindex eb59eb83d..5e58e8d8f 100644--- a/packages/vscode/src/features/lmTools.ts+++ b/packages/vscode/src/features/lmTools.ts@@ -249,10 +249,11 @@ export function registerLmTools(ctx: RepowiseContext): vscode.Disposable {return jsonResult({base,score: result.score,- level: result.level,- probability: result.probability,+ score_unit: result.score_unit,risk_percentile: result.risk_percentile,review_priority: result.review_priority,+ classification: result.classification,+ fallback_band: result.fallback_band,drivers: result.drivers,features: result.features,});diff --git a/packages/vscode/webview/src/views/risk/App.test.tsx b/packages/vscode/webview/src/views/risk/App.test.tsxindex cb90a98fa..49cd71fd0 100644--- a/packages/vscode/webview/src/views/risk/App.test.tsx+++ b/packages/vscode/webview/src/views/risk/App.test.tsx@@ -15,10 +15,11 @@ const REPORT: RiskRangeReport = {base: "main",head: "HEAD",score: 7.4,- probability: 0.63,- level: "high",+ score_unit: "per-commit",risk_percentile: 88,review_priority: "high",+ classification: "Elevated",+ fallback_band: null,is_fix: false,features: { la: 120, ld: 30, nf: 6, nd: 2, ns: 1, entropy: 2.31, exp: null },drivers: [@@ -107,12 +108,13 @@ describe("risk App", () => {beforeEach(() => vi.clearAllMocks());afterEach(() => cleanup());- it("renders the score, level, and drivers from a fixture", async () => {+ it("leads with the repo-relative ranking and keeps the raw score secondary", async () => {const riskRange = vi.fn().mockResolvedValue(REPORT);render(<App host={makeHost(riskRange)} repo={REPO} params={{}} refreshToken={0} />);- expect(await screen.findByText("7.4")).toBeTruthy();- expect(screen.getByText("high risk")).toBeTruthy();+ expect(await screen.findByText("Elevated")).toBeTruthy();+ expect(screen.getByText("88th percentile")).toBeTruthy();+ expect(screen.getByText("7.4/10")).toBeTruthy();expect(screen.getByText("+1.80")).toBeTruthy();expect(screen.getByText("−0.50")).toBeTruthy();// The change-shape table renders labelled features and skips null ones.@@ -124,7 +126,7 @@ describe("risk App", () => {const riskRange = vi.fn().mockResolvedValue(REPORT);render(<App host={makeHost(riskRange)} repo={REPO} params={{}} refreshToken={0} />);- await screen.findByText("7.4");+ await screen.findByText("Elevated");expect(riskRange).toHaveBeenCalledTimes(1);fireEvent.click(screen.getByRole("button", { name: /run again/i }));@@ -214,7 +216,7 @@ describe("risk App", () => {const riskRange = vi.fn().mockResolvedValue(REPORT);render(<App host={makeHost(riskRange)} repo={REPO} params={{}} refreshToken={0} />);- await screen.findByText("7.4");+ await screen.findByText("Elevated");expect(screen.queryByText(/downstream file/)).toBeNull();expect(screen.queryByText(/untouched/)).toBeNull();expect(screen.queryByText(/associated test/)).toBeNull();diff --git a/packages/vscode/webview/src/views/risk/App.tsx b/packages/vscode/webview/src/views/risk/App.tsxindex dc43f8a63..775578f5d 100644--- a/packages/vscode/webview/src/views/risk/App.tsx+++ b/packages/vscode/webview/src/views/risk/App.tsx@@ -219,25 +219,42 @@ function RiskSkeleton({ base }: { base: string }) {);}+/** Repo-relative review priority mapped onto the three risk tones. */+const PRIORITY_TONE: Record<string, Tone> = {+ low: "low",+ moderate: "medium",+ high: "high",+};+/**- * The Kamei diff-shape risk score for the committed range (base..HEAD).+ * Where this range sits in its own repo's risk distribution.*- * The figure carries a sentence rather than three badges: "6.8" and a- * "high review priority" pill say the same thing twice and neither says what- * the number was computed from.+ * The lede is the ranking, not the raw score. That 0-10 figure is calibrated+ * on single commits, so a range spanning several reads high by construction+ * and says more about the corpus than about this change; it stays on the page+ * as a secondary, explicitly anchored line.*/function ScoreHero({ report }: { report: RiskRangeReport }) {const r = report.result;- const color = TONE_VAR[scoreTone(r.score)];+ const priority = r.review_priority;+ const percentile = r.risk_percentile;+ const ranked = percentile != null && priority != null;+ const color = ranked+ ? TONE_VAR[PRIORITY_TONE[priority] ?? "medium"]+ : TONE_VAR[scoreTone(r.score)];return (<PageLede// Not "Change risk" again: the page's h1 two lines above already says// that, and a micro-label repeating the heading verbatim labels nothing.- label="Diff shape"- value={r.score.toFixed(1)}+ label={ranked ? "Review priority" : "Diff shape"}+ value={ranked ? (r.classification ?? priority) : r.score.toFixed(1)}valueColor={color}- unit="out of 10"- band={{ label: `${r.level} risk`, color }}+ unit={ranked ? "for this repo" : "out of 10"}+ band={+ ranked+ ? { label: `${ordinal(percentile)} percentile`, color }+ : { label: `${r.fallback_band ?? "unranked"} risk`, color }+ }layout="beside"badge={r.is_fix ? (@@ -250,36 +267,25 @@ function ScoreHero({ report }: { report: RiskRangeReport }) {<p>Scored from the shape of this range's diff — how much it adds anddeletes, how many files, directories and subsystems it spreads across,- and how experienced its author is in them. We put the chance it carries- a defect at{" "}- <strong className="font-semibold text-[var(--color-text-primary)] tabular-nums">- {(r.probability * 100).toFixed(1)}%- </strong>- .+ and how experienced its author is in them.{" "}+ {ranked ? (+ <>+ That ranks it above{" "}+ <strong className="font-semibold text-[var(--color-text-primary)] tabular-nums">+ {Math.round(percentile)}%+ </strong>{" "}+ of recent commits in this repository.+ </>+ ) : (+ <>There was no baseline of recent commits to rank it against.</>+ )}+ </p>+ <p className="mt-2.5 text-[var(--color-text-tertiary)]">+ Raw model score{" "}+ <strong className="font-semibold tabular-nums">{r.score.toFixed(1)}/10</strong>, anchored+ to a corpus of single commits — a range spans several, so it reads high by construction.+ Prefer the ranking above for review order.</p>- {(r.risk_percentile != null || r.review_priority) && (- <p className="mt-2.5">- {r.risk_percentile != null && (- <>- That ranks it at the{" "}- <strong className="font-semibold text-[var(--color-text-primary)] tabular-nums">- {ordinal(r.risk_percentile)} percentile- </strong>{" "}- against recent commits here- {r.review_priority ? ", so " : "."}- </>- )}- {r.review_priority && (- <>- {r.risk_percentile == null && "Worth "}- <strong className="font-semibold text-[var(--color-text-primary)]">- {r.review_priority}- </strong>{" "}- review priority.- </>- )}- </p>- )}</PageLede>);}@@ -359,7 +365,7 @@ function RiskBreakdown({ report }: { report: RiskRangeReport }) {{drivers.length > 0 && (<OverviewSectiontitle="What moves the score"- description="Each feature's signed contribution. Positive raises the estimate, negative lowers it; the bar is relative to the strongest driver."+ description="The signed contribution of each feature that explains the score. Positive raises the estimate, negative lowers it; the bar is relative to the strongest driver. File, directory and subsystem counts enter the score but are not shown, because their fitted signs are collinearity with diff size rather than a finding."><div className="flex flex-col gap-3">{drivers.map((d) => {diff --git a/plugins/claude-code/skills/change-review/SKILL.md b/plugins/claude-code/skills/change-review/SKILL.mdindex a56ae113b..d8c05eccf 100644--- a/plugins/claude-code/skills/change-review/SKILL.md+++ b/plugins/claude-code/skills/change-review/SKILL.md@@ -23,8 +23,10 @@ Two complementary risk signals, use both:change entropy, author familiarity). No LLM, no network. Prefer this in-MCPtool; it takes a revspec and diffs server-side, so you never shell out. Leadwith `risk_percentile` (this change ranked against sampled recent commits),- summarized by `review_priority` and `classification`; `score` / `level` are- the corpus-calibrated fallback. This is the pre-merge gate: "how risky is this+ summarized by `review_priority` and `classification`. `score` is calibrated+ per single commit, so a PR-sized change reads high by construction, and+ `fallback_band` appears only when there was no baseline to rank against.+ Omit `revspec` to score uncommitted work. This is the pre-merge gate: "how risky is thischange overall?" The `repowise risk <revspec>` CLI is the identical scorer forwhen you are already in a terminal.- **`get_risk(changed_files=…)` (MCP)** works *per file* and returns thediff --git a/plugins/codex/skills/change-review/SKILL.md b/plugins/codex/skills/change-review/SKILL.mdindex 87b3b7ad5..2cfea211b 100644--- a/plugins/codex/skills/change-review/SKILL.md+++ b/plugins/codex/skills/change-review/SKILL.md@@ -18,8 +18,10 @@ Two complementary risk signals, use both:change entropy, author familiarity). No LLM, no network. Prefer this in-MCPtool; it takes a revspec and diffs server-side, so you never shell out. Leadwith `risk_percentile` (this change ranked against sampled recent commits),- summarized by `review_priority` and `classification`; `score` / `level` are- the corpus-calibrated fallback. This is the pre-merge gate: "how risky is this+ summarized by `review_priority` and `classification`. `score` is calibrated+ per single commit, so a PR-sized change reads high by construction, and+ `fallback_band` appears only when there was no baseline to rank against.+ Omit `revspec` to score uncommitted work. This is the pre-merge gate: "how risky is thischange overall?" The `repowise risk <revspec>` CLI is the identical scorer forwhen you are already in a terminal.- **`get_risk(changed_files=…)` (MCP)** works *per file* and returns thediff --git a/plugins/shared/skills/change-review.md b/plugins/shared/skills/change-review.mdindex 06174bfd1..2bf29d32d 100644--- a/plugins/shared/skills/change-review.md+++ b/plugins/shared/skills/change-review.md@@ -31,8 +31,10 @@ Two complementary risk signals, use both:change entropy, author familiarity). No LLM, no network. Prefer this in-MCPtool; it takes a revspec and diffs server-side, so you never shell out. Leadwith `risk_percentile` (this change ranked against sampled recent commits),- summarized by `review_priority` and `classification`; `score` / `level` are- the corpus-calibrated fallback. This is the pre-merge gate: "how risky is this+ summarized by `review_priority` and `classification`. `score` is calibrated+ per single commit, so a PR-sized change reads high by construction, and+ `fallback_band` appears only when there was no baseline to rank against.+ Omit `revspec` to score uncommitted work. This is the pre-merge gate: "how risky is thischange overall?" The `repowise risk <revspec>` CLI is the identical scorer forwhen you are already in a terminal.- **`get_risk(changed_files=…)` (MCP)** works *per file* and returns thediff --git a/tests/unit/analysis/test_change_risk.py b/tests/unit/analysis/test_change_risk.pyindex 8d40703ca..3eda9e025 100644--- a/tests/unit/analysis/test_change_risk.py+++ b/tests/unit/analysis/test_change_risk.py@@ -34,7 +34,6 @@ def _feat(**kw) -> ChangeFeatures: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.0assert 0.0 <= risk.score <= 10.0assert risk.level in {"low", "moderate", "high"}@@ -45,7 +44,6 @@ def test_logit_is_exact_sum_of_driver_contributions() -> None: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))@@ -78,7 +76,7 @@ def test_unknown_experience_is_neutral() -> None:logit = float(_CONSTANTS["intercept"]) + sum(d.contribution for d in risk.drivers if d.feature != "exp")- assert risk.probability == pytest.approx(_sigmoid(logit))+ assert risk.score == pytest.approx(round(10.0 * _sigmoid(logit), 1))def test_top_drivers_sorted_by_magnitude() -> None:@@ -278,7 +276,7 @@ def test_score_change_on_real_commit(git_repo: Path) -> None:risk = score_change(f)assert 0.0 <= risk.score <= 10.0assert risk.features is f- assert not math.isnan(risk.probability)+ assert not math.isnan(risk.score)def test_extract_commit_features_bad_revspec_raises(git_repo: Path) -> None:@@ -385,3 +383,138 @@ def test_baseline_cache_isolated_by_filters(git_repo: Path, monkeypatch) -> Noneassert calls["n"] == 2baseline.clear_baseline_cache()+++# ---------------------------------------------------------------------------+# The unit actually scored: working tree, merge commits, unknown authors.+# ---------------------------------------------------------------------------+++def test_default_revspec_scores_the_uncommitted_change(git_repo: Path) -> None:+ """No revspec + a dirty tree means the code the caller just wrote."""+ _commit(git_repo, {"src/a.py": "x = 1\n"}, "feat: a", author="Dev")+ (git_repo / "src" / "a.py").write_text("x = 1\ny = 2\n", encoding="utf-8") # unstaged+ (git_repo / "src" / "staged.py").write_text("s = 1\n", encoding="utf-8")+ _git(["add", "src/staged.py"], git_repo)+ (git_repo / "src" / "new.py").write_text("n = 1\nm = 2\n", encoding="utf-8") # untracked++ result = score_live_change(str(git_repo), baseline=0)++ assert result.working_tree is True+ assert result.features.ref == "working tree"+ assert result.features.nf == 3 # unstaged edit, staged add, untracked add+ assert result.features.la == 4 # 1 + 1 + 2+ assert change_risk_payload(result)["working_tree"] is True+++def test_dirt_the_filters_drop_falls_back_to_head(git_repo: Path) -> None:+ """A tree dirty only in excluded paths is not a change we can score."""+ _commit(git_repo, {"src/a.py": "x = 1\n"}, "feat: a", author="Dev")+ (git_repo / "notes.md").write_text("scratch\n", encoding="utf-8")++ result = score_live_change(str(git_repo), extensions=(".py",), baseline=0)++ assert result.working_tree is False+ assert result.features.ref == "HEAD"+ assert result.features.nf == 1 # the committed src/a.py, not an empty change+++def test_explicit_head_scores_the_commit_even_when_dirty(git_repo: Path) -> None:+ """An explicit revspec always means committed refs."""+ _commit(git_repo, {"src/a.py": "x = 1\n"}, "feat: a", author="Dev")+ (git_repo / "src" / "dirty.py").write_text("d = 1\n", encoding="utf-8")++ result = score_live_change(str(git_repo), "HEAD", baseline=0)++ assert result.working_tree is False+ assert result.features.nf == 1+ assert result.features.la == 1+ assert change_risk_payload(result)["working_tree"] is False+++def test_default_revspec_falls_back_to_head_when_clean(git_repo: Path) -> None:+ head = _commit(git_repo, {"src/a.py": "x = 1\n"}, "feat: a", author="Dev")++ result = score_live_change(str(git_repo), baseline=0)++ assert result.working_tree is False+ assert result.features.ref == "HEAD"+ assert result.features.subject == "feat: a"+ assert head # the tree is clean, so the commit is the subject+++def test_merge_commit_scores_its_first_parent_diff(git_repo: Path) -> None:+ """A merge is scored for what it brought onto the first parent.++ Combined-diff semantics drop every file that matches a parent, which would+ score a whole merged PR as an empty change.+ """+ _git(["checkout", "-q", "-b", "side"], git_repo)+ _commit(git_repo, {"side.py": "s = 1\ns2 = 2\n"}, "feat: side", author="Dev")+ _git(["checkout", "-q", "-"], git_repo)+ _commit(git_repo, {"main.py": "m = 1\n"}, "feat: main", author="Dev")+ _git(+ ["-c", "user.name=Dev", "-c", "[email protected]", "merge", "-q", "--no-ff", "side",+ "-m", "merge: side"],+ git_repo,+ )++ f = extract_commit_features(str(git_repo), "HEAD", extensions=(".py",))++ # side.py is exactly what the merge added to the first parent; main.py was+ # already there. The reverse holds for the second parent, so a combined+ # diff would report neither.+ assert f.nf == 1+ assert f.la == 2+ assert f.exp is not None # ``sha^`` is the first parent, so the walk resolves+++def test_failed_author_lookup_is_unknown_not_zero(git_repo: Path, monkeypatch) -> None:+ """A lookup that fails must not read as a first-ever commit.++ ``exp=0`` is a real value the model pushes risk up for; ``None`` is the+ neutral path it already has for a caller with no history to read.+ """+ from repowise.core.analysis.change_risk import features as feature_mod++ _commit(git_repo, {"a.py": "x = 1\n"}, "feat: a", author="Dev")+ real_git = feature_mod._git++ def _fail_rev_list(args, cwd, *, check=True):+ if args[:1] == ["rev-list"]:+ return "fatal: bad revision\n" # what check=False yields on error+ return real_git(args, cwd, check=check)++ monkeypatch.setattr(feature_mod, "_git", _fail_rev_list)+ f = extract_commit_features(str(git_repo), "HEAD")++ assert f.exp is None+ exp_driver = next(d for d in score_change(f).drivers if d.feature == "exp")+ assert exp_driver.contribution == 0.0+++def test_collinear_diffusion_features_are_not_reported_as_drivers() -> None:+ """nf/nd/ns still enter the logit; they just stop explaining it."""+ risk = score_change(_feat(la=300, ld=20, nf=25, nd=10, ns=5, entropy=3.0, exp=50))++ reported = {d.feature for d in risk.top_drivers}+ assert reported.isdisjoint({"nf", "nd", "ns"})+ assert {"la", "ld", "entropy", "exp"} <= reported+ # The full attribution is untouched, so the logit still reconstructs.+ logit = float(_CONSTANTS["intercept"]) + sum(d.contribution for d in risk.drivers)+ assert risk.score == pytest.approx(round(10.0 * _sigmoid(logit), 1))+++def test_payload_offers_the_absolute_band_only_as_a_fallback(git_repo: Path) -> None:+ for i in range(12):+ _commit(git_repo, {f"f{i}.py": f"x = {i}\n"}, f"feat: {i}", author="Dev")++ ranked = change_risk_payload(score_live_change(str(git_repo), "HEAD", baseline=200))+ unranked = change_risk_payload(score_live_change(str(git_repo), "HEAD", baseline=0))++ assert ranked["review_priority"] is not None+ assert ranked["fallback_band"] is None+ assert unranked["review_priority"] is None+ assert unranked["fallback_band"] in {"low", "moderate", "high"}+ assert unranked["score_unit"] == "per-commit"+ assert "probability" not in ranked and "level" not in rankeddiff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.pyindex ea78a54d0..503cebf7d 100644--- a/tests/unit/server/mcp/test_change_risk.py+++ b/tests/unit/server/mcp/test_change_risk.py@@ -46,10 +46,13 @@ async def test_get_change_risk_honors_riskignore_and_request_filters(tmp_path, mreturn SimpleNamespace(path=str(repo))monkeypatch.setattr(module, "_resolve_repo_context", _context)+ # Explicit revspec, so the uncommitted .riskignore does not become the+ # subject of the score.result = await module.get_change_risk(- extensions=["py", "md"], exclude_patterns=["docs/"], baseline=0+ "HEAD", extensions=["py", "md"], exclude_patterns=["docs/"], baseline=0)+ assert result["working_tree"] is Falseassert result["features"] == {"la": 1,"ld": 0,diff --git a/tests/unit/server/test_git.py b/tests/unit/server/test_git.pyindex ab9d70167..7508aa659 100644--- a/tests/unit/server/test_git.py+++ b/tests/unit/server/test_git.py@@ -284,9 +284,10 @@ async def test_get_commit_detail_has_drivers(client: AsyncClient, app) -> None:assert data["author_experience"] == 3# Re-scoring the stored features reproduces the persisted score exactly.assert data["change_risk_score"] == 8.5- assert len(data["drivers"]) == 7 # la, ld, nf, nd, ns, entropy, exp+ # The reportable drivers only: nf/nd/ns still enter the score, but their+ # fitted signs are collinearity with diff size, so they explain nothing.feats = {d["feature"] for d in data["drivers"]}- assert {"la", "exp", "entropy"} <= feats+ assert feats == {"la", "ld", "entropy", "exp"}@pytest.mark.asynciodiff --git a/tests/unit/server/test_risk_range.py b/tests/unit/server/test_risk_range.pyindex 970de373b..e511417cc 100644--- a/tests/unit/server/test_risk_range.py+++ b/tests/unit/server/test_risk_range.py@@ -65,15 +65,19 @@ async def test_risk_range_happy_path(client: AsyncClient, git_repo: Path, tmp_paassert data["base"] == baseassert data["head"] == "HEAD"assert 0.0 <= data["score"] <= 10.0- assert 0.0 <= data["probability"] <= 1.0- assert data["level"] in {"low", "moderate", "high"}+ assert data["score_unit"] == "per-commit"assert data["is_fix"] is Trueassert data["features"]["nf"] == 2assert data["features"]["la"] == 3assert isinstance(data["drivers"], list) and len(data["drivers"]) > 0- # Only two commits sampled, below _MIN_BASELINE, so no percentile.+ # The collinear diffusion features stay out of the reported drivers.+ assert {d["feature"] for d in data["drivers"]}.isdisjoint({"nf", "nd", "ns"})+ # Only two commits sampled, below _MIN_BASELINE, so no percentile — which+ # is exactly when the absolute band is offered, and only then.assert data["risk_percentile"] is Noneassert data["review_priority"] is None+ assert data["classification"] is None+ assert data["fallback_band"] in {"low", "moderate", "high"}@pytest.mark.asynciodiff --git a/website/cli-reference.md b/website/cli-reference.mdindex 0c5bfaf32..125f589df 100644--- a/website/cli-reference.md+++ b/website/cli-reference.md@@ -554,7 +554,8 @@ repowise risk [REVSPEC] [OPTIONS]### Examples```bash-repowise risk # score HEAD+repowise risk # score uncommitted work, else HEAD+repowise risk HEAD # score the last commitrepowise risk main..HEAD # score a branch / PR rangerepowise risk --ext .ts,.tsx```diff --git a/website/mcp-server.md b/website/mcp-server.mdindex 83f9b48f4..16174d3dd 100644--- a/website/mcp-server.md+++ b/website/mcp-server.md@@ -365,16 +365,18 @@ Live risk scoring for one commit or a `base..head` range. Unlike `get_risk`refresh.**Parameters:**-- `revspec` (optional, string) — commit or `base..head` (default `"HEAD"`)+- `revspec` (optional, string) — commit or `base..head`; omit it to score uncommitted work- `extensions` (optional) — file suffixes to count (e.g. `[".py", ".ts"]`)- `exclude_patterns` (optional) — gitignore-style paths; combined with root `.riskignore`- `baseline` (optional, int) — recent commits for percentile ranking (default `200`)-**Returns:** Corpus-calibrated `score` / `probability` / `level`, repo-relative-`risk_percentile`, `review_priority`, `classification`, plus `impacted_tests`-when a per-test coverage map is ingested (`repowise coverage add`).+**Returns:** Repo-relative `risk_percentile`, `review_priority` and+`classification`, the raw `score` with the `score_unit` it is calibrated on, a+`fallback_band` when there was no baseline to rank against, plus+`impacted_tests` when a per-test coverage map is ingested (`repowise coverage add`).-**When to use:** Before merging a commit or PR range.+**When to use:** Before merging a commit or PR range, or on work you have not+committed yet.**Example:**```