Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(refactoring): quote the test functions that call a plan's code (#3478)
Raghav Chamadiya9a6f95d1fbd9
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex 17c4ddb5a..2c65a4753 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -64,8 +64,12 @@ structured plan for an agent. The page never edits code or runs tests on its ownA plan lists the tests closest to the change first: measured coverage, thentests 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.+through a widely imported hub module are left out. When the plan changes known+functions, it quotes the few test functions nearest each one as runnable+selectors (`tests/test_orders.py::test_total`), and its command runs only the+files they live in. When no test reaches the change, the plan has no command and+asks for a characterization test first; it also asks when tests reach the file+but none reaches the changed function.In a plan with several steps, such as a performance fix at several call sites,plan detail adds a `verify` to each step whose tests differ from the plan's: thediff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.mdindex f881582f4..d4c214163 100644--- a/docs/layers/TEST_INTELLIGENCE.md+++ b/docs/layers/TEST_INTELLIGENCE.md@@ -70,6 +70,13 @@ known direction: a call edge says control *can* reach a file, not that a rundid. So it is safe as a floor ("something reaches this, do not call ituntested") and unsafe as a quantity.+Each index also keeps, for every function, the few test functions nearest it in+the call graph. Refactoring plans quote them as runnable selectors in place of+whole test files, and they are inferred like the rest of the graph map. A+function with no resolved caller, or in a language whose tests cannot be told+apart by name (such as Java's `@Test` or Rust's `#[test]`), is left unknown+rather than called untested.+Each ingest replaces the previous per-file and per-test rows. Ingest at thecommit you intend to query so line numbers match. The repo-wide totals of thenewest 50 ingests are kept as history and drawn as a trend on the Tests tabdiff --git a/packages/core/alembic/versions/0106_function_tests.py b/packages/core/alembic/versions/0106_function_tests.pynew file mode 100644index 000000000..6f4c9c9aa--- /dev/null+++ b/packages/core/alembic/versions/0106_function_tests.py@@ -0,0 +1,30 @@+"""Add ``function_facts.tests_json``: each function's nearest test functions.++Local SQLite stores get the column from ``init_db``; this migration covers+managed Postgres. Values appear on the next analysis.++Revision ID: 0106+Revises: 0105+Create Date: 2026-10-11+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0106"+down_revision: str | None = "0105"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.add_column("function_facts", sa.Column("tests_json", sa.Text(), nullable=True))+++def downgrade() -> None:+ op.drop_column("function_facts", "tests_json")diff --git a/packages/core/src/repowise/core/analysis/function_test_map.py b/packages/core/src/repowise/core/analysis/function_test_map.pynew file mode 100644index 000000000..2c8985c85--- /dev/null+++ b/packages/core/src/repowise/core/analysis/function_test_map.py@@ -0,0 +1,223 @@+"""Each function's nearest test functions, read off the call graph the health pass holds.++``test_reachability`` answers which test *files* reach a file. A plan that+changes one function wants something narrower: the few test functions that+run it, as selectors a test runner takes (``tests/x/test_a.py::TestC::test_b``),+so a check between edits runs seconds of tests rather than whole files.++One forward walk from every runnable test over the reliable execution edges+(``ExecutionGraphIndex.forward``), at most :data:`DEFAULT_CALL_DEPTH` hops, the+depth the file walk measured as saturating. Helpers inside test files are walked+through but never quoted: only a symbol a runner collects is a selector. Each+node keeps its :data:`FUNCTION_TEST_K` nearest tests and passes on only the ones+it just gained, so the cost is O(edges x k x depth) however large the suite.+That is exact by hops: if a test is among a function's k nearest through some+caller, either it is among that caller's k nearest one hop closer, or the+caller already holds k tests at least as close.++Which tests run is the per-language rule the health walk already uses+(``complexity.test_case``), read off the symbol's name. A language whose cases+that rule cannot tell from a name (JUnit's ``@Test``, Rust's ``#[test]``, a+language with no rule) seeds nothing, so its functions are left unmapped rather+than called untested. A mapped function with no test is one the graph saw+called, by resolved edges, and no test reached within the depth; a function+with no resolved caller at all (dispatch by name, a framework hook) is left+unmapped too. Rows two and three hops out are stored for readers that want+reach; plans quote only the tests one hop away.+"""++from __future__ import annotations++import json+from collections.abc import Collection, Iterable, Mapping+from dataclasses import dataclass+from functools import lru_cache+from pathlib import PurePosixPath++from repowise.core.analysis.execution_graph import ExecutionGraphIndex, file_of_symbol+from repowise.core.analysis.health.complexity.test_case import (+ runs_module_callbacks,+ test_case_by_name,+)+from repowise.core.ingestion.models import EXTENSION_TO_LANGUAGE+from repowise.core.test_paths import paired_test_names++# How many tests each function keeps. Measured on this repository and hermes:+# recall against direct callers gains under 4 points past 5 while the stored+# bytes grow by half again at 8.+FUNCTION_TEST_K = 5++_MODULE = "__module__"+# A shorter name matches inside unrelated test names (``get`` in ``test_target``).+_MIN_NAME_MATCH = 3+++@dataclass(frozen=True, slots=True)+class MappedTest:+ """A test that runs a function: its runnable selector and the call hops to it.++ A selector is a symbol id, which is a pytest node id without parameters+ (pytest runs every parametrization of it), or a JS/TS test file, whose+ ``it`` cases have no symbols of their own.+ """++ selector: str+ hops: int+++FunctionTests = dict[str, tuple[MappedTest, ...]]+++@lru_cache(maxsize=4096)+def _language(path: str) -> str | None:+ return EXTENSION_TO_LANGUAGE.get(PurePosixPath(path).suffix)+++@lru_cache(maxsize=64)+def _seeds_tests(language: str | None) -> bool:+ """Whether the language's test cases can be found from the graph alone."""+ return test_case_by_name("", language) is not None or runs_module_callbacks(language)+++def runnable_selector(symbol_id: str) -> str | None:+ """The selector that runs test-file symbol *symbol_id*, or ``None`` for a helper."""+ path, _, rest = symbol_id.partition("::")+ if not rest:+ return None+ language = _language(path)+ name = rest.rsplit("::", 1)[-1]+ if name == _MODULE:+ return path if runs_module_callbacks(language) else None+ return symbol_id if test_case_by_name(name, language) else None+++@lru_cache(maxsize=65536)+def _paired(file_path: str) -> frozenset[str]:+ return paired_test_names(file_path)+++def _affinity(function_id: str, selector: str) -> tuple[int, int, str]:+ """Among tests the same hops away: one naming the function, then one in a+ file named for the function's file, then by selector."""+ name = function_id.rsplit("::", 1)[-1].lstrip("_").lower()+ test_name = selector.rsplit("::", 1)[-1].lower()+ names_it = len(name) >= _MIN_NAME_MATCH and name in test_name+ test_file = PurePosixPath(file_of_symbol(selector)).name+ return (+ 0 if names_it else 1,+ 0 if test_file in _paired(file_of_symbol(function_id)) else 1,+ selector,+ )+++def _seeds(index: ExecutionGraphIndex, test_files: Iterable[str]) -> dict[str, str]:+ """Every runnable test symbol, mapped to its selector."""+ seeds: dict[str, str] = {}+ for path in test_files:+ for symbol in index.declares.get(path, ()):+ selector = runnable_selector(symbol)+ if selector is not None:+ seeds[symbol] = selector+ return seeds+++def _offer(+ best: dict[str, dict[str, int]], callee: str, selectors: set[str], hops: int, k: int+) -> tuple[str, ...]:+ """Add to *callee*'s nearest the closest of *selectors* it has room for; the gain."""+ known = best.setdefault(callee, {})+ room = k - len(known)+ fresh = [selector for selector in selectors if selector not in known]+ if room <= 0 or not fresh:+ return ()+ fresh.sort(key=lambda selector: _affinity(callee, selector))+ gained = tuple(fresh[:room])+ known.update(dict.fromkeys(gained, hops))+ return gained+++def function_test_map(+ index: ExecutionGraphIndex,+ test_files: Collection[str],+ *,+ k: int = FUNCTION_TEST_K,+) -> FunctionTests:+ """Each mapped non-test symbol's *k* nearest tests, nearest first.++ A symbol is mapped when a test reaches it, or when it has a resolved caller+ and its language seeds tests: then an empty tuple means no test reaches it.+ """+ # Here, not at the top: the store imports this module, and the reach module+ # imports the store's models.+ from repowise.core.analysis.test_reachability import DEFAULT_CALL_DEPTH++ tests = set(test_files)+ frontier = {symbol: (selector,) for symbol, selector in _seeds(index, tests).items()}+ best: dict[str, dict[str, int]] = {}+ for hops in range(1, DEFAULT_CALL_DEPTH + 1):+ offers: dict[str, set[str]] = {}+ for node, selectors in frontier.items():+ for callee in index.forward.get(node, ()):+ offers.setdefault(callee, set()).update(selectors)+ frontier = {}+ for callee, selectors in offers.items():+ if gained := _offer(best, callee, selectors, hops, k):+ frontier[callee] = gained+ out: FunctionTests = {+ node: tuple(+ MappedTest(selector, hops)+ for selector, hops in sorted(+ known.items(), key=lambda item, n=node: (item[1], *_affinity(n, item[0]))+ )+ )+ for node, known in best.items()+ if file_of_symbol(node) not in tests+ }+ for node in index.reverse:+ path = file_of_symbol(node)+ if node not in out and path not in tests and _seeds_tests(_language(path)):+ out[node] = ()+ return out+++def encode_tests(tests: Iterable[MappedTest]) -> str:+ """The stored form: ``[[selector, hops], ...]``, compact."""+ return json.dumps([[test.selector, test.hops] for test in tests], separators=(",", ":"))+++def decode_tests(value: str | None) -> tuple[MappedTest, ...] | None:+ """The stored form back; ``None`` when the row was never mapped or is unreadable."""+ if value is None:+ return None+ try:+ rows = json.loads(value)+ except (TypeError, ValueError):+ return None+ if not isinstance(rows, list):+ return None+ return tuple(+ MappedTest(row[0], row[1])+ for row in rows+ if isinstance(row, list)+ and len(row) == 2+ and isinstance(row[0], str)+ and isinstance(row[1], int)+ )+++def encoded_map(tests: Mapping[str, tuple[MappedTest, ...]]) -> dict[str, str]:+ """Each mapped symbol's stored form, encoded once per run; an absent symbol+ stores NULL (never mapped)."""+ return {symbol: encode_tests(mapped) for symbol, mapped in tests.items()}+++__all__ = [+ "FUNCTION_TEST_K",+ "FunctionTests",+ "MappedTest",+ "decode_tests",+ "encode_tests",+ "encoded_map",+ "function_test_map",+ "runnable_selector",+]diff --git a/packages/core/src/repowise/core/analysis/health/complexity/test_case.py b/packages/core/src/repowise/core/analysis/health/complexity/test_case.pyindex 09595fb43..557c8bf19 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/test_case.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/test_case.py@@ -133,6 +133,34 @@ def _matches_runner_prefix(name: str, prefixes: tuple[str, ...]) -> bool:return False+def _named_case(name: str, dialect: TestCaseDialect) -> bool:+ """The name rules alone: a prefix, either case rule, and not excluded."""+ if name in dialect.excluded_names:+ return False+ if dialect.name_prefixes and name.lower().startswith(dialect.name_prefixes):+ return True+ return _matches_runner_prefix(name, dialect.runner_prefixes)+++def test_case_by_name(name: str, language: str | None) -> bool | None:+ """:func:`is_test_case` for a graph symbol, which has a name and no node.++ ``None`` when the language's rule cannot be read off a name: it has no+ row, or its cases are marked by annotations or are anonymous callbacks.+ """+ dialect = TEST_CASE_DIALECTS.get(language or "")+ if dialect is None or dialect.annotations or dialect.callback_callees:+ return None+ return _named_case(name, dialect)+++def runs_module_callbacks(language: str | None) -> bool:+ """Whether the language's cases are callbacks (``it(...)``), which the graph+ files under the module, so the test file is the case to run."""+ dialect = TEST_CASE_DIALECTS.get(language or "")+ return dialect is not None and bool(dialect.callback_callees)++def is_test_case(fn_node: Node, name: str, language: str) -> bool:"""True when *fn_node* is a test case the language's runner would collect."""dialect = TEST_CASE_DIALECTS.get(language)@@ -146,8 +174,6 @@ def is_test_case(fn_node: Node, name: str, language: str) -> bool:# The first dotted segment is the framework function in every form of# it (``it``, ``it.each``, ``it.skip``).return callee.split(".", 1)[0] in dialect.callback_callees- if dialect.name_prefixes and lowered.startswith(dialect.name_prefixes):- return True- if _matches_runner_prefix(name, dialect.runner_prefixes):+ if _named_case(name, dialect):return Truereturn bool(dialect.annotations) and bool(dialect.annotations & _annotation_names(fn_node))diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex 85e37fc57..3ffd826b5 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -45,6 +45,7 @@ from ...installed_components import is_installed_componentfrom ...test_paths import paired_test_namesfrom ..dead_code.file_reachability import file_dependency_neighborsfrom ..execution_roles import ExecutionRoles+from ..function_test_map import FunctionTests, function_test_mapfrom ..graph_view import HasEdge, ImportEdgeViewfrom ..test_reachability import files_reached_by_tests, files_with_paired_testsfrom .asserts.lexicon import AssertVocabulary@@ -867,11 +868,12 @@ class HealthAnalyzer:return self._tests_reach_cachedef _paired_tests(self, analyzed_paths: set[str]) -> set[str]:- """Analyzed files a test is paired with; see ``files_with_paired_tests``.+ """Analyzed files a test is paired with; see ``files_with_paired_tests``."""+ return files_with_paired_tests(self.graph, analyzed_paths, self._all_test_files())- Test files come from the graph as well as this pass, so an incremental- run that re-parses only the changed files still sees every test.- """+ def _all_test_files(self) -> set[str]:+ """Test files from this pass and the graph, so an incremental run that+ re-parses only the changed files still sees every test."""test_files = {pf.file_info.path for pf in self.parsed_files if pf.file_info.is_test}if self.graph is not None:test_files.update(@@ -879,7 +881,12 @@ class HealthAnalyzer:for node, data in self.graph.nodes(data=True)if data.get("is_test") and data.get("node_type") != "symbol")- return files_with_paired_tests(self.graph, analyzed_paths, test_files)+ return test_files++ def _function_tests(self) -> FunctionTests | None:+ """Each function's nearest test functions, over the whole graph."""+ index = self._execution_graph()+ return None if index is None else function_test_map(index, self._all_test_files())def _package_boundaries(self, analyzed_paths: set[str]) -> set[str]:"""Package roots for this repo, decided once per analyzer.@@ -1155,6 +1162,8 @@ class HealthAnalyzer:with timed(timings, "analysis.health.finalize"):execution_roles = self._mark_perf_entry_reachability(findings)suggestions = self._with_performance_plans(run, findings, suggestions)+ with timed(timings, "analysis.health.function_tests"):+ function_tests = self._function_tests()return HealthReport(repo_id="",analyzed_at=datetime.now(UTC),@@ -1164,6 +1173,7 @@ class HealthAnalyzer:function_blame_rows=self._function_blame_rows(walked),execution_roles=execution_roles,function_facts=self._function_fact_rows(walked),+ function_tests=function_tests,repo_function_mod_p80=full_repo_fn_mod_p80,refactoring_suggestions=suggestions,performance_plan_policy=PerformancePlanPolicy(diff --git a/packages/core/src/repowise/core/analysis/health/models.py b/packages/core/src/repowise/core/analysis/health/models.pyindex df07d4056..563de1b65 100644--- a/packages/core/src/repowise/core/analysis/health/models.py+++ b/packages/core/src/repowise/core/analysis/health/models.py@@ -246,3 +246,7 @@ class HealthReport:# (``HealthAnalyzer._function_fact_rows``). None when there was no graph to# key rows on: the writers then leave the stored rows alone.function_facts: list[dict] | None = None+ # Each function's nearest tests over the whole graph+ # (``function_test_map.function_test_map``), restamped onto every stored+ # row. None without a graph, like ``function_facts``.+ function_tests: dict[str, tuple] | None = Nonediff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.pyindex 717865974..12cc159b4 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py@@ -16,6 +16,7 @@ from collections.abc import Callable, Collection, Mapping, Sequencefrom dataclasses import dataclass, fieldfrom typing import Any, Literal+from repowise.core.analysis.function_test_map import MappedTestfrom repowise.core.analysis.health.grading import TARGET_SCOREfrom repowise.core.analysis.health.perf.ranking import _percentile_thresholdfrom repowise.core.analysis.health.queue_rules import FilterRule@@ -327,6 +328,8 @@ 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.+ ``function_tests`` is each mapped function's nearest test functions+ (``function_facts.tests_json``); an absent id was never mapped.``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."""@@ -334,6 +337,7 @@ class ValidationEvidence: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)+ function_tests: Mapping[str, tuple[MappedTest, ...]] = field(default_factory=dict)hubs: frozenset[str] = frozenset()siblings: Mapping[str, tuple[str, ...]] = field(default_factory=dict)@@ -621,6 +625,44 @@ def _rank_target_tests(return out+# Quoted only at one hop: per-test coverage confirmed 99% there, 82% at two, 59% at three.+QUOTED_HOPS = 1+++def _nearest_function_tests(+ ranges: Sequence[tuple[str, set[int] | None]],+ symbols: Mapping[str, Sequence[str]],+ evidence: ValidationEvidence,+) -> list[tuple[MappedTest, str]] | None:+ """The nearest test functions of the functions the plan changes, nearest first,+ each with the function it runs. ``None`` unless every file the plan changes+ names its functions and every one is mapped; ``[]`` when no test reaches any."""+ picked: dict[str, tuple[MappedTest, str]] = {}+ for path, _lines in ranges:+ ids = symbols[path]+ if not ids or any(symbol not in evidence.function_tests for symbol in ids):+ return None+ for symbol in ids:+ _merge_nearest(picked, evidence.function_tests[symbol], symbol)+ # Stable, so each function's own order holds among tests the same hops away.+ return sorted(picked.values(), key=lambda pair: pair[0].hops)+++def _merge_nearest(+ picked: dict[str, tuple[MappedTest, str]], tests: Sequence[MappedTest], symbol: str+) -> None:+ """Add *symbol*'s tests to *picked*, a test shared by two functions keeping its nearer."""+ for test in tests:+ held = picked.get(test.selector)+ if held is None or test.hops < held[0].hops:+ picked[test.selector] = (test, symbol)+++def _runs_reason(test: MappedTest, symbol: str) -> str:+ label = _symbol_label(symbol)+ return f"calls {label}" if test.hops == 1 else f"reaches {label} in {test.hops} calls"++def _characterization_step(suggestion: RefactoringSuggestion) -> str:"""The step before an edit no test reaches: pin today's behaviour first."""symbol = suggestion.target_symbol@@ -834,20 +876,40 @@ def build_validation_plan(if len(target_rows) == 1else sum(target.total for target in target_rows))+ # Measured coverage outranks the graph; otherwise the plan quotes the test+ # functions that call the functions it changes, as runnable selectors.+ nearest = (+ _nearest_function_tests(ranges, symbols, facts) if aggregate_basis != "measured" else None+ )+ direct = [pair for pair in nearest or () if pair[0].hops <= QUOTED_HOPS]+ if direct:+ aggregate_basis, aggregate_via, aggregate_total = "inferred", "call-graph", len(direct)+ shown = [test.selector for test, _ in direct[:cap]]+ reasons = {test.selector: _runs_reason(test, symbol) for test, symbol in direct[:cap]}+ # Each quoted test's file, whole: shorter than naming every function,+ # and it runs at least the tests the plan quotes.+ commands = commands_for_tests(sorted({test.split("::", 1)[0] for test in shown}))+ else:+ shown = ordered_tests[:cap]+ reasons = {test: best[test][1] for test in shown}+ commands = commands_for_tests(shown, total=aggregate_total)files = affected_files(suggestion)return ValidationPlan(basis=aggregate_basis,via=aggregate_via,total=aggregate_total,- tests=ordered_tests[:cap],- truncated=aggregate_total > len(ordered_tests[:cap]),+ tests=shown,+ truncated=aggregate_total > len(shown),affected_files=files,affected_symbols=affected_symbols(suggestion),- commands=commands_for_tests(ordered_tests[:cap], total=aggregate_total),+ commands=commands,targets=target_rows,- reasons={test: best[test][1] for test in ordered_tests[:cap]} if order_tests else {},+ reasons=reasons if order_tests else {},+ # Also when tests reach the file but none reaches a function it changes.prerequisite=(- _characterization_step(suggestion) if aggregate_basis == "unknown" else None+ _characterization_step(suggestion)+ if aggregate_basis == "unknown" or nearest == []+ else None),)diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.pyindex 7470b8952..f731b7527 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py@@ -66,7 +66,7 @@ from .doc_drift import (serialize_doc_drift_row,summarize_confidence_rows,)-from .function_facts import get_function_facts, write_function_facts+from .function_facts import get_function_facts, tests_for_functions, write_function_factsfrom .health import (FILE_TREND_SNAPSHOT_WINDOW,HEALTH_SNAPSHOT_RETENTION,@@ -223,6 +223,7 @@ __all__ = ["summarize_open_plans","tests_covering","tests_covering_files",+ "tests_for_functions","update_dead_code_status","update_health_finding_status","update_refactoring_opportunity_status",diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/function_facts.py b/packages/core/src/repowise/core/persistence/crud/analysis/function_facts.pyindex 5bad6a91f..96d0f5be4 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/function_facts.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/function_facts.py@@ -1,21 +1,29 @@-"""The per-function store: one row per function symbol, its role and body facts.+"""The per-function store: one row per function symbol, its role, body facts and tests.Facts are pure on a file's bytes, so a run rewrites the rows of the files itwalked and leaves the rest. A role is not: a seed or a call in another file-moves it, so every run restamps every row's role from its own role map.+moves it, so every run restamps every row's role from its own role map. The+nearest tests move the same way (a test or a caller elsewhere changes), so they+are restamped with it, and only the rows whose answer changed are written."""from __future__ import annotationsimport json-from collections.abc import Iterable, Iterator, Mapping+from collections.abc import Callable, Iterable, Iterator, Mappingfrom typing import TYPE_CHECKING, Anyfrom sqlalchemy import and_, delete, insert, or_, select, updatefrom sqlalchemy.ext.asyncio import AsyncSessionfrom ....analysis.execution_graph import file_of_symbol-from ...models import FunctionFact+from ....analysis.function_test_map import (+ FunctionTests,+ MappedTest,+ decode_tests,+ encoded_map,+)+from ...models import FunctionFact, GraphNodeif TYPE_CHECKING:from ....analysis.execution_roles import ExecutionRoles@@ -26,7 +34,7 @@ _CHUNK = 500_RANGES_PER_DELETE = 200-def _row(repository_id: str, row: Mapping[str, Any]) -> dict[str, Any]:+def _row(repository_id: str, row: Mapping[str, Any], tests: Mapping[str, str]) -> dict[str, Any]:assigns = row.get("receiver_assigns")return {"repository_id": repository_id,@@ -41,6 +49,7 @@ def _row(repository_id: str, row: Mapping[str, Any]) -> dict[str, Any]:"nloc": row.get("nloc"),"params": row.get("params"),"max_nesting": row.get("max_nesting"),+ "tests_json": tests.get(row["symbol_id"]),}@@ -94,39 +103,73 @@ async def write_function_facts(*,file_paths: Iterable[str] | None = None,roles: ExecutionRoles | None = None,+ tests: FunctionTests | None = None,) -> int:"""Replace the rows of *file_paths* (every row when ``None``) with *rows*,- then restamp every row's role from *roles*. Returns the rows written."""+ then restamp every row's role from *roles* and its tests from *tests*+ (``analysis.function_test_map``). Returns the rows written."""if file_paths is None:await session.execute(delete(FunctionFact).where(FunctionFact.repository_id == repository_id))else:await delete_file_rows(session, repository_id, file_paths)# Two walked functions can resolve to one symbol; the first keeps it. Key# order fills the clustered pages instead of splitting them half empty.- by_symbol = {row["symbol_id"]: _row(repository_id, row) for row in reversed(list(rows))}+ encoded = encoded_map(tests) if tests is not None else {}+ by_symbol = {row["symbol_id"]: _row(repository_id, row, encoded) for row in reversed(list(rows))}fresh = [by_symbol[symbol] for symbol in sorted(by_symbol)]# On the table, not the mapper: the ORM bulk path splits a batch wherever a# column flips between NULL and a value, which doubled this write.for i in range(0, len(fresh), _CHUNK):await session.execute(insert(FunctionFact.__table__), fresh[i : i + _CHUNK])- if roles is not None:- await _restamp_roles(session, repository_id, roles)+ if roles is not None or tests is not None:+ await _restamp(session, repository_id, roles, None if tests is None else encoded)return len(fresh)-async def _restamp_roles(session: AsyncSession, repository_id: str, roles: ExecutionRoles) -> None:- stored = await session.execute(- select(FunctionFact.symbol_id, FunctionFact.execution_role).where(- FunctionFact.repository_id == repository_id+async def _restamp(+ session: AsyncSession,+ repository_id: str,+ roles: ExecutionRoles | None,+ tests: Mapping[str, str] | None,+) -> None:+ """Write each row's role and tests where they moved. *tests* is the run's+ encoded map; a symbol it leaves out stores NULL (never mapped)."""+ stored = (+ await session.execute(+ select(+ FunctionFact.symbol_id, FunctionFact.execution_role, FunctionFact.tests_json+ ).where(FunctionFact.repository_id == repository_id))- )- changed = [- {"repository_id": repository_id, "symbol_id": symbol, "execution_role": role}- for symbol, current in stored.all()- if (role := roles.role_of(symbol, file_of_symbol(symbol))) != current+ ).all()+ if roles is not None:+ await _write_moved(+ session,+ repository_id,+ _moved(stored, 1, "execution_role", lambda s: roles.role_of(s, file_of_symbol(s))),+ )+ if tests is not None:+ await _write_moved(session, repository_id, _moved(stored, 2, "tests_json", tests.get))+++def _moved(+ stored: Iterable[Any], at: int, column: str, now: Callable[[str], Any]+) -> list[dict[str, Any]]:+ """``{symbol_id, column}`` for each stored row whose *column* (row index+ *at*) differs from *now*'s answer."""+ return [+ {"symbol_id": row[0], column: value}+ for row in stored+ if (value := now(row[0])) != row[at]]+++async def _write_moved(+ session: AsyncSession, repository_id: str, changed: list[dict[str, Any]]+) -> None:+ """One column per batch: the ORM bulk path splits a batch whose rows set different columns."""for i in range(0, len(changed), _CHUNK):- await session.execute(update(FunctionFact), changed[i : i + _CHUNK])+ batch = [{"repository_id": repository_id, **row} for row in changed[i : i + _CHUNK]]+ await session.execute(update(FunctionFact), batch)async def get_function_facts(@@ -146,10 +189,66 @@ async def get_function_facts(return out+async def tests_for_functions(+ session: AsyncSession,+ repository_id: str,+ function_ids: Iterable[str],+ k: int | None = None,+) -> dict[str, tuple[MappedTest, ...]]:+ """The stored nearest tests of each of *function_ids*, nearest first, at most *k*.++ An empty tuple is a mapped function no test reaches; an id absent from the+ result was never mapped (no row, or a run before the map existed).+ """+ ids = sorted(set(function_ids))+ out: dict[str, tuple[MappedTest, ...]] = {}+ for i in range(0, len(ids), _CHUNK):+ result = await session.execute(+ select(FunctionFact.symbol_id, FunctionFact.tests_json).where(+ FunctionFact.repository_id == repository_id,+ FunctionFact.symbol_id.in_(ids[i : i + _CHUNK]),+ )+ )+ out.update(_decoded(result.all(), k))+ return out+++async def tests_in_files(+ session: AsyncSession, repository_id: str, paths: Iterable[str]+) -> dict[str, tuple[MappedTest, ...]]:+ """:func:`tests_for_functions` for every function in *paths*, in one statement."""+ files = sorted(set(paths))+ if not files:+ return {}+ result = await session.execute(+ select(FunctionFact.symbol_id, FunctionFact.tests_json)+ .join(+ GraphNode,+ and_(+ GraphNode.repository_id == FunctionFact.repository_id,+ GraphNode.node_id == FunctionFact.symbol_id,+ ),+ )+ .where(FunctionFact.repository_id == repository_id, GraphNode.file_path.in_(files))+ )+ return dict(_decoded(result.all(), None))+++def _decoded(+ rows: Iterable[tuple[str, str | None]], k: int | None+) -> Iterator[tuple[str, tuple[MappedTest, ...]]]:+ for symbol, stored in rows:+ mapped = decode_tests(stored)+ if mapped is not None:+ yield symbol, mapped[:k] if k is not None else mapped++__all__ = ["delete_file_rows","get_file_facts","get_function_facts","key_range",+ "tests_for_functions",+ "tests_in_files","write_function_facts",]diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_recommendations.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_recommendations.pyindex f77b9d597..cc8419b63 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_recommendations.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_recommendations.py@@ -49,6 +49,7 @@ from repowise.core.analysis.test_reachability import (from ...models import GraphMetric, GraphNode, HealthFileMetricfrom ..graph import get_graph_metricsfrom .coverage_map import tests_covering_files+from .function_facts import tests_in_filesfrom .health import get_health_metrics@@ -198,7 +199,14 @@ async def validation_inputs([item for item in suggestions if hubs.intersection(affected_files(item))],hub_targets,test_files,- ValidationEvidence(hubs=hubs, siblings=_siblings(in_degree)),+ # Spans and nearest tests for every target file, hub or not, and for+ # every function there: a step of a multi-step plan narrows to its own.+ ValidationEvidence(+ hubs=hubs,+ siblings=_siblings(in_degree),+ symbols=await _symbol_spans(session, repository_id, target_files),+ function_tests=await tests_in_files(session, repository_id, target_files),+ ),)return ValidationInputs(measured=measured, inferred=inferred, test_files=test_files, evidence=evidence@@ -220,15 +228,8 @@ async def _validation_evidence("""if not target_files:return base- 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)))+ unread = [path for path in target_files if path not in base.symbols]+ spans = {**base.symbols, **await _symbol_spans(session, repository_id, unread)}symbol_ids = {symbolfor suggestion in suggestions@@ -245,6 +246,24 @@ async def _validation_evidence()+async def _symbol_spans(+ session: AsyncSession, repository_id: str, files: Sequence[str]+) -> dict[str, list[SymbolSpan]]:+ """Each file's symbol ids with their line spans, in one statement."""+ if not files:+ return {}+ 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(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)))+ return spans++async def plan_rank_inputs(session: AsyncSession, repository_id: str, file_path: str) -> tuple[dict[str, Any], dict[str, float]]:diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 5f03bf3c7..6fef880f6 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -2115,6 +2115,10 @@ class FunctionFact(Base):nloc: Mapped[int | None] = mapped_column(Integer, nullable=True)params: Mapped[int | None] = mapped_column(Integer, nullable=True)max_nesting: Mapped[int | None] = mapped_column(Integer, nullable=True)+ # The nearest test functions (``analysis.function_test_map``), as+ # ``[[selector, hops], ...]``: ``[]`` when no test reaches the function,+ # NULL when no run has mapped it. Restamped every run, like the role.+ tests_json: Mapped[str | None] = mapped_column(Text, nullable=True)__table_args__ = ({"sqlite_with_rowid": False},)diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex 0ff898858..382552e67 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -1346,6 +1346,20 @@ async def persist_partial_health(commit=analyzed_commit,),)+ # Facts for the files this run walked; roles and nearest tests for every+ # stored row, written only where they moved. No rows means no graph to+ # key them on: the stored ones stay. Before the finalizers, which read+ # each plan's nearest tests off these rows.+ fact_rows = getattr(report, "function_facts", None)+ if fact_rows is not None:+ await write_function_facts(+ session,+ repo_id,+ fact_rows,+ file_paths={*changed_paths, *performance_paths},+ roles=getattr(report, "execution_roles", None),+ tests=getattr(report, "function_tests", None),+ )# A partial run sees a subset of the findings, so the plans and the# queue it would derive are a subset too. Both are rebuilt here instead,# from the merged stored rows, by the same writer the full path uses.@@ -1363,17 +1377,6 @@ async def persist_partial_health(# opportunity folds a file's plans, and a file this run did not touch# can still lose one when a cross-file plan elsewhere resolves.await finalize_refactoring_opportunities(session, repo_id, analyzed_commit=analyzed_commit)- # Facts for the files this run walked; roles for every stored row. No- # rows means no graph to key them on: the stored ones stay.- fact_rows = getattr(report, "function_facts", None)- if fact_rows is not None:- await write_function_facts(- session,- repo_id,- fact_rows,- file_paths={*changed_paths, *performance_paths},- roles=getattr(report, "execution_roles", None),- )# Per-function blame rollup for the changed files (keeps git_function_blame# current between full indexes; FULL git tier only — empty otherwise).fn_blame_rows = getattr(report, "function_blame_rows", None)diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex 111f3b9bf..35b1f8436 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -2007,6 +2007,17 @@ async def save_full_health_report(commit=analyzed_commit,),)+ # No rows means no graph to key them on: the stored ones stay. Before+ # the finalizers, which read each plan's nearest tests off these rows.+ fact_rows = getattr(hr, "function_facts", None)+ if fact_rows is not None:+ await write_function_facts(+ session,+ repo_id,+ fact_rows,+ roles=getattr(hr, "execution_roles", None),+ tests=getattr(hr, "function_tests", None),+ )# Group the stored performance findings into the materialized causal# read model, then reconcile lifecycle and plans.await finalize_performance_opportunities(@@ -2020,12 +2031,6 @@ async def save_full_health_report(# savepoint because it composes over the stored rows, so it has to see# the reconciliation above rather than the detector output.await finalize_refactoring_opportunities(session, repo_id, analyzed_commit=analyzed_commit)- # No rows means no graph to key them on: the stored ones stay.- fact_rows = getattr(hr, "function_facts", None)- if fact_rows is not None:- await write_function_facts(- session, repo_id, fact_rows, roles=getattr(hr, "execution_roles", None)- )async def refresh_governance_findings(diff --git a/tests/unit/health/test_function_test_map.py b/tests/unit/health/test_function_test_map.pynew file mode 100644index 000000000..7f4a2cd5f--- /dev/null+++ b/tests/unit/health/test_function_test_map.py@@ -0,0 +1,321 @@+"""Each function's nearest test functions: the walk, the store, and the plans that quote them."""++from __future__ import annotations++from pathlib import Path++import networkx as nx+import pytest++from repowise.core.analysis.execution_graph import ExecutionGraphIndex+from repowise.core.analysis.function_test_map import (+ MappedTest,+ decode_tests,+ encode_tests,+ function_test_map,+ runnable_selector,+)+from repowise.core.analysis.health import HealthAnalyzer+from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion+from repowise.core.analysis.health.refactoring.recommendations import (+ ValidationEvidence,+ build_validation_plan,+)+from repowise.core.analysis.test_reachability import ReachedBy++T = "tests/test_core.py"+++def _index(calls: dict[str, list[str]]) -> ExecutionGraphIndex:+ declares: dict[str, list[str]] = {}+ for symbol in {*calls, *(c for callees in calls.values() for c in callees)}:+ declares.setdefault(symbol.split("::", 1)[0], []).append(symbol)+ return ExecutionGraphIndex(declares=declares, calls=calls)+++def test_only_collected_tests_are_selectors() -> None:+ assert runnable_selector(f"{T}::test_parse") == f"{T}::test_parse"+ assert runnable_selector(f"{T}::TestParse::test_empty") == f"{T}::TestParse::test_empty"+ assert runnable_selector(f"{T}::_helper") is None+ assert runnable_selector(f"{T}::__module__") is None+ # A JS suite's ``it`` callbacks sit on the module: the file runs them.+ assert runnable_selector("src/a.test.ts::__module__") == "src/a.test.ts"+ # Go's own rule: ``TestXxx``, not the ``TestMain`` entry or a ``testHelper``.+ assert runnable_selector("pkg/a_test.go::TestParse") == "pkg/a_test.go::TestParse"+ assert runnable_selector("pkg/a_test.go::TestMain") is None+ assert runnable_selector("pkg/a_test.go::testHelper") is None+ # A case marked by an annotation cannot be read off a name: never guessed.+ assert runnable_selector("src/FooTest.java::FooTest::testParse") is None+ assert runnable_selector("src/lib_test.rs::test_parse") is None+++def test_nearest_tests_walk_through_test_helpers_and_stop_at_three_hops() -> None:+ index = _index(+ {+ f"{T}::test_parse": ["core.py::parse"],+ f"{T}::test_via_helper": [f"{T}::_helper"],+ f"{T}::_helper": ["core.py::deep"],+ "core.py::deep": ["core.py::deeper"],+ "core.py::deeper": ["core.py::deepest"],+ "src/a.test.ts::__module__": ["src/a.ts::load"],+ "core.py::orphan": ["core.py::called_by_orphan"],+ "src/Foo.java::Foo::run": ["src/Foo.java::Foo::step"],+ }+ )+ found = function_test_map(index, {T, "src/a.test.ts"})+ assert found["core.py::parse"] == (MappedTest(f"{T}::test_parse", 1),)+ assert found["core.py::deep"] == (MappedTest(f"{T}::test_via_helper", 2),)+ assert found["core.py::deeper"] == (MappedTest(f"{T}::test_via_helper", 3),)+ # Called by resolved edges, and no test within three hops: mapped, untested.+ assert found["core.py::deepest"] == ()+ assert found["core.py::called_by_orphan"] == ()+ # No resolved caller at all (a framework hook, dispatch by name): unknown,+ # never untested.+ assert "core.py::orphan" not in found+ # A language whose tests cannot be seeded from names: unknown, never untested.+ assert "src/Foo.java::Foo::step" not in found+ assert found["src/a.ts::load"] == (MappedTest("src/a.test.ts", 1),)+ # Test-file symbols are walked through, never mapped.+ assert not any(node.startswith(T) for node in found)+++def test_each_function_keeps_k_tests_nearest_first_naming_it_first() -> None:+ calls = {f"tests/test_other.py::test_{n}": ["core.py::parse"] for n in "abcdef"}+ calls["tests/test_other.py::test_parse_empty"] = ["core.py::parse"]+ calls["tests/test_z.py::test_far"] = ["core.py::outer"]+ calls["core.py::outer"] = ["core.py::parse"]+ found = function_test_map(_index(calls), {"tests/test_other.py", "tests/test_z.py"}, k=3)+ assert [t.selector for t in found["core.py::parse"]] == [+ "tests/test_other.py::test_parse_empty",+ "tests/test_other.py::test_a",+ "tests/test_other.py::test_b",+ ]+ assert all(t.hops == 1 for t in found["core.py::parse"])+ # A test named for the file ranks before a stranger at the same distance.+ named = function_test_map(+ _index({"tests/test_x.py::test_a": ["core.py::f"], "tests/test_core.py::test_b": ["core.py::f"]}),+ {"tests/test_x.py", "tests/test_core.py"},+ k=1,+ )+ assert named["core.py::f"] == (MappedTest("tests/test_core.py::test_b", 1),)+++def test_the_stored_form_round_trips_and_rejects_garbage() -> None:+ tests = (MappedTest(f"{T}::test_a", 1), MappedTest("src/a.test.ts", 2))+ assert decode_tests(encode_tests(tests)) == tests+ assert decode_tests("[]") == ()+ assert decode_tests(None) is None+ assert decode_tests("{") is None+++def test_the_analyzer_maps_tests_over_the_whole_graph() -> None:+ graph = nx.DiGraph()+ graph.add_node(T, node_type="file", is_test=True)+ graph.add_node("core.py", node_type="file", is_test=False)+ for symbol, path in ((f"{T}::test_parse", T), ("core.py::parse", "core.py")):+ graph.add_node(symbol, node_type="symbol", name=symbol.rsplit("::", 1)[-1], file_path=path)+ graph.add_edge(path, symbol, edge_type="defines")+ graph.add_edge(f"{T}::test_parse", "core.py::parse", edge_type="calls")+ assert HealthAnalyzer(graph)._function_tests() == {+ "core.py::parse": (MappedTest(f"{T}::test_parse", 1),)+ }+ assert HealthAnalyzer(None)._function_tests() is None+++async def store(tmp_path: Path):+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )++ engine = create_engine(f"sqlite+aiosqlite:///{(tmp_path / 'wiki.db').as_posix()}")+ try:+ await init_db(engine)+ async with get_session(create_session_factory(engine)) as session:+ repo = await upsert_repository(session, name="repo", local_path=str(tmp_path))+ await session.commit()+ yield session, repo.id+ finally:+ await engine.dispose()+++async def test_tests_are_stamped_on_every_row_and_read_back_nearest_first(store) -> None:+ from sqlalchemy import event++ from repowise.core.persistence.crud import tests_for_functions, write_function_facts++ session, repo = store+ near = (MappedTest(f"{T}::test_a", 1), MappedTest(f"{T}::test_b", 2))+ rows = [{"symbol_id": "a.py::f"}, {"symbol_id": "a.py::g"}, {"symbol_id": "b.py::h"}]+ await write_function_facts(session, repo, rows)+ assert await tests_for_functions(session, repo, ["a.py::f"]) == {}+ await write_function_facts(session, repo, rows, tests={"a.py::f": near, "a.py::g": ()})+ # b.py::h is not in the map: stored NULL, never mapped, so absent here.+ assert await tests_for_functions(session, repo, ["a.py::f", "a.py::g", "b.py::h"]) == {+ "a.py::f": near,+ "a.py::g": (),+ }+ assert await tests_for_functions(session, repo, ["a.py::f"], k=1) == {"a.py::f": near[:1]}++ # An update walking only b.py: a test moved for a.py::g, so only its row is written.+ updates: list[int] = []+ engine = session.bind.sync_engine++ def count(conn, cursor, statement, parameters, context, executemany):+ if statement.startswith("UPDATE function_facts"):+ updates.append(len(parameters) if executemany else 1)++ event.listen(engine, "before_cursor_execute", count)+ try:+ await write_function_facts(+ session,+ repo,+ [{"symbol_id": "b.py::h"}],+ file_paths=["b.py"],+ tests={"a.py::f": near, "a.py::g": near[1:]},+ )+ finally:+ event.remove(engine, "before_cursor_execute", count)+ assert sum(updates) == 1+ assert (await tests_for_functions(session, repo, ["a.py::g"]))["a.py::g"] == near[1:]++ from repowise.core.persistence.crud.analysis.function_facts import tests_in_files+ from repowise.core.persistence.models import GraphNode++ for symbol in ("a.py::f", "a.py::g", "b.py::h"):+ path = symbol.split("::", 1)[0]+ session.add(+ GraphNode(repository_id=repo, node_id=symbol, node_type="symbol", file_path=path)+ )+ await session.flush()+ assert await tests_in_files(session, repo, ["a.py"]) == {"a.py::f": near, "a.py::g": near[1:]}+++def _extract(file_path: str = "core.py") -> RefactoringSuggestion:+ return RefactoringSuggestion(+ refactoring_type="extract_method",+ file_path=file_path,+ target_symbol="parse",+ line_start=10,+ line_end=20,+ plan={},+ evidence={},+ impact_delta=2.0,+ effort_bucket="M",+ blast_radius={},+ confidence="high",+ source_biomarker="long_function",+ )+++_FILE_REACH = {+ "core.py": ReachedBy(+ ["tests/test_core.py", "tests/test_misc.py"],+ "call-graph",+ 2,+ ("tests/test_core.py", "tests/test_misc.py"),+ )+}+++def _evidence(tests: tuple[MappedTest, ...]) -> ValidationEvidence:+ return ValidationEvidence(+ symbols={"core.py": [("core.py::parse", 5, 30)]},+ function_tests={"core.py::parse": tests},+ )+++def test_a_plan_quotes_the_test_functions_that_call_its_function() -> None:+ near = (+ MappedTest(f"{T}::test_parse", 1),+ MappedTest("tests/test_io.py::test_read", 1),+ MappedTest(f"{T}::test_load", 2),+ )+ plan = build_validation_plan(_extract(), {}, _FILE_REACH, evidence=_evidence(near))+ # A test that only reaches a caller is not quoted: it may never take the call.+ assert plan.tests == [f"{T}::test_parse", "tests/test_io.py::test_read"]+ # The quoted tests' files, whole: at least the tests quoted, in a short command.+ assert plan.commands == [f"pytest {T} tests/test_io.py"]+ assert plan.reasons == {+ f"{T}::test_parse": "calls parse",+ "tests/test_io.py::test_read": "calls parse",+ }+ assert (plan.basis, plan.via, plan.total, plan.prerequisite) == ("inferred", "call-graph", 2, None)+ # The file's own reach stays on the target row.+ assert plan.targets[0].tests == ["tests/test_core.py", "tests/test_misc.py"]+++def test_a_function_reached_only_through_callers_keeps_the_file_answer() -> None:+ near = (MappedTest(f"{T}::test_load", 2),)+ plan = build_validation_plan(_extract(), {}, _FILE_REACH, evidence=_evidence(near))+ assert plan.tests == ["tests/test_core.py", "tests/test_misc.py"]+ assert plan.prerequisite is None+++def test_a_function_no_test_reaches_asks_for_a_characterization_test_in_a_tested_file() -> None:+ plan = build_validation_plan(_extract(), {}, _FILE_REACH, evidence=_evidence(()))+ assert plan.tests == ["tests/test_core.py", "tests/test_misc.py"]+ assert plan.prerequisite == (+ "No test reaches this; add a characterization test for `parse` before the edit."+ )+++def test_an_unmapped_function_keeps_the_file_level_answer() -> None:+ plan = build_validation_plan(+ _extract(), {}, _FILE_REACH, evidence=ValidationEvidence(symbols=_evidence(()).symbols)+ )+ assert plan.tests == ["tests/test_core.py", "tests/test_misc.py"]+ assert plan.prerequisite is None+++def test_measured_coverage_outranks_the_map() -> None:+ measured = {"core.py": [{"test_id": "tests/test_core.py::test_cov", "covered_lines": [12]}]}+ near = (MappedTest(f"{T}::test_parse", 1),)+ plan = build_validation_plan(_extract(), measured, {}, evidence=_evidence(near))+ assert plan.basis == "measured"+ assert plan.tests == ["tests/test_core.py::test_cov"]+++def test_a_capped_list_quotes_the_nearest_and_counts_the_rest() -> None:+ near = (MappedTest(f"{T}::test_parse", 1), MappedTest("tests/test_io.py::test_load", 1))+ plan = build_validation_plan(_extract(), {}, _FILE_REACH, test_limit=1, evidence=_evidence(near))+ assert plan.tests == [f"{T}::test_parse"]+ assert plan.truncated is True+ assert plan.commands == [f"pytest {T}"]+++async def test_validation_inputs_carry_spans_and_tests_for_files_that_are_no_hub(store) -> None:+ """The planless-finding path reads only these inputs, so a non-hub file needs+ its spans and nearest tests here, not only in the plan path's second read."""+ from repowise.core.persistence.crud import write_function_facts+ from repowise.core.persistence.crud.analysis.refactoring_recommendations import (+ validation_inputs,+ )+ from repowise.core.persistence.models import GraphNode++ session, repo = store+ session.add(+ GraphNode(+ repository_id=repo,+ node_id="core.py::parse",+ node_type="symbol",+ file_path="core.py",+ start_line=5,+ end_line=30,+ )+ )+ near = (MappedTest(f"{T}::test_parse", 1),)+ await write_function_facts(+ session, repo, [{"symbol_id": "core.py::parse"}], tests={"core.py::parse": near}+ )+ inputs = await validation_inputs(session, repo, [_extract()], ["core.py"], in_degree={})+ assert inputs.evidence.symbols["core.py"] == [("core.py::parse", 5, 30)]+ assert inputs.evidence.function_tests == {"core.py::parse": near}+ plan = build_validation_plan(+ _extract(), inputs.measured, inputs.inferred, evidence=inputs.evidence, order_tests=False+ )+ assert plan.tests == [f"{T}::test_parse"]