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(analysis): compose one change review over the existing primitives (#2273)

Raghav Chamadiya35b50695e0c1
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 1941bb371..4da22f990 100644
--- a/packages/core/src/repowise/core/analysis/change_health/__init__.py
+++ b/packages/core/src/repowise/core/analysis/change_health/__init__.py
@@ -36,6 +36,7 @@ from .sources import (
MappingRevisionSource,
RevisionPair,
RevisionSource,
+ filter_changes,
)
__all__ = [
@@ -64,6 +65,7 @@ __all__ = [
"RevisionSource",
"ScopeCounts",
"change_finding_id",
+ "filter_changes",
"finding_key",
"opportunities_for",
]
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 9380546b3..cf339f88b 100644
--- a/packages/core/src/repowise/core/analysis/change_health/service.py
+++ b/packages/core/src/repowise/core/analysis/change_health/service.py
@@ -27,7 +27,13 @@ from .models import (
ScopeCounts,
)
from .perf_delta import PerfOpportunityView, index_by_finding, opportunities_for
-from .sources import FileChange, GitRevisionSource, RevisionPair, RevisionSource
+from .sources import (
+ FileChange,
+ GitRevisionSource,
+ RevisionPair,
+ RevisionSource,
+ filter_changes,
+)
#: Changed files above this count are refused rather than analysed twice.
MAX_CHANGED_FILES = 300
@@ -338,25 +344,11 @@ class ChangeHealthDeltaService:
def _filter(changes: list[FileChange], request: DeltaRequest) -> list[FileChange]:
"""Apply the caller's extension and exclusion filters to the change set."""
- import pathspec
-
- spec = (
- pathspec.PathSpec.from_lines("gitwildmatch", request.exclude_patterns)
- if request.exclude_patterns
- else None
+ return filter_changes(
+ changes,
+ extensions=request.extensions,
+ exclude_patterns=request.exclude_patterns,
)
- exts = {e if e.startswith(".") else f".{e}" for e in request.extensions}
- out = []
- for change in changes:
- path = change.head_path or change.base_path or ""
- if not path:
- continue
- if spec is not None and spec.match_file(path):
- continue
- if exts and not any(path.endswith(e) for e in exts):
- continue
- out.append(change)
- return out
def _skip_reason(change: FileChange) -> str:
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 06dc1f0d0..b90e6f0c5 100644
--- a/packages/core/src/repowise/core/analysis/change_health/sources.py
+++ b/packages/core/src/repowise/core/analysis/change_health/sources.py
@@ -325,6 +325,39 @@ class MappingRevisionSource:
return {path: self._head[path] for path in paths if path in self._head}
+def filter_changes(
+ changes: list[FileChange],
+ *,
+ extensions: tuple[str, ...] = (),
+ exclude_patterns: tuple[str, ...] = (),
+) -> list[FileChange]:
+ """Drop the changes a caller's extension and exclusion filters exclude.
+
+ One implementation, because a change the health comparison counted and one
+ the change manifest counted have to be the same change; two copies of this
+ rule drift the moment either grows a case.
+ """
+ import pathspec
+
+ spec = (
+ pathspec.PathSpec.from_lines("gitwildmatch", exclude_patterns)
+ if exclude_patterns
+ else None
+ )
+ exts = {e if e.startswith(".") else f".{e}" for e in extensions}
+ return [change for change in changes if _counts(change, spec, exts)]
+
+
+def _counts(change: FileChange, spec: object | None, exts: set[str]) -> bool:
+ """Whether *change* survives the caller's filters. One path, one decision."""
+ path = change.head_path or change.base_path or ""
+ if not path:
+ return False
+ if spec is not None and spec.match_file(path): # type: ignore[attr-defined]
+ return False
+ return not exts or any(path.endswith(ext) for ext in exts)
+
+
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_review/__init__.py b/packages/core/src/repowise/core/analysis/change_review/__init__.py
new file mode 100644
index 000000000..2dcbd8b48
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/change_review/__init__.py
@@ -0,0 +1,37 @@
+"""One composition of the change-review primitives, for every surface.
+
+The primitives each answer one question well -- risk scoring, health delta,
+contract impact, test impact, independent grouping, branch overlap -- and every
+surface has been composing them itself. :class:`ChangeReviewService` composes
+them once, over a single change manifest, into a versioned
+:class:`ChangeReviewBundle` that carries the full population and says which
+lanes were actually consulted.
+
+Semantics live here; caps, ordering for display and rendering live in the
+surface. Nothing in this package imports ``repowise.server``, an MCP registry,
+a response budget, GitHub, or a database session.
+"""
+
+from __future__ import annotations
+
+from .models import (
+ CHANGE_REVIEW_CONTRACT_VERSION,
+ LANES,
+ ChangeManifestEntry,
+ ChangeReviewBundle,
+ ChangeReviewRequest,
+ LaneState,
+)
+from .service import ChangeReviewEvidence, ChangeReviewService, ContractInputs
+
+__all__ = [
+ "CHANGE_REVIEW_CONTRACT_VERSION",
+ "LANES",
+ "ChangeManifestEntry",
+ "ChangeReviewBundle",
+ "ChangeReviewEvidence",
+ "ChangeReviewRequest",
+ "ChangeReviewService",
+ "ContractInputs",
+ "LaneState",
+]
diff --git a/packages/core/src/repowise/core/analysis/change_review/models.py b/packages/core/src/repowise/core/analysis/change_review/models.py
new file mode 100644
index 000000000..120d1ebda
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/change_review/models.py
@@ -0,0 +1,243 @@
+"""What a change review contains, as one versioned, uncapped result.
+
+Every surface that reviews a change asks the same questions -- what moved, how
+risky is its shape, what did it newly make worse, whose contracts changed,
+which tests cover it, is it really several changes -- and each has been
+answering them with its own composition of the same primitives. This module
+names the answer once so those compositions can converge on it.
+
+Two rules hold here:
+
+* **Uncapped.** Core returns the full population and says how big it is. Caps,
+ display ordering, Markdown, URLs and tool-call syntax belong to a surface.
+* **A lane that was not consulted says so.** Every lane carries an
+ :data:`~repowise.core.analysis.review_directive.EvidenceState`, so an empty
+ population is never confused with an absent one.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import asdict, dataclass
+from typing import Any
+
+from ..branch_overlap import BranchOverlap
+from ..change_contracts import ContractImpact
+from ..change_health.models import ChangeHealthDelta, RevisionId
+from ..change_health.sources import FileChange
+from ..change_risk import ChangeRiskResult, change_risk_payload
+from ..independent_changes import IndependentChanges
+from ..review_directive import EvidenceState, ReviewDirective
+
+#: Bumped when a serialized bundle stops being readable by the previous reader.
+#: Adding a field does not bump it; removing or renaming one, or changing what
+#: an existing field means, does.
+CHANGE_REVIEW_CONTRACT_VERSION = 1
+
+#: Every lane a bundle can carry, in the order :meth:`ChangeReviewBundle.as_dict`
+#: emits them. A reader may rely on each name here being a key of ``lanes``.
+LANES: tuple[str, ...] = (
+ "manifest",
+ "risk",
+ "health",
+ "contracts",
+ "tests",
+ "prior_fixes",
+ "independent_changes",
+ "branch_overlap",
+)
+
+
+@dataclass(frozen=True, slots=True)
+class LaneState:
+ """How much of one lane's evidence was computed, and why not more."""
+
+ state: EvidenceState
+ reason: str | None = None
+
+ def as_dict(self) -> dict[str, Any]:
+ return {"state": self.state, "reason": self.reason}
+
+
+def _collapse(lines: set[int]) -> tuple[tuple[int, int], ...]:
+ """Adjacent line numbers as inclusive spans: ``{1,2,3,7}`` -> ``((1,3),(7,7))``."""
+ spans: list[tuple[int, int]] = []
+ for line in sorted(lines):
+ if spans and line == spans[-1][1] + 1:
+ spans[-1] = (spans[-1][0], line)
+ else:
+ spans.append((line, line))
+ return tuple(spans)
+
+
+@dataclass(frozen=True, slots=True)
+class ChangeManifestEntry:
+ """One changed path, as every lane of the review counts it.
+
+ Built from the :class:`~repowise.core.analysis.change_health.sources.FileChange`
+ the revision source produced, rather than from a parallel mapping that could
+ disagree with it about what changed.
+ """
+
+ #: The single path naming this change: head side, or base side for a delete.
+ path: str
+ base_path: str | None
+ head_path: str | None
+ #: ``added`` | ``modified`` | ``deleted`` | ``renamed``.
+ status: str
+ #: ``parsed`` | ``unavailable`` | ``truncated`` | ``binary``. Anything but
+ #: ``parsed`` means the line-level lanes worked from an incomplete diff.
+ diff_reliability: str
+ #: Inclusive ``(start, end)`` spans of the lines this change added, collapsed
+ #: from the individual line numbers. Empty for a delete or an unparsed diff.
+ added_ranges: tuple[tuple[int, int], ...] = ()
+
+ @property
+ def added_line_count(self) -> int:
+ return sum(end - start + 1 for start, end in self.added_ranges)
+
+ @classmethod
+ def from_file_change(cls, change: FileChange) -> ChangeManifestEntry:
+ return cls(
+ path=change.path,
+ base_path=change.base_path or None,
+ head_path=change.head_path,
+ status=change.status,
+ diff_reliability=change.diff_reliability,
+ added_ranges=_collapse(change.added_lines),
+ )
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "path": self.path,
+ "base_path": self.base_path,
+ "head_path": self.head_path,
+ "status": self.status,
+ "diff_reliability": self.diff_reliability,
+ "added_ranges": [list(span) for span in self.added_ranges],
+ "added_line_count": self.added_line_count,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class ChangeReviewRequest:
+ """Which change to review, and which files count as part of it.
+
+ The filters are applied once, to the manifest, so every lane downstream
+ counts the same universe rather than each re-deriving it.
+ """
+
+ revspec: str | None = None
+ #: File suffixes to keep. Empty means every suffix.
+ extensions: tuple[str, ...] = ()
+ #: Gitwildmatch patterns to drop.
+ exclude_patterns: tuple[str, ...] = ()
+ #: Recent commits sampled to rank this change's shape. 0 disables ranking.
+ baseline: int = 200
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "revspec": self.revspec,
+ "extensions": list(self.extensions),
+ "exclude_patterns": list(self.exclude_patterns),
+ "baseline": self.baseline,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class ChangeReviewBundle:
+ """One change, reviewed by every lane that could be consulted."""
+
+ request: ChangeReviewRequest
+ base: RevisionId | None
+ head: RevisionId | None
+ manifest: tuple[ChangeManifestEntry, ...]
+ directive: ReviewDirective
+ #: One entry per name in :data:`LANES`, always populated.
+ lanes: Mapping[str, LaneState]
+ risk: ChangeRiskResult | None = None
+ health: ChangeHealthDelta | None = None
+ contracts: ContractImpact | None = None
+ #: The uncapped population from ``analyze_test_impact``, in that analyzer's
+ #: own shape. Core does not restate it in a second vocabulary.
+ tests: Mapping[str, Any] | None = None
+ independent_changes: IndependentChanges | None = None
+ branch_overlap: BranchOverlap | None = None
+ contract_version: int = CHANGE_REVIEW_CONTRACT_VERSION
+
+ def lane(self, name: str) -> LaneState:
+ """The state of *name*, or ``unsupported`` for a lane this build omits."""
+ return self.lanes.get(name, LaneState("unsupported", f"unknown lane {name!r}"))
+
+ @property
+ def degraded_lanes(self) -> tuple[str, ...]:
+ """Lanes whose evidence is anything less than complete."""
+ return tuple(name for name in LANES if self.lane(name).state != "available")
+
+ def as_dict(self) -> dict[str, Any]:
+ """Stable serialization. Uncapped, and every lane present as a key."""
+ return {
+ "contract_version": self.contract_version,
+ "request": self.request.as_dict(),
+ "base": self.base.as_dict() if self.base else None,
+ "head": self.head.as_dict() if self.head else None,
+ "lanes": {name: self.lane(name).as_dict() for name in LANES},
+ "manifest": [entry.as_dict() for entry in self.manifest],
+ "directive": _directive_dict(self.directive),
+ "risk": change_risk_payload(self.risk) if self.risk else None,
+ "health": _delta_dict(self.health) if self.health else None,
+ "contracts": _contracts_dict(self.contracts) if self.contracts else None,
+ "tests": dict(self.tests) if self.tests is not None else None,
+ "independent_changes": (
+ self.independent_changes.to_dict() if self.independent_changes else None
+ ),
+ "branch_overlap": self.branch_overlap.to_dict() if self.branch_overlap else None,
+ }
+
+
+def _directive_dict(directive: ReviewDirective) -> dict[str, Any]:
+ # ``fingerprint`` is a property rather than a field, so asdict() drops it --
+ # and it is the whole point of the directive to a caller telling a repeat
+ # action from a new one.
+ return {
+ "status": directive.status,
+ "headline": directive.headline,
+ "evidence_state": directive.evidence_state,
+ "fingerprint": directive.fingerprint,
+ "reasons": list(directive.reasons),
+ "actions": [
+ {**asdict(action), "targets": list(action.targets), "fingerprint": action.fingerprint}
+ for action in directive.actions
+ ],
+ }
+
+
+def _contracts_dict(impact: ContractImpact) -> dict[str, Any]:
+ return {
+ "status": impact.status,
+ "reason": impact.reason,
+ "base_is_snapshot": impact.base_is_snapshot,
+ "breaking_total": len(impact.breaking),
+ "changes_total": len(impact.changes),
+ "changes": [{**asdict(c), "is_breaking": c.is_breaking} for c in impact.changes],
+ }
+
+
+def _delta_dict(delta: ChangeHealthDelta) -> dict[str, Any]:
+ return {
+ "status": delta.status,
+ "explanation": delta.explanation,
+ "comparison_basis": delta.comparison_basis,
+ "base": delta.base.as_dict() if delta.base else None,
+ "head": delta.head.as_dict() if delta.head else None,
+ "fingerprint": delta.fingerprint.as_dict() if delta.fingerprint else None,
+ "scope": delta.scope.as_dict(),
+ "introduced_total": delta.introduced_total,
+ "worsened_total": delta.worsened_total,
+ "resolved_total": delta.resolved_total,
+ "unchanged_total": delta.unchanged_total,
+ "uncertain_total": delta.uncertain_total,
+ "findings": [asdict(finding) for finding in delta.findings],
+ "skipped": dict(delta.skipped),
+ "limits": list(delta.limits),
+ }
diff --git a/packages/core/src/repowise/core/analysis/change_review/service.py b/packages/core/src/repowise/core/analysis/change_review/service.py
new file mode 100644
index 000000000..e003a3aea
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/change_review/service.py
@@ -0,0 +1,386 @@
+"""Compose a change review once, from evidence the caller has already gathered.
+
+The split here is deliberate. Everything that needs a database session, a
+network call or a snapshot artifact is *collected* by a surface and handed in
+as :class:`ChangeReviewEvidence`; everything that decides what the evidence
+means happens here, over one manifest, so two surfaces cannot reach different
+conclusions from the same facts.
+
+That keeps this module synchronous and free of `AsyncSession`, MCP context,
+GitHub clients and Supabase clients, and it keeps the expensive lanes opt-in:
+a caller that gathers nothing still gets a bundle, with every lane honestly
+marked ``unsupported`` rather than empty.
+"""
+
+from __future__ import annotations
+
+import subprocess
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass, field
+from typing import Any
+
+from ..change_contracts import (
+ ContractImpact,
+ analyze_contract_impact,
+ unavailable_contract_impact,
+)
+from ..change_health import ChangeHealthDeltaService, DeltaRequest, RevisionSource
+from ..change_health.models import ChangeHealthDelta, RevisionId
+from ..change_health.sources import RevisionPair, filter_changes
+from ..change_risk import ChangeRiskResult, score_live_change
+from ..independent_changes import IndependentChangeEvidence, partition_independent_changes
+from ..review_directive import (
+ CoveringTestEvidence,
+ EvidenceState,
+ ReviewDirective,
+ review_directive,
+)
+from .models import (
+ LANES,
+ ChangeManifestEntry,
+ ChangeReviewBundle,
+ ChangeReviewRequest,
+ LaneState,
+)
+
+_NO_SOURCE = "no evidence was supplied for this lane"
+
+
+@dataclass(frozen=True, slots=True)
+class ContractInputs:
+ """The parses and graph :func:`analyze_contract_impact` compares over.
+
+ Collected by the surface, because where they come from differs: a live
+ checkout parses both sides, while an indexed consumer reads the last
+ snapshot for the base -- which is what ``base_is_snapshot`` records, so the
+ result never implies a comparison against the change's true base.
+ """
+
+ graph: dict
+ base_parsed: Any
+ head_parsed: Any
+ base_is_snapshot: bool = False
+
+
+@dataclass(frozen=True, slots=True)
+class ChangeReviewEvidence:
+ """Everything a lane needs that this module will not go and fetch itself.
+
+ Each field left at ``None`` marks its lane ``unsupported``: nobody asked
+ that question, which is a different answer from asking and finding nothing.
+ """
+
+ #: A pre-scored change. Omitted, the service scores the change itself when
+ #: it has a checkout to score from.
+ risk: ChangeRiskResult | None = None
+ contracts: ContractInputs | None = None
+ #: The result of ``analyze_test_impact``, uncapped, in its own shape.
+ tests: Mapping[str, Any] | None = None
+ independent: IndependentChangeEvidence | None = None
+ #: Already-ranked overlap, or ``None`` when no branch scan ran.
+ branch_overlap: Any = None
+ #: Why ``branch_overlap`` is ``None``, when it is absent rather than empty.
+ branch_overlap_reason: str | None = None
+ #: Lanes the caller wants skipped outright, by name from ``LANES``.
+ skip: frozenset[str] = field(default_factory=frozenset)
+
+
+class ChangeReviewService:
+ """Build one :class:`ChangeReviewBundle` for a change."""
+
+ def __init__(
+ self,
+ source: RevisionSource,
+ *,
+ repo_path: str | None = None,
+ delta_service: ChangeHealthDeltaService | None = None,
+ ) -> None:
+ self.source = source
+ self.repo_path = repo_path
+ self.delta_service = delta_service
+
+ def review(
+ self,
+ request: ChangeReviewRequest | None = None,
+ *,
+ evidence: ChangeReviewEvidence | None = None,
+ ) -> ChangeReviewBundle:
+ """Review the change *request* names, with whatever *evidence* allows."""
+ request = request or ChangeReviewRequest()
+ evidence = evidence or ChangeReviewEvidence()
+ try:
+ pair = self.source.resolve(request.revspec)
+ except ValueError as exc:
+ return _unresolved(request, str(exc))
+
+ changes = filter_changes(
+ pair.changes,
+ extensions=request.extensions,
+ exclude_patterns=request.exclude_patterns,
+ )
+ manifest = tuple(ChangeManifestEntry.from_file_change(c) for c in changes)
+ lanes: dict[str, LaneState] = {
+ "manifest": LaneState("available")
+ if manifest
+ else LaneState("unavailable", "the change touches no file this request counts")
+ }
+
+ health = self._health(request, evidence, lanes)
+ risk = self._risk(request, evidence, lanes)
+ self._prior_fixes(risk, lanes)
+ contracts = self._contracts(manifest, evidence, lanes)
+ tests = self._tests(evidence, lanes)
+ independent = self._independent(evidence, lanes)
+ overlap = self._branch_overlap(evidence, lanes)
+
+ directive = (
+ review_directive(health, _covering_tests(tests, lanes["tests"].state))
+ if health is not None
+ else ReviewDirective(
+ status="unknown",
+ headline=f"Change health was not compared: {lanes['health'].reason}",
+ evidence_state=lanes["health"].state,
+ )
+ )
+ return ChangeReviewBundle(
+ request=request,
+ base=RevisionId(pair.base_ref, pair.base_sha, "commit"),
+ head=_head_id(pair),
+ manifest=manifest,
+ directive=directive,
+ lanes=lanes,
+ risk=risk,
+ health=health,
+ contracts=contracts,
+ tests=tests,
+ independent_changes=independent,
+ branch_overlap=overlap,
+ )
+
+ # -- lanes --------------------------------------------------------------
+
+ def _health(
+ self,
+ request: ChangeReviewRequest,
+ evidence: ChangeReviewEvidence,
+ lanes: dict[str, LaneState],
+ ) -> ChangeHealthDelta | None:
+ if "health" in evidence.skip:
+ lanes["health"] = LaneState("unsupported", "the caller skipped this lane")
+ return None
+ service = self.delta_service or ChangeHealthDeltaService(
+ self.source, repo_path=self.repo_path
+ )
+ delta = service.compare(
+ DeltaRequest(
+ repo_path=self.repo_path or "",
+ revspec=request.revspec,
+ extensions=request.extensions,
+ exclude_patterns=request.exclude_patterns,
+ )
+ )
+ # The delta's own status already says how complete the comparison was;
+ # restating it in a second vocabulary is how the two drift apart.
+ lanes["health"] = LaneState(
+ _DELTA_LANE_STATE.get(delta.status, "degraded"),
+ None if delta.status == "available" else delta.explanation,
+ )
+ return delta
+
+ def _risk(
+ self,
+ request: ChangeReviewRequest,
+ evidence: ChangeReviewEvidence,
+ lanes: dict[str, LaneState],
+ ) -> ChangeRiskResult | None:
+ if evidence.risk is not None:
+ lanes["risk"] = LaneState("available")
+ return evidence.risk
+ if "risk" in evidence.skip:
+ lanes["risk"] = LaneState("unsupported", "the caller skipped this lane")
+ return None
+ if self.repo_path is None:
+ lanes["risk"] = LaneState(
+ "unsupported", "scoring a change's shape needs a checkout or a pre-scored result"
+ )
+ return None
+ try:
+ result = score_live_change(
+ self.repo_path,
+ request.revspec,
+ extensions=request.extensions,
+ exclude_patterns=request.exclude_patterns,
+ baseline=request.baseline,
+ )
+ # ``score_live_change`` walks git itself, and its ``_git`` raises
+ # CalledProcessError on a bad ref and TimeoutExpired on a wedged repo --
+ # neither of which is a ValueError or an OSError. One lane failing must
+ # not take the bundle down with it, which is the whole point of building
+ # a bundle rather than a response.
+ except (ValueError, OSError, subprocess.SubprocessError) as exc:
+ lanes["risk"] = LaneState("degraded", f"the change could not be scored: {exc}")
+ return None
+ lanes["risk"] = LaneState(
+ "available" if result.percentile is not None else "partial",
+ None
+ if result.percentile is not None
+ else (
+ f"{result.baseline_sample_size} comparable commits is too small a cohort "
+ "to rank this change against"
+ ),
+ )
+ return result
+
+ def _prior_fixes(self, risk: ChangeRiskResult | None, lanes: dict[str, LaneState]) -> None:
+ """The fix history the risk lane already walked, stated as its own lane.
+
+ It answers a different question from the score -- what has broken here
+ before, rather than how big this diff is -- and it can fail on its own
+ while the score survives, so it cannot share the risk lane's state.
+ """
+ if risk is None:
+ lanes["prior_fixes"] = LaneState("unsupported", _NO_SOURCE)
+ elif not risk.fix_history_available:
+ lanes["prior_fixes"] = LaneState("unavailable", "the fix-history walk could not run")
+ else:
+ lanes["prior_fixes"] = LaneState("available")
+
+ def _contracts(
+ self,
+ manifest: Sequence[ChangeManifestEntry],
+ evidence: ChangeReviewEvidence,
+ lanes: dict[str, LaneState],
+ ) -> ContractImpact:
+ inputs = evidence.contracts
+ if inputs is None or "contracts" in evidence.skip:
+ reason = "no graph or parsed revisions were supplied"
+ lanes["contracts"] = LaneState("unsupported", reason)
+ return unavailable_contract_impact(reason)
+ # The changed set and the added ranges come from the one manifest, so
+ # the symbols this lane blames are the symbols every other lane counted.
+ impact = analyze_contract_impact(
+ graph=inputs.graph,
+ base_parsed=inputs.base_parsed,
+ head_parsed=inputs.head_parsed,
+ changed_set={e.path for e in manifest if e.head_path},
+ added_ranges_by_file={
+ e.path: list(e.added_ranges) for e in manifest if e.added_ranges
+ },
+ base_is_snapshot=inputs.base_is_snapshot,
+ )
+ lanes["contracts"] = LaneState(
+ "partial" if inputs.base_is_snapshot else "available",
+ "the base side is the last indexed snapshot, not this change's base"
+ if inputs.base_is_snapshot
+ else None,
+ )
+ return impact
+
+ def _tests(
+ self, evidence: ChangeReviewEvidence, lanes: dict[str, LaneState]
+ ) -> Mapping[str, Any] | None:
+ if evidence.tests is None or "tests" in evidence.skip:
+ lanes["tests"] = LaneState("unsupported", _NO_SOURCE)
+ return None
+ coverage = evidence.tests.get("coverage") or {}
+ measured_map = bool(coverage.get("map_present"))
+ lanes["tests"] = LaneState(
+ "available" if measured_map else "partial",
+ None if measured_map else "no measured coverage map; candidates are graph-inferred",
+ )
+ return evidence.tests
+
+ def _independent(
+ self, evidence: ChangeReviewEvidence, lanes: dict[str, LaneState]
+ ) -> Any:
+ if evidence.independent is None or "independent_changes" in evidence.skip:
+ lanes["independent_changes"] = LaneState("unsupported", _NO_SOURCE)
+ return None
+ lanes["independent_changes"] = LaneState("available")
+ # ``None`` here means one change, not a missing answer: the lane ran.
+ return partition_independent_changes(evidence.independent)
+
+ def _branch_overlap(
+ self, evidence: ChangeReviewEvidence, lanes: dict[str, LaneState]
+ ) -> Any:
+ if "branch_overlap" in evidence.skip:
+ lanes["branch_overlap"] = LaneState("unsupported", "the caller skipped this lane")
+ return None
+ if evidence.branch_overlap is None:
+ lanes["branch_overlap"] = LaneState(
+ "unsupported", evidence.branch_overlap_reason or _NO_SOURCE
+ )
+ return None
+ lanes["branch_overlap"] = LaneState("available")
+ return evidence.branch_overlap
+
+
+# -- helpers ----------------------------------------------------------------
+
+#: A delta status is already an evidence state in another vocabulary. Map it
+#: rather than re-deriving one, so a new delta status degrades loudly (to
+#: ``degraded``) instead of silently reading as available.
+#:
+#: ``timeout`` maps to ``degraded`` here while the directive reports the same
+#: status as ``unavailable``, and that is deliberate: the directive is saying
+#: it has no verdict, whereas the lane is saying the comparison began and was
+#: cut short. Two readers, two true statements.
+_DELTA_LANE_STATE: dict[str, EvidenceState] = {
+ "available": "available",
+ "partial": "partial",
+ "unavailable": "unavailable",
+ "unsupported_range": "unsupported",
+ "too_large": "unavailable",
+ "timeout": "degraded",
+ "analyzer_mismatch": "degraded",
+ "rules_mismatch": "degraded",
+ "stale_baseline": "degraded",
+}
+
+
+def _head_id(pair: RevisionPair) -> RevisionId:
+ return RevisionId(
+ pair.head_ref,
+ pair.head_sha or "",
+ "working_tree" if pair.working_tree else "commit",
+ )
+
+
+def _covering_tests(
+ tests: Mapping[str, Any] | None, state: EvidenceState
+) -> CoveringTestEvidence:
+ """The test lane's contribution to the directive, in the directive's terms."""
+ if tests is None:
+ return CoveringTestEvidence()
+ rows = tests.get("recommendations") or []
+ ids = tuple(row["test_id"] for row in rows if row.get("test_id"))
+ bases = {row.get("basis") for row in rows}
+ basis = "measured" if "measured" in bases else ("inferred" if "inferred" in bases else None)
+ # Nothing to run AND no measured map is the one case that means "go and
+ # establish coverage"; with a map, an empty list is a real answer.
+ if not ids and state == "partial":
+ return CoveringTestEvidence(state="unavailable", basis=basis)
+ return CoveringTestEvidence(state=state, tests_to_run=ids, basis=basis)
+
+
+def _unresolved(request: ChangeReviewRequest, reason: str) -> ChangeReviewBundle:
+ """A bundle for a change that could not be identified at all."""
+ return ChangeReviewBundle(
+ request=request,
+ base=None,
+ head=None,
+ manifest=(),
+ directive=ReviewDirective(
+ status="unknown",
+ headline=f"The change could not be resolved: {reason}",
+ evidence_state="unavailable",
+ ),
+ lanes={name: LaneState("unavailable", reason) for name in LANES},
+ )
+
+
+__all__ = [
+ "ChangeReviewEvidence",
+ "ChangeReviewService",
+ "ContractInputs",
+]
diff --git a/tests/unit/change_health/test_change_review_bundle.py b/tests/unit/change_health/test_change_review_bundle.py
new file mode 100644
index 000000000..48e55d56c
--- /dev/null
+++ b/tests/unit/change_health/test_change_review_bundle.py
@@ -0,0 +1,464 @@
+"""The bundle must compose the primitives without changing what they say.
+
+Two properties are worth protecting here. First, a lane nobody consulted has to
+read as ``unsupported`` rather than as an empty answer -- the whole point of
+composing evidence in one place is that a caller can tell the difference.
+Second, the manifest is the one counted universe: every lane that takes a set
+of changed files has to take it from there, so the filters cannot be applied
+twice with two different results.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+
+import pytest
+
+from repowise.core.analysis.branch_overlap import BranchOverlap
+from repowise.core.analysis.change_health import GitRevisionSource, MappingRevisionSource
+from repowise.core.analysis.change_review import (
+ CHANGE_REVIEW_CONTRACT_VERSION,
+ LANES,
+ ChangeManifestEntry,
+ ChangeReviewEvidence,
+ ChangeReviewRequest,
+ ChangeReviewService,
+ ContractInputs,
+)
+from repowise.core.analysis.change_risk import assess_change, features_from_file_changes
+from repowise.core.analysis.independent_changes import IndependentChangeEvidence
+
+from .conftest import Repo, python_complex
+
+
+def _service(repo: Repo, **kwargs) -> ChangeReviewService:
+ return ChangeReviewService(GitRevisionSource(str(repo.path)), repo_path=str(repo.path), **kwargs)
+
+
+def _supplied_source(repo: Repo) -> MappingRevisionSource:
+ """The same change, served from bytes instead of from a checkout."""
+ git_source = GitRevisionSource(str(repo.path))
+ pair = git_source.resolve("HEAD")
+ return MappingRevisionSource(
+ pair,
+ git_source.read(pair.base_sha, [c.base_path for c in pair.changes if c.base_path]),
+ git_source.read(pair.head_sha, [c.head_path for c in pair.changes if c.head_path]),
+ )
+
+
+def _two_commit_repo(make_repo, name: str = "bundle") -> Repo:
+ repo: Repo = make_repo(name)
+ repo.commit("base", {"app/a.py": python_complex("run", 2), "docs/readme.md": "hello\n"})
+ repo.commit("head", {"app/a.py": python_complex("run", 8), "docs/readme.md": "hello there\n"})
+ return repo
+
+
+# ---------------------------------------------------------------------------
+# Lane honesty
+# ---------------------------------------------------------------------------
+
+
+def test_every_lane_is_named_even_when_nothing_was_collected(make_repo):
+ repo = _two_commit_repo(make_repo)
+
+ bundle = _service(repo).review(ChangeReviewRequest(revspec="HEAD", baseline=0))
+
+ assert set(bundle.lanes) == set(LANES)
+ assert bundle.lanes["tests"].state == "unsupported"
+ assert bundle.lanes["contracts"].state == "unsupported"
+ assert bundle.lanes["independent_changes"].state == "unsupported"
+ # An unsupported lane is an unasked question, and it has to say why.
+ assert bundle.lanes["tests"].reason
+
+
+def test_an_uncollected_lane_is_not_an_empty_one(make_repo):
+ repo = _two_commit_repo(make_repo)
+
+ bundle = _service(repo).review(ChangeReviewRequest(revspec="HEAD", baseline=0))
+
+ assert bundle.tests is None
+ assert bundle.independent_changes is None
+ assert bundle.contracts is not None and bundle.contracts.status == "unavailable"
+
+
+def test_a_consulted_lane_that_found_nothing_is_available(make_repo):
+ repo = _two_commit_repo(make_repo)
+ evidence = ChangeReviewEvidence(
+ independent=IndependentChangeEvidence(
+ paths=("app/a.py",), groupable=frozenset(), pairs=frozenset(), linked=frozenset()
+ )
+ )
+
+ bundle = _service(repo).review(
+ ChangeReviewRequest(revspec="HEAD", baseline=0), evidence=evidence
+ )
+
+ assert bundle.lanes["independent_changes"].state == "available"
+ # One change is not two independent ones; the lane ran and said so.
+ assert bundle.independent_changes is None
+
+
+def test_an_unresolvable_revspec_marks_every_lane_unavailable(make_repo):
+ repo = _two_commit_repo(make_repo)
+
+ bundle = _service(repo).review(ChangeReviewRequest(revspec="no-such-ref"))
+
+ assert {state.state for state in bundle.lanes.values()} == {"unavailable"}
+ assert bundle.directive.status == "unknown"
+ assert bundle.base is None and bundle.head is None
+ assert bundle.degraded_lanes == LANES
+
+
+def test_a_skipped_lane_says_the_caller_skipped_it(make_repo):
+ repo = _two_commit_repo(make_repo)
+
+ bundle = _service(repo).review(
+ ChangeReviewRequest(revspec="HEAD", baseline=0),
+ evidence=ChangeReviewEvidence(skip=frozenset({"health", "risk"})),
+ )
+
+ assert bundle.health is None and bundle.risk is None
+ assert bundle.lanes["health"].state == "unsupported"
+ # Prior fixes ride on the risk walk, so skipping risk unsupports them too.
+ assert bundle.lanes["prior_fixes"].state == "unsupported"
+
+
+# ---------------------------------------------------------------------------
+# One counted universe
+# ---------------------------------------------------------------------------
+
+
+def test_the_manifest_carries_the_change_the_source_reported(make_repo):
+ repo = _two_commit_repo(make_repo)
+
+ bundle = _service(repo).review(ChangeReviewRequest(revspec="HEAD", baseline=0))
+
+ paths = {entry.path for entry in bundle.manifest}
+ assert paths == {"app/a.py", "docs/readme.md"}
+ entry = next(e for e in bundle.manifest if e.path == "app/a.py")
+ assert entry.status == "modified"
+ assert entry.diff_reliability == "parsed"
+ assert entry.added_line_count > 0
+
+
+def test_filters_apply_once_and_every_lane_sees_the_result(make_repo):
+ repo = _two_commit_repo(make_repo)
+
+ bundle = _service(repo).review(
+ ChangeReviewRequest(revspec="HEAD", extensions=(".py",), baseline=0)
+ )
+
+ assert {entry.path for entry in bundle.manifest} == {"app/a.py"}
+ # The health lane filters from the same request rather than its own copy.
+ assert bundle.health is not None
+ assert bundle.health.scope.changed == len(bundle.manifest)
+
+
+def test_exclusions_reach_the_manifest_and_the_health_scope(make_repo):
+ repo = _two_commit_repo(make_repo)
+
+ bundle = _service(repo).review(
+ ChangeReviewRequest(revspec="HEAD", exclude_patterns=("docs/",), baseline=0)
+ )
+
+ assert {entry.path for entry in bundle.manifest} == {"app/a.py"}
+ assert bundle.health is not None
+ assert bundle.health.scope.changed == 1
+
+
+def test_a_change_with_no_counted_file_says_so(make_repo):
+ repo = _two_commit_repo(make_repo)
+
+ bundle = _service(repo).review(
+ ChangeReviewRequest(revspec="HEAD", extensions=(".rs",), baseline=0)
+ )
+
+ assert bundle.manifest == ()
+ assert bundle.lanes["manifest"].state == "unavailable"
+
+
+def test_a_deleted_path_keeps_its_base_side_in_the_manifest(make_repo):
+ repo: Repo = make_repo("deletion")
+ repo.commit("base", {"app/gone.py": python_complex("run", 2)})
+ repo.remove("app/gone.py")
+ repo.commit("head")
+
+ bundle = _service(repo).review(ChangeReviewRequest(revspec="HEAD", baseline=0))
+
+ entry = next(e for e in bundle.manifest if e.path == "app/gone.py")
+ assert entry.status == "deleted"
+ assert entry.head_path is None
+ assert entry.base_path == "app/gone.py"
+ # Nothing was added, so nothing may claim added lines for it.
+ assert entry.added_ranges == ()
+
+
+def test_added_lines_collapse_into_inclusive_spans():
+ from repowise.core.analysis.change_health import FileChange
+ from repowise.core.analysis.changed_lines import FileDiff
+
+ diff = FileDiff(path="a.py", new_lines={1, 2, 3, 7, 8, 20})
+ entry = ChangeManifestEntry.from_file_change(
+ FileChange(head_path="a.py", base_path="a.py", status="modified", diff=diff)
+ )
+
+ assert entry.added_ranges == ((1, 3), (7, 8), (20, 20))
+ assert entry.added_line_count == 6
+
+
+# ---------------------------------------------------------------------------
+# Composition
+# ---------------------------------------------------------------------------
+
+
+def test_contract_impact_reads_its_scope_from_the_manifest(make_repo):
+ """The lane must not be handed a changed-file set that can disagree."""
+ repo: Repo = make_repo("contracts")
+ repo.commit("base", {"app/a.py": "def run(value):\n return value\n"})
+ repo.commit("head", {"app/a.py": "def run(value, extra):\n return value + extra\n"})
+
+ base_parsed = [
+ {
+ "file_info": {"path": "app/a.py"},
+ "symbols": [
+ {
+ "id": "app/a.py::run",
+ "name": "run",
+ "kind": "function",
+ "signature": "run(value)",
+ "start_line": 1,
+ "end_line": 2,
+ }
+ ],
+ }
+ ]
+ head_parsed = [
+ {
+ "file_info": {"path": "app/a.py"},
+ "symbols": [
+ {
+ "id": "app/a.py::run",
+ "name": "run",
+ "kind": "function",
+ "signature": "run(value, extra)",
+ "start_line": 1,
+ "end_line": 2,
+ }
+ ],
+ }
+ ]
+ graph = {
+ "links": [
+ {"source": "other/b.py::caller", "target": "app/a.py::run", "edge_type": "calls"}
+ ]
+ }
+
+ bundle = _service(repo).review(
+ ChangeReviewRequest(revspec="HEAD", baseline=0),
+ evidence=ChangeReviewEvidence(
+ contracts=ContractInputs(graph=graph, base_parsed=base_parsed, head_parsed=head_parsed)
+ ),
+ )
+
+ assert bundle.lanes["contracts"].state == "available"
+ assert bundle.contracts is not None
+ breaking = bundle.contracts.breaking
+ assert [c.name for c in breaking] == ["run"]
+ assert breaking[0].outside_callers == ["other/b.py::caller"]
+
+
+def test_a_snapshot_base_makes_the_contract_lane_partial(make_repo):
+ repo = _two_commit_repo(make_repo)
+
+ bundle = _service(repo).review(
+ ChangeReviewRequest(revspec="HEAD", baseline=0),
+ evidence=ChangeReviewEvidence(
+ contracts=ContractInputs(
+ graph={}, base_parsed=[], head_parsed=[], base_is_snapshot=True
+ )
+ ),
+ )
+
+ assert bundle.lanes["contracts"].state == "partial"
+ assert "snapshot" in (bundle.lanes["contracts"].reason or "")
+
+
+def test_the_directive_carries_the_tests_the_test_lane_found(make_repo):
+ repo = _two_commit_repo(make_repo)
+ tests = {
+ "recommendations": [
+ {"test_id": "tests/test_a.py::test_run", "basis": "measured"},
+ {"test_id": "tests/test_b.py::test_other", "basis": "inferred"},
+ ],
+ "coverage": {"map_present": True, "status": "current"},
+ }
+
+ bundle = _service(repo).review(
+ ChangeReviewRequest(revspec="HEAD", baseline=0),
+ evidence=ChangeReviewEvidence(tests=tests),
+ )
+
+ run = [a for a in bundle.directive.actions if a.kind == "run_tests"]
+ assert len(run) == 1
+ assert run[0].targets == ("tests/test_a.py::test_run", "tests/test_b.py::test_other")
+ assert run[0].evidence_basis == "measured"
+ assert bundle.lanes["tests"].state == "available"
+
+
+def test_no_coverage_map_and_no_candidates_asks_for_coverage(make_repo):
+ repo = _two_commit_repo(make_repo)
+ tests = {"recommendations": [], "coverage": {"map_present": False, "status": "unavailable"}}
+
+ bundle = _service(repo).review(
+ ChangeReviewRequest(revspec="HEAD", baseline=0),
+ evidence=ChangeReviewEvidence(tests=tests),
+ )
+
+ assert bundle.lanes["tests"].state == "partial"
+ kinds = {a.kind for a in bundle.directive.actions}
+ assert "establish_test_coverage" in kinds
+
+
+def test_a_supplied_risk_result_is_used_rather_than_rescored(make_repo):
+ """A caller holding file stats from an API gets its own numbers back."""
+ repo = _two_commit_repo(make_repo)
+ supplied = assess_change(
+ features_from_file_changes([("app/a.py", 40, 4)], ref="supplied"),
+ )
+
+ bundle = _service(repo).review(
+ ChangeReviewRequest(revspec="HEAD", baseline=0),
+ evidence=ChangeReviewEvidence(risk=supplied),
+ )
+
+ assert bundle.risk is supplied
+ assert bundle.lanes["risk"].state == "available"
+
+
+def test_risk_without_a_checkout_or_a_result_is_unsupported(make_repo):
+ repo = _two_commit_repo(make_repo)
+ supplied = _supplied_source(repo)
+
+ bundle = ChangeReviewService(supplied).review(ChangeReviewRequest(revspec="HEAD"))
+
+ assert bundle.risk is None
+ assert bundle.lanes["risk"].state == "unsupported"
+ # The lanes that need no checkout still answer.
+ assert bundle.lanes["health"].state in {"available", "partial"}
+ assert bundle.manifest
+
+
+ "failure",
+ [
+ subprocess.CalledProcessError(128, ["git", "diff"], stderr="bad revision"),
+ subprocess.TimeoutExpired(["git", "diff"], 60),
+ ],
+ ids=["git_failed", "git_timed_out"],
+)
+def test_a_failed_score_degrades_its_lane_rather_than_the_bundle(make_repo, monkeypatch, failure):
+ """git failing inside one lane must not cost the caller every other lane."""
+ repo = _two_commit_repo(make_repo)
+ monkeypatch.setattr(
+ "repowise.core.analysis.change_review.service.score_live_change",
+ lambda *a, **k: (_ for _ in ()).throw(failure),
+ )
+
+ bundle = _service(repo).review(ChangeReviewRequest(revspec="HEAD", baseline=0))
+
+ assert bundle.risk is None
+ assert bundle.lanes["risk"].state == "degraded"
+ assert bundle.lanes["risk"].reason
+ # The fix record rides on the same walk, so it cannot claim to be available.
+ assert bundle.lanes["prior_fixes"].state == "unsupported"
+ # Everything that did not depend on that walk still answered.
+ assert bundle.manifest
+ assert bundle.lanes["health"].state in {"available", "partial"}
+
+
+def test_supplied_branch_overlap_is_carried_through(make_repo):
+ repo = _two_commit_repo(make_repo)
+ overlap = BranchOverlap(base="main", current="feature", branches=(), scanned=12, total=12)
+
+ bundle = _service(repo).review(
+ ChangeReviewRequest(revspec="HEAD", baseline=0),
+ evidence=ChangeReviewEvidence(branch_overlap=overlap),
+ )
+
+ assert bundle.branch_overlap is overlap
+ assert bundle.lanes["branch_overlap"].state == "available"
+ assert bundle.as_dict()["branch_overlap"] == overlap.to_dict()
+
+
+def test_an_absent_branch_scan_can_say_why(make_repo):
+ repo = _two_commit_repo(make_repo)
+
+ bundle = _service(repo).review(
+ ChangeReviewRequest(revspec="HEAD", baseline=0),
+ evidence=ChangeReviewEvidence(branch_overlap_reason="the remote was unreachable"),
+ )
+
+ assert bundle.lanes["branch_overlap"].state == "unsupported"
+ assert bundle.lanes["branch_overlap"].reason == "the remote was unreachable"
+
+
+def test_a_supplied_source_bundles_the_same_change_as_a_checkout(make_repo):
+ repo = _two_commit_repo(make_repo)
+ supplied = _supplied_source(repo)
+ request = ChangeReviewRequest(revspec="HEAD", baseline=0)
+
+ from_git = _service(repo).review(request)
+ from_supplied = ChangeReviewService(supplied).review(request)
+
+ assert [e.as_dict() for e in from_supplied.manifest] == [
+ e.as_dict() for e in from_git.manifest
+ ]
+ assert from_supplied.directive.status == from_git.directive.status
+ assert from_supplied.directive.fingerprint == from_git.directive.fingerprint
+
+
+# ---------------------------------------------------------------------------
+# Serialization
+# ---------------------------------------------------------------------------
+
+
+def test_the_serialized_bundle_is_versioned_and_json_safe(make_repo):
+ repo = _two_commit_repo(make_repo)
+
+ payload = _service(repo).review(ChangeReviewRequest(revspec="HEAD", baseline=0)).as_dict()
+
+ assert payload["contract_version"] == CHANGE_REVIEW_CONTRACT_VERSION
+ assert set(payload["lanes"]) == set(LANES)
+ json.dumps(payload) # raises on anything a surface could not send
+
+
+def test_serialization_keeps_every_lane_as_a_key(make_repo):
+ repo = _two_commit_repo(make_repo)
+
+ payload = _service(repo).review(ChangeReviewRequest(revspec="HEAD", baseline=0)).as_dict()
+
+ # A lane that answered nothing is still present, so a reader never has to
+ # infer the difference between "absent" and "empty" from a missing key.
+ for lane in ("risk", "health", "contracts", "tests", "branch_overlap"):
+ assert lane in payload
+
+
+def test_the_directive_serializes_its_fingerprints(make_repo):
+ repo = _two_commit_repo(make_repo)
+
+ payload = _service(repo).review(ChangeReviewRequest(revspec="HEAD", baseline=0)).as_dict()
+
+ assert payload["directive"]["fingerprint"]
+ for action in payload["directive"]["actions"]:
+ assert action["fingerprint"]
+
+
[email protected]("revspec", ["HEAD", "HEAD~1..HEAD", "HEAD~1...HEAD"])
+def test_common_revspec_spellings_all_produce_a_bundle(make_repo, revspec):
+ repo = _two_commit_repo(make_repo)
+
+ bundle = _service(repo).review(ChangeReviewRequest(revspec=revspec, baseline=0))
+
+ assert bundle.manifest
+ assert bundle.lanes["manifest"].state == "available"