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): lead change risk with the size percentile, not a review priority (#3664)
Swati Ahuja983a340db99f
diff --git a/action.yml b/action.ymlindex 4bcf8b6b7..4f4ca25a4 100644--- a/action.yml+++ b/action.yml@@ -91,7 +91,8 @@ inputs:risk-fail-above-percentile:description: >-Fail when the change ranks above this percentile of the repository's- recent commits by size and spread. Empty reports the rank without gating.+ recent commits by size and spread: a size gate, not a bug predictor.+ Empty reports the rank without gating.default: ""upload-sarif:description: >-diff --git a/ci/gitlab/repowise.gitlab-ci.yml b/ci/gitlab/repowise.gitlab-ci.ymlindex db3e44d99..d0dd19cf0 100644--- a/ci/gitlab/repowise.gitlab-ci.yml+++ b/ci/gitlab/repowise.gitlab-ci.yml@@ -35,7 +35,8 @@# REPOWISE_SECURITY_FAIL_ON Lowest severity that fails: high (default), med, low.# REPOWISE_RISK_FAIL_ABOVE_PERCENTILE# Fail when the change ranks above this percentile of-# recent commits. The risk job runs only when it is set.+# recent commits by size (a size gate, not a bug+# predictor). The risk job runs only when it is set.# REPOWISE_IMPACTED_TESTS "true" adds repowise-impacted-tests, which selects the# tests the change needs from a cached index.# REPOWISE_IMPACTED_TESTS_RUNNER Runner its arguments are for: auto (default), pytest,diff --git a/docs/architecture/change-risk.md b/docs/architecture/change-risk.mdindex 37503fd08..b749d3a34 100644--- a/docs/architecture/change-risk.md+++ b/docs/architecture/change-risk.md@@ -100,8 +100,8 @@ threshold, and all three bands are occupied.| Public value | Producer | Unit / range | Authority || --- | --- | --- | --- || `get_change_risk.score` / REST `score` / stored `change_risk_score` | Logistic model over diff size, spread, entropy, author experience | normalized points 0-10, single-commit scale | Supporting; not a probability |-| `risk_percentile` | Mid-rank of the score among filtered recent commits | percentile 0-100 | Authoritative with `classification` |-| `review_priority` / `classification` | Percentile terciles at 33.33 and 66.67 | category | Authoritative |+| `risk_percentile` | Mid-rank of the score among filtered recent commits | percentile 0-100 | The diff-size rank; not a bug predictor |+| `review_priority` / `classification` | Percentile terciles at 33.33 and 66.67 | category | Label for the same rank || `fallback_band` | Score thresholds at 4 and 7, only without a baseline | category | Absolute fallback || `fix_history.density` | Churn-weighted, recency-decayed prior fixes | decayed fixes, unbounded | Uncalibrated, separate evidence || `get_risk` `hotspot_score` | Repo-relative churn percentile | ratio 0-1 | Uncalibrated component |diff --git a/docs/layers/CHANGE_RISK.md b/docs/layers/CHANGE_RISK.mdindex ff1e4f5d6..29299b13c 100644--- a/docs/layers/CHANGE_RISK.md+++ b/docs/layers/CHANGE_RISK.md@@ -11,8 +11,8 @@ learned offline. A typical run is one `git log` walk and a sample of recentcommits. Branch overlap and the independent-changes report use the index whenthere is one.-Lead with `risk_percentile` and `classification`. They are the-population-relative signal for review. `fix_history` is separate evidence about+Lead with `risk_percentile`: the change's rank among recent commits by diff+size and spread, not a bug predictor. `fix_history` is separate evidence aboutwhere the change lands. The 0-10 score is a supporting measure of diff size andspread, not a probability (see [Accuracy and limits](#accuracy-and-limits)).@@ -54,9 +54,9 @@ Read the result in this order:| Field | What it is | Act on it ||---|---|---|-| `review_priority` / `classification` | Tercile of the percentile: `low` / `moderate` / `high`, labelled Below typical / Typical / Elevated | Yes: the review signal |-| `risk_percentile` | Where this change's diff shape ranks among the repo's recent commits (0-100) | Yes |-| `fix_history` | Prior bug fixes on the touched files, ranked against recent commits | Yes: where to look |+| `risk_percentile` | Where this change's diff size and spread ranks among the repo's recent commits (0-100) | Yes: size, not danger |+| `fix_history` | Prior bug fixes on the touched files | Yes: where to look |+| `review_priority` / `classification` | Tercile of the percentile: `low` / `moderate` / `high`. MCP returns them only with `include=["scales"]` | Same fact as the percentile || `score` | 0-10 diff size and spread, on a single-commit scale | Supporting only || `fallback_band` | `low` / `moderate` / `high` from the score | Only present when there was nothing to rank against || `independent_changes` | Groups of changed files that nothing links | Consider splitting |@@ -67,7 +67,7 @@ Read the result in this order:before?```-These files have broken before · 82nd percentile of this repo's recent commits+Bug-fix record for HEAD: touches files with prior bug fixesFile Lines Prior fixescore/pipeline/persist.py 40 21.6cli/commands/update_cmd/command.py 6 19.3@@ -82,7 +82,12 @@ cli/commands/update_cmd/command.py 6 19.3times outranks a thousand lines in files never fixed.- **`percentile`** ranks that density against the same measure over the repo'srecent commits. It is `null` when the change touches no fix history, or when- fewer than eight sampled commits are available.+ fewer than eight sampled commits are available. It ships in `--format json`+ and MCP `include=["diagnostics"]` only, so one percentile leads each surface.+- **Manifests and lockfiles** (`package.json`, `package-lock.json`,+ `pyproject.toml`, `go.sum` and the like) are left out of the listed files: a+ dependency bump edits them, which does not make them files that broke.+ `density` and its `percentile` still count them.History is read from before the change: a commit is never ranked against fixesit caused. For a range, the record is read at the fork point. Up to 20,000@@ -241,7 +246,8 @@ branch scan times out.## In CI-`--fail-above-percentile P` turns the command into a gate on `risk_percentile`.+`--fail-above-percentile P` turns the command into a size gate on+`risk_percentile`. It flags changes larger than most, not likelier to break.The absolute 0-10 value never decides.```bashdiff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex b9a80bb8d..77e94d663 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -836,9 +836,9 @@ constants). With no `REVSPEC` it scores your uncommitted work, falling back to`base..head` range to score a whole branch / PR as one change (`base...head`diffs from the merge-base, so commits that landed on `base` meanwhile stay out).-The headline is **repo-relative**: the change's percentile and review priority-(`Below typical` / `Typical` / `Elevated`) within the repo's own recent commits,-sampled live. The raw 0–10 model score is still shown, but as a secondary,+The headline is **repo-relative**: the change's percentile by size and spread+within the repo's own recent commits, sampled live. It ranks diff size, not+danger; the bug-fix record of the touched files follows it. The raw 0–10 model score is still shown, but as a secondary,corpus-anchored number (it skews high on repos whose typical commit is large, sothe percentile is the signal to act on). Each risk driver is reported relativeto the model's baseline commit, not this repo.@@ -853,7 +853,7 @@ to the model's baseline commit, not this repo.| `--baseline` | Recent commits to sample for the repo-relative percentile (default 200; `0` shows only the absolute per-commit model-score band) || `--target` / `-t` | Score what history says about these **files** instead of a change. Repeatable; switches the command to the `get_risk` tool || `--changed-file` | With `--target`: PR mode. Leads with a directive naming what may break, which co-changes and tests are missing, and what to run |-| `--fail-above-percentile` | CI gate (0-100): exit `1` when the change ranks above this percentile of recent commits (`risk_percentile`, never the 0-10 score), `2` when it has no percentile (`--baseline 0`, or fewer than 8 commits to rank against). Without `REVSPEC` it scores the CI change: the target branch `...HEAD` |+| `--fail-above-percentile` | CI size gate (0-100): exit `1` when the change ranks above this percentile of recent commits (`risk_percentile`, never the 0-10 score), `2` when it has no percentile (`--baseline 0`, or fewer than 8 commits to rank against). Without `REVSPEC` it scores the CI change: the target branch `...HEAD` || `--format` | Output format: `table` (default), `json`, `markdown` or `github`. `markdown` and `github` are not for `--target`; without `REVSPEC` they score the CI change. `github` writes an `::error::` when the gate fails (else a `::notice::`) and the markdown to `$GITHUB_STEP_SUMMARY` || `--full` | With `--target`: emit the complete tool payload as JSON (implies `--format json`) |diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex e27cd2af0..c80bc1787 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -245,12 +245,12 @@ Every float is rounded to 4 significant digits. Direct rows' `structural_score`|-------|---------|| `directive` | `status` (`review_required`, `review_recommended`, `clear_in_analyzed_scope`, `unknown`), a headline, reasons, next actions || `health_delta` | What the change newly made worse. See below |-| `risk_percentile`, `review_priority`, `classification` | The change's diff size and spread ranked against the repo's recent commits (`classification` reads `Below-typical`, `Typical` or `Above-typical diff size`). Size, not a verdict: `directive.status` is the verdict |+| `risk_percentile` | The change's diff size and spread ranked against the repo's recent commits. Size, not a verdict: `directive.status` is the verdict. `include=["scales"]` adds the `review_priority` tercile and its `classification` (`Below-typical`, `Typical` or `Above-typical diff size`) || `is_fix` | Present only when the change is a bug fix || `exclude_patterns` | Present only when something was excluded: the request's patterns plus `.riskignore` || `diff_shape` | One sentence on size and spread; never a danger verdict || `working_tree` | Present only when `revspec` was omitted: whether uncommitted work was scored, or a clean tree fell back to `HEAD` |-| `fix_history` | Recency-weighted bug-fix record of the touched files, with `percentile` and `overlap`; the raw `density` ships with `include=["diagnostics"]` |+| `fix_history` | Recency-weighted bug-fix record of the touched files (manifests and lockfiles not listed), with `overlap`; `density` and its `percentile` ship with `include=["diagnostics"]` || `impacted_tests` | The tests the change needs, and whether every test must run || `patch_coverage` | Share of changed executable lines the stored coverage ran || `branch_overlap` | Other branches editing the same files |diff --git a/docs/start/QUICKSTART.md b/docs/start/QUICKSTART.mdindex d5de63d3b..2c030e8ba 100644--- a/docs/start/QUICKSTART.md+++ b/docs/start/QUICKSTART.md@@ -146,7 +146,7 @@ The same answers are on the command line:```bashrepowise health # lowest-scoring files, and whyrepowise dead-code # what nothing references-repowise risk main..HEAD # review priority for your branch+repowise risk main..HEAD # size and bug-fix record for your branchrepowise impacted-tests main..HEAD # tests your branch's changes exercise```@@ -211,7 +211,7 @@ seeds its index from the main checkout: [Worktrees](../scale/WORKTREES.md).| Fewer tokens on test and build output | [Distill](../agent/DISTILL.md) || What the health score measures | [Code Health](../layers/CODE_HEALTH.md) || Unused files and exports | [Dead Code](../layers/DEAD_CODE.md) |-| Review priority for a change | [Change Risk](../layers/CHANGE_RISK.md) |+| Size and bug-fix record of a change | [Change Risk](../layers/CHANGE_RISK.md) || Gates and annotations on pull requests | [CI](CI.md) || Several repositories as one | [Workspaces](../scale/WORKSPACES.md) || Every setting and environment variable | [Config](../reference/CONFIG.md) |diff --git a/docs/start/USER_GUIDE.md b/docs/start/USER_GUIDE.mdindex 4dc59d805..97017147e 100644--- a/docs/start/USER_GUIDE.md+++ b/docs/start/USER_GUIDE.md@@ -138,7 +138,7 @@ Grouped by what you are trying to do. Every flag for every command lives in the| `repowise symbol "<file>::<Name>"` | One symbol's body with live-verified line bounds. || `repowise why "<q>"` | Decisions and rationale behind the shape of the code. A path gets its origin story; no argument gets the decision health dashboard. || `repowise health` | Lowest-scoring files and why. `--trend` for direction, `--refactoring-targets` for concrete plans. |-| `repowise risk main..HEAD` | Repo-relative review percentile/classification plus a supporting 0-10 diff-shape score. |+| `repowise risk main..HEAD` | Repo-relative size-and-spread percentile, the touched files' bug-fix record, and a supporting 0-10 diff-shape score. || `repowise dead-code` | What nothing references any more, by confidence tier. || `repowise doc-drift` | Documentation whose claims about the tree no longer hold, by confidence. || `repowise decision list` | Architectural decisions, their evidence and status. |@@ -315,7 +315,7 @@ repowise watch # or sync continuously while you code### Before you open a pull request```bash-repowise risk main..HEAD # repo-relative review priority and supporting evidence+repowise risk main..HEAD # size-and-spread percentile and bug-fix recordrepowise impacted-tests main..HEAD # the tests your changes exerciserepowise health --trend # did anything you touched get worse```@@ -352,7 +352,7 @@ instead of them interrupting someone.```bashexport REPOWISE_SKIP_EDITOR_SETUP=1 # no hooks or editor files on the runnerrepowise init --yes --no-prose # free, no keys in CI, no questions-repowise risk "$BASE_SHA..$HEAD_SHA" # gate or annotate on review priority+repowise risk "$BASE_SHA..$HEAD_SHA" # gate or annotate on change sizerepowise export --format markdown --output ./docs/wiki/ # static hosting```diff --git a/examples/risk/README.md b/examples/risk/README.mdindex 78f71c874..bf87fe012 100644--- a/examples/risk/README.md+++ b/examples/risk/README.md@@ -23,12 +23,11 @@ repowise risk main..HEAD # whole branch / PR as one changerepowise 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 own-recent commits. 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.+The headline is **size and spread**: the change's percentile among this+repo's recent commits by diff size, not a bug predictor. Below it, the **fix+history**: which of the touched files have needed bug fixes before,+recency-weighted. Then the 0–10 score, which measures how large and spread out+the change is rather than how dangerous.## 2. Narrow what counts@@ -51,7 +50,7 @@ repowise risk main..HEAD --format json| Step | Expected ||------|----------|-| `repowise risk` | Table led by percentile/review priority, with a supporting diff-shape score |+| `repowise risk` | Table led by the size-and-spread percentile, with a supporting diff-shape score || `repowise risk main..HEAD` | Same shape for the range (or a clear revspec error) || `repowise risk --format json` | JSON object; no API key needed |diff --git a/packages/api-client/src/types/git.ts b/packages/api-client/src/types/git.tsindex 0995f4dbb..7660bf473 100644--- a/packages/api-client/src/types/git.ts+++ b/packages/api-client/src/types/git.ts@@ -119,7 +119,7 @@ export interface CommitResponse {change_risk_level: ReviewPriority | null;/** Repo-relative percentile rank, 0–100. */risk_percentile: number;- /** Authoritative repo-relative review-priority tercile. */+ /** Repo-relative tercile of the diff-size percentile; size, not danger. */review_priority: ReviewPriority;/** Label of the dominant risk driver; null when never risk-scored. */top_driver?: string | null;diff --git a/packages/claude-mod/test/fixtures/change-risk/clear.json b/packages/claude-mod/test/fixtures/change-risk/clear.jsonindex bf2bf86e9..ad6c90029 100644--- a/packages/claude-mod/test/fixtures/change-risk/clear.json+++ b/packages/claude-mod/test/fixtures/change-risk/clear.json@@ -50,7 +50,6 @@"fix_history": {"available": true,"density": 1.329,- "percentile": 75.0,"files": [{"path": "src/requests/_internal_utils.py",@@ -79,8 +78,6 @@}},"risk_percentile": 34.0,- "review_priority": "moderate",- "classification": "Typical","exclude_patterns": [],"is_fix": false,"impacted_tests": {@@ -107,7 +104,7 @@},"summary": "2 test(s) to run for this change; the rest can be skipped."},- "diff_shape": "Diff shape: bigger than 34% of this repo's recent commits. Size and spread, not danger. Mechanics: get_change_risk(include=['diagnostics']).",+ "diff_shape": "Size and spread: 34th percentile of recent commits (diff size, not a bug predictor). The rank is a diff-size statistic: it barely beats churn alone and cannot rank danger. Mechanics: get_change_risk(include=['diagnostics']).","_meta": {"contract_version": 2,"timing_ms": 1054.0,diff --git a/packages/claude-mod/test/fixtures/change-risk/findings.json b/packages/claude-mod/test/fixtures/change-risk/findings.jsonindex ba6ee8893..f55df20c5 100644--- a/packages/claude-mod/test/fixtures/change-risk/findings.json+++ b/packages/claude-mod/test/fixtures/change-risk/findings.json@@ -101,7 +101,6 @@"fix_history": {"available": true,"density": 1.329,- "percentile": 75.0,"files": [{"path": "src/requests/_internal_utils.py",@@ -130,8 +129,6 @@}},"risk_percentile": 92.0,- "review_priority": "high",- "classification": "Elevated","exclude_patterns": [],"is_fix": false,"impacted_tests": {@@ -158,7 +155,7 @@},"summary": "2 test(s) to run for this change; the rest can be skipped."},- "diff_shape": "Diff shape: bigger than 92% of this repo's recent commits. Size and spread, not danger. Mechanics: get_change_risk(include=['diagnostics']).",+ "diff_shape": "Size and spread: 92nd percentile of recent commits (diff size, not a bug predictor). The rank is a diff-size statistic: it barely beats churn alone and cannot rank danger. Mechanics: get_change_risk(include=['diagnostics']).","_meta": {"contract_version": 2,"timing_ms": 999.7,diff --git a/packages/claude-mod/test/fixtures/change-risk/overlap.json b/packages/claude-mod/test/fixtures/change-risk/overlap.jsonindex b1eb2486c..b309b7fdb 100644--- a/packages/claude-mod/test/fixtures/change-risk/overlap.json+++ b/packages/claude-mod/test/fixtures/change-risk/overlap.json@@ -50,7 +50,6 @@"fix_history": {"available": true,"density": 1.329,- "percentile": 75.0,"files": [{"path": "src/requests/_internal_utils.py",@@ -79,8 +78,6 @@}},"risk_percentile": 34.0,- "review_priority": "moderate",- "classification": "Typical","exclude_patterns": [],"is_fix": false,"impacted_tests": {@@ -129,7 +126,7 @@"truncated": false,"summary": "1 of 6 open branches (6 exist) edit files this change also edits."},- "diff_shape": "Diff shape: bigger than 34% of this repo's recent commits. Size and spread, not danger. Mechanics: get_change_risk(include=['diagnostics']).",+ "diff_shape": "Size and spread: 34th percentile of recent commits (diff size, not a bug predictor). The rank is a diff-size statistic: it barely beats churn alone and cannot rank danger. Mechanics: get_change_risk(include=['diagnostics']).","_meta": {"contract_version": 2,"timing_ms": 1333.0,diff --git a/packages/claude-mod/test/fixtures/change-risk/partial.json b/packages/claude-mod/test/fixtures/change-risk/partial.jsonindex ec06e435b..8d3270d91 100644--- a/packages/claude-mod/test/fixtures/change-risk/partial.json+++ b/packages/claude-mod/test/fixtures/change-risk/partial.json@@ -59,7 +59,6 @@"fix_history": {"available": true,"density": 1.14,- "percentile": 72.5,"files": [{"path": "src/requests/utils.py",@@ -92,8 +91,6 @@}},"risk_percentile": 40.2,- "review_priority": "moderate",- "classification": "Typical","exclude_patterns": [],"is_fix": false,"impacted_tests": {@@ -154,7 +151,7 @@"truncated": false,"summary": "2 of 6 open branches (6 exist) edit files this change also edits."},- "diff_shape": "Diff shape: bigger than 40% of this repo's recent commits. Size and spread, not danger. Mechanics: get_change_risk(include=['diagnostics']).",+ "diff_shape": "Size and spread: 40th percentile of recent commits (diff size, not a bug predictor). The rank is a diff-size statistic: it barely beats churn alone and cannot rank danger. Mechanics: get_change_risk(include=['diagnostics']).","_meta": {"contract_version": 2,"timing_ms": 2135.0,diff --git a/packages/claude-mod/test/fixtures/change-risk/resolved.json b/packages/claude-mod/test/fixtures/change-risk/resolved.jsonindex de7347dfa..4f3974002 100644--- a/packages/claude-mod/test/fixtures/change-risk/resolved.json+++ b/packages/claude-mod/test/fixtures/change-risk/resolved.json@@ -50,7 +50,6 @@"fix_history": {"available": true,"density": 1.329,- "percentile": 74.8,"files": [{"path": "src/requests/_internal_utils.py",@@ -79,8 +78,6 @@}},"risk_percentile": 17.5,- "review_priority": "low",- "classification": "Below typical","exclude_patterns": [],"is_fix": false,"impacted_tests": {@@ -107,7 +104,7 @@},"summary": "2 test(s) to run for this change; the rest can be skipped."},- "diff_shape": "Diff shape: bigger than 18% of this repo's recent commits. Size and spread, not danger. Mechanics: get_change_risk(include=['diagnostics']).",+ "diff_shape": "Size and spread: 18th percentile of recent commits (diff size, not a bug predictor). The rank is a diff-size statistic: it barely beats churn alone and cannot rank danger. Mechanics: get_change_risk(include=['diagnostics']).","_meta": {"contract_version": 2,"timing_ms": 1016.0,diff --git a/packages/claude-mod/test/fixtures/change-risk/unavailable.json b/packages/claude-mod/test/fixtures/change-risk/unavailable.jsonindex 2bfaf8a27..8de22a6a7 100644--- a/packages/claude-mod/test/fixtures/change-risk/unavailable.json+++ b/packages/claude-mod/test/fixtures/change-risk/unavailable.json@@ -56,7 +56,6 @@"fix_history": {"available": true,"density": 0.0,- "percentile": 21.8,"files": [{"path": "tox.ini",@@ -66,8 +65,6 @@]},"risk_percentile": 34.0,- "review_priority": "moderate",- "classification": "Typical","exclude_patterns": [],"is_fix": false,"impacted_tests": {@@ -124,7 +121,7 @@"truncated": false,"summary": "2 of 6 open branches (6 exist) edit files this change also edits."},- "diff_shape": "Diff shape: bigger than 34% of this repo's recent commits. Size and spread, not danger. Mechanics: get_change_risk(include=['diagnostics']).",+ "diff_shape": "Size and spread: 34th percentile of recent commits (diff size, not a bug predictor). The rank is a diff-size statistic: it barely beats churn alone and cannot rank danger. Mechanics: get_change_risk(include=['diagnostics']).","_meta": {"contract_version": 2,"timing_ms": 1242.0,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 22bd9902b..a3d19017c 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@@ -4,11 +4,10 @@ description: Rank a live change for review using a repo-relative percentile and# Repowise Risk-Assess a *change* (not a file) for review priority. The authoritative fields are-the repo-relative `risk_percentile` and `classification`. The response includes-`fix_history`: the recency-weighted bug-fix record of the files the change-touches, which of them carry it, and where that sits among the repo's own-recent commits. The supporting 0–10 score measures diff size and spread (named+Rank a *change* (not a file) by size and spread. `risk_percentile` is its rank+among the repo's recent commits by diff size: not a bug predictor. The response+includes `fix_history`: the recency-weighted bug-fix record of the files the+change touches, manifests and lockfiles excluded. The supporting 0–10 score measures diff size and spread (namedin `score_measures`) rather than danger and is not a probability. Pure git +learned constants: no LLM, no network. A natural pre-merge / PR gate.@@ -16,8 +15,8 @@ learned constants: no LLM, no network. A natural pre-merge / PR gate.1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `/prompts:repowise-init` first." Stop.2. Resolve the target from `$ARGUMENTS`, run `repowise risk`, and present the- fix history first (which files keep breaking, and the repo-relative- percentile), then the score and its drivers.+ size-and-spread percentile, then the fix history (which files carry prior+ bug fixes), then the score and its drivers.## Choosing the revspecdiff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.pyindex 2859629f2..f651bb954 100644--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py@@ -3,8 +3,9 @@Two questions, one command, because they are the same question asked ofdifferent subjects.-A REVSPEC scores a *change* from its diff shape — size, diffusion, author-familiarity — and prints a benchmarked review priority plus a supporting 0-10+A REVSPEC scores a *change* from its diff shape (size, diffusion, author+familiarity) and leads with its percentile of recent commits by size and+spread, then the bug-fix record of the files it touches, then a supporting 0-10diff-shape score with an attributable breakdown. Runsin-process: pure git + learned constants, no LLM, no network. A naturalpre-merge / PR gate, complementary to ``repowise health`` (which scores files).@@ -15,7 +16,7 @@ is the ``get_risk`` MCP tool, and this command is a thin adapter over it — thesame seam ``ask`` / ``context`` / ``symbol`` / ``why`` use. It reads the indexrather than git, so the repo must be indexed.-``--fail-above-percentile P`` makes the REVSPEC path a CI gate on the+``--fail-above-percentile P`` makes the REVSPEC path a CI size gate on therepo-relative percentile (never the 0-10 score), with the shared CI exit codes(:mod:`repowise.cli.ci`): 1 above the gate, 2 when the change cannot be reador ranked.@@ -36,6 +37,7 @@ from dataclasses import dataclassfrom pathlib import Pathimport click+from rich.markup import escapefrom rich.table import Tablefrom repowise.cli.ci import (@@ -54,18 +56,9 @@ from repowise.cli.output import emit_json, format_option, full_optionfrom repowise.core.analysis.change_risk import (ChangeRiskResult,change_risk_payload,- review_priority_classification,score_live_change,)-from repowise.core.analysis.change_risk.render import ordinal as _ordinal-from repowise.core.analysis.change_risk.render import percentile_text--_PRIORITY_LEAD = {- "low": "Smaller or more focused than a typical commit in this repo",- "moderate": "Typical diff size and spread for this repo",- "high": "Larger or more dispersed than most commits in this repo",-}-+from repowise.core.analysis.change_risk.render import LIMITS, fix_history_text, size_text#: Per-target keys the trim drops, and nothing else.#:@@ -547,7 +540,7 @@ def risk_command(fmt: str,full: bool,) -> None:- """Assess a change's review priority, or the history of named files.+ """Rank a change by size and spread, or report the history of named files.With no --target this scores REVSPEC (a commit, or a ``base..head``range) from its diff. Omit REVSPEC to score your uncommitted work, or@@ -643,38 +636,29 @@ def _score(def _print_change(subject: _Subject, result: ChangeRiskResult, failed: bool) -> None:"""The table rendering of a scored change."""- _print_priority(result, subject.fail_above, failed)+ _print_size(result, subject.fail_above, failed)_print_fix_history_and_shape(result)groups = _independent_changes_for(subject.repo_path, result, subject.revspec)if groups:_print_independent_changes(groups)-def _print_priority(result: ChangeRiskResult, fail_above: float | None, failed: bool) -> None:- """Lead with the benchmarked population-relative authority.+def _print_size(result: ChangeRiskResult, fail_above: float | None, failed: bool) -> None:+ """Lead with the one percentile: the change's rank by diff size and spread.Without a usable baseline, label the offline absolute band explicitly asthe fallback."""- risk, priority = result.risk, result.priority- if result.percentile is not None and priority is not None:- console.print(- f"\n[bold]Benchmarked review priority[/bold]: "- f"{review_priority_classification(priority)} · "- f"{percentile_text(result, fail_above)} percentile of recent commits by size and spread"- )- console.print(f" [dim]{_PRIORITY_LEAD[priority]}.[/dim]")- if fail_above is not None:- from repowise.core.analysis.change_risk.render import gate_text+ console.print(f"\n[bold]{size_text(result.percentile, fail_above)}[/bold]")+ if result.percentile is None:+ level = result.risk.level+ color = {"high": "red", "moderate": "yellow", "low": "green"}[level]+ console.print(f" Absolute per-commit diff-size band: [{color}]{level}[/{color}]")+ elif fail_above is not None:+ from repowise.core.analysis.change_risk.render import gate_text- color = "red" if failed else "green"- console.print(f" [{color}]Gate: {gate_text(result, fail_above)}.[/{color}]")- else:- color = {"high": "red", "moderate": "yellow", "low": "green"}[risk.level]- console.print(- f"\n[bold]Absolute fallback band[/bold]: [{color}]{risk.level}[/{color}] "- "(absolute per-commit band — no repo baseline to rank against)"- )+ color = "red" if failed else "green"+ console.print(f" [{color}]Gate: {gate_text(result, fail_above)}.[/{color}]")def _print_fix_history_and_shape(result: ChangeRiskResult) -> None:@@ -687,27 +671,13 @@ def _print_fix_history_and_shape(result: ChangeRiskResult) -> None:def _print_fix_headline(result: ChangeRiskResult) -> None:"""Fix history remains separate evidence about where the change lands."""- features = result.features+ color = "red" if result.hot_files else "green"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 recent commits"- if result.fix_percentile is not None- else ""- )- console.print(- f"\n[bold]Change risk[/bold] for [cyan]{features.ref}[/cyan]: "- f"[red]touches files that have broken before[/red]{where}"- )- else:- console.print(- f"\n[bold]Change risk[/bold] for [cyan]{features.ref}[/cyan]: "- "[green]no bug-fix history in the files it touches[/green]"- )+ color = "yellow"+ console.print(+ f"\n[bold]Bug-fix record[/bold] for [cyan]{escape(result.features.ref)}[/cyan]: "+ f"[{color}]{fix_history_text(result)}[/{color}]"+ )def _print_change_facts(result: ChangeRiskResult) -> None:@@ -736,7 +706,7 @@ def _print_hot_files(result: ChangeRiskResult) -> None: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}")+ hot.add_row(escape(path), str(churn), f"{pressure:.1f}")console.print(hot)console.print(" [dim]Prior fixes are recency-weighted against this change's own date — "@@ -751,6 +721,7 @@ def _print_diff_shape(result: ChangeRiskResult) -> None: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]")+ console.print(f" [dim]{LIMITS}[/dim]")table = Table(title="Diff shape (each driver vs. the model's baseline commit)")table.add_column("Driver")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.pyindex dc2cf5605..3a6b16c91 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@@ -22,7 +22,9 @@ from __future__ import annotationsimport subprocessfrom collections.abc import Iterable, Sequence+from ...ingestion.external_systems import manifest_ecosystemfrom ...ingestion.git_indexer._constants import is_fix_commit+from ..test_selection import DEPENDENCIES_REASON, full_run_reasonfrom .features import GIT_TIMEOUT_SECONDS, _gitfrom .normalize import RiskNormalizer@@ -263,18 +265,37 @@ MAX_HOT_FILES = 5MIN_DENSITY_POPULATION = 8+#: Manifest parsers whose files hold build logic as well as dependencies.+_BUILD_ECOSYSTEMS = frozenset({"cmake", "bazel"})+++def is_dependency_file(path: str) -> bool:+ """A dependency manifest or lockfile: a fix that bumps a dependency edits it.++ Such a file did not break. Runner configs (``tox.ini``, ``tsconfig.json``)+ and build files the cmake and bazel parsers read (``CMakeLists.txt``,+ ``BUILD``) are not dependency files and keep their fix record.+ """+ ecosystem = manifest_ecosystem(path)+ if ecosystem is not None:+ return ecosystem not in _BUILD_ECOSYSTEMS+ return full_run_reason(path) == DEPENDENCIES_REASON++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.+ order or round the same list differently. Dependency manifests and+ lockfiles are left out of the list (:func:`is_dependency_file`). Display+ only; *pressure* and every density keep them."""rows = [(path, churn, pressure[rename_target(path)])for path, churn in changes- if pressure.get(rename_target(path))+ if pressure.get(rename_target(path)) and not is_dependency_file(rename_target(path))]rows.sort(key=lambda row: -row[2])return tuple((path, churn, round(p, 2)) for path, churn, p in rows[:limit])diff --git a/packages/core/src/repowise/core/analysis/change_risk/render.py b/packages/core/src/repowise/core/analysis/change_risk/render.pyindex 36d798818..e3a76d3a3 100644--- a/packages/core/src/repowise/core/analysis/change_risk/render.py+++ b/packages/core/src/repowise/core/analysis/change_risk/render.py@@ -1,9 +1,9 @@"""CI renderings of a change's risk: markdown, GitHub annotations, the gate.-The gate reads only ``risk_percentile``, the repo-relative rank the risk-authority names as primary (``risk_semantics.change_risk_authority``), never-the 0-10 diff-shape score. A change with no rank cannot be gated, which is the-caller's cue to exit "could not evaluate" with :func:`unranked_reason`.+The gate is a size gate: it reads only ``risk_percentile``, the change's+repo-relative rank by diff size and spread (``risk_semantics.change_risk_authority``),+never the 0-10 diff-shape score. A change with no rank cannot be gated, which is+the caller's cue to exit "could not evaluate" with :func:`unranked_reason`.Workflow-command and markdown mechanics come from :mod:`repowise.core.ci`,shared with every other CI gate.@@ -20,6 +20,9 @@ from .service import _MIN_BASELINE, ChangeRiskResultPercentileGate = Literal["pass", "fail", "no_data", "not_set"]+#: What the rank cannot say, from docs/layers/CHANGE_RISK.md "Accuracy and limits".+LIMITS = "The rank is a diff-size statistic: it barely beats churn alone and cannot rank danger."+def percentile_gate(result: ChangeRiskResult, threshold: float | None) -> PercentileGate:"""``fail`` when the change ranks above *threshold*; unrounded, like every gate."""@@ -66,7 +69,10 @@ def _rank_text(value: float) -> str:def percentile_number(result: ChangeRiskResult, threshold: float | None = None) -> str | None:"""The change's rank as a number, rounded unless rounding would contradict the gate."""- pct = result.percentile+ return _percentile_number(result.percentile, threshold)+++def _percentile_number(pct: float | None, threshold: float | None) -> str | None:if pct is None:return Noneshown = round(pct)@@ -76,12 +82,16 @@ def percentile_number(result: ChangeRiskResult, threshold: float | None = None)return str(shown)-def percentile_text(result: ChangeRiskResult, threshold: float | None = None) -> str:- """:func:`percentile_number` as an ordinal (``97th``, ``95.4th``), or ``unranked``."""- number = percentile_number(result, threshold)+def size_text(percentile: float | None, threshold: float | None = None) -> str:+ """The lead line every surface shows: the one percentile, named for what it ranks.++ The rank reads as an ordinal (``97th``, or ``95.4th`` beside a 95 gate).+ """+ number = _percentile_number(percentile, threshold)if number is None:- return "unranked"- return f"{number}th" if "." in number else ordinal(int(number))+ return "Size and spread: unranked (no baseline to rank it against)"+ rank = f"{number}th" if "." in number else ordinal(int(number))+ return f"Size and spread: {rank} percentile of recent commits (diff size, not a bug predictor)"def headline(result: ChangeRiskResult, threshold: float | None, *, markdown: bool = True) -> str:@@ -90,42 +100,40 @@ def headline(result: ChangeRiskResult, threshold: float | None, *, markdown: boonumber = percentile_number(result, threshold)if number is None:# True for --baseline 0 and for a history of fewer than the minimum.- return f"{bold}Change risk: unranked{bold} · too few recent commits to rank it"+ return f"{bold}Size and spread: unranked{bold} · no baseline to rank it against"if "." not in number:# "Larger than N%" is a lower bound: floor it, and never claim all 100%.number = str(min(math.floor(result.percentile), 99))rank = f"larger and more spread out than {number}% of recent commits"gate = percentile_gate(result, threshold)if gate == "fail":- return f"{bold}Above the {_rank_text(threshold)} percentile gate{bold}: {rank}"+ return f"{bold}Above the {_rank_text(threshold)} percentile size gate{bold}: {rank}"if gate == "pass":- return f"{bold}Within the {_rank_text(threshold)} percentile gate{bold}: {rank}"- return f"{bold}Change risk{bold}: {rank}"+ return f"{bold}Within the {_rank_text(threshold)} percentile size gate{bold}: {rank}"+ return f"{bold}Size and spread{bold}: {rank}"def gate_text(result: ChangeRiskResult, threshold: float | None) -> str:- """``"above the 95th percentile gate"``, ``"within ..."``, or ``""`` ungated."""+ """``"above the 95th percentile size gate"``, ``"within ..."``, or ``""`` ungated."""gate = percentile_gate(result, threshold)if gate == "fail":- return f"above the {_rank_text(threshold)} percentile gate"+ return f"above the {_rank_text(threshold)} percentile size gate"if gate == "pass":- return f"within the {_rank_text(threshold)} percentile gate"+ return f"within the {_rank_text(threshold)} percentile size gate"return ""def fix_history_text(result: ChangeRiskResult) -> str:- """Where the change lands: the bug-fix record of the files it touches."""+ """Where the change lands: the bug-fix record of the files it touches.++ No percentile: the size rank is the one percentile on screen, and the fix+ record reads plainest as the files and their recency-weighted fix counts.+ """if not result.fix_history_available:return "fix history unavailable (the git history walk failed)"if not result.hot_files:return "no bug-fix history in the files it touches"- where = (- f" ({ordinal(round(result.fix_percentile))} percentile of recent commits "- "by bug-fix history)"- if result.fix_percentile is not None- else ""- )- return f"touches files that have broken before{where}"+ return "touches files with prior bug fixes"def scope_line(result: ChangeRiskResult, *, markdown: bool = True) -> str:@@ -156,6 +164,7 @@ def render_markdown(result: ChangeRiskResult, threshold: float | None = None) ->if len(hot) > ROW_LIMIT:out += ["", more_line(len(hot) - ROW_LIMIT, "files with bug-fix history")]out += ["", "Bug fixes are recency-weighted: one from a year earlier counts a half."]+ out += ["", LIMITS]return "\n".join(out) + "\n"diff --git a/packages/core/src/repowise/core/analysis/risk_semantics.py b/packages/core/src/repowise/core/analysis/risk_semantics.pyindex fe0fd4886..579ad49fc 100644--- a/packages/core/src/repowise/core/analysis/risk_semantics.py+++ b/packages/core/src/repowise/core/analysis/risk_semantics.py@@ -77,11 +77,16 @@ def structural_impact_band(score: float) -> str:def change_risk_authority() -> dict[str, Any]:- """Authority and scalar metadata shared by live-diff public surfaces."""+ """What the live-diff fields rank, shared by every public surface.++ The rank is of diff size and spread, not of defect risk: against churn+ alone it barely moves, and it cannot rank danger (docs/layers/CHANGE_RISK.md).+ The key names are wire contract; the values say what is ranked.+ """return {- "authoritative_for": "live_change_review",- "primary_fields": ["risk_percentile", "classification"],- "primary_basis": "benchmarked_population_relative",+ "authoritative_for": "diff_size_rank",+ "primary_fields": ["risk_percentile"],+ "primary_basis": "population_relative_diff_size","fallback_field": "fallback_band","fallback_basis": "absolute_model_score_band","score_role": "supporting_diff_shape_signal",@@ -115,7 +120,7 @@ def change_risk_scales() -> list[dict[str, Any]]:"measures": "rank of the diff-shape score among sampled recent commits","deterministic": True,"calibration": {- "status": "benchmarked",+ "status": "not_applicable","source": "live repository baseline","population": "sampled recent commits after the same filters",},@@ -132,16 +137,16 @@ def change_risk_scales() -> list[dict[str, Any]]:"moderate_percentile": REVIEW_PRIORITY_MODERATE_PERCENTILE,"high_percentile": REVIEW_PRIORITY_HIGH_PERCENTILE,},- "authoritative": True,+ "authoritative": False,},{"field": "classification","kind": "classification_label","unit": "category","range": None,- "measures": "human-facing label for review_priority",+ "measures": "human-facing label for review_priority: a diff-size tercile","deterministic": True,- "authoritative": True,+ "authoritative": False,},{"field": "fallback_band",@@ -179,7 +184,7 @@ def change_risk_scales() -> list[dict[str, Any]]:"measures": "rank of fix-history density among sampled recent commits","deterministic": True,"calibration": {- "status": "benchmarked",+ "status": "not_applicable","source": "live repository baseline","population": "sampled recent commits after the same filters",},diff --git a/packages/core/src/repowise/core/analysis/test_selection.py b/packages/core/src/repowise/core/analysis/test_selection.pyindex 8a2507b16..523fe4081 100644--- a/packages/core/src/repowise/core/analysis/test_selection.py+++ b/packages/core/src/repowise/core/analysis/test_selection.py@@ -80,12 +80,13 @@ RUN_ALL = ":all"RUNNERS = ("auto", "pytest", "go", "jest", "files")SHARED_TEST_DATA_REASON = "shared test data can change any test"+DEPENDENCIES_REASON = "dependencies can change any test"# (why it forces a full run, gitwildmatch patterns). The config extends these,# never replaces them. Ceiling: no opt-out until someone needs one._FULL_RUN_GROUPS: tuple[tuple[str, tuple[str, ...]], ...] = ((- "dependencies can change any test",+ DEPENDENCIES_REASON,("package-lock.json","yarn.lock",diff --git a/packages/core/src/repowise/core/ingestion/external_systems/__init__.py b/packages/core/src/repowise/core/ingestion/external_systems/__init__.pyindex 19eab5155..cfcf7d680 100644--- a/packages/core/src/repowise/core/ingestion/external_systems/__init__.py+++ b/packages/core/src/repowise/core/ingestion/external_systems/__init__.py@@ -29,6 +29,7 @@ __all__ = ["ManifestParser","extract_external_systems","is_manifest_path",+ "manifest_ecosystem",]_PARSERS: tuple[ModuleType, ...] = (npm, pypi, cargo, go, nuget, maven, cmake, bazel)@@ -66,6 +67,12 @@ def is_manifest_path(path: Path | str) -> bool:return _parser_for(Path(path)) is not None+def manifest_ecosystem(path: Path | str) -> str | None:+ """The ``ecosystem`` of the parser that reads ``path``, or ``None``."""+ parser = _parser_for(Path(path))+ return parser.ecosystem if parser is not None else None++def extract_external_systems(repo_root: Path,manifest_paths: Iterable[Path] | None = None,diff --git a/packages/server/src/repowise/server/chat_suggestions.py b/packages/server/src/repowise/server/chat_suggestions.pyindex 4b477c432..93d851521 100644--- a/packages/server/src/repowise/server/chat_suggestions.py+++ b/packages/server/src/repowise/server/chat_suggestions.py@@ -238,23 +238,22 @@ def _from_get_change_risk(target: str, result: Mapping[str, Any]) -> list[dict[s# ``drivers`` is diagnostics-gated and absent from the prefetch, so the# measured values named here are the ones the default response always# carries.+ # The tercile label ships only with include=["scales"]; the percentile+ # always does, so either one means the change was ranked.classification = result.get("classification") or result.get("review_priority")- if isinstance(classification, str) and classification:- percentile = result.get("risk_percentile")- # Stored to one decimal; every other surface shows it whole.- measured = (- f" at p{round(percentile)}" if isinstance(percentile, (int, float)) else ""- )- out.append(- _suggestion(- f"What makes {ref} {classification.lower()}{measured}?",- "page",- "get_change_risk",- )- )+ percentile = result.get("risk_percentile")+ # Stored to one decimal; every other surface shows it whole.+ measured = f" at p{round(percentile)}" if isinstance(percentile, (int, float)) else ""+ labelled = isinstance(classification, str) and bool(classification)+ if labelled:+ question = f"What makes {ref} {classification.lower()}{measured}?"+ else:+ question = f"What drives the diff size of {ref}{measured}?" if measured else ""+ if question:+ out.append(_suggestion(question, "page", "get_change_risk"))if result.get("is_fix") is True:out.append(_suggestion(f"What did {ref} fix?", "page", "get_change_risk"))- if isinstance(classification, str) and classification:+ if question:out.append(_suggestion(f"Which files in {ref} deserve the closest review?", "page", "get_risk"diff --git a/packages/server/src/repowise/server/chat_summaries.py b/packages/server/src/repowise/server/chat_summaries.pyindex 474c58e57..834e9de3a 100644--- a/packages/server/src/repowise/server/chat_summaries.py+++ b/packages/server/src/repowise/server/chat_summaries.py@@ -32,10 +32,12 @@ def _risk_summary(result: dict[str, Any]) -> str:def _change_risk_summary(result: dict[str, Any]) -> str:ref = result.get("ref", "change")# The tercile ranks diff size, so the summary names the size label, not a verdict.- size = result.get("classification") or result.get("review_priority") or "unranked"+ # The label ships only with include=["scales"]; the percentile always does.+ label = result.get("classification") or result.get("review_priority")+ size = label or "unranked"pct = result.get("risk_percentile")if pct is not None:- return f"Diff size for {ref}: {size} (p{pct})"+ return f"Diff size for {ref}: {label} (p{pct})" if label else f"Diff size for {ref}: p{pct}"score = result.get("score")if score is not None:return f"Diff size for {ref}: {size} (score {score})"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.pyindex 3f3aef51c..2293f49ef 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@@ -4,7 +4,6 @@ from __future__ import annotationsimport asyncioimport contextlib-import mathimport shutilimport subprocessimport threading@@ -29,6 +28,7 @@ from repowise.core.analysis.change_risk import (normalize_extensions,score_live_change,)+from repowise.core.analysis.change_risk.render import LIMITS, size_textfrom repowise.core.analysis.prior_fix_impact import (FixRecord,PriorFixFile,@@ -144,6 +144,8 @@ _HEALTH_DIAGNOSTIC_FIELDS = ("analyzer", "base", "head", "limits")#: ``classification`` labels for the MCP surface. ``review_priority`` is a#: tercile of the diff-shape rank, so the label names size, not a verdict.+#: Both ship only under ``include=["scales"]``: ``risk_percentile`` is the one+#: rank on the default response._DIFF_SIZE_LABELS = {"low": "Below-typical diff size","moderate": "Typical diff size",@@ -268,10 +270,16 @@ def _shape_payload(result: Any, include_set: set[str], revspec: str | None) -> tout of the payload when the caller did not ask for them."""payload = change_risk_payload(result, scales="scales" in include_set)- if payload.get("review_priority") in _DIFF_SIZE_LABELS:+ if "scales" not in include_set:+ payload.pop("review_priority")+ payload.pop("classification")+ elif payload.get("review_priority") in _DIFF_SIZE_LABELS:payload["classification"] = _DIFF_SIZE_LABELS[payload["review_priority"]]if "diagnostics" not in include_set:diagnostics = {f: payload.pop(f) for f in _DIAGNOSTIC_FIELDS if f in payload}+ # The fix record reads as files and counts; its rank is a second+ # percentile beside ``risk_percentile`` and only invited comparing them.+ payload["fix_history"].pop("percentile", None)payload["fix_history"].pop("density", None)else:diagnostics = {}@@ -310,8 +318,8 @@ async def get_change_risk(pre-existing.``directive.status`` is the verdict; ``partial`` health means code files- were skipped. ``review_priority``, ``classification`` and ``diff_shape``- measure diff size only, not danger.+ were skipped. ``risk_percentile`` and ``diff_shape`` measure diff size+ only, not danger.``impacted_tests`` is the ``impacted-tests`` selection; read ``run_all``.``patch_coverage`` is the share of changed executable lines stored coverage@@ -330,7 +338,7 @@ async def get_change_risk(comma-separated string, e.g. ``"src/api/,src/db/"``. Omit for all.baseline: Recent commits sampled for percentile ranking; 0 disables it.include: ``"findings"``, ``"diagnostics"`` (raw mechanics) or- ``"scales"`` (units).+ ``"scales"`` (units, size tercile).finding_id: Expand one ``health_delta`` finding by its id."""if repo == "all":@@ -592,14 +600,8 @@ def _diff_shape_sentence(payload: dict, diagnostics: dict) -> str:It replaced a block that restated four fields already at the top level andwas read in 2 of 118 recorded calls."""- pct = payload.get("risk_percentile")- where = (- f"bigger than {min(math.floor(pct), 99)}% of this repo's recent commits"- if pct is not None- else "unranked (no baseline to compare against)"- )tail = " Mechanics: get_change_risk(include=['diagnostics'])." if diagnostics else ""- return f"Diff shape: {where}. Size and spread, not danger.{tail}"+ return f"{size_text(payload.get('risk_percentile'))}. {LIMITS}{tail}"def _drill_down(payload: dict, delta: Any, finding_id: str, revspec: str | None) -> dict:diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.pyindex 94dc37b11..15c381958 100644--- a/packages/server/src/repowise/server/schemas/git.py+++ b/packages/server/src/repowise/server/schemas/git.py@@ -198,7 +198,7 @@ class CommitResponse(BaseModel):# Repo-relative normalization (the portable signal).#: Repo-relative percentile rank, 0-100.risk_percentile: float- #: Authoritative repo-relative review-priority tercile.+ #: Repo-relative tercile of the diff-size percentile; size, not danger.review_priority: str# The dominant risk driver, surfaced on rows so reviewers don't have to# open every detail sheet. Recomputed deterministically from the stored@@ -395,7 +395,7 @@ class RiskRangeResponse(BaseModel):base: strhead: str#: Separate historical evidence about where the change lands; it is not- #: folded into the authoritative percentile/classification.+ #: folded into the diff-size percentile.fix_history: FixHistoryResponserisk_authority: RiskAuthorityscore: floatdiff --git a/packages/types/src/git.ts b/packages/types/src/git.tsindex 6f6e42c8d..1c68bc195 100644--- a/packages/types/src/git.ts+++ b/packages/types/src/git.ts@@ -121,8 +121,8 @@ export interface Hotspot {original_path?: string | null;}-/** Repo-relative review priority derived from the score's percentile within- * its own repo (terciles) — portable, unlike the absolute calibration band. */+/** Repo-relative tercile of the diff-size percentile within its own repo;+ * size, not danger. */export type ReviewPriority = "low" | "moderate" | "high";export interface Commit {@@ -146,7 +146,7 @@ export interface Commit {change_risk_level: ReviewPriority | null;/** Where this commit's score sits within its repo's distribution, 0–100. */risk_percentile: number;- /** Repo-relative review priority (the portable ranking signal). */+ /** Repo-relative tercile of the diff-size percentile; size, not danger. */review_priority: ReviewPriority;/** Label of the dominant risk driver, so rows explain themselves without* opening the detail sheet. Null when the commit was never risk-scored. */diff --git a/packages/types/src/risk-semantics.ts b/packages/types/src/risk-semantics.tsindex f0cf63884..60d69a7ce 100644--- a/packages/types/src/risk-semantics.ts+++ b/packages/types/src/risk-semantics.ts@@ -33,9 +33,9 @@ export interface RiskScalarSemantics {}export interface RiskAuthority {- authoritative_for: "live_change_review";- primary_fields: ["risk_percentile", "classification"];- primary_basis: "benchmarked_population_relative";+ authoritative_for: "diff_size_rank";+ primary_fields: ["risk_percentile"];+ primary_basis: "population_relative_diff_size";fallback_field: "fallback_band";fallback_basis: "absolute_model_score_band";score_role: "supporting_diff_shape_signal";diff --git a/packages/vscode/webview/src/views/risk/App.test.tsx b/packages/vscode/webview/src/views/risk/App.test.tsxindex 6929db1ec..3c4478e79 100644--- a/packages/vscode/webview/src/views/risk/App.test.tsx+++ b/packages/vscode/webview/src/views/risk/App.test.tsx@@ -27,9 +27,9 @@ const REPORT: RiskRangeReport = {files: [{ path: "src/core.ts", churn: 40, fix_pressure: 5.5 }],},risk_authority: {- authoritative_for: "live_change_review",- primary_fields: ["risk_percentile", "classification"],- primary_basis: "benchmarked_population_relative",+ authoritative_for: "diff_size_rank",+ primary_fields: ["risk_percentile"],+ primary_basis: "population_relative_diff_size",fallback_field: "fallback_band",fallback_basis: "absolute_model_score_band",score_role: "supporting_diff_shape_signal",diff --git a/plugins/claude-code/README.md b/plugins/claude-code/README.mdindex c189e8f76..00e2ecbc2 100644--- a/plugins/claude-code/README.md+++ b/plugins/claude-code/README.md@@ -90,7 +90,7 @@ surface is the ten flagship tools below plus `list_repos` (see| `get_symbol` | Raw source of one symbol with exact line bounds || `search_codebase` | Hybrid code search — `mode="auto"` routes identifiers to indexed symbols, paths to files, prose to semantic wiki search || `get_risk` | Per-file hotspot, dependents, co-changes, owners; PR `directive` block with `changed_files` |-| `get_change_risk` | Benchmarked live-change percentile/classification plus supporting diff-shape score |+| `get_change_risk` | Health delta of a change, its size-and-spread percentile and the touched files' bug-fix record || `get_why` | Architectural decisions — search, path-anchored, or health dashboard || `get_dead_code` | Unused/unreachable findings tiered by confidence || `get_health` | 1–10 code-health score and marker findings per file |diff --git a/plugins/claude-code/commands/risk.md b/plugins/claude-code/commands/risk.mdindex 94a4c098a..667e9ea5e 100644--- a/plugins/claude-code/commands/risk.md+++ b/plugins/claude-code/commands/risk.md@@ -5,11 +5,10 @@ allowed-tools: Bash(repowise risk:*), Read# Repowise Risk-Assess a *change* (not a file) for review priority. The authoritative fields are-the repo-relative `risk_percentile` and `classification`. The response includes-`fix_history`: the recency-weighted bug-fix record of the files the change-touches, which of them carry it, and where that sits among the repo's own-recent commits. The supporting 0–10 score measures diff size and spread (named+Rank a *change* (not a file) by size and spread. `risk_percentile` is its rank+among the repo's recent commits by diff size: not a bug predictor. The response+includes `fix_history`: the recency-weighted bug-fix record of the files the+change touches, manifests and lockfiles excluded. The supporting 0–10 score measures diff size and spread (namedin `score_measures`) rather than danger and is not a probability. Pure git +learned constants: no LLM, no network. A natural pre-merge / PR gate.@@ -17,8 +16,8 @@ learned constants: no LLM, no network. A natural pre-merge / PR gate.1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `/repowise:init` first." Stop.2. Resolve the target from `$ARGUMENTS`, run `repowise risk`, and present the- fix history first (which files keep breaking, and the repo-relative- percentile), then the score and its drivers.+ size-and-spread percentile, then the fix history (which files carry prior+ bug fixes), then the score and its drivers.## Choosing the revspecdiff --git a/plugins/claude-code/skills/change-review/SKILL.md b/plugins/claude-code/skills/change-review/SKILL.mdindex 3f0b97bff..b9c009bb1 100644--- a/plugins/claude-code/skills/change-review/SKILL.md+++ b/plugins/claude-code/skills/change-review/SKILL.md@@ -22,10 +22,12 @@ Two complementary risk signals, use both:tool; it takes a revspec and diffs server-side, so you never shell out. Leadwith `directive` and `health_delta` — what the change actually made worse.Findings the change wrote sort above pre-existing ones it only touched.- Then `risk_percentile` (this change ranked against sampled recent commits),- summarized by `review_priority` and `classification`. The raw 0-10 `score`+ Then `risk_percentile` (this change ranked against sampled recent commits by+ diff size and spread, not a bug predictor), stated in one line by+ `diff_shape`; `include=["scales"]` adds its `review_priority` tercile and+ `classification` label. The raw 0-10 `score`ranks 0.99 against lines added, so it sits behind `include=["diagnostics"]`- rather than on the wire; `diff_shape` states the ranking in one line.+ rather than on the wire.Omit `revspec` to score uncommitted work. This is the pre-merge gate: "how risky is thischange overall?" The `repowise risk <revspec>` CLI is the identical scorer forwhen you are already in a terminal.diff --git a/plugins/codex/skills/change-review/SKILL.md b/plugins/codex/skills/change-review/SKILL.mdindex 51d2036b5..b48136c09 100644--- a/plugins/codex/skills/change-review/SKILL.md+++ b/plugins/codex/skills/change-review/SKILL.md@@ -17,10 +17,12 @@ Two complementary risk signals, use both:tool; it takes a revspec and diffs server-side, so you never shell out. Leadwith `directive` and `health_delta` — what the change actually made worse.Findings the change wrote sort above pre-existing ones it only touched.- Then `risk_percentile` (this change ranked against sampled recent commits),- summarized by `review_priority` and `classification`. The raw 0-10 `score`+ Then `risk_percentile` (this change ranked against sampled recent commits by+ diff size and spread, not a bug predictor), stated in one line by+ `diff_shape`; `include=["scales"]` adds its `review_priority` tercile and+ `classification` label. The raw 0-10 `score`ranks 0.99 against lines added, so it sits behind `include=["diagnostics"]`- rather than on the wire; `diff_shape` states the ranking in one line.+ rather than on the wire.Omit `revspec` to score uncommitted work. This is the pre-merge gate: "how risky is thischange overall?" The `repowise risk <revspec>` CLI is the identical scorer forwhen you are already in a terminal.diff --git a/plugins/shared/commands/risk.md b/plugins/shared/commands/risk.mdindex aa10aa8d4..c777daa9e 100644--- a/plugins/shared/commands/risk.md+++ b/plugins/shared/commands/risk.md@@ -6,11 +6,10 @@ frontmatter: |# Repowise Risk-Assess a *change* (not a file) for review priority. The authoritative fields are-the repo-relative `risk_percentile` and `classification`. The response includes-`fix_history`: the recency-weighted bug-fix record of the files the change-touches, which of them carry it, and where that sits among the repo's own-recent commits. The supporting 0–10 score measures diff size and spread (named+Rank a *change* (not a file) by size and spread. `risk_percentile` is its rank+among the repo's recent commits by diff size: not a bug predictor. The response+includes `fix_history`: the recency-weighted bug-fix record of the files the+change touches, manifests and lockfiles excluded. The supporting 0–10 score measures diff size and spread (namedin `score_measures`) rather than danger and is not a probability. Pure git +learned constants: no LLM, no network. A natural pre-merge / PR gate.@@ -18,8 +17,8 @@ learned constants: no LLM, no network. A natural pre-merge / PR gate.1. If `.repowise/` doesn't exist: "This repo isn't indexed yet. Run `{{cmd:init}}` first." Stop.2. Resolve the target from `$ARGUMENTS`, run `repowise risk`, and present the- fix history first (which files keep breaking, and the repo-relative- percentile), then the score and its drivers.+ size-and-spread percentile, then the fix history (which files carry prior+ bug fixes), then the score and its drivers.## Choosing the revspecdiff --git a/plugins/shared/skills/change-review.md b/plugins/shared/skills/change-review.mdindex c23a565e6..4b023980f 100644--- a/plugins/shared/skills/change-review.md+++ b/plugins/shared/skills/change-review.md@@ -30,10 +30,12 @@ Two complementary risk signals, use both:tool; it takes a revspec and diffs server-side, so you never shell out. Leadwith `directive` and `health_delta` — what the change actually made worse.Findings the change wrote sort above pre-existing ones it only touched.- Then `risk_percentile` (this change ranked against sampled recent commits),- summarized by `review_priority` and `classification`. The raw 0-10 `score`+ Then `risk_percentile` (this change ranked against sampled recent commits by+ diff size and spread, not a bug predictor), stated in one line by+ `diff_shape`; `include=["scales"]` adds its `review_priority` tercile and+ `classification` label. The raw 0-10 `score`ranks 0.99 against lines added, so it sits behind `include=["diagnostics"]`- rather than on the wire; `diff_shape` states the ranking in one line.+ rather than on the wire.Omit `revspec` to score uncommitted work. This is the pre-merge gate: "how risky is thischange overall?" The `repowise risk <revspec>` CLI is the identical scorer forwhen you are already in a terminal.diff --git a/tests/unit/analysis/test_change_risk.py b/tests/unit/analysis/test_change_risk.pyindex ffc6090cd..8c39ad382 100644--- a/tests/unit/analysis/test_change_risk.py+++ b/tests/unit/analysis/test_change_risk.py@@ -104,9 +104,9 @@ def test_payload_includes_friendly_repo_relative_classification() -> None:assert payload["classification"] == "Typical"assert payload["baseline_sample_size"] == 200assert payload["risk_authority"] == {- "authoritative_for": "live_change_review",- "primary_fields": ["risk_percentile", "classification"],- "primary_basis": "benchmarked_population_relative",+ "authoritative_for": "diff_size_rank",+ "primary_fields": ["risk_percentile"],+ "primary_basis": "population_relative_diff_size","fallback_field": "fallback_band","fallback_basis": "absolute_model_score_band","score_role": "supporting_diff_shape_signal",diff --git a/tests/unit/analysis/test_change_risk_fix_history.py b/tests/unit/analysis/test_change_risk_fix_history.pyindex 247488cad..36823e15b 100644--- a/tests/unit/analysis/test_change_risk_fix_history.py+++ b/tests/unit/analysis/test_change_risk_fix_history.py@@ -22,6 +22,7 @@ from repowise.core.analysis.change_risk import (fix_density_percentile,fix_pressure,fixes_reachable_from,+ hot_files,score_live_change,)from repowise.core.analysis.change_risk.fix_history import rename_target@@ -127,6 +128,39 @@ def test_fix_pressure_counts_only_fix_commits(repo_with_history: Path) -> None:assert "cold.py" not in pressure # churn is not fix history+_MANIFESTS = ("package.json", "web/package-lock.json", "pyproject.toml")+++def _dependency_fix(repo: Path) -> None:+ files = {"hot.py": "v = 9\n", **{path: "{}\n" for path in _MANIFESTS}}+ _commit(repo, files, "fix: pin the parser dependency")+++def test_fix_pressure_still_counts_manifests(repo_with_history: Path) -> None:+ """The pressure feeds densities and the risky-file gate, so it stays whole."""+ _dependency_fix(repo_with_history)+ pressure = fix_pressure(str(repo_with_history), "HEAD")+ assert pressure["hot.py"] == pytest.approx(4.0, abs=0.05)+ assert set(_MANIFESTS) <= set(pressure)+++def test_hot_files_leave_out_manifests_and_lockfiles(repo_with_history: Path) -> None:+ """A fix that bumps a dependency edits the manifest; that file did not break."""+ _dependency_fix(repo_with_history)+ pressure = fix_pressure(str(repo_with_history), "HEAD")+ rows = hot_files(pressure, [("hot.py", 1), *((path, 1) for path in _MANIFESTS)])+ assert [path for path, _, _ in rows] == ["hot.py"]+++def test_hot_files_keep_runner_configs_with_prior_fixes() -> None:+ """Only dependency files drop out; runner configs and build files can break."""+ kept = ("tox.ini", "web/tsconfig.json", "CMakeLists.txt", "lib/BUILD.bazel")+ paths = (*kept, "package.json", "web/yarn.lock", "go.sum")+ pressure = {path: 2.0 for path in paths}+ rows = hot_files(pressure, [(path, 1) for path in paths], limit=len(paths))+ assert sorted(path for path, _, _ in rows) == sorted(kept)++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")diff --git a/tests/unit/change_health/test_mcp_contract.py b/tests/unit/change_health/test_mcp_contract.pyindex 325614c9e..2465faf2e 100644--- a/tests/unit/change_health/test_mcp_contract.py+++ b/tests/unit/change_health/test_mcp_contract.py@@ -77,9 +77,14 @@ async def test_legacy_ranked_fields_stay_at_the_top_level(tool, make_repo):module = tool(seeded(make_repo))result = await module.get_change_risk("HEAD", baseline=0)+ scaled = await module.get_change_risk("HEAD", baseline=0, include=["scales"])- for field in ("ref", "risk_percentile", "review_priority", "classification"):+ for field in ("ref", "risk_percentile"):assert field in result+ # The size tercile repeats the percentile, so it ships with the scales.+ for field in ("review_priority", "classification"):+ assert field not in result+ assert field in scaledasync def test_the_raw_score_is_not_on_the_wire_by_default(tool, make_repo):diff --git a/tests/unit/cli/test_risk_cmd.py b/tests/unit/cli/test_risk_cmd.pyindex fbf361fe2..344ef6c1f 100644--- a/tests/unit/cli/test_risk_cmd.py+++ b/tests/unit/cli/test_risk_cmd.py@@ -60,7 +60,7 @@ def test_risk_uses_root_riskignore_and_repeatable_excludes(tmp_path: Path) -> Noassert payload["features"]["nf"] == 1assert payload["features"]["la"] == 1assert payload["exclude_patterns"] == ["tests/", "*.spec.ts"]- assert payload["risk_authority"]["primary_fields"] == ["risk_percentile", "classification"]+ assert payload["risk_authority"]["primary_fields"] == ["risk_percentile"]assert payload["risk_authority"]["score_role"] == "supporting_diff_shape_signal"assert {scale["unit"] for scale in payload["risk_scales"]} >= {"normalized_points",@@ -89,12 +89,12 @@ def test_risk_human_output_labels_absolute_fallback_when_baseline_is_disabled()assert result.exit_code == 0, result.output- assert "Absolute fallback band:" in result.output- assert "Benchmarked review priority:" not in result.output+ assert "Size and spread: unranked" in result.output+ assert "Absolute per-commit diff-size band:" in result.outputassert "probability" not in result.output.lower()-def test_risk_human_output_leads_with_benchmarked_review_priority(tmp_path: Path) -> None:+def test_risk_human_output_leads_with_the_size_percentile(tmp_path: Path) -> None:repo = tmp_path / "repo"repo.mkdir()_git(["init", "-q"], repo)@@ -105,9 +105,13 @@ def test_risk_human_output_leads_with_benchmarked_review_priority(tmp_path: Pathresult = CliRunner().invoke(risk_command, ["HEAD", "--path", str(repo)])assert result.exit_code == 0, result.output- assert "Benchmarked review priority:" in result.output- assert "percentile of recent commits by size and spread" in result.output- assert "Absolute fallback band:" not in result.output+ lead = result.output.split("Size and spread: ", 1)[1].splitlines()[0]+ assert lead.endswith("percentile of recent commits (diff size, not a bug predictor)")+ # One percentile on screen: the fix record is files and counts, never a rank.+ assert result.output.count("percentile") == 1+ assert "priority" not in result.output.lower()+ assert "cannot rank danger" in result.output+ assert "diff-size band" not in result.outputdef test_risk_help_describes_repeatable_exclude() -> None:@@ -225,18 +229,21 @@ def test_markdown_and_github_lead_with_the_verdict(tmp_path: Path) -> None:md = _gate(repo, "HEAD", "--fail-above-percentile", "0", "--format", "markdown")assert md.exit_code == 1first, _, scope = md.stdout.splitlines()[:3]- assert first.startswith("**Above the 0th percentile gate**: larger and more spread out than ")+ assert first.startswith(+ "**Above the 0th percentile size gate**: larger and more spread out than "+ )assert first.endswith("% of recent commits")assert "absolute" not in md.stdoutassert "across 1 directory" in scope+ assert md.stdout.rstrip().endswith("cannot rank danger.")gh = _gate(repo, "HEAD", "--fail-above-percentile", "0", "--format", "github",env={"GITHUB_STEP_SUMMARY": str(summary)},)assert gh.exit_code == 1- assert gh.stdout.startswith("::error::Above the 0th percentile gate: ")- assert summary.read_text(encoding="utf-8").startswith("**Above the 0th percentile gate**")+ assert gh.stdout.startswith("::error::Above the 0th percentile size gate: ")+ assert summary.read_text(encoding="utf-8").startswith("**Above the 0th percentile size gate**")def test_ci_formats_score_the_ci_change_without_the_gate(tmp_path: Path) -> None:@@ -245,7 +252,7 @@ def test_ci_formats_score_the_ci_change_without_the_gate(tmp_path: Path) -> Nonemd = _gate(repo, "--format", "markdown", env={"GITHUB_BASE_REF": "main"})assert md.exit_code == 0, md.output- assert md.stdout.startswith("**Change risk**: larger and more spread out than ")+ assert md.stdout.startswith("**Size and spread**: larger and more spread out than ")assert "`origin/main...HEAD`" in md.stdout@@ -255,30 +262,39 @@ def _scored(percentile: float | None):return SimpleNamespace(percentile=percentile)-def test_percentile_text_never_hides_which_side_of_the_gate() -> None:+def test_size_text_never_hides_which_side_of_the_gate() -> None:from repowise.core.analysis.change_risk.render import (_rank_text,headline,percentile_gate,- percentile_text,+ size_text,)+ def rank(pct: float | None, gate: float | None = None) -> str:+ text = size_text(pct, gate).removeprefix("Size and spread: ")+ return text.split(" percentile")[0].split(" (")[0]+assert _rank_text(95.0) == "95th"assert _rank_text(95.4) == "95.4th"assert _rank_text(95.001) == "95.001th"assert "." not in _rank_text(95.0).removesuffix("th")# Rounds as usual when rounding agrees with the gate.- assert percentile_text(_scored(96.7), 95) == "97th"- assert percentile_text(_scored(21.0)) == "21st"+ assert rank(96.7, 95) == "97th"+ assert rank(21.0) == "21st"# Just above an integer gate: rounding to 95 would read as "not above".- assert percentile_text(_scored(95.4), 95) == "95.4th"- assert percentile_text(_scored(95.0004), 95) == "95.0004th"+ assert rank(95.4, 95) == "95.4th"+ assert rank(95.0004, 95) == "95.0004th"assert percentile_gate(_scored(95.0004), 95) == "fail"- assert percentile_text(_scored(None)) == "unranked"+ assert rank(None) == "unranked"+ # --baseline 0 turns ranking off on purpose, so the line blames no history.+ assert size_text(None) == "Size and spread: unranked (no baseline to rank it against)"+ assert size_text(21.0) == (+ "Size and spread: 21st percentile of recent commits (diff size, not a bug predictor)"+ )unranked = headline(_scored(None), 95, markdown=False)- assert unranked == "Change risk: unranked · too few recent commits to rank it"+ assert unranked == "Size and spread: unranked · no baseline to rank it against"assert headline(_scored(40.0), 95, markdown=False) == (- "Within the 95th percentile gate: larger and more spread out than 40% of recent commits"+ "Within the 95th percentile size gate: larger and more spread out than 40% of recent commits")diff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.pyindex 1883f0174..5f06084eb 100644--- a/tests/unit/server/mcp/test_change_risk.py+++ b/tests/unit/server/mcp/test_change_risk.py@@ -79,14 +79,12 @@ async def test_get_change_risk_honors_riskignore_and_request_filters(tmp_path, m"entropy": 0.0,"exp": 1,}- assert diagnostics["risk_authority"]["primary_fields"] == [- "risk_percentile",- "classification",- ]+ assert diagnostics["risk_authority"]["primary_fields"] == ["risk_percentile"]assert result["exclude_patterns"] == ["tests/", "docs/"]assert result["risk_percentile"] is None- assert result["review_priority"] is None- assert result["classification"] is None+ # The tercile and its label repeat the percentile, so they wait for scales.+ assert "review_priority" not in result+ assert "classification" not in resultassert diagnostics["fallback_band"] in {"low", "moderate", "high"}assert diagnostics["baseline_sample_size"] == 0# The per-field dictionary is identical on every call, so it is opt-in.@@ -97,6 +95,8 @@ async def test_get_change_risk_honors_riskignore_and_request_filters(tmp_path, mscales = {scale["field"]: scale for scale in expanded["risk_scales"]}assert scales["score"]["authoritative"] is Falseassert scales["risk_percentile"]["authoritative"] is True+ assert scales["classification"]["authoritative"] is False+ assert expanded["review_priority"] is Noneassert scales["features.la|features.ld"]["unit"] == "lines"assert scales["drivers[].contribution"]["unit"] == "logit_points"# Live-git responses carry a _meta envelope flagged as index-independent.@@ -127,7 +127,7 @@ async def test_get_change_risk_labels_the_priority_tercile_as_diff_size(tmp_pathmonkeypatch.setattr(module, "_resolve_repo_context", _context)monkeypatch.setattr(module, "change_risk_payload", _ranked)- result = await module.get_change_risk("HEAD", baseline=0)+ result = await module.get_change_risk("HEAD", baseline=0, include=["scales"])assert result["review_priority"] == "high"assert result["classification"] == "Above-typical diff size"@@ -542,10 +542,12 @@ async def test_get_change_risk_drops_request_echoes_and_empty_fields(tmp_path, massert "working_tree" not in resultassert "is_fix" not in resultassert "density" not in result["fix_history"]- assert "percentile" in result["fix_history"]+ # One percentile on the default response: the size rank, not the fix rank.+ assert "percentile" not in result["fix_history"]diagnostics = await module.get_change_risk("HEAD", baseline=0, include=["diagnostics"])assert "density" in diagnostics["fix_history"]+ assert "percentile" in diagnostics["fix_history"]@pytest.mark.asynciodiff --git a/tests/unit/server/mcp/test_independent_changes_block.py b/tests/unit/server/mcp/test_independent_changes_block.pyindex 5220edbc9..4e42dc148 100644--- a/tests/unit/server/mcp/test_independent_changes_block.py+++ b/tests/unit/server/mcp/test_independent_changes_block.py@@ -227,9 +227,9 @@ async def test_get_change_risk_carries_the_split_end_to_end(tmp_path, monkeypatcdef test_the_diff_shape_line_ranks_without_naming_a_raw_score():- assert "42%" in _diff_shape_sentence({"risk_percentile": 42.0}, {})- assert "42%" in _diff_shape_sentence({"risk_percentile": 42.9}, {})- assert "bigger than 99%" in _diff_shape_sentence({"risk_percentile": 99.5}, {})- assert "bigger than 99%" in _diff_shape_sentence({"risk_percentile": 100.0}, {})+ line = _diff_shape_sentence({"risk_percentile": 42.0}, {})+ assert line.startswith("Size and spread: 42nd percentile of recent commits")+ assert "not a bug predictor" in line and "cannot rank danger" in line+ assert "43rd percentile" in _diff_shape_sentence({"risk_percentile": 42.9}, {})assert "unranked" in _diff_shape_sentence({"risk_percentile": None}, {})assert "diagnostics" in _diff_shape_sentence({"risk_percentile": 42.0}, {"score": 3.0})diff --git a/tests/unit/server/test_risk_range.py b/tests/unit/server/test_risk_range.pyindex 94a114e94..44de01a8b 100644--- a/tests/unit/server/test_risk_range.py+++ b/tests/unit/server/test_risk_range.py@@ -82,7 +82,7 @@ async def test_risk_range_happy_path(client: AsyncClient, git_repo: Path, tmp_paassert data["review_priority"] is Noneassert data["classification"] is Noneassert data["fallback_band"] in {"low", "moderate", "high"}- assert data["risk_authority"]["primary_fields"] == ["risk_percentile", "classification"]+ assert data["risk_authority"]["primary_fields"] == ["risk_percentile"]assert data["risk_authority"]["score_role"] == "supporting_diff_shape_signal"assert "risk_scales" not in datadiff --git a/website/cli-reference.md b/website/cli-reference.mdindex 1c57f0abe..24633e1ee 100644--- a/website/cli-reference.md+++ b/website/cli-reference.md@@ -539,8 +539,9 @@ repowise health --trend## `risk`-Rank a *change* (commit or `base..head` range) for review. The repo-relative-percentile/classification is authoritative; the supporting 0-10 score measures+Rank a *change* (commit or `base..head` range) by size and spread among the+repo's recent commits, then report the bug-fix record of the files it touches.+The percentile ranks diff size, not danger; the supporting 0-10 score measuresdiff size and spread and is not a probability. No LLM.```bashdiff --git a/website/mcp-server.md b/website/mcp-server.mdindex 42e40cc84..fde7055bc 100644--- a/website/mcp-server.md+++ b/website/mcp-server.md@@ -371,18 +371,17 @@ refresh.- `exclude_patterns` (optional) — gitignore-style paths; combined with root `.riskignore`- `baseline` (optional, int) — recent commits for percentile ranking (default `200`)-**Returns:** `risk_authority` names `risk_percentile` and `classification` as-the benchmarked, population-relative authority for live change review.-`fix_history` reports the recency-weighted bug-fix record of the-files touched, which is what distinguishes a small dangerous change from a large-boring one. `diff_shape` is one sentence on size and spread, beside repo-relative-`risk_percentile` / `review_priority` / `classification`, plus+**Returns:** `risk_percentile` ranks the change among recent commits by diff+size and spread; it is not a bug predictor. `fix_history` reports the+recency-weighted bug-fix record of the files touched (manifests and lockfiles+excluded), which is what distinguishes a small dangerous change from a large+boring one. `diff_shape` is one sentence on size and spread and its limits, plus`impacted_tests` when a per-test coverage map is ingested(`repowise coverage add`). The raw 0-10 `score` and its absolute`fallback_band` sit behind `include=["diagnostics"]`: the score ranks 0.99against lines added, so the percentile already carries the ranking.-`include=["scales"]` supplies the kind, units, range, calibration, authority-and shared thresholds for each value.+`include=["scales"]` adds the `review_priority` / `classification` tercile and+the kind, units, range and shared thresholds for each value.**When to use:** Before merging a commit or PR range, or on work you have notcommitted yet.