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
feat(risk): say which side of a co-change pair leads (#2202)
Raghav Chamadiya184a65e1a774
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 3a9cdfc4f..2227ed27c 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -503,7 +503,7 @@ Modification risk assessment for files or a set of changed files.| `include` | list[string] | No | Opt-in blocks: `graph` (typed `dependents`, `consumers`, `cross_repo_links`, structural `impact_surface`, `direct_risks`), `churn` (`change_magnitude`, `risk_type`, `change_pattern`) || `repo` | string | No | *(workspace only)* Target repo alias |-**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), 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.+**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.> **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.diff --git a/packages/core/src/repowise/core/analysis/coupling/graph.py b/packages/core/src/repowise/core/analysis/coupling/graph.pyindex 7d29c885d..0b3480b99 100644--- a/packages/core/src/repowise/core/analysis/coupling/graph.py+++ b/packages/core/src/repowise/core/analysis/coupling/graph.py@@ -37,7 +37,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Protocol-from ...co_change import canonical_pair, parse_partners+from ...co_change import canonical_pair, confidence_ratio, parse_partnersclass MetricLike(Protocol):@@ -131,13 +131,6 @@ class _Pair:)-def _ratio(support: int, commits: int) -> float | None:- """Share of *commits* that also touched the partner, or ``None`` if unknown."""- if support <= 0 or commits <= 0:- return None- return round(min(support / commits, 1.0), 3)--@dataclassclass CouplingGraph:"""The assembled graph: nodes referenced by the (possibly capped) edges."""@@ -206,8 +199,8 @@ def coupling_graph(strength=round(pair.strength, 4),last_co_change=pair.last,support=pair.support,- confidence_ab=_ratio(pair.support, pair.commits_a),- confidence_ba=_ratio(pair.support, pair.commits_b),+ confidence_ab=confidence_ratio(pair.support, pair.commits_a),+ confidence_ba=confidence_ratio(pair.support, pair.commits_b),structural=pair.structural,dependency_kind=pair.dependency_kind,)diff --git a/packages/core/src/repowise/core/co_change.py b/packages/core/src/repowise/core/co_change.pyindex d72135774..e6673a2f7 100644--- a/packages/core/src/repowise/core/co_change.py+++ b/packages/core/src/repowise/core/co_change.py@@ -36,6 +36,7 @@ __all__ = ["STRUCTURAL_UNEXPLAINED","CoChangePartner","canonical_pair",+ "confidence_ratio","parse_partners",]@@ -157,3 +158,15 @@ def parse_partners(raw: object) -> list[CoChangePartner]:def canonical_pair(a: str, b: str) -> tuple[str, str]:"""The two paths in a stable order, so an undirected pair deduplicates."""return (a, b) if a < b else (b, a)+++def confidence_ratio(support: int, commits: int) -> float | None:+ """Share of *commits* that also touched the partner, or ``None`` if unknown.++ Lives here rather than beside either caller because the coupling graph and+ the risk tools must agree on what a confidence means; a second copy of the+ formula is how the two drift apart.+ """+ if support <= 0 or commits <= 0:+ return None+ return round(min(support / commits, 1.0), 3)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.pyindex dcae38cdc..3ebc804a6 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@@ -12,7 +12,7 @@ from sqlalchemy import select, textfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.health.engine import _has_paired_test_file, _path_basenames-from repowise.core.co_change import parse_partners+from repowise.core.co_change import confidence_ratio, parse_partnersfrom repowise.core.persistence.models import (GitMetadata,GraphNode,@@ -347,6 +347,19 @@ async def _get_security_signals(session: AsyncSession, repo_id: str, target: strreturn []+def _co_change_direction(conf_ab: float | None, conf_ba: float | None) -> str:+ """Which side of a pair leads, where ``a`` is the target and ``b`` the partner.++ A higher ``conf_ab`` means the target seldom changes without the partner, so+ the target is the antecedent. Equal confidences, or an index written before+ the two commit totals were recorded, stay ``undirected`` rather than having+ a lead broken arbitrarily.+ """+ if conf_ab is None or conf_ba is None or conf_ab == conf_ba:+ return "undirected"+ return "a_to_b" if conf_ab > conf_ba else "b_to_a"++def _build_co_changes(meta: Any, structural_related: Any, exclude_spec: Any) -> tuple[list[dict], int]:@@ -358,6 +371,9 @@ def _build_co_changes(The strength field is emitted as ``weight``, not ``count``: the stored valueis a recency-decayed sum (``exp(-age_days / tau)`` per shared commit), so itis fractional. Named ``count`` it read as "5.52 co-changes" to every agent.++ ``conf_ab`` and ``conf_ba`` are the two directional confidences behind+ ``direction``, omitted when the commit totals are unknown."""partners_sorted = parse_partners(meta.co_change_partners_json)relation_types = structural_related if isinstance(structural_related, dict) else {}@@ -366,12 +382,14 @@ def _build_co_changes(for partner in partners_sorted:path = partner.file_pathtypes = sorted(relation_types.get(path, ()))+ conf_ab = confidence_ratio(partner.support, partner.self_commits)+ conf_ba = confidence_ratio(partner.support, partner.partner_commits)row = {"file_path": path,"weight": partner.weight,"last_co_change": partner.last_co_change,"relationship_type": "co_change",- "direction": "undirected",+ "direction": _co_change_direction(conf_ab, conf_ba),"evidence_kind": "historical","provenance": "git_history","has_structural_link": path in related_paths,@@ -383,6 +401,10 @@ def _build_co_changes(row["structural_relationship_types"] = typesif partner.support:row["support"] = partner.support+ if conf_ab is not None:+ row["conf_ab"] = conf_ab+ if conf_ba is not None:+ row["conf_ba"] = conf_barows.append(row)population = filter_dicts_by_key(rows, "file_path", exclude_spec)return population, len(population)diff --git a/tests/unit/server/mcp/test_risk.py b/tests/unit/server/mcp/test_risk.pyindex dc1e6edd9..1dbe3859d 100644--- a/tests/unit/server/mcp/test_risk.py+++ b/tests/unit/server/mcp/test_risk.py@@ -6,6 +6,8 @@ test data, mirroring the conftest pattern from the REST API tests.from __future__ import annotations+import json+import pytest@@ -616,3 +618,78 @@ async def test_missing_tests_totals_use_full_precap_changed_file_population(setuassert directive["missing_tests_reduced_reason"] == "construction_cap"assert directive["missing_tests_truncated"] is Trueassert directive["missing_tests_omitted"] == 2+++def _co_change_row(**partner):+ """The single row ``_build_co_changes`` makes from one stored partner record."""+ from types import SimpleNamespace++ from repowise.server.mcp_server.tool_risk.assessment import _build_co_changes++ meta = SimpleNamespace(+ co_change_partners_json=json.dumps([{"file_path": "b.py", **partner}])+ )+ rows, total = _build_co_changes(meta, {}, None)+ assert total == 1+ return rows[0]+++def test_co_change_direction_target_leads():+ """The target seldom moves without the partner, so it is the antecedent."""+ row = _co_change_row(count=2.0, frequency=8, self_commits=10, partner_commits=20)++ assert row["direction"] == "a_to_b"+ assert row["conf_ab"] == 0.8+ assert row["conf_ba"] == 0.4+++def test_co_change_direction_partner_leads():+ """The mirror case: the partner is the side that cannot move alone."""+ row = _co_change_row(count=2.0, frequency=8, self_commits=20, partner_commits=10)++ assert row["direction"] == "b_to_a"+ assert row["conf_ab"] == 0.4+ assert row["conf_ba"] == 0.8+++def test_co_change_direction_tie_is_undirected():+ """Equal confidences report a tie rather than breaking the lead arbitrarily."""+ row = _co_change_row(count=2.0, frequency=5, self_commits=10, partner_commits=10)++ assert row["direction"] == "undirected"+ assert row["conf_ab"] == 0.5+ assert row["conf_ba"] == 0.5+++def test_co_change_direction_without_commit_totals():+ """An index written before the commit totals existed stays undirected.++ ``self_commits``/``partner_commits`` are absent from such a record, so there+ is no denominator to divide by; the confidences are omitted rather than+ emitted as a guessed zero.+ """+ row = _co_change_row(count=2.0, frequency=8)++ assert row["direction"] == "undirected"+ assert "conf_ab" not in row+ assert "conf_ba" not in row+++async def test_get_risk_co_change_rows_carry_direction(setup_mcp):+ """The field survives the whole pipeline, and says nothing it cannot back.++ The seeded records carry no commit totals, so every row must come back+ ``undirected`` with no confidence beside it -- a guessed ``0.0`` here would+ read as "these files never change together", the opposite of unknown.+ """+ from repowise.server.mcp_server import get_risk++ result = await get_risk(["src/auth/service.py"])+ partners = result["targets"]["src/auth/service.py"]["co_change_partners"]++ assert partners+ for p in partners:+ assert p["direction"] == "undirected"+ assert "conf_ab" not in p+ assert "conf_ba" not in p