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.

feat(change-risk): change-risk health reads the index's dependents on both sides (#4128)

Raghav Chamadiya11c0d841bf94
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 13bbd59d7..39750c7c2 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -280,7 +280,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`, 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.
+`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, and `context`: `index_dependents` when centrality gates read the index's dependents counts on both sides, `changed_files` with no index), `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. Tree-sitter query files (`.scm` under a `queries` directory) and text templates (`.j2`, `.jinja`, `.jinja2`, `.tmpl`, `.tpl`, `.hbs`, `.mustache`, `.ejs`, `.njk`) are skipped with reason `not_analyzable_data`, which also never makes a run `partial`; a change made only of them reads `clear_in_analyzed_scope` with its own headline, since they can still change behaviour. 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/core/src/repowise/core/analysis/change_health/analyzer.py b/packages/core/src/repowise/core/analysis/change_health/analyzer.py
index eb2357db5..9596b71f0 100644
--- a/packages/core/src/repowise/core/analysis/change_health/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/change_health/analyzer.py
@@ -97,11 +97,11 @@ class RevisionHealthAnalyzer:
remainder are closure context that shapes resolution without being
charged to the change.
- *dependents* is the other side's :attr:`RevisionAnalysis.dependents`.
- Both sides see only the changed files, so a file's dependents count
- here is a slice of its real one, and an import added between two
- changed files can carry it across a centrality gate. Scoring both
- sides against one count keeps that from reading as a code change.
+ *dependents* is one count both sides score against: the index's when
+ there is one, else the other side's :attr:`RevisionAnalysis.dependents`.
+ Both sides see only the changed files, so a local count is a slice of
+ the real one, and an import added between two changed files can carry
+ a file across a centrality gate without any change to its code.
"""
result = RevisionAnalysis()
parsed, usable = self._parse(sources, result)
diff --git a/packages/core/src/repowise/core/analysis/change_health/index_context.py b/packages/core/src/repowise/core/analysis/change_health/index_context.py
new file mode 100644
index 000000000..015c72075
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/change_health/index_context.py
@@ -0,0 +1,52 @@
+"""The index's file centrality, for a change-health pass that sees only changed files.
+
+Centrality gates read how many files use a file. An isolated pass counts only
+the changed files, so the same code scores differently there than in the full
+index; feeding both sides the index's counts keeps the two readings in step.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from ...ids import SYMBOL_SEP, is_external
+from ...ingestion.cohesion import records_no_use
+from ...persistence.models import GraphEdge
+
+#: History, not code: the edge kind the in-memory dependents count leaves out.
+_NOT_A_USE = ("co_changes",)
+
+
+async def index_dependents(session: AsyncSession, repository_id: str) -> dict[str, int]:
+ """``{file: distinct files that use it}``, counted as the health engine counts."""
+ rows = await session.execute(
+ select(GraphEdge.source_node_id, GraphEdge.target_node_id, GraphEdge.hint_source)
+ .where(
+ GraphEdge.repository_id == repository_id,
+ GraphEdge.edge_type.not_in(_NOT_A_USE),
+ )
+ .distinct()
+ )
+ return dependents_counts(rows.all())
+
+
+def dependents_counts(edges: Iterable[tuple[str, str, str | None]]) -> dict[str, int]:
+ """Distinct using files per file from ``(source, target, hint)`` edges.
+
+ Symbols, externals, self-edges and edges that record no use are left out.
+ """
+ users: dict[str, set[str]] = {}
+ for source, target, hint in edges:
+ if source == target or not _is_file(source) or not _is_file(target):
+ continue
+ if records_no_use({"hint_source": hint}, source, target):
+ continue
+ users.setdefault(target, set()).add(source)
+ return {target: len(sources) for target, sources in users.items()}
+
+
+def _is_file(node_id: str) -> bool:
+ return SYMBOL_SEP not in node_id and not is_external(node_id)
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 702bcb53f..0863fee7b 100644
--- a/packages/core/src/repowise/core/analysis/change_health/models.py
+++ b/packages/core/src/repowise/core/analysis/change_health/models.py
@@ -200,6 +200,8 @@ class ChangeHealthDelta:
timing_ms: float = 0.0
cache_hit: bool = False
limits: list[str] = field(default_factory=list)
+ #: Where centrality gates read dependents: ``index_dependents`` or ``changed_files``.
+ context: str = "changed_files"
#: Per-file scores on both sides, largest structure move first.
files: list[FileScoreDelta] = field(default_factory=list)
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 4d60b3756..405410638 100644
--- a/packages/core/src/repowise/core/analysis/change_health/service.py
+++ b/packages/core/src/repowise/core/analysis/change_health/service.py
@@ -11,6 +11,7 @@ import hashlib
import threading
import time
from collections import OrderedDict
+from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import PurePosixPath
@@ -87,6 +88,8 @@ class DeltaRequest:
exclude_patterns: tuple[str, ...] = ()
#: Gitignore-style paths to keep; empty keeps every path.
include_paths: tuple[str, ...] = ()
+ #: ``{path: dependents}`` from the index, scored on both sides when given.
+ dependents: Mapping[str, int] | None = None
class ChangeHealthDeltaService:
@@ -182,6 +185,7 @@ class ChangeHealthDeltaService:
repr(tuple(request.extensions)),
repr(tuple(request.exclude_patterns)),
repr(tuple(request.include_paths)),
+ _dependents_digest(request.dependents),
)
return hashlib.sha256("\x00".join(parts).encode("utf-8")).hexdigest()
@@ -243,7 +247,8 @@ class ChangeHealthDeltaService:
fingerprint=self.fingerprint,
)
- sides = self._analyze(pair, eligible, departed)
+ index = _index_dependents(request.dependents, pair.rename_map())
+ sides = self._analyze(pair, eligible, departed, index)
skipped.update(sides.head_run.skipped)
skipped.update(_held_origins(sides.head_sources, self.repo_path))
skipped.update(_base_failures(eligible + departed, sides.base_run, skipped))
@@ -282,6 +287,7 @@ class ChangeHealthDeltaService:
skipped=skipped,
moved_to={old: new for old, new in moves.destinations().items() if old in gone},
limits=_limits(sides.head_run.findings_for(subject)),
+ context="index_dependents" if index is not None else "changed_files",
files=file_score_deltas(
sides.base_run.metrics,
sides.head_run.metrics,
@@ -294,7 +300,11 @@ class ChangeHealthDeltaService:
return delta
def _analyze(
- self, pair: RevisionPair, eligible: list[FileChange], departed: list[FileChange]
+ self,
+ pair: RevisionPair,
+ eligible: list[FileChange],
+ departed: list[FileChange],
+ index: dict[str, int] | None,
) -> _Sides:
"""Read and analyse both sides; *departed* (deleted) files go on the base side only.
@@ -310,9 +320,13 @@ class ChangeHealthDeltaService:
)
base_sources = self.source.read(pair.base_sha, base_paths)
rename = pair.rename_map()
- head_run = self.analyzer.analyze(head_sources, subject_paths=set(head_paths))
+ head_run = self.analyzer.analyze(
+ head_sources, subject_paths=set(head_paths), dependents=index
+ )
base_run = self.analyzer.analyze(
- base_sources, subject_paths=set(base_paths), dependents=_on_base(head_run, rename)
+ base_sources,
+ subject_paths=set(base_paths),
+ dependents=index if index is not None else _on_base(head_run, rename),
)
return _Sides(head_paths, head_sources, base_sources, head_run, base_run, rename)
@@ -583,6 +597,30 @@ def _on_base(head_run: RevisionAnalysis, rename: dict[str, str]) -> dict[str, in
return {to_base.get(path, path): count for path, count in head_run.dependents.items()}
+def _index_dependents(
+ dependents: Mapping[str, int] | None, rename: dict[str, str]
+) -> dict[str, int] | None:
+ """The index's counts with each renamed file under both of its paths."""
+ if dependents is None:
+ return None
+ merged = dict(dependents)
+ for old, new in rename.items():
+ count = dependents.get(old, dependents.get(new))
+ if count is not None:
+ merged.setdefault(old, count)
+ merged.setdefault(new, count)
+ return merged
+
+
+def _dependents_digest(dependents: Mapping[str, int] | None) -> str:
+ if dependents is None:
+ return ""
+ digest = hashlib.sha256()
+ for path, count in sorted(dependents.items()):
+ digest.update(f"{path}\t{count}\n".encode())
+ return digest.hexdigest()
+
+
def _hunks(changes: list[FileChange]) -> dict[str, list[tuple[int, int, int, int]]]:
"""Each changed file's diff hunks, by head path, for the matcher's line map."""
return {c.head_path: c.diff.hunks for c in changes if c.head_path and c.diff}
diff --git a/packages/server/src/repowise/server/mcp_server/_change_health.py b/packages/server/src/repowise/server/mcp_server/_change_health.py
index 8e891b6d7..3ccde06f8 100644
--- a/packages/server/src/repowise/server/mcp_server/_change_health.py
+++ b/packages/server/src/repowise/server/mcp_server/_change_health.py
@@ -185,7 +185,7 @@ def health_delta_block(delta: ChangeHealthDelta, *, revspec: str | None) -> dict
if delta.head is not None:
block["head"] = delta.head.as_dict()
if delta.fingerprint is not None:
- block["analyzer"] = delta.fingerprint.as_dict()
+ block["analyzer"] = {**delta.fingerprint.as_dict(), "context": delta.context}
if len(delta.findings) > len(emitted):
block["findings_reduced_reason"] = "top_findings_cap"
block["all_findings_via"] = _call(revspec, extra="include=['findings']")
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/health.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/health.py
index cb0364a41..aa5d1906d 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk/health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/health.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
import threading
from collections import OrderedDict
from typing import Any
@@ -110,19 +111,60 @@ def _delta_service(repo_path: str) -> ChangeHealthDeltaService:
return service
+async def _index_dependents(ctx: Any) -> dict[str, int] | None:
+ """The index's dependents count per file, or ``None`` with no readable index."""
+ from repowise.core.analysis.change_health.index_context import index_dependents
+ from repowise.core.persistence.database import get_session
+
+ session_factory = getattr(ctx, "session_factory", None)
+ if session_factory is None:
+ return None
+ try:
+ async with get_session(session_factory) as session:
+ repository = await _pkg._get_repo(session)
+ return await index_dependents(session, repository.id)
+ except Exception as exc:
+ # An input that sharpens the delta, never a reason to fail the call.
+ log.warning("change_health_index_dependents_failed", error=str(exc))
+ return None
+
+
+async def _delta_with_index(
+ ctx: Any,
+ revspec: str | None,
+ extensions: tuple[str, ...],
+ exclude_patterns: tuple[str, ...],
+ include_paths: tuple[str, ...],
+) -> Any:
+ """Read the index's dependents, then compare off the event loop."""
+ dependents = await _index_dependents(ctx)
+ return await asyncio.to_thread(
+ _pkg._compare_health,
+ str(ctx.path),
+ revspec,
+ extensions,
+ exclude_patterns,
+ include_paths,
+ dependents,
+ )
+
+
def _compare_health(
repo_path: str,
revspec: str | None,
extensions: tuple[str, ...],
exclude_patterns: tuple[str, ...],
include_paths: tuple[str, ...] = (),
+ dependents: dict[str, int] | None = None,
) -> Any:
"""Run the comparison, degrading to an explicit unavailable state."""
from repowise.core.analysis.change_health.models import ChangeHealthDelta
try:
return _pkg._delta_service(repo_path).compare(
- DeltaRequest(repo_path, revspec, extensions, exclude_patterns, include_paths)
+ DeltaRequest(
+ repo_path, revspec, extensions, exclude_patterns, include_paths, dependents
+ )
)
except Exception as exc:
log.warning("change_health_comparison_failed", revspec=revspec, error=str(exc))
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py
index a4da344e9..9e75035dd 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py
@@ -27,7 +27,7 @@ from .changed import _changed_in_scope, _push_change
from .cross_repo import _cross_repo_block
from .health import (
_attach_health_references,
- _compare_health,
+ _delta_with_index,
_evidence_block,
_repository,
_scored_repo,
@@ -234,9 +234,8 @@ async def get_change_risk(
# The delta is the expensive half and needs nothing the enrichments need,
# so it runs alongside them rather than after.
delta_task = asyncio.create_task(
- asyncio.to_thread(
- _compare_health,
- str(ctx.path),
+ _delta_with_index(
+ ctx,
revspec,
tuple(extensions or ()),
tuple(result.riskignore_excludes + result.request_excludes),
diff --git a/tests/unit/change_health/test_index_context.py b/tests/unit/change_health/test_index_context.py
new file mode 100644
index 000000000..9a9e30511
--- /dev/null
+++ b/tests/unit/change_health/test_index_context.py
@@ -0,0 +1,70 @@
+"""Change-health centrality reads the index's dependents counts when one exists."""
+
+from __future__ import annotations
+
+from repowise.core.analysis.change_health.analyzer import RevisionHealthAnalyzer
+from repowise.core.analysis.change_health.index_context import dependents_counts
+from repowise.core.analysis.change_health.service import ChangeHealthDeltaService, DeltaRequest
+
+from .conftest import git, python_complex
+
+
+class _Recording(RevisionHealthAnalyzer):
+ def __init__(self) -> None:
+ super().__init__()
+ self.seen: list[dict[str, int] | None] = []
+
+ def analyze(self, sources, *, subject_paths, dependents=None):
+ self.seen.append(None if dependents is None else dict(dependents))
+ return super().analyze(sources, subject_paths=subject_paths, dependents=dependents)
+
+
+def _compare(repo, dependents=None):
+ analyzer = _Recording()
+ service = ChangeHealthDeltaService(repo_path=str(repo.path), analyzer=analyzer)
+ delta = service.compare(DeltaRequest(str(repo.path), "HEAD", dependents=dependents))
+ return delta, analyzer.seen
+
+
+def test_both_sides_score_against_the_index_counts(make_repo):
+ repo = make_repo()
+ repo.commit("seed", {"core.py": python_complex("run", 8)})
+ git(repo.path, "mv", "core.py", "engine.py")
+ repo.commit("rename", {"engine.py": python_complex("run", 9)})
+
+ delta, seen = _compare(repo, {"core.py": 7, "other.py": 3})
+
+ head, base = seen
+ assert head == base
+ # A renamed file keeps its count under both paths.
+ assert head["engine.py"] == head["core.py"] == 7
+ assert delta.context == "index_dependents"
+
+
+def test_without_an_index_the_changed_files_alone_set_centrality(make_repo):
+ repo = make_repo()
+ repo.commit("seed", {"core.py": python_complex("run", 8)})
+ repo.commit("grow", {"core.py": python_complex("run", 9)})
+
+ delta, seen = _compare(repo)
+
+ assert seen[0] is None
+ assert delta.context == "changed_files"
+
+
+def test_dependents_count_distinct_files_that_use_the_file():
+ from repowise.core.ingestion.cohesion import SAME_PACKAGE_HINT
+
+ edges = [
+ ("b.py", "a.py", None),
+ ("b.py", "a.py", "dynamic"),
+ ("c.py", "a.py", None),
+ ("a.py", "a.py", None),
+ ("c.py::f", "a.py", None),
+ ("external:requests", "a.py", None),
+ ("a.py", "b.py::Cls", None),
+ # A Go same-package edge joins two files that import nothing from each other.
+ ("x.go", "y.go", SAME_PACKAGE_HINT),
+ ]
+ assert dependents_counts(edges) == {"a.py": 2}
+
diff --git a/tests/unit/change_health/test_mcp_contract.py b/tests/unit/change_health/test_mcp_contract.py
index cfffa14e6..a3dfa0bb1 100644
--- a/tests/unit/change_health/test_mcp_contract.py
+++ b/tests/unit/change_health/test_mcp_contract.py
@@ -288,7 +288,7 @@ def test_every_request_filter_is_part_of_the_cache_key(make_repo):
plain = DeltaRequest(str(repo.path), "HEAD")
# repo_path and revspec reach the key through the service and the resolved pair.
for field in dataclasses.fields(DeltaRequest):
- if field.name in ("repo_path", "revspec"):
+ if field.name in ("repo_path", "revspec", "dependents"):
continue
narrowed = dataclasses.replace(plain, **{field.name: ("vendor/",)})
assert service._cache_key(narrowed, pair) != service._cache_key(plain, pair), field.name
@@ -296,6 +296,9 @@ def test_every_request_filter_is_part_of_the_cache_key(make_repo):
joined = dataclasses.replace(plain, **{field.name: ("a,b",)})
split = dataclasses.replace(plain, **{field.name: ("a", "b")})
assert service._cache_key(joined, pair) != service._cache_key(split, pair), field.name
+ counted = dataclasses.replace(plain, dependents={"app.py": 3})
+ recounted = dataclasses.replace(plain, dependents={"app.py": 4})
+ assert len({service._cache_key(r, pair) for r in (plain, counted, recounted)}) == 3
async def test_include_paths_as_a_string_filters_like_the_list(tool, make_repo):
diff --git a/tests/unit/server/mcp/test_tool_change_risk.py b/tests/unit/server/mcp/test_tool_change_risk.py
index 88c3f9fc5..e482412f3 100644
--- a/tests/unit/server/mcp/test_tool_change_risk.py
+++ b/tests/unit/server/mcp/test_tool_change_risk.py
@@ -878,3 +878,16 @@ def test_the_patch_coverage_action_joins_the_directive(monkeypatch):
assert payload["directive"]["next_actions"][-1] == (
"1 changed executable line since origin/main is uncovered; extend tests/test_a.py"
)
+
+
+async def test_index_dependents_come_from_the_stored_graph(setup_mcp, factory):
+ """Distinct importing files per file, read once for both sides of the delta."""
+ from types import SimpleNamespace
+
+ from repowise.server.mcp_server.tool_change_risk.health import _index_dependents
+
+ counts = await _index_dependents(SimpleNamespace(session_factory=factory))
+ assert counts["src/auth/service.py"] == 2
+ assert counts["src/db/models.py"] == 1
+ assert await _index_dependents(SimpleNamespace(session_factory=None)) is None