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(impacted-tests): order selected tests by likely relevance and add --prioritize (#3322)
Raghav Chamadiya09f953351ef7
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 07cc5b580..2bca33454 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1069,7 +1069,8 @@ line up.| `--staged` | Diff the staged changes (`git diff --cached`); the default with no range outside CI (in CI: the pull request's change) || `--format` | `table` (default), `json` (full report plus the selection), `list` (test ids one per line), or `args` (one line of runner arguments, or `:all`; reasons on stderr) || `--runner` | For `--format args`: `auto` (default; `files` when mixed), `pytest` (node ids or files), `go` (package dirs), `jest` (files; pass with `--runTestsByPath`), `files` |-| `--explain` | A test file or node id: say why it was or was not selected (the changed file, the evidence and the import route, or the rule that runs it). Added to `--format json` as `explain` |+| `--explain` | A test file or node id: say why it was or was not selected (the changed file, the evidence and the import route, or the rule that runs it) and its place in the run order. Added to `--format json` as `explain` |+| `--prioritize` | With `--format args`, `list` or `json`: the whole suite, the selected tests first in run order, then every other test. Skips nothing; a full run is ordered too |```bashrepowise impacted-tests # staged changes@@ -1079,6 +1080,7 @@ repowise impacted-tests abc123 # a single commitrepowise impacted-tests main..HEAD --format list | xargs pytestrepowise impacted-tests main...HEAD --format args --runner pytestrepowise impacted-tests main...HEAD --explain tests/unit/test_api.py+repowise impacted-tests main...HEAD --format args --prioritize````--format args` exits `0` whether it selects a subset or everything, and `2`@@ -1091,6 +1093,17 @@ or `none` (no index), and a per-test `selected.why`: the first changed file andevidence that selected it, or why it runs with every subset. When it runs everything:[CI](../start/CI.md#selecting-the-tests-a-change-needs).+**Run order.** `--format args` and `json` list the selected tests likeliest to fail+first (`--format list` without `--prioritize` keeps the report's order). Tiers, in+order: a test the change edits; one the per-test map runs on a changed line, then on+a changed file; one whose calls, fixtures or direct import reach the change; one+reaching it through other files; tests that run with every subset. Within a tier:+a failure in the last local pytest run (`.pytest_cache`, ids relative to the+repository root), fewer graph hops (when measured), more changes shared with the+changed files, more changed files reached, then path. `--format json` lists each test under+`order` with its `tier`, `hops`, `co_change` and `failed_last_run`. With+`--prioritize`, a file selected only by some node ids runs whole at its place.+---### `repowise health [PATH]`diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex c0c05b2d7..7984a147d 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -223,7 +223,7 @@ Opt-in blocks: `owners` adds `owner_pct`, `owner_line_pct`, `recent_owner`, `rec|-------|---------|| `may_break` | Production files in reverse-import reach of the change: candidates for review, not proven breakage || `missing_cochanges` | Historical co-change partners absent from the change |-| `tests_to_run`, `tests_to_run_basis` | The tests the change needs, from the same selection `repowise impacted-tests` makes, capped at ten: a test the change edits first, then those reaching more of the changed files, then tests that run with every subset. `tests_to_run_basis` is `measured` when coverage decided a changed file, `inferred` when only the graph or a rule did, `none` when nothing named a test. `tests_to_run_why` gives the reason for each listed file (the changed file and evidence, or `runs with every subset: ...`). `tests_run_all` true means no subset can be vouched for and `tests_run_all_reasons` says why; the list is then what to run first. A failed selection carries `tests_status` and `tests_status_reason` and names nothing |+| `tests_to_run`, `tests_to_run_basis` | The tests the change needs, from the same selection `repowise impacted-tests` makes, capped at ten, in `repowise impacted-tests`' [run order](CLI_REFERENCE.md#repowise-impacted-tests-revspec). `tests_to_run_basis` is `measured` when coverage decided a changed file, `inferred` when only the graph or a rule did, `none` when nothing named a test. `tests_to_run_why` gives the reason for each listed file (the changed file and evidence, or `runs with every subset: ...`). `tests_run_all` true means no subset can be vouched for and `tests_run_all_reasons` says why; the list is then what to run first. A failed selection carries `tests_status` and `tests_status_reason` and names nothing || `tests_to_update` | Up to three test files the change will probably need edited, each `{path, reason}` with `reason` `name_pair` (named for a changed file), `imports` (its own code imports one; a conftest or setup file reaching it does not count) or `co_change` (changes with one in git history), in that order. Only tests the selection runs because of a changed file and that a runner collects. Tests to edit, not to run: a file can appear in both lists. Empty when none qualify || `missing_tests`, `files_without_measured_tests` | Changed files with no measured test. `missing_tests` is absent when coverage is unavailable or stale, since an empty list would read as no gaps || `coverage` | `{status, reason}` when there is no per-test coverage map. With a map, `coverage_analysis`, `test_analysis` and `test_inference_analysis` say whether each evidence source was available, stale, partial or degraded |@@ -260,7 +260,7 @@ Every float is rounded to 4 significant digits. Direct rows' `structural_score`**health_delta.** Both revisions are analysed from their own content, and a finding at head is reported only when the diff explains it. `scope` counts changed, eligible, analysed, skipped and failed files; `status` is `available`, `partial` or `unavailable`, and `partial` is never a clean bill. Documentation and configuration files (Markdown, JSON, YAML, TOML and the other doc or config extensions) are skipped with reason `not_code` and never make a run `partial`; a change made only of them reads `clear_in_analyzed_scope` with a headline saying health analysis does not cover them. HTML, schema and other files with no health dialect still make a run `partial`. `introduced`, `worsened` and `resolved` are totals; `top_findings` holds the three most actionable, with `findings_total`. Each finding names `dimension`, `biomarker`, `severity`, `path`, `symbol`, head-side `lines`, a `reason`, and an `attribution` (`basis` of `added_lines`, `changed_symbol`, `changed_call_edge`, `new_file`, `file_change`, `context_change` or `unknown`, with a `confidence`). Identity ignores line numbers, so moved code introduces nothing. `inspect` gives the `finding_id` call that expands one; ids are bound to the two revisions. A finding that matches a stored one carries `health_reference` for `get_health(finding_id=...)`. Performance findings carry `opportunity_id` and are ordered by opportunity rank.-**impacted_tests.** The same selection `repowise impacted-tests` makes over the whole change (every touched path, whatever the score's filters). `status` is `selected` or `run_all` (or `no_index`, `unknown`, `config_invalid`, `timeout`, `busy`, `no_source_line_changes` when nothing was selected, each with `run_all` true; `timeout` means the selection took over 30 seconds and `busy` that one for this repository is still running, and `repowise impacted-tests` gives the answer); `run_all` true means no subset can be vouched for, with up to three `reasons` (`reasons_total` counts them all). `tests_to_run` (capped at ten, `total` and `truncated`) leads with a test the change edits, then tests reaching more of the changed files, then the `always_run_total` tests that run with every subset; `why` gives each listed file's reason. With `run_all` the list is what to run first. `tests_to_run_kind` is `test_id` when a coverage node id is listed, else `test_file`. `basis` is `measured` when coverage decided a changed file, `inferred` when only the graph or a rule did, `none` when nothing named a test; `basis_by_file` names the evidence per changed file (`coverage`, `changed-test`, `call-graph`, `import-graph`, `conftest`, `full-run`, `no-tests-needed`, ...). With a coverage map, `map_present` is true and `line_coverage` buckets the scored files' changed lines, matched on the side of the diff the map was measured at (by file when it was measured at neither): `untested_changes`, `stale_test_candidates` (covered lines whose test file is absent from the diff), `covered`, `no_coverage_data`. Build the measured map with `coverage run --contexts=test` and `repowise coverage add`.+**impacted_tests.** The same selection `repowise impacted-tests` makes over the whole change (every touched path, whatever the score's filters). `status` is `selected` or `run_all` (or `no_index`, `unknown`, `config_invalid`, `timeout`, `busy`, `no_source_line_changes` when nothing was selected, each with `run_all` true; `timeout` means the selection took over 30 seconds and `busy` that one for this repository is still running, and `repowise impacted-tests` gives the answer); `run_all` true means no subset can be vouched for, with up to three `reasons` (`reasons_total` counts them all). `tests_to_run` (capped at ten, `total` and `truncated`) is in `repowise impacted-tests`' [run order](CLI_REFERENCE.md#repowise-impacted-tests-revspec), the `always_run_total` tests that run with every subset last; `why` gives each listed file's reason. With `run_all` the list is what to run first. `tests_to_run_kind` is `test_id` when a coverage node id is listed, else `test_file`. `basis` is `measured` when coverage decided a changed file, `inferred` when only the graph or a rule did, `none` when nothing named a test; `basis_by_file` names the evidence per changed file (`coverage`, `changed-test`, `call-graph`, `import-graph`, `conftest`, `full-run`, `no-tests-needed`, ...). With a coverage map, `map_present` is true and `line_coverage` buckets the scored files' changed lines, matched on the side of the diff the map was measured at (by file when it was measured at neither): `untested_changes`, `stale_test_candidates` (covered lines whose test file is absent from the diff), `covered`, `no_coverage_data`. Build the measured map with `coverage run --contexts=test` and `repowise coverage add`.**patch_coverage.** Present when the index stores coverage; the same computation and JSON shape `repowise coverage check --format json` gates on. `patch_coverage_pct` is null when no changed line is executable; files the report never names read `not_in_report`. `scope.freshness` is `stale` when coverage was measured at another commit than the change's head. `path_gates` judges the path-scoped gates in `coverage.gates`. Each file row carries `risk` (`fix_pressure`, `dependents`, `hotspot`, `bug_magnet`, `risky`, `reasons`, `basis`) and up to eight `hints` per uncovered range: `range`, `symbol`, up to three `tests` to extend, and a `basis` of `per_test` (measured), `call_graph` or `import_graph` (inferred). Without a `revspec`, it covers everything a push would bring, diffed from the merge-base with the default base branch.diff --git a/docs/start/CI.md b/docs/start/CI.mdindex 9470b7f9c..2d3b1060a 100644--- a/docs/start/CI.md+++ b/docs/start/CI.md@@ -270,6 +270,9 @@ a per-test coverage map (`repowise coverage add`) makes it more precise.- Without a range, in CI it reads the pull request's change; locally, the staged changes.- `tests.full_run_on` (gitignore patterns) adds run-everything paths, and a path it matches is never scoped; `tests.always_run` is appended to every selection as written, for the runner whose language each entry is in.- With `--runner pytest`, `go` or `jest`, the arguments hold only that runner's tests, `tests.always_run` included. A repository with tests in several languages needs one job per runner: the tests a job leaves out are counted on stderr, and listed per runner under `left_out` with `--format json`. `--runner files` gets every test.+- Selected tests come likeliest to fail first ([run order](../reference/CLI_REFERENCE.md#repowise-impacted-tests-revspec)).+ `--prioritize` prints the whole suite with the selection first, so a job can run the+ head with `-x` and the rest after; it skips nothing.- `--explain <test>` says why one test file was or was not selected: the first changed file that reached it, the evidence (coverage, call graph, import graph) and the import route from the test to that file when there is one, or the rule that runs it. With `--format json` the same answer is added as `explain`, and `selected.why` holds it for every selected test.- Ceiling: on the JVM and .NET, a same-package test linked only by an unresolved call is missed. So is a test that reaches the change through a plugin or registry loaded by a string name, a tree walk or child process done inside a shared helper it calls, or one in another language: list such tests in `tests.always_run`, and run the full suite on the default branch.diff --git a/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py b/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.pyindex 3e7711172..cda182c4a 100644--- a/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py+++ b/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py@@ -26,6 +26,7 @@ Examples:repowise impacted-tests main..HEAD --format list | xargs pytestrepowise impacted-tests main...HEAD --format args --runner pytestrepowise impacted-tests main...HEAD --explain tests/unit/test_api.py+ repowise impacted-tests main...HEAD --format args --prioritize"""from __future__ import annotations@@ -107,6 +108,13 @@ def _resolve_repo_path(path: str | None, fmt: str):"the route that reached it, or the rule that runs it. With --format json it is added ""to the report as 'explain'.",)+ "--prioritize",+ is_flag=True,+ help="With --format args, list or json: list the whole suite, the selected tests first in "+ "the order likeliest to fail, then every other test. Nothing is skipped, and a full run "+ "is ordered too, so CI can run the head with -x and then the rest.",+)def impacted_tests_command(revspec: str | None,repo: str | None,@@ -114,10 +122,13 @@ def impacted_tests_command(fmt: str,runner: str,explain: str | None,+ prioritize: bool,) -> None:"""Print the tests whose coverage intersects a change's changed lines."""if revspec and staged:raise click.ClickException("Give a revision range or --staged, not both.")+ if prioritize and fmt == "table":+ raise click.ClickException("--prioritize needs --format args, list or json.")# json/list/args go to downstream tools; keep stdout clean of log noise.if fmt != "table":@@ -125,21 +136,19 @@ def impacted_tests_command(repo_path = _resolve_repo_path(repo, fmt)try:- change, config = _read_change(repo_path, revspec, staged, fmt, bool(explain))+ change, config = _read_change(repo_path, revspec, staged, fmt, bool(explain) or prioritize)except CannotEvaluateError as exc:cannot_evaluate(fmt, exc.code, str(exc))explain = explain.replace("\\", "/").removeprefix("./") if explain else Nonecheckout = read_checkout(repo_path)plan = plan_scopes(change, config, checkout) if config is not None else None- result = run_async(_collect(repo_path, change, checkout, config, explain, plan))+ result = run_async(_collect(repo_path, change, checkout, config, explain, plan, prioritize))result["diff"] = change.label- if plan is not None:- result["selection"] = select(change, result, config, checkout, plan)if explain and fmt != "json":_render_explain(result, explain)return- _render(result, fmt, runner, explain)+ _render(result, fmt, runner, explain, prioritize)def _read_change(repo_path, revspec: str | None, staged: bool, fmt: str, explain: bool = False):@@ -163,21 +172,24 @@ def _selection_config(repo_path):raise CannotEvaluateError("config_invalid", str(exc)) from exc-async def _collect(repo_path, change, checkout, config, explain: str | None, plan) -> dict:- """Open the index and collect the change's tests (``test_collection.collect``)."""+async def _collect(+ repo_path, change, checkout, config, explain: str | None, plan, prioritize: bool = False+) -> dict:+ """Open the index, collect the change's tests (``test_collection.collect``) and decide."""from repowise.core.analysis.test_collection import collect, empty_resultfrom repowise.core.persistence.crud import get_repository+ decide = (change, checkout, config, plan, prioritize)if not (change.files or change.deleted):- return empty_result(0)+ return await _decide(None, "", empty_result(0), *decide)async with repo_index_session(Path(repo_path)) as opened:if opened is None:out = empty_result(len(change.files) + len(change.deleted))out["no_index"] = True- return out+ return await _decide(None, "", out, *decide)session, repo_id = openedrepo_row = await get_repository(session, repo_id)- return await collect(+ out = await collect(session,repo_id,repo_path,@@ -189,6 +201,26 @@ async def _collect(repo_path, change, checkout, config, explain: str | None, pladict(checkout.pytest_texts),indexed_commit=repo_row.head_commit if repo_row else None,)+ return await _decide(session, repo_id, out, *decide)+++async def _decide(session, repo_id: str, out: dict, change, checkout, config, plan, prioritize):+ """Select (when the config was read) and order the selection, inside the index session.++ ``ranked`` holds the selected tests in run order, then with *prioritize*+ every other test of the suite.+ """+ from repowise.core.analysis.test_ranking import ordered, rank_change, suite++ if plan is None:+ return out+ selection = select(change, out, config, checkout, plan)+ everything = suite(checkout.tracked, checkout.roots) if prioritize else None+ out["ranked"] = await rank_change(+ session, repo_id, change, out, selection, checkout.read, everything=everything+ )+ out["selection"] = ordered(selection, out["ranked"])+ return outdef _machine_test_ids(result: dict) -> list[str]:@@ -200,9 +232,20 @@ def _machine_test_ids(result: dict) -> list[str]:return [i for i in ids if not (i in seen or seen.add(i))]-def _render(result: dict, fmt: str, runner: str = "auto", explain: str | None = None) -> None:+def _render(+ result: dict,+ fmt: str,+ runner: str = "auto",+ explain: str | None = None,+ prioritize: bool = False,+) -> None:if fmt in ("json", "args"):- _render_selection(result, fmt, runner, explain)+ _render_selection(result, fmt, runner, explain, prioritize)+ return++ if fmt == "list" and prioritize:+ for test in _run_list(result, True).tests:+ click.echo(test)returnif fmt == "list":@@ -232,7 +275,14 @@ def _explanation(result: dict, test: str) -> dict:route = result["explain_route"] if selected_by_change(result["selection"], test) else []if len(route) > 1:lines.append("Route: " + " -> ".join(route))- return {"test": test, "selected": selected, "lines": lines, "route": route}+ out = {"test": test, "selected": selected, "lines": lines, "route": route}+ ranked = result.get("ranked") or []+ path = test.split("::", 1)[0]+ at = next((i for i, r in enumerate(ranked) if r.test in (test, path)), None)+ if at is not None:+ lines.append(f"Order: {at + 1} of {len(ranked)} ({ranked[at].reason}).")+ out["order"] = {"position": at + 1, "of": len(ranked), **ranked[at].to_dict()}+ return outdef _render_explain(result: dict, test: str) -> None:@@ -240,7 +290,32 @@ def _render_explain(result: dict, test: str) -> None:click.echo(line)-def _render_selection(result: dict, fmt: str, runner: str, explain: str | None = None) -> None:+def _run_list(result: dict, prioritize: bool):+ """The selection in run order; with *prioritize*, the whole suite with it first."""+ from repowise.core.analysis.test_ranking import ordered++ if not prioritize:+ return result["selection"]+ return ordered(result["selection"], result["ranked"], whole=True)+++def _args_header(selection, args: list[str], resolved: str, prioritize: bool) -> str:+ if prioritize:+ selected = {*selection.tests, *selection.test_files}+ head = sum(a in selected for a in args)+ lead = "Run every test" if selection.run_all else "Run the selected tests first"+ return (+ f"{lead}, in this order: {len(args)} argument(s) for {resolved}, "+ f"the {head} selected first."+ )+ if selection.run_all:+ return "Run every test:"+ return f"{len(args)} argument(s) for {resolved}."+++def _render_selection(+ result: dict, fmt: str, runner: str, explain: str | None = None, prioritize: bool = False+) -> None:"""``--format args`` (one line, reasons on stderr) or ``--format json``."""from repowise.core.analysis.test_selection import (format_args,@@ -251,16 +326,14 @@ def _render_selection(result: dict, fmt: str, runner: str, explain: str | None =)selection = result["selection"]- resolved = resolve_runner(selection, runner)- args = runner_args(selection, resolved)- notes = runner_notes(selection, resolved)+ run_list = _run_list(result, prioritize)+ resolved = resolve_runner(run_list, runner)+ args = runner_args(run_list, resolved)+ notes = runner_notes(run_list, resolved)if fmt == "args":click.echo(format_args(args))# Plain stderr, one reason per line: a CI log must not wrap or style them.- if selection.run_all:- click.echo("Run every test:", err=True)- else:- click.echo(f"{len(args)} argument(s) for {resolved}.", err=True)+ click.echo(_args_header(selection, args, resolved, prioritize), err=True)for reason in (*selection.reasons, *notes):click.echo(f" {reason}", err=True)return@@ -292,7 +365,8 @@ def _render_selection(result: dict, fmt: str, runner: str, explain: str | None ="selected": selected,"runner": resolved,"args": args,- "left_out": left_out(selection, resolved),+ "left_out": left_out(run_list, resolved),+ "order": [r.to_dict() for r in result.get("ranked") or ()],**extra,})diff --git a/packages/core/src/repowise/core/analysis/test_ranking.py b/packages/core/src/repowise/core/analysis/test_ranking.pynew file mode 100644index 000000000..01ec39fe0--- /dev/null+++ b/packages/core/src/repowise/core/analysis/test_ranking.py@@ -0,0 +1,356 @@+"""Order the tests a selection runs, the ones likeliest to fail first.++:func:`~.test_selection.select_tests` decides which tests a change needs; this+module only orders them, so a runner told to stop at the first failure reaches+a real breakage sooner. It never adds or drops a selected test. Each test is+ordered by, in turn:++1. tier: a test the change edits; one the per-test map names for a changed+ line; one it names for a changed file; one whose calls or fixtures reach a+ changed file, or that imports it directly (one hop); one reaching a changed+ file through other files; one that runs with every subset. Tests that run+ with every subset come last among the selected because nothing links them+ to this change: they are there because the graph cannot see into them, and+ a head meant to fail fast should be the tests evidence points at. With+ *everything* (:func:`rank_selection`) the unselected tests follow.+2. a failure in the last local pytest run (pytest's own last-failed cache):+ a test that just failed is the likeliest to fail again.+3. graph distance: fewer hops first, when the collection measured them.+4. co-change: the commits that touched both the test and a changed file, read+ from the partners the indexer stored per file. Both ends are read, since+ each file keeps only its strongest partners.+5. how many changed files the test reaches, then its path.++No model and no score: every key is a count a reader can check, and+:attr:`RankedTest.reason` spells them out.++Cost: one indexed query of two columns over the changed files and the ranked+test files (batched, a few thousand rows on a large repository), one small+file read for the last-failed cache, and a sort. No walk, git call or source+read.+"""++from __future__ import annotations++import json+import sys+from collections.abc import Collection, Iterable, Mapping, Sequence+from dataclasses import dataclass, replace+from typing import Any++from .test_selection import Selection, is_runnable_test, selected_by_change++#: Tiers, strongest first. ``rest`` is a test the selection left out.+TIERS = ("changed-test", "line", "file", "direct", "transitive", "every-subset", "rest")+_TIER_INDEX = {tier: i for i, tier in enumerate(TIERS)}+_TIER_WHY = {+ "changed-test": "the change edits it",+ "line": "the per-test map runs a changed line",+ "file": "the per-test map runs a changed file",+ "direct": "its calls, a fixture or a direct import reach a changed file",+ "transitive": "reaches a changed file through other files",+ "every-subset": "runs with every subset",+ "rest": "not selected",+}+# Vias where the test's own calls or fixtures reach the changed file (the call+# walk takes a few hops; still nearer than an import closure).+_DIRECT_VIAS = frozenset({"call-graph", "conftest-fixture"})++#: Where pytest records the node ids that failed in its last run. Its ids are+#: relative to pytest's rootdir, so a rootdir other than the repository root+#: matches nothing. Ceiling: a ``cache_dir`` moved in pytest's config is not+#: followed, and no other runner's results are read; a runner's own results+#: file is the upgrade.+LAST_FAILED_PATH = ".pytest_cache/v/cache/lastfailed"+++@dataclass(frozen=True)+class RankedTest:+ """One test in run order, and the counts that placed it there."""++ __test__ = False # not a pytest class, whatever its name says++ test: str+ tier: str+ hops: int | None = None+ co_change: int = 0+ failed: bool = False+ reach: int = 0++ @property+ def reason(self) -> str:+ parts = [_TIER_WHY[self.tier]]+ if self.hops is not None:+ parts.append(f"{self.hops} hop(s)")+ if self.co_change:+ parts.append(f"{self.co_change} shared change(s) with the changed files")+ if self.failed:+ parts.append("failed in the last run")+ return "; ".join(parts)++ def to_dict(self) -> dict[str, Any]:+ return {+ "test": self.test,+ "tier": self.tier,+ "hops": self.hops,+ "co_change": self.co_change,+ "failed_last_run": self.failed,+ "reason": self.reason,+ }+++def suite(tracked: Iterable[str], roots: Any = None) -> list[str]:+ """Every runnable test among *tracked*, the set the selection expands scopes to."""+ return sorted(p for p in tracked if is_runnable_test(p, roots))+++def last_failed(text: str | None) -> frozenset[str]:+ """Node ids (or files) pytest's last-failed cache names; empty when unreadable."""+ try:+ data = json.loads(text) if text else {}+ except ValueError:+ return frozenset()+ return frozenset(k for k, v in data.items() if v) if isinstance(data, dict) else frozenset()+++def co_change_counts(+ changed: Collection[str], partners: Mapping[str, Sequence[Any]]+) -> dict[str, int]:+ """``{file: shared changes with the changed files}``, summed over each changed file.++ *partners* maps a file to its :class:`~repowise.core.co_change.CoChangePartner`+ list. A pair recorded at both ends counts once. Ceiling: each file stores+ only its 25 strongest partners, so a weaker pair recorded at neither end+ counts 0.+ """+ changed = set(changed)+ pairs: dict[tuple[str, str], int] = {}+ for owner, records in partners.items():+ for p in records:+ if key := _pair(owner, p.file_path, changed):+ # No plain count on an older index: its recency-decayed weight stands in.+ pairs[key] = max(pairs.get(key, 0), p.support or round(p.weight))+ out: dict[str, int] = {}+ for (_, other), count in pairs.items():+ out[other] = out.get(other, 0) + count+ return out+++def _pair(a: str, b: str, changed: set[str]) -> tuple[str, str] | None:+ """``(changed file, other file)`` when exactly one of *a* and *b* changed."""+ if (a in changed) == (b in changed):+ return None+ return (a, b) if a in changed else (b, a)+++def _lift(best: dict[str, int], test_file: str | None, tier: str) -> None:+ if test_file:+ best[test_file] = min(best.get(test_file, len(TIERS)), _TIER_INDEX[tier])+++def _covered_tier(sources: set[str], line_matched: set[str], changed: set[str]) -> str:+ if sources & line_matched:+ return "line"+ return "file" if sources & changed else "transitive"+++def _graph_tier(row: Mapping[str, str], changed: set[str], hops: Mapping[str, int]) -> str:+ if row["source_file"] not in changed:+ return "transitive" # a route to the change, not a changed file+ if row["via"] == "changed-test":+ return "changed-test"+ if row["via"] in _DIRECT_VIAS or hops.get(row["test_file"]) == 1:+ return "direct"+ return "transitive"+++def tiers_of(+ result: Mapping[str, Any],+ selection: Selection,+ line_matched: Collection[str],+ hops: Mapping[str, int] | None = None,+) -> dict[str, str]:+ """``{selected test file: its tier}`` from the collection *result*.++ *line_matched* are the changed files the per-test map was asked by line.+ A test several changed files reach keeps its strongest tier. Ceiling: a+ file's node ids share its tier; ordering them apart needs a tier per id.+ """+ changed, by_line = set(selection.basis), set(line_matched)+ best: dict[str, int] = {}+ for info in (result.get("covered") or {}).values():+ sources = set(info.get("source_files") or ())+ _lift(best, info.get("test_file"), _covered_tier(sources, by_line, changed))+ for row in result.get("inferred") or ():+ _lift(best, row["test_file"], _graph_tier(row, changed, hops or {}))+ return {t: _tier(t, best, selection) for t in selection.test_files}+++def _tier(test: str, best: Mapping[str, int], selection: Selection) -> str:+ """*test*'s strongest evidence; with none, whether a changed file or a rule put it in."""+ if test in best:+ return TIERS[best[test]]+ return "transitive" if selected_by_change(selection, test) else "every-subset"+++def _reach(result: Mapping[str, Any], changed: Collection[str]) -> dict[str, int]:+ """``{test file: changed files it reaches}``."""+ seen: dict[str, set[str]] = {}+ for row in result.get("inferred") or ():+ seen.setdefault(row["test_file"], set()).add(row["source_file"])+ for info in (result.get("covered") or {}).values():+ if info.get("test_file"):+ seen.setdefault(info["test_file"], set()).update(info.get("source_files") or ())+ changed = set(changed)+ return {t: len(s & changed) for t, s in seen.items()}+++def rank(+ tests: Iterable[str],+ tiers: Mapping[str, str],+ *,+ hops: Mapping[str, int] | None = None,+ co_change: Mapping[str, int] | None = None,+ failed: Collection[str] = frozenset(),+ reach: Mapping[str, int] | None = None,+) -> list[RankedTest]:+ """*tests* (files or node ids) in run order; a file *tiers* lacks is ``rest``."""+ hops, co_change, reach = hops or {}, co_change or {}, reach or {}+ failed_files = {f.split("::", 1)[0] for f in failed}+ ranked = []+ for test in dict.fromkeys(tests):+ path = test.split("::", 1)[0]+ ranked.append(+ RankedTest(+ test=test,+ tier=tiers.get(path, "rest"),+ hops=hops.get(path),+ co_change=co_change.get(path, 0),+ # A node id fails only on its own; another test in its file says nothing.+ failed=test in failed or ("::" not in test and path in failed_files),+ reach=reach.get(path, 0),+ )+ )++ def key(r: RankedTest) -> tuple:+ far = r.hops if r.hops is not None else sys.maxsize+ return _TIER_INDEX[r.tier], not r.failed, far, -r.co_change, -r.reach, r.test++ return sorted(ranked, key=key)+++@dataclass(frozen=True)+class Signals:+ """History behind the order: co-change counts per file and last-run failures."""++ co_change: Mapping[str, int]+ failed: frozenset[str] = frozenset()+++def rank_selection(+ result: Mapping[str, Any],+ selection: Selection,+ line_matched: Collection[str],+ signals: Signals,+ *,+ hops: Mapping[str, int] | None = None,+ everything: Sequence[str] | None = None,+) -> list[RankedTest]:+ """``selection.tests`` in run order, then, given *everything* (the suite), the rest.++ In a whole-suite order a file the selection runs only some node ids of is+ run whole at its first id's place: pytest given ``a.py::t1 a.py`` runs t1+ twice, and the file's other ids are not known here.+ """+ tiers = tiers_of(result, selection, line_matched, hops)+ common = {+ "hops": hops,+ "co_change": signals.co_change,+ "failed": signals.failed,+ "reach": _reach(result, selection.basis),+ }+ ranked = rank(selection.tests, tiers, **common)+ if everything is None:+ return ranked+ head: dict[str, RankedTest] = {}+ for r in ranked:+ path = r.test.split("::", 1)[0]+ head.setdefault(path, replace(r, test=path))+ rest = rank([t for t in everything if t not in head], {}, **common)+ return [*head.values(), *rest]+++def ordered(+ selection: Selection, ranked: Sequence[RankedTest], *, whole: bool = False+) -> Selection:+ """*selection* with its tests in *ranked* order; with *whole*, every ranked test.++ A whole-suite order is a subset of nothing: ``run_all`` turns false so a+ runner gets the list, and the reasons still say why every test runs.+ """+ tests = tuple(r.test for r in ranked)+ if not whole:+ # A node id a whole-suite order folded into its file sorts at the file's place.+ at: dict[str, int] = {}+ for i, test in enumerate(tests):+ at.setdefault(test, i)+ last = len(at)+ tests = tuple(+ sorted(selection.tests, key=lambda t: at.get(t, at.get(t.split("::", 1)[0], last)))+ )+ # Every selected file has an entry in ``tests``, so this keeps them all.+ files = tuple(dict.fromkeys(t.split("::", 1)[0] for t in tests))+ run_all = False if whole else selection.run_all+ return replace(selection, run_all=run_all, tests=tests, test_files=files)+++async def read_signals(+ session: Any, repo_id: str, changed: Collection[str], tests: Iterable[str], read: Any+) -> Signals:+ """Co-change counts between *changed* and *tests*, and the last run's failures.++ *read* returns a repository file's text or ``None`` (a checkout's reader);+ a server without the working tree gets no failures, never an error.+ """+ from ..persistence.crud import get_co_change_partners++ files = {t.split("::", 1)[0] for t in tests}+ partners = await get_co_change_partners(session, repo_id, sorted({*changed, *files}))+ return Signals(co_change_counts(changed, partners), last_failed(read(LAST_FAILED_PATH)))+++# The collection's fewest hops from each reached test file to the change, once+# it records them; absent, distance does not order and tiers decide.+_HOPS_KEY = "test_hops"+++async def rank_change(+ session: Any,+ repo_id: str,+ change: Any,+ result: Mapping[str, Any],+ selection: Selection,+ read: Any,+ *,+ everything: Sequence[str] | None = None,+) -> list[RankedTest]:+ """:func:`rank_selection` for *change*, with its signals read; no *session* reads none.++ *result* is :func:`~.test_collection.collect`'s, *read* a checkout's reader.+ """+ from .test_collection import query_lines++ lines = query_lines(change, result.get("measured_commit"))+ tests = [*selection.tests, *(everything or ())]+ if session is None:+ signals = Signals({}, last_failed(read(LAST_FAILED_PATH)))+ else:+ signals = await read_signals(session, repo_id, selection.basis, tests, read)+ return rank_selection(+ result,+ selection,+ {p for p, touched in lines.items() if touched},+ signals,+ hops=result.get(_HOPS_KEY),+ everything=everything,+ )diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.pyindex 67db3d2ab..eab9fb2b2 100644--- a/packages/core/src/repowise/core/persistence/crud/git.py+++ b/packages/core/src/repowise/core/persistence/crud/git.py@@ -14,6 +14,7 @@ from sqlalchemy import ColumnElement, and_, delete, func, or_, select, textfrom sqlalchemy.engine import Connectionfrom sqlalchemy.ext.asyncio import AsyncSession+from ...co_change import CoChangePartner, parse_partnersfrom ..models import (FixEvent,GitCommit,@@ -118,6 +119,25 @@ async def get_git_metadata_bulk(return out+async def get_co_change_partners(+ session: AsyncSession, repository_id: str, file_paths: Sequence[str]+) -> dict[str, list[CoChangePartner]]:+ """``{file: its stored co-change partners}`` for *file_paths*, reading only that column."""+ out: dict[str, list[CoChangePartner]] = {}+ unique_paths = list(dict.fromkeys(file_paths))+ for i in range(0, len(unique_paths), _BATCH_SIZE):+ result = await session.execute(+ select(GitMetadata.file_path, GitMetadata.co_change_partners_json).where(+ GitMetadata.repository_id == repository_id,+ GitMetadata.file_path.in_(unique_paths[i : i + _BATCH_SIZE]),+ )+ )+ for file_path, raw in result.all():+ if partners := parse_partners(raw):+ out[file_path] = partners+ return out++async def get_all_git_metadata(session: AsyncSession, repository_id: str) -> dict[str, GitMetadata]:"""Return all GitMetadata rows for a repository."""result = await session.execute(diff --git a/packages/server/src/repowise/server/mcp_server/_test_selection.py b/packages/server/src/repowise/server/mcp_server/_test_selection.pyindex b93451ae9..fa0badd1b 100644--- a/packages/server/src/repowise/server/mcp_server/_test_selection.py+++ b/packages/server/src/repowise/server/mcp_server/_test_selection.py@@ -3,7 +3,8 @@``get_change_risk`` and ``get_risk`` ask the same question ``repowiseimpacted-tests`` answers, so they run the same collection and the samefail-closed :func:`~repowise.core.analysis.test_selection.select_tests`-(:mod:`repowise.core.analysis.test_collection`) and only shape the answer:+(:mod:`repowise.core.analysis.test_collection`) and the same order+(:mod:`repowise.core.analysis.test_ranking`), and only shape the answer:whether every test must run and why, the head of the run list with the reasoneach test is in it, and which evidence decided each changed file."""@@ -50,7 +51,7 @@ class SelectionUnavailableError(Exception):async def select_change_tests(repo_path: Any, session_factory: Any, change: Any) -> tuple[dict[str, Any], Selection, Any]:- """``(collection result, selection, checkout)`` for *change*, or+ """``(collection result, selection in run order, checkout)`` for *change*, or:class:`SelectionUnavailableError`.The checkout read (``git ls-files`` plus pytest's conftests and configs)@@ -100,6 +101,7 @@ async def _select(repo_path: Any, session_factory: Any, change: Any, config: Any, cancel: threading.Event) -> tuple:from repowise.core.analysis.test_collection import read_checkout, select_for_change+ from repowise.core.analysis.test_ranking import ordered, rank_changefrom repowise.core.persistence.database import get_sessionfrom repowise.server.mcp_server._helpers import _get_repo@@ -116,7 +118,10 @@ async def _select(indexed_commit=repository.head_commit,cancelled=cancel.is_set,)- return result, selection, checkout+ ranked = await rank_change(+ session, repository.id, change, result, selection, checkout.read+ )+ return result, ordered(selection, ranked), checkoutdef files_change(repo_path: Any, paths: list[str]) -> Any:@@ -140,30 +145,6 @@ def files_change(repo_path: Any, paths: list[str]) -> Any:)-def run_order(result: dict[str, Any], selection: Selection) -> list[str]:- """``selection.tests`` ordered for a reader who runs the head first.-- A test the change edits leads, then tests reaching more of the changed- files, then the selection's own order; tests that run with every subset- come last, since no changed file named them.- """- changed = set(selection.basis)- reach: dict[str, set[str]] = {}- for row in result.get("inferred") or ():- reach.setdefault(row["test_file"], set()).add(row["source_file"])- for info in (result.get("covered") or {}).values():- if info.get("test_file"):- reach.setdefault(info["test_file"], set()).update(info.get("source_files") or ())-- def key(item: tuple[int, str]) -> tuple[bool, bool, int, int]:- index, test = item- path = test.split("::", 1)[0]- hits = len(reach.get(path, set()) & changed)- return path not in changed, not selected_by_change(selection, path), -hits, index-- return [test for _, test in sorted(enumerate(selection.tests), key=key)]--def run_kind(tests: list[str]) -> str | None:"""``test_id`` when a coverage node id is listed, ``test_file`` otherwise, ``None`` empty."""if not tests:@@ -193,12 +174,12 @@ def selection_block(test (documentation, a deleted test); with ``run_all`` true it means nothingnarrower than the full suite is known."""- ordered = run_order(result, selection)- shown = ordered[:limit]- if len(ordered) > limit:+ run_list = list(selection.tests) # in run order (``test_ranking``)+ shown = run_list[:limit]+ if len(run_list) > limit:collector.add(- f"{label}.tests_to_run beyond cap={limit} ({len(ordered) - limit} dropped)",- ordered[limit:],+ f"{label}.tests_to_run beyond cap={limit} ({len(run_list) - limit} dropped)",+ run_list[limit:],)reasons = list(selection.reasons)if len(reasons) > _REASONS_LIMIT:@@ -218,8 +199,8 @@ def selection_block("map_present": not result.get("map_empty", True),"tests_to_run": shown,"tests_to_run_kind": run_kind(shown),- "total": len(ordered),- "truncated": len(ordered) > limit,+ "total": len(run_list),+ "truncated": len(run_list) > limit,"always_run_total": always,"why": {path: selection.why[path]@@ -227,7 +208,7 @@ def selection_block(if path in selection.why},"basis_by_file": dict(basis_rows[:_BASIS_LIMIT]),- "summary": _summary(selection, len(ordered), always, limit),+ "summary": _summary(selection, len(run_list), always, limit),}if len(basis_rows) > _BASIS_LIMIT:block["basis_by_file_total"] = len(basis_rows)diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.pyindex 2c043b1ca..e7cbe87b8 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py@@ -35,7 +35,6 @@ from repowise.server.mcp_server._test_selection import (UNAVAILABLE_REASON,basis_of,run_kind,- run_order,)@@ -587,7 +586,7 @@ def _tests_to_run("tests_status": tests.status,"tests_status_reason": tests.message,}- population = run_order(tests.result, selection)+ population = list(selection.tests) # in run order (``test_ranking``)reasons = list(selection.reasons)if len(reasons) > _RUN_ALL_REASONS_LIMIT:collector.add(diff --git a/tests/unit/analysis/test_test_ranking.py b/tests/unit/analysis/test_test_ranking.pynew file mode 100644index 000000000..bc5e4848b--- /dev/null+++ b/tests/unit/analysis/test_test_ranking.py@@ -0,0 +1,161 @@+"""The order inside a selection: tier, distance, co-change, last failure, path."""++from __future__ import annotations++from repowise.core.analysis.test_ranking import (+ Signals,+ co_change_counts,+ last_failed,+ ordered,+ rank,+ rank_selection,+ tiers_of,+)+from repowise.core.analysis.test_selection import Selection+from repowise.core.co_change import CoChangePartner+++def _selection(tests: list[str], why: dict[str, str], changed: list[str]) -> Selection:+ files = list(dict.fromkeys(t.split("::", 1)[0] for t in tests))+ return Selection(+ run_all=False,+ reasons=(),+ tests=tuple(tests),+ test_files=tuple(files),+ basis=dict.fromkeys(changed, "import-graph"),+ why=why,+ )+++def _row(source: str, test: str, via: str) -> dict:+ return {"source_file": source, "test_file": test, "via": via}+++def test_tiers_follow_the_strength_of_the_evidence() -> None:+ result = {+ "covered": {+ f"tests/test_{kind}.py::t|run": {+ "test_file": f"tests/test_{kind}.py",+ "source_files": [source],+ }+ for kind, source in (("line", "a.py"), ("file", "b.py"))+ },+ "inferred": [+ _row("tests/test_edit.py", "tests/test_edit.py", "changed-test"),+ _row("a.py", "tests/test_call.py", "call-graph"),+ _row("a.py", "tests/test_far.py", "import-graph"),+ _row("route.py", "tests/test_route.py", "call-graph"),+ ],+ }+ tests = [+ "tests/test_line.py::t",+ "tests/test_file.py::t",+ "tests/test_edit.py",+ "tests/test_call.py",+ "tests/test_far.py",+ "tests/test_route.py",+ "tests/test_walker.py",+ ]+ why = {t.split("::")[0]: "a.py changed" for t in tests}+ why["tests/test_walker.py"] = "runs with every subset: it walks the tree"+ selection = _selection(tests, why, ["a.py", "b.py", "tests/test_edit.py"])+ tiers = tiers_of(result, selection, line_matched={"a.py"})+ assert tiers == {+ "tests/test_line.py": "line",+ "tests/test_file.py": "file",+ "tests/test_edit.py": "changed-test",+ "tests/test_call.py": "direct",+ "tests/test_far.py": "transitive",+ "tests/test_route.py": "transitive",+ "tests/test_walker.py": "every-subset",+ }+ # One import hop, once the collection measures it, is a direct edge.+ assert tiers_of(result, selection, {"a.py"}, hops={"tests/test_far.py": 1})[+ "tests/test_far.py"+ ] == "direct"+ run = [r.test for r in rank_selection(result, selection, {"a.py"}, Signals({}))]+ assert run == [+ "tests/test_edit.py",+ "tests/test_line.py::t",+ "tests/test_file.py::t",+ "tests/test_call.py",+ "tests/test_far.py",+ "tests/test_route.py",+ "tests/test_walker.py",+ ]+++def test_within_a_tier_failure_then_hops_then_co_change_then_path() -> None:+ tiers = dict.fromkeys(["t/a.py", "t/b.py", "t/c.py", "t/d.py", "t/e.py"], "transitive")+ ranked = rank(+ ["t/e.py", "t/d.py", "t/c.py", "t/b.py", "t/a.py"],+ tiers,+ hops={"t/e.py": 1, "t/d.py": 2, "t/c.py": 2, "t/b.py": 2, "t/a.py": 2},+ co_change={"t/d.py": 3},+ failed={"t/c.py::test_x"},+ )+ # The last run's failure leads its tier, even two hops out.+ assert [r.test for r in ranked] == ["t/c.py", "t/e.py", "t/d.py", "t/a.py", "t/b.py"]+ assert ranked[2].reason == (+ "reaches a changed file through other files; 2 hop(s); "+ "3 shared change(s) with the changed files"+ )+ assert ranked[0].failed and ranked[0].reason.endswith("failed in the last run")+ # A node id fails only on its own record, a whole file on any of its ids.+ ids = ["t/c.py::test_y", "t/c.py::test_x", "t/c.py"]+ by_test = {r.test: r.failed for r in rank(ids, tiers, failed={"t/c.py::test_x"})}+ assert by_test == {"t/c.py::test_y": False, "t/c.py::test_x": True, "t/c.py": True}+ # Without hops, distance does not order; the rest of the keys still do.+ assert [r.test for r in rank(["t/b.py", "t/a.py"], tiers)] == ["t/a.py", "t/b.py"]+++def test_co_change_counts_each_pair_once_from_either_end() -> None:+ partners = {+ "src/a.py": [CoChangePartner("tests/test_a.py", 2.5, support=3)],+ "tests/test_a.py": [CoChangePartner("src/a.py", 2.5, support=3)],+ "tests/test_b.py": [+ CoChangePartner("src/a.py", 1.0, support=2),+ CoChangePartner("src/b.py", 1.0, support=1),+ ],+ # An index from before the plain count: the weight stands in.+ "tests/test_old.py": [CoChangePartner("src/a.py", 1.6)],+ }+ assert co_change_counts(["src/a.py", "src/b.py"], partners) == {+ "tests/test_a.py": 3,+ "tests/test_b.py": 3,+ "tests/test_old.py": 2,+ }+++def test_last_failed_reads_pytests_cache_and_tolerates_junk() -> None:+ text = '{"tests/test_a.py::test_x": true, "tests/test_b.py": true, "gone": false}'+ assert last_failed(text) == {"tests/test_a.py::test_x", "tests/test_b.py"}+ assert last_failed(None) == frozenset()+ assert last_failed("not json") == frozenset()+ assert last_failed("[1, 2]") == frozenset()+++def test_a_whole_suite_order_keeps_every_test_and_partly_selected_files() -> None:+ selection = _selection(+ ["tests/test_a.py::test_one", "tests/test_b.py"],+ {"tests/test_a.py": "a.py changed", "tests/test_b.py": "a.py changed"},+ ["a.py"],+ )+ result = {"inferred": [_row("a.py", "tests/test_b.py", "call-graph")]}+ suite = ["tests/test_a.py", "tests/test_b.py", "tests/test_c.py", "tests/test_d.py"]+ ranked = rank_selection(+ result, selection, set(), Signals({"tests/test_d.py": 1}), everything=suite+ )+ # pytest given ``a.py::t1 a.py`` runs t1 twice, so the partly selected file+ # runs whole at its node id's place and not again in the tail.+ assert [r.test for r in ranked] == [+ "tests/test_b.py",+ "tests/test_a.py",+ "tests/test_d.py",+ "tests/test_c.py",+ ]+ whole = ordered(selection, ranked, whole=True)+ assert not whole.run_all and whole.tests == tuple(r.test for r in ranked)+ subset = ordered(selection, ranked)+ assert subset.tests == ("tests/test_b.py", "tests/test_a.py::test_one")+ assert subset.test_files == ("tests/test_b.py", "tests/test_a.py")diff --git a/tests/unit/cli/test_impacted_tests_cmd.py b/tests/unit/cli/test_impacted_tests_cmd.pyindex 537f0c7e5..d183e3273 100644--- a/tests/unit/cli/test_impacted_tests_cmd.py+++ b/tests/unit/cli/test_impacted_tests_cmd.py@@ -432,6 +432,7 @@ def test_explain_names_the_changed_file_and_the_route(repo) -> None:assert result.stdout.splitlines() == ["Selected: src/a.py changed (import-graph).","Route: tests/test_a.py -> src/a.py",+ "Order: 1 of 1 (reaches a changed file through other files).",]missed = _run(repo, "main...feat", "--explain", "./tests/test_b.py")assert missed.stdout.startswith("Not selected: no changed file reaches it")@@ -443,8 +444,22 @@ def test_explain_joins_the_json_report(repo) -> None:assert data["explain"] == {"test": "tests/test_a.py","selected": True,- "lines": ["Selected: src/a.py changed (import-graph).", "Route: tests/test_a.py -> src/a.py"],+ "lines": [+ "Selected: src/a.py changed (import-graph).",+ "Route: tests/test_a.py -> src/a.py",+ "Order: 1 of 1 (reaches a changed file through other files).",+ ],"route": ["tests/test_a.py", "src/a.py"],+ "order": {+ "position": 1,+ "of": 1,+ "test": "tests/test_a.py",+ "tier": "transitive",+ "hops": None,+ "co_change": 0,+ "failed_last_run": False,+ "reason": "reaches a changed file through other files",+ },}assert data["selected"]["why"] == {"tests/test_a.py": "src/a.py changed (import-graph)"}@@ -461,3 +476,77 @@ def test_a_runner_is_told_of_always_run_tests_for_another(repo) -> None:assert data["left_out"] == {"jest": ["web/app.test.ts"]}files = _run(repo, "main...feat", "--format", "args", "--runner", "files")assert files.stdout == "tests/test_a.py web/app.test.ts\n"+++def _co_change(repo, path: str, partners: dict[str, int]) -> None:+ """Store *partners* as *path*'s co-change record, each with that many shared commits."""+ from repowise.core.persistence.models import GitMetadata++ async def add() -> None:+ db = (repo / ".repowise" / "wiki.db").as_posix()+ engine = create_async_engine(f"sqlite+aiosqlite:///{db}")+ records = [+ {"file_path": p, "co_change_count": float(n), "frequency": n}+ for p, n in partners.items()+ ]+ async with async_sessionmaker(engine, expire_on_commit=False)() as session:+ session.add(+ GitMetadata(+ repository_id="r1", file_path=path, co_change_partners_json=json.dumps(records)+ )+ )+ await session.commit()+ await engine.dispose()++ asyncio.run(add())+++def test_prioritize_lists_the_whole_suite_selected_first(repo) -> None:+ _add_test(repo, "tests/test_b.py", "src/b.py")+ _add_test(repo, "tests/test_c.py", "src/b.py")+ _co_change(repo, "src/a.py", {"tests/test_c.py": 4})+ result = _run(repo, "main...feat", "--format", "args", "--runner", "pytest", "--prioritize")+ assert result.exit_code == 0, result.output+ # The selected test leads; of the rest, the one history pairs with src/a.py.+ assert result.stdout == "tests/test_a.py tests/test_c.py tests/test_b.py\n"+ assert "the 1 selected first" in _err(result)+ listed = _run(repo, "main...feat", "--format", "list", "--prioritize")+ assert listed.stdout.splitlines() == ["tests/test_a.py", "tests/test_c.py", "tests/test_b.py"]+ data = json.loads(_run(repo, "main...feat", "--format", "json", "--prioritize").stdout)+ assert data["run_all"] is False and data["selected"]["tests"] == ["tests/test_a.py"]+ assert [(o["test"], o["tier"], o["co_change"]) for o in data["order"]] == [+ ("tests/test_a.py", "transitive", 0),+ ("tests/test_c.py", "rest", 4),+ ("tests/test_b.py", "rest", 0),+ ]+++def test_prioritize_still_orders_a_full_run(repo) -> None:+ _write(repo, {"Makefile": "all:\n"})+ _git(repo, "add", "-A")+ _git(repo, "commit", "-qm", "build")+ result = _run(repo, "main...feat", "--format", "args", "--runner", "pytest", "--prioritize")+ assert result.stdout == "tests/test_a.py\n"+ assert _err(result).startswith("Run every test, in this order:")+ assert "Makefile changed" in _err(result)+++def test_selected_tests_run_in_order_and_a_last_failure_breaks_a_tie(repo) -> None:+ _add_test(repo, "tests/test_z.py", "src/a.py")+ plain = _run(repo, "main...feat", "--format", "args", "--runner", "pytest")+ assert plain.stdout == "tests/test_a.py tests/test_z.py\n"+ cache = repo / ".pytest_cache" / "v" / "cache"+ cache.mkdir(parents=True)+ (cache / "lastfailed").write_text('{"tests/test_z.py::test_x": true}', encoding="utf-8")+ result = _run(repo, "main...feat", "--format", "args", "--runner", "pytest")+ assert result.stdout == "tests/test_z.py tests/test_a.py\n"+ explained = _run(repo, "main...feat", "--explain", "tests/test_z.py")+ assert explained.stdout.splitlines()[-1] == (+ "Order: 1 of 2 (reaches a changed file through other files; failed in the last run)."+ )+++def test_prioritize_needs_a_machine_format(repo) -> None:+ result = _run(repo, "main...feat", "--prioritize")+ assert result.exit_code != 0+ assert "--prioritize needs --format args, list or json" in result.output + result.stderrdiff --git a/tests/unit/server/mcp/test_change_test_selection.py b/tests/unit/server/mcp/test_change_test_selection.pyindex d88d3a168..9aa246551 100644--- a/tests/unit/server/mcp/test_change_test_selection.py+++ b/tests/unit/server/mcp/test_change_test_selection.py@@ -414,3 +414,40 @@ async def test_workspace_get_risk_selects_in_the_member_repository(tmp_path, mon# test_walks.py is tracked there but not indexed, so it runs with every subset.assert directive["tests_to_run"] == ["tests/test_status.py", "tests/test_walks.py"]assert directive["tests_run_all"] is False+++async def test_both_tools_list_tests_in_the_selections_run_order(tmp_path, monkeypatch) -> None:+ import json++ from repowise.core.persistence.models import GitMetadata++ repo, base = _repo(tmp_path, {**_STATUS, "tests/test_z.py": "from src.status import status\n"})+ _commit(repo, {"src/status.py": "def status():\n return 2\n"}, "fix: status")+ factory = await _index(+ base,+ {"src/status.py": False, "tests/test_status.py": True, "tests/test_z.py": True},+ [+ ("tests/test_status.py", "src/status.py", "imports"),+ ("tests/test_z.py", "src/status.py", "imports"),+ ],+ )+ # History pairs tests/test_z.py with the changed file, so it leads its tier.+ partners = [{"file_path": "tests/test_z.py", "co_change_count": 3.0, "frequency": 3}]+ async with factory() as s:+ s.add(+ GitMetadata(+ repository_id="repo1",+ file_path="src/status.py",+ co_change_partners_json=json.dumps(partners),+ )+ )+ await s.commit()++ it = (await _change_risk(monkeypatch, repo, factory))["impacted_tests"]+ directive = await _risk_directive(monkeypatch, repo, factory, ["src/status.py"])++ # tests/test_walks.py imports nothing indexed, so it runs with every subset, last.+ order = ["tests/test_z.py", "tests/test_status.py", "tests/test_walks.py"]+ assert it["tests_to_run"] == order and list(it["why"]) == order+ assert directive["tests_to_run"] == order