Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(change-risk): compare a split source on the base side so a pure split reads as moved (#4125)

Raghav Chamadiya800a2a830101
diff --git a/packages/core/src/repowise/core/analysis/change_health/matcher.py b/packages/core/src/repowise/core/analysis/change_health/matcher.py
index 7ecac2ac7..2819f2e27 100644
--- a/packages/core/src/repowise/core/analysis/change_health/matcher.py
+++ b/packages/core/src/repowise/core/analysis/change_health/matcher.py
@@ -105,22 +105,46 @@ class FindingMatcher:
if not self.moves.moved_total:
return
candidates = []
+ origins: dict[int, SymbolKey] = {}
for mi, m in enumerate(result.matched):
- origin = self.moves.origin_of(m.head.file_path, m.head.function_name)
- if m.base is None and origin is not None:
+ new = self.moves.locate(m.head.file_path, m.head.function_name, m.head.line_start)
+ if m.base is None and new is not None:
+ origins[mi] = old = self.moves.by_new[new]
candidates += [
- (_shape_gap(b, m.head), mi, bi)
+ (self._move_distance(b, m.head, new, old), mi, bi)
for bi, b in enumerate(result.resolved)
- if _same_marker_at(b, m.head, origin)
+ if self._held_by(b, m.head, old)
]
peers = _closest_first(candidates)
for mi, bi in peers.items():
m, base = result.matched[mi], result.resolved[bi]
m.base, m.kind = base, _classify(base, m.head, carried="moved")
- m.moved_from = (base.file_path, str(base.function_name))
+ m.moved_from = origins[mi]
claimed = {id(result.resolved[bi]) for bi in peers.values()}
result.resolved = [f for f in result.resolved if id(f) not in claimed]
+ def _held_by(self, base: HealthFindingData, head: HealthFindingData, old: SymbolKey) -> bool:
+ """*base* is *head*'s marker, inside the symbol *old* names."""
+ if (base.dimension, base.biomarker_type) != (head.dimension, head.biomarker_type):
+ return False
+ if base.file_path != old[0]:
+ return False
+ if base.function_name == old[1]:
+ return True
+ # An unnamed marker on either side is placed by its line instead.
+ named_both = bool(base.function_name and head.function_name)
+ return not named_both and self.moves.holds(old, base.line_start)
+
+ def _move_distance(
+ self, base: HealthFindingData, head: HealthFindingData, new: SymbolKey, old: SymbolKey
+ ) -> tuple[int, int]:
+ """Shape first, then where each sits inside its symbol: offsets travel, lines do not."""
+ offsets = abs(
+ self.moves.offset(old, base.line_start, old=True)
+ - self.moves.offset(new, head.line_start)
+ )
+ return (_shape_gap(base, head), offsets)
+
def _pair_renames(self, result: MatchResult) -> None:
"""Pair introduced head findings with resolved base findings of one shape.
@@ -207,14 +231,6 @@ def _closest_first(candidates: Iterable[tuple[int, int, int]]) -> dict[int, int]
return peers
-def _same_marker_at(base: HealthFindingData, head: HealthFindingData, origin: SymbolKey) -> bool:
- """*base* is *head*'s marker on the symbol *origin* names."""
- return (base.file_path, base.function_name) == origin and (
- base.dimension,
- base.biomarker_type,
- ) == (head.dimension, head.biomarker_type)
-
-
def _shape_gap(base: HealthFindingData, head: HealthFindingData) -> int:
"""0 when both measured the same, else 1; line numbers do not travel across files."""
return 0 if measured_shape(base, path=head.file_path) == measured_shape(head) else 1
diff --git a/packages/core/src/repowise/core/analysis/change_health/models.py b/packages/core/src/repowise/core/analysis/change_health/models.py
index c7e7d7559..2b365cdca 100644
--- a/packages/core/src/repowise/core/analysis/change_health/models.py
+++ b/packages/core/src/repowise/core/analysis/change_health/models.py
@@ -193,6 +193,8 @@ class ChangeHealthDelta:
moved_total: int = 0
#: ``{path: reason}``. Any reason outside ``NO_CODE_GAP`` means the run was partial.
skipped: dict[str, str] = field(default_factory=dict)
+ #: Deleted files compared on the base side, and the files their code moved to.
+ moved_to: dict[str, list[str]] = field(default_factory=dict)
timing_ms: float = 0.0
cache_hit: bool = False
limits: list[str] = field(default_factory=list)
diff --git a/packages/core/src/repowise/core/analysis/change_health/moves.py b/packages/core/src/repowise/core/analysis/change_health/moves.py
index 12c0993a0..65ff0fe3c 100644
--- a/packages/core/src/repowise/core/analysis/change_health/moves.py
+++ b/packages/core/src/repowise/core/analysis/change_health/moves.py
@@ -34,7 +34,7 @@ _SKIPPED_KINDS = frozenset({"module", "impl"})
MIN_RENAMED_TOKENS = 20
#: An edited move may grow or shrink by at most this factor.
-_MAX_EDITED_GROWTH = 2
+_MAX_EDITED_GROWTH = 3
#: An edited move keeps at least this share of its adjacent token pairs.
_MIN_EDITED_OVERLAP = 0.5
@@ -53,6 +53,8 @@ class SymbolBody:
tokens: int
#: Adjacent token pairs, hashed; how much of the body an edit kept.
pairs: frozenset[int] = field(default=frozenset(), compare=False, repr=False)
+ #: ``(start_line, end_line)`` in its file.
+ span: tuple[int, int] = field(default=(0, 0), compare=False)
@property
def key(self) -> SymbolKey:
@@ -66,14 +68,45 @@ class MoveMap:
by_new: Mapping[SymbolKey, SymbolKey] = field(default_factory=lambda: MappingProxyType({}))
#: Moved keys whose body also changed on the way.
edited: frozenset[SymbolKey] = frozenset()
+ #: Line spans of the moved symbols at head, by new key.
+ new_spans: Mapping[SymbolKey, tuple[int, int]] = field(
+ default_factory=lambda: MappingProxyType({})
+ )
+ #: Line spans of their origins on the base side, by origin key.
+ old_spans: Mapping[SymbolKey, tuple[int, int]] = field(
+ default_factory=lambda: MappingProxyType({})
+ )
def origin_of(self, path: str, symbol: str | None) -> SymbolKey | None:
return self.by_new.get((path, symbol)) if symbol else None
+ def locate(self, path: str, symbol: str | None, line: int | None) -> SymbolKey | None:
+ """The moved key owning a finding: its symbol, else the innermost span at *line*."""
+ if symbol:
+ return (path, symbol) if (path, symbol) in self.by_new else None
+ held = [k for k, span in self.new_spans.items() if k[0] == path and _within(span, line)]
+ return min(held, key=lambda k: _length(self.new_spans[k]), default=None)
+
+ def offset(self, key: SymbolKey, line: int | None, *, old: bool = False) -> int:
+ """*line* relative to the start of *key*'s span, which travels with the code."""
+ spans = self.old_spans if old else self.new_spans
+ return (line or 0) - spans.get(key, (0, 0))[0]
+
+ def holds(self, old_key: SymbolKey, line: int | None) -> bool:
+ """True when *line* falls inside the origin symbol *old_key*."""
+ return _within(self.old_spans.get(old_key), line)
+
@property
def moved_total(self) -> int:
return len(self.by_new)
+ def destinations(self) -> dict[str, list[str]]:
+ """``{old_path: [new_path, ...]}``: where each source file's moved symbols went."""
+ out: dict[str, set[str]] = {}
+ for (new_path, _), (old_path, _) in self.by_new.items():
+ out.setdefault(old_path, set()).add(new_path)
+ return {old: sorted(new) for old, new in sorted(out.items())}
+
def symbol_bodies(path: str, raw: bytes, symbols: Iterable[Symbol]) -> list[SymbolBody]:
"""The normalized body of each named symbol in *path*, read from its *raw* bytes."""
@@ -89,7 +122,7 @@ def symbol_bodies(path: str, raw: bytes, symbols: Iterable[Symbol]) -> list[Symb
# Line-bounded: code sharing a line with the symbol joins its body.
span = rows[bisect_left(starts, symbol.start_line) : bisect_right(starts, symbol.end_line)]
if span:
- out.append(_body(path, symbol.name, raw, span))
+ out.append(_body(symbol, path, raw, span))
return out
@@ -133,7 +166,12 @@ def build_move_map(
if _similar(old, new)
]
by_new = {new.key: old.key for old, new in verbatim + edited}
- return MoveMap(MappingProxyType(by_new), frozenset(new.key for _, new in edited))
+ return MoveMap(
+ MappingProxyType(by_new),
+ frozenset(new.key for _, new in edited),
+ MappingProxyType({new.key: new.span for _, new in verbatim + edited}),
+ MappingProxyType({old.key: old.span for old, _ in verbatim + edited}),
+ )
def _pair_unique(
@@ -176,11 +214,21 @@ def _similar(old: SymbolBody, new: SymbolBody) -> bool:
return shared >= _MIN_EDITED_OVERLAP * max(len(old.pairs), len(new.pairs), 1)
-def _body(path: str, name: str, raw: bytes, rows: list[TokenRow]) -> SymbolBody:
+def _within(span: tuple[int, int] | None, line: int | None) -> bool:
+ return span is not None and line is not None and span[0] <= line <= span[1]
+
+
+def _length(span: tuple[int, int]) -> int:
+ return span[1] - span[0]
+
+
+def _body(symbol: Symbol, path: str, raw: bytes, rows: list[TokenRow]) -> SymbolBody:
+ name = symbol.name
parts = [_NAME_MARK if row[5] == name else raw[row[3] : row[4]] for row in rows]
digest = hashlib.blake2b(_SEPARATOR.join(parts), digest_size=16).hexdigest()
pairs = frozenset(hash(pair) for pair in pairwise(parts))
- return SymbolBody(path, name, digest, len(parts), pairs)
+ span = (symbol.start_line, symbol.end_line)
+ return SymbolBody(path, name, digest, len(parts), pairs, span)
def _order(body: SymbolBody) -> tuple[str, str, str]:
diff --git a/packages/core/src/repowise/core/analysis/change_health/service.py b/packages/core/src/repowise/core/analysis/change_health/service.py
index 9df3d9c48..c83336785 100644
--- a/packages/core/src/repowise/core/analysis/change_health/service.py
+++ b/packages/core/src/repowise/core/analysis/change_health/service.py
@@ -23,7 +23,7 @@ from ..health.scoring import ADVISORY_DIMENSION, is_advisory
from .analyzer import RevisionAnalysis, RevisionHealthAnalyzer, language_for, language_of
from .attribution import FindingAttributor, changed_symbols_for
from .identity import change_finding_id, finding_key, severity_rank
-from .matcher import FindingMatcher, MatchedFinding
+from .matcher import FindingMatcher, MatchedFinding, MatchResult
from .models import (
NO_CODE_GAP,
NOT_ANALYZABLE_DATA,
@@ -69,6 +69,8 @@ _CLAIM_ATTEMPTS = 2
_DIMENSION_ORDER = {"defect": 0, "maintainability": 1, "performance": 2, ADVISORY_DIMENSION: 3}
+_BASIS = "both_sides_analyzed"
+
#: Bases that place a finding away from the lines the change wrote.
_INCIDENTAL_BASES = {"file_change", "context_change", "unknown"}
@@ -206,35 +208,21 @@ class ChangeHealthDeltaService:
# -- comparison ---------------------------------------------------------
- def _compare_uncached(
- self, request: DeltaRequest, pair: RevisionPair
- ) -> ChangeHealthDelta:
+ def _compare_uncached(self, request: DeltaRequest, pair: RevisionPair) -> ChangeHealthDelta:
started = time.perf_counter()
changes = _filter(pair.changes, request)
- scope = ScopeCounts(changed=len(changes))
- eligible = [c for c in changes if c.head_path and language_for(c.head_path)]
- scope.eligible = len(eligible)
- skipped = {
- c.head_path or c.base_path or "": _skip_reason(c) for c in changes if c not in eligible
- }
- skipped.pop("", None)
+ eligible, departed, skipped = _partition(changes)
+ scope = ScopeCounts(changed=len(changes), eligible=len(eligible) + len(departed))
+ base_id, head_id = _revision_ids(pair)
- base_id = RevisionId(pair.base_ref, pair.base_sha, "commit")
- head_id = RevisionId(
- pair.head_ref,
- pair.head_sha or "",
- "working_tree" if pair.working_tree else "commit",
- )
- basis = "both_sides_analyzed"
-
- if not eligible:
+ if not scope.eligible:
delta = ChangeHealthDelta(
# Nothing was compared either way, so neither case is a clean bill.
status="unavailable",
explanation=_nothing_compared(changes, skipped),
base=base_id,
head=head_id,
- comparison_basis=basis,
+ comparison_basis=_BASIS,
fingerprint=self.fingerprint,
scope=scope,
skipped=skipped,
@@ -242,10 +230,10 @@ class ChangeHealthDeltaService:
delta.timing_ms = (time.perf_counter() - started) * 1000
return delta
- if len(eligible) > MAX_CHANGED_FILES:
+ if scope.eligible > MAX_CHANGED_FILES:
return _unavailable(
"too_large",
- f"{len(eligible)} changed files exceeds the {MAX_CHANGED_FILES}-file "
+ f"{scope.eligible} changed files exceeds the {MAX_CHANGED_FILES}-file "
"ceiling for a two-sided analysis.",
base=base_id,
head=head_id,
@@ -253,65 +241,82 @@ class ChangeHealthDeltaService:
fingerprint=self.fingerprint,
)
+ sides = self._analyze(pair, eligible, departed)
+ skipped.update(sides.head_run.skipped)
+ skipped.update(_held_origins(sides.head_sources, self.repo_path))
+ skipped.update(_base_failures(eligible + departed, sides.base_run, skipped))
+ subject = {
+ p for p in sides.head_run.analyzed if p in set(sides.head_paths) and p not in skipped
+ }
+ moves = build_move_map(
+ bodies_for(sides.base_sources, sides.base_run.symbols),
+ bodies_for(sides.head_sources, sides.head_run.symbols),
+ rename_map=sides.rename,
+ )
+ gone = {c.base_path for c in departed if c.base_path and c.base_path not in skipped}
+
+ scope.analyzed = len(subject) + len(gone)
+ scope.skipped = len(skipped)
+ scope.failed = sum(
+ 1 for r in skipped.values() if r.removeprefix("base_") in {"parse_failed", "unreadable"}
+ )
+ match = _match(sides, subject, gone, FindingMatcher(sides.rename, _hunks(eligible), moves))
+ findings = self._surface(match, eligible, sides.head_run.findings_for(subject), pair)
+
+ status, explanation = _status_for(scope, skipped, findings, deleted=len(gone))
+ delta = ChangeHealthDelta(
+ status=status,
+ explanation=explanation,
+ base=base_id,
+ head=head_id,
+ comparison_basis=_BASIS,
+ fingerprint=self.fingerprint,
+ scope=scope,
+ findings=findings,
+ resolved_total=len(match.resolved),
+ unchanged_total=match.unchanged_total,
+ improved_total=match.improved_total,
+ moved_total=match.moved_total,
+ skipped=skipped,
+ moved_to={old: new for old, new in moves.destinations().items() if old in gone},
+ limits=_limits(sides.head_run.findings_for(subject)),
+ )
+ delta.timing_ms = (time.perf_counter() - started) * 1000
+ return delta
+
+ def _analyze(
+ self, pair: RevisionPair, eligible: list[FileChange], departed: list[FileChange]
+ ) -> _Sides:
+ """Read and analyse both sides; *departed* (deleted) files go on the base side only.
+
+ Code split out of a deleted file then pairs with its new home instead of
+ reading as introduced.
+ """
head_paths = [c.head_path for c in eligible if c.head_path]
- base_paths = [c.base_path for c in eligible if c.base_path]
+ base_paths = [c.base_path for c in eligible + departed if c.base_path]
head_sources = (
self.source.read_working_tree(head_paths)
if pair.working_tree
else self.source.read(pair.head_sha, head_paths)
)
base_sources = self.source.read(pair.base_sha, base_paths)
-
rename = pair.rename_map()
head_run = self.analyzer.analyze(head_sources, subject_paths=set(head_paths))
base_run = self.analyzer.analyze(
base_sources, subject_paths=set(base_paths), dependents=_on_base(head_run, rename)
)
+ return _Sides(head_paths, head_sources, base_sources, head_run, base_run, rename)
- skipped.update(head_run.skipped)
- skipped.update(_held_origins(head_sources, self.repo_path))
- # A file whose BASE side failed has no baseline, so every finding at its
- # head would read as introduced. Drop it from the subject and say so:
- # silently keeping it is how a partial run fabricates new findings.
- for change in eligible:
- head_path, base_path = change.head_path, change.base_path
- if head_path is None or base_path is None or head_path in skipped:
- continue
- reason = base_run.skipped.get(base_path)
- if reason is not None:
- skipped[head_path] = f"base_{reason}"
- subject = {p for p in head_run.analyzed if p in set(head_paths) and p not in skipped}
-
- scope.analyzed = len(subject)
- scope.skipped = len(skipped)
- scope.failed = sum(
- 1 for r in skipped.values() if r.removeprefix("base_") in {"parse_failed", "unreadable"}
- )
-
- moves = build_move_map(
- bodies_for(base_sources, base_run.symbols),
- bodies_for(head_sources, head_run.symbols),
- rename_map=rename,
- )
- matcher = FindingMatcher(rename, _hunks(eligible), moves)
- # Both sides are restricted to the same comparable set, so an excluded
- # file cannot contribute a one-sided "introduced" or "resolved".
- # Advisory markers deduct nothing, so adding one is not a regression
- # and removing one is not a fix. Dropped from BOTH sides before
- # matching, so every counter derived from the match agrees. Types the
- # finding-type registry withholds go the same way, for the same reason,
- # as do findings on a language the registry gates for health findings.
- withheld = excluded_types()
- base_findings = [
- f
- for f in base_run.findings
- if rename.get(f.file_path, f.file_path) in subject and _comparable(f, withheld)
- ]
- head_findings = [f for f in head_run.findings_for(subject) if _comparable(f, withheld)]
- match = matcher.match(base_findings, head_findings)
-
+ def _surface(
+ self,
+ match: MatchResult,
+ eligible: list[FileChange],
+ head_findings: list[HealthFindingData],
+ pair: RevisionPair,
+ ) -> list[ChangeFinding]:
+ """The introduced and worsened findings, attributed and in priority order."""
by_file: dict[str, list[HealthFindingData]] = {}
- for finding in head_run.findings_for(subject):
+ for finding in head_findings:
by_file.setdefault(finding.file_path, []).append(finding)
change_map = {c.head_path: c for c in eligible if c.head_path}
attributor = FindingAttributor(change_map)
@@ -329,26 +334,7 @@ class ChangeHealthDeltaService:
for m in surfaced
]
findings.sort(key=_priority)
-
- status, explanation = _status_for(scope, skipped, findings)
- delta = ChangeHealthDelta(
- status=status,
- explanation=explanation,
- base=base_id,
- head=head_id,
- comparison_basis=basis,
- fingerprint=self.fingerprint,
- scope=scope,
- findings=findings,
- resolved_total=len(match.resolved),
- unchanged_total=match.unchanged_total,
- improved_total=match.improved_total,
- moved_total=match.moved_total,
- skipped=skipped,
- limits=_limits(head_run.findings_for(subject)),
- )
- delta.timing_ms = (time.perf_counter() - started) * 1000
- return delta
+ return findings
def _to_change_finding(
self,
@@ -393,6 +379,85 @@ class ChangeHealthDeltaService:
# -- helpers ----------------------------------------------------------------
+@dataclass(frozen=True, slots=True)
+class _Sides:
+ """Both sides' bytes and analyses, as one comparison reads them."""
+
+ head_paths: list[str]
+ head_sources: dict[str, bytes]
+ base_sources: dict[str, bytes]
+ head_run: RevisionAnalysis
+ base_run: RevisionAnalysis
+ rename: dict[str, str]
+
+
+def _partition(
+ changes: list[FileChange],
+) -> tuple[list[FileChange], list[FileChange], dict[str, str]]:
+ """``(eligible, departed, skipped)``: analysable on head, deleted but analysable, the rest."""
+ eligible: list[FileChange] = []
+ departed: list[FileChange] = []
+ skipped: dict[str, str] = {}
+ for change in changes:
+ if change.head_path and language_for(change.head_path):
+ eligible.append(change)
+ elif change.head_path is None and language_for(change.base_path or ""):
+ departed.append(change)
+ elif path := change.head_path or change.base_path:
+ skipped[path] = _skip_reason(change)
+ return eligible, departed, skipped
+
+
+def _revision_ids(pair: RevisionPair) -> tuple[RevisionId, RevisionId]:
+ base = RevisionId(pair.base_ref, pair.base_sha, "commit")
+ head = RevisionId(
+ pair.head_ref, pair.head_sha or "", "working_tree" if pair.working_tree else "commit"
+ )
+ return base, head
+
+
+def _base_failures(
+ changes: list[FileChange], base_run: RevisionAnalysis, skipped: dict[str, str]
+) -> dict[str, str]:
+ """``{path: "base_<reason>"}`` for the files whose base side failed.
+
+ Without a baseline every head finding in the file would read as introduced,
+ so the file leaves the subject and the run says so.
+ """
+ out: dict[str, str] = {}
+ for change in changes:
+ path = change.head_path or change.base_path
+ reason = base_run.skipped.get(change.base_path or "")
+ if path and path not in skipped and reason is not None:
+ out[path] = f"base_{reason}"
+ return out
+
+
+def _match(
+ sides: _Sides, subject: set[str], gone: set[str], matcher: FindingMatcher
+) -> MatchResult:
+ """Match the comparable findings of both sides over the same file set.
+
+ Advisory markers deduct nothing, so adding one is not a regression and
+ removing one is not a fix; registry-withheld types and gated languages go
+ the same way. Dropped from both sides before matching, so every counter
+ derived from the match agrees.
+ """
+ withheld = excluded_types()
+ base_findings = [
+ f
+ for f in sides.base_run.findings
+ if (sides.rename.get(f.file_path, f.file_path) in subject or f.file_path in gone)
+ and _comparable(f, withheld)
+ ]
+ head_findings = [f for f in sides.head_run.findings_for(subject) if _comparable(f, withheld)]
+ match = matcher.match(base_findings, head_findings)
+ # A deleted file's unpaired findings may have moved somewhere this run did
+ # not read (an excluded or unparsed file), so they never count as resolved.
+ match.resolved = [f for f in match.resolved if f.file_path not in gone]
+ return match
+
+
def _filter(changes: list[FileChange], request: DeltaRequest) -> list[FileChange]:
"""Apply the caller's extension, inclusion and exclusion filters to the change set."""
return filter_changes(
@@ -455,7 +520,7 @@ def _skip_reason(change: FileChange) -> str:
def _status_for(
- scope: ScopeCounts, skipped: dict[str, str], findings: list[ChangeFinding]
+ scope: ScopeCounts, skipped: dict[str, str], findings: list[ChangeFinding], *, deleted: int = 0
) -> tuple[str, str]:
if scope.analyzed == 0:
return "unavailable", (
@@ -475,7 +540,8 @@ def _status_for(
"available",
"No supported new findings surfaced in the analyzed scope.",
)
- return "available", f"Compared {scope.analyzed} changed files on both sides."
+ both = f"Compared {scope.analyzed - deleted} changed files on both sides"
+ return "available", f"{both} and {deleted} deleted on the base side." if deleted else f"{both}."
def _limits(head_findings: list[HealthFindingData]) -> list[str]:
diff --git a/packages/core/src/repowise/core/analysis/change_review/models.py b/packages/core/src/repowise/core/analysis/change_review/models.py
index 8ab9e0a9f..8e6c00ad1 100644
--- a/packages/core/src/repowise/core/analysis/change_review/models.py
+++ b/packages/core/src/repowise/core/analysis/change_review/models.py
@@ -228,6 +228,7 @@ def _delta_dict(delta: ChangeHealthDelta) -> dict[str, Any]:
"unchanged_total": delta.unchanged_total,
"improved_total": delta.improved_total,
"moved_total": delta.moved_total,
+ "moved_to": dict(delta.moved_to),
"uncertain_total": delta.uncertain_total,
"findings": [asdict(finding) for finding in delta.findings],
"skipped": dict(delta.skipped),
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 165322288..31e68dbe5 100644
--- a/packages/server/src/repowise/server/mcp_server/_change_health.py
+++ b/packages/server/src/repowise/server/mcp_server/_change_health.py
@@ -25,6 +25,9 @@ TOP_FINDINGS_LIMIT = 3
#: Reasons carried on the directive.
REASON_LIMIT = 3
+#: Deleted sources listed with where their code went.
+MOVED_TO_LIMIT = 10
+
#: Findings whose next-action is carried in the default response.
_ACTIONABLE_FINDINGS = 2
@@ -180,6 +183,8 @@ def health_delta_block(delta: ChangeHealthDelta, *, revspec: str | None) -> dict
block["findings_reduced_reason"] = "top_findings_cap"
block["all_findings_via"] = _call(revspec, extra="include=['findings']")
block.update(_nonzero(improved=delta.improved_total, moved=delta.moved_total))
+ if delta.moved_to:
+ block["moved_to"] = dict(list(delta.moved_to.items())[:MOVED_TO_LIMIT])
if delta.skipped:
block["skipped"] = _skipped(delta.skipped)
if delta.limits:
diff --git a/tests/unit/change_health/test_comparison.py b/tests/unit/change_health/test_comparison.py
index 9623b727c..82ec469a5 100644
--- a/tests/unit/change_health/test_comparison.py
+++ b/tests/unit/change_health/test_comparison.py
@@ -100,7 +100,7 @@ def test_a_rename_carries_the_finding_across(make_repo):
assert delta.unchanged_total >= 1
-def test_deleting_a_file_surfaces_nothing_and_is_recorded_as_skipped(make_repo):
+def test_deleting_a_file_compares_its_base_side_and_surfaces_nothing(make_repo):
repo = make_repo()
repo.commit("seed", {"app.py": python_complex("tangle", 14), "keep.py": "x = 1\n"})
repo.remove("app.py")
@@ -109,7 +109,19 @@ def test_deleting_a_file_surfaces_nothing_and_is_recorded_as_skipped(make_repo):
delta = compare(repo)
assert delta.introduced_total == 0
- assert delta.skipped.get("app.py") == "deleted"
+ assert "app.py" not in delta.skipped
+ assert delta.resolved_total == 0
+ assert delta.status == "available"
+ assert delta.explanation == "No supported new findings surfaced in the analyzed scope."
+
+
+def test_a_deleted_file_with_no_health_dialect_is_still_recorded_as_skipped(make_repo):
+ repo = make_repo()
+ repo.commit("seed", {"page.html": "<p>hi</p>\n", "app.py": python_complex("tangle", 14)})
+ repo.remove("page.html")
+ repo.commit("delete", {"app.py": python_complex("tangle", 14) + "\n"})
+
+ assert compare(repo).skipped.get("page.html") == "deleted"
# -- multiplicity -----------------------------------------------------------
diff --git a/tests/unit/change_health/test_split_source.py b/tests/unit/change_health/test_split_source.py
new file mode 100644
index 000000000..038ca014c
--- /dev/null
+++ b/tests/unit/change_health/test_split_source.py
@@ -0,0 +1,135 @@
+"""A file split into new files: the deleted source joins the base side."""
+
+from __future__ import annotations
+
+from types import MappingProxyType
+
+from repowise.core.analysis.change_health.matcher import FindingMatcher
+from repowise.core.analysis.change_health.moves import MoveMap
+from repowise.core.analysis.change_health.service import ChangeHealthDeltaService, DeltaRequest
+from repowise.core.analysis.health import HealthFindingData, Severity
+
+from .conftest import python_complex
+
+
+def compare(repo):
+ service = ChangeHealthDeltaService(repo_path=str(repo.path))
+ return service.compare(DeltaRequest(str(repo.path), "HEAD"))
+
+
+def split(make_repo, *, extra: str = ""):
+ """``tool.py`` split three ways into a package, so no part reads as a rename."""
+ repo = make_repo()
+ parts = [python_complex(name, 14 + i) for i, name in enumerate(("tangle", "knot", "braid"))]
+ repo.commit("seed", {"tool.py": "\n\n".join(parts), "keep.py": "x = 1\n"})
+ repo.remove("tool.py")
+ repo.commit(
+ "split",
+ {
+ "tool/__init__.py": "from .a import tangle\nfrom .b import knot\n",
+ "tool/a.py": parts[0],
+ "tool/b.py": parts[1],
+ "tool/c.py": parts[2],
+ **({"tool/d.py": extra} if extra else {}),
+ },
+ )
+ return repo
+
+
+def test_a_pure_split_introduces_nothing_and_names_where_the_code_went(make_repo):
+ delta = compare(split(make_repo))
+
+ assert delta.introduced_total == 0
+ assert delta.resolved_total == 0
+ assert delta.moved_total >= 3
+ assert delta.moved_to == {"tool.py": ["tool/a.py", "tool/b.py", "tool/c.py"]}
+ assert "tool.py" not in delta.skipped
+ assert delta.status == "available"
+
+
+def test_new_code_beside_a_split_is_still_introduced(make_repo):
+ delta = compare(split(make_repo, extra="\n\n" + python_complex("fresh", 14)))
+
+ introduced = [f for f in delta.findings if f.change_kind == "introduced"]
+ assert {f.symbol for f in introduced} == {"fresh"}
+
+
+def test_the_mcp_block_lists_the_deleted_source_and_its_destinations(make_repo):
+ from repowise.server.mcp_server._change_health import health_delta_block
+
+ block = health_delta_block(compare(split(make_repo)), revspec="HEAD")
+
+ assert block["moved_to"] == {"tool.py": ["tool/a.py", "tool/b.py", "tool/c.py"]}
+ assert "skipped" not in block
+
+
+def unnamed(path: str, line: int) -> HealthFindingData:
+ return HealthFindingData(
+ biomarker_type="error_handling",
+ severity=Severity.MEDIUM,
+ file_path=path,
+ function_name=None,
+ line_start=line,
+ line_end=line,
+ details={},
+ health_impact=0.2,
+ reason="bare except",
+ dimension="defect",
+ )
+
+
+def test_a_finding_with_no_symbol_moves_with_the_symbol_whose_lines_hold_it():
+ moves = MoveMap(
+ MappingProxyType({("pkg/run.py", "run"): ("tool.py", "run")}),
+ new_spans=MappingProxyType({("pkg/run.py", "run"): (1, 30)}),
+ old_spans=MappingProxyType({("tool.py", "run"): (200, 229)}),
+ )
+ base = [unnamed("tool.py", 205), unnamed("tool.py", 220), unnamed("tool.py", 400)]
+ head = [unnamed("pkg/run.py", 21), unnamed("pkg/run.py", 6)]
+
+ result = FindingMatcher(moves=moves).match(base, head)
+
+ pairs = {m.head.line_start: m.base.line_start for m in result.matched if m.base}
+ assert pairs == {6: 205, 21: 220}
+ assert [m.kind for m in result.matched] == ["moved", "moved"]
+ assert [f.line_start for f in result.resolved] == [400]
+
+
+def test_a_split_beside_new_code_names_both_sides_in_its_explanation(make_repo):
+ delta = compare(split(make_repo, extra="\n\n" + python_complex("fresh", 14)))
+
+ assert delta.explanation == (
+ "Compared 5 changed files on both sides and 1 deleted on the base side."
+ )
+
+
+def test_a_deleted_source_that_fails_to_parse_on_base_leaves_a_gap(make_repo, monkeypatch):
+ from repowise.core.analysis.change_health import analyzer
+
+ real = analyzer.parse_file
+
+ def failing(info, raw):
+ if info.path == "tool.py":
+ raise ValueError("boom")
+ return real(info, raw)
+
+ monkeypatch.setattr(analyzer, "parse_file", failing)
+ delta = compare(split(make_repo))
+
+ assert delta.skipped.get("tool.py") == "base_parse_failed"
+ assert delta.status == "partial"
+
+
+def test_an_unnamed_marker_at_head_pairs_with_its_named_origin_by_span():
+ moves = MoveMap(
+ MappingProxyType({("pkg/run.py", "run"): ("tool.py", "run")}),
+ new_spans=MappingProxyType({("pkg/run.py", "run"): (1, 30)}),
+ old_spans=MappingProxyType({("tool.py", "run"): (200, 229)}),
+ )
+ base = unnamed("tool.py", 205)
+ base.function_name = "run"
+
+ result = FindingMatcher(moves=moves).match([base], [unnamed("pkg/run.py", 6)])
+
+ assert [m.kind for m in result.matched] == ["moved"]
+ assert result.resolved == []