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(coverage): repowise impacted-tests command (run only the tests a diff exercises) (#792)
Raghav Chamadiya01bdc7084960
diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.mdindex f61951070..8deb288ca 100644--- a/docs/CLI_REFERENCE.md+++ b/docs/CLI_REFERENCE.md@@ -2,9 +2,9 @@Complete reference for all `repowise` commands. For a guided introduction, see the [Quickstart](QUICKSTART.md).-Command list (in `--help` order): `augment`, `init`, `delete`, `generate-claude-md`, `costs`, `update`, `dead-code`, `health`, `risk`, `decision`, `coverage`, `search`, `distill`, `expand`, `saved`, `corrections`, `export`, `hook`, `status`, `doctor`, `watch`, `serve`, `mcp`, `reindex`, `restyle`, `wiki-styles`, `whats-new`, `telemetry`, `login`, `logout`, `whoami`, `workspace`. Two more ship as separate console scripts, not subcommands: `repowise-augment`, `repowise-rewrite` (both hook entry points, not meant to be run by hand).+Command list (in `--help` order): `augment`, `init`, `delete`, `generate-claude-md`, `costs`, `update`, `dead-code`, `health`, `risk`, `decision`, `coverage`, `impacted-tests`, `search`, `distill`, `expand`, `saved`, `corrections`, `export`, `hook`, `status`, `doctor`, `watch`, `serve`, `mcp`, `reindex`, `restyle`, `wiki-styles`, `whats-new`, `telemetry`, `login`, `logout`, `whoami`, `workspace`. Two more ship as separate console scripts, not subcommands: `repowise-augment`, `repowise-rewrite` (both hook entry points, not meant to be run by hand).-**Do you need an LLM key?** Most commands are pure index/analysis and never call an LLM. The exceptions: `init` (unless `--index-only` or `--mode fast`), `update` (unless `--index-only` or `--no-docs`), `restyle`, `watch` (when it regenerates a page), `health --generate-code`, and `workspace add --docs`. Everything else, `search`, `dead-code`, `health`, `risk`, `decision`, `coverage`, `export`, `mcp`, `reindex`, `doctor`, and so on, works index-only, with no provider configured.+**Do you need an LLM key?** Most commands are pure index/analysis and never call an LLM. The exceptions: `init` (unless `--index-only` or `--mode fast`), `update` (unless `--index-only` or `--no-docs`), `restyle`, `watch` (when it regenerates a page), `health --generate-code`, and `workspace add --docs`. Everything else, `search`, `dead-code`, `health`, `risk`, `impacted-tests`, `decision`, `coverage`, `export`, `mcp`, `reindex`, `doctor`, and so on, works index-only, with no provider configured.## Workspace auto-detect (cross-cutting)@@ -399,6 +399,45 @@ See [`docs/CHANGE_RISK.md`](./CHANGE_RISK.md) for the scoring model.---+### `repowise impacted-tests [REVSPEC]`++Print the tests a change actually exercises, so CI can run "these 40 tests, not+all 4,000". For each changed line it consults the per-test test-to-code map+built by [`repowise coverage add`](#repowise-coverage) and returns the tests+whose recorded coverage intersects the diff. No LLM, no network - a straight+index lookup.++`REVSPEC` is a `base..head` range or a single commit; with no argument (or+`--staged`) it diffs the staged changes. It is honest about what it does not+know, and always says which path fired:++- a changed file with per-test coverage -> the exact covering tests (`via: coverage`);+- a changed file with no coverage rows -> a filename-pattern **guess** at its paired test, labelled as a guess (never presented as coverage-backed);+- a new file with neither coverage nor a paired test -> reported as "unknown, run the full suite" (never implied as "no tests needed");+- no map ingested at all -> a prompt to run `repowise coverage add` on a report with contexts first.++The map only exists when coverage was ingested from a report that carries+per-test contexts (a coverage.py `.coverage` written with dynamic contexts, or a+per-test lcov). Score the same `head` the map was ingested at so line numbers+line up.++**Options:**++| Flag | Description |+|------|-------------|+| `--path` | Repo path (defaults to cwd / workspace primary) |+| `--staged` | Diff the staged changes (`git diff --cached`); the default when no range is given |+| `--format` | `table` (default), `json` (full report), or `list` (test ids one per line, for piping) |++```bash+repowise impacted-tests # staged changes+repowise impacted-tests main..HEAD # a branch / PR range+repowise impacted-tests abc123 # a single commit+repowise impacted-tests main..HEAD --format list | xargs pytest+```++---+### `repowise health [PATH]`Compute per-file code-health scores from 25 deterministic markers (McCabe complexity, nesting, brain methods, LCOM4 cohesion, god classes, native clone detection, untested hotspots, coverage gradient, function/ownership/churn/change-entropy organizational risk, test-quality smells, and more). Zero LLM calls by default, pure Python over tree-sitter + git data. See [`docs/CODE_HEALTH.md`](./CODE_HEALTH.md) for the user guide and [`docs/architecture/code-health.md`](./architecture/code-health.md) for the internals.diff --git a/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py b/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.pynew file mode 100644index 000000000..7a00e708a--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/impacted_tests_cmd.py@@ -0,0 +1,284 @@+"""``repowise impacted-tests`` - the tests a change actually exercises.++Given a diff (a ``base..head`` range, a commit, or the staged changes), map+each changed source line to the tests whose recorded coverage touches it, using+the per-test test-to-code map built by ``repowise coverage add``. The output is+"run these N tests, not all N-thousand" - a CI story that needs no agent.++Honest about what it knows:+ - a changed file with per-test coverage -> the exact covering tests;+ - a changed file with no coverage rows -> a filename-pattern *guess* at its+ paired test, clearly labelled as a guess;+ - a new file with neither -> "unknown, run the full suite" (never implied+ as "no tests needed").++Examples:+ repowise impacted-tests # staged changes+ repowise impacted-tests main..HEAD # a branch / PR range+ repowise impacted-tests abc123 # a single commit+ repowise impacted-tests main..HEAD --format list | xargs pytest+"""++from __future__ import annotations++import json++import click+from rich.table import Table++from repowise.cli.helpers import (+ console,+ err_console,+ get_db_url_for_repo,+ resolve_command_target,+ run_async,+ silence_logs_for_machine_output,+)+++def _resolve_repo_path(path: str | None):+ """Resolve the repo path (workspace-aware), mirroring ``coverage``."""+ target = resolve_command_target(path=path)+ target.notice(console, command="impacted-tests")+ if target.is_workspace:+ primary = target.primary_path()+ if primary is None:+ raise click.ClickException("Workspace has no primary repo configured.")+ return primary+ assert target.repo_path is not None+ return target.repo_path++[email protected]("impacted-tests")[email protected]("revspec", required=False)+ "--path", "repo", default=None, help="Repo path (defaults to cwd / workspace primary)."+)+ "--staged",+ is_flag=True,+ help="Diff the staged changes (git diff --cached). The default when no range is given.",+)+ "--format",+ "fmt",+ default="table",+ type=click.Choice(["table", "json", "list"]),+ help="table (human), json (full report), or list (test ids, one per line, for piping).",+)+def impacted_tests_command(revspec: str | None, repo: str | None, staged: bool, fmt: str) -> 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.")++ # json/list go to downstream tools; keep stdout clean of log noise.+ if fmt != "table":+ silence_logs_for_machine_output()++ repo_path = _resolve_repo_path(repo)++ from repowise.core.analysis.changed_lines import changed_lines++ try:+ changed, label = changed_lines(str(repo_path), revspec, staged=staged)+ except ValueError as exc:+ raise click.ClickException(str(exc)) from exc++ result = run_async(_collect(repo_path, changed))+ result["diff"] = label+ _render(result, fmt)+++async def _collect(repo_path, changed: dict[str, set[int]]) -> dict:+ """Resolve changed files to impacted tests + labelled fallbacks."""+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ )+ from repowise.core.persistence.crud import (+ get_health_metrics,+ get_repository_by_path,+ get_test_coverage_summary,+ )++ out = _empty_result(len(changed))+ if not changed:+ return out++ engine = create_engine(get_db_url_for_repo(repo_path))+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ repo_row = await get_repository_by_path(session, str(repo_path))+ if repo_row is None:+ out["no_index"] = True+ return out+ repo_id = repo_row.id++ summary = await get_test_coverage_summary(session, repo_id)+ out["map_empty"] = summary.get("pair_count", 0) == 0++ # Repo file keys back the filename-pattern fallback (same source the+ # aggregate coverage ingest resolves against).+ repo_keys = {m.file_path for m in await get_health_metrics(session, repo_id)}+ await _resolve_impacted(session, repo_id, changed, repo_keys, out)++ return out+++def _empty_result(changed_files: int) -> dict:+ return {+ "no_index": False,+ "map_empty": False,+ "changed_files": changed_files,+ "covered": {}, # test_id -> {test_file, source_files: [...]}+ "guessed": [], # {source_file, test_file}+ "unknown": [], # source_file (no coverage, no paired test)+ }+++async def _resolve_impacted(+ session,+ repo_id: str,+ changed: dict[str, set[int]],+ repo_keys: set[str],+ out: dict,+) -> dict:+ """Classify each changed file: covered tests, guessed test, or unknown.++ Mutates and returns *out*. Split from ``_collect`` (which owns the DB+ bootstrap) so the diff -> lines -> tests path is testable against a seeded+ ``test_coverage`` table.+ """+ from repowise.core.analysis.health.coverage import paired_test_file+ from repowise.core.persistence.crud import tests_covering++ covered: dict[str, dict] = out["covered"]+ for source_file, lines in sorted(changed.items()):+ rows = await tests_covering(session, repo_id, source_file, lines=lines)+ if rows:+ for r in rows:+ entry = covered.setdefault(+ r["test_id"],+ {"test_file": r["test_file"], "source_files": []},+ )+ if source_file not in entry["source_files"]:+ entry["source_files"].append(source_file)+ continue+ # No per-test rows for this file: fall back to a filename guess.+ guess = paired_test_file(source_file, repo_keys)+ if guess:+ out["guessed"].append({"source_file": source_file, "test_file": guess})+ else:+ out["unknown"].append(source_file)+ return out+++def _machine_test_ids(result: dict) -> list[str]:+ """Test ids for --format list: covered node ids + guessed test files."""+ ids = list(result["covered"].keys())+ ids += [g["test_file"] for g in result["guessed"]]+ # Dedup while preserving order.+ seen: set[str] = set()+ return [i for i in ids if not (i in seen or seen.add(i))]+++def _render(result: dict, fmt: str) -> None:+ if fmt == "json":+ click.echo(+ json.dumps(+ {+ "diff": result["diff"],+ "changed_files": result["changed_files"],+ "no_index": result["no_index"],+ "map_empty": result["map_empty"],+ "impacted_tests": [+ {+ "test_id": tid,+ "test_file": info["test_file"],+ "source_files": info["source_files"],+ "via": "coverage",+ }+ for tid, info in result["covered"].items()+ ],+ "guessed_tests": [+ {**g, "via": "filename-pattern-guess"} for g in result["guessed"]+ ],+ "unknown_files": result["unknown"],+ },+ indent=2,+ )+ )+ return++ if fmt == "list":+ # Clean stdout for piping (e.g. `... --format list | xargs pytest`).+ # Caveats (unknown files, empty map) go to stderr so they don't corrupt+ # the piped list but are never silently swallowed.+ for tid in _machine_test_ids(result):+ click.echo(tid)+ if result["no_index"]:+ err_console.print("[yellow]No index - run `repowise init`.[/yellow]")+ elif result["unknown"]:+ err_console.print(+ f"[yellow]{len(result['unknown'])} changed file(s) have no coverage and "+ f"no paired test; run the full suite to be safe.[/yellow]"+ )+ return++ _render_table(result)+++def _render_table(result: dict) -> None:+ if result["no_index"]:+ console.print("[yellow]No index yet - run `repowise init` first.[/yellow]")+ return++ console.print(f"[bold]Impacted tests[/bold] for [cyan]{result['diff']}[/cyan]")++ if result["changed_files"] == 0:+ console.print("[dim]No changed source lines in this diff.[/dim]")+ return++ if result["map_empty"]:+ console.print(+ "[yellow]No test-to-code map ingested.[/yellow] Run "+ "[cyan]repowise coverage add[/cyan] on a coverage.py report written with "+ "[cyan]coverage run --contexts=test[/cyan] to get exact impacted tests. "+ "Falling back to filename-pattern guesses below."+ )++ covered = result["covered"]+ if covered:+ table = Table(title="Tests covering the changed lines")+ table.add_column("Test", style="green")+ table.add_column("Changed file(s) it covers")+ for tid, info in sorted(covered.items()):+ table.add_row(tid, "\n".join(info["source_files"]))+ console.print(table)+ console.print(+ f"[green]{len(covered)} test(s)[/green] directly cover the change "+ "(via recorded per-test coverage)."+ )+ elif not result["map_empty"]:+ console.print("[dim]No recorded test covers the changed lines directly.[/dim]")++ if result["guessed"]:+ gtable = Table(title="Filename-pattern guesses (NOT coverage-backed)")+ gtable.add_column("Changed file")+ gtable.add_column("Guessed test", style="yellow")+ for g in result["guessed"]:+ gtable.add_row(g["source_file"], g["test_file"])+ console.print(gtable)+ console.print(+ f"[yellow]{len(result['guessed'])} file(s)[/yellow] had no coverage; guessed "+ "their test by filename. Verify these actually exercise the change."+ )++ if result["unknown"]:+ console.print(+ f"[red]{len(result['unknown'])} changed file(s)[/red] have no coverage and no "+ "paired test - run the full suite to be safe:"+ )+ for path in result["unknown"]:+ console.print(f" [red]{path}[/red]")diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex ba3e70fc3..32eaedc90 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -20,6 +20,7 @@ from repowise.cli.commands.expand_cmd import expand_commandfrom repowise.cli.commands.export_cmd import export_commandfrom repowise.cli.commands.health_cmd import health_commandfrom repowise.cli.commands.hook_cmd import hook_group+from repowise.cli.commands.impacted_tests_cmd import impacted_tests_commandfrom repowise.cli.commands.init_cmd import init_commandfrom repowise.cli.commands.login_cmd import login_command, logout_command, whoami_commandfrom repowise.cli.commands.mcp_cmd import mcp_command@@ -71,6 +72,7 @@ register_command(health_command)register_command(risk_command)register_command(decision_group)register_command(coverage_group)+register_command(impacted_tests_command)register_command(search_command)register_command(distill_command)register_command(expand_command)diff --git a/packages/core/src/repowise/core/analysis/changed_lines.py b/packages/core/src/repowise/core/analysis/changed_lines.pynew file mode 100644index 000000000..12481b5f5--- /dev/null+++ b/packages/core/src/repowise/core/analysis/changed_lines.py@@ -0,0 +1,90 @@+"""Map a git change to the source lines it touches, per file.++``repowise risk`` reads a change as aggregate counts (``--numstat``); the+test-impact query needs the actual changed *line numbers* so it can intersect+them with per-test coverage. This module parses a ``--unified=0`` diff into+``{file: {line, ...}}`` over the *new* side of the change - the lines that+exist in the head/index/working tree, which is the space coverage is keyed in.++Pure ``git`` subprocess walking, reusing the wrapper from the change-risk+feature extractor (no new dependency, deterministic).+"""++from __future__ import annotations++import re++from .change_risk.features import _git++# New-side hunk header: ``@@ -a,b +c,d @@`` -> we only care about ``+c,d``+# (the lines present after the change). ``d`` defaults to 1 when omitted.+_HUNK_RE = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@")+++def _parse_unified_diff(diff: str) -> dict[str, set[int]]:+ """Parse ``git diff --unified=0`` into new-side changed lines per file."""+ result: dict[str, set[int]] = {}+ current: str | None = None+ for line in diff.splitlines():+ if line.startswith("+++ "):+ path = line[4:].strip()+ # git quotes paths with special chars ("b/pa\tth"); strip the quotes+ # so the common (unquoted) key still resolves. Rare enough to accept+ # the imperfect unescaping.+ if len(path) >= 2 and path[0] == '"' and path[-1] == '"':+ path = path[1:-1]+ if path == "/dev/null": # file deleted - nothing on the new side+ current = None+ continue+ if path.startswith("b/"):+ path = path[2:]+ current = path+ result.setdefault(current, set())+ elif current is not None and line.startswith("@@"):+ m = _HUNK_RE.match(line)+ if not m:+ continue+ start = int(m.group(1))+ count = int(m.group(2)) if m.group(2) is not None else 1+ result[current].update(range(start, start + count))+ # Drop files whose only change was a deletion (no new-side lines): they+ # cannot intersect coverage, and would otherwise read as "touched".+ return {path: lines for path, lines in result.items() if lines}+++def _verify_ref(repo_path: str, ref: str) -> None:+ if not _git(["rev-parse", "--verify", "--quiet", ref], repo_path).strip():+ raise ValueError(f"unknown revision {ref!r}")+++def changed_lines(+ repo_path: str,+ revspec: str | None = None,+ *,+ staged: bool = False,+) -> tuple[dict[str, set[int]], str]:+ """Return ``({file: changed_lines}, label)`` for a change.++ *revspec* mirrors ``repowise risk``: ``base..head`` is a range, a bare ref+ is a single commit. With no *revspec* (or *staged*), the staged diff+ (``git diff --cached``) is used - the "what will I commit" case. *label*+ is a human string naming what was diffed. Raises ``ValueError`` on an+ unknown revision so the caller can fail loudly rather than silently+ reporting "no changes".+ """+ if staged or not revspec:+ diff = _git(["diff", "--cached", "--unified=0"], repo_path)+ return _parse_unified_diff(diff), "staged changes"++ if ".." in revspec:+ base, _, head = revspec.partition("..")+ head = head or "HEAD"+ _verify_ref(repo_path, base)+ _verify_ref(repo_path, head)+ diff = _git(["diff", "--unified=0", f"{base}..{head}"], repo_path)+ return _parse_unified_diff(diff), f"{base}..{head}"++ _verify_ref(repo_path, revspec)+ # --format= drops the commit message so only the diff body is parsed.+ diff = _git(["show", "--unified=0", "--format=", revspec], repo_path)+ return _parse_unified_diff(diff), revspecdiff --git a/tests/unit/analysis/test_changed_lines.py b/tests/unit/analysis/test_changed_lines.pynew file mode 100644index 000000000..01d2f8f6d--- /dev/null+++ b/tests/unit/analysis/test_changed_lines.py@@ -0,0 +1,114 @@+"""Diff -> changed-line parsing for ``repowise impacted-tests``.++The pure parser is exercised on hand-written unified diffs (no git needed);+:func:`changed_lines` is exercised end-to-end against a real temp git repo so+the range / commit / staged revspec handling is covered too.+"""++from __future__ import annotations++import subprocess++import pytest++from repowise.core.analysis.changed_lines import _parse_unified_diff, changed_lines+++def test_parse_single_hunk_new_side_lines() -> None:+ diff = (+ "diff --git a/src/foo.py b/src/foo.py\n"+ "index 111..222 100644\n"+ "--- a/src/foo.py\n"+ "+++ b/src/foo.py\n"+ "@@ -10,0 +11,3 @@\n"+ "+one\n"+ "+two\n"+ "+three\n"+ )+ assert _parse_unified_diff(diff) == {"src/foo.py": {11, 12, 13}}+++def test_parse_hunk_without_count_defaults_to_one() -> None:+ diff = "--- a/x.py\n+++ b/x.py\n@@ -4 +4 @@\n-old\n+new\n"+ assert _parse_unified_diff(diff) == {"x.py": {4}}+++def test_parse_pure_deletion_yields_no_file() -> None:+ # ``+7,0`` = nothing on the new side; the file must not appear.+ diff = "--- a/gone.py\n+++ b/gone.py\n@@ -7,2 +7,0 @@\n-a\n-b\n"+ assert _parse_unified_diff(diff) == {}+++def test_parse_deleted_file_skipped() -> None:+ diff = "--- a/dead.py\n+++ /dev/null\n@@ -1,2 +0,0 @@\n-a\n-b\n"+ assert _parse_unified_diff(diff) == {}+++def test_parse_multiple_files_and_hunks() -> None:+ diff = (+ "--- a/a.py\n+++ b/a.py\n"+ "@@ -1 +1 @@\n-x\n+x2\n"+ "@@ -5,0 +6,2 @@\n+n1\n+n2\n"+ "--- a/b.py\n+++ b/b.py\n"+ "@@ -3,0 +4,1 @@\n+only\n"+ )+ assert _parse_unified_diff(diff) == {"a.py": {1, 6, 7}, "b.py": {4}}+++# --- end-to-end against a real git repo -----------------------------------+++def _git(cwd, *args: str) -> None:+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)+++def git_repo(tmp_path):+ _git(tmp_path, "init", "-q")+ _git(tmp_path, "config", "user.email", "[email protected]")+ _git(tmp_path, "config", "user.name", "t")+ f = tmp_path / "mod.py"+ f.write_text("a = 1\nb = 2\nc = 3\n", encoding="utf-8")+ _git(tmp_path, "add", "-A")+ _git(tmp_path, "commit", "-qm", "init")+ return tmp_path+++def test_changed_lines_range(git_repo) -> None:+ (git_repo / "mod.py").write_text("a = 1\nb = 22\nc = 3\nd = 4\n", encoding="utf-8")+ _git(git_repo, "add", "-A")+ _git(git_repo, "commit", "-qm", "edit")++ changed, label = changed_lines(str(git_repo), "HEAD~1..HEAD")+ assert label == "HEAD~1..HEAD"+ # Line 2 modified, line 4 added.+ assert changed == {"mod.py": {2, 4}}+++def test_changed_lines_single_commit(git_repo) -> None:+ (git_repo / "mod.py").write_text("a = 1\nb = 2\nc = 3\ne = 5\n", encoding="utf-8")+ _git(git_repo, "add", "-A")+ _git(git_repo, "commit", "-qm", "add line")++ changed, label = changed_lines(str(git_repo), "HEAD")+ assert label == "HEAD"+ assert changed == {"mod.py": {4}}+++def test_changed_lines_staged(git_repo) -> None:+ (git_repo / "mod.py").write_text("a = 1\nb = 2\nc = 3\nf = 6\n", encoding="utf-8")+ _git(git_repo, "add", "-A") # stage, do not commit++ changed, label = changed_lines(str(git_repo))+ assert label == "staged changes"+ assert changed == {"mod.py": {4}}++ # Explicit --staged is the same as the no-arg default.+ assert changed_lines(str(git_repo), staged=True)[0] == {"mod.py": {4}}+++def test_changed_lines_unknown_revision_raises(git_repo) -> None:+ with pytest.raises(ValueError):+ changed_lines(str(git_repo), "nope123..HEAD")+ with pytest.raises(ValueError):+ changed_lines(str(git_repo), "deadbeef")diff --git a/tests/unit/persistence/test_impacted_tests_resolution.py b/tests/unit/persistence/test_impacted_tests_resolution.pynew file mode 100644index 000000000..9691e9200--- /dev/null+++ b/tests/unit/persistence/test_impacted_tests_resolution.py@@ -0,0 +1,96 @@+"""The ``impacted-tests`` resolution path: changed lines -> impacted tests.++Exercises :func:`_resolve_impacted` against a seeded ``test_coverage`` table so+the three honest outcomes are pinned: coverage-backed hit, filename-pattern+guess when a changed file has no coverage rows, and "unknown" when it has+neither. The diff parser and CRUD line-intersection are tested separately.+"""++from __future__ import annotations++from repowise.cli.commands.impacted_tests_cmd import _empty_result, _resolve_impacted+from repowise.core.analysis.health.coverage import TestCoverage+from repowise.core.persistence.crud import save_test_coverage+from tests.unit.persistence.helpers import insert_repo++# Repo tree the filename-pattern fallback resolves guesses against.+_REPO_KEYS = {+ "src/foo.py",+ "src/bar.py",+ "src/lonely.py",+ "tests/test_bar.py",+}+++def _rec(test_id: str, source_file: str, lines: list[int], test_file: str):+ return TestCoverage(+ test_id=test_id,+ file_path=source_file,+ covered_lines=lines,+ source_format="coverage.py",+ test_file=test_file,+ )+++async def _seed(async_session):+ repo = await insert_repo(async_session)+ await save_test_coverage(+ async_session,+ repo.id,+ [+ _rec("tests/test_foo.py::test_a|run", "src/foo.py", [1, 2, 3], "tests/test_foo.py"),+ _rec("tests/test_foo.py::test_b|run", "src/foo.py", [8, 9], "tests/test_foo.py"),+ ],+ source_format="coverage.py",+ )+ await async_session.commit()+ return repo+++async def test_covered_change_returns_exact_tests(async_session) -> None:+ repo = await _seed(async_session)+ out = _empty_result(1)+ await _resolve_impacted(async_session, repo.id, {"src/foo.py": {2}}, _REPO_KEYS, out)++ assert set(out["covered"]) == {"tests/test_foo.py::test_a|run"}+ assert out["covered"]["tests/test_foo.py::test_a|run"]["source_files"] == ["src/foo.py"]+ assert out["guessed"] == []+ assert out["unknown"] == []+++async def test_change_missing_covered_lines_falls_to_guess_or_unknown(async_session) -> None:+ repo = await _seed(async_session)+ out = _empty_result(3)+ # foo.py line 99 has no covering test; bar.py has no coverage at all but a+ # paired test; lonely.py has neither coverage nor a paired test.+ changed = {"src/foo.py": {99}, "src/bar.py": {5}, "src/lonely.py": {1}}+ await _resolve_impacted(async_session, repo.id, changed, _REPO_KEYS, out)++ # foo.py: had rows for the file but none intersect line 99 -> guessed (no+ # test_foo.py in repo keys, so it should look for foo's pair). foo's pair+ # (test_foo.py) is NOT in _REPO_KEYS, so foo.py lands in unknown.+ assert "src/foo.py" in out["unknown"]+ assert "src/lonely.py" in out["unknown"]+ assert out["guessed"] == [{"source_file": "src/bar.py", "test_file": "tests/test_bar.py"}]+ assert out["covered"] == {}+++async def test_one_test_covering_multiple_changed_files_dedupes(async_session) -> None:+ repo = await insert_repo(async_session)+ await save_test_coverage(+ async_session,+ repo.id,+ [+ _rec("t::shared|run", "src/foo.py", [1], "tests/t.py"),+ _rec("t::shared|run", "src/bar.py", [2], "tests/t.py"),+ ],+ source_format="coverage.py",+ )+ await async_session.commit()++ out = _empty_result(2)+ await _resolve_impacted(+ async_session, repo.id, {"src/foo.py": {1}, "src/bar.py": {2}}, _REPO_KEYS, out+ )+ assert set(out["covered"]) == {"t::shared|run"}+ assert sorted(out["covered"]["t::shared|run"]["source_files"]) == ["src/bar.py", "src/foo.py"]