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 answering an unresolved target with a confident zero (#2321)

Raghav Chamadiya92481d80c2b1
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 037ada5b6..7399a249a 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -505,6 +505,12 @@ Modification risk assessment for files or a set of changed files.
**Returns:** Per-file `hotspot_score` (0-1 churn percentile), `health_score` (0-10), hotspot status, direct directed `dependents_count`, historical `co_change_partners` (each with a recency-decayed `weight`, not an integer count, and a `direction` of `a_to_b`, `b_to_a` or `undirected`, where `a` is the assessed file and `b` the partner; `conf_ab` and `conf_ba` are the share of each file's own commits that touched the other, and both are omitted on an index written before those commit totals were recorded, which also reads as `undirected`), blast radius, recommended reviewers, test gap analysis, and security signals. With `include=["graph"]`, `dependents` preserves direct versus transitive structural reach, `consumers` contains typed contract consumers only, and `cross_repo_links` retains both repository identities, direction, relationship type, evidence kind, and file- or repository-level granularity. Package-manifest links are repository-level and never invent a target file. Every typed relationship collection carries matching total/emitted/truncated fields. `relationship_analysis` distinguishes available-empty analysis from unavailable, degraded, partial, and source-truncated artifacts and retains artifact generation/provenance fields. Structural reach is not proof of runtime breakage.
+> **Unresolved targets.** A target naming no indexed file comes back as
+> `{"resolved": false, "unresolved_reason": ...}` with no counts — omitted
+> rather than zeroed, since a structural zero reads as a measured one. Reasons:
+> `unsupported_target_kind` (a `module:` id; risk is scored per file),
+> `directory`, `not_indexed` (run `repowise update`), `no_such_path`.
+
> **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.** Every response carries the facts that stop a misreading: unit,
diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.py
index 3a871ea2a..0bb81f5fe 100644
--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py
@@ -213,6 +213,12 @@ def _render_card(name: str, card: dict) -> None:
summary = card.get("risk_summary")
if summary:
console.print(f" {escape(str(summary))}")
+ if card.get("resolved") is False:
+ # The line below defaults its missing fields to numbers rather than
+ # gating on them, so stop here rather than print "0 direct dependents".
+ reason = escape(str(card.get("unresolved_reason") or "unknown"))
+ console.print(f" [dim]unresolved: {reason}[/dim]")
+ return
trend = card.get("trend") or "unknown"
console.print(
f" [dim]hotspot {float(card.get('hotspot_score') or 0.0):.0%} ({trend}) · "
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
index 461ad9b70..9d6b3af12 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py
@@ -510,6 +510,28 @@ def _load_commit_categories(meta: Any) -> dict:
return categories
+def _unresolved_reason(target: str, lookup_path: str, repo_root: str | None) -> str:
+ """Why *target* names nothing this tool can score, in the caller's terms.
+
+ ``not_indexed`` and ``no_such_path`` are spelled as
+ ``get_health._unresolved_targets`` spells them. The other two are not
+ borrowed: ``get_health``'s ``no_such_module`` means "no module of that
+ name", and it resolves a directory to ``not_indexed`` — both would
+ prescribe a fix that cannot help here.
+ """
+ if target.startswith("module:"):
+ return "unsupported_target_kind"
+ try:
+ on_disk = Path(repo_root) / lookup_path if repo_root else Path(lookup_path)
+ if on_disk.is_dir():
+ return "directory"
+ if on_disk.exists():
+ return "not_indexed"
+ except (OSError, ValueError):
+ pass
+ return "no_such_path"
+
+
async def _assess_one_target(
session: AsyncSession,
repository: Repository,
@@ -642,6 +664,24 @@ async def _assess_one_target(
)
meta = res.scalar_one_or_none()
+ symbol_target = "::" in target
+ if meta is None and lookup_path not in node_meta and not symbol_target:
+ # Nothing below measured this target, so every numeric field would be
+ # a structural zero no reader could tell from a measured one. Name the
+ # miss and emit no counts.
+ #
+ # All three conditions are required. A graph node without a git row is
+ # a real target (a new file); a ``path::Symbol`` id is an accepted
+ # input shape here, so rejecting one is a different change.
+ return {
+ "target": target,
+ "resolved": False,
+ "unresolved_reason": _unresolved_reason(target, lookup_path, repository.local_path),
+ "risk_summary": (
+ f"{target} — not resolved to an indexed file; no risk signal was computed"
+ ),
+ }
+
if meta is None:
result_data["hotspot_score"] = 0.0
result_data["is_hotspot"] = False
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 1758b7851..a0bffae1c 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
@@ -469,6 +469,10 @@ def _build_pr_directive(
# Everything trimmed below is persisted via the collector so the
# response carries an expandable [repowise#<ref>] marker for it.
for r in response["targets"].values():
+ # The counts below would be the structural zeros get_risk stopped
+ # emitting for a card that resolved nothing.
+ if r.get("resolved") is False:
+ continue
partners = r.get("co_change_partners") or []
if len(partners) > 3:
r["co_change_partners"] = partners[:3]
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.py
index bf3035d09..2def737f2 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
@@ -276,21 +276,25 @@ async def get_risk(
analyzer = PRBlastRadiusAnalyzer(session, repo_id, repository_alias=ctx.alias)
pr_blast_radius = await analyzer.analyze_files(changed_files, exclude_spec=exclude_spec)
+ # Enrichers key on a path prefix, so they will bind signal to a card that
+ # resolved nothing. Mutation is in place, so ``results`` keeps its order.
+ scored = [r for r in results if r.get("resolved") is not False]
+
# Cross-repo blast radius enrichment (Phase 3 + 4)
await _enrich_cross_repo(
- results, ctx.alias, collector, include_graph="graph" in include_set
+ scored, ctx.alias, collector, include_graph="graph" in include_set
)
# ---- Code-health enrichment --------------------------------------------
# Attach per-file health_score + top_biomarkers (up to 3) drawn from the
# health tables. Conservative: missing data → no field, never invented.
- await _enrich_health(results, ctx, repo_id)
+ await _enrich_health(scored, ctx, repo_id)
# ---- Precedent enrichment ----------------------------------------------
# One integer per target: how many dated episodes are bound here. A number
# invites a follow-up get_why; a paragraph would spend the budget of every
# caller that only wanted the risk card. Absent rather than zero.
- await asyncio.to_thread(_enrich_episodes, results, ctx.path)
+ await asyncio.to_thread(_enrich_episodes, scored, ctx.path)
response: dict = {
"targets": {r["target"]: r for r in results},
diff --git a/tests/unit/server/mcp/test_risk_unresolved_targets.py b/tests/unit/server/mcp/test_risk_unresolved_targets.py
new file mode 100644
index 000000000..815dd6dd2
--- /dev/null
+++ b/tests/unit/server/mcp/test_risk_unresolved_targets.py
@@ -0,0 +1,177 @@
+"""``get_risk`` must not answer a target it never resolved with zeros.
+
+A ``module:`` id or a directory used to come back with every numeric field
+zeroed, indistinguishable from a measured zero, while an enricher keyed on the
+path prefix bound real signal to the same card.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+#: Fields no unresolved card may carry. The four ``*_total``/direction counts
+#: are ``include=["graph"]`` keys popped from every card otherwise, so tests
+#: asserting their absence must ask for the block or prove nothing.
+_MEASUREMENT_KEYS = (
+ "dependents_count",
+ "dependents_total",
+ "direct_dependents_total",
+ "transitive_dependents_total",
+ "impact_surface_total",
+ "co_change_partners_total",
+ "hotspot_score",
+ "is_hotspot",
+ "test_gap",
+ "security_signals",
+ "episodes",
+ "health_score",
+)
+
+
+async def test_module_target_is_rejected_not_zeroed(setup_mcp):
+ from repowise.server.mcp_server import get_risk
+
+ result = await get_risk(["module:auth"], include=["graph", "churn"])
+ card = result["targets"]["module:auth"]
+
+ assert card["resolved"] is False
+ # Not ``no_such_module``: that is get_health's "no module of that name",
+ # and ``auth`` is a real module there.
+ assert card["unresolved_reason"] == "unsupported_target_kind"
+ for key in _MEASUREMENT_KEYS:
+ assert key not in card, f"{key} must be absent, not zero, on an unresolved target"
+ assert "not resolved" in card["risk_summary"]
+
+
+async def test_directory_target_is_rejected_not_zeroed(setup_mcp, tmp_path):
+ """The dangerous case: a real directory looks like an ordinary target."""
+ from repowise.server.mcp_server import get_risk
+
+ (tmp_path / "src" / "auth").mkdir(parents=True, exist_ok=True)
+
+ result = await get_risk(["src/auth"], include=["graph", "churn"])
+ card = result["targets"]["src/auth"]
+
+ assert card["resolved"] is False
+ assert card["unresolved_reason"] == "directory"
+ for key in _MEASUREMENT_KEYS:
+ assert key not in card
+
+
+async def test_missing_path_reports_the_reason_that_names_the_fix(setup_mcp, tmp_path):
+ """``not_indexed`` sends the caller to ``repowise update``; a typo does not."""
+ from repowise.server.mcp_server import get_risk
+
+ (tmp_path / "src" / "auth").mkdir(parents=True, exist_ok=True)
+ (tmp_path / "src" / "auth" / "on_disk_only.py").write_text("x = 1\n", encoding="utf-8")
+
+ result = await get_risk(["src/auth/on_disk_only.py", "src/auth/typo.py"])
+
+ assert result["targets"]["src/auth/on_disk_only.py"]["unresolved_reason"] == "not_indexed"
+ assert result["targets"]["src/auth/typo.py"]["unresolved_reason"] == "no_such_path"
+
+
+async def test_a_real_file_keeps_its_real_counts(setup_mcp):
+ """The discriminator: rejecting bad targets must not reject good ones."""
+ from repowise.server.mcp_server import get_risk
+
+ result = await get_risk(["src/auth/service.py"], include=["graph"])
+ card = result["targets"]["src/auth/service.py"]
+
+ assert "resolved" not in card
+ assert "unresolved_reason" not in card
+ assert card["dependents_count"] >= 1
+ assert card["hotspot_score"] == 0.92
+ # Pins the ``include=["graph"]`` gate open, so the ``*_total`` absences
+ # asserted above mean something.
+ assert card["dependents_total"] >= 1
+
+
+async def test_unresolved_and_resolved_targets_coexist_in_one_call(setup_mcp, tmp_path):
+ """A batch must not lose the good card, or leak counts onto the bad one."""
+ from repowise.server.mcp_server import get_risk
+
+ (tmp_path / "src" / "auth").mkdir(parents=True, exist_ok=True)
+
+ result = await get_risk(["src/auth", "src/auth/service.py"])
+ targets = result["targets"]
+
+ assert set(targets) == {"src/auth", "src/auth/service.py"}
+ assert targets["src/auth"]["resolved"] is False
+ assert targets["src/auth/service.py"]["dependents_count"] >= 1
+
+
+async def test_enrichment_does_not_bind_signal_to_an_unresolved_card(setup_mcp, tmp_path):
+ """An enricher must not attach a measurement to a card that resolved nothing."""
+ import time
+
+ from repowise.core.precedent.store import (
+ TIER_STRUCTURAL,
+ Episode,
+ EpisodeStore,
+ default_store_path,
+ )
+ from repowise.server.mcp_server import get_risk
+
+ (tmp_path / ".repowise").mkdir(parents=True, exist_ok=True)
+ (tmp_path / "src" / "auth").mkdir(parents=True, exist_ok=True)
+ with EpisodeStore(default_store_path(tmp_path)) as store:
+ store.replace_kinds(
+ tier=TIER_STRUCTURAL,
+ kinds=["layout_drift"],
+ episodes=[
+ Episode(
+ tier=TIER_STRUCTURAL,
+ kind="layout_drift",
+ subject="src/auth",
+ body="The auth package was reorganised.",
+ evidence="git log --stat src/auth",
+ nodes=("src/auth",),
+ birth_commit=None,
+ )
+ ],
+ now=time.time(),
+ )
+
+ card = (await get_risk(["src/auth"]))["targets"]["src/auth"]
+
+ assert card["resolved"] is False
+ assert "episodes" not in card
+
+
+async def test_symbol_targets_are_not_rejected(setup_mcp):
+ """``path::Symbol`` is an accepted input shape: it reaches no git row and no
+ file node, so the guard would swallow it without the carve-out.
+ """
+ from repowise.server.mcp_server import get_risk
+
+ card = (await get_risk(["src/auth/service.py::AuthService"]))["targets"][
+ "src/auth/service.py::AuthService"
+ ]
+
+ assert "resolved" not in card
+ assert card["dependents_count"] == 0
+
+
+async def test_pr_mode_does_not_stamp_counts_back_onto_an_unresolved_card(setup_mcp, tmp_path):
+ """PR mode re-walks the response's cards, not the assessed set, and restates
+ co-change counts — putting two structural zeros back without a skip.
+ """
+ from repowise.server.mcp_server import get_risk
+
+ (tmp_path / "src" / "auth").mkdir(parents=True, exist_ok=True)
+
+ result = await get_risk(["src/auth"], changed_files=["src/auth/service.py"])
+ card = result["targets"]["src/auth"]
+
+ assert card["resolved"] is False
+ assert "co_change_partners_emitted" not in card
+ assert "co_change_partners_truncated" not in card