Skip to content

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

feat(health): rank verification tests by how directly they exercise the change (#2825)

Raghav Chamadiyadb15daaccd56
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
index 233692eb4..41bc2c38c 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
@@ -8,6 +8,8 @@ batched across the complete plan set; adding plans never adds SQL statements.
from __future__ import annotations
+import dataclasses
+import functools
import json
import math
from collections.abc import Callable, Mapping, Sequence
@@ -17,13 +19,18 @@ from typing import Any, Literal
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.grading import TARGET_SCORE
+from repowise.core.analysis.pr_blast import rank_tests_by_reach
from repowise.core.analysis.test_reachability import (
+ DEFAULT_CALL_DEPTH,
+ ReachDistance,
ReachedBy,
+ imported_names_by_test,
load_test_files,
- rank_tests,
+ reach_into_symbols,
tests_matching_by_name,
tests_reaching_by_tier,
)
+from repowise.core.test_paths import is_test_support_path, paired_test_names
from .models import RefactoringSuggestion
@@ -282,6 +289,8 @@ class ValidationPlan:
affected_symbols: list[str]
commands: list[str]
targets: list[ValidationTarget] = field(default_factory=list)
+ # Why each shown test is listed where it is, keyed by test id.
+ reasons: dict[str, str] = field(default_factory=dict)
def as_dict(self) -> dict[str, Any]:
return {
@@ -294,9 +303,220 @@ class ValidationPlan:
"affected_symbols": self.affected_symbols,
"commands": self.commands,
"targets": [target.as_dict() for target in self.targets],
+ "reasons": self.reasons,
}
+SymbolSpan = tuple[str, int, int]
+
+
+@dataclass(frozen=True, slots=True)
+class ValidationEvidence:
+ """Graph facts that order a plan's tests, read once for the whole plan set.
+
+ ``symbols`` is each file's symbol ids with their line spans, ``symbol_reach``
+ how close each test gets to a symbol, and ``imports`` the names each test
+ imports from a file. Empty, the order falls back to name and directory.
+ """
+
+ symbols: Mapping[str, Sequence[SymbolSpan]] = field(default_factory=dict)
+ symbol_reach: Mapping[str, Mapping[str, ReachDistance]] = field(default_factory=dict)
+ imports: Mapping[str, Mapping[str, frozenset[str]]] = field(default_factory=dict)
+
+
+@dataclass(frozen=True, slots=True)
+class ValidationInputs:
+ """The coverage rows and reachability walk one hydration read."""
+
+ measured: Mapping[str, list[dict[str, Any]]]
+ inferred: Mapping[str, ReachedBy]
+ test_files: set[str]
+
+
+def target_symbol_ids(
+ suggestion: RefactoringSuggestion,
+ file_path: str,
+ lines: set[int] | None,
+ spans: Sequence[SymbolSpan],
+) -> list[str]:
+ """Graph ids of the symbols in *file_path* the plan changes.
+
+ Named symbols first: a full id, a bare name, or ``Class.method``. When none
+ name a symbol here, the innermost symbol enclosing the plan's lines, which
+ is how a line-range target (``extract_helper``) finds its function.
+ """
+ ids = {span[0] for span in spans}
+ found: set[str] = set()
+ for name in affected_symbols(suggestion):
+ candidates = (
+ (name,)
+ if "::" in name
+ else (f"{file_path}::{name}", f"{file_path}::{name.replace('.', '::')}")
+ )
+ found.update(candidate for candidate in candidates if candidate in ids)
+ if found or not lines:
+ return sorted(found)
+ first, last = min(lines), max(lines)
+ enclosing = [
+ (end - start, symbol)
+ for symbol, start, end in spans
+ if start <= first and last <= end and not symbol.endswith("::__module__")
+ ]
+ return [min(enclosing)[1]] if enclosing else []
+
+
+def _symbol_label(symbol_id: str) -> str:
+ return symbol_id.split("::", 1)[-1].replace("::", ".")
+
+
+def _line_span(lines: set[int]) -> str:
+ first, last = min(lines), max(lines)
+ return f"line {first}" if first == last else f"lines {first}-{last}"
+
+
+# Sort keys put a test with no call path behind every test with one: past the
+# deepest call hop, an import of the file, then nothing but a name.
+_IMPORT_ONLY = 2 * DEFAULT_CALL_DEPTH + 1
+_NO_PATH = 2 * DEFAULT_CALL_DEPTH + 2
+
+# The same few hundred test paths are classified once per plan they guard;
+# the classifier is the hot spot of a whole-repository hydration.
+_is_support = functools.lru_cache(maxsize=8192)(is_test_support_path)
+
+RankedTest = tuple[tuple[int, ...], str]
+
+
+def _test_reason(
+ *,
+ name: str,
+ lines: set[int] | None,
+ hits: set[int],
+ edited: bool,
+ nearest: tuple[int, int, str] | None,
+ named_import: str | None,
+ reach: ReachDistance | None,
+ imported: frozenset[str] | None,
+ named: bool,
+ shared: list[str],
+) -> str:
+ """The strongest single piece of evidence, in the order the key ranks it."""
+ if hits:
+ return f"covers {_line_span(hits)}" if lines is not None else f"covers {name}"
+ if edited:
+ return "edited by this plan"
+ if nearest is not None and nearest[0] == 1:
+ callers = -nearest[1]
+ suffix = f" from {callers} test functions" if callers > 1 else ""
+ return f"calls {_symbol_label(nearest[2])}{suffix}"
+ if named_import is not None:
+ return f"imports {_symbol_label(named_import)}"
+ if nearest is not None:
+ return f"reaches {_symbol_label(nearest[2])} in {nearest[0]} calls"
+ if reach is not None:
+ return f"calls into {name}" if reach.hops == 1 else f"reaches {name} in {reach.hops} calls"
+ if imported is not None:
+ return f"imports {name.rsplit('.', 1)[0]}"
+ if named:
+ return f"named for {name}"
+ if shared:
+ return f"shares {'/'.join(shared)}"
+ return f"reaches {name}"
+
+
+def _rank_target_tests(
+ file_path: str,
+ lines: set[int] | None,
+ labels: set[str],
+ covered: Mapping[str, set[int]],
+ reached: ReachedBy | None,
+ symbol_ids: Sequence[str],
+ evidence: ValidationEvidence,
+ *,
+ plan_has_symbols: bool,
+) -> dict[str, RankedTest]:
+ """Each test's sort key and reason for one target file.
+
+ Most direct evidence first: measured coverage of the changed lines, then a
+ test naming the changed symbol (a direct call or an import of it), then
+ fewer call hops to it, then more of the test's functions at that distance,
+ then a test named for the file, then directory overlap. Test support
+ (``conftest.py``) runs nothing on its own, so it goes last.
+ """
+ name = file_path.rsplit("/", 1)[-1]
+ named_for = paired_test_names(file_path)
+ target_dirs = file_path.split("/")[:-1]
+ file_reach = reached.reach if reached is not None and reached.reach else {}
+ imports = evidence.imports.get(file_path, {})
+ out: dict[str, RankedTest] = {}
+ for label in labels:
+ path = label.split("::", 1)[0]
+ hits = covered.get(label) or set()
+ nearest = min(
+ (
+ (reach.hops, -reach.callers, symbol)
+ for symbol in symbol_ids
+ if (reach := evidence.symbol_reach.get(symbol, {}).get(path)) is not None
+ ),
+ default=None,
+ )
+ imported = imports.get(path)
+ named_import = next(
+ (
+ symbol
+ for symbol in symbol_ids
+ if _symbol_label(symbol).split(".", 1)[0] in (imported or ())
+ ),
+ None,
+ )
+ reach = file_reach.get(path)
+ # A test the plan itself edits (an importer a split rewrites) runs the
+ # change by definition.
+ edited = path == file_path
+ if edited:
+ distance, callers = 0, 0
+ elif nearest is not None:
+ distance, callers = nearest[0], -nearest[1]
+ elif reach is not None:
+ # A test that reaches the file but not the changed symbol ranks
+ # behind every test that reaches the symbol.
+ distance = reach.hops + (DEFAULT_CALL_DEPTH if plan_has_symbols else 0)
+ callers = reach.callers
+ else:
+ distance, callers = (_IMPORT_ONLY if imported is not None else _NO_PATH), 0
+ test_dirs = set(path.split("/")[:-1])
+ shared = [segment for segment in target_dirs if segment in test_dirs]
+ named = path.rsplit("/", 1)[-1] in named_for
+ references = (
+ edited or named_import is not None or (nearest is not None and nearest[0] == 1)
+ )
+ key = (
+ int(_is_support(path)),
+ 0 if hits else 1,
+ -len(hits),
+ 0 if references else 1,
+ distance,
+ -callers,
+ 0 if named else 1,
+ -len(shared),
+ )
+ out[label] = (
+ key,
+ _test_reason(
+ name=name,
+ lines=lines,
+ hits=hits,
+ edited=edited,
+ nearest=nearest,
+ named_import=named_import,
+ reach=reach,
+ imported=imported,
+ named=named,
+ shared=shared,
+ ),
+ )
+ return out
+
+
def _commands(tests: list[str], files: list[str], *, total: int | None = None) -> list[str]:
"""A command that runs at least everything the plan says validates it.
@@ -347,16 +567,22 @@ def _line_ranges(suggestion: RefactoringSuggestion) -> dict[str, set[int] | None
return ranges
-def _measured_labels(rows: list[dict[str, Any]], lines: set[int] | None) -> set[str]:
- labels: set[str] = set()
+def _measured_hits(rows: list[dict[str, Any]], lines: set[int] | None) -> dict[str, set[int]]:
+ """Measured tests and the lines of the target each one ran."""
+ hits: dict[str, set[int]] = {}
for row in rows:
covered = set(row.get("covered_lines") or [])
- if lines is not None and not lines.intersection(covered):
+ ran = covered if lines is None else lines & covered
+ if not ran:
continue
label = row.get("test_id") or row.get("test_file")
if isinstance(label, str) and label:
- labels.add(label)
- return labels
+ hits.setdefault(label, set()).update(ran)
+ return hits
+
+
+def _measured_labels(rows: list[dict[str, Any]], lines: set[int] | None) -> set[str]:
+ return set(_measured_hits(rows, lines))
def _validation_target(
@@ -365,8 +591,11 @@ def _validation_target(
measured: Mapping[str, list[dict[str, Any]]],
inferred: Mapping[str, ReachedBy],
cap: int,
-) -> tuple[ValidationTarget, set[str], bool]:
- labels = _measured_labels(measured.get(file_path, []), lines)
+ rank: Callable[[set[str], Mapping[str, set[int]], ReachedBy | None], dict[str, RankedTest]],
+) -> tuple[ValidationTarget, set[str], bool, dict[str, RankedTest]]:
+ covered = _measured_hits(measured.get(file_path, []), lines)
+ labels = set(covered)
+ reached = None
if labels:
basis: ValidationBasis = "measured"
via: ValidationVia | None = "coverage"
@@ -381,7 +610,8 @@ def _validation_target(
identities_complete = (
reached is None or reached.all_tests is not None or total == len(labels)
)
- ordered = rank_tests(file_path, labels)
+ ranked = rank(labels, covered, reached)
+ ordered = sorted(labels, key=lambda label: (ranked[label][0], label))
return (
ValidationTarget(
file_path=file_path,
@@ -393,6 +623,7 @@ def _validation_target(
),
labels,
identities_complete,
+ ranked,
)
@@ -402,17 +633,57 @@ def build_validation_plan(
inferred: Mapping[str, ReachedBy],
*,
test_limit: int = DEFAULT_TEST_LIMIT,
+ evidence: ValidationEvidence | None = None,
+ order_tests: bool = True,
) -> ValidationPlan:
- """Resolve target evidence in strict measured/call/import precedence."""
+ """Resolve target evidence in strict measured/call/import precedence.
+
+ Tests are ordered by how directly they exercise what the plan changes
+ (:func:`_rank_target_tests`). A test reaching several of the plan's files
+ keeps its best evidence, and ties go to the one reaching more of them.
+ """
cap = max(0, test_limit)
+ facts = evidence or ValidationEvidence()
+ ranges = sorted(_line_ranges(suggestion).items())
+ symbols = {
+ path: target_symbol_ids(suggestion, path, lines, facts.symbols.get(path, ()))
+ for path, lines in ranges
+ }
+ plan_has_symbols = any(symbols.values())
target_rows: list[ValidationTarget] = []
- ranked: dict[str, None] = {}
+ best: dict[str, RankedTest] = {}
+ by_file: dict[str, set[str]] = {}
identities_complete = True
- for file_path, lines in sorted(_line_ranges(suggestion).items()):
- target, labels, target_complete = _validation_target(
- file_path, lines, measured, inferred, cap
+ for file_path, lines in ranges:
+
+ def rank(
+ labels: set[str],
+ covered: Mapping[str, set[int]],
+ reached: ReachedBy | None,
+ path: str = file_path,
+ span: set[int] | None = lines,
+ ) -> dict[str, RankedTest]:
+ if not order_tests:
+ # A rank-only pass needs the evidence basis, not the order.
+ return {label: ((), "") for label in labels}
+ return _rank_target_tests(
+ path,
+ span,
+ labels,
+ covered,
+ reached,
+ symbols[path],
+ facts,
+ plan_has_symbols=plan_has_symbols,
+ )
+
+ target, labels, target_complete, ranked = _validation_target(
+ file_path, lines, measured, inferred, cap, rank
)
- ranked.update(dict.fromkeys(rank_tests(file_path, labels)))
+ by_file[file_path] = labels
+ for test, scored in ranked.items():
+ if test not in best or scored[0] < best[test][0]:
+ best[test] = scored
identities_complete = identities_complete and target_complete
target_rows.append(target)
@@ -425,7 +696,8 @@ def build_validation_plan(
aggregate_via: ValidationVia | None = (
None if not vias else next(iter(vias)) if len(vias) == 1 else "mixed"
)
- ordered_tests = list(ranked)
+ reach_order = {test: index for index, test in enumerate(rank_tests_by_reach(by_file))}
+ ordered_tests = sorted(best, key=lambda test: (best[test][0], reach_order[test]))
aggregate_total = (
len(ordered_tests)
if identities_complete
@@ -444,6 +716,7 @@ def build_validation_plan(
affected_symbols=affected_symbols(suggestion),
commands=_commands(ordered_tests[:cap], files, total=aggregate_total),
targets=target_rows,
+ reasons={test: best[test][1] for test in ordered_tests[:cap]} if order_tests else {},
)
@@ -459,6 +732,8 @@ class Recommendation:
file_nloc: int
file_weighted_deficit: int
validation: ValidationPlan
+ # The reads a rank-only pass made, so detailing a page reuses them.
+ inputs: ValidationInputs | None = field(default=None, repr=False, compare=False)
@property
def id(self) -> str:
@@ -619,15 +894,20 @@ async def hydrate_recommendations(
metric_rows: Sequence[Any] | None = None,
view: RecommendationView = "canonical",
test_limit: int = DEFAULT_TEST_LIMIT,
+ rank_only: bool = False,
) -> list[Recommendation]:
"""Hydrate, enrich, validate, rank, and serialize-ready all *rows*.
Query shape is constant in plan/test count: health metrics and graph metrics
are bulk reads, measured coverage is one ``IN`` query, and inferred walks
use their existing bounded level queries over the complete unanswered set.
+
+ *rank_only* skips the symbol-level evidence that orders each plan's tests:
+ rank and validation basis are unchanged, the test order falls back to name
+ and directory. A paged surface ranks every row this way, then passes the
+ rows it returns through :func:`detail_recommendations`.
"""
from repowise.core.persistence import crud
- from repowise.core.persistence.crud.analysis.coverage_map import tests_covering_files
if not rows:
return []
@@ -641,9 +921,101 @@ async def hydrate_recommendations(
centrality = {
node_id: float(metric.get("in_degree") or 0.0) for node_id, metric in graph_metrics.items()
}
+ plans, inputs = await _validation_plans(
+ session, repository_id, suggestions, test_limit=test_limit, detailed=not rank_only
+ )
+ recommendations = build_recommendations(
+ suggestions,
+ metric_by_path={metric.file_path: metric for metric in metrics},
+ centrality=centrality,
+ validations=dict(enumerate(plans)),
+ )
+ if rank_only:
+ recommendations = [dataclasses.replace(item, inputs=inputs) for item in recommendations]
+ return apply_view(recommendations, view)
+
+
+async def detail_recommendations(
+ session: AsyncSession,
+ repository_id: str,
+ recommendations: Sequence[Recommendation],
+ *,
+ test_limit: int = DEFAULT_TEST_LIMIT,
+) -> list[Recommendation]:
+ """*recommendations* with their tests ordered by full evidence, same order.
+
+ Only the validation is rebuilt; rank, benefit and the rest come from the
+ pass that ranked them, so a page detailed here matches a full hydration.
+ """
+ if not recommendations:
+ return []
+ suggestions = [item.suggestion for item in recommendations]
+ shared = {id(item.inputs): item.inputs for item in recommendations}
+ plans, _ = await _validation_plans(
+ session,
+ repository_id,
+ suggestions,
+ test_limit=test_limit,
+ detailed=True,
+ inputs=next(iter(shared.values())) if len(shared) == 1 else None,
+ )
+ out = []
+ for item, plan in zip(recommendations, plans, strict=True):
+ item.suggestion.validation = plan.as_dict()
+ out.append(dataclasses.replace(item, validation=plan))
+ return out
+
+
+async def _validation_plans(
+ session: AsyncSession,
+ repository_id: str,
+ suggestions: Sequence[RefactoringSuggestion],
+ *,
+ test_limit: int,
+ detailed: bool,
+ inputs: ValidationInputs | None = None,
+) -> tuple[list[ValidationPlan], ValidationInputs]:
+ """One validation plan per suggestion, every read batched across the set.
+
+ *inputs* from an earlier pass over a superset of these suggestions skips
+ the coverage read and the reachability walk; only the symbol evidence is
+ read again, and only for these suggestions.
+ """
target_files = sorted(
{path for suggestion in suggestions for path in affected_files(suggestion)}
)
+ if inputs is None:
+ inputs = await _validation_inputs(session, repository_id, suggestions, target_files)
+ evidence = (
+ await _validation_evidence(
+ session, repository_id, suggestions, target_files, inputs.test_files
+ )
+ if detailed
+ else None
+ )
+ plans = [
+ build_validation_plan(
+ suggestion,
+ inputs.measured,
+ inputs.inferred,
+ test_limit=test_limit,
+ evidence=evidence,
+ order_tests=detailed,
+ )
+ for suggestion in suggestions
+ ]
+ return plans, inputs
+
+
+async def _validation_inputs(
+ session: AsyncSession,
+ repository_id: str,
+ suggestions: Sequence[RefactoringSuggestion],
+ target_files: Sequence[str],
+) -> ValidationInputs:
+ """Measured coverage and the tiered reachability walk for every plan's files."""
+ from repowise.core.persistence.crud.analysis.coverage_map import tests_covering_files
+
measured = await tests_covering_files(session, repository_id, set(target_files))
# A measured row only answers a target when it intersects the plan's line
@@ -654,27 +1026,58 @@ async def hydrate_recommendations(
for file_path, lines in _line_ranges(suggestion).items():
if not _measured_labels(measured.get(file_path, []), lines):
unanswered.add(file_path)
+ test_files = await load_test_files(session, repository_id)
inferred = (
- await tests_reaching_by_tier(session, repository_id, sorted(unanswered))
+ await tests_reaching_by_tier(
+ session, repository_id, sorted(unanswered), test_files=test_files
+ )
if unanswered
else {}
)
unreached = sorted(unanswered - inferred.keys())
if unreached:
- inferred.update(
- tests_matching_by_name(unreached, await load_test_files(session, repository_id))
- )
- validations = {
- index: build_validation_plan(suggestion, measured, inferred, test_limit=test_limit)
- for index, suggestion in enumerate(suggestions)
+ inferred.update(tests_matching_by_name(unreached, test_files))
+ return ValidationInputs(measured=measured, inferred=inferred, test_files=test_files)
+
+
+async def _validation_evidence(
+ session: AsyncSession,
+ repository_id: str,
+ suggestions: Sequence[RefactoringSuggestion],
+ target_files: Sequence[str],
+ test_files: set[str],
+) -> ValidationEvidence:
+ """Symbol spans, symbol-level reach and test imports for every plan at once.
+
+ Bounded reads over the whole plan set (the symbol walk is one ``IN`` query
+ per hop), so adding plans adds no statements.
+ """
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import GraphNode
+
+ if not target_files:
+ return ValidationEvidence()
+ rows = await session.execute(
+ select(GraphNode.file_path, GraphNode.node_id, GraphNode.start_line, GraphNode.end_line)
+ .where(GraphNode.repository_id == repository_id)
+ .where(GraphNode.node_type == "symbol")
+ .where(GraphNode.file_path.in_(list(target_files)))
+ )
+ spans: dict[str, list[SymbolSpan]] = {}
+ for file_path, node_id, start, end in rows:
+ spans.setdefault(file_path, []).append((node_id, int(start or 0), int(end or 0)))
+ symbol_ids = {
+ symbol
+ for suggestion in suggestions
+ for file_path, lines in _line_ranges(suggestion).items()
+ for symbol in target_symbol_ids(suggestion, file_path, lines, spans.get(file_path, ()))
}
- recommendations = build_recommendations(
- suggestions,
- metric_by_path={metric.file_path: metric for metric in metrics},
- centrality=centrality,
- validations=validations,
+ return ValidationEvidence(
+ symbols=spans,
+ symbol_reach=await reach_into_symbols(session, repository_id, symbol_ids, test_files),
+ imports=await imported_names_by_test(session, repository_id, target_files, test_files),
)
- return apply_view(recommendations, view)
def serialize_recommendations(
@@ -689,6 +1092,7 @@ __all__ = [
"EFFORT_COST",
"Recommendation",
"RecommendationView",
+ "ValidationEvidence",
"ValidationPlan",
"ValidationTarget",
"affected_files",
@@ -698,6 +1102,7 @@ __all__ = [
"build_recommendations",
"build_validation_plan",
"canonical_order",
+ "detail_recommendations",
"detector_native_benefit",
"enrich_blast_radius",
"hydrate_recommendations",
@@ -705,4 +1110,5 @@ __all__ = [
"rehydrate_suggestion",
"serialize_recommendations",
"surface_confidence_risk",
+ "target_symbol_ids",
]
diff --git a/packages/core/src/repowise/core/analysis/test_reachability.py b/packages/core/src/repowise/core/analysis/test_reachability.py
index 4ac118f01..1be4a8d90 100644
--- a/packages/core/src/repowise/core/analysis/test_reachability.py
+++ b/packages/core/src/repowise/core/analysis/test_reachability.py
@@ -151,7 +151,7 @@ import json
from collections.abc import Collection, Mapping
from dataclasses import dataclass
from pathlib import PurePosixPath
-from typing import Any, Literal, TypeAlias
+from typing import Any, Literal, NamedTuple, TypeAlias
from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession
@@ -194,14 +194,17 @@ __all__ = [
"MAX_TESTS_PER_TARGET",
"UNRELIABLE_CALL_ORIGINS",
"CallGraphView",
+ "ReachDistance",
"ReachedBy",
"call_graph_from_db",
"call_graph_from_graph",
"direct_dependents",
"files_reached_by_tests",
"files_with_paired_tests",
+ "imported_names_by_test",
"load_test_files",
"rank_tests",
+ "reach_into_symbols",
"tests_matching_by_name",
"tests_reaching",
"tests_reaching_by_tier",
@@ -211,6 +214,14 @@ __all__ = [
CallGraphView: TypeAlias = ExecutionGraphIndex
+class ReachDistance(NamedTuple):
+ """How a test reached a seed: the fewest call hops, and how many of the
+ test's symbols made a call at that depth."""
+
+ hops: int
+ callers: int
+
+
@dataclass(frozen=True)
class ReachedBy:
"""Tests reaching one target, and which tier found them.
@@ -228,6 +239,9 @@ class ReachedBy:
# Internal uncapped identities let downstream aggregators de-duplicate one
# test that reaches several targets while public lists remain bounded.
all_tests: tuple[str, ...] | None = None
+ # How close each test came, for the call tier only: the import and name
+ # tiers have no hop count to report.
+ reach: Mapping[str, ReachDistance] | None = None
def call_graph_from_graph(graph: Any) -> CallGraphView:
@@ -497,10 +511,10 @@ async def tests_reaching_by_tier(
found = await _call_reaching(
session, repo_id, seeds, test_files, call_depth, symbol_seeds=symbol_seeds
)
- for seed, tests in found.items():
- ordered = tuple(rank_tests(seed.split("::", 1)[0], tests))
+ for seed, reach in found.items():
+ ordered = tuple(rank_tests(seed.split("::", 1)[0], reach))
out[seed] = ReachedBy(
- list(ordered[:MAX_TESTS_PER_TARGET]), "call-graph", len(ordered), ordered
+ list(ordered[:MAX_TESTS_PER_TARGET]), "call-graph", len(ordered), ordered, reach
)
unanswered = [seed for seed in seeds if seed not in out]
@@ -522,14 +536,27 @@ async def _call_reaching(
max_depth: int,
*,
symbol_seeds: Mapping[str, Collection[str]] | None = None,
-) -> dict[str, set[str]]:
+ strict: bool = False,
+) -> dict[str, dict[str, ReachDistance]]:
"""Tests that can execute into each seed file, walking call edges backwards.
Starts one layer below the other walk: the seeds are files and call edges
join symbols, so the first query resolves each seed to the symbols it
declares, and the walk carries the seed from there.
+
+ Each test carries the fewest call hops it took and how many of its symbols
+ made a call at that depth. Every node records each seed's distance, not
+ the level it was found at: one level's batch can carry a seed through a
+ node another seed entered, so the level alone overstates how close a test
+ is. A shorter distance found later re-queues the node; which tests reach
+ which seed is unchanged by that, only how far.
+
+ *strict* reads each level against the distances it started with, so a seed
+ moves one hop per level and its answer does not depend on which other
+ seeds share the walk. The file tiers keep the historical batch semantics.
"""
- origins: dict[str, set[str]] = {}
+ # node -> seed -> call hops from the node to the seed.
+ origins: dict[str, dict[str, int]] = {}
# A caller that knows which symbol in the file it cares about enters there,
# so a test reaching an unrelated symbol in the same file does not count.
# An empty entry names no symbol, so that file is unseeded and keeps the
@@ -541,22 +568,23 @@ async def _call_reaching(
}
for seed, symbol_ids in seeded.items():
for symbol in symbol_ids:
- origins.setdefault(symbol, set()).add(seed)
+ origins.setdefault(symbol, {})[seed] = 0
unseeded = [seed for seed in seeds if seed not in seeded]
if unseeded:
declared = await _edges_from(session, repo_id, unseeded, ["defines"])
for seed, symbol in declared:
- origins.setdefault(symbol, set()).add(seed)
+ origins.setdefault(symbol, {})[seed] = 0
if not origins:
return {}
- found: dict[str, set[str]] = {}
+ found: dict[str, dict[str, tuple[int, set[str]]]] = {}
frontier = list(origins)
for _ in range(max_depth):
if not frontier:
break
level, frontier = frontier, []
queued: set[str] = set()
+ start = {node: dict(origins[node]) for node in level} if strict else origins
for caller, callee in await _edges_into(
session,
repo_id,
@@ -564,25 +592,103 @@ async def _call_reaching(
sorted(EXECUTION_EDGE_TYPES),
UNRELIABLE_CALL_ORIGINS,
):
- carried = origins.get(callee)
+ carried = start.get(callee)
if not carried:
continue
owner = file_of_symbol(caller)
if owner in test_files:
- for seed in carried:
- found.setdefault(seed, set()).add(owner)
+ for seed, distance in carried.items():
+ hops = distance + 1
+ by_test = found.setdefault(seed, {})
+ best = by_test.get(owner)
+ if best is None or hops < best[0]:
+ by_test[owner] = (hops, {caller})
+ elif hops == best[0]:
+ best[1].add(caller)
# A test is a leaf. Walking through one would let "test A calls
# shared helper B" drag B's unrelated targets in.
continue
- known = origins.setdefault(caller, set())
- fresh = carried - known
- if not fresh:
+ known = origins.setdefault(caller, {})
+ closer = {
+ seed: distance + 1
+ for seed, distance in carried.items()
+ if seed not in known or distance + 1 < known[seed]
+ }
+ if not closer:
continue
- known |= fresh
+ known.update(closer)
if caller not in queued:
queued.add(caller)
frontier.append(caller)
- return found
+ return {
+ seed: {test: ReachDistance(depth, len(callers)) for test, (depth, callers) in tests.items()}
+ for seed, tests in found.items()
+ }
+
+
+async def reach_into_symbols(
+ session: AsyncSession,
+ repo_id: str,
+ symbol_ids: Collection[str],
+ test_files: set[str],
+ *,
+ max_depth: int = DEFAULT_CALL_DEPTH,
+) -> dict[str, dict[str, ReachDistance]]:
+ """Tests that call into each symbol id, keyed by the symbol, with their hops.
+
+ The file walk answers "does a test reach this file"; this one answers how
+ close each test gets to one symbol in it, which is what decides which of a
+ file's many tests to run first after changing that symbol.
+ """
+ seeds = sorted({symbol for symbol in symbol_ids if symbol})
+ if not seeds or not test_files:
+ return {}
+ return await _call_reaching(
+ session,
+ repo_id,
+ seeds,
+ test_files,
+ max_depth,
+ symbol_seeds={symbol: (symbol,) for symbol in seeds},
+ strict=True,
+ )
+
+
+async def imported_names_by_test(
+ session: AsyncSession, repo_id: str, files: Collection[str], test_files: set[str]
+) -> dict[str, dict[str, frozenset[str]]]:
+ """The names each test file imports from each of *files*, keyed by file then test.
+
+ An empty set is an import of the module itself. One query, one hop: what a
+ test names, not what it reaches.
+ """
+ targets = sorted({path for path in files if path})
+ if not targets or not test_files:
+ return {}
+ params: dict[str, Any] = {"repo_id": repo_id}
+ tgt = _in_clause("p", targets, params)
+ ets = _in_clause("e", sorted(FILE_DEPENDENCY_EDGE_TYPES), params)
+ rows = await session.execute(
+ text(
+ "SELECT source_node_id, target_node_id, imported_names_json FROM graph_edges "
+ "WHERE repository_id = :repo_id "
+ f"AND target_node_id IN ({tgt}) AND edge_type IN ({ets})"
+ ),
+ params,
+ )
+ out: dict[str, dict[str, frozenset[str]]] = {}
+ for source, target, names_json in rows:
+ if source not in test_files:
+ continue
+ try:
+ names = json.loads(names_json or "[]")
+ except (TypeError, ValueError):
+ names = []
+ by_test = out.setdefault(target, {})
+ by_test[source] = by_test.get(source, frozenset()) | frozenset(
+ name for name in names if isinstance(name, str)
+ )
+ return out
async def _import_reaching(
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
index 9cc8a7363..478d2cd5e 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
@@ -21,6 +21,7 @@ from repowise.core.analysis.health.perf.coverage import PerfCoverage, coverage_f
from repowise.core.analysis.health.ranking import deduction_by_path, sort_metrics_worst_first
from repowise.core.analysis.health.refactoring.recommendations import (
Recommendation,
+ detail_recommendations,
hydrate_recommendations,
)
from repowise.core.analysis.health.signals import file_signals
@@ -237,7 +238,17 @@ async def _read_refactoring_plans(
rows,
metric_rows=pop.all_metrics,
view=plan_view(req.refactoring_view),
+ rank_only=True,
)
+ # Every row is ranked; only the page the response emits, and the lede's
+ # lead plan, need the evidence that orders their tests.
+ shown = {0, *range(req.cursor, req.cursor + req.plans_cap)}
+ indexes = [index for index in sorted(shown) if index < len(recommendations)]
+ detailed = await detail_recommendations(
+ session, repository.id, [recommendations[index] for index in indexes]
+ )
+ for index, item in zip(indexes, detailed, strict=True):
+ recommendations[index] = item
return rows, recommendations
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/plans.py b/packages/server/src/repowise/server/mcp_server/tool_health/plans.py
index c9f604670..b51998d32 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/plans.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/plans.py
@@ -31,7 +31,7 @@ def _render_plans(
validation_profiles: dict[str, dict[str, Any]] = {}
plan_payload = []
for recommendation in pager.bound(
- recommendations, "refactoring_plans", cap=min(req.limit, 6)
+ recommendations, "refactoring_plans", cap=req.plans_cap
):
payload = _serialize_refactoring(recommendation, data.reference_repository)
validation = payload.pop("validation", None)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/request.py b/packages/server/src/repowise/server/mcp_server/tool_health/request.py
index e273cf04e..c497f8957 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/request.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/request.py
@@ -109,6 +109,11 @@ class HealthRequest:
t.replace("\\", "/") for t in self.raw_targets if not t.startswith("module:")
]
+ @property
+ def plans_cap(self) -> int:
+ """How many refactoring plans one response emits, whatever ``limit`` says."""
+ return min(self.limit, 6)
+
def wants(self, block: str) -> bool:
"""True when ``block`` survives the ``only`` projection.
diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.py
index b526c4aff..0e9290b61 100644
--- a/packages/server/src/repowise/server/routers/refactoring.py
+++ b/packages/server/src/repowise/server/routers/refactoring.py
@@ -22,6 +22,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.refactoring.recommendations import (
apply_view,
blast_size,
+ detail_recommendations,
hydrate_recommendations,
)
from repowise.core.analysis.health.refactoring_summary import STRUCTURAL_TYPES, summarize_plans
@@ -276,12 +277,15 @@ async def get_refactoring_plan_page(
) -> RefactoringPlanPageResponse:
"""Bounded list with server-owned filters and deterministic ordering.
- Hydration remains one batched pass over the repository plans so validation
- and priority have exactly the Phase 3 semantics and a constant SQL shape.
- Only the requested page crosses the wire.
+ Ranking is one batched pass over the repository plans, so priority keeps its
+ validation-basis input and a constant SQL shape. The symbol-level evidence
+ that orders each plan's tests is read only for the rows this response
+ returns.
"""
rows = await crud.get_refactoring_suggestions(session, repo_id, min_confidence=min_confidence)
- canonical = await hydrate_recommendations(session, repo_id, rows, view="canonical")
+ canonical = await hydrate_recommendations(
+ session, repo_id, rows, view="canonical", rank_only=True
+ )
summary = _summary(canonical)
structural_leads = [
item for item in canonical if item.suggestion.refactoring_type in _STRUCTURAL_TYPES
@@ -310,6 +314,13 @@ async def get_refactoring_plan_page(
total = len(ordered)
page = ordered[offset : offset + limit]
next_offset = offset + len(page) if offset + len(page) < total else None
+ shown = list({id(item): item for item in [*page, *structural_leads]}.values())
+ detailed = {
+ id(item.suggestion): item
+ for item in await detail_recommendations(session, repo_id, shown)
+ }
+ page = [detailed[id(item.suggestion)] for item in page]
+ structural_leads = [detailed[id(item.suggestion)] for item in structural_leads]
return RefactoringPlanPageResponse(
items=[_to_response(item.as_dict()) for item in page],
total=total,
diff --git a/packages/server/src/repowise/server/services/performance_health.py b/packages/server/src/repowise/server/services/performance_health.py
index 8bc088194..504298642 100644
--- a/packages/server/src/repowise/server/services/performance_health.py
+++ b/packages/server/src/repowise/server/services/performance_health.py
@@ -588,7 +588,7 @@ def _plan_brief(plan: dict[str, Any] | None) -> dict[str, Any]:
if not plan:
return {}
validation = plan.get("validation") or {}
- keys = ("basis", "via", "total", "tests", "commands")
+ keys = ("basis", "via", "total", "tests", "reasons", "commands")
return {
"validation": {key: validation.get(key) for key in keys},
"plan_steps": plan.get("steps", []),
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index 12db48ac5..721e3119b 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -414,6 +414,8 @@ export interface PerformanceOpportunityValidation {
via: ValidationVia | null;
total: number;
tests: string[];
+ /** Why each test is listed, keyed by test id. Null on a store written before it. */
+ reasons?: Record<string, string> | null;
commands: string[];
}
diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.ts
index cd0506d15..551953fbe 100644
--- a/packages/types/src/refactoring.ts
+++ b/packages/types/src/refactoring.ts
@@ -35,6 +35,9 @@ export interface RecommendationValidation {
affected_symbols: string[];
commands: string[];
targets: RecommendationValidationTarget[];
+ /** Why each shown test is listed where it is ("calls walk_file", "covers lines
+ * 94-208"), keyed by test id. Absent on a payload from an older server. */
+ reasons?: Record<string, string>;
}
export interface RefactoringPlan {
diff --git a/packages/ui/__tests__/health/refactoring-verify-prompt.test.ts b/packages/ui/__tests__/health/refactoring-verify-prompt.test.ts
new file mode 100644
index 000000000..5aeb12225
--- /dev/null
+++ b/packages/ui/__tests__/health/refactoring-verify-prompt.test.ts
@@ -0,0 +1,181 @@
+/**
+ * The agent handoff names the tests to run after the change, in the server's
+ * relevance order with its reasons, or tells the agent to write one first.
+ */
+import { describe, expect, it } from "vitest";
+import type { PerformanceOpportunity } from "@repowise-dev/types/health";
+import type {
+ RecommendationValidation,
+ RefactoringOpportunityDetailResolved,
+ RefactoringPlan,
+} from "@repowise-dev/types/refactoring";
+
+import {
+ buildPerformanceOpportunityPrompt,
+ buildRefactoringOpportunityPrompt,
+ buildRefactoringPlanPrompt,
+} from "../../src/health/ai-prompt-builder";
+
+function validation(overrides: Partial<RecommendationValidation> = {}): RecommendationValidation {
+ return {
+ basis: "inferred",
+ via: "call-graph",
+ total: 34,
+ tests: ["tests/unit/health/test_complexity_walker.py", "tests/unit/health/test_file_nloc.py"],
+ truncated: true,
+ affected_files: ["pkg/walker.py"],
+ affected_symbols: ["walk_file"],
+ commands: ["pytest tests/unit/health/test_complexity_walker.py tests/unit/health/test_file_nloc.py"],
+ targets: [],
+ reasons: {
+ "tests/unit/health/test_complexity_walker.py": "calls walk_file from 9 test functions",
+ "tests/unit/health/test_file_nloc.py": "imports walk_file",
+ },
+ ...overrides,
+ };
+}
+
+function plan(v: RecommendationValidation | undefined): RefactoringPlan {
+ return {
+ id: "refac2_walk",
+ refactoring_type: "extract_method",
+ file_path: "pkg/walker.py",
+ target_symbol: "walk_file",
+ line_start: 94,
+ line_end: 208,
+ plan: { span: { start: 120, end: 140 }, params: [], returns: [] },
+ evidence: {},
+ impact_delta: 1.2,
+ effort_bucket: "M",
+ blast_radius: {},
+ confidence: "high",
+ source_biomarker: "complex_method",
+ rank_score: 1,
+ ...(v ? { validation: v } : {}),
+ };
+}
+
+describe("Verify section", () => {
+ it("lists the ranked tests with their reasons, then the command", () => {
+ const prompt = buildRefactoringPlanPrompt({ plan: plan(validation()) });
+ const verify = prompt.slice(prompt.indexOf("## Verify"));
+ expect(verify).toContain(
+ "- `tests/unit/health/test_complexity_walker.py` (calls walk_file from 9 test functions)\n" +
+ "- `tests/unit/health/test_file_nloc.py` (imports walk_file)",
+ );
+ expect(verify).toContain("2 of 34 guarding tests shown.");
+ expect(verify).toContain(
+ "```\npytest tests/unit/health/test_complexity_walker.py tests/unit/health/test_file_nloc.py\n```",
+ );
+ // The order the server ranked is the order the agent reads.
+ expect(verify.indexOf("test_complexity_walker")).toBeLessThan(verify.indexOf("test_file_nloc"));
+ });
+
+ it("tells the agent to add a test when nothing guards the symbol", () => {
+ const prompt = buildRefactoringPlanPrompt({
+ plan: plan(
+ validation({ basis: "unknown", via: null, total: 0, tests: [], commands: [], reasons: {} }),
+ ),
+ });
+ expect(prompt).toContain(
+ "No guarding tests found: add a test for `walk_file` before changing it.",
+ );
+ });
+
+ it("renders a test without a reason from an older server", () => {
+ const { reasons: _dropped, ...older } = validation();
+ const prompt = buildRefactoringPlanPrompt({ plan: plan(older) });
+ expect(prompt).toContain("- `tests/unit/health/test_file_nloc.py`\n");
+ });
+
+ it("says nothing about tests when the payload carries no validation", () => {
+ expect(buildRefactoringPlanPrompt({ plan: plan(undefined) })).not.toContain("## Verify");
+ });
+
+ it("names a profile's step symbols in the opportunity prompt", () => {
+ const empty = validation({ basis: "unknown", via: null, total: 0, tests: [], commands: [] });
+ const opportunity = {
+ opportunity_id: "opp_1",
+ file_path: "pkg/walker.py",
+ lead_refactoring_type: "extract_method",
+ lead_biomarker: "complex_method",
+ step_count: 1,
+ mechanical_steps: 1,
+ judgment_steps: 0,
+ recoverable_health: 1,
+ effort_bucket: "M",
+ confidence: "high",
+ addresses_primary_problem: true,
+ affected_files: ["pkg/walker.py"],
+ steps: [
+ {
+ plan_id: "refac2_walk",
+ refactoring_type: "extract_method",
+ target_symbol: "walk_file",
+ file_path: "pkg/walker.py",
+ line_start: 94,
+ line_end: 208,
+ effort_bucket: "M",
+ confidence: "high",
+ impact_delta: 1,
+ source_biomarker: "complex_method",
+ relocated_by: null,
+ applicability: { classification: "mechanical", reasons: [], unknowns: [] },
+ validation_profile_id: "validation_a",
+ },
+ ],
+ evidence: [],
+ evidence_emitted: 0,
+ evidence_truncated: false,
+ validation_profiles: [{ id: "validation_a", ...empty }],
+ plans: [plan(empty)],
+ next_actions: [],
+ } as unknown as RefactoringOpportunityDetailResolved;
+ const prompt = buildRefactoringOpportunityPrompt({ opportunity });
+ expect(prompt).toContain("## Verify");
+ expect(prompt).toContain(
+ "No guarding tests found: add a test for `walk_file` before changing it.",
+ );
+ });
+
+ it("adds Verify to the performance handoff when the queue carries validation", () => {
+ const opportunity = {
+ opportunity_id: "perf_1",
+ biomarker_type: "n_plus_one",
+ execution_context: "request",
+ boundary_kind: "database",
+ confidence: "high",
+ provenance: "call_graph",
+ affected_call_sites_total: 3,
+ affected_files_total: 1,
+ intervention_symbol: "pkg/decision_graph.py::sync_links_from_record",
+ terminal_sink: null,
+ file_path: "pkg/decision_graph.py",
+ plan_reason: "A stored plan exists.",
+ evidence: [],
+ validation: {
+ basis: "inferred",
+ via: "call-graph",
+ total: 1,
+ tests: ["tests/test_decision_graph.py"],
+ reasons: { "tests/test_decision_graph.py": "calls sync_links_from_record" },
+ commands: ["pytest tests/test_decision_graph.py"],
+ },
+ } as unknown as PerformanceOpportunity;
+ const prompt = buildPerformanceOpportunityPrompt({ opportunity });
+ expect(prompt).toContain(
+ "- `tests/test_decision_graph.py` (calls sync_links_from_record)",
+ );
+ expect(prompt.indexOf("## Verify")).toBeLessThan(prompt.indexOf("## What to do"));
+
+ const bare = buildPerformanceOpportunityPrompt({
+ opportunity: {
+ ...opportunity,
+ validation: { ...opportunity.validation!, total: 0, tests: [], commands: [] },
+ },
+ });
+ expect(bare).toContain(
+ "No guarding tests found: add a test for `sync_links_from_record` before changing it.",
+ );
+ });
+});
diff --git a/packages/ui/__tests__/refactoring/opportunity-prompt.test.ts b/packages/ui/__tests__/refactoring/opportunity-prompt.test.ts
index c80f2f3ce..df1e09761 100644
--- a/packages/ui/__tests__/refactoring/opportunity-prompt.test.ts
+++ b/packages/ui/__tests__/refactoring/opportunity-prompt.test.ts
@@ -222,7 +222,7 @@ describe("buildRefactoringOpportunityPrompt", () => {
it("carries the runnable validation commands", () => {
const text = buildRefactoringOpportunityPrompt({ opportunity: detail() });
- expect(text).toContain("## Validation plan");
+ expect(text).toContain("## Verify");
expect(text).toContain("pytest tests/test_big.py");
expect(text).toMatch(/3 guarding tests via coverage/);
});
@@ -234,7 +234,7 @@ describe("buildRefactoringOpportunityPrompt", () => {
const text = buildRefactoringOpportunityPrompt({
opportunity: detail({ validation_profiles: profiles }),
});
- expect(text).toMatch(/treat this as a validation gap/);
+ expect(text).toMatch(/No guarding tests found: add a test for `[^`]+`.* before changing it\./);
});
it("tells the agent to keep the co-affected files consistent", () => {
diff --git a/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts b/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts
index 6dd06fa49..2ec787f2c 100644
--- a/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts
+++ b/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts
@@ -113,7 +113,7 @@ describe("extract_method suggested_name reaches the rendered prompt", () => {
},
};
const prompt = buildRefactoringPlanPrompt({ plan });
- expect(prompt).toContain("## Validation plan");
+ expect(prompt).toContain("## Verify");
expect(prompt).toContain("guarding test via coverage");
expect(prompt).toContain("tests/test_pipeline.py::test_average");
expect(prompt).toContain("pytest tests/test_pipeline.py::test_average");
diff --git a/packages/ui/__tests__/refactoring/validation-summary.test.tsx b/packages/ui/__tests__/refactoring/validation-summary.test.tsx
new file mode 100644
index 000000000..cfaf6e9fc
--- /dev/null
+++ b/packages/ui/__tests__/refactoring/validation-summary.test.tsx
@@ -0,0 +1,27 @@
+/** Each listed test carries the server's reason for listing it, when it sent one. */
+import { describe, expect, it } from "vitest";
+import { render } from "@testing-library/react";
+import type { RecommendationValidation } from "@repowise-dev/types/refactoring";
+
+import { ValidationSummary } from "../../src/refactoring/validation-summary";
+
+const validation: RecommendationValidation = {
+ basis: "inferred",
+ via: "call-graph",
+ total: 2,
+ tests: ["tests/test_walker.py", "tests/test_other.py"],
+ truncated: false,
+ affected_files: [],
+ affected_symbols: [],
+ commands: [],
+ targets: [],
+ reasons: { "tests/test_walker.py": "calls walk_file" },
+};
+
+describe("ValidationSummary", () => {
+ it("shows a test's reason under it, and nothing for a test without one", () => {
+ const { getAllByRole } = render(<ValidationSummary validation={validation} />);
+ const rows = getAllByRole("listitem").map((row) => row.textContent);
+ expect(rows).toEqual(["tests/test_walker.pycalls walk_file", "tests/test_other.py"]);
+ });
+});
diff --git a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts
index 4a7eecae5..3bfabbfdc 100644
--- a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts
+++ b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts
@@ -147,3 +147,60 @@ export function refactoringPlanSteps(plan: RefactoringPlan): string {
const render = PLAN_STEPS.get(plan.refactoring_type);
return render ? render(plan) : "Apply the refactoring described above.";
}
+
+/** The validation fields the Verify block reads; refactoring plans, opportunity
+ * profiles and the performance queue all carry them. */
+export interface VerifyValidation {
+ total: number;
+ tests: string[];
+ reasons?: Record<string, string> | null | undefined;
+ commands: string[];
+}
+
+/** What a missing test should exercise: the changed symbol, or the file for a
+ * plan that changes a whole file (a split, a cycle). Stored ids lose their path. */
+export function verifySubject(plan: RefactoringPlan): string {
+ if (plan.refactoring_type === "split_file" || plan.refactoring_type === "break_cycle") {
+ return plan.file_path;
+ }
+ return plan.target_symbol.split("::").pop() || plan.file_path;
+}
+
+/** The tests to run after the change, most direct first, each with why it is
+ * listed, then the command. With no guarding test, the instruction to add one. */
+export function verifyLines(validation: VerifyValidation, subjects: string[]): string[] {
+ if (validation.tests.length === 0) {
+ return validation.total > 0
+ ? [`Guarding tests: ${validation.total}, but none were included in this payload.`]
+ : [
+ `No guarding tests found: add a test for ${subjects.map((s) => `\`${s}\``).join(", ")} before changing it.`,
+ ];
+ }
+ const rows = validation.tests.map((test) => {
+ const reason = validation.reasons?.[test];
+ return `- \`${test}\`${reason ? ` (${reason})` : ""}`;
+ });
+ const shown =
+ validation.total > validation.tests.length
+ ? [`${validation.tests.length} of ${validation.total} guarding tests shown.`]
+ : [];
+ const run = validation.commands.length
+ ? ["", "Run:", "", "```", ...validation.commands, "```"]
+ : [];
+ return [
+ "Run these after the change. The tests that exercise it most directly come first:",
+ "",
+ ...rows,
+ ...shown,
+ ...run,
+ ];
+}
+
+/** A `## Verify` section, or nothing when the payload carries no validation. */
+export function verifySection(
+ validation: VerifyValidation | null | undefined,
+ subjects: string[],
+): string {
+ if (!validation) return "";
+ return ["## Verify", "", ...verifyLines(validation, subjects)].join("\n");
+}
diff --git a/packages/ui/src/health/ai-prompts/refactoring-prompts.ts b/packages/ui/src/health/ai-prompts/refactoring-prompts.ts
index 8f6a23b7d..24cefc8b1 100644
--- a/packages/ui/src/health/ai-prompts/refactoring-prompts.ts
+++ b/packages/ui/src/health/ai-prompts/refactoring-prompts.ts
@@ -8,7 +8,13 @@ import type {
import { typeMeta } from "../../refactoring/meta";
import { blastFiles } from "../../refactoring/types";
-import { planSourceLink, refactoringPlanSteps } from "./refactoring-plan-steps";
+import {
+ planSourceLink,
+ refactoringPlanSteps,
+ verifyLines,
+ verifySection,
+ verifySubject,
+} from "./refactoring-plan-steps";
import {
bulletList,
closingSections,
@@ -42,6 +48,14 @@ export function buildPerformanceOpportunityPrompt({
const intervention = opportunity.intervention_symbol
? `Candidate shared intervention: \`${opportunity.intervention_symbol}\`.`
: "No shared intervention was proven.";
+ const subject = (
+ opportunity.intervention_symbol ??
+ opportunity.terminal_sink ??
+ opportunity.file_path
+ )
+ .split("::")
+ .pop() ?? opportunity.file_path;
+ const verify = verifySection(opportunity.validation, [subject]);
return [
FLAVOR_PREAMBLE[flavor],
@@ -61,11 +75,14 @@ export function buildPerformanceOpportunityPrompt({
"",
evidence.length ? evidence.join("\n") : "No resolved evidence paths were included in this page.",
"",
+ ...(verify ? [verify, ""] : []),
"## What to do",
"",
"1. Verify the repeated cost and caller-to-sink paths against the real code.",
"2. Determine whether one behavior-preserving intervention safely addresses the shared cause.",
- "3. Identify the tests and commands that prove result equivalence and performance improvement.",
+ verify
+ ? "3. Use the tests under Verify to prove result equivalence, and add a measurement that shows the performance improvement."
+ : "3. Identify the tests and commands that prove result equivalence and performance improvement.",
"4. If the evidence is insufficient or the intervention is unsafe, stop and explain the blocker instead of editing.",
"",
"Do not run commands or change files until the evidence and proposed validation have been reviewed.",
@@ -84,39 +101,26 @@ function codeList(items: string[], separator = ", "): string {
}
/** How many tests guard the change and how that was established. */
-function guardingTests(v: RecommendationValidation): string {
- if (v.basis === "unknown") {
- return "No measured or inferred guarding test was found; treat this as a validation gap.";
- }
- return `${v.total} guarding test${pluralS(v.total)} via ${v.via ?? v.basis}${
- v.truncated ? ` (showing ${v.tests.length})` : ""
- }.`;
-}
-
-function testsLine(v: RecommendationValidation): string | null {
- return v.tests.length ? `Tests: ${codeList(v.tests)}.` : null;
-}
-
-function runLine(v: RecommendationValidation): string | null {
- return v.commands.length ? `Run: ${codeList(v.commands, "; ")}.` : null;
+function guardingTests(v: RecommendationValidation): string | null {
+ // With none listed, the Verify block already says to add one.
+ if (v.basis === "unknown" || v.tests.length === 0) return null;
+ return `${v.total} guarding test${pluralS(v.total)} via ${v.via ?? v.basis}.`;
}
function recommendationValidation(plan: RefactoringPlan): string {
const validation = plan.validation;
if (!validation) return "";
return [
- "## Validation plan",
+ verifySection(validation, [verifySubject(plan)]),
"",
bulletList([
guardingTests(validation),
- testsLine(validation),
validation.affected_files.length
? `Affected files: ${codeList(validation.affected_files)}.`
: null,
validation.affected_symbols.length
? `Affected symbols: ${codeList(validation.affected_symbols)}.`
: null,
- runLine(validation),
]),
].join("\n");
}
@@ -267,13 +271,32 @@ function opportunityEvidence(opportunity: RefactoringOpportunityDetailResolved):
]);
}
-/** The validation profiles the steps share, with their runnable commands. */
+/** What each validation profile's steps change, so a missing test names it. */
+function profileSubjects(opportunity: RefactoringOpportunityDetailResolved, id: string): string[] {
+ const plans = new Map(opportunity.plans.map((plan) => [plan.id, plan]));
+ const subjects = opportunity.steps
+ .filter((step) => step.validation_profile_id === id)
+ .map((step) => {
+ const plan = plans.get(step.plan_id);
+ return plan ? verifySubject(plan) : step.target_symbol || step.file_path;
+ });
+ return subjects.length ? [...new Set(subjects)] : [opportunity.file_path];
+}
+
+/** The validation profiles the steps share: ranked tests with reasons and commands. */
function opportunityValidation(opportunity: RefactoringOpportunityDetailResolved): string {
- if (opportunity.validation_profiles.length === 0) return "";
- const blocks = opportunity.validation_profiles.map((profile) =>
- bulletList([guardingTests(profile), testsLine(profile), runLine(profile)]),
- );
- return ["## Validation plan", "", blocks.join("\n")].join("\n");
+ const profiles = opportunity.validation_profiles;
+ if (profiles.length === 0) return "";
+ const blocks = profiles.map((profile) => {
+ const subjects = profileSubjects(opportunity, profile.id);
+ const summary = guardingTests(profile);
+ return [
+ ...(profiles.length > 1 ? [`### For ${codeList(subjects)}`, ""] : []),
+ ...(summary ? [summary, ""] : []),
+ ...verifyLines(profile, subjects),
+ ].join("\n");
+ });
+ return ["## Verify", "", blocks.join("\n\n")].join("\n");
}
/**
diff --git a/packages/ui/src/health/performance/drawer.tsx b/packages/ui/src/health/performance/drawer.tsx
index 7c91a99a9..10e6a3b4e 100644
--- a/packages/ui/src/health/performance/drawer.tsx
+++ b/packages/ui/src/health/performance/drawer.tsx
@@ -49,6 +49,7 @@ function toRecommendationValidation(
affected_symbols: [],
commands: validation.commands,
targets: [],
+ ...(validation.reasons ? { reasons: validation.reasons } : {}),
};
}
diff --git a/packages/ui/src/refactoring/validation-summary.tsx b/packages/ui/src/refactoring/validation-summary.tsx
index cb2d4944a..feec04d6d 100644
--- a/packages/ui/src/refactoring/validation-summary.tsx
+++ b/packages/ui/src/refactoring/validation-summary.tsx
@@ -40,14 +40,21 @@ export function ValidationSummary({ validation, fileHref }: ValidationSummaryPro
{validation.tests.length > 0 ? (
<ul className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">
- {validation.tests.map((test) => (
- <li
- key={test}
- className="break-all py-2 font-mono text-xs text-[var(--color-text-secondary)]"
- >
- {test}
- </li>
- ))}
+ {validation.tests.map((test) => {
+ const reason = validation.reasons?.[test];
+ return (
+ <li key={test} className="py-2">
+ <span className="block break-all font-mono text-xs text-[var(--color-text-secondary)]">
+ {test}
+ </span>
+ {reason ? (
+ <span className="mt-0.5 block text-xs text-[var(--color-text-tertiary)]">
+ {reason}
+ </span>
+ ) : null}
+ </li>
+ );
+ })}
</ul>
) : null}
diff --git a/tests/unit/health/test_recommendations.py b/tests/unit/health/test_recommendations.py
index 84db09e11..9a90d86d9 100644
--- a/tests/unit/health/test_recommendations.py
+++ b/tests/unit/health/test_recommendations.py
@@ -11,14 +11,16 @@ from sqlalchemy.pool import StaticPool
from repowise.core.analysis.health.coverage import TestCoverage
from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion
from repowise.core.analysis.health.refactoring.recommendations import (
+ ValidationEvidence,
apply_view,
build_recommendations,
build_validation_plan,
detector_native_benefit,
hydrate_recommendations,
rehydrate_suggestion,
+ target_symbol_ids,
)
-from repowise.core.analysis.test_reachability import ReachedBy
+from repowise.core.analysis.test_reachability import ReachDistance, ReachedBy
from repowise.core.persistence.crud import save_test_coverage
from repowise.core.persistence.database import init_db
from tests.unit.persistence.helpers import insert_repo
@@ -388,3 +390,166 @@ def test_performance_fix_benefit_stays_detector_native() -> None:
native = detector_native_benefit(rehydrate_suggestion(plan))
assert item.benefit == round(native, 4)
assert item.benefit > 0.0
+
+
+# The walker shape from the audit: a file reached by many tests, most of which
+# only pass through it. Alphabetical order used to lead with the bystanders.
+_WALKER = "src/health/walker.py"
+_WALK_FILE = f"{_WALKER}::walk_file"
+_WALKER_TESTS = [
+ "tests/health/conftest.py",
+ "tests/health/test_assertions.py",
+ "tests/health/test_bystander.py",
+ "tests/health/test_imports_it.py",
+ "tests/health/test_two_hops.py",
+ "tests/health/test_walker.py",
+ "tests/health/test_walks_a_lot.py",
+]
+
+
+def _walker_plan() -> RefactoringSuggestion:
+ return RefactoringSuggestion(
+ refactoring_type="extract_method",
+ file_path=_WALKER,
+ target_symbol="walk_file",
+ line_start=94,
+ line_end=208,
+ plan={},
+ evidence={},
+ impact_delta=1.0,
+ effort_bucket="M",
+ blast_radius={},
+ confidence="high",
+ source_biomarker="long_function",
+ )
+
+
+def _walker_evidence() -> ValidationEvidence:
+ return ValidationEvidence(
+ symbols={_WALKER: [(_WALK_FILE, 94, 208), (f"{_WALKER}::helper", 210, 220)]},
+ symbol_reach={
+ _WALK_FILE: {
+ "tests/health/conftest.py": ReachDistance(1, 3),
+ "tests/health/test_assertions.py": ReachDistance(1, 1),
+ "tests/health/test_walks_a_lot.py": ReachDistance(1, 9),
+ "tests/health/test_two_hops.py": ReachDistance(2, 4),
+ }
+ },
+ imports={_WALKER: {"tests/health/test_imports_it.py": frozenset({"walk_file"})}},
+ )
+
+
+def _walker_reached() -> dict[str, ReachedBy]:
+ reach = {test: ReachDistance(1, 1) for test in _WALKER_TESTS}
+ return {
+ _WALKER: ReachedBy(
+ _WALKER_TESTS, "call-graph", len(_WALKER_TESTS), tuple(_WALKER_TESTS), reach
+ )
+ }
+
+
+def test_tests_that_call_the_changed_symbol_lead_the_list_with_reasons() -> None:
+ validation = build_validation_plan(
+ _walker_plan(), {}, _walker_reached(), evidence=_walker_evidence()
+ )
+ assert validation.tests == [
+ # Calls walk_file directly, more of its functions first.
+ "tests/health/test_walks_a_lot.py",
+ "tests/health/test_assertions.py",
+ # Imports walk_file by name, no call edge.
+ "tests/health/test_imports_it.py",
+ # Two calls away from walk_file.
+ "tests/health/test_two_hops.py",
+ # Reaches the file only, the named test before the bystander.
+ "tests/health/test_walker.py",
+ "tests/health/test_bystander.py",
+ # Test support runs nothing on its own, however close it is.
+ "tests/health/conftest.py",
+ ]
+ assert validation.reasons == {
+ "tests/health/test_walks_a_lot.py": "calls walk_file from 9 test functions",
+ "tests/health/test_assertions.py": "calls walk_file",
+ "tests/health/test_imports_it.py": "imports walk_file",
+ "tests/health/test_two_hops.py": "reaches walk_file in 2 calls",
+ "tests/health/test_walker.py": "calls into walker.py",
+ "tests/health/test_bystander.py": "calls into walker.py",
+ "tests/health/conftest.py": "calls walk_file from 3 test functions",
+ }
+ assert validation.targets[0].tests == validation.tests
+ assert validation.as_dict()["reasons"] == validation.reasons
+
+
+def test_measured_coverage_of_the_changed_lines_outranks_every_graph_signal() -> None:
+ measured = {
+ _WALKER: [
+ {"test_id": "tests/health/test_bystander.py::test_x", "covered_lines": [100, 150]},
+ {"test_id": "tests/health/test_walker.py::test_y", "covered_lines": [99]},
+ ]
+ }
+ validation = build_validation_plan(
+ _walker_plan(), measured, _walker_reached(), evidence=_walker_evidence()
+ )
+ assert validation.tests == [
+ "tests/health/test_bystander.py::test_x",
+ "tests/health/test_walker.py::test_y",
+ ]
+ assert validation.reasons == {
+ "tests/health/test_bystander.py::test_x": "covers lines 100-150",
+ "tests/health/test_walker.py::test_y": "covers line 99",
+ }
+
+
+def test_the_cap_keeps_the_strongest_evidence_and_reasons_follow_it() -> None:
+ validation = build_validation_plan(
+ _walker_plan(), {}, _walker_reached(), evidence=_walker_evidence(), test_limit=2
+ )
+ assert validation.tests == [
+ "tests/health/test_walks_a_lot.py",
+ "tests/health/test_assertions.py",
+ ]
+ assert list(validation.reasons) == validation.tests
+ assert validation.total == len(_WALKER_TESTS)
+ assert validation.truncated is True
+
+
+def test_without_graph_evidence_name_then_directory_reasons_are_given() -> None:
+ plan = _plan("Core", file_path="src/pkg/core.py")
+ reached = ReachedBy(
+ ["tests/other/test_misc.py", "tests/pkg/test_near.py", "tests/unit/test_core.py"],
+ "name-match",
+ 3,
+ )
+ validation = build_validation_plan(plan, {}, {"src/pkg/core.py": reached})
+ assert validation.tests == [
+ "tests/unit/test_core.py",
+ "tests/pkg/test_near.py",
+ "tests/other/test_misc.py",
+ ]
+ assert validation.reasons == {
+ "tests/unit/test_core.py": "named for core.py",
+ "tests/pkg/test_near.py": "shares pkg",
+ "tests/other/test_misc.py": "reaches core.py",
+ }
+
+
+def test_a_line_range_target_resolves_to_its_enclosing_symbol() -> None:
+ plan = _walker_plan()
+ plan.target_symbol = "walker.py:120-130"
+ spans = [(f"{_WALKER}::__module__", 0, 0), (_WALK_FILE, 94, 208), (f"{_WALKER}::inner", 118, 140)]
+ assert target_symbol_ids(plan, _WALKER, set(range(120, 131)), spans) == [f"{_WALKER}::inner"]
+ # A full id, as a performance plan stores it, resolves as itself.
+ plan.target_symbol = _WALK_FILE
+ assert target_symbol_ids(plan, _WALKER, None, spans) == [_WALK_FILE]
+
+
+def test_a_test_file_the_plan_edits_is_listed_as_edited() -> None:
+ plan = _plan("Core", rtype="split_file", file_path="src/core.py")
+ plan.line_start = plan.line_end = None
+ plan.blast_radius = {"files": ["tests/test_user.py"]}
+ inferred = {
+ "src/core.py": ReachedBy(["tests/test_core.py"], "import-graph", 1),
+ "tests/test_user.py": ReachedBy(["tests/test_user.py"], "import-graph", 1),
+ }
+ validation = build_validation_plan(plan, {}, inferred)
+ assert validation.tests == ["tests/test_user.py", "tests/test_core.py"]
+ assert validation.reasons["tests/test_user.py"] == "edited by this plan"
diff --git a/tests/unit/persistence/test_test_reachability_walk.py b/tests/unit/persistence/test_test_reachability_walk.py
index c28dc4ff7..6d0502e65 100644
--- a/tests/unit/persistence/test_test_reachability_walk.py
+++ b/tests/unit/persistence/test_test_reachability_walk.py
@@ -15,7 +15,13 @@ from __future__ import annotations
import networkx as nx
-from repowise.core.analysis.test_reachability import call_graph_from_db, call_graph_from_graph
+from repowise.core.analysis.test_reachability import (
+ ReachDistance,
+ call_graph_from_db,
+ call_graph_from_graph,
+ imported_names_by_test,
+ reach_into_symbols,
+)
from repowise.core.analysis.test_reachability import tests_reaching as reaching
from repowise.core.analysis.test_reachability import tests_reaching_by_tier as by_tier
from repowise.core.persistence.crud.graph import (
@@ -275,3 +281,145 @@ async def test_call_site_lines_round_trip_through_edge_persistence(async_session
rows = await get_all_graph_edges(async_session, repo.id)
assert rows[0]["call_lines"] == [4, 9]
+
+
+async def test_symbol_reach_keeps_the_fewest_hops_and_counts_direct_callers(async_session):
+ """Two test functions call the symbol directly; another test only reaches it
+ through a facade. The direct test is one hop away with two callers."""
+ repo = await insert_repo(async_session)
+ await _seed(
+ async_session,
+ repo.id,
+ nodes={"tests/test_walk.py": True, "tests/test_api.py": True, "src/walk.py": False},
+ edges=[
+ ("tests/test_walk.py", "tests/test_walk.py::test_one", "defines"),
+ ("tests/test_walk.py", "tests/test_walk.py::test_two", "defines"),
+ ("tests/test_api.py", "tests/test_api.py::test_it", "defines"),
+ ("src/walk.py", "src/walk.py::walk", "defines"),
+ ("src/walk.py", "src/walk.py::facade", "defines"),
+ ("tests/test_walk.py::test_one", "src/walk.py::walk", "calls"),
+ ("tests/test_walk.py::test_two", "src/walk.py::walk", "calls"),
+ ("tests/test_api.py::test_it", "src/walk.py::facade", "calls"),
+ ("src/walk.py::facade", "src/walk.py::walk", "calls"),
+ ],
+ )
+ found = await reach_into_symbols(
+ async_session, repo.id, ["src/walk.py::walk"], {"tests/test_walk.py", "tests/test_api.py"}
+ )
+ assert found == {
+ "src/walk.py::walk": {
+ "tests/test_walk.py": ReachDistance(hops=1, callers=2),
+ "tests/test_api.py": ReachDistance(hops=2, callers=1),
+ }
+ }
+
+
+async def test_imported_names_are_read_per_test_and_file(async_session):
+ repo = await insert_repo(async_session)
+ for source, names in (("tests/test_walk.py", '["walk"]'), ("src/other.py", '["walk"]')):
+ async_session.add(
+ GraphEdge(
+ repository_id=repo.id,
+ source_node_id=source,
+ target_node_id="src/walk.py",
+ edge_type="imports",
+ imported_names_json=names,
+ )
+ )
+ await async_session.flush()
+ found = await imported_names_by_test(
+ async_session, repo.id, ["src/walk.py"], {"tests/test_walk.py"}
+ )
+ # A production importer is not a test, so it never appears.
+ assert found == {"src/walk.py": {"tests/test_walk.py": frozenset({"walk"})}}
+
+
+async def test_a_detailed_page_matches_a_full_hydration(async_session):
+ """Paged surfaces rank every plan without symbol evidence and detail only
+ the rows they return; those rows must serialize exactly as before."""
+ from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion
+ from repowise.core.analysis.health.refactoring.recommendations import (
+ detail_recommendations,
+ hydrate_recommendations,
+ )
+
+ repo = await insert_repo(async_session)
+ nodes = {"tests/test_bystander.py": True, "tests/test_walk.py": True, "src/walk.py": False}
+ for path, is_test in nodes.items():
+ async_session.add(
+ GraphNode(repository_id=repo.id, node_id=path, node_type="file", is_test=is_test)
+ )
+ for name, start, end in (("walk", 1, 20), ("other", 30, 40)):
+ async_session.add(
+ GraphNode(
+ repository_id=repo.id,
+ node_id=f"src/walk.py::{name}",
+ node_type="symbol",
+ file_path="src/walk.py",
+ start_line=start,
+ end_line=end,
+ )
+ )
+ await _seed(
+ async_session,
+ repo.id,
+ nodes={},
+ edges=[
+ ("src/walk.py", "src/walk.py::walk", "defines"),
+ ("src/walk.py", "src/walk.py::other", "defines"),
+ ("tests/test_walk.py", "tests/test_walk.py::test_it", "defines"),
+ ("tests/test_bystander.py", "tests/test_bystander.py::test_it", "defines"),
+ ("tests/test_walk.py::test_it", "src/walk.py::walk", "calls"),
+ ("tests/test_bystander.py::test_it", "src/walk.py::other", "calls"),
+ ],
+ )
+
+ def plans():
+ return [
+ RefactoringSuggestion(
+ refactoring_type="extract_method",
+ file_path="src/walk.py",
+ target_symbol="walk",
+ line_start=1,
+ line_end=20,
+ plan={},
+ evidence={},
+ impact_delta=1.0,
+ effort_bucket="M",
+ blast_radius={},
+ confidence="high",
+ source_biomarker="long_function",
+ )
+ ]
+
+ full = await hydrate_recommendations(async_session, repo.id, plans())
+ ranked = await hydrate_recommendations(async_session, repo.id, plans(), rank_only=True)
+ detailed = await detail_recommendations(async_session, repo.id, ranked)
+
+ assert [item.as_dict() for item in detailed] == [item.as_dict() for item in full]
+ assert full[0].validation.tests == ["tests/test_walk.py", "tests/test_bystander.py"]
+ assert full[0].validation.reasons["tests/test_walk.py"] == "calls walk"
+ # The rank pass orders nothing it will not serve.
+ assert ranked[0].validation.reasons == {}
+ assert ranked[0].rank_score == full[0].rank_score
+
+
+async def test_a_seed_that_calls_another_seed_does_not_shorten_its_distance(async_session):
+ """Walked together, ``load`` (a seed) calls ``parse`` (another seed). A test
+ calling ``load`` is two hops from ``parse``, however the batch is ordered."""
+ repo = await insert_repo(async_session)
+ await _seed(
+ async_session,
+ repo.id,
+ nodes={"tests/test_load.py": True, "src/io.py": False},
+ edges=[
+ ("tests/test_load.py", "tests/test_load.py::test_it", "defines"),
+ ("tests/test_load.py::test_it", "src/io.py::load", "calls"),
+ ("src/io.py::load", "src/io.py::parse", "calls"),
+ ],
+ )
+ found = await reach_into_symbols(
+ async_session, repo.id, ["src/io.py::load", "src/io.py::parse"], {"tests/test_load.py"}
+ )
+ assert found["src/io.py::load"] == {"tests/test_load.py": ReachDistance(1, 1)}
+ assert found["src/io.py::parse"] == {"tests/test_load.py": ReachDistance(2, 1)}