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
refactor(risk): drop the uncalibrated structural score from get_risk replies (#3124)
Raghav Chamadiyaa6cee9d9fc14
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 249c6e312..461c5f089 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -230,9 +230,9 @@ What history says about touching a file: hotspot score, bug-fix record, owners,| `include` | list[string] | none | `graph` (typed dependents, consumers, cross-repo links), `churn`, `tests` (typed `test_recommendations` in PR mode), `blast` (`pr_blast_radius` in PR mode), `scales` (units and calibration, identical per call) || `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |-**Key return fields:** per file: `hotspot_score` (0 to 1), `health_score` (0 to 10), `dependents_count`, `co_change_partners`, owners, test gaps, `security_signals`. In PR mode, `directive` with `may_break`, `missing_cochanges`, `tests_to_run`, `tests_to_run_basis` (`measured`, `inferred` or `none`), `tests_to_update` (test files to edit, each with a `name_pair`, `imports` or `co_change` reason), `coverage`, `recommended_reviewers` and `next_calls`. `include=["blast"]` adds `pr_blast_radius` with the 0 to 10 `structural_impact_score`. `missing_tests` appears only when coverage can back it. A target naming no indexed file returns `resolved: false` with a reason, never zeroed counts.+**Key return fields:** per file: `hotspot_score` (0 to 1), `health_score` (0 to 10), `dependents_count`, `co_change_partners`, owners, test gaps, `security_signals`. In PR mode, `directive` with `may_break`, `missing_cochanges`, `tests_to_run`, `tests_to_run_basis` (`measured`, `inferred` or `none`), `tests_to_update` (test files to edit, each with a `name_pair`, `imports` or `co_change` reason), `coverage`, `recommended_reviewers`, `next_calls`, and `reach` (`localized`, `moderate` or `broad`; `null` when no structural score was computed). `include=["blast"]` adds `pr_blast_radius`; the raw 0 to 10 `structural_impact_score` and its scale appear there only with `include=["blast", "scales"]`. `missing_tests` appears only when coverage can back it. A target naming no indexed file returns `resolved: false` with a reason, never zeroed counts.-Dependent counts are a floor over the indexed graph, and structural reach is not proof of runtime breakage. `structural_impact_score` is an uncalibrated heuristic, not a probability.+Dependent counts are a floor over the indexed graph, and structural reach is not proof of runtime breakage. `reach` bands an uncalibrated heuristic that never sees the diff; it is not a probability.```get_risk(targets=["src/auth/middleware.ts"])@@ -250,7 +250,7 @@ Reviews one commit, a `base..head` range, or uncommitted work by comparing the t| `exclude_patterns` | list[string] | none | Gitignore-style paths to omit; combined with a root `.riskignore` || `include_paths` | list[string] or string | all | Gitignore-style paths to keep, as a list or one comma-separated string || `baseline` | int | `200` | Recent commits sampled for percentile ranking; `0` disables percentiles |-| `include` | list[string] | none | `findings` (every finding), `diagnostics` (raw score mechanics), `scales` (units) |+| `include` | list[string] | none | `findings` (every finding), `diagnostics` (raw score mechanics, plus the delta's analyzer, revisions and limits), `scales` (units) || `finding_id` | string | none | Expand one `health_delta` finding || `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |diff --git a/docs/layers/CHANGE_RISK.md b/docs/layers/CHANGE_RISK.mdindex 802ae3c32..7bc436559 100644--- a/docs/layers/CHANGE_RISK.md+++ b/docs/layers/CHANGE_RISK.md@@ -145,6 +145,7 @@ files reach, and what is missing from it. The response opens with a| `missing_tests` | Changed files with a test gap; present only when coverage can back it || `coverage` | `{status, reason}` when there is no per-test coverage map || `tests_to_update` | Up to three test files the change will probably need edited, with why: `name_pair`, `imports` or `co_change`; empty when none qualify |+| `reach` | `localized`, `moderate` or `broad`: the band of the structural heuristic below; `null` when no score was computed || `next_calls` | What to call next || `summary` | One sentence over all of the above |@@ -156,12 +157,14 @@ index), `conformance_violations` and `dependency_cycles`. See[Cross-Repo Blast Radius](../scale/WORKSPACES.md#cross-repo-blast-radius) and[Breaking-Change Guard](../scale/WORKSPACES.md#breaking-change-guard).-The directive also names `recommended_reviewers`. With `include=["blast"]`,-PR mode adds `pr_blast_radius`, whose `structural_impact_score` is a deterministic, uncalibrated+The directive also names `recommended_reviewers`, and `include=["blast"]` adds+`pr_blast_radius`. The structural impact score is a deterministic, uncalibrated0-10 heuristic over PageRank, churn and transitive dependents, banded`localized` (below 4), `moderate` (4 to below 7) and `broad` (7 and up). It is-not a probability and does not decide review. `overall_risk_score` is an exact-deprecated alias.+not a probability and does not decide review. The MCP reply carries only its+band, as `directive.reach`; `include=["blast", "scales"]` adds the score and+its scale. The REST blast-radius response and the CLI keep the score with its+exact deprecated alias `overall_risk_score`.## Independent changesdiff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex 5b2b4ae17..d91d77a8f 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -228,7 +228,7 @@ Opt-in blocks: `tests` adds the PR directive's typed `test_recommendations`, and| `coverage` | `{status, reason}` when there is no per-test coverage map. With a map, `coverage_analysis`, `test_analysis` and `test_inference_analysis` say whether each evidence source was available, stale, partial or degraded || `test_recommendations` | With `include=["tests"]`: typed rows, each with a `basis`: `measured` (the per-test coverage map found the test) or `inferred` (structural reach, not coverage proof) || `recommended_reviewers` | Up to five primary owners of the affected files |-| `pr_blast_radius.structural_impact_score` | With `include=["blast"]`: uncalibrated 0 to 10 structural heuristic: `localized` below 4, `moderate` 4 to below 7, `broad` 7 and up. Not a breakage probability. `overall_risk_score` is a deprecated alias |+| `reach` | Band of the uncalibrated 0 to 10 structural heuristic: `localized` below 4, `moderate` 4 to below 7, `broad` 7 and up. `null` when the analyzer computed no score. Not a breakage probability, and it never sees the diff. The raw `pr_blast_radius.structural_impact_score` and its scale appear only with `include=["blast", "scales"]` || `next_calls` | `get_change_risk()` for the diff itself, then `get_context` on the first `may_break` files |In workspace mode the directive also carries `will_break_consumers` (services in other repos that structurally depend on this one; structural reach only despite the name), `missing_cross_repo_cochanges`, `breaking_changes` (provider incompatibilities since the last index, with impacted consumers; a consumer link does not prove field use), `conformance_violations` and `dependency_cycles`. They are dropped when no workspace is loaded.@@ -253,7 +253,7 @@ Every float is rounded to 4 significant digits. Direct rows' `structural_score`| `independent_changes` | When the diff is several unrelated changes || `cross_repo` | Workspace mode: consumers and breaking changes across repos |-`include=["diagnostics"]` adds `score` (the raw 0 to 10 number), `fallback_band`, `risk_authority`, `score_measures`, `score_unit`, `baseline_sample_size`, `features` and `drivers`. `include=["scales"]` adds each field's unit, range and calibration.+`include=["diagnostics"]` adds `score` (the raw 0 to 10 number), `fallback_band`, `risk_authority`, `score_measures`, `score_unit`, `baseline_sample_size`, `features` and `drivers`, plus `health_delta.analyzer` (analyzer and rules fingerprint), `health_delta.base` and `health_delta.head` (the two resolved revisions) and `health_delta.limits`. `include=["scales"]` adds each field's unit, range and calibration.**health_delta.** Both revisions are analysed from their own content, and a finding at head is reported only when the diff explains it. `scope` counts changed, eligible, analysed, skipped and failed files; `status` is `available`, `partial` or `unavailable`, and `partial` is never a clean bill. Documentation and configuration files (Markdown, JSON, YAML, TOML and the other doc or config extensions) are skipped with reason `not_code` and never make a run `partial`; a change made only of them reads `clear_in_analyzed_scope` with a headline saying health analysis does not cover them. HTML, schema and other files with no health dialect still make a run `partial`. `introduced`, `worsened` and `resolved` are totals; `top_findings` holds the three most actionable, with `findings_total`. Each finding names `dimension`, `biomarker`, `severity`, `path`, `symbol`, head-side `lines`, a `reason`, and an `attribution` (`basis` of `added_lines`, `changed_symbol`, `changed_call_edge`, `new_file`, `file_change`, `context_change` or `unknown`, with a `confidence`). Identity ignores line numbers, so moved code introduces nothing. `inspect` gives the `finding_id` call that expands one; ids are bound to the two revisions. A finding that matches a stored one carries `health_reference` for `get_health(finding_id=...)`. Performance findings carry `opportunity_id` and are ordered by opportunity rank.diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.pyindex c905b5306..977e211b3 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py@@ -150,7 +150,6 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {"patch_coverage.files[]","patch_coverage","impacted_tests",- "health_delta.limits","health_delta.skipped","health_delta.top_findings[]",),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 3442eb126..9836e81c6 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@@ -129,6 +129,10 @@ _DIAGNOSTIC_FIELDS = ("fallback_band",)+#: Comparison mechanics on ``health_delta``: the analyzer fingerprint, the two+#: resolved revisions and the fixed limits text. Behind ``diagnostics`` too.+_HEALTH_DIAGNOSTIC_FIELDS = ("analyzer", "base", "head", "limits")+#: ``classification`` labels for the MCP surface. ``review_priority`` is a#: tercile of the diff-shape rank, so the label names size, not a verdict._DIFF_SIZE_LABELS = {@@ -181,7 +185,7 @@ async def get_change_risk(include_paths: Gitignore-style paths to keep, as a list or onecomma-separated string, e.g. ``"src/api/,src/db/"``. Omit for all.baseline: Recent commits sampled for percentile ranking; 0 disables it.- include: ``"findings"``, ``"diagnostics"`` (raw score mechanics) or+ include: ``"findings"``, ``"diagnostics"`` (raw mechanics) or``"scales"`` (units).finding_id: Expand one ``health_delta`` finding by its id."""@@ -296,7 +300,13 @@ async def get_change_risk(payload["diff_shape"] = _diff_shape_sentence(payload, diagnostics)if independent is not None:payload["independent_changes"] = independent- _attach_health(payload, delta, revspec, expand="findings" in include_set)+ _attach_health(+ payload,+ delta,+ revspec,+ expand="findings" in include_set,+ diagnostics="diagnostics" in include_set,+ )# source: live_git marks that the *score* is computed from the working# checkout's git. The two blocks above are index-backed, so the freshness# fields do apply to them, scoped to the change's files. None (not []) when@@ -435,9 +445,14 @@ async def _attach_health_references(ctx: Any, delta: Any) -> None:}-def _attach_health(payload: dict, delta: Any, revspec: str | None, *, expand: bool) -> None:+def _attach_health(+ payload: dict, delta: Any, revspec: str | None, *, expand: bool, diagnostics: bool = False+) -> None:"""Put the directive first and the compact delta second."""block = _health_delta_block(delta, revspec=revspec)+ if not diagnostics:+ for key in _HEALTH_DIAGNOSTIC_FIELDS:+ block.pop(key, None)if expand:from repowise.server.mcp_server._change_health import finding_rowdiff --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 684fc6a70..f174631aa 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@@ -7,7 +7,10 @@ from typing import Anyfrom sqlalchemy import selectfrom repowise.core.analysis.next_call import ActionCommand-from repowise.core.analysis.risk_semantics import structural_impact_contract+from repowise.core.analysis.risk_semantics import (+ structural_impact_band,+ structural_impact_contract,+)from repowise.core.analysis.test_reachability import tests_matching_by_namefrom repowise.core.co_change import MIN_CO_CHANGE_SUPPORTfrom repowise.core.persistence.crud.authority import decision_currencies@@ -336,12 +339,16 @@ 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.+ # The structural score is uncalibrated and never sees the diff, so the MCP+ # reply carries only its band (``directive.reach``). The number and its+ # scale ride with ``include=["scales"]``; REST and the CLI keep the alias.structural_score = trimmed_blast.get("structural_impact_score")- if structural_score is not None:+ contract = structural_impact_contract(float(structural_score or 0.0), full_scale=True)+ for key in contract:+ trimmed_blast.pop(key, None)+ if structural_score is not None and full_scale:trimmed_blast.update(- structural_impact_contract(float(structural_score), full_scale=full_scale)+ {k: v for k, v in contract.items() if k.startswith("structural_impact_")})for key, cap in (("transitive_affected", 15),@@ -758,9 +765,17 @@ def _build_pr_directive())+ structural_score = pr_blast_radius.get("structural_impact_score")directive = {"may_break": may_break,"missing_cochanges": missing_cochanges,+ # Band of the structural heuristic: how far the import graph reaches,+ # not whether anything breaks.+ "reach": (+ structural_impact_band(float(structural_score))+ if structural_score is not None+ else None+ ),"missing_tests": missing_tests,"missing_tests_semantics": "changed_file_test_gap_compatibility_projection","missing_tests_total": missing_tests_total,diff --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 5da1a963a..6df7119e4 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@@ -370,9 +370,10 @@ async def get_risk(measured or inferred. To score a commit or ``base..head`` range instead,use ``get_change_risk``.- ``include=["blast"]`` adds ``pr_blast_radius``, whose- ``structural_impact_score`` is an uncalibrated 0-10 heuristic, never a- runtime-breakage probability.+ ``directive.reach`` (localized, moderate, broad) bands import-graph reach:+ uncalibrated, never a breakage probability.+ ``include=["blast"]`` adds ``pr_blast_radius``; its raw+ ``structural_impact_score`` appears only with ``include=["blast", "scales"]``.Default responses fit 24,000 serialized chars; nonempty ``include`` uses32,000. Reductions carry counts and ``_meta.omitted`` recovery refs;@@ -384,7 +385,7 @@ async def get_risk(repo: usually omitted.changed_files: PR-changed files for blast-radius mode.include: opt-in blocks - "graph", "churn", "tests" (typed test- rows), "blast", "scales" (units and calibration; identical per call).+ rows), "blast", "scales" (units and calibration)."""if repo == "all":return _unsupported_repo_all("get_risk")diff --git a/tests/fixtures/mcp/tool_response_shapes.json b/tests/fixtures/mcp/tool_response_shapes.jsonindex be991fdd8..7b2513758 100644--- a/tests/fixtures/mcp/tool_response_shapes.json+++ b/tests/fixtures/mcp/tool_response_shapes.json@@ -206,31 +206,13 @@"percentile": null},"health_delta": {- "analyzer": {- "analyzer_version": null,- "performance_model_version": null,- "rules_fingerprint": null- },- "base": {- "kind": null,- "ref": null,- "sha": null- },"basis": null,"by_dimension": {},"by_severity": {},"explanation": null,"findings_emitted": null,"findings_total": null,- "head": {- "kind": null,- "ref": null,- "sha": null- },"introduced": null,- "limits": [- null- ],"resolved": null,"scope": {"analyzed": null,@@ -1400,6 +1382,7 @@"tool": null}],+ "reach": null,"recommended_reviewers": [{"email": null,@@ -1535,34 +1518,6 @@}]},- "overall_risk_score": null,- "overall_risk_score_compatibility": {- "deprecated": null,- "equivalent_value": null,- "historical_meaning": null,- "replacement": null- },- "structural_impact_band": null,- "structural_impact_scale": {- "authoritative_for_change_review": null,- "band_thresholds": {- "broad": null,- "moderate": null- },- "calibration": {- "status": null- },- "field": null,- "kind": null,- "measures": null,- "range": {- "maximum": null,- "minimum": null- },- "runtime_breakage_probability": null,- "unit": null- },- "structural_impact_score": null,"test_gaps": [null],diff --git a/tests/unit/change_health/test_mcp_contract.py b/tests/unit/change_health/test_mcp_contract.pyindex 93eb53ac2..325614c9e 100644--- a/tests/unit/change_health/test_mcp_contract.py+++ b/tests/unit/change_health/test_mcp_contract.py@@ -209,11 +209,17 @@ async def test_every_surfaced_finding_carries_an_attribution(tool, make_repo):async def test_the_delta_names_the_analyzer_and_the_two_sides(tool, make_repo):module = tool(seeded(make_repo))- delta = (await module.get_change_risk("HEAD", baseline=0))["health_delta"]+ default = (await module.get_change_risk("HEAD", baseline=0))["health_delta"]+ delta = (await module.get_change_risk("HEAD", baseline=0, include=["diagnostics"]))[+ "health_delta"+ ]+ # Comparison mechanics are a projection: absent by default, exact on request.+ assert not {"analyzer", "base", "head", "limits"} & set(default)assert delta["analyzer"]["analyzer_version"] > 0assert delta["base"]["sha"] and delta["head"]["sha"]- assert delta["basis"] == "both_sides_analyzed"+ assert delta["limits"]+ assert default["basis"] == delta["basis"] == "both_sides_analyzed"# -- caching and concurrency ------------------------------------------------diff --git a/tests/unit/server/mcp/test_budget.py b/tests/unit/server/mcp/test_budget.pyindex e0768327b..cc3add5a1 100644--- a/tests/unit/server/mcp/test_budget.py+++ b/tests/unit/server/mcp/test_budget.py@@ -597,8 +597,12 @@ def test_risk_trim_blast_lists_collects_drops(repo_root: Path):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 True+ # The raw structural score is a scales-only projection on the MCP surface.+ assert "structural_impact_score" not in trimmed+ assert "overall_risk_score" not in trimmed+ scaled = _trim_blast_lists(blast, None, None, full_scale=True)+ assert scaled["structural_impact_score"] == 4.2+ assert "overall_risk_score_compatibility" not in scaledresponse: dict = {"_meta": {}}collector.attach(response)diff --git a/tests/unit/server/mcp/test_risk.py b/tests/unit/server/mcp/test_risk.pyindex ade3593a9..f3873f814 100644--- a/tests/unit/server/mcp/test_risk.py+++ b/tests/unit/server/mcp/test_risk.py@@ -6,6 +6,7 @@ test data, mirroring the conftest pattern from the REST API tests.from __future__ import annotations+import importlibimport jsonimport pytest@@ -822,35 +823,65 @@ async def test_get_risk_names_an_unknown_include_rather_than_applying_it(setup_m@pytest.mark.asyncio-async def test_get_risk_directive_does_not_copy_the_analyzer_score(setup_mcp):- """The structural heuristic lives in blast detail, not the directive."""+async def test_get_risk_reports_reach_not_the_uncalibrated_score(setup_mcp):+ """PR mode carries the structural band as ``reach``; the raw score is opt-in."""+ from repowise.core.analysis.risk_semantics import structural_impact_bandfrom repowise.server.mcp_server import get_riskresult = await get_risk(["src/auth/service.py"], changed_files=["src/auth/service.py"], include=["blast"])- assert "overall_risk_score" not in result["directive"]blast = result["pr_blast_radius"]- 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+ for key in (+ "structural_impact_score",+ "structural_impact_band",+ "structural_impact_scale",+ "overall_risk_score",+ "overall_risk_score_compatibility",+ ):+ assert key not in blast+ assert key not in result["directive"]+ assert result["directive"]["reach"] in {"localized", "moderate", "broad"}assert "risk_scales" not in resultexpanded = await get_risk(["src/auth/service.py"], changed_files=["src/auth/service.py"], include=["scales", "blast"])+ blast = expanded["pr_blast_radius"]assert expanded["risk_scales"][0]["field"] == "targets.*.hotspot_score"- assert expanded["pr_blast_radius"]["structural_impact_scale"]["component_fields"]+ assert structural_impact_band(blast["structural_impact_score"]) == (+ expanded["directive"]["reach"]+ )+ scale = blast["structural_impact_scale"]+ assert scale["calibration"]["status"] == "uncalibrated"+ assert scale["runtime_breakage_probability"] is False+ assert scale["component_fields"]+ assert "overall_risk_score" not in blast+ assert "overall_risk_score_compatibility" not in blast+++async def test_get_risk_reach_is_null_when_the_analyzer_gave_no_score(setup_mcp, monkeypatch):+ from repowise.server.mcp_server import get_risk+ get_risk_module = importlib.import_module("repowise.server.mcp_server.tool_risk.get_risk")++ real = get_risk_module._pr_blast_radius++ async def _unscored(*args, **kwargs):+ blast = await real(*args, **kwargs)+ blast.pop("structural_impact_score", None)+ return blast++ monkeypatch.setattr(get_risk_module, "_pr_blast_radius", _unscored)+ result = await get_risk(+ ["src/auth/service.py"],+ changed_files=["src/auth/service.py"],+ include=["blast", "scales"],+ )++ assert result["directive"]["reach"] is None+ assert "structural_impact_score" not in result["pr_blast_radius"]@pytest.mark.asyncio@@ -1082,7 +1113,10 @@ async def test_get_risk_serves_the_blast_radius_on_request(setup_mcp):assert isinstance(plain["directive"]["recommended_reviewers"], list)blast = await get_risk(files, changed_files=files, include=["blast"])- assert "structural_impact_score" in blast["pr_blast_radius"]+ # The raw structural score also needs "scales"; the directive carries its band.+ assert "structural_impact_score" not in blast["pr_blast_radius"]+ scaled = await get_risk(files, changed_files=files, include=["blast", "scales"])+ assert "structural_impact_score" in scaled["pr_blast_radius"]# Named once, in the directive.reviewers = plain["directive"]["recommended_reviewers"]assert blast["directive"]["recommended_reviewers"] == reviewers