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): clarify public risk scale semantics (#1914)
Raghav Chamadiyac314f5b003ce
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 4ad85e21b..9bcef5e52 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -451,7 +451,21 @@ Modification risk assessment for files or a set of changed files.> **Opt-in blocks.** `impact_surface` and `direct_risks` are pagerank floats an agent cannot rank; `change_magnitude`, `risk_type` and `change_pattern` restate numbers printed beside them. All five are computed regardless and feed `risk_summary`; `include` only decides whether they ship. `global_hotspots` accompanies a multi-target call only, being ambient orientation that a single named file does not need; it ranks by fix history the same way `defect_profile` does.-> **Scales.** `overall_risk_score` (in `pr_blast_radius`, with an `overall_risk_score_measures` note beside it) reads where the change lands. It is not comparable to `get_change_risk.score`, which is also 0-10 and reads the shape of the diff. Ratios derived from ownership or percentile columns are 0-1 (`hotspot_score`, `owner_pct`, `recent_owner_pct`); coverage and gap fields are 0-100 (`coverage_pct`, `branch_coverage_pct`, `share_of_repo_gap_pct`, `change_entropy_pct`, `churn_percentile`). The `_pct` suffix alone does not tell you which — check this table. Every emitted float is rounded to 4 significant digits.+> **Scales.** Every response carries the facts that stop a misreading: unit,+> range, calibration status, and whether the value is authoritative. The+> per-field dictionary behind them never varies between calls, so it ships only+> with `include=["scales"]` - ask for it once per session, not per call. That+> dictionary describes indexed file values: `hotspot_score`, `owner_pct`, and+> `recent_owner_pct` are 0-1 ratios, while `risk_type` is an+> uncalibrated category. In PR mode, `structural_impact_score` is a deterministic,+> uncalibrated 0-10 structural-exposure heuristic; `localized` is below 4,+> `moderate` is 4 to below 7, and `broad` is 7 or above. It is not a runtime-+> breakage probability and is not authoritative for live change review.+> Deprecated `overall_risk_score` remains an exact alias, with migration metadata.+> Direct rows expose raw, unbounded `structural_score` values in+> pagerank-weighted-hotspot units. These are not comparable to+> `get_change_risk.score`. Coverage and gap fields are percentages from 0-100.+> Every emitted float is rounded to 4 significant digits.When `changed_files` is passed, the exact serialized response starts with a `directive` block. Its core lists are the local blast radius: `may_break` (production files in structural reverse-import reach of the diff, candidates for review rather than proven breakage), `may_break_tests` (test files reached the same way, kept separate so a burst of tests doesn't crowd production impact out of the capped list), `missing_cochanges` (historical co-changers absent from the diff), compatibility `missing_tests`, and additive typed `test_recommendations`. Every recommendation retains `basis`, all retained `bases`, repository identity, source files, and evidence: `measured` means the per-test coverage map found the test; `inferred` means structural reachability found a candidate and is not coverage proof. `tests_to_run` preserves the older measured-first/fallback id projection and `tests_to_run_basis` remains `measured`, `inferred`, or `none`; `files_without_measured_tests` carries the narrower typed coverage claim. Matching total/emitted/truncated/omitted fields describe each exact pre-cap population. `coverage_analysis`, `test_inference_analysis`, and `test_analysis` distinguish available-empty evidence from unavailable, stale, partial, or degraded analysis; unavailable coverage with `tests_to_run: []` never means that no tests are needed. The full typed population is shared with the REST blast-radius response, while any budget-omitted directive rows are recoverable through the response omission marker. In workspace mode the directive also carries the cross-repo fallout of the changed repo:@@ -498,14 +512,17 @@ shape of the live diff and needs no index refresh.| `exclude_patterns` | list[string] | No | Gitignore-style paths to omit; combined with root `.riskignore` rules || `baseline` | int | No | Recent commits to sample for percentile ranking (default `200`; `0` disables every percentile, `risk_percentile` and `fix_history.percentile` alike) |-**Returns:** `fix_history` first — the recency-weighted bug-fix record of the+**Returns:** `risk_authority` identifies `risk_percentile` and `classification`+as the benchmarked, population-relative authority for live change review.+`fix_history` reports the recency-weighted bug-fix record of thefiles the change touches, with `files` naming where the pressure sits and`percentile` ranking it against the same measure over the repo's own recentcommits. 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.-`score` measures diff size and spread, not where the change lands — see+`score` is a supporting, offline-calibrated 0-10 model output that measures diff+size and spread, not a probability and not where the change lands — see`score_measures` — and `score_unit` names the unit it is calibrated on (a singlecommit, so a PR-sized range reads high by construction). `risk_percentile`,`review_priority` and `classification` rank that same diff shape against recent@@ -513,7 +530,11 @@ commits. `fallback_band` carries the absolute band and appears only when nobaseline was available. `working_tree` says whether uncommitted work was thesubject. `baseline_sample_size` reports how many filtered commits informed thepercentile; `features`, `drivers`, and combined `exclude_patterns` make the-result auditable.+result auditable. `risk_authority` always names the field to act on;+`include=["scales"]` adds each field's kind, unit, range, calibration,+authority, and shared thresholds. When a baseline is unavailable,+`fallback_band` is the absolute per-commit classification; it is distinct from+population-relative percentile behavior.It also returns `impacted_tests`, whose `tests_to_run` names the tests theper-test coverage map proves execute the change's changed *lines* (line-precise,@@ -872,7 +893,7 @@ list_repos()#### `get_blast_radius`-Cross-repo downstream impact: if you change this service, what breaks across the other repos?+Cross-repo structural and historical reach from a changed service.| Parameter | Type | Required | Description ||-----------|------|----------|-------------|@@ -880,9 +901,16 @@ Cross-repo downstream impact: if you change this service, what breaks across the| `max_depth` | int | No | Reachability depth (1-8, default 3) || `include_behavioral` | bool | No | Include co-change (behavioral) edges (default `true`) |-**Returns:** The impacted services ranked by impact `score`, each with `distance` (hops), `structural` (a real dependency vs co-change only), and the edge kinds that carried the impact; plus `impacted_repos`, `structural_count` / `behavioral_count`, `total_impacted`, and any `unresolved_targets`.+**Returns:** The impacted services ranked by uncalibrated `score` (0-1 relative+path weight, not a breakage probability), each with `distance` (hops),+`structural` (a real dependency vs co-change only), and the edge kinds that+carried the impact; plus `impact_score_semantics`, `impacted_repos`,+`structural_count` / `behavioral_count`, `total_impacted`, and unresolved targets.-**When to use:** Before changing a high-fan-out provider, see who consumes it across repo boundaries. Structural impact ("will break") outweighs behavioral co-change ("may drift"). Reads the same system graph the [Live System Map](../scale/WORKSPACES.md#live-system-map) renders.+**When to use:** Before changing a high-fan-out provider, see who structurally+consumes it across repo boundaries. Structural reach outweighs historical+co-change in ranking, but neither is a runtime-breakage claim. Reads the same+system graph the [Live System Map](../scale/WORKSPACES.md#live-system-map) renders.```get_blast_radius(targets=["backend"])diff --git a/docs/layers/CHANGE_RISK.md b/docs/layers/CHANGE_RISK.mdindex 6687454b6..305607ce6 100644--- a/docs/layers/CHANGE_RISK.md+++ b/docs/layers/CHANGE_RISK.md@@ -5,10 +5,11 @@ bug-fix history of the files it touches, and the shape of its diff. It is ajust-in-time / pre-merge signal, complementary to `repowise health`, whichscores files rather than changes.-**Read `fix_history` first, not `score`.** The 0–10 score measures how big and-spread out a change is. It does not measure where the change lands, and the two-are not the same question — see [What the score does and does not-buy](#what-the-score-does-and-does-not-buy).+**Lead with `risk_percentile` and `classification`.** They are the benchmarked,+population-relative authority for live change review. `fix_history` is+complementary evidence about where the change lands. The supporting 0–10 score+measures how big and spread out a change is; it is not a probability. See+[What the score does and does not buy](#what-the-score-does-and-does-not-buy).```bashrepowise risk # score uncommitted work, else HEAD@@ -164,14 +165,19 @@ lands at 0.46–0.57 AUC — which is a fact about the labels, not about thefeature. So the model constants are unchanged and the score is reported as whatit demonstrably is.-`score_measures` states this in the payload. Read the result in this order:+`risk_authority` and `score_measures` state this in every payload;+`include=["scales"]` adds the per-field dictionary.+Read the result in this order:-- **`fix_history`**: where the change lands. The signal to triage on.- **Review priority** / **classification** / **percentile**: where this change's- *diff shape* sits in the repo's own distribution. Useful for "is this a big- one for us", not for "is this a dangerous one".-- **`score`** (0–10): diff size and spread, corpus-anchored to a single commit.-- **`fallback_band`**: the absolute `low` / `moderate` / `high` band. Present+ *diff shape* sits in the repo's own distribution. This is the authoritative+ population-relative review signal.+- **`fix_history`**: uncalibrated historical evidence about where the change+ lands, reported separately rather than folded into a probability.+- **`score`** (0–10 normalized points): supporting diff size and spread,+ offline-calibrated and corpus-anchored to a single commit.+- **`fallback_band`**: the heuristic-thresholded absolute `low` / `moderate` /+ `high` model-score band. Present*only* when there was no baseline to rank against (a shallow repo, or`--baseline 0`), which is why it is not a peer of the review priority.@@ -248,6 +254,65 @@ free of new dependencies. Recalibrate via`repowise-bench/health-defect/jit_calibration.py`; the constants live in`packages/core/src/repowise/core/analysis/change_risk/model.py`.+## PR structural-impact scale (`get_risk`)++PR-mode `get_risk` answers a different question. Its+`structural_impact_score` is a deterministic, uncalibrated structural-exposure+heuristic in normalized points from 0 to 10. It combines the mean and maximum+of `pagerank * (1 + temporal_hotspot)` across changed files, maps that component+to at most 8 points with `8 * (1 - exp(-10 * combined))`, then adds at most 2+points for `min(transitive_dependents / 20, 1)`. Bands are `localized` below 4,+`moderate` from 4 to below 7, and `broad` from 7. It is not a probability and is+not authoritative for live change review. Historical co-change evidence is+reported separately and never enters this structural score.++`overall_risk_score` remains an exact deprecated alias so older clients keep+the same value and unit. `overall_risk_score_compatibility` names the migration+to `structural_impact_score`; the two fields cannot contradict.++The deterministic fixture corpus records the retained scale's distribution:++| Control | Score | Band |+| --- | ---: | --- |+| documentation / low signal | 0.01 | localized |+| small ordinary source | 0.34 | localized |+| historical fixes, limited reach | 0.34 | localized |+| co-change only | 0.08 | localized |+| moderate multi-file | 4.27 | moderate |+| structurally broad, little history | 7.34 | broad |+| genuinely broad high control | 9.91 | broad |++The numeric formula was retained, so the before-and-after numeric distributions+are identical; the correction changes names, units, authority, and labels. No+fixture saturates at 10, ordinary controls remain below the moderate threshold,+and all three bands are occupied. The corpus lives in+`tests/fixtures/risk_scale_corpus.json`.++## Public scale inventory++| Public value | Producer and evidence | Unit / range | Calibration and authority |+| --- | --- | --- | --- |+| `get_change_risk.score` / REST `score` / stored `change_risk_score` | Offline-fitted logistic model over live diff size, spread, entropy, and author experience; deterministic at runtime | normalized points, 0-10; calibrated at single-commit granularity | Benchmarked on 4,102 commits across 7 repositories; supporting signal, not a probability or review authority |+| `risk_percentile` | Mid-rank of the same score among filtered recent commits | percentile rank, 0-100 | Population-relative benchmark; authoritative with `classification` for live change review |+| `review_priority` / `classification` | Shared percentile terciles at 33.33 and 66.67 | category | Authoritative population-relative label |+| `fallback_band` | Shared score thresholds at 4 and 7, emitted only without a usable baseline | category | Heuristic thresholds on the benchmarked model score; absolute fallback, not population-relative |+| `fix_history.density` | Churn-weighted, recency-decayed prior bug fixes on touched files | recency-weighted prior fixes, unbounded | Uncalibrated historical heuristic; separate evidence, never folded into a probability |+| `get_risk` `hotspot_score` | Repository-relative churn percentile from the index | ratio, 0-1 | Uncalibrated normalized component |+| `get_risk` `health_score` | Indexed code-health model | health points, 0-10; higher is healthier | Benchmarked file-health signal, not interchangeable with change-risk points |+| `structural_impact_score` | PR structural formula above | normalized points, 0-10 | Deterministic and uncalibrated; not authoritative. `overall_risk_score` is an exact deprecated alias |+| `direct_risks[].structural_score` | `pagerank * (1 + temporal_hotspot)` | raw pagerank-weighted-hotspot value, unbounded | Uncalibrated within-change structural weight. `risk_score` is an exact deprecated alias |+| `cochange_warnings[].score` | Number of historical commits in which the pair co-changed | raw commit count, 0+ | Historical evidence only; cannot become structural or runtime-breakage evidence |+| workspace `impacted[].score` | Strongest path product of edge confidence, edge-kind weight, and `0.6` per hop | relative path weight, 0-1 | Deterministic, uncalibrated ranking heuristic; not a probability or change-review authority |+| dashboard hotspot triage index | `40% * churn percentile + 35% * bus-factor tier + 25% * bounded temporal activity` | heuristic points, 0-100 | Client-side, uncalibrated orientation only; labelled adjacent to the chart |++Machine-readable `risk_authority`, `structural_impact_scale`,+`overall_risk_score_compatibility`, and `impact_score_semantics` carry these+definitions on every payload. They ship the guard tier - unit, range,+calibration status, authority - by default. The reference tier (fitting corpus,+formula, component breakdown, and the full `risk_scales` dictionary) is+identical on every call, so MCP returns it only for `include=["scales"]`; the+CLI `--json` output and this table carry it unconditionally.+## Cross-repo change risk (workspace mode)> **Note:** This section describes `get_risk` in PR mode (`changed_files`). `get_change_risk` is@@ -257,9 +322,9 @@ In a workspace, a change rarely stops at the repo boundary. When `get_risk` iscalled in PR mode (`changed_files`), its `directive` block gains two cross-repofields derived from the [system graph](../scale/WORKSPACES.md#system-graph):-- `will_break_consumers`: services in *other* repos that structurally depend on- the changed repo (a contract or package import). These are the consumers most- likely to break.+- `will_break_consumers`: deprecated compatibility name for services in *other*+ repos that structurally depend on the changed repo (a contract or package+ import). This is structural reach for review, not a runtime-breakage claim.- `missing_cross_repo_cochanges`: services in other repos that historicallyco-change with the changed repo but aren't in the diff. Correlation, not acall, so they read as "may drift," not "will break."diff --git a/docs/layers/GRAPH.md b/docs/layers/GRAPH.mdindex a33521692..92d962cb7 100644--- a/docs/layers/GRAPH.md+++ b/docs/layers/GRAPH.md@@ -452,7 +452,7 @@ graph, which is why the graph is reproducible and why indexing needs no API key.- [architecture/language-support.md](../architecture/language-support.md) · call resolution internals and the contributor recipe- [architecture/graph-algorithms.md](../architecture/graph-algorithms.md) · PageRank, Leiden, betweenness and SCC in detail- [DEAD_CODE.md](DEAD_CODE.md) · how reachability becomes a confidence-tiered report-- [CHANGE_RISK.md](CHANGE_RISK.md) · how the graph feeds a per-change risk score+- [CHANGE_RISK.md](CHANGE_RISK.md) · how live diff-shape review and structural PR impact remain distinct- [reference/COMPUTED_GLOSSARY.md](../reference/COMPUTED_GLOSSARY.md) · every derived metric, defined- [BENCHMARKS.md §7](../BENCHMARKS.md#7-edge-precision) and [§8](../BENCHMARKS.md#8-the-same-question-against-an-answer-key-we-do-not-control) · the precision numbers on this page, with their sample sizes and intervals- [repowise-bench/graph](https://github.com/repowise-dev/repowise-bench/tree/master/graph) · the harnesses, the five arms, the graded rows and the pre-registrations behind all of itdiff --git a/docs/layers/INTELLIGENCE_LAYERS.md b/docs/layers/INTELLIGENCE_LAYERS.mdindex 2c071d46c..004968ad8 100644--- a/docs/layers/INTELLIGENCE_LAYERS.md+++ b/docs/layers/INTELLIGENCE_LAYERS.md@@ -227,11 +227,13 @@ Full guide, the calibration story and the head-to-head against CodeScene:## Change Risk-A calibrated 0–10 defect-risk score for **a whole commit or `base..head`-range**, computed from the diff's shape against the live checkout, no index-lookup, no model call. Distinct from `get_risk()`, which scores indexed files by-path. Lead with `risk_percentile`, which ranks the change against sampled recent-commits in the same repo.+A deterministic live-diff assessment for **a whole commit or `base..head`+range**, computed against the live checkout with no index lookup or model call.+Lead with the benchmarked `risk_percentile` and `classification`, which rank the+diff-shape score against sampled recent commits in the same repo. The supporting+0–10 score is calibrated at single-commit granularity and is not a probability.+Distinct from `get_risk()`, whose PR-blast value is an uncalibrated structural+heuristic over indexed files.```bashrepowise risk HEADdiff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.mdindex 54f08f722..0999bed68 100644--- a/docs/layers/TEST_INTELLIGENCE.md+++ b/docs/layers/TEST_INTELLIGENCE.md@@ -435,6 +435,6 @@ Full reference: [CLI_REFERENCE.md](../reference/CLI_REFERENCE.md#repowise-covera## See also- [CODE_HEALTH.md](CODE_HEALTH.md): the coverage markers and how they deduct from the score.-- [CHANGE_RISK.md](CHANGE_RISK.md): the risk score that `impacted_tests` rides alongside.+- [CHANGE_RISK.md](CHANGE_RISK.md): the authoritative review percentile and supporting diff-shape score that `impacted_tests` rides alongside.- [MCP_TOOLS.md](../agent/MCP_TOOLS.md#get_change_risk): full parameter and response reference.- [CONFIG.md](../reference/CONFIG.md): the `coverage:` block.diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex ce417928e..92334a93d 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -749,7 +749,7 @@ to the model's baseline commit, not this repo.| `--path` | Path to the git repository (default: current directory) || `--ext` | Comma-separated file suffixes to count (e.g. `.py` or `.ts,.tsx`) || `--exclude` / `-x` | Gitignore-style path pattern to omit. Repeatable; filters both the change and baseline. Root `.riskignore` patterns also apply. |-| `--baseline` | Recent commits to sample for the repo-relative percentile (default 200; `0` shows only the absolute calibrated band) |+| `--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 || `--format` | Output format: `table` (default) or `json` |diff --git a/docs/reference/COMPUTED_GLOSSARY.md b/docs/reference/COMPUTED_GLOSSARY.mdindex f52abd4e7..cabe2ccfd 100644--- a/docs/reference/COMPUTED_GLOSSARY.md+++ b/docs/reference/COMPUTED_GLOSSARY.md@@ -232,8 +232,8 @@ workspace overlays, MCP responses, and CLI output.| Term | Definition | Computed by | Example || --- | --- | --- | --- |-| File risk score | Pagerank centrality multiplied by `1 + temporal_hotspot_score`. | `PRBlastRadiusAnalyzer._score_file()` | `0.018 * (1 + 2.4) = 0.0612` |-| Overall PR risk score | 0 to 10 composite using average direct risk, max direct risk, and transitive breadth. | `_compute_overall_risk()` | `7.25` |+| Direct structural weight | Raw, unbounded PageRank centrality multiplied by `1 + temporal_hotspot_score`; used only within the PR structural heuristic. Deprecated `risk_score` is an exact alias. | `PRBlastRadiusAnalyzer._score_file()` | `0.018 * (1 + 0.4) = 0.0252` |+| PR structural-impact score | Deterministic, uncalibrated 0-10 normalized-point heuristic from mean/max direct structural weight (up to 8 points) plus transitive-dependent breadth (up to 2). Not a probability or live-change authority. Deprecated `overall_risk_score` is an exact alias. | `_compute_overall_risk()` | `{structural_impact_score: 7.25, structural_impact_band: "broad"}` || Transitive affected file | Importer reached by reverse BFS from changed files. | `_transitive_affected()` | `{path: "src/api.py", depth: 2}` || Co-change warning | Historical co-change partner missing from a PR/change set. | `_cochange_warnings()` | `{changed: "src/a.py", missing_partner: "src/b.py", score: 4.2}` || Recommended reviewer | Owner aggregate over changed and affected files. | `_recommend_reviewers()` | `{email: "[email protected]", files: 7, ownership_pct: 0.63}` |@@ -376,7 +376,7 @@ workspace overlays, MCP responses, and CLI output.| `get_dependency_path` | Dependency-path or bridge context between files/symbols. | `{path: ["src/a.py", "src/b.py"]}` || `get_symbol` | Exact symbol metadata and source slice. | `{name: "create_app", signature: "def create_app(...)"}` || `get_execution_flows` | Entry-point traces through call edges. | `{flows: [{entry_point, trace, crosses_community}]}` |-| Blast radius API | Direct risks, transitive affected files, co-change warnings, reviewers, test gaps, overall score. | `{overall_risk_score: 7.25}` |+| Blast radius API | Direct structural weights, transitive affected files, historical co-change warnings, reviewers, test gaps, and an uncalibrated 0-10 structural-impact heuristic. Deprecated `overall_risk_score` is an exact alias. | `{structural_impact_score: 7.25, structural_impact_band: "broad", overall_risk_score: 7.25}` || Knowledge map API | Top owners, knowledge silos, onboarding targets. | `{top_owners: [...], knowledge_silos: [...]}` || Cost summary API | Grouped costs and totals. | `{groups: [...], total_cost_usd: 3.21}` || Provider API | Available provider/model configuration. | `{providers: [...], active_provider: "gemini"}` |diff --git a/docs/start/DASHBOARD.md b/docs/start/DASHBOARD.mdindex 25d5fbbf4..004270469 100644--- a/docs/start/DASHBOARD.md+++ b/docs/start/DASHBOARD.md@@ -147,7 +147,7 @@ zoomed on one node. The older `/c4` and `/zoom` URLs redirect here.`/repos/<id>/code-health`-**Answers:** which files are likely to break next, and why?+**Answers:** which files have the strongest defect indicators, and why?<img src="../../.github/assets/dashboard/code-health.png" alt="Repowise code health: the three co-equal pillars, the alert/warning/healthy band distribution, KPI cards and the code health map" width="100%" />@@ -230,9 +230,10 @@ anywhere.`/repos/<id>/commits`-**Answers:** what has been happening in this repo, and how risky was it?+**Answers:** what has been happening in this repo, and which changes deserve review?-The commit table with a per-commit risk score, a risk distribution, a+The commit table led by repo-relative review priority, a supporting diff-shape+score distribution, acode-evolution chart, commit-category breakdowns, and AI-agent provenancebadges plus their trend over time where the commits carry agent trailers. Therisk model is documented indiff --git a/docs/start/USER_GUIDE.md b/docs/start/USER_GUIDE.mdindex 12bc0fcc1..78fb3005d 100644--- a/docs/start/USER_GUIDE.md+++ b/docs/start/USER_GUIDE.md@@ -164,7 +164,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` | Defect risk for a commit or range, scored 0-10. |+| `repowise risk main..HEAD` | Repo-relative review percentile/classification plus a supporting 0-10 diff-shape score. || `repowise dead-code` | What nothing references any more, by confidence tier. || `repowise decision list` | Architectural decisions, their evidence and status. || `repowise impacted-tests` | Only the tests a diff actually exercises. |@@ -371,14 +371,14 @@ git pull && repowise update # C: manual, when you prefer control### Before you open a pull request```bash-repowise risk main..HEAD # how risky does this change look, and why+repowise risk main..HEAD # repo-relative review priority and supporting evidencerepowise impacted-tests # the tests this diff actually exercisesrepowise health --trend # did anything you touched get worse```-`repowise risk` in PR mode also tells you what a change is likely to break, which-companion files usually move with the ones you touched, and where tests are-missing.+`get_risk` in PR mode also shows structural dependency reach (review candidates,+not proven runtime breakage), companion files that historically move with the+ones you touched, and where test evidence is missing.### Reviewing someone else's pull request@@ -407,7 +407,7 @@ instead of them interrupting someone.```bashrepowise init --no-prose -y # free, no keys in CI, no questions-repowise risk "$BASE_SHA..$HEAD_SHA" # gate or annotate on risk+repowise risk "$BASE_SHA..$HEAD_SHA" # gate or annotate on review priorityrepowise export --format markdown --output ./docs/wiki/ # static hosting```diff --git a/examples/risk/README.md b/examples/risk/README.mdindex ea984511f..78f71c874 100644--- a/examples/risk/README.md+++ b/examples/risk/README.md@@ -1,6 +1,6 @@# Change-Risk Example-Score the defect risk of a commit or `base..head` range with+Rank a commit or `base..head` range against recent repository changes with`repowise risk`. No LLM key required — pure git + calibrated signals.Works without `repowise init` (index is optional).@@ -51,7 +51,7 @@ repowise risk main..HEAD --format json| Step | Expected ||------|----------|-| `repowise risk` | Table with score / percentile / review priority for HEAD |+| `repowise risk` | Table led by percentile/review priority, 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/risk.ts b/packages/api-client/src/risk.tsindex cf504f6db..b39fe9f35 100644--- a/packages/api-client/src/risk.ts+++ b/packages/api-client/src/risk.ts@@ -4,6 +4,7 @@*/import { apiGet } from "./client";+import type { RiskAuthority } from "@repowise-dev/types/risk-semantics";import type { RiskDriverResponse } from "./types/git";export interface RiskRangeParams {@@ -43,8 +44,10 @@ export interface FixHistory {export interface RiskRangeResponse {base: string;head: string;- /** Where the change lands. Read before `score`. */+ /** Separate historical evidence about where the change lands. */fix_history: FixHistory;+ /** Percentile/classification authority plus explicit absolute fallback. */+ risk_authority: RiskAuthority;score: number;/** What `score` measures: diff size and spread, not where the change lands. */score_measures: string;@@ -60,7 +63,7 @@ export interface RiskRangeResponse {drivers: RiskDriverResponse[];}-/** Scores the aggregate diff between two revisions (0-10, with drivers). */+/** Assesses a live diff; lead with its repo-relative percentile/classification. */export async function getRiskRange(repoId: string,params: RiskRangeParams,diff --git a/packages/api-client/src/types/git.ts b/packages/api-client/src/types/git.tsindex 3760c2a90..a600ef4c8 100644--- a/packages/api-client/src/types/git.ts+++ b/packages/api-client/src/types/git.ts@@ -113,9 +113,13 @@ export interface CommitResponse {subsystems_changed: number;entropy: number;is_fix: boolean;+ /** Supporting 0–10 calibrated diff-size/spread score; not a probability. */change_risk_score: number | null;+ /** Absolute per-commit fallback band retained for compatibility. */change_risk_level: ReviewPriority | null;+ /** Repo-relative percentile rank, 0–100. */risk_percentile: number;+ /** Authoritative repo-relative review-priority tercile. */review_priority: ReviewPriority;/** Label of the dominant risk driver; null when never risk-scored. */top_driver?: string | null;@@ -185,7 +189,7 @@ export interface CommitEvolution {last_commit_at: string | null;}-/** One bin of the repo's raw change-risk score distribution. */+/** One bin of the repo's supporting 0-10 diff-shape score distribution. */export interface RiskHistogramBucket {/** Bin lower bound on the 0-10 raw score axis (inclusive). */start: number;diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-impacted-tests.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-impacted-tests.mdindex d13f66532..0810a1732 100644--- a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-impacted-tests.md+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-impacted-tests.md@@ -44,5 +44,5 @@ repowise impacted-tests main..HEAD --format list | xargs pytestguess). Report them as candidates. Only `via: coverage` proves a testexecuted the change.- A file none of those can speak to is "unknown, run the full suite".-- For a whole-change defect-risk score, use `/prompts:repowise-risk`. For per-file+- For a whole-change repo-relative review priority, use `/prompts:repowise-risk`. For per-fileblast radius / `tests_to_run`, use the `get_risk` MCP tool.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 96524bb94..22bd9902b 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@@ -1,16 +1,16 @@----description: Score the defect risk of a change — a commit or a base..head range — as a single 0–10 with drivers.+description: Rank a live change for review using a repo-relative percentile and an auditable supporting diff-shape score.---# Repowise Risk-Score a *change* (not a file) for defect risk. The response leads with+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 changetouches, which of them carry it, and where that sits among the repo's own-recent commits. The 0–10 score sits beside it and measures diff size and-spread (named in `score_measures`) rather than danger, so read the fix history-first. Pure git + learned constants: no LLM, no network. A natural pre-merge /-PR gate.+recent commits. The supporting 0–10 score measures diff size and spread (named+in `score_measures`) rather than danger and is not a probability. Pure git ++learned constants: no LLM, no network. A natural pre-merge / PR gate.## Steps@@ -35,7 +35,7 @@ Useful flags:## How this differs from the other risk views-- This command = the **whole change** as one number (defect-risk gate).-- For **per-file** blast radius (what breaks, missing co-changes, missing tests),+- This command = the **whole change** ranked against recent repository history.+- For **per-file** structural reach, missing co-changes, and missing tests,use the `get_risk` MCP tool / the `change-review` skill.- For **per-file health** scores, use `/prompts:repowise-health`.diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-security.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-security.mdindex aa4e19eaa..6d7a842e5 100644--- a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-security.md+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-security.md@@ -48,4 +48,4 @@ repowise security scan --history --all-patterns --output json(`hardcoded_password` / `hardcoded_secret`) to avoid noise. Pass`--all-patterns` for code-smell patterns (`eval`, `os.system`, weak hashes, …).- Never invent findings. If the scan stores zero findings, say so plainly.-- For change defect risk (not secret scanning), use `/prompts:repowise-risk`.+- For live-change review priority (not secret scanning), use `/prompts:repowise-risk`.diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.pyindex 7f9fed8f2..3fa5da5dc 100644--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py@@ -4,7 +4,8 @@ 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 0-10 risk with an attributable breakdown. Runs+familiarity — and prints a benchmarked review priority plus a supporting 0-10+diff-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).@@ -39,9 +40,9 @@ from repowise.core.analysis.change_risk import ()_PRIORITY_LEAD = {- "low": "Lower risk than a typical commit in this repo",- "moderate": "About as risky as a typical commit in this repo",- "high": "Riskier than most commits in this repo",+ "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",}@@ -88,7 +89,7 @@ def project_risk(payload: dict) -> dict:out["targets"] = {name: _project_target(card) for name, card in (payload.get("targets") or {}).items()}- for key in ("pr_blast_radius", "global_hotspots", "omission_marker"):+ for key in ("risk_scales", "pr_blast_radius", "global_hotspots", "omission_marker"):if payload.get(key):out[key] = payload[key]note = _ta.index_note(payload)@@ -411,7 +412,7 @@ def _ordinal(n: int) -> str:default=200,type=click.IntRange(min=0),help="Sample this many recent commits to rank the change within the repo "- "(0 disables; shows only the absolute calibrated band).",+ "(0 disables; shows only the absolute per-commit model-score band).",)@click.option("--exclude",@@ -436,7 +437,7 @@ def _ordinal(n: int) -> str:multiple=True,metavar="PATH",help="With --target: PR mode. The response leads with a directive naming "- "what may break, which co-changes and tests are missing, and what to run.",+ "structural review candidates, missing co-changes/tests, and what to run.",)@format_option()@full_option()@@ -451,7 +452,7 @@ def risk_command(fmt: str,full: bool,) -> None:- """Score the defect risk of a change, or of touching some files.+ """Assess a change's review priority, or 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@@ -500,11 +501,26 @@ def risk_command()if fmt == "json":- click.echo(json.dumps(change_risk_payload(result), indent=2))+ click.echo(json.dumps(change_risk_payload(result, scales=True), indent=2))return- # The headline is the fix record, not the score: the score restates diff- # size, so leading with it put the least informative number first.+ # Lead with the benchmarked population-relative authority. Without a usable+ # baseline, label the offline absolute band explicitly as the fallback.+ if percentile is not None and priority is not None:+ console.print(+ f"\n[bold]Benchmarked review priority[/bold]: "+ f"{review_priority_classification(priority)} · "+ f"{_ordinal(round(percentile))} percentile of recent commits by size and spread"+ )+ console.print(f" [dim]{_PRIORITY_LEAD[priority]}.[/dim]")+ else:+ 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)"+ )++ # Fix history remains separate evidence about where the change lands.if not result.fix_history_available:console.print(f"\n[bold]Change risk[/bold] for [cyan]{features.ref}[/cyan]: "@@ -552,22 +568,6 @@ def risk_command("one from a year earlier counts a half.[/dim]")- # Diff shape second, and labelled for what it measures rather than as a- # verdict. The absolute band appears only when no percentile outranks it.- if percentile is not None and priority is not None:- console.print(- f"\n[bold]Diff shape[/bold]: {review_priority_classification(priority)} · "- f"{_ordinal(round(percentile))} percentile of recent commits by size and spread"- )- console.print(f" [dim]{_PRIORITY_LEAD[priority]}.[/dim]")- else:- # No usable baseline (shallow repo, --baseline 0): fall back to the- # absolute calibrated band, labelled honestly as such.- color = {"high": "red", "moderate": "yellow", "low": "green"}[risk.level]- console.print(- f"\n[bold]Diff shape[/bold]: [{color}]{risk.level}[/{color}] "- "(absolute per-commit band — no repo baseline to rank against)"- )console.print(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]"diff --git a/packages/core/src/repowise/core/analysis/change_risk/__init__.py b/packages/core/src/repowise/core/analysis/change_risk/__init__.pyindex 44aece89a..d4da46037 100644--- a/packages/core/src/repowise/core/analysis/change_risk/__init__.py+++ b/packages/core/src/repowise/core/analysis/change_risk/__init__.py@@ -1,10 +1,10 @@"""Just-in-time change-risk scoring.-Scores a *change* (a commit or a ``base..head`` range) for defect risk from its-diff shape — size, diffusion, authorship — using a linear, interpretable model-with offline-calibrated constants. Complements the file-level health score: it-is not size-dominated, so it flags risky *small* changes the file delta misses,-and is a natural pre-merge / PR gate.+Assesses a *change* (a commit or a ``base..head`` range) from its diff shape —+size, diffusion, and authorship — using a linear, interpretable model with+offline-calibrated constants. The repo-relative percentile/classification is+the review authority; the 0-10 model output is a supporting diff-shape signal,+not a probability. Complements the indexed file-health score."""from __future__ import annotationsdiff --git a/packages/core/src/repowise/core/analysis/change_risk/model.py b/packages/core/src/repowise/core/analysis/change_risk/model.pyindex 10622db65..16530c5a1 100644--- a/packages/core/src/repowise/core/analysis/change_risk/model.py+++ b/packages/core/src/repowise/core/analysis/change_risk/model.py@@ -18,8 +18,17 @@ from __future__ import annotationsimport mathfrom dataclasses import dataclass, field+from ..risk_semantics import (+ ABSOLUTE_CHANGE_SCORE_HIGH,+ ABSOLUTE_CHANGE_SCORE_MODERATE,+ CHANGE_RISK_SCORE_MEASURES,+ CHANGE_RISK_SCORE_UNIT,+)from .features import ChangeFeatures+SCORE_MEASURES = CHANGE_RISK_SCORE_MEASURES+SCORE_UNIT = CHANGE_RISK_SCORE_UNIT+# Calibrated offline (2026-05-30) on a 7-repo, 5-language slice of the corpus# (clap, pydantic, fd, gin, fastify, bat, chi; AG-SZZ bug-inducing commits as# labels, gap_days=120 right-censoring, pooled L2-logistic over the genuinely@@ -54,8 +63,8 @@ _CONSTANTS: dict[str, object] = {# compares the feature to *the model's baseline commit* (the calibration-corpus# mean), NOT to this repo — so the wording is deliberately neutral and relative# ("more / fewer ... than baseline"), never an absolute verdict like "large".-# The signed contribution + colour carry the risk direction, so a collinear-# coefficient sign never makes a risk-lowering feature read like a warning. The+# The signed contribution + colour carry the model-output direction, so a+# collinear coefficient sign never makes a score-lowering feature a warning. The# shared anchor phrase ("than the model's baseline commit") is stated once by the# surface that renders these, so it is omitted from every individual label._FEATURE_LABELS: dict[str, tuple[str, str]] = {@@ -94,7 +103,7 @@ _UNREPORTABLE_DRIVERS = frozenset({"nf", "nd", "ns"})class ChangeRisk:"""Result of scoring a change."""- score: float # 0-10 (10 * predicted probability)+ score: float # 0-10 offline-calibrated model output; public supporting signallevel: str # absolute band; see _leveldrivers: list[RiskDriver] = field(default_factory=list)features: ChangeFeatures | None = None@@ -119,16 +128,7 @@ def _sigmoid(z: float) -> float:return e / (1.0 + e)-#: The unit the absolute band assumes, stated wherever the band is emitted.-#:-#: The constants were fit on *individual commits* (corpus baseline: 10.5 lines-#: added, 1.7 files), so a squash-merged PR or a multi-commit range is several-#: commits' worth of diff read against a one-commit scale and lands high by-#: construction. The repo-relative percentile is immune to this; the band is not.-SCORE_UNIT = "per-commit"--#: What the score actually measures, stated wherever the score is emitted.-#:+#: What the score actually measures is centralized in ``risk_semantics``.#: Measured, not asserted: `la` (lines added) carries a coefficient 7.6x the next#: largest, and scoring by `la` alone reproduces the full score to within#: 0.12-0.16 points on every repo tried. Refitting at PR granularity with two@@ -138,23 +138,19 @@ SCORE_UNIT = "per-commit"#: blamed by a later fix. Ranking changes by lines-added alone beats the fitted#: model on that benchmark. So the score is reported as what it demonstrably is —#: a diff-size statistic — and ``fix_history`` carries the part that is not.-SCORE_MEASURES = (- "diff size and spread; not where the change lands - overall_risk_score "- "is the separate 0-10 for that"-)def _level(score: float) -> str:- """Absolute calibrated band — the fallback when no percentile is available.+ """Absolute model-score band — the fallback when no percentile is available.Portable only across repos whose typical commit resembles the calibrationcorpus (see :data:`SCORE_UNIT`). Surfaces lead with the repo-relativereview priority and fall back to this only when the baseline sample isempty or too small to rank against."""- if score >= 7.0:+ if score >= ABSOLUTE_CHANGE_SCORE_HIGH:return "high"- if score >= 4.0:+ if score >= ABSOLUTE_CHANGE_SCORE_MODERATE:return "moderate"return "low"@@ -199,7 +195,7 @@ def score_change(features: ChangeFeatures) -> ChangeRisk:logit += contributionabove, below = _FEATURE_LABELS.get(name, (name, name))# Label describes the feature's STATE (above/below typical); the signed- # contribution carries the risk direction.+ # contribution carries the model-output direction.drivers.append(RiskDriver(feature=name,diff --git a/packages/core/src/repowise/core/analysis/change_risk/normalize.py b/packages/core/src/repowise/core/analysis/change_risk/normalize.pyindex c841c5a1b..d851ff3bb 100644--- a/packages/core/src/repowise/core/analysis/change_risk/normalize.py+++ b/packages/core/src/repowise/core/analysis/change_risk/normalize.py@@ -1,7 +1,7 @@"""Repo-relative normalization of change-risk scores.-The raw :func:`change_risk.score_change` value is a calibrated absolute-probability, anchored to the offline calibration corpus — which makes its+The raw :func:`change_risk.score_change` value is an offline-calibrated+0-10 model score, anchored to a single-commit corpus — which makes itshigh/moderate/low *banding* portable only across repos whose typical commitresembles that corpus. On a repo whose median commit is large, the diff-sizefeature (``la``) dominates and the absolute band skews high (two-thirds of@@ -19,10 +19,15 @@ from __future__ import annotationsfrom bisect import bisect_left, bisect_rightfrom dataclasses import dataclass+from ..risk_semantics import (+ REVIEW_PRIORITY_HIGH_PERCENTILE,+ REVIEW_PRIORITY_MODERATE_PERCENTILE,+)+# Tercile cut points on the repo-relative percentile (0-100). A commit in the# top third of its repo's risk distribution is the review-priority tier.-_HIGH_PCT = 200.0 / 3.0 # ≈ 66.67-_MODERATE_PCT = 100.0 / 3.0 # ≈ 33.33+_HIGH_PCT = REVIEW_PRIORITY_HIGH_PERCENTILE+_MODERATE_PCT = REVIEW_PRIORITY_MODERATE_PERCENTILE_PRIORITY_CLASSIFICATIONS = {"low": "Below typical","moderate": "Typical",@@ -111,7 +116,7 @@ class RiskNormalizer:"""Repo-relative review priority: ``high`` | ``moderate`` | ``low``.Derived from the repo-relative percentile (terciles), NOT the absolute- calibrated band — so two-thirds of commits can never all read "high".+ model-score band — so two-thirds of commits can never all read "high"."""if score is None or not self.scores:return "low"diff --git a/packages/core/src/repowise/core/analysis/change_risk/service.py b/packages/core/src/repowise/core/analysis/change_risk/service.pyindex 42afd0332..703e6ac6a 100644--- a/packages/core/src/repowise/core/analysis/change_risk/service.py+++ b/packages/core/src/repowise/core/analysis/change_risk/service.py@@ -6,6 +6,7 @@ import subprocessfrom dataclasses import dataclass, replacefrom pathlib import Path+from ..risk_semantics import change_risk_authority, change_risk_scalesfrom .baseline import BaselineSample, baseline_samples_cached, densities_excluding, scores_excludingfrom .features import (GIT_TIMEOUT_SECONDS,@@ -228,16 +229,20 @@ def score_live_change()-def change_risk_payload(result: ChangeRiskResult) -> dict:+def change_risk_payload(result: ChangeRiskResult, *, scales: bool = False) -> dict:"""Render the machine-readable response shared by the CLI and MCP tool.``fix_history`` leads: it is the block that distinguishes a surgical edit toa file that keeps breaking from a bulk rename of files that never have.``score`` and ``risk_percentile`` describe the *shape* of the diff and arekept for continuity, labelled for what they measure — see ``score_measures``.- ``fallback_band`` is the absolute calibrated band, non-null only when there+ ``fallback_band`` is the absolute model-score band, non-null only when therewas no baseline to rank against. ``score_unit`` names the unit that bandassumes.++ ``risk_authority`` always ships: it names the field to act on. The+ per-field ``risk_scales`` dictionary is identical on every call, so it+ ships only when ``scales`` is set."""features, risk = result.features, result.riskreturn {@@ -252,6 +257,7 @@ def change_risk_payload(result: ChangeRiskResult) -> dict:for path, churn, pressure in result.hot_files],},+ "risk_authority": change_risk_authority(),"score": risk.score,"score_measures": SCORE_MEASURES,"score_unit": SCORE_UNIT,@@ -261,6 +267,7 @@ def change_risk_payload(result: ChangeRiskResult) -> dict:"fallback_band": risk.level if result.priority is None else None,"baseline_sample_size": result.baseline_sample_size,"exclude_patterns": list(result.riskignore_excludes + result.request_excludes),+ **({"risk_scales": change_risk_scales()} if scales else {}),"is_fix": features.is_fix,"features": {"la": features.la,diff --git a/packages/core/src/repowise/core/analysis/pr_blast.py b/packages/core/src/repowise/core/analysis/pr_blast.pyindex 75adac5b6..abbdb39e5 100644--- a/packages/core/src/repowise/core/analysis/pr_blast.py+++ b/packages/core/src/repowise/core/analysis/pr_blast.py@@ -6,7 +6,7 @@ Given a set of changed files, computes:- Co-change warnings (historical co-change partners NOT in the PR)- Recommended reviewers (top owners of affected files)- Test gaps (affected files without a corresponding test file)- - Overall risk score (0-10)+ - Structural impact heuristic (0-10; uncalibrated, not a probability)Reuses existing data: graph_nodes/graph_edges (SQL), git_metadata, and theco_change_partners_json field stored in git_metadata rows.@@ -24,6 +24,7 @@ from typing import Anyfrom sqlalchemy import select, textfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.risk_semantics import structural_impact_contractfrom repowise.core.exclusion import build_exclude_spec, is_excludedfrom repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPESfrom repowise.core.persistence.models import GitMetadata, GraphNode, Repository@@ -153,8 +154,9 @@ class PRBlastRadiusAnalyzer:guarding_tests = legacy_guarding_tests(test_impact)- # 7. Overall risk score (0-10)- overall_risk_score = self._compute_overall_risk(direct_risks, transitive_affected)+ # 7. Structural impact heuristic (0-10). The compatibility field is an+ # exact alias supplied by the shared public semantics contract.+ structural_impact_score = self._compute_overall_risk(direct_risks, transitive_affected)return {"direct_risks": direct_risks,@@ -164,7 +166,7 @@ class PRBlastRadiusAnalyzer:"test_gaps": test_gaps,"test_impact": test_impact,"guarding_tests": guarding_tests,- "overall_risk_score": overall_risk_score,+ **structural_impact_contract(structural_impact_score),}# ------------------------------------------------------------------@@ -200,17 +202,19 @@ class PRBlastRadiusAnalyzer:node = node_by_path.get(path)temporal = float(getattr(meta, "temporal_hotspot_score", 0.0) or 0.0)centrality = float(getattr(node, "pagerank", 0.0) or 0.0)- risk_score = self._score_file(temporal, centrality)+ structural_score = self._score_file(temporal, centrality)results.append({"path": path,- "risk_score": round(risk_score, 4),+ "structural_score": round(structural_score, 4),+ # Compatibility alias for pre-semantics clients.+ "risk_score": round(structural_score, 4),"temporal_hotspot": round(temporal, 4),"centrality": round(centrality, 6),})- results.sort(key=lambda x: -float(x["risk_score"]))+ results.sort(key=lambda x: -float(x["structural_score"]))return results@staticmethod@@ -499,7 +503,7 @@ class PRBlastRadiusAnalyzer:direct_risks: list[dict],transitive_affected: list[dict],) -> float:- """Compute overall risk score on 0-10 scale.+ """Compute the uncalibrated structural-impact heuristic on 0-10.Per-file risk is ``pagerank * (1 + temporal_hotspot)`` — unboundedand pagerank-scaled (typically 0-0.3). The old ``min(raw * 100, 10)``@@ -516,8 +520,8 @@ class PRBlastRadiusAnalyzer:if not direct_risks:return 0.0- avg_direct = sum(r["risk_score"] for r in direct_risks) / len(direct_risks)- max_direct = max(r["risk_score"] for r in direct_risks)+ avg_direct = sum(r["structural_score"] for r in direct_risks) / len(direct_risks)+ max_direct = max(r["structural_score"] for r in direct_risks)breadth_bonus = min(len(transitive_affected) / 20.0, 1.0) # 0-1combined = 0.5 * avg_direct + 0.5 * max_directdiff --git a/packages/core/src/repowise/core/analysis/risk_semantics.py b/packages/core/src/repowise/core/analysis/risk_semantics.pynew file mode 100644index 000000000..d1549c8d7--- /dev/null+++ b/packages/core/src/repowise/core/analysis/risk_semantics.py@@ -0,0 +1,381 @@+"""Shared public vocabulary for risk and structural-impact scalars.++The codebase exposes two deliberately different 0-10 values:++* live change risk scores the *shape* of a git diff with an offline-calibrated+ model and ranks it against recent commits; and+* PR blast radius summarizes indexed centrality and structural reach with an+ uncalibrated heuristic.++Keeping their labels, thresholds, and machine-readable descriptions here makes+it impossible for MCP, REST, CLI, and UI adapters to invent competing meanings.++It ships in two tiers. The guard tier (unit, range, calibration status,+authority) travels with the value and is never omitted. The reference tier+(fitting corpus, formula, component breakdown) is identical on every call and+is returned only for ``include=["scales"]``. :func:`compact_scale` is the one+projection between them, so the tiers cannot disagree.+"""++from __future__ import annotations++from typing import Any++REVIEW_PRIORITY_MODERATE_PERCENTILE = 100.0 / 3.0+REVIEW_PRIORITY_HIGH_PERCENTILE = 200.0 / 3.0++ABSOLUTE_CHANGE_SCORE_MODERATE = 4.0+ABSOLUTE_CHANGE_SCORE_HIGH = 7.0++STRUCTURAL_IMPACT_MODERATE = 4.0+STRUCTURAL_IMPACT_BROAD = 7.0++CHANGE_RISK_SCORE_MEASURES = "diff size and spread; not where the change lands"+CHANGE_RISK_SCORE_UNIT = "per-commit"+STRUCTURAL_IMPACT_MEASURES = (+ "indexed structural exposure: centrality of the changed files plus bounded "+ "direct and transitive dependent breadth"+)+STRUCTURAL_IMPACT_FORMULA = (+ "combined = 0.5 * mean(pagerank * (1 + temporal_hotspot)) + "+ "0.5 * max(pagerank * (1 + temporal_hotspot)); score = min(8 * "+ "(1 - exp(-10 * combined)) + 2 * min(transitive_dependents / 20, 1), 10)"+)+WORKSPACE_IMPACT_SCORE_FORMULA = (+ "maximum path product of edge confidence * edge-kind weight * 0.6 per hop; "+ "structural edge weight = 1.0 and historical co-change edge weight = 0.5"+)+++#: Reference-tier keys: they document a scalar rather than guard a reading.+_REFERENCE_KEYS = frozenset({"deterministic", "formula", "component_fields"})+_CALIBRATION_REFERENCE_KEYS = frozenset(+ {"source", "population", "calibrated_at", "granularity"}+)+++def compact_scale(row: dict[str, Any]) -> dict[str, Any]:+ """Project one scale row onto the facts that prevent a misreading."""+ compact = {key: value for key, value in row.items() if key not in _REFERENCE_KEYS}+ calibration = compact.get("calibration")+ if isinstance(calibration, dict):+ compact["calibration"] = {+ key: value+ for key, value in calibration.items()+ if key not in _CALIBRATION_REFERENCE_KEYS+ }+ return compact+++def structural_impact_band(score: float) -> str:+ """Classify the uncalibrated 0-10 structural heuristic."""+ if score >= STRUCTURAL_IMPACT_BROAD:+ return "broad"+ if score >= STRUCTURAL_IMPACT_MODERATE:+ return "moderate"+ return "localized"+++def change_risk_authority() -> dict[str, Any]:+ """Authority and scalar metadata shared by live-diff public surfaces."""+ return {+ "authoritative_for": "live_change_review",+ "primary_fields": ["risk_percentile", "classification"],+ "primary_basis": "benchmarked_population_relative",+ "fallback_field": "fallback_band",+ "fallback_basis": "absolute_model_score_band",+ "score_role": "supporting_diff_shape_signal",+ }+++def change_risk_scales() -> list[dict[str, Any]]:+ """Describe every scalar or categorical change-risk value and its units."""+ return [+ {+ "field": "score",+ "kind": "benchmarked_model_score",+ "unit": "normalized_points",+ "range": {"minimum": 0.0, "maximum": 10.0},+ "measures": CHANGE_RISK_SCORE_MEASURES,+ "deterministic": True,+ "calibration": {+ "status": "benchmarked",+ "source": "repowise-bench/health-defect/jit_calibration.py",+ "calibrated_at": "2026-05-30",+ "population": "4102 commits across 7 repositories using AG-SZZ labels",+ "granularity": "single_commit",+ },+ "authoritative": False,+ },+ {+ "field": "risk_percentile",+ "kind": "percentile",+ "unit": "percentile_rank",+ "range": {"minimum": 0.0, "maximum": 100.0},+ "measures": "rank of the diff-shape score among sampled recent commits",+ "deterministic": True,+ "calibration": {+ "status": "benchmarked",+ "source": "live repository baseline",+ "population": "sampled recent commits after the same filters",+ },+ "authoritative": True,+ },+ {+ "field": "review_priority",+ "kind": "classification",+ "unit": "category",+ "range": None,+ "measures": "repo-relative review-priority tercile",+ "deterministic": True,+ "thresholds": {+ "moderate_percentile": REVIEW_PRIORITY_MODERATE_PERCENTILE,+ "high_percentile": REVIEW_PRIORITY_HIGH_PERCENTILE,+ },+ "authoritative": True,+ },+ {+ "field": "classification",+ "kind": "classification_label",+ "unit": "category",+ "range": None,+ "measures": "human-facing label for review_priority",+ "deterministic": True,+ "authoritative": True,+ },+ {+ "field": "fallback_band",+ "kind": "absolute_classification",+ "unit": "category",+ "range": None,+ "measures": "absolute model-score band when no baseline can rank the change",+ "deterministic": True,+ "thresholds": {+ "moderate_score": ABSOLUTE_CHANGE_SCORE_MODERATE,+ "high_score": ABSOLUTE_CHANGE_SCORE_HIGH,+ },+ "calibration": {+ "status": "heuristic_thresholds",+ "source": "shared 4.0 and 7.0 model-score thresholds",+ "granularity": "single_commit",+ },+ "authoritative": False,+ },+ {+ "field": "fix_history.density",+ "kind": "historical_heuristic",+ "unit": "recency_weighted_prior_fixes",+ "range": {"minimum": 0.0, "maximum": None},+ "measures": "churn-weighted prior bug-fix pressure of touched files",+ "deterministic": True,+ "calibration": {"status": "uncalibrated", "source": None},+ "authoritative": False,+ },+ {+ "field": "fix_history.percentile",+ "kind": "percentile",+ "unit": "percentile_rank",+ "range": {"minimum": 0.0, "maximum": 100.0},+ "measures": "rank of fix-history density among sampled recent commits",+ "deterministic": True,+ "calibration": {+ "status": "benchmarked",+ "source": "live repository baseline",+ "population": "sampled recent commits after the same filters",+ },+ "authoritative": False,+ },+ {+ "field": "features.la|features.ld",+ "kind": "raw_count",+ "unit": "lines",+ "range": {"minimum": 0.0, "maximum": None},+ "measures": "added or deleted lines in the filtered live diff",+ "deterministic": True,+ "calibration": {"status": "not_applicable", "source": None},+ "authoritative": False,+ },+ {+ "field": "features.nf|features.nd|features.ns",+ "kind": "raw_count",+ "unit": "items",+ "range": {"minimum": 0.0, "maximum": None},+ "measures": "changed files, directories, or top-level subsystems",+ "deterministic": True,+ "calibration": {"status": "not_applicable", "source": None},+ "authoritative": False,+ },+ {+ "field": "features.entropy",+ "kind": "distribution_statistic",+ "unit": "shannon_bits",+ "range": {"minimum": 0.0, "maximum": None},+ "measures": "Shannon entropy of changed-line distribution across files",+ "deterministic": True,+ "calibration": {"status": "not_applicable", "source": None},+ "authoritative": False,+ },+ {+ "field": "features.exp",+ "kind": "raw_count",+ "unit": "prior_commits",+ "range": {"minimum": 0.0, "maximum": None},+ "measures": "author commits before the assessed change; null when unknown",+ "deterministic": True,+ "calibration": {"status": "not_applicable", "source": None},+ "authoritative": False,+ },+ {+ "field": "drivers[].contribution",+ "kind": "model_component",+ "unit": "logit_points",+ "range": {"minimum": None, "maximum": None},+ "measures": "signed exact feature contribution to the model logit",+ "deterministic": True,+ "calibration": {+ "status": "benchmarked",+ "source": "repowise-bench/health-defect/jit_calibration.py",+ },+ "authoritative": False,+ },+ ]+++def structural_impact_contract(score: float, *, full_scale: bool = False) -> dict[str, Any]:+ """Typed additive contract plus exact legacy alias for PR blast responses."""+ contract: dict[str, Any] = {+ "structural_impact_score": score,+ "structural_impact_band": structural_impact_band(score),+ "structural_impact_scale": {+ "field": "structural_impact_score",+ "kind": "heuristic_structural_score",+ "unit": "normalized_points",+ "range": {"minimum": 0.0, "maximum": 10.0},+ "measures": STRUCTURAL_IMPACT_MEASURES,+ "formula": STRUCTURAL_IMPACT_FORMULA,+ "deterministic": True,+ "calibration": {"status": "uncalibrated", "source": None},+ "authoritative_for_change_review": False,+ "runtime_breakage_probability": False,+ "band_thresholds": {+ "moderate": STRUCTURAL_IMPACT_MODERATE,+ "broad": STRUCTURAL_IMPACT_BROAD,+ },+ "component_fields": {+ "direct_risks.structural_score": {+ "kind": "raw_structural_heuristic",+ "unit": "pagerank_weighted_hotspot",+ "range": {"minimum": 0.0, "maximum": None},+ "formula": "pagerank * (1 + temporal_hotspot)",+ },+ "direct_risks.risk_score": {+ "kind": "compatibility_alias",+ "unit": "pagerank_weighted_hotspot",+ "range": {"minimum": 0.0, "maximum": None},+ "deprecated": True,+ "replacement": "direct_risks.structural_score",+ "equivalent_value": True,+ },+ "direct_risks.temporal_hotspot": {+ "kind": "normalized_component_score",+ "unit": "ratio",+ "range": {"minimum": 0.0, "maximum": 1.0},+ },+ "direct_risks.centrality": {+ "kind": "graph_centrality",+ "unit": "pagerank",+ "range": {"minimum": 0.0, "maximum": 1.0},+ },+ "transitive_affected.depth": {+ "kind": "raw_count",+ "unit": "dependency_hops",+ "range": {"minimum": 1.0, "maximum": None},+ },+ "cochange_warnings.score": {+ "kind": "raw_count",+ "unit": "historical_cochange_commits",+ "range": {"minimum": 0.0, "maximum": None},+ },+ "recommended_reviewers.ownership_pct": {+ "kind": "ownership_fraction",+ "unit": "ratio",+ "range": {"minimum": 0.0, "maximum": 1.0},+ },+ },+ },+ # Public compatibility field. It is deliberately an exact alias, never+ # repurposed, so old clients cannot interpret a new unit as the old one.+ "overall_risk_score": score,+ "overall_risk_score_compatibility": {+ "deprecated": True,+ "replacement": "structural_impact_score",+ "equivalent_value": True,+ "historical_meaning": "uncalibrated 0-10 structural blast-radius heuristic",+ },+ }+ if not full_scale:+ contract["structural_impact_scale"] = compact_scale(contract["structural_impact_scale"])+ return contract+++def file_risk_scales() -> list[dict[str, Any]]:+ """Metadata for indexed-file risk cards returned by ``get_risk``."""+ return [+ {+ "field": "targets.*.hotspot_score",+ "kind": "normalized_component_score",+ "unit": "ratio",+ "range": {"minimum": 0.0, "maximum": 1.0},+ "measures": "repository-relative churn percentile",+ "calibration": {"status": "uncalibrated", "source": None},+ },+ {+ "field": "targets.*.health_score",+ "kind": "code_health_score",+ "unit": "health_points",+ "range": {"minimum": 0.0, "maximum": 10.0},+ "measures": "overall code health; higher is healthier",+ "calibration": {"status": "benchmarked", "source": "code-health model"},+ },+ {+ "field": "targets.*.owner_pct",+ "kind": "ownership_fraction",+ "unit": "ratio",+ "range": {"minimum": 0.0, "maximum": 1.0},+ "measures": "share of commits attributed to the primary owner",+ "calibration": {"status": "not_applicable", "source": None},+ },+ {+ "field": "targets.*.recent_owner_pct",+ "kind": "ownership_fraction",+ "unit": "ratio",+ "range": {"minimum": 0.0, "maximum": 1.0},+ "measures": "share of recent commits attributed to the recent owner",+ "calibration": {"status": "not_applicable", "source": None},+ },+ {+ "field": "targets.*.risk_type",+ "kind": "heuristic_classification",+ "unit": "category",+ "range": None,+ "measures": "dominant indexed warning type from fixes, churn, coupling, or ownership",+ "calibration": {"status": "uncalibrated", "source": None},+ },+ ]+++def workspace_impact_score_semantics(*, full: bool = False) -> dict[str, Any]:+ """Metadata for the workspace blast-radius path-ranking score."""+ scale: dict[str, Any] = {+ "field": "impacted[].score",+ "kind": "heuristic_path_rank",+ "unit": "relative_weight",+ "range": {"minimum": 0.0, "maximum": 1.0},+ "measures": "strongest bounded structural or historical path from a target service",+ "formula": WORKSPACE_IMPACT_SCORE_FORMULA,+ "deterministic": True,+ "calibration": {"status": "uncalibrated", "source": None},+ "authoritative_for_change_review": False,+ "runtime_breakage_probability": False,+ }+ return scale if full else compact_scale(scale)diff --git a/packages/core/src/repowise/core/generation/editor_files/tool_table.py b/packages/core/src/repowise/core/generation/editor_files/tool_table.pyindex d6fbced7f..91a16bbad 100644--- a/packages/core/src/repowise/core/generation/editor_files/tool_table.py+++ b/packages/core/src/repowise/core/generation/editor_files/tool_table.py@@ -87,15 +87,15 @@ TOOL_TABLE_ROWS: dict[str, tuple[str, str]] = {),"get_risk": ("get_risk(targets, changed_files?, include?)",- "Call before editing for file history and blast radius. PR mode "- "(`changed_files`) leads with `directive`; read typed "- "`test_recommendations` and coverage state first.",+ "File history and structural reach. PR mode leads with `directive`; its "+ "0-10 structural heuristic is uncalibrated, not a probability. Read typed "+ "test recommendations and coverage state first.",),"get_change_risk": ("get_change_risk(revspec?, extensions?, exclude_patterns?)",- "Defect score for a whole commit or `base..head` range, from its diff on the "- "live checkout. Lead with `fix_history`. Scores a range; `get_risk` "- "scores paths.",+ "Deterministic live-diff review signal for a commit or range. Lead with "+ "benchmarked percentile/classification; the 0-10 diff-shape score is "+ "supporting, not a probability. `get_risk` scores paths.",),"get_health": ("get_health(targets?, include?)",diff --git a/packages/core/src/repowise/core/workspace/blast_radius.py b/packages/core/src/repowise/core/workspace/blast_radius.pyindex 2acc47e45..bff5db819 100644--- a/packages/core/src/repowise/core/workspace/blast_radius.py+++ b/packages/core/src/repowise/core/workspace/blast_radius.py@@ -3,9 +3,9 @@Answers "if I change this service, what downstream services and repos areaffected?" by traversing the Phase 1 :class:`SystemGraph` *against* its edgedirection: an edge ``source → target`` means *source depends on / calls-target*, so changing ``target`` puts ``source`` at risk. We follow those-reverse links outward from the changed node(s) to find everything that could-break.+target*, so changing ``target`` makes ``source`` structurally reachable. We+follow those reverse links outward from the changed node(s); reachability is not+proof that runtime behavior will break.Two edge classes are weighted and labeled distinctly (the D5 honesty rule):@@ -50,8 +50,8 @@ MAX_DEPTH_LIMIT = 8#: the reachability ranking — keep it the only place that distinction is tuned.BEHAVIORAL_EDGE_WEIGHT = 0.5-#: Each additional hop attenuates the propagated impact: a service two calls away-#: is less likely to actually break than a direct consumer. Applied once per hop,+#: Each additional hop attenuates the propagated ranking weight: a service two+#: calls away is weaker structural evidence than a direct consumer. Applied per hop,#: so a node at distance *d* carries roughly ``DISTANCE_DECAY ** d`` of the base.DISTANCE_DECAY = 0.6diff --git a/packages/server/README.md b/packages/server/README.mdindex 8a778847d..5e8ffe1fb 100644--- a/packages/server/README.md+++ b/packages/server/README.md@@ -161,7 +161,7 @@ Job progress events (`JobProgressEvent`) carry: `event` type, `file` currently b| Method | Path | Description ||--------|------|-------------|-| `POST` | `/api/repos/{repo_id}/blast-radius` | Estimate PR impact for a list of changed files — returns overall risk score, direct/transitive risks, co-change warnings, recommended reviewers, and test gaps |+| `POST` | `/api/repos/{repo_id}/blast-radius` | Structural PR impact for changed files — returns an uncalibrated 0-10 structural heuristic, raw direct weights, transitive reach, historical co-change, reviewers, and typed test state |### Costs@@ -252,7 +252,7 @@ repowise mcp --transport sse # legacy SSE transport on port 7338| `get_symbol(symbol_id)` | Source body, signature, docstring for a qualified symbol | When the question names a specific function or class || `search_codebase(query, mode?)` | Hybrid symbol / path / concept search (auto-routes by query shape) | When locating a symbol, a file, or code by topic || `get_risk(targets)` | Hotspot score, dependents, co-change partners, risk summary | Before modifying files — assess what could break |-| `get_change_risk(revspec?)` | Whole-change defect-risk score for a commit or `base..head` range | Before merging a commit or PR range |+| `get_change_risk(revspec?)` | Benchmarked repo-relative review percentile/classification plus a supporting live diff-shape score | Before merging a commit or PR range || `get_why(query?)` | Architectural decisions, rationale, constraints | Before making architectural changes — understand existing intent || `get_dead_code` | Unused/unreachable code sorted by cleanup impact | Before cleanup tasks || `get_health` | 1–10 code-health scores and marker findings | Before refactoring — find the worst files |diff --git a/packages/server/src/repowise/server/chat_tools.py b/packages/server/src/repowise/server/chat_tools.pyindex ac0f66ca6..505cb5829 100644--- a/packages/server/src/repowise/server/chat_tools.py+++ b/packages/server/src/repowise/server/chat_tools.py@@ -118,7 +118,7 @@ _TOOL_SCHEMAS: list[dict[str, Any]] = [},{"name": "get_change_risk",- "description": "Score the defect risk of a live commit or branch range from diff size, diffusion, and author familiarity. Use for pre-merge ranking; use get_risk for per-file history and blast radius.",+ "description": "Rank a live commit or branch range against recent repository changes. The percentile/classification is authoritative; the 0-10 diff-shape score is supporting, not a probability. Use get_risk for indexed file history and structural reach.","parameters": {"type": "object","properties": {diff --git a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.pyindex b1417e755..aa9b58930 100644--- a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py+++ b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py@@ -1,6 +1,6 @@"""MCP Tool: get_blast_radius — cross-repo downstream impact (workspace only).-Answers "if I change this service, what breaks across the other repos?" by+Answers "what structural or historical reach follows from this service?" bytraversing the workspace system graph. Structural dependencies (contracts,package deps) are ranked above behavioral co-change. Mirrors the single-repochange-risk vocabulary (``get_risk`` PR-mode, ``blast-radius.ts``): impacted@@ -35,10 +35,12 @@ async def get_blast_radius(max_depth: int = 3,include_behavioral: bool = True,) -> dict[str, Any]:- """Cross-repo blast radius — what downstream services break if you change this.+ """Cross-repo blast radius — which downstream services are structurally reachable.Workspace-only. Traverses the system graph from the given service(s) and- returns the impacted services across every repo, ranked by impact score.+ returns the reachable services across every repo, ranked by an uncalibrated+ 0-1 path-weight heuristic. It is not runtime-breakage evidence or a+ probability.Structural edges (http / grpc / event / package) outweigh behavioralco-change. Call before changing a high-fan-out provider to see who consumesit across repo boundaries.@@ -71,6 +73,7 @@ async def get_blast_radius("_meta": _build_meta(),}+ from repowise.core.analysis.risk_semantics import workspace_impact_score_semanticsfrom repowise.core.workspace.blast_radius import cross_repo_blast_radius, resolve_targetsfrom repowise.core.workspace.system_graph import SystemGraph@@ -119,6 +122,7 @@ async def get_blast_radius("max_distance": result.max_distance,"total_impacted": result.total_impacted,"unresolved_targets": result.unresolved_targets,+ "impact_score_semantics": workspace_impact_score_semantics(),"summary": summary,"_meta": _build_meta(extra=_analysis_meta(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 a505dfc13..0c4f24e11 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@@ -27,6 +27,8 @@ from repowise.server.mcp_server._helpers import (_is_workspace_mode,_resolve_repo_context,_unsupported_repo_all,+ attach_ignored_arguments,+ resolve_enum_argument,)from repowise.server.mcp_server._meta import build_meta as _build_meta@@ -45,6 +47,9 @@ _PRIOR_FIXES_LIMIT = 10_CROSS_REPO_BREAKING_LIMIT = 5_CROSS_REPO_CONSUMER_LIMIT = 10+#: Per-field units and calibration. Identical on every call, so it is opt-in.+_INCLUDE_BLOCKS = frozenset({"scales"})+# Cheapest loss first; the score, its drivers and fix_history's numbers are the# answer and never shed. cross_repo outlives the run-list: a test list is# recoverable by running the suite, a broken consumer in another repo is not.@@ -64,29 +69,25 @@ async def get_change_risk(extensions: list[str] | None = None,exclude_patterns: list[str] | None = None,baseline: int = 200,+ include: list[str] | None = None,) -> dict:"""Score a live commit, ``base..head`` range, or uncommitted work.For a pre-merge read on a commit or PR range; ``get_risk`` scores indexedfiles instead. The filters also apply to the percentile baseline.- Lead with ``fix_history``: the recency-weighted bug-fix record of the- touched files, ``files`` naming where the pressure sits. It separates a- surgical edit to a bug magnet from a bulk rename. ``score`` measures diff- size and spread, not where the change lands (see ``score_measures``),- calibrated per commit; ``risk_percentile`` ranks that shape against recent- commits.+ Act on ``risk_percentile`` + ``classification``: they rank this diff+ against recent commits, and ``risk_authority`` names them. ``score`` is a+ supporting 0-10 model score for diff size and spread, never a probability;+ ``fallback_band`` stands in only when no baseline exists. ``fix_history``+ carries the bug-fix record of the touched files.- ``impacted_tests.tests_to_run`` names the tests to run; ``line_coverage``- the uncovered lines. ``basis``: ``measured`` = a coverage map proves those- tests run the changed *lines*; ``inferred`` = test files the graph shows- reaching it (file-level candidates). No map is never "untested":- ``no_map`` means run the suite. On ``truncated``, expand- ``omission_marker`` for the tail. ``prior_fixes``- counts past fixes whose lines overlap this diff.+ ``impacted_tests`` keeps measured coverage and inferred graph candidates+ distinct, labels unavailable analysis, and exposes truncation metadata.+ ``prior_fixes`` counts past fixes whose lines overlap this diff.- ``cross_repo`` (workspace mode) names other repos' consumers of the changed- files and what broke, as of the last workspace update.+ ``cross_repo`` names typed consumers and contract breaks from the last+ workspace update.Args:revspec: Commit or ``base..head`` range to score. Omit it to score the@@ -95,6 +96,8 @@ async def get_change_risk(extensions: File suffixes to count, e.g. ``[".py", ".ts"]``.exclude_patterns: Gitignore-style paths to omit, e.g. ``["tests/"]``.baseline: Recent commits to sample for percentile ranking; 0 disables it.+ include: opt-in blocks - "scales" for every scalar's unit, range and+ calibration. Identical on every call, so ask once."""if repo == "all":return _unsupported_repo_all("get_change_risk")@@ -116,7 +119,13 @@ async def get_change_risk(return {"error": f"Could not read change {revspec or 'HEAD'!r}: {detail}"}except subprocess.TimeoutExpired:return {"error": f"git timed out reading change {revspec or 'HEAD'!r}."}- payload = change_risk_payload(result)+ ignored: list[dict] = []+ include_set = {+ block+ for block in (include or [])+ if resolve_enum_argument(block, _INCLUDE_BLOCKS, argument="include", ignored=ignored)+ }+ payload = change_risk_payload(result, scales="scales" in include_set)if result.features.nf == 0:payload["warning"] = (f"No counted file changes in {payload['ref']!r} "@@ -158,6 +167,7 @@ async def get_change_risk(targets=sorted(changed) or None,extra={"source": "live_git"},)+ attach_ignored_arguments(payload, ignored)fit_to_budget(payload, _SHED_ORDER, collector)collector.attach(payload)return payloaddiff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.pyindex 90cada489..54c8e1cf0 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py@@ -4,6 +4,7 @@ from __future__ import annotationsfrom typing import Any+from repowise.core.analysis.risk_semantics import structural_impact_contractfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.decision_graph import get_governing_decisions, list_conflict_edgesfrom repowise.server.mcp_server import _state@@ -53,13 +54,6 @@ _MAY_BREAK_TESTS_LIMIT = 3#: the overflow and full typed rows live in pr_blast_radius.test_impact._TESTS_TO_RUN_LIMIT = 10-#: get_risk and get_change_risk both render 0-10 and measure unrelated things.-#: Whichever an agent reads first, this says the other is not the same scale.-_OVERALL_SCORE_MEASURES = (- "where the change lands: centrality of the changed files and how far it "- "reaches; not comparable to get_change_risk.score, which measures diff shape"-)-def _breaking_change_directive(repo_alias: str) -> tuple[list[dict[str, Any]], int]:"""Breaking-change half of the PR directive: incompatible provider changes.@@ -264,6 +258,8 @@ def _trim_blast_lists(pr_blast_radius: dict[str, Any],exclude_spec: Any,collector: OmissionCollector | None = None,+ *,+ full_scale: bool = False,) -> dict[str, Any]:"""Cap the noisy ``pr_blast_radius`` lists, capturing what gets dropped.@@ -275,6 +271,13 @@ def _trim_blast_lists(are filtered by policy, not budget)."""trimmed_blast: dict[str, Any] = dict(pr_blast_radius)+ # Re-derive so the scale tier follows the caller's include, not the+ # analyzer's default. The legacy field stays an exact alias.+ structural_score = trimmed_blast.get("structural_impact_score")+ if structural_score is not None:+ trimmed_blast.update(+ structural_impact_contract(float(structural_score), full_scale=full_scale)+ )for key, cap in (("transitive_affected", 15),("cochange_warnings", 10),@@ -299,8 +302,6 @@ def _trim_blast_lists(trimmed_blast[f"{key}_total"] = totaltrimmed_blast[f"{key}_emitted"] = len(trimmed_blast.get(key, []))trimmed_blast[f"{key}_truncated"] = total > len(trimmed_blast.get(key, []))- if trimmed_blast.get("overall_risk_score") is not None:- trimmed_blast["overall_risk_score_measures"] = _OVERALL_SCORE_MEASURESreturn trimmed_blast@@ -366,6 +367,8 @@ def _build_pr_directive(governance_risk: list[dict[str, Any]],test_paths: set[str],alias: str,+ *,+ full_scale: bool = False,) -> None:"""Assemble PR-mode output: trim co-change lists + blast radius, then buildthe directive block. Mutates *response* in place. Behavior preserved.@@ -388,7 +391,9 @@ def _build_pr_directive(r["co_change_partners_emitted"] = emittedr["co_change_partners_truncated"] = emitted < total- trimmed_blast = _trim_blast_lists(pr_blast_radius, exclude_spec, collector)+ trimmed_blast = _trim_blast_lists(+ pr_blast_radius, exclude_spec, collector, full_scale=full_scale+ )response["pr_blast_radius"] = trimmed_blast# Directive: 3 short lists the agent can read in one glance. Eachdiff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.pyindex 95cd2ff85..be5b32631 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py@@ -6,6 +6,7 @@ import asynciofrom sqlalchemy import select+from repowise.core.analysis.risk_semantics import file_risk_scalesfrom repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPESfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import (@@ -70,7 +71,8 @@ _TARGET_CARD_INCLUDES: dict[str, tuple[str, ...]] = {"churn": ("change_magnitude", "risk_type", "change_pattern"),}_BLAST_INCLUDES: dict[str, tuple[str, ...]] = {"graph": ("direct_risks",)}-_INCLUDE_BLOCKS = frozenset(_TARGET_CARD_INCLUDES) | frozenset(_BLAST_INCLUDES)+#: Per-field units and calibration. Identical on every call, so it is opt-in.+_INCLUDE_BLOCKS = frozenset(_TARGET_CARD_INCLUDES) | frozenset(_BLAST_INCLUDES) | {"scales"}def _drop_opt_in_blocks(response: dict, include: set[str]) -> None:@@ -100,27 +102,28 @@ async def get_risk(reach (source depends on target), ``consumers`` require typed contract links,and ``co_change_partners`` are historical correlation only. Structural reachis not proof of runtime breakage. The response also includes security- findings. Consult before editing a bug-fixed or busy file. Pass- changed_files for PR mode: the response leads with a directive block- (may_break, missing_cochanges, missing_tests, tests_to_run) — read it- first. Each test_recommendations row carries a measured or inferred basis;- tests_to_run keeps its measured-first compatibility projection. Coverage- availability and freshness are explicit. To score a commit- or ``base..head`` range instead, use ``get_change_risk``.+ findings. Pass changed_files for PR mode: the response leads with a+ directive block (may_break, missing_cochanges, missing_tests,+ tests_to_run) — read it first. Each test_recommendations row carries a+ measured or inferred basis, and coverage availability is explicit. To+ score a commit or ``base..head`` range instead, use ``get_change_risk``.- defect_profile appears only with counted fixes; top_symbols is approximate- attribution, and nothing names a bug-inducing commit.+ In PR mode ``structural_impact_score`` is an uncalibrated 0-10 structural+ heuristic, never a runtime-breakage probability; ``overall_risk_score`` is+ its deprecated exact alias.- episodes counts the dated records bound to a target — what happened here and- why, evidenced by a commit or a filesystem fact. It appears only when there- is at least one, and get_why serves the bodies. A directory target- aggregates everything beneath it, so compare within a kind of target.+ ``defect_profile`` appears only with counted fixes; ``top_symbols`` is+ approximate attribution. ``episodes`` counts dated records bound to a+ target, evidenced by a commit or a filesystem fact; ``get_why`` serves the+ bodies. Directory targets aggregate everything beneath them, so compare+ within a kind of target.Args:targets: file paths to assess.repo: usually omitted.changed_files: PR-changed files for blast-radius mode.- include: opt-in blocks - "graph", "churn".+ include: opt-in blocks - "graph", "churn", "scales" (units and+ calibration for every scalar; identical per call, so ask once)."""if repo == "all":return _unsupported_repo_all("get_risk")@@ -271,6 +274,7 @@ async def get_risk(response: dict = {"targets": {r["target"]: r for r in results},+ **({"risk_scales": file_risk_scales()} if "scales" in include_set else {}),}collector = OmissionCollector("get_risk", repo_root=ctx.path)@@ -287,6 +291,7 @@ async def get_risk(governance_risk,test_paths,ctx.alias,+ full_scale="scales" in include_set,)# Dict insertion order is the serialized external order. PR mode is# action-first by contract, so the directive must precede dossiers,diff --git a/packages/server/src/repowise/server/routers/blast_radius.py b/packages/server/src/repowise/server/routers/blast_radius.pyindex 49c1b5697..eb79f7438 100644--- a/packages/server/src/repowise/server/routers/blast_radius.py+++ b/packages/server/src/repowise/server/routers/blast_radius.py@@ -24,9 +24,10 @@ async def analyze_blast_radius() -> BlastRadiusResponse:"""Compute blast radius for a proposed PR given its changed files.- Returns direct risk scores, transitive structural reach, historical+ Returns raw per-file structural scores, transitive structural reach, historicalco-change warnings, reviewers, compatibility test gaps, a canonical typed- test-impact population with evidence/availability state, and a 0–10 score.+ test-impact population with evidence/availability state, and an uncalibrated+ 0–10 structural-impact heuristic. None is a runtime-breakage probability."""analyzer = PRBlastRadiusAnalyzer(session=session, repo_id=repo_id)result = await analyzer.analyze_files(diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.pyindex 1171180f0..e5163c0fd 100644--- a/packages/server/src/repowise/server/routers/git.py+++ b/packages/server/src/repowise/server/routers/git.py@@ -32,6 +32,7 @@ from repowise.core.analysis.change_risk import (score_change,scores_excluding,)+from repowise.core.analysis.risk_semantics import change_risk_authorityfrom repowise.core.ingestion.git_indexer._constants import (EVOLUTION_CATEGORIES,classify_commit_category,@@ -235,7 +236,7 @@ async def get_commits() -> Paginated[CommitResponse]:"""Per-commit change-risk feed — the review-priority queue.- ``sort=risk`` (default) orders by raw change-risk score descending (the+ ``sort=risk`` (default) orders by supporting diff-shape score descending (thereview-priority order); ``sort=date`` orders by recency. ``authorship``narrows the feed to agent-attributed or human commits. Each commit alsocarries a **repo-relative** ``risk_percentile`` + ``review_priority`` so the@@ -357,11 +358,11 @@ async def get_commit_stats()-_HISTOGRAM_BINS = 20 # 0.5-wide bins across the 0-10 raw change-risk score+_HISTOGRAM_BINS = 20 # 0.5-wide bins across the 0-10 supporting diff-shape scoredef _risk_histogram(sorted_scores: list[float]) -> list[RiskHistogramBucket]:- """Bin the repo's raw change-risk scores for the distribution chart.+ """Bin the repo's supporting diff-shape scores for the distribution chart.Reuses the score list already fetched for the normalizer, so this costs noextra query. The top bin is closed on the right so a perfect 10.0 lands@@ -676,7 +677,7 @@ def get_risk_range(),repo: Repository = Depends(_resolve_local_repo),) -> RiskRangeResponse:- """Score a ``base..head`` git range's defect risk from its live diff shape.+ """Assess a ``base..head`` range from its live diff shape and history.Mirrors ``repowise risk <base>..<head> --format json``: same Kameichange-risk model, scored on demand against the working tree instead of@@ -734,6 +735,7 @@ def get_risk_range(for path, churn, p in hot_files(pressure, features.file_churn)],),+ risk_authority=change_risk_authority(),score=risk.score,score_measures=SCORE_MEASURES,score_unit=SCORE_UNIT,diff --git a/packages/server/src/repowise/server/schemas/blast_radius.py b/packages/server/src/repowise/server/schemas/blast_radius.pyindex 330907143..971d7ba92 100644--- a/packages/server/src/repowise/server/schemas/blast_radius.py+++ b/packages/server/src/repowise/server/schemas/blast_radius.py@@ -6,6 +6,11 @@ from typing import Literalfrom pydantic import BaseModel, Field+from repowise.server.schemas.risk_semantics import (+ RiskCompatibilityField,+ RiskScalarSemantics,+)+class BlastRadiusRequest(BaseModel):changed_files: list[str]@@ -14,6 +19,8 @@ class BlastRadiusRequest(BaseModel):class DirectRiskEntry(BaseModel):path: str+ structural_score: float+ #: Deprecated exact alias of ``structural_score`` for older clients.risk_score: floattemporal_hotspot: floatcentrality: float@@ -124,4 +131,9 @@ class BlastRadiusResponse(BaseModel):recommended_reviewers: list[ReviewerEntry]test_gaps: list[str]test_impact: TestImpactResponse+ structural_impact_score: float+ structural_impact_band: Literal["localized", "moderate", "broad"]+ structural_impact_scale: RiskScalarSemantics+ #: Deprecated exact alias; never repurposed to a new unit.overall_risk_score: float+ overall_risk_score_compatibility: RiskCompatibilityFielddiff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.pyindex afaa3fe21..dd8b2ed01 100644--- a/packages/server/src/repowise/server/schemas/git.py+++ b/packages/server/src/repowise/server/schemas/git.py@@ -7,6 +7,8 @@ from datetime import datetimefrom pydantic import BaseModel+from repowise.server.schemas.risk_semantics import RiskAuthority+class GitMetadataResponse(BaseModel):file_path: str@@ -181,10 +183,14 @@ class CommitResponse(BaseModel):subsystems_changed: intentropy: floatis_fix: bool+ #: Supporting 0-10 calibrated diff-size/spread score; not a probability.change_risk_score: float | None+ #: Absolute per-commit compatibility band; prefer ``review_priority``.change_risk_level: str | None# Repo-relative normalization (the portable signal).+ #: Repo-relative percentile rank, 0-100.risk_percentile: float+ #: Authoritative repo-relative review-priority tercile.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@@ -323,9 +329,10 @@ class RiskRangeResponse(BaseModel):base: strhead: str- #: Where the change lands. Read this before ``score``: it is the part that- #: distinguishes a small edit to a fragile file from a large boring one.+ #: Separate historical evidence about where the change lands; it is not+ #: folded into the authoritative percentile/classification.fix_history: FixHistoryResponse+ risk_authority: RiskAuthorityscore: float#: What ``score`` measures. It tracks diff size and spread, not danger.score_measures: str@@ -335,7 +342,7 @@ class RiskRangeResponse(BaseModel):risk_percentile: float | Nonereview_priority: str | Noneclassification: str | None- #: Absolute calibrated band, present only when there was no baseline to+ #: Absolute model-score band, present only when there was no baseline to#: rank against — so it is not a peer of ``review_priority``.fallback_band: str | Noneis_fix: bool@@ -344,7 +351,7 @@ class RiskRangeResponse(BaseModel):class RiskHistogramBucket(BaseModel):- """One bin of the repo's raw change-risk score distribution."""+ """One bin of the repo's supporting 0-10 diff-shape score distribution."""start: float # bin lower bound on the 0-10 raw score axis (inclusive)end: float # bin upper bound (exclusive, except the final bin)diff --git a/packages/server/src/repowise/server/schemas/risk_semantics.py b/packages/server/src/repowise/server/schemas/risk_semantics.pynew file mode 100644index 000000000..1d8bb0785--- /dev/null+++ b/packages/server/src/repowise/server/schemas/risk_semantics.py@@ -0,0 +1,53 @@+"""Typed wire metadata shared by public risk-report schemas."""++from __future__ import annotations++from typing import Any++from pydantic import BaseModel+++class RiskScaleRange(BaseModel):+ minimum: float | None+ maximum: float | None+++class RiskCalibration(BaseModel):+ status: str+ source: str | None = None+ calibrated_at: str | None = None+ population: str | None = None+ granularity: str | None = None+++class RiskScalarSemantics(BaseModel):+ field: str+ kind: str+ unit: str+ range: RiskScaleRange | None+ measures: str+ deterministic: bool = True+ calibration: RiskCalibration | None = None+ authoritative: bool | None = None+ authoritative_for_change_review: bool | None = None+ runtime_breakage_probability: bool | None = None+ formula: str | None = None+ thresholds: dict[str, float] | None = None+ band_thresholds: dict[str, float] | None = None+ component_fields: dict[str, dict[str, Any]] | None = None+++class RiskAuthority(BaseModel):+ authoritative_for: str+ primary_fields: list[str]+ primary_basis: str+ fallback_field: str+ fallback_basis: str+ score_role: str+++class RiskCompatibilityField(BaseModel):+ deprecated: bool+ replacement: str+ equivalent_value: bool+ historical_meaning: strdiff --git a/packages/types/package.json b/packages/types/package.jsonindex 5c7923230..a63f13607 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -19,6 +19,7 @@"./chat": "./src/chat.ts","./workspace": "./src/workspace.ts","./blast-radius": "./src/blast-radius.ts",+ "./risk-semantics": "./src/risk-semantics.ts","./jobs": "./src/jobs.ts","./settings": "./src/settings.ts","./security": "./src/security.ts",diff --git a/packages/types/src/blast-radius.ts b/packages/types/src/blast-radius.tsindex 28809145e..d2aadc29c 100644--- a/packages/types/src/blast-radius.ts+++ b/packages/types/src/blast-radius.ts@@ -6,9 +6,16 @@* Both backends produce the same shape; this is the canonical TS contract.*/+import type {+ RiskCompatibilityField,+ RiskScalarSemantics,+} from "./risk-semantics.js";+export interface DirectRiskEntry {path: string;- /** centrality * (1 + temporal_hotspot); unbounded, compare within a change set. */+ /** Raw unbounded structural heuristic; compare only within this change set. */+ structural_score: number;+ /** @deprecated Exact alias of structural_score for older clients. */risk_score: number;/** 0-1 normalised. */temporal_hotspot: number;@@ -119,8 +126,13 @@ export interface BlastRadiusResponse {test_gaps: string[];/** Canonical typed test-impact population. Optional for older servers. */test_impact?: TestImpactResponse;- /** 0–10. */+ /** Deterministic, uncalibrated structural-impact heuristic, 0–10. */+ structural_impact_score: number;+ structural_impact_band: "localized" | "moderate" | "broad";+ structural_impact_scale: RiskScalarSemantics;+ /** @deprecated Exact alias of structural_impact_score; not a probability. */overall_risk_score: number;+ overall_risk_score_compatibility: RiskCompatibilityField;}export interface BlastRadiusRequest {diff --git a/packages/types/src/git.ts b/packages/types/src/git.tsindex 0c88d8fc5..4947f7cbe 100644--- a/packages/types/src/git.ts+++ b/packages/types/src/git.ts@@ -136,7 +136,7 @@ export interface Commit {subsystems_changed: number;entropy: number;is_fix: boolean;- /** Raw 0–10 change-risk score from the calibrated model (stored). */+ /** Supporting 0–10 calibrated diff-size/spread score (stored; not a probability). */change_risk_score: number | null;/** Absolute calibration band — kept for transparency, but skews high on* repos with large typical commits; prefer {@link review_priority}. */@@ -165,7 +165,7 @@ export interface Commit {export interface RiskDriver {feature: string;value: number | null;- /** Signed push on the logit; positive raises risk, negative lowers it. */+ /** Signed push on the model logit; positive raises the supporting score. */contribution: number;label: string;}@@ -225,7 +225,7 @@ export interface CommitEvolution {last_commit_at: string | null;}-/** One bin of the repo's raw change-risk score distribution. */+/** One bin of the repo's supporting 0-10 diff-shape score distribution. */export interface RiskHistogramBucket {/** Bin lower bound on the 0-10 raw score axis (inclusive). */start: number;diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex a2b9669bf..0a8252cdd 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -19,6 +19,7 @@ export * from "./symbols.js";export * from "./chat.js";export * from "./workspace.js";export * from "./blast-radius.js";+export * from "./risk-semantics.js";export * from "./jobs.js";export * from "./settings.js";export * from "./security.js";diff --git a/packages/types/src/risk-semantics.ts b/packages/types/src/risk-semantics.tsnew file mode 100644index 000000000..f0cf63884--- /dev/null+++ b/packages/types/src/risk-semantics.ts@@ -0,0 +1,49 @@+/** Shared machine-readable vocabulary for public risk and impact scalars. */++export interface RiskScaleRange {+ minimum: number | null;+ maximum: number | null;+}++export interface RiskCalibration {+ status: "benchmarked" | "heuristic_thresholds" | "uncalibrated" | "not_applicable";+ /** Reference tier: present only under include=["scales"]. */+ source?: string | null;+ calibrated_at?: string | null;+ population?: string | null;+ granularity?: string | null;+}++export interface RiskScalarSemantics {+ field: string;+ kind: string;+ unit: string;+ range: RiskScaleRange | null;+ measures: string;+ /** Reference tier: present only under include=["scales"]. */+ deterministic?: boolean;+ calibration?: RiskCalibration | null;+ authoritative?: boolean | null;+ authoritative_for_change_review?: boolean | null;+ runtime_breakage_probability?: boolean | null;+ formula?: string | null;+ thresholds?: Record<string, number> | null;+ band_thresholds?: Record<string, number> | null;+ component_fields?: Record<string, Record<string, unknown>> | null;+}++export interface RiskAuthority {+ authoritative_for: "live_change_review";+ primary_fields: ["risk_percentile", "classification"];+ primary_basis: "benchmarked_population_relative";+ fallback_field: "fallback_band";+ fallback_basis: "absolute_model_score_band";+ score_role: "supporting_diff_shape_signal";+}++export interface RiskCompatibilityField {+ deprecated: true;+ replacement: string;+ equivalent_value: true;+ historical_meaning: string;+}diff --git a/packages/ui/COMPONENT_CONTRACTS.md b/packages/ui/COMPONENT_CONTRACTS.mdindex fb295dbeb..9b32a9653 100644--- a/packages/ui/COMPONENT_CONTRACTS.md+++ b/packages/ui/COMPONENT_CONTRACTS.md@@ -1155,11 +1155,13 @@ these components only render `BlastRadiusResponse` (from### `blast-radius/risk-score-card` — `RiskScoreCard`-Coloured 0–10 gauge. Red ≥7, amber ≥4, emerald otherwise.+Structural-impact gauge. The server-owned band is `broad`, `moderate`, or+`localized`; the value is an uncalibrated 0–10 heuristic, not a probability.| Prop | Type | Required ||------|------|----------|| `score` | `number` (0–10) | yes |+| `band` | `"localized" \| "moderate" \| "broad"` | no |### `blast-radius/table-section` — `TableSection`@@ -1174,8 +1176,9 @@ Card wrapper with title and "empty" placeholder.### `blast-radius/direct-risks-table` — `DirectRisksTable`-Renders `DirectRiskEntry[]`. Multiplies `risk_score` and-`temporal_hotspot` by 10 for display (backend ships 0–1).+Renders `DirectRiskEntry[]`. `structural_score` is the raw, unbounded+pagerank-weighted-hotspot heuristic and is displayed in those units. Bars use+within-change relative share only; they do not invent a 0–10 scale.| Prop | Type | Required ||------|------|----------|diff --git a/packages/ui/__tests__/blast-radius/blast-radius.test.tsx b/packages/ui/__tests__/blast-radius/blast-radius.test.tsxindex 379857dfe..a6f877b2e 100644--- a/packages/ui/__tests__/blast-radius/blast-radius.test.tsx+++ b/packages/ui/__tests__/blast-radius/blast-radius.test.tsx@@ -15,6 +15,7 @@ const fixture: BlastRadiusResponse = {direct_risks: [{path: "src/auth/login.py",+ structural_score: 0.82,risk_score: 0.82,temporal_hotspot: 0.74,centrality: 0.045,@@ -102,19 +103,38 @@ const fixture: BlastRadiusResponse = {basis_categories: ["measured"],},},+ structural_impact_score: 7.6,+ structural_impact_band: "broad",+ structural_impact_scale: {+ field: "structural_impact_score",+ kind: "heuristic_structural_score",+ unit: "normalized_points",+ range: { minimum: 0, maximum: 10 },+ measures: "indexed structural exposure",+ deterministic: true,+ calibration: { status: "uncalibrated", source: null },+ authoritative_for_change_review: false,+ runtime_breakage_probability: false,+ },overall_risk_score: 7.6,+ overall_risk_score_compatibility: {+ deprecated: true,+ replacement: "structural_impact_score",+ equivalent_value: true,+ historical_meaning: "uncalibrated 0-10 structural blast-radius heuristic",+ },};describe("RiskScoreCard", () => {- it("labels High Risk for score >= 7", () => {- render(<RiskScoreCard score={7.6} />);- expect(screen.getByText("High Risk")).toBeTruthy();+ it("uses the server-provided broad structural band", () => {+ render(<RiskScoreCard score={7.6} band="broad" />);+ expect(screen.getByText("Broad structural impact")).toBeTruthy();expect(screen.getByText("7.6")).toBeTruthy();});- it("labels Low Risk for score < 4", () => {+ it("does not derive a risk band when a legacy caller omits one", () => {render(<RiskScoreCard score={2.1} />);- expect(screen.getByText("Low Risk")).toBeTruthy();+ expect(screen.getByText("Structural impact")).toBeTruthy();});});@@ -140,9 +160,9 @@ describe("TableSection", () => {});describe("DirectRisksTable", () => {- it("scales risk_score 0–1 → 0–10", () => {+ it("shows the raw structural weight instead of inventing a 0–10 scale", () => {render(<DirectRisksTable rows={fixture.direct_risks} />);- expect(screen.getByText("8.2")).toBeTruthy();+ expect(screen.getByText("0.8200")).toBeTruthy();expect(screen.getByText("7.4")).toBeTruthy();});});@@ -195,7 +215,7 @@ describe("BlastRadiusResults", () => {/>,);// Header band label + gauge score.- expect(screen.getByText("High risk")).toBeTruthy();+ expect(screen.getByText("Broad structural impact")).toBeTruthy();expect(screen.getByText("7.6")).toBeTruthy();// The header tile and the collapsible toggle share the "Direct risks" /// "Test gaps" copy, so each appears more than once.@@ -213,16 +233,19 @@ describe("BlastRadiusResults", () => {it("shows an empty impact map when nothing is affected", () => {const empty: BlastRadiusResponse = {+ ...fixture,direct_risks: [],transitive_affected: [],cochange_warnings: [],recommended_reviewers: [],test_gaps: [],+ structural_impact_score: 1.5,+ structural_impact_band: "localized",overall_risk_score: 1.5,};render(<BlastRadiusResults result={empty} />);expect(screen.getByText("No downstream impact found")).toBeTruthy();- expect(screen.getByText("Low risk")).toBeTruthy();+ expect(screen.getByText("Localized structural impact")).toBeTruthy();});it("keeps older server payloads compatible without assuming test availability", () => {diff --git a/packages/ui/__tests__/blast-radius/impact-view.test.tsx b/packages/ui/__tests__/blast-radius/impact-view.test.tsxindex b9a8102a4..91038b2ce 100644--- a/packages/ui/__tests__/blast-radius/impact-view.test.tsx+++ b/packages/ui/__tests__/blast-radius/impact-view.test.tsx@@ -7,7 +7,26 @@ import type { ImpactAdapter } from "../../src/blast-radius/impact-adapter.js";import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";const RESULT: BlastRadiusResponse = {+ structural_impact_score: 0.42,+ structural_impact_band: "localized",+ structural_impact_scale: {+ field: "structural_impact_score",+ kind: "heuristic_structural_score",+ unit: "normalized_points",+ range: { minimum: 0, maximum: 10 },+ measures: "indexed structural exposure",+ deterministic: true,+ calibration: { status: "uncalibrated", source: null },+ authoritative_for_change_review: false,+ runtime_breakage_probability: false,+ },overall_risk_score: 0.42,+ overall_risk_score_compatibility: {+ deprecated: true,+ replacement: "structural_impact_score",+ equivalent_value: true,+ historical_meaning: "uncalibrated 0-10 structural blast-radius heuristic",+ },direct_risks: [],transitive_affected: [],cochange_warnings: [],diff --git a/packages/ui/__tests__/git/risk-distribution-chart.test.tsx b/packages/ui/__tests__/git/risk-distribution-chart.test.tsxnew file mode 100644index 000000000..970ed2754--- /dev/null+++ b/packages/ui/__tests__/git/risk-distribution-chart.test.tsx@@ -0,0 +1,31 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import type { Hotspot } from "@repowise-dev/types/git";+import { RiskDistributionChart } from "../../src/git/risk-distribution-chart.js";++const hotspot: Hotspot = {+ file_path: "src/hot.py",+ commit_count_90d: 8,+ commit_count_30d: 3,+ churn_percentile: 80,+ temporal_hotspot_score: 4,+ primary_owner: "Dev",+ is_hotspot: true,+ is_stable: false,+ bus_factor: 1,+ contributor_count: 1,+ lines_added_90d: 20,+ lines_deleted_90d: 5,+ avg_commit_size: 4,+ commit_categories: {},+};++describe("RiskDistributionChart vocabulary", () => {+ it("labels its client-side scalar as an uncalibrated triage heuristic", () => {+ render(<RiskDistributionChart hotspots={[hotspot]} />);++ expect(screen.getByText(/Triage index \(0–100 heuristic\)/)).toBeTruthy();+ expect(screen.getByText(/Uncalibrated; not a probability/)).toBeTruthy();+ expect(screen.queryByText(/Risk Score/)).toBeNull();+ });+});diff --git a/packages/ui/src/blast-radius/blast-radius-header.tsx b/packages/ui/src/blast-radius/blast-radius-header.tsxindex 80ae191bd..eb069832c 100644--- a/packages/ui/src/blast-radius/blast-radius-header.tsx+++ b/packages/ui/src/blast-radius/blast-radius-header.tsx@@ -20,23 +20,23 @@ interface Band {ring: string;}-function band(score: number): Band {- if (score >= 7)+function band(value: BlastRadiusResponse["structural_impact_band"]): Band {+ if (value === "broad")return {- label: "High risk",+ label: "Broad structural impact",color: "var(--color-error)",text: "text-[var(--color-error)]",ring: "border-[var(--color-error)]/30 bg-[var(--color-error)]/5",};- if (score >= 4)+ if (value === "moderate")return {- label: "Medium risk",+ label: "Moderate structural impact",color: "var(--color-warning)",text: "text-[var(--color-warning)]",ring: "border-[var(--color-warning)]/30 bg-[var(--color-warning)]/5",};return {- label: "Low risk",+ label: "Localized structural impact",color: "var(--color-success)",text: "text-[var(--color-success)]",ring: "border-[var(--color-success)]/30 bg-[var(--color-success)]/5",@@ -69,9 +69,12 @@ function arcPath(return `M ${start.x} ${start.y} A ${r} ${r} 0 ${largeArc} 1 ${end.x} ${end.y}`;}-/** A 180° gauge that fills proportionally to the 0–10 score. */-function RiskGauge({ score }: { score: number }) {- const b = band(score);+/** A 180° gauge for the server-classified 0–10 structural heuristic. */+function StructuralImpactGauge({ score, impactBand }: {+ score: number;+ impactBand: BlastRadiusResponse["structural_impact_band"];+}) {+ const b = band(impactBand);const frac = Math.max(0, Math.min(1, score / 10));const valueEnd = 180 + frac * 180;return (@@ -187,7 +190,7 @@ function verdict(result: BlastRadiusResponse, changedCount: number): string {}/**- * The blast-radius headline: a risk gauge, four signal tiles, and a one-line+ * The blast-radius headline: a structural-impact gauge, four signal tiles, and a one-line* plain-English verdict — replacing the old centred-number card + flat stat* grid so the result reads as a conclusion, not a row of figures.*/@@ -195,10 +198,10 @@ export function BlastRadiusHeader({result,changedFiles = [],}: BlastRadiusHeaderProps) {- const b = band(result.overall_risk_score);+ const b = band(result.structural_impact_band);const tiles: Tile[] = [{- label: "Direct risks",+ label: "Changed files scored",value: result.direct_risks.length,icon: <AlertTriangle className="h-5 w-5" />,tone: "text-[var(--color-error)]",@@ -230,7 +233,10 @@ export function BlastRadiusHeader({return (<div className={cn("rounded-xl border p-4 sm:p-5", b.ring)}><div className="flex flex-col gap-5 sm:flex-row sm:items-center">- <RiskGauge score={result.overall_risk_score} />+ <StructuralImpactGauge+ score={result.structural_impact_score}+ impactBand={result.structural_impact_band}+ /><div className="min-w-0 flex-1 space-y-3"><div className="flex flex-wrap items-center gap-2">@@ -238,7 +244,7 @@ export function BlastRadiusHeader({{b.label}</span><span className="text-xs text-[var(--color-text-tertiary)]">- · blast radius of this change+ · uncalibrated structural heuristic, not breakage probability</span></div><p className="text-sm leading-relaxed text-[var(--color-text-secondary)]">diff --git a/packages/ui/src/blast-radius/direct-risks-table.tsx b/packages/ui/src/blast-radius/direct-risks-table.tsxindex 82c006e3e..e9b83e33b 100644--- a/packages/ui/src/blast-radius/direct-risks-table.tsx+++ b/packages/ui/src/blast-radius/direct-risks-table.tsx@@ -2,12 +2,13 @@import type { DirectRiskEntry } from "@repowise-dev/types/blast-radius";import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";-import { riskInk } from "../health/tokens";interface DirectRisksTableProps {rows: DirectRiskEntry[];}+type DisplayDirectRisk = DirectRiskEntry & { structuralShare: number };+/** A 0–1 value rendered as a labelled mini-bar so rows scan visually. */function MiniBar({value01,@@ -34,7 +35,7 @@ function MiniBar({);}-const COLUMNS: ResponsiveColumn<DirectRiskEntry>[] = [+const COLUMNS: ResponsiveColumn<DisplayDirectRisk>[] = [{key: "path",header: "File",@@ -48,17 +49,17 @@ const COLUMNS: ResponsiveColumn<DirectRiskEntry>[] = [),},{- key: "risk_score",- header: "Risk (0–10)",+ key: "structural_score",+ header: "Structural weight (raw)",headerClassName: "w-[28%]",render: (r) => (<MiniBar- value01={r.risk_score}- color={riskInk(r.risk_score)}- display={(r.risk_score * 10).toFixed(1)}+ value01={r.structuralShare}+ color="var(--color-accent-secondary)"+ display={r.structural_score.toFixed(4)}/>),- mobileRender: (r) => (r.risk_score * 10).toFixed(1),+ mobileRender: (r) => r.structural_score.toFixed(4),},{key: "temporal_hotspot",@@ -91,18 +92,24 @@ const COLUMNS: ResponsiveColumn<DirectRiskEntry>[] = [];/**- * Direct dependents of the changed files, sorted by risk. Each numeric column- * is an inline mini-bar (risk health-banded, hotspot/centrality neutral) so the- * heaviest rows pop without reading every figure.+ * Changed files sorted by raw structural weight. The bar is relative to the+ * strongest file in this change; the displayed value remains the unbounded raw+ * pagerank-weighted heuristic and is never presented as a 0–10 risk score.*/export function DirectRisksTable({ rows }: DirectRisksTableProps) {- const sorted = [...rows].sort((a, b) => b.risk_score - a.risk_score);+ const max = rows.reduce((value, row) => Math.max(value, row.structural_score), 0);+ const sorted: DisplayDirectRisk[] = rows+ .map((row) => ({+ ...row,+ structuralShare: max > 0 ? row.structural_score / max : 0,+ }))+ .sort((a, b) => b.structural_score - a.structural_score);return (<ResponsiveTablecolumns={COLUMNS}rows={sorted}rowKey={(r) => r.path}- caption="Direct risks for the changed files"+ caption="Structural weights for the changed files"bare/>);diff --git a/packages/ui/src/blast-radius/impact-graph.tsx b/packages/ui/src/blast-radius/impact-graph.tsxindex dc9eb8f70..c0f5f9b25 100644--- a/packages/ui/src/blast-radius/impact-graph.tsx+++ b/packages/ui/src/blast-radius/impact-graph.tsx@@ -22,10 +22,10 @@ function basename(path: string): string {return path.split("/").pop() || path;}-/** Health-band ink for a direct-risk node, mirroring the coupling vocabulary. */-function riskInk(risk: number): string {- if (risk >= 0.66) return "var(--color-error)";- if (risk >= 0.33) return "var(--color-warning)";+/** Within-change visual emphasis, not a public risk classification. */+function structuralInk(share: number): string {+ if (share >= 0.66) return "var(--color-error)";+ if (share >= 0.33) return "var(--color-warning)";return "var(--color-success)";}@@ -43,13 +43,17 @@ interface PlacedNode {/*** The impact map: changed files at the hub, direct risks on an inner ring- * (sized by centrality, health-banded, high-risk nodes haloed), and transitive+ * (sized by centrality, emphasized relative to the strongest changed file), and transitive* dependents on an outer ring graded by reach depth. Curved hairline edges and* faint ring guides give the blast radius a readable shape before the tables.*/export function ImpactGraph({ result, changedFiles }: ImpactGraphProps) {const { centre, direct, transitive, maxDepth, truncDirect, truncTrans } = useMemo(() => {const directRows = result.direct_risks.slice(0, MAX_DIRECT);+ const maxStructuralScore = directRows.reduce(+ (value, row) => Math.max(value, row.structural_score),+ 0,+ );const transitiveRows = result.transitive_affected.slice(0, MAX_TRANSITIVE);const depthCeil = Math.max(1,@@ -74,16 +78,18 @@ export function ImpactGraph({ result, changedFiles }: ImpactGraphProps) {const directNodes: PlacedNode[] = directRows.map((d, i) => {const angle = (i / Math.max(1, directRows.length)) * 2 * Math.PI - Math.PI / 2;+ const structuralShare =+ maxStructuralScore > 0 ? d.structural_score / maxStructuralScore : 0;const node: PlacedNode = {key: `d-${d.path}`,label: basename(d.path),- full: `${d.path} · risk ${(d.risk_score * 10).toFixed(1)} · centrality ${(d.centrality * 100).toFixed(0)}%`,+ full: `${d.path} · raw structural weight ${d.structural_score.toFixed(4)} · centrality ${(d.centrality * 100).toFixed(0)}%`,x: CX + Math.cos(angle) * INNER_R,y: CY + Math.sin(angle) * INNER_R,r: 5 + d.centrality * 6,- fill: riskInk(d.risk_score),+ fill: structuralInk(structuralShare),};- if (d.risk_score >= 0.66) node.glow = "var(--color-error)";+ if (structuralShare >= 0.66) node.glow = "var(--color-error)";return node;});@@ -209,11 +215,11 @@ export function ImpactGraph({ result, changedFiles }: ImpactGraphProps) {</span><span className="flex items-center gap-1.5"><span className="h-2.5 w-2.5 rounded-full bg-[var(--color-error)]" />- Direct, high risk+ Highest relative structural weight</span><span className="flex items-center gap-1.5"><span className="h-2.5 w-2.5 rounded-full bg-[var(--color-success)]" />- Direct, lower risk+ Lower relative structural weight</span><span className="flex items-center gap-1.5"><span className="h-2.5 w-2.5 rounded-full bg-[var(--color-text-secondary)]" />diff --git a/packages/ui/src/blast-radius/risk-score-card.tsx b/packages/ui/src/blast-radius/risk-score-card.tsxindex 1c9781e8e..c5b028b25 100644--- a/packages/ui/src/blast-radius/risk-score-card.tsx+++ b/packages/ui/src/blast-radius/risk-score-card.tsx@@ -1,28 +1,44 @@import { Card, CardContent } from "../ui/card";import { cn } from "../lib/cn";+import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";interface RiskScoreCardProps {- /** 0–10. */+ /** Uncalibrated structural-impact heuristic, 0–10. */score: number;+ /** Server-classified band. Omit for legacy payloads; no client threshold is inferred. */+ band?: BlastRadiusResponse["structural_impact_band"];}-export function RiskScoreCard({ score }: RiskScoreCardProps) {+/** Legacy component name retained for callers; copy uses structural semantics. */+export function RiskScoreCard({ score, band }: RiskScoreCardProps) {const tone =- score >= 7+ band === "broad"? {text: "text-[var(--color-error)]",card: "border-[var(--color-error)]/30 bg-[var(--color-error)]/5",}- : score >= 4+ : band === "moderate"? {text: "text-[var(--color-warning)]",card: "border-[var(--color-warning)]/30 bg-[var(--color-warning)]/5",}- : {+ : band === "localized"+ ? {text: "text-[var(--color-success)]",card: "border-[var(--color-success)]/30 bg-[var(--color-success)]/5",- };- const label = score >= 7 ? "High Risk" : score >= 4 ? "Medium Risk" : "Low Risk";+ }+ : {+ text: "text-[var(--color-info)]",+ card: "border-[var(--color-info)]/30 bg-[var(--color-info)]/5",+ };+ const label =+ band === "broad"+ ? "Broad structural impact"+ : band === "moderate"+ ? "Moderate structural impact"+ : band === "localized"+ ? "Localized structural impact"+ : "Structural impact";return (<Card className={cn("border", tone.card)}>@@ -32,7 +48,7 @@ export function RiskScoreCard({ score }: RiskScoreCardProps) {</span><span className={cn("text-sm font-medium", tone.text)}>{label}</span><span className="text-xs text-[var(--color-text-tertiary)]">- Overall Risk Score (0–10)+ Uncalibrated structural heuristic (0–10)</span></CardContent></Card>diff --git a/packages/ui/src/commits/commit-detail-card.tsx b/packages/ui/src/commits/commit-detail-card.tsxindex b3a0bff78..c8e5467ba 100644--- a/packages/ui/src/commits/commit-detail-card.tsx+++ b/packages/ui/src/commits/commit-detail-card.tsx@@ -21,21 +21,9 @@ export interface CommitDetailCardProps {/*** Drill-down for one commit.*- * Rebuilt on the section style, and reorganised around one rule: say each fact- * once. The card used to state the percentile four times over — a 24px- * `100%ile`, a priority pill, "Riskier than 100% of this repo's commits", and- * then "Riskier than most commits in this repo (100th percentile)" — with the- * summary paragraph restating the box immediately above it.- *- * What leads is now the raw score against this repo's own review line, for two- * reasons. The queue this sheet opens from already carries a percentile column- * per row, so repeating it here spends the largest figure on the page on- * something the reader just clicked past. And the percentile cannot honestly be- * turned into a rank: the raw score is rounded to one decimal before ranking,- * so 886 commits share 86 distinct percentiles, and "the 1st riskiest of 886"- * would be a computed guess printed as a measurement.- *- * The tercile still appears, once, as the badge beside the figure.+ * The benchmarked repo-relative percentile and its server-owned priority lead.+ * The supporting raw score remains visible with its per-commit unit and+ * diff-shape interpretation, never as a probability.*/export function CommitDetailCard({ commit, reviewCut, className }: CommitDetailCardProps) {const c = commit;@@ -84,12 +72,18 @@ export function CommitDetailCard({ commit, reviewCut, className }: CommitDetailC<div className="mt-7">{/* Named for what it measures: diff size, not danger. */}<PageLede- label="Diff-size score"- value={c.change_risk_score != null ? c.change_risk_score.toFixed(1) : "—"}- unit="out of 10"+ label="Review priority"+ value={`${Math.round(c.risk_percentile)}th`}+ unit="percentile in this repo"badge={<PriorityBadge priority={c.review_priority} />}><p>{riskSentence(c, reviewCut)}</p>+ {c.change_risk_score != null && (+ <p>+ Supporting diff-size score: {c.change_risk_score.toFixed(1)} out of 10,+ calibrated per commit and not a probability.+ </p>+ )}</PageLede></div>@@ -113,19 +107,16 @@ export function CommitDetailCard({ commit, reviewCut, className }: CommitDetailC/*** The sentence that makes the score mean something.*- * It leads with where the commit sits in this repo rather than with the raw- * number, because the raw number is anchored to a calibration corpus and skews- * high on any repo whose typical commit is large — this index has 296 of 884- * commits in the top tercile and a score distribution piled against the 10- * ceiling. The percentile is deliberately absent: the queue row the reader- * arrived from already carried it.+ * It explains where the commit sits in this repo. The headline already carries+ * the exact percentile; this sentence explains its tercile without inventing a+ * defect probability from the supporting model score.*/function riskSentence(c: CommitDetail, reviewCut: number | null | undefined): string {const tercile: Record<string, string> = {- high: "sits in the top third of this repo's own risk distribution, the band worth reviewing",+ high: "sits in the top third of this repo's own diff-shape distribution, the review-priority band worth reviewing",moderate:- "sits in the middle third of this repo's own risk distribution, so it is about as risky as the work around it",- low: "sits in the bottom third of this repo's own risk distribution",+ "sits in the middle third of this repo's own diff-shape distribution, so its review priority is typical here",+ low: "sits in the bottom third of this repo's own diff-shape distribution",};let out = `This commit ${tercile[c.review_priority] ?? tercile.moderate}`;@@ -139,7 +130,7 @@ function riskSentence(c: CommitDetail, reviewCut: number | null | undefined): stout += ".";if (c.change_risk_score != null) {- // `drivers` arrive strongest-first, and only the risk-raising ones explain+ // `drivers` arrive strongest-first, and only score-raising ones explain// why the score landed where it did.const raising = c.drivers.filter((d) => d.value !== null && d.contribution > 0);if (raising.length === 0) {diff --git a/packages/ui/src/commits/commit-distribution.tsx b/packages/ui/src/commits/commit-distribution.tsxindex f87803974..8865c9b0a 100644--- a/packages/ui/src/commits/commit-distribution.tsx+++ b/packages/ui/src/commits/commit-distribution.tsx@@ -12,7 +12,7 @@ export interface CommitDistributionProps {}/**- * The two views of how the change-risk score behaves in this repo.+ * Two views of how the supporting diff-shape score behaves in this repo.** They stay a pair. The histogram says where the tercile cuts fall, the* scatter says what commit shape lands you above them, and neither answers thediff --git a/packages/ui/src/commits/commit-risk-histogram.tsx b/packages/ui/src/commits/commit-risk-histogram.tsxindex 786a635af..c69f497ae 100644--- a/packages/ui/src/commits/commit-risk-histogram.tsx+++ b/packages/ui/src/commits/commit-risk-histogram.tsx@@ -6,7 +6,7 @@ import { cn } from "../lib/cn";/*** The distribution behind the review-priority terciles: how this repo's raw- * change-risk scores are actually spread, with the low/typical and+ * supporting diff-shape scores are actually spread, with the low/typical and* typical/elevated cut lines drawn on top.** Binned on the **raw 0-10 score**, never the percentile — percentile ranks@@ -90,7 +90,7 @@ export function CommitRiskHistogram({preserveAspectRatio="xMidYMid meet"className="h-auto w-full"role="img"- aria-label="Histogram of commit change-risk scores across the repository"+ aria-label="Histogram of supporting commit diff-shape scores across the repository">{/* Baseline + y axis, both recessive */}<line@@ -204,7 +204,7 @@ export function CommitRiskHistogram({fontSize="10"fill="var(--color-text-tertiary)">- Change-risk score →+ Supporting diff-shape score →</text></svg>diff --git a/packages/ui/src/commits/commit-table.tsx b/packages/ui/src/commits/commit-table.tsxindex 82532e1c9..4a076c333 100644--- a/packages/ui/src/commits/commit-table.tsx+++ b/packages/ui/src/commits/commit-table.tsx@@ -106,7 +106,7 @@ const COLUMNS: ResponsiveColumn<CommitRow>[] = [},{key: "risk",- header: "Risk",+ header: "Review priority",headerClassName: "w-28",// No ChurnBar. The cell was carrying the same fact three times over (a// filled bar, the percentile, and the pill), and because the queue sorts@@ -116,14 +116,14 @@ const COLUMNS: ResponsiveColumn<CommitRow>[] = [render: (c) => (<div className="flex items-center gap-2"><span className="w-8 text-xs tabular-nums text-[var(--color-text-tertiary)]">- {Math.round(c.risk_percentile)}%+ {Math.round(c.risk_percentile)}th</span><PriorityBadge priority={c.review_priority as ReviewPriority} /></div>),mobileRender: (c) => (<span className="inline-flex items-center gap-2">- <span className="tabular-nums">{Math.round(c.risk_percentile)}%</span>+ <span className="tabular-nums">{Math.round(c.risk_percentile)}th</span><PriorityBadge priority={c.review_priority as ReviewPriority} /></span>),@@ -148,7 +148,7 @@ const COLUMNS: ResponsiveColumn<CommitRow>[] = [/*** The review-priority queue: per-commit change-risk, ranked. Ordering is* server-driven (risk vs date); search + priority filters are client-side over- * the loaded page. Risk is shown as a **repo-relative** percentile + priority,+ * the loaded page. Review priority is shown as a **repo-relative** percentile + category,* so the column is portable across repos.*/export function CommitTable({diff --git a/packages/ui/src/dashboard/commits-mini.tsx b/packages/ui/src/dashboard/commits-mini.tsxindex 9903fab7d..236f10c9c 100644--- a/packages/ui/src/dashboard/commits-mini.tsx+++ b/packages/ui/src/dashboard/commits-mini.tsx@@ -11,6 +11,7 @@ export interface CommitsMiniEntry {committed_at: string | null;change_risk_level?: string | null;risk_percentile?: number | null;+ review_priority?: string | null;}interface CommitsMiniProps {@@ -72,9 +73,16 @@ export function CommitsMini({ commits, repoId, linkPrefix, previewCount = 8 }: C><spanclassName={`h-2 w-2 rounded-full shrink-0 ${- RISK_DOT[c.change_risk_level ?? ""] ?? "bg-[var(--color-text-tertiary)]"+ RISK_DOT[c.review_priority ?? c.change_risk_level ?? ""] ??+ "bg-[var(--color-text-tertiary)]"}`}- title={c.change_risk_level ? `${c.change_risk_level} change risk` : undefined}+ title={+ c.review_priority+ ? `${c.review_priority} repo-relative review priority`+ : c.change_risk_level+ ? `${c.change_risk_level} absolute per-commit fallback band`+ : undefined+ }/><span className="text-xs font-mono text-[var(--color-text-tertiary)] shrink-0">{c.short_sha}diff --git a/packages/ui/src/git/risk-distribution-chart.tsx b/packages/ui/src/git/risk-distribution-chart.tsxindex 355cce1ee..3006a38f2 100644--- a/packages/ui/src/git/risk-distribution-chart.tsx+++ b/packages/ui/src/git/risk-distribution-chart.tsx@@ -24,14 +24,14 @@ interface RiskDistributionChartProps {maxBars?: number;}-function computeRiskScore(h: Hotspot): number {+function computeTriageIndex(h: Hotspot): number {const churn = h.churn_percentile / 100;const busFactor = h.bus_factor <= 1 ? 1 : h.bus_factor === 2 ? 0.5 : 0;const trend = Math.min(1, (h.temporal_hotspot_score ?? 0) / 10);return Math.round((churn * 0.4 + busFactor * 0.35 + trend * 0.25) * 100);}-function riskColor(score: number): string {+function triageColor(score: number): string {return riskInk(score / 100);}@@ -41,24 +41,30 @@ export function RiskDistributionChart({ hotspots, maxBars = 30 }: RiskDistributi.map((h) => ({name: h.file_path.split("/").pop() ?? h.file_path,fullPath: h.file_path,- risk: computeRiskScore(h),+ triageIndex: computeTriageIndex(h),churn: Math.round(h.churn_percentile),busFactor: h.bus_factor,}))- .sort((a, b) => b.risk - a.risk)+ .sort((a, b) => b.triageIndex - a.triageIndex).slice(0, maxBars);}, [hotspots, maxBars]);if (data.length === 0) return null;- const avgRisk = Math.round(data.reduce((s, d) => s + d.risk, 0) / data.length);+ const averageIndex = Math.round(+ data.reduce((sum, row) => sum + row.triageIndex, 0) / data.length,+ );const truncated = hotspots.length > data.length;return (<div className="w-full">+ <p className="mb-1 text-[10px] text-[var(--color-text-tertiary)]">+ Triage index (0–100 heuristic): 40% churn percentile + 35% bus-factor tier ++ 25% temporal activity. Uncalibrated; not a probability.+ </p>{truncated && (<p className="text-[10px] text-[var(--color-text-tertiary)] mb-1 text-right tabular-nums">- Showing top {data.length} of {hotspots.length.toLocaleString()} by risk score+ Showing top {data.length} of {hotspots.length.toLocaleString()} by triage index</p>)}<ResponsiveContainer width="100%" height={Math.max(200, data.length * 22 + 40)}>@@ -91,18 +97,18 @@ export function RiskDistributionChart({ hotspots, maxBars = 30 }: RiskDistributifontSize: 11,color: "var(--color-text-primary)",}}- formatter={(value) => [`${typeof value === "number" ? value : 0}`, "Risk Score"]}+ formatter={(value) => [`${typeof value === "number" ? value : 0}`, "Triage index"]}labelFormatter={(label) => String(label)}/><ReferenceLine- x={avgRisk}+ x={averageIndex}stroke="var(--color-text-tertiary)"strokeDasharray="4 4"- label={{ value: `avg ${avgRisk}`, position: "top", fontSize: 9, fill: "var(--color-text-tertiary)" }}+ label={{ value: `avg ${averageIndex}`, position: "top", fontSize: 9, fill: "var(--color-text-tertiary)" }}/>- <Bar dataKey="risk" radius={[0, 4, 4, 0]}>+ <Bar dataKey="triageIndex" radius={[0, 4, 4, 0]}>{data.map((entry, idx) => (- <Cell key={idx} fill={riskColor(entry.risk)} fillOpacity={0.85} />+ <Cell key={idx} fill={triageColor(entry.triageIndex)} fillOpacity={0.85} />))}</Bar></BarChart>diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.tsindex b63f12695..8295f9dff 100644--- a/packages/ui/src/health/ai-prompt-builder.ts+++ b/packages/ui/src/health/ai-prompt-builder.ts@@ -421,7 +421,7 @@ export function buildCoverageAiPrompt({: null,row.nloc ? `File size: ${row.nloc} NLOC` : null,row.health_score != null- ? `Current health score: ${row.health_score.toFixed(1)}/10 — risky changes here are likely to break things, so tests pay off.`+ ? `Current health score: ${row.health_score.toFixed(1)}/10 — stronger defect indicators make focused tests especially valuable.`: null,row.module ? `Module: \`${row.module}\`` : null,row.source_format ? `Coverage source: ${row.source_format.toUpperCase()}` : null,@@ -1245,7 +1245,7 @@ export function buildCommitAiPrompt({const short = c.sha.slice(0, 10);const constraintList = [- "Read the diff first. The risk score is a prior, not a verdict — a high score on a mechanical rename is fine; a low score hiding a logic change is not.",+ "Read the diff first. The calibrated diff-size score is supporting evidence, not a verdict — a high score on a mechanical rename is fine; a low score hiding a logic change is not.","Focus on what the change-risk drivers flag: scattered edits, missing tests, a hotspot touch, a new-to-the-area author. Confirm each against the actual diff.","Check the blast radius: what depends on the changed files, and is anything that usually changes with them missing from this commit?","Call out missing or weak test coverage for the behavior this commit changes.",@@ -1274,8 +1274,8 @@ export function buildCommitAiPrompt({c.author_name ? `Author: ${c.author_name}` : null,c.is_fix ? "Tagged as a bug-fix commit." : null,c.review_priority ? `Review priority (repo-relative): **${c.review_priority}**` : null,- c.risk_percentile != null ? `Risk percentile in this repo: ${Math.round(c.risk_percentile)}th` : null,- c.change_risk_score != null ? `Raw change-risk score: ${c.change_risk_score.toFixed(1)}/10` : null,+ c.risk_percentile != null ? `Diff-shape percentile in this repo: ${Math.round(c.risk_percentile)}th` : null,+ c.change_risk_score != null ? `Supporting diff-size score: ${c.change_risk_score.toFixed(1)}/10 (calibrated per commit)` : null,c.files_changed != null ? `Files changed: ${c.files_changed}` : null,c.lines_added != null || c.lines_deleted != null? `Lines: +${c.lines_added ?? 0} / −${c.lines_deleted ?? 0}`diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsxindex edceeb432..6ac587261 100644--- a/packages/ui/src/health/coverage-view.tsx+++ b/packages/ui/src/health/coverage-view.tsx@@ -377,7 +377,7 @@ function CoverageBody({<OverviewSectiontitle="Health against coverage"- description="Every instrumented file placed by its defect-risk score and its line coverage, sized by lines of code. The bottom-left quadrant is the one that costs money: code we score as weak, with no test watching it. Click a file to open its line-level heatmap."+ description="Every instrumented file placed by its 0–10 defect-health score (higher is healthier) and its line coverage, sized by lines of code. The bottom-left quadrant is the one that costs money: code we score as weak, with no test watching it. Click a file to open its line-level heatmap."><RiskCoverageScatterpoints={scatterPoints}diff --git a/packages/ui/src/health/inferred-tests-view.tsx b/packages/ui/src/health/inferred-tests-view.tsxindex c5feabf0f..71fcb85ad 100644--- a/packages/ui/src/health/inferred-tests-view.tsx+++ b/packages/ui/src/health/inferred-tests-view.tsx@@ -184,7 +184,7 @@ export function InferredTestsView({<OverviewSectiontitle="Health against tests"- description="Every file placed by its defect-risk score, split by whether any test reaches it, sized by lines of code. There is no percentage axis here because there is no line-level evidence to build one from. The left column is the page: weak code nothing runs. Click a file to open it."+ description="Every file placed by its 0–10 defect-health score (higher is healthier), split by whether any test reaches it, sized by lines of code. There is no percentage axis here because there is no line-level evidence to build one from. The left column is the page: weak code nothing runs. Click a file to open it."><RiskCoverageScatterbasis="inferred"diff --git a/packages/ui/src/health/kpi-cards.tsx b/packages/ui/src/health/kpi-cards.tsxindex ff8dad398..70739b168 100644--- a/packages/ui/src/health/kpi-cards.tsx+++ b/packages/ui/src/health/kpi-cards.tsx@@ -356,7 +356,7 @@ function PerformanceTile({</span></div><p className="mt-1.5 text-xs text-[var(--color-text-tertiary)] tabular-nums">- Risk score {score.toFixed(1)}/10+ Performance health {score.toFixed(1)}/10 (higher is healthier)</p></>) : (@@ -370,7 +370,7 @@ function PerformanceTile({</span></div><p className="mt-1.5 inline-flex items-center gap-1.5 text-xs tabular-nums text-[var(--color-text-tertiary)]">- Risk score {score.toFixed(1)}/10+ Performance health {score.toFixed(1)}/10 (higher is healthier){band ? (<span className={`font-semibold uppercase tracking-wide ${healthBandTextColor(band)}`}>{HEALTH_BAND_LABEL[band]}diff --git a/packages/ui/src/health/risk-coverage-scatter.tsx b/packages/ui/src/health/risk-coverage-scatter.tsxindex 0e2241e72..56a8f399b 100644--- a/packages/ui/src/health/risk-coverage-scatter.tsx+++ b/packages/ui/src/health/risk-coverage-scatter.tsx@@ -26,7 +26,7 @@ export interface RiskCoverageScatterProps {}/**- * Health × tests. Y is the defect-risk score (0 to 10, higher is better) and+ * Health × tests. Y is the defect-health score (0 to 10, higher is healthier) and* dot radius encodes lines of code on both bases. What X means depends on which* signal answered, and that is the whole design.*diff --git a/packages/vscode/README.md b/packages/vscode/README.mdindex d8ecc883a..c0a93837f 100644--- a/packages/vscode/README.md+++ b/packages/vscode/README.md@@ -16,7 +16,7 @@ Everything runs on your machine. Everything is free.Click **Analyze Change Risk** in the Source Control view and get the full picture of your uncommitted work in seconds:-- A risk score for the change, with the exact factors that move it.+- A benchmarked repo-relative review priority, with the supporting diff-shape score and exact factors that move it.- **The riskiest files in your change**, ranked, so you know where to focus your own review first.- **What is downstream**: the files that depend on what you touched.- **What you might have forgotten**: files that historically change together with yours but are untouched, plus measured and inferred test recommendations with explicit analysis state.diff --git a/packages/vscode/package.json b/packages/vscode/package.jsonindex dfdccf7da..1f4ca536a 100644--- a/packages/vscode/package.json+++ b/packages/vscode/package.json@@ -403,8 +403,8 @@"icon": "$(pulse)","tags": ["repowise"],"when": "repowise.agentToolsEnabled",- "modelDescription": "Report on the current branch's changes against a base branch. Lead with fix_history: the recency-weighted bug-fix record of the files touched, which is what separates a small dangerous change from a large boring one. The 0-10 score measures diff size and spread, not danger. Use it after making changes to judge whether the change set needs extra review or tests before pushing.",- "userDescription": "Defect risk score for the current branch.",+ "modelDescription": "Report on the current branch's changes against a base branch. Lead with the benchmarked repo-relative percentile and classification. Fix history is separate historical evidence; the supporting 0-10 score measures diff size and spread and is not a probability. Use it after making changes to judge whether the change set needs extra review or tests before pushing.",+ "userDescription": "Repo-relative review priority for the current branch.","inputSchema": {"type": "object","properties": {diff --git a/packages/vscode/src/features/lmTools.ts b/packages/vscode/src/features/lmTools.tsindex f7ba907f2..a2ae2b5cb 100644--- a/packages/vscode/src/features/lmTools.ts+++ b/packages/vscode/src/features/lmTools.ts@@ -251,6 +251,7 @@ export function registerLmTools(ctx: RepowiseContext): vscode.Disposable {// First, because the score below measures diff size rather than danger,// and a model handed only the score will read it as a verdict.fix_history: result.fix_history,+ risk_authority: result.risk_authority,score: result.score,score_measures: result.score_measures,score_unit: result.score_unit,diff --git a/packages/vscode/webview/src/changeImpact.test.ts b/packages/vscode/webview/src/changeImpact.test.tsindex aa52bcd88..e1a946937 100644--- a/packages/vscode/webview/src/changeImpact.test.ts+++ b/packages/vscode/webview/src/changeImpact.test.ts@@ -28,7 +28,26 @@ function report(cochange_warnings,recommended_reviewers: [],test_gaps: [],+ structural_impact_score: 0,+ structural_impact_band: "localized",+ structural_impact_scale: {+ field: "structural_impact_score",+ kind: "heuristic_structural_score",+ unit: "normalized_points",+ range: { minimum: 0, maximum: 10 },+ measures: "indexed structural exposure",+ deterministic: true,+ calibration: { status: "uncalibrated", source: null },+ authoritative_for_change_review: false,+ runtime_breakage_probability: false,+ },overall_risk_score: 0,+ overall_risk_score_compatibility: {+ deprecated: true,+ replacement: "structural_impact_score",+ equivalent_value: true,+ historical_meaning: "uncalibrated structural heuristic",+ },},...rest,};diff --git a/packages/vscode/webview/src/views/risk/App.test.tsx b/packages/vscode/webview/src/views/risk/App.test.tsxindex 25e487b4b..d9585813a 100644--- a/packages/vscode/webview/src/views/risk/App.test.tsx+++ b/packages/vscode/webview/src/views/risk/App.test.tsx@@ -26,6 +26,14 @@ const REPORT: RiskRangeReport = {percentile: 74,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",+ fallback_field: "fallback_band",+ fallback_basis: "absolute_model_score_band",+ score_role: "supporting_diff_shape_signal",+ },score: 7.4,score_measures: "diff size and spread; not where the change lands",score_unit: "per-commit",@@ -82,12 +90,14 @@ const IMPACT: ChangeImpactReport = {direct_risks: [{path: "src/a.ts",+ structural_score: 0.3,risk_score: 0.3,temporal_hotspot: 0.1,centrality: 0.8,},{path: "src/b.ts",+ structural_score: 0.82,risk_score: 0.82,temporal_hotspot: 0.9,centrality: 0.1,@@ -162,7 +172,26 @@ const IMPACT: ChangeImpactReport = {basis_categories: ["measured"],},},+ structural_impact_score: 5.6,+ structural_impact_band: "moderate",+ structural_impact_scale: {+ field: "structural_impact_score",+ kind: "heuristic_structural_score",+ unit: "normalized_points",+ range: { minimum: 0, maximum: 10 },+ measures: "indexed structural exposure",+ deterministic: true,+ calibration: { status: "uncalibrated", source: null },+ authoritative_for_change_review: false,+ runtime_breakage_probability: false,+ },overall_risk_score: 5.6,+ overall_risk_score_compatibility: {+ deprecated: true,+ replacement: "structural_impact_score",+ equivalent_value: true,+ historical_meaning: "uncalibrated 0-10 structural blast-radius heuristic",+ },},reviewers: [{@@ -311,11 +340,11 @@ describe("risk App", () => {);expect(- await screen.findByText("Riskiest files in this change"),+ await screen.findByText("Highest structural weight in this change"),).toBeTruthy();expect(screen.getByText("hotspot")).toBeTruthy();const bars = screen.getAllByTitle(- "Risk relative to the riskiest file in this change",+ "Structural weight relative to the strongest file in this change",);expect(bars).toHaveLength(2);// Sorted riskiest first: b.ts (0.82) gets the full bar, a.ts a partial one.diff --git a/packages/vscode/webview/src/views/risk/App.tsx b/packages/vscode/webview/src/views/risk/App.tsxindex e044ce21f..f0715197d 100644--- a/packages/vscode/webview/src/views/risk/App.tsx+++ b/packages/vscode/webview/src/views/risk/App.tsx@@ -48,10 +48,10 @@ const FEATURE_LABELS: ReadonlyArray<readonly [string, string]> = [type Tone = "low" | "medium" | "high";-/** Buckets a 0-10 score into the three risk tones the palette defines. */-function scoreTone(score: number): Tone {- if (score >= 6.5) return "high";- if (score >= 3.5) return "medium";+/** Maps the server's authoritative absolute fallback band to presentation. */+function fallbackBandTone(band: string | null): Tone {+ if (band === "high") return "high";+ if (band === "moderate") return "medium";return "low";}@@ -79,7 +79,7 @@ function scrollToSection(id: string) {?.scrollIntoView({ behavior: "smooth", block: "start" });}-/** Formats a contribution with an explicit sign (positive raises risk). */+/** Formats a contribution with an explicit sign (positive raises the model score). */function signed(value: number): string {return `${value >= 0 ? "+" : "−"}${Math.abs(value).toFixed(2)}`;}@@ -125,7 +125,7 @@ export function App({ host, repo, refreshToken }: ViewProps<"risk">) {),).finally(() => setLoading(false));- // Impact is independent: a git-less workspace still shows the risk score.+ // Structural impact is independent: a git-less workspace still shows it.host.api.changeImpact().then((r) => setImpact(r))@@ -249,7 +249,7 @@ function ScoreHero({ report }: { report: RiskRangeReport }) {const ranked = percentile != null && priority != null;const color = ranked? TONE_VAR[PRIORITY_TONE[priority] ?? "medium"]- : TONE_VAR[scoreTone(r.score)];+ : TONE_VAR[fallbackBandTone(r.fallback_band)];return (<PageLede// Not "Change risk" again: the page's h1 two lines above already says@@ -261,7 +261,7 @@ function ScoreHero({ report }: { report: RiskRangeReport }) {band={ranked? { label: `${ordinal(percentile)} percentile`, color }- : { label: `${r.fallback_band ?? "unranked"} risk`, color }+ : { label: `${r.fallback_band ?? "unranked"} absolute per-commit band`, color }}layout="beside"badge={@@ -590,7 +590,7 @@ function ChangeImpact({? "Test analysis is partial; recommendations may not cover every evidence input.": "Recommendations keep measured coverage evidence separate from structural inference.";const reviewers = impact.reviewers;- const overall = blast?.overall_risk_score ?? null;+ const structuralImpact = blast?.structural_impact_score ?? null;const scopeLabel =impact.scope === "branch" ? "uncommitted and unpushed" : "uncommitted";@@ -602,11 +602,12 @@ function ChangeImpact({<span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">{impact.changed.length} {scopeLabel} file{impact.changed.length === 1 ? "" : "s"}- {overall != null && (+ {structuralImpact != null && (<>{" · "}<span className="font-medium text-[var(--color-text-secondary)]">- impact {overall.toFixed(1)}/10+ structural impact {structuralImpact.toFixed(1)}/10 (+ {blast?.structural_impact_band}; heuristic)</span></>)}@@ -618,8 +619,8 @@ function ChangeImpact({<ImpactBlockid={SECTION_IDS.directRisks}icon={<Gauge className="h-4 w-4" />}- title="Riskiest files in this change"- hint="Per-file risk from history and structure. Start your review here."+ title="Highest structural weight in this change"+ hint="Relative pagerank-weighted hotspot heuristic. It is not a breakage probability.">{directRisks.slice(0, 10).map((f) => (<DirectRiskRow@@ -814,7 +815,7 @@ function DirectRiskRow({)}<spanclassName="h-1.5 w-16 shrink-0 overflow-hidden rounded-full bg-[var(--color-bg-elevated)]"- title="Risk relative to the riskiest file in this change"+ title="Structural weight relative to the strongest file in this change"><spanclassName="block h-full rounded-full"diff --git a/packages/vscode/webview/src/views/risk/selectors.test.ts b/packages/vscode/webview/src/views/risk/selectors.test.tsindex 46c97454c..209b7f5fa 100644--- a/packages/vscode/webview/src/views/risk/selectors.test.ts+++ b/packages/vscode/webview/src/views/risk/selectors.test.ts@@ -18,7 +18,26 @@ function report(direct_risks: DirectRiskEntry[] = [], blast = true): ChangeImpaccochange_warnings: [],recommended_reviewers: [],test_gaps: [],+ structural_impact_score: 0,+ structural_impact_band: "localized",+ structural_impact_scale: {+ field: "structural_impact_score",+ kind: "heuristic_structural_score",+ unit: "normalized_points",+ range: { minimum: 0, maximum: 10 },+ measures: "indexed structural exposure",+ deterministic: true,+ calibration: { status: "uncalibrated", source: null },+ authoritative_for_change_review: false,+ runtime_breakage_probability: false,+ },overall_risk_score: 0,+ overall_risk_score_compatibility: {+ deprecated: true,+ replacement: "structural_impact_score",+ equivalent_value: true,+ historical_meaning: "uncalibrated structural heuristic",+ },}: null,};@@ -28,8 +47,8 @@ describe("selectDirectRisks", () => {it("ranks riskiest first with shares relative to the set maximum", () => {const out = selectDirectRisks(report([- { path: "a.ts", risk_score: 0.005, temporal_hotspot: 0, centrality: 0.005 },- { path: "b.ts", risk_score: 0.02, temporal_hotspot: 0, centrality: 0.02 },+ { path: "a.ts", structural_score: 0.005, risk_score: 0.005, temporal_hotspot: 0, centrality: 0.005 },+ { path: "b.ts", structural_score: 0.02, risk_score: 0.02, temporal_hotspot: 0, centrality: 0.02 },]),);expect(out.map((r) => r.path)).toEqual(["b.ts", "a.ts"]);@@ -40,8 +59,8 @@ describe("selectDirectRisks", () => {it("flags hotspots only above the floor", () => {const out = selectDirectRisks(report([- { path: "hot.ts", risk_score: 0.01, temporal_hotspot: 0.9, centrality: 0.005 },- { path: "quiet.ts", risk_score: 0.01, temporal_hotspot: 0.2, centrality: 0.005 },+ { path: "hot.ts", structural_score: 0.01, risk_score: 0.01, temporal_hotspot: 0.9, centrality: 0.005 },+ { path: "quiet.ts", structural_score: 0.01, risk_score: 0.01, temporal_hotspot: 0.2, centrality: 0.005 },]),);expect(out.find((r) => r.path === "hot.ts")?.hotspot).toBe(true);@@ -50,7 +69,7 @@ describe("selectDirectRisks", () => {it("serves zero shares when every risk score is zero", () => {const out = selectDirectRisks(- report([{ path: "a.ts", risk_score: 0, temporal_hotspot: 0, centrality: 0 }]),+ report([{ path: "a.ts", structural_score: 0, risk_score: 0, temporal_hotspot: 0, centrality: 0 }]),);expect(out[0]?.share).toBe(0);});diff --git a/packages/vscode/webview/src/views/risk/selectors.ts b/packages/vscode/webview/src/views/risk/selectors.tsindex e3c1842bf..86ddbb44b 100644--- a/packages/vscode/webview/src/views/risk/selectors.ts+++ b/packages/vscode/webview/src/views/risk/selectors.ts@@ -7,29 +7,29 @@ import type { ChangeImpactReport } from "../../../../src/shared/webviewMessages"/*** Temporal-hotspot fraction above which a file earns the quiet hotspot marker.- * The per-file risk score itself is centrality-weighted and unbounded, so rows+ * The per-file structural weight is centrality-weighted and unbounded, so rows* carry a share relative to the riskiest file instead of an absolute scale.*/export const HOTSPOT_FLOOR = 0.6;-/** One changed file ranked by its blast-radius risk. */+/** One changed file ranked by its raw blast-radius structural weight. */export interface RankedDirectRisk {/** Repo-relative path of the changed file. */path: string;- /** Risk relative to the riskiest file in this change, 0 to 1. */+ /** Structural weight relative to the strongest changed file, 0 to 1. */share: number;/** True when git history marks the file as a temporal hotspot. */hotspot: boolean;}-/** Ranks the blast response's per-file risks for display, riskiest first. */+/** Ranks per-file structural weights for display, strongest first. */export function selectDirectRisks(report: ChangeImpactReport): RankedDirectRisk[] {const risks = report.blast?.direct_risks ?? [];- const max = risks.reduce((m, d) => Math.max(m, d.risk_score), 0);+ const max = risks.reduce((m, d) => Math.max(m, d.structural_score), 0);return risks.map((d) => ({path: d.path,- share: max > 0 ? d.risk_score / max : 0,+ share: max > 0 ? d.structural_score / max : 0,hotspot: d.temporal_hotspot >= HOTSPOT_FLOOR,})).sort((a, b) => b.share - a.share);diff --git a/packages/web/README.md b/packages/web/README.mdindex 82ee05d8d..f8b7eb315 100644--- a/packages/web/README.md+++ b/packages/web/README.md@@ -100,7 +100,7 @@ Lists extracted architectural decision records with health metrics. Each decisio### Blast Radius (`/repos/[id]/blast-radius`)-Pre-PR impact estimator. Paste a list of changed file paths (one per line) — or click hotspot suggestion chips to prefill — and get an overall risk score (0–10), breakdown of direct risks (per-file risk score, temporal hotspot, centrality), transitive affected files with depth, co-change warnings (files that historically change together but aren't in the diff), recommended reviewers ranked by ownership, and test gaps for code paths without coverage.+Pre-PR structural-impact estimator. Paste changed file paths (one per line) — or click hotspot suggestions — and get an uncalibrated structural-impact score (0–10 normalized points), raw direct structural weights, transitive affected files with depth, historical co-change warnings, recommended reviewers, and explicit test-analysis state. The structural score is not a runtime-breakage probability or the authoritative live change-risk signal.### Cost Tracking (`/repos/[id]/costs`)diff --git a/plugins/claude-code/README.md b/plugins/claude-code/README.mdindex aae12dda0..689ab9138 100644--- a/plugins/claude-code/README.md+++ b/plugins/claude-code/README.md@@ -57,7 +57,7 @@ defect-validated score from deterministic markers).| `/repowise:health` | Code-health KPIs, lowest-scoring files, refactoring targets, trends || `/repowise:coverage` | Ingest or inspect coverage reports (lights up untested hotspots + per-test map) || `/repowise:impacted-tests` | Tests whose coverage intersects a change (commit / range / staged) |-| `/repowise:risk` | Defect-risk score for a change (commit or `base..head` range) |+| `/repowise:risk` | Repo-relative review priority plus a supporting diff-shape score || `/repowise:security` | Full-history secret scan (`repowise security scan --history`) || `/repowise:dead-code` | Unreachable files, unused exports, zombie packages by confidence || `/repowise:export` | Export wiki pages or a Structurizr architecture model |@@ -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` | Whole-change defect-risk score for a commit or `base..head` range |+| `get_change_risk` | Benchmarked live-change percentile/classification plus supporting diff-shape score || `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/impacted-tests.md b/plugins/claude-code/commands/impacted-tests.mdindex e637a85be..df16255a6 100644--- a/plugins/claude-code/commands/impacted-tests.md+++ b/plugins/claude-code/commands/impacted-tests.md@@ -45,5 +45,5 @@ repowise impacted-tests main..HEAD --format list | xargs pytestguess). Report them as candidates. Only `via: coverage` proves a testexecuted the change.- A file none of those can speak to is "unknown, run the full suite".-- For a whole-change defect-risk score, use `/repowise:risk`. For per-file+- For a whole-change repo-relative review priority, use `/repowise:risk`. For per-fileblast radius / `tests_to_run`, use the `get_risk` MCP tool.diff --git a/plugins/claude-code/commands/risk.md b/plugins/claude-code/commands/risk.mdindex 49c502b6f..6f09c919c 100644--- a/plugins/claude-code/commands/risk.md+++ b/plugins/claude-code/commands/risk.md@@ -1,17 +1,17 @@----description: Score the defect risk of a change — a commit or a base..head range — as a single 0–10 with drivers.+description: Rank a live change for review using a repo-relative percentile and an auditable supporting diff-shape score.allowed-tools: Bash, Read---# Repowise Risk-Score a *change* (not a file) for defect risk. The response leads with+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 changetouches, which of them carry it, and where that sits among the repo's own-recent commits. The 0–10 score sits beside it and measures diff size and-spread (named in `score_measures`) rather than danger, so read the fix history-first. Pure git + learned constants: no LLM, no network. A natural pre-merge /-PR gate.+recent commits. The supporting 0–10 score measures diff size and spread (named+in `score_measures`) rather than danger and is not a probability. Pure git ++learned constants: no LLM, no network. A natural pre-merge / PR gate.## Steps@@ -36,7 +36,7 @@ Useful flags:## How this differs from the other risk views-- This command = the **whole change** as one number (defect-risk gate).-- For **per-file** blast radius (what breaks, missing co-changes, missing tests),+- This command = the **whole change** ranked against recent repository history.+- For **per-file** structural reach, missing co-changes, and missing tests,use the `get_risk` MCP tool / the `change-review` skill.- For **per-file health** scores, use `/repowise:health`.diff --git a/plugins/claude-code/commands/security.md b/plugins/claude-code/commands/security.mdindex 7280c7c4c..547e134ad 100644--- a/plugins/claude-code/commands/security.md+++ b/plugins/claude-code/commands/security.md@@ -49,4 +49,4 @@ repowise security scan --history --all-patterns --output json(`hardcoded_password` / `hardcoded_secret`) to avoid noise. Pass`--all-patterns` for code-smell patterns (`eval`, `os.system`, weak hashes, …).- Never invent findings. If the scan stores zero findings, say so plainly.-- For change defect risk (not secret scanning), use `/repowise:risk`.+- For live-change review priority (not secret scanning), use `/repowise:risk`.diff --git a/plugins/shared/commands/impacted-tests.md b/plugins/shared/commands/impacted-tests.mdindex fb6c929c1..b5c576dcf 100644--- a/plugins/shared/commands/impacted-tests.md+++ b/plugins/shared/commands/impacted-tests.md@@ -46,5 +46,5 @@ repowise impacted-tests main..HEAD --format list | xargs pytestguess). Report them as candidates. Only `via: coverage` proves a testexecuted the change.- A file none of those can speak to is "unknown, run the full suite".-- For a whole-change defect-risk score, use `{{cmd:risk}}`. For per-file+- For a whole-change repo-relative review priority, use `{{cmd:risk}}`. For per-fileblast radius / `tests_to_run`, use the `get_risk` MCP tool.diff --git a/plugins/shared/commands/risk.md b/plugins/shared/commands/risk.mdindex b773b10f6..45d93b595 100644--- a/plugins/shared/commands/risk.md+++ b/plugins/shared/commands/risk.md@@ -1,18 +1,18 @@---frontmatter: |- description: Score the defect risk of a change — a commit or a base..head range — as a single 0–10 with drivers.+ description: Rank a live change for review using a repo-relative percentile and an auditable supporting diff-shape score.allowed-tools: Bash, Read---# Repowise Risk-Score a *change* (not a file) for defect risk. The response leads with+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 changetouches, which of them carry it, and where that sits among the repo's own-recent commits. The 0–10 score sits beside it and measures diff size and-spread (named in `score_measures`) rather than danger, so read the fix history-first. Pure git + learned constants: no LLM, no network. A natural pre-merge /-PR gate.+recent commits. The supporting 0–10 score measures diff size and spread (named+in `score_measures`) rather than danger and is not a probability. Pure git ++learned constants: no LLM, no network. A natural pre-merge / PR gate.## Steps@@ -37,7 +37,7 @@ Useful flags:## How this differs from the other risk views-- This command = the **whole change** as one number (defect-risk gate).-- For **per-file** blast radius (what breaks, missing co-changes, missing tests),+- This command = the **whole change** ranked against recent repository history.+- For **per-file** structural reach, missing co-changes, and missing tests,use the `get_risk` MCP tool / the `change-review` skill.- For **per-file health** scores, use `{{cmd:health}}`.diff --git a/plugins/shared/commands/security.md b/plugins/shared/commands/security.mdindex a8cbc8622..a774ea669 100644--- a/plugins/shared/commands/security.md+++ b/plugins/shared/commands/security.md@@ -50,4 +50,4 @@ repowise security scan --history --all-patterns --output json(`hardcoded_password` / `hardcoded_secret`) to avoid noise. Pass`--all-patterns` for code-smell patterns (`eval`, `os.system`, weak hashes, …).- Never invent findings. If the scan stores zero findings, say so plainly.-- For change defect risk (not secret scanning), use `{{cmd:risk}}`.+- For live-change review priority (not secret scanning), use `{{cmd:risk}}`.diff --git a/tests/fixtures/risk_scale_corpus.json b/tests/fixtures/risk_scale_corpus.jsonnew file mode 100644index 000000000..fe226a1ec--- /dev/null+++ b/tests/fixtures/risk_scale_corpus.json@@ -0,0 +1,52 @@+[+ {+ "name": "documentation_low_signal",+ "direct_scores": [0.0001],+ "transitive_dependents": 0,+ "historical_fix_evidence": false,+ "expected_band": "localized"+ },+ {+ "name": "small_ordinary_source",+ "direct_scores": [0.001, 0.002],+ "transitive_dependents": 2,+ "historical_fix_evidence": false,+ "expected_band": "localized"+ },+ {+ "name": "historical_fix_limited_reach",+ "direct_scores": [0.001, 0.002],+ "transitive_dependents": 2,+ "historical_fix_evidence": true,+ "expected_band": "localized"+ },+ {+ "name": "cochange_only_relationship",+ "direct_scores": [0.001],+ "transitive_dependents": 0,+ "historical_fix_evidence": true,+ "cochange_only": true,+ "expected_band": "localized"+ },+ {+ "name": "moderate_multi_file",+ "direct_scores": [0.03, 0.04, 0.05, 0.06],+ "transitive_dependents": 10,+ "historical_fix_evidence": false,+ "expected_band": "moderate"+ },+ {+ "name": "structurally_broad_low_history",+ "direct_scores": [0.08, 0.1, 0.12],+ "transitive_dependents": 40,+ "historical_fix_evidence": false,+ "expected_band": "broad"+ },+ {+ "name": "genuinely_broad_high_control",+ "direct_scores": [0.3, 0.4, 0.5],+ "transitive_dependents": 100,+ "historical_fix_evidence": true,+ "expected_band": "broad"+ }+]diff --git a/tests/unit/analysis/test_change_risk.py b/tests/unit/analysis/test_change_risk.pyindex 84e7e103c..2db9daf9a 100644--- a/tests/unit/analysis/test_change_risk.py+++ b/tests/unit/analysis/test_change_risk.py@@ -39,7 +39,7 @@ def test_score_is_bounded_and_levelled() -> None:def test_logit_is_exact_sum_of_driver_contributions() -> None:- """The reported per-driver contributions must reconstruct the probability+ """The reported per-driver contributions must reconstruct the model outputexactly — the attribution is the model, not a post-hoc approximation."""f = _feat(la=50, ld=10, nf=5, nd=3, ns=2, entropy=2.0, exp=8)risk = score_change(f)@@ -103,6 +103,41 @@ def test_payload_includes_friendly_repo_relative_classification() -> None:assert payload["review_priority"] == "moderate"assert payload["classification"] == "Typical"assert payload["baseline_sample_size"] == 200+ assert payload["risk_authority"] == {+ "authoritative_for": "live_change_review",+ "primary_fields": ["risk_percentile", "classification"],+ "primary_basis": "benchmarked_population_relative",+ "fallback_field": "fallback_band",+ "fallback_basis": "absolute_model_score_band",+ "score_role": "supporting_diff_shape_signal",+ }+ # The per-field dictionary never varies between calls, so it is opt-in.+ assert "risk_scales" not in payload+ expanded = change_risk_payload(+ ChangeRiskResult(+ features=features,+ risk=score_change(features),+ percentile=66.6,+ priority="moderate",+ baseline_sample_size=200,+ riskignore_excludes=(),+ request_excludes=(),+ ),+ scales=True,+ )+ scales = {scale["field"]: scale for scale in expanded["risk_scales"]}+ assert scales["score"]["unit"] == "normalized_points"+ assert scales["score"]["authoritative"] is False+ assert scales["risk_percentile"]["unit"] == "percentile_rank"+ assert scales["risk_percentile"]["authoritative"] is True+ assert scales["fallback_band"]["thresholds"] == {+ "moderate_score": 4.0,+ "high_score": 7.0,+ }+ # No uncalibrated scalar may be described as a probability, anywhere.+ assert "probability" not in str(expanded["risk_scales"]).lower()+ assert all(s["kind"] != "probability" for s in expanded["risk_scales"])+ assert all(s["unit"] != "probability" for s in expanded["risk_scales"])# ---------------------------------------------------------------------------@@ -503,8 +538,18 @@ def test_merge_commit_scores_its_first_parent_diff(git_repo: Path) -> None:_git(["checkout", "-q", "-"], git_repo)_commit(git_repo, {"main.py": "m = 1\n"}, "feat: main", author="Dev")_git(- ["-c", "user.name=Dev", "-c", "[email protected]", "merge", "-q", "--no-ff", "side",- "-m", "merge: side"],+ [+ "-c",+ "user.name=Dev",+ "-c",+ "[email protected]",+ "merge",+ "-q",+ "--no-ff",+ "side",+ "-m",+ "merge: side",+ ],git_repo,)diff --git a/tests/unit/analysis/test_pr_blast_risk.py b/tests/unit/analysis/test_pr_blast_risk.pyindex 71f40a0cb..a87785474 100644--- a/tests/unit/analysis/test_pr_blast_risk.py+++ b/tests/unit/analysis/test_pr_blast_risk.py@@ -9,11 +9,21 @@ diffs, and only approach 10 asymptotically.from __future__ import annotations+import json+from pathlib import Path+from repowise.core.analysis.pr_blast import PRBlastRadiusAnalyzer+from repowise.core.analysis.risk_semantics import (+ structural_impact_band,+ structural_impact_contract,+)++_CORPUS = Path(__file__).parents[2] / "fixtures" / "risk_scale_corpus.json"def _direct(*scores: float) -> list[dict]:- return [{"risk_score": s} for s in scores]+ # Mirrors _score_files: the alias ships beside the typed field.+ return [{"structural_score": s, "risk_score": s} for s in scores]def _transitive(n: int) -> list[dict]:@@ -63,3 +73,107 @@ class TestOverallRiskCalibration:_direct(5.0, 5.0, 5.0), _transitive(500))assert score <= 10.0+++def test_deterministic_corpus_preserves_separation_without_ordinary_saturation() -> None:+ """Band mapping and ordering over the heuristic's own input space.++ These are constructed inputs, not sampled commits: they prove the formula+ separates and never pins at 10, not that a real repo's changes land where+ they should. Live distribution evidence belongs in the dogfood record.+ """+ fixtures = json.loads(_CORPUS.read_text(encoding="utf-8"))+ scored: dict[str, float] = {}+ for fixture in fixtures:+ score = PRBlastRadiusAnalyzer._compute_overall_risk(+ _direct(*fixture["direct_scores"]),+ _transitive(fixture["transitive_dependents"]),+ )+ scored[fixture["name"]] = score+ assert structural_impact_band(score) == fixture["expected_band"]++ ordinary = [+ score+ for name, score in scored.items()+ if name+ in {+ "documentation_low_signal",+ "small_ordinary_source",+ "historical_fix_limited_reach",+ "cochange_only_relationship",+ }+ ]+ assert max(ordinary) < 4.0+ assert all(score < 10.0 for score in scored.values())+ assert scored["documentation_low_signal"] < scored["moderate_multi_file"]+ assert scored["moderate_multi_file"] < scored["structurally_broad_low_history"]+ assert scored["structurally_broad_low_history"] < scored["genuinely_broad_high_control"]+++def test_cochange_only_relationships_are_not_structural_reach() -> None:+ """A co-change partner is temporal correlation, never a transitive dependent."""+ fixtures = {item["name"]: item for item in json.loads(_CORPUS.read_text(encoding="utf-8"))}+ cochange = fixtures["cochange_only_relationship"]+ assert cochange["cochange_only"] is True+ assert cochange["transitive_dependents"] == 0+ score = PRBlastRadiusAnalyzer._compute_overall_risk(+ _direct(*cochange["direct_scores"]), _transitive(cochange["transitive_dependents"])+ )+ assert structural_impact_band(score) == "localized"+++def test_historical_evidence_does_not_change_structural_impact_score() -> None:+ fixtures = {item["name"]: item for item in json.loads(_CORPUS.read_text(encoding="utf-8"))}+ ordinary = fixtures["small_ordinary_source"]+ historical = fixtures["historical_fix_limited_reach"]+ assert ordinary["direct_scores"] == historical["direct_scores"]+ assert ordinary["transitive_dependents"] == historical["transitive_dependents"]+ assert ordinary["historical_fix_evidence"] is False+ assert historical["historical_fix_evidence"] is True+ assert PRBlastRadiusAnalyzer._compute_overall_risk(+ _direct(*ordinary["direct_scores"]), _transitive(ordinary["transitive_dependents"])+ ) == PRBlastRadiusAnalyzer._compute_overall_risk(+ _direct(*historical["direct_scores"]), _transitive(historical["transitive_dependents"])+ )+++def test_default_contract_guards_the_reading_without_the_reference_tier() -> None:+ """The default ships what stops a misreading; include=["scales"] ships the rest."""+ default = structural_impact_contract(6.25)+ scale = default["structural_impact_scale"]+ for guard in ("unit", "range", "measures", "band_thresholds"):+ assert guard in scale+ assert scale["calibration"] == {"status": "uncalibrated"}+ assert scale["runtime_breakage_probability"] is False+ assert "formula" not in scale+ assert "component_fields" not in scale+ assert "deterministic" not in scale++ full = structural_impact_contract(6.25, full_scale=True)+ full_scale_block = full["structural_impact_scale"]+ assert full_scale_block["formula"] and full_scale_block["component_fields"]+ assert full_scale_block["deterministic"] is True+ assert full_scale_block["calibration"]["source"] is None++ # Ceiling, not a ratio: this block rides every PR-mode response, so a+ # future field cannot quietly reintroduce the reference tier by default.+ assert len(json.dumps(default)) < 1000+ assert len(json.dumps(full)) > 2000+++def test_structural_contract_is_typed_and_legacy_alias_cannot_contradict() -> None:+ contract = structural_impact_contract(6.25, full_scale=True)+ assert contract["structural_impact_score"] == contract["overall_risk_score"] == 6.25+ assert contract["structural_impact_band"] == "moderate"+ scale = contract["structural_impact_scale"]+ assert scale["unit"] == "normalized_points"+ assert scale["calibration"]["status"] == "uncalibrated"+ assert scale["runtime_breakage_probability"] is False+ assert scale["authoritative_for_change_review"] is False+ direct_alias = scale["component_fields"]["direct_risks.risk_score"]+ assert direct_alias["deprecated"] is True+ assert direct_alias["replacement"] == "direct_risks.structural_score"+ assert direct_alias["equivalent_value"] is True+ assert contract["overall_risk_score_compatibility"]["replacement"] == (+ "structural_impact_score"+ )diff --git a/tests/unit/cli/test_risk_cmd.py b/tests/unit/cli/test_risk_cmd.pyindex 7c7e9d7e4..3b0633627 100644--- a/tests/unit/cli/test_risk_cmd.py+++ b/tests/unit/cli/test_risk_cmd.py@@ -60,6 +60,54 @@ 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"]["score_role"] == "supporting_diff_shape_signal"+ assert {scale["unit"] for scale in payload["risk_scales"]} >= {+ "normalized_points",+ "percentile_rank",+ "category",+ "lines",+ "items",+ "shannon_bits",+ "prior_commits",+ "logit_points",+ }+++def test_risk_human_output_labels_absolute_fallback_when_baseline_is_disabled(+ tmp_path: Path,+) -> None:+ repo = tmp_path / "repo"+ repo.mkdir()+ _git(["init", "-q"], repo)+ _commit(repo, {"README.md": "# seed\n"}, "chore: seed")+ _commit(repo, {"src/app.py": "value = 1\n"}, "feat: app")++ result = CliRunner().invoke(+ risk_command,+ ["HEAD", "--path", str(repo), "--baseline", "0"],+ )++ assert result.exit_code == 0, result.output+ assert "Absolute fallback band:" in result.output+ assert "Benchmarked review priority:" not in result.output+ assert "probability" not in result.output.lower()+++def test_risk_human_output_leads_with_benchmarked_review_priority(tmp_path: Path) -> None:+ repo = tmp_path / "repo"+ repo.mkdir()+ _git(["init", "-q"], repo)+ _commit(repo, {"README.md": "# seed\n"}, "chore: seed")+ for index in range(9):+ _commit(repo, {f"src/f{index}.py": f"value = {index}\n"}, f"feat: add {index}")++ result = 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.outputdef test_risk_help_describes_repeatable_exclude() -> None:diff --git a/tests/unit/cli/test_search_collapse.py b/tests/unit/cli/test_search_collapse.pyindex 5aefab7bc..9eeae890c 100644--- a/tests/unit/cli/test_search_collapse.py+++ b/tests/unit/cli/test_search_collapse.py@@ -792,7 +792,8 @@ def test_risk_full_on_a_revspec_is_json_not_a_table(monkeypatch, repo):from repowise.core.analysis.change_risk import ChangeRiskResultmonkeypatch.setattr(- "repowise.cli.commands.risk_cmd.change_risk_payload", lambda r: {"risk": 4.2}+ "repowise.cli.commands.risk_cmd.change_risk_payload",+ lambda r, **kw: {"risk": 4.2},)monkeypatch.setattr("repowise.cli.commands.risk_cmd.score_live_change",diff --git a/tests/unit/server/mcp/test_budget.py b/tests/unit/server/mcp/test_budget.pyindex 2b9a2b465..e0679fd60 100644--- a/tests/unit/server/mcp/test_budget.py+++ b/tests/unit/server/mcp/test_budget.py@@ -302,9 +302,7 @@ def test_fit_to_budget_sheds_a_nested_block(repo_root: Path, monkeypatch):assert response["nested"]["light"] == 1-def test_fit_to_budget_trims_a_ranked_tail_but_never_empties_it(- repo_root: Path, monkeypatch-):+def test_fit_to_budget_trims_a_ranked_tail_but_never_empties_it(repo_root: Path, monkeypatch):_narrow_budget(monkeypatch, 700)response = {"results": [{"row": i, "body": "r" * 900} for i in range(6)]}collector = OmissionCollector("search_codebase", repo_root=repo_root)@@ -492,12 +490,14 @@ def test_risk_trim_blast_lists_collects_drops(repo_root: Path):blast = {"transitive_affected": [f"pkg/f{i}.py" for i in range(20)],- "overall_risk_score": 4.2,+ "structural_impact_score": 4.2,}collector = OmissionCollector("get_risk", repo_root=repo_root)trimmed = _trim_blast_lists(blast, None, collector)assert len(trimmed["transitive_affected"]) == 15assert trimmed["transitive_affected_truncated_total"] == 20+ assert trimmed["structural_impact_score"] == trimmed["overall_risk_score"] == 4.2+ assert trimmed["overall_risk_score_compatibility"]["equivalent_value"] is Trueresponse: dict = {"_meta": {}}collector.attach(response)diff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.pyindex ce26324da..98bb337cf 100644--- a/tests/unit/server/mcp/test_change_risk.py+++ b/tests/unit/server/mcp/test_change_risk.py@@ -66,7 +66,22 @@ async def test_get_change_risk_honors_riskignore_and_request_filters(tmp_path, massert result["risk_percentile"] is Noneassert result["review_priority"] is Noneassert result["classification"] is None+ assert result["fallback_band"] in {"low", "moderate", "high"}assert result["baseline_sample_size"] == 0+ assert result["risk_authority"]["primary_fields"] == [+ "risk_percentile",+ "classification",+ ]+ # The per-field dictionary is identical on every call, so it is opt-in.+ assert "risk_scales" not in result+ expanded = await module.get_change_risk(+ "HEAD", extensions=["py", "md"], exclude_patterns=["docs/"], baseline=0, include=["scales"]+ )+ scales = {scale["field"]: scale for scale in expanded["risk_scales"]}+ assert scales["score"]["authoritative"] is False+ assert scales["risk_percentile"]["authoritative"] is True+ assert 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.assert result["_meta"]["source"] == "live_git"assert "warning" not in result@@ -280,9 +295,7 @@ async def test_impacted_tests_falls_back_to_the_graph_without_a_map(tmp_path, mofactory = await _factory_with_repo(None)async with factory() as s:for path, is_test in (("tests/test_round_trips.py", True), ("src/app.py", False)):- s.add(- GraphNode(repository_id="repo1", node_id=path, node_type="file", is_test=is_test)- )+ s.add(GraphNode(repository_id="repo1", node_id=path, node_type="file", is_test=is_test))s.add(GraphEdge(repository_id="repo1",@@ -345,7 +358,9 @@ async def test_impacted_tests_overflow_cap_is_honest(tmp_path, monkeypatch) -> N@pytest.mark.asyncio-async def test_impacted_tests_no_session_factory_degrades_to_no_index(tmp_path, monkeypatch) -> None:+async def test_impacted_tests_no_session_factory_degrades_to_no_index(+ tmp_path, monkeypatch+) -> None:repo = tmp_path / "repo"repo.mkdir()_git(["init", "-q"], repo)@@ -385,9 +400,10 @@ async def test_the_two_risk_tools_do_not_share_a_key_for_different_questions() -}-def test_score_measures_names_the_other_zero_to_ten() -> None:- """Whichever risk tool an agent calls first, it learns the other is not it."""+def test_score_measures_names_only_the_supporting_diff_shape_signal() -> None:+ """The compatibility string stays precise while typed metadata carries authority."""from repowise.core.analysis.change_risk import SCORE_MEASURESassert "diff size and spread" in SCORE_MEASURES- assert "overall_risk_score" in SCORE_MEASURES+ assert "where the change lands" in SCORE_MEASURES+ assert "probability" not in SCORE_MEASURESdiff --git a/tests/unit/server/mcp/test_risk.py b/tests/unit/server/mcp/test_risk.pyindex 187419f44..122872cc7 100644--- a/tests/unit/server/mcp/test_risk.py+++ b/tests/unit/server/mcp/test_risk.py@@ -438,21 +438,38 @@ async def test_get_risk_names_an_unknown_include_rather_than_applying_it(setup_mresult = await get_risk(["src/auth/service.py"], include=["graph", "nonsense"])assert "impact_surface" in result["targets"]["src/auth/service.py"]assert result["ignored_arguments"] == [- {"argument": "include", "values": ["nonsense"], "valid": ["churn", "graph"]}+ {"argument": "include", "values": ["nonsense"], "valid": ["churn", "graph", "scales"]}]@pytest.mark.asyncioasync def test_get_risk_directive_does_not_copy_the_analyzer_score(setup_mcp):- """overall_risk_score lives in pr_blast_radius, with a note on its scale."""+ """The structural heuristic lives in blast detail, not the directive."""from repowise.server.mcp_server import get_riskresult = await get_risk(["src/auth/service.py"], changed_files=["src/auth/service.py"])assert "overall_risk_score" not in result["directive"]blast = result["pr_blast_radius"]- assert "overall_risk_score" in blast- assert "get_change_risk.score" in blast["overall_risk_score_measures"]+ assert blast["overall_risk_score"] == blast["structural_impact_score"]+ assert blast["overall_risk_score_compatibility"] == {+ "deprecated": True,+ "replacement": "structural_impact_score",+ "equivalent_value": True,+ "historical_meaning": "uncalibrated 0-10 structural blast-radius heuristic",+ }+ scale = blast["structural_impact_scale"]+ assert scale["calibration"]["status"] == "uncalibrated"+ assert scale["runtime_breakage_probability"] is False+ # Guard tier by default; the reference tier follows the caller's include.+ assert "component_fields" not in scale+ assert "risk_scales" not in result++ expanded = await get_risk(+ ["src/auth/service.py"], changed_files=["src/auth/service.py"], include=["scales"]+ )+ assert expanded["risk_scales"][0]["field"] == "targets.*.hotspot_score"+ assert expanded["pr_blast_radius"]["structural_impact_scale"]["component_fields"]@pytest.mark.asynciodiff --git a/tests/unit/server/test_mcp_blast_radius.py b/tests/unit/server/test_mcp_blast_radius.pyindex a14bb558a..729e82e45 100644--- a/tests/unit/server/test_mcp_blast_radius.py+++ b/tests/unit/server/test_mcp_blast_radius.py@@ -119,6 +119,11 @@ async def test_changing_provider_impacts_consumer(workspace_state):assert "frontend" in result["impacted_repos"]assert "backend" in result["targets"]assert "downstream service" in result["summary"]+ semantics = result["impact_score_semantics"]+ assert semantics["field"] == "impacted[].score"+ assert semantics["unit"] == "relative_weight"+ assert semantics["calibration"]["status"] == "uncalibrated"+ assert semantics["runtime_breakage_probability"] is False@pytest.mark.asynciodiff --git a/tests/unit/server/test_pr_test_impact_rest.py b/tests/unit/server/test_pr_test_impact_rest.pyindex 64b5bb9d1..3c4cbe994 100644--- a/tests/unit/server/test_pr_test_impact_rest.py+++ b/tests/unit/server/test_pr_test_impact_rest.py@@ -78,6 +78,15 @@ async def test_rest_and_shared_analyzer_return_identical_test_impact(client, sesassert response.status_code == 200external = response.json()assert external["test_impact"] == internal["test_impact"]+ assert external["structural_impact_score"] == external["overall_risk_score"]+ assert external["structural_impact_band"] in {"localized", "moderate", "broad"}+ assert external["structural_impact_scale"]["unit"] == "normalized_points"+ assert external["structural_impact_scale"]["calibration"]["status"] == "uncalibrated"+ assert external["structural_impact_scale"]["runtime_breakage_probability"] is False+ assert external["overall_risk_score_compatibility"]["replacement"] == (+ "structural_impact_score"+ )+ assert all(row["structural_score"] == row["risk_score"] for row in external["direct_risks"])assert external["test_impact"]["recommendations_total"] == 16assert external["test_impact"]["recommendations_emitted"] == len(external["test_impact"]["recommendations"]@@ -94,6 +103,9 @@ async def test_openapi_exposes_typed_test_impact_contract(client):blast = schema["BlastRadiusResponse"]assert blast["properties"]["test_impact"]["$ref"].endswith("/TestImpactResponse")+ assert blast["properties"]["structural_impact_scale"]["$ref"].endswith("/RiskScalarSemantics")+ assert "structural_impact_score" in blast["required"]+ assert "overall_risk_score_compatibility" in blast["required"]recommendation = schema["TestRecommendation"]assert recommendation["required"] == ["test_id",diff --git a/tests/unit/server/test_risk_range.py b/tests/unit/server/test_risk_range.pyindex 134930d27..3134e6e1a 100644--- a/tests/unit/server/test_risk_range.py+++ b/tests/unit/server/test_risk_range.py@@ -82,6 +82,9 @@ 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"]["score_role"] == "supporting_diff_shape_signal"+ assert "risk_scales" not in data@pytest.mark.asynciodiff --git a/website/claude-code-plugin.md b/website/claude-code-plugin.mdindex 4994e0210..a7f6b2847 100644--- a/website/claude-code-plugin.md+++ b/website/claude-code-plugin.md@@ -145,7 +145,7 @@ Code-health KPIs, lowest-scoring files, refactoring targets, or trends### `/repowise:risk`-Defect-risk score for a commit or `base..head` range (`repowise risk`).+Repo-relative review percentile/classification with a supporting diff-shape score (`repowise risk`).---diff --git a/website/cli-reference.md b/website/cli-reference.mdindex d157a94e0..8aad8fa67 100644--- a/website/cli-reference.md+++ b/website/cli-reference.md@@ -536,7 +536,9 @@ repowise health --trend## `risk`-Score the defect risk of a *change* (commit or `base..head` range). No LLM.+Rank a *change* (commit or `base..head` range) for review. The repo-relative+percentile/classification is authoritative; the supporting 0-10 score measures+diff size and spread and is not a probability. No LLM.```bashrepowise risk [REVSPEC] [OPTIONS]diff --git a/website/mcp-server.md b/website/mcp-server.mdindex 3d04ef0d7..791c3e976 100644--- a/website/mcp-server.md+++ b/website/mcp-server.md@@ -370,13 +370,20 @@ refresh.- `exclude_patterns` (optional) — gitignore-style paths; combined with root `.riskignore`- `baseline` (optional, int) — recent commits for percentile ranking (default `200`)-**Returns:** `fix_history` first — the recency-weighted bug-fix record of the+**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 thefiles touched, which is what distinguishes a small dangerous change from a large-boring one. Then the `score` (diff size and spread, per `score_measures`) with+boring one. The supporting `score` is an offline-calibrated 0-10 diff-size and+spread output, not a probability (see `score_measures`), withthe `score_unit` it is calibrated on, repo-relative `risk_percentile` /`review_priority` / `classification` for that diff shape, a `fallback_band` whenthere was no baseline to rank against, plus `impacted_tests` when a per-test-coverage map is ingested (`repowise coverage add`).+coverage map is ingested (`repowise coverage add`). `risk_authority` names the+field to act on; `include=["scales"]` supplies the kind, units, range,+calibration, authority, and shared thresholds for each value. `fallback_band`+is an absolute per-commit classification, not the population-relative+percentile classification.**When to use:** Before merging a commit or PR range, or on work you have notcommitted yet.