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
refactor(mcp): split tool_change_risk into a package of review blocks (#4058)
Raghav Chamadiya1af8c4109429
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.pydeleted file mode 100644index e09918b18..000000000--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py+++ /dev/null@@ -1,1604 +0,0 @@-"""MCP tool for live commit and range change-risk scoring."""--from __future__ import annotations--import asyncio-import contextlib-import shutil-import subprocess-import threading-import time-from collections import OrderedDict-from functools import partial-from typing import Any--import structlog-from sqlalchemy import select-from sqlalchemy.exc import OperationalError, SQLAlchemyError--from repowise.core.analysis.change_health.service import (- ChangeHealthDeltaService,- DeltaRequest,-)-from repowise.core.analysis.change_risk import (- FixHistoryUnavailableError,- change_risk_payload,- fixes_reachable_from,- normalize_extensions,- score_live_change,-)-from repowise.core.analysis.change_risk.features import revspec_head-from repowise.core.analysis.change_risk.render import LIMITS, size_text-from repowise.core.analysis.git_cli import path_filter-from repowise.core.analysis.prior_fix_impact import (- FixRecord,- PriorFixFile,- PriorFixImpact,- dominant_file,- parse_old_ranges,- summarize_prior_fixes,- unavailable_prior_fixes,- unsupported_prior_fixes,-)-from repowise.core.fsutils import comparable_path-from repowise.core.registry import mcp_tool_registry as mcp-from repowise.server.mcp_server._budget import OmissionCollector, cap_collection-from 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._change_health import (- patch_coverage_action as _patch_coverage_action,-)-from repowise.server.mcp_server._failure_shield import (- is_stale_server_import,- stale_server_notice,-)-from repowise.server.mcp_server._helpers import (- _get_repo,- _is_workspace_mode,- _resolve_repo_context,- _unsupported_repo_all,- attach_ignored_arguments,- is_missing_table,- resolve_enum_argument,-)-from repowise.server.mcp_server._meta import build_meta as _build_meta-from repowise.server.mcp_server._test_impact import (- cross_repo_tests,- tests_block_for,-)-from repowise.server.mcp_server._test_selection import (- UNAVAILABLE_REASON,- SelectionUnavailableError,- select_change_tests,- selection_block,-)--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.-_IMPACTED_TESTS_LIMIT = 10--#: Cap on the per-file prior-fix list, matching ``_IMPACTED_TESTS_LIMIT`` so both-#: per-file blocks in this response stay the same size.-_PRIOR_FIXES_LIMIT = 10--#: Caps on the cross-repo block. It answers "does this commit cross a repo-#: boundary", not "list every consumer" — get_blast_radius is the tool for the-#: full traversal, so both lists stay short and report their own overflow.-_CROSS_REPO_BREAKING_LIMIT = 5-_CROSS_REPO_CONSUMER_LIMIT = 10--#: Ceiling on the branch scan, bounded so a repository with hundreds of refs-#: cannot hold the response.-_BRANCH_OVERLAP_TIMEOUT_SECONDS = 20--#: Caps on the branch-overlap block. It answers "is anyone else editing these-#: files", not "list every branch", so both lists stay short and their tails go-#: to the omission store.-_BRANCH_OVERLAP_LIMIT = 5-_BRANCH_OVERLAP_FILES_LIMIT = 10--#: Cap on the files the index cannot link. The count is already in the block's-#: summary, so the names are supporting detail and their tail is recoverable.-_UNGROUPED_FILES_LIMIT = 10--# Compatibility projection for direct callers and older tests. The shared-# response contract remains the single source of truth for this order.-_SHED_ORDER = response_budget_shed_order("get_change_risk")--#: Per-field units and calibration. Identical on every call, so it is opt-in.-#: ``diagnostics`` carries the raw model mechanics; ``findings`` lifts the-#: top-findings cap. Both are projections, recoverable by an exact call.-#: ``evidence`` adds the change's evidence checklist, the record ``repowise-#: changes show`` and the REST change detail serve.-_INCLUDE_BLOCKS = frozenset({"scales", "diagnostics", "findings", "evidence"})--#: Score mechanics that are identical or near-identical on every call. Moved-#: behind ``include=["diagnostics"]`` so the action-first blocks lead.-#: ``score`` and ``fallback_band`` sit here rather than on the wire: the score-#: ranks 0.99 against lines added on every repository measured, so the-#: percentile beside it already carries the ranking and the raw number only-#: invited it being read as a danger verdict. Still recoverable, not deleted.-_DIAGNOSTIC_FIELDS = (- "risk_authority",- "score_measures",- "score_unit",- "baseline_sample_size",- "features",- "drivers",- "score",- "fallback_band",-)--#: Comparison mechanics on ``health_delta``: the analyzer fingerprint, the two-#: resolved revisions and the fixed limits text. Behind ``diagnostics`` too.-_HEALTH_DIAGNOSTIC_FIELDS = ("analyzer", "base", "head", "limits")--#: ``classification`` labels for the MCP surface. ``review_priority`` is a-#: tercile of the diff-shape rank, so the label names size, not a verdict.-#: Both ship only under ``include=["scales"]``: ``risk_percentile`` is the one-#: rank on the default response.-_DIFF_SIZE_LABELS = {- "low": "Below-typical diff size",- "moderate": "Typical diff size",- "high": "Above-typical diff size",-}---def _path_patterns(value: list[str] | str | None) -> tuple[str, ...]:- """A list of patterns, or one comma-separated string, as a pattern tuple.-- ``tuple("src/")`` would be one pattern per character, which matches nothing.- """- items = value.split(",") if isinstance(value, str) else value or ()- return tuple(item.strip() for item in items if item.strip())---async def _score_change(- repo_path: Any,- revspec: str | None,- extensions: list[str] | None,- exclude_patterns: list[str] | None,- include_paths: tuple[str, ...],- baseline: int,-) -> tuple[Any, dict | None]:- """Score the live change: ``(result, None)``, or ``(None, error reply)``."""- try:- result = await asyncio.to_thread(- score_live_change,- repo_path,- revspec,- extensions=tuple(extensions or ()),- exclude_patterns=tuple(exclude_patterns or ()),- include_paths=include_paths,- baseline=baseline,- )- except ValueError as exc:- return None, {"error": str(exc)}- except subprocess.CalledProcessError as exc:- detail = (exc.stderr or "").strip() or str(exc)- return None, {"error": f"Could not read change {revspec or 'HEAD'!r}: {detail}"}- except subprocess.TimeoutExpired:- return None, {"error": f"git timed out reading change {revspec or 'HEAD'!r}."}- except FileNotFoundError:- # Scoring spawns git from several readers, so the missing binary is- # named once here. Any other missing file is a real bug: re-raise.- if shutil.which("git") is not None:- raise- return None, {- "error": "git was not found on PATH; change risk reads the repository history."- }- return result, None---async def _attach_change_blocks(- ctx: Any,- payload: dict,- result: Any,- revspec: str | None,- extensions: list[str] | None,- changed_read: tuple[Any, Any],- collector: OmissionCollector,- include_paths: tuple[str, ...] = (),-) -> None:- """Attach the tests, patch coverage, prior fixes and cross-repo blocks, in that order."""- changed, changed_error = changed_read- payload["impacted_tests"] = await _impacted_tests_block(- ctx,- changed,- changed_error,- collector,- revspec=revspec,- working_tree=result.working_tree,- owned_excludes=result.owned_excludes,- )- patch_changed, patch_error, patch_label, patch_revspec = await _push_change(- str(ctx.path),- revspec,- result.working_tree,- normalize_extensions(tuple(extensions or ())),- result.riskignore_excludes + result.request_excludes,- (changed, changed_error),- include_paths,- )- patch = await _patch_coverage_block(- ctx, patch_changed, patch_error, patch_revspec, result, collector, label=patch_label- )- if patch is not None:- payload["patch_coverage"] = patch- prior_fixes = await _prior_fixes_block(ctx, changed, history_ref=result.history_ref)- if prior_fixes is not None:- # One fix record, not two. The blocks answered the same question- # with different arithmetic (decayed pressure vs raw count) and a- # reader had to work out which was which.- payload.setdefault("fix_history", {})["overlap"] = prior_fixes- alias = getattr(ctx, "alias", "")- # The join needs an open index per consumer repo, so it runs once for- # the whole change and the block distributes its rows.- impact = await cross_repo_tests(alias, sorted(changed))- cross_repo = _cross_repo_block(alias, sorted(changed), impact, collector)- if cross_repo is not None:- payload["cross_repo"] = cross_repo---def _include_blocks(include: list[str] | None, ignored: list[dict]) -> set[str]:- """The valid ``include`` blocks; unknown ones are recorded in ``ignored``."""- return {- block- for block in (include or [])- if resolve_enum_argument(block, _INCLUDE_BLOCKS, argument="include", ignored=ignored)- }---async def _attach_branch_blocks(- ctx: Any,- payload: dict,- changed: Any,- collector: OmissionCollector,- revspec: str | None,- finding_id: str | None,-) -> Any:- """Attach ``branch_overlap`` and return the independent-changes block, or None."""- # A drill-down returns one finding and nothing else, so neither block- # would reach the caller; both are pure cost on that path.- if finding_id is not None:- return None- overlap = await _branch_overlap_block(ctx, changed, collector, revspec_head(revspec))- if overlap is not None:- payload["branch_overlap"] = overlap- return await _independent_changes_block(ctx, changed, collector, revspec)---def _shape_payload(result: Any, include_set: set[str], revspec: str | None) -> tuple[dict, dict]:- """The score's payload trimmed to what the request asked for.-- Returns ``(payload, diagnostics)``; ``diagnostics`` holds the fields moved- out of the payload when the caller did not ask for them.- """- payload = change_risk_payload(result, scales="scales" in include_set)- if "scales" not in include_set:- payload.pop("review_priority")- payload.pop("classification")- elif payload.get("review_priority") in _DIFF_SIZE_LABELS:- payload["classification"] = _DIFF_SIZE_LABELS[payload["review_priority"]]- if "diagnostics" not in include_set:- diagnostics = {f: payload.pop(f) for f in _DIAGNOSTIC_FIELDS if f in payload}- # The fix record reads as files and counts; its rank is a second- # percentile beside ``risk_percentile`` and only invited comparing them.- payload["fix_history"].pop("percentile", None)- payload["fix_history"].pop("density", None)- else:- diagnostics = {}- # Fields that only repeat the request or say nothing: an empty exclude list,- # a working-tree flag after an explicit revspec, a false ``is_fix``.- if not payload["exclude_patterns"]:- del payload["exclude_patterns"]- if revspec is not None:- del payload["working_tree"]- if not payload["is_fix"]:- del payload["is_fix"]- return payload, diagnostics--- surface_order=60,- artifact_type="change_risk",- presentation="change_risk",- evidence_basis="measured",-)-async def get_change_risk(- revspec: str | None = None,- repo: str | None = None,- extensions: list[str] | None = None,- exclude_patterns: list[str] | None = None,- include_paths: list[str] | str | None = None,- baseline: int = 200,- include: list[str] | None = None,- finding_id: str | None = None,-) -> dict:- """Review a commit, ``base..head`` range, or uncommitted work.-- Leads with ``directive`` (what to do) and ``health_delta`` (what this- change newly made worse). Findings are reported only when the diff explains- them, name their ``attribution`` basis, and sort change-written above- pre-existing.-- ``directive.status`` is the verdict; ``partial`` health means code files- were skipped. ``risk_percentile`` and ``diff_shape`` measure diff size- only, not danger.-- ``impacted_tests`` is the ``impacted-tests`` selection; read ``run_all``.- ``patch_coverage`` is the share of changed executable lines stored coverage- ran; ``hints`` name tests to extend. ``fix_history`` is the changed files'- bug-fix record, ``overlap`` the past fixes on these exact lines,- ``branch_overlap`` other branches editing them. An empty diff returns- ``status: "nothing_to_score"``.-- Args:- 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/"]``.- include_paths: Gitignore-style paths to keep, as a list or one- comma-separated string, e.g. ``"src/api/,src/db/"``. Omit for all.- baseline: Recent commits sampled for percentile ranking; 0 disables it.- include: ``"findings"``, ``"diagnostics"`` (raw mechanics),- ``"scales"`` (units, tercile) or ``"evidence"`` (checklist).- finding_id: Expand one ``health_delta`` finding by its id.- """- if repo == "all":- return _unsupported_repo_all("get_change_risk")- ctx = await _resolve_repo_context(repo)- started = time.perf_counter()- includes = _path_patterns(include_paths)- result, error = await _score_change(- ctx.path, revspec, extensions, exclude_patterns, includes, baseline- )- if error is not None:- return error- ignored: list[dict] = []- include_set = _include_blocks(include, ignored)- payload, diagnostics = _shape_payload(result, include_set, revspec)- scored = await asyncio.to_thread(_scored_repo, str(ctx.path), revspec, result.working_tree)- if result.features.nf == 0:- return await _nothing_to_score(ctx, payload["ref"], scored, started)- payload = {"ref": payload.pop("ref"), "scored_repo": scored, **payload}- # Changed lines over the SAME file universe the score counted (its- # extensions, includes, riskignore + request excludes), so nothing downstream- # disagrees with the score about which files the change touches. Read once- # and shared: both blocks below need it and git is the expensive part.- # The test and fix blocks need the index and the cross-repo block needs- # workspace contracts, but the branch-overlap block needs only git, so every- # call pays this read rather than an unindexed repo going blind.- changed, changed_error = await _changed_in_scope(- str(ctx.path),- revspec,- normalize_extensions(tuple(extensions or ())),- result.riskignore_excludes + result.request_excludes,- includes,- working_tree=result.working_tree,- )- collector = OmissionCollector("get_change_risk", repo_root=ctx.path)- # 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),- includes,- )- )- try:- # A drill-down returns one finding and nothing else, so the tests,- # coverage, fix and cross-repo blocks would never reach the caller.- if finding_id is None:- await _attach_change_blocks(- ctx,- payload,- result,- revspec,- extensions,- (changed, changed_error),- collector,- includes,- )- independent = await _attach_branch_blocks(- ctx, payload, changed, collector, revspec, finding_id- )- 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)- payload["diff_shape"] = _diff_shape_sentence(payload, diagnostics)- if independent is not None:- payload["independent_changes"] = independent- _attach_health(- payload,- delta,- revspec,- expand="findings" in include_set,- diagnostics="diagnostics" in include_set,- )- if "evidence" in include_set:- payload["evidence"] = await _evidence_block(- ctx,- revspec,- result,- delta,- tuple(extensions or ()),- tuple(result.riskignore_excludes + result.request_excludes),- scoped=bool(extensions or exclude_patterns or includes or baseline != 200),- )- # 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- # there are none, so a degraded read keeps the repo-level staleness warning- # instead of reading as "nothing served, nothing to warn about".- payload["_meta"] = _build_meta(- timing_ms=(time.perf_counter() - started) * 1000,- repository=await _repository(ctx),- targets=sorted(changed) or None,- extra={"source": "live_git"},- )- attach_ignored_arguments(payload, ignored)- collector.attach(payload)- return payload---async def _evidence_block(- ctx: Any,- revspec: str | None,- result: Any,- delta: Any,- extensions: tuple[str, ...],- exclude_patterns: tuple[str, ...],- *,- scoped: bool,-) -> dict[str, Any]:- """The change's evidence checklist, reusing the score and delta already computed.-- A revspec naming a stored change, asked with no filters of the caller's- own, returns that change's kept record (building and keeping it when- there is none), so this and ``repowise changes show`` serve the same one.- """- from repowise.core.changes.collect import (- NO_INDEX,- change_evidence,- evidence_for_revspec,- stored_change_at,- )- from repowise.core.persistence.database import get_session-- kwargs: dict[str, Any] = {- "risk": result,- "health": delta,- "extensions": extensions,- "exclude_patterns": exclude_patterns,- }- no_index = NO_INDEX- session_factory = getattr(ctx, "session_factory", None)- if session_factory is not None:- try:- async with get_session(session_factory) as session:- repo = await _get_repo(session)- row = await stored_change_at(session, repo.id, ctx.path, revspec)- if row is not None and not scoped and not result.riskignore_excludes:- evidence = await change_evidence(- session, repo.id, ctx.path, row, risk=result, health=delta- )- else:- evidence = await evidence_for_revspec(- session, repo.id, ctx.path, revspec, row=row, **kwargs- )- return evidence.to_dict()- except (LookupError, SQLAlchemyError) as exc:- no_index = f"the index could not be read: {type(exc).__name__}: {exc}"- evidence = await evidence_for_revspec(None, "", ctx.path, revspec, no_index=no_index, **kwargs)- return evidence.to_dict()---#: 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.- from repowise.core.repo_config import health_rules_fingerprint-- service = ChangeHealthDeltaService(- repo_path=repo_path, rules_fingerprint=health_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 _compare_health(- repo_path: str,- revspec: str | None,- extensions: tuple[str, ...],- exclude_patterns: tuple[str, ...],- include_paths: 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, include_paths)- )- except Exception as exc:- log.warning("change_health_comparison_failed", revspec=revspec, error=str(exc))- explanation = (- stale_server_notice(exc)- if is_stale_server_import(exc)- else f"Health comparison failed: {exc}"- )- return ChangeHealthDelta(- status="unavailable",- explanation=explanation,- 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 (LookupError, SQLAlchemyError):- # No repository row is "no index", as in the sibling enrichments.- 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, diagnostics: bool = False-) -> None:- """Put the directive first and the compact delta second."""- block = _health_delta_block(delta, revspec=revspec)- if not diagnostics:- for key in _HEALTH_DIAGNOSTIC_FIELDS:- block.pop(key, None)- 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)- directive = _directive(delta, payload.get("impacted_tests"))- if action := _patch_coverage_action(payload.get("patch_coverage")):- directive["next_actions"].append(action)- ordered = {- "directive": directive,- "health_delta": block,- }- for key, value in payload.items():- ordered[key] = value- payload.clear()- payload.update(ordered)---def _scored_repo(path: str, revspec: str | None, working_tree: bool) -> dict[str, Any]:- """The checkout the change was read in and the commit its head resolved to.-- ``HEAD`` or a branch name resolves in the served checkout, not in the- caller's worktree, so naming both makes a review of the wrong tree visible.- Uncommitted work is marked, so its ``head`` does not read as the change.- """- from repowise.core import git_refs-- head = git_refs.resolve(path, revspec_head(revspec))[:12] or None- return {"root": path, "head": head, **({"working_tree": True} if working_tree else {})}---async def _nothing_to_score(ctx: Any, ref: str, scored: dict[str, Any], started: float) -> dict:- """An empty diff, reported as one rather than scored.-- Scoring it anyway produced a real-looking "Below typical" verdict, which- read as a clean bill of health on a tree the caller had not in fact pointed- at. Naming the tree makes a worktree mismatch visible here.- """- return {- "ref": ref,- "status": "nothing_to_score",- "warning": (- f"No counted file changes in {ref!r} "- "(check the revspec, extensions, or include/exclude filters)."- ),- "scored_repo": scored,- "_meta": _build_meta(- timing_ms=(time.perf_counter() - started) * 1000,- repository=await _repository(ctx),- extra={"source": "live_git"},- ),- }---def _diff_shape_sentence(payload: dict, diagnostics: dict) -> str:- """One line for what the diff-shape rank says, and what it does not.-- It replaced a block that restated four fields already at the top level and- was read in 2 of 118 recorded calls.- """- tail = " Mechanics: get_change_risk(include=['diagnostics'])." if diagnostics else ""- return f"{size_text(payload.get('risk_percentile'))}. {LIMITS}{tail}"---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.-- Only ``_meta`` needs it: the per-file blocks below resolve their own repo id- inside the session they query in.- """- from repowise.core.persistence.database import get_session-- session_factory = getattr(ctx, "session_factory", None)- if session_factory is None:- return None- try:- async with get_session(session_factory) as session:- return await _get_repo(session)- except (LookupError, SQLAlchemyError):- return None---def _filter_changed(- changed: dict[str, set[int]],- extensions: tuple[str, ...],- exclude_patterns: tuple[str, ...],- include_paths: tuple[str, ...] = (),-) -> dict[str, set[int]]:- """Restrict changed-line files to the score's counted universe.-- ``changed_lines`` applies no suffix/include/exclude filtering, so without- this a change scored ``nf == 0`` under a filter could still surface impacted- tests for the filtered-out files. Uses the score's own path rule.- """- counts = path_filter(extensions, exclude_patterns, include_paths)- return {path: lines for path, lines in changed.items() if counts(path)}---def _present(key: str, value: Any) -> dict[str, Any]:- """``{key: value}`` when *value* is truthy, else ``{}``: an optional field."""- return {key: value} if value else {}---def _cross_repo_consumers(enricher: Any, alias: str, changed_files: list[str]) -> list[dict]:- """Contract links in other repos whose provider file this change touches."""- consumers: list[dict[str, Any]] = []- seen: set[tuple[str, str, str, str]] = set()- for path in changed_files:- for link in enricher.get_contract_links_as_provider(alias, path):- if link.get("consumer_repo") == alias:- continue- # Keyed by contract too: collapsing loses a contract_id.- key = (- link.get("consumer_repo") or "",- link.get("consumer_file") or "",- link.get("contract_id") or "",- path,- )- if key in seen:- continue- seen.add(key)- consumers.append(- {- "provider_file": path,- "repo": link.get("consumer_repo"),- "file": link.get("consumer_file"),- "contract_id": link.get("contract_id"),- "contract_type": link.get("contract_type"),- "match_type": link.get("match_type"),- **_present("provider_symbol_id", link.get("provider_symbol_id")),- **_present("symbol_id", link.get("consumer_symbol_id")),- }- )- return consumers---def _breaking_row(change: dict[str, Any], cross: list[dict[str, Any]]) -> dict[str, Any]:- return {- "contract_id": change.get("contract_id"),- "type": change.get("contract_type"),- "kind": change.get("kind"),- "severity": change.get("severity"),- "detail": change.get("detail"),- "provider_file": change.get("provider_file"),- **_present("side", change.get("side")),- **_present("comparison_source", change.get("comparison_source")),- **_present("comparison_key", change.get("comparison_key")),- **_present("field_name", change.get("field_name")),- "impacted_repos": sorted({c.get("repo") or "" for c in cross}),- **_present("provider_symbol_id", change.get("provider_symbol_id")),- }---def _cross_repo_breaking(- enricher: Any, alias: str, touched: set[str]-) -> tuple[list[dict[str, Any]], int, int]:- """Capped breaking rows with consumers elsewhere, the total, and how many are incompatible."""- breaking: list[dict[str, Any]] = []- total = 0- incompatible = 0- for change in enricher.get_breaking_changes_for_repo(alias):- if change.get("provider_file") not in touched:- continue- cross = [c for c in change.get("impacted_consumers", []) if c.get("repo") != alias]- if not cross:- continue- total += 1- if change.get("severity") == "breaking":- incompatible += 1- if len(breaking) < _CROSS_REPO_BREAKING_LIMIT:- breaking.append(_breaking_row(change, cross))- return breaking, total, incompatible---def _cross_repo_summary(- consumers: list[dict], repos: list[str], totals: tuple[int, int], has_breaking_report: bool-) -> str:- breaking_total, breaking_incompatible_total = totals- summary = (- f"{len(consumers)} consumer link(s) in {len(repos)} other repo(s) touch the "- f"files this change edits"- )- if breaking_total:- warnings = breaking_total - breaking_incompatible_total- summary += (- f"; {breaking_incompatible_total} provider incompatibility finding(s) and "- f"{warnings} comparison warning(s) have endpoint-exposed consumers."- )- elif has_breaking_report:- summary += "; the last workspace update found no break in them."- else:- summary += "; no breaking-change report has been built for them."- return summary---def _consumer_test_files(shown: list[dict], impact: Any) -> set[str]:- """Test files recommended for the shown consumer rows."""- # Counted over the shown rows, so it never promises tests the cap dropped.- keys = {- (- row.get("repo") or "",- comparable_path(row.get("file") or ""),- row.get("contract_id") or "",- )- for row in shown- }- return {- rec.test_file- for rec in impact.recommendations- for path in rec.consumer_files- for cid in rec.contract_ids- if (rec.consumer_repo, path, cid) in keys- }---def _attach_consumer_tests(- shown: list[dict], impact: Any, collector: OmissionCollector | None-) -> str:- """Add each shown consumer's tests block; return the sentence counting them."""- for i, row in enumerate(shown):- row["tests"] = tests_block_for(- impact,- row.get("repo") or "",- row.get("file") or "",- row.get("contract_id") or "",- collector,- f"cross_repo.consumers[{i}].tests.tests_to_run",- )- test_files = _consumer_test_files(shown, impact)- undetermined = sum(1 for row in shown if row["tests"]["state"] == "unresolved")- return (- f" {len(test_files)} consumer test file(s) to run, "- f"{undetermined} link(s) could not be determined."- )---def _workspace_enricher(changed_files: list[str]) -> Any:- """The cross-repo enricher when it holds contract data for a non-empty change."""- from repowise.server.mcp_server import _state-- if not changed_files or not _is_workspace_mode():- return None- enricher = _state._cross_repo_enricher- if enricher is None or not getattr(enricher, "has_contract_data", False):- return None- return enricher---def _cross_repo_block(- alias: str,- changed_files: list[str],- impact: Any = None,- collector: OmissionCollector | None = None,-) -> dict[str, Any] | None:- """What this change does to consumers in other repos, or ``None``.-- Built from the last workspace update: contract links whose provider file the- change touches, and breaking-change entries for those files. ``None`` outside- workspace mode, without artifacts, or when nothing published is touched.- Never raises.- """- try:- enricher = _workspace_enricher(changed_files)- if enricher is None:- return None- consumers = _cross_repo_consumers(enricher, alias, changed_files)- has_breaking_report = bool(getattr(enricher, "has_breaking_changes", False))- breaking, breaking_total, incompatible = (- _cross_repo_breaking(enricher, alias, set(changed_files))- if has_breaking_report- else ([], 0, 0)- )- if not consumers and not breaking:- return None- report = enricher.get_breaking_changes() or {}- # A removed endpoint has no current link; its repos survive only as breaks.- repos = sorted(- {c["repo"] for c in consumers if c.get("repo")}- | {r for b in breaking for r in b["impacted_repos"] if r}- )- summary = _cross_repo_summary(- consumers, repos, (breaking_total, incompatible), has_breaking_report- )- shown = consumers[:_CROSS_REPO_CONSUMER_LIMIT]- if impact is not None:- summary += _attach_consumer_tests(shown, impact, collector)- return {- "consumers": shown,- "consumers_truncated": max(0, len(consumers) - _CROSS_REPO_CONSUMER_LIMIT),- "consumer_repos": repos,- "breaking_changes": breaking,- "breaking_changes_truncated": breaking_total - len(breaking),- # False: no detection pass ran, so an empty list is silence.- "breaking_changes_available": has_breaking_report,- # Dates the breaking half only; contract links carry no stamp.- "breaking_changes_as_of": report.get("generated_at") or None,- "summary": summary,- }- except Exception:- return None---def _empty_impacted(status: str, summary: str) -> dict[str, Any]:- """Uniform impacted-tests block for the paths where no selection was made.-- Nothing vouches for a subset there, so the block says ``run_all`` with the- reason, like a selection that cannot vouch for one. ``basis`` is ``none``- and nothing is named, so there is no ``tests_to_run_kind``, ``map_present``- or ``line_coverage``.- """- return {- "status": status,- "run_all": True,- "reasons": [summary, UNAVAILABLE_REASON],- "basis": "none",- "tests_to_run": [],- "total": 0,- "truncated": False,- "summary": summary,- }---def _serialize_missing(report: Any) -> dict[str, Any]:- """Render the detect_missing_tests dataclass buckets as JSON-ready dicts."""- return {- "untested_changes": [- {- "source_file": u.source_file,- "uncovered_lines": u.uncovered_lines,- "changed_line_count": u.changed_line_count,- }- for u in report.untested_changes- ],- "stale_test_candidates": [- {- "source_file": s.source_file,- "covering_test_files": s.covering_test_files,- "covering_test_ids_without_file": s.covering_test_ids_without_file,- }- for s in report.stale_test_candidates- ],- "covered": list(report.covered),- # ``no_data`` is "file not in the map" = unknown, never "untested".- "no_coverage_data": list(report.no_data),- }---async def _changed_in_scope(- repo_path: str,- revspec: str | None,- extensions: tuple[str, ...],- exclude_patterns: tuple[str, ...],- include_paths: tuple[str, ...] = (),- *,- working_tree: bool = False,-) -> tuple[dict[str, set[int]], tuple[str, str] | None]:- """The change's changed lines, restricted to the score's counted universe.-- Returns ``(changed, error)`` where *error* is a ``(status, summary)`` pair- for the degraded paths, so the callers below can report the same reason- without each re-reading git. Shared because ``changed_lines`` shells out and- two blocks want the same answer.- """- changed, error, _label = await _changed_with_label(- repo_path, revspec, extensions, exclude_patterns, include_paths, working_tree=working_tree- )- return changed, error---async def _changed_with_label(- repo_path: str,- revspec: str | None,- extensions: tuple[str, ...],- exclude_patterns: tuple[str, ...],- include_paths: tuple[str, ...] = (),- *,- working_tree: bool = False,- base: str | None = None,-) -> tuple[dict[str, set[int]], tuple[str, str] | None, str | None]:- """:func:`_changed_in_scope` plus the label ``changed_lines`` gave what it read.-- *base* widens a working-tree read to the merge-base with it, untracked- files included, and falls back to the plain working tree (label and all)- when the base does not resolve.- """- from repowise.core.analysis.changed_lines import changed_lines-- label = None- try:- changed, label = await asyncio.to_thread(- partial(- changed_lines,- repo_path,- revspec or "HEAD",- working_tree=working_tree,- base=base,- skip_untracked=exclude_patterns,- )- )- except ValueError as exc:- return {}, ("unknown", f"Could not read changed lines: {exc}"), label- except (subprocess.SubprocessError, OSError):- return {}, ("unknown", "Could not read changed lines from git."), label-- changed = _filter_changed(changed, extensions, exclude_patterns, include_paths)- if not changed:- return {}, ("no_source_line_changes", "No changed source lines to map to tests."), label- return changed, None, label---async def _prior_fixes_block(- ctx: Any, changed: dict[str, set[int]], *, history_ref: str | None = None-) -> dict[str, Any] | None:- """Past bug fixes that landed on the lines this change touches, or ``None``.-- Aggregate only. No inducing commit is named: file-level SZZ measured 74.5%- precision against the frozen judgments, enough to count fixes and not enough- to accuse the commit that caused one.-- ``overlapping_lines`` is the honest weak signal and is labelled as such. A- fix's stored ranges are line numbers on ITS parent commit while the change's- are line numbers now, so any commit in between shifts them; the count says- "this neighbourhood has been patched before", never "this exact line". The- per-file fix count beside it carries no such caveat.-- Silent (``None``) when the index has no fix events for these files at all,- so a repo without the feature grows no noise block. A read that *failed* is- not silent: it renders with ``status: "unavailable"``, because "we could not- look" and "nothing has broken here" are opposite claims about the change.- """- impact = await _read_prior_fixes(ctx, changed, history_ref=history_ref)- if impact.status == "unsupported" or (impact.status == "available" and impact.is_empty):- return None- if impact.status != "available":- return {- "status": impact.status,- "reason": impact.reason,- "summary": (- "The bug-fix record for these files could not be read, so this "- "change is not cleared of a fix-prone history."- ),- }-- shown = impact.files[:_PRIOR_FIXES_LIMIT]- block = {- "files": [_prior_fix_row(f) for f in shown],- "truncated": len(impact.files) > _PRIOR_FIXES_LIMIT,- "total_fixes": impact.total_fixes,- "files_with_fixes": impact.files_with_fixes,- "changed_lines_in_fixed_files": impact.changed_lines_in_fixed_files,- "line_overlap": impact.line_overlap_basis,- "summary": (- f"{impact.total_fixes} past bug-fix commit(s) touched "- f"{impact.files_with_fixes} of the changed file(s). "- "Line overlap is approximate (past ranges are numbered on their own "- "parent commit); the per-file counts are not."- ),- }- # Only over the files actually returned, so the sentence never names a path- # the reader cannot find anywhere else in the block.- top = dominant_file(shown)- if top is not None:- block["concentration"] = (- f"{top.file_path} carries {top.share_of_change:.0%} of the changed lines "- f"and {top.fix_count} past bug fix(es)."- )- return block---def _prior_fix_row(entry: PriorFixFile) -> dict[str, Any]:- """One core row on the wire, keeping the historical key set and order."""- row: dict[str, Any] = {- "file_path": entry.file_path,- "fix_count": entry.fix_count,- "overlapping_lines": entry.overlapping_lines,- "changed_lines": entry.changed_lines,- "share_of_change": entry.share_of_change,- }- # Absent rather than null when no event carried a date, as before.- if entry.last_fix_days_ago is not None:- row["last_fix_days_ago"] = entry.last_fix_days_ago- return row---async def _read_prior_fixes(- ctx: Any, changed: dict[str, set[int]], *, history_ref: str | None = None-) -> PriorFixImpact:- """Collect fix events from the index. Collection only; core summarizes.-- With *history_ref* (the score's own fix-history anchor) only fixes in that- ref's history count, so a reviewed commit and its successors in the index- are not read back as the ground it stood on.-- The four ways this can come back empty are not one state. An index that- predates fix events has nothing to read (``unsupported``), while a query- that failed means the record exists and was not read (``unavailable``).- Collapsing those is how a failure reads as a clean bill.- """- from repowise.core.persistence.database import get_session- from repowise.core.persistence.models import FixEvent-- session_factory = getattr(ctx, "session_factory", None)- if session_factory is None:- return unsupported_prior_fixes("this repository has no index to read a fix record from")- if not changed:- return unsupported_prior_fixes("no changed lines were counted for this change")-- try:- async with get_session(session_factory) as session:- repo_id = (await _get_repo(session)).id- res = await session.execute(- select(FixEvent).where(- FixEvent.repository_id == repo_id,- FixEvent.file_path.in_(list(changed)),- FixEvent.shape_kind == "code_fix",- )- )- events = list(res.scalars().all())- except LookupError:- return unsupported_prior_fixes("this repository is not indexed")- except OperationalError as exc:- # An index built before fix events existed has no table to read. That is- # silence, not an error the caller should have to handle -- but a locked- # or unreadable database is a real failure and falls through below.- if is_missing_table(exc):- return unsupported_prior_fixes("this index predates the bug-fix record")- return unavailable_prior_fixes(_read_failure(exc))- except SQLAlchemyError as exc:- return unavailable_prior_fixes(_read_failure(exc))-- if history_ref is not None:- try:- events = await _events_before(ctx, events, history_ref)- except FixHistoryUnavailableError as exc:- return unavailable_prior_fixes(f"could not place fixes in history: {exc}")-- return summarize_prior_fixes(- (- FixRecord(- fix_sha=event.fix_sha,- file_path=event.file_path,- old_ranges=parse_old_ranges(event.old_ranges_json),- committed_at=event.committed_at,- )- for event in events- ),- changed,- )---async def _events_before(ctx: Any, events: list[Any], history_ref: str) -> list[Any]:- """The fix events in *history_ref*'s history, so a review never counts itself."""- kept = await asyncio.to_thread(- fixes_reachable_from, str(ctx.path), history_ref, (event.fix_sha for event in events)- )- return [event for event in events if event.fix_sha in kept]---def _read_failure(exc: SQLAlchemyError) -> str:- """Name the failure without quoting the driver.-- Driver text can carry connection-string fragments, and this string goes out- on the wire. The class of failure is what a caller can act on; the detail- belongs in the server log, where it already is.- """- log.warning("prior_fixes_read_failed", error=str(exc))- return f"the fix record could not be read ({type(exc).__name__})"---async def _independent_changes_block(- ctx: Any,- changed: dict[str, set[int]],- collector: OmissionCollector,- revspec: str | None = None,-) -> dict[str, Any] | None:- """The changed files split into groups nothing in the index links, or ``None``.-- Silent for a single changed file and without an index: the split is a claim- about what the index holds, so an unindexed repo makes no claim at all.- """- from repowise.core.analysis.independent_changes import independent_changes- from repowise.core.git_refs import commit_file_sets- from repowise.core.persistence.database import get_session-- session_factory = getattr(ctx, "session_factory", None)- if session_factory is None or len(changed) < 2:- return None- # Returns [] without a git call for anything that is not a range, so the- # range test lives in one place rather than here as well.- sets = await asyncio.to_thread(commit_file_sets, str(ctx.path), revspec)- try:- async with get_session(session_factory) as session:- repo_id = (await _get_repo(session)).id- result = await independent_changes(session, repo_id, list(changed), commit_sets=sets)- except (LookupError, SQLAlchemyError):- return None- if result is None:- return None- block = result.to_dict()- cap_collection(- block,- "ungrouped_files",- block["ungrouped_files"],- _UNGROUPED_FILES_LIMIT,- collector,- label=(- f"independent_changes.ungrouped_files beyond cap={_UNGROUPED_FILES_LIMIT}"- ),- )- return block---def _scan_from_trunk(path: str, files: list[str], current: str) -> Any:- """The base lookup and the scan, both git, in one hop off the event loop.-- *current* is the reviewed change's head, so a branch reviewed from another- worktree is the change itself, not a rival to the served checkout's branch.- """- from repowise.core.analysis.branch_overlap import scan_branches- from repowise.core.git_refs import default_base-- return scan_branches(path, files, base=default_base(path), current=current)---async def _scan_overlap(ctx: Any, files: list[str], current: str = "HEAD") -> Any:- """Run the branch scan, with the index when one opens and without when it does not."""- from repowise.core.analysis.branch_overlap import rank_with_index- from repowise.core.persistence.database import get_session-- path = str(ctx.path)- scan = await asyncio.to_thread(_scan_from_trunk, path, files, current)- session_factory = getattr(ctx, "session_factory", None)- if session_factory is not None:- try:- # The session opens only for the index step, never across the git work.- async with get_session(session_factory) as session:- return await rank_with_index(session, (await _get_repo(session)).id, scan)- except (LookupError, SQLAlchemyError):- pass- return scan.overlap---async def _branch_overlap_block(- ctx: Any, changed: dict[str, set[int]], collector: OmissionCollector, current: str = "HEAD"-) -> dict[str, Any] | None:- """Other open branches editing the files this change edits, or ``None``.-- Git alone answers it, so a repo without an index still gets the block; an- index only ranks the shared files and adds the history rows. ``None`` when- no other branch overlaps, because an all-clear block is noise.- """- if not changed:- return None- try:- overlap = await asyncio.wait_for(- _scan_overlap(ctx, sorted(changed), current), timeout=_BRANCH_OVERLAP_TIMEOUT_SECONDS- )- except (TimeoutError, subprocess.SubprocessError, OSError):- return None-- block = overlap.to_dict()- if not block["branches"]:- return None- # Branches first: an entry the cap drops goes to the store whole, and only- # the entries that survive can carry an index the reader can find.- kept = cap_collection(- block,- "branches",- block["branches"],- _BRANCH_OVERLAP_LIMIT,- collector,- label=f"branch_overlap.branches beyond cap={_BRANCH_OVERLAP_LIMIT}",- )- for i, entry in enumerate(kept):- cap_collection(- entry,- "files",- entry["files"],- _BRANCH_OVERLAP_FILES_LIMIT,- collector,- label=f"branch_overlap.branches[{i}].files beyond cap={_BRANCH_OVERLAP_FILES_LIMIT}",- )- return block---async def _push_change(- repo_path: str,- revspec: str | None,- working_tree: bool,- extensions: tuple[str, ...],- exclude_patterns: tuple[str, ...],- scored: tuple[dict[str, set[int]], tuple[str, str] | None],- include_paths: tuple[str, ...] = (),-) -> tuple[dict[str, set[int]], tuple[str, str] | None, str | None, str | None]:- """``(changed, error, label, revspec)`` the patch-coverage block measures.-- An explicit *revspec* is measured as given (*scored*, the lines the score- read). Without one an agent is checking its work before a push, so the- patch is everything the push brings, the branch's commits and any- uncommitted edits, and the self-check does not shrink to the last commit- once it lands: ``<base>...working tree`` when dirty, ``<base>...HEAD``- when clean. No resolvable base keeps what was scored.- """- changed, error = scored- if revspec is not None:- return changed, error, None, revspec- base = await asyncio.to_thread(_push_base, repo_path)- if not working_tree and base == "HEAD":- return changed, error, None, revspec- branch = None if working_tree else f"{base}...HEAD"- found, found_error, label = await _changed_with_label(- repo_path,- branch,- extensions,- exclude_patterns,- include_paths,- working_tree=working_tree,- base=base,- )- if found_error is not None and branch is not None:- # No merge-base with the base (a shallow clone): measure the commit as scored.- return changed, error, None, revspec- return found, found_error, label, branch---def _push_base(repo_path: str) -> str:- """The branch a push of this checkout is reviewed against, else ``HEAD``.-- The base ``repowise coverage check`` would diff from in CI, so an agent's- self-check and the pull request's gate measure the same lines.- """- from repowise.core.analysis.change_risk.features import split_revspec- from repowise.core.ci.base import BaseNotFoundError, default_revspec-- try:- parts = split_revspec(default_revspec(repo_path))- except (BaseNotFoundError, subprocess.SubprocessError, OSError):- return "HEAD"- return parts[0] if parts else "HEAD"---async def _patch_coverage_block(- ctx: Any,- changed: dict[str, set[int]],- changed_error: tuple[str, str] | None,- revspec: str | None,- result: Any,- collector: OmissionCollector,- *,- label: str | None = None,-) -> dict[str, Any] | None:- """Share of the change's executable lines the stored coverage ran, or ``None``.-- The same computation ``repowise coverage check`` gates on, read from the- coverage the index stores. ``None`` when there is no index, no stored- coverage, or no readable change: ``impacted_tests`` already says why.- ``files`` lists only the files that need attention, riskiest first, capped;- the totals and ``file_counts`` still count every file. ``coverage.ignore``,- ``coverage.min_coverable_lines`` and the path-scoped ``coverage.gates``- apply as they do in the CLI gate; path gates read ``no_data`` on stale- coverage or invalid config, which ``scope.config_errors`` names. Each row- carries its file's risk, from the index and the checkout's git history, and- ``hints``: the test file to extend per uncovered range. ``project``- compares the ingest measured at the change's base commit with the current- one, when both exist (repo-wide totals only, never gated here).-- With no revspec, *changed* is what a push would bring (the caller diffs- from the merge-base with the push base, *label* names it). For uncommitted- work no commit names that code, so freshness is by time: ``current`` when- the last coverage ingest came after the newest edit to the changed files.- """- from repowise.core import git_refs- from repowise.core.analysis.health.coverage import configured_coverage- from repowise.core.analysis.health.coverage.freshness import newest_mtime- from repowise.core.analysis.patch_coverage import (- assess_risks,- attach_hints,- attach_history_delta,- attach_risk,- attention_rows,- read_git_fix_history,- read_index_facts,- read_test_hints,- stored_patch_coverage,- )- from repowise.core.persistence.database import get_session-- session_factory = getattr(ctx, "session_factory", None)- if session_factory is None or changed_error is not None or not changed:- return None- head_commit = mtime = None- if result.working_tree:- mtime = await asyncio.to_thread(newest_mtime, ctx.path, changed)- else:- head_commit = git_refs.resolve(str(ctx.path), revspec_head(revspec)) or None- base_commit = await asyncio.to_thread(- _change_base, str(ctx.path), revspec, label, result.working_tree- )- index: dict = {}- try:- async with get_session(session_factory) as session:- repo_id = (await _get_repo(session)).id- patch = await stored_patch_coverage(- session,- repo_id,- changed,- label=label or result.features.ref,- head_commit=head_commit,- config=configured_coverage(ctx.path),- working_tree_mtime=mtime,- repo_path=str(ctx.path),- )- # An unreadable index row leaves risk to git alone and hints null.- if patch is not None:- patch = await attach_history_delta(session, repo_id, patch, base_commit)- with contextlib.suppress(SQLAlchemyError):- index = await read_index_facts(- session, repo_id, [f.file_path for f in patch.files]- )- # Advice: read_test_hints logs any failure and returns None.- hints = await read_test_hints(- session,- repo_id,- patch,- repo_path=str(ctx.path),- head_commit=head_commit,- working_tree=result.working_tree,- )- if hints is not None:- patch = attach_hints(patch, hints)- except (LookupError, SQLAlchemyError):- return None- if patch is None:- return None- # Git after the session closes: no subprocess while a connection is held.- git = await asyncio.to_thread(- read_git_fix_history, str(ctx.path), revspec, working_tree=result.working_tree- )- patch = attach_risk(patch, assess_risks([f.file_path for f in patch.files], git, index))- block = patch.to_dict()- rows = [f.to_dict() for f in attention_rows(patch)]- if len(rows) > _IMPACTED_TESTS_LIMIT:- collector.add(- f"patch_coverage.files beyond cap={_IMPACTED_TESTS_LIMIT} "- f"({len(rows) - _IMPACTED_TESTS_LIMIT} dropped)",- [row["file_path"] for row in rows[_IMPACTED_TESTS_LIMIT:]],- )- block["files"] = rows[:_IMPACTED_TESTS_LIMIT]- return block---def _change_base(- repo_path: str, revspec: str | None, label: str | None, working_tree: bool-) -> str | None:- """The commit the measured change starts from, ``None`` when git cannot name it.-- A working-tree change starts at the merge-base with its push base when the- label names one (``<base>...working tree``), else at ``HEAD``.- """- from repowise.core import git_refs- from repowise.core.analysis.change_risk.features import split_revspec-- if not working_tree:- return git_refs.change_base(repo_path, revspec or "HEAD") or None- parts = split_revspec(label or "")- if parts is None:- return git_refs.resolve(repo_path, "HEAD") or None- return git_refs.change_base(repo_path, f"{parts[0]}...HEAD") or None---async def _impacted_tests_block(- ctx: Any,- changed: dict[str, set[int]],- changed_error: tuple[str, str] | None,- collector: OmissionCollector,- *,- revspec: str | None = None,- working_tree: bool = False,- owned_excludes: tuple[str, ...] = (),-) -> dict[str, Any]:- """The tests the change needs, decided as ``repowise impacted-tests`` decides them.-- The same collection and fail-closed selection (``test_collection`` then- ``select_tests``) over the whole change, every touched path included, so a- manifest, a conftest or a test that walks the source tree weighs here as it- does in CI. The caller's suffix, include and exclude filters do not narrow- it; only *owned_excludes*, repowise's own output, leaves it, as it leaves- every other block. ``line_coverage`` classifies the scored files' lines against- the per-test map, on the side of the diff the map was measured at.- Any failure degrades to a ``status`` string with ``run_all`` true and never- raises, so it cannot fail the surrounding score.- """- from repowise.core.analysis.changed_lines import change_set- from repowise.core.analysis.missing_test_signal import detect_missing_tests- from repowise.core.analysis.test_collection import query_lines- from repowise.core.persistence.database import get_session-- session_factory = getattr(ctx, "session_factory", None)- if session_factory is None:- return _empty_impacted(- "no_index", "No index; run `repowise init` to enable impacted tests."- )- if changed_error is not None:- return _empty_impacted(*changed_error)- try:- change = await asyncio.to_thread(- partial(- change_set,- str(ctx.path),- None if working_tree else revspec or "HEAD",- working_tree=working_tree,- exclude_patterns=owned_excludes,- )- )- except Exception: # git refused the change, or could not run- return _empty_impacted("unknown", "Could not read the change from git.")- try:- result, selection, _ = await select_change_tests(ctx.path, session_factory, change)- block = selection_block(- result, selection, collector, limit=_IMPACTED_TESTS_LIMIT, label="impacted_tests"- )- if not result["map_empty"]:- lines = query_lines(change, result["measured_commit"])- async with get_session(session_factory) as session:- repo_id = (await _get_repo(session)).id- report = await detect_missing_tests(- session, repo_id, {p: lines[p] for p in changed if p in lines}- )- block["line_coverage"] = _serialize_missing(report)- except SelectionUnavailableError as exc:- return _empty_impacted(exc.status, str(exc))- except LookupError:- return _empty_impacted("no_index", "No indexed repository; run `repowise init`.")- except SQLAlchemyError:- return _empty_impacted("unknown", "Could not read the index.")- except Exception as exc: # a selection bug must not take the score with it- log.warning("impacted_tests_failed", error=f"{type(exc).__name__}: {exc}")- return _empty_impacted("unknown", f"Selecting tests failed ({type(exc).__name__}).")- return blockdiff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/__init__.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/__init__.pynew file mode 100644index 000000000..036b4c24b--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/__init__.py@@ -0,0 +1,172 @@+"""MCP tool for live commit and range change-risk scoring.++``tool.py`` holds the registered tool; the sibling modules build its blocks.+Every name the single module had is re-exported here, and a block calls a+name tests patch through the package (``_pkg.<name>``), never by bare name,+or the patch stops reaching it.+"""++# ruff: noqa: F401++from __future__ import annotations++import asyncio+import contextlib+import shutil+import subprocess+import threading+import time+from collections import OrderedDict+from functools import partial+from typing import Any++import structlog+from sqlalchemy import select+from sqlalchemy.exc import OperationalError, SQLAlchemyError++from repowise.core.analysis.change_health.service import (+ ChangeHealthDeltaService,+ DeltaRequest,+)+from repowise.core.analysis.change_risk import (+ FixHistoryUnavailableError,+ change_risk_payload,+ fixes_reachable_from,+ normalize_extensions,+ score_live_change,+)+from repowise.core.analysis.change_risk.features import revspec_head+from repowise.core.analysis.change_risk.render import LIMITS, size_text+from repowise.core.analysis.git_cli import path_filter+from repowise.core.analysis.prior_fix_impact import (+ FixRecord,+ PriorFixFile,+ PriorFixImpact,+ dominant_file,+ parse_old_ranges,+ summarize_prior_fixes,+ unavailable_prior_fixes,+ unsupported_prior_fixes,+)+from repowise.core.fsutils import comparable_path+from repowise.core.registry import mcp_tool_registry as mcp+from repowise.server.mcp_server._budget import OmissionCollector, cap_collection+from 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._change_health import (+ patch_coverage_action as _patch_coverage_action,+)+from repowise.server.mcp_server._failure_shield import (+ is_stale_server_import,+ stale_server_notice,+)+from repowise.server.mcp_server._helpers import (+ _get_repo,+ _is_workspace_mode,+ _resolve_repo_context,+ _unsupported_repo_all,+ attach_ignored_arguments,+ is_missing_table,+ resolve_enum_argument,+)+from repowise.server.mcp_server._meta import build_meta as _build_meta+from repowise.server.mcp_server._test_impact import (+ cross_repo_tests,+ tests_block_for,+)+from repowise.server.mcp_server._test_selection import (+ UNAVAILABLE_REASON,+ SelectionUnavailableError,+ select_change_tests,+ selection_block,+)+from repowise.server.mcp_server.tool_change_risk.branches import (+ _BRANCH_OVERLAP_FILES_LIMIT,+ _BRANCH_OVERLAP_LIMIT,+ _BRANCH_OVERLAP_TIMEOUT_SECONDS,+ _UNGROUPED_FILES_LIMIT,+ _branch_overlap_block,+ _independent_changes_block,+ _scan_from_trunk,+ _scan_overlap,+)+from repowise.server.mcp_server.tool_change_risk.changed import (+ _change_base,+ _changed_in_scope,+ _changed_with_label,+ _filter_changed,+ _push_base,+ _push_change,+)+from repowise.server.mcp_server.tool_change_risk.cross_repo import (+ _CROSS_REPO_BREAKING_LIMIT,+ _CROSS_REPO_CONSUMER_LIMIT,+ _attach_consumer_tests,+ _breaking_row,+ _consumer_test_files,+ _cross_repo_block,+ _cross_repo_breaking,+ _cross_repo_consumers,+ _cross_repo_summary,+ _present,+ _workspace_enricher,+)+from repowise.server.mcp_server.tool_change_risk.health import (+ _DELTA_SERVICE_CAPACITY,+ _DELTA_SERVICES,+ _DELTA_SERVICES_LOCK,+ _attach_health_references,+ _compare_health,+ _delta_service,+ _evidence_block,+ _repository,+ _scored_repo,+ log,+)+from repowise.server.mcp_server.tool_change_risk.impacted import (+ _IMPACTED_TESTS_LIMIT,+ _empty_impacted,+ _impacted_tests_block,+ _serialize_missing,+)+from repowise.server.mcp_server.tool_change_risk.patch_coverage import (+ _attention_files,+ _enrich_patch,+ _patch_coverage_block,+)+from repowise.server.mcp_server.tool_change_risk.payload import (+ _DIAGNOSTIC_FIELDS,+ _DIFF_SIZE_LABELS,+ _HEALTH_DIAGNOSTIC_FIELDS,+ _INCLUDE_BLOCKS,+ _SHED_ORDER,+ _attach_health,+ _diff_shape_sentence,+ _drill_down,+ _include_blocks,+ _path_patterns,+ _shape_payload,+)+from repowise.server.mcp_server.tool_change_risk.prior_fixes import (+ _PRIOR_FIXES_LIMIT,+ _events_before,+ _prior_fix_row,+ _prior_fixes_block,+ _read_failure,+ _read_prior_fixes,+)+from repowise.server.mcp_server.tool_change_risk.tool import (+ _attach_branch_blocks,+ _attach_change_blocks,+ _nothing_to_score,+ _score_change,+ get_change_risk,+)diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/branches.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/branches.pynew file mode 100644index 000000000..b75a94543--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/branches.py@@ -0,0 +1,143 @@+"""Branch overlap and independent changes: who else edits these files."""++from __future__ import annotations++import asyncio+import subprocess+from typing import Any++from sqlalchemy.exc import SQLAlchemyError++# Patchable names are read off the package at call time so patches reach them.+from repowise.server.mcp_server import tool_change_risk as _pkg+from repowise.server.mcp_server._budget import OmissionCollector, cap_collection++#: Ceiling on the branch scan, bounded so a repository with hundreds of refs+#: cannot hold the response.+_BRANCH_OVERLAP_TIMEOUT_SECONDS = 20++#: Caps on the branch-overlap block. It answers "is anyone else editing these+#: files", not "list every branch", so both lists stay short and their tails go+#: to the omission store.+_BRANCH_OVERLAP_LIMIT = 5+_BRANCH_OVERLAP_FILES_LIMIT = 10++#: Cap on the files the index cannot link. The count is already in the block's+#: summary, so the names are supporting detail and their tail is recoverable.+_UNGROUPED_FILES_LIMIT = 10+++async def _independent_changes_block(+ ctx: Any,+ changed: dict[str, set[int]],+ collector: OmissionCollector,+ revspec: str | None = None,+) -> dict[str, Any] | None:+ """The changed files split into groups nothing in the index links, or ``None``.++ Silent for a single changed file and without an index: the split is a claim+ about what the index holds, so an unindexed repo makes no claim at all.+ """+ from repowise.core.analysis.independent_changes import independent_changes+ from repowise.core.git_refs import commit_file_sets+ from repowise.core.persistence.database import get_session++ session_factory = getattr(ctx, "session_factory", None)+ if session_factory is None or len(changed) < 2:+ return None+ # Returns [] without a git call for anything that is not a range, so the+ # range test lives in one place rather than here as well.+ sets = await asyncio.to_thread(commit_file_sets, str(ctx.path), revspec)+ try:+ async with get_session(session_factory) as session:+ repo_id = (await _pkg._get_repo(session)).id+ result = await independent_changes(session, repo_id, list(changed), commit_sets=sets)+ except (LookupError, SQLAlchemyError):+ return None+ if result is None:+ return None+ block = result.to_dict()+ cap_collection(+ block,+ "ungrouped_files",+ block["ungrouped_files"],+ _UNGROUPED_FILES_LIMIT,+ collector,+ label=(+ f"independent_changes.ungrouped_files beyond cap={_UNGROUPED_FILES_LIMIT}"+ ),+ )+ return block+++def _scan_from_trunk(path: str, files: list[str], current: str) -> Any:+ """The base lookup and the scan, both git, in one hop off the event loop.++ *current* is the reviewed change's head, so a branch reviewed from another+ worktree is the change itself, not a rival to the served checkout's branch.+ """+ from repowise.core.analysis.branch_overlap import scan_branches+ from repowise.core.git_refs import default_base++ return scan_branches(path, files, base=default_base(path), current=current)+++async def _scan_overlap(ctx: Any, files: list[str], current: str = "HEAD") -> Any:+ """Run the branch scan, with the index when one opens and without when it does not."""+ from repowise.core.analysis.branch_overlap import rank_with_index+ from repowise.core.persistence.database import get_session++ path = str(ctx.path)+ scan = await asyncio.to_thread(_pkg._scan_from_trunk, path, files, current)+ session_factory = getattr(ctx, "session_factory", None)+ if session_factory is not None:+ try:+ # The session opens only for the index step, never across the git work.+ async with get_session(session_factory) as session:+ return await rank_with_index(session, (await _pkg._get_repo(session)).id, scan)+ except (LookupError, SQLAlchemyError):+ pass+ return scan.overlap+++async def _branch_overlap_block(+ ctx: Any, changed: dict[str, set[int]], collector: OmissionCollector, current: str = "HEAD"+) -> dict[str, Any] | None:+ """Other open branches editing the files this change edits, or ``None``.++ Git alone answers it, so a repo without an index still gets the block; an+ index only ranks the shared files and adds the history rows. ``None`` when+ no other branch overlaps, because an all-clear block is noise.+ """+ if not changed:+ return None+ try:+ overlap = await asyncio.wait_for(+ _pkg._scan_overlap(ctx, sorted(changed), current), timeout=_BRANCH_OVERLAP_TIMEOUT_SECONDS+ )+ except (TimeoutError, subprocess.SubprocessError, OSError):+ return None++ block = overlap.to_dict()+ if not block["branches"]:+ return None+ # Branches first: an entry the cap drops goes to the store whole, and only+ # the entries that survive can carry an index the reader can find.+ kept = cap_collection(+ block,+ "branches",+ block["branches"],+ _BRANCH_OVERLAP_LIMIT,+ collector,+ label=f"branch_overlap.branches beyond cap={_BRANCH_OVERLAP_LIMIT}",+ )+ for i, entry in enumerate(kept):+ cap_collection(+ entry,+ "files",+ entry["files"],+ _BRANCH_OVERLAP_FILES_LIMIT,+ collector,+ label=f"branch_overlap.branches[{i}].files beyond cap={_BRANCH_OVERLAP_FILES_LIMIT}",+ )+ return blockdiff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/changed.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/changed.pynew file mode 100644index 000000000..6f9f428a4--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/changed.py@@ -0,0 +1,163 @@+"""The change's changed lines, scoped to the files the score counted."""++from __future__ import annotations++import asyncio+import subprocess+from functools import partial++from repowise.core.analysis.git_cli import path_filter+++def _filter_changed(+ changed: dict[str, set[int]],+ extensions: tuple[str, ...],+ exclude_patterns: tuple[str, ...],+ include_paths: tuple[str, ...] = (),+) -> dict[str, set[int]]:+ """Restrict changed-line files to the score's counted universe.++ ``changed_lines`` applies no suffix/include/exclude filtering, so without+ this a change scored ``nf == 0`` under a filter could still surface impacted+ tests for the filtered-out files. Uses the score's own path rule.+ """+ counts = path_filter(extensions, exclude_patterns, include_paths)+ return {path: lines for path, lines in changed.items() if counts(path)}+++async def _changed_in_scope(+ repo_path: str,+ revspec: str | None,+ extensions: tuple[str, ...],+ exclude_patterns: tuple[str, ...],+ include_paths: tuple[str, ...] = (),+ *,+ working_tree: bool = False,+) -> tuple[dict[str, set[int]], tuple[str, str] | None]:+ """The change's changed lines, restricted to the score's counted universe.++ Returns ``(changed, error)`` where *error* is a ``(status, summary)`` pair+ for the degraded paths, so the callers below can report the same reason+ without each re-reading git. Shared because ``changed_lines`` shells out and+ two blocks want the same answer.+ """+ changed, error, _label = await _changed_with_label(+ repo_path, revspec, extensions, exclude_patterns, include_paths, working_tree=working_tree+ )+ return changed, error+++async def _changed_with_label(+ repo_path: str,+ revspec: str | None,+ extensions: tuple[str, ...],+ exclude_patterns: tuple[str, ...],+ include_paths: tuple[str, ...] = (),+ *,+ working_tree: bool = False,+ base: str | None = None,+) -> tuple[dict[str, set[int]], tuple[str, str] | None, str | None]:+ """:func:`_changed_in_scope` plus the label ``changed_lines`` gave what it read.++ *base* widens a working-tree read to the merge-base with it, untracked+ files included, and falls back to the plain working tree (label and all)+ when the base does not resolve.+ """+ from repowise.core.analysis.changed_lines import changed_lines++ label = None+ try:+ changed, label = await asyncio.to_thread(+ partial(+ changed_lines,+ repo_path,+ revspec or "HEAD",+ working_tree=working_tree,+ base=base,+ skip_untracked=exclude_patterns,+ )+ )+ except ValueError as exc:+ return {}, ("unknown", f"Could not read changed lines: {exc}"), label+ except (subprocess.SubprocessError, OSError):+ return {}, ("unknown", "Could not read changed lines from git."), label++ changed = _filter_changed(changed, extensions, exclude_patterns, include_paths)+ if not changed:+ return {}, ("no_source_line_changes", "No changed source lines to map to tests."), label+ return changed, None, label+++async def _push_change(+ repo_path: str,+ revspec: str | None,+ working_tree: bool,+ extensions: tuple[str, ...],+ exclude_patterns: tuple[str, ...],+ scored: tuple[dict[str, set[int]], tuple[str, str] | None],+ include_paths: tuple[str, ...] = (),+) -> tuple[dict[str, set[int]], tuple[str, str] | None, str | None, str | None]:+ """``(changed, error, label, revspec)`` the patch-coverage block measures.++ An explicit *revspec* is measured as given (*scored*, the lines the score+ read). Without one an agent is checking its work before a push, so the+ patch is everything the push brings, the branch's commits and any+ uncommitted edits, and the self-check does not shrink to the last commit+ once it lands: ``<base>...working tree`` when dirty, ``<base>...HEAD``+ when clean. No resolvable base keeps what was scored.+ """+ changed, error = scored+ if revspec is not None:+ return changed, error, None, revspec+ base = await asyncio.to_thread(_push_base, repo_path)+ if not working_tree and base == "HEAD":+ return changed, error, None, revspec+ branch = None if working_tree else f"{base}...HEAD"+ found, found_error, label = await _changed_with_label(+ repo_path,+ branch,+ extensions,+ exclude_patterns,+ include_paths,+ working_tree=working_tree,+ base=base,+ )+ if found_error is not None and branch is not None:+ # No merge-base with the base (a shallow clone): measure the commit as scored.+ return changed, error, None, revspec+ return found, found_error, label, branch+++def _push_base(repo_path: str) -> str:+ """The branch a push of this checkout is reviewed against, else ``HEAD``.++ The base ``repowise coverage check`` would diff from in CI, so an agent's+ self-check and the pull request's gate measure the same lines.+ """+ from repowise.core.analysis.change_risk.features import split_revspec+ from repowise.core.ci.base import BaseNotFoundError, default_revspec++ try:+ parts = split_revspec(default_revspec(repo_path))+ except (BaseNotFoundError, subprocess.SubprocessError, OSError):+ return "HEAD"+ return parts[0] if parts else "HEAD"+++def _change_base(+ repo_path: str, revspec: str | None, label: str | None, working_tree: bool+) -> str | None:+ """The commit the measured change starts from, ``None`` when git cannot name it.++ A working-tree change starts at the merge-base with its push base when the+ label names one (``<base>...working tree``), else at ``HEAD``.+ """+ from repowise.core import git_refs+ from repowise.core.analysis.change_risk.features import split_revspec++ if not working_tree:+ return git_refs.change_base(repo_path, revspec or "HEAD") or None+ parts = split_revspec(label or "")+ if parts is None:+ return git_refs.resolve(repo_path, "HEAD") or None+ return git_refs.change_base(repo_path, f"{parts[0]}...HEAD") or Nonediff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/cross_repo.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/cross_repo.pynew file mode 100644index 000000000..4aad57320--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/cross_repo.py@@ -0,0 +1,224 @@+"""What a change does to consumers in other workspace repos."""++from __future__ import annotations++from typing import Any++from repowise.core.fsutils import comparable_path++# Patchable names are read off the package at call time so patches reach them.+from repowise.server.mcp_server import tool_change_risk as _pkg+from repowise.server.mcp_server._budget import OmissionCollector+from repowise.server.mcp_server._test_impact import (+ tests_block_for,+)++#: Caps on the cross-repo block. It answers "does this commit cross a repo+#: boundary", not "list every consumer" — get_blast_radius is the tool for the+#: full traversal, so both lists stay short and report their own overflow.+_CROSS_REPO_BREAKING_LIMIT = 5+_CROSS_REPO_CONSUMER_LIMIT = 10+++def _present(key: str, value: Any) -> dict[str, Any]:+ """``{key: value}`` when *value* is truthy, else ``{}``: an optional field."""+ return {key: value} if value else {}+++def _cross_repo_consumers(enricher: Any, alias: str, changed_files: list[str]) -> list[dict]:+ """Contract links in other repos whose provider file this change touches."""+ consumers: list[dict[str, Any]] = []+ seen: set[tuple[str, str, str, str]] = set()+ for path in changed_files:+ for link in enricher.get_contract_links_as_provider(alias, path):+ if link.get("consumer_repo") == alias:+ continue+ # Keyed by contract too: collapsing loses a contract_id.+ key = (+ link.get("consumer_repo") or "",+ link.get("consumer_file") or "",+ link.get("contract_id") or "",+ path,+ )+ if key in seen:+ continue+ seen.add(key)+ consumers.append(+ {+ "provider_file": path,+ "repo": link.get("consumer_repo"),+ "file": link.get("consumer_file"),+ "contract_id": link.get("contract_id"),+ "contract_type": link.get("contract_type"),+ "match_type": link.get("match_type"),+ **_present("provider_symbol_id", link.get("provider_symbol_id")),+ **_present("symbol_id", link.get("consumer_symbol_id")),+ }+ )+ return consumers+++def _breaking_row(change: dict[str, Any], cross: list[dict[str, Any]]) -> dict[str, Any]:+ return {+ "contract_id": change.get("contract_id"),+ "type": change.get("contract_type"),+ "kind": change.get("kind"),+ "severity": change.get("severity"),+ "detail": change.get("detail"),+ "provider_file": change.get("provider_file"),+ **_present("side", change.get("side")),+ **_present("comparison_source", change.get("comparison_source")),+ **_present("comparison_key", change.get("comparison_key")),+ **_present("field_name", change.get("field_name")),+ "impacted_repos": sorted({c.get("repo") or "" for c in cross}),+ **_present("provider_symbol_id", change.get("provider_symbol_id")),+ }+++def _cross_repo_breaking(+ enricher: Any, alias: str, touched: set[str]+) -> tuple[list[dict[str, Any]], int, int]:+ """Capped breaking rows with consumers elsewhere, the total, and how many are incompatible."""+ breaking: list[dict[str, Any]] = []+ total = 0+ incompatible = 0+ for change in enricher.get_breaking_changes_for_repo(alias):+ if change.get("provider_file") not in touched:+ continue+ cross = [c for c in change.get("impacted_consumers", []) if c.get("repo") != alias]+ if not cross:+ continue+ total += 1+ if change.get("severity") == "breaking":+ incompatible += 1+ if len(breaking) < _CROSS_REPO_BREAKING_LIMIT:+ breaking.append(_breaking_row(change, cross))+ return breaking, total, incompatible+++def _cross_repo_summary(+ consumers: list[dict], repos: list[str], totals: tuple[int, int], has_breaking_report: bool+) -> str:+ breaking_total, breaking_incompatible_total = totals+ summary = (+ f"{len(consumers)} consumer link(s) in {len(repos)} other repo(s) touch the "+ f"files this change edits"+ )+ if breaking_total:+ warnings = breaking_total - breaking_incompatible_total+ summary += (+ f"; {breaking_incompatible_total} provider incompatibility finding(s) and "+ f"{warnings} comparison warning(s) have endpoint-exposed consumers."+ )+ elif has_breaking_report:+ summary += "; the last workspace update found no break in them."+ else:+ summary += "; no breaking-change report has been built for them."+ return summary+++def _consumer_test_files(shown: list[dict], impact: Any) -> set[str]:+ """Test files recommended for the shown consumer rows."""+ # Counted over the shown rows, so it never promises tests the cap dropped.+ keys = {+ (+ row.get("repo") or "",+ comparable_path(row.get("file") or ""),+ row.get("contract_id") or "",+ )+ for row in shown+ }+ return {+ rec.test_file+ for rec in impact.recommendations+ for path in rec.consumer_files+ for cid in rec.contract_ids+ if (rec.consumer_repo, path, cid) in keys+ }+++def _attach_consumer_tests(+ shown: list[dict], impact: Any, collector: OmissionCollector | None+) -> str:+ """Add each shown consumer's tests block; return the sentence counting them."""+ for i, row in enumerate(shown):+ row["tests"] = tests_block_for(+ impact,+ row.get("repo") or "",+ row.get("file") or "",+ row.get("contract_id") or "",+ collector,+ f"cross_repo.consumers[{i}].tests.tests_to_run",+ )+ test_files = _consumer_test_files(shown, impact)+ undetermined = sum(1 for row in shown if row["tests"]["state"] == "unresolved")+ return (+ f" {len(test_files)} consumer test file(s) to run, "+ f"{undetermined} link(s) could not be determined."+ )+++def _workspace_enricher(changed_files: list[str]) -> Any:+ """The cross-repo enricher when it holds contract data for a non-empty change."""+ from repowise.server.mcp_server import _state++ if not changed_files or not _pkg._is_workspace_mode():+ return None+ enricher = _state._cross_repo_enricher+ if enricher is None or not getattr(enricher, "has_contract_data", False):+ return None+ return enricher+++def _cross_repo_block(+ alias: str,+ changed_files: list[str],+ impact: Any = None,+ collector: OmissionCollector | None = None,+) -> dict[str, Any] | None:+ """What this change does to consumers in other repos, or ``None``.++ Built from the last workspace update: contract links whose provider file the+ change touches, and breaking-change entries for those files. ``None`` outside+ workspace mode, without artifacts, or when nothing published is touched.+ Never raises.+ """+ try:+ enricher = _workspace_enricher(changed_files)+ if enricher is None:+ return None+ consumers = _cross_repo_consumers(enricher, alias, changed_files)+ has_breaking_report = bool(getattr(enricher, "has_breaking_changes", False))+ breaking, breaking_total, incompatible = (+ _cross_repo_breaking(enricher, alias, set(changed_files))+ if has_breaking_report+ else ([], 0, 0)+ )+ if not consumers and not breaking:+ return None+ report = enricher.get_breaking_changes() or {}+ # A removed endpoint has no current link; its repos survive only as breaks.+ repos = sorted(+ {c["repo"] for c in consumers if c.get("repo")}+ | {r for b in breaking for r in b["impacted_repos"] if r}+ )+ summary = _cross_repo_summary(+ consumers, repos, (breaking_total, incompatible), has_breaking_report+ )+ shown = consumers[:_CROSS_REPO_CONSUMER_LIMIT]+ if impact is not None:+ summary += _attach_consumer_tests(shown, impact, collector)+ return {+ "consumers": shown,+ "consumers_truncated": max(0, len(consumers) - _CROSS_REPO_CONSUMER_LIMIT),+ "consumer_repos": repos,+ "breaking_changes": breaking,+ "breaking_changes_truncated": breaking_total - len(breaking),+ # False: no detection pass ran, so an empty list is silence.+ "breaking_changes_available": has_breaking_report,+ # Dates the breaking half only; contract links carry no stamp.+ "breaking_changes_as_of": report.get("generated_at") or None,+ "summary": summary,+ }+ except Exception:+ return Nonediff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/health.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/health.pynew file mode 100644index 000000000..cb0364a41--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/health.py@@ -0,0 +1,232 @@+"""Health delta: the comparison service, stored-finding links and evidence."""++from __future__ import annotations++import threading+from collections import OrderedDict+from typing import Any++import structlog+from sqlalchemy import select+from sqlalchemy.exc import SQLAlchemyError++from repowise.core.analysis.change_health.service import (+ ChangeHealthDeltaService,+ DeltaRequest,+)+from repowise.core.analysis.change_risk.features import revspec_head++# Patchable names are read off the package at call time so patches reach them.+from repowise.server.mcp_server import tool_change_risk as _pkg+from repowise.server.mcp_server._failure_shield import (+ is_stale_server_import,+ stale_server_notice,+)++# Named for the tool module so log records keep their source.+log = structlog.get_logger("repowise.server.mcp_server.tool_change_risk")+++async def _evidence_block(+ ctx: Any,+ revspec: str | None,+ result: Any,+ delta: Any,+ extensions: tuple[str, ...],+ exclude_patterns: tuple[str, ...],+ *,+ scoped: bool,+) -> dict[str, Any]:+ """The change's evidence checklist, reusing the score and delta already computed.++ A revspec naming a stored change, asked with no filters of the caller's+ own, returns that change's kept record (building and keeping it when+ there is none), so this and ``repowise changes show`` serve the same one.+ """+ from repowise.core.changes.collect import (+ NO_INDEX,+ change_evidence,+ evidence_for_revspec,+ stored_change_at,+ )+ from repowise.core.persistence.database import get_session++ kwargs: dict[str, Any] = {+ "risk": result,+ "health": delta,+ "extensions": extensions,+ "exclude_patterns": exclude_patterns,+ }+ no_index = NO_INDEX+ session_factory = getattr(ctx, "session_factory", None)+ if session_factory is not None:+ try:+ async with get_session(session_factory) as session:+ repo = await _pkg._get_repo(session)+ row = await stored_change_at(session, repo.id, ctx.path, revspec)+ if row is not None and not scoped and not result.riskignore_excludes:+ evidence = await change_evidence(+ session, repo.id, ctx.path, row, risk=result, health=delta+ )+ else:+ evidence = await evidence_for_revspec(+ session, repo.id, ctx.path, revspec, row=row, **kwargs+ )+ return evidence.to_dict()+ except (LookupError, SQLAlchemyError) as exc:+ no_index = f"the index could not be read: {type(exc).__name__}: {exc}"+ evidence = await evidence_for_revspec(None, "", ctx.path, revspec, no_index=no_index, **kwargs)+ return evidence.to_dict()+++#: 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.+ from repowise.core.repo_config import health_rules_fingerprint++ service = ChangeHealthDeltaService(+ repo_path=repo_path, rules_fingerprint=health_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 _compare_health(+ repo_path: str,+ revspec: str | None,+ extensions: tuple[str, ...],+ exclude_patterns: tuple[str, ...],+ include_paths: tuple[str, ...] = (),+) -> Any:+ """Run the comparison, degrading to an explicit unavailable state."""+ from repowise.core.analysis.change_health.models import ChangeHealthDelta++ try:+ return _pkg._delta_service(repo_path).compare(+ DeltaRequest(repo_path, revspec, extensions, exclude_patterns, include_paths)+ )+ except Exception as exc:+ log.warning("change_health_comparison_failed", revspec=revspec, error=str(exc))+ explanation = (+ stale_server_notice(exc)+ if is_stale_server_import(exc)+ else f"Health comparison failed: {exc}"+ )+ return ChangeHealthDelta(+ status="unavailable",+ explanation=explanation,+ 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 _pkg._get_repo(session)+ rows = (+ (+ await session.execute(+ select(HealthFinding).where(+ HealthFinding.repository_id == repository.id,+ HealthFinding.file_path.in_(paths),+ )+ )+ )+ .scalars()+ .all()+ )+ except (LookupError, SQLAlchemyError):+ # No repository row is "no index", as in the sibling enrichments.+ 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 _scored_repo(path: str, revspec: str | None, working_tree: bool) -> dict[str, Any]:+ """The checkout the change was read in and the commit its head resolved to.++ ``HEAD`` or a branch name resolves in the served checkout, not in the+ caller's worktree, so naming both makes a review of the wrong tree visible.+ Uncommitted work is marked, so its ``head`` does not read as the change.+ """+ from repowise.core import git_refs++ head = git_refs.resolve(path, revspec_head(revspec))[:12] or None+ return {"root": path, "head": head, **({"working_tree": True} if working_tree else {})}+++async def _repository(ctx: Any) -> Any | None:+ """The indexed repository row, or ``None`` without an index.++ Only ``_meta`` needs it: the per-file blocks below resolve their own repo id+ inside the session they query in.+ """+ from repowise.core.persistence.database import get_session++ session_factory = getattr(ctx, "session_factory", None)+ if session_factory is None:+ return None+ try:+ async with get_session(session_factory) as session:+ return await _pkg._get_repo(session)+ except (LookupError, SQLAlchemyError):+ return Nonediff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/impacted.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/impacted.pynew file mode 100644index 000000000..de1b738c9--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/impacted.py@@ -0,0 +1,144 @@+"""Impacted tests: the selection ``repowise impacted-tests`` makes for the change."""++from __future__ import annotations++import asyncio+from functools import partial+from typing import Any++import structlog+from sqlalchemy.exc import SQLAlchemyError++# Patchable names are read off the package at call time so patches reach them.+from repowise.server.mcp_server import tool_change_risk as _pkg+from repowise.server.mcp_server._budget import OmissionCollector+from repowise.server.mcp_server._test_selection import (+ UNAVAILABLE_REASON,+ SelectionUnavailableError,+ selection_block,+)++# Named for the tool module so log records keep their source.+log = structlog.get_logger("repowise.server.mcp_server.tool_change_risk")+++#: 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.+_IMPACTED_TESTS_LIMIT = 10+++def _empty_impacted(status: str, summary: str) -> dict[str, Any]:+ """Uniform impacted-tests block for the paths where no selection was made.++ Nothing vouches for a subset there, so the block says ``run_all`` with the+ reason, like a selection that cannot vouch for one. ``basis`` is ``none``+ and nothing is named, so there is no ``tests_to_run_kind``, ``map_present``+ or ``line_coverage``.+ """+ return {+ "status": status,+ "run_all": True,+ "reasons": [summary, UNAVAILABLE_REASON],+ "basis": "none",+ "tests_to_run": [],+ "total": 0,+ "truncated": False,+ "summary": summary,+ }+++def _serialize_missing(report: Any) -> dict[str, Any]:+ """Render the detect_missing_tests dataclass buckets as JSON-ready dicts."""+ return {+ "untested_changes": [+ {+ "source_file": u.source_file,+ "uncovered_lines": u.uncovered_lines,+ "changed_line_count": u.changed_line_count,+ }+ for u in report.untested_changes+ ],+ "stale_test_candidates": [+ {+ "source_file": s.source_file,+ "covering_test_files": s.covering_test_files,+ "covering_test_ids_without_file": s.covering_test_ids_without_file,+ }+ for s in report.stale_test_candidates+ ],+ "covered": list(report.covered),+ # ``no_data`` is "file not in the map" = unknown, never "untested".+ "no_coverage_data": list(report.no_data),+ }+++async def _impacted_tests_block(+ ctx: Any,+ changed: dict[str, set[int]],+ changed_error: tuple[str, str] | None,+ collector: OmissionCollector,+ *,+ revspec: str | None = None,+ working_tree: bool = False,+ owned_excludes: tuple[str, ...] = (),+) -> dict[str, Any]:+ """The tests the change needs, decided as ``repowise impacted-tests`` decides them.++ The same collection and fail-closed selection (``test_collection`` then+ ``select_tests``) over the whole change, every touched path included, so a+ manifest, a conftest or a test that walks the source tree weighs here as it+ does in CI. The caller's suffix, include and exclude filters do not narrow+ it; only *owned_excludes*, repowise's own output, leaves it, as it leaves+ every other block. ``line_coverage`` classifies the scored files' lines against+ the per-test map, on the side of the diff the map was measured at.+ Any failure degrades to a ``status`` string with ``run_all`` true and never+ raises, so it cannot fail the surrounding score.+ """+ from repowise.core.analysis.changed_lines import change_set+ from repowise.core.analysis.missing_test_signal import detect_missing_tests+ from repowise.core.analysis.test_collection import query_lines+ from repowise.core.persistence.database import get_session++ session_factory = getattr(ctx, "session_factory", None)+ if session_factory is None:+ return _empty_impacted(+ "no_index", "No index; run `repowise init` to enable impacted tests."+ )+ if changed_error is not None:+ return _empty_impacted(*changed_error)+ try:+ change = await asyncio.to_thread(+ partial(+ change_set,+ str(ctx.path),+ None if working_tree else revspec or "HEAD",+ working_tree=working_tree,+ exclude_patterns=owned_excludes,+ )+ )+ except Exception: # git refused the change, or could not run+ return _empty_impacted("unknown", "Could not read the change from git.")+ try:+ result, selection, _ = await _pkg.select_change_tests(ctx.path, session_factory, change)+ block = selection_block(+ result, selection, collector, limit=_IMPACTED_TESTS_LIMIT, label="impacted_tests"+ )+ if not result["map_empty"]:+ lines = query_lines(change, result["measured_commit"])+ async with get_session(session_factory) as session:+ repo_id = (await _pkg._get_repo(session)).id+ report = await detect_missing_tests(+ session, repo_id, {p: lines[p] for p in changed if p in lines}+ )+ block["line_coverage"] = _serialize_missing(report)+ except SelectionUnavailableError as exc:+ return _empty_impacted(exc.status, str(exc))+ except LookupError:+ return _empty_impacted("no_index", "No indexed repository; run `repowise init`.")+ except SQLAlchemyError:+ return _empty_impacted("unknown", "Could not read the index.")+ except Exception as exc: # a selection bug must not take the score with it+ log.warning("impacted_tests_failed", error=f"{type(exc).__name__}: {exc}")+ return _empty_impacted("unknown", f"Selecting tests failed ({type(exc).__name__}).")+ return blockdiff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/patch_coverage.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/patch_coverage.pynew file mode 100644index 000000000..ac3e43016--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/patch_coverage.py@@ -0,0 +1,152 @@+"""Patch coverage: the share of changed lines the stored coverage ran."""++from __future__ import annotations++import asyncio+import contextlib+from typing import Any++from sqlalchemy.exc import SQLAlchemyError++from repowise.core.analysis.change_risk.features import revspec_head++# Patchable names are read off the package at call time so patches reach them.+from repowise.server.mcp_server import tool_change_risk as _pkg+from repowise.server.mcp_server._budget import OmissionCollector++from .changed import _change_base+from .impacted import _IMPACTED_TESTS_LIMIT+++async def _patch_coverage_block(+ ctx: Any,+ changed: dict[str, set[int]],+ changed_error: tuple[str, str] | None,+ revspec: str | None,+ result: Any,+ collector: OmissionCollector,+ *,+ label: str | None = None,+) -> dict[str, Any] | None:+ """Share of the change's executable lines the stored coverage ran, or ``None``.++ The same computation ``repowise coverage check`` gates on, read from the+ coverage the index stores. ``None`` when there is no index, no stored+ coverage, or no readable change: ``impacted_tests`` already says why.+ ``files`` lists only the files that need attention, riskiest first, capped;+ the totals and ``file_counts`` still count every file. ``coverage.ignore``,+ ``coverage.min_coverable_lines`` and the path-scoped ``coverage.gates``+ apply as they do in the CLI gate; path gates read ``no_data`` on stale+ coverage or invalid config, which ``scope.config_errors`` names. Each row+ carries its file's risk, from the index and the checkout's git history, and+ ``hints``: the test file to extend per uncovered range. ``project``+ compares the ingest measured at the change's base commit with the current+ one, when both exist (repo-wide totals only, never gated here).++ With no revspec, *changed* is what a push would bring (the caller diffs+ from the merge-base with the push base, *label* names it). For uncommitted+ work no commit names that code, so freshness is by time: ``current`` when+ the last coverage ingest came after the newest edit to the changed files.+ """+ from repowise.core import git_refs+ from repowise.core.analysis.health.coverage import configured_coverage+ from repowise.core.analysis.health.coverage.freshness import newest_mtime+ from repowise.core.analysis.patch_coverage import (+ assess_risks,+ attach_risk,+ read_git_fix_history,+ stored_patch_coverage,+ )+ from repowise.core.persistence.database import get_session++ session_factory = getattr(ctx, "session_factory", None)+ if session_factory is None or changed_error is not None or not changed:+ return None+ head_commit = mtime = None+ if result.working_tree:+ mtime = await asyncio.to_thread(newest_mtime, ctx.path, changed)+ else:+ head_commit = git_refs.resolve(str(ctx.path), revspec_head(revspec)) or None+ base_commit = await asyncio.to_thread(+ _change_base, str(ctx.path), revspec, label, result.working_tree+ )+ index: dict = {}+ try:+ async with get_session(session_factory) as session:+ repo_id = (await _pkg._get_repo(session)).id+ patch = await stored_patch_coverage(+ session,+ repo_id,+ changed,+ label=label or result.features.ref,+ head_commit=head_commit,+ config=configured_coverage(ctx.path),+ working_tree_mtime=mtime,+ repo_path=str(ctx.path),+ )+ if patch is not None:+ patch, index = await _enrich_patch(+ session, repo_id, patch, base_commit, str(ctx.path), head_commit, result+ )+ except (LookupError, SQLAlchemyError):+ return None+ if patch is None:+ return None+ # Git after the session closes: no subprocess while a connection is held.+ git = await asyncio.to_thread(+ read_git_fix_history, str(ctx.path), revspec, working_tree=result.working_tree+ )+ patch = attach_risk(patch, assess_risks([f.file_path for f in patch.files], git, index))+ block = patch.to_dict()+ block["files"] = _attention_files(patch, collector)+ return block+++async def _enrich_patch(+ session: Any,+ repo_id: str,+ patch: Any,+ base_commit: str | None,+ repo_path: str,+ head_commit: str | None,+ result: Any,+) -> tuple[Any, dict]:+ """The patch with its history delta and test hints, plus the index facts read."""+ from repowise.core.analysis.patch_coverage import (+ attach_hints,+ attach_history_delta,+ read_index_facts,+ read_test_hints,+ )++ # An unreadable index row leaves risk to git alone and hints null.+ index: dict = {}+ patch = await attach_history_delta(session, repo_id, patch, base_commit)+ with contextlib.suppress(SQLAlchemyError):+ index = await read_index_facts(session, repo_id, [f.file_path for f in patch.files])+ # Advice: read_test_hints logs any failure and returns None.+ hints = await read_test_hints(+ session,+ repo_id,+ patch,+ repo_path=repo_path,+ head_commit=head_commit,+ working_tree=result.working_tree,+ )+ if hints is not None:+ patch = attach_hints(patch, hints)+ return patch, index+++def _attention_files(patch: Any, collector: OmissionCollector) -> list[dict]:+ """The files needing attention, riskiest first, capped; the tail goes to *collector*."""+ from repowise.core.analysis.patch_coverage import attention_rows++ rows = [f.to_dict() for f in attention_rows(patch)]+ if len(rows) > _IMPACTED_TESTS_LIMIT:+ collector.add(+ f"patch_coverage.files beyond cap={_IMPACTED_TESTS_LIMIT} "+ f"({len(rows) - _IMPACTED_TESTS_LIMIT} dropped)",+ [row["file_path"] for row in rows[_IMPACTED_TESTS_LIMIT:]],+ )+ return rows[:_IMPACTED_TESTS_LIMIT]diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/payload.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/payload.pynew file mode 100644index 000000000..c58cdd758--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/payload.py@@ -0,0 +1,165 @@+"""The score's payload: include blocks, diagnostics, health order and drill-down."""++from __future__ import annotations++from typing import Any++from repowise.core.analysis.change_risk.render import LIMITS, size_text++# Patchable names are read off the package at call time so patches reach them.+from repowise.server.mcp_server import tool_change_risk as _pkg+from 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._change_health import (+ patch_coverage_action as _patch_coverage_action,+)+from repowise.server.mcp_server._helpers import (+ resolve_enum_argument,+)++# Compatibility projection for direct callers and older tests. The shared+# response contract remains the single source of truth for this order.+_SHED_ORDER = response_budget_shed_order("get_change_risk")++#: Per-field units and calibration. Identical on every call, so it is opt-in.+#: ``diagnostics`` carries the raw model mechanics; ``findings`` lifts the+#: top-findings cap. Both are projections, recoverable by an exact call.+#: ``evidence`` adds the change's evidence checklist, the record ``repowise+#: changes show`` and the REST change detail serve.+_INCLUDE_BLOCKS = frozenset({"scales", "diagnostics", "findings", "evidence"})++#: Score mechanics that are identical or near-identical on every call, behind+#: ``include=["diagnostics"]`` so the action-first blocks lead. ``score`` and+#: ``fallback_band`` sit here: the percentile already carries the ranking, and+#: the raw number reads as a danger verdict it is not.+_DIAGNOSTIC_FIELDS = (+ "risk_authority",+ "score_measures",+ "score_unit",+ "baseline_sample_size",+ "features",+ "drivers",+ "score",+ "fallback_band",+)++#: Comparison mechanics on ``health_delta``: the analyzer fingerprint, the two+#: resolved revisions and the fixed limits text. Behind ``diagnostics`` too.+_HEALTH_DIAGNOSTIC_FIELDS = ("analyzer", "base", "head", "limits")++#: ``classification`` labels for the MCP surface. ``review_priority`` is a+#: tercile of the diff-shape rank, so the label names size, not a verdict.+#: Both ship only under ``include=["scales"]``: ``risk_percentile`` is the one+#: rank on the default response.+_DIFF_SIZE_LABELS = {+ "low": "Below-typical diff size",+ "moderate": "Typical diff size",+ "high": "Above-typical diff size",+}+++def _path_patterns(value: list[str] | str | None) -> tuple[str, ...]:+ """A list of patterns, or one comma-separated string, as a pattern tuple.++ ``tuple("src/")`` would be one pattern per character, which matches nothing.+ """+ items = value.split(",") if isinstance(value, str) else value or ()+ return tuple(item.strip() for item in items if item.strip())+++def _include_blocks(include: list[str] | None, ignored: list[dict]) -> set[str]:+ """The valid ``include`` blocks; unknown ones are recorded in ``ignored``."""+ return {+ block+ for block in (include or [])+ if resolve_enum_argument(block, _INCLUDE_BLOCKS, argument="include", ignored=ignored)+ }+++def _shape_payload(result: Any, include_set: set[str], revspec: str | None) -> tuple[dict, dict]:+ """The score's payload trimmed to what the request asked for.++ Returns ``(payload, diagnostics)``; ``diagnostics`` holds the fields moved+ out of the payload when the caller did not ask for them.+ """+ payload = _pkg.change_risk_payload(result, scales="scales" in include_set)+ if "scales" not in include_set:+ payload.pop("review_priority")+ payload.pop("classification")+ elif payload.get("review_priority") in _DIFF_SIZE_LABELS:+ payload["classification"] = _DIFF_SIZE_LABELS[payload["review_priority"]]+ if "diagnostics" not in include_set:+ diagnostics = {f: payload.pop(f) for f in _DIAGNOSTIC_FIELDS if f in payload}+ # The fix record reads as files and counts; its rank is a second+ # percentile beside ``risk_percentile`` and only invited comparing them.+ payload["fix_history"].pop("percentile", None)+ payload["fix_history"].pop("density", None)+ else:+ diagnostics = {}+ # Fields that only repeat the request or say nothing: an empty exclude list,+ # a working-tree flag after an explicit revspec, a false ``is_fix``.+ if not payload["exclude_patterns"]:+ del payload["exclude_patterns"]+ if revspec is not None:+ del payload["working_tree"]+ if not payload["is_fix"]:+ del payload["is_fix"]+ return payload, diagnostics+++def _attach_health(+ payload: dict, delta: Any, revspec: str | None, *, expand: bool, diagnostics: bool = False+) -> None:+ """Put the directive first and the compact delta second."""+ block = _health_delta_block(delta, revspec=revspec)+ if not diagnostics:+ for key in _HEALTH_DIAGNOSTIC_FIELDS:+ block.pop(key, None)+ 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)+ directive = _directive(delta, payload.get("impacted_tests"))+ if action := _patch_coverage_action(payload.get("patch_coverage")):+ directive["next_actions"].append(action)+ ordered = {+ "directive": directive,+ "health_delta": block,+ }+ for key, value in payload.items():+ ordered[key] = value+ payload.clear()+ payload.update(ordered)+++def _diff_shape_sentence(payload: dict, diagnostics: dict) -> str:+ """One line for what the diff-shape rank says, and what it does not."""+ tail = " Mechanics: get_change_risk(include=['diagnostics'])." if diagnostics else ""+ return f"{size_text(payload.get('risk_percentile'))}. {LIMITS}{tail}"+++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,+ }diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/prior_fixes.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/prior_fixes.pynew file mode 100644index 000000000..d62a33e43--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/prior_fixes.py@@ -0,0 +1,197 @@+"""Past bug fixes on the lines a change touches."""++from __future__ import annotations++import asyncio+from typing import Any++import structlog+from sqlalchemy import select+from sqlalchemy.exc import OperationalError, SQLAlchemyError++from repowise.core.analysis.change_risk import (+ FixHistoryUnavailableError,+ fixes_reachable_from,+)+from repowise.core.analysis.prior_fix_impact import (+ FixRecord,+ PriorFixFile,+ PriorFixImpact,+ dominant_file,+ parse_old_ranges,+ summarize_prior_fixes,+ unavailable_prior_fixes,+ unsupported_prior_fixes,+)++# Patchable names are read off the package at call time so patches reach them.+from repowise.server.mcp_server import tool_change_risk as _pkg+from repowise.server.mcp_server._helpers import (+ is_missing_table,+)++# Named for the tool module so log records keep their source.+log = structlog.get_logger("repowise.server.mcp_server.tool_change_risk")+++#: Cap on the per-file prior-fix list, matching ``_IMPACTED_TESTS_LIMIT`` so both+#: per-file blocks in this response stay the same size.+_PRIOR_FIXES_LIMIT = 10+++async def _prior_fixes_block(+ ctx: Any, changed: dict[str, set[int]], *, history_ref: str | None = None+) -> dict[str, Any] | None:+ """Past bug fixes that landed on the lines this change touches, or ``None``.++ Aggregate only. No inducing commit is named: attribution is precise enough+ to count fixes, not to accuse the commit that caused one.++ ``overlapping_lines`` is the honest weak signal and is labelled as such. A+ fix's stored ranges are line numbers on ITS parent commit while the change's+ are line numbers now, so any commit in between shifts them; the count says+ "this neighbourhood has been patched before", never "this exact line". The+ per-file fix count beside it carries no such caveat.++ Silent (``None``) when the index has no fix events for these files at all,+ so a repo without the feature grows no noise block. A read that *failed* is+ not silent: it renders with ``status: "unavailable"``, because "we could not+ look" and "nothing has broken here" are opposite claims about the change.+ """+ impact = await _pkg._read_prior_fixes(ctx, changed, history_ref=history_ref)+ if impact.status == "unsupported" or (impact.status == "available" and impact.is_empty):+ return None+ if impact.status != "available":+ return {+ "status": impact.status,+ "reason": impact.reason,+ "summary": (+ "The bug-fix record for these files could not be read, so this "+ "change is not cleared of a fix-prone history."+ ),+ }++ shown = impact.files[:_PRIOR_FIXES_LIMIT]+ block = {+ "files": [_prior_fix_row(f) for f in shown],+ "truncated": len(impact.files) > _PRIOR_FIXES_LIMIT,+ "total_fixes": impact.total_fixes,+ "files_with_fixes": impact.files_with_fixes,+ "changed_lines_in_fixed_files": impact.changed_lines_in_fixed_files,+ "line_overlap": impact.line_overlap_basis,+ "summary": (+ f"{impact.total_fixes} past bug-fix commit(s) touched "+ f"{impact.files_with_fixes} of the changed file(s). "+ "Line overlap is approximate (past ranges are numbered on their own "+ "parent commit); the per-file counts are not."+ ),+ }+ # Only over the files actually returned, so the sentence never names a path+ # the reader cannot find anywhere else in the block.+ top = dominant_file(shown)+ if top is not None:+ block["concentration"] = (+ f"{top.file_path} carries {top.share_of_change:.0%} of the changed lines "+ f"and {top.fix_count} past bug fix(es)."+ )+ return block+++def _prior_fix_row(entry: PriorFixFile) -> dict[str, Any]:+ """One core row on the wire, keeping the historical key set and order."""+ row: dict[str, Any] = {+ "file_path": entry.file_path,+ "fix_count": entry.fix_count,+ "overlapping_lines": entry.overlapping_lines,+ "changed_lines": entry.changed_lines,+ "share_of_change": entry.share_of_change,+ }+ # Absent rather than null when no event carried a date, as before.+ if entry.last_fix_days_ago is not None:+ row["last_fix_days_ago"] = entry.last_fix_days_ago+ return row+++async def _read_prior_fixes(+ ctx: Any, changed: dict[str, set[int]], *, history_ref: str | None = None+) -> PriorFixImpact:+ """Collect fix events from the index. Collection only; core summarizes.++ With *history_ref* (the score's own fix-history anchor) only fixes in that+ ref's history count, so a reviewed commit and its successors in the index+ are not read back as the ground it stood on.++ The four ways this can come back empty are not one state. An index that+ predates fix events has nothing to read (``unsupported``), while a query+ that failed means the record exists and was not read (``unavailable``).+ Collapsing those is how a failure reads as a clean bill.+ """+ from repowise.core.persistence.database import get_session+ from repowise.core.persistence.models import FixEvent++ session_factory = getattr(ctx, "session_factory", None)+ if session_factory is None:+ return unsupported_prior_fixes("this repository has no index to read a fix record from")+ if not changed:+ return unsupported_prior_fixes("no changed lines were counted for this change")++ try:+ async with get_session(session_factory) as session:+ repo_id = (await _pkg._get_repo(session)).id+ res = await session.execute(+ select(FixEvent).where(+ FixEvent.repository_id == repo_id,+ FixEvent.file_path.in_(list(changed)),+ FixEvent.shape_kind == "code_fix",+ )+ )+ events = list(res.scalars().all())+ except LookupError:+ return unsupported_prior_fixes("this repository is not indexed")+ except OperationalError as exc:+ # An index built before fix events existed has no table to read. That is+ # silence, not an error the caller should have to handle -- but a locked+ # or unreadable database is a real failure and falls through below.+ if is_missing_table(exc):+ return unsupported_prior_fixes("this index predates the bug-fix record")+ return unavailable_prior_fixes(_read_failure(exc))+ except SQLAlchemyError as exc:+ return unavailable_prior_fixes(_read_failure(exc))++ if history_ref is not None:+ try:+ events = await _events_before(ctx, events, history_ref)+ except FixHistoryUnavailableError as exc:+ return unavailable_prior_fixes(f"could not place fixes in history: {exc}")++ return summarize_prior_fixes(+ (+ FixRecord(+ fix_sha=event.fix_sha,+ file_path=event.file_path,+ old_ranges=parse_old_ranges(event.old_ranges_json),+ committed_at=event.committed_at,+ )+ for event in events+ ),+ changed,+ )+++async def _events_before(ctx: Any, events: list[Any], history_ref: str) -> list[Any]:+ """The fix events in *history_ref*'s history, so a review never counts itself."""+ kept = await asyncio.to_thread(+ fixes_reachable_from, str(ctx.path), history_ref, (event.fix_sha for event in events)+ )+ return [event for event in events if event.fix_sha in kept]+++def _read_failure(exc: SQLAlchemyError) -> str:+ """Name the failure without quoting the driver.++ Driver text can carry connection-string fragments, and this string goes out+ on the wire. The class of failure is what a caller can act on; the detail+ belongs in the server log, where it already is.+ """+ log.warning("prior_fixes_read_failed", error=str(exc))+ return f"the fix record could not be read ({type(exc).__name__})"diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.pynew file mode 100644index 000000000..a4da344e9--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py@@ -0,0 +1,326 @@+"""MCP tool for live commit and range change-risk scoring."""++from __future__ import annotations++import asyncio+import shutil+import subprocess+import time+from typing import Any++from repowise.core.analysis.change_risk import (+ normalize_extensions,+)+from repowise.core.analysis.change_risk.features import revspec_head+from repowise.core.registry import mcp_tool_registry as mcp++# Patchable names are read off the package at call time so patches reach them.+from repowise.server.mcp_server import tool_change_risk as _pkg+from repowise.server.mcp_server._budget import OmissionCollector+from repowise.server.mcp_server._helpers import (+ _unsupported_repo_all,+ attach_ignored_arguments,+)++from .branches import _branch_overlap_block, _independent_changes_block+from .changed import _changed_in_scope, _push_change+from .cross_repo import _cross_repo_block+from .health import (+ _attach_health_references,+ _compare_health,+ _evidence_block,+ _repository,+ _scored_repo,+)+from .impacted import _impacted_tests_block+from .patch_coverage import _patch_coverage_block+from .payload import (+ _attach_health,+ _diff_shape_sentence,+ _drill_down,+ _include_blocks,+ _path_patterns,+ _shape_payload,+)+from .prior_fixes import _prior_fixes_block+++async def _score_change(+ repo_path: Any,+ revspec: str | None,+ extensions: list[str] | None,+ exclude_patterns: list[str] | None,+ include_paths: tuple[str, ...],+ baseline: int,+) -> tuple[Any, dict | None]:+ """Score the live change: ``(result, None)``, or ``(None, error reply)``."""+ try:+ result = await asyncio.to_thread(+ _pkg.score_live_change,+ repo_path,+ revspec,+ extensions=tuple(extensions or ()),+ exclude_patterns=tuple(exclude_patterns or ()),+ include_paths=include_paths,+ baseline=baseline,+ )+ except ValueError as exc:+ return None, {"error": str(exc)}+ except subprocess.CalledProcessError as exc:+ detail = (exc.stderr or "").strip() or str(exc)+ return None, {"error": f"Could not read change {revspec or 'HEAD'!r}: {detail}"}+ except subprocess.TimeoutExpired:+ return None, {"error": f"git timed out reading change {revspec or 'HEAD'!r}."}+ except FileNotFoundError:+ # Scoring spawns git from several readers, so the missing binary is+ # named once here. Any other missing file is a real bug: re-raise.+ if shutil.which("git") is not None:+ raise+ return None, {+ "error": "git was not found on PATH; change risk reads the repository history."+ }+ return result, None+++async def _attach_change_blocks(+ ctx: Any,+ payload: dict,+ result: Any,+ revspec: str | None,+ extensions: list[str] | None,+ changed_read: tuple[Any, Any],+ collector: OmissionCollector,+ include_paths: tuple[str, ...] = (),+) -> None:+ """Attach the tests, patch coverage, prior fixes and cross-repo blocks, in that order."""+ changed, changed_error = changed_read+ payload["impacted_tests"] = await _impacted_tests_block(+ ctx,+ changed,+ changed_error,+ collector,+ revspec=revspec,+ working_tree=result.working_tree,+ owned_excludes=result.owned_excludes,+ )+ patch_changed, patch_error, patch_label, patch_revspec = await _push_change(+ str(ctx.path),+ revspec,+ result.working_tree,+ normalize_extensions(tuple(extensions or ())),+ result.riskignore_excludes + result.request_excludes,+ (changed, changed_error),+ include_paths,+ )+ patch = await _patch_coverage_block(+ ctx, patch_changed, patch_error, patch_revspec, result, collector, label=patch_label+ )+ if patch is not None:+ payload["patch_coverage"] = patch+ prior_fixes = await _prior_fixes_block(ctx, changed, history_ref=result.history_ref)+ if prior_fixes is not None:+ # One fix record, not two. The blocks answered the same question+ # with different arithmetic (decayed pressure vs raw count) and a+ # reader had to work out which was which.+ payload.setdefault("fix_history", {})["overlap"] = prior_fixes+ alias = getattr(ctx, "alias", "")+ # The join needs an open index per consumer repo, so it runs once for+ # the whole change and the block distributes its rows.+ impact = await _pkg.cross_repo_tests(alias, sorted(changed))+ cross_repo = _cross_repo_block(alias, sorted(changed), impact, collector)+ if cross_repo is not None:+ payload["cross_repo"] = cross_repo+++async def _attach_branch_blocks(+ ctx: Any,+ payload: dict,+ changed: Any,+ collector: OmissionCollector,+ revspec: str | None,+ finding_id: str | None,+) -> Any:+ """Attach ``branch_overlap`` and return the independent-changes block, or None."""+ # A drill-down returns one finding and nothing else, so neither block+ # would reach the caller; both are pure cost on that path.+ if finding_id is not None:+ return None+ overlap = await _branch_overlap_block(ctx, changed, collector, revspec_head(revspec))+ if overlap is not None:+ payload["branch_overlap"] = overlap+ return await _independent_changes_block(ctx, changed, collector, revspec)+++ surface_order=60,+ artifact_type="change_risk",+ presentation="change_risk",+ evidence_basis="measured",+)+async def get_change_risk(+ revspec: str | None = None,+ repo: str | None = None,+ extensions: list[str] | None = None,+ exclude_patterns: list[str] | None = None,+ include_paths: list[str] | str | None = None,+ baseline: int = 200,+ include: list[str] | None = None,+ finding_id: str | None = None,+) -> dict:+ """Review a commit, ``base..head`` range, or uncommitted work.++ Leads with ``directive`` (what to do) and ``health_delta`` (what this+ change newly made worse). Findings are reported only when the diff explains+ them, name their ``attribution`` basis, and sort change-written above+ pre-existing.++ ``directive.status`` is the verdict; ``partial`` health means code files+ were skipped. ``risk_percentile`` and ``diff_shape`` measure diff size+ only, not danger.++ ``impacted_tests`` is the ``impacted-tests`` selection; read ``run_all``.+ ``patch_coverage`` is the share of changed executable lines stored coverage+ ran; ``hints`` name tests to extend. ``fix_history`` is the changed files'+ bug-fix record, ``overlap`` the past fixes on these exact lines,+ ``branch_overlap`` other branches editing them. An empty diff returns+ ``status: "nothing_to_score"``.++ Args:+ 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/"]``.+ include_paths: Gitignore-style paths to keep, as a list or one+ comma-separated string, e.g. ``"src/api/,src/db/"``. Omit for all.+ baseline: Recent commits sampled for percentile ranking; 0 disables it.+ include: ``"findings"``, ``"diagnostics"`` (raw mechanics),+ ``"scales"`` (units, tercile) or ``"evidence"`` (checklist).+ finding_id: Expand one ``health_delta`` finding by its id.+ """+ if repo == "all":+ return _unsupported_repo_all("get_change_risk")+ ctx = await _pkg._resolve_repo_context(repo)+ started = time.perf_counter()+ includes = _path_patterns(include_paths)+ result, error = await _score_change(+ ctx.path, revspec, extensions, exclude_patterns, includes, baseline+ )+ if error is not None:+ return error+ ignored: list[dict] = []+ include_set = _include_blocks(include, ignored)+ payload, diagnostics = _shape_payload(result, include_set, revspec)+ scored = await asyncio.to_thread(_scored_repo, str(ctx.path), revspec, result.working_tree)+ if result.features.nf == 0:+ return await _nothing_to_score(ctx, payload["ref"], scored, started)+ payload = {"ref": payload.pop("ref"), "scored_repo": scored, **payload}+ # Changed lines over the SAME file universe the score counted (its+ # extensions, includes, riskignore + request excludes), so nothing downstream+ # disagrees with the score about which files the change touches. Read once+ # and shared: both blocks below need it and git is the expensive part.+ # The test and fix blocks need the index and the cross-repo block needs+ # workspace contracts, but the branch-overlap block needs only git, so every+ # call pays this read rather than an unindexed repo going blind.+ changed, changed_error = await _changed_in_scope(+ str(ctx.path),+ revspec,+ normalize_extensions(tuple(extensions or ())),+ result.riskignore_excludes + result.request_excludes,+ includes,+ working_tree=result.working_tree,+ )+ collector = OmissionCollector("get_change_risk", repo_root=ctx.path)+ # 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),+ includes,+ )+ )+ try:+ # A drill-down returns one finding and nothing else, so the tests,+ # coverage, fix and cross-repo blocks would never reach the caller.+ if finding_id is None:+ await _pkg._attach_change_blocks(+ ctx,+ payload,+ result,+ revspec,+ extensions,+ (changed, changed_error),+ collector,+ includes,+ )+ independent = await _attach_branch_blocks(+ ctx, payload, changed, collector, revspec, finding_id+ )+ 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)+ payload["diff_shape"] = _diff_shape_sentence(payload, diagnostics)+ if independent is not None:+ payload["independent_changes"] = independent+ _attach_health(+ payload,+ delta,+ revspec,+ expand="findings" in include_set,+ diagnostics="diagnostics" in include_set,+ )+ if "evidence" in include_set:+ payload["evidence"] = await _evidence_block(+ ctx,+ revspec,+ result,+ delta,+ tuple(extensions or ()),+ tuple(result.riskignore_excludes + result.request_excludes),+ scoped=bool(extensions or exclude_patterns or includes or baseline != 200),+ )+ # 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+ # there are none, so a degraded read keeps the repo-level staleness warning+ # instead of reading as "nothing served, nothing to warn about".+ payload["_meta"] = _pkg._build_meta(+ timing_ms=(time.perf_counter() - started) * 1000,+ repository=await _repository(ctx),+ targets=sorted(changed) or None,+ extra={"source": "live_git"},+ )+ attach_ignored_arguments(payload, ignored)+ collector.attach(payload)+ return payload+++async def _nothing_to_score(ctx: Any, ref: str, scored: dict[str, Any], started: float) -> dict:+ """An empty diff, reported as one rather than scored.++ A score would read as a clean bill of health on a tree the caller may not+ have meant; naming the tree makes a worktree mismatch visible.+ """+ return {+ "ref": ref,+ "status": "nothing_to_score",+ "warning": (+ f"No counted file changes in {ref!r} "+ "(check the revspec, extensions, or include/exclude filters)."+ ),+ "scored_repo": scored,+ "_meta": _pkg._build_meta(+ timing_ms=(time.perf_counter() - started) * 1000,+ repository=await _repository(ctx),+ extra={"source": "live_git"},+ ),+ }