Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(change-risk): lead with what the change made worse, not what the diff weighs (#1980)
Raghav Chamadiya7ddbfa636600
diff --git a/README.md b/README.mdindex 14ffe7120..497f9feac 100644--- a/README.md+++ b/README.md@@ -695,7 +695,7 @@ so your agent always knows how much to trust what it just read.| `get_symbol("file.py::Name")` | Source for one indexed symbol with exact line bounds. Cheaper and safer than `Read` plus offset math. || `search_codebase(query, kind?)` | Semantic search over the wiki, filterable by kind (implementation / test / config / doc), tagging each result's `search_method`. || `get_risk(targets, changed_files?)` | Hotspots, dependents, co-change partners, ownership, test gaps, bug history. Pass `changed_files` for PR mode and get a `directive` block back. |-| `get_change_risk(revspec)` | Pre-merge defect score for a whole commit or range from the shape of the diff, ranked as a percentile against recent commits, plus the tests coverage proves it touches. |+| `get_change_risk(revspec)` | What a commit, range or uncommitted change newly made worse across defect, maintainability and performance, why each finding is attributable to it, the tests coverage proves it touches, and how the diff's shape ranks against recent commits. || `get_why(query?, targets?)` | Architectural decisions and their verbatim evidence spans, stamped exact / fuzzy / unverified. Falls back to git archaeology when no decisions exist. || `get_dead_code(...)` | Unreachable code by confidence tier with cleanup-impact estimates, and cross-repo consumer detection in workspace mode. || `get_health(targets?, include?)` | Per-file marker scores across all three signals. `include` opens coverage, trends, per-file signals, the accuracy self-check, and structured refactoring plans. |diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex cf32e590b..1f030f6c0 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -57,7 +57,7 @@ Also see [Configuring the tool surface](#configuring-the-tool-surface), [Reversi| `get_symbol` | Raw source bytes for one symbol | When you need one function/class body || `search_codebase` | Hybrid symbol / path / concept search | Finding a symbol or file, or discovering code by topic || `get_risk` | Modification risk | Before changing hotspot files |-| `get_change_risk` | Live commit or range risk | Before merging a commit or PR range |+| `get_change_risk` | What a commit or range newly made worse | Before merging a commit or PR range || `get_why` | Architectural decisions | Before structural changes || `get_dead_code` | Unreachable code | Cleanup tasks || `get_health` | Code-health marker scores | Before refactoring, find the worst files |@@ -499,9 +499,9 @@ get_risk(targets=["src/auth/middleware.ts"], include=["graph", "churn"])## `get_change_risk`-Live risk scoring for one commit or a `base..head` range. Unlike `get_risk`,-which evaluates indexed files and can report blast radius, this scores the-shape of the live diff and needs no index refresh.+Review one commit, a `base..head` range, or uncommitted work. Unlike+`get_risk`, which evaluates indexed files and can report blast radius, this+compares the two revisions directly and needs no index refresh.**Parameters:**@@ -512,30 +512,52 @@ shape of the live diff and needs no index refresh.| `extensions` | list[string] | No | File suffixes to count, such as `[".py", ".ts"]` || `exclude_patterns` | list[string] | No | Gitignore-style paths to omit; combined with root `.riskignore` rules || `baseline` | int | No | Recent commits to sample for percentile ranking (default `200`; `0` disables every percentile, `risk_percentile` and `fix_history.percentile` alike) |--**Returns:** `risk_authority` identifies `risk_percentile` and `classification`-as the benchmarked, population-relative authority for live change review.-`fix_history` reports the recency-weighted bug-fix record of the-files the change touches, with `files` naming where the pressure sits and-`percentile` ranking it against the same measure over the repo's own recent-commits. Triage on-this: it is the part that separates a small edit to a fragile file from a large-edit to a safe one. `available` is false when the history walk could not run.--`score` is a supporting, offline-calibrated 0-10 model output that measures diff-size and spread, not a probability and not where the change lands — see-`score_measures` — and `score_unit` names the unit it is calibrated on (a single-commit, so a PR-sized range reads high by construction). `risk_percentile`,-`review_priority` and `classification` rank that same diff shape against recent-commits. `fallback_band` carries the absolute band and appears only when no-baseline was available. `working_tree` says whether uncommitted work was the-subject. `baseline_sample_size` reports how many filtered commits informed the-percentile; `features`, `drivers`, and combined `exclude_patterns` make the-result auditable. `risk_authority` always names the field to act on;-`include=["scales"]` adds each field's kind, unit, range, calibration,-authority, and shared thresholds. When a baseline is unavailable,-`fallback_band` is the absolute per-commit classification; it is distinct from-population-relative percentile behavior.+| `include` | list[string] | No | `"findings"` for every change finding, `"diagnostics"` for the raw score mechanics, `"scales"` for units and calibration |+| `finding_id` | string | No | Expand one `health_delta` finding by its id |++**Returns:** `directive` leads with a `status`+(`review_required`, `review_recommended`, `clear_in_analyzed_scope`, `unknown`),+a headline, bounded reasons, and concrete next actions.++`health_delta` is what the change newly made worse, across defect,+maintainability and performance. Both revisions are analysed from their own+content, so a finding present at head is reported only when the diff explains+it. `scope` counts changed, eligible, analysed, skipped and failed files, and+`status` distinguishes `available` from `partial` and `unavailable` — a+`partial` comparison is never a clean bill, and `skipped` says why each file+was left out. `introduced`, `worsened` and `resolved` are totals;+`top_findings` carries the three most actionable, with `findings_total` and a+recovery call for the rest.++Each finding names its `dimension`, `biomarker`, `severity`, `path`, `symbol`+and head-side `lines`, a `reason`, and an `attribution` — `basis`+(`added_lines`, `changed_symbol`, `changed_call_edge`, `new_file`,+`file_change`, `context_change`, `unknown`) with a `confidence`. Identity+ignores line numbers, so moving code introduces nothing and a rename carries+its findings across. Performance findings carry `opportunity_id` and+`opportunity_rank` and are ordered by opportunity rank and actionability, never+by defect impact, which is zero for them by construction. `inspect` gives the+exact `finding_id` call that expands one; ids are bound to the two revisions+that produced them. A finding that exactly matches a stored one also carries a+`health_reference` for `get_health(finding_id=...)`.++`fix_history` reports the recency-weighted bug-fix record of the files the+change touches, with `files` naming where the pressure sits and `percentile`+ranking it against the same measure over the repo's own recent commits. It is+the part that separates a small edit to a fragile file from a large edit to a+safe one. `available` is false when the history walk could not run.++`change_shape` carries the supporting diff-shape reading: `score`,+`risk_percentile`, `review_priority`, `classification`, `fallback_band` and+`is_fix`, which also stay at the top level. `score` is an offline-calibrated+0-10 output measuring diff size and spread — not a probability, and not where+the change lands. `fallback_band` appears only when no baseline was available.+`working_tree` says whether uncommitted work was the subject.++`include=["diagnostics"]` adds the raw mechanics: `risk_authority`,+`score_measures`, `score_unit`, `baseline_sample_size`, `features` and+`drivers`. `include=["scales"]` adds each field's kind, unit, range,+calibration and thresholds. Both are identical on every call, so ask once.It also returns `impacted_tests`, whose `tests_to_run` names the tests theper-test coverage map proves execute the change's changed *lines* (line-precise,@@ -590,13 +612,15 @@ not enough to accuse one commit of causing them. The block is absent entirelyon an index with no fix history.**When to use:** Before merging a commit or PR range, especially when you need-to assess the diff itself rather than the risk of an already-indexed file.+to assess the change itself rather than the risk of an already-indexed file.**Example calls:**```get_change_risk()get_change_risk(revspec="main..HEAD", extensions=[".py"], exclude_patterns=["tests/"])+get_change_risk(revspec="main..HEAD", include=["findings"])+get_change_risk(revspec="main..HEAD", finding_id="chf_27a13be11e7ee33f")```---diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.mdindex 2dadddf6b..9edcbd8bf 100644--- a/docs/architecture/ARCHITECTURE.md+++ b/docs/architecture/ARCHITECTURE.md@@ -1097,7 +1097,7 @@ Workspace mode adds `list_repos`. Six specialists are registered but opt-in:| `get_symbol` | Resolve a qualified symbol id to source body, signature, and docstring. | When the question names a specific class, function, or method. || `search_codebase(query)` | Hybrid symbol / path / wiki search. | When you don't know where something lives. || `get_risk(targets)` | Hotspot score, dependents, co-change partners, risk summary per target. | Before modifying indexed files. |-| `get_change_risk(revspec?)` | Live commit / range defect score from the diff itself. | Before merging a commit or PR range. |+| `get_change_risk(revspec?)` | What a commit, range or uncommitted change newly made worse, with attribution. | Before merging a commit or PR range. || `get_why(query?)` | Architectural decisions and git archaeology. | Before making architectural changes. || `get_dead_code` | Dead/unused code findings sorted by confidence. | Before cleanup tasks. || `get_health` | Code-health marker scores (defect / maintainability / performance). | Self-check before a PR or refactor. |diff --git a/docs/layers/CHANGE_RISK.md b/docs/layers/CHANGE_RISK.mdindex 305607ce6..2e3c47ca4 100644--- a/docs/layers/CHANGE_RISK.md+++ b/docs/layers/CHANGE_RISK.md@@ -11,6 +11,11 @@ complementary evidence about where the change lands. The supporting 0–10 scoremeasures how big and spread out a change is; it is not a probability. See[What the score does and does not buy](#what-the-score-does-and-does-not-buy).+Everything below describes diff shape, which is what `repowise risk` reports.+The `get_change_risk` MCP tool leads instead with what the change newly made+worse — it compares the health of both revisions and keeps diff shape as+supporting context. See [MCP tools](../agent/MCP_TOOLS.md#get_change_risk).+```bashrepowise risk # score uncommitted work, else HEADrepowise risk HEAD # score the last commit@@ -315,8 +320,9 @@ CLI `--json` output and this table carry it unconditionally.## Cross-repo change risk (workspace mode)-> **Note:** This section describes `get_risk` in PR mode (`changed_files`). `get_change_risk` is-> pure diff-shape scoring and does not access the workspace graph — it produces no cross-repo fields.+> **Note:** This section describes `get_risk` in PR mode (`changed_files`).+> `get_change_risk` carries its own `cross_repo` block, built from workspace+> contracts rather than from the graph traversal described here.In a workspace, a change rarely stops at the repo boundary. When `get_risk` iscalled in PR mode (`changed_files`), its `directive` block gains two cross-repodiff --git a/docs/start/QUICKSTART.md b/docs/start/QUICKSTART.mdindex fff2e3452..0df5832dc 100644--- a/docs/start/QUICKSTART.md+++ b/docs/start/QUICKSTART.md@@ -220,7 +220,7 @@ too, so the same index serves you and your agent. See [VS Code](../agent/VSCODE.> *"What's the blast radius if I change `src/auth.py`? Use `get_context` with> `include: ["callers"]`."*>-> *"Score my branch with `get_change_risk` for `main..HEAD`."*+> *"Review my branch with `get_change_risk` for `main..HEAD`."*You should get a graph-grounded answer immediately, instead of a run of greps andfile reads. That is the whole point.diff --git a/packages/core/src/repowise/core/analysis/change_health/__init__.py b/packages/core/src/repowise/core/analysis/change_health/__init__.pynew file mode 100644index 000000000..41f07bd40--- /dev/null+++ b/packages/core/src/repowise/core/analysis/change_health/__init__.py@@ -0,0 +1,62 @@+"""Base-versus-head code-health comparison.++Answers "what did this change newly make worse", for a commit, a range, or the+uncommitted tree. Both sides are analysed from their own content through a+:class:`RevisionSource`, so nothing here assumes a local checkout and a hosted+adapter can be added without touching matching or attribution.++The pipeline, in order::++ RevisionSource -> RevisionHealthAnalyzer -> FindingMatcher+ -> FindingAttributor -> ChangeHealthDeltaService+"""++from __future__ import annotations++from .analyzer import RevisionAnalysis, RevisionHealthAnalyzer+from .attribution import Attribution, FindingAttributor+from .identity import change_finding_id, finding_key+from .matcher import FindingMatcher, MatchedFinding, MatchResult+from .models import (+ AnalysisFingerprint,+ AttributionBasis,+ ChangeFinding,+ ChangeHealthDelta,+ ChangeKind,+ DeltaStatus,+ FindingKey,+ RevisionId,+ ScopeCounts,+)+from .perf_delta import PerfOpportunityView, opportunities_for+from .service import ChangeHealthDeltaService, DeltaRequest+from .sources import FileChange, GitRevisionSource, RevisionPair, RevisionSource++__all__ = [+ "AnalysisFingerprint",+ "Attribution",+ "AttributionBasis",+ "ChangeFinding",+ "ChangeHealthDelta",+ "ChangeHealthDeltaService",+ "ChangeKind",+ "DeltaRequest",+ "DeltaStatus",+ "FileChange",+ "FindingAttributor",+ "FindingKey",+ "FindingMatcher",+ "GitRevisionSource",+ "MatchResult",+ "MatchedFinding",+ "PerfOpportunityView",+ "RevisionAnalysis",+ "RevisionHealthAnalyzer",+ "RevisionId",+ "RevisionPair",+ "RevisionSource",+ "ScopeCounts",+ "change_finding_id",+ "finding_key",+ "opportunities_for",+]diff --git a/packages/core/src/repowise/core/analysis/change_health/analyzer.py b/packages/core/src/repowise/core/analysis/change_health/analyzer.pynew file mode 100644index 000000000..653a2264f--- /dev/null+++ b/packages/core/src/repowise/core/analysis/change_health/analyzer.py@@ -0,0 +1,162 @@+"""Run the health pass over one revision's content, in memory.++Both sides of a comparison go through this class with the same analyzer+version, the same rules, and the same file universe, so a difference in the+findings is a difference in the code rather than in how it was analysed.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from datetime import UTC, datetime+from pathlib import PurePosixPath++from ...ingestion.graph.builder import GraphBuilder+from ...ingestion.models import EXTENSION_TO_LANGUAGE, SPECIAL_FILENAMES, FileInfo, ParsedFile+from ...ingestion.parser import parse_file+from ...test_paths import is_test_related_path+from ..health import HealthAnalyzer, HealthFindingData+from ..health.complexity.languages import get_language_map+from ..health.source_reader import MappingSourceReader++#: Files above this size are skipped rather than parsed on both sides.+MAX_FILE_BYTES = 1_500_000++_GENERATED_MARKERS = (b"GENERATED CODE", b"AUTO-GENERATED", b"@generated", b"DO NOT EDIT")+++def language_of(path: str) -> str | None:+ """The language *path* is written in, whether or not health can read it."""+ name = PurePosixPath(path).name+ if name in SPECIAL_FILENAMES:+ return SPECIAL_FILENAMES[name]+ return EXTENSION_TO_LANGUAGE.get(PurePosixPath(path).suffix)+++def language_for(path: str) -> str | None:+ """The language the health pass can actually analyse, else ``None``.++ Recognising a language is not the same as being able to score it: Markdown+ and JSON parse fine and produce no findings, so counting them as analysed+ would let a docs-only change read as a clean bill of health.+ """+ language = language_of(path)+ if language is None:+ return None+ if language == "sql": # walked by the sqlglot path, not a node map+ return language+ return language if get_language_map(language) is not None else None+++def is_generated(source: bytes) -> bool:+ """True when the file announces itself as generated in its header."""+ header = source[:512].upper()+ return any(marker.upper() in header for marker in _GENERATED_MARKERS)+++def is_binary(source: bytes) -> bool:+ return b"\0" in source[:8192]+++@dataclass(slots=True)+class RevisionAnalysis:+ """One side's findings plus what it could not look at."""++ findings: list[HealthFindingData] = field(default_factory=list)+ analyzed: set[str] = field(default_factory=set)+ skipped: dict[str, str] = field(default_factory=dict)++ def findings_for(self, paths: set[str]) -> list[HealthFindingData]:+ return [f for f in self.findings if f.file_path in paths]+++class RevisionHealthAnalyzer:+ """Analyze a set of paths at one revision from supplied bytes alone."""++ def __init__(self, *, repo_root: str | None = None, config: dict | None = None) -> None:+ self.repo_root = repo_root+ self.config = config++ def analyze(self, sources: dict[str, bytes], *, subject_paths: set[str]) -> RevisionAnalysis:+ """Analyze *sources*, reporting findings for the whole supplied set.++ *subject_paths* names the files the caller actually cares about; the+ remainder are closure context that shapes resolution without being+ charged to the change.+ """+ result = RevisionAnalysis()+ parsed, usable = self._parse(sources, result)+ if not parsed:+ return result+ analyzer = HealthAnalyzer(+ self._graph(parsed, usable),+ parsed_files=parsed,+ repo_root=self.repo_root,+ source_reader=MappingSourceReader(usable),+ )+ report = analyzer.analyze(config=self.config, changed_files=set(usable))+ result.findings = list(report.findings)+ result.analyzed = set(usable)+ return result++ # -- internals ----------------------------------------------------------++ def _parse(+ self, sources: dict[str, bytes], result: RevisionAnalysis+ ) -> tuple[list[ParsedFile], dict[str, bytes]]:+ parsed: list[ParsedFile] = []+ usable: dict[str, bytes] = {}+ for path, raw in sorted(sources.items()):+ reason = self._reject(path, raw)+ if reason is not None:+ result.skipped[path] = reason+ continue+ language = language_for(path)+ assert language is not None # _reject already screened this+ try:+ parsed.append(parse_file(_file_info(path, language, raw), raw))+ except Exception:+ result.skipped[path] = "parse_failed"+ continue+ usable[path] = raw+ return parsed, usable++ @staticmethod+ def _reject(path: str, raw: bytes) -> str | None:+ if language_for(path) is None:+ return "unsupported_language"+ if len(raw) > MAX_FILE_BYTES:+ return "too_large"+ if is_binary(raw):+ return "binary"+ if is_generated(raw):+ return "generated"+ return None++ @staticmethod+ def _graph(parsed: list[ParsedFile], sources: dict[str, bytes]):+ builder = GraphBuilder()+ for pf in parsed:+ builder.add_file(pf)+ builder.set_source_map(dict(sources))+ return builder.build()+++def _file_info(path: str, language: str, raw: bytes) -> FileInfo:+ """A FileInfo whose ``abs_path`` is the repo-relative key.++ The health pass reads every byte through the injected source reader, which+ is keyed the same way, so no absolute path is ever resolved against disk.+ """+ return FileInfo(+ path=path,+ abs_path=path,+ language=language, # type: ignore[arg-type]+ size_bytes=len(raw),+ git_hash="",+ last_modified=datetime.now(UTC),+ is_test=is_test_related_path(path, language),+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )diff --git a/packages/core/src/repowise/core/analysis/change_health/attribution.py b/packages/core/src/repowise/core/analysis/change_health/attribution.pynew file mode 100644index 000000000..076b2ad97--- /dev/null+++ b/packages/core/src/repowise/core/analysis/change_health/attribution.py@@ -0,0 +1,106 @@+"""Why a finding is charged to this change, and how sure that is.++Presence at head is never on its own a reason. Every surfaced finding carries+the basis that ties it to the diff, and a finding the diff cannot explain is+reported as such rather than quietly counted as new.+"""++from __future__ import annotations++from dataclasses import dataclass++from ..health import HealthFindingData+from .models import ATTRIBUTION_CONFIDENCE, AttributionBasis+from .sources import FileChange+++@dataclass(frozen=True, slots=True)+class Attribution:+ basis: AttributionBasis+ confidence: str+ detail: str+++_UNKNOWN = Attribution(+ "unknown",+ ATTRIBUTION_CONFIDENCE["unknown"],+ "Present at head, but the diff does not explain it.",+)+++def _overlaps(finding: HealthFindingData, added: set[int]) -> bool:+ start, end = finding.line_start, finding.line_end+ if start is None:+ return False+ return any(line in added for line in range(start, (end or start) + 1))+++class FindingAttributor:+ """Decide the strongest basis tying a head finding to the change."""++ def __init__(self, changes: dict[str, FileChange]) -> None:+ self.changes = changes++ def attribute(+ self,+ finding: HealthFindingData,+ *,+ changed_symbols: set[tuple[str, str]] | None = None,+ changed_call_edge: str | None = None,+ ) -> Attribution:+ change = self.changes.get(finding.file_path)+ if change is None:+ return _UNKNOWN+ if change.is_new:+ return Attribution(+ "new_file",+ ATTRIBUTION_CONFIDENCE["new_file"],+ f"{finding.file_path} is added by this change.",+ )+ added = change.added_lines+ if _overlaps(finding, added):+ return Attribution(+ "added_lines",+ ATTRIBUTION_CONFIDENCE["added_lines"],+ f"Lines {finding.line_start}-{finding.line_end or finding.line_start} "+ "are added or rewritten by this change.",+ )+ symbol = finding.function_name+ if symbol and changed_symbols and (finding.file_path, symbol) in changed_symbols:+ return Attribution(+ "changed_symbol",+ ATTRIBUTION_CONFIDENCE["changed_symbol"],+ f"{symbol} is edited by this change.",+ )+ if changed_call_edge:+ return Attribution(+ "changed_call_edge",+ ATTRIBUTION_CONFIDENCE["changed_call_edge"],+ f"Reached through {changed_call_edge}, whose call path this change edits.",+ )+ if added:+ return Attribution(+ "file_change",+ ATTRIBUTION_CONFIDENCE["file_change"],+ f"{finding.file_path} is edited by this change, away from these lines.",+ )+ return Attribution(+ "context_change",+ ATTRIBUTION_CONFIDENCE["context_change"],+ f"{finding.file_path} changed only in ways the diff does not localise.",+ )+++def changed_symbols_for(+ changes: dict[str, FileChange], findings_by_file: dict[str, list[HealthFindingData]]+) -> set[tuple[str, str]]:+ """``(path, symbol)`` pairs whose body overlaps the change's added lines."""+ out: set[tuple[str, str]] = set()+ for path, change in changes.items():+ added = change.added_lines+ if not added:+ continue+ for finding in findings_by_file.get(path, ()):+ if finding.function_name and _overlaps(finding, added):+ out.add((path, finding.function_name))+ return outdiff --git a/packages/core/src/repowise/core/analysis/change_health/identity.py b/packages/core/src/repowise/core/analysis/change_health/identity.pynew file mode 100644index 000000000..1347d9c3a--- /dev/null+++ b/packages/core/src/repowise/core/analysis/change_health/identity.py@@ -0,0 +1,70 @@+"""Semantic identity for findings, stable across line movement and renames."""++from __future__ import annotations++import hashlib+from typing import Any++from ..health import HealthFindingData+from .models import SEVERITY_RANK, FindingKey++_ID_PREFIX = "chf_"++#: Bumped when the identity inputs change, so ids from two versions of this+#: module are never mistaken for one another.+IDENTITY_VERSION = 1+++def severity_rank(severity: Any) -> int:+ return SEVERITY_RANK.get(str(severity).lower(), 0)+++def finding_key(finding: HealthFindingData, *, path: str | None = None) -> FindingKey:+ """The identity of *finding*, optionally under a rename-normalized *path*.++ Line numbers are deliberately absent: a finding that moves with its symbol+ is the same finding. Where a detector reports no owning symbol the file is+ the anchor, which is the honest granularity for a file-level marker.+ """+ return FindingKey(+ dimension=str(finding.dimension),+ biomarker_type=str(finding.biomarker_type),+ path=path or finding.file_path,+ symbol=finding.function_name or None,+ )+++def change_finding_id(key: FindingKey, ordinal: int, *, comparison: str = "") -> str:+ """A deterministic, ephemeral id for one surfaced change finding.++ Deterministic so the same comparison always names a finding the same way+ and an agent can drill straight back into it; ephemeral because the finding+ may exist in no persisted health run at all.++ *comparison* binds the id to the two revisions it came from, so an id+ carried to a different revspec fails to resolve rather than silently+ matching a same-shaped finding from an unrelated diff.+ """+ payload = "\x00".join(+ [+ str(IDENTITY_VERSION),+ comparison,+ *(str(part) for part in key.as_tuple()),+ str(ordinal),+ ]+ )+ digest = hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]+ return f"{_ID_PREFIX}{digest}"+++def normalize_path(path: str, rename_map: dict[str, str]) -> str:+ """Map a base-side path onto its head-side name when the file moved."""+ return rename_map.get(path, path)+++def line_distance(left: HealthFindingData, right: HealthFindingData) -> int:+ """Proximity tie-breaker for two findings that share an identity."""+ a, b = left.line_start, right.line_start+ if a is None or b is None:+ return 0+ return abs(a - b)diff --git a/packages/core/src/repowise/core/analysis/change_health/matcher.py b/packages/core/src/repowise/core/analysis/change_health/matcher.pynew file mode 100644index 000000000..624996a14--- /dev/null+++ b/packages/core/src/repowise/core/analysis/change_health/matcher.py@@ -0,0 +1,125 @@+"""Pair base-side and head-side findings, and say what changed between them."""++from __future__ import annotations++from dataclasses import dataclass, field++from ..health import HealthFindingData+from .identity import finding_key, line_distance, normalize_path, severity_rank+from .models import ChangeKind, FindingKey++#: Health-impact movement below this is rounding, not a regression.+_IMPACT_EPSILON = 0.01+++@dataclass(slots=True)+class MatchedFinding:+ """One head finding and the base finding it corresponds to, if any."""++ head: HealthFindingData+ base: HealthFindingData | None+ key: FindingKey+ ordinal: int+ kind: ChangeKind++ @property+ def severity_before(self) -> str | None:+ return str(self.base.severity) if self.base is not None else None+++@dataclass(slots=True)+class MatchResult:+ matched: list[MatchedFinding] = field(default_factory=list)+ resolved: list[HealthFindingData] = field(default_factory=list)++ @property+ def unchanged_total(self) -> int:+ return sum(1 for m in self.matched if m.kind == "unchanged")++ def of_kind(self, *kinds: ChangeKind) -> list[MatchedFinding]:+ return [m for m in self.matched if m.kind in kinds]+++class FindingMatcher:+ """Match two finding sets by tolerant identity, then classify each pair.++ Pairing is per identity group: findings sharing a key are zipped by line+ proximity so a marker that fires twice in one symbol keeps a stable+ correspondence, and a same-marker replacement reads as one unchanged+ finding rather than one introduced plus one resolved.+ """++ def __init__(self, rename_map: dict[str, str] | None = None) -> None:+ self.rename_map = rename_map or {}++ def match(self, base: list[HealthFindingData], head: list[HealthFindingData]) -> MatchResult:+ base_groups = self._group(base, normalize=True)+ head_groups = self._group(head, normalize=False)+ result = MatchResult()+ for key, head_items in head_groups.items():+ base_items = base_groups.pop(key, [])+ matched, unmatched = self._pair(key, base_items, head_items)+ result.matched.extend(matched)+ # Base findings this group could not account for are gone from head.+ result.resolved.extend(unmatched)+ for leftovers in base_groups.values():+ result.resolved.extend(leftovers)+ return result++ # -- internals ----------------------------------------------------------++ def _group(+ self, findings: list[HealthFindingData], *, normalize: bool+ ) -> dict[FindingKey, list[HealthFindingData]]:+ groups: dict[FindingKey, list[HealthFindingData]] = {}+ for finding in findings:+ path = (+ normalize_path(finding.file_path, self.rename_map)+ if normalize+ else finding.file_path+ )+ groups.setdefault(finding_key(finding, path=path), []).append(finding)+ for items in groups.values():+ items.sort(key=lambda f: (f.line_start or 0, f.line_end or 0))+ return groups++ def _pair(+ self, key: FindingKey, base: list[HealthFindingData], head: list[HealthFindingData]+ ) -> tuple[list[MatchedFinding], list[HealthFindingData]]:+ """Pair the group's findings closest-first, and report what is left over.++ Closest-first over all candidate pairs, not first-come-first-served:+ letting the earliest head finding claim the only base peer lets an+ unrelated new finding absorb a moved one, which both hides the new+ finding and reports the moved one as introduced.+ """+ candidates = sorted(+ (line_distance(b, h), hi, bi)+ for hi, h in enumerate(head)+ for bi, b in enumerate(base)+ )+ peers: dict[int, HealthFindingData] = {}+ taken: set[int] = set()+ for _distance, head_index, base_index in candidates:+ if head_index in peers or base_index in taken:+ continue+ peers[head_index] = base[base_index]+ taken.add(base_index)+ matched = [+ MatchedFinding(item, peers.get(ordinal), key, ordinal, _classify(peers.get(ordinal), item))+ for ordinal, item in enumerate(head)+ ]+ return matched, [b for i, b in enumerate(base) if i not in taken]+++def _classify(base: HealthFindingData | None, head: HealthFindingData) -> ChangeKind:+ """Introduced when nothing matched; worsened only on a real regression."""+ if base is None:+ return "introduced"+ if severity_rank(head.severity) > severity_rank(base.severity):+ return "worsened"+ if severity_rank(head.severity) < severity_rank(base.severity):+ return "unchanged"+ if (head.health_impact or 0.0) - (base.health_impact or 0.0) > _IMPACT_EPSILON:+ return "worsened"+ return "unchanged"diff --git a/packages/core/src/repowise/core/analysis/change_health/models.py b/packages/core/src/repowise/core/analysis/change_health/models.pynew file mode 100644index 000000000..a350c790a--- /dev/null+++ b/packages/core/src/repowise/core/analysis/change_health/models.py@@ -0,0 +1,187 @@+"""Typed vocabulary for a base-versus-head health comparison."""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any, Literal++DeltaStatus = Literal[+ "available",+ "partial",+ "unavailable",+ "unsupported_range",+ "too_large",+ "timeout",+ "analyzer_mismatch",+ "rules_mismatch",+ "stale_baseline",+]++ChangeKind = Literal["introduced", "worsened", "unchanged", "resolved", "uncertain"]++#: How a head-side finding is tied to the change. Ordered most to least direct;+#: ``unknown`` never claims the change caused the finding.+AttributionBasis = Literal[+ "added_lines",+ "changed_symbol",+ "changed_call_edge",+ "new_file",+ "file_change",+ "context_change",+ "unknown",+]++ATTRIBUTION_CONFIDENCE: dict[str, str] = {+ "added_lines": "high",+ "changed_symbol": "high",+ "new_file": "high",+ "changed_call_edge": "medium",+ "file_change": "medium",+ "context_change": "low",+ "unknown": "low",+}++SEVERITY_RANK: dict[str, int] = {"low": 0, "medium": 1, "high": 2, "critical": 3}++#: Why a changed file produced no comparison. Kept per file so a partial run+#: can never render as a clean one.+SkipReason = Literal[+ "unsupported_language",+ "generated",+ "binary",+ "excluded",+ "deleted",+ "unreadable",+ "parse_failed",+ "too_large",+]+++@dataclass(frozen=True, slots=True)+class RevisionId:+ """What was actually analysed on one side of the comparison."""++ ref: str+ sha: str+ kind: Literal["commit", "working_tree"]++ def as_dict(self) -> dict[str, Any]:+ return {"ref": self.ref, "sha": self.sha, "kind": self.kind}+++@dataclass(frozen=True, slots=True)+class AnalysisFingerprint:+ """Identity both sides must share for a comparison to mean anything."""++ analyzer_version: int+ rules_fingerprint: str+ performance_model_version: int++ def as_dict(self) -> dict[str, Any]:+ return {+ "analyzer_version": self.analyzer_version,+ "rules_fingerprint": self.rules_fingerprint,+ "performance_model_version": self.performance_model_version,+ }+++@dataclass(frozen=True, slots=True)+class FindingKey:+ """Tolerant semantic identity for one finding.++ Deliberately free of line numbers and storage ids: a finding that moves+ with its symbol is the same finding. Multiplicity within one key is+ resolved by line proximity at match time, never by identity.+ """++ dimension: str+ biomarker_type: str+ path: str+ symbol: str | None++ def as_tuple(self) -> tuple[str, str, str, str | None]:+ return (self.dimension, self.biomarker_type, self.path, self.symbol)+++@dataclass(slots=True)+class ChangeFinding:+ """One finding the change introduced or worsened, and why it is charged here."""++ change_finding_id: str+ change_kind: ChangeKind+ dimension: str+ biomarker_type: str+ severity: str+ path: str+ symbol: str | None+ line_start: int | None+ line_end: int | None+ reason: str+ attribution_basis: AttributionBasis+ attribution_confidence: str+ attribution_detail: str+ suggestion: str+ follow_up: str+ severity_before: str | None = None+ health_impact: float = 0.0+ #: Performance only: the causal opportunity this finding belongs to.+ opportunity_id: str | None = None+ opportunity_rank: int | None = None+ #: Canonical typed reference, only when the head finding exists in storage.+ health_reference: dict[str, Any] | None = None+ evidence: dict[str, Any] = field(default_factory=dict)+++@dataclass(slots=True)+class ScopeCounts:+ """How much of the change the comparison actually covered."""++ changed: int = 0+ eligible: int = 0+ analyzed: int = 0+ skipped: int = 0+ failed: int = 0++ def as_dict(self) -> dict[str, int]:+ return {+ "changed": self.changed,+ "eligible": self.eligible,+ "analyzed": self.analyzed,+ "skipped": self.skipped,+ "failed": self.failed,+ }+++@dataclass(slots=True)+class ChangeHealthDelta:+ """The full comparison result, before any response-shaping."""++ status: DeltaStatus+ explanation: str+ base: RevisionId | None+ head: RevisionId | None+ comparison_basis: str+ fingerprint: AnalysisFingerprint | None+ scope: ScopeCounts = field(default_factory=ScopeCounts)+ findings: list[ChangeFinding] = field(default_factory=list)+ resolved_total: int = 0+ unchanged_total: int = 0+ uncertain_total: int = 0+ #: ``{path: reason}``; a non-empty map means the run was partial.+ skipped: dict[str, str] = field(default_factory=dict)+ timing_ms: float = 0.0+ cache_hit: bool = False+ limits: list[str] = field(default_factory=list)++ @property+ def introduced_total(self) -> int:+ return sum(1 for f in self.findings if f.change_kind == "introduced")++ @property+ def worsened_total(self) -> int:+ return sum(1 for f in self.findings if f.change_kind == "worsened")++ @property+ def is_clean(self) -> bool:+ """True only when a valid comparison surfaced nothing new."""+ return self.status == "available" and not self.findingsdiff --git a/packages/core/src/repowise/core/analysis/change_health/perf_delta.py b/packages/core/src/repowise/core/analysis/change_health/perf_delta.pynew file mode 100644index 000000000..a0a048276--- /dev/null+++ b/packages/core/src/repowise/core/analysis/change_health/perf_delta.py@@ -0,0 +1,99 @@+"""Group changed performance findings into the causal opportunities they belong to.++Performance is never ranked by defect ``health_impact`` — a performance finding+carries none by construction. Ranking reuses the opportunity layer's own order:+actionable work first, then rank score, then reach.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any++from ..health import HealthFindingData+from ..health.perf.opportunities import build_performance_opportunities+from ..health.perf.opportunity_rank import rank_sort_key++#: Supporting evidence rows kept per surfaced opportunity.+EVIDENCE_CAP = 3+++@dataclass(slots=True)+class PerfOpportunityView:+ """One causal opportunity, reduced to what a change review needs."""++ opportunity_id: str+ rank_score: int+ actionability_state: str+ actionability_reason: str+ intervention_symbol: str | None+ terminal_sink: str | None+ boundary_kind: str | None+ execution_context: str+ amplification: str+ exposure: str+ affected_call_sites_total: int+ observations_total: int+ evidence: list[dict[str, Any]]++ @property+ def is_cross_function(self) -> bool:+ return self.intervention_symbol is not None++ def summary(self) -> str:+ if self.is_cross_function:+ return (+ f"{self.intervention_symbol} repeats {self.terminal_sink or 'a sink'} "+ f"across {self.affected_call_sites_total} call site(s)"+ )+ return f"{self.boundary_kind or 'work'} repeated in {self.execution_context} code"+++def opportunities_for(findings: list[HealthFindingData]) -> list[PerfOpportunityView]:+ """Build and rank the opportunities covering *findings*."""+ rows = [f for f in findings if f.dimension == "performance"]+ if not rows:+ return []+ built = build_performance_opportunities(rows, evidence_limit=max(len(rows), EVIDENCE_CAP))+ return [_view(o) for o in sorted(built, key=rank_sort_key)]+++def index_by_finding(+ views: list[PerfOpportunityView], findings: list[HealthFindingData]+) -> dict[int, PerfOpportunityView]:+ """Map ``id(finding)`` to the opportunity whose evidence names it.++ Identity by object rather than by value: two findings can share a file,+ symbol, and marker, and only their position tells them apart.+ """+ by_location: dict[tuple[str, int | None], PerfOpportunityView] = {}+ for view in views:+ for row in view.evidence:+ key = (str(row.get("file_path", "")), row.get("line_start"))+ by_location.setdefault(key, view)+ out: dict[int, PerfOpportunityView] = {}+ for finding in findings:+ view = by_location.get((finding.file_path, finding.line_start))+ if view is not None:+ out[id(finding)] = view+ return out+++def _view(opportunity: Any) -> PerfOpportunityView:+ facets = dict(getattr(opportunity, "facets", {}) or {})+ evidence = [dict(row) for row in (getattr(opportunity, "evidence", ()) or ())]+ return PerfOpportunityView(+ opportunity_id=opportunity.opportunity_id,+ rank_score=opportunity.rank_score,+ actionability_state=opportunity.actionability_state,+ actionability_reason=opportunity.actionability_reason,+ intervention_symbol=opportunity.intervention_symbol,+ terminal_sink=opportunity.terminal_sink,+ boundary_kind=opportunity.boundary_kind,+ execution_context=str(opportunity.execution_context),+ amplification=facets.get("amplification", "unknown"),+ exposure=facets.get("exposure", "unknown"),+ affected_call_sites_total=opportunity.affected_call_sites_total,+ observations_total=opportunity.observations_total,+ evidence=evidence[:EVIDENCE_CAP],+ )diff --git a/packages/core/src/repowise/core/analysis/change_health/service.py b/packages/core/src/repowise/core/analysis/change_health/service.pynew file mode 100644index 000000000..9380546b3--- /dev/null+++ b/packages/core/src/repowise/core/analysis/change_health/service.py@@ -0,0 +1,460 @@+"""Orchestrate a base-versus-head health comparison.++The one entry point every surface calls. It owns the order of the work, the+honesty of the status, and the cache; it owns none of the analysis, matching,+or attribution policy, which live in the neighbouring modules.+"""++from __future__ import annotations++import hashlib+import threading+import time+from collections import OrderedDict+from dataclasses import dataclass++from ..health import HEALTH_ANALYZER_VERSION, HealthFindingData+from ..health.perf.causal import PERFORMANCE_MODEL_VERSION+from .analyzer import 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 .models import (+ AnalysisFingerprint,+ ChangeFinding,+ ChangeHealthDelta,+ RevisionId,+ ScopeCounts,+)+from .perf_delta import PerfOpportunityView, index_by_finding, opportunities_for+from .sources import FileChange, GitRevisionSource, RevisionPair, RevisionSource++#: Changed files above this count are refused rather than analysed twice.+MAX_CHANGED_FILES = 300++#: Comparisons kept in the process cache.+_CACHE_CAPACITY = 32++#: How long a caller waits on an identical in-flight comparison before doing+#: the work itself. Short enough not to hold a pool thread for minutes.+_WAIT_TIMEOUT_SECONDS = 30++#: Wait-then-retry rounds before a caller stops queueing and computes.+_CLAIM_ATTEMPTS = 2++_DIMENSION_ORDER = {"defect": 0, "maintainability": 1, "performance": 2}+++@dataclass(frozen=True, slots=True)+class DeltaRequest:+ repo_path: str+ revspec: str | None+ extensions: tuple[str, ...] = ()+ exclude_patterns: tuple[str, ...] = ()+++class ChangeHealthDeltaService:+ """Compare the health of two revisions of the same repository."""++ def __init__(+ self,+ source: RevisionSource | None = None,+ *,+ repo_path: str | None = None,+ analyzer: RevisionHealthAnalyzer | None = None,+ rules_fingerprint: str = "",+ ) -> None:+ if source is None:+ if repo_path is None:+ raise ValueError("a RevisionSource or a repo_path is required")+ source = GitRevisionSource(repo_path)+ self.source = source+ self.repo_path = repo_path+ self.analyzer = analyzer or RevisionHealthAnalyzer()+ self.rules_fingerprint = rules_fingerprint+ self._cache: OrderedDict[str, ChangeHealthDelta] = OrderedDict()+ self._lock = threading.Lock()+ self._inflight: dict[str, threading.Event] = {}++ @property+ def fingerprint(self) -> AnalysisFingerprint:+ return AnalysisFingerprint(+ analyzer_version=HEALTH_ANALYZER_VERSION,+ rules_fingerprint=self.rules_fingerprint,+ performance_model_version=PERFORMANCE_MODEL_VERSION,+ )++ # -- entry point --------------------------------------------------------++ def compare(self, request: DeltaRequest) -> ChangeHealthDelta:+ """Compare *request*, serving an identical in-flight call one result.++ The revision is resolved once and threaded through, so neither the+ cache key nor a cache hit re-reads the change shape from the source.+ """+ try:+ pair = self.source.resolve(request.revspec)+ except ValueError as exc:+ return _unavailable("unsupported_range", str(exc))+ key = self._cache_key(request, pair)+ # One wait, then one retry at becoming the leader. A caller that still+ # finds work in flight does it rather than blocking a thread again.+ for _ in range(_CLAIM_ATTEMPTS):+ cached, waiter = self._claim(key)+ if cached is not None:+ return cached+ if waiter is None:+ try:+ result = self._compare_uncached(request, pair)+ except BaseException:+ self._release(key, None)+ raise+ self._release(key, result)+ return result+ waiter.wait(timeout=_WAIT_TIMEOUT_SECONDS)+ return self._compare_uncached(request, pair)++ # -- cache --------------------------------------------------------------++ def _cache_key(self, request: DeltaRequest, pair: RevisionPair) -> str:+ """Identity of a comparison: the two sides plus how they were analysed."""+ if pair.working_tree:+ # Content identity: HEAD alone does not describe an edited tree.+ paths = sorted(p for p in pair.head_paths)+ blobs = self.source.read_working_tree(paths)+ digest = hashlib.sha256()+ for path in paths:+ digest.update(path.encode("utf-8"))+ digest.update(hashlib.sha256(blobs.get(path, b"")).digest())+ head_identity = f"wt:{digest.hexdigest()[:24]}"+ else:+ head_identity = pair.head_sha+ parts = (+ str(self.repo_path or ""),+ pair.base_sha,+ head_identity,+ str(HEALTH_ANALYZER_VERSION),+ self.rules_fingerprint,+ str(PERFORMANCE_MODEL_VERSION),+ ",".join(request.extensions),+ ",".join(request.exclude_patterns),+ )+ return hashlib.sha256("\x00".join(parts).encode("utf-8")).hexdigest()++ def _claim(self, key: str) -> tuple[ChangeHealthDelta | None, threading.Event | None]:+ with self._lock:+ hit = self._cache.get(key)+ if hit is not None:+ self._cache.move_to_end(key)+ hit.cache_hit = True+ return hit, None+ waiting = self._inflight.get(key)+ if waiting is not None:+ return None, waiting+ self._inflight[key] = threading.Event()+ return None, None++ def _release(self, key: str, result: ChangeHealthDelta | None) -> None:+ with self._lock:+ if result is not None:+ self._cache[key] = result+ while len(self._cache) > _CACHE_CAPACITY:+ self._cache.popitem(last=False)+ event = self._inflight.pop(key, None)+ if event is not None:+ event.set()++ # -- comparison ---------------------------------------------------------++ 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)++ 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:+ delta = ChangeHealthDelta(+ # Nothing was compared either way, so neither case is a clean bill.+ status="unavailable",+ explanation=(+ "No changed file is health-analyzable, so nothing was compared."+ if changes+ else "This change touches no files."+ ),+ base=base_id,+ head=head_id,+ comparison_basis=basis,+ fingerprint=self.fingerprint,+ scope=scope,+ skipped=skipped,+ )+ delta.timing_ms = (time.perf_counter() - started) * 1000+ return delta++ if len(eligible) > MAX_CHANGED_FILES:+ return _unavailable(+ "too_large",+ f"{len(eligible)} changed files exceeds the {MAX_CHANGED_FILES}-file "+ "ceiling for a two-sided analysis.",+ base=base_id,+ head=head_id,+ scope=scope,+ fingerprint=self.fingerprint,+ )++ 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]+ 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)++ head_run = self.analyzer.analyze(head_sources, subject_paths=set(head_paths))+ base_run = self.analyzer.analyze(base_sources, subject_paths=set(base_paths))++ skipped.update(head_run.skipped)+ # 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"}+ )++ rename = pair.rename_map()+ matcher = FindingMatcher(rename)+ # Both sides are restricted to the same comparable set, so an excluded+ # file cannot contribute a one-sided "introduced" or "resolved".+ base_findings = [+ f for f in base_run.findings if rename.get(f.file_path, f.file_path) in subject+ ]+ match = matcher.match(base_findings, head_run.findings_for(subject))++ by_file: dict[str, list[HealthFindingData]] = {}+ for finding in head_run.findings_for(subject):+ 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)+ changed_symbols = changed_symbols_for(change_map, by_file)++ surfaced = match.of_kind("introduced", "worsened")+ perf_views = opportunities_for([m.head for m in surfaced])+ perf_index = index_by_finding(perf_views, [m.head for m in surfaced])++ comparison = f"{pair.base_sha}:{pair.head_sha or 'worktree'}"+ findings = [+ self._to_change_finding(+ m, attributor, changed_symbols, perf_index.get(id(m.head)), comparison+ )+ 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,+ skipped=skipped,+ limits=_limits(),+ )+ delta.timing_ms = (time.perf_counter() - started) * 1000+ return delta++ def _to_change_finding(+ self,+ matched: MatchedFinding,+ attributor: FindingAttributor,+ changed_symbols: set[tuple[str, str]],+ perf: PerfOpportunityView | None,+ comparison: str,+ ) -> ChangeFinding:+ head = matched.head+ edge = perf.intervention_symbol if perf and perf.is_cross_function else None+ attribution = attributor.attribute(+ head, changed_symbols=changed_symbols, changed_call_edge=edge+ )+ key = finding_key(head)+ return ChangeFinding(+ change_finding_id=change_finding_id(key, matched.ordinal, comparison=comparison),+ change_kind=matched.kind,+ dimension=str(head.dimension),+ biomarker_type=str(head.biomarker_type),+ severity=str(head.severity),+ path=head.file_path,+ symbol=head.function_name,+ line_start=head.line_start,+ line_end=head.line_end,+ reason=head.reason or str(head.biomarker_type).replace("_", " "),+ attribution_basis=attribution.basis,+ attribution_confidence=attribution.confidence,+ attribution_detail=attribution.detail,+ suggestion=_suggestion(head, perf),+ follow_up="", # the surface owns its own call syntax+ severity_before=matched.severity_before,+ health_impact=float(head.health_impact or 0.0),+ opportunity_id=perf.opportunity_id if perf else None,+ opportunity_rank=perf.rank_score if perf else None,+ evidence=_evidence(head, perf),+ )+++# -- helpers ----------------------------------------------------------------+++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+ )+ 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:+ """Why a changed path never reached the analyzer."""+ if change.head_path is None:+ return "deleted"+ if language_of(change.head_path) is None:+ return "unsupported_language"+ return "not_health_analyzable"+++def _status_for(+ scope: ScopeCounts, skipped: dict[str, str], findings: list[ChangeFinding]+) -> tuple[str, str]:+ if scope.analyzed == 0:+ return "unavailable", (+ f"None of the {scope.changed} changed "+ f"{'file' if scope.changed == 1 else 'files'} could be analysed."+ )+ if skipped or scope.failed:+ return (+ "partial",+ f"Compared {scope.analyzed} of {scope.changed} changed files; "+ f"{len(skipped)} were not analysed.",+ )+ if not findings:+ return (+ "available",+ "No supported new findings surfaced in the analyzed scope.",+ )+ return "available", f"Compared {scope.analyzed} changed files on both sides."+++def _limits() -> list[str]:+ return [+ "Both sides are analysed over the changed files only, so cross-file "+ "detectors (duplication, cross-function performance) see no wider context."+ ]+++def _priority(finding: ChangeFinding) -> tuple:+ """Severity first, then dimension, then reach — never defect impact for perf."""+ if finding.dimension == "performance":+ return (+ 0,+ -severity_rank(finding.severity),+ -(finding.opportunity_rank or 0),+ _DIMENSION_ORDER["performance"],+ finding.path,+ )+ return (+ 0,+ -severity_rank(finding.severity),+ -int((finding.health_impact or 0.0) * 1000),+ _DIMENSION_ORDER.get(finding.dimension, 9),+ finding.path,+ )+++def _suggestion(finding: HealthFindingData, perf: PerfOpportunityView | None) -> str:+ if perf is not None:+ if perf.actionability_state == "plan_ready" and perf.intervention_symbol:+ return f"Hoist or batch the repeated call in {perf.intervention_symbol}."+ return perf.actionability_reason or "Confirm the cost before changing it."+ return finding.reason or f"Review the {finding.biomarker_type.replace('_', ' ')}."+++def _evidence(finding: HealthFindingData, perf: PerfOpportunityView | None) -> dict:+ evidence: dict = {}+ if perf is not None:+ evidence["opportunity"] = perf.summary()+ evidence["amplification"] = perf.amplification+ evidence["exposure"] = perf.exposure+ evidence["actionability"] = perf.actionability_state+ if perf.observations_total > 1:+ evidence["observations"] = perf.observations_total+ details = finding.details or {}+ for field in ("ccn", "nloc", "nesting", "params", "lines"):+ if field in details:+ evidence[field] = details[field]+ return evidence+++def _unavailable(+ status: str,+ explanation: str,+ *,+ base: RevisionId | None = None,+ head: RevisionId | None = None,+ scope: ScopeCounts | None = None,+ fingerprint: AnalysisFingerprint | None = None,+) -> ChangeHealthDelta:+ return ChangeHealthDelta(+ status=status, # type: ignore[arg-type]+ explanation=explanation,+ base=base,+ head=head,+ comparison_basis="not_compared",+ fingerprint=fingerprint,+ scope=scope or ScopeCounts(),+ )diff --git a/packages/core/src/repowise/core/analysis/change_health/sources.py b/packages/core/src/repowise/core/analysis/change_health/sources.pynew file mode 100644index 000000000..c271dce07--- /dev/null+++ b/packages/core/src/repowise/core/analysis/change_health/sources.py@@ -0,0 +1,266 @@+"""Where the bytes of a revision come from.++The comparison engine depends only on :class:`RevisionSource`, so a hosted+GitHub or artifact adapter can be added without touching matching or+attribution. The local adapter reads Git object content directly and never+checks out, resets, or writes to the caller's tree.+"""++from __future__ import annotations++import subprocess+from collections.abc import Iterator+from dataclasses import dataclass, field+from pathlib import Path+from typing import Protocol++from ..changed_lines import FileDiff, parse_unified_diff++GIT_TIMEOUT_SECONDS = 120++#: Git's rename similarity threshold, as a percentage.+_RENAME_SIMILARITY = 50++#: The empty tree, for diffing a root commit that has no parent.+_EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"+++@dataclass(frozen=True, slots=True)+class FileChange:+ """One path's transition across the change."""++ head_path: str | None+ base_path: str | None+ status: str # added | modified | deleted | renamed+ diff: FileDiff | None = None++ @property+ def is_new(self) -> bool:+ return self.status == "added"++ @property+ def is_rename(self) -> bool:+ return self.status == "renamed"++ @property+ def added_lines(self) -> set[int]:+ return self.diff.new_lines if self.diff else set()+++@dataclass(slots=True)+class RevisionPair:+ """The two sides of a change and the paths that differ between them."""++ base_ref: str+ head_ref: str+ base_sha: str+ head_sha: str+ working_tree: bool+ changes: list[FileChange] = field(default_factory=list)++ @property+ def head_paths(self) -> list[str]:+ return [c.head_path for c in self.changes if c.head_path]++ def rename_map(self) -> dict[str, str]:+ """``{base_path: head_path}`` for renamed files."""+ return {+ c.base_path: c.head_path+ for c in self.changes+ if c.is_rename and c.base_path and c.head_path+ }+++class RevisionSource(Protocol):+ """Reads revision content and change shape without mutating a checkout."""++ def resolve(self, revspec: str | None) -> RevisionPair:+ """Identify both sides and the paths that differ."""+ ...++ def read(self, sha: str, paths: list[str]) -> dict[str, bytes]:+ """Bulk-read *paths* as they exist at *sha*. Missing paths are absent."""+ ...++ def read_working_tree(self, paths: list[str]) -> dict[str, bytes]:+ """Bulk-read *paths* from the uncommitted tree."""+ ...+++def _git(args: list[str], repo_path: str, *, check: bool = True) -> str:+ proc = subprocess.run(+ ["git", "-C", repo_path, *args],+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ stdin=subprocess.DEVNULL,+ timeout=GIT_TIMEOUT_SECONDS,+ )+ if check and proc.returncode != 0:+ raise ValueError((proc.stderr or "").strip() or f"git {args[0]} failed")+ return proc.stdout+++def _status_word(code: str) -> str:+ return {"A": "added", "D": "deleted", "R": "renamed", "M": "modified"}.get(code[:1], "modified")+++class GitRevisionSource:+ """Local adapter over a Git checkout."""++ def __init__(self, repo_path: str) -> None:+ self.repo_path = repo_path++ # -- resolution ---------------------------------------------------------++ def resolve(self, revspec: str | None) -> RevisionPair:+ if not revspec:+ return self._resolve_working_tree()+ if ".." in revspec:+ return self._resolve_range(revspec)+ return self._resolve_commit(revspec)++ def _sha(self, ref: str) -> str:+ out = _git(+ ["rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}"],+ self.repo_path,+ check=False,+ ).strip()+ if not out:+ raise ValueError(f"Could not resolve {ref!r} to a commit.")+ return out++ def _resolve_working_tree(self) -> RevisionPair:+ head = self._sha("HEAD")+ return RevisionPair(+ "HEAD",+ "WORKTREE",+ head,+ "",+ True,+ self._changes(["diff", f"-M{_RENAME_SIMILARITY}%", "HEAD"]),+ )++ def _resolve_commit(self, ref: str) -> RevisionPair:+ head = self._sha(ref)+ parent = _git(+ ["rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}^"],+ self.repo_path,+ check=False,+ ).strip()+ base = parent or _EMPTY_TREE+ return RevisionPair(+ f"{ref}^" if parent else _EMPTY_TREE,+ ref,+ base,+ head,+ False,+ self._changes(["diff", f"-M{_RENAME_SIMILARITY}%", base, head]),+ )++ def _resolve_range(self, revspec: str) -> RevisionPair:+ base, _, head = revspec.partition("..")+ three_dot = head.startswith(".")+ head = head.lstrip(".") or "HEAD"+ base = base or "HEAD"+ base_sha = self._sha(base)+ head_sha = self._sha(head)+ if three_dot:+ base_sha = (+ _git(["merge-base", base, head], self.repo_path, check=False).strip() or base_sha+ )+ return RevisionPair(+ base,+ head,+ base_sha,+ head_sha,+ False,+ self._changes(["diff", f"-M{_RENAME_SIMILARITY}%", base_sha, head_sha]),+ )++ # -- change shape -------------------------------------------------------++ def _changes(self, diff_args: list[str]) -> list[FileChange]:+ name_status = _git([*diff_args, "--name-status", "-z"], self.repo_path)+ diffs = parse_unified_diff(_git([*diff_args, "--unified=0", "--format="], self.repo_path))+ changes: list[FileChange] = []+ for code, base_path, head_path in _iter_name_status(name_status):+ status = _status_word(code)+ key = head_path or base_path+ changes.append(+ FileChange(+ head_path=None if status == "deleted" else head_path,+ base_path=None if status == "added" else base_path,+ status=status,+ diff=diffs.get(key) if key else None,+ )+ )+ return changes++ # -- content ------------------------------------------------------------++ def read(self, sha: str, paths: list[str]) -> dict[str, bytes]:+ """Read every path at *sha* in one ``git cat-file --batch`` pass."""+ if not paths:+ return {}+ return _cat_file_batch(self.repo_path, sha, paths)++ def read_working_tree(self, paths: list[str]) -> dict[str, bytes]:+ root = Path(self.repo_path)+ out: dict[str, bytes] = {}+ for path in paths:+ try:+ out[path] = (root / path).read_bytes()+ except OSError:+ continue+ return out+++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 != ""]+ i = 0+ while i < len(fields):+ code = fields[i]+ if code.startswith("R") and i + 2 < len(fields):+ yield code, fields[i + 1], fields[i + 2]+ i += 3+ elif i + 1 < len(fields):+ yield code, fields[i + 1], fields[i + 1]+ i += 2+ else:+ break+++def _cat_file_batch(repo_path: str, sha: str, paths: list[str]) -> dict[str, bytes]:+ """One batch read; an object missing at *sha* is omitted rather than raising."""+ specs = "\n".join(f"{sha}:{path}" for path in paths) + "\n"+ proc = subprocess.run(+ ["git", "-C", repo_path, "cat-file", "--batch"],+ input=specs.encode("utf-8"),+ capture_output=True,+ timeout=GIT_TIMEOUT_SECONDS,+ )+ if proc.returncode != 0:+ return {}+ out: dict[str, bytes] = {}+ data, cursor = proc.stdout, 0+ for path in paths:+ newline = data.find(b"\n", cursor)+ if newline == -1:+ break+ header = data[cursor:newline]+ # A missing object echoes the whole spec back: "<sha>:<path> missing".+ # Match the suffix, not the field count, because a path may hold spaces.+ if header.endswith(b" missing"):+ cursor = newline + 1+ continue+ fields = header.decode("utf-8", "replace").split()+ if len(fields) < 3 or not fields[2].isdigit():+ break # unparseable header: stop rather than misread the stream+ size = int(fields[2])+ start = newline + 1+ out[path] = data[start : start + size]+ cursor = start + size + 1 # trailing newline+ return outdiff --git a/packages/core/src/repowise/core/analysis/health/dataflow/facts.py b/packages/core/src/repowise/core/analysis/health/dataflow/facts.pyindex 437987d3c..dcb813208 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/facts.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/facts.py@@ -30,7 +30,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom pathlib import Path-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Anyimport structlog@@ -209,10 +209,19 @@ class FileDataflow:non-convergence -- degrades to an empty result for the affected scope."""- def __init__(self, abs_path: str, language: str, source: bytes | None = None) -> None:+ def __init__(+ self,+ abs_path: str,+ language: str,+ source: bytes | None = None,+ read_source: Any | None = None,+ ) -> None:self.abs_path = abs_pathself.language = languageself._source = source+ # When set, the only source of bytes: a miss is unreadable, not a+ # fall-through to the checkout.+ self._read_source_fn = read_sourceself._parsed = Falseself._root: Node | None = Noneself._lmap: LanguageNodeMap | None = None@@ -312,6 +321,9 @@ class FileDataflow:def _read_source(self) -> bytes | None:if self._source is not None:return self._source+ if self._read_source_fn is not None:+ self._source = self._read_source_fn(self.abs_path)+ return self._sourcetry:self._source = Path(self.abs_path).read_bytes()except OSError:@@ -368,14 +380,18 @@ class FileDataflowCache:Keyed by absolute path; entries are created lazily and hold no parse untila consumer gate fires. The cache lives for one pass and is dropped with it.++ *read_source* is the pass's source reader, handed to each entry so a+ revision analysis cannot fall through to the working tree for any file."""- def __init__(self) -> None:+ def __init__(self, read_source: Any | None = None) -> None:self._by_path: dict[str, FileDataflow] = {}+ self._read_source = read_sourcedef get(self, abs_path: str, language: str) -> FileDataflow:fd = self._by_path.get(abs_path)if fd is None:- fd = FileDataflow(abs_path, language)+ fd = FileDataflow(abs_path, language, read_source=self._read_source)self._by_path[abs_path] = fdreturn fddiff --git a/packages/core/src/repowise/core/analysis/health/duplication/detector.py b/packages/core/src/repowise/core/analysis/health/duplication/detector.pyindex fd19d7131..da11d9ca4 100644--- a/packages/core/src/repowise/core/analysis/health/duplication/detector.py+++ b/packages/core/src/repowise/core/analysis/health/duplication/detector.py@@ -86,7 +86,9 @@ class DuplicationReport:diagnostics: dict[str, int | bool] = field(default_factory=dict)-def _read_source(abs_path: str) -> bytes | None:+def _read_source(abs_path: str, read_source: Any | None = None) -> bytes | None:+ if read_source is not None:+ return read_source(abs_path)try:return Path(abs_path).read_bytes()except OSError:@@ -186,6 +188,7 @@ def detect_clones(limits: DuplicationLimits | None = None,cache_dir: Path | None = None,changed_files: set[str] | None = None,+ source_reader: Any | None = None,) -> DuplicationReport:"""Run the duplication pipeline over the supplied parsed files.@@ -238,6 +241,7 @@ def detect_clones(cache,index,cache_dir,+ source_reader,)if report is not None:return report@@ -245,7 +249,7 @@ def detect_clones(diag = DuplicationDiagnostics()per_file_kinds, per_file_nloc, all_windows, per_file_hash = _collect_windows(- parsed_list, window_tokens, lim, diag, cache+ parsed_list, window_tokens, lim, diag, cache, source_reader)if cache is not None:cache.save()@@ -295,6 +299,7 @@ def _collect_windows(limits: DuplicationLimits,diag: DuplicationDiagnostics,cache: Any | None = None,+ read_source: Any | None = None,) -> tuple[dict[str, list[str]], dict[str, int], list[WindowHash], dict[str, str]]:"""Tokenize each file once and emit its rolling-hash windows.@@ -323,7 +328,7 @@ def _collect_windows(path = pf.file_info.pathlanguage = pf.file_info.language- source = _read_source(pf.file_info.abs_path)+ source = _read_source(pf.file_info.abs_path, read_source)if source is None:diag.skipped_unreadable += 1continue@@ -498,6 +503,7 @@ def _detect_clones_incremental(cache: Any,index: Any,cache_dir: Path,+ read_source: Any | None = None,) -> DuplicationReport | None:"""Splice the persisted raw-pair multiset instead of recomputing it.@@ -541,7 +547,7 @@ def _detect_clones_incremental(# Sorted for deterministic window-budget behaviour.changed_pfs = [current[p] for p in sorted(changed)]new_kinds, new_nloc, new_windows, new_hash = _collect_windows(- changed_pfs, window_tokens, lim, diag, cache+ changed_pfs, window_tokens, lim, diag, cache, read_source)if diag.window_budget_hit:return Nonediff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex 09bcc3b09..f417a3861 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -64,6 +64,7 @@ from .refactoring import ()from .refactoring.graph_signals import build_file_scc_index, build_methods_by_filefrom .scoring import attach_impacts, compute_kpis, remap_severities, score_file+from .source_reader import SourceReader, disk_source_readerlog = structlog.get_logger(__name__)@@ -124,7 +125,7 @@ def _log_duplication_diagnostics(report: DuplicationReport) -> None:log.debug("health_duplication_limits", **diag)-def _read_source_lines(abs_path: str) -> list[str] | None:+def _read_source_lines(abs_path: str, read_source: SourceReader) -> list[str] | None:"""Read a file's source as 1-indexed lines for the Extract Helper snippet.Failure-isolated: a read or decode error yields ``None`` (the detector then@@ -132,9 +133,12 @@ def _read_source_lines(abs_path: str) -> list[str] | None:health pass. Decodes UTF-8 leniently since the snippet is for display, notre-parsing."""+ raw = read_source(abs_path)+ if raw is None:+ return Nonetry:- text = Path(abs_path).read_bytes().decode("utf-8", errors="replace")- except OSError:+ text = raw.decode("utf-8", errors="replace")+ except (UnicodeError, AttributeError):return Nonereturn text.splitlines()@@ -289,6 +293,7 @@ class HealthAnalyzer:community_label_map: dict[str, str] | None = None,duplication_cache_dir: Any | None = None,repo_root: Any | None = None,+ source_reader: SourceReader | None = None,) -> None:self.graph = graphself.git_meta_map = git_meta_map or {}@@ -312,6 +317,9 @@ class HealthAnalyzer:# falls back to inferring them from the analyzed file list, which sees# only the manifests the traverser emitted.self.repo_root = repo_root+ # Every source read in the pass. Defaults to the working tree; a+ # revision comparison supplies bytes instead.+ self.read_source: SourceReader = source_reader or disk_source_readerself._package_roots_cache: set[str] | None = Noneself._tests_reach_cache: set[str] | None = Noneself._execution_graph_cache: CallGraphIndex | None = None@@ -426,6 +434,7 @@ class HealthAnalyzer:self.parsed_files,self.git_meta_map,cache_dir=self.duplication_cache_dir,+ source_reader=self.read_source,changed_files=changed_set,)_log_duplication_diagnostics(dup_report)@@ -475,7 +484,7 @@ class HealthAnalyzer:# One shared dataflow service for the whole pass: the promotion pass# and the Extract Method detector below read the same lazily parsed# per-file object, so no file is parsed twice for dataflow.- dataflow_cache = FileDataflowCache()+ dataflow_cache = FileDataflowCache(self.read_source)# Dataflow promotion: mark advisory perf hits whose loop is provably# iteration-independent (runs after the graph passes so the# centrality-gated nested-loop hits are present to promote).@@ -606,6 +615,7 @@ class HealthAnalyzer:self.parsed_files,self.git_meta_map,cache_dir=self.duplication_cache_dir,+ source_reader=self.read_source,changed_files=changed_set,))@@ -668,7 +678,7 @@ class HealthAnalyzer:walked = list(walked)self._apply_crossfn_perf(walked)# One shared dataflow service per pass (see the sync path above).- dataflow_cache = FileDataflowCache()+ dataflow_cache = FileDataflowCache(self.read_source)# Dataflow promotion: mark advisory perf hits whose loop is provably# iteration-independent (after the graph passes populate the hits).apply_perf_promotions(walked, dataflow=dataflow_cache)@@ -853,9 +863,8 @@ class HealthAnalyzer:def _walk(self, pf: Any) -> FileComplexity:path = pf.file_info.abs_pathlanguage = pf.file_info.language- try:- source = Path(path).read_bytes()- except OSError:+ source = self.read_source(path)+ if source is None:return FileComplexity(functions=[], classes=[])if language == "sql":# SQL has no tree-sitter grammar here; the sqlglot-backed walker@@ -884,7 +893,7 @@ class HealthAnalyzer:"""if not any(getattr(f, "biomarker_type", "") in _EXTRACT_METHOD_SOURCES for f in findings):return []- cache = dataflow_cache if dataflow_cache is not None else FileDataflowCache()+ cache = dataflow_cache if dataflow_cache is not None else FileDataflowCache(self.read_source)return cache.get(pf.file_info.abs_path, pf.file_info.language).flagged_analyses()def _populate_symbol_complexity(self, pf: Any, fc_list: list[FunctionComplexity]) -> None:@@ -1065,7 +1074,9 @@ class HealthAnalyzer:# detector's snippet). Reading it unconditionally would put a# repo-sized read back into the per-file path; gating on clones keeps# it proportional to the small set of files that actually carry one.- source_lines=_read_source_lines(pf.file_info.abs_path) if clones else None,+ source_lines=(+ _read_source_lines(pf.file_info.abs_path, self.read_source) if clones else None+ ),)suggestions = detect_refactorings(rctx,diff --git a/packages/core/src/repowise/core/analysis/health/source_reader.py b/packages/core/src/repowise/core/analysis/health/source_reader.pynew file mode 100644index 000000000..135816a32--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/source_reader.py@@ -0,0 +1,49 @@+"""How the health pass obtains file bytes.++Routing every source read through a :class:`SourceReader` lets the pass analyse+content that is not the working tree -- the base side of a diff, a historical+commit -- without checking anything out. The default reads the working tree.++Keyed by ``abs_path``: the key every read site already holds.+"""++from __future__ import annotations++from pathlib import Path+from typing import Protocol+++class SourceReader(Protocol):+ """Return the bytes of one file, or ``None`` when it cannot be read."""++ def __call__(self, abs_path: str) -> bytes | None: ...+++def disk_source_reader(abs_path: str) -> bytes | None:+ """Read *abs_path* from the filesystem, degrading to ``None``."""+ try:+ return Path(abs_path).read_bytes()+ except OSError:+ return None+++class MappingSourceReader:+ """Serve bytes from an in-memory map, with no filesystem fallback.++ The absent fallback is the point: filling a gap from the working tree would+ report its findings as the revision's. A missing path reads as unreadable,+ which the health pass already degrades on and the caller can count.+ """++ __slots__ = ("_sources", "misses")++ def __init__(self, sources: dict[str, bytes]) -> None:+ self._sources = sources+ #: Paths asked for and not held, so coverage is reported, not inferred.+ self.misses: set[str] = set()++ def __call__(self, abs_path: str) -> bytes | None:+ source = self._sources.get(abs_path)+ if source is None:+ self.misses.add(abs_path)+ return sourcediff --git a/packages/server/README.md b/packages/server/README.mdindex 5e8ffe1fb..df28e072e 100644--- a/packages/server/README.md+++ b/packages/server/README.md@@ -252,7 +252,7 @@ repowise mcp --transport sse # legacy SSE transport on port 7338| `get_symbol(symbol_id)` | Source body, signature, docstring for a qualified symbol | When the question names a specific function or class || `search_codebase(query, mode?)` | Hybrid symbol / path / concept search (auto-routes by query shape) | When locating a symbol, a file, or code by topic || `get_risk(targets)` | Hotspot score, dependents, co-change partners, risk summary | Before modifying files — assess what could break |-| `get_change_risk(revspec?)` | Benchmarked repo-relative review percentile/classification plus a supporting live diff-shape score | Before merging a commit or PR range |+| `get_change_risk(revspec?)` | What the change newly made worse, with attribution, plus a supporting diff-shape percentile | Before merging a commit or PR range || `get_why(query?)` | Architectural decisions, rationale, constraints | Before making architectural changes — understand existing intent || `get_dead_code` | Unused/unreachable code sorted by cleanup impact | Before cleanup tasks || `get_health` | 1–10 code-health scores and marker findings | Before refactoring — find the worst files |diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.pyindex e82d799c9..c15cf2be1 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py@@ -55,14 +55,27 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {"get_change_risk": ResponseBudgetContract("blocks",(+ # Cheapest loss first. Diff-shape context and history go before the+ # delta and the tests, so what to do survives what the diff weighs."exclude_patterns",- "prior_fixes",- "impacted_tests",- "cross_repo",+ "change_shape","fix_history.files[]","fix_history.files",+ "fix_history",+ "prior_fixes",+ "cross_repo",+ "impacted_tests",+ "health_delta.limits",+ "health_delta.skipped",+ "health_delta.top_findings[]",+ ),+ protected=(+ "directive",+ "health_delta",+ "classification",+ "risk_percentile",+ "score",),- protected=("classification", "risk_percentile", "risk_authority", "score"),),"get_answer": ResponseBudgetContract("blocks",diff --git a/packages/server/src/repowise/server/mcp_server/_change_health.py b/packages/server/src/repowise/server/mcp_server/_change_health.pynew file mode 100644index 000000000..609bb9506--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/_change_health.py@@ -0,0 +1,196 @@+"""Render a change-health comparison as the action-first half of the response.++The tool owns orchestration; this module owns what an agent is told first and+how little of it there is. Everything here is derived from the core delta, so+the MCP surface holds no comparison policy of its own.+"""++from __future__ import annotations++from typing import Any++from repowise.core.analysis.change_health.models import ChangeFinding, ChangeHealthDelta++#: Actionable findings carried in the default response. The rest are counted+#: and recoverable by an exact call, never silently dropped.+TOP_FINDINGS_LIMIT = 3++#: Reasons carried on the directive.+REASON_LIMIT = 3++_BLOCKING_SEVERITIES = {"high", "critical"}++#: Dimensions whose findings are advice, not a gate. A performance advisory+#: never blocks on its own; it ranks and it explains.+_ADVISORY_DIMENSIONS = {"performance"}+++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)+ return {+ "status": status,+ "headline": headline,+ "reasons": _reasons(delta)[:REASON_LIMIT],+ "next_actions": _next_actions(delta, tests),+ }+++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]+ block: dict[str, Any] = {+ "status": delta.status,+ "explanation": delta.explanation,+ "basis": delta.comparison_basis,+ "introduced": delta.introduced_total,+ "worsened": delta.worsened_total,+ "resolved": delta.resolved_total,+ "by_dimension": _counts(delta.findings, "dimension"),+ "by_severity": _counts(delta.findings, "severity"),+ "scope": delta.scope.as_dict(),+ "top_findings": [finding_row(f, revspec) for f in emitted],+ "findings_total": len(delta.findings),+ "findings_emitted": len(emitted),+ }+ if delta.base is not None:+ block["base"] = delta.base.as_dict()+ if delta.head is not None:+ block["head"] = delta.head.as_dict()+ if delta.fingerprint is not None:+ block["analyzer"] = delta.fingerprint.as_dict()+ if len(delta.findings) > len(emitted):+ block["findings_reduced_reason"] = "top_findings_cap"+ block["all_findings_via"] = _call(revspec, extra="include=['findings']")+ if delta.skipped:+ block["skipped"] = _skipped(delta.skipped)+ if delta.limits:+ block["limits"] = delta.limits+ return block+++def finding_row(finding: ChangeFinding, revspec: str | None) -> dict[str, Any]:+ """One surfaced finding, with the exact call that expands it."""+ row: dict[str, Any] = {+ "id": finding.change_finding_id,+ "change": finding.change_kind,+ "dimension": finding.dimension,+ "biomarker": finding.biomarker_type,+ "severity": finding.severity,+ "path": finding.path,+ "reason": finding.reason,+ "attribution": {+ "basis": finding.attribution_basis,+ "confidence": finding.attribution_confidence,+ "why": finding.attribution_detail,+ },+ "inspect": _call(revspec, extra=f"finding_id={finding.change_finding_id!r}"),+ }+ if finding.suggestion and finding.suggestion != finding.reason:+ row["suggestion"] = finding.suggestion+ if finding.symbol:+ row["symbol"] = finding.symbol+ if finding.line_start is not None:+ row["lines"] = [finding.line_start, finding.line_end or finding.line_start]+ if finding.severity_before:+ row["severity_before"] = finding.severity_before+ if finding.opportunity_id:+ row["opportunity_id"] = finding.opportunity_id+ row["opportunity_rank"] = finding.opportunity_rank+ if finding.health_reference:+ row["health_reference"] = finding.health_reference+ return row+++def finding_detail(finding: ChangeFinding, revspec: str | None) -> dict[str, Any]:+ """The drill-down view: the row plus the evidence behind it."""+ row = finding_row(finding, revspec)+ row.pop("inspect", None)+ row["evidence"] = finding.evidence+ row["health_impact"] = finding.health_impact+ return row+++# -- 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]:+ counts: dict[str, int] = {}+ for finding in findings:+ key = str(getattr(finding, attribute))+ counts[key] = counts.get(key, 0) + 1+ return counts+++def _skipped(skipped: dict[str, str]) -> dict[str, Any]:+ by_reason: dict[str, int] = {}+ for reason in skipped.values():+ by_reason[reason] = by_reason.get(reason, 0) + 1+ return {"total": len(skipped), "by_reason": by_reason}+++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/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.pyindex d64ad0962..15bcd1415 100644--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py@@ -5,15 +5,22 @@ from __future__ import annotationsimport asyncioimport jsonimport subprocess+import threadingimport time+from collections import OrderedDictfrom datetime import UTC, datetimefrom functools import partialfrom typing import Anyimport pathspec+import structlogfrom sqlalchemy import selectfrom sqlalchemy.exc import SQLAlchemyError+from repowise.core.analysis.change_health.service import (+ ChangeHealthDeltaService,+ DeltaRequest,+)from repowise.core.analysis.change_risk import (change_risk_payload,normalize_extensions,@@ -23,6 +30,15 @@ from repowise.core.analysis.pr_blast import rank_tests_by_reachfrom repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server._budget import OmissionCollectorfrom repowise.server.mcp_server._budget.contracts import response_budget_shed_order+from repowise.server.mcp_server._change_health import (+ directive as _directive,+)+from repowise.server.mcp_server._change_health import (+ finding_detail as _finding_detail,+)+from repowise.server.mcp_server._change_health import (+ health_delta_block as _health_delta_block,+)from repowise.server.mcp_server._helpers import (_get_repo,_is_workspace_mode,@@ -33,6 +49,8 @@ from repowise.server.mcp_server._helpers import ()from repowise.server.mcp_server._meta import build_meta as _build_meta+log = structlog.get_logger(__name__)+#: Cap on the line-precise impacted-test list, matching the get_risk directive's#: ``tests_to_run`` cap so both surfaces stay glanceable. The tail goes to the#: omission store, so ``truncated: true`` is recoverable rather than a dead end.@@ -53,7 +71,30 @@ _CROSS_REPO_CONSUMER_LIMIT = 10_SHED_ORDER = response_budget_shed_order("get_change_risk")#: Per-field units and calibration. Identical on every call, so it is opt-in.-_INCLUDE_BLOCKS = frozenset({"scales"})+#: ``diagnostics`` carries the raw model mechanics; ``findings`` lifts the+#: top-findings cap. Both are projections, recoverable by an exact call.+_INCLUDE_BLOCKS = frozenset({"scales", "diagnostics", "findings"})++#: Score mechanics that are identical or near-identical on every call. Moved+#: behind ``include=["diagnostics"]`` so the action-first blocks lead.+_DIAGNOSTIC_FIELDS = (+ "risk_authority",+ "score_measures",+ "score_unit",+ "baseline_sample_size",+ "features",+ "drivers",+)++#: Compact supporting context: the ranked reading, not the model's workings.+_CHANGE_SHAPE_FIELDS = (+ "score",+ "risk_percentile",+ "review_priority",+ "classification",+ "fallback_band",+ "is_fix",+)@mcp.tool(surface_order=60,@@ -68,35 +109,34 @@ async def get_change_risk(exclude_patterns: list[str] | None = None,baseline: int = 200,include: list[str] | None = None,+ finding_id: str | None = None,) -> dict:- """Score a live commit, ``base..head`` range, or uncommitted work.+ """Review a commit, ``base..head`` range, or uncommitted work.- For a pre-merge read on a commit or PR range; ``get_risk`` scores indexed- files instead. The filters also apply to the percentile baseline.+ Leads with ``directive`` (what to do) and ``health_delta`` (what this+ change newly made worse across defect, maintainability, and performance).+ Both sides are analysed from their own content, so a finding present at+ head is only reported when the diff explains it; every finding names its+ ``attribution`` basis and confidence.- Act on ``risk_percentile`` + ``classification``: they rank this diff- against recent commits, and ``risk_authority`` names them. ``score`` is a- supporting 0-10 model score for diff size and spread, never a probability;- ``fallback_band`` stands in only when no baseline exists. ``fix_history``- carries the bug-fix record of the touched files.+ Trust ``health_delta.status``: ``partial`` means files were skipped and the+ change is not cleared. ``scope`` counts what was actually compared.- ``impacted_tests`` keeps measured coverage and inferred graph candidates- distinct, labels unavailable analysis, and exposes truncation metadata.- ``prior_fixes`` counts past fixes whose lines overlap this diff.-- Defaults fit 24,000 chars; nonempty ``include`` uses 32,000. Reductions- carry counts and recovery status in ``_meta``.- Include-gated blocks are projections, not omissions.+ ``impacted_tests`` keeps measured coverage and inferred candidates distinct.+ ``prior_fixes`` counts past fixes overlapping this diff. ``change_shape``+ ranks the diff's size and spread against recent commits.Args:- revspec: Commit or ``base..head`` range to score. Omit it to score the- uncommitted change, or ``HEAD`` when the working tree is clean.+ revspec: Commit or ``base..head`` range. Omit to review uncommitted+ work, or ``HEAD`` when the tree is clean.repo: Repository alias in workspace mode; omit for the default.extensions: File suffixes to count, e.g. ``[".py", ".ts"]``.exclude_patterns: Gitignore-style paths to omit, e.g. ``["tests/"]``.- baseline: Recent commits to sample for percentile ranking; 0 disables it.- include: opt-in blocks - "scales" for every scalar's unit, range and- calibration. Identical on every call, so ask once.+ baseline: Recent commits sampled for percentile ranking; 0 disables it.+ include: ``"findings"`` for every change finding, ``"diagnostics"`` for+ raw score mechanics, ``"scales"`` for units. All identical on+ repeat, so ask once.+ finding_id: Expand one ``health_delta`` finding by its id."""if repo == "all":return _unsupported_repo_all("get_change_risk")@@ -125,6 +165,10 @@ async def get_change_risk(if resolve_enum_argument(block, _INCLUDE_BLOCKS, argument="include", ignored=ignored)}payload = change_risk_payload(result, scales="scales" in include_set)+ if "diagnostics" not in include_set:+ diagnostics = {f: payload.pop(f) for f in _DIAGNOSTIC_FIELDS if f in payload}+ else:+ diagnostics = {}if result.features.nf == 0:payload["warning"] = (f"No counted file changes in {payload['ref']!r} "@@ -148,13 +192,37 @@ async def get_change_risk(working_tree=result.working_tree,)collector = OmissionCollector("get_change_risk", repo_root=ctx.path)- payload["impacted_tests"] = await _impacted_tests_block(ctx, changed, changed_error, collector)- prior_fixes = await _prior_fixes_block(ctx, changed)- if prior_fixes is not None:- payload["prior_fixes"] = prior_fixes- cross_repo = _cross_repo_block(getattr(ctx, "alias", ""), sorted(changed))- if cross_repo is not None:- payload["cross_repo"] = cross_repo+ # The delta is the expensive half and needs nothing the enrichments need,+ # so it runs alongside them rather than after.+ delta_task = asyncio.create_task(+ asyncio.to_thread(+ _compare_health,+ str(ctx.path),+ revspec,+ tuple(extensions or ()),+ tuple(result.riskignore_excludes + result.request_excludes),+ )+ )+ try:+ payload["impacted_tests"] = await _impacted_tests_block(+ ctx, changed, changed_error, collector+ )+ prior_fixes = await _prior_fixes_block(ctx, changed)+ if prior_fixes is not None:+ payload["prior_fixes"] = prior_fixes+ cross_repo = _cross_repo_block(getattr(ctx, "alias", ""), sorted(changed))+ if cross_repo is not None:+ payload["cross_repo"] = cross_repo+ except BaseException:+ # Never leave the comparison running for a request that is already over.+ delta_task.cancel()+ raise+ delta = await delta_task+ await _attach_health_references(ctx, delta)+ if finding_id is not None:+ return _drill_down(payload, delta, finding_id, revspec)+ _attach_health(payload, delta, revspec, expand="findings" in include_set)+ payload["change_shape"] = _change_shape(payload, diagnostics)# source: live_git marks that the *score* is computed from the working# checkout's git. The two blocks above are index-backed, so the freshness# fields do apply to them, scoped to the change's files. None (not []) when@@ -171,6 +239,172 @@ async def get_change_risk(return payload+#: One service per repository, so its comparison cache and stampede guard+#: outlive a single call. LRU-bounded: a long-lived server can see many+#: worktrees and workspace members over its lifetime.+_DELTA_SERVICES: OrderedDict[str, ChangeHealthDeltaService] = OrderedDict()+_DELTA_SERVICE_CAPACITY = 8+_DELTA_SERVICES_LOCK = threading.Lock()+++def _delta_service(repo_path: str) -> ChangeHealthDeltaService:+ with _DELTA_SERVICES_LOCK:+ service = _DELTA_SERVICES.get(repo_path)+ if service is not None:+ _DELTA_SERVICES.move_to_end(repo_path)+ return service+ # Built outside the lock: the fingerprint reads config off disk.+ service = ChangeHealthDeltaService(+ repo_path=repo_path, rules_fingerprint=_rules_fingerprint(repo_path)+ )+ with _DELTA_SERVICES_LOCK:+ existing = _DELTA_SERVICES.get(repo_path)+ if existing is not None:+ _DELTA_SERVICES.move_to_end(repo_path)+ return existing+ _DELTA_SERVICES[repo_path] = service+ while len(_DELTA_SERVICES) > _DELTA_SERVICE_CAPACITY:+ _DELTA_SERVICES.popitem(last=False)+ return service+++def _rules_fingerprint(repo_path: str) -> str:+ """Identity of the effective health rules; empty when they cannot be read."""+ try:+ from repowise.core.repo_config import config_fingerprint++ return config_fingerprint(repo_path)+ except Exception:+ return ""+++def _compare_health(+ repo_path: str,+ revspec: str | None,+ extensions: tuple[str, ...],+ exclude_patterns: tuple[str, ...],+) -> Any:+ """Run the comparison, degrading to an explicit unavailable state."""+ from repowise.core.analysis.change_health.models import ChangeHealthDelta++ try:+ return _delta_service(repo_path).compare(+ DeltaRequest(repo_path, revspec, extensions, exclude_patterns)+ )+ except Exception as exc:+ log.warning("change_health_comparison_failed", revspec=revspec, error=str(exc))+ return ChangeHealthDelta(+ status="unavailable",+ explanation=f"Health comparison failed: {exc}",+ base=None,+ head=None,+ comparison_basis="not_compared",+ fingerprint=None,+ )+++async def _attach_health_references(ctx: Any, delta: Any) -> None:+ """Point a change finding at its stored twin, when it has one exactly.++ Only an exact match earns the canonical reference: same file, marker,+ symbol, and span. Anything looser would hand an agent a pointer to a+ different finding, and most change findings have no stored twin at all+ because uncommitted and historical work is never persisted.+ """+ from repowise.core.persistence.database import get_session+ from repowise.core.persistence.models import HealthFinding++ session_factory = getattr(ctx, "session_factory", None)+ if session_factory is None or not delta.findings:+ return+ paths = sorted({f.path for f in delta.findings})+ try:+ async with get_session(session_factory) as session:+ repository = await _get_repo(session)+ rows = (+ await session.execute(+ select(HealthFinding).where(+ HealthFinding.repository_id == repository.id,+ HealthFinding.file_path.in_(paths),+ )+ )+ ).scalars().all()+ except SQLAlchemyError:+ return+ if not rows:+ return+ from repowise.server.mcp_server.tool_health import _health_finding_id++ alias = getattr(ctx, "alias", None) or repository.name+ stored = {+ (r.file_path, r.biomarker_type, r.function_name or "", r.line_start, r.line_end): r+ for r in rows+ }+ for finding in delta.findings:+ row = stored.get(+ (+ finding.path,+ finding.biomarker_type,+ finding.symbol or "",+ finding.line_start,+ finding.line_end,+ )+ )+ if row is None:+ continue+ finding.health_reference = {+ "tool": "get_health",+ "arguments": {"finding_id": _health_finding_id(row, alias)},+ }+++def _attach_health(payload: dict, delta: Any, revspec: str | None, *, expand: bool) -> None:+ """Put the directive first and the compact delta second."""+ block = _health_delta_block(delta, revspec=revspec)+ if expand:+ from repowise.server.mcp_server._change_health import finding_row++ block["top_findings"] = [finding_row(f, revspec) for f in delta.findings]+ block["findings_emitted"] = len(delta.findings)+ block.pop("findings_reduced_reason", None)+ block.pop("all_findings_via", None)+ ordered = {+ "directive": _directive(delta, payload.get("impacted_tests")),+ "health_delta": block,+ }+ for key, value in payload.items():+ ordered[key] = value+ payload.clear()+ payload.update(ordered)+++def _change_shape(payload: dict, diagnostics: dict) -> dict[str, Any]:+ """The ranked diff-shape reading, kept compact and clearly supporting."""+ shape = {f: payload[f] for f in _CHANGE_SHAPE_FIELDS if f in payload}+ shape["measures"] = "diff size and spread, not danger"+ if diagnostics:+ shape["diagnostics_via"] = "get_change_risk(include=['diagnostics'])"+ return shape+++def _drill_down(payload: dict, delta: Any, finding_id: str, revspec: str | None) -> dict:+ """Expand one ephemeral change finding, or say why it is not there."""+ match = next(+ (f for f in delta.findings if f.change_finding_id == finding_id), None+ )+ if match is None:+ return {+ "error": f"No change finding {finding_id!r} in {payload.get('ref', 'this change')}.",+ "hint": "Ids are scoped to one comparison; re-run without finding_id to list them.",+ "available": [f.change_finding_id for f in delta.findings[:10]],+ }+ return {+ "finding": _finding_detail(match, revspec),+ "ref": payload.get("ref"),+ "health_delta_status": delta.status,+ }++async def _repository(ctx: Any) -> Any | None:"""The indexed repository row, or ``None`` without an index.@@ -697,6 +931,8 @@ async def _impacted_tests_block(by_file[source_file] = idsexcept LookupError:return _empty_impacted("no_index", "No indexed repository; run `repowise init`.")+ except SQLAlchemyError:+ return _empty_impacted("unknown", "Could not read the coverage map.")tests = rank_tests_by_reach(by_file)total = len(tests)diff --git a/packages/types/src/chat.ts b/packages/types/src/chat.tsindex 201563d08..90d161257 100644--- a/packages/types/src/chat.ts+++ b/packages/types/src/chat.ts@@ -238,8 +238,73 @@ export interface RiskReportArtifactData {classification?: string;warning?: string;error?: string;+ /** `get_change_risk` action-first blocks. */+ directive?: ChangeRiskDirective;+ health_delta?: ChangeHealthDeltaData;+ change_shape?: Record<string, unknown>;+ impacted_tests?: { tests_to_run?: string[]; status?: string; summary?: string };+ /** Bug-fix record of the touched files: the "historically fragile" signal. */+ fix_history?: {+ available?: boolean;+ files?: Array<{ path: string; churn: number; fix_pressure: number }>;+ };+ prior_fixes?: { files_with_fixes?: number; total_fixes?: number };[k: string]: unknown;}++/** What the change did to the codebase's health, and how sure the tool is. */+export interface ChangeFindingRow {+ id: string;+ change: "introduced" | "worsened";+ dimension: "defect" | "maintainability" | "performance";+ biomarker: string;+ severity: "low" | "medium" | "high" | "critical";+ path: string;+ reason: string;+ attribution: { basis: string; confidence: "high" | "medium" | "low"; why: string };+ symbol?: string;+ lines?: [number, number];+ severity_before?: string;+ suggestion?: string;+ opportunity_id?: string;+ opportunity_rank?: number;+ inspect?: string;+}++export interface ChangeHealthDeltaData {+ /** `partial` and `unavailable` must never render as a clean result. */+ status:+ | "available"+ | "partial"+ | "unavailable"+ | "unsupported_range"+ | "too_large"+ | "timeout"+ | "analyzer_mismatch"+ | "rules_mismatch"+ | "stale_baseline";+ explanation: string;+ introduced: number;+ worsened: number;+ resolved: number;+ top_findings: ChangeFindingRow[];+ findings_total: number;+ findings_emitted: number;+ by_dimension?: Record<string, number>;+ by_severity?: Record<string, number>;+ scope?: { changed: number; eligible: number; analyzed: number; skipped: number; failed: number };+ skipped?: { total: number; by_reason: Record<string, number> };+ base?: { ref: string; sha: string; kind: string };+ head?: { ref: string; sha: string; kind: string };+ limits?: string[];+}++export interface ChangeRiskDirective {+ status: "review_required" | "review_recommended" | "clear_in_analyzed_scope" | "unknown";+ headline: string;+ reasons?: string[];+ next_actions?: string[];+}export interface RiskReportArtifact extends ArtifactEnvelopeIdentity {type: "risk_report";data: RiskReportArtifactData;diff --git a/packages/ui/__tests__/chat/change-risk-artifact.test.tsx b/packages/ui/__tests__/chat/change-risk-artifact.test.tsxnew file mode 100644index 000000000..dd15805bf--- /dev/null+++ b/packages/ui/__tests__/chat/change-risk-artifact.test.tsx@@ -0,0 +1,154 @@+import { render, screen, within } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import type { RiskReportArtifactData } from "@repowise-dev/types/chat";+import { RiskReportRenderer } from "../../src/chat/artifacts";++const finding = {+ id: "chf_abc123",+ change: "introduced" as const,+ dimension: "defect" as const,+ biomarker: "complex_method",+ severity: "high" as const,+ path: "src/app.py",+ symbol: "handler",+ lines: [12, 40] as [number, number],+ reason: "handler has cyclomatic complexity 21",+ attribution: {+ basis: "added_lines",+ confidence: "high" as const,+ why: "Lines 12-40 are added or rewritten by this change.",+ },+ inspect: "get_change_risk(revspec='HEAD', finding_id='chf_abc123')",+};++const data: RiskReportArtifactData = {+ ref: "HEAD",+ score: 6.4,+ risk_percentile: 82,+ review_priority: "Elevated",+ classification: "Higher-risk than most recent commits",+ directive: {+ status: "review_required",+ headline: "1 new finding needs review, starting with complex_method in src/app.py.",+ reasons: ["high defect: complex_method in handler (added_lines)"],+ next_actions: ["Inspect src/app.py:12 (chf_abc123)", "Run: tests/test_app.py"],+ },+ health_delta: {+ status: "available",+ explanation: "Compared 3 changed files on both sides.",+ introduced: 1,+ worsened: 0,+ resolved: 2,+ top_findings: [finding],+ findings_total: 1,+ findings_emitted: 1,+ scope: { changed: 3, eligible: 3, analyzed: 3, skipped: 0, failed: 0 },+ },+ impacted_tests: { tests_to_run: ["tests/test_app.py"], status: "map_present" },+};++describe("change risk artifact", () => {+ it("leads with the verdict and what the change made worse", () => {+ render(<RiskReportRenderer data={data} />);++ expect(screen.getByText("Review required")).toBeInTheDocument();+ expect(screen.getByText(/1 new finding needs review/)).toBeInTheDocument();+ expect(screen.getByText("What this change made worse")).toBeInTheDocument();+ expect(+ screen.getByText("handler has cyclomatic complexity 21"),+ ).toBeInTheDocument();+ });++ it("shows each finding's attribution, not just its location", () => {+ render(<RiskReportRenderer data={data} />);++ expect(+ screen.getByText(/Lines 12-40 are added or rewritten by this change/),+ ).toBeInTheDocument();+ expect(screen.getByText(/high confidence/)).toBeInTheDocument();+ });++ it("names severity in words via the shared SeverityMark, not colour alone", () => {+ render(<RiskReportRenderer data={data} />);++ // The finding cards lead; the disclosure lists come after them.+ const card = screen.getAllByRole("listitem")[0]!;+ expect(within(card).getByText("High")).toBeInTheDocument();+ expect(within(card).getByText(/introduced · defect/)).toBeInTheDocument();+ });++ it("surfaces historically fragile files in the context row", () => {+ render(+ <RiskReportRenderer+ data={{+ ...data,+ fix_history: {+ available: true,+ files: [{ path: "src/app.py", churn: 42, fix_pressure: 9.1 }],+ },+ }}+ />,+ );++ expect(screen.getByText("Fragile")).toBeInTheDocument();+ expect(screen.getByText("Historically fragile files")).toBeInTheDocument();+ expect(screen.getByText("42 changes")).toBeInTheDocument();+ });++ it("demotes the diff-shape score behind progressive disclosure", () => {+ render(<RiskReportRenderer data={data} />);++ // The ranked reading stays in the compact context row...+ expect(screen.getByText("p82")).toBeInTheDocument();+ // ...while the raw model score is inside the collapsed section.+ const disclosure = screen.getByText("More detail");+ expect(disclosure.closest("details")).not.toBeNull();+ expect(screen.getByText("Diff-shape score")).toBeInTheDocument();+ });++ it("announces a partial comparison as a live status, not a clean result", () => {+ render(+ <RiskReportRenderer+ data={{+ ...data,+ directive: {+ status: "unknown",+ headline: "Nothing new in what was compared, but part was not analysed.",+ },+ health_delta: {+ ...data.health_delta!,+ status: "partial",+ explanation: "Compared 2 of 3 changed files; 1 was not analysed.",+ top_findings: [],+ introduced: 0,+ findings_total: 0,+ findings_emitted: 0,+ skipped: { total: 1, by_reason: { not_health_analyzable: 1 } },+ },+ }}+ />,+ );++ const status = screen.getByRole("status");+ expect(status).toHaveTextContent("Compared 2 of 3 changed files");+ expect(screen.getByText("Not established")).toBeInTheDocument();+ expect(screen.queryByText("What this change made worse")).toBeNull();+ });++ it("reports an error with an alert role", () => {+ render(<RiskReportRenderer data={{ error: "Could not read change 'nope'." }} />);++ expect(screen.getByRole("alert")).toHaveTextContent("Could not read change");+ });++ it("still renders a legacy payload that has no delta", () => {+ render(+ <RiskReportRenderer+ data={{ ref: "HEAD", score: 3.1, risk_percentile: 40, review_priority: "Normal" }}+ />,+ );++ expect(screen.getByText("p40")).toBeInTheDocument();+ expect(screen.getByText("Normal")).toBeInTheDocument();+ });+});diff --git a/packages/ui/src/chat/artifacts.tsx b/packages/ui/src/chat/artifacts.tsxindex 7726a168b..245d44b72 100644--- a/packages/ui/src/chat/artifacts.tsx+++ b/packages/ui/src/chat/artifacts.tsx@@ -22,6 +22,7 @@ import {Sparkles,} from "lucide-react";import type {+ ChangeFindingRow,ContextArtifactData,DeadCodeArtifactData,DecisionsArtifactData,@@ -31,6 +32,8 @@ import type {RiskReportArtifactData,SearchResultsArtifactData,} from "@repowise-dev/types/chat";+import { SeverityMark } from "../health/severity-mark";+import type { Severity } from "../health/tokens";import { Markdown } from "../shared/markdown";import { MermaidDiagram } from "../wiki/mermaid-diagram";import { getPageTypeLabel } from "../lib/page-types";@@ -255,38 +258,255 @@ function normalizeGlobalHotspots(data: RiskReportArtifactData): Array<{.filter((h): h is { path: string; score: number } => h !== null);}-export function RiskReportRenderer({ data }: { data: RiskReportArtifactData }) {- // get_change_risk returns a live-git score card, not per-file targets.- if (data.error || data.ref || data.review_priority || data.risk_percentile != null) {- const pct =- typeof data.risk_percentile === "number"- ? Math.round(data.risk_percentile)- : null;- return (- <div className="space-y-3">- {data.error && (- <p className="text-xs text-[var(--color-warning)]">{String(data.error)}</p>- )}- {data.ref && (- <StatRow label="Change" value={String(data.ref)} />- )}+const DIRECTIVE_TONE: Record<string, { label: string; className: string }> = {+ review_required: {+ label: "Review required",+ className: "text-[var(--color-error)]",+ },+ review_recommended: {+ label: "Review recommended",+ className: "text-[var(--color-warning)]",+ },+ clear_in_analyzed_scope: {+ label: "Clear in analyzed scope",+ className: "text-[var(--color-success)]",+ },+ unknown: {+ label: "Not established",+ className: "text-[var(--color-text-secondary)]",+ },+};++function ContextItem({ label, value }: { label: string; value: React.ReactNode }) {+ return (+ <div className="flex items-baseline gap-1">+ <dt className="text-[var(--color-text-tertiary)]">{label}</dt>+ <dd className="font-mono tabular-nums text-[var(--color-text-secondary)]">+ {value}+ </dd>+ </div>+ );+}++function ChangeFindingCard({ finding }: { finding: ChangeFindingRow }) {+ const lines = finding.lines ? `:${finding.lines[0]}` : "";+ return (+ <li className="rounded-lg border border-[var(--color-border-default)] p-2.5">+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">+ <SeverityMark severity={finding.severity as Severity} />+ <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {finding.change} · {finding.dimension}+ </span>+ </div>+ <p className="mt-1 text-xs text-[var(--color-text-primary)]">+ {finding.reason}+ </p>+ <p className="mt-0.5 truncate font-mono text-[10px] text-[var(--color-text-secondary)]">+ {finding.symbol ? `${finding.symbol} — ` : ""}+ <span title={finding.path}>+ {finding.path}+ {lines}+ </span>+ </p>+ <p className="mt-1 text-[10px] text-[var(--color-text-secondary)]">+ <span className="text-[var(--color-text-tertiary)]">Why this change: </span>+ {finding.attribution.why}{" "}+ <span className="uppercase tracking-wider">+ ({finding.attribution.confidence} confidence)+ </span>+ </p>+ {finding.inspect && (+ <p+ className="mt-1 truncate font-mono text-[10px] text-[var(--color-text-secondary)]"+ title={finding.inspect}+ >+ {finding.inspect}+ </p>+ )}+ </li>+ );+}++function ChangeRiskCard({ data }: { data: RiskReportArtifactData }) {+ const directive = data.directive;+ const delta = data.health_delta;+ const tone: { label: string; className: string } =+ DIRECTIVE_TONE[directive?.status ?? "unknown"] ?? {+ label: "Not established",+ className: "text-[var(--color-text-secondary)]",+ };+ const pct =+ typeof data.risk_percentile === "number"+ ? Math.round(data.risk_percentile)+ : null;+ const findings = delta?.top_findings ?? [];+ const tests = data.impacted_tests?.tests_to_run ?? [];+ const fragile = data.fix_history?.files ?? [];+ const partial = delta ? delta.status !== "available" : false;++ return (+ <div className="space-y-3">+ {data.error && (+ <p role="alert" className="text-xs text-[var(--color-error)]">+ {String(data.error)}+ </p>+ )}++ {/* One verdict, named in words as well as colour. */}+ {directive && (+ <div>+ <p+ className={`text-[10px] font-medium uppercase tracking-wider ${tone.className}`}+ >+ {tone.label}+ </p>+ <p className="mt-0.5 text-xs text-[var(--color-text-primary)]">+ {directive.headline}+ </p>+ </div>+ )}++ {partial && delta && (+ <p role="status" className="text-[10px] text-[var(--color-warning)]">+ {delta.explanation}+ </p>+ )}++ {findings.length > 0 && (+ <div>+ <SectionTitle icon={ShieldAlert}>+ What this change made worse+ </SectionTitle>+ <ul className="space-y-1.5">+ {findings.slice(0, 3).map((finding) => (+ <ChangeFindingCard key={finding.id} finding={finding} />+ ))}+ </ul>+ </div>+ )}++ {/* One compact context row, not a second dashboard. */}+ <dl className="flex flex-wrap gap-x-4 gap-y-1 border-t border-[var(--color-border-default)] pt-2 text-[10px]">+ {data.ref && <ContextItem label="Change" value={String(data.ref)} />}+ {pct !== null && <ContextItem label="Diff shape" value={`p${pct}`} />}{data.review_priority && (- <StatRow label="Review priority" value={String(data.review_priority)} />+ <ContextItem label="Priority" value={String(data.review_priority)} />)}- {pct !== null && <StatRow label="Risk percentile" value={`p${pct}`} />}- {typeof data.score === "number" && (- <StatRow label="Score" value={data.score.toFixed(1)} />+ {delta?.scope && (+ <ContextItem+ label="Compared"+ value={`${delta.scope.analyzed}/${delta.scope.changed} files`}+ />)}- {data.classification && (- <p className="text-xs text-[var(--color-text-secondary)]">- {String(data.classification)}- </p>+ {fragile.length > 0 && (+ <ContextItem label="Fragile" value={`${fragile.length} files`} />)}- {data.warning && (- <p className="text-xs text-[var(--color-text-tertiary)]">{String(data.warning)}</p>+ {tests.length > 0 && (+ <ContextItem label="Tests" value={`${tests.length} to run`} />)}- </div>- );+ </dl>++ {(directive?.next_actions?.length ||+ delta ||+ tests.length > 0 ||+ fragile.length > 0 ||+ data.classification) && (+ <details>+ <summary className="cursor-pointer text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]">+ More detail+ </summary>+ <div className="mt-2 space-y-2">+ {directive?.next_actions?.length ? (+ <div>+ <SectionTitle icon={ArrowRight}>Next actions</SectionTitle>+ <ul className="space-y-0.5 text-[10px] text-[var(--color-text-secondary)]">+ {directive.next_actions.map((action) => (+ <li key={action}>{action}</li>+ ))}+ </ul>+ </div>+ ) : null}+ {tests.length > 0 && (+ <div>+ <SectionTitle icon={CheckCircle2}>Tests to run</SectionTitle>+ <ul className="space-y-0.5 font-mono text-[10px] text-[var(--color-text-secondary)]">+ {tests.slice(0, 10).map((test) => (+ <li key={test} className="truncate" title={test}>+ {test}+ </li>+ ))}+ </ul>+ </div>+ )}+ {fragile.length > 0 && (+ <div>+ <SectionTitle icon={GitBranch}>+ Historically fragile files+ </SectionTitle>+ <ul className="space-y-0.5 text-[10px] text-[var(--color-text-secondary)]">+ {fragile.slice(0, 5).map((file) => (+ <li key={file.path} className="flex justify-between gap-2">+ <span className="truncate font-mono" title={file.path}>+ {file.path}+ </span>+ <span className="shrink-0 tabular-nums text-[var(--color-text-tertiary)]">+ {file.churn} changes+ </span>+ </li>+ ))}+ </ul>+ </div>+ )}+ {delta && (+ <div className="space-y-1">+ <StatRow+ label="Introduced / worsened / resolved"+ value={`${delta.introduced} / ${delta.worsened} / ${delta.resolved}`}+ />+ {delta.findings_total > delta.findings_emitted && (+ <StatRow+ label="Findings shown"+ value={`${delta.findings_emitted} of ${delta.findings_total}`}+ />+ )}+ {delta.skipped && (+ <StatRow+ label="Files not analysed"+ value={delta.skipped.total}+ />+ )}+ </div>+ )}+ {typeof data.score === "number" && (+ <StatRow label="Diff-shape score" value={data.score.toFixed(1)} />+ )}+ {data.classification && (+ <p className="text-[10px] text-[var(--color-text-tertiary)]">+ {String(data.classification)}+ </p>+ )}+ {data.warning && (+ <p className="text-[10px] text-[var(--color-text-tertiary)]">+ {String(data.warning)}+ </p>+ )}+ </div>+ </details>+ )}+ </div>+ );+}++export function RiskReportRenderer({ data }: { data: RiskReportArtifactData }) {+ // get_change_risk returns a live-git review card, not per-file targets.+ if (+ data.error ||+ data.directive ||+ data.ref ||+ data.review_priority ||+ data.risk_percentile != null+ ) {+ return <ChangeRiskCard data={data} />;}const targets = normalizeRiskTargets(data);diff --git a/tests/unit/change_health/__init__.py b/tests/unit/change_health/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/unit/change_health/conftest.py b/tests/unit/change_health/conftest.pynew file mode 100644index 000000000..11069ce40--- /dev/null+++ b/tests/unit/change_health/conftest.py@@ -0,0 +1,125 @@+"""Synthetic Git repositories for change-health comparison tests.++Small, purpose-built repos rather than Repowise's own history: the comparison+must generalise across languages and change shapes, and a fixture that only+ever sees this codebase cannot show that.+"""++from __future__ import annotations++import subprocess+from collections.abc import Callable+from pathlib import Path++import pytest+++def git(repo: Path, *args: str) -> str:+ proc = subprocess.run(+ ["git", "-C", str(repo), *args],+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ check=True,+ )+ return proc.stdout+++class Repo:+ """A throwaway repository built one commit at a time."""++ def __init__(self, path: Path) -> None:+ self.path = path+ path.mkdir(parents=True, exist_ok=True)+ git(path, "init", "-q", "-b", "main")+ git(path, "config", "user.email", "[email protected]")+ git(path, "config", "user.name", "Dev")++ def write(self, relative: str, content: str) -> None:+ target = self.path / relative+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(content, encoding="utf-8")++ def remove(self, relative: str) -> None:+ git(self.path, "rm", "-q", relative)++ def move(self, source: str, destination: str) -> None:+ (self.path / destination).parent.mkdir(parents=True, exist_ok=True)+ git(self.path, "mv", source, destination)++ def commit(self, message: str, files: dict[str, str] | None = None) -> str:+ for relative, content in (files or {}).items():+ self.write(relative, content)+ git(self.path, "add", "-A")+ git(self.path, "commit", "-q", "-m", message, "--allow-empty")+ return git(self.path, "rev-parse", "HEAD").strip()+++def make_repo(tmp_path: Path) -> Callable[[str], Repo]:+ counter = {"n": 0}++ def factory(name: str = "repo") -> Repo:+ counter["n"] += 1+ return Repo(tmp_path / f"{name}{counter['n']}")++ return factory+++# -- source builders --------------------------------------------------------+# Each returns a function body whose complexity is driven by *branches*, so a+# test can ask for "the same function, more complex" in any language without+# hand-writing both revisions.+++def python_complex(name: str, branches: int, *, indent: str = "") -> str:+ lines = [f"{indent}def {name}(value):"]+ for i in range(branches):+ lines.append(f"{indent} if value == {i} and value > {i - 1}:")+ lines.append(f"{indent} value = value + {i}")+ lines.append(f"{indent} return value")+ return "\n".join(lines) + "\n"+++def typescript_complex(name: str, branches: int) -> str:+ lines = [f"export function {name}(value: number): number {{"]+ for i in range(branches):+ lines.append(f" if (value === {i} && value > {i - 1}) {{")+ lines.append(f" value = value + {i};")+ lines.append(" }")+ lines.append(" return value;")+ lines.append("}")+ return "\n".join(lines) + "\n"+++def go_complex(name: str, branches: int) -> str:+ lines = ["package main", "", f"func {name}(value int) int {{"]+ for i in range(branches):+ lines.append(f"\tif value == {i} && value > {i - 1} {{")+ lines.append(f"\t\tvalue = value + {i}")+ lines.append("\t}")+ lines.append("\treturn value")+ lines.append("}")+ return "\n".join(lines) + "\n"+++#: Language name to (path suffix, builder). Drives the cross-language tests so+#: no response-shaping code is language-specific.+LANGUAGES: dict[str, tuple[str, Callable[[str, int], str]]] = {+ "python": ("app.py", python_complex),+ "typescript": ("app.ts", typescript_complex),+ "go": ("app.go", go_complex),+}+++def python_io_in_loop(*, in_loop: bool) -> str:+ """A module whose sink is called from a loop, or not."""+ body = " for row in rows:\n fetch(row)\n" if in_loop else " fetch(rows[0])\n"+ return (+ "import sqlite3\n\n\n"+ "def fetch(row):\n"+ " conn = sqlite3.connect('db')\n"+ " return conn.execute('select 1', row).fetchall()\n\n\n"+ "def handler(rows):\n" + body + " return rows\n"+ )diff --git a/tests/unit/change_health/test_comparison.py b/tests/unit/change_health/test_comparison.pynew file mode 100644index 000000000..148965514--- /dev/null+++ b/tests/unit/change_health/test_comparison.py@@ -0,0 +1,391 @@+"""Base-versus-head comparison: identity, attribution, and honesty."""++from __future__ import annotations++import pytest++from repowise.core.analysis.change_health.service import ChangeHealthDeltaService, DeltaRequest++from .conftest import (+ LANGUAGES,+ Repo,+ python_complex,+ python_io_in_loop,+)+++def compare(repo: Repo, revspec: str | None = "HEAD", **kwargs):+ service = ChangeHealthDeltaService(repo_path=str(repo.path))+ return service.compare(DeltaRequest(str(repo.path), revspec, **kwargs))+++def kinds(delta) -> dict[str, int]:+ out: dict[str, int] = {}+ for finding in delta.findings:+ out[finding.change_kind] = out.get(finding.change_kind, 0) + 1+ return out+++# -- the core claim ---------------------------------------------------------+++def test_a_new_complex_function_is_introduced(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": python_complex("stable", 1)})+ repo.commit("add", {"app.py": python_complex("stable", 1) + python_complex("tangle", 14)})++ delta = compare(repo)++ assert delta.status == "available"+ assert delta.introduced_total >= 1+ introduced = [f for f in delta.findings if f.change_kind == "introduced"]+ assert any(f.symbol == "tangle" for f in introduced)+ assert all(f.attribution_basis == "added_lines" for f in introduced)+ assert all(f.attribution_confidence == "high" for f in introduced)+++def test_pure_line_movement_introduces_nothing(make_repo):+ """The whole point: moving a finding must not create one."""+ repo = make_repo()+ tangled = python_complex("tangle", 14)+ repo.commit("seed", {"app.py": tangled})+ repo.commit("shift", {"app.py": "# a new header comment\n" * 30 + tangled})++ delta = compare(repo)++ assert delta.introduced_total == 0+ assert delta.worsened_total == 0+ assert delta.unchanged_total >= 1+ assert delta.is_clean+++def test_a_function_growing_more_complex_is_worsened_not_introduced(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": python_complex("tangle", 6)})+ repo.commit("grow", {"app.py": python_complex("tangle", 26)})++ delta = compare(repo)++ assert delta.introduced_total == 0+ worsened = [f for f in delta.findings if f.change_kind == "worsened"]+ assert worsened, kinds(delta)+ assert worsened[0].symbol == "tangle"+ assert worsened[0].severity_before is not None+ assert worsened[0].severity_before != worsened[0].severity+++def test_removing_the_problem_resolves_it_and_surfaces_nothing(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": python_complex("tangle", 14)})+ repo.commit("simplify", {"app.py": python_complex("tangle", 1)})++ delta = compare(repo)++ assert delta.findings == []+ assert delta.resolved_total >= 1+ assert delta.is_clean+++def test_a_rename_carries_the_finding_across(make_repo):+ """A moved file is the same file; its findings are not new."""+ repo = make_repo()+ repo.commit("seed", {"app.py": python_complex("tangle", 14)})+ repo.move("app.py", "pkg/app.py")+ repo.commit("move")++ delta = compare(repo)++ assert delta.introduced_total == 0+ assert delta.resolved_total == 0+ assert delta.unchanged_total >= 1+++def test_deleting_a_file_surfaces_nothing_and_is_recorded_as_skipped(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": python_complex("tangle", 14), "keep.py": "x = 1\n"})+ repo.remove("app.py")+ repo.commit("delete")++ delta = compare(repo)++ assert delta.introduced_total == 0+ assert delta.skipped.get("app.py") == "deleted"+++# -- multiplicity -----------------------------------------------------------+++def test_a_second_hit_of_the_same_marker_is_one_introduced_finding(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": python_complex("one", 14)})+ repo.commit("add", {"app.py": python_complex("one", 14) + python_complex("two", 14)})++ delta = compare(repo)++ introduced = [f for f in delta.findings if f.change_kind == "introduced"]+ assert [f.symbol for f in introduced].count("two") == 1+ assert not any(f.symbol == "one" for f in introduced)+++def test_replacing_one_marker_hit_with_another_is_not_a_regression(make_repo):+ """Same symbol, same marker, rewritten body: one finding, not two."""+ repo = make_repo()+ repo.commit("seed", {"app.py": python_complex("tangle", 14)})+ repo.commit("rewrite", {"app.py": python_complex("tangle", 15)})++ delta = compare(repo)++ assert delta.introduced_total == 0+ assert delta.resolved_total == 0+++# -- attribution ------------------------------------------------------------+++def test_an_untouched_finding_in_an_edited_file_is_not_charged_to_added_lines(make_repo):+ """Editing elsewhere in a file must not claim its pre-existing problems."""+ repo = make_repo()+ original = python_complex("tangle", 14)+ repo.commit("seed", {"app.py": original})+ repo.commit("append", {"app.py": original + "\n\ndef helper():\n return 1\n"})++ delta = compare(repo)++ assert not any(f.symbol == "tangle" and f.change_kind == "introduced" for f in delta.findings)+++def test_a_new_file_is_attributed_as_a_new_file(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})+ repo.commit("add", {"new.py": python_complex("tangle", 14)})++ delta = compare(repo)++ introduced = [f for f in delta.findings if f.change_kind == "introduced"]+ assert introduced+ assert all(f.attribution_basis == "new_file" for f in introduced)+++def test_every_surfaced_finding_names_a_basis_and_confidence(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})+ repo.commit("add", {"app.py": python_complex("tangle", 20)})++ delta = compare(repo)++ for finding in delta.findings:+ assert finding.attribution_basis+ assert finding.attribution_confidence in {"high", "medium", "low"}+ assert finding.attribution_detail+++# -- cross-language ---------------------------------------------------------++[email protected]("language", sorted(LANGUAGES))+def test_the_same_change_shape_works_in_every_language(make_repo, language):+ """No language-specific code in the comparison or the response."""+ filename, build = LANGUAGES[language]+ repo = make_repo()+ repo.commit("seed", {filename: build("stable", 1)})+ repo.commit("add", {filename: build("stable", 1) + "\n" + build("tangle", 16)})++ delta = compare(repo)++ assert delta.status == "available"+ assert delta.scope.analyzed == 1+ assert any(f.path == filename for f in delta.findings), (+ f"{language}: {[(f.path, f.biomarker_type) for f in delta.findings]}"+ )+++# -- dimensions -------------------------------------------------------------+++def test_a_performance_finding_is_ranked_without_defect_impact(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": python_io_in_loop(in_loop=False)})+ repo.commit("loop", {"app.py": python_io_in_loop(in_loop=True)})++ delta = compare(repo)+ perf = [f for f in delta.findings if f.dimension == "performance"]++ assert perf, [(f.dimension, f.biomarker_type) for f in delta.findings]+ assert perf[0].health_impact == 0.0+ assert perf[0].opportunity_id+ assert perf[0].opportunity_rank is not None+++def test_findings_are_ordered_by_severity_not_by_dimension(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})+ repo.commit("add", {"app.py": python_complex("tangle", 26)})++ delta = compare(repo)++ severities = [f.severity for f in delta.findings]+ ranks = {"critical": 3, "high": 2, "medium": 1, "low": 0}+ assert severities == sorted(severities, key=lambda s: -ranks[s])+++# -- honesty ----------------------------------------------------------------+++def test_an_unsupported_file_is_skipped_and_never_looks_clean(make_repo):+ repo = make_repo()+ repo.commit("seed", {"README.md": "# hi\n"})+ repo.commit("edit", {"README.md": "# hi there\n"})++ delta = compare(repo)++ assert delta.findings == []+ assert delta.status == "unavailable"+ assert delta.skipped == {"README.md": "not_health_analyzable"}+ assert not delta.is_clean+++def test_a_partial_run_is_reported_as_partial(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})+ repo.commit(+ "mixed",+ {"app.py": python_complex("tangle", 16), "notes.md": "text\n"},+ )++ delta = compare(repo)++ assert delta.status == "partial"+ assert delta.skipped+ assert not delta.is_clean+++def test_a_generated_file_is_excluded_by_reason(make_repo):+ repo = make_repo()+ repo.commit("seed", {"gen.py": "# GENERATED CODE\nx = 1\n"})+ repo.commit("edit", {"gen.py": "# GENERATED CODE\n" + python_complex("tangle", 16)})++ delta = compare(repo)++ assert delta.skipped.get("gen.py") == "generated"+ assert delta.findings == []+ # Nothing was compared, so this is not a partial pass and not a clean one.+ assert delta.status == "unavailable"+ assert not delta.is_clean+++def test_a_bad_revspec_is_an_explicit_unsupported_range(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})++ delta = compare(repo, "no-such-ref")++ assert delta.status == "unsupported_range"+ assert delta.findings == []+ assert not delta.is_clean+++def test_clean_only_claims_the_analyzed_scope(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})+ repo.commit("edit", {"app.py": "x = 2\n"})++ delta = compare(repo)++ assert delta.is_clean+ assert "analyzed scope" in delta.explanation+++# -- revspec shapes ---------------------------------------------------------+++def test_working_tree_changes_are_compared_against_head(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})+ repo.write("app.py", python_complex("tangle", 16))++ delta = compare(repo, None)++ assert delta.head is not None and delta.head.kind == "working_tree"+ assert delta.introduced_total >= 1+++def test_two_dot_and_three_dot_ranges_resolve(make_repo):+ repo = make_repo()+ base = repo.commit("seed", {"app.py": "x = 1\n"})+ repo.commit("add", {"app.py": python_complex("tangle", 16)})++ two_dot = compare(repo, f"{base}..HEAD")+ three_dot = compare(repo, f"{base}...HEAD")++ assert two_dot.introduced_total == three_dot.introduced_total >= 1+ assert two_dot.base is not None and two_dot.base.sha == base+++def test_a_historical_commit_is_compared_against_its_own_parent(make_repo):+ """Not against HEAD, and not against whatever the index last saw."""+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})+ target = repo.commit("add", {"app.py": python_complex("tangle", 16)})+ repo.commit("later", {"other.py": "y = 2\n"})++ delta = compare(repo, target)++ assert delta.head is not None and delta.head.sha == target+ assert delta.introduced_total >= 1+ assert all(f.path == "app.py" for f in delta.findings)+++def test_a_root_commit_compares_against_the_empty_tree(make_repo):+ repo = make_repo()+ root = repo.commit("seed", {"app.py": python_complex("tangle", 16)})++ delta = compare(repo, root)++ assert delta.introduced_total >= 1+ assert all(f.attribution_basis == "new_file" for f in delta.findings)+++# -- filters and identity ---------------------------------------------------+++def test_exclusions_and_extensions_narrow_the_compared_scope(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})+ repo.commit(+ "add",+ {"app.py": python_complex("a", 16), "vendor/lib.py": python_complex("b", 16)},+ )++ excluded = compare(repo, "HEAD", exclude_patterns=("vendor/",))++ assert all(not f.path.startswith("vendor/") for f in excluded.findings)+ assert excluded.scope.changed == 1+++def test_change_finding_ids_are_deterministic_across_runs(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})+ repo.commit("add", {"app.py": python_complex("tangle", 16)})++ first = compare(repo)+ second = ChangeHealthDeltaService(repo_path=str(repo.path)).compare(+ DeltaRequest(str(repo.path), "HEAD")+ )++ assert [f.change_finding_id for f in first.findings] == [+ f.change_finding_id for f in second.findings+ ]+ assert all(f.change_finding_id.startswith("chf_") for f in first.findings)+++def test_the_analyzer_fingerprint_is_reported_on_both_sides(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})+ repo.commit("add", {"app.py": python_complex("tangle", 16)})++ delta = compare(repo)++ assert delta.fingerprint is not None+ assert delta.fingerprint.analyzer_version > 0+ assert delta.fingerprint.performance_model_version > 0+ assert delta.comparison_basis == "both_sides_analyzed"diff --git a/tests/unit/change_health/test_mcp_contract.py b/tests/unit/change_health/test_mcp_contract.pynew file mode 100644index 000000000..1cae7bb6b--- /dev/null+++ b/tests/unit/change_health/test_mcp_contract.py@@ -0,0 +1,231 @@+"""The agent-facing contract: what leads, what is opt-in, what survives pressure."""++from __future__ import annotations++import importlib+import json+from concurrent.futures import ThreadPoolExecutor+from types import SimpleNamespace++import pytest++from repowise.core.analysis.change_health.service import ChangeHealthDeltaService, DeltaRequest++from .conftest import python_complex, python_io_in_loop++MODULE = "repowise.server.mcp_server.tool_change_risk"+++def tool(monkeypatch):+ """The MCP tool, bound to a throwaway repo and with no index behind it."""+ module = importlib.import_module(MODULE)+ module._DELTA_SERVICES.clear()++ def bind(repo):+ async def _context(_alias=None):+ return SimpleNamespace(path=str(repo.path), alias=None)++ monkeypatch.setattr(module, "_resolve_repo_context", _context)+ return module++ return bind+++def seeded(make_repo, *, branches: int = 20):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})+ repo.commit("add", {"app.py": python_complex("tangle", branches)})+ return repo+++# -- ordering and size ------------------------------------------------------+++async def test_the_response_leads_with_the_directive_then_the_delta(tool, make_repo):+ module = tool(seeded(make_repo))++ result = await module.get_change_risk("HEAD", baseline=0)++ assert list(result)[:2] == ["directive", "health_delta"]+ assert result["directive"]["headline"]+ assert result["directive"]["next_actions"]+++async def test_the_default_response_stays_small_and_omits_score_mechanics(tool, make_repo):+ module = tool(seeded(make_repo))++ result = await module.get_change_risk("HEAD", baseline=0)++ assert len(json.dumps(result, default=str)) < 8000+ for field in ("drivers", "risk_authority", "features", "score_measures", "score_unit"):+ assert field not in result+ assert result["change_shape"]["diagnostics_via"] == ("get_change_risk(include=['diagnostics'])")+++async def test_diagnostics_are_a_projection_not_a_removal(tool, make_repo):+ module = tool(seeded(make_repo))++ expanded = await module.get_change_risk("HEAD", baseline=0, include=["diagnostics"])++ for field in ("drivers", "risk_authority", "features", "score_measures"):+ assert field in expanded+++async def test_legacy_ranked_fields_stay_at_the_top_level(tool, make_repo):+ """The chat summary and artifact renderer read these by name."""+ module = tool(seeded(make_repo))++ result = await module.get_change_risk("HEAD", baseline=0)++ for field in ("ref", "score", "risk_percentile", "review_priority", "classification"):+ assert field in result+++async def test_the_top_findings_cap_is_recoverable(tool, make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})+ repo.commit(+ "add",+ {"app.py": "".join(python_complex(f"tangle{i}", 18) for i in range(6))},+ )+ module = tool(repo)++ result = await module.get_change_risk("HEAD", baseline=0)+ delta = result["health_delta"]++ assert delta["findings_emitted"] <= 3+ if delta["findings_total"] > delta["findings_emitted"]:+ assert delta["findings_reduced_reason"] == "top_findings_cap"+ full = await module.get_change_risk("HEAD", baseline=0, include=["findings"])+ assert full["health_delta"]["findings_emitted"] == delta["findings_total"]+++# -- drill-down -------------------------------------------------------------+++async def test_a_surfaced_finding_can_be_expanded_by_its_id(tool, make_repo):+ module = tool(seeded(make_repo))++ listing = await module.get_change_risk("HEAD", baseline=0)+ row = listing["health_delta"]["top_findings"][0]+ assert row["inspect"] == f"get_change_risk(revspec='HEAD', finding_id={row['id']!r})"++ detail = await module.get_change_risk("HEAD", baseline=0, finding_id=row["id"])++ assert detail["finding"]["id"] == row["id"]+ assert "evidence" in detail["finding"]+++async def test_an_unknown_finding_id_says_so_and_lists_the_real_ones(tool, make_repo):+ module = tool(seeded(make_repo))++ result = await module.get_change_risk("HEAD", baseline=0, finding_id="chf_missing")++ assert "error" in result+ assert result["available"]+++# -- honesty at the surface -------------------------------------------------+++async def test_a_clean_change_says_analyzed_scope_not_safe(tool, make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})+ repo.commit("edit", {"app.py": "x = 2\n"})+ module = tool(repo)++ result = await module.get_change_risk("HEAD", baseline=0)++ assert result["directive"]["status"] == "clear_in_analyzed_scope"+ assert "analyzed scope" in result["health_delta"]["explanation"]+ assert "safe" not in result["directive"]["headline"].lower()+++async def test_a_partial_comparison_never_reads_as_clear(tool, make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})+ repo.commit("mixed", {"app.py": python_complex("tangle", 18), "notes.md": "text\n"})+ module = tool(repo)++ result = await module.get_change_risk("HEAD", baseline=0)++ assert result["health_delta"]["status"] == "partial"+ assert result["health_delta"]["skipped"]["total"] == 1+ assert any("not analysed" in reason for reason in result["directive"]["reasons"])+++async def test_performance_findings_do_not_by_themselves_demand_review(tool, make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": python_io_in_loop(in_loop=False)})+ repo.commit("loop", {"app.py": python_io_in_loop(in_loop=True)})+ module = tool(repo)++ result = await module.get_change_risk("HEAD", baseline=0)+ delta = result["health_delta"]++ assert delta["by_dimension"].get("performance")+ assert result["directive"]["status"] == "review_recommended"+ row = next(f for f in delta["top_findings"] if f["dimension"] == "performance")+ assert row["opportunity_id"]+ assert row["opportunity_rank"] is not None+++async def test_every_surfaced_finding_carries_an_attribution(tool, make_repo):+ module = tool(seeded(make_repo))++ result = await module.get_change_risk("HEAD", baseline=0)++ for row in result["health_delta"]["top_findings"]:+ assert row["attribution"]["basis"]+ assert row["attribution"]["confidence"] in {"high", "medium", "low"}+ assert row["attribution"]["why"]+++async def test_the_delta_names_the_analyzer_and_the_two_sides(tool, make_repo):+ module = tool(seeded(make_repo))++ delta = (await module.get_change_risk("HEAD", baseline=0))["health_delta"]++ assert delta["analyzer"]["analyzer_version"] > 0+ assert delta["base"]["sha"] and delta["head"]["sha"]+ assert delta["basis"] == "both_sides_analyzed"+++# -- caching and concurrency ------------------------------------------------+++def test_identical_concurrent_comparisons_run_once(make_repo, monkeypatch):+ repo = seeded(make_repo)+ service = ChangeHealthDeltaService(repo_path=str(repo.path))+ calls = {"n": 0}+ original = service.analyzer.analyze++ def counted(*args, **kwargs):+ calls["n"] += 1+ return original(*args, **kwargs)++ monkeypatch.setattr(service.analyzer, "analyze", counted)+ request = DeltaRequest(str(repo.path), "HEAD")++ with ThreadPoolExecutor(max_workers=4) as pool:+ results = [f.result() for f in [pool.submit(service.compare, request) for _ in range(4)]]++ # Two analyses (base and head) for one comparison, however many callers ask.+ assert calls["n"] == 2+ assert all(r.introduced_total == results[0].introduced_total for r in results)+++def test_a_working_tree_comparison_is_keyed_by_content_not_by_head(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})+ service = ChangeHealthDeltaService(repo_path=str(repo.path))+ request = DeltaRequest(str(repo.path), None)++ repo.write("app.py", python_complex("tangle", 18))+ first = service.compare(request)+ repo.write("app.py", "x = 1\n")+ second = service.compare(request)++ assert first.introduced_total >= 1+ assert second.introduced_total == 0diff --git a/tests/unit/change_health/test_regressions.py b/tests/unit/change_health/test_regressions.pynew file mode 100644index 000000000..4377328c0--- /dev/null+++ b/tests/unit/change_health/test_regressions.py@@ -0,0 +1,150 @@+"""Regressions for defects found in adversarial review of the comparison."""++from __future__ import annotations++from repowise.core.analysis.change_health.analyzer import MAX_FILE_BYTES+from repowise.core.analysis.change_health.identity import change_finding_id, finding_key+from repowise.core.analysis.change_health.matcher import FindingMatcher+from repowise.core.analysis.change_health.models import FindingKey+from repowise.core.analysis.change_health.service import ChangeHealthDeltaService, DeltaRequest+from repowise.core.analysis.change_health.sources import GitRevisionSource+from repowise.core.analysis.health import HealthFindingData, Severity++from .conftest import python_complex+++def finding(marker="long_method", *, line, severity=Severity.MEDIUM, symbol=None, impact=1.0):+ return HealthFindingData(+ biomarker_type=marker,+ severity=severity,+ file_path="app.py",+ function_name=symbol,+ line_start=line,+ line_end=line + 5,+ details={},+ health_impact=impact,+ reason="",+ dimension="defect",+ )+++# -- a base-side failure must not fabricate introduced findings --------------+++def test_a_base_side_read_failure_excludes_the_file_instead_of_inventing_findings(make_repo):+ """The file shrank below the size ceiling: its base blob is unreadable.++ Without both-sided bookkeeping every head finding in it reads as new, and+ the run still claims it compared both sides.+ """+ repo = make_repo()+ filler = "# pad\n" * (MAX_FILE_BYTES // 6)+ repo.commit("seed", {"app.py": filler + python_complex("tangle", 18)})+ repo.commit("shrink", {"app.py": python_complex("tangle", 18)})++ service = ChangeHealthDeltaService(repo_path=str(repo.path))+ delta = service.compare(DeltaRequest(str(repo.path), "HEAD"))++ assert delta.skipped.get("app.py") == "base_too_large"+ assert delta.introduced_total == 0+ assert delta.status in {"partial", "unavailable"}+ assert not delta.is_clean+++# -- pairing must be closest-first, not first-come-first-served --------------+++def test_an_unrelated_new_finding_does_not_absorb_a_moved_one():+ """First-come pairing hid the new finding and flagged the moved one."""+ base = [finding(line=100, severity=Severity.CRITICAL)]+ head = [+ finding(line=50, severity=Severity.MEDIUM), # genuinely new, listed first+ finding(line=102, severity=Severity.CRITICAL), # the same one, shifted+ ]++ result = FindingMatcher().match(base, head)+ by_line = {m.head.line_start: m for m in result.matched}++ assert by_line[102].kind == "unchanged"+ assert by_line[102].base is base[0]+ assert by_line[50].kind == "introduced"+ assert by_line[50].base is None+++def test_a_base_finding_left_over_inside_a_matched_group_is_resolved():+ base = [finding(line=10), finding(line=200)]+ head = [finding(line=12)]++ result = FindingMatcher().match(base, head)++ assert result.matched[0].kind == "unchanged"+ assert [f.line_start for f in result.resolved] == [200]+++# -- cat-file batch parsing --------------------------------------------------+++def test_a_path_with_a_space_missing_at_a_revision_does_not_derail_the_batch(make_repo):+ """``<sha>:<path> missing`` splits into three fields when the path has one."""+ repo = make_repo()+ repo.commit("seed", {"keep.py": "x = 1\n"})+ repo.commit("add", {"a file.py": "y = 2\n", "after.py": "z = 3\n"})++ source = GitRevisionSource(str(repo.path))+ pair = source.resolve("HEAD")+ # Read the added paths at the BASE revision, where neither exists yet.+ blobs = source.read(pair.base_sha, ["a file.py", "after.py", "keep.py"])++ assert "a file.py" not in blobs+ assert "after.py" not in blobs+ # The reader stayed in sync and still found the file that does exist.+ assert blobs["keep.py"] == b"x = 1\n"+++def test_a_change_touching_a_path_with_a_space_still_compares(make_repo):+ repo = make_repo()+ repo.commit("seed", {"keep.py": "x = 1\n"})+ repo.commit("add", {"my module.py": python_complex("tangle", 18)})++ service = ChangeHealthDeltaService(repo_path=str(repo.path))+ delta = service.compare(DeltaRequest(str(repo.path), "HEAD"))++ assert delta.status == "available"+ assert any(f.path == "my module.py" for f in delta.findings)+++# -- ephemeral ids are scoped to their comparison ----------------------------+++def test_the_same_finding_shape_in_two_comparisons_gets_two_ids():+ key = FindingKey("defect", "complex_method", "app.py", "handler")++ assert change_finding_id(key, 0, comparison="a:b") != change_finding_id(+ key, 0, comparison="c:d"+ )+ assert change_finding_id(key, 0, comparison="a:b") == change_finding_id(+ key, 0, comparison="a:b"+ )+++def test_an_id_from_one_revspec_does_not_resolve_against_another(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n"})+ first = repo.commit("add", {"app.py": python_complex("tangle", 18)})+ repo.commit("touch", {"other.py": "y = 1\n"})+ second = repo.commit("again", {"app.py": python_complex("tangle", 19)})++ service = ChangeHealthDeltaService(repo_path=str(repo.path))+ older = service.compare(DeltaRequest(str(repo.path), first))+ newer = service.compare(DeltaRequest(str(repo.path), second))++ older_ids = {f.change_finding_id for f in older.findings}+ newer_ids = {f.change_finding_id for f in newer.findings}+ assert older_ids.isdisjoint(newer_ids)+++def test_line_movement_alone_keeps_the_finding_key_stable():+ moved = finding(line=400, symbol="handler")+ original = finding(line=10, symbol="handler")++ assert finding_key(moved) == finding_key(original)diff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.pyindex 98bb337cf..bbc63deda 100644--- a/tests/unit/server/mcp/test_change_risk.py+++ b/tests/unit/server/mcp/test_change_risk.py@@ -53,7 +53,24 @@ async def test_get_change_risk_honors_riskignore_and_request_filters(tmp_path, m)assert result["working_tree"] is False- assert result["features"] == {+ # Raw model mechanics are a projection now; the default leads with action.+ assert "features" not in result+ assert "drivers" not in result+ assert "risk_authority" not in result+ assert result["directive"]["status"] in {+ "review_required",+ "review_recommended",+ "clear_in_analyzed_scope",+ "unknown",+ }+ diagnostics = await module.get_change_risk(+ "HEAD",+ extensions=["py", "md"],+ exclude_patterns=["docs/"],+ baseline=0,+ include=["diagnostics"],+ )+ assert diagnostics["features"] == {"la": 1,"ld": 0,"nf": 1,@@ -62,16 +79,16 @@ async def test_get_change_risk_honors_riskignore_and_request_filters(tmp_path, m"entropy": 0.0,"exp": 1,}+ assert diagnostics["risk_authority"]["primary_fields"] == [+ "risk_percentile",+ "classification",+ ]assert result["exclude_patterns"] == ["tests/", "docs/"]assert result["risk_percentile"] is Noneassert result["review_priority"] is Noneassert result["classification"] is Noneassert result["fallback_band"] in {"low", "moderate", "high"}- assert result["baseline_sample_size"] == 0- assert result["risk_authority"]["primary_fields"] == [- "risk_percentile",- "classification",- ]+ assert diagnostics["baseline_sample_size"] == 0# The per-field dictionary is identical on every call, so it is opt-in.assert "risk_scales" not in resultexpanded = await module.get_change_risk(@@ -125,7 +142,7 @@ async def test_get_change_risk_empty_diff_warns(tmp_path, monkeypatch) -> None:# Only a .py change exists; restricting to .md counts zero files.result = await module.get_change_risk(extensions=["md"], baseline=0)- assert result["features"]["nf"] == 0+ assert result["change_shape"]["score"] is not Noneassert "warning" in resultassert "no counted file changes" in result["warning"].lower()diff --git a/tests/unit/server/mcp/test_response_budget_contracts.py b/tests/unit/server/mcp/test_response_budget_contracts.pyindex 1c6c6017b..261338dce 100644--- a/tests/unit/server/mcp/test_response_budget_contracts.py+++ b/tests/unit/server/mcp/test_response_budget_contracts.py@@ -223,9 +223,11 @@ def test_adversarial_payload_goldens_fit_and_recover_in_one_lookup(for row in reductions)elif tool == "get_change_risk":- assert result["prior_fixes_total"] == 3- assert result["prior_fixes_emitted"] == 0- assert result["prior_fixes_reduced_reason"] == "response_budget"+ # Diff-shape history sheds before the action blocks: fix_history's rows+ # go first, and the directive/health_delta never do.+ assert result["fix_history"]["files_total"] == 3+ assert result["fix_history"]["files_emitted"] < 3+ assert result["fix_history"]["files_reduced_reason"] == "response_budget"elif tool == "get_health":assert result["high_leverage_files_total"] == 3assert result["high_leverage_files_emitted"] < 3diff --git a/tests/unit/server/test_mcp_change_risk_cross_repo.py b/tests/unit/server/test_mcp_change_risk_cross_repo.pyindex e94e221cd..81ebd4bf5 100644--- a/tests/unit/server/test_mcp_change_risk_cross_repo.py+++ b/tests/unit/server/test_mcp_change_risk_cross_repo.py@@ -303,9 +303,10 @@ def test_cross_repo_participates_in_the_response_ceiling(tmp_path: Path):from repowise.server.mcp_server.tool_change_risk import _SHED_ORDERassert "cross_repo" in _SHED_ORDER- # Shed after the run-list, before fix_history's numbers.- assert _SHED_ORDER.index("impacted_tests") < _SHED_ORDER.index("cross_repo")- assert _SHED_ORDER.index("cross_repo") < _SHED_ORDER.index("fix_history.files")+ # Shed after fix_history's rows, before the run-list: an agent keeps the+ # tests to run for longer than the list of downstream consumers.+ assert _SHED_ORDER.index("fix_history.files") < _SHED_ORDER.index("cross_repo")+ assert _SHED_ORDER.index("cross_repo") < _SHED_ORDER.index("impacted_tests")payload = {"score": 7.0,@@ -317,5 +318,6 @@ def test_cross_repo_participates_in_the_response_ceiling(tmp_path: Path):fit_to_budget(payload, _SHED_ORDER, collector)assert "cross_repo" not in payloadassert payload["truncated"] is True- # The score and its drivers are the answer and survive.- assert payload["fix_history"]["density"] == 1.0+ # The tests to run outlive both the consumer list and the fix record.+ assert payload["impacted_tests"]["tests_to_run"] == ["t.py"]+ assert "fix_history" not in payload