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): rank fix density against commits, not individual files (#1891)
Raghav Chamadiya6afef055983b
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex cf2497a35..35420cbf8 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -487,11 +487,12 @@ shape of the live diff and needs no index refresh.| `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) |+| `baseline` | int | No | Recent commits to sample for percentile ranking (default `200`; `0` disables every percentile, `risk_percentile` and `fix_history.percentile` alike) |**Returns:** `fix_history` first — the recency-weighted bug-fix record of thefiles the change touches, with `files` naming where the pressure sits and-`percentile` ranking it against the repo's own fix-bearing files. Triage on+`percentile` ranking it against the same measure over the repo's own recent+commits. Triage onthis: it is the part that separates a small edit to a fragile file from a largeedit to a safe one. `available` is false when the history walk could not run.diff --git a/docs/layers/CHANGE_RISK.md b/docs/layers/CHANGE_RISK.mdindex 6959d3627..6687454b6 100644--- a/docs/layers/CHANGE_RISK.md+++ b/docs/layers/CHANGE_RISK.md@@ -49,7 +49,7 @@ The first block in the result is `fix_history`, and it is the one to act on. Itanswers 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+These files have broken before · 82nd percentile of this repo's recent commits┌──────────────────────────────────────────┬───────┬─────────────┐│ File │ Lines │ Prior fixes │├──────────────────────────────────────────┼───────┼─────────────┤@@ -69,11 +69,16 @@ These files have broken before · 82nd percentile of this repo's fix-bearing fila one-line drive-by next door. It is a *ratio*, so unlike the score it doesnot grow with the size of the diff: one line in a file fixed twenty timesoutranks 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.+- **`percentile`** ranks that density against the same measure over the+ repository's own recent commits, since a bare "3.4 decayed fixes" means+ nothing on its own. Ranking against whole commits rather than against+ individual per-file numbers is what keeps it readable: a change spread over+ several files averages below any single hot file, so a per-file population+ pinned every multi-file change to the bottom. Commits that touch no+ fix-bearing file stay in the population; they are a legitimate answer to how+ much fix pressure a change here usually stands on. It is `null` when the+ change touches no fix history, or when fewer than eight sampled commits are+ available to rank against.This comes from one `git log` walk (up to 20 000 commits, memoized perrepository state) using the same bug-fix classifier the indexer uses. It needsdiff --git a/examples/risk/README.md b/examples/risk/README.mdindex f238de5f0..ea984511f 100644--- a/examples/risk/README.md+++ b/examples/risk/README.md@@ -24,8 +24,8 @@ repowise risk HEAD~5..HEAD # recent local work```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+fixes before, recency-weighted, and where that sits among this repo's own+recent commits. Below it, the diff shape — percentile and review priority(`Below typical` / `Typical` / `Elevated`) among recent commits, and the 0–10score, which measures how large and spread out the change is rather than howdangerous.diff --git a/packages/api-client/src/risk.ts b/packages/api-client/src/risk.tsindex 328fd0202..cf504f6db 100644--- a/packages/api-client/src/risk.ts+++ b/packages/api-client/src/risk.ts@@ -13,7 +13,8 @@ export interface RiskRangeParams {head?: string;/*** How many recent commits to build the percentile baseline from. 0 skips- * the percentile (risk_percentile and review_priority come back null).+ * every percentile (risk_percentile, review_priority and+ * fix_history.percentile all come back null).*/baseline?: number;}@@ -34,7 +35,7 @@ export interface FixHistory {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. */+ /** Rank against the fix density of this repo's own recent commits; null if too few to rank. */percentile: number | null;files: FixHistoryFile[];}diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-risk.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-risk.mdindex 656fa02a7..96524bb94 100644--- a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-risk.md+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-risk.md@@ -7,7 +7,7 @@ description: Score the defect risk of a change — a commit or a base..head rangScore a *change* (not a file) for defect risk. The response leads with`fix_history`: the recency-weighted bug-fix record of the files the changetouches, which of them carry it, and where that sits among the repo's own-fix-bearing files. The 0–10 score sits beside it and measures diff size and+recent commits. The 0–10 score sits beside it and measures diff size andspread (named in `score_measures`) rather than danger, so read the fix historyfirst. Pure git + learned constants: no LLM, no network. A natural pre-merge /PR gate.diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.pyindex b80385990..1e54df9e3 100644--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py@@ -506,7 +506,7 @@ def risk_command(elif result.hot_files:where = (f" · {_ordinal(round(result.fix_percentile))} percentile of this repo's "- "fix-bearing files"+ "recent commits"if result.fix_percentile is not Noneelse "")diff --git a/packages/core/src/repowise/core/analysis/change_risk/__init__.py b/packages/core/src/repowise/core/analysis/change_risk/__init__.pyindex 950003869..44aece89a 100644--- a/packages/core/src/repowise/core/analysis/change_risk/__init__.py+++ b/packages/core/src/repowise/core/analysis/change_risk/__init__.py@@ -9,7 +9,7 @@ and is a natural pre-merge / PR gate.from __future__ import annotations-from .baseline import baseline_samples, scores_excluding+from .baseline import BaselineSample, baseline_samples, densities_excluding, scores_excludingfrom .features import (WORKING_TREE_REF,ChangeFeatures,@@ -43,6 +43,7 @@ __all__ = ["SCORE_MEASURES","SCORE_UNIT","WORKING_TREE_REF",+ "BaselineSample","ChangeFeatures","ChangeRisk","ChangeRiskResult",@@ -54,6 +55,7 @@ __all__ = ["change_fix_density","change_risk_payload","clear_fix_pressure_cache",+ "densities_excluding","extract_commit_features","extract_range_features","extract_worktree_features",diff --git a/packages/core/src/repowise/core/analysis/change_risk/baseline.py b/packages/core/src/repowise/core/analysis/change_risk/baseline.pyindex b0c6ff436..0e11a9426 100644--- a/packages/core/src/repowise/core/analysis/change_risk/baseline.py+++ b/packages/core/src/repowise/core/analysis/change_risk/baseline.py@@ -9,12 +9,27 @@ sample without duplicating the walk.from __future__ import annotationsimport subprocess+from typing import NamedTupleimport pathspecfrom .features import GIT_TIMEOUT_SECONDS, _git, features_from_file_changes+from .fix_history import change_fix_densityfrom .model import score_change++class BaselineSample(NamedTuple):+ """One sampled commit: its sha, its diff-shape score, and its file churn.++ ``file_churn`` rides along so a caller can compute the commit's fix density+ against a pressure map without a second walk — the sample is the only place+ the sampled commits' paths exist.+ """++ sha: str+ score: float+ file_churn: tuple[tuple[str, int], ...]+# Process-wide memo for the 200-commit baseline walk, which is the dominant cost# of a default get_change_risk call and is identical for every change scored# against the same repo state. Keyed on the *resolved anchor sha* (not the ref@@ -22,7 +37,7 @@ from .model import score_change# changes the sample (sample size, filters). Deliberately NOT keyed on the# target being scored: the sample is stored whole and the target's own score is# dropped when ranking, so two changes against the same history share one walk.-_BASELINE_CACHE: dict[tuple, list[tuple[str, float]]] = {}+_BASELINE_CACHE: dict[tuple, list[BaselineSample]] = {}# Crude bound so a long-lived MCP server that scores many distinct changes does# not grow the memo without limit. On overflow the whole cache is dropped# (correctness is unaffected; the next call just recomputes). Upgrade to an LRU@@ -45,8 +60,8 @@ def _resolve_anchor_sha(repo_path: str, anchor: str) -> str | None:return sha or None-def scores_excluding(samples: list[tuple[str, float]], excluded_ref: str) -> list[float]:- """Drop the target commit's own score from a sample, keeping the rest.+def _retained(samples: list[BaselineSample], excluded_ref: str) -> list[BaselineSample]:+ """The sample with the target commit's own entry removed.Self-exclusion is a rank-time filter, not a property of the sample, so thewalk is cached whole and each target removes only itself. *excluded_ref* is@@ -56,11 +71,41 @@ def scores_excluding(samples: list[tuple[str, float]], excluded_ref: str) -> lisshort enough to prefix-match several shas will drop all of them."""if not excluded_ref:- return [score for _, score in samples]+ return list(samples)+ return [+ sample+ for sample in samples+ if not (sample.sha.startswith(excluded_ref) or excluded_ref.startswith(sample.sha))+ ]+++def scores_excluding(samples: list[BaselineSample], excluded_ref: str) -> list[float]:+ """Diff-shape scores of the sample, minus the target commit's own."""+ return [sample.score for sample in _retained(samples, excluded_ref)]+++def densities_excluding(+ samples: list[BaselineSample], excluded_ref: str, pressure: dict[str, float]+) -> list[float]:+ """Fix densities of the sample, minus the target commit's own.++ Every sampled commit is measured against the *same* pressure map the target+ is, so the population and the target share a unit. That map is read once at+ the target's history ref rather than rebuilt per sampled commit: a per-commit+ walk would cost one deep git log each, and the question being asked is where+ this change's ground sits on today's map, not on each commit's own.++ That does leave one asymmetry. The map is cut strictly before the target, so+ the target is never credited with its own fixes, while a sampled commit is+ measured on a map that already holds the fixes landing after it. Population+ densities therefore read slightly high and the target's rank slightly low,+ growing with how far the sample reaches past the half-life. Correcting it+ means one deep walk per sampled commit, which is the cost this whole design+ exists to avoid.+ """return [- score- for sha, score in samples- if not (sha.startswith(excluded_ref) or excluded_ref.startswith(sha))+ change_fix_density(pressure, sample.file_churn)+ for sample in _retained(samples, excluded_ref)]@@ -70,11 +115,13 @@ def baseline_samples(limit: int,extensions: tuple[str, ...],exclude_patterns: tuple[str, ...] = (),-) -> list[tuple[str, float]]:+) -> list[BaselineSample]:"""Score the repo's recent commits to build a local risk distribution.- Returns ``(sha, score)`` pairs so a caller can exclude the change it is- ranking (see :func:`scores_excluding`) without needing a sample of its own.+ Returns :class:`BaselineSample` rows so a caller can exclude the change it+ is ranking (see :func:`scores_excluding`) without needing a sample of its+ own, and can rank a fix density against the same commits+ (see :func:`densities_excluding`).One ``git log --numstat`` call (no per-commit author lookup), so it stayscheap enough for a pre-merge gate. Experience is left unknown for the@@ -98,7 +145,7 @@ def baseline_samples(timeout=GIT_TIMEOUT_SECONDS,).stdout- samples: list[tuple[str, float]] = []+ samples: list[BaselineSample] = []exclude_spec = pathspec.PathSpec.from_lines("gitwildmatch", exclude_patterns)for block in out.split("\x1e"):lines = block.strip().split("\n")@@ -121,7 +168,7 @@ def baseline_samples(if not changes:continuefeats = features_from_file_changes(changes, exp=None)- samples.append((sha, score_change(feats).score))+ samples.append(BaselineSample(sha, score_change(feats).score, feats.file_churn))return samples@@ -131,7 +178,7 @@ def baseline_samples_cached(limit: int,extensions: tuple[str, ...],exclude_patterns: tuple[str, ...] = (),-) -> list[tuple[str, float]]:+) -> list[BaselineSample]:"""Memoized :func:`baseline_samples`, keyed on the resolved anchor sha.Same result as :func:`baseline_samples` for the same inputs; it just skipsdiff --git a/packages/core/src/repowise/core/analysis/change_risk/fix_history.py b/packages/core/src/repowise/core/analysis/change_risk/fix_history.pyindex d47fb5c11..4ea6347a1 100644--- a/packages/core/src/repowise/core/analysis/change_risk/fix_history.py+++ b/packages/core/src/repowise/core/analysis/change_risk/fix_history.py@@ -20,10 +20,11 @@ number is the broadest of the three by design.from __future__ import annotationsimport subprocess-from collections.abc import Iterable+from collections.abc import Iterable, Sequencefrom ...ingestion.git_indexer._constants import is_fix_commitfrom .features import GIT_TIMEOUT_SECONDS, _git+from .normalize import RiskNormalizer#: 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@@ -207,6 +208,11 @@ def change_fix_density(#: short enough to stay readable on a wide PR.MAX_HOT_FILES = 5+#: Smallest commit sample worth ranking a density against. Matches the score+#: percentile's own floor, which is a separate constant on a separate call+#: path - nothing enforces that they stay equal.+MIN_DENSITY_POPULATION = 8+def hot_files(pressure: dict[str, float], changes: Iterable[tuple[str, int]], *, limit: int = MAX_HOT_FILES@@ -225,19 +231,27 @@ def hot_files(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.+def fix_density_percentile(population: Sequence[float], density: float) -> float | None:+ """Where *density* sits among the fix densities of the repo's own commits.++ *population* is one density per sampled commit, computed the same way as+ *density* — see :func:`~.baseline.densities_excluding`. Ranking against+ whole commits rather than against individual per-file pressures is what+ makes the number readable: a change touching several files averages below+ any single hot file, so the per-file population pinned every multi-file+ commit to 0.++ Zero-density commits stay in the population. A commit touching no+ fix-bearing file is a legitimate answer to "how much fix pressure does a+ change here usually stand on", and dropping them would narrow the field to+ a question it is not labelled as. Mid-rank percentiles mean the run of+ zeros shares one averaged rank rather than pinning anything.- 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.+ ``None`` when the change touches no fix history, or when the sample is too+ small to rank against."""if density <= 0:return None- values = [v for v in pressure.values() if v > 0]- if len(values) < 8:+ if len(population) < MIN_DENSITY_POPULATION:return None- below = sum(1 for v in values if v < density)- return round(100.0 * below / len(values), 1)+ return round(RiskNormalizer.from_scores(list(population)).percentile(density), 1)diff --git a/packages/core/src/repowise/core/analysis/change_risk/service.py b/packages/core/src/repowise/core/analysis/change_risk/service.pyindex 26d34c1e6..42afd0332 100644--- a/packages/core/src/repowise/core/analysis/change_risk/service.py+++ b/packages/core/src/repowise/core/analysis/change_risk/service.py@@ -6,7 +6,7 @@ import subprocessfrom dataclasses import dataclass, replacefrom pathlib import Path-from .baseline import baseline_samples_cached, scores_excluding+from .baseline import BaselineSample, baseline_samples_cached, densities_excluding, scores_excludingfrom .features import (GIT_TIMEOUT_SECONDS,ChangeFeatures,@@ -43,8 +43,9 @@ class ChangeRiskResult: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.+ # it against the same measure over the repo's own recent commits, and+ # ``hot_files`` names where the pressure is. Unlike the score, none of+ # these grow with diff size.fix_density: float = 0.0fix_percentile: float | None = Nonehot_files: tuple[tuple[str, int, float], ...] = () # (path, churn, pressure)@@ -192,6 +193,7 @@ def score_live_change(percentile: float | None = Nonepriority: str | None = Nonebaseline_sample_size = 0+ samples: list[BaselineSample] = []if baseline:samples = baseline_samples_cached(repo_path,@@ -218,7 +220,9 @@ def score_live_change(request_excludes=exclude_patterns,working_tree=working_tree,fix_density=round(density, 3),- fix_percentile=fix_density_percentile(pressure, density),+ fix_percentile=fix_density_percentile(+ densities_excluding(samples, excluded_ref, pressure), density+ ),hot_files=fix_bearing,fix_history_available=fix_history_available,)diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.pyindex 857186f52..1171180f0 100644--- a/packages/server/src/repowise/server/routers/git.py+++ b/packages/server/src/repowise/server/routers/git.py@@ -16,11 +16,13 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.change_risk import (SCORE_MEASURES,SCORE_UNIT,+ BaselineSample,FixHistoryUnavailableError,RiskNormalizer,baseline_samples,change_features_from_stored,change_fix_density,+ densities_excluding,extract_range_features,fix_density_percentile,fix_pressure,@@ -697,6 +699,7 @@ def get_risk_range(percentile: float | None = Nonepriority: str | None = None+ samples: list[BaselineSample] = []if baseline:# Same anchor rule as the CLI/MCP scorer, so both surfaces rank a range# against the history it forked from rather than against its own commits.@@ -725,7 +728,7 @@ def get_risk_range(fix_history=FixHistoryResponse(available=fix_available,density=round(density, 3),- percentile=fix_density_percentile(pressure, density),+ percentile=fix_density_percentile(densities_excluding(samples, "", pressure), density),files=[FixHistoryFileResponse(path=path, churn=churn, fix_pressure=p)for path, churn, p in hot_files(pressure, features.file_churn)diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.pyindex 5c35365c7..afaa3fe21 100644--- a/packages/server/src/repowise/server/schemas/git.py+++ b/packages/server/src/repowise/server/schemas/git.py@@ -299,8 +299,9 @@ class FixHistoryResponse(BaseModel):The size-orthogonal half of the answer: unlike ``score``, none of this growswith 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.+ touched files; ``percentile`` ranks it against the same measure over the+ repository's own recent commits, and is ``None`` when there is no sample to+ rank against."""#: False when the history walk could not run — distinguishes "no fixesdiff --git a/packages/vscode/webview/src/views/risk/App.tsx b/packages/vscode/webview/src/views/risk/App.tsxindex a0fc29fa4..a2296cbd7 100644--- a/packages/vscode/webview/src/views/risk/App.tsx+++ b/packages/vscode/webview/src/views/risk/App.tsx@@ -312,7 +312,7 @@ function FixHistoryNote({ history }: { history: RiskRangeReport["result"]["fix_h{history.percentile != null ? (<>{" "}- — {ordinal(history.percentile)} percentile of this repo's fix-bearing files+ — {ordinal(history.percentile)} percentile of this repo's recent commits</>) : null}.diff --git a/plugins/claude-code/commands/risk.md b/plugins/claude-code/commands/risk.mdindex 33e3ff1a9..49c502b6f 100644--- a/plugins/claude-code/commands/risk.md+++ b/plugins/claude-code/commands/risk.md@@ -8,7 +8,7 @@ allowed-tools: Bash, ReadScore a *change* (not a file) for defect risk. The response leads with`fix_history`: the recency-weighted bug-fix record of the files the changetouches, which of them carry it, and where that sits among the repo's own-fix-bearing files. The 0–10 score sits beside it and measures diff size and+recent commits. The 0–10 score sits beside it and measures diff size andspread (named in `score_measures`) rather than danger, so read the fix historyfirst. Pure git + learned constants: no LLM, no network. A natural pre-merge /PR gate.diff --git a/plugins/shared/commands/risk.md b/plugins/shared/commands/risk.mdindex 0a81d6c8e..b773b10f6 100644--- a/plugins/shared/commands/risk.md+++ b/plugins/shared/commands/risk.md@@ -9,7 +9,7 @@ frontmatter: |Score a *change* (not a file) for defect risk. The response leads with`fix_history`: the recency-weighted bug-fix record of the files the changetouches, which of them carry it, and where that sits among the repo's own-fix-bearing files. The 0–10 score sits beside it and measures diff size and+recent commits. The 0–10 score sits beside it and measures diff size andspread (named in `score_measures`) rather than danger, so read the fix historyfirst. Pure git + learned constants: no LLM, no network. A natural pre-merge /PR gate.diff --git a/tests/unit/analysis/test_change_risk_fix_history.py b/tests/unit/analysis/test_change_risk_fix_history.pyindex 9db5e3124..7677f89e6 100644--- a/tests/unit/analysis/test_change_risk_fix_history.py+++ b/tests/unit/analysis/test_change_risk_fix_history.py@@ -13,10 +13,12 @@ from pathlib import Pathimport pytestfrom repowise.core.analysis.change_risk import (+ BaselineSample,FixHistoryUnavailableError,change_fix_density,change_risk_payload,clear_fix_pressure_cache,+ densities_excluding,fix_density_percentile,fix_pressure,score_live_change,@@ -152,16 +154,74 @@ def test_fix_history_excludes_the_change_being_scored(repo_with_history: Path) -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_needs_enough_commits_to_rank_against() -> None:+ assert fix_density_percentile([1.0, 2.0, 3.0], 2.5) is None+ assert fix_density_percentile([float(i) for i in range(8)], 2.5) is not Nonedef 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+ population = [float(i + 1) for i in range(10)]+ assert fix_density_percentile(population, 0.0) is None+ assert fix_density_percentile(population, 5.5) is not None+++def test_percentile_ranks_a_multi_file_change_against_whole_commits() -> None:+ """The population is per-commit densities, so averaging is not a penalty.++ The old population was per-*file* pressures. A change spread over several+ files averages below the lowest single per-file value that exists anywhere,+ so it fell under the whole population and pinned to 0. The same change+ against per-commit densities lands where its ground actually sits.+ """+ pressure = {"hot.py": 5.0, "warm.py": 1.0, "cold.py": 0.0}+ spread = change_fix_density(pressure, [("hot.py", 10), ("cold.py", 10)])+ assert spread == pytest.approx(2.5)++ per_file = sorted(v for v in pressure.values() if v > 0) # the old population+ assert spread > per_file[0] # ... which this change would still clear here++ # The real repo has no per-file value below 0.75, so a wider spread does not.+ diluted = change_fix_density(pressure, [("hot.py", 1), ("cold.py", 20)])+ assert diluted < min(per_file)++ # Under the old per-file population it would have sat below every member+ # and pinned to 0. Against whole commits it ranks above the zero-density+ # ones and below the rest.+ population = [0.0, 0.0, 0.4, 0.9, 1.4, 2.5, 3.1, 4.0, 4.4, 5.0]+ assert fix_density_percentile(population, diluted) == pytest.approx(20.0)+++def test_zero_density_commits_stay_in_the_population() -> None:+ """They are legitimate members; dropping them would inflate every rank."""+ pressure = {"hot.py": 4.0}+ samples = [+ BaselineSample(f"{i:040x}", 1.0, (("cold.py", 10),)) # touches no fix history+ for i in range(6)+ ] + [+ BaselineSample(f"{i:040x}", 1.0, (("hot.py", 10),)) for i in range(6, 10)+ ]++ population = densities_excluding(samples, "", pressure)++ assert population.count(0.0) == 6 # the zero-density commits survived the walk+ assert len(population) == 10+++def test_percentile_uses_the_repos_own_commits(repo_with_history: Path) -> None:+ """End to end: a change to the fragile file outranks one to the safe file."""+ hot_sha = _commit(repo_with_history, {"hot.py": "v = 9\n"}, "feat: touch the hot file")+ cold_sha = _commit(repo_with_history, {"cold.py": "c = 9\n"}, "feat: touch the cold file")+ # Enough commits for the sample to clear MIN_DENSITY_POPULATION.+ for i in range(4, 8):+ _commit(repo_with_history, {"cold.py": f"c = {i}\n"}, f"feat: add capability {i}")++ hot = score_live_change(str(repo_with_history), hot_sha, baseline=200)+ cold = score_live_change(str(repo_with_history), cold_sha, baseline=200)++ assert hot.fix_percentile is not None+ assert hot.fix_percentile > 0.0+ assert cold.fix_percentile is None # touches no fix history at alldef test_decay_is_anchored_to_the_change_not_to_the_latest_fix(tmp_path: Path) -> None:diff --git a/tests/unit/server/test_risk_range.py b/tests/unit/server/test_risk_range.pyindex 49251e3d6..134930d27 100644--- a/tests/unit/server/test_risk_range.py+++ b/tests/unit/server/test_risk_range.py@@ -8,7 +8,11 @@ from pathlib import Pathimport pytestfrom httpx import AsyncClient-from repowise.core.analysis.change_risk import baseline_samples, scores_excluding+from repowise.core.analysis.change_risk import (+ baseline_samples,+ densities_excluding,+ scores_excluding,+)from tests.unit.server.conftest import create_test_repo@@ -117,15 +121,20 @@ async def test_risk_range_baseline_zero_skips_percentile(data = resp.json()assert data["risk_percentile"] is Noneassert data["review_priority"] is None+ # The fix density is ranked against the same sample, so it goes too.+ assert data["fix_history"]["percentile"] is None-def test_baseline_samples_pair_each_sha_with_a_float(git_repo: Path) -> None:+def test_baseline_samples_carry_sha_score_and_churn(git_repo: Path) -> None:_commit(git_repo, {"src/d.py": "a = 1\nb = 2\n"}, "feat: add d")_commit(git_repo, {"src/e.py": "c = 3\n"}, "fix: crash on null")samples = baseline_samples(str(git_repo), "HEAD", 200, ())assert len(samples) >= 1- assert all(isinstance(sha, str) and isinstance(score, float) for sha, score in samples)+ assert all(isinstance(sample.sha, str) for sample in samples)+ assert all(isinstance(sample.score, float) for sample in samples)+ # The churn rides along so a fix density can be computed without a second walk.+ assert all(sample.file_churn for sample in samples)def test_baseline_samples_filters_excluded_paths(git_repo: Path) -> None:@@ -141,6 +150,21 @@ def test_baseline_samples_filters_excluded_paths(git_repo: Path) -> None:assert len(samples) == 1+def test_densities_excluding_omits_target_ref(git_repo: Path) -> None:+ """Same self-exclusion contract as the scores: a change never ranks itself."""+ _commit(git_repo, {"src/app.py": "a = 1\n"}, "feat: app")+ head = _commit(git_repo, {"src/next.py": "b = 2\n"}, "feat: next")++ samples = baseline_samples(str(git_repo), "HEAD", 2, ())+ pressure = {"src/app.py": 2.0, "src/next.py": 1.0}++ assert len(densities_excluding(samples, head, pressure)) == 1+ assert len(densities_excluding(samples, head[:7], pressure)) == 1+ assert len(densities_excluding(samples, "", pressure)) == 2+ # And it is a density, not a score: the retained commit touches app.py only.+ assert densities_excluding(samples, head, pressure) == [2.0]++def test_scores_excluding_omits_target_ref(git_repo: Path) -> None:_commit(git_repo, {"src/app.py": "a = 1\n"}, "feat: app")head = _commit(git_repo, {"src/next.py": "b = 2\n"}, "feat: next")