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.

refactor(analysis): separate change-analysis semantics from git and transport (#2263)

Raghav Chamadiya1c1b63fa4fec
diff --git a/packages/core/src/repowise/core/analysis/change_contracts.py b/packages/core/src/repowise/core/analysis/change_contracts.py
new file mode 100644
index 000000000..4de7bd5c6
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/change_contracts.py
@@ -0,0 +1,336 @@
+"""Symbol-level contract impact: which symbols a change altered, and who calls them.
+
+File-level reach (:mod:`repowise.core.analysis.pr_blast`) answers "which files
+import the files you touched". That is a file-altitude answer to a
+symbol-altitude question: importing a module says nothing about whether the
+*function whose signature changed* is the one being called. This module answers
+the narrower question, and the two are kept distinct on purpose:
+
+* contract impact -- which changed symbols affect callers (here);
+* PR blast radius -- file-level structural reach, ownership, and test gaps.
+
+The algorithm:
+
+1. Diff a base parse against a head parse per changed file, classifying every
+ symbol as added / removed / signature-changed / body-changed.
+2. Walk the graph's ``calls`` edges to collect each changed symbol's callers,
+ partitioned into inside-change (already under review) and outside-change.
+3. Outside callers of a *removed* or *signature-changed* symbol are the finding.
+
+Everything here is deterministic set/graph work over data the caller already
+holds. No SQL, no network, no LLM.
+
+Two honesty constraints shape the output:
+
+* A symbol whose signature is unchanged and whose line range does not overlap
+ the change's added lines is not reported at all. The base parse may come from
+ the last indexed snapshot rather than the change's true base, and a snapshot
+ can be many commits behind -- without the added-line gate, every symbol that
+ drifted since indexing would be blamed on this change.
+* ``callers_total`` is the uncapped count. A surface may cap the rendered list,
+ but the number never lies about how many there are.
+
+Core returns the full population: ``callers_per_symbol`` defaults to ``None``
+(uncapped). Capping is surface policy, and a surface that needs a cap passes it
+explicitly rather than reimplementing the walk.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+# Symbol kinds worth reporting on. Constants and variables produce enormous,
+# low-signal churn (every literal edit reads as a "signature change"), and the
+# call graph does not resolve calls *to* them anyway.
+REPORTED_KINDS = frozenset(
+ {"function", "method", "class", "interface", "trait", "struct", "impl", "enum"}
+)
+
+#: Classification values for :attr:`SymbolContractChange.change`.
+CHANGE_ADDED = "added"
+CHANGE_REMOVED = "removed"
+CHANGE_SIGNATURE = "signature"
+CHANGE_BODY = "body"
+
+
+@dataclass(frozen=True, slots=True)
+class SymbolFacts:
+ """The subset of a parsed symbol this module compares on."""
+
+ symbol_id: str
+ name: str
+ kind: str
+ signature: str
+ start_line: int
+ end_line: int
+
+
+@dataclass
+class SymbolContractChange:
+ """One symbol the change altered, with its resolved callers.
+
+ ``outside_callers`` holds symbol ids (``path::Name``) of callers whose file
+ is not part of this change -- the ones nobody is currently reviewing.
+ """
+
+ file: str
+ name: str
+ symbol_id: str
+ kind: str
+ change: str
+ start_line: int
+ end_line: int
+ outside_callers: list[str] = field(default_factory=list)
+ inside_caller_count: int = 0
+ callers_total: int = 0
+ outside_callers_total: int = 0
+
+ @property
+ def is_breaking(self) -> bool:
+ """A contract change with callers nobody in this change is looking at.
+
+ Body-only changes are excluded on purpose: the caller's contract still
+ holds, so listing its callers is noise. Added symbols have no prior
+ callers by construction.
+ """
+ return self.change in (CHANGE_REMOVED, CHANGE_SIGNATURE) and bool(self.outside_callers)
+
+
+@dataclass
+class ContractImpact:
+ """The typed result of one contract-impact analysis."""
+
+ changes: list[SymbolContractChange] = field(default_factory=list)
+ #: ``available`` | ``partial`` | ``unavailable`` | ``degraded`` | ``unsupported``.
+ status: str = "available"
+ reason: str | None = None
+ # True when the base side came from the last indexed snapshot rather than
+ # the change's true base commit -- the comparison is then against whatever
+ # was indexed, which may be several commits behind. Renderers say so.
+ base_is_snapshot: bool = False
+
+ @property
+ def breaking(self) -> list[SymbolContractChange]:
+ return [c for c in self.changes if c.is_breaking]
+
+ def is_empty(self) -> bool:
+ return not self.changes
+
+
+def _containing_file(symbol_id: str) -> str:
+ """The file a symbol node belongs to.
+
+ Ids are ``<path>::<name>`` (and ``<path>::<class>::<method>`` for methods),
+ so the first segment wins.
+ """
+ return symbol_id.split("::", 1)[0]
+
+
+def symbol_index(
+ parsed: Any, changed_set: set[str] | None = None
+) -> dict[str, dict[str, SymbolFacts]]:
+ """``{file_path: {symbol_name: SymbolFacts}}`` from either shape of parse.
+
+ Accepts both live ``ParsedFile``-shaped objects and the plain dicts in a
+ ``parsed_files.json`` artifact, so the same index builder serves the head
+ parse, the base parse, and a snapshot fallback. Unknown or malformed rows
+ are skipped rather than raised on: this feeds advisory evidence, and one bad
+ row must not cost the whole analysis.
+ """
+ out: dict[str, dict[str, SymbolFacts]] = {}
+ for pf in parsed or []:
+ info = pf.get("file_info") if isinstance(pf, dict) else getattr(pf, "file_info", None)
+ if info is None:
+ continue
+ path = info.get("path") if isinstance(info, dict) else getattr(info, "path", None)
+ if not path:
+ continue
+ if changed_set is not None and path not in changed_set:
+ continue
+ symbols = pf.get("symbols") if isinstance(pf, dict) else getattr(pf, "symbols", None)
+ bucket: dict[str, SymbolFacts] = {}
+ for sym in symbols or []:
+ facts = _facts(sym, path)
+ if facts is not None:
+ bucket[facts.name] = facts
+ if bucket:
+ out[path] = bucket
+ return out
+
+
+def _facts(sym: Any, path: str) -> SymbolFacts | None:
+ get = sym.get if isinstance(sym, dict) else lambda k, d=None: getattr(sym, k, d)
+ name = get("name")
+ kind = str(get("kind") or "")
+ if not name or kind not in REPORTED_KINDS:
+ return None
+ # A method's qualified id carries its class ("f.py::Cls::method"); the
+ # graph's call edges are keyed on that id, so prefer the parser's own id.
+ symbol_id = str(get("id") or f"{path}::{name}")
+ try:
+ start = int(get("start_line") or 0)
+ end = int(get("end_line") or 0)
+ except (TypeError, ValueError):
+ return None
+ return SymbolFacts(
+ symbol_id=symbol_id,
+ name=str(name),
+ kind=kind,
+ signature=str(get("signature") or ""),
+ start_line=start,
+ end_line=end,
+ )
+
+
+def caller_index(graph: dict) -> dict[str, list[str]]:
+ """``{callee_symbol_id: [caller_symbol_id, ...]}`` from the graph's ``calls`` edges.
+
+ A node-link graph holds one node per file *and* one per extracted symbol,
+ with ``edge_type`` on every edge. Only ``calls`` edges are read here;
+ ``imports`` edges are file-level reach's business. Edges written by an
+ indexer old enough to predate ``edge_type`` are accepted when both endpoints
+ look like symbol ids, so an old snapshot degrades to fewer callers rather
+ than to none.
+ """
+ index: dict[str, list[str]] = {}
+ for edge in graph.get("links") or graph.get("edges") or []:
+ if not isinstance(edge, dict):
+ continue
+ src, tgt = edge.get("source"), edge.get("target")
+ if src is None or tgt is None:
+ continue
+ src, tgt = str(src), str(tgt)
+ edge_type = edge.get("edge_type") or edge.get("type")
+ if edge_type is None:
+ if "::" not in src or "::" not in tgt:
+ continue
+ elif edge_type != "calls":
+ continue
+ index.setdefault(tgt, []).append(src)
+ return index
+
+
+def _overlaps(start: int, end: int, ranges: list[tuple[int, int]]) -> bool:
+ lo, hi = (start, end) if start <= end else (end, start)
+ return any(lo <= b and a <= hi for a, b in ranges)
+
+
+def analyze_contract_impact(
+ *,
+ graph: dict,
+ base_parsed: Any,
+ head_parsed: Any,
+ changed_set: set[str],
+ added_ranges_by_file: dict[str, list[tuple[int, int]]],
+ base_is_snapshot: bool = False,
+ callers_per_symbol: int | None = None,
+) -> ContractImpact:
+ """Classify each changed symbol and resolve its callers.
+
+ ``base_parsed`` / ``head_parsed`` are lists of ``ParsedFile``-shaped objects
+ or of ``parsed_files.json`` rows (mixed is fine). Only files in
+ ``changed_set`` are compared -- a symbol in an untouched file cannot have
+ been changed here.
+
+ ``callers_per_symbol`` caps the rendered ``outside_callers`` list. It
+ defaults to ``None`` (the full population); ``callers_total`` and
+ ``outside_callers_total`` are computed before any cap bites.
+ """
+ base = symbol_index(base_parsed, changed_set)
+ head = symbol_index(head_parsed, changed_set)
+ callers = caller_index(graph)
+
+ changes: list[SymbolContractChange] = []
+ for path in sorted(changed_set):
+ base_syms = base.get(path, {})
+ head_syms = head.get(path, {})
+ if not base_syms and not head_syms:
+ continue
+ ranges = added_ranges_by_file.get(path, [])
+
+ for name, facts in sorted(head_syms.items()):
+ prior = base_syms.get(name)
+ if prior is None:
+ # A file with no base side at all (added by this change, or
+ # missing from the snapshot) would otherwise report every symbol
+ # as "added" -- true but useless. Only report added symbols when
+ # there IS a base side to have added them to.
+ if not base_syms:
+ continue
+ change = CHANGE_ADDED
+ elif prior.signature != facts.signature:
+ change = CHANGE_SIGNATURE
+ elif _overlaps(facts.start_line, facts.end_line, ranges):
+ change = CHANGE_BODY
+ else:
+ continue
+ changes.append(
+ _with_callers(path, facts, change, callers, changed_set, callers_per_symbol)
+ )
+
+ for name, facts in sorted(base_syms.items()):
+ if name not in head_syms:
+ changes.append(
+ _with_callers(
+ path, facts, CHANGE_REMOVED, callers, changed_set, callers_per_symbol
+ )
+ )
+
+ changes.sort(key=_rank)
+ return ContractImpact(
+ changes=changes,
+ status="available",
+ reason=None,
+ base_is_snapshot=base_is_snapshot,
+ )
+
+
+_CHANGE_ORDER = {CHANGE_REMOVED: 0, CHANGE_SIGNATURE: 1, CHANGE_ADDED: 2, CHANGE_BODY: 3}
+
+
+def _rank(c: SymbolContractChange) -> tuple:
+ """Breaking changes first, then by how many outside callers they reach."""
+ return (
+ not c.is_breaking,
+ _CHANGE_ORDER.get(c.change, 9),
+ -c.outside_callers_total,
+ c.file,
+ c.name,
+ )
+
+
+def _with_callers(
+ path: str,
+ facts: SymbolFacts,
+ change: str,
+ callers: dict[str, list[str]],
+ changed_set: set[str],
+ cap: int | None,
+) -> SymbolContractChange:
+ inside = 0
+ outside: list[str] = []
+ for caller in callers.get(facts.symbol_id, ()):
+ if _containing_file(caller) in changed_set:
+ inside += 1
+ else:
+ outside.append(caller)
+ outside.sort()
+ return SymbolContractChange(
+ file=path,
+ name=facts.name,
+ symbol_id=facts.symbol_id,
+ kind=facts.kind,
+ change=change,
+ start_line=facts.start_line,
+ end_line=facts.end_line,
+ outside_callers=outside if cap is None else outside[:cap],
+ inside_caller_count=inside,
+ callers_total=inside + len(outside),
+ outside_callers_total=len(outside),
+ )
+
+
+def unavailable_contract_impact(reason: str) -> ContractImpact:
+ """An honest empty result when the inputs for this lane were not supplied."""
+ return ContractImpact(changes=[], status="unavailable", reason=reason)
diff --git a/packages/core/src/repowise/core/analysis/change_health/__init__.py b/packages/core/src/repowise/core/analysis/change_health/__init__.py
index 41f07bd40..1941bb371 100644
--- a/packages/core/src/repowise/core/analysis/change_health/__init__.py
+++ b/packages/core/src/repowise/core/analysis/change_health/__init__.py
@@ -30,7 +30,13 @@ from .models import (
)
from .perf_delta import PerfOpportunityView, opportunities_for
from .service import ChangeHealthDeltaService, DeltaRequest
-from .sources import FileChange, GitRevisionSource, RevisionPair, RevisionSource
+from .sources import (
+ FileChange,
+ GitRevisionSource,
+ MappingRevisionSource,
+ RevisionPair,
+ RevisionSource,
+)
__all__ = [
"AnalysisFingerprint",
@@ -47,6 +53,7 @@ __all__ = [
"FindingKey",
"FindingMatcher",
"GitRevisionSource",
+ "MappingRevisionSource",
"MatchResult",
"MatchedFinding",
"PerfOpportunityView",
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 c271dce07..06dc1f0d0 100644
--- a/packages/core/src/repowise/core/analysis/change_health/sources.py
+++ b/packages/core/src/repowise/core/analysis/change_health/sources.py
@@ -33,6 +33,12 @@ class FileChange:
base_path: str | None
status: str # added | modified | deleted | renamed
diff: FileDiff | None = None
+ # Why there is no parsed diff, when the provider knows. ``None`` means it
+ # did not say, and :attr:`diff_reliability` infers from ``diff`` instead.
+ # A provider that serves truncated patches (a size-capped API page) or
+ # binary blobs sets this so a consumer can tell "no lines changed" apart
+ # from "the line-level view of this change was never available".
+ diff_status: str | None = None # parsed | unavailable | truncated | binary
@property
def is_new(self) -> bool:
@@ -42,6 +48,40 @@ class FileChange:
def is_rename(self) -> bool:
return self.status == "renamed"
+ @property
+ def is_deleted(self) -> bool:
+ return self.status == "deleted"
+
+ @property
+ def path(self) -> str:
+ """The one path that names this change.
+
+ The head side where there is one, falling back to the base side for a
+ deletion. Every change has exactly one of these, which is what keyed
+ collections and per-file evidence lanes need.
+ """
+ path = self.head_path or self.base_path
+ if not path: # pragma: no cover - a change with neither side is malformed
+ raise ValueError("FileChange has neither a head_path nor a base_path")
+ return path
+
+ @property
+ def diff_reliability(self) -> str:
+ """``parsed`` | ``unavailable`` | ``truncated`` | ``binary``.
+
+ An explicit *diff_status* wins; otherwise the presence of a parsed diff
+ is the answer. A deletion legitimately has no new-side lines, so an
+ empty :attr:`added_lines` is never on its own evidence of an unreliable
+ diff -- read this instead.
+ """
+ if self.diff_status:
+ return self.diff_status
+ return "parsed" if self.diff is not None else "unavailable"
+
+ @property
+ def diff_reliable(self) -> bool:
+ return self.diff_reliability == "parsed"
+
@property
def added_lines(self) -> set[int]:
return self.diff.new_lines if self.diff else set()
@@ -217,6 +257,74 @@ class GitRevisionSource:
return out
+class MappingRevisionSource:
+ """A :class:`RevisionSource` over content the caller already holds.
+
+ The comparison engine is synchronous and reads bytes in bulk, which suits a
+ checkout and not a caller that has to fetch them. Such a caller collects the
+ content first and hands it here; this source only serves what it was given
+ and does no IO, so comparison, matching, and attribution stay unchanged.
+
+ *base* and *head* map repository-relative path to bytes. A path absent from
+ its side did not exist there -- the same thing :meth:`GitRevisionSource.read`
+ reports by omitting it. So a deletion is a path in *base* and not in *head*;
+ ``b""`` means the file existed and was empty, and the two are not the same.
+
+ ``pair.working_tree`` decides what :meth:`read_working_tree` means: an
+ uncommitted head side answers from its blobs, a commit has none and raises.
+ """
+
+ def __init__(
+ self,
+ pair: RevisionPair,
+ base: dict[str, bytes],
+ head: dict[str, bytes],
+ ) -> None:
+ self.pair = pair
+ self._base = base
+ self._head = head
+
+ def resolve(self, revspec: str | None) -> RevisionPair:
+ """Return the supplied pair.
+
+ Nothing is derived here, so a *revspec* naming a different pair raises
+ rather than silently answering a question nobody asked.
+ """
+ if revspec is not None and revspec not in self._spellings():
+ raise ValueError(
+ f"{revspec!r} does not name this revision pair "
+ f"({self.pair.base_ref}..{self.pair.head_ref}); "
+ "a supplied source cannot resolve a different revision."
+ )
+ return self.pair
+
+ def _spellings(self) -> set[str]:
+ base, head = self.pair.base_ref, self.pair.head_ref
+ return {head, f"{base}..{head}", f"{base}...{head}"}
+
+ def read(self, sha: str, paths: list[str]) -> dict[str, bytes]:
+ """Serve *paths* from whichever supplied side *sha* names."""
+ if not paths:
+ return {}
+ if sha == self.pair.base_sha:
+ side = self._base
+ elif sha == self.pair.head_sha:
+ side = self._head
+ else:
+ raise ValueError(
+ f"{sha!r} is neither side of this revision pair "
+ f"({self.pair.base_sha!r}, {self.pair.head_sha!r})."
+ )
+ return {path: side[path] for path in paths if path in side}
+
+ def read_working_tree(self, paths: list[str]) -> dict[str, bytes]:
+ if not self.pair.working_tree:
+ raise ValueError(
+ "This revision pair compares two commits; it has no working tree to read."
+ )
+ return {path: self._head[path] for path in paths if path in self._head}
+
+
def _iter_name_status(raw: str) -> Iterator[tuple[str, str, str]]:
"""Yield ``(code, base_path, head_path)`` from ``--name-status -z`` output."""
fields = [f for f in raw.split("\0") if f != ""]
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 703e6ac6a..d9fc44bca 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/service.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/service.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import subprocess
+from collections.abc import Mapping, Sequence
from dataclasses import dataclass, replace
from pathlib import Path
@@ -183,17 +184,11 @@ def score_live_change(
# which is the honest answer for the first commit in a repository.
history_ref = f"{target}^"
- risk = score_change(features)
try:
- pressure = fix_pressure(repo_path, history_ref)
- fix_history_available = True
+ pressure: dict[str, float] | None = fix_pressure(repo_path, history_ref)
except FixHistoryUnavailableError:
- pressure, fix_history_available = {}, False
- density = change_fix_density(pressure, features.file_churn)
- fix_bearing = hot_files(pressure, features.file_churn)
- percentile: float | None = None
- priority: str | None = None
- baseline_sample_size = 0
+ pressure = None
+
samples: list[BaselineSample] = []
if baseline:
samples = baseline_samples_cached(
@@ -203,29 +198,75 @@ def score_live_change(
extensions,
exclude_patterns=effective_excludes,
)
- scores = scores_excluding(samples, excluded_ref)
- baseline_sample_size = len(scores)
- if len(scores) >= _MIN_BASELINE:
- normalizer = RiskNormalizer.from_scores(scores)
- rank_score = score_change(replace(features, exp=None)).score
- percentile = normalizer.percentile(rank_score)
- priority = normalizer.priority(rank_score)
+
+ return assess_change(
+ features,
+ fix_pressure=pressure,
+ baseline_scores=scores_excluding(samples, excluded_ref),
+ baseline_fix_densities=densities_excluding(samples, excluded_ref, pressure or {}),
+ working_tree=working_tree,
+ riskignore_excludes=from_riskignore,
+ request_excludes=exclude_patterns,
+ )
+
+
+def assess_change(
+ features: ChangeFeatures,
+ *,
+ fix_pressure: Mapping[str, float] | None = None,
+ baseline_scores: Sequence[float] = (),
+ baseline_fix_densities: Sequence[float] = (),
+ min_baseline: int = _MIN_BASELINE,
+ working_tree: bool = False,
+ riskignore_excludes: tuple[str, ...] = (),
+ request_excludes: tuple[str, ...] = (),
+) -> ChangeRiskResult:
+ """Score an already-extracted change. The whole risk composition, no IO.
+
+ This is the pure tail of :func:`score_live_change`: model scoring, the
+ fix-history load the change stands on, and the repo-relative ranking.
+ Everything upstream of it -- resolving a revspec, walking git for features,
+ walking git for fix pressure, sampling a baseline -- is IO, and stays with
+ the caller. A consumer holding file stats from an API rather than a
+ checkout reaches this directly and gets the same numbers, because they come
+ from the same composition rather than a second copy of it.
+
+ ``fix_pressure`` of ``None`` means the history walk could not run, which is
+ reported as ``fix_history_available=False``. An empty mapping is different:
+ the walk ran and found no fixes.
+
+ ``baseline_scores`` ranks this change against its cohort. Fewer than
+ *min_baseline* of them leaves ``percentile`` and ``priority`` as ``None`` --
+ an honest "no cohort to rank against" rather than a percentile computed from
+ too little to mean anything.
+ """
+ risk = score_change(features)
+ pressure = dict(fix_pressure or {})
+ density = change_fix_density(pressure, features.file_churn)
+
+ percentile: float | None = None
+ priority: str | None = None
+ if len(baseline_scores) >= min_baseline:
+ normalizer = RiskNormalizer.from_scores(list(baseline_scores))
+ # Author experience is a property of the author, not of the change, so
+ # it is excluded from the score this change is *ranked* by.
+ rank_score = score_change(replace(features, exp=None)).score
+ percentile = normalizer.percentile(rank_score)
+ priority = normalizer.priority(rank_score)
return ChangeRiskResult(
features=features,
risk=risk,
percentile=percentile,
priority=priority,
- baseline_sample_size=baseline_sample_size,
- riskignore_excludes=from_riskignore,
- request_excludes=exclude_patterns,
+ baseline_sample_size=len(baseline_scores),
+ riskignore_excludes=riskignore_excludes,
+ request_excludes=request_excludes,
working_tree=working_tree,
fix_density=round(density, 3),
- fix_percentile=fix_density_percentile(
- densities_excluding(samples, excluded_ref, pressure), density
- ),
- hot_files=fix_bearing,
- fix_history_available=fix_history_available,
+ fix_percentile=fix_density_percentile(list(baseline_fix_densities), density),
+ hot_files=hot_files(pressure, features.file_churn),
+ fix_history_available=fix_pressure is not None,
)
diff --git a/packages/core/src/repowise/core/analysis/independent_changes.py b/packages/core/src/repowise/core/analysis/independent_changes.py
index 0d9614c42..f98acb852 100644
--- a/packages/core/src/repowise/core/analysis/independent_changes.py
+++ b/packages/core/src/repowise/core/analysis/independent_changes.py
@@ -270,48 +270,111 @@ def _partition(
return groups, ungrouped
-async def independent_changes(
+@dataclass(frozen=True)
+class IndependentChangeEvidence:
+ """Everything the partition needs, already collected.
+
+ Splitting this out keeps one grouping algorithm for every caller: the index
+ reads below are one way to gather this, and a caller that gathers it some
+ other way must not end up with a second notion of "independent".
+ """
+
+ #: Every changed path, including ones nothing could group.
+ paths: tuple[str, ...]
+ #: Paths that are indexed source files, so absence of an edge means something.
+ groupable: frozenset[str]
+ #: Unordered file pairs some edge or co-change record connects.
+ pairs: frozenset[tuple[str, str]]
+ #: Files the index has in fact linked to something, ever.
+ linked: frozenset[str]
+ #: Files each commit of the range touched. Empty means none were available,
+ #: which the reported basis says out loud.
+ commit_sets: tuple[tuple[str, ...], ...] = ()
+
+
+def partition_independent_changes(
+ evidence: IndependentChangeEvidence,
+) -> IndependentChanges | None:
+ """Group the changed files. Pure: no session, no index, no IO.
+
+ ``None`` when fewer than two groups survive -- one change gets no report.
+ """
+ if len(evidence.paths) < 2 or len(evidence.groupable) < 2:
+ return None
+
+ groupable = set(evidence.groupable)
+ commit_linked = _commit_pairs(evidence.commit_sets, groupable)
+ pairs = set(evidence.pairs) | commit_linked
+ linked = set(evidence.linked) | {f for pair in commit_linked for f in pair}
+
+ # Only groupable files are graph nodes, so an edge touching a doc or a test
+ # must not survive to bridge two groups through it.
+ pairs = {(a, b) for a, b in pairs if a in groupable and b in groupable}
+
+ groups, ungrouped = _partition(groupable, linked, pairs)
+ if len(groups) < 2:
+ return None
+
+ ungrouped.extend(p for p in evidence.paths if p not in groupable)
+ return IndependentChanges(
+ groups=tuple(groups),
+ ungrouped_files=tuple(sorted(ungrouped)),
+ commits_known=bool(evidence.commit_sets),
+ )
+
+
+async def collect_independent_change_evidence(
session: AsyncSession,
repo_id: str,
changed_files: Iterable[str],
*,
commit_sets: Iterable[Iterable[str]] = (),
-) -> IndependentChanges | None:
- """The changed files split into groups nothing connects.
-
- *commit_sets* is the files each commit of the range touched. ``None`` when
- fewer than two groups survive: one change gets no report.
- """
+) -> IndependentChangeEvidence:
+ """Read the index for what :func:`partition_independent_changes` needs."""
paths = sorted({p for p in changed_files if p})
- if len(paths) < 2:
- return None
# Materialised once: the caller may hand over a generator, and the basis
# states whether there was anything to check.
- known_commits = [list(touched) for touched in commit_sets]
+ known_commits = tuple(tuple(touched) for touched in commit_sets)
+ empty = IndependentChangeEvidence(
+ paths=tuple(paths),
+ groupable=frozenset(),
+ pairs=frozenset(),
+ linked=frozenset(),
+ commit_sets=known_commits,
+ )
+ if len(paths) < 2:
+ return empty
owner, indexed, groupable = await _read_nodes(session, repo_id, paths)
if len(groupable) < 2:
- return None
+ return empty
pairs, linked = await _read_pairs(session, repo_id, owner)
linked |= await _read_inbound_links(session, repo_id, owner)
linked |= {f for pair in pairs for f in pair}
co_pairs, partnered = await _read_co_change(session, repo_id, indexed)
- commit_linked = _commit_pairs(known_commits, groupable)
- pairs |= co_pairs | commit_linked
- linked |= partnered | {f for pair in commit_linked for f in pair}
+ return IndependentChangeEvidence(
+ paths=tuple(paths),
+ groupable=frozenset(groupable),
+ pairs=frozenset(pairs | co_pairs),
+ linked=frozenset(linked | partnered),
+ commit_sets=known_commits,
+ )
- # Only groupable files are graph nodes, so an edge touching a doc or a test
- # must not survive to bridge two groups through it.
- pairs = {(a, b) for a, b in pairs if a in groupable and b in groupable}
- groups, ungrouped = _partition(groupable, linked, pairs)
- if len(groups) < 2:
- return None
+async def independent_changes(
+ session: AsyncSession,
+ repo_id: str,
+ changed_files: Iterable[str],
+ *,
+ commit_sets: Iterable[Iterable[str]] = (),
+) -> IndependentChanges | None:
+ """The changed files split into groups nothing connects.
- ungrouped.extend(p for p in paths if p not in groupable)
- return IndependentChanges(
- groups=tuple(groups),
- ungrouped_files=tuple(sorted(ungrouped)),
- commits_known=bool(known_commits),
+ *commit_sets* is the files each commit of the range touched. ``None`` when
+ fewer than two groups survive: one change gets no report.
+ """
+ evidence = await collect_independent_change_evidence(
+ session, repo_id, changed_files, commit_sets=commit_sets
)
+ return partition_independent_changes(evidence)
diff --git a/packages/core/src/repowise/core/analysis/review_directive.py b/packages/core/src/repowise/core/analysis/review_directive.py
new file mode 100644
index 000000000..99c0c3832
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/review_directive.py
@@ -0,0 +1,235 @@
+"""What a change review concludes, as data rather than prose.
+
+A verdict, why it was reached, and what to do next are analysis, not
+presentation: two surfaces that render them differently must still reach the
+same conclusion. So the policy lives here and the rendering does not.
+
+Core may carry a factual explanation. It must not carry Markdown, URLs, tool
+invocation syntax, or per-surface limits -- a surface caps and formats what it
+is given.
+"""
+
+from __future__ import annotations
+
+import hashlib
+from dataclasses import dataclass
+from typing import Literal
+
+from .change_health.models import ChangeHealthDelta
+
+#: How much of a lane's evidence was actually computed.
+#:
+#: ``available`` with an empty population is known-empty, which is a different
+#: claim from ``unavailable``. None of these may collapse into ``None``, a
+#: missing key, or an empty list.
+EvidenceState = Literal[
+ "available", # computed successfully
+ "partial", # some of the requested scope was analyzed
+ "unavailable", # required data was not provided
+ "degraded", # computation failed or fell back to something weaker
+ "unsupported", # the provider cannot answer this at all
+]
+
+ReviewStatus = Literal[
+ "review_required",
+ "review_recommended",
+ "clear_in_analyzed_scope",
+ "unknown",
+]
+
+ReviewActionKind = Literal[
+ "inspect_finding",
+ "run_tests",
+ "establish_test_coverage",
+ "review_skipped_files",
+]
+
+_BLOCKING_SEVERITIES = {"high", "critical"}
+
+#: Dimensions whose findings are advice, not a gate.
+_ADVISORY_DIMENSIONS = {"performance"}
+
+#: Delta statuses that mean the comparison did not happen.
+_NOT_COMPARED = {"unavailable", "unsupported_range", "too_large", "timeout"}
+
+#: Delta statuses that mean it happened against something untrustworthy.
+_UNTRUSTWORTHY = {"analyzer_mismatch", "rules_mismatch", "stale_baseline"}
+
+
+def _fingerprint(*parts: str) -> str:
+ return hashlib.sha256("\x1f".join(parts).encode("utf-8")).hexdigest()[:12]
+
+
+@dataclass(frozen=True, slots=True)
+class ReviewAction:
+ """One thing to do next, and what makes it worth doing."""
+
+ kind: ReviewActionKind
+ #: 0 is most urgent. Ordering within a directive, not a global scale.
+ priority: int
+ #: Paths, symbol ids, or test ids, depending on *kind*. Uncapped.
+ targets: tuple[str, ...] = ()
+ #: Where the evidence for this action came from, in the emitting lane's own
+ #: vocabulary (for example a finding's attribution basis, or "measured").
+ evidence_basis: str | None = None
+ #: A plain factual sentence. No Markdown, no URLs, no call syntax.
+ explanation: str = ""
+
+ @property
+ def fingerprint(self) -> str:
+ """Stable across runs, so a surface can tell a repeat from a new action."""
+ return _fingerprint(self.kind, *self.targets)
+
+
+@dataclass(frozen=True, slots=True)
+class ReviewDirective:
+ """The verdict on a change, its reasons, and its actions."""
+
+ status: ReviewStatus
+ headline: str
+ reasons: tuple[str, ...] = ()
+ actions: tuple[ReviewAction, ...] = ()
+ #: How complete the evidence behind this verdict is.
+ evidence_state: EvidenceState = "available"
+
+ @property
+ def fingerprint(self) -> str:
+ return _fingerprint(self.status, *(a.fingerprint for a in self.actions))
+
+
+@dataclass(frozen=True, slots=True)
+class CoveringTestEvidence:
+ """The test lane's contribution, already resolved by its own analyzer.
+
+ The default is ``unsupported``: a caller that supplies no test evidence has
+ not consulted the lane, which is a different claim from having looked and
+ found no coverage map. Only the latter is grounds to ask for coverage.
+ """
+
+ state: EvidenceState = "unsupported"
+ #: Uncapped. A surface decides how many to show.
+ tests_to_run: tuple[str, ...] = ()
+ basis: str | None = None # measured | inferred | None
+
+
+def _plural(word: str, count: int) -> str:
+ return word if count == 1 else f"{word}s"
+
+
+def _verdict(delta: ChangeHealthDelta) -> tuple[ReviewStatus, str, EvidenceState]:
+ if delta.status in _NOT_COMPARED:
+ return "unknown", f"Change health could not be compared: {delta.explanation}", "unavailable"
+ if delta.status in _UNTRUSTWORTHY:
+ return "unknown", f"No trustworthy baseline: {delta.explanation}", "degraded"
+
+ blocking = [
+ f
+ for f in delta.findings
+ if f.severity in _BLOCKING_SEVERITIES and f.dimension not in _ADVISORY_DIMENSIONS
+ ]
+ state: EvidenceState = "partial" if delta.status == "partial" else "available"
+ if blocking:
+ lead = blocking[0]
+ return (
+ "review_required",
+ f"{len(blocking)} new {_plural('finding', len(blocking))} "
+ f"{'needs' if len(blocking) == 1 else 'need'} review, "
+ f"starting with {lead.biomarker_type} in {lead.path}.",
+ state,
+ )
+ if delta.findings:
+ return (
+ "review_recommended",
+ f"{len(delta.findings)} new {_plural('finding', len(delta.findings))} "
+ "of low or advisory severity.",
+ state,
+ )
+ if delta.status == "partial":
+ return (
+ "unknown",
+ "Nothing new in what was compared, but part of the change was not analysed.",
+ "partial",
+ )
+ return (
+ "clear_in_analyzed_scope",
+ "No supported new findings surfaced in the analyzed scope.",
+ "available",
+ )
+
+
+def _reasons(delta: ChangeHealthDelta) -> tuple[str, ...]:
+ reasons = [
+ f"{f.severity} {f.dimension}: {f.biomarker_type} in "
+ f"{f.symbol or f.path} ({f.attribution_basis})"
+ for f in delta.findings
+ ]
+ if delta.skipped:
+ reasons.append(
+ f"{len(delta.skipped)} changed {_plural('file', len(delta.skipped))} "
+ "were not analysed, so this is not a clean bill."
+ )
+ return tuple(reasons)
+
+
+def _actions(delta: ChangeHealthDelta, tests: CoveringTestEvidence) -> tuple[ReviewAction, ...]:
+ actions: list[ReviewAction] = []
+ for priority, finding in enumerate(delta.findings):
+ where = f"{finding.path}:{finding.line_start}" if finding.line_start else finding.path
+ actions.append(
+ ReviewAction(
+ kind="inspect_finding",
+ priority=priority,
+ targets=(finding.change_finding_id,),
+ evidence_basis=finding.attribution_basis,
+ explanation=f"Inspect {where}",
+ )
+ )
+ next_priority = len(actions)
+ if tests.tests_to_run:
+ actions.append(
+ ReviewAction(
+ kind="run_tests",
+ priority=next_priority,
+ targets=tests.tests_to_run,
+ evidence_basis=tests.basis,
+ explanation="Run the tests that cover the changed files.",
+ )
+ )
+ next_priority += 1
+ elif tests.state == "unavailable":
+ actions.append(
+ ReviewAction(
+ kind="establish_test_coverage",
+ priority=next_priority,
+ evidence_basis=tests.basis,
+ explanation="No measured test map; run the suite covering the changed files.",
+ )
+ )
+ next_priority += 1
+ if delta.skipped:
+ actions.append(
+ ReviewAction(
+ kind="review_skipped_files",
+ priority=next_priority,
+ targets=tuple(sorted(delta.skipped)),
+ explanation="Review the skipped files by hand; they were not compared.",
+ )
+ )
+ return tuple(actions)
+
+
+def review_directive(
+ delta: ChangeHealthDelta,
+ tests: CoveringTestEvidence | None = None,
+) -> ReviewDirective:
+ """Decide the verdict, its reasons, and the actions. Uncapped and unrendered."""
+ tests = tests or CoveringTestEvidence()
+ status, headline, state = _verdict(delta)
+ return ReviewDirective(
+ status=status,
+ headline=headline,
+ reasons=_reasons(delta),
+ actions=_actions(delta, tests),
+ evidence_state=state,
+ )
+
diff --git a/packages/core/src/repowise/core/analysis/test_impact.py b/packages/core/src/repowise/core/analysis/test_impact.py
index 555d27474..6e485d3cf 100644
--- a/packages/core/src/repowise/core/analysis/test_impact.py
+++ b/packages/core/src/repowise/core/analysis/test_impact.py
@@ -9,6 +9,7 @@ from an empty recommendation population.
from __future__ import annotations
from collections import defaultdict
+from collections.abc import Mapping
from typing import Any
from sqlalchemy import select
@@ -92,12 +93,18 @@ async def analyze_test_impact(
*,
repository_alias: str | None = None,
exclude_spec: Any = None,
+ change_status: Mapping[str, str] | None = None,
) -> dict[str, Any]:
"""Return one typed, untruncated recommendation population.
The same result is consumed by MCP PR mode and the REST blast-radius route.
Coverage and graph inference are both evaluated; de-duplication keeps every
evidence basis on the surviving recommendation.
+
+ *change_status* maps path to ``added``/``modified``/``deleted``/``renamed``.
+ A deleted path has no head side to cover, so "no measured tests" there is a
+ consequence of the deletion and not a coverage gap. Without it every path is
+ treated as present, which is the historical behaviour.
"""
from repowise.core.analysis.test_reachability import tests_reaching_by_tier
from repowise.core.persistence.crud import get_test_coverage_summary, tests_covering
@@ -122,6 +129,7 @@ async def analyze_test_impact(
"files_total": 0,
"files_without_measured_tests": [],
"unknown_files": [],
+ "deleted_files": [],
"coverage": {
"status": "unavailable",
"reason": "no_changed_files",
@@ -300,15 +308,28 @@ async def analyze_test_impact(
"candidates_before_dedup": sum(inferred_totals_by_file.values()),
}
+ statuses = dict(change_status or {})
files = []
for path in changed:
measured_tests = sorted(set(measured_by_file[path]))
inferred_tests = sorted(set(inferred_by_file[path]))
- status = "measured" if measured_tests else "inferred" if inferred_tests else "unknown"
+ deleted = statuses.get(path) == "deleted"
+ if measured_tests:
+ status = "measured"
+ elif inferred_tests:
+ status = "inferred"
+ elif deleted:
+ # The path is gone at head. Nothing covers it because there is
+ # nothing to cover, which is an answer rather than a missing map.
+ status = "deleted"
+ else:
+ status = "unknown"
files.append(
{
"source_file": path,
"status": status,
+ "change_status": statuses.get(path),
+ "head_present": not deleted,
"measured_tests": measured_tests,
"measured_tests_total": len(measured_tests),
"inferred_tests": inferred_tests,
@@ -326,8 +347,15 @@ async def analyze_test_impact(
else:
analysis_status = "available"
- no_measured = [row["source_file"] for row in files if not row["measured_tests"]]
+ # A deleted path is excluded from both: it has no head side to be
+ # uncovered, so counting it as a gap would overstate the coverage debt.
+ no_measured = [
+ row["source_file"]
+ for row in files
+ if not row["measured_tests"] and row["status"] != "deleted"
+ ]
unknown = [row["source_file"] for row in files if row["status"] == "unknown"]
+ deleted_paths = [row["source_file"] for row in files if row["status"] == "deleted"]
total = len(recommendations)
basis_totals = {
basis: sum(row["basis"] == basis for row in recommendations)
@@ -344,6 +372,7 @@ async def analyze_test_impact(
"files_total": len(files),
"files_without_measured_tests": no_measured,
"unknown_files": unknown,
+ "deleted_files": deleted_paths,
"coverage": coverage,
"inference": inference,
"analysis": {
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 609bb9506..001a47f8a 100644
--- a/packages/server/src/repowise/server/mcp_server/_change_health.py
+++ b/packages/server/src/repowise/server/mcp_server/_change_health.py
@@ -10,6 +10,12 @@ from __future__ import annotations
from typing import Any
from repowise.core.analysis.change_health.models import ChangeFinding, ChangeHealthDelta
+from repowise.core.analysis.review_directive import (
+ CoveringTestEvidence,
+ ReviewAction,
+ ReviewDirective,
+ review_directive,
+)
#: Actionable findings carried in the default response. The rest are counted
#: and recoverable by an exact call, never silently dropped.
@@ -18,24 +24,67 @@ TOP_FINDINGS_LIMIT = 3
#: Reasons carried on the directive.
REASON_LIMIT = 3
-_BLOCKING_SEVERITIES = {"high", "critical"}
+#: Findings whose next-action is carried in the default response.
+_ACTIONABLE_FINDINGS = 2
-#: Dimensions whose findings are advice, not a gate. A performance advisory
-#: never blocks on its own; it ranks and it explains.
-_ADVISORY_DIMENSIONS = {"performance"}
+#: Test ids rendered into a single run command.
+_TESTS_SHOWN = 3
def directive(delta: ChangeHealthDelta, tests: dict[str, Any] | None) -> dict[str, Any]:
- """The first thing an agent reads: a verdict and what to do next."""
- status, headline = _verdict(delta)
+ """The first thing an agent reads: a verdict and what to do next.
+
+ The verdict is decided by core. This caps it and renders it.
+ """
+ decided = review_directive(delta, _test_evidence(tests))
return {
- "status": status,
- "headline": headline,
- "reasons": _reasons(delta)[:REASON_LIMIT],
- "next_actions": _next_actions(delta, tests),
+ "status": decided.status,
+ "headline": decided.headline,
+ "reasons": list(decided.reasons[:REASON_LIMIT]),
+ "next_actions": _render_actions(decided),
}
+def _test_evidence(tests: dict[str, Any] | None) -> CoveringTestEvidence:
+ """Translate the tool's test block into the lane core reasons over."""
+ if not tests:
+ # No block at all: the lane was never consulted, so there is nothing to
+ # report and nothing to ask for.
+ return CoveringTestEvidence()
+ to_run = tuple(tests.get("tests_to_run") or ())
+ if to_run:
+ state = "available"
+ elif tests.get("status") in {"no_map", "no_index"}:
+ state = "unavailable"
+ else:
+ state = "available"
+ return CoveringTestEvidence(state=state, tests_to_run=to_run, basis=tests.get("basis"))
+
+
+def _render_actions(decided: ReviewDirective) -> list[str]:
+ """Strings for the wire. Every cap and every join belongs here, not in core."""
+ out: list[str] = []
+ inspected = 0
+ for action in decided.actions:
+ rendered = _render_action(action, inspected)
+ if rendered is None:
+ continue
+ if action.kind == "inspect_finding":
+ inspected += 1
+ out.append(rendered)
+ return out
+
+
+def _render_action(action: ReviewAction, inspected: int) -> str | None:
+ if action.kind == "inspect_finding":
+ if inspected >= _ACTIONABLE_FINDINGS:
+ return None
+ return f"{action.explanation} ({action.targets[0]})"
+ if action.kind == "run_tests":
+ return f"Run: {' '.join(action.targets[:_TESTS_SHOWN])}"
+ return action.explanation
+
+
def health_delta_block(delta: ChangeHealthDelta, *, revspec: str | None) -> dict[str, Any]:
"""The compact delta: what got worse, how much was compared, and how sure."""
emitted = delta.findings[:TOP_FINDINGS_LIMIT]
@@ -114,62 +163,10 @@ def finding_detail(finding: ChangeFinding, revspec: str | None) -> dict[str, Any
# -- internals --------------------------------------------------------------
-def _verdict(delta: ChangeHealthDelta) -> tuple[str, str]:
- if delta.status in {"unavailable", "unsupported_range", "too_large", "timeout"}:
- return "unknown", f"Change health could not be compared: {delta.explanation}"
- if delta.status in {"analyzer_mismatch", "rules_mismatch", "stale_baseline"}:
- return "unknown", f"No trustworthy baseline: {delta.explanation}"
- blocking = [
- f
- for f in delta.findings
- if f.severity in _BLOCKING_SEVERITIES and f.dimension not in _ADVISORY_DIMENSIONS
- ]
- if blocking:
- lead = blocking[0]
- return "review_required", (
- f"{len(blocking)} new {_plural('finding', len(blocking))} "
- f"{'needs' if len(blocking) == 1 else 'need'} review, "
- f"starting with {lead.biomarker_type} in {lead.path}."
- )
- if delta.findings:
- return "review_recommended", (
- f"{len(delta.findings)} new {_plural('finding', len(delta.findings))} "
- "of low or advisory severity."
- )
- if delta.status == "partial":
- return "unknown", (
- "Nothing new in what was compared, but part of the change was not analysed."
- )
- return "clear_in_analyzed_scope", "No supported new findings surfaced in the analyzed scope."
-
-
-def _reasons(delta: ChangeHealthDelta) -> list[str]:
- reasons = [
- f"{f.severity} {f.dimension}: {f.biomarker_type} in "
- f"{f.symbol or f.path} ({f.attribution_basis})"
- for f in delta.findings
- ]
- if delta.skipped:
- reasons.append(
- f"{len(delta.skipped)} changed {_plural('file', len(delta.skipped))} "
- "were not analysed, so this is not a clean bill."
- )
- return reasons
-
-
-def _next_actions(delta: ChangeHealthDelta, tests: dict[str, Any] | None) -> list[str]:
- actions: list[str] = []
- for finding in delta.findings[:2]:
- where = f"{finding.path}:{finding.line_start}" if finding.line_start else finding.path
- actions.append(f"Inspect {where} ({finding.change_finding_id})")
- to_run = (tests or {}).get("tests_to_run") or []
- if to_run:
- actions.append(f"Run: {' '.join(to_run[:3])}")
- elif tests and tests.get("status") in {"no_map", "no_index"}:
- actions.append("No measured test map; run the suite covering the changed files.")
- if delta.skipped:
- actions.append("Review the skipped files by hand; they were not compared.")
- return actions
+
+
+
+
def _counts(findings: list[ChangeFinding], attribute: str) -> dict[str, int]:
@@ -190,7 +187,3 @@ def _skipped(skipped: dict[str, str]) -> dict[str, Any]:
def _call(revspec: str | None, *, extra: str) -> str:
ref = f"revspec={revspec!r}, " if revspec else ""
return f"get_change_risk({ref}{extra})"
-
-
-def _plural(word: str, count: int) -> str:
- return word if count == 1 else f"{word}s"
diff --git a/packages/server/src/repowise/server/schemas/blast_radius.py b/packages/server/src/repowise/server/schemas/blast_radius.py
index 971d7ba92..e888769d2 100644
--- a/packages/server/src/repowise/server/schemas/blast_radius.py
+++ b/packages/server/src/repowise/server/schemas/blast_radius.py
@@ -63,7 +63,11 @@ class TestRecommendation(BaseModel):
class TestImpactFile(BaseModel):
source_file: str
- status: Literal["measured", "inferred", "unknown"]
+ status: Literal["measured", "inferred", "unknown", "deleted"]
+ #: The path's transition, when the caller supplied one.
+ change_status: str | None = None
+ #: False for a path the change deletes: it has no head side to cover.
+ head_present: bool = True
measured_tests: list[str]
measured_tests_total: int
inferred_tests: list[str]
@@ -119,6 +123,8 @@ class TestImpactResponse(BaseModel):
files_total: int
files_without_measured_tests: list[str]
unknown_files: list[str]
+ #: Changed paths the change deletes. Not a coverage gap.
+ deleted_files: list[str] = []
coverage: TestImpactCoverage
inference: TestImpactInference
analysis: TestImpactAnalysis
diff --git a/tests/unit/analysis/test_change_contracts.py b/tests/unit/analysis/test_change_contracts.py
new file mode 100644
index 000000000..dc4ee2b3b
--- /dev/null
+++ b/tests/unit/analysis/test_change_contracts.py
@@ -0,0 +1,286 @@
+"""Symbol-level contract impact: classification and caller partitioning.
+
+Fixtures are the two parse shapes the analyzer accepts -- ``parsed_files.json``
+rows (dicts) and live ``ParsedFile``-shaped objects -- because the whole point
+of :func:`symbol_index` is that it takes both.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from repowise.core.analysis.change_contracts import (
+ analyze_contract_impact,
+ caller_index,
+ symbol_index,
+ unavailable_contract_impact,
+)
+
+
+def _sym(name: str, *, path: str, sig: str, start: int = 10, end: int = 20, kind: str = "function"):
+ return {
+ "id": f"{path}::{name}",
+ "name": name,
+ "kind": kind,
+ "signature": sig,
+ "start_line": start,
+ "end_line": end,
+ }
+
+
+def _file(path: str, symbols: list[dict]) -> dict:
+ return {"file_info": {"path": path}, "symbols": symbols}
+
+
+def _live_file(path: str, symbols: list[dict]):
+ """The object shape a live re-parse returns."""
+ return SimpleNamespace(
+ file_info=SimpleNamespace(path=path),
+ symbols=[SimpleNamespace(**s) for s in symbols],
+ )
+
+
+def _graph(*calls: tuple[str, str]) -> dict:
+ return {
+ "nodes": [],
+ "links": [{"source": src, "target": tgt, "edge_type": "calls"} for src, tgt in calls],
+ }
+
+
+def _compute(base, head, *, calls=(), changed=("app/a.py",), ranges=None, **kwargs):
+ return analyze_contract_impact(
+ graph=_graph(*calls),
+ base_parsed=base,
+ head_parsed=head,
+ changed_set=set(changed),
+ added_ranges_by_file=ranges or {},
+ **kwargs,
+ )
+
+
+# ---------------------------------------------------------------------------
+# symbol_index / caller_index
+# ---------------------------------------------------------------------------
+
+
+def test_symbol_index_accepts_both_artifact_and_live_shapes():
+ rows = [_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x)")])]
+ live = [_live_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x)")])]
+ assert symbol_index(rows)["app/a.py"]["run"].signature == "run(x)"
+ assert symbol_index(live)["app/a.py"]["run"].signature == "run(x)"
+
+
+def test_symbol_index_drops_uninteresting_kinds():
+ rows = [
+ _file(
+ "app/a.py",
+ [
+ _sym("run", path="app/a.py", sig="run()"),
+ _sym("MAX", path="app/a.py", sig="MAX = 3", kind="constant"),
+ ],
+ )
+ ]
+ assert set(symbol_index(rows)["app/a.py"]) == {"run"}
+
+
+def test_caller_index_reads_calls_edges_only():
+ graph = {
+ "links": [
+ {"source": "app/b.py::caller", "target": "app/a.py::run", "edge_type": "calls"},
+ {"source": "app/b.py", "target": "app/a.py", "edge_type": "imports"},
+ ]
+ }
+ assert caller_index(graph) == {"app/a.py::run": ["app/b.py::caller"]}
+
+
+def test_caller_index_tolerates_pre_edge_type_snapshots():
+ # An indexer old enough to omit edge_type: symbol-to-symbol edges are still
+ # read (degrade to fewer callers, never to none), file edges are not.
+ graph = {
+ "links": [
+ {"source": "app/b.py::caller", "target": "app/a.py::run"},
+ {"source": "app/b.py", "target": "app/a.py"},
+ ]
+ }
+ assert caller_index(graph) == {"app/a.py::run": ["app/b.py::caller"]}
+
+
+# ---------------------------------------------------------------------------
+# analyze_contract_impact
+# ---------------------------------------------------------------------------
+
+
+def test_signature_change_with_outside_caller_is_breaking():
+ base = [_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x)")])]
+ head = [_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x, y)")])]
+ impact = _compute(base, head, calls=[("app/b.py::main", "app/a.py::run")])
+
+ assert impact.status == "available"
+ assert len(impact.breaking) == 1
+ change = impact.breaking[0]
+ assert change.change == "signature"
+ assert change.outside_callers == ["app/b.py::main"]
+ assert change.inside_caller_count == 0
+ assert change.callers_total == 1
+ assert change.outside_callers_total == 1
+
+
+def test_callers_inside_the_change_are_not_the_finding():
+ # The caller is in a file this change also touches, so it is already under
+ # review -- a signature change reaching only those is not a finding.
+ base = [_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x)")])]
+ head = [_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x, y)")])]
+ impact = _compute(
+ base,
+ head,
+ calls=[("app/b.py::main", "app/a.py::run")],
+ changed=("app/a.py", "app/b.py"),
+ )
+ assert impact.breaking == []
+ assert impact.changes[0].inside_caller_count == 1
+ assert impact.changes[0].callers_total == 1
+
+
+def test_removed_symbol_with_outside_caller_is_breaking():
+ base = [_file("app/a.py", [_sym("gone", path="app/a.py", sig="gone()")])]
+ head = [_file("app/a.py", [_sym("kept", path="app/a.py", sig="kept()")])]
+ impact = _compute(base, head, calls=[("app/b.py::main", "app/a.py::gone")])
+ kinds = {c.name: c.change for c in impact.changes}
+ assert kinds["gone"] == "removed"
+ assert kinds["kept"] == "added"
+ assert [c.name for c in impact.breaking] == ["gone"]
+
+
+def test_body_change_needs_an_added_line_and_never_breaks():
+ # Same signature. Without an overlapping added-line range the symbol is not
+ # reported at all: the base side may be an out-of-date snapshot, and
+ # everything that drifted since indexing would otherwise be blamed here.
+ base = [_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x)")])]
+ head = [_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x)")])]
+ calls = [("app/b.py::main", "app/a.py::run")]
+
+ assert _compute(base, head, calls=calls).changes == []
+
+ touched = _compute(base, head, calls=calls, ranges={"app/a.py": [(12, 14)]})
+ assert [c.change for c in touched.changes] == ["body"]
+ # A body edit keeps the caller's contract, so it is never breaking.
+ assert touched.breaking == []
+
+
+def test_new_file_does_not_report_every_symbol_as_added():
+ head = [_file("app/new.py", [_sym("run", path="app/new.py", sig="run()")])]
+ impact = _compute([], head, changed=("app/new.py",))
+ assert impact.changes == []
+
+
+def test_breaking_changes_rank_first_and_by_reach():
+ base = [
+ _file(
+ "app/a.py",
+ [
+ _sym("wide", path="app/a.py", sig="wide(x)"),
+ _sym("narrow", path="app/a.py", sig="narrow(x)"),
+ ],
+ )
+ ]
+ head = [
+ _file(
+ "app/a.py",
+ [
+ _sym("wide", path="app/a.py", sig="wide(x, y)"),
+ _sym("narrow", path="app/a.py", sig="narrow(x, y)"),
+ ],
+ )
+ ]
+ impact = _compute(
+ base,
+ head,
+ calls=[
+ ("app/b.py::one", "app/a.py::wide"),
+ ("app/c.py::two", "app/a.py::wide"),
+ ("app/d.py::three", "app/a.py::narrow"),
+ ],
+ )
+ assert [c.name for c in impact.changes] == ["wide", "narrow"]
+
+
+# ---------------------------------------------------------------------------
+# Core owns the untruncated population; caps are surface policy
+# ---------------------------------------------------------------------------
+
+
+def test_core_returns_every_outside_caller_by_default():
+ base = [_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x)")])]
+ head = [_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x, y)")])]
+ calls = [(f"app/c{i}.py::main", "app/a.py::run") for i in range(50)]
+ change = _compute(base, head, calls=calls).changes[0]
+ assert len(change.outside_callers) == 50
+ assert change.outside_callers_total == 50
+ assert change.callers_total == 50
+
+
+def test_a_surface_cap_never_changes_the_reported_totals():
+ base = [_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x)")])]
+ head = [_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x, y)")])]
+ calls = [(f"app/c{i}.py::main", "app/a.py::run") for i in range(50)]
+ change = _compute(base, head, calls=calls, callers_per_symbol=40).changes[0]
+ assert len(change.outside_callers) == 40
+ assert change.outside_callers_total == 50
+ assert change.callers_total == 50
+ # A capped list is still the top of the same sorted population.
+ assert change.outside_callers == sorted(f"app/c{i}.py::main" for i in range(50))[:40]
+
+
+def test_ranking_uses_the_uncapped_reach_not_the_capped_list():
+ # Both symbols cap to the same rendered length; only the totals separate
+ # them, so ranking must read the total.
+ base = [
+ _file(
+ "app/a.py",
+ [
+ _sym("wide", path="app/a.py", sig="wide(x)"),
+ _sym("narrow", path="app/a.py", sig="narrow(x)"),
+ ],
+ )
+ ]
+ head = [
+ _file(
+ "app/a.py",
+ [
+ _sym("wide", path="app/a.py", sig="wide(x, y)"),
+ _sym("narrow", path="app/a.py", sig="narrow(x, y)"),
+ ],
+ )
+ ]
+ calls = [(f"app/w{i}.py::c", "app/a.py::wide") for i in range(6)]
+ calls += [(f"app/n{i}.py::c", "app/a.py::narrow") for i in range(3)]
+ impact = _compute(base, head, calls=calls, callers_per_symbol=2)
+ assert [c.name for c in impact.changes] == ["wide", "narrow"]
+
+
+# ---------------------------------------------------------------------------
+# Explicit evidence states
+# ---------------------------------------------------------------------------
+
+
+def test_known_empty_is_available_not_unavailable():
+ base = [_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x)")])]
+ impact = _compute(base, base)
+ assert impact.is_empty()
+ assert impact.status == "available"
+ assert impact.reason is None
+
+
+def test_unavailable_carries_its_reason():
+ impact = unavailable_contract_impact("base_parse_not_supplied")
+ assert impact.status == "unavailable"
+ assert impact.reason == "base_parse_not_supplied"
+ assert impact.is_empty()
+ assert impact.breaking == []
+
+
+def test_snapshot_base_is_carried_on_the_result():
+ base = [_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x)")])]
+ head = [_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x, y)")])]
+ assert _compute(base, head).base_is_snapshot is False
+ assert _compute(base, head, base_is_snapshot=True).base_is_snapshot is True
diff --git a/tests/unit/analysis/test_change_risk_facade.py b/tests/unit/analysis/test_change_risk_facade.py
new file mode 100644
index 000000000..5c93b4b0e
--- /dev/null
+++ b/tests/unit/analysis/test_change_risk_facade.py
@@ -0,0 +1,166 @@
+"""The pure risk facade must equal the live path, and serve a checkout-less caller.
+
+:func:`assess_change` lets a caller holding only file stats score a change
+without a checkout. That is worth nothing unless the live path runs the same
+composition, so these tests pin both directions.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.change_risk.features import features_from_file_changes
+from repowise.core.analysis.change_risk.model import score_change
+from repowise.core.analysis.change_risk.service import (
+ _MIN_BASELINE,
+ assess_change,
+ score_live_change,
+)
+from tests.unit.change_health.conftest import Repo, python_complex
+
+
+def make_repo(tmp_path):
+ counter = {"n": 0}
+
+ def factory(name: str = "repo") -> Repo:
+ counter["n"] += 1
+ return Repo(tmp_path / f"{name}{counter['n']}")
+
+ return factory
+
+
+def _repo_with_history(make_repo, commits: int = 14):
+ repo = make_repo("risk")
+ for i in range(commits):
+ # A mix of shapes so the baseline cohort is not degenerate.
+ repo.commit(
+ f"fix: adjust {i}" if i % 3 == 0 else f"feat: extend {i}",
+ {f"app/m{i % 4}.py": python_complex("run", 2 + (i % 5))},
+ )
+ return repo
+
+
+# ---------------------------------------------------------------------------
+# Live path delegates to the facade
+# ---------------------------------------------------------------------------
+
+
+def test_live_scoring_equals_the_facade_over_the_same_inputs(make_repo):
+ """The live path must be the facade plus IO, not a parallel composition."""
+ repo = _repo_with_history(make_repo)
+ live = score_live_change(str(repo.path), "HEAD")
+
+ # Re-run the facade over exactly what the live path collected. Every number
+ # the result carries has to come back identical.
+ replayed = assess_change(
+ live.features,
+ fix_pressure={} if live.fix_history_available else None,
+ baseline_scores=[],
+ working_tree=live.working_tree,
+ riskignore_excludes=live.riskignore_excludes,
+ request_excludes=live.request_excludes,
+ )
+ assert replayed.risk.score == live.risk.score
+ assert replayed.risk.level == live.risk.level
+ assert replayed.features == live.features
+ assert replayed.fix_history_available == live.fix_history_available
+
+
+def test_live_scoring_still_ranks_against_its_cohort(make_repo):
+ repo = _repo_with_history(make_repo, commits=20)
+ live = score_live_change(str(repo.path), "HEAD")
+ assert live.baseline_sample_size >= _MIN_BASELINE
+ assert live.percentile is not None
+ assert live.priority is not None
+
+
+# ---------------------------------------------------------------------------
+# The facade, used the way a checkout-less consumer would
+# ---------------------------------------------------------------------------
+
+
+def _file_stat_features():
+ """What a caller without a checkout has: per-file (path, additions, deletions)."""
+ return features_from_file_changes(
+ [("app/a.py", 40, 10), ("app/b.py", 5, 1), ("docs/readme.md", 2, 0)],
+ subject="feat: widen the interface",
+ ref="pr-123",
+ )
+
+
+def test_facade_scores_file_stats_with_no_checkout():
+ result = assess_change(_file_stat_features())
+ assert result.risk.score == score_change(_file_stat_features()).score
+ assert result.features.nf == 3
+ assert result.features.la == 47
+ assert result.features.ld == 11
+
+
+def test_facade_and_model_agree_on_the_score():
+ """No second scorer: the facade's number is the model's number."""
+ features = _file_stat_features()
+ assert assess_change(features).risk.score == score_change(features).score
+
+
+# ---------------------------------------------------------------------------
+# Explicit states: absent fix history, and too small a cohort
+# ---------------------------------------------------------------------------
+
+
+def test_no_fix_history_is_distinguishable_from_no_fixes():
+ features = _file_stat_features()
+ could_not_look = assess_change(features, fix_pressure=None)
+ looked_and_found_none = assess_change(features, fix_pressure={})
+
+ assert could_not_look.fix_history_available is False
+ assert looked_and_found_none.fix_history_available is True
+ # Both report zero pressure; only the availability flag tells them apart.
+ assert could_not_look.fix_density == looked_and_found_none.fix_density == 0.0
+
+
+def test_fix_pressure_feeds_density_and_hot_files():
+ features = features_from_file_changes([("app/a.py", 30, 0), ("app/b.py", 10, 0)])
+ result = assess_change(features, fix_pressure={"app/a.py": 4.0})
+ assert result.fix_density > 0
+ assert [path for path, _churn, _pressure in result.hot_files] == ["app/a.py"]
+
+
+def test_too_small_a_cohort_declines_to_rank():
+ features = _file_stat_features()
+ result = assess_change(features, baseline_scores=[0.1, 0.5, 0.9])
+ assert result.baseline_sample_size == 3
+ # Not a percentile computed from three samples -- no answer at all.
+ assert result.percentile is None
+ assert result.priority is None
+
+
+def test_a_sufficient_cohort_ranks():
+ features = _file_stat_features()
+ scores = [i / 100 for i in range(1, 41)]
+ result = assess_change(features, baseline_scores=scores)
+ assert result.baseline_sample_size == 40
+ assert result.percentile is not None
+ assert result.priority is not None
+
+
[email protected]("size", [_MIN_BASELINE - 1, _MIN_BASELINE])
+def test_min_baseline_is_the_boundary(size):
+ result = assess_change(_file_stat_features(), baseline_scores=[i / 100 for i in range(size)])
+ assert (result.percentile is None) is (size < _MIN_BASELINE)
+
+
+def test_author_experience_is_excluded_from_the_ranking_score():
+ """Experience is a property of the author, not of the change being ranked."""
+ scores = [i / 100 for i in range(1, 41)]
+ novice = features_from_file_changes([("app/a.py", 40, 10)], exp=0.0)
+ veteran = features_from_file_changes([("app/a.py", 40, 10)], exp=500.0)
+
+ ranked_novice = assess_change(novice, baseline_scores=scores)
+ ranked_veteran = assess_change(veteran, baseline_scores=scores)
+
+ # The absolute scores differ, because experience is a real model feature...
+ assert ranked_novice.risk.score != ranked_veteran.risk.score
+ # ...but the repo-relative ranking is about the change, so it does not.
+ assert ranked_novice.percentile == ranked_veteran.percentile
+ assert ranked_novice.priority == ranked_veteran.priority
diff --git a/tests/unit/analysis/test_core_analysis_layering.py b/tests/unit/analysis/test_core_analysis_layering.py
new file mode 100644
index 000000000..d907c3043
--- /dev/null
+++ b/tests/unit/analysis/test_core_analysis_layering.py
@@ -0,0 +1,60 @@
+"""Core analysis must not depend on anything above it.
+
+Core owns the semantics; surfaces own caps, rendering and transport. That only
+holds as long as the dependency arrow points one way, and an accidental import
+is the easy way to lose it silently.
+"""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+import pytest
+
+_CORE = Path(__file__).parents[3] / "packages" / "core" / "src" / "repowise" / "core"
+
+#: Module prefixes core may never import. Transport, presentation, and any
+#: deployment-specific integration all sit above it.
+_FORBIDDEN = (
+ "repowise.server",
+ "repowise.cli",
+ "mcp",
+ "fastapi",
+ "starlette",
+)
+
+
+def _imported_modules(path: Path) -> set[str]:
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ found: set[str] = set()
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ found.update(alias.name for alias in node.names)
+ elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
+ found.add(node.module)
+ return found
+
+
+def _violates(module: str) -> str | None:
+ for prefix in _FORBIDDEN:
+ if module == prefix or module.startswith(f"{prefix}."):
+ return prefix
+ return None
+
+
+ "source", sorted(_CORE.rglob("*.py")), ids=lambda p: str(p.relative_to(_CORE))
+)
+def test_core_does_not_import_a_surface(source: Path):
+ offenders = {
+ module: prefix
+ for module in _imported_modules(source)
+ if (prefix := _violates(module)) is not None
+ }
+ assert not offenders, f"{source.relative_to(_CORE)} imports {offenders}"
+
+
+def test_the_guard_is_actually_looking_at_core():
+ """A glob that matched nothing would make every assertion above vacuous."""
+ assert len(list(_CORE.rglob("*.py"))) > 100
diff --git a/tests/unit/analysis/test_independent_changes_partition.py b/tests/unit/analysis/test_independent_changes_partition.py
new file mode 100644
index 000000000..3504a98fb
--- /dev/null
+++ b/tests/unit/analysis/test_independent_changes_partition.py
@@ -0,0 +1,193 @@
+"""The pure partition is the only grouping algorithm.
+
+The index-backed entry point must be collection plus this function, never a
+second notion of "independent". So every case here is asserted twice: once over
+a seeded wiki.db, and once over evidence handed in directly.
+"""
+
+from __future__ import annotations
+
+from repowise.core.analysis.independent_changes import (
+ IndependentChangeEvidence,
+ collect_independent_change_evidence,
+ independent_changes,
+ partition_independent_changes,
+)
+
+from .test_independent_changes import _REPO_ID, _seed
+
+
+def _evidence(**kwargs) -> IndependentChangeEvidence:
+ base = {
+ "paths": (),
+ "groupable": frozenset(),
+ "pairs": frozenset(),
+ "linked": frozenset(),
+ "commit_sets": (),
+ }
+ base.update(kwargs)
+ return IndependentChangeEvidence(**base)
+
+
+# ---------------------------------------------------------------------------
+# Index-backed and supplied evidence agree
+# ---------------------------------------------------------------------------
+
+
+async def _both(tmp_path, *, files, edges=(), symbols=(), changed=None, commit_sets=()):
+ """Run the index path and the pure path over the same seeded index."""
+ factory = await _seed(tmp_path, files=files, edges=edges, symbols=symbols)
+ changed = changed or files
+ async with factory() as session:
+ from_index = await independent_changes(
+ session, _REPO_ID, changed, commit_sets=commit_sets
+ )
+ async with factory() as session:
+ evidence = await collect_independent_change_evidence(
+ session, _REPO_ID, changed, commit_sets=commit_sets
+ )
+ return from_index, partition_independent_changes(evidence)
+
+
+async def test_two_unconnected_groups_agree_across_paths(tmp_path):
+ files = ["a/one.py", "a/two.py", "b/one.py", "b/two.py"]
+ edges = (
+ ("a/one.py", "a/two.py", "imports"),
+ ("b/one.py", "b/two.py", "imports"),
+ )
+ from_index, from_evidence = await _both(tmp_path, files=files, edges=edges)
+
+ assert from_index is not None
+ assert from_evidence is not None
+ assert from_index.groups == from_evidence.groups
+ assert from_index.ungrouped_files == from_evidence.ungrouped_files
+ assert from_index.commits_known == from_evidence.commits_known
+ assert len(from_evidence.groups) == 2
+
+
+async def test_one_connected_change_agrees_on_no_report(tmp_path):
+ files = ["a/one.py", "a/two.py"]
+ edges = (("a/one.py", "a/two.py", "imports"),)
+ from_index, from_evidence = await _both(tmp_path, files=files, edges=edges)
+ assert from_index is None
+ assert from_evidence is None
+
+
+async def test_a_shared_commit_merges_groups_on_both_paths(tmp_path):
+ files = ["a/one.py", "a/two.py", "b/one.py", "b/two.py"]
+ edges = (
+ ("a/one.py", "a/two.py", "imports"),
+ ("b/one.py", "b/two.py", "imports"),
+ )
+ # One commit touching one file from each group links them.
+ commits = [["a/one.py", "b/one.py"]]
+ from_index, from_evidence = await _both(
+ tmp_path, files=files, edges=edges, commit_sets=commits
+ )
+ assert from_index == from_evidence
+
+
+# ---------------------------------------------------------------------------
+# The pure function on its own
+# ---------------------------------------------------------------------------
+
+
+def test_fewer_than_two_paths_is_no_report():
+ assert partition_independent_changes(_evidence(paths=("a.py",))) is None
+
+
+def test_fewer_than_two_groupable_files_is_no_report():
+ evidence = _evidence(paths=("a.py", "README.md"), groupable=frozenset({"a.py"}))
+ assert partition_independent_changes(evidence) is None
+
+
+def test_two_islands_split():
+ result = partition_independent_changes(
+ _evidence(
+ paths=("a1.py", "a2.py", "b1.py", "b2.py"),
+ groupable=frozenset({"a1.py", "a2.py", "b1.py", "b2.py"}),
+ pairs=frozenset({("a1.py", "a2.py"), ("b1.py", "b2.py")}),
+ linked=frozenset({"a1.py", "a2.py", "b1.py", "b2.py"}),
+ )
+ )
+ assert result is not None
+ assert [g.files for g in result.groups] == [("a1.py", "a2.py"), ("b1.py", "b2.py")]
+
+
+def test_an_unlinked_component_is_reported_not_claimed_as_a_change():
+ """Absent edges only mean independence for files the index has ever linked."""
+ result = partition_independent_changes(
+ _evidence(
+ paths=("a1.py", "a2.py", "b1.py", "b2.py", "orphan.py"),
+ groupable=frozenset({"a1.py", "a2.py", "b1.py", "b2.py", "orphan.py"}),
+ pairs=frozenset({("a1.py", "a2.py"), ("b1.py", "b2.py")}),
+ linked=frozenset({"a1.py", "a2.py", "b1.py", "b2.py"}),
+ )
+ )
+ assert result is not None
+ assert "orphan.py" in result.ungrouped_files
+ assert all("orphan.py" not in g.files for g in result.groups)
+
+
+def test_ungroupable_paths_survive_into_the_report():
+ result = partition_independent_changes(
+ _evidence(
+ paths=("a1.py", "a2.py", "b1.py", "b2.py", "docs/guide.md"),
+ groupable=frozenset({"a1.py", "a2.py", "b1.py", "b2.py"}),
+ pairs=frozenset({("a1.py", "a2.py"), ("b1.py", "b2.py")}),
+ linked=frozenset({"a1.py", "a2.py", "b1.py", "b2.py"}),
+ )
+ )
+ assert result is not None
+ assert "docs/guide.md" in result.ungrouped_files
+
+
+def test_a_commit_covering_every_file_says_nothing():
+ """A commit set equal to the whole diff is the diff restated, so it is skipped."""
+ groupable = frozenset({"a1.py", "a2.py", "b1.py", "b2.py"})
+ result = partition_independent_changes(
+ _evidence(
+ paths=tuple(sorted(groupable)),
+ groupable=groupable,
+ pairs=frozenset({("a1.py", "a2.py"), ("b1.py", "b2.py")}),
+ linked=frozenset(groupable),
+ commit_sets=(tuple(sorted(groupable)),),
+ )
+ )
+ assert result is not None
+ assert len(result.groups) == 2
+
+
+def test_commits_known_reflects_whether_there_was_anything_to_check():
+ groupable = frozenset({"a1.py", "a2.py", "b1.py", "b2.py"})
+ args = {
+ "paths": tuple(sorted(groupable)),
+ "groupable": groupable,
+ "pairs": frozenset({("a1.py", "a2.py"), ("b1.py", "b2.py")}),
+ "linked": frozenset(groupable),
+ }
+ assert partition_independent_changes(_evidence(**args)).commits_known is False
+ with_commits = partition_independent_changes(
+ _evidence(**args, commit_sets=(("a1.py",),))
+ )
+ assert with_commits.commits_known is True
+
+
+def test_an_edge_through_a_non_groupable_file_cannot_bridge_groups():
+ result = partition_independent_changes(
+ _evidence(
+ paths=("a1.py", "a2.py", "b1.py", "b2.py", "conf.yaml"),
+ groupable=frozenset({"a1.py", "a2.py", "b1.py", "b2.py"}),
+ pairs=frozenset(
+ {
+ ("a1.py", "a2.py"),
+ ("b1.py", "b2.py"),
+ ("a1.py", "conf.yaml"),
+ ("b1.py", "conf.yaml"),
+ }
+ ),
+ linked=frozenset({"a1.py", "a2.py", "b1.py", "b2.py"}),
+ )
+ )
+ assert result is not None
+ assert len(result.groups) == 2
diff --git a/tests/unit/analysis/test_review_directive.py b/tests/unit/analysis/test_review_directive.py
new file mode 100644
index 000000000..8d108c6ee
--- /dev/null
+++ b/tests/unit/analysis/test_review_directive.py
@@ -0,0 +1,197 @@
+"""The verdict is analysis, so it lives in core and carries no rendering.
+
+These tests pin two things: the policy itself, and the boundary -- core emits
+targets and states, never Markdown, URLs, tool-call syntax, or surface caps.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.change_health.models import ChangeFinding, ChangeHealthDelta
+from repowise.core.analysis.review_directive import (
+ CoveringTestEvidence,
+ review_directive,
+)
+
+
+def _finding(
+ *,
+ severity: str = "high",
+ dimension: str = "defect",
+ path: str = "app/a.py",
+ biomarker: str = "deep_nesting",
+ line_start: int | None = 12,
+ symbol: str | None = None,
+) -> ChangeFinding:
+ return ChangeFinding(
+ change_finding_id=f"cf_{path}_{biomarker}_{severity}",
+ change_kind="introduced",
+ dimension=dimension,
+ biomarker_type=biomarker,
+ severity=severity,
+ path=path,
+ symbol=symbol,
+ line_start=line_start,
+ line_end=line_start,
+ reason="",
+ attribution_basis="symbol_overlap",
+ attribution_confidence="high",
+ attribution_detail="",
+ suggestion="",
+ follow_up="",
+ )
+
+
+def _delta(findings=(), *, status="available", skipped=(), explanation="") -> ChangeHealthDelta:
+ return ChangeHealthDelta(
+ status=status,
+ explanation=explanation,
+ base=None,
+ head=None,
+ comparison_basis="commit",
+ fingerprint=None,
+ findings=list(findings),
+ skipped={path: "unsupported_language" for path in skipped},
+ )
+
+
+# ---------------------------------------------------------------------------
+# Verdict policy
+# ---------------------------------------------------------------------------
+
+
+def test_blocking_finding_requires_review():
+ directive = review_directive(_delta([_finding(severity="critical")]))
+ assert directive.status == "review_required"
+ assert "needs review" in directive.headline
+ assert directive.evidence_state == "available"
+
+
+def test_low_severity_only_recommends_review():
+ directive = review_directive(_delta([_finding(severity="low")]))
+ assert directive.status == "review_recommended"
+
+
+def test_a_performance_finding_is_advisory_not_a_gate():
+ directive = review_directive(_delta([_finding(severity="high", dimension="performance")]))
+ assert directive.status == "review_recommended"
+
+
+def test_nothing_found_is_clear_only_within_the_analyzed_scope():
+ directive = review_directive(_delta())
+ assert directive.status == "clear_in_analyzed_scope"
+ assert "analyzed scope" in directive.headline
+
+
[email protected]("status", ["unavailable", "unsupported_range", "too_large", "timeout"])
+def test_a_comparison_that_did_not_happen_is_unknown(status):
+ directive = review_directive(_delta(status=status, explanation="the repo is enormous"))
+ assert directive.status == "unknown"
+ assert directive.evidence_state == "unavailable"
+
+
[email protected]("status", ["analyzer_mismatch", "rules_mismatch", "stale_baseline"])
+def test_an_untrustworthy_baseline_is_degraded_not_merely_absent(status):
+ directive = review_directive(_delta(status=status, explanation="analyzer moved"))
+ assert directive.status == "unknown"
+ assert directive.evidence_state == "degraded"
+
+
+def test_a_clean_partial_comparison_is_not_reported_as_clean():
+ directive = review_directive(_delta(status="partial"))
+ assert directive.status == "unknown"
+ assert directive.evidence_state == "partial"
+ assert "not analysed" in directive.headline
+
+
+def test_skipped_files_are_a_reason_not_a_clean_bill():
+ directive = review_directive(_delta(skipped=["app/b.py", "app/c.py"]))
+ assert any("not a clean bill" in reason for reason in directive.reasons)
+
+
+# ---------------------------------------------------------------------------
+# Actions carry targets, not rendered strings
+# ---------------------------------------------------------------------------
+
+
+def test_each_finding_produces_an_inspect_action_with_its_id():
+ delta = _delta([_finding(path="app/a.py"), _finding(path="app/b.py")])
+ actions = [a for a in review_directive(delta).actions if a.kind == "inspect_finding"]
+ assert len(actions) == 2
+ assert all(a.targets and a.evidence_basis == "symbol_overlap" for a in actions)
+ assert [a.priority for a in actions] == [0, 1]
+
+
+def test_measured_tests_become_a_run_action_with_every_target():
+ tests = CoveringTestEvidence(state="available", tests_to_run=tuple(f"t{i}" for i in range(9)), basis="measured")
+ action = next(a for a in review_directive(_delta(), tests).actions if a.kind == "run_tests")
+ # Uncapped: a surface decides how many of these to show.
+ assert len(action.targets) == 9
+ assert action.evidence_basis == "measured"
+
+
+def test_looking_and_finding_no_map_asks_for_coverage():
+ directive = review_directive(_delta(), CoveringTestEvidence(state="unavailable"))
+ kinds = {a.kind for a in directive.actions}
+ assert "establish_test_coverage" in kinds
+ assert "run_tests" not in kinds
+
+
+def test_a_lane_nobody_consulted_asks_for_nothing():
+ """Not consulting the test lane is not evidence that coverage is missing."""
+ assert review_directive(_delta()).actions == ()
+ assert review_directive(_delta(), CoveringTestEvidence()).actions == ()
+ assert review_directive(_delta(), CoveringTestEvidence(state="unsupported")).actions == ()
+
+
+def test_known_empty_test_evidence_does_not_ask_for_coverage():
+ """The map exists and nothing covers these files. That is an answer."""
+ directive = review_directive(_delta(), CoveringTestEvidence(state="available", tests_to_run=()))
+ assert {a.kind for a in directive.actions} == set()
+
+
+def test_skipped_files_become_an_action_naming_them():
+ delta = _delta(skipped=["app/z.py", "app/b.py"])
+ action = next(a for a in review_directive(delta).actions if a.kind == "review_skipped_files")
+ assert action.targets == ("app/b.py", "app/z.py")
+
+
+def test_core_emits_no_markdown_urls_or_call_syntax():
+ delta = _delta([_finding()], skipped=["app/b.py"])
+ tests = CoveringTestEvidence(state="available", tests_to_run=("tests/test_a.py::test_x",))
+ directive = review_directive(delta, tests)
+
+ prose = [directive.headline, *directive.reasons, *(a.explanation for a in directive.actions)]
+ for text in prose:
+ assert "`" not in text
+ assert "**" not in text
+ assert "http" not in text
+ assert "(" not in text or ")" in text # no dangling call syntax
+ assert "get_change_risk" not in text
+ assert "](" not in text
+
+
+# ---------------------------------------------------------------------------
+# Fingerprints
+# ---------------------------------------------------------------------------
+
+
+def test_action_fingerprints_are_stable_across_runs():
+ delta = _delta([_finding()])
+ first = review_directive(delta).actions[0].fingerprint
+ second = review_directive(delta).actions[0].fingerprint
+ assert first == second
+
+
+def test_fingerprints_separate_different_actions():
+ delta = _delta([_finding(path="app/a.py"), _finding(path="app/b.py")])
+ actions = review_directive(delta).actions
+ assert len({a.fingerprint for a in actions}) == len(actions)
+
+
+def test_directive_fingerprint_tracks_its_actions():
+ clean = review_directive(_delta())
+ flagged = review_directive(_delta([_finding()]))
+ assert clean.fingerprint != flagged.fingerprint
+
diff --git a/tests/unit/change_health/test_supplied_source_parity.py b/tests/unit/change_health/test_supplied_source_parity.py
new file mode 100644
index 000000000..f3d0b985d
--- /dev/null
+++ b/tests/unit/change_health/test_supplied_source_parity.py
@@ -0,0 +1,269 @@
+"""A supplied-content source must answer exactly like the Git one.
+
+The point of :class:`MappingRevisionSource` is that a caller with no checkout
+gets the comparison a checkout gets. That holds only if the two sources are
+interchangeable at the protocol boundary, so these tests mirror one against the
+other over the same fixture rather than asserting either in isolation.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.change_health import (
+ ChangeHealthDeltaService,
+ DeltaRequest,
+ FileChange,
+ GitRevisionSource,
+ MappingRevisionSource,
+ RevisionPair,
+)
+
+from .conftest import Repo, python_complex
+
+
+def _mirror(git_source: GitRevisionSource, revspec: str | None) -> MappingRevisionSource:
+ """Build a supplied source carrying exactly what the Git one would serve."""
+ pair = git_source.resolve(revspec)
+ base_paths = [c.base_path for c in pair.changes if c.base_path]
+ head_paths = [c.head_path for c in pair.changes if c.head_path]
+ base = git_source.read(pair.base_sha, base_paths)
+ head = (
+ git_source.read_working_tree(head_paths)
+ if pair.working_tree
+ else git_source.read(pair.head_sha, head_paths)
+ )
+ return MappingRevisionSource(pair, base, head)
+
+
+def _shape(pair: RevisionPair) -> list[tuple]:
+ return sorted(
+ (c.base_path, c.head_path, c.status, tuple(sorted(c.added_lines)), c.diff_reliability)
+ for c in pair.changes
+ )
+
+
+# ---------------------------------------------------------------------------
+# Revision-pair equivalence
+# ---------------------------------------------------------------------------
+
+
+def test_supplied_source_resolves_the_same_pair(make_repo):
+ repo: Repo = make_repo("parity")
+ repo.commit("base", {"app/a.py": python_complex("run", 2)})
+ repo.commit("head", {"app/a.py": python_complex("run", 6)})
+
+ git_source = GitRevisionSource(str(repo.path))
+ supplied = _mirror(git_source, "HEAD")
+
+ assert _shape(supplied.resolve("HEAD")) == _shape(git_source.resolve("HEAD"))
+
+
+def test_supplied_source_serves_the_same_bytes(make_repo):
+ repo: Repo = make_repo("parity")
+ repo.commit("base", {"app/a.py": python_complex("run", 2)})
+ repo.commit("head", {"app/a.py": python_complex("run", 6)})
+
+ git_source = GitRevisionSource(str(repo.path))
+ pair = git_source.resolve("HEAD")
+ supplied = _mirror(git_source, "HEAD")
+
+ for sha in (pair.base_sha, pair.head_sha):
+ assert supplied.read(sha, ["app/a.py"]) == git_source.read(sha, ["app/a.py"])
+
+
[email protected]("revspec", ["HEAD", None])
+def test_health_delta_is_identical_across_sources(make_repo, revspec):
+ """The whole comparison, not just the protocol, must agree."""
+ repo: Repo = make_repo("parity")
+ repo.commit("base", {"app/a.py": python_complex("run", 2)})
+ repo.commit("head", {"app/a.py": python_complex("run", 9)})
+
+ request = DeltaRequest(repo_path=str(repo.path), revspec=revspec)
+ from_git = ChangeHealthDeltaService(repo_path=str(repo.path)).compare(request)
+
+ # Same request, same fixture, but every byte arrives pre-fetched.
+ git_source = GitRevisionSource(str(repo.path))
+ supplied = _mirror(git_source, revspec)
+ from_supplied = ChangeHealthDeltaService(supplied, repo_path=str(repo.path)).compare(request)
+
+ assert from_supplied.status == from_git.status
+ assert [f.change_finding_id for f in from_supplied.findings] == [
+ f.change_finding_id for f in from_git.findings
+ ]
+
+
+# ---------------------------------------------------------------------------
+# Change shapes that must survive the round trip
+# ---------------------------------------------------------------------------
+
+
+def test_deletion_keeps_its_base_content(make_repo):
+ """A deletion has base content and no head content. It is not an empty change."""
+ repo: Repo = make_repo("parity")
+ repo.commit("base", {"app/gone.py": python_complex("run", 3)})
+ repo.commit("head", {"app/kept.py": "x = 1\n"})
+ repo.remove("app/gone.py")
+ repo.commit("delete")
+
+ git_source = GitRevisionSource(str(repo.path))
+ supplied = _mirror(git_source, "HEAD")
+ pair = supplied.resolve("HEAD")
+
+ deleted = next(c for c in pair.changes if c.status == "deleted")
+ assert deleted.is_deleted
+ assert deleted.head_path is None
+ assert deleted.path == "app/gone.py"
+ assert supplied.read(pair.base_sha, ["app/gone.py"])["app/gone.py"]
+ # Absent from head means "did not exist there" -- not b"".
+ assert supplied.read(pair.head_sha, ["app/gone.py"]) == {}
+
+
+def test_rename_survives_with_both_sides(make_repo):
+ repo: Repo = make_repo("parity")
+ repo.commit("base", {"app/old.py": python_complex("run", 4)})
+ repo.move("app/old.py", "app/new.py")
+ repo.commit("rename")
+
+ git_source = GitRevisionSource(str(repo.path))
+ supplied = _mirror(git_source, "HEAD")
+ pair = supplied.resolve("HEAD")
+
+ assert _shape(pair) == _shape(git_source.resolve("HEAD"))
+ assert pair.rename_map() == git_source.resolve("HEAD").rename_map()
+
+
+def test_delete_and_add_pair_is_two_changes(make_repo):
+ repo: Repo = make_repo("parity")
+ repo.commit("base", {"app/a.py": python_complex("run", 3)})
+ repo.remove("app/a.py")
+ repo.commit("swap", {"app/b.py": "y = 2\n"})
+
+ supplied = _mirror(GitRevisionSource(str(repo.path)), "HEAD")
+ statuses = {c.path: c.status for c in supplied.resolve("HEAD").changes}
+ assert statuses == {"app/a.py": "deleted", "app/b.py": "added"}
+
+
+def test_zero_new_line_change_is_not_an_unreliable_diff(make_repo):
+ """Pure deletion of lines leaves no new side. That is a fact, not a gap."""
+ repo: Repo = make_repo("parity")
+ repo.commit("base", {"app/a.py": "a = 1\nb = 2\nc = 3\n"})
+ repo.commit("head", {"app/a.py": "a = 1\n"})
+
+ supplied = _mirror(GitRevisionSource(str(repo.path)), "HEAD")
+ change = next(c for c in supplied.resolve("HEAD").changes if c.path == "app/a.py")
+ assert change.added_lines == set()
+ assert change.diff_reliable is True
+
+
+def test_missing_blob_reads_as_absent_not_empty(make_repo):
+ repo: Repo = make_repo("parity")
+ repo.commit("base", {"app/a.py": python_complex("run", 2)})
+ repo.commit("head", {"app/a.py": python_complex("run", 5)})
+
+ git_source = GitRevisionSource(str(repo.path))
+ pair = git_source.resolve("HEAD")
+ # A source that was handed nothing for this path reports absence, exactly
+ # as git cat-file does for an object that is not there.
+ starved = MappingRevisionSource(pair, {}, {})
+ assert starved.read(pair.base_sha, ["app/a.py"]) == {}
+ assert git_source.read(pair.base_sha, ["does/not/exist.py"]) == {}
+
+
+def test_binary_and_truncated_diffs_are_named_not_guessed(make_repo):
+ """A provider that knows why there is no line diff says so."""
+ repo: Repo = make_repo("parity")
+ repo.commit("base", {"app/a.py": "a = 1\n"})
+ pair = GitRevisionSource(str(repo.path)).resolve("HEAD")
+
+ binary = FileChange("assets/logo.png", "assets/logo.png", "modified", None, "binary")
+ truncated = FileChange("app/huge.py", "app/huge.py", "modified", None, "truncated")
+ silent = FileChange("app/x.py", "app/x.py", "modified", None)
+
+ assert binary.diff_reliability == "binary"
+ assert truncated.diff_reliability == "truncated"
+ # No claim from the provider falls back to what the diff itself shows.
+ assert silent.diff_reliability == "unavailable"
+ assert not any(c.diff_reliable for c in (binary, truncated, silent))
+ # And a real parsed diff is still reliable.
+ assert all(c.diff_reliable for c in pair.changes)
+
+
+# ---------------------------------------------------------------------------
+# The supplied source refuses to answer a question it was not given
+# ---------------------------------------------------------------------------
+
+
+def test_resolving_a_different_revspec_raises(make_repo):
+ repo: Repo = make_repo("parity")
+ repo.commit("base", {"app/a.py": "a = 1\n"})
+ repo.commit("head", {"app/a.py": "a = 2\n"})
+
+ supplied = _mirror(GitRevisionSource(str(repo.path)), "HEAD")
+ with pytest.raises(ValueError, match="does not name this revision pair"):
+ supplied.resolve("some-other-branch")
+
+
+def test_reading_an_unknown_sha_raises(make_repo):
+ repo: Repo = make_repo("parity")
+ repo.commit("base", {"app/a.py": "a = 1\n"})
+ repo.commit("head", {"app/a.py": "a = 2\n"})
+
+ supplied = _mirror(GitRevisionSource(str(repo.path)), "HEAD")
+ with pytest.raises(ValueError, match="neither side"):
+ supplied.read("0" * 40, ["app/a.py"])
+
+
+def test_a_commit_pair_has_no_working_tree_to_read(make_repo):
+ repo: Repo = make_repo("parity")
+ repo.commit("base", {"app/a.py": "a = 1\n"})
+ repo.commit("head", {"app/a.py": "a = 2\n"})
+
+ supplied = _mirror(GitRevisionSource(str(repo.path)), "HEAD")
+ with pytest.raises(ValueError, match="no working tree"):
+ supplied.read_working_tree(["app/a.py"])
+
+
+# ---------------------------------------------------------------------------
+# The MCP directive keeps its wire shape after the policy moved to core
+# ---------------------------------------------------------------------------
+
+
+def _clean_delta():
+ from repowise.core.analysis.change_health.models import ChangeHealthDelta
+
+ return ChangeHealthDelta(
+ status="available",
+ explanation="",
+ base=None,
+ head=None,
+ comparison_basis="commit",
+ fingerprint=None,
+ )
+
+
+def test_directive_without_a_test_block_asks_for_nothing():
+ """No test block means the lane was never consulted, not that coverage is absent.
+
+ The pre-extraction code added no action for a falsy ``tests``; treating an
+ absent block as "no coverage map" would invent an instruction out of
+ silence.
+ """
+ from repowise.server.mcp_server._change_health import directive
+
+ for absent in (None, {}):
+ assert directive(_clean_delta(), absent)["next_actions"] == []
+
+
+def test_directive_still_names_a_missing_coverage_map():
+ from repowise.server.mcp_server._change_health import directive
+
+ actions = directive(_clean_delta(), {"status": "no_map"})["next_actions"]
+ assert actions == ["No measured test map; run the suite covering the changed files."]
+
+
+def test_directive_renders_at_most_three_tests_in_one_run_command():
+ from repowise.server.mcp_server._change_health import directive
+
+ tests = {"tests_to_run": [f"t{i}" for i in range(9)], "basis": "measured"}
+ assert directive(_clean_delta(), tests)["next_actions"] == ["Run: t0 t1 t2"]
diff --git a/tests/unit/persistence/test_test_impact_deleted_paths.py b/tests/unit/persistence/test_test_impact_deleted_paths.py
new file mode 100644
index 000000000..daa3d9041
--- /dev/null
+++ b/tests/unit/persistence/test_test_impact_deleted_paths.py
@@ -0,0 +1,106 @@
+"""A deleted path has no head side, so "no tests cover it" is not a gap.
+
+Without the change status every path is treated as present, and a deletion
+reads as an uncovered file -- overstating the coverage debt of a change whose
+whole point was to remove the code. These tests pin both readings.
+"""
+
+from __future__ import annotations
+
+from repowise.core.analysis.test_impact import analyze_test_impact
+from tests.unit.persistence.helpers import insert_repo
+from tests.unit.persistence.test_pr_test_impact_semantics import _fixture, _seed
+
+
+async def _impact(session, repo_id, changed, **kwargs):
+ return await analyze_test_impact(session, repo_id, changed, **kwargs)
+
+
+async def test_a_deleted_path_is_not_counted_as_a_coverage_gap(async_session):
+ fixture = _fixture()
+ repo = await insert_repo(async_session, name="deleted", head_commit="fixture-head")
+ await _seed(async_session, repo.id, fixture)
+
+ gone = "app/removed_module.py"
+ impact = await _impact(
+ async_session, repo.id, [gone], change_status={gone: "deleted"}
+ )
+
+ row = next(r for r in impact["files"] if r["source_file"] == gone)
+ assert row["status"] == "deleted"
+ assert row["head_present"] is False
+ assert row["change_status"] == "deleted"
+ assert impact["deleted_files"] == [gone]
+ # The two lanes that mean "you are missing tests" must not claim it.
+ assert gone not in impact["files_without_measured_tests"]
+ assert gone not in impact["unknown_files"]
+
+
+async def test_without_a_status_the_same_path_reads_as_an_unknown_gap(async_session):
+ """The historical behaviour, kept for callers that supply no status."""
+ fixture = _fixture()
+ repo = await insert_repo(async_session, name="nostatus", head_commit="fixture-head")
+ await _seed(async_session, repo.id, fixture)
+
+ gone = "app/removed_module.py"
+ impact = await _impact(async_session, repo.id, [gone])
+
+ row = next(r for r in impact["files"] if r["source_file"] == gone)
+ assert row["status"] == "unknown"
+ assert row["head_present"] is True
+ assert row["change_status"] is None
+ assert impact["deleted_files"] == []
+ assert gone in impact["files_without_measured_tests"]
+
+
+async def test_a_deleted_path_that_tests_did_cover_still_reports_them(async_session):
+ """Deletion is not a reason to hide the tests that exercised the file."""
+ fixture = _fixture()
+ repo = await insert_repo(async_session, name="covereddel", head_commit="fixture-head")
+ await _seed(async_session, repo.id, fixture)
+
+ covered = fixture["coverage"][0]["source_file"]
+ impact = await _impact(
+ async_session, repo.id, [covered], change_status={covered: "deleted"}
+ )
+
+ row = next(r for r in impact["files"] if r["source_file"] == covered)
+ assert row["measured_tests"]
+ # Measured evidence wins the status: there is something concrete to run.
+ assert row["status"] == "measured"
+ assert row["head_present"] is False
+ assert impact["deleted_files"] == []
+
+
+async def test_modified_and_added_paths_are_unaffected(async_session):
+ fixture = _fixture()
+ repo = await insert_repo(async_session, name="mixed", head_commit="fixture-head")
+ await _seed(async_session, repo.id, fixture)
+
+ changed = ["app/added.py", "app/modified.py"]
+ impact = await _impact(
+ async_session,
+ repo.id,
+ changed,
+ change_status={"app/added.py": "added", "app/modified.py": "modified"},
+ )
+
+ assert impact["deleted_files"] == []
+ assert all(row["head_present"] for row in impact["files"])
+ assert sorted(impact["files_without_measured_tests"]) == sorted(changed)
+
+
+async def test_a_deletion_alongside_a_real_gap_separates_the_two(async_session):
+ fixture = _fixture()
+ repo = await insert_repo(async_session, name="both", head_commit="fixture-head")
+ await _seed(async_session, repo.id, fixture)
+
+ impact = await _impact(
+ async_session,
+ repo.id,
+ ["app/gone.py", "app/kept.py"],
+ change_status={"app/gone.py": "deleted", "app/kept.py": "modified"},
+ )
+
+ assert impact["deleted_files"] == ["app/gone.py"]
+ assert impact["files_without_measured_tests"] == ["app/kept.py"]