Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(impacted-tests): narrow conftest import-only routes and count the broadcast apart (#4324)
Raghav Chamadiya2252790f2324
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 1d5dd430d..62e550428 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1122,7 +1122,10 @@ per-file `selected.basis`: `full-run`, `no-tests-needed`, `test-tree`,`test-package`, `conftest`, `helper-importers`, `deleted-test`, `coverage`,`changed-test`, `call-graph`, `import-graph`, `filename-pattern`, `unknown`,or `none` (no index), and a per-test `selected.why`: the first changed file and-evidence that selected it, or why it runs with every subset. When it runs everything:+evidence that selected it, or why it runs with every subset. `selected.broadcast`+maps each selected test file that runs only because a conftest or test-package+`__init__.py` on a route keeps every test under it to that file; agent views+count these apart from the tests the change reaches. 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 faildiff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex 1dc86095f..44c62c8f7 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -247,7 +247,7 @@ Opt-in blocks: `changes` adds `recent_changes` (and `recent_changes_total`), sha|-------|---------|| `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, 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_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. `tests_broadcast_total` counts the tests that run only because a conftest on a route keeps every test under it; they are left out of the list and its total. 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 |@@ -286,7 +286,7 @@ Every float is rounded to 4 significant digits. Direct rows' `structural_score``files` lists up to 10 analysed files, largest structure move first, each with `base_score`, `head_score`, `nloc_base` and `nloc_head`; a side the file is missing on reads null. `files_total` counts them all. `include=["diagnostics"]` adds `base_structure` and `head_structure` (the structure deduction). `score_basis` is `structure_only`: each score is 10 minus the structure deduction, the reading `get_health(counts="code_shape")` gives, from two passes that read no git history or coverage. A deleted file has a base-only row, with `moved_to` naming where its code went when it was split. `score_change` averages files scored on both sides, weighted by base nloc so a file that grows while improving keeps its gain: `base`, `head`, `delta` (two decimals), `structure_delta` (the deduction change, which still moves when a file sits on the 1.0 floor) and `files_compared`.-**impacted_tests.** The selection `repowise impacted-tests` makes, over every path the change touched whatever the score's filters, less the repowise output the score also leaves out (the index, and a managed file whose only change is repowise's block or entry), which the CLI still reads when tracked. `status` is `selected`, `run_all` or `degraded` (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). `degraded` means the index predates files changed outside the change and the selection holds over half the test files; the list stands, `summary` says so, and the directive asks for every test. `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. When most of the suite is to run anyway, the list's tail is not stored for recovery. 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. `include=["tests"]` adds `why` (each listed file's reason) and `basis_by_file`, 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 `pytest --cov=<package> --cov-context=test` (needs pytest-cov) and `repowise coverage add`.+**impacted_tests.** The selection `repowise impacted-tests` makes, over every path the change touched whatever the score's filters, less the repowise output the score also leaves out (the index, and a managed file whose only change is repowise's block or entry), which the CLI still reads when tracked. `status` is `selected`, `run_all` or `degraded` (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). `degraded` means the index predates files changed outside the change and the selection holds over half the test files; the list stands, `summary` says so, and the directive asks for every test. `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. `broadcast_total` counts the tests that run only because a conftest on a route keeps every test under it; they are left out of `tests_to_run` and `total`. When most of the suite is to run anyway, the list's tail is not stored for recovery. 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. `include=["tests"]` adds `why` (each listed file's reason) and `basis_by_file`, 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 `pytest --cov=<package> --cov-context=test` (needs pytest-cov) and `repowise coverage add`.**patch_coverage.** Present when the index stores coverage. With a gate set and coverage measured at the change's head, it is the same computation and JSON shape `repowise coverage check --format json` gates on. Otherwise it reads `status` (`measured` or `not_measured`), `freshness` and the nonzero `file_counts`, plus the totals and `files` when a changed file was measured; `include=["diagnostics"]` keeps the full shape. `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; then a file git shows changed since that commit reads `stale_file`, with no figures, and only untouched files keep theirs. `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 7fd671e83..643ebc721 100644--- a/docs/start/CI.md+++ b/docs/start/CI.md@@ -281,8 +281,9 @@ a per-test coverage map (`repowise coverage add`) makes it more precise.- Tests the graph cannot see into run with every subset, and the reasons say how many and why: a test not indexed or importing nothing it resolves; a Python, JavaScript or TypeScript test that lists and reads files under a source directory (the working directory, a module's location, or its own location climbed out of the test directory; never its fixtures, sibling data or a temporary directory); one that runs the project's own command, `python -m` module, code importing the project, or package `bin` in a child process; a Java or Kotlin `@SpringBootTest`, which loads the whole application context (a slice such as `@WebMvcTest` is selected through its imports). A test that inherits `@SpringBootTest` from a base class or carries it through a custom meta-annotation is not detected and is selected through its imports only. The indexer finds them once from each test's source and stores the reason, so selection reads it without opening test files. An index built before this check runs everything until `repowise update` checks its tests. A Python module named like a test but outside every test directory is not a test when the nearest pytest config's `testpaths` or `python_files` leaves it out, as a bare `pytest` does: it is selected through like any other code. The rule follows a bare `pytest` run, so a test that CI only names explicitly on the command line outside `testpaths` is not seen as one: list it in `tests.always_run`. Inside a JavaScript or TypeScript `src` tree a `tests/` folder is not a test directory, since it often holds a product feature: a file there is a test when its name says so (`.test.`, `.spec.`) or a test directory such as `__tests__/` holds it.- A changed `conftest.py`, test package `__init__.py` or imported test helper selects the tests under or importing it, not everything.- A change that reaches a `conftest.py` only through its imports selects the tests that ask for a fixture using that change (directly, through other fixtures, `usefixtures` or `getfixturevalue`), plus one test under the conftest as an import check.- - Every test under the conftest still runs when an autouse fixture, a `pytest_*` hook or module-level code uses the change, or when the conftest imports it only for side effects.- - Reading a literal constant of an imported module, or calling one of its functions that uses nothing the module imports beyond standard modules that cannot load code by name (emptying a `functools` cache or a standard container counts), reaches only a change in that module itself. Ceiling: such a function that reads or runs repo files by path (`open`, `Path.read_text`, `os.system`) is judged by its imports only.+ - Every test under the conftest still runs when an autouse fixture, a `pytest_*` hook or module-level code uses the change, or when the conftest imports it only for side effects. The tests it adds that nothing else reaches are listed in `selected.broadcast` and counted apart in the summary.+ - Patching an attribute of an imported module or of a class in it (`monkeypatch.setattr(mod.Cls, "name", ...)`) in an autouse fixture is left to the import check.+ - Reading a literal constant of an imported module, or calling one of its functions that uses nothing the module imports beyond standard modules that cannot load code by name (emptying a `functools` cache or a standard container counts), reaches only a change in that module itself. A module re-exporting such a name (`from .console import NAMES as NAMES`) passes this through to the module defining it. Ceiling: such a function that reads or runs repo files by path (`open`, `Path.read_text`, `os.system`) is judged by its imports only.- It also runs everything there when a fixture request cannot be read from the code (a computed name, a mark kept in a variable, a config `usefixtures`), when the conftest loads plugins or cannot be read, and on an index built before this was recorded. The reasons name the cause.- Ceiling: a change that only alters what the changed module does at import time, seen by a test that does not import it, is caught by the import check alone.- Wiring no import states counts as a use: a JS/TS setup file named under `setupFiles`, `setupFilesAfterEnv`, `globalSetup` or `globalTeardown` in a `vitest.*`, `jest.*`, `vite.*` or `playwright.*` config or a `package.json` stands for the tests in that config's package, and a helper a test names by a path relative to itself (`Path(__file__).parent / "server.py"`, `path.join(__dirname, "server.ts")`) stands for that test. A `conftest.py` links only the files pytest collects (its `python_files`), so a helper beside the tests is not on every route the conftest reaches.diff --git a/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py b/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.pyindex 6345ffa7c..dfa95e93f 100644--- a/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py+++ b/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py@@ -312,6 +312,11 @@ def _args_header(selection, args: list[str], resolved: str, prioritize: bool) ->)if selection.run_all:return "Run every test:"+ if spread := len(selection.broadcast):+ return (+ f"{len(args)} argument(s) for {resolved}; {spread} selected test file(s) run "+ "only because a conftest on a route keeps every test under it."+ )return f"{len(args)} argument(s) for {resolved}."diff --git a/packages/core/src/repowise/core/analysis/conftest_routes.py b/packages/core/src/repowise/core/analysis/conftest_routes.pyindex 30aad005a..517608496 100644--- a/packages/core/src/repowise/core/analysis/conftest_routes.py+++ b/packages/core/src/repowise/core/analysis/conftest_routes.py@@ -18,7 +18,8 @@ through its imports can break a test through either:working fails there as well.2. **What the conftest does with the module.** A fixture, a hook ormodule-level code that names something from a module on the route, in any- way but as the ``setattr`` target in an autouse fixture or hook,+ way but as the ``setattr`` target (the module or an attribute of it) in an+ autouse fixture or hook,can change what a test sees: calling it, reading a constant, comparing,iterating or formatting it all do. An autouse fixture, a ``pytest_*`` hook,module-level code (class bodies included) and a fixture or hook defined in@@ -33,7 +34,9 @@ change is. One exception: reading a literal constant of a module on the route,or calling a function of it that uses nothing the module imports beyond standardmodules that cannot load code by name (:func:`local_names`), depends on thatmodule's text alone, so it reaches a change only in that module, not one in a-module it merely imports. A binding the conftest never reads (``import+module it merely imports. The same holds for such a name a module on the route+re-exports (``from .console import NAMES as NAMES``): it reaches a change only+in the module that defines it (:func:`entry_names`). A binding the conftest never reads (``importapp.models # registers them``) is imported for its side effects, which everytest sees, so it keeps every test.@@ -82,7 +85,7 @@ from ..ingestion.framework_edges.pytest_edges import (from ..ingestion.languages.python_modules import module_partsfrom ..ingestion.languages.python_strings import PY_DYNAMIC_LOAD_MARKERSfrom .test_reachability import _in_clause-from .test_selection import is_runnable_test, scope_kind+from .test_selection import BROADCAST_VIA, is_runnable_test, scope_kind# The call whose first argument is the object an attribute is patched on:# naming a module there in an autouse fixture is caught by the import check.@@ -236,9 +239,11 @@ def _parents(tree: ast.AST) -> dict[int, ast.AST]:def _patch_target(name: ast.Name, parents: Mapping[int, ast.AST]) -> bool:- """Whether the name is the first argument of an attribute patch or probe call."""- par = parents.get(id(name))- if not (isinstance(par, ast.Call) and par.args and par.args[0] is name):+ """Whether the name, or an attribute chain read from it (``mod.Cls``), is the+ first argument of an attribute patch call."""+ node, _ = _dotted_read(name, parents)+ par = parents.get(id(node))+ if not (isinstance(par, ast.Call) and par.args and par.args[0] is node):return Falsefunc = par.funccalled = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "")@@ -525,6 +530,82 @@ def local_names(source: str) -> frozenset[str]:)+@dataclass(frozen=True)+class EntryNames:+ """A route entry's names whose use depends on one file's text (:func:`entry_names`)."""++ own: frozenset[str] = frozenset()+ # {the file a name is re-exported from: those names, as the entry binds them}+ borrowed: Mapping[str, frozenset[str]] = field(default_factory=dict)++ def stable(self, target: str) -> frozenset[str]:+ """The names whose use cannot reach a change in *target*."""+ return self.own.union(*(n for origin, n in self.borrowed.items() if origin != target))+++def _reexports(source: str, here: tuple[str, ...]) -> dict[str, tuple[tuple[str, ...], str]]:+ """``{bound name: (module, the name imported)}`` for each name *source* binds once,+ by a top-level ``from`` import."""+ try:+ tree = parse_python(source)+ except (SyntaxError, ValueError):+ return {}+ counts = Counter(n for node in ast.walk(tree) for n in _bound_names(node))+ if "*" in counts:+ return {}+ return {+ alias.asname or alias.name: (_from_module(stmt, here), alias.name)+ for stmt in tree.body+ if isinstance(stmt, ast.ImportFrom)+ for alias in stmt.names+ if counts[alias.asname or alias.name] == 1+ }+++def _module_file(+ module: tuple[str, ...], entry: str, read: Callable[[str], str | None]+) -> str | None:+ """The one readable file *module* names, from the repository root or a source root+ above *entry*; ``None`` when none is, or several are.++ Ceiling: a module under another source root (a namespace package split+ across distributions) is not found, so its names stay unresolved.+ """+ if not module:+ return None+ parts = PurePosixPath(entry).parts+ roots = [()] + [parts[:i] for i in range(1, len(parts)) if parts[i] == module[0]]+ found = {+ path+ for root in roots+ for path in ("/".join((*root, *module)) + ".py", "/".join((*root, *module, "__init__.py")))+ if read(path) is not None+ }+ return found.pop() if len(found) == 1 else None+++def entry_names(path: str, read: Callable[[str], str | None]) -> EntryNames:+ """The :func:`local_names` of the file at *path*, and those it re-exports.++ A name the module binds once by ``from X import N`` reads ``X.N``, so when+ ``N`` is a local name of ``X`` its use depends on ``X``'s text alone. One+ hop: a name ``X`` itself re-exports stays unresolved.+ """+ source = read(path) or ""+ parts = module_parts(path)+ here = parts if PurePosixPath(path).name == "__init__.py" else parts[:-1]+ borrowed: dict[str, set[str]] = {}+ for bound, (module, name) in _reexports(source, here).items():+ origin = _module_file(module, path, read)+ if origin is None or origin == path:+ continue+ names = local_names(read(origin) or "")+ mine = {bound + n[len(name) :] for n in names if n == name or n.startswith(f"{name}.")}+ if mine:+ borrowed.setdefault(origin, set()).update(mine)+ return EntryNames(local_names(source), {o: frozenset(n) for o, n in borrowed.items()})++def _dotted_read(name: ast.Name, parents: Mapping[int, ast.AST]) -> tuple[ast.AST, list[str]]:"""The outermost ``name.a.b`` attribute chain read from *name*, and its attributes."""node: ast.AST = name@@ -1003,7 +1084,7 @@ def _judge_routes("""Set each route's use and reason. One parse per conftest and per entry; each distinctroute through it is matched against it once."""facts: dict[str, ConftestFacts | None] = {}- consts: dict[str, frozenset[str]] = {}+ consts: dict[str, EntryNames] = {}uses: dict[tuple, ConftestUse] = {}for target, conf, route in ((t, c, r) for t, by in routes.items() for c, r in by.items()):if conf not in facts:@@ -1012,8 +1093,8 @@ def _judge_routes(# The changed file's own local names may be what changed.others = route.entries - {target}for e in others - set(consts) if read_source else ():- consts[e] = local_names(read_source(e) or "")- stable = {e: consts[e] for e in others if consts.get(e)}+ consts[e] = entry_names(e, read_source)+ stable = {e: names for e in others if e in consts and (names := consts[e].stable(target))}_judge(conf, route, facts[conf], plugin_loader, uses, stable)@@ -1032,7 +1113,7 @@ def _judge(elif parsed is None:route.reason = f"{conf} could not be read"else:- key = (conf, route.entries, frozenset(stable))+ key = (conf, route.entries, frozenset(stable.items()))if key not in uses:uses[key] = parsed.use(route.entries, stable)route.use = uses[key]@@ -1106,8 +1187,13 @@ def _narrow(scope: _Scope,notes: dict[tuple[str, str], list[str]],) -> list[tuple[str, str]]:- """One target's picks, each narrowable conftest replaced by the tests it can break."""+ """One target's picks, each narrowable conftest replaced by the tests it can break.++ A test only a conftest keeping every test under it adds is labelled+ :data:`BROADCAST_VIA`.+ """blocked: set[str] = set()+ spread: set[str] = set()added: dict[str, str] = {}narrowed: list[str] = []hidden_importer = scope.unresolved_conftest_import()@@ -1115,6 +1201,7 @@ def _narrow(reason, users = _route_users(conf, route, scope, hidden_importer)if reason is not None:_add_note(notes, (f"{conf} keeps every test under it for ", f": {reason}"), target)+ spread.add(conf)continueif route.use is None:# Reached only through another conftest's tests, which decide it.@@ -1127,7 +1214,13 @@ def _narrow(kept = {t: v for t, v in picks.items() if t not in blocked}for test, via in added.items():kept.setdefault(test, via)+ # Before the walk below, which adds to the dict it is given.+ start = {t: v for t, v in kept.items() if t not in spread}result = dict(with_importers(kept, scope.parents, blocked))+ if spread:+ inner = dict(with_importers(start, scope.parents, blocked | spread))+ for t in [t for t in result if t not in inner and t not in spread]:+ result[t] = BROADCAST_VIAfor conf in narrowed:check = _add_import_check(conf, result, scope)_add_note(notes, _narrow_note(conf, routes[conf], check), target)diff --git a/packages/core/src/repowise/core/analysis/test_selection.py b/packages/core/src/repowise/core/analysis/test_selection.pyindex 4d57c291c..96b1a2bfe 100644--- a/packages/core/src/repowise/core/analysis/test_selection.py+++ b/packages/core/src/repowise/core/analysis/test_selection.py@@ -37,7 +37,11 @@ in a child process (it imports one module, but exercises far more). The testsreaching files whose imports moved between the indexed commit and the base(:func:`plan_gap`) run too. A test package's ``__init__.py`` or a``conftest.py`` (changed, deleted, or on a route to a changed file) stands for-every test under its directory. A helper module tests import stands for the+every test under its directory, unless :mod:`.conftest_routes` narrows a+conftest the change reaches only through its imports to the tests it can+break. The tests only a scope file on a route stands for are the selection's+``broadcast``: they run, and are counted apart from the tests the change+reaches. A helper module tests import stands for thetests that import it, directly or through other helpers (basis``helper-importers``), which are the files that run it: Python runs thepackage file for each module in it, and pytest loads a conftest for each test@@ -272,13 +276,18 @@ class Selection:``changed-test``, ``call-graph``, ``import-graph``, ``conftest-fixture``(a test using a conftest fixture that reaches the change),``conftest-import-check`` (one test that loads a conftest the change reaches- only through its imports), ``filename-pattern``, ``unknown``, ``none`` when+ only through its imports), ``conftest-broadcast`` (a test only a conftest+ keeping every test under it reaches), ``filename-pattern``, ``unknown``, ``none`` whennothing was asked (no index), or a scope's ``ecosystem``,``package-importers``, ``named-by``, ``fixture-readers`` or ``owner-package``.``why`` says, per selected test file, what put it in: the changed file and evidence thatreached it, or the reason it runs with every subset. ``known_tests`` arethe checkout's runnable test files (empty when not read), so a selection- can say how much of the suite it is.+ can say how much of the suite it is. ``broadcast`` maps each selected test+ file that runs only because a ``conftest.py`` or test-package+ ``__init__.py`` on a route to a changed file stands for every test under+ it to that file: they run, but a count of what the change reaches leaves+ them out."""run_all: bool@@ -291,6 +300,11 @@ class Selection:basis: Mapping[str, str] = field(default_factory=dict)why: Mapping[str, str] = field(default_factory=dict)known_tests: tuple[str, ...] = ()+ broadcast: Mapping[str, str] = field(default_factory=dict)++ def reached_tests(self) -> list[str]:+ """:attr:`tests` without the :attr:`broadcast` ones, in order."""+ return [t for t in self.tests if t.split("::", 1)[0] not in self.broadcast]def to_dict(self) -> dict[str, Any]:return {@@ -303,6 +317,7 @@ class Selection:"skipped_files": list(self.skipped_files),"basis": dict(self.basis),"why": dict(self.why),+ "broadcast": dict(self.broadcast),}@@ -608,6 +623,12 @@ def select_tests(inp: SelectionInput) -> Selection:])notes = _notes(inp, triage.skipped, always, traced)+ broadcast = _broadcast(evidence, test_files, {f for _, f in in_scope} | set(always))+ why = {**scope_why, **gap_why, **_why(triage.code, per_file, evidence), **always}+ why.update(+ (t, f"{path} changed ({scope} is on its route and stands for every test under it)")+ for t, (path, scope) in broadcast.items()+ )return Selection(run_all=bool(run_all),reasons=tuple(run_all + evidence.notes + scope_notes + notes),@@ -617,11 +638,28 @@ def select_tests(inp: SelectionInput) -> Selection:always_run=inp.config.always_run,skipped_files=tuple(triage.skipped),basis=basis,- why={**scope_why, **gap_why, **_why(triage.code, per_file, evidence), **always},+ why=why,known_tests=tuple(inp.known_tests),+ broadcast={t: scope for t, (_, scope) in broadcast.items()},)+def _broadcast(+ ev: _Evidence, selected: Collection[str], also: Collection[str]+) -> dict[str, tuple[str, str]]:+ """Selected test files only a scope file on a route put in, nothing else.++ *also* are the test files selected outside the per-file evidence (a+ scope's own tests, the tests every subset runs).+ """+ selected = set(selected)+ return {+ t: v+ for t, v in ev.broadcast.items()+ if t in selected and t not in ev.reached and t not in also+ }++_UNPLACED_REASON = "the graph has no edge from it into the repository's code"_EVERY_SUBSET = "runs with every subset: "@@ -659,8 +697,15 @@ def _why(return out-# The two vias a narrowed conftest route adds (``conftest_routes``), spelled out.+#: The via of a test that runs only because a conftest on the route keeps every+#: test under it (``conftest_routes``): selected, not reached by the change.+BROADCAST_VIA = "conftest-broadcast"++# The vias a conftest route adds (``conftest_routes``), spelled out._VIA_WHY = {+ BROADCAST_VIA: (+ f"{BROADCAST_VIA}: a conftest above it is on the route and keeps every test under it"+ ),"conftest-fixture": ("conftest-fixture: it asks for a conftest fixture whose code runs into the change"),@@ -1021,6 +1066,10 @@ class _Evidence:notes: list[str] = field(default_factory=list)# Known tests under each directory set (:func:`_known_under`), per selection.under_memo: dict[frozenset[str], list[str]] = field(default_factory=dict, compare=False)+ # Test files evidence or a changed scope file reached, and ``{test file:+ # (changed file, scope on its route)}`` for those a route's scope expanded to.+ reached: set[str] = field(default_factory=set, compare=False)+ broadcast: dict[str, tuple[str, str]] = field(default_factory=dict, compare=False)@classmethoddef of(cls, inp: SelectionInput, deleted: set[str]) -> _Evidence:@@ -1092,7 +1141,7 @@ def _file_tests(tests = ev.present([*ev.covered.get(path, ()), *found])basis = _basis(path, ev.covered, ev.inferred, ev.unknown)scopes, basis = _scope_files(path, found, basis)- tests = _expand_scopes(tests, scopes, ev)+ tests = _expand_scopes(path, tests, scopes, ev)helpers = sorted({f for _, f in found if not is_runnable_test(f)} - ev.deleted - scopes - {path})@@ -1123,10 +1172,36 @@ def _scope_files(path: str, found: list[_TestRef], basis: str) -> tuple[set[str]return scopes, basis-def _expand_scopes(tests: list[_TestRef], scopes: set[str], ev: _Evidence) -> list[_TestRef]:+def _expand_scopes(+ path: str, tests: list[_TestRef], scopes: set[str], ev: _Evidence+) -> list[_TestRef]:+ """*tests* with each scope file replaced by the tests under its directory.++ Records what reached *path* (:attr:`_Evidence.reached`), and each test only+ a scope on its route, not *path* itself, put in (:attr:`_Evidence.broadcast`).+ """kept = [(t, f) for t, f in tests if f not in scopes]dirs = {str(PurePosixPath(i).parent) for i in scopes}- return kept + [(t, t) for t in _known_under(ev, dirs) if t not in ev.deleted]+ under = [t for t in _known_under(ev, dirs) if t not in ev.deleted]+ own = set(_known_under(ev, {str(PurePosixPath(path).parent)})) if path in scopes else set()+ spread = {t for t, via in ev.inferred.get(path, ()) if via == BROADCAST_VIA}+ ev.reached.update({f for _, f in kept if f and f not in spread} | own)+ route_scopes = sorted(scopes - {path}, key=lambda s: -len(s))+ for t in spread:+ ev.broadcast.setdefault(t, (path, _scope_over(t, route_scopes)))+ for scope in route_scopes:+ for t in _known_under(ev, {str(PurePosixPath(scope).parent)}):+ ev.broadcast.setdefault(t, (path, scope))+ return kept + [(t, t) for t in under]+++def _scope_over(test: str, scopes: list[str]) -> str:+ """The first of *scopes* whose directory holds *test*, else the first (a test+ reached through an importer elsewhere), else ``""``."""+ return next(+ (s for s in scopes if _under({str(PurePosixPath(s).parent)}, [test])),+ scopes[0] if scopes else "",+ )def _known_under(ev: _Evidence, dirs: Collection[str]) -> list[str]:@@ -1248,6 +1323,7 @@ _VIAS = ("import-graph","conftest-fixture","conftest-import-check",+ BROADCAST_VIA,"filename-pattern",)diff --git a/packages/server/src/repowise/server/mcp_server/_test_selection.py b/packages/server/src/repowise/server/mcp_server/_test_selection.pyindex a94cb9fe9..16ff414f9 100644--- a/packages/server/src/repowise/server/mcp_server/_test_selection.py+++ b/packages/server/src/repowise/server/mcp_server/_test_selection.py@@ -303,6 +303,17 @@ def basis_of(selection: Selection) -> str:return "measured" if "coverage" in selection.basis.values() else "inferred"+def split_broadcast(selection: Selection) -> tuple[list[str], list[str]]:+ """``(the tests the change reaches, the broadcast ones)``, each in run order.++ A full run has no broadcast: every test runs for the run-all reasons.+ """+ if selection.run_all or not selection.broadcast:+ return list(selection.tests), []+ spread = [t for t in selection.tests if t.split("::", 1)[0] in selection.broadcast]+ return selection.reached_tests(), spread++def selection_block(result: dict[str, Any],selection: Selection,@@ -320,9 +331,14 @@ def selection_block(index predates files outside the change and the selection holds over halfthe suite: the list stands and ``summary`` says why. The tail of a listholding most of the suite is not stored when every test is to run anyway.+ ``total`` and ``tests_to_run`` leave out the broadcast (:func:`split_broadcast`),+ counted in ``broadcast_total`` when there is one and stored apart.*detail* adds ``why`` and ``basis_by_file``."""- run_list = list(selection.tests) # in run order (``test_ranking``)+ # In run order (``test_ranking``); the broadcast is counted apart.+ run_list, broadcast = split_broadcast(selection)+ if broadcast:+ collector.add(f"{label}.broadcast_tests ({len(broadcast)})", broadcast)shown = run_list[:limit]known = set(selection.known_tests)held = len(known & set(selection.test_files))@@ -361,9 +377,11 @@ def selection_block(f"{len(known)} test files were selected; run the whole suite, or ""`repowise update` to narrow it."if degraded- else _summary(selection, len(run_list), always, limit)+ else _summary(selection, len(run_list), always, limit, len(broadcast))),}+ if broadcast:+ block["broadcast_total"] = len(broadcast)if not detail:return blockblock["why"] = {@@ -382,19 +400,32 @@ def selection_block(return block-def _summary(selection: Selection, total: int, always: int, limit: int) -> str:+NO_TESTS = "No test needs to run for this change."+++def _summary(+ selection: Selection, total: int, always: int, limit: int, broadcast: int = 0+) -> str:shown = f"; showing first {limit}" if total > limit else ""if selection.run_all:lead = selection.reasons[0] if selection.reasons else "the selection could not vouch"named = f" Run these {total} first{shown}." if total else ""return f"Run every test: {lead}{named}"+ spread = (+ f" {broadcast} more test(s) must still run because a conftest on a route keeps "+ "every test under it (broadcast_total; the reasons say why)."+ if broadcast+ else ""+ )if not total:- return "No test needs to run for this change."+ return f"No test the change reaches directly.{spread}" if spread else NO_TESTS# The share of the suite, so a selection holding most of it never reads as targeted.known = set(selection.known_tests)- held = len(known & set(selection.test_files))+ held = len(known & (set(selection.test_files) - set(selection.broadcast)))share = f" ({held} of {len(known)} test files)" if known else ""rule = f", {always} of them because they run with every subset" if always else ""if known and held == len(known):return f"{total} test(s) to run for this change, every test file there is{rule}{shown}."+ if spread:+ return f"{total} test(s) to run for this change{share}{rule}{shown}.{spread}"return f"{total} test(s) to run for this change{share}{rule}{shown}; the rest can be skipped."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 5415e0088..dc3851871 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@@ -32,6 +32,7 @@ from repowise.server.mcp_server._helpers import (from repowise.server.mcp_server._test_selection import (UNAVAILABLE_REASON,basis_of,+ split_broadcast,)from repowise.server.mcp_server.tool_risk.directives_pr import (_WORKSPACE_FAMILIES, # noqa: F401 re-exported@@ -562,7 +563,10 @@ def _tests_to_run("tests_status": tests.status,"tests_status_reason": tests.message,}- population = list(selection.tests) # in run order (``test_ranking``)+ # In run order (``test_ranking``); the broadcast is counted apart.+ population, broadcast = split_broadcast(selection)+ if broadcast:+ collector.add(f"directive.broadcast_tests ({len(broadcast)})", broadcast)reasons = list(selection.reasons)if len(reasons) > _RUN_ALL_REASONS_LIMIT:collector.add(@@ -572,6 +576,8 @@ def _tests_to_run()shown = dict.fromkeys(t.split("::", 1)[0] for t in population[:_TESTS_TO_RUN_LIMIT])extra: dict[str, Any] = {"tests_run_all": selection.run_all}+ if broadcast:+ extra["tests_broadcast_total"] = len(broadcast)if selection.run_all:extra["tests_run_all_reasons"] = reasons[:_RUN_ALL_REASONS_LIMIT]extra["tests_to_run_why"] = {p: selection.why[p] for p in shown if p in selection.why}diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/directives_pr.py b/packages/server/src/repowise/server/mcp_server/tool_risk/directives_pr.pyindex ac074eb72..2fcb0947e 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/directives_pr.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/directives_pr.py@@ -128,6 +128,11 @@ def tests_summary() -> str:"""Summary sentences for the run list and, on request, the typed recommendations."""suffix = f" {run_total} test(s) to run, {basis}." if run_total else ""+ if spread := tests_fields.get("tests_broadcast_total"):+ suffix += (+ f" {spread} more must still run because a conftest on a route keeps every test "+ "under it (tests_broadcast_total)."+ )if tests_fields.get("tests_run_all"):suffix += " Every test must run (tests_run_all_reasons)."recommendations_total = len(test_impact.get("recommendations") or [])diff --git a/tests/unit/analysis/test_conftest_routes.py b/tests/unit/analysis/test_conftest_routes.pyindex 97d80d5b3..b26581a54 100644--- a/tests/unit/analysis/test_conftest_routes.py+++ b/tests/unit/analysis/test_conftest_routes.py@@ -9,6 +9,7 @@ import pytestfrom repowise.core.analysis.conftest_routes import (ConftestFacts,conftest_use,+ entry_names,local_names,)@@ -627,3 +628,80 @@ def test_an_autouse_fixture_using_what_the_module_imports_or_holds_still_reaches) -> None:use = _autouse("from app import store", line, _STORE_FUNCTIONS)assert use.run_all and "autouse fixture _f uses store" in use.run_all+++ ("line", "narrowed"),+ [+ ('monkeypatch.setattr(store.Client, "detect", lambda self: False)', True),+ ('monkeypatch.setattr(store.Client.Inner, "x", None)', True),+ ('monkeypatch.setattr(store.make(), "x", None)', False),+ ('monkeypatch.delattr(store.Client, "detect")', False),+ ],+)+def test_patching_an_attribute_read_from_the_route_in_an_autouse_fixture_is_import_time_only(+ line: str, narrowed: bool+) -> None:+ """A patch target that stops resolving fails the import check, which runs the fixture."""+ use = _use(+ f"""+ import pytest+ from app import store++ @pytest.fixture(autouse=True)+ def _isolate(monkeypatch):+ {line}+ """+ )+ assert (use.run_all is None) is narrowed+++_FACADE = {+ "src/app/facade.py": (+ "from app.console import NAMES as NAMES\n"+ "from .console import reset\n"+ "from app.console import LEVEL\n"+ "from app.other import THING\n"+ "from app import util\n"+ "LEVEL = LEVEL + 1\n"+ ),+ "src/app/console.py": (+ "import logging\nNAMES = ('a', 'b')\nLEVEL = 3\n_seen = {}\n\n"+ "def reset():\n _seen.clear()\n"+ ),+ "src/app/other.py": "from app.deep import THING\n",+}+++def test_a_re_exported_local_name_is_stable_unless_the_change_is_where_it_is_defined() -> None:+ names = entry_names("src/app/facade.py", _FACADE.get)+ assert {"NAMES", "reset"} <= names.stable("src/app/util.py")+ # The defining module is the change, so the name may be what changed.+ assert not {"NAMES", "reset"} & names.stable("src/app/console.py")+ # Rebound in the facade, or re-exported twice over: not followed.+ assert not {"LEVEL", "THING", "util"} & names.stable("src/app/util.py")+++def test_a_re_exported_name_with_no_single_defining_file_stays_unresolved() -> None:+ gone = {k: v for k, v in _FACADE.items() if k != "src/app/console.py"}+ assert "NAMES" not in entry_names("src/app/facade.py", gone.get).stable("src/app/util.py")+ # Two source roots both hold app/console.py: which one runs is unknown.+ twice = {**_FACADE, "app/console.py": "NAMES = ()\n"}+ assert "NAMES" not in entry_names("src/app/facade.py", twice.get).stable("src/app/util.py")++[email protected]("where", ["top", "fixture"])+def test_an_autouse_fixture_reading_a_re_exported_constant_reaches_only_its_definer(+ where: str,+) -> None:+ """``from facade import NAMES`` at top level or in the fixture body: an import-only route."""+ imports, body = "from app.facade import NAMES", "loggers = list(NAMES)"+ if where == "fixture":+ imports, body = "", f"{imports}\n {body}"+ names = entry_names("src/app/facade.py", _FACADE.get)+ source = f"import pytest\n{imports}\n\[email protected](autouse=True)\ndef _f():\n {body}\n"+ entries = ["src/app/facade.py"]+ behind = {"src/app/facade.py": names.stable("src/app/util.py")}+ assert conftest_use(source, "tests/conftest.py", entries, behind).run_all is None+ at_definer = {"src/app/facade.py": names.stable("src/app/console.py")}+ assert conftest_use(source, "tests/conftest.py", entries, at_definer).run_alldiff --git a/tests/unit/analysis/test_test_selection.py b/tests/unit/analysis/test_test_selection.pyindex e3736ee1a..def2efea6 100644--- a/tests/unit/analysis/test_test_selection.py+++ b/tests/unit/analysis/test_test_selection.py@@ -729,6 +729,8 @@ def test_a_changed_conftest_selects_every_test_at_or_below_it(path, expected, deassert not sel.run_all, sel.reasonsassert sel.tests == expectedassert sel.basis[path] == "conftest"+ # The change is the conftest itself: its tests are what it reaches.+ assert not sel.broadcastdef test_a_route_through_a_conftest_selects_the_tests_under_it() -> None:@@ -741,6 +743,38 @@ def test_a_route_through_a_conftest_selects_the_tests_under_it() -> None:sel = _select(["src/a.py"], tiers, known_tests=_KNOWN)assert not sel.run_all, sel.reasonsassert sel.tests == ("other/test_c.py", "tests/unit/test_a.py", "tests/unit/sub/test_b.py")+ # They still run, but are counted apart from what the change reaches.+ assert sel.broadcast == dict.fromkeys(sel.tests[1:], "tests/unit/conftest.py")+ assert sel.reached_tests() == ["other/test_c.py"]+ assert "tests/unit/conftest.py is on its route" in sel.why["tests/unit/sub/test_b.py"]+ assert sel.to_dict()["broadcast"] == dict(sel.broadcast)+++def test_a_test_the_conftest_broadcast_labels_is_broadcast_unless_evidence_reaches_it() -> None:+ tiers = _tiers(+ inferred=[+ _inferred("src/a.py", "tests/unit/conftest.py", "import-graph"),+ _inferred("src/a.py", "tests/unit/test_a.py", "conftest-broadcast"),+ _inferred("src/a.py", "tests/test_top.py", "conftest-broadcast"),+ _inferred("src/b.py", "tests/unit/sub/test_b.py", "import-graph"),+ ]+ )+ sel = _select(["src/a.py", "src/b.py"], tiers, known_tests=_KNOWN)+ assert not sel.run_all, sel.reasons+ assert set(sel.test_files) == set(_KNOWN) - {"other/test_c.py"}+ # src/b.py reaches test_b on its own; a broadcast row outside the+ # conftest's directory (an importer) still names that conftest.+ assert sel.broadcast == {+ "tests/unit/test_a.py": "tests/unit/conftest.py",+ "tests/test_top.py": "tests/unit/conftest.py",+ }+ assert sel.reached_tests() == ["tests/unit/sub/test_b.py"]+++def test_a_full_run_or_a_plain_subset_has_no_broadcast() -> None:+ tiers = _tiers(inferred=[_inferred("src/a.py", "tests/unit/test_a.py", "import-graph")])+ assert not _select(["src/a.py"], tiers, known_tests=_KNOWN).broadcast+ assert not _select(["uv.lock"], known_tests=_KNOWN).broadcastdef test_a_route_through_an_imported_helper_selects_its_importers() -> None:diff --git a/tests/unit/cli/test_impacted_tests_cmd.py b/tests/unit/cli/test_impacted_tests_cmd.pyindex b6c77b098..5af835d9f 100644--- a/tests/unit/cli/test_impacted_tests_cmd.py+++ b/tests/unit/cli/test_impacted_tests_cmd.py@@ -111,6 +111,24 @@ def test_args_prints_the_subset_on_one_line(repo) -> None:assert "documentation: no tests needed" in _err(result)+def test_the_args_header_counts_the_conftest_broadcast_apart() -> None:+ from repowise.cli.commands.impacted_tests_cmd import _args_header+ from repowise.core.analysis.test_selection import Selection++ tests = ("tests/test_a.py", "tests/test_b.py")+ selection = Selection(+ run_all=False,+ reasons=(),+ tests=tests,+ test_files=tests,+ broadcast={"tests/test_b.py": "tests/conftest.py"},+ )+ assert _args_header(selection, list(tests), "pytest", False) == (+ "2 argument(s) for pytest; 1 selected test file(s) run only because a conftest "+ "on a route keeps every test under it."+ )++def test_json_adds_the_selection_to_the_report(repo) -> None:result = _run(repo, "main...feat", "--format", "json", "--runner", "files")assert result.exit_code == 0, result.outputdiff --git a/tests/unit/persistence/test_impacted_tests_resolution.py b/tests/unit/persistence/test_impacted_tests_resolution.pyindex 2eeffe7e3..a852af208 100644--- a/tests/unit/persistence/test_impacted_tests_resolution.py+++ b/tests/unit/persistence/test_impacted_tests_resolution.py@@ -497,7 +497,58 @@ async def test_an_autouse_fixture_calling_a_function_reaches_only_what_the_functif narrowed:assert picks == {"tests/test_a.py": "conftest-import-check"}else:- assert "tests/conftest.py" in picks+ # A behavioural route keeps every test, each labelled as the conftest's broadcast.+ assert picks == {+ "tests/conftest.py": "import-graph",+ **dict.fromkeys(+ ["tests/test_a.py", "tests/test_b.py", "tests/test_c.py"], "conftest-broadcast"+ ),+ }++[email protected]("where", ["top", "fixture"])+async def test_an_autouse_fixture_reading_a_re_exported_constant_runs_one_import_check(+ async_session, where: str+) -> None:+ """``store`` re-exports ``NAMES`` from ``names``, which the change is not in."""+ repo = await insert_repo(async_session)+ await _conftest_graph(async_session, repo.id, stamped=True)+ imports, body = "from app.store import NAMES", "assert list(NAMES)"+ if where == "fixture":+ imports, body = "", f"{imports}\n {body}"+ source = f"import pytest\n{imports}\n\n\[email protected](autouse=True)\ndef _n():\n {body}\n"+ files = {+ "src/app/store.py": "from app import util\nfrom app.names import NAMES as NAMES\n",+ "src/app/names.py": "NAMES = ('a', 'b')\n",+ }++ out = _empty_result(1)+ await _resolve_impacted(+ async_session,+ repo.id,+ {"src/app/util.py": None},+ set(),+ out,+ pytest_texts={"tests/conftest.py": source},+ read_source=files.get,+ )++ assert _pairs(out, "src/app/util.py") == {"tests/test_a.py": "conftest-import-check"}+++async def test_a_conftest_route_that_cannot_be_judged_keeps_every_test(async_session) -> None:+ """No text for the conftest: unknown runs more, never fewer."""+ repo = await insert_repo(async_session)+ await _conftest_graph(async_session, repo.id, stamped=True)++ out = _empty_result(1)+ await _resolve_impacted(+ async_session, repo.id, {"src/app/util.py": None}, set(), out, pytest_texts={}+ )++ picks = _pairs(out, "src/app/util.py")+ assert {"tests/test_a.py", "tests/test_b.py", "tests/test_c.py"} <= set(picks)+ assert any("tests/conftest.py could not be read" in n for n in out["conftest_notes"])async def _add_edge(session, repo_id, source, target, edge_type, hint=None, **flags) -> None:diff --git a/tests/unit/server/mcp/test_change_test_selection.py b/tests/unit/server/mcp/test_change_test_selection.pyindex 94d0eeb1a..a5acbe27d 100644--- a/tests/unit/server/mcp/test_change_test_selection.py+++ b/tests/unit/server/mcp/test_change_test_selection.py@@ -545,3 +545,52 @@ def test_a_run_all_list_holding_most_of_the_suite_stores_no_tail(tmp_path) -> Noassert block["status"] == "run_all" and block["truncated"] is Trueassert collector.empty+++def _spread(*, run_all: bool = False) -> object:+ from repowise.core.analysis.test_selection import Selection++ suite = tuple(f"tests/test_{i}.py" for i in range(20))+ return Selection(+ run_all=run_all,+ reasons=("tests/conftest.py keeps every test under it",),+ tests=suite[:5],+ test_files=suite[:5],+ known_tests=suite,+ why=dict.fromkeys(suite[:5], "src/a.py changed (import-graph)"),+ broadcast=dict.fromkeys(suite[2:5], "tests/conftest.py"),+ )+++def test_the_conftest_broadcast_is_counted_apart_from_the_headline(tmp_path) -> None:+ from repowise.server.mcp_server._budget import OmissionCollector+ from repowise.server.mcp_server._test_selection import selection_block++ collector = OmissionCollector("get_change_risk", store_path=tmp_path / "omissions.db")+ block = selection_block({}, _spread(), collector, limit=10, label="impacted_tests")++ assert block["total"] == 2 and block["broadcast_total"] == 3+ assert block["tests_to_run"] == ["tests/test_0.py", "tests/test_1.py"]+ assert block["summary"].startswith("2 test(s) to run for this change (2 of 20 test files).")+ assert "3 more test(s) must still run because a conftest" in block["summary"]+ # The broadcast tests are stored for recovery, not dropped.+ assert not collector.empty++ # A full run has no broadcast: every listed test is what to run first.+ full = selection_block({}, _spread(run_all=True), collector, limit=10, label="impacted_tests")+ assert full["total"] == 5 and "broadcast_total" not in full+++def test_get_risk_counts_the_conftest_broadcast_apart(tmp_path) -> None:+ from repowise.server.mcp_server._budget import OmissionCollector+ from repowise.server.mcp_server.tool_risk.directives import ChangeTests, _tests_to_run+ from repowise.server.mcp_server.tool_risk.directives_pr import tests_summary++ collector = OmissionCollector("get_risk", store_path=tmp_path / "omissions.db")+ population, basis, fields = _tests_to_run(ChangeTests(selection=_spread()), collector)++ assert population == ["tests/test_0.py", "tests/test_1.py"]+ assert fields["tests_broadcast_total"] == 3+ assert "3 more must still run because a conftest" in tests_summary(+ len(population), basis, fields, {}, False, 10+ )