Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(risk): stop risk summaries from overstating or understating a change (#3123)

Raghav Chamadiyabe9e88a02b12
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 625b2aa6e..249c6e312 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -256,7 +256,7 @@ Reviews one commit, a `base..head` range, or uncommitted work by comparing the t
**Key return fields:** `directive` (`status` of `review_required`, `review_recommended`, `clear_in_analyzed_scope` or `unknown`, with reasons and next actions), `health_delta` (introduced, worsened and resolved findings with `status` and `top_findings`), `impacted_tests`, `patch_coverage` (when coverage is stored), `fix_history`, `branch_overlap`, `independent_changes`, `diff_shape`, `risk_percentile`, `cross_repo` (workspace mode).
-Trust `health_delta.status`: `partial` means files were skipped and the change is not cleared. `diff_shape` describes size and spread, never danger. An empty diff returns `status: "nothing_to_score"`.
+`directive.status` is the verdict. `health_delta.status` `partial` means files that may hold code were skipped, so the change is not cleared; docs and config files never cause it. `review_priority`, `classification` and `diff_shape` describe diff size and spread, never danger. An empty diff returns `status: "nothing_to_score"`.
```
get_change_risk()
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index a483cb5e4..5b2b4ae17 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -243,7 +243,7 @@ Every float is rounded to 4 significant digits. Direct rows' `structural_score`
|-------|---------|
| `directive` | `status` (`review_required`, `review_recommended`, `clear_in_analyzed_scope`, `unknown`), a headline, reasons, next actions |
| `health_delta` | What the change newly made worse. See below |
-| `risk_percentile`, `review_priority`, `classification`, `is_fix` | The change ranked against the repo's recent commits |
+| `risk_percentile`, `review_priority`, `classification`, `is_fix` | The change's diff size and spread ranked against the repo's recent commits (`classification` reads `Below-typical`, `Typical` or `Above-typical diff size`). Size, not a verdict: `directive.status` is the verdict |
| `diff_shape` | One sentence on size and spread; never a danger verdict |
| `working_tree` | Whether uncommitted work was the subject |
| `fix_history` | Recency-weighted bug-fix record of the touched files, with `percentile` and `overlap` |
@@ -255,7 +255,7 @@ Every float is rounded to 4 significant digits. Direct rows' `structural_score`
`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.
-**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. `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.
+**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.
**impacted_tests.** `tests_to_run` names tests the per-test coverage map proves execute the changed lines, capped at ten with `total` and `truncated`. `line_coverage` buckets: `untested_changes`, `stale_test_candidates` (covered lines whose test file is absent from the diff), `covered`, `no_coverage_data`. With no coverage map, `status` is `inferred` when the import graph names test files reaching the change, or `no_map` (run the full suite). `basis` is always present: `measured`, `inferred` or `none`; `tests_to_run_kind` is `test_id` or `test_file`. Build the measured map with `coverage run --contexts=test` and `repowise coverage add`.
diff --git a/packages/core/src/repowise/core/analysis/change_health/models.py b/packages/core/src/repowise/core/analysis/change_health/models.py
index a350c790a..e709c81a0 100644
--- a/packages/core/src/repowise/core/analysis/change_health/models.py
+++ b/packages/core/src/repowise/core/analysis/change_health/models.py
@@ -43,9 +43,13 @@ ATTRIBUTION_CONFIDENCE: dict[str, str] = {
SEVERITY_RANK: dict[str, int] = {"low": 0, "medium": 1, "high": 2, "critical": 3}
+#: Documentation or configuration: skipped, but no code went unexamined.
+NOT_CODE = "not_code"
+
#: Why a changed file produced no comparison. Kept per file so a partial run
#: can never render as a clean one.
SkipReason = Literal[
+ "not_code",
"unsupported_language",
"generated",
"binary",
@@ -167,7 +171,7 @@ class ChangeHealthDelta:
resolved_total: int = 0
unchanged_total: int = 0
uncertain_total: int = 0
- #: ``{path: reason}``; a non-empty map means the run was partial.
+ #: ``{path: reason}``. Any reason but ``not_code`` means the run was partial.
skipped: dict[str, str] = field(default_factory=dict)
timing_ms: float = 0.0
cache_hit: bool = False
@@ -181,6 +185,11 @@ class ChangeHealthDelta:
def worsened_total(self) -> int:
return sum(1 for f in self.findings if f.change_kind == "worsened")
+ @property
+ def code_skipped(self) -> dict[str, str]:
+ """Skipped files that may hold code, so their absence leaves a gap."""
+ return {p: r for p, r in self.skipped.items() if r != NOT_CODE}
+
@property
def is_clean(self) -> bool:
"""True only when a valid comparison surfaced nothing new."""
diff --git a/packages/core/src/repowise/core/analysis/change_health/service.py b/packages/core/src/repowise/core/analysis/change_health/service.py
index 10e30b710..7a12b209c 100644
--- a/packages/core/src/repowise/core/analysis/change_health/service.py
+++ b/packages/core/src/repowise/core/analysis/change_health/service.py
@@ -13,6 +13,7 @@ import time
from collections import OrderedDict
from dataclasses import dataclass
+from ...support_paths import is_doc_or_config_path
from ...test_paths import is_test_related_path
from ..finding_registry import excluded_types
from ..health import HEALTH_ANALYZER_VERSION, HealthFindingData
@@ -23,6 +24,7 @@ from .attribution import FindingAttributor, changed_symbols_for
from .identity import change_finding_id, finding_key, severity_rank
from .matcher import FindingMatcher, MatchedFinding
from .models import (
+ NOT_CODE,
AnalysisFingerprint,
ChangeFinding,
ChangeHealthDelta,
@@ -41,6 +43,10 @@ from .sources import (
#: Changed files above this count are refused rather than analysed twice.
MAX_CHANGED_FILES = 300
+#: Documentation and configuration languages. Anything else with no health
+#: dialect (HTML, schemas, shell) may carry logic, so it stays a gap.
+_NOT_CODE_LANGUAGES = frozenset({"json", "yaml", "toml", "markdown"})
+
#: Comparisons kept in the process cache.
_CACHE_CAPACITY = 32
@@ -209,14 +215,19 @@ class ChangeHealthDeltaService:
basis = "both_sides_analyzed"
if not eligible:
+ if not changes:
+ explanation = "This change touches no files."
+ elif all(r == NOT_CODE for r in skipped.values()):
+ explanation = (
+ "Only documentation or configuration files changed; "
+ "health analysis does not cover them."
+ )
+ else:
+ explanation = "No changed file is health-analyzable, so nothing was compared."
delta = ChangeHealthDelta(
# Nothing was compared either way, so neither case is a clean bill.
status="unavailable",
- explanation=(
- "No changed file is health-analyzable, so nothing was compared."
- if changes
- else "This change touches no files."
- ),
+ explanation=explanation,
base=base_id,
head=head_id,
comparison_basis=basis,
@@ -388,7 +399,10 @@ def _skip_reason(change: FileChange) -> str:
"""Why a changed path never reached the analyzer."""
if change.head_path is None:
return "deleted"
- if language_of(change.head_path) is None:
+ language = language_of(change.head_path)
+ if language in _NOT_CODE_LANGUAGES or is_doc_or_config_path(change.head_path):
+ return NOT_CODE
+ if language is None:
return "unsupported_language"
return "not_health_analyzable"
@@ -401,11 +415,13 @@ def _status_for(
f"None of the {scope.changed} changed "
f"{'file' if scope.changed == 1 else 'files'} could be analysed."
)
- if skipped or scope.failed:
+ # Docs, config and data hold no code, so skipping them leaves nothing unexamined.
+ code_skipped = sum(1 for r in skipped.values() if r != NOT_CODE)
+ if code_skipped or scope.failed:
return (
"partial",
f"Compared {scope.analyzed} of {scope.changed} changed files; "
- f"{len(skipped)} were not analysed.",
+ f"{code_skipped} that may hold code were not analysed.",
)
if not findings:
return (
diff --git a/packages/core/src/repowise/core/analysis/review_directive.py b/packages/core/src/repowise/core/analysis/review_directive.py
index a46774b66..1c212995c 100644
--- a/packages/core/src/repowise/core/analysis/review_directive.py
+++ b/packages/core/src/repowise/core/analysis/review_directive.py
@@ -119,6 +119,13 @@ def _plural(word: str, count: int) -> str:
def _verdict(delta: ChangeHealthDelta) -> tuple[ReviewStatus, str, EvidenceState]:
+ if delta.status == "unavailable" and delta.skipped and not delta.code_skipped:
+ return (
+ "clear_in_analyzed_scope",
+ "No code changed: only documentation or configuration files; "
+ "health analysis does not cover them.",
+ "available",
+ )
if delta.status in _NOT_COMPARED:
return "unknown", f"Change health could not be compared: {delta.explanation}", "unavailable"
if delta.status in _UNTRUSTWORTHY:
@@ -168,9 +175,10 @@ def _reasons(delta: ChangeHealthDelta) -> tuple[str, ...]:
f"{f.symbol or f.path} ({f.attribution_basis})"
for f in delta.findings
]
- if delta.skipped:
+ skipped = len(delta.code_skipped)
+ if skipped:
reasons.append(
- f"{len(delta.skipped)} changed {_plural('file', len(delta.skipped))} "
+ f"{skipped} changed {_plural('file', skipped)} "
"were not analysed, so this is not a clean bill."
)
return tuple(reasons)
@@ -211,12 +219,12 @@ def _actions(delta: ChangeHealthDelta, tests: CoveringTestEvidence) -> tuple[Rev
)
)
next_priority += 1
- if delta.skipped:
+ if delta.code_skipped:
actions.append(
ReviewAction(
kind="review_skipped_files",
priority=next_priority,
- targets=tuple(sorted(delta.skipped)),
+ targets=tuple(sorted(delta.code_skipped)),
explanation="Review the skipped files by hand; they were not compared.",
)
)
diff --git a/packages/core/src/repowise/core/analysis/risk_semantics.py b/packages/core/src/repowise/core/analysis/risk_semantics.py
index f82c0f7db..fe0fd4886 100644
--- a/packages/core/src/repowise/core/analysis/risk_semantics.py
+++ b/packages/core/src/repowise/core/analysis/risk_semantics.py
@@ -126,7 +126,7 @@ def change_risk_scales() -> list[dict[str, Any]]:
"kind": "classification",
"unit": "category",
"range": None,
- "measures": "repo-relative review-priority tercile",
+ "measures": "repo-relative tercile of diff size and spread, not a verdict",
"deterministic": True,
"thresholds": {
"moderate_percentile": REVIEW_PRIORITY_MODERATE_PERCENTILE,
diff --git a/packages/server/src/repowise/server/chat_suggestions.py b/packages/server/src/repowise/server/chat_suggestions.py
index 16a450242..4b477c432 100644
--- a/packages/server/src/repowise/server/chat_suggestions.py
+++ b/packages/server/src/repowise/server/chat_suggestions.py
@@ -247,7 +247,9 @@ def _from_get_change_risk(target: str, result: Mapping[str, Any]) -> list[dict[s
)
out.append(
_suggestion(
- f"Why is {ref} rated {classification}{measured}?", "page", "get_change_risk"
+ f"What makes {ref} {classification.lower()}{measured}?",
+ "page",
+ "get_change_risk",
)
)
if result.get("is_fix") is True:
diff --git a/packages/server/src/repowise/server/chat_summaries.py b/packages/server/src/repowise/server/chat_summaries.py
index 516ddc55b..474c58e57 100644
--- a/packages/server/src/repowise/server/chat_summaries.py
+++ b/packages/server/src/repowise/server/chat_summaries.py
@@ -31,14 +31,15 @@ def _risk_summary(result: dict[str, Any]) -> str:
def _change_risk_summary(result: dict[str, Any]) -> str:
ref = result.get("ref", "change")
- priority = result.get("review_priority") or result.get("classification") or "unknown"
+ # The tercile ranks diff size, so the summary names the size label, not a verdict.
+ size = result.get("classification") or result.get("review_priority") or "unranked"
pct = result.get("risk_percentile")
if pct is not None:
- return f"Change risk for {ref}: {priority} (p{pct})"
+ return f"Diff size for {ref}: {size} (p{pct})"
score = result.get("score")
if score is not None:
- return f"Change risk for {ref}: {priority} (score {score})"
- return f"Change risk for {ref}: {priority}"
+ return f"Diff size for {ref}: {size} (score {score})"
+ return f"Diff size for {ref}: {size}"
def _why_path_summary(result: dict[str, Any]) -> str:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
index 52eff64b6..3442eb126 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,14 @@ _DIAGNOSTIC_FIELDS = (
"fallback_band",
)
+#: ``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 = {
+ "low": "Below-typical diff size",
+ "moderate": "Typical diff size",
+ "high": "Above-typical diff size",
+}
+
@mcp.tool(
surface_order=60,
@@ -153,15 +161,15 @@ async def get_change_risk(
them, name their ``attribution`` basis, and sort change-written above
pre-existing.
- Trust ``health_delta.status``: ``partial`` means files were skipped and the
- change is not cleared.
+ ``directive.status`` is the verdict; ``partial`` health means code files
+ were skipped. ``review_priority``, ``classification`` and ``diff_shape``
+ measure diff size only, not danger.
``impacted_tests`` keeps measured coverage and inferred candidates distinct.
``patch_coverage`` is the share of changed executable lines stored coverage
ran; ``hints`` name tests to extend. ``fix_history`` is the changed files'
bug-fix record, ``overlap`` the past fixes on these exact lines,
- ``branch_overlap`` other branches editing them. ``diff_shape`` is one line
- on size, not a danger verdict. An empty diff returns
+ ``branch_overlap`` other branches editing them. An empty diff returns
``status: "nothing_to_score"``.
Args:
@@ -204,6 +212,8 @@ async def get_change_risk(
if resolve_enum_argument(block, _INCLUDE_BLOCKS, argument="include", ignored=ignored)
}
payload = change_risk_payload(result, scales="scales" in include_set)
+ if payload.get("review_priority") in _DIFF_SIZE_LABELS:
+ payload["classification"] = _DIFF_SIZE_LABELS[payload["review_priority"]]
if "diagnostics" not in include_set:
diagnostics = {f: payload.pop(f) for f in _DIAGNOSTIC_FIELDS if f in payload}
else:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py
index 9318875ea..684fc6a70 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
@@ -829,10 +829,11 @@ def _build_pr_directive(
"governance_risk": governance_risk,
"recommended_reviewers": trimmed_blast.get("recommended_reviewers") or [],
"next_calls": [c.as_dict() for c in next_calls],
+ # Totals, not the capped list lengths: "~5" of 24 understates the reach.
"summary": (
f"PR touches {len(changed_files)} file(s). "
- f"~{len(may_break)} downstream file(s) may be affected, "
- f"{len(missing_cochanges)} historical co-changer(s) missing, "
+ f"~{len(all_may_break)} downstream file(s) may be affected, "
+ f"{len(all_missing_cochanges)} historical co-changer(s) missing, "
f"{missing_tests_summary}"
f"{tests_to_run_suffix}{gov_suffix}{xr_suffix}{bc_suffix}{cf_suffix}"
),
diff --git a/packages/ui/src/chat/artifacts.tsx b/packages/ui/src/chat/artifacts.tsx
index 8a257c77d..20321e1ab 100644
--- a/packages/ui/src/chat/artifacts.tsx
+++ b/packages/ui/src/chat/artifacts.tsx
@@ -391,7 +391,7 @@ function ChangeRiskCard({ data }: { data: RiskReportArtifactData }) {
{data.ref && <ContextItem label="Change" value={String(data.ref)} />}
{pct !== null && <ContextItem label="Diff shape" value={`p${pct}`} />}
{data.review_priority && (
- <ContextItem label="Priority" value={String(data.review_priority)} />
+ <ContextItem label="Diff size" value={String(data.review_priority)} />
)}
{delta?.scope && (
<ContextItem
diff --git a/tests/unit/analysis/test_review_directive.py b/tests/unit/analysis/test_review_directive.py
index 8d108c6ee..4a918b640 100644
--- a/tests/unit/analysis/test_review_directive.py
+++ b/tests/unit/analysis/test_review_directive.py
@@ -110,6 +110,33 @@ def test_skipped_files_are_a_reason_not_a_clean_bill():
assert any("not a clean bill" in reason for reason in directive.reasons)
+def test_skipped_docs_beside_analysed_code_ask_for_nothing():
+ delta = _delta()
+ delta.skipped = {"CHANGES.rst": "not_code", "package.json": "not_code"}
+ directive = review_directive(delta)
+ assert directive.status == "clear_in_analyzed_scope"
+ assert directive.reasons == ()
+ assert all(a.kind != "review_skipped_files" for a in directive.actions)
+
+
+def test_a_docs_only_change_says_there_is_no_code_rather_than_unknown():
+ delta = _delta(status="unavailable", explanation="Only documentation changed")
+ delta.skipped = {"README.md": "not_code"}
+ directive = review_directive(delta)
+ assert directive.status == "clear_in_analyzed_scope"
+ assert "No code changed" in directive.headline
+ assert "does not cover them" in directive.headline
+ assert not directive.actions
+
+
+def test_an_unsupported_code_file_still_leaves_the_verdict_unknown():
+ delta = _delta(status="unavailable", explanation="nothing compared")
+ delta.skipped = {"README.md": "not_code", "lib.ex": "not_health_analyzable"}
+ directive = review_directive(delta)
+ assert directive.status == "unknown"
+ assert [a.targets for a in directive.actions] == [("lib.ex",)]
+
+
# ---------------------------------------------------------------------------
# Actions carry targets, not rendered strings
# ---------------------------------------------------------------------------
diff --git a/tests/unit/change_health/test_comparison.py b/tests/unit/change_health/test_comparison.py
index a0d777a02..e6028afd7 100644
--- a/tests/unit/change_health/test_comparison.py
+++ b/tests/unit/change_health/test_comparison.py
@@ -301,7 +301,7 @@ def test_test_file_findings_sort_below_source_findings(make_repo):
# -- honesty ----------------------------------------------------------------
-def test_an_unsupported_file_is_skipped_and_never_looks_clean(make_repo):
+def test_a_docs_only_change_says_there_is_no_code_and_never_looks_clean(make_repo):
repo = make_repo()
repo.commit("seed", {"README.md": "# hi\n"})
repo.commit("edit", {"README.md": "# hi there\n"})
@@ -310,16 +310,29 @@ def test_an_unsupported_file_is_skipped_and_never_looks_clean(make_repo):
assert delta.findings == []
assert delta.status == "unavailable"
- assert delta.skipped == {"README.md": "not_health_analyzable"}
+ assert delta.skipped == {"README.md": "not_code"}
+ assert "health analysis does not cover them" in delta.explanation
assert not delta.is_clean
+def test_an_unsupported_code_file_is_skipped_and_never_looks_clean(make_repo):
+ repo = make_repo()
+ repo.commit("seed", {"lib.ex": "defmodule A do\nend\n"})
+ repo.commit("edit", {"lib.ex": "defmodule B do\nend\n"})
+
+ delta = compare(repo)
+
+ assert delta.status == "unavailable"
+ assert delta.skipped == {"lib.ex": "not_health_analyzable"}
+ assert "nothing was compared" in delta.explanation
+
+
def test_a_partial_run_is_reported_as_partial(make_repo):
repo = make_repo()
repo.commit("seed", {"app.py": "x = 1\n"})
repo.commit(
"mixed",
- {"app.py": python_complex("tangle", 16), "notes.md": "text\n"},
+ {"app.py": python_complex("tangle", 16), "lib.ex": "defmodule A do\nend\n"},
)
delta = compare(repo)
@@ -329,6 +342,43 @@ def test_a_partial_run_is_reported_as_partial(make_repo):
assert not delta.is_clean
[email protected]("path", ["page.html", "api.proto", "q.graphql", "x.xaml"])
+def test_data_and_markup_with_logic_still_make_the_run_partial(make_repo, path):
+ repo = make_repo()
+ repo.commit("seed", {"app.py": "x = 1\n", path: "a\n"})
+ repo.commit("edit", {"app.py": "x = 2\n", path: "b\n"})
+
+ delta = compare(repo)
+
+ assert delta.status == "partial"
+ assert delta.skipped[path] != "not_code"
+
+
+def test_docs_beside_an_unsupported_code_file_are_still_partial(make_repo):
+ repo = make_repo()
+ repo.commit("seed", {"app.py": "x = 1\n", "README.md": "a\n", "lib.ex": "defmodule A do\nend\n"})
+ repo.commit("edit", {"app.py": "x = 2\n", "README.md": "b\n", "lib.ex": "defmodule B do\nend\n"})
+
+ delta = compare(repo)
+
+ assert delta.status == "partial"
+ assert delta.code_skipped == {"lib.ex": "not_health_analyzable"}
+ assert delta.skipped["README.md"] == "not_code"
+
+
[email protected]("path", ["CHANGES.rst", "package.json", "docs/guide.md", ".ci.yml"])
+def test_docs_and_config_beside_code_do_not_make_the_run_partial(make_repo, path):
+ repo = make_repo()
+ repo.commit("seed", {"app.py": "x = 1\n", path: "a\n"})
+ repo.commit("edit", {"app.py": "x = 2\n", path: "b\n"})
+
+ delta = compare(repo)
+
+ assert delta.status == "available"
+ assert delta.skipped == {path: "not_code"}
+ assert delta.code_skipped == {}
+
+
def test_a_generated_file_is_excluded_by_reason(make_repo):
repo = make_repo()
repo.commit("seed", {"gen.py": "# GENERATED CODE\nx = 1\n"})
diff --git a/tests/unit/change_health/test_mcp_contract.py b/tests/unit/change_health/test_mcp_contract.py
index 021d121f1..93eb53ac2 100644
--- a/tests/unit/change_health/test_mcp_contract.py
+++ b/tests/unit/change_health/test_mcp_contract.py
@@ -156,7 +156,7 @@ async def test_a_clean_change_says_analyzed_scope_not_safe(tool, make_repo):
async def test_a_partial_comparison_never_reads_as_clear(tool, make_repo):
repo = make_repo()
repo.commit("seed", {"app.py": "x = 1\n"})
- repo.commit("mixed", {"app.py": python_complex("tangle", 18), "notes.md": "text\n"})
+ repo.commit("mixed", {"app.py": python_complex("tangle", 18), "lib.ex": "defmodule A do\nend\n"})
module = tool(repo)
result = await module.get_change_risk("HEAD", baseline=0)
@@ -166,6 +166,19 @@ async def test_a_partial_comparison_never_reads_as_clear(tool, make_repo):
assert any("not analysed" in reason for reason in result["directive"]["reasons"])
+async def test_a_docs_only_change_says_there_is_no_code_to_analyse(tool, make_repo):
+ repo = make_repo()
+ repo.commit("seed", {"app.py": "x = 1\n", "CHANGES.rst": "a\n"})
+ repo.commit("docs", {"CHANGES.rst": "b\n"})
+ module = tool(repo)
+
+ result = await module.get_change_risk("HEAD", baseline=0)
+
+ assert result["directive"]["status"] == "clear_in_analyzed_scope"
+ assert "No code changed" in result["directive"]["headline"]
+ assert result["health_delta"]["skipped"]["by_reason"] == {"not_code": 1}
+
+
async def test_performance_findings_do_not_by_themselves_demand_review(tool, make_repo):
repo = make_repo()
repo.commit("seed", {"app.py": python_io_in_loop(in_loop=False)})
diff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.py
index 1b7120b32..64a9d533f 100644
--- a/tests/unit/server/mcp/test_change_risk.py
+++ b/tests/unit/server/mcp/test_change_risk.py
@@ -104,6 +104,35 @@ async def test_get_change_risk_honors_riskignore_and_request_filters(tmp_path, m
assert "warning" not in result
+async def test_get_change_risk_labels_the_priority_tercile_as_diff_size(tmp_path, monkeypatch):
+ """The tercile ranks diff shape, so its label names size rather than a verdict."""
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(["init", "-q"], repo)
+ _commit(repo, {"src/app.py": "value = 1\n"}, "chore: seed")
+ _commit(repo, {"src/app.py": "value = 2\n"}, "feat: app")
+
+ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")
+
+ async def _context(_: str | None) -> SimpleNamespace:
+ return SimpleNamespace(path=str(repo))
+
+ real_payload = module.change_risk_payload
+
+ def _ranked(result, **kwargs):
+ payload = real_payload(result, **kwargs)
+ payload.update(review_priority="high", classification="Elevated")
+ return payload
+
+ monkeypatch.setattr(module, "_resolve_repo_context", _context)
+ monkeypatch.setattr(module, "change_risk_payload", _ranked)
+ result = await module.get_change_risk("HEAD", baseline=0)
+
+ assert result["review_priority"] == "high"
+ assert result["classification"] == "Above-typical diff size"
+
+
@pytest.mark.asyncio
async def test_get_change_risk_bad_revspec_returns_error(tmp_path, monkeypatch) -> None:
repo = tmp_path / "repo"
diff --git a/tests/unit/server/mcp/test_risk.py b/tests/unit/server/mcp/test_risk.py
index 806a24572..ade3593a9 100644
--- a/tests/unit/server/mcp/test_risk.py
+++ b/tests/unit/server/mcp/test_risk.py
@@ -175,6 +175,21 @@ async def test_get_risk_pr_directive_splits_test_breakage(setup_mcp):
assert set(RISK_RELATED_FILE_KEYS) <= set(directive)
+async def test_get_risk_pr_summary_counts_totals_not_capped_lists(setup_mcp, monkeypatch):
+ """The summary reports every affected file, not the length of the capped list."""
+ from repowise.server.mcp_server import get_risk
+ from repowise.server.mcp_server.tool_risk import directives
+
+ monkeypatch.setattr(directives, "_MAY_BREAK_LIMIT", 0)
+ result = await get_risk(["src/auth/service.py"], changed_files=["src/auth/service.py"])
+ directive = result["directive"]
+
+ assert directive["may_break"] == []
+ assert directive["may_break_total"] == 1
+ assert "~1 downstream file(s) may be affected" in directive["summary"]
+
+
@pytest.mark.asyncio
async def test_get_risk_pr_directive_names_its_next_calls(setup_mcp):
"""The diff first, then the callers of what may break; tests_to_run gets no call."""
diff --git a/tests/unit/server/test_chat_change_risk_summary.py b/tests/unit/server/test_chat_change_risk_summary.py
index 137c1026a..3caade999 100644
--- a/tests/unit/server/test_chat_change_risk_summary.py
+++ b/tests/unit/server/test_chat_change_risk_summary.py
@@ -12,14 +12,12 @@ def test_get_change_risk_summary_is_not_generic_completed():
{
"ref": "HEAD",
"score": 7.2,
- "review_priority": "Elevated",
+ "review_priority": "high",
+ "classification": "Above-typical diff size",
"risk_percentile": 82.0,
},
)
- assert summary != "Completed"
- assert "HEAD" in summary
- assert "Elevated" in summary
- assert "p82" in summary
+ assert summary == "Diff size for HEAD: Above-typical diff size (p82.0)"
def test_every_chat_registry_tool_has_a_non_generic_summary_shape():
diff --git a/tests/unit/server/test_chat_suggestions.py b/tests/unit/server/test_chat_suggestions.py
index feb42dd74..2ad5fc7ee 100644
--- a/tests/unit/server/test_chat_suggestions.py
+++ b/tests/unit/server/test_chat_suggestions.py
@@ -151,14 +151,14 @@ def test_decision_health_mode_has_no_single_decision_to_name():
def test_a_commit_names_its_rating_without_the_gated_drivers_block():
result = {
"ref": "9f52f0a",
- "classification": "elevated",
+ "classification": "Above-typical diff size",
"review_priority": "high",
"risk_percentile": 88,
"is_fix": True,
}
texts = _texts(page_suggestions("get_change_risk", "9f52f0a", result))
- assert "Why is 9f52f0a rated elevated at p88?" in texts
+ assert "What makes 9f52f0a above-typical diff size at p88?" in texts
assert "What did 9f52f0a fix?" in texts