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
fix(refactoring): list the tests that guard a plan, not the ones that pass through a hub (#3289)
Raghav Chamadiyaa07880be9555
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex bb9d7ce97..13a21551f 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -55,6 +55,11 @@ filters for type, confidence and effort. A plan's drawer explains its rank, showthe tests that reach the code and the command to run them, and can export thestructured plan for an agent. The page never edits code or runs tests on its own.+A plan lists the tests closest to the change first: measured coverage, then+tests named for the file, then the call graph. Tests that reach the file only+through a widely imported hub module are left out. When no test reaches the+change, the plan has no command and asks for a characterization test first.+## Reading the resultsA **plan** is one detector's output for one target. An **opportunity** is onediff --git a/packages/core/src/repowise/core/analysis/health/perf/serving.py b/packages/core/src/repowise/core/analysis/health/perf/serving.pyindex 2e1e5bd70..bb842ebcb 100644--- a/packages/core/src/repowise/core/analysis/health/perf/serving.py+++ b/packages/core/src/repowise/core/analysis/health/perf/serving.py@@ -429,7 +429,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", "reasons", "commands")+ keys = ("basis", "via", "total", "tests", "reasons", "commands", "prerequisite")return {"validation": {key: validation.get(key) for key in keys},"plan_steps": plan.get("steps", []),diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.pyindex eee8e2a02..0fdb6781a 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py@@ -12,13 +12,14 @@ import dataclassesimport functoolsimport jsonimport math-from collections.abc import Callable, Mapping, Sequence+from collections.abc import Callable, Collection, Mapping, Sequencefrom dataclasses import dataclass, fieldfrom typing import Any, Literalfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.health.grading import TARGET_SCORE+from repowise.core.analysis.health.perf.ranking import _percentile_thresholdfrom repowise.core.analysis.pr_blast import rank_tests_by_reachfrom repowise.core.analysis.test_reachability import (DEFAULT_CALL_DEPTH,@@ -34,7 +35,7 @@ from repowise.core.analysis.test_reachability import ()from repowise.core.analysis.test_selection import expand_test_scopesfrom repowise.core.code_origin import ship_rank-from repowise.core.test_paths import is_test_support_path, paired_test_names+from repowise.core.test_paths import is_test_support_path, names_test_for, paired_test_namesfrom .models import RefactoringSuggestion@@ -295,6 +296,8 @@ class ValidationPlan: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)+ # What to do before the edit when no test reaches the change.+ prerequisite: str | None = Nonedef as_dict(self) -> dict[str, Any]:return {@@ -308,6 +311,7 @@ class ValidationPlan:"commands": self.commands,"targets": [target.as_dict() for target in self.targets],"reasons": self.reasons,+ "prerequisite": self.prerequisite,}@@ -321,20 +325,61 @@ class ValidationEvidence:``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 testimports from a file. Empty, the order falls back to name and directory.+ ``hubs`` are the files no reach walk passes through (:func:`hub_files`), and+ ``siblings`` each directory's files, which decide whose test a name is."""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)+ hubs: frozenset[str] = frozenset()+ siblings: Mapping[str, tuple[str, ...]] = field(default_factory=dict)@dataclass(frozen=True, slots=True)class ValidationInputs:- """The coverage rows and reachability walk one hydration read."""+ """The coverage rows and reachability walk one hydration read.++ ``evidence`` holds the hubs and the symbol facts for hub files only: every+ pass narrows a hub target the same way, detailed or not.+ """measured: Mapping[str, list[dict[str, Any]]]inferred: Mapping[str, ReachedBy]test_files: set[str]+ evidence: ValidationEvidence = field(default_factory=ValidationEvidence)+++# A hub is a module most of the code imports: fan-in above the absolute bar, or+# in the top 1% of the repository's files and at least the floor. Far stricter+# than ``PerfRanker``'s top-quintile "central": that marks a function worth a+# performance claim, while a hub's reach is dropped from validation, so it must+# be a module most tests would pass through. Fan-in counts every importer,+# tests included, as ``graph_metrics.in_degree`` stores it.+HUB_MIN_FAN_IN = 50+HUB_TOP_PERCENTILE = 0.99+HUB_FAN_IN_FLOOR = 10+++def hub_files(in_degree: Mapping[str, float], test_files: Collection[str]) -> frozenset[str]:+ """The repository's own non-test files that are hubs by stored fan-in."""+ own = {+ path: int(fan_in or 0)+ for path, fan_in in in_degree.items()+ if not path.startswith("external:") and path not in test_files+ }+ bar = max(HUB_FAN_IN_FLOOR, _percentile_threshold(list(own.values()), HUB_TOP_PERCENTILE))+ return frozenset(+ path for path, fan_in in own.items() if fan_in > HUB_MIN_FAN_IN or fan_in >= bar+ )+++def _siblings(paths: Collection[str]) -> dict[str, tuple[str, ...]]:+ by_dir: dict[str, list[str]] = {}+ for path in paths:+ if not path.startswith("external:"):+ by_dir.setdefault(path.rsplit("/", 1)[0] if "/" in path else "", []).append(path)+ return {directory: tuple(sorted(files)) for directory, files in by_dir.items()}def target_symbol_ids(@@ -390,6 +435,63 @@ _is_support = functools.lru_cache(maxsize=8192)(is_test_support_path)RankedTest = tuple[tuple[int, ...], str]+# Test names are compared once per plan they guard, like the support check.+_names_test_for = functools.lru_cache(maxsize=65536)(names_test_for)+++@dataclass(frozen=True, slots=True)+class _Target:+ """What a test's path is compared against: the file's name and directories."""++ path: str+ name: str+ dirs: list[str]+ siblings: tuple[str, ...]++ @classmethod+ def of(cls, file_path: str, evidence: ValidationEvidence) -> _Target:+ directory = file_path.rsplit("/", 1)[0] if "/" in file_path else ""+ return cls(+ file_path,+ file_path.rsplit("/", 1)[-1],+ file_path.split("/")[:-1],+ evidence.siblings.get(directory, ()),+ )++ def named(self, path: str) -> bool:+ """A test named for the file (:func:`names_test_for`)."""+ return _names_test_for(path, self.path, self.siblings)++ def shared(self, path: str) -> list[str]:+ test_dirs = set(path.split("/")[:-1])+ return [segment for segment in self.dirs if segment in test_dirs]+++def _near_key(path: str, hits: set[int], named: bool, shared: list[str]) -> tuple[int, ...]:+ """Measured coverage of the changed lines, then a test named for the file,+ then one mirroring its directories. Graph distance only breaks ties after."""+ return (+ int(_is_support(path)),+ 0 if hits else 1,+ -len(hits),+ 0 if named else 1,+ -len(shared),+ )+++def _rank_by_name(+ file_path: str, labels: set[str], covered: Mapping[str, set[int]], evidence: ValidationEvidence+) -> dict[str, RankedTest]:+ """:func:`_rank_target_tests` without the graph evidence a rank-only pass skips."""+ target = _Target.of(file_path, evidence)+ out: dict[str, RankedTest] = {}+ for label in labels:+ path = label.split("::", 1)[0]+ hits = covered.get(label) or set()+ out[label] = (_near_key(path, hits, target.named(path), target.shared(path)), "")+ return out++def _test_reason(*,name: str,@@ -440,16 +542,16 @@ def _rank_target_tests() -> 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 (a- helper module) runs nothing on its own, so it goes last; a ``conftest.py``- was already replaced by the tests under it (:func:`_expand_scopes`).+ Measured coverage of the changed lines first, then a test named for the+ file, then directory overlap (:func:`_near_key`); within those, 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. Test+ support (a helper module) runs nothing on its own, so it goes last; a+ ``conftest.py`` was already replaced by the tests under it+ (:func:`_expand_scopes`)."""- name = file_path.rsplit("/", 1)[-1]- named_for = paired_test_names(file_path)- target_dirs = file_path.split("/")[:-1]+ target = _Target.of(file_path, evidence)+ name = target.namefile_reach = reached.reach if reached is not None and reached.reach else {}imports = evidence.imports.get(file_path, {})out: dict[str, RankedTest] = {}@@ -488,21 +590,16 @@ def _rank_target_tests(callers = reach.callerselse: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+ shared = target.shared(path)+ named = target.named(path)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),+ *_near_key(path, hits, named, shared),0 if references else 1,distance,-callers,- 0 if named else 1,- -len(shared),)out[label] = (key,@@ -522,7 +619,7 @@ def _rank_target_tests(return out-def _commands(tests: list[str], files: list[str], *, total: int | None = None) -> list[str]:+def _commands(tests: list[str], *, total: int | None = None) -> list[str]:"""A command that runs at least everything the plan says validates it.When the displayed list is capped, enumerating only the shown tests would@@ -530,9 +627,11 @@ def _commands(tests: list[str], files: list[str], *, total: int | None = None) -selection widens to the files those tests live in: bounded by file countrather than test count, and never narrower than the evidence.- An empty list means the plan has no command to suggest. Nothing here looks- at the repository's tooling, so a language other than Python or JS/TS gets- none in place of a guess that would fail when run.+ An empty list means the plan has no command to suggest. Every command names+ its tests: with none found, a bare ``pytest`` or ``npm test`` would run a+ whole suite as if it guarded the change. Nothing here looks at the+ repository's tooling, so a language other than Python or JS/TS gets none in+ place of a guess that would fail when run."""if total is not None and total > len(tests):tests = sorted({test.split("::", 1)[0] for test in tests})@@ -545,13 +644,15 @@ def _commands(tests: list[str], files: list[str], *, total: int | None = None) -commands.append("pytest " + " ".join(python_tests))if js_tests:commands.append("npm test -- " + " ".join(js_tests))- if commands:- return commands- if any(path.endswith(".py") for path in files):- return ["pytest"]- if any(path.endswith((".ts", ".tsx", ".js", ".jsx")) for path in files):- return ["npm test", "npm run type-check"]- return []+ return commands+++def _characterization_step(suggestion: RefactoringSuggestion) -> str:+ """The step before an edit no test reaches: pin today's behaviour first."""+ symbol = suggestion.target_symbol+ if not symbol or not symbol.replace(".", "_").isidentifier():+ symbol = suggestion.file_path.rsplit("/", 1)[-1]+ return f"No test reaches this; add a characterization test for `{symbol}` before the edit."def _line_ranges(suggestion: RefactoringSuggestion) -> dict[str, set[int] | None]:@@ -594,6 +695,38 @@ def _measured_labels(rows: list[dict[str, Any]], lines: set[int] | None) -> set[return set(_measured_hits(rows, lines))+def _hub_tests(+ file_path: str, symbol_ids: Sequence[str], evidence: ValidationEvidence+) -> set[str] | None:+ """For a hub file, the tests that may exercise the symbols the plan changes.++ Most of the suite reaches a hub through some other symbol of it, so its+ file-level reach says nothing about this change. A test counts when it+ reaches a changed symbol, imports one by name, or imports the module whole+ (``import utils``, ``import * as u``), whose calls the graph may not have+ resolved; only a test proven to import other names is left out. ``None``+ keeps the file's reach: it is no hub, or the plan names no symbol in it.+ """+ if file_path not in evidence.hubs or not symbol_ids:+ return None+ module = file_path.rsplit("/", 1)[-1].split(".", 1)[0]+ names = {_symbol_label(symbol).split(".", 1)[0] for symbol in symbol_ids} | {module, "*"}+ imported = evidence.imports.get(file_path, {})+ return {+ test for symbol in symbol_ids for test in evidence.symbol_reach.get(symbol, {})+ } | {test for test, imports in imported.items() if not imports or imports & names}+++def _drop_hub_only(file_path: str, labels: set[str], keep: set[str]) -> set[str]:+ """A hub target's tests: :func:`_hub_tests`, which may name an importer the+ file walk never reached, and any of *labels* with the file's exact paired+ name. A qualified name (``test_utils_extra.py``) earns no exemption."""+ paired = paired_test_names(file_path)+ return set(keep) | {+ label for label in labels if label.split("::", 1)[0].rsplit("/", 1)[-1] in paired+ }++def _validation_target(file_path: str,lines: set[int] | None,@@ -601,6 +734,7 @@ def _validation_target(inferred: Mapping[str, ReachedBy],cap: int,rank: Callable[[set[str], Mapping[str, set[int]], ReachedBy | None], dict[str, RankedTest]],+ keep: set[str] | None = None,) -> tuple[ValidationTarget, set[str], bool, dict[str, RankedTest]]:covered = _measured_hits(measured.get(file_path, []), lines)labels = set(covered)@@ -619,6 +753,12 @@ def _validation_target(identities_complete = (reached is None or reached.all_tests is not None or total == len(labels))+ if keep is not None and reached is not None:+ labels = _drop_hub_only(file_path, labels, keep)+ if identities_complete:+ # The whole list was filtered, so what is left is the answer.+ basis, via = ("inferred", via) if labels else ("unknown", None)+ total = len(labels)ranked = rank(labels, covered, reached)ordered = sorted(labels, key=lambda label: (ranked[label][0], label))return (@@ -628,7 +768,7 @@ def _validation_target(via=via,total=total,tests=ordered[:cap],- truncated=total > cap,+ truncated=total > cap or not identities_complete,),labels,identities_complete,@@ -673,8 +813,8 @@ def build_validation_plan(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}+ # A rank-only pass reads no graph evidence; name and directory still order.+ return _rank_by_name(path, labels, covered, facts)return _rank_target_tests(path,span,@@ -687,7 +827,13 @@ def build_validation_plan()target, labels, target_complete, ranked = _validation_target(- file_path, lines, measured, inferred, cap, rank+ file_path,+ lines,+ measured,+ inferred,+ cap,+ rank,+ _hub_tests(file_path, symbols[file_path], facts),)by_file[file_path] = labelsfor test, scored in ranked.items():@@ -723,9 +869,12 @@ def build_validation_plan(truncated=aggregate_total > len(ordered_tests[:cap]),affected_files=files,affected_symbols=affected_symbols(suggestion),- commands=_commands(ordered_tests[:cap], files, total=aggregate_total),+ commands=_commands(ordered_tests[:cap], total=aggregate_total),targets=target_rows,reasons={test: best[test][1] for test in ordered_tests[:cap]} if order_tests else {},+ prerequisite=(+ _characterization_step(suggestion) if aggregate_basis == "unknown" else None+ ),)@@ -934,7 +1083,12 @@ async def hydrate_recommendations(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+ session,+ repository_id,+ suggestions,+ test_limit=test_limit,+ detailed=not rank_only,+ in_degree=centrality,)recommendations = build_recommendations(suggestions,@@ -986,6 +1140,7 @@ async def _validation_plans(test_limit: int,detailed: bool,inputs: ValidationInputs | None = None,+ in_degree: Mapping[str, float] | None = None,) -> tuple[list[ValidationPlan], ValidationInputs]:"""One validation plan per suggestion, every read batched across the set.@@ -997,13 +1152,15 @@ async def _validation_plans({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)+ inputs = await _validation_inputs(+ session, repository_id, suggestions, target_files, in_degree=in_degree+ )evidence = (await _validation_evidence(- session, repository_id, suggestions, target_files, inputs.test_files+ session, repository_id, suggestions, target_files, inputs.test_files, inputs.evidence)if detailed- else None+ else inputs.evidence)plans = [build_validation_plan(@@ -1024,8 +1181,14 @@ async def _validation_inputs(repository_id: str,suggestions: Sequence[RefactoringSuggestion],target_files: Sequence[str],+ *,+ in_degree: Mapping[str, float] | None = None,) -> ValidationInputs:- """Measured coverage and the tiered reachability walk for every plan's files."""+ """Measured coverage and the tiered reachability walk for every plan's files.++ *in_degree* is the stored fan-in a caller already read; without it, read here.+ """+ from repowise.core.persistence import crudfrom repowise.core.persistence.crud.analysis.coverage_map import tests_covering_filesmeasured = await tests_covering_files(session, repository_id, set(target_files))@@ -1039,9 +1202,17 @@ async def _validation_inputs(if not _measured_labels(measured.get(file_path, []), lines):unanswered.add(file_path)test_files = await cached_test_files(session, repository_id)+ if in_degree is None:+ in_degree = {+ node: float(metric.get("in_degree") or 0.0)+ for node, metric in (await crud.get_graph_metrics(session, repository_id)).items()+ }+ # A test that reaches the file only through a hub tests the hub; it is not+ # listed, and with nothing else the plan says no test reaches it.+ hubs = hub_files(in_degree, test_files)inferred = (await tests_reaching_by_tier(- session, repository_id, sorted(unanswered), test_files=test_files+ session, repository_id, sorted(unanswered), test_files=test_files, avoid=hubs)if unansweredelse {}@@ -1052,7 +1223,18 @@ async def _validation_inputs(inferred = {path: _expand_scopes(path, reached, test_files) for path, reached in inferred.items()}- return ValidationInputs(measured=measured, inferred=inferred, test_files=test_files)+ hub_targets = [path for path in target_files if path in hubs]+ evidence = await _validation_evidence(+ session,+ repository_id,+ [item for item in suggestions if hubs.intersection(affected_files(item))],+ hub_targets,+ test_files,+ ValidationEvidence(hubs=hubs, siblings=_siblings(in_degree)),+ )+ return ValidationInputs(+ measured=measured, inferred=inferred, test_files=test_files, evidence=evidence+ )def _expand_scopes(path: str, reached: ReachedBy, test_files: set[str]) -> ReachedBy:@@ -1087,6 +1269,7 @@ async def _validation_evidence(suggestions: Sequence[RefactoringSuggestion],target_files: Sequence[str],test_files: set[str],+ base: ValidationEvidence,) -> ValidationEvidence:"""Symbol spans, symbol-level reach and test imports for every plan at once.@@ -1098,7 +1281,7 @@ async def _validation_evidence(from repowise.core.persistence.models import GraphNodeif not target_files:- return ValidationEvidence()+ return baserows = await session.execute(select(GraphNode.file_path, GraphNode.node_id, GraphNode.start_line, GraphNode.end_line).where(GraphNode.repository_id == repository_id)@@ -1114,9 +1297,12 @@ async def _validation_evidence(for file_path, lines in _line_ranges(suggestion).items()for symbol in target_symbol_ids(suggestion, file_path, lines, spans.get(file_path, ()))}- return ValidationEvidence(+ return dataclasses.replace(+ base,symbols=spans,- symbol_reach=await reach_into_symbols(session, repository_id, symbol_ids, test_files),+ symbol_reach=await reach_into_symbols(+ session, repository_id, symbol_ids, test_files, avoid=base.hubs+ ),imports=await imported_names_by_test(session, repository_id, target_files, test_files),)@@ -1146,6 +1332,7 @@ __all__ = ["detail_recommendations","detector_native_benefit","enrich_blast_radius",+ "hub_files","hydrate_recommendations","priority_score","rehydrate_suggestion",diff --git a/packages/core/src/repowise/core/analysis/test_reachability.py b/packages/core/src/repowise/core/analysis/test_reachability.pyindex 4845cd421..dbe4be62e 100644--- a/packages/core/src/repowise/core/analysis/test_reachability.py+++ b/packages/core/src/repowise/core/analysis/test_reachability.py@@ -663,6 +663,7 @@ async def tests_reaching_by_tier(import_depth: int = DEFAULT_MAX_DEPTH,symbol_seeds: Mapping[str, Collection[str]] | None = None,test_files: set[str] | None = None,+ avoid: Collection[str] = frozenset(),) -> dict[str, ReachedBy]:""":func:`tests_reaching`, also saying which tier answered each target.@@ -676,6 +677,10 @@ async def tests_reaching_by_tier(``defines`` lookup, and theimport tier stays file-level either way.+ *avoid* names files the call walk does not pass reach through, except+ into a target's own symbols. The import tier is+ one hop, so it never passes through anything.+The call walk runs first; the import walk is then seeded with only thetargets it left unanswered, so the weaker tier never speaks over thestronger one and costs nothing where the stronger one already spoke.@@ -700,7 +705,7 @@ async def tests_reaching_by_tier(out: dict[str, ReachedBy] = {}if call_depth >= 1:found = await _call_reaching(- session, repo_id, seeds, test_files, call_depth, symbol_seeds=symbol_seeds+ session, repo_id, seeds, test_files, call_depth, symbol_seeds=symbol_seeds, avoid=avoid)for seed, reach in found.items():ordered = tuple(rank_tests(seed.split("::", 1)[0], reach))@@ -734,6 +739,7 @@ async def _call_reaching(*,symbol_seeds: Mapping[str, Collection[str]] | None = None,strict: bool = False,+ avoid: Collection[str] = frozenset(),) -> dict[str, dict[str, ReachDistance]]:"""Tests that can execute into each seed file, walking call edges backwards.@@ -805,6 +811,11 @@ async def _call_reaching(# A test is a leaf. Walking through one would let "test A calls# shared helper B" drag B's unrelated targets in.continue+ if owner in avoid:+ # A hub carries on only the seeds it declares itself.+ carried = {s: d for s, d in carried.items() if s.split("::", 1)[0] == owner}+ if not carried:+ continueknown = origins.setdefault(caller, {})closer = {seed: distance + 1@@ -830,6 +841,7 @@ async def reach_into_symbols(test_files: set[str],*,max_depth: int = DEFAULT_CALL_DEPTH,+ avoid: Collection[str] = frozenset(),) -> dict[str, dict[str, ReachDistance]]:"""Tests that call into each symbol id, keyed by the symbol, with their hops.@@ -848,6 +860,7 @@ async def reach_into_symbols(max_depth,symbol_seeds={symbol: (symbol,) for symbol in seeds},strict=True,+ avoid=avoid,)@@ -856,12 +869,44 @@ async def imported_names_by_test() -> 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.+ An empty set is an import of the module itself. One hop, plus one through a+ re-export barrel (``index.ts``, ``__init__.py``) that imports the file: a+ test importing ``foo`` from the barrel imports it from the file. 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 {}+ out: dict[str, dict[str, frozenset[str]]] = {}+ barrels: dict[str, dict[str, frozenset[str]]] = {}+ for source, target, names in await _imported_names(session, repo_id, targets):+ if source in test_files:+ _add_names(out, target, source, names)+ elif PurePosixPath(source).name in BARREL_FILENAMES:+ barrels.setdefault(source, {})[target] = names+ if barrels:+ for source, barrel, names in await _imported_names(session, repo_id, sorted(barrels)):+ if source not in test_files:+ continue+ for target, exported in barrels[barrel].items():+ # ``export *`` passes every name on; otherwise only the ones it re-exports.+ passed = names if not exported or "*" in exported else names & exported+ if passed or not names:+ _add_names(out, target, source, passed)+ return out+++def _add_names(+ out: dict[str, dict[str, frozenset[str]]], target: str, test: str, names: frozenset[str]+) -> None:+ by_test = out.setdefault(target, {})+ by_test[test] = by_test.get(test, frozenset()) | names+++async def _imported_names(+ session: AsyncSession, repo_id: str, targets: list[str]+) -> list[tuple[str, str, frozenset[str]]]:+ """``(importer, imported file, names)`` for every import edge into *targets*."""params: dict[str, Any] = {"repo_id": repo_id}tgt = _in_clause("p", targets, params)ets = _in_clause("e", sorted(FILE_DEPENDENCY_EDGE_TYPES), params)@@ -873,18 +918,13 @@ async def imported_names_by_test(),params,)- out: dict[str, dict[str, frozenset[str]]] = {}+ out = []for source, target, names_json in rows:- if source not in test_files:- continuetry: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)- )+ out.append((source, target, frozenset(n for n in names if isinstance(n, str))))return outdiff --git a/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py b/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.pyindex 0b76740c7..5a007d89d 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py@@ -471,6 +471,7 @@ async def _finding_validator(inputs.measured,inputs.inferred,test_limit=DEFAULT_TEST_LIMIT,+ evidence=inputs.evidence,order_tests=False,)# No test found: unknown, not the bare repo-wide command a plan falls back to.diff --git a/packages/core/src/repowise/core/test_paths.py b/packages/core/src/repowise/core/test_paths.pyindex ad58e4e3e..05c133b98 100644--- a/packages/core/src/repowise/core/test_paths.py+++ b/packages/core/src/repowise/core/test_paths.py@@ -63,6 +63,8 @@ from pathlib import PurePath, PurePosixPathfrom typing import TYPE_CHECKINGif TYPE_CHECKING:+ from collections.abc import Collection+from .pytest_roots import PytestRoots# Directory segments that mark every file beneath them as test material,@@ -509,29 +511,77 @@ _CLASS_TEST_SUFFIXES: dict[str, tuple[str, ...]] = {}+_JS_TEST_TAILS = (+ ".test.ts",+ ".test.tsx",+ ".test.js",+ ".test.mts",+ ".test.cts",+ ".spec.ts",+ ".spec.js",+ ".spec.mts",+ ".spec.cts",+)+++def _paired_affixes(p: PurePath) -> list[tuple[str, str]]:+ """``(before the stem, after the stem)`` of every conventional test name for *p*."""+ test_suffix = ".exs" if p.suffix == ".ex" else p.suffix+ return [+ ("test_", test_suffix),+ ("", f"_test{test_suffix}"),+ ("", f"_spec{test_suffix}"),+ *(("", tail) for tail in _JS_TEST_TAILS),+ *(("", f"{suffix}{p.suffix}") for suffix in _CLASS_TEST_SUFFIXES.get(p.suffix, ())),+ ]++def paired_test_names(rel_path: str) -> frozenset[str]:"""Filenames a test for *rel_path* would conventionally carry, any directory."""p = PurePath(rel_path)stem = p.stem- test_suffix = ".exs" if p.suffix == ".ex" else p.suffix- names = {- f"test_{stem}{test_suffix}",- f"{stem}_test{test_suffix}",- f"{stem}_spec{test_suffix}",- f"{stem}.test.ts",- f"{stem}.test.tsx",- f"{stem}.test.js",- f"{stem}.test.mts",- f"{stem}.test.cts",- f"{stem}.spec.ts",- f"{stem}.spec.js",- f"{stem}.spec.mts",- f"{stem}.spec.cts",- }+ names = {f"{head}{stem}{tail}" for head, tail in _paired_affixes(p)}if p.suffix.lower() in _PASCAL_UNIT_SUFFIXES:# Delphi pairs ``uFoo.pas`` with a ``TestFoo.dpr`` program; only a# lowercase ``u`` is the unit prefix (``Utils.pas`` keeps its U).names.add(f"Test{stem[1:] if stem[:1] == 'u' else stem}.dpr")- for suffix in _CLASS_TEST_SUFFIXES.get(p.suffix, ()):- names.add(f"{stem}{suffix}{p.suffix}")return frozenset(names)+++def _qualified_name(test_name: str, rel_path: str) -> bool:+ """*test_name* is a paired name for *rel_path* with a qualifier after the stem."""+ p = PurePath(rel_path)+ for head, tail in _paired_affixes(p):+ lead = f"{head}{p.stem}"+ if len(test_name) <= len(lead) + len(tail) + 1:+ continue+ if not (test_name.startswith(lead) and test_name.endswith(tail)):+ continue+ middle = test_name[len(lead) : len(test_name) - len(tail)]+ # ``_golden``, ``.retry``, ``-cli``; or a PascalCase word before ``Test``.+ if middle[0] in "._-" or (middle[0].isupper() and tail[:1].isupper()):+ return True+ return False+++def names_test_for(test_path: str, rel_path: str, siblings: Collection[str] = ()) -> bool:+ """Whether *test_path* is named for *rel_path*: a paired name, or one with a+ qualifier after the stem (``test_loader_golden.py``, ``loader.retry.test.ts``,+ ``loader_retry_test.go``, ``LoaderRetryTest.java``).++ *siblings* are the other files in *rel_path*'s directory. A qualified name+ one of them claims is that file's test: ``test_foo_bar.py`` is for+ ``foo_bar.py``, not ``foo.py``, and ``foo.config.test.ts`` for ``foo.config.ts``.+ """+ name = PurePath(test_path).name+ if name in paired_test_names(rel_path):+ return True+ if not _qualified_name(name, rel_path):+ return False+ own = len(PurePath(rel_path).stem)+ return not any(+ name in paired_test_names(other)+ or (len(PurePath(other).stem) > own and _qualified_name(name, other))+ for other in siblings+ if other != rel_path+ )diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.tsindex bf20899aa..61c453447 100644--- a/packages/types/src/refactoring.ts+++ b/packages/types/src/refactoring.ts@@ -40,6 +40,9 @@ export interface RecommendationValidation {/** 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>;+ /** Set when no test reaches the change: the step to take before the edit.+ * Absent on a payload from an older server. */+ prerequisite?: string | null;}export interface RefactoringPlan {diff --git a/packages/ui/__tests__/refactoring/validation-summary.test.tsx b/packages/ui/__tests__/refactoring/validation-summary.test.tsxindex cfaf6e9fc..4aac6d267 100644--- a/packages/ui/__tests__/refactoring/validation-summary.test.tsx+++ b/packages/ui/__tests__/refactoring/validation-summary.test.tsx@@ -24,4 +24,14 @@ describe("ValidationSummary", () => {const rows = getAllByRole("listitem").map((row) => row.textContent);expect(rows).toEqual(["tests/test_walker.pycalls walk_file", "tests/test_other.py"]);});++ it("says what to do first when no test reaches the change", () => {+ const step = "No test reaches this; add a characterization test for `walk` before the edit.";+ const { getByText } = render(+ <ValidationSummary+ validation={{ ...validation, basis: "unknown", via: null, total: 0, tests: [], prerequisite: step }}+ />,+ );+ expect(getByText(step)).toBeTruthy();+ });});diff --git a/packages/ui/src/refactoring/validation-summary.tsx b/packages/ui/src/refactoring/validation-summary.tsxindex feec04d6d..9b54056ff 100644--- a/packages/ui/src/refactoring/validation-summary.tsx+++ b/packages/ui/src/refactoring/validation-summary.tsx@@ -33,7 +33,8 @@ export function ValidationSummary({ validation, fileHref }: ValidationSummaryPro</p>{validation.basis === "unknown" ? (<p className="mt-1 text-xs text-[var(--color-text-tertiary)]">- No measured or inferred guarding test was found. Treat this as explicit validation work.+ {validation.prerequisite ??+ "No measured or inferred guarding test was found. Treat this as explicit validation work."}</p>) : null}</div>diff --git a/tests/unit/health/test_recommendations.py b/tests/unit/health/test_recommendations.pyindex 40db16ea0..9b7422420 100644--- a/tests/unit/health/test_recommendations.py+++ b/tests/unit/health/test_recommendations.py@@ -16,6 +16,7 @@ from repowise.core.analysis.health.refactoring.recommendations import (build_recommendations,build_validation_plan,detector_native_benefit,+ hub_files,hydrate_recommendations,rehydrate_suggestion,target_symbol_ids,@@ -415,11 +416,26 @@ def test_tests_in_a_language_with_no_known_runner_suggest_no_command() -> None:assert plan.commands == []-def test_python_and_js_plans_keep_their_default_commands() -> None:- python = build_validation_plan(_plan("target", file_path="a/b.py"), {}, {})- assert python.commands == ["pytest"]- typescript = build_validation_plan(_plan("target", file_path="web/app.ts"), {}, {})- assert typescript.commands == ["npm test", "npm run type-check"]+def test_a_plan_no_test_reaches_has_no_command_and_asks_for_a_characterization_test() -> None:+ """A bare ``pytest`` or ``npm test`` ran a whole suite as if it guarded the change."""+ for path in ("a/b.py", "web/app.ts"):+ plan = build_validation_plan(_plan("target", file_path=path), {}, {})+ assert plan.basis == "unknown"+ assert plan.commands == [], path+ assert plan.prerequisite == (+ "No test reaches this; add a characterization test for `target` before the edit."+ )+ assert plan.as_dict()["prerequisite"] == plan.prerequisite+ # A target that is not a symbol name is named by its file.+ split = build_validation_plan(_plan("core.py -> 3 files", rtype="split_file"), {}, {})+ assert "characterization test for `core.py` before" in split.prerequisite+++def test_a_reached_plan_carries_no_prerequisite() -> None:+ reached = ReachedBy(["tests/test_b.py"], "call-graph", 1, ("tests/test_b.py",))+ plan = build_validation_plan(_plan("target", file_path="a/b.py"), {}, {"a/b.py": reached})+ assert plan.prerequisite is None+ assert plan.commands == ["pytest tests/test_b.py"]def test_an_untruncated_test_list_keeps_the_precise_command() -> None:@@ -534,6 +550,8 @@ def test_tests_that_call_the_changed_symbol_lead_the_list_with_reasons() -> None_walker_plan(), {}, _walker_reached(), evidence=_walker_evidence())assert validation.tests == [+ # Named for the file: the test someone wrote for it leads.+ "tests/health/test_walker.py",# Calls walk_file directly, more of its functions first."tests/health/test_walks_a_lot.py","tests/health/test_assertions.py",@@ -541,8 +559,7 @@ def test_tests_that_call_the_changed_symbol_lead_the_list_with_reasons() -> None"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",+ # Reaches the file only."tests/health/test_bystander.py",# Test support runs nothing on its own, however close it is."tests/health/conftest.py",@@ -585,8 +602,8 @@ def test_the_cap_keeps_the_strongest_evidence_and_reasons_follow_it() -> None:_walker_plan(), {}, _walker_reached(), evidence=_walker_evidence(), test_limit=2)assert validation.tests == [+ "tests/health/test_walker.py","tests/health/test_walks_a_lot.py",- "tests/health/test_assertions.py",]assert list(validation.reasons) == validation.testsassert validation.total == len(_WALKER_TESTS)@@ -632,5 +649,47 @@ def test_a_test_file_the_plan_edits_is_listed_as_edited() -> None:"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"]+ # The test named for the file leads; the edited one follows.+ assert validation.tests == ["tests/test_core.py", "tests/test_user.py"]assert validation.reasons["tests/test_user.py"] == "edited by this plan"+++def test_a_same_stem_test_leads_the_attention_plan() -> None:+ """``_health_items`` in ``services/attention.py``: the golden test written for+ the file stays first, ahead of tests that only share its directory."""+ path = "packages/server/src/repowise/server/services/attention.py"+ tests = [+ "tests/unit/server/test_alerts.py",+ "tests/unit/server/test_overview_attention.py",+ "tests/unit/server/test_attention_golden.py",+ "tests/unit/cli/test_far_away.py",+ ]+ reached = ReachedBy(tests, "call-graph", len(tests), tuple(tests))+ for order_tests in (True, False):+ plan = build_validation_plan(+ _plan("_health_items", rtype="extract_method", file_path=path),+ {},+ {path: reached},+ order_tests=order_tests,+ )+ assert plan.tests[0] == "tests/unit/server/test_attention_golden.py", order_tests+ assert plan.tests[-1] == "tests/unit/cli/test_far_away.py", order_tests+++def test_a_qualified_spec_name_counts_as_same_stem() -> None:+ path = "src/agents/run/attempt.ts"+ tests = ["src/other/zz.test.ts", "src/agents/run/attempt.spawn-workspace.test.ts"]+ reached = ReachedBy(tests, "call-graph", 2, tuple(tests))+ plan = build_validation_plan(_plan("run", file_path=path), {}, {path: reached})+ assert plan.tests[0] == "src/agents/run/attempt.spawn-workspace.test.ts"+ assert plan.reasons[plan.tests[0]] == "named for attempt.ts"+++def test_hubs_are_files_above_the_fan_in_bar_or_in_the_top_percent() -> None:+ fan_in = {f"src/m{i:03}.py": 2 for i in range(300)}+ fan_in |= {"src/top.py": 12, "src/wide.py": 51, "src/second.py": 11}+ fan_in |= {"tests/test_a.py": 90, "external:os": 900}+ # The top 1% of 303 files is three, and the floor keeps a fan-in of 2 out.+ assert hub_files(fan_in, {"tests/test_a.py"}) == {"src/top.py", "src/wide.py", "src/second.py"}+ small = {"src/a.py": 4, "src/b.py": 1}+ assert hub_files(small, set()) == frozenset()diff --git a/tests/unit/persistence/test_test_reachability_walk.py b/tests/unit/persistence/test_test_reachability_walk.pyindex 6d0502e65..ab61f8f02 100644--- a/tests/unit/persistence/test_test_reachability_walk.py+++ b/tests/unit/persistence/test_test_reachability_walk.py@@ -28,7 +28,7 @@ from repowise.core.persistence.crud.graph import (batch_upsert_graph_edges,get_all_graph_edges,)-from repowise.core.persistence.models import GraphEdge, GraphNode+from repowise.core.persistence.models import GraphEdge, GraphMetric, GraphNodefrom tests.unit.persistence.helpers import insert_repo@@ -423,3 +423,227 @@ async def test_a_seed_that_calls_another_seed_does_not_shorten_its_distance(asyn)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)}+++async def _fan_in(session, repo_id, fan_in):+ for path, degree in fan_in.items():+ session.add(GraphMetric(repository_id=repo_id, node_id=path, in_degree=degree))+ await session.flush()+++def _via(test, middle, target):+ return [+ (test, f"{test}::test_it", "defines"),+ (middle, f"{middle}::m", "defines"),+ (target, f"{target}::run", "defines"),+ (f"{test}::test_it", f"{middle}::m", "calls"),+ (f"{middle}::m", f"{target}::run", "calls"),+ ]+++async def test_a_test_reaching_a_file_only_through_a_hub_is_dropped(async_session):+ repo = await insert_repo(async_session)+ await _seed(+ async_session,+ repo.id,+ nodes={+ "tests/test_app.py": True,+ "tests/test_helper.py": True,+ "src/app.py": False,+ "src/helper.py": False,+ "src/a.py": False,+ },+ edges=[+ *_via("tests/test_app.py", "src/app.py", "src/a.py"),+ *_via("tests/test_helper.py", "src/helper.py", "src/a.py"),+ ],+ )+ both = await by_tier(async_session, repo.id, ["src/a.py"])+ assert set(both["src/a.py"].tests) == {"tests/test_app.py", "tests/test_helper.py"}+ gated = await by_tier(async_session, repo.id, ["src/a.py"], avoid={"src/app.py"})+ assert gated["src/a.py"].tests == ["tests/test_helper.py"]+ assert gated["src/a.py"].total == 1+++async def test_a_hub_still_carries_reach_into_its_own_symbols(async_session):+ repo = await insert_repo(async_session)+ await _seed(+ async_session,+ repo.id,+ nodes={"tests/test_hub.py": True, "src/hub.py": False},+ edges=[+ ("tests/test_hub.py", "tests/test_hub.py::test_it", "defines"),+ ("tests/test_hub.py::test_it", "src/hub.py::outer", "calls"),+ ("src/hub.py::outer", "src/hub.py::inner", "calls"),+ ],+ )+ found = await reach_into_symbols(+ async_session, repo.id, ["src/hub.py::inner"], {"tests/test_hub.py"}, avoid={"src/hub.py"}+ )+ assert found == {"src/hub.py::inner": {"tests/test_hub.py": ReachDistance(2, 1)}}+++async def test_a_test_importing_a_file_through_a_barrel_imports_it(async_session):+ repo = await insert_repo(async_session)+ imports = [+ ("src/index.ts", "src/util.ts", '["walk", "other"]'),+ ("src/all.ts", "src/util.ts", '["*"]'),+ ("tests/a.test.ts", "src/index.ts", '["walk"]'),+ ("tests/b.test.ts", "src/index.ts", '["unrelated"]'),+ ("tests/c.test.ts", "src/index.ts", "[]"),+ ("tests/d.test.ts", "src/all.ts", '["lonely"]'),+ ]+ for source, target, names in imports:+ async_session.add(+ GraphEdge(+ repository_id=repo.id,+ source_node_id=source,+ target_node_id=target,+ edge_type="imports",+ imported_names_json=names,+ )+ )+ await async_session.flush()+ tests = {"tests/a.test.ts", "tests/b.test.ts", "tests/c.test.ts", "tests/d.test.ts"}+ # ``all.ts`` is no barrel by name, so ``d`` is not followed through it.+ assert await imported_names_by_test(async_session, repo.id, ["src/util.ts"], tests) == {+ "src/util.ts": {"tests/a.test.ts": frozenset({"walk"}), "tests/c.test.ts": frozenset()}+ }+++async def _hub_repo(session, *, tests=(), edges=()):+ """``src/util.py`` is a hub (fan-in 60) with three functions: ``test_runner``+ calls ``walk``, ``test_bystander`` calls ``other``, nothing calls ``lonely``."""+ repo = await insert_repo(session)+ nodes = {"tests/test_bystander.py": True, "tests/test_runner.py": True, "src/util.py": False}+ nodes |= dict.fromkeys(tests, True)+ for path, is_test in nodes.items():+ 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), ("lonely", 50, 60)):+ session.add(+ GraphNode(+ repository_id=repo.id,+ node_id=f"src/util.py::{name}",+ node_type="symbol",+ file_path="src/util.py",+ start_line=start,+ end_line=end,+ )+ )+ await _seed(+ session,+ repo.id,+ nodes={},+ edges=[+ ("src/util.py", "src/util.py::walk", "defines"),+ ("src/util.py", "src/util.py::other", "defines"),+ ("src/util.py", "src/util.py::lonely", "defines"),+ ("tests/test_runner.py", "tests/test_runner.py::test_it", "defines"),+ ("tests/test_bystander.py", "tests/test_bystander.py::test_it", "defines"),+ ("tests/test_runner.py::test_it", "src/util.py::walk", "calls"),+ ("tests/test_bystander.py::test_it", "src/util.py::other", "calls"),+ ],+ )+ for source, target, names in edges:+ session.add(+ GraphEdge(+ repository_id=repo.id,+ source_node_id=source,+ target_node_id=target,+ edge_type="imports",+ imported_names_json=names,+ )+ )+ session.add(GraphMetric(repository_id=repo.id, node_id="src/util.py", in_degree=60))+ await session.flush()+ return repo+++async def _util_validations(session, repo_id, *, rank_only=False):+ from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion+ from repowise.core.analysis.health.refactoring.recommendations import (+ hydrate_recommendations,+ )++ plans = [+ RefactoringSuggestion(+ refactoring_type="extract_method",+ file_path="src/util.py",+ target_symbol=symbol,+ line_start=start,+ line_end=end,+ plan={},+ evidence={},+ impact_delta=1.0,+ effort_bucket="M",+ blast_radius={},+ confidence="high",+ source_biomarker="long_function",+ )+ for symbol, start, end in (("walk", 1, 20), ("lonely", 50, 60))+ ]+ items = await hydrate_recommendations(session, repo_id, plans, rank_only=rank_only)+ return {item.suggestion.target_symbol: item for item in items}+++async def test_a_hub_plan_lists_only_tests_reaching_the_changed_symbol(async_session):+ """Most of a suite reaches a hub through some other symbol of it; only reach+ into the symbol a plan changes validates the plan. With none, the plan has no+ command and asks for a characterization test first."""+ repo = await _hub_repo(async_session)+ full = await _util_validations(async_session, repo.id)+ walked, lonely = full["walk"].validation, full["lonely"].validation+ assert walked.tests == ["tests/test_runner.py"]+ assert walked.total == 1+ assert walked.prerequisite is None+ assert lonely.basis == "unknown"+ assert lonely.tests == []+ assert lonely.commands == []+ assert lonely.prerequisite == (+ "No test reaches this; add a characterization test for `lonely` before the edit."+ )+ # The rank-only pass a paged list makes narrows the same way.+ ranked = await _util_validations(async_session, repo.id, rank_only=True)+ for symbol, item in full.items():+ fast = ranked[symbol]+ assert (fast.validation.basis, fast.validation.total, fast.validation.prerequisite) == (+ item.validation.basis,+ item.validation.total,+ item.validation.prerequisite,+ )+ assert set(fast.validation.tests) == set(item.validation.tests)+ assert fast.risk == item.risk+++async def test_a_hub_import_the_graph_cannot_tie_to_a_symbol_still_counts(async_session):+ """``import util`` then ``util.lonely()`` with the call unresolved, a namespace+ import, or ``lonely`` through a barrel: none proves the test misses the+ change, so none is dropped into "no test reaches this". An import of other+ names is proof enough."""+ repo = await _hub_repo(+ async_session,+ tests=(+ "tests/test_module.py",+ "tests/test_star.py",+ "tests/test_barrel.py",+ "tests/test_named.py",+ "tests/test_util_extra.py",+ ),+ edges=(+ ("tests/test_module.py", "src/util.py", '["util"]'),+ ("tests/test_star.py", "src/util.py", '["*"]'),+ ("src/__init__.py", "src/util.py", '["lonely"]'),+ ("tests/test_barrel.py", "src/__init__.py", '["lonely"]'),+ ("tests/test_named.py", "src/util.py", '["other"]'),+ # Named like a test of the file, but no exemption from the hub filter.+ ("tests/test_util_extra.py", "src/util.py", '["other"]'),+ ),+ )+ lonely = (await _util_validations(async_session, repo.id))["lonely"].validation+ assert lonely.basis == "inferred"+ assert set(lonely.tests) == {+ "tests/test_module.py",+ "tests/test_star.py",+ "tests/test_barrel.py",+ }+ assert lonely.prerequisite is Nonediff --git a/tests/unit/server/mcp/test_performance_levels.py b/tests/unit/server/mcp/test_performance_levels.pyindex 6b57b839a..3fbec2166 100644--- a/tests/unit/server/mcp/test_performance_levels.py+++ b/tests/unit/server/mcp/test_performance_levels.py@@ -272,7 +272,9 @@ async def test_one_id_returns_the_cause_its_plan_and_its_rank_rationale(assert result["confidence"] == "high"assert result["fix"]["safety"] == "advisory"assert [step["order"] for step in result["plan_steps"]] == [1, 2, 3, 4, 5]- assert result["validation"]["commands"]+ # No test reaches the fixture's code: no command, and the plan says so.+ assert result["validation"]["commands"] == []+ assert "add a characterization test" in result["validation"]["prerequisite"]assert result["facets"]["leverage"] == "shared"assert result["why_ranked"]assert len(json.dumps(result)) <= 20_000diff --git a/tests/unit/test_test_paths.py b/tests/unit/test_test_paths.pyindex c472af8b7..482b7846c 100644--- a/tests/unit/test_test_paths.py+++ b/tests/unit/test_test_paths.py@@ -16,6 +16,7 @@ from repowise.core.test_paths import (is_test_related_path,is_test_support_path,is_unambiguous_test_path,+ names_test_for,)# (path, language or None, expected classification)@@ -367,3 +368,29 @@ def test_pytest_config_overrules_a_test_shaped_python_name(path: str, expected:assert got == expected# Without the config the name decides, as it does for a bare pytest.assert is_test_related_path(path)+++ ("test_path", "source", "siblings", "named"),+ [+ ("tests/test_loader.py", "src/loader.py", (), True),+ ("tests/test_attention_golden.py", "src/attention.py", (), True),+ ("tests/test_loaders.py", "src/loader.py", (), False),+ ("tests/test_foo_bar.py", "src/foo.py", (), True),+ # A sibling the qualified name names exactly is that file's test.+ ("tests/test_foo_bar.py", "src/foo.py", ("src/foo_bar.py",), False),+ ("tests/test_foo_bar.py", "src/foo_bar.py", ("src/foo.py",), True),+ ("src/attempt.spawn-workspace.test.ts", "src/attempt.ts", (), True),+ # Multi-dot stems keep PurePath semantics in both directions.+ ("src/foo.test.ts", "src/foo.config.ts", (), False),+ ("src/foo.config.test.ts", "src/foo.config.ts", (), True),+ ("src/foo.config.test.ts", "src/foo.ts", ("src/foo.config.ts",), False),+ ("pkg/foo_bar_test.go", "pkg/foo.go", (), True),+ ("pkg/foo_bar_test.go", "pkg/foo.go", ("pkg/foo_bar.go",), False),+ ("src/FooBarTest.java", "src/Foo.java", (), True),+ ("src/FooBarTests.cs", "src/Foo.cs", ("src/FooBar.cs",), False),+ ("src/Footest.java", "src/Foo.java", (), False),+ ],+)+def test_a_test_named_for_a_file_may_carry_a_qualifier(test_path, source, siblings, named):+ assert names_test_for(test_path, source, siblings) is named