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(risk): lead change risk with the bug-fix history of the files it touches (#1593)

Raghav Chamadiyab4f19b4c0e24
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 5b11f1225..7fb12e13b 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -432,11 +432,18 @@ shape of the live diff and needs no index refresh.
| `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:** 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
+**Returns:** `fix_history` first — the recency-weighted bug-fix record of the
+files the change touches, with `files` naming where the pressure sits and
+`percentile` ranking it against the repo's own fix-bearing files. Triage on
+this: it is the part that separates a small edit to a fragile file from a large
+edit to a safe one. `available` is false when the history walk could not run.
+
+`score` measures diff size and spread, not where the change lands — see
+`score_measures` — and `score_unit` names the unit it is calibrated on (a single
+commit, so a PR-sized range reads high by construction). `risk_percentile`,
+`review_priority` and `classification` rank that same diff shape against recent
+commits. `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.
diff --git a/docs/layers/CHANGE_RISK.md b/docs/layers/CHANGE_RISK.md
index f885466fe..6959d3627 100644
--- a/docs/layers/CHANGE_RISK.md
+++ b/docs/layers/CHANGE_RISK.md
@@ -1,10 +1,14 @@
# 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.
+`repowise risk` reports on a **change** (a commit or a `base..head` range): the
+bug-fix history of the files it touches, and the shape of its diff. It is a
+just-in-time / pre-merge signal, complementary to `repowise health`, which
+scores files rather than changes.
+
+**Read `fix_history` first, not `score`.** The 0–10 score measures how big and
+spread out a change is. It does not measure where the change lands, and the two
+are not the same question — see [What the score does and does not
+buy](#what-the-score-does-and-does-not-buy).
```bash
repowise risk # score uncommitted work, else HEAD
@@ -39,7 +43,66 @@ those patterns apply automatically and are combined with any command-line
flags. For example, `tests/` excludes that directory recursively, while
`test_*.py` excludes matching test filenames anywhere in the repository.
-## What it measures
+## Fix history: where the change lands
+
+The first block in the result is `fix_history`, and it is the one to act on. It
+answers a question the diff shape cannot: **have these files broken before?**
+
+```
+These files have broken before · 82nd percentile of this repo's fix-bearing files
+┌──────────────────────────────────────────┬───────┬─────────────┐
+│ File │ Lines │ Prior fixes │
+├──────────────────────────────────────────┼───────┼─────────────┤
+│ core/pipeline/persist.py │ 40 │ 21.6 │
+│ cli/commands/update_cmd/command.py │ 6 │ 19.3 │
+└──────────────────────────────────────────┴───────┴─────────────┘
+```
+
+- **Prior fixes** is a count of bug-fix commits that previously touched that
+ file, **recency-weighted against the change's own date**: a fix from a year
+ earlier counts a half, from two years a quarter. So the number is
+ "recent-equivalent fixes", not a raw tally, and a file that broke constantly
+ and then settled decays away. Anchoring to the change rather than to today
+ means the same commit scores the same on every re-run.
+- **`density`** is the churn-weighted mean of those per-file numbers. Weighting
+ by churn means the file a change mostly edits dominates the answer rather than
+ a one-line drive-by next door. It is a *ratio*, so unlike the score it does
+ not grow with the size of the diff: one line in a file fixed twenty times
+ outranks a thousand lines in files never fixed at all.
+- **`percentile`** ranks that density against the repository's own fix-bearing
+ files, since a bare "3.4 decayed fixes" means nothing on its own. Both sides
+ are the same unit, so the comparison is like for like. It is `null` when the
+ repo has fewer than eight files with any fix history, or when the change
+ touches none of it.
+
+This comes from one `git log` walk (up to 20 000 commits, memoized per
+repository state) using the same bug-fix classifier the indexer uses. It needs
+no index, no database and no coverage data, so it is available on a repository
+`repowise` has never indexed.
+
+Fix history is read from **before** the change being scored: a commit is ranked
+against the fixes that had already landed when it was written, never against
+fixes it caused. For a range, the record is read at the fork point the diff
+starts from, not at the base branch's current tip.
+
+> **Caveat, stated rather than buried.** The bug-fix classifier is keyword-based
+> and shared with the indexer, so `fix_history` under-reports in two ways.
+>
+> It matches `fix`, `bug`, `patch`, `resolves`, `closes #N`, `fixes #N` — and
+> misses conventions outside that set. Django's `Fixed #12345` is the notable
+> one: on a 4 000-commit sample it classifies 5 commits as fixes where roughly
+> 1 800 use that prefix. (Django also uses `Fixed #N` for features, so the
+> subject line alone cannot separate the two — which is why the classifier has
+> not simply been widened.)
+>
+> It also **excludes** any subject containing `docs`, `typo`, `bump`, `deps`,
+> `chore`, `lint`, `format` or `style`. That keeps cosmetic commits out, but
+> drops genuine fixes like "fix: docs build crash" with them.
+>
+> Where the classifier fires the ranking is good; where a project's convention
+> falls outside it, `fix_history` reads lower than the truth.
+
+## What the diff-shape score measures
The model uses Kamei-style *change* metrics (Kamei et al., "A large-scale
empirical study of just-in-time quality assurance"):
@@ -64,30 +127,55 @@ log-compressed features (`logit = intercept + Σ coefᵢ·zᵢ`), so every featu
push on the risk is exact and reported as an attributable driver (the same
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 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** / **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.
+## What the score does and does not buy
+
+The score is a **diff-size statistic**. That is a measured claim, not a hedge:
+
+- `la` (lines added) carries a coefficient 7.6× the next largest, and scoring by
+ `la` alone reproduces the full seven-feature score to within 0.12–0.16 points
+ on every repository tried.
+- On a hand-picked set of small-but-dangerous changes versus large-but-boring
+ ones (47 within-repo pairs across repowise, flask, django and zod), the score
+ ranks the dangerous change above the boring one in **0 of 47** pairs. Ranking
+ by fix density alone gets **46 of 47**.
+
+ That set is constructed, not held out: the pairs were chosen so that the
+ dangerous change is always the smaller one, which means ranking by lines added
+ scores 0 by construction and any signal genuinely independent of size scores
+ near-perfectly. It is a falsification test — "can the score ever do this?" —
+ and not an accuracy estimate. Its value is that the score failed it
+ completely, on cases a reviewer would call obvious.
+
+A refit was measured and rejected rather than shipped. Regrouping the corpus to
+PR granularity (`--first-parent` merge spans) and adding two size-orthogonal
+features made accuracy *worse*: pooled leave-one-repo-out AUC 0.769 for the
+refit against 0.776 for the current feature set and 0.780 for a churn-only
+baseline. Per repository, **lines added alone matches or beats the fitted model
+in five of six repos**. The reason is the labels: a commit is marked
+defect-inducing when a later bug-fix's blame points back at a line it wrote, and
+a larger commit writes more lines, so the label is itself size-biased. Any
+deliberately size-orthogonal feature scores near chance against it — fix density
+lands at 0.46–0.57 AUC — which is a fact about the labels, not about the
+feature. So the model constants are unchanged and the score is reported as what
+it demonstrably is.
+
+`score_measures` states this in the payload. Read the result in this order:
+
+- **`fix_history`**: where the change lands. The signal to triage on.
+- **Review priority** / **classification** / **percentile**: where this change's
+ *diff shape* sits in the repo's own distribution. Useful for "is this a big
+ one for us", not for "is this a dangerous one".
+- **`score`** (0–10): diff size and spread, corpus-anchored to a single commit.
- **`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.
+The score's absolute band is also **unit-blind**. Its corpus is individual
+commits (baseline: 10.5 lines added, 1.7 files), so a squash-merged PR or a
+`base..head` range is several commits' worth of diff read against a one-commit
+scale and skews high: two-thirds of commits can read "high" while ranking
+normally for *that* repo. The payload states the assumption in `score_unit`.
+
Each **driver** is reported relative to *the model's baseline commit* (the
calibration-corpus mean), not this repo, so a `+19 / −1` change can legitimately
read "more lines added than baseline" while still ranking `Below typical` for a
@@ -134,14 +222,26 @@ 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`.
+churn-only** (Δ +0.0068, 95% CI [-0.0003, +0.0131]).
+
+Read that number for what it is. A churn-only baseline scores 0.766 on the same
+labels, and lines-added alone scores higher still, so the margin measures very
+little. It is reported because it is the number the constants were selected on,
+not as evidence the score ranks danger — for that claim, see
+[What the score does and does not buy](#what-the-score-does-and-does-not-buy),
+where it fails.
+
+**`fix_history` carries no AUC of its own, deliberately.** Its evidence is the
+47-pair ranking gate (46/47) and the fact that the files it ranks highest in
+this repository are the ones with the longest bug-fix records. It scores near
+chance against the SZZ labels, which — as above — is a property of those labels.
+Quoting a number from a benchmark that structurally cannot see the signal would
+be worse than quoting none.
+
+Only learned constants ship; the runtime stays deterministic, zero-LLM, and
+free of new dependencies. Recalibrate via
+`repowise-bench/health-defect/jit_calibration.py`; the constants live in
+`packages/core/src/repowise/core/analysis/change_risk/model.py`.
## Cross-repo change risk (workspace mode)
diff --git a/examples/risk/README.md b/examples/risk/README.md
index d0837fe47..f238de5f0 100644
--- a/examples/risk/README.md
+++ b/examples/risk/README.md
@@ -23,9 +23,12 @@ repowise risk main..HEAD # whole branch / PR as one change
repowise risk HEAD~5..HEAD # recent local work
```
-The headline is **repo-relative**: percentile and review priority
-(`Below typical` / `Typical` / `Elevated`) among recent commits. The raw
-0–10 model score is secondary context.
+The headline is **fix history**: which of the touched files have needed bug
+fixes before, recency-weighted, and where that sits among this repo's
+fix-bearing files. Below it, the diff shape — percentile and review priority
+(`Below typical` / `Typical` / `Elevated`) among recent commits, and the 0–10
+score, which measures how large and spread out the change is rather than how
+dangerous.
## 2. Narrow what counts
diff --git a/packages/api-client/src/risk.ts b/packages/api-client/src/risk.ts
index b71fe3f74..328fd0202 100644
--- a/packages/api-client/src/risk.ts
+++ b/packages/api-client/src/risk.ts
@@ -18,10 +18,35 @@ export interface RiskRangeParams {
baseline?: number;
}
+export interface FixHistoryFile {
+ path: string;
+ churn: number;
+ /** Prior bug fixes on this file, recency-weighted (a year ago counts a half). */
+ fix_pressure: number;
+}
+
+/**
+ * Bug-fix history of the files a change touches — the part of the answer that
+ * does not grow with the diff, and the part `score` cannot see.
+ */
+export interface FixHistory {
+ /** False when the history walk could not run — not the same as "no fixes". */
+ available: boolean;
+ /** Churn-weighted mean fix pressure across the changed files. */
+ density: number;
+ /** Rank against this repo's own fix-bearing files; null if too few to rank. */
+ percentile: number | null;
+ files: FixHistoryFile[];
+}
+
export interface RiskRangeResponse {
base: string;
head: string;
+ /** Where the change lands. Read before `score`. */
+ fix_history: FixHistory;
score: number;
+ /** What `score` measures: diff size and spread, not where the change lands. */
+ score_measures: string;
/** The unit `score` is calibrated on: a single commit, not a whole range. */
score_unit: string;
risk_percentile: number | null;
diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.py
index 38e59caa0..b7a0746ca 100644
--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py
@@ -38,7 +38,6 @@ from repowise.core.analysis.change_risk import (
score_live_change,
)
-_PRIORITY_COLOR = {"high": "yellow", "moderate": "dim", "low": "green"}
_PRIORITY_LEAD = {
"low": "Lower risk than a typical commit in this repo",
"moderate": "About as risky as a typical commit in this repo",
@@ -486,21 +485,28 @@ def risk_command(
click.echo(json.dumps(change_risk_payload(result), indent=2))
return
- if percentile is not None and priority is not None:
- pcolor = _PRIORITY_COLOR[priority]
+ # The headline is the fix record, not the score: the score restates diff
+ # size, so leading with it put the least informative number first.
+ if not result.fix_history_available:
+ console.print(
+ f"\n[bold]Change risk[/bold] for [cyan]{features.ref}[/cyan]: "
+ "[yellow]fix history unavailable[/yellow] (the git history walk failed)"
+ )
+ elif result.hot_files:
+ where = (
+ f" · {_ordinal(round(result.fix_percentile))} percentile of this repo's "
+ "fix-bearing files"
+ if result.fix_percentile is not None
+ else ""
+ )
console.print(
f"\n[bold]Change risk[/bold] for [cyan]{features.ref}[/cyan]: "
- f"[{pcolor}]{review_priority_classification(priority)}[/{pcolor}] · "
- f"{_ordinal(round(percentile))} percentile of recent commits"
+ f"[red]touches files that have broken before[/red]{where}"
)
else:
- # No usable baseline (shallow repo, --baseline 0): fall back to the
- # absolute calibrated band, labelled honestly as such.
- 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 per-commit band — "
- "no repo baseline to rank against)"
+ "[green]no bug-fix history in the files it touches[/green]"
)
if result.working_tree:
console.print(" [dim]Scoring your uncommitted changes, not the last commit.[/dim]")
@@ -515,20 +521,42 @@ def risk_command(
f"{'unknown' if features.exp is None else features.exp}"
+ (" [magenta](fix)[/magenta]" if features.is_fix else "")
)
+ # The fix record, named in the headline above and itemized here.
+ if result.hot_files:
+ hot = Table(show_header=True)
+ hot.add_column("File")
+ hot.add_column("Lines", justify="right")
+ hot.add_column("Prior fixes", justify="right")
+ for path, churn, pressure in result.hot_files:
+ hot.add_row(path, str(churn), f"{pressure:.1f}")
+ console.print(hot)
+ console.print(
+ " [dim]Prior fixes are recency-weighted against this change's own date — "
+ "one from a year earlier counts a half.[/dim]"
+ )
+
+ # Diff shape second, and labelled for what it measures rather than as a
+ # verdict. The absolute band appears only when no percentile outranks it.
if percentile is not None and priority is not None:
console.print(
- f" [dim]{_PRIORITY_LEAD[priority]} ({_ordinal(round(percentile))} percentile).[/dim]"
+ f"\n[bold]Diff shape[/bold]: {review_priority_classification(priority)} · "
+ f"{_ordinal(round(percentile))} percentile of recent commits by size and spread"
+ )
+ console.print(f" [dim]{_PRIORITY_LEAD[priority]}.[/dim]")
+ else:
+ # No usable baseline (shallow repo, --baseline 0): fall back to the
+ # absolute calibrated band, labelled honestly as such.
+ color = {"high": "red", "moderate": "yellow", "low": "green"}[risk.level]
+ console.print(
+ f"\n[bold]Diff shape[/bold]: [{color}]{risk.level}[/{color}] "
+ "(absolute per-commit band — no repo baseline to rank against)"
)
- # 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 to a single commit; "
- f"prefer the percentile for review order.[/dim]"
+ f" [dim]Diff-size score: {risk.score:.1f}/10 — how big and spread out the change is, "
+ f"not where it lands. Corpus-anchored to a single commit.[/dim]"
)
- table = Table(title="Why this score (each driver vs. the model's baseline commit)")
+ table = Table(title="Diff shape (each driver vs. the model's baseline commit)")
table.add_column("Driver")
table.add_column("Value", justify="right")
table.add_column("Push", justify="right")
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 2aedbcac5..950003869 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/__init__.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/__init__.py
@@ -20,7 +20,15 @@ from .features import (
features_from_file_changes,
working_tree_is_dirty,
)
-from .model import SCORE_UNIT, ChangeRisk, RiskDriver, score_change
+from .fix_history import (
+ FixHistoryUnavailableError,
+ change_fix_density,
+ clear_fix_pressure_cache,
+ fix_density_percentile,
+ fix_pressure,
+ hot_files,
+)
+from .model import SCORE_MEASURES, SCORE_UNIT, ChangeRisk, RiskDriver, score_change
from .normalize import RiskNormalizer, review_priority_classification
from .service import (
ChangeRiskResult,
@@ -32,20 +40,27 @@ from .service import (
)
__all__ = [
+ "SCORE_MEASURES",
"SCORE_UNIT",
"WORKING_TREE_REF",
"ChangeFeatures",
"ChangeRisk",
"ChangeRiskResult",
+ "FixHistoryUnavailableError",
"RiskDriver",
"RiskNormalizer",
"baseline_samples",
"change_features_from_stored",
+ "change_fix_density",
"change_risk_payload",
+ "clear_fix_pressure_cache",
"extract_commit_features",
"extract_range_features",
"extract_worktree_features",
"features_from_file_changes",
+ "fix_density_percentile",
+ "fix_pressure",
+ "hot_files",
"normalize_extensions",
"range_anchor",
"review_priority_classification",
diff --git a/packages/core/src/repowise/core/analysis/change_risk/features.py b/packages/core/src/repowise/core/analysis/change_risk/features.py
index 73cf1ca26..d1cd4cf7d 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/features.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/features.py
@@ -50,6 +50,10 @@ class ChangeFeatures:
author: str = ""
subject: str = ""
ref: str = "" # the commit sha or "base..head" range scored
+ # ``(path, churn)`` per counted file, from the same walk the counts above
+ # come from. Carried so fix-history attribution costs no extra git call.
+ # Empty when the vector was rebuilt from stored metrics, which keep no paths.
+ file_churn: tuple[tuple[str, int], ...] = ()
# Generous ceiling: even a 200-commit numstat walk finishes in seconds. The
@@ -82,11 +86,12 @@ def _git(args: list[str], cwd: str, *, check: bool = True) -> str:
def _accumulate_numstat(
numstat: str, extensions: tuple[str, ...], exclude_patterns: tuple[str, ...]
-) -> tuple[int, int, int, set[str], set[str], list[int]]:
+) -> tuple[int, int, int, set[str], set[str], list[int], list[tuple[str, int]]]:
la = ld = nf = 0
dirs: set[str] = set()
subs: set[str] = set()
per_file: list[int] = []
+ files: list[tuple[str, int]] = []
exclude_spec = pathspec.PathSpec.from_lines("gitwildmatch", exclude_patterns)
for row in numstat.strip().split("\n"):
if not row:
@@ -107,10 +112,11 @@ def _accumulate_numstat(
churn = a + d
if churn:
per_file.append(churn)
+ files.append((path, churn))
segs = path.split("/")
dirs.add("/".join(segs[:-1]))
subs.add(segs[0])
- return la, ld, nf, dirs, subs, per_file
+ return la, ld, nf, dirs, subs, per_file, files
def _entropy(per_file: list[int]) -> float:
@@ -165,6 +171,7 @@ def features_from_file_changes(
dirs: set[str] = set()
subs: set[str] = set()
per_file: list[int] = []
+ files: list[tuple[str, int]] = []
for path, additions, deletions in changes:
a = max(int(additions or 0), 0)
d = max(int(deletions or 0), 0)
@@ -174,6 +181,7 @@ def features_from_file_changes(
churn = a + d
if churn:
per_file.append(churn)
+ files.append((path, churn))
segs = path.split("/")
dirs.add("/".join(segs[:-1]))
subs.add(segs[0])
@@ -189,6 +197,7 @@ def features_from_file_changes(
author=author,
subject=subject,
ref=ref,
+ file_churn=tuple(files),
)
@@ -289,7 +298,9 @@ def extract_worktree_features(
]
if rows:
numstat = numstat.rstrip("\n") + "\n" + "\n".join(rows)
- la, ld, nf, dirs, subs, per_file = _accumulate_numstat(numstat, extensions, exclude_patterns)
+ la, ld, nf, dirs, subs, per_file, files = _accumulate_numstat(
+ numstat, extensions, exclude_patterns
+ )
author = _git(["config", "user.name"], root, check=False).strip()
return ChangeFeatures(
la=la,
@@ -299,6 +310,7 @@ def extract_worktree_features(
ns=len(subs),
entropy=_entropy(per_file),
exp=_author_experience(root, author, "HEAD"),
+ file_churn=tuple(files),
is_fix=False,
author=author,
subject="",
@@ -326,7 +338,9 @@ def extract_commit_features(
# 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)
+ la, ld, nf, dirs, subs, per_file, files = _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()
exp = _author_experience(repo_path, author, parent or sha)
@@ -342,6 +356,7 @@ def extract_commit_features(
author=author,
subject=subject,
ref=sha,
+ file_churn=tuple(files),
)
@@ -360,7 +375,9 @@ def extract_range_features(
commit count at *base*.
"""
numstat = _git(["diff", "--numstat", f"{base}..{head}"], repo_path)
- la, ld, nf, dirs, subs, per_file = _accumulate_numstat(numstat, extensions, exclude_patterns)
+ la, ld, nf, dirs, subs, per_file, files = _accumulate_numstat(
+ numstat, extensions, exclude_patterns
+ )
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).
@@ -379,4 +396,5 @@ def extract_range_features(
author=author,
subject=subject,
ref=f"{base}..{head}",
+ file_churn=tuple(files),
)
diff --git a/packages/core/src/repowise/core/analysis/change_risk/fix_history.py b/packages/core/src/repowise/core/analysis/change_risk/fix_history.py
new file mode 100644
index 000000000..2e09e6d8b
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/change_risk/fix_history.py
@@ -0,0 +1,231 @@
+"""Per-file bug-fix pressure, derived from git alone.
+
+The change-risk features in :mod:`.features` describe the *shape* of a diff —
+how big it is and how far it spreads. Shape says nothing about where the diff
+lands, so a 40-line edit to a file that has broken twenty times reads lower than
+a 400-line bulk rename of files that have never broken at all.
+
+This module supplies the missing half: how much bug-fix history sits in the
+files a change touches. Pure ``git log`` (no index, no DB, no LLM), so it is
+available on the CLI path and on a repository that was never indexed, and it
+uses the same fix-commit classifier the indexer does.
+
+Note that the *classifier* is shared but the *count* is not: the indexed
+``prior_defect`` applies a 180-day hard window, and the MCP ``prior_fixes``
+block counts only fixes whose edited lines overlap the diff. This module is
+whole-file and recency-decayed rather than windowed or line-scoped, so its
+number is the broadest of the three by design.
+"""
+
+from __future__ import annotations
+
+import subprocess
+from collections.abc import Iterable
+
+from ...ingestion.git_indexer._constants import is_fix_commit
+from .features import GIT_TIMEOUT_SECONDS, _git
+
+#: How far back to walk for fix history. Matches the git indexer's
+#: ``_DEEP_WALK_COMMIT_LIMIT``: deep enough that a long-lived file's fix record
+#: is essentially complete, bounded so a 100k-commit monorepo cannot turn one
+#: score into a minute of git. Measured on django (34k commits): the full walk
+#: and a 20k walk rank identically, while 10k already loses long-lived files.
+DEEP_WALK_LIMIT = 20_000
+
+#: Half-life for recency decay, in days. A file fixed last month is a live
+#: hazard; the same file fixed twice a decade ago is history. Swept against the
+#: ranking gate at 180 / 365 / 730 days and no decay: 365, 730 and no decay all
+#: scored 46/47 and 180 scored 44/47, so anything from a year up is as good as
+#: the gate can distinguish. Picked at the near end of that range so recency
+#: still counts for something.
+FIX_HALF_LIFE_DAYS = 365.0
+
+#: Process-wide memo, same contract as the baseline sample's: one walk per
+#: repository state, shared by every change scored against it. Keyed on the
+#: resolved sha so a new commit busts the entry. Cleared wholesale on overflow,
+#: like the baseline memo — correctness is unaffected, the next call recomputes.
+_PRESSURE_CACHE: dict[tuple, dict[str, float]] = {}
+_PRESSURE_CACHE_MAX = 64
+
+
+class FixHistoryUnavailableError(RuntimeError):
+ """The fix-history walk could not be completed.
+
+ Raised rather than degrading to an empty record, because empty is
+ indistinguishable from "this repository has never had a bug fix" and the
+ surfaces say exactly that. Callers that would rather report a gap than fail
+ catch this and mark the block unavailable.
+ """
+
+
+def clear_fix_pressure_cache() -> None:
+ """Drop all memoized fix-pressure walks (test isolation / manual reset)."""
+ _PRESSURE_CACHE.clear()
+
+
+def _walk(repo_path: str, upto_ref: str, depth: int) -> dict[str, list[float]]:
+ """Commit timestamps of every bug-fix touching each file, up to *upto_ref*."""
+ try:
+ proc = subprocess.run(
+ [
+ "git", "log", f"-n{depth}", "--no-merges",
+ "--format=%x1e%ct%x1f%s", "--name-only", "--end-of-options", upto_ref,
+ ],
+ cwd=repo_path,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ stdin=subprocess.DEVNULL,
+ timeout=GIT_TIMEOUT_SECONDS,
+ )
+ except subprocess.TimeoutExpired as exc:
+ # A 20k-commit walk on a very large repository can outrun the timeout.
+ # That is a missing block, not a reason to fail the whole score.
+ raise FixHistoryUnavailableError(f"git log timed out after {GIT_TIMEOUT_SECONDS}s") from exc
+ if proc.returncode != 0:
+ raise FixHistoryUnavailableError((proc.stderr or "").strip() or "git log failed")
+ out = proc.stdout
+
+ history: dict[str, list[float]] = {}
+ for block in out.split("\x1e"):
+ block = block.strip("\n")
+ if not block:
+ continue
+ lines = block.split("\n")
+ head = lines[0].split("\x1f")
+ if len(head) != 2:
+ continue
+ try:
+ timestamp = float(head[0])
+ except ValueError:
+ continue
+ if not is_fix_commit(head[1]):
+ continue
+ for path in lines[1:]:
+ path = path.strip()
+ if path:
+ history.setdefault(path, []).append(timestamp)
+ return history
+
+
+def fix_pressure(
+ repo_path: str, upto_ref: str = "HEAD", *, depth: int = DEEP_WALK_LIMIT
+) -> dict[str, float]:
+ """Per-file recency-decayed bug-fix count, as of *upto_ref*.
+
+ Each prior fix contributes ``0.5 ** (age / half-life)``, where age is
+ measured back from *upto_ref*'s own commit date — not from wall clock and
+ not from the newest fix in the repository, either of which would make the
+ same file's pressure move when something unrelated changed. So the value is
+ "how many recent-equivalent fixes had this file had, at that point in
+ history", and two changes at different refs are comparable.
+
+ Files with no fix history are absent from the mapping rather than present
+ with a zero. Raises :class:`FixHistoryUnavailableError` if the walk fails.
+ """
+ sha = _git(["rev-parse", "--verify", "--quiet", upto_ref], repo_path, check=False).strip()
+ if not sha:
+ # Two reasons a ref will not resolve, and they are not the same answer.
+ # Inside a repository it means there is no history before this point — a
+ # root commit's ``sha^`` on the common path — and empty is correct.
+ # Outside one, nothing was looked at, and "no fixes" would be a claim we
+ # did not earn.
+ if not _git(["rev-parse", "--git-dir"], repo_path, check=False).strip():
+ raise FixHistoryUnavailableError(f"{repo_path} is not a git repository")
+ return {}
+ key = (repo_path, sha, depth)
+ if key in _PRESSURE_CACHE:
+ return _PRESSURE_CACHE[key]
+
+ history = _walk(repo_path, sha, depth)
+ as_of = float(_git(["show", "-s", "--format=%ct", sha], repo_path, check=False).strip() or 0.0)
+ half_life = FIX_HALF_LIFE_DAYS * 86400.0
+ pressure = {
+ path: sum(0.5 ** (max(as_of - t, 0.0) / half_life) for t in stamps)
+ for path, stamps in history.items()
+ }
+ if len(_PRESSURE_CACHE) >= _PRESSURE_CACHE_MAX:
+ _PRESSURE_CACHE.clear()
+ _PRESSURE_CACHE[key] = pressure
+ return pressure
+
+
+def rename_target(path: str) -> str:
+ """The post-rename path, for a numstat path that encodes a rename.
+
+ With rename detection on (git's default) ``--numstat`` reports a move as
+ ``src/{old => new}.py`` or ``old.py => new.py``, neither of which matches
+ the plain paths ``git log --name-only`` reports. Left unresolved, a file
+ that was moved *and* edited — the shape most likely to be both surgical and
+ dangerous — silently loses its whole fix record.
+ """
+ if "=>" not in path:
+ return path
+ if "{" in path and "}" in path:
+ prefix, _, rest = path.partition("{")
+ middle, _, suffix = rest.partition("}")
+ _, _, new = middle.partition("=>")
+ return f"{prefix}{new.strip()}{suffix}".replace("//", "/")
+ _, _, new = path.partition("=>")
+ return new.strip()
+
+
+def change_fix_density(
+ pressure: dict[str, float], changes: Iterable[tuple[str, int]]
+) -> float:
+ """Churn-weighted mean fix pressure over a change's ``(path, churn)`` pairs.
+
+ A ratio, deliberately: it answers "how dangerous is the ground this change
+ stands on", which is independent of how much of it there is. Weighting by
+ churn means the file a change mostly edits dominates the answer, rather than
+ a one-line drive-by in a neighbouring file.
+ """
+ weighted = 0.0
+ total = 0
+ for path, churn in changes:
+ if churn <= 0:
+ continue
+ weighted += churn * pressure.get(rename_target(path), 0.0)
+ total += churn
+ return weighted / total if total else 0.0
+
+
+#: How many fix-bearing files to name. Enough to show where the risk sits,
+#: short enough to stay readable on a wide PR.
+MAX_HOT_FILES = 5
+
+
+def hot_files(
+ pressure: dict[str, float], changes: Iterable[tuple[str, int]], *, limit: int = MAX_HOT_FILES
+) -> tuple[tuple[str, int, float], ...]:
+ """The change's fix-bearing files as ``(path, churn, pressure)``, worst first.
+
+ Shared by every surface so the CLI, the MCP payload and the HTTP API cannot
+ order or round the same list differently.
+ """
+ rows = [
+ (path, churn, pressure[rename_target(path)])
+ for path, churn in changes
+ if pressure.get(rename_target(path))
+ ]
+ rows.sort(key=lambda row: -row[2])
+ return tuple((path, churn, round(p, 2)) for path, churn, p in rows[:limit])
+
+
+def fix_density_percentile(pressure: dict[str, float], density: float) -> float | None:
+ """Where *density* sits among the repository's own fix-bearing files.
+
+ Both sides are in the same unit — decayed fixes — since the density is a
+ churn-weighted mean of exactly these per-file values. On its own that number
+ means nothing to a reader; against the files that actually carry fix history
+ it becomes a statement worth acting on. ``None`` when the repository has too
+ little fix history to rank against, or when the change touches none of it.
+ """
+ if density <= 0:
+ return None
+ values = [v for v in pressure.values() if v > 0]
+ if len(values) < 8:
+ return None
+ below = sum(1 for v in values if v < density)
+ return round(100.0 * below / len(values), 1)
diff --git a/packages/core/src/repowise/core/analysis/change_risk/model.py b/packages/core/src/repowise/core/analysis/change_risk/model.py
index 386353ba5..3132982bb 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/model.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/model.py
@@ -26,12 +26,20 @@ from .features import ChangeFeatures
# 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.
+# AUC 0.772 vs churn-only baseline 0.766 (Δ +0.0068 [95% CI -0.0003, +0.0131]).
+# 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.
+#
+# Kept unchanged deliberately. A PR-granularity refit adding two size-orthogonal
+# features was measured and scored *worse*: pooled LOO AUC 0.769 against 0.776
+# for this feature set and 0.780 for churn-only, with la alone matching or
+# beating the fitted model in five of six repos. The SZZ labels are size-biased
+# (a bigger commit writes more lines, so more of them get blamed later), so AUC
+# against them rewards predicting size and cannot see a size-orthogonal signal.
+# That is why the score is now reported as a diff-size statistic and the
+# fix-history block carries what it cannot. See SCORE_MEASURES below.
_CONSTANTS: dict[str, object] = {
"features": ["la", "ld", "nf", "nd", "ns", "entropy", "exp"],
"log1p": [True, True, True, True, True, False, True],
@@ -119,6 +127,19 @@ def _sigmoid(z: float) -> float:
#: construction. The repo-relative percentile is immune to this; the band is not.
SCORE_UNIT = "per-commit"
+#: What the score actually measures, stated wherever the score is emitted.
+#:
+#: Measured, not asserted: `la` (lines added) carries a coefficient 7.6x the next
+#: largest, and scoring by `la` alone reproduces the full score to within
+#: 0.12-0.16 points on every repo tried. Refitting at PR granularity with two
+#: size-orthogonal features added made this worse, not better (`la` 18x the next
+#: largest), because the SZZ labels the model is fit against are themselves
+#: size-biased: a bigger commit writes more lines, so more of its lines get
+#: blamed by a later fix. Ranking changes by lines-added alone beats the fitted
+#: model on that benchmark. So the score is reported as what it demonstrably is —
+#: a diff-size statistic — and ``fix_history`` carries the part that is not.
+SCORE_MEASURES = "diff size and spread; not where the change lands"
+
def _level(score: float) -> str:
"""Absolute calibrated band — the fallback when no percentile is available.
diff --git a/packages/core/src/repowise/core/analysis/change_risk/service.py b/packages/core/src/repowise/core/analysis/change_risk/service.py
index 5a4c94e8c..26d34c1e6 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/service.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/service.py
@@ -16,7 +16,14 @@ from .features import (
extract_worktree_features,
working_tree_is_dirty,
)
-from .model import SCORE_UNIT, ChangeRisk, score_change
+from .fix_history import (
+ FixHistoryUnavailableError,
+ change_fix_density,
+ fix_density_percentile,
+ fix_pressure,
+ hot_files,
+)
+from .model import SCORE_MEASURES, SCORE_UNIT, ChangeRisk, score_change
from .normalize import RiskNormalizer, review_priority_classification
_MIN_BASELINE = 8
@@ -24,7 +31,7 @@ _MIN_BASELINE = 8
@dataclass(frozen=True)
class ChangeRiskResult:
- """A live change score and its optional repository-relative ranking."""
+ """A live change score, its repo-relative ranking, and its fix-history load."""
features: ChangeFeatures
risk: ChangeRisk
@@ -34,6 +41,17 @@ class ChangeRiskResult:
riskignore_excludes: tuple[str, ...]
request_excludes: tuple[str, ...]
working_tree: bool = False # scored the uncommitted change, not a commit
+ # Bug-fix history of the ground this change stands on. ``density`` is the
+ # churn-weighted mean fix pressure of the touched files, ``percentile`` ranks
+ # it against the repo's own fix-bearing files, and ``hot_files`` names where
+ # the pressure is. Unlike the score, none of these grow with diff size.
+ fix_density: float = 0.0
+ fix_percentile: float | None = None
+ hot_files: tuple[tuple[str, int, float], ...] = () # (path, churn, pressure)
+ # False when the history walk could not run (git failure, timeout on a very
+ # large repository). Distinguishes "no fixes here" from "we could not look",
+ # which the surfaces would otherwise report identically.
+ fix_history_available: bool = True
def riskignore_patterns(repo_path: str) -> tuple[str, ...]:
@@ -134,6 +152,10 @@ def score_live_change(
# 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
+ # Ref whose history the fix record is read from. Strictly *before* the
+ # change being scored, so a commit is never credited with fixes that only
+ # landed because of it.
+ history_ref = "HEAD"
if working_tree:
features = uncommitted
anchor, excluded_ref = "HEAD", ""
@@ -144,14 +166,29 @@ def score_live_change(
features = extract_range_features(
repo_path, base, head, extensions=extensions, exclude_patterns=effective_excludes
)
- anchor, excluded_ref = range_anchor(repo_path, base, head), ""
+ # Fix history is read at the fork point, not at ``base``'s tip: with
+ # three-dot syntax the diff starts at the merge-base, so base's later
+ # commits are not part of this change's ground.
+ anchor = range_anchor(repo_path, base, head)
+ excluded_ref = ""
+ history_ref = anchor
else:
features = extract_commit_features(
repo_path, target, extensions=extensions, exclude_patterns=effective_excludes
)
anchor, excluded_ref = _commit_anchor(repo_path, target)
+ # A root commit has no parent; its own ref then yields an empty record,
+ # which is the honest answer for the first commit in a repository.
+ history_ref = f"{target}^"
risk = score_change(features)
+ try:
+ pressure = fix_pressure(repo_path, history_ref)
+ fix_history_available = True
+ except FixHistoryUnavailableError:
+ pressure, fix_history_available = {}, False
+ density = change_fix_density(pressure, features.file_churn)
+ fix_bearing = hot_files(pressure, features.file_churn)
percentile: float | None = None
priority: str | None = None
baseline_sample_size = 0
@@ -180,21 +217,39 @@ def score_live_change(
riskignore_excludes=from_riskignore,
request_excludes=exclude_patterns,
working_tree=working_tree,
+ fix_density=round(density, 3),
+ fix_percentile=fix_density_percentile(pressure, density),
+ hot_files=fix_bearing,
+ fix_history_available=fix_history_available,
)
def change_risk_payload(result: ChangeRiskResult) -> dict:
"""Render the machine-readable response shared by the CLI and MCP tool.
+ ``fix_history`` leads: it is the block that distinguishes a surgical edit to
+ a file that keeps breaking from a bulk rename of files that never have.
+ ``score`` and ``risk_percentile`` describe the *shape* of the diff and are
+ kept for continuity, labelled for what they measure — see ``score_measures``.
``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.
+ was no baseline to rank against. ``score_unit`` names the unit that band
+ assumes.
"""
features, risk = result.features, result.risk
return {
"ref": features.ref,
"working_tree": result.working_tree,
+ "fix_history": {
+ "available": result.fix_history_available,
+ "density": result.fix_density,
+ "percentile": result.fix_percentile,
+ "files": [
+ {"path": path, "churn": churn, "fix_pressure": pressure}
+ for path, churn, pressure in result.hot_files
+ ],
+ },
"score": risk.score,
+ "score_measures": SCORE_MEASURES,
"score_unit": SCORE_UNIT,
"risk_percentile": round(result.percentile, 1) if result.percentile is not None else None,
"review_priority": result.priority,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
index 8d70908d4..8570a96d3 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
@@ -47,24 +47,23 @@ async def get_change_risk(
) -> dict:
"""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
+ Use this for a pre-merge read on a commit or PR range. Distinct from
``get_risk``, which assesses indexed files and PR blast radius. Both filters
- below also apply to the baseline used for the repository percentile.
-
- 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 execute
- the change's changed *lines* (line-precise, narrower than get_risk's
- file-level ``tests_to_run``), with ``missing_tests`` buckets for changed
- lines no test covers. Its ``status`` is ``no_map`` (unknown, run the full
- suite), never "untested", when no map is ingested.
-
- ``prior_fixes`` appears only when the changed files carry counted bug fixes:
- per-file counts, never a commit name; ``concentration`` names where it sits.
+ below also apply to the baseline behind the repository percentile.
+
+ Lead with ``fix_history``: the recency-weighted bug-fix record of the files
+ touched, ``files`` naming where the pressure sits. It is what separates a
+ surgical edit to a file that keeps breaking from a bulk rename of files that
+ never have. ``score`` measures diff size and spread, not where the change
+ lands (see ``score_measures``); calibrated per commit, so a PR-sized change
+ reads high by construction. ``risk_percentile`` ranks that diff shape against
+ recent commits.
+
+ ``impacted_tests`` names the tests a coverage map proves execute the changed
+ *lines*, with ``missing_tests`` for lines no test covers; ``status`` is
+ ``no_map`` (unknown — run the full suite), never "untested", when no map is
+ ingested. ``prior_fixes`` asks the index the same question git answered
+ above, counting only fixes whose lines overlap this diff.
Args:
revspec: Commit or ``base..head`` range to score. Omit it to score the
diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.py
index ad180dc64..95fbec1bf 100644
--- a/packages/server/src/repowise/server/routers/git.py
+++ b/packages/server/src/repowise/server/routers/git.py
@@ -14,11 +14,17 @@ from sqlalchemy import case, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.change_risk import (
+ SCORE_MEASURES,
SCORE_UNIT,
+ FixHistoryUnavailableError,
RiskNormalizer,
baseline_samples,
change_features_from_stored,
+ change_fix_density,
extract_range_features,
+ fix_density_percentile,
+ fix_pressure,
+ hot_files,
range_anchor,
review_priority_classification,
score_change,
@@ -42,6 +48,8 @@ from repowise.server.schemas import (
CommitEvolutionResponse,
CommitResponse,
CommitStatsResponse,
+ FixHistoryFileResponse,
+ FixHistoryResponse,
GitMetadataResponse,
GitSummaryResponse,
HotspotResponse,
@@ -702,10 +710,29 @@ def get_risk_range(
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.
+ try:
+ pressure = fix_pressure(local_path, range_anchor(local_path, base, head))
+ fix_available = True
+ except FixHistoryUnavailableError:
+ pressure, fix_available = {}, False
+ density = change_fix_density(pressure, features.file_churn)
+
return RiskRangeResponse(
base=base,
head=head,
+ fix_history=FixHistoryResponse(
+ available=fix_available,
+ density=round(density, 3),
+ percentile=fix_density_percentile(pressure, density),
+ files=[
+ FixHistoryFileResponse(path=path, churn=churn, fix_pressure=p)
+ for path, churn, p in hot_files(pressure, features.file_churn)
+ ],
+ ),
score=risk.score,
+ score_measures=SCORE_MEASURES,
score_unit=SCORE_UNIT,
risk_percentile=percentile,
review_priority=priority,
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index 34e340e69..4a64e017a 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -77,6 +77,8 @@ from .git import (
CommitEvolutionResponse,
CommitResponse,
CommitStatsResponse,
+ FixHistoryFileResponse,
+ FixHistoryResponse,
GitMetadataResponse,
GitSummaryResponse,
HotspotResponse,
@@ -294,6 +296,8 @@ __all__ = [
"ExecutionFlowsResponse",
"ExternalSystemEntry",
"ExternalSystemsResponse",
+ "FixHistoryFileResponse",
+ "FixHistoryResponse",
"GitMetadataResponse",
"GitSummaryResponse",
"GoverningDecisionRef",
diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.py
index 7f84d04dd..5c35365c7 100644
--- a/packages/server/src/repowise/server/schemas/git.py
+++ b/packages/server/src/repowise/server/schemas/git.py
@@ -286,8 +286,33 @@ class ChangeFeaturesResponse(BaseModel):
exp: int | None
+class FixHistoryFileResponse(BaseModel):
+ """One changed file's recency-weighted bug-fix record."""
+
+ path: str
+ churn: int
+ fix_pressure: float
+
+
+class FixHistoryResponse(BaseModel):
+ """Bug-fix history of the files a change touches.
+
+ The size-orthogonal half of the answer: unlike ``score``, none of this grows
+ with the diff. ``density`` is the churn-weighted mean fix pressure of the
+ touched files; ``percentile`` ranks it against the repository's own
+ fix-bearing files, and is ``None`` when there is too little history to rank.
+ """
+
+ #: False when the history walk could not run — distinguishes "no fixes
+ #: here" from "we could not look".
+ available: bool
+ density: float
+ percentile: float | None
+ files: list[FixHistoryFileResponse]
+
+
class RiskRangeResponse(BaseModel):
- """Change-risk score for a live ``base..head`` git range.
+ """Change-risk report for a live ``base..head`` git range.
Scored on demand from the working tree rather than the indexed commit
table, so it works for ranges that haven't been indexed yet (an open PR
@@ -297,7 +322,12 @@ class RiskRangeResponse(BaseModel):
base: str
head: str
+ #: Where the change lands. Read this before ``score``: it is the part that
+ #: distinguishes a small edit to a fragile file from a large boring one.
+ fix_history: FixHistoryResponse
score: float
+ #: What ``score`` measures. It tracks diff size and spread, not danger.
+ score_measures: 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: str
diff --git a/packages/ui/src/commits/commit-detail-card.tsx b/packages/ui/src/commits/commit-detail-card.tsx
index 27e0557e4..b3a0bff78 100644
--- a/packages/ui/src/commits/commit-detail-card.tsx
+++ b/packages/ui/src/commits/commit-detail-card.tsx
@@ -82,8 +82,9 @@ export function CommitDetailCard({ commit, reviewCut, className }: CommitDetailC
</div>
<div className="mt-7">
+ {/* Named for what it measures: diff size, not danger. */}
<PageLede
- label="Change-risk score"
+ label="Diff-size score"
value={c.change_risk_score != null ? c.change_risk_score.toFixed(1) : "—"}
unit="out of 10"
badge={<PriorityBadge priority={c.review_priority} />}
diff --git a/packages/ui/src/commits/credibility-strip.tsx b/packages/ui/src/commits/credibility-strip.tsx
index 17fd8bd72..0803d10cc 100644
--- a/packages/ui/src/commits/credibility-strip.tsx
+++ b/packages/ui/src/commits/credibility-strip.tsx
@@ -8,10 +8,12 @@ import {
} from "../ui/tooltip";
/**
- * Honest credibility note for the change-risk model. The numbers are the
- * backtested leave-one-repo-out result from `docs/layers/CHANGE_RISK.md` — we show
- * them rather than imply the score is infallible. The model edges churn-only
- * on average and is stronger on some repos; it is a ranking aid, not a verdict.
+ * Honest note on what this score is. It used to lead with the backtested
+ * 0.772-vs-0.766 AUC, which overstated the case: a churn-only baseline scores
+ * 0.766 on those labels and lines-added alone scores higher than the model, so
+ * the margin measures very little. See `docs/layers/CHANGE_RISK.md`. The copy
+ * now says what the score tracks — diff size — rather than implying it ranks
+ * danger.
*/
/** Shared copy so the strip and the compact info button never drift. */
@@ -19,12 +21,13 @@ function CredibilityCopy() {
return (
<>
Change-risk is a calibrated linear model over each commit&apos;s diff shape
- (size, diffusion, author experience). Backtested leave-one-repo-out it scores{" "}
- <span className="font-medium text-[var(--color-text-primary)] tabular-nums">
- 0.772 AUC
- </span>{" "}
- vs <span className="tabular-nums">0.766</span> for a churn-only baseline — a
- ranking aid for review order, not a verdict. Priority is{" "}
+ (size, diffusion, author experience). In practice it tracks{" "}
+ <span className="font-medium text-[var(--color-text-primary)]">
+ how large a change is
+ </span>
+ , not where it lands: lines added alone reproduces it closely. Use it to
+ sort by size, and check a file&apos;s bug-fix history for whether the ground
+ is fragile. Priority is{" "}
<span className="font-medium">relative to this repo&apos;s own distribution</span>.
</>
);
diff --git a/packages/vscode/package.json b/packages/vscode/package.json
index 5af7fe1fb..dfdccf7da 100644
--- a/packages/vscode/package.json
+++ b/packages/vscode/package.json
@@ -403,7 +403,7 @@
"icon": "$(pulse)",
"tags": ["repowise"],
"when": "repowise.agentToolsEnabled",
- "modelDescription": "Score the defect risk of the current branch's changes against a base branch (0 to 10, higher is riskier), with the drivers behind the score. Use it after making changes to judge whether the change set needs extra review or tests before pushing.",
+ "modelDescription": "Report on the current branch's changes against a base branch. Lead with fix_history: the recency-weighted bug-fix record of the files touched, which is what separates a small dangerous change from a large boring one. The 0-10 score measures diff size and spread, not danger. Use it after making changes to judge whether the change set needs extra review or tests before pushing.",
"userDescription": "Defect risk score for the current branch.",
"inputSchema": {
"type": "object",
diff --git a/packages/vscode/src/features/lmTools.ts b/packages/vscode/src/features/lmTools.ts
index 5e58e8d8f..f7ba907f2 100644
--- a/packages/vscode/src/features/lmTools.ts
+++ b/packages/vscode/src/features/lmTools.ts
@@ -248,7 +248,11 @@ export function registerLmTools(ctx: RepowiseContext): vscode.Disposable {
const result = await getRiskRange(repoId, { base, head: "HEAD" });
return jsonResult({
base,
+ // First, because the score below measures diff size rather than danger,
+ // and a model handed only the score will read it as a verdict.
+ fix_history: result.fix_history,
score: result.score,
+ score_measures: result.score_measures,
score_unit: result.score_unit,
risk_percentile: result.risk_percentile,
review_priority: result.review_priority,
diff --git a/packages/vscode/webview/src/views/risk/App.test.tsx b/packages/vscode/webview/src/views/risk/App.test.tsx
index 49cd71fd0..bc03b84dd 100644
--- a/packages/vscode/webview/src/views/risk/App.test.tsx
+++ b/packages/vscode/webview/src/views/risk/App.test.tsx
@@ -14,7 +14,14 @@ const REPORT: RiskRangeReport = {
result: {
base: "main",
head: "HEAD",
+ fix_history: {
+ available: true,
+ density: 3.2,
+ percentile: 74,
+ files: [{ path: "src/core.ts", churn: 40, fix_pressure: 5.5 }],
+ },
score: 7.4,
+ score_measures: "diff size and spread; not where the change lands",
score_unit: "per-commit",
risk_percentile: 88,
review_priority: "high",
diff --git a/packages/vscode/webview/src/views/risk/App.tsx b/packages/vscode/webview/src/views/risk/App.tsx
index 775578f5d..a0fc29fa4 100644
--- a/packages/vscode/webview/src/views/risk/App.tsx
+++ b/packages/vscode/webview/src/views/risk/App.tsx
@@ -280,16 +280,46 @@ function ScoreHero({ report }: { report: RiskRangeReport }) {
<>There was no baseline of recent commits to rank it against.</>
)}
</p>
+ <FixHistoryNote history={r.fix_history} />
<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.
+ Diff-size score{" "}
+ <strong className="font-semibold tabular-nums">{r.score.toFixed(1)}/10</strong> — how big
+ and spread out the change is, not where it lands. Anchored to a corpus of single commits,
+ so a range reads high by construction.
</p>
</PageLede>
);
}
+/**
+ * The bug-fix record of the files this range touches — the part the diff-size
+ * score cannot see. Renders nothing when no touched file has fix history, which
+ * is itself worth not padding out.
+ */
+function FixHistoryNote({ history }: { history: RiskRangeReport["result"]["fix_history"] }) {
+ if (!history.available) {
+ return <p className="mt-2.5">Fix history unavailable — the git history walk failed.</p>;
+ }
+ if (!history.files.length) return null;
+ const [worst] = history.files;
+ return (
+ <p className="mt-2.5">
+ These files have broken before:{" "}
+ <strong className="font-semibold text-[var(--color-text-primary)]">{worst.path}</strong> has{" "}
+ <strong className="font-semibold tabular-nums">{worst.fix_pressure.toFixed(1)}</strong>{" "}
+ recency-weighted prior fixes
+ {history.files.length > 1 ? `, and ${history.files.length - 1} more do too` : ""}
+ {history.percentile != null ? (
+ <>
+ {" "}
+ — {ordinal(history.percentile)} percentile of this repo&apos;s fix-bearing files
+ </>
+ ) : null}
+ .
+ </p>
+ );
+}
+
/** Quiet one-line summary of the blast data. Each chip anchors its section;
* zero counts render no chip, and a clean tree renders nothing at all. */
function VerdictStrip({
diff --git a/tests/unit/analysis/test_change_risk_fix_history.py b/tests/unit/analysis/test_change_risk_fix_history.py
new file mode 100644
index 000000000..e9fa503b4
--- /dev/null
+++ b/tests/unit/analysis/test_change_risk_fix_history.py
@@ -0,0 +1,197 @@
+"""Fix-history pressure: the size-orthogonal half of the change-risk answer.
+
+The score restates diff size, so these tests are mostly about the property the
+score does not have: a small change to a file that keeps breaking must read as
+carrying more fix history than a large change to files that never have.
+"""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.change_risk import (
+ FixHistoryUnavailableError,
+ change_fix_density,
+ change_risk_payload,
+ clear_fix_pressure_cache,
+ fix_density_percentile,
+ fix_pressure,
+ score_live_change,
+)
+from repowise.core.analysis.change_risk.fix_history import rename_target
+
+
+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) -> 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", "user.name=Dev", "-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()
+
+
[email protected](autouse=True)
+def _clear_cache():
+ clear_fix_pressure_cache()
+ yield
+ clear_fix_pressure_cache()
+
+
+def repo_with_history(tmp_path: Path) -> Path:
+ """A repo where ``hot.py`` has broken repeatedly and ``cold.py`` never has."""
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(["init", "-q"], repo)
+ _git(["config", "user.name", "Dev"], repo)
+ _git(["config", "user.email", "[email protected]"], repo)
+ _commit(repo, {"hot.py": "v = 0\n", "cold.py": "c = 0\n"}, "feat: seed")
+ for i in range(1, 4):
+ _commit(repo, {"hot.py": f"v = {i}\n"}, f"fix: crash number {i}")
+ # Feature work on cold.py, so it has churn history but no fix history.
+ for i in range(1, 4):
+ _commit(repo, {"cold.py": f"c = {i}\n"}, f"feat: add capability {i}")
+ return repo
+
+
+def test_fix_pressure_counts_only_fix_commits(repo_with_history: Path) -> None:
+ pressure = fix_pressure(str(repo_with_history), "HEAD")
+ assert pressure["hot.py"] == pytest.approx(3.0, abs=0.05)
+ assert "cold.py" not in pressure # churn is not fix history
+
+
+def test_fix_density_is_orthogonal_to_diff_size(repo_with_history: Path) -> None:
+ """One line in the fragile file outranks a thousand in the safe one."""
+ pressure = fix_pressure(str(repo_with_history), "HEAD")
+ surgical = change_fix_density(pressure, [("hot.py", 1)])
+ bulk = change_fix_density(pressure, [("cold.py", 1000)])
+ assert surgical > bulk
+ assert bulk == 0.0
+
+
+def test_fix_density_is_churn_weighted(repo_with_history: Path) -> None:
+ """The file a change mostly edits dominates, not a one-line drive-by."""
+ pressure = fix_pressure(str(repo_with_history), "HEAD")
+ mostly_hot = change_fix_density(pressure, [("hot.py", 90), ("cold.py", 10)])
+ mostly_cold = change_fix_density(pressure, [("hot.py", 10), ("cold.py", 90)])
+ assert mostly_hot > mostly_cold
+
+
+def test_fix_history_excludes_the_change_being_scored(repo_with_history: Path) -> None:
+ """A commit is never credited with fix history it created itself."""
+ sha = _commit(repo_with_history, {"hot.py": "v = 99\n"}, "fix: one more crash")
+ before = fix_pressure(str(repo_with_history), f"{sha}^")
+ after = fix_pressure(str(repo_with_history), sha)
+ assert after["hot.py"] > before["hot.py"]
+ result = score_live_change(str(repo_with_history), sha, baseline=0)
+ # Scored against the parent's record — three prior fixes, not four.
+ assert result.fix_density == pytest.approx(before["hot.py"], abs=0.05)
+
+
+def test_percentile_needs_enough_fix_bearing_files(repo_with_history: Path) -> None:
+ pressure = fix_pressure(str(repo_with_history), "HEAD")
+ assert fix_density_percentile(pressure, 1.0) is None # only one such file
+
+
+def test_percentile_is_none_when_the_change_touches_no_fix_history() -> None:
+ """Not "0th percentile" — the question does not apply, and 0 reads as a rank."""
+ pressure = {f"f{i}.py": float(i + 1) for i in range(10)}
+ assert fix_density_percentile(pressure, 0.0) is None
+ assert fix_density_percentile(pressure, 5.5) is not None
+
+
+def test_decay_is_anchored_to_the_change_not_to_the_latest_fix(tmp_path: Path) -> None:
+ """A file's pressure must not move because an unrelated file was fixed.
+
+ Anchoring decay to the newest fix anywhere in the repo would rescale every
+ value whenever any fix landed, so the same commit would score differently
+ on two runs and two commits would not be comparable.
+ """
+ repo = tmp_path / "anchored"
+ repo.mkdir()
+ _git(["init", "-q"], repo)
+ _git(["config", "user.name", "Dev"], repo)
+ _git(["config", "user.email", "[email protected]"], repo)
+ _commit(repo, {"a.py": "a = 0\n", "b.py": "b = 0\n"}, "feat: seed")
+ _commit(repo, {"a.py": "a = 1\n"}, "fix: a breaks")
+ sha = _commit(repo, {"a.py": "a = 2\n"}, "refactor: tidy a")
+ before = fix_pressure(str(repo), sha)["a.py"]
+
+ clear_fix_pressure_cache()
+ _commit(repo, {"b.py": "b = 1\n"}, "fix: b breaks, unrelated to a")
+ after = fix_pressure(str(repo), sha)["a.py"]
+ assert after == pytest.approx(before)
+
+
+ ("numstat_path", "expected"),
+ [
+ ("src/{old => new}.py", "src/new.py"),
+ ("old.py => new.py", "new.py"),
+ ("{a => b}/mod.py", "b/mod.py"),
+ ("plain/path.py", "plain/path.py"),
+ ],
+)
+def test_rename_target_resolves_numstat_rename_syntax(numstat_path: str, expected: str) -> None:
+ """A moved-and-edited file must not lose its fix record to path syntax."""
+ assert rename_target(numstat_path) == expected
+
+
+def test_failed_walk_raises_rather_than_reporting_no_history(tmp_path: Path) -> None:
+ """An empty record and a failed lookup must not read the same."""
+ not_a_repo = tmp_path / "empty"
+ not_a_repo.mkdir()
+ with pytest.raises(FixHistoryUnavailableError):
+ fix_pressure(str(not_a_repo), "HEAD", depth=10)
+
+
+def test_payload_leads_with_fix_history(repo_with_history: Path) -> None:
+ _commit(repo_with_history, {"hot.py": "v = 42\n"}, "refactor: tidy")
+ payload = change_risk_payload(score_live_change(str(repo_with_history), "HEAD", baseline=0))
+ block = payload["fix_history"]
+ assert block["density"] > 0
+ assert [f["path"] for f in block["files"]] == ["hot.py"]
+ assert block["files"][0]["fix_pressure"] > 0
+ # The score is still emitted, but says what it measures.
+ assert "size" in payload["score_measures"]
+
+
+def test_hot_files_are_ordered_by_pressure(tmp_path: Path) -> None:
+ repo = tmp_path / "multi"
+ repo.mkdir()
+ _git(["init", "-q"], repo)
+ _git(["config", "user.name", "Dev"], repo)
+ _git(["config", "user.email", "[email protected]"], repo)
+ _commit(repo, {"a.py": "a = 0\n", "b.py": "b = 0\n"}, "feat: seed")
+ for i in range(1, 5):
+ _commit(repo, {"a.py": f"a = {i}\n"}, f"fix: a breaks {i}")
+ _commit(repo, {"b.py": "b = 1\n"}, "fix: b breaks once")
+ _commit(repo, {"a.py": "a = 9\n", "b.py": "b = 9\n"}, "refactor: touch both")
+
+ result = score_live_change(str(repo), "HEAD", baseline=0)
+ assert [path for path, _, _ in result.hot_files] == ["a.py", "b.py"]
+
+
+def test_repo_without_fix_history_reports_nothing(tmp_path: Path) -> None:
+ repo = tmp_path / "clean"
+ repo.mkdir()
+ _git(["init", "-q"], repo)
+ _git(["config", "user.name", "Dev"], repo)
+ _git(["config", "user.email", "[email protected]"], repo)
+ _commit(repo, {"a.py": "a = 0\n"}, "feat: seed")
+ _commit(repo, {"a.py": "a = 1\n"}, "feat: extend")
+
+ result = score_live_change(str(repo), "HEAD", baseline=0)
+ assert result.fix_density == 0.0
+ assert result.hot_files == ()
+ assert result.fix_percentile is None
diff --git a/website/mcp-server.md b/website/mcp-server.md
index 16174d3dd..575223533 100644
--- a/website/mcp-server.md
+++ b/website/mcp-server.md
@@ -370,10 +370,13 @@ refresh.
- `exclude_patterns` (optional) — gitignore-style paths; combined with root `.riskignore`
- `baseline` (optional, int) — recent commits for percentile ranking (default `200`)
-**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`).
+**Returns:** `fix_history` first — the recency-weighted bug-fix record of the
+files touched, which is what distinguishes a small dangerous change from a large
+boring one. Then the `score` (diff size and spread, per `score_measures`) with
+the `score_unit` it is calibrated on, repo-relative `risk_percentile` /
+`review_priority` / `classification` for that diff shape, 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, or on work you have not
committed yet.