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(change-risk): scope every per-file block to include_paths, not only the health delta (#3730)

Swati Ahuja0179554f6199
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 87ec89269..c9c45e964 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -263,7 +263,7 @@ Reviews one commit, a `base..head` range, or uncommitted work by comparing the t
| `revspec` | string | uncommitted work | A commit, `base..head`, or `base...head` (from the merge-base). Pass `HEAD` when the tree is clean |
| `extensions` | list[string] | all | File suffixes to count, e.g. `[".py", ".ts"]` |
| `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 |
+| `include_paths` | list[string] or string | all | Gitignore-style paths to keep, as a list or one comma-separated string. Like `exclude_patterns`, it scopes the score, the health delta and every per-file block; `impacted_tests` still selects over the whole change |
| `baseline` | int | `200` | Recent commits sampled for percentile ranking; `0` disables percentiles |
| `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 |
diff --git a/packages/core/src/repowise/core/analysis/change_health/sources.py b/packages/core/src/repowise/core/analysis/change_health/sources.py
index 1ee5aada7..aca5c54e1 100644
--- a/packages/core/src/repowise/core/analysis/change_health/sources.py
+++ b/packages/core/src/repowise/core/analysis/change_health/sources.py
@@ -15,7 +15,7 @@ from pathlib import Path
from typing import Protocol
from ..changed_lines import FileDiff, is_shallow_root, parse_unified_diff, untracked_diffs
-from ..git_cli import split_revspec, untracked_paths
+from ..git_cli import path_filter, split_revspec, untracked_paths
GIT_TIMEOUT_SECONDS = 120
@@ -357,34 +357,9 @@ def filter_changes(
the change manifest counted have to be the same change; two copies of this
rule drift the moment either grows a case.
"""
- import pathspec
-
- spec = (
- pathspec.PathSpec.from_lines("gitwildmatch", exclude_patterns)
- if exclude_patterns
- else None
- )
- keep = (
- pathspec.PathSpec.from_lines("gitwildmatch", include_paths)
- if include_paths
- else None
- )
- exts = {e if e.startswith(".") else f".{e}" for e in extensions}
- return [change for change in changes if _counts(change, spec, exts, keep)]
-
-
-def _counts(
- change: FileChange, spec: object | None, exts: set[str], keep: object | None = None
-) -> bool:
- """Whether *change* survives the caller's filters. One path, one decision."""
- path = change.head_path or change.base_path or ""
- if not path:
- return False
- if keep is not None and not keep.match_file(path): # type: ignore[attr-defined]
- return False
- if spec is not None and spec.match_file(path): # type: ignore[attr-defined]
- return False
- return not exts or any(path.endswith(ext) for ext in exts)
+ counts = path_filter(extensions, exclude_patterns, include_paths)
+ # A deletion has no head path, so it is matched on the path it had.
+ return [c for c in changes if (path := c.head_path or c.base_path) and counts(path)]
def _iter_name_status(raw: str) -> Iterator[tuple[str, str, str]]:
diff --git a/packages/core/src/repowise/core/analysis/change_risk/baseline.py b/packages/core/src/repowise/core/analysis/change_risk/baseline.py
index 0e11a9426..6067e3b90 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/baseline.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/baseline.py
@@ -11,8 +11,7 @@ from __future__ import annotations
import subprocess
from typing import NamedTuple
-import pathspec
-
+from ..git_cli import path_filter
from .features import GIT_TIMEOUT_SECONDS, _git, features_from_file_changes
from .fix_history import change_fix_density
from .model import score_change
@@ -115,6 +114,7 @@ def baseline_samples(
limit: int,
extensions: tuple[str, ...],
exclude_patterns: tuple[str, ...] = (),
+ include_paths: tuple[str, ...] = (),
) -> list[BaselineSample]:
"""Score the repo's recent commits to build a local risk distribution.
@@ -127,8 +127,8 @@ def baseline_samples(
cheap enough for a pre-merge gate. Experience is left unknown for the
baseline; the target is ranked with experience likewise unknown, so the
comparison is like-with-like: a diff-shape percentile within this repo.
- *exclude_patterns* use gitignore syntax and are applied to every sampled
- commit, matching the target change's filtering.
+ *exclude_patterns* and *include_paths* use gitignore syntax and are applied
+ to every sampled commit, matching the target change's filtering.
"""
# stdin=DEVNULL + timeout: a stuck git must not hang the caller (on MCP
# stdio transport an inherited pipe handle can wedge the whole session).
@@ -146,7 +146,7 @@ def baseline_samples(
).stdout
samples: list[BaselineSample] = []
- exclude_spec = pathspec.PathSpec.from_lines("gitwildmatch", exclude_patterns)
+ counts = path_filter(extensions, exclude_patterns, include_paths)
for block in out.split("\x1e"):
lines = block.strip().split("\n")
if not lines or not lines[0]:
@@ -158,9 +158,7 @@ def baseline_samples(
if len(parts) != 3:
continue
a_raw, d_raw, path = parts
- if extensions and not path.endswith(extensions):
- continue
- if exclude_spec.match_file(path):
+ if not counts(path):
continue
a = int(a_raw) if a_raw.isdigit() else 0
d = int(d_raw) if d_raw.isdigit() else 0
@@ -178,6 +176,7 @@ def baseline_samples_cached(
limit: int,
extensions: tuple[str, ...],
exclude_patterns: tuple[str, ...] = (),
+ include_paths: tuple[str, ...] = (),
) -> list[BaselineSample]:
"""Memoized :func:`baseline_samples`, keyed on the resolved anchor sha.
@@ -189,11 +188,13 @@ def baseline_samples_cached(
"""
sha = _resolve_anchor_sha(repo_path, anchor)
if sha is None:
- return baseline_samples(repo_path, anchor, limit, extensions, exclude_patterns)
- key = (repo_path, sha, limit, extensions, exclude_patterns)
+ return baseline_samples(
+ repo_path, anchor, limit, extensions, exclude_patterns, include_paths
+ )
+ key = (repo_path, sha, limit, extensions, exclude_patterns, include_paths)
if key in _BASELINE_CACHE:
return _BASELINE_CACHE[key]
- samples = baseline_samples(repo_path, anchor, limit, extensions, exclude_patterns)
+ samples = baseline_samples(repo_path, anchor, limit, extensions, exclude_patterns, include_paths)
if len(_BASELINE_CACHE) >= _BASELINE_CACHE_MAX:
_BASELINE_CACHE.clear()
_BASELINE_CACHE[key] = samples
diff --git a/packages/core/src/repowise/core/analysis/change_risk/features.py b/packages/core/src/repowise/core/analysis/change_risk/features.py
index 9a8774703..1a8ff85f9 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/features.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/features.py
@@ -17,16 +17,14 @@ offline calibration. Two entry points:
from __future__ import annotations
import math
-from collections.abc import Iterable
+from collections.abc import Callable, Iterable
from dataclasses import dataclass
-import pathspec
-
from ...ingestion.git_indexer._constants import is_fix_commit
from ..changed_lines import untracked_diffs
-# Re-exported: callers across the package import these from here.
-from ..git_cli import GIT_TIMEOUT_SECONDS, _git, split_revspec # noqa: F401
+# All but path_filter are re-exported: callers across the package import them from here.
+from ..git_cli import GIT_TIMEOUT_SECONDS, _git, path_filter, split_revspec # noqa: F401
#: ``ChangeFeatures.ref`` for a score of the uncommitted change. Not a revspec —
#: it names the unit scored, in the same slot a sha or ``base..head`` occupies.
@@ -65,14 +63,13 @@ def revspec_head(revspec: str | None) -> str:
def _accumulate_numstat(
- numstat: str, extensions: tuple[str, ...], exclude_patterns: tuple[str, ...]
+ numstat: str, counts: Callable[[str], bool]
) -> tuple[int, int, int, set[str], set[str], list[int], list[tuple[str, int]]]:
la = ld = nf = 0
dirs: set[str] = set()
subs: set[str] = set()
per_file: list[int] = []
files: list[tuple[str, int]] = []
- exclude_spec = pathspec.PathSpec.from_lines("gitwildmatch", exclude_patterns)
for row in numstat.strip().split("\n"):
if not row:
continue
@@ -80,9 +77,7 @@ def _accumulate_numstat(
if len(parts) != 3:
continue
a_raw, d_raw, path = parts
- if extensions and not path.endswith(extensions):
- continue
- if exclude_spec.match_file(path):
+ if not counts(path):
continue
a = int(a_raw) if a_raw.isdigit() else 0
d = int(d_raw) if d_raw.isdigit() else 0
@@ -232,6 +227,7 @@ def extract_worktree_features(
*,
extensions: tuple[str, ...] = (),
exclude_patterns: tuple[str, ...] = (),
+ include_paths: tuple[str, ...] = (),
) -> ChangeFeatures:
"""Extract features for the uncommitted change: the diff against ``HEAD``.
@@ -252,7 +248,7 @@ def extract_worktree_features(
if rows:
numstat = numstat.rstrip("\n") + "\n" + "\n".join(rows)
la, ld, nf, dirs, subs, per_file, files = _accumulate_numstat(
- numstat, extensions, exclude_patterns
+ numstat, path_filter(extensions, exclude_patterns, include_paths)
)
author = _git(["config", "user.name"], root, check=False).strip()
return ChangeFeatures(
@@ -277,12 +273,13 @@ def extract_commit_features(
*,
extensions: tuple[str, ...] = (),
exclude_patterns: tuple[str, ...] = (),
+ include_paths: tuple[str, ...] = (),
) -> ChangeFeatures:
"""Extract change features for a single commit.
*extensions* optionally restricts the counted files to a set of suffixes
- (e.g. ``(".py",)``); *exclude_patterns* uses gitignore syntax to omit
- changed paths. Empty filters count every changed file.
+ (e.g. ``(".py",)``); *exclude_patterns* and *include_paths* use gitignore
+ syntax to omit or keep changed paths. Empty filters count every changed file.
"""
meta = _git(["show", "-s", "--format=%an%x00%s", sha], repo_path).strip("\n")
author, _, subject = meta.partition("\x00")
@@ -292,7 +289,7 @@ def extract_commit_features(
# No effect on a non-merge commit.
numstat = _git(["show", sha, "--numstat", "--format=", "-m", "--first-parent"], repo_path)
la, ld, nf, dirs, subs, per_file, files = _accumulate_numstat(
- numstat, extensions, exclude_patterns
+ numstat, path_filter(extensions, exclude_patterns, include_paths)
)
# check=False: a root commit has no parent and that is not an error.
parent = _git(["rev-parse", "--verify", "--quiet", f"{sha}^"], repo_path, check=False).strip()
@@ -320,6 +317,7 @@ def extract_range_features(
*,
extensions: tuple[str, ...] = (),
exclude_patterns: tuple[str, ...] = (),
+ include_paths: tuple[str, ...] = (),
sep: str = "..",
) -> ChangeFeatures:
"""Extract features for a ``base..head`` range scored as one change.
@@ -330,7 +328,7 @@ def extract_range_features(
"""
numstat = _git(["diff", "--numstat", f"{base}{sep}{head}"], repo_path)
la, ld, nf, dirs, subs, per_file, files = _accumulate_numstat(
- numstat, extensions, exclude_patterns
+ numstat, path_filter(extensions, exclude_patterns, include_paths)
)
meta = _git(["show", "-s", "--format=%an%x00%s", head], repo_path).strip("\n")
author, _, subject = meta.partition("\x00")
diff --git a/packages/core/src/repowise/core/analysis/change_risk/service.py b/packages/core/src/repowise/core/analysis/change_risk/service.py
index febc5a67f..26a0d767b 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/service.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/service.py
@@ -168,6 +168,7 @@ def score_live_change(
*,
extensions: tuple[str, ...] = (),
exclude_patterns: tuple[str, ...] = (),
+ include_paths: tuple[str, ...] = (),
baseline: int = 200,
) -> ChangeRiskResult:
"""Score a commit or ``base..head`` range with optional live filters.
@@ -193,7 +194,10 @@ def score_live_change(
# block or entry is repowise's output too, while the user's edits count.
worktree_ignores = from_riskignore + generated_worktree_paths(repo_path)
uncommitted = extract_worktree_features(
- repo_path, extensions=extensions, exclude_patterns=worktree_ignores + exclude_patterns
+ repo_path,
+ extensions=extensions,
+ exclude_patterns=worktree_ignores + exclude_patterns,
+ include_paths=include_paths,
)
# A tree dirty only in paths the filters drop is not a change this command
# can score, so fall through to HEAD rather than answer "empty change".
@@ -214,6 +218,7 @@ def score_live_change(
head,
extensions=extensions,
exclude_patterns=effective_excludes,
+ include_paths=include_paths,
sep=sep,
)
# The baseline shares the fix history's anchor: the range's merge-base.
@@ -221,7 +226,11 @@ def score_live_change(
excluded_ref = ""
else:
features = extract_commit_features(
- repo_path, target, extensions=extensions, exclude_patterns=effective_excludes
+ repo_path,
+ target,
+ extensions=extensions,
+ exclude_patterns=effective_excludes,
+ include_paths=include_paths,
)
anchor, excluded_ref = _commit_anchor(repo_path, target)
@@ -238,6 +247,7 @@ def score_live_change(
baseline,
extensions,
exclude_patterns=baseline_excludes,
+ include_paths=include_paths,
)
result = assess_change(
diff --git a/packages/core/src/repowise/core/analysis/git_cli.py b/packages/core/src/repowise/core/analysis/git_cli.py
index 1f3eabc85..5a55c53a7 100644
--- a/packages/core/src/repowise/core/analysis/git_cli.py
+++ b/packages/core/src/repowise/core/analysis/git_cli.py
@@ -1,5 +1,5 @@
-"""The git helpers every change reader shares: split a revspec, run git, list
-the untracked files and the managed files only repowise edited.
+"""The git helpers every change reader shares: split a revspec, run git, filter
+changed paths, list the untracked files and the managed files only repowise edited.
A leaf (only the owned-path list beside it), so a caller that only needs the
diff shape (changed lines, the drift gate's scope) does not load change risk's
@@ -9,6 +9,7 @@ baseline and, through it, GitPython.
from __future__ import annotations
import subprocess
+from collections.abc import Callable
from pathlib import Path
import pathspec
@@ -35,6 +36,33 @@ def split_revspec(revspec: str) -> tuple[str, str, str] | None:
return base or "HEAD", sep, head or "HEAD"
+def path_filter(
+ extensions: tuple[str, ...] = (),
+ exclude_patterns: tuple[str, ...] = (),
+ include_paths: tuple[str, ...] = (),
+) -> Callable[[str], bool]:
+ """Whether a changed path counts under a caller's suffix, include and exclude filters.
+
+ One rule for every reader of a change (the score, its baseline, the changed
+ lines, the health delta), so they agree on which files the change touches.
+ Patterns are gitignore-style; an empty filter keeps everything.
+ """
+ exts = tuple(e if e.startswith(".") else f".{e}" for e in extensions)
+ drop = (
+ pathspec.PathSpec.from_lines("gitwildmatch", exclude_patterns) if exclude_patterns else None
+ )
+ keep = pathspec.PathSpec.from_lines("gitwildmatch", include_paths) if include_paths else None
+
+ def counts(path: str) -> bool:
+ if exts and not path.endswith(exts):
+ return False
+ if keep is not None and not keep.match_file(path):
+ return False
+ return drop is None or not drop.match_file(path)
+
+ return counts
+
+
def _git(args: list[str], cwd: str, *, check: bool = True) -> str:
# stdin=DEVNULL: on MCP stdio transport a child that inherits the JSON-RPC
# pipe handles can wedge the session (same failure mode _meta.py guards
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 f7281f114..985a91534 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
@@ -12,7 +12,6 @@ from collections import OrderedDict
from functools import partial
from typing import Any
-import pathspec
import structlog
from sqlalchemy import select
from sqlalchemy.exc import OperationalError, SQLAlchemyError
@@ -30,6 +29,7 @@ from repowise.core.analysis.change_risk import (
)
from repowise.core.analysis.change_risk.features import revspec_head
from repowise.core.analysis.change_risk.render import LIMITS, size_text
+from repowise.core.analysis.git_cli import path_filter
from repowise.core.analysis.prior_fix_impact import (
FixRecord,
PriorFixFile,
@@ -167,6 +167,7 @@ async def _score_change(
revspec: str | None,
extensions: list[str] | None,
exclude_patterns: list[str] | None,
+ include_paths: tuple[str, ...],
baseline: int,
) -> tuple[Any, dict | None]:
"""Score the live change: ``(result, None)``, or ``(None, error reply)``."""
@@ -177,6 +178,7 @@ async def _score_change(
revspec,
extensions=tuple(extensions or ()),
exclude_patterns=tuple(exclude_patterns or ()),
+ include_paths=include_paths,
baseline=baseline,
)
except ValueError as exc:
@@ -205,6 +207,7 @@ async def _attach_change_blocks(
extensions: list[str] | None,
changed_read: tuple[Any, Any],
collector: OmissionCollector,
+ include_paths: tuple[str, ...] = (),
) -> None:
"""Attach the tests, patch coverage, prior fixes and cross-repo blocks, in that order."""
changed, changed_error = changed_read
@@ -223,6 +226,7 @@ async def _attach_change_blocks(
normalize_extensions(tuple(extensions or ())),
result.riskignore_excludes + result.request_excludes,
(changed, changed_error),
+ include_paths,
)
patch = await _patch_coverage_block(
ctx, patch_changed, patch_error, patch_revspec, result, collector, label=patch_label
@@ -354,7 +358,10 @@ async def get_change_risk(
return _unsupported_repo_all("get_change_risk")
ctx = await _resolve_repo_context(repo)
started = time.perf_counter()
- result, error = await _score_change(ctx.path, revspec, extensions, exclude_patterns, baseline)
+ includes = _path_patterns(include_paths)
+ result, error = await _score_change(
+ ctx.path, revspec, extensions, exclude_patterns, includes, baseline
+ )
if error is not None:
return error
ignored: list[dict] = []
@@ -365,7 +372,7 @@ async def get_change_risk(
return await _nothing_to_score(ctx, payload["ref"], scored, started)
payload = {"ref": payload.pop("ref"), "scored_repo": scored, **payload}
# Changed lines over the SAME file universe the score counted (its
- # extensions + riskignore + request excludes), so nothing downstream
+ # extensions, includes, riskignore + request excludes), so nothing downstream
# disagrees with the score about which files the change touches. Read once
# and shared: both blocks below need it and git is the expensive part.
# The test and fix blocks need the index and the cross-repo block needs
@@ -376,6 +383,7 @@ async def get_change_risk(
revspec,
normalize_extensions(tuple(extensions or ())),
result.riskignore_excludes + result.request_excludes,
+ includes,
working_tree=result.working_tree,
)
collector = OmissionCollector("get_change_risk", repo_root=ctx.path)
@@ -388,12 +396,12 @@ async def get_change_risk(
revspec,
tuple(extensions or ()),
tuple(result.riskignore_excludes + result.request_excludes),
- _path_patterns(include_paths),
+ includes,
)
)
try:
await _attach_change_blocks(
- ctx, payload, result, revspec, extensions, (changed, changed_error), collector
+ ctx, payload, result, revspec, extensions, (changed, changed_error), collector, includes
)
independent = await _attach_branch_blocks(
ctx, payload, changed, collector, revspec, finding_id
@@ -607,7 +615,7 @@ async def _nothing_to_score(ctx: Any, ref: str, scored: dict[str, Any], started:
"status": "nothing_to_score",
"warning": (
f"No counted file changes in {ref!r} "
- "(check the revspec, extensions, or exclusion filters)."
+ "(check the revspec, extensions, or include/exclude filters)."
),
"scored_repo": scored,
"_meta": _build_meta(
@@ -666,23 +674,16 @@ def _filter_changed(
changed: dict[str, set[int]],
extensions: tuple[str, ...],
exclude_patterns: tuple[str, ...],
+ include_paths: tuple[str, ...] = (),
) -> dict[str, set[int]]:
"""Restrict changed-line files to the score's counted universe.
- ``changed_lines`` applies no suffix/exclude filtering, so without this a
- change scored ``nf == 0`` under an extension filter could still surface
- impacted tests for the filtered-out files. Uses the same ``endswith`` +
- gitwildmatch rules as the numstat accumulator.
+ ``changed_lines`` applies no suffix/include/exclude filtering, so without
+ this a change scored ``nf == 0`` under a filter could still surface impacted
+ tests for the filtered-out files. Uses the score's own path rule.
"""
- spec = pathspec.PathSpec.from_lines("gitwildmatch", exclude_patterns)
- out: dict[str, set[int]] = {}
- for path, lines in changed.items():
- if extensions and not path.endswith(extensions):
- continue
- if spec.match_file(path):
- continue
- out[path] = lines
- return out
+ counts = path_filter(extensions, exclude_patterns, include_paths)
+ return {path: lines for path, lines in changed.items() if counts(path)}
def _cross_repo_block(
@@ -914,6 +915,7 @@ async def _changed_in_scope(
revspec: str | None,
extensions: tuple[str, ...],
exclude_patterns: tuple[str, ...],
+ include_paths: tuple[str, ...] = (),
*,
working_tree: bool = False,
) -> tuple[dict[str, set[int]], tuple[str, str] | None]:
@@ -925,7 +927,7 @@ async def _changed_in_scope(
two blocks want the same answer.
"""
changed, error, _label = await _changed_with_label(
- repo_path, revspec, extensions, exclude_patterns, working_tree=working_tree
+ repo_path, revspec, extensions, exclude_patterns, include_paths, working_tree=working_tree
)
return changed, error
@@ -935,6 +937,7 @@ async def _changed_with_label(
revspec: str | None,
extensions: tuple[str, ...],
exclude_patterns: tuple[str, ...],
+ include_paths: tuple[str, ...] = (),
*,
working_tree: bool = False,
base: str | None = None,
@@ -964,7 +967,7 @@ async def _changed_with_label(
except (subprocess.SubprocessError, OSError):
return {}, ("unknown", "Could not read changed lines from git."), label
- changed = _filter_changed(changed, extensions, exclude_patterns)
+ changed = _filter_changed(changed, extensions, exclude_patterns, include_paths)
if not changed:
return {}, ("no_source_line_changes", "No changed source lines to map to tests."), label
return changed, None, label
@@ -1252,6 +1255,7 @@ async def _push_change(
extensions: tuple[str, ...],
exclude_patterns: tuple[str, ...],
scored: tuple[dict[str, set[int]], tuple[str, str] | None],
+ include_paths: tuple[str, ...] = (),
) -> tuple[dict[str, set[int]], tuple[str, str] | None, str | None, str | None]:
"""``(changed, error, label, revspec)`` the patch-coverage block measures.
@@ -1270,7 +1274,13 @@ async def _push_change(
return changed, error, None, revspec
branch = None if working_tree else f"{base}...HEAD"
found, found_error, label = await _changed_with_label(
- repo_path, branch, extensions, exclude_patterns, working_tree=working_tree, base=base
+ repo_path,
+ branch,
+ extensions,
+ exclude_patterns,
+ include_paths,
+ working_tree=working_tree,
+ base=base,
)
if found_error is not None and branch is not None:
# No merge-base with the base (a shallow clone): measure the commit as scored.
diff --git a/tests/unit/change_health/test_mcp_contract.py b/tests/unit/change_health/test_mcp_contract.py
index aa13954ea..60b72a6e5 100644
--- a/tests/unit/change_health/test_mcp_contract.py
+++ b/tests/unit/change_health/test_mcp_contract.py
@@ -302,3 +302,32 @@ async def test_include_paths_as_a_string_filters_like_the_list(tool, make_repo):
assert await changed(include_paths="docs/, vendor/") == 1
# A filtered result is never served to the unfiltered call.
assert await changed() == 2
+
+
+async def test_include_paths_scope_the_score_and_every_block_that_reads_the_files(
+ tool, make_repo, monkeypatch
+):
+ repo = make_repo()
+ repo.commit("seed", {"app.py": "x = 1\n"})
+ repo.commit(
+ "add",
+ {"app.py": python_complex("a", 16), "vendor/lib.py": python_complex("b", 16)},
+ )
+ module = tool(repo)
+ # The changed-lines read every enrichment block shares, seen at the cross-repo join.
+ seen: list[list[str]] = []
+
+ async def cross_repo_tests(_alias, files):
+ seen.append(files)
+
+ monkeypatch.setattr(module, "cross_repo_tests", cross_repo_tests)
+
+ result = await module.get_change_risk(
+ "HEAD", baseline=0, include_paths="vendor/", include=["diagnostics"]
+ )
+
+ assert result["features"]["nf"] == 1
+ assert result["health_delta"]["scope"]["changed"] == 1
+ assert seen == [["vendor/lib.py"]]
+ nothing = await module.get_change_risk("HEAD", baseline=0, include_paths="docs/")
+ assert nothing["status"] == "nothing_to_score"
diff --git a/tests/unit/server/mcp/test_tool_change_risk.py b/tests/unit/server/mcp/test_tool_change_risk.py
index 510830b40..e2ac1e13e 100644
--- a/tests/unit/server/mcp/test_tool_change_risk.py
+++ b/tests/unit/server/mcp/test_tool_change_risk.py
@@ -169,10 +169,11 @@ async def test_repository_is_none_without_a_factory_or_a_repository_row(factory)
# ---------------------------------------------------------------------------
-def test_filter_changed_applies_the_scores_suffixes_and_excludes():
+def test_filter_changed_applies_the_scores_suffixes_includes_and_excludes():
changed = {"src/a.py": {1}, "src/b.ts": {2}, "docs/c.py": {3}}
assert tool._filter_changed(changed, (".py",), ("docs/",)) == {"src/a.py": {1}}
assert tool._filter_changed(changed, (), ()) == changed
+ assert tool._filter_changed(changed, (), ("src/b.ts",), ("src/",)) == {"src/a.py": {1}}
@pytest.mark.asyncio
diff --git a/tests/unit/server/test_risk_range.py b/tests/unit/server/test_risk_range.py
index 44de01a8b..c795b5813 100644
--- a/tests/unit/server/test_risk_range.py
+++ b/tests/unit/server/test_risk_range.py
@@ -151,6 +151,8 @@ def test_baseline_samples_filters_excluded_paths(git_repo: Path) -> None:
samples = baseline_samples(str(git_repo), "HEAD", 2, (), exclude_patterns=("tests/",))
assert len(samples) == 1
+ # Inclusion is the same filter from the other side.
+ assert len(baseline_samples(str(git_repo), "HEAD", 2, (), include_paths=("tests/",))) == 1
def test_densities_excluding_omits_target_ref(git_repo: Path) -> None: