Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(workspace): cross-repo test impact analysis (#2006) (#2008)

Soumojit Das0e8c5c6f6995
diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.md
index e7dec5563..7ce03d4bb 100644
--- a/docs/scale/WORKSPACES.md
+++ b/docs/scale/WORKSPACES.md
@@ -198,6 +198,16 @@ repowise workspace metrics # human-readable summary
repowise workspace metrics --json # raw metrics JSON
```
+### `repowise workspace impacted-tests <repo:path>...`
+
+Given one or more changed provider files, list the tests in consumer repos worth running. See [Cross-Repo Test Impact](#cross-repo-test-impact).
+
+```bash
+repowise workspace impacted-tests backend:app/routers/users.py
+repowise workspace impacted-tests backend:app/routers/users.py --target-repo frontend --format list | cut -d: -f2- | xargs npx vitest run
+repowise workspace impacted-tests backend:app/routers/users.py --format json
+```
+
---
## Cross-Repo Intelligence
@@ -402,6 +412,29 @@ Use it three ways:
---
+## Cross-Repo Test Impact
+
+Where the breaking-change guard answers *did this change break a consumer*, test impact answers the question you ask before you push: **I changed this provider file, which tests in the other repos should I run?** It starts from the matched contract links, so the answer is scoped to the consumers that actually call the changed code, and then walks each consumer's own index to find the tests that exercise the call site.
+
+```bash
+repowise workspace impacted-tests backend:app/routers/users.py
+```
+
+Three output formats: `table` (the default, grouped by consumer repo), `json` (the full result, including the counts below), and `list` (one `repo:test-file` per line, for piping into a test runner).
+
+Every consumer call site the walk considers ends in one of four states, and the command names the one it landed on:
+
+- **measured**, a coverage map ingested from that repo says the test actually ran the consumer code. The strongest evidence, and it only exists where coverage has been ingested.
+- **inferred**, no coverage, but the consumer's call graph or import graph reaches the call site from a test. The call graph is entered at the *symbol* the contract bound to, not the file, so a test that reaches an unrelated function in the same file is not recommended. The import fallback only knows files, so it is entered at the file; every row says which it was, in the `entry` field of its evidence.
+- **none**, the consumer was analyzed and nothing reaches the call site. A real answer, not a failure: that code has no test guarding it.
+- **unresolved**, the join could not determine an answer. Four causes, each reported by name: the consumer repo has no index, the contract never bound to a symbol, the bound symbol is no longer in the index, or the lookup itself failed.
+
+An empty answer always says which of these produced it, so "no tests" is never ambiguous between "nothing guards this" and "we could not look". That holds in every format: the `table` format prints a `Could not determine` table listing the unresolved links with their reason, `json` carries the states and the unresolved rows, and `list` writes the explanation and the unresolved count to stderr so the piped list on stdout stays clean.
+
+Results are capped per consumer and provider pair so one widely-called helper cannot flood the list; when the cap bites, the command prints how many it dropped and `--format json` carries the exact counts.
+
+---
+
## Architecture Conformance
Workspaces let you declare, in `.repowise-workspace.yaml`, which services are *allowed* to depend on which others, and then continuously check the live system graph against those rules. This is your team's **architecture lint**: the intended architecture, expressed as code, verified on every update.
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd.py b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
index 83232e46b..daab3ce52 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
@@ -1432,3 +1432,250 @@ def workspace_metrics(path: str | None, fmt: str, as_json: bool) -> None:
}
parts = ", ".join(f"{role_labels[r]} {breakdown.get(r, 0)}" for r in role_labels)
console.print(f"\n Service roles: {parts}")
+
+
+# ---------------------------------------------------------------------------
+# workspace impacted-tests
+# ---------------------------------------------------------------------------
+
+
+_UNRESOLVED_REASONS = {
+ "no_index": "consumer has no index",
+ "unbound": "contract never bound to a symbol",
+ "symbol_missing": "bound symbol is not in the index",
+}
+
+_EMPTY_REASONS = {
+ "no_contract_store": "there is no contract map yet; run 'repowise update --workspace'",
+ "no_matching_links": "no contract link connects the changed files to a consumer",
+ "no_changed_files": "no changed files were given",
+}
+
+
+def _unresolved_reason_text(reason: str, detail: str | None) -> str:
+ """Plain words for why a contract link could not be followed."""
+ if reason == "lookup_failed":
+ return f"lookup failed ({detail or 'unknown'})"
+ return _UNRESOLVED_REASONS.get(reason, reason)
+
+
+def _empty_explanation(result: object) -> str:
+ """Say which state produced an empty answer, never just that it is empty."""
+ summary = getattr(result, "summary", {}) or {}
+ reason = summary.get("reason")
+ if reason:
+ return f"No tests found: {_EMPTY_REASONS.get(reason, reason)}."
+ parts = []
+ reached_nothing = (summary.get("states") or {}).get("none", 0)
+ if reached_nothing:
+ parts.append(f"{reached_nothing} consumer file(s) the requested passes found nothing for")
+ unresolved = len(getattr(result, "unresolved", []) or [])
+ if unresolved:
+ parts.append(f"{unresolved} link(s) could not be determined")
+ passes = summary.get("passes") or {}
+ disabled = [name for name in ("measured", "inferred") if passes.get(name) is False]
+ suffix = "".join(f" ({name} pass disabled)" for name in disabled)
+ if not parts:
+ return f"No tests found: no consumer call site was analysed.{suffix}"
+ return f"No tests found: {', '.join(parts)}.{suffix}"
+
+
+@workspace_group.command("impacted-tests")
[email protected]("changed_files", required=True, nargs=-1)
+ "--path",
+ "workspace_path",
+ default=None,
+ help="Path to workspace root (default: auto-detect from cwd).",
+)
+ "--call-depth",
+ default=3,
+ type=click.IntRange(1, 8),
+ help="Call graph walk depth (default: 3).",
+)
+ "--import-depth",
+ default=1,
+ type=click.IntRange(1, 3),
+ help="Import graph fallback depth (default: 1).",
+)
+ "--no-measured",
+ is_flag=True,
+ help="Exclude measured coverage-backed recommendations.",
+)
+ "--no-inferred",
+ is_flag=True,
+ help="Exclude graph-inferred recommendations.",
+)
+ "--min-confidence",
+ default=0.0,
+ type=click.FloatRange(0.0, 1.0),
+ help="Minimum contract link confidence to consider (0.0-1.0).",
+)
+ "--target-repo",
+ "target_repos",
+ multiple=True,
+ help="Limit analysis to these consumer repo aliases. Repeatable.",
+)
+@format_option(choices=("table", "json", "list"))
+@json_option()
+def workspace_impacted_tests(
+ changed_files: tuple[str, ...],
+ workspace_path: str | None,
+ call_depth: int,
+ import_depth: int,
+ no_measured: bool,
+ no_inferred: bool,
+ min_confidence: float,
+ target_repos: tuple[str, ...],
+ fmt: str,
+ as_json: bool,
+) -> None:
+ """Cross-repository test impact: which downstream tests to run.
+
+ Given a list of changed files in provider repositories (format: repo:path),
+ returns the test files in consumer repositories that cover those changes,
+ via measured per-test coverage, call-graph reachability, and import-graph
+ fallback.
+
+ Example:
+ repowise workspace impacted-tests backend-api:src/api/users.py
+
+ Output format:
+ - table (default): human-readable grouped by consumer repo
+ - json: full machine-readable result
+ - list: one repo:path line per test file
+ """
+ configure_cli_logging()
+ fmt = resolve_format(fmt, as_json)
+
+ if not changed_files:
+ raise click.ClickException(
+ "At least one changed file required. Format: repo_alias:path/to/file.py"
+ )
+
+ # Parse changed_files
+ parsed_changed: list[dict[str, str]] = []
+ for cf in changed_files:
+ if ":" not in cf:
+ raise click.ClickException(
+ f"Invalid format: {cf}. Use repo_alias:path/to/file.py"
+ )
+ repo, path = cf.split(":", 1)
+ parsed_changed.append({"repo": repo, "path": path})
+
+ start = resolve_repo_path(workspace_path)
+ ws_root, _ = _require_workspace(start)
+
+ from repowise.core.workspace.test_impact import (
+ MAX_TESTS_PER_TARGET,
+ workspace_test_impact_from_root,
+ workspace_test_impact_to_dict,
+ )
+
+ result = run_async(
+ workspace_test_impact_from_root(
+ ws_root,
+ parsed_changed,
+ call_depth=call_depth,
+ import_depth=import_depth,
+ include_measured=not no_measured,
+ include_inferred=not no_inferred,
+ min_confidence=min_confidence,
+ target_repos=list(target_repos) if target_repos else None,
+ )
+ )
+
+ if fmt == "json":
+ emit_json(workspace_test_impact_to_dict(result))
+ return
+
+ if fmt == "list":
+ # Output test file paths only, one per line
+ seen: set[str] = set()
+ for rec in result.recommendations:
+ key = f"{rec.consumer_repo}:{rec.test_file}"
+ if key not in seen:
+ seen.add(key)
+ click.echo(key)
+ if not seen:
+ # A pipeline reading stdout must never get silence with exit 0.
+ click.echo(_empty_explanation(result), err=True)
+ if result.unresolved:
+ click.echo(
+ f"{len(result.unresolved)} contract link(s) could not be determined; "
+ "run with --format table to see why.",
+ err=True,
+ )
+ return
+
+ # Group by consumer repo
+ by_consumer: dict[str, list] = {}
+ for rec in result.recommendations:
+ by_consumer.setdefault(rec.consumer_repo, []).append(rec)
+
+ console.print(f"[bold]Workspace test impact[/bold] for {len(parsed_changed)} changed file(s):")
+ for item in parsed_changed:
+ console.print(f" [dim]{item['repo']}:{item['path']}[/dim]")
+
+ for consumer_repo, recs in sorted(by_consumer.items()):
+ table = Table(title=f"Consumer: {consumer_repo}")
+ table.add_column("Test File", style="green")
+ table.add_column("Basis", style="yellow")
+ table.add_column("Via", style="dim")
+ table.add_column("Provider Repo", style="cyan")
+ table.add_column("Provider Files", style="dim")
+ table.add_column("Contract", style="dim")
+ table.add_column("Confidence", justify="right")
+
+ for rec in recs:
+ table.add_row(
+ rec.test_file,
+ rec.basis,
+ rec.via,
+ rec.provider_repo,
+ ", ".join(rec.source_files),
+ ", ".join(rec.contract_ids),
+ f"{rec.confidence:.2f}",
+ )
+ console.print(table)
+
+ if result.unresolved:
+ unresolved_table = Table(title="Could not determine")
+ unresolved_table.add_column("Consumer", style="cyan")
+ unresolved_table.add_column("File", style="dim")
+ unresolved_table.add_column("Contract", style="dim")
+ unresolved_table.add_column("Reason", style="yellow")
+ for link in result.unresolved:
+ unresolved_table.add_row(
+ link.consumer_repo,
+ link.consumer_file,
+ link.contract_id,
+ _unresolved_reason_text(link.reason, link.detail),
+ )
+ console.print(unresolved_table)
+
+ if result.recommendations_emitted == 0:
+ console.print(f"[yellow]{_empty_explanation(result)}[/yellow]")
+ return
+
+ by_basis = result.recommendations_by_basis
+ console.print(
+ f"\n[bold]{result.recommendations_emitted}[/bold] test recommendation(s) across "
+ f"[bold]{len(by_consumer)}[/bold] consumer repo(s):"
+ )
+ if by_basis.get("measured", 0):
+ console.print(f" [green]{by_basis['measured']}[/green] from measured coverage")
+ if by_basis.get("inferred", 0):
+ console.print(f" [yellow]{by_basis['inferred']}[/yellow] inferred from call/import graph")
+ if result.recommendations_truncated:
+ console.print(
+ f" [dim]{result.recommendations_omitted} more omitted "
+ f"(cap {MAX_TESTS_PER_TARGET} per consumer and provider pair); "
+ f"use --format json for counts.[/dim]"
+ )
diff --git a/packages/core/src/repowise/core/analysis/test_reachability.py b/packages/core/src/repowise/core/analysis/test_reachability.py
index 216b11132..6ca9f19cd 100644
--- a/packages/core/src/repowise/core/analysis/test_reachability.py
+++ b/packages/core/src/repowise/core/analysis/test_reachability.py
@@ -148,6 +148,7 @@ over data already in the database.
from __future__ import annotations
import json
+from collections.abc import Collection, Mapping
from dataclasses import dataclass
from typing import Any, Literal, TypeAlias
@@ -346,9 +347,16 @@ async def tests_reaching_by_tier(
*,
call_depth: int = DEFAULT_CALL_DEPTH,
import_depth: int = DEFAULT_MAX_DEPTH,
+ symbol_seeds: Mapping[str, Collection[str]] | None = None,
) -> dict[str, ReachedBy]:
""":func:`tests_reaching`, also saying which tier answered each target.
+ *symbol_seeds* narrows the call walk for the targets it names: the walk
+ enters at exactly those symbol ids instead of at every symbol the file
+ declares. A target it does not name, or names with no ids, keeps the
+ ``defines`` lookup, and the
+ import tier stays file-level either way.
+
The call walk runs first; the import walk is then seeded with only the
targets it left unanswered, so the weaker tier never speaks over the
stronger one and costs nothing where the stronger one already spoke.
@@ -371,7 +379,9 @@ async def tests_reaching_by_tier(
out: dict[str, ReachedBy] = {}
if call_depth >= 1:
- found = await _call_reaching(session, repo_id, seeds, test_files, call_depth)
+ found = await _call_reaching(
+ session, repo_id, seeds, test_files, call_depth, symbol_seeds=symbol_seeds
+ )
for seed, tests in found.items():
ordered = tuple(sorted(tests))
out[seed] = ReachedBy(
@@ -395,6 +405,8 @@ async def _call_reaching(
seeds: list[str],
test_files: set[str],
max_depth: int,
+ *,
+ symbol_seeds: Mapping[str, Collection[str]] | None = None,
) -> dict[str, set[str]]:
"""Tests that can execute into each seed file, walking call edges backwards.
@@ -402,10 +414,24 @@ async def _call_reaching(
join symbols, so the first query resolves each seed to the symbols it
declares, and the walk carries the seed from there.
"""
- declared = await _edges_from(session, repo_id, seeds, ["defines"])
origins: dict[str, set[str]] = {}
- for seed, symbol in declared:
- origins.setdefault(symbol, set()).add(seed)
+ # A caller that knows which symbol in the file it cares about enters there,
+ # so a test reaching an unrelated symbol in the same file does not count.
+ # An empty entry names no symbol, so that file is unseeded and keeps the
+ # ``defines`` lookup; treating it as seeded would silence the file entirely.
+ seeded = {
+ seed: symbol_seeds[seed]
+ for seed in seeds
+ if symbol_seeds and symbol_seeds.get(seed)
+ }
+ for seed, symbol_ids in seeded.items():
+ for symbol in symbol_ids:
+ origins.setdefault(symbol, set()).add(seed)
+ unseeded = [seed for seed in seeds if seed not in seeded]
+ if unseeded:
+ declared = await _edges_from(session, repo_id, unseeded, ["defines"])
+ for seed, symbol in declared:
+ origins.setdefault(symbol, set()).add(seed)
if not origins:
return {}
diff --git a/packages/core/src/repowise/core/workspace/repo_index.py b/packages/core/src/repowise/core/workspace/repo_index.py
index 07efe322e..8ef88d0e2 100644
--- a/packages/core/src/repowise/core/workspace/repo_index.py
+++ b/packages/core/src/repowise/core/workspace/repo_index.py
@@ -24,6 +24,7 @@ from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
+ from collections.abc import Collection
from pathlib import Path
from sqlalchemy.ext.asyncio import AsyncSession
@@ -83,9 +84,19 @@ class RepoIndex:
dialect may call one from the worker thread it runs in.
"""
- def __init__(self, alias: str, repo_path: Path, session: AsyncSession, engine: Any) -> None:
+ def __init__(
+ self,
+ alias: str,
+ repo_path: Path,
+ session: AsyncSession,
+ engine: Any,
+ *,
+ # Required: an empty id makes every repository-scoped query return nothing.
+ repo_id: str,
+ ) -> None:
self.alias = alias
self.repo_path = repo_path
+ self.repo_id = repo_id
self._session = session
self._engine = engine
self._by_file: dict[str, list[IndexedSymbol]] = {}
@@ -165,6 +176,11 @@ class RepoIndex:
# -- Public API --------------------------------------------------------
+ @property
+ def session(self) -> AsyncSession:
+ """The connection the index holds; reachability queries run on it too."""
+ return self._session
+
def symbols_for_file(self, rel_path: str) -> list[IndexedSymbol]:
"""Symbols declared in *rel_path* (POSIX, repo-relative), outermost first."""
return self._by_file.get(rel_path, [])
@@ -292,7 +308,7 @@ async def open_repo_index(alias: str, repo_path: Path) -> RepoIndex | None:
).scalar_one_or_none()
if repo is None:
raise LookupError(f"No repository row in {repo_path}")
- index = RepoIndex(alias, repo_path, session, engine)
+ index = RepoIndex(alias, repo_path, session, engine, repo_id=repo.id)
await index._load(repo.id)
ok = True
finally:
@@ -304,9 +320,17 @@ async def open_repo_index(alias: str, repo_path: Path) -> RepoIndex | None:
return index
-async def open_workspace_index(ws_config: Any, workspace_root: Path) -> WorkspaceIndex:
- """Open every indexed repo in the workspace. A repo that fails is skipped."""
- entries = list(ws_config.repos)
+async def open_workspace_index(
+ ws_config: Any,
+ workspace_root: Path,
+ *,
+ aliases: Collection[str] | None = None,
+) -> WorkspaceIndex:
+ """Open every indexed repo in the workspace. A repo that fails is skipped.
+
+ *aliases*, when given, restricts the open to those repos.
+ """
+ entries = [e for e in ws_config.repos if aliases is None or e.alias in aliases]
opened = await asyncio.gather(
*(
open_repo_index(e.alias, (workspace_root / e.path).resolve())
diff --git a/packages/core/src/repowise/core/workspace/test_impact.py b/packages/core/src/repowise/core/workspace/test_impact.py
new file mode 100644
index 000000000..79f096b65
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/test_impact.py
@@ -0,0 +1,623 @@
+"""Cross-repository test impact: which consumer tests guard a provider change.
+
+Joins the workspace contract map (provider call site -> consumer call site)
+with each consumer repo's test reachability, to answer "given a change in
+provider repo X, which tests in consumer repos Y and Z should I run?".
+
+The join enters the consumer's call graph at the contract's
+``consumer_symbol_id`` instead of at the consumer file, so a test that reaches
+an unrelated symbol in the same file is not recommended. A link that cannot be
+followed is reported as an unresolved row with a reason, never dropped: an
+empty answer always says which state produced it.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from collections import defaultdict
+from dataclasses import dataclass, field, replace
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from repowise.core.analysis.test_reachability import (
+ DEFAULT_CALL_DEPTH,
+ DEFAULT_MAX_DEPTH,
+ MAX_TESTS_PER_TARGET,
+ tests_reaching_by_tier,
+)
+from repowise.core.persistence.crud.analysis.coverage_map import tests_covering_files
+from repowise.core.workspace.config import WorkspaceConfig
+from repowise.core.workspace.contracts import ContractLink, load_contract_store
+from repowise.core.workspace.repo_index import WorkspaceIndex, open_workspace_index
+
+if TYPE_CHECKING:
+ from collections.abc import Collection, Mapping, Sequence
+
+ from repowise.core.workspace.repo_index import RepoIndex
+
+_BASIS_ORDER = {"measured": 0, "inferred": 1}
+
+_TIER_PRIORITY = {"call-graph": 0, "import-graph": 1}
+
+# The call walk enters at the bound symbol; the import fallback only knows files.
+_ENTRY_BY_TIER = {"call-graph": "symbol", "import-graph": "file"}
+
+__all__ = [
+ "MAX_TESTS_PER_TARGET",
+ "UnresolvedLink",
+ "WorkspaceTestImpactResult",
+ "WorkspaceTestRecommendation",
+ "analyze_workspace_test_impact",
+ "workspace_test_impact_from_root",
+ "workspace_test_impact_to_dict",
+]
+
+
+@dataclass(frozen=True)
+class WorkspaceTestRecommendation:
+ """A test in a consumer repo that guards a changed provider file."""
+
+ test_id: str
+ test_file: str
+ consumer_repo: str
+ consumer_file: str
+ consumer_symbol_id: str | None
+ provider_repo: str
+ contract_ids: list[str]
+ contract_types: list[str]
+ basis: str # "measured" | "inferred"
+ via: str # "coverage-map" | "call-graph" | "import-graph"
+ confidence: float
+ source_files: list[str]
+ evidence: list[dict[str, Any]]
+
+
+@dataclass(frozen=True)
+class UnresolvedLink:
+ """A contract link the join could not follow, and why."""
+
+ consumer_repo: str
+ consumer_file: str
+ consumer_symbol_id: str | None
+ provider_repo: str
+ provider_file: str
+ contract_id: str
+ contract_type: str
+ reason: str # "no_index" | "unbound" | "symbol_missing" | "lookup_failed"
+ detail: str | None = None
+
+
+@dataclass
+class WorkspaceTestImpactResult:
+ """Recommendations, the links that could not be followed, and the counts."""
+
+ workspace: bool = True
+ recommendations: list[WorkspaceTestRecommendation] = field(default_factory=list)
+ recommendations_total: int = 0
+ recommendations_emitted: int = 0
+ recommendations_truncated: bool = False
+ recommendations_omitted: int = 0
+ recommendations_by_basis: dict[str, int] = field(
+ default_factory=lambda: {"measured": 0, "inferred": 0}
+ )
+ recommendations_by_repo: dict[str, int] = field(default_factory=dict)
+ recommendations_by_consumer_repo: dict[str, int] = field(default_factory=dict)
+ unresolved: list[UnresolvedLink] = field(default_factory=list)
+ files_analyzed: list[dict[str, Any]] = field(default_factory=list)
+ summary: dict[str, Any] = field(default_factory=dict)
+
+
+def _norm(path: str) -> str:
+ """One comparable spelling of a repo-relative path."""
+ cleaned = (path or "").replace("\\", "/")
+ while cleaned.startswith("./"):
+ cleaned = cleaned[2:]
+ return cleaned
+
+
+def _internal_call(link: ContractLink) -> bool:
+ """Mirror of ``contracts._same_repo_same_service``, which takes Contracts.
+
+ A provider and consumer in the same repo and the same service boundary are
+ one program calling itself, not a cross-repo contract.
+ """
+ return link.provider_repo == link.consumer_repo and (
+ link.provider_service == link.consumer_service
+ )
+
+
+def _recommendation_sort_key(rec: WorkspaceTestRecommendation) -> tuple:
+ """More source files first, then measured over inferred, then repo and id."""
+ return (
+ -len(rec.source_files),
+ _BASIS_ORDER.get(rec.basis, 99),
+ _TIER_PRIORITY.get(rec.via, 99),
+ rec.consumer_repo,
+ rec.test_id,
+ )
+
+
+def _signal_rank(rec: WorkspaceTestRecommendation) -> tuple[int, int]:
+ return (_BASIS_ORDER.get(rec.basis, 99), _TIER_PRIORITY.get(rec.via, 99))
+
+
+def _merge_recommendations(
+ first: WorkspaceTestRecommendation, second: WorkspaceTestRecommendation
+) -> WorkspaceTestRecommendation:
+ """Fold two rows for the same test and repo pair into one.
+
+ The row keeps the strongest signal but every contract and provider file it
+ guards, so a reader sees the whole reason the test is on the list.
+ """
+ strongest, weaker = (
+ (first, second) if _signal_rank(first) <= _signal_rank(second) else (second, first)
+ )
+ return replace(
+ strongest,
+ consumer_file=min(first.consumer_file, second.consumer_file),
+ consumer_symbol_id=min(
+ (s for s in (first.consumer_symbol_id, second.consumer_symbol_id) if s),
+ default=None,
+ ),
+ contract_ids=sorted(set(first.contract_ids) | set(second.contract_ids)),
+ contract_types=sorted(set(first.contract_types) | set(second.contract_types)),
+ confidence=max(first.confidence, second.confidence),
+ source_files=sorted(set(first.source_files) | set(second.source_files)),
+ evidence=[*strongest.evidence, *weaker.evidence],
+ )
+
+
+def _unresolved_for(link: ContractLink, reason: str, detail: str | None = None) -> UnresolvedLink:
+ return UnresolvedLink(
+ consumer_repo=link.consumer_repo,
+ consumer_file=_norm(link.consumer_file),
+ consumer_symbol_id=link.consumer_symbol_id,
+ provider_repo=link.provider_repo,
+ provider_file=_norm(link.provider_file),
+ contract_id=link.contract_id,
+ contract_type=link.contract_type,
+ reason=reason,
+ detail=detail,
+ )
+
+
+@dataclass
+class _ConsumerOutcome:
+ recommendations: list[WorkspaceTestRecommendation] = field(default_factory=list)
+ unresolved: list[UnresolvedLink] = field(default_factory=list)
+ files_analyzed: list[dict[str, Any]] = field(default_factory=list)
+
+
+def _file_row(
+ alias: str,
+ consumer_file: str,
+ links: Sequence[ContractLink],
+ *,
+ state: str,
+ measured_count: int = 0,
+ inferred_count: int = 0,
+ via: str | None = None,
+) -> dict[str, Any]:
+ return {
+ "consumer_repo": alias,
+ "consumer_file": consumer_file,
+ "state": state,
+ "measured_tests_count": measured_count,
+ "inferred_tests_count": inferred_count,
+ "via": via,
+ "provider_repos": sorted({lk.provider_repo for lk in links}),
+ "contract_ids": sorted({lk.contract_id for lk in links}),
+ "consumer_symbol_ids": sorted(
+ {lk.consumer_symbol_id for lk in links if lk.consumer_symbol_id}
+ ),
+ }
+
+
+async def _analyze_consumer(
+ alias: str,
+ links: Sequence[ContractLink],
+ repo_index: RepoIndex | None,
+ *,
+ call_depth: int,
+ import_depth: int,
+ include_measured: bool,
+ include_inferred: bool,
+) -> _ConsumerOutcome:
+ """Resolve one consumer repo, sequentially on the one session it holds."""
+ out = _ConsumerOutcome()
+ by_file: dict[str, list[ContractLink]] = defaultdict(list)
+ for link in links:
+ by_file[_norm(link.consumer_file)].append(link)
+
+ if repo_index is None:
+ out.unresolved = [_unresolved_for(lk, "no_index") for lk in links]
+ out.files_analyzed = [
+ _file_row(alias, path, group, state="unresolved") for path, group in by_file.items()
+ ]
+ return out
+
+ bound: dict[str, list[ContractLink]] = defaultdict(list)
+ seeds: dict[str, set[str]] = defaultdict(set)
+ for path, group in by_file.items():
+ known = {sym.symbol_id for sym in repo_index.symbols_for_file(path)}
+ for link in group:
+ if link.consumer_symbol_id is None:
+ out.unresolved.append(_unresolved_for(link, "unbound"))
+ elif link.consumer_symbol_id not in known:
+ # The index moved on since the link was built.
+ out.unresolved.append(_unresolved_for(link, "symbol_missing"))
+ else:
+ bound[path].append(link)
+ seeds[path].add(link.consumer_symbol_id)
+
+ files = sorted(bound)
+ measured: dict[str, list[dict[str, Any]]] = {}
+ reached: dict[str, Any] = {}
+ # A pass that fails takes down only its own signal; whatever the other pass
+ # found, and the links already classified, still reach the caller.
+ failures: list[str] = []
+ if files:
+ session = repo_index.session
+ if include_measured:
+ try:
+ rows = await tests_covering_files(session, repo_index.repo_id, set(files))
+ for path, covering in rows.items():
+ measured[path] = [
+ {
+ "test_id": str(row["test_id"]),
+ "test_file": str(
+ row.get("test_file") or str(row["test_id"]).split("::", 1)[0]
+ ),
+ "source_format": row.get("source_format"),
+ }
+ for row in covering
+ ]
+ except Exception as exc:
+ failures.append(f"measured: {type(exc).__name__}")
+ if include_inferred:
+ try:
+ # Two walks so each link is credited only with what reaches its
+ # own symbol: the call tier is keyed by symbol id, and the import
+ # tier, which only knows files, runs for the files no symbol answered.
+ symbol_ids = sorted({sid for path in files for sid in seeds[path]})
+ by_symbol = await tests_reaching_by_tier(
+ session,
+ repo_index.repo_id,
+ symbol_ids,
+ call_depth=call_depth,
+ import_depth=0,
+ symbol_seeds={sid: {sid} for sid in symbol_ids},
+ )
+ unanswered = [
+ path for path in files if not any(sid in by_symbol for sid in seeds[path])
+ ]
+ by_file_reached = await tests_reaching_by_tier(
+ session,
+ repo_index.repo_id,
+ unanswered,
+ call_depth=0,
+ import_depth=import_depth,
+ )
+ reached = {**by_file_reached, **by_symbol}
+ except Exception as exc:
+ failures.append(f"inferred: {type(exc).__name__}")
+
+ if failures:
+ detail = "; ".join(failures)
+ for group in bound.values():
+ out.unresolved.extend(_unresolved_for(lk, "lookup_failed", detail) for lk in group)
+
+ for path, group in by_file.items():
+ links_for_file = bound.get(path, [])
+ measured_tests = measured.get(path, [])
+ for entry in measured_tests:
+ for link in links_for_file:
+ out.recommendations.append(
+ WorkspaceTestRecommendation(
+ test_id=entry["test_id"],
+ test_file=entry["test_file"],
+ consumer_repo=alias,
+ consumer_file=path,
+ consumer_symbol_id=link.consumer_symbol_id,
+ provider_repo=link.provider_repo,
+ contract_ids=[link.contract_id],
+ contract_types=[link.contract_type],
+ basis="measured",
+ via="coverage-map",
+ confidence=link.confidence,
+ source_files=[_norm(link.provider_file)],
+ evidence=[
+ {
+ "basis": "measured",
+ "source_file": _norm(link.provider_file),
+ "via": "coverage-map",
+ "contract_id": link.contract_id,
+ # Coverage rows are recorded per file, not per symbol.
+ "entry": "file",
+ "source_format": entry.get("source_format"),
+ }
+ ],
+ )
+ )
+
+ file_tests: set[str] = set()
+ file_via: str | None = None
+ for link in links_for_file:
+ # A link's own symbol answers first; the file-level import tier
+ # only speaks for files no symbol answered.
+ hit = reached.get(link.consumer_symbol_id or "") or reached.get(path)
+ if hit is None:
+ continue
+ # The walk trims its own list per target; the join caps per consumer
+ # and provider pair below and reports the cut, so start from all of them.
+ reached_tests = list(hit.all_tests or hit.tests)
+ file_tests.update(reached_tests)
+ if file_via is None or _TIER_PRIORITY.get(hit.via, 99) < _TIER_PRIORITY.get(file_via, 99):
+ file_via = hit.via
+ for test_id in reached_tests:
+ out.recommendations.append(
+ WorkspaceTestRecommendation(
+ test_id=test_id,
+ test_file=test_id.split("::", 1)[0],
+ consumer_repo=alias,
+ consumer_file=path,
+ consumer_symbol_id=link.consumer_symbol_id,
+ provider_repo=link.provider_repo,
+ contract_ids=[link.contract_id],
+ contract_types=[link.contract_type],
+ basis="inferred",
+ via=hit.via,
+ confidence=link.confidence,
+ source_files=[_norm(link.provider_file)],
+ evidence=[
+ {
+ "basis": "inferred",
+ "source_file": _norm(link.provider_file),
+ "via": hit.via,
+ "contract_id": link.contract_id,
+ "entry": _ENTRY_BY_TIER.get(hit.via, "file"),
+ }
+ ],
+ )
+ )
+
+ if measured_tests:
+ state = "measured"
+ elif file_tests:
+ state = "inferred"
+ elif links_for_file and not failures:
+ state = "none"
+ else:
+ state = "unresolved"
+ out.files_analyzed.append(
+ _file_row(
+ alias,
+ path,
+ group,
+ state=state,
+ measured_count=len(measured_tests),
+ inferred_count=len(file_tests),
+ via=file_via,
+ )
+ )
+ return out
+
+
+async def analyze_workspace_test_impact(
+ index: WorkspaceIndex,
+ links: Sequence[ContractLink],
+ changed_files: Sequence[Mapping[str, str]],
+ *,
+ call_depth: int = DEFAULT_CALL_DEPTH,
+ import_depth: int = DEFAULT_MAX_DEPTH,
+ include_measured: bool = True,
+ include_inferred: bool = True,
+ min_confidence: float = 0.0,
+ target_repos: Collection[str] | None = None,
+) -> WorkspaceTestImpactResult:
+ """Tests in consumer repos that guard *changed_files* in provider repos.
+
+ *index* and *links* are supplied by the caller, so a request handler that
+ already holds both opens nothing here.
+ """
+ changed_by_provider: dict[str, set[str]] = defaultdict(set)
+ for entry in changed_files:
+ repo = entry.get("repo")
+ path = entry.get("path")
+ if repo and path:
+ changed_by_provider[repo].add(_norm(path))
+
+ summary: dict[str, Any] = {
+ "changed_provider_files": {
+ repo: sorted(paths) for repo, paths in sorted(changed_by_provider.items())
+ },
+ "changed_files_without_contracts": {},
+ "consumer_repos_analyzed": [],
+ "consumer_repos_without_index": [],
+ "total_contract_links": len(links),
+ "relevant_contract_links": 0,
+ "states": {"measured": 0, "inferred": 0, "none": 0, "unresolved": 0},
+ # A caller that turned a pass off should see that in the answer.
+ "passes": {"measured": include_measured, "inferred": include_inferred},
+ }
+ if not changed_by_provider:
+ summary["reason"] = "no_changed_files"
+ return WorkspaceTestImpactResult(summary=summary)
+
+ kept = [
+ link
+ for link in links
+ if link.confidence >= min_confidence
+ and (target_repos is None or link.consumer_repo in target_repos)
+ and _norm(link.provider_file) in changed_by_provider.get(link.provider_repo, set())
+ and not _internal_call(link)
+ ]
+ summary["relevant_contract_links"] = len(kept)
+
+ named: dict[str, set[str]] = defaultdict(set)
+ for link in kept:
+ named[link.provider_repo].add(_norm(link.provider_file))
+ summary["changed_files_without_contracts"] = {
+ repo: sorted(paths - named.get(repo, set()))
+ for repo, paths in sorted(changed_by_provider.items())
+ if paths - named.get(repo, set())
+ }
+
+ if not kept:
+ summary["reason"] = "no_matching_links"
+ return WorkspaceTestImpactResult(summary=summary)
+
+ by_consumer: dict[str, list[ContractLink]] = defaultdict(list)
+ for link in kept:
+ by_consumer[link.consumer_repo].append(link)
+
+ aliases = sorted(by_consumer)
+ # Consumers run in parallel because each holds its own session; everything
+ # inside one consumer is sequential, since a session is not concurrent-safe.
+ outcomes = await asyncio.gather(
+ *(
+ _analyze_consumer(
+ alias,
+ by_consumer[alias],
+ index.get(alias),
+ call_depth=call_depth,
+ import_depth=import_depth,
+ include_measured=include_measured,
+ include_inferred=include_inferred,
+ )
+ for alias in aliases
+ )
+ )
+
+ raw: list[WorkspaceTestRecommendation] = []
+ unresolved: list[UnresolvedLink] = []
+ files_analyzed: list[dict[str, Any]] = []
+ for outcome in outcomes:
+ raw.extend(outcome.recommendations)
+ unresolved.extend(outcome.unresolved)
+ files_analyzed.extend(outcome.files_analyzed)
+
+ seen: dict[tuple, WorkspaceTestRecommendation] = {}
+ for rec in raw:
+ key = (rec.test_id, rec.consumer_repo, rec.provider_repo)
+ existing = seen.get(key)
+ seen[key] = _merge_recommendations(existing, rec) if existing is not None else rec
+
+ deduplicated = sorted(seen.values(), key=_recommendation_sort_key)
+
+ capped: list[WorkspaceTestRecommendation] = []
+ counts: dict[tuple[str, str], int] = defaultdict(int)
+ for rec in deduplicated:
+ pair = (rec.consumer_repo, rec.provider_repo)
+ if counts[pair] < MAX_TESTS_PER_TARGET:
+ capped.append(rec)
+ counts[pair] += 1
+
+ by_basis: dict[str, int] = {"measured": 0, "inferred": 0}
+ by_repo: dict[str, int] = defaultdict(int)
+ by_consumer_repo: dict[str, int] = defaultdict(int)
+ for rec in capped:
+ by_basis[rec.basis] = by_basis.get(rec.basis, 0) + 1
+ by_repo[rec.provider_repo] += 1
+ by_consumer_repo[rec.consumer_repo] += 1
+
+ states = summary["states"]
+ for row in files_analyzed:
+ states[row["state"]] = states.get(row["state"], 0) + 1
+ summary["consumer_repos_analyzed"] = [a for a in aliases if index.get(a) is not None]
+ summary["consumer_repos_without_index"] = [a for a in aliases if index.get(a) is None]
+
+ return WorkspaceTestImpactResult(
+ recommendations=capped,
+ recommendations_total=len(deduplicated),
+ recommendations_emitted=len(capped),
+ recommendations_truncated=len(capped) < len(deduplicated),
+ recommendations_omitted=len(deduplicated) - len(capped),
+ recommendations_by_basis=by_basis,
+ recommendations_by_repo=dict(by_repo),
+ recommendations_by_consumer_repo=dict(by_consumer_repo),
+ unresolved=unresolved,
+ files_analyzed=files_analyzed,
+ summary=summary,
+ )
+
+
+async def workspace_test_impact_from_root(
+ workspace_root: Path | str,
+ changed_files: Sequence[Mapping[str, str]],
+ **options: Any,
+) -> WorkspaceTestImpactResult:
+ """:func:`analyze_workspace_test_impact` over an on-disk workspace."""
+ root = Path(workspace_root)
+ store = load_contract_store(root)
+ if store is None:
+ return WorkspaceTestImpactResult(
+ summary={
+ "reason": "no_contract_store",
+ "hint": "Run `repowise update --workspace` to build the contract map.",
+ }
+ )
+ ws_config = WorkspaceConfig.load(root)
+ changed_repos = {entry.get("repo") for entry in changed_files if entry.get("repo")}
+ # Only consumers of a changed repo can survive the join, and the primary
+ # repo holds the largest symbol table while never being a consumer here.
+ consumers = {
+ link.consumer_repo
+ for link in store.contract_links
+ if link.provider_repo in changed_repos
+ }
+ index = await open_workspace_index(ws_config, root, aliases=consumers)
+ try:
+ return await analyze_workspace_test_impact(
+ index, store.contract_links, changed_files, **options
+ )
+ finally:
+ await index.close()
+
+
+def workspace_test_impact_to_dict(result: WorkspaceTestImpactResult) -> dict[str, Any]:
+ """Serialize the result for the CLI, the API and MCP."""
+ return {
+ "workspace": result.workspace,
+ "recommendations": [
+ {
+ "test_id": r.test_id,
+ "test_file": r.test_file,
+ "consumer_repo": r.consumer_repo,
+ "consumer_file": r.consumer_file,
+ "consumer_symbol_id": r.consumer_symbol_id,
+ "provider_repo": r.provider_repo,
+ "contract_ids": r.contract_ids,
+ "contract_types": r.contract_types,
+ "basis": r.basis,
+ "via": r.via,
+ "confidence": r.confidence,
+ "source_files": r.source_files,
+ "evidence": r.evidence,
+ }
+ for r in result.recommendations
+ ],
+ "recommendations_total": result.recommendations_total,
+ "recommendations_emitted": result.recommendations_emitted,
+ "recommendations_truncated": result.recommendations_truncated,
+ "recommendations_omitted": result.recommendations_omitted,
+ "recommendations_by_basis": result.recommendations_by_basis,
+ "recommendations_by_repo": result.recommendations_by_repo,
+ "recommendations_by_consumer_repo": result.recommendations_by_consumer_repo,
+ "unresolved": [
+ {
+ "consumer_repo": u.consumer_repo,
+ "consumer_file": u.consumer_file,
+ "consumer_symbol_id": u.consumer_symbol_id,
+ "provider_repo": u.provider_repo,
+ "provider_file": u.provider_file,
+ "contract_id": u.contract_id,
+ "contract_type": u.contract_type,
+ "reason": u.reason,
+ "detail": u.detail,
+ }
+ for u in result.unresolved
+ ],
+ "files_analyzed": result.files_analyzed,
+ "summary": result.summary,
+ }
diff --git a/tests/unit/cli/test_workspace_cmd.py b/tests/unit/cli/test_workspace_cmd.py
index a02c06800..1b0d76bd5 100644
--- a/tests/unit/cli/test_workspace_cmd.py
+++ b/tests/unit/cli/test_workspace_cmd.py
@@ -848,3 +848,197 @@ class TestWorkspaceCheckBreaking:
),
root,
)
+
+
+# ---------------------------------------------------------------------------
+# workspace impacted-tests
+# ---------------------------------------------------------------------------
+
+
+class TestWorkspaceImpactedTests:
+ """The command's own reporting, over a canned result.
+
+ The join itself is covered in tests/unit/workspace/test_test_impact.py;
+ what matters here is that a link the join could not follow reaches the
+ reader instead of vanishing.
+ """
+
+ def _canned(self):
+ from repowise.core.workspace.test_impact import (
+ UnresolvedLink,
+ WorkspaceTestImpactResult,
+ WorkspaceTestRecommendation,
+ )
+
+ rec = WorkspaceTestRecommendation(
+ test_id="tests/api.test.ts::it_getUser",
+ test_file="tests/api.test.ts",
+ consumer_repo="frontend",
+ consumer_file="src/api.ts",
+ consumer_symbol_id="src/api.ts::getUser",
+ provider_repo="backend",
+ contract_ids=["http::GET::/users"],
+ contract_types=["http"],
+ basis="inferred",
+ via="call-graph",
+ confidence=0.9,
+ source_files=["app/routers/users.py"],
+ evidence=[
+ {
+ "basis": "inferred",
+ "via": "call-graph",
+ "entry": "symbol",
+ "contract_id": "http::GET::/users",
+ "source_file": "app/routers/users.py",
+ }
+ ],
+ )
+ unresolved = UnresolvedLink(
+ consumer_repo="frontend",
+ consumer_file="src/legacy.ts",
+ consumer_symbol_id=None,
+ provider_repo="backend",
+ provider_file="app/routers/users.py",
+ contract_id="http::POST::/users",
+ contract_type="http",
+ reason="unbound",
+ detail=None,
+ )
+ return WorkspaceTestImpactResult(
+ workspace=True,
+ recommendations=[rec],
+ recommendations_total=1,
+ recommendations_emitted=1,
+ recommendations_truncated=False,
+ recommendations_omitted=0,
+ recommendations_by_basis={"measured": 0, "inferred": 1},
+ recommendations_by_repo={"backend": 1},
+ recommendations_by_consumer_repo={"frontend": 1},
+ unresolved=[unresolved],
+ files_analyzed=[],
+ summary={
+ "states": {"measured": 0, "inferred": 1, "none": 0, "unresolved": 1},
+ "passes": {"measured": True, "inferred": True},
+ },
+ )
+
+ def _empty(self):
+ """What the command gets when the workspace has no contract map yet."""
+ from repowise.core.workspace.test_impact import WorkspaceTestImpactResult
+
+ return WorkspaceTestImpactResult(
+ summary={
+ "reason": "no_contract_store",
+ "passes": {"measured": True, "inferred": True},
+ }
+ )
+
+ def _install(self, tmp_path, monkeypatch, canned):
+ from repowise.core.workspace import test_impact
+
+ _make_git_repo(tmp_path / "backend")
+ _make_git_repo(tmp_path / "frontend")
+ _write_workspace_config(
+ tmp_path,
+ repos=[
+ {"path": "backend", "alias": "backend"},
+ {"path": "frontend", "alias": "frontend"},
+ ],
+ )
+
+ async def _fake(root, changed, **options):
+ return canned
+
+ monkeypatch.setattr(test_impact, "workspace_test_impact_from_root", _fake)
+ return tmp_path
+
+ @pytest.fixture
+ def workspace(self, tmp_path, monkeypatch):
+ return self._install(tmp_path, monkeypatch, self._canned())
+
+ @pytest.fixture
+ def empty_workspace(self, tmp_path, monkeypatch):
+ return self._install(tmp_path, monkeypatch, self._empty())
+
+ def test_a_link_that_could_not_be_followed_is_printed(self, runner, workspace):
+ result = runner.invoke(
+ cli,
+ [
+ "workspace",
+ "impacted-tests",
+ "backend:app/routers/users.py",
+ "--path",
+ str(workspace),
+ ],
+ )
+ assert result.exit_code == 0, result.output
+ assert "Could not determine" in result.output
+ assert "contract never bound to a symbol" in result.output
+
+ def test_list_format_prints_the_test_file(self, runner, workspace):
+ result = runner.invoke(
+ cli,
+ [
+ "workspace",
+ "impacted-tests",
+ "backend:app/routers/users.py",
+ "--path",
+ str(workspace),
+ "--format",
+ "list",
+ ],
+ )
+ assert result.exit_code == 0, result.output
+ assert "frontend:tests/api.test.ts" in result.output
+
+ def test_the_table_names_the_contracts_and_the_provider_files(
+ self, runner, workspace
+ ):
+ result = runner.invoke(
+ cli,
+ [
+ "workspace",
+ "impacted-tests",
+ "backend:app/routers/users.py",
+ "--path",
+ str(workspace),
+ ],
+ )
+ assert result.exit_code == 0, result.output
+ flattened = " ".join(result.output.split())
+ assert "http::GET::/users" in flattened
+ assert "Provider Files" in flattened
+ assert "app/routers/users.py" in flattened
+
+ def _split_runner(self):
+ """A runner that keeps stderr out of ``stdout``.
+
+ ``mix_stderr`` exists on click 8.1 and was removed in 8.2, where the
+ two streams are already separate.
+ """
+ import inspect
+
+ from click.testing import CliRunner
+
+ if "mix_stderr" in inspect.signature(CliRunner.__init__).parameters:
+ return CliRunner(mix_stderr=False)
+ return CliRunner()
+
+ def test_list_format_explains_an_empty_answer_on_stderr(self, empty_workspace):
+ """A pipeline reading stdout must never get silence with exit 0."""
+ result = self._split_runner().invoke(
+ cli,
+ [
+ "workspace",
+ "impacted-tests",
+ "backend:app/routers/users.py",
+ "--path",
+ str(empty_workspace),
+ "--format",
+ "list",
+ ],
+ )
+ assert result.exit_code == 0, result.output
+ assert result.stdout.strip() == ""
+ assert "No tests found" in result.stderr
+ assert "contract map" in result.stderr
diff --git a/tests/unit/workspace/_repo_index.py b/tests/unit/workspace/_repo_index.py
index 1534d78f1..f67e2c3ef 100644
--- a/tests/unit/workspace/_repo_index.py
+++ b/tests/unit/workspace/_repo_index.py
@@ -11,7 +11,9 @@ from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any
-from repowise.core.persistence.models import GraphEdge, Repository, WikiSymbol
+from repowise.core.analysis.health.coverage.model import TestCoverage
+from repowise.core.persistence.crud.analysis.coverage_map import save_test_coverage
+from repowise.core.persistence.models import GraphEdge, GraphNode, Repository, WikiSymbol
from repowise.core.workspace.registry import open_repo_db
from repowise.core.workspace.repo_index import RepoIndex, open_repo_index
@@ -28,6 +30,9 @@ async def make_repo_index(
*,
alias: str = "backend",
external_edges: Sequence[tuple[str, str, list[str]]] = (),
+ graph_nodes: Sequence[tuple[str, bool]] = (),
+ graph_edges: Sequence[tuple[str, str, str]] = (),
+ coverage: Sequence[tuple[str, str, str]] = (),
) -> RepoIndex:
"""Persist *symbols_by_file* to ``repo``'s wiki.db and open it.
@@ -35,6 +40,12 @@ async def make_repo_index(
exactly as :func:`repowise.core.persistence.crud.external_systems` does.
*external_edges* are ``(source_file, target_node_id, imported_names)``;
``imported_names`` is written verbatim so a malformed payload can be tested.
+
+ The reachability substrate is optional: *graph_nodes* are
+ ``(node_id, is_test)`` file nodes, *graph_edges* are
+ ``(source, target, edge_type)`` rows, and *coverage* are
+ ``(test_id, test_file, source_file)`` triples written through
+ :func:`save_test_coverage` so a measured row exists.
"""
(repo / ".repowise").mkdir(parents=True, exist_ok=True)
engine, session_factory = await open_repo_db(repo)
@@ -72,6 +83,39 @@ async def make_repo_index(
imported_names_json=json.dumps(names),
)
)
+ for node_id, is_test in graph_nodes:
+ session.add(
+ GraphNode(
+ repository_id=_REPO_ID,
+ node_id=node_id,
+ node_type="file",
+ is_test=is_test,
+ )
+ )
+ for source, target, edge_type in graph_edges:
+ session.add(
+ GraphEdge(
+ repository_id=_REPO_ID,
+ source_node_id=source,
+ target_node_id=target,
+ edge_type=edge_type,
+ )
+ )
+ if coverage:
+ await save_test_coverage(
+ session,
+ _REPO_ID,
+ [
+ TestCoverage(
+ test_id=test_id,
+ file_path=source_file,
+ covered_lines=[1],
+ test_file=test_file,
+ )
+ for test_id, test_file, source_file in coverage
+ ],
+ source_format="lcov",
+ )
await session.commit()
await engine.dispose()
diff --git a/tests/unit/workspace/test_test_impact.py b/tests/unit/workspace/test_test_impact.py
new file mode 100644
index 000000000..697345437
--- /dev/null
+++ b/tests/unit/workspace/test_test_impact.py
@@ -0,0 +1,664 @@
+"""Cross-repo test impact: the join from a provider change to consumer tests.
+
+The join runs against a real per-repo index, because the two things it has to
+get right are both query-path facts. A consumer repo is named by its alias but
+its row is keyed by ``local_path``, so a lookup by alias silently finds nothing
+and the command reports zero tests. And a contract link names a *symbol*, so
+entering the call walk at the file would recommend every test that reaches any
+symbol in it.
+
+The other claim under test is that an empty answer is never silent: a link that
+cannot be followed becomes an ``unresolved`` row saying why.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.core.ingestion.models import Symbol
+from repowise.core.workspace.config import RepoEntry, WorkspaceConfig
+from repowise.core.workspace.contracts import (
+ ContractLink,
+ ContractStore,
+ save_contract_store,
+)
+from repowise.core.workspace.repo_index import (
+ RepoIndex,
+ WorkspaceIndex,
+ open_workspace_index,
+)
+from repowise.core.workspace.test_impact import (
+ analyze_workspace_test_impact,
+ workspace_test_impact_from_root,
+ workspace_test_impact_to_dict,
+)
+
+from ._repo_index import make_repo_index
+
+PROVIDER_FILE = "app/routers/users.py"
+CHANGED = [{"repo": "backend", "path": PROVIDER_FILE}]
+
+
+def _symbol(symbol_id: str) -> Symbol:
+ name = symbol_id.split("::", 1)[1]
+ return Symbol(
+ id=symbol_id,
+ name=name,
+ qualified_name=name,
+ kind="function",
+ signature=f"function {name}()",
+ start_line=1,
+ end_line=5,
+ docstring=None,
+ visibility="public",
+ )
+
+
+def _link(
+ *,
+ consumer_file: str,
+ consumer_symbol_id: str | None,
+ consumer_repo: str = "frontend",
+ contract_id: str = "http::GET::/users/{param}",
+ confidence: float = 0.9,
+ provider_repo: str = "backend",
+ provider_file: str = PROVIDER_FILE,
+) -> ContractLink:
+ return ContractLink(
+ contract_id=contract_id,
+ contract_type="http",
+ match_type="exact",
+ confidence=confidence,
+ provider_repo=provider_repo,
+ provider_file=provider_file,
+ provider_symbol="get_user",
+ provider_service=None,
+ consumer_repo=consumer_repo,
+ consumer_file=consumer_file,
+ consumer_symbol="getUser",
+ consumer_service=None,
+ consumer_symbol_id=consumer_symbol_id,
+ )
+
+
+BOUND = _link(consumer_file="src/api.ts", consumer_symbol_id="src/api.ts::getUser")
+UNBOUND = _link(consumer_file="src/legacy.ts", consumer_symbol_id=None)
+NO_INDEX = _link(
+ consumer_file="src/client.ts",
+ consumer_symbol_id="src/client.ts::call",
+ consumer_repo="mobile",
+)
+NOTHING_REACHES = _link(
+ consumer_file="src/other.ts", consumer_symbol_id="src/other.ts::helper"
+)
+SYMBOL_GONE = _link(consumer_file="src/api.ts", consumer_symbol_id="src/api.ts::gone")
+#: Nothing calls ``src/imported.ts``; one test file imports it, so only the
+#: weaker file-level tier can answer for it.
+ONLY_IMPORTED = _link(
+ consumer_file="src/imported.ts", consumer_symbol_id="src/imported.ts::thing"
+)
+
+ALL_LINKS = [BOUND, UNBOUND, NO_INDEX, NOTHING_REACHES, SYMBOL_GONE]
+
+
+async def _frontend(repo: Path) -> RepoIndex:
+ """A consumer repo whose two tests each reach one symbol of ``src/api.ts``."""
+ return await make_repo_index(
+ repo,
+ {
+ "src/api.ts": [_symbol("src/api.ts::getUser"), _symbol("src/api.ts::listUsers")],
+ "src/other.ts": [_symbol("src/other.ts::helper")],
+ "src/imported.ts": [_symbol("src/imported.ts::thing")],
+ },
+ alias="frontend",
+ graph_nodes=(
+ ("src/api.ts", False),
+ ("src/other.ts", False),
+ ("src/imported.ts", False),
+ ("tests/api.test.ts", True),
+ ("tests/list.test.ts", True),
+ ("tests/imports.test.ts", True),
+ ),
+ graph_edges=(
+ ("src/api.ts", "src/api.ts::getUser", "defines"),
+ ("src/api.ts", "src/api.ts::listUsers", "defines"),
+ ("src/other.ts", "src/other.ts::helper", "defines"),
+ ("src/imported.ts", "src/imported.ts::thing", "defines"),
+ ("tests/api.test.ts", "tests/api.test.ts::it_getUser", "defines"),
+ ("tests/list.test.ts", "tests/list.test.ts::it_listUsers", "defines"),
+ ("tests/api.test.ts::it_getUser", "src/api.ts::getUser", "calls"),
+ ("tests/list.test.ts::it_listUsers", "src/api.ts::listUsers", "calls"),
+ ("tests/imports.test.ts", "src/imported.ts", "imports"),
+ ),
+ coverage=(("tests/cov.test.ts::covers", "tests/cov.test.ts", "src/api.ts"),),
+ )
+
+
+async def frontend_index(tmp_path: Path):
+ index = await _frontend(tmp_path / "frontend")
+ try:
+ yield index
+ finally:
+ await index.close()
+
+
+def workspace(frontend_index: RepoIndex) -> WorkspaceIndex:
+ return WorkspaceIndex({"frontend": frontend_index})
+
+
+# ---------------------------------------------------------------------------
+# The four states
+# ---------------------------------------------------------------------------
+
+
+class TestStates:
+ async def test_a_bound_link_yields_both_a_measured_and_an_inferred_row(
+ self, workspace: WorkspaceIndex
+ ) -> None:
+ result = await analyze_workspace_test_impact(workspace, [BOUND], CHANGED)
+
+ by_basis = {rec.basis: rec for rec in result.recommendations}
+ assert by_basis["measured"].test_id == "tests/cov.test.ts::covers"
+ assert by_basis["measured"].via == "coverage-map"
+ assert by_basis["inferred"].test_file == "tests/api.test.ts"
+ assert by_basis["inferred"].via == "call-graph"
+ assert by_basis["inferred"].consumer_symbol_id == "src/api.ts::getUser"
+ assert by_basis["inferred"].contract_ids == [BOUND.contract_id]
+ assert by_basis["inferred"].contract_types == ["http"]
+ assert by_basis["inferred"].source_files == [PROVIDER_FILE]
+
+ async def test_a_link_that_never_bound_says_so(self, workspace: WorkspaceIndex) -> None:
+ result = await analyze_workspace_test_impact(workspace, [UNBOUND], CHANGED)
+
+ assert [u.reason for u in result.unresolved] == ["unbound"]
+ assert result.unresolved[0].consumer_file == "src/legacy.ts"
+ assert result.unresolved[0].contract_id == UNBOUND.contract_id
+ assert result.unresolved[0].contract_type == "http"
+ assert result.unresolved[0].provider_file == PROVIDER_FILE
+ assert not result.recommendations
+
+ async def test_a_consumer_without_an_index_says_so(
+ self, workspace: WorkspaceIndex
+ ) -> None:
+ result = await analyze_workspace_test_impact(workspace, [NO_INDEX], CHANGED)
+
+ assert [u.reason for u in result.unresolved] == ["no_index"]
+ assert result.summary["consumer_repos_without_index"] == ["mobile"]
+
+ async def test_a_call_site_nothing_reaches_is_analysed_and_empty(
+ self, workspace: WorkspaceIndex
+ ) -> None:
+ """``none`` is a result: the walk ran, and no test came back."""
+ result = await analyze_workspace_test_impact(workspace, [NOTHING_REACHES], CHANGED)
+
+ assert not result.recommendations
+ rows = [f for f in result.files_analyzed if f["consumer_file"] == "src/other.ts"]
+ assert [row["state"] for row in rows] == ["none"]
+
+ async def test_a_symbol_the_index_no_longer_holds_says_so(
+ self, workspace: WorkspaceIndex
+ ) -> None:
+ result = await analyze_workspace_test_impact(workspace, [SYMBOL_GONE], CHANGED)
+
+ assert [u.reason for u in result.unresolved] == ["symbol_missing"]
+ assert result.unresolved[0].consumer_symbol_id == "src/api.ts::gone"
+
+ async def test_the_state_counts_agree_with_the_rows(
+ self, workspace: WorkspaceIndex
+ ) -> None:
+ result = await analyze_workspace_test_impact(workspace, ALL_LINKS, CHANGED)
+
+ states = result.summary["states"]
+ assert states["measured"] == 1, "src/api.ts, from the coverage map"
+ assert states["inferred"] == 0, "measured wins on the one file that has both"
+ assert states["none"] == 1, "src/other.ts"
+ assert states["unresolved"] == 2, "src/legacy.ts, and mobile's src/client.ts"
+ assert sum(states.values()) == len(result.files_analyzed)
+ assert sorted(u.reason for u in result.unresolved) == [
+ "no_index",
+ "symbol_missing",
+ "unbound",
+ ]
+ assert result.summary["consumer_repos_analyzed"] == ["frontend"]
+ assert result.summary["total_contract_links"] == 5
+
+
+# ---------------------------------------------------------------------------
+# Entry at the symbol, not the file
+# ---------------------------------------------------------------------------
+
+
+async def test_a_test_reaching_another_symbol_in_the_same_file_is_not_recommended(
+ workspace: WorkspaceIndex,
+) -> None:
+ """The regression for a file-keyed join.
+
+ ``tests/list.test.ts`` reaches ``listUsers``, which lives in the linked
+ file but is not the linked symbol, so the contract does not endanger it.
+ """
+ result = await analyze_workspace_test_impact(
+ workspace, [BOUND], CHANGED, include_measured=False
+ )
+
+ reached = {rec.test_file for rec in result.recommendations}
+ assert reached == {"tests/api.test.ts"}
+
+
+async def test_the_join_runs_against_the_indexed_consumer(
+ frontend_index: RepoIndex, workspace: WorkspaceIndex, tmp_path: Path
+) -> None:
+ """The index the join queries is the one on disk, keyed by its own path."""
+ assert frontend_index.repo_path == tmp_path / "frontend"
+ assert frontend_index.repo_id
+
+ result = await analyze_workspace_test_impact(
+ workspace, [BOUND], CHANGED, include_measured=False
+ )
+ assert result.recommendations
+
+
+async def test_from_root_resolves_the_consumer_by_path_not_by_alias(
+ tmp_path: Path,
+) -> None:
+ """The regression: the alias is ``frontend``, the directory is ``web-app``.
+
+ Opening the consumer's index by its alias would look for ``frontend/`` and
+ find nothing, and the command would report zero tests with no unresolved
+ row to explain it.
+ """
+ (tmp_path / "backend").mkdir()
+ index = await _frontend(tmp_path / "web-app")
+ await index.close()
+
+ WorkspaceConfig(
+ repos=[
+ RepoEntry(path="backend", alias="backend", is_primary=True),
+ RepoEntry(path="web-app", alias="frontend"),
+ ]
+ ).save(tmp_path)
+ save_contract_store(ContractStore(contract_links=[BOUND]), tmp_path)
+
+ result = await workspace_test_impact_from_root(tmp_path, CHANGED)
+
+ inferred = [rec for rec in result.recommendations if rec.basis == "inferred"]
+ assert [rec.test_file for rec in inferred] == ["tests/api.test.ts"]
+ assert inferred[0].consumer_repo == "frontend"
+
+
+# ---------------------------------------------------------------------------
+# One row per test per consumer and provider pair
+# ---------------------------------------------------------------------------
+
+
+async def test_two_contracts_on_one_file_are_one_row_naming_both(
+ workspace: WorkspaceIndex,
+) -> None:
+ """Two endpoints in the same handler file do not double the test list."""
+ second = _link(
+ consumer_file="src/api.ts",
+ consumer_symbol_id="src/api.ts::getUser",
+ contract_id="http::POST::/users",
+ )
+ result = await analyze_workspace_test_impact(
+ workspace, [BOUND, second], CHANGED, include_measured=False
+ )
+
+ assert len(result.recommendations) == 1
+ assert result.recommendations_total == 1
+ row = result.recommendations[0]
+ assert row.contract_ids == sorted([BOUND.contract_id, second.contract_id])
+ assert row.contract_types == ["http"]
+ assert row.source_files == [PROVIDER_FILE]
+
+
+async def test_a_test_guarding_two_changed_files_sorts_first(
+ workspace: WorkspaceIndex,
+) -> None:
+ other_provider = "app/routers/orders.py"
+ third_provider = "app/routers/listing.py"
+ result = await analyze_workspace_test_impact(
+ workspace,
+ [
+ BOUND,
+ _link(
+ consumer_file="src/api.ts",
+ consumer_symbol_id="src/api.ts::getUser",
+ contract_id="http::GET::/orders",
+ provider_file=other_provider,
+ ),
+ _link(
+ consumer_file="src/imported.ts",
+ consumer_symbol_id="src/imported.ts::thing",
+ contract_id="http::GET::/listing",
+ provider_file=third_provider,
+ ),
+ ],
+ [
+ *CHANGED,
+ {"repo": "backend", "path": other_provider},
+ {"repo": "backend", "path": third_provider},
+ ],
+ include_measured=False,
+ )
+
+ assert [rec.test_file for rec in result.recommendations] == [
+ "tests/api.test.ts",
+ "tests/imports.test.ts",
+ ]
+ assert result.recommendations[0].source_files == sorted([PROVIDER_FILE, other_provider])
+ assert result.recommendations[1].source_files == [third_provider]
+
+
+async def test_the_evidence_says_where_each_tier_entered(
+ workspace: WorkspaceIndex,
+) -> None:
+ """The call walk enters at a symbol; the import fallback is file level."""
+ result = await analyze_workspace_test_impact(
+ workspace, [BOUND, ONLY_IMPORTED], CHANGED, include_measured=False
+ )
+
+ by_via = {rec.via: rec for rec in result.recommendations}
+ assert by_via["call-graph"].evidence[0]["entry"] == "symbol"
+ assert by_via["call-graph"].evidence[0]["contract_id"] == BOUND.contract_id
+ assert by_via["import-graph"].test_file == "tests/imports.test.ts"
+ assert by_via["import-graph"].evidence[0]["entry"] == "file"
+
+
+async def test_a_measured_row_says_it_entered_at_the_file(
+ workspace: WorkspaceIndex,
+) -> None:
+ """Coverage rows are per file, so the measured tier claims no symbol."""
+ result = await analyze_workspace_test_impact(
+ workspace, [BOUND], CHANGED, include_inferred=False
+ )
+
+ entry = result.recommendations[0].evidence[0]
+ assert entry["basis"] == "measured"
+ assert entry["entry"] == "file"
+ assert entry["contract_id"] == BOUND.contract_id
+
+
+# ---------------------------------------------------------------------------
+# Failure is reported, never swallowed
+# ---------------------------------------------------------------------------
+
+
+async def test_a_failing_pass_keeps_what_the_other_pass_found(
+ workspace: WorkspaceIndex, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The inferred walk falls over; the coverage rows it never touched stay."""
+ from repowise.core.workspace import test_impact as test_impact_mod
+
+ async def boom(*args, **kwargs):
+ raise RuntimeError("connection went away")
+
+ monkeypatch.setattr(test_impact_mod, "tests_reaching_by_tier", boom)
+
+ result = await analyze_workspace_test_impact(
+ workspace, [BOUND, UNBOUND, NOTHING_REACHES], CHANGED
+ )
+
+ assert [rec.basis for rec in result.recommendations] == ["measured"]
+ assert result.recommendations[0].test_id == "tests/cov.test.ts::covers"
+
+ by_reason: dict[str, list] = {}
+ for link in result.unresolved:
+ by_reason.setdefault(link.reason, []).append(link)
+ assert sorted(by_reason) == ["lookup_failed", "unbound"]
+ assert {u.detail for u in by_reason["lookup_failed"]} == {"inferred: RuntimeError"}
+ assert [u.consumer_file for u in by_reason["unbound"]] == ["src/legacy.ts"]
+
+
+# ---------------------------------------------------------------------------
+# Filtering
+# ---------------------------------------------------------------------------
+
+
+class TestFilters:
+ async def test_min_confidence_drops_the_weaker_link(
+ self, workspace: WorkspaceIndex
+ ) -> None:
+ weak = _link(
+ consumer_file="src/api.ts",
+ consumer_symbol_id="src/api.ts::getUser",
+ contract_id="http::POST::/users",
+ confidence=0.5,
+ )
+ result = await analyze_workspace_test_impact(
+ workspace, [BOUND, weak], CHANGED, min_confidence=0.8
+ )
+
+ assert result.summary["relevant_contract_links"] == 1
+ assert {
+ contract_id
+ for rec in result.recommendations
+ for contract_id in rec.contract_ids
+ } == {BOUND.contract_id}
+
+ async def test_target_repos_limits_the_consumers_considered(
+ self, workspace: WorkspaceIndex
+ ) -> None:
+ result = await analyze_workspace_test_impact(
+ workspace, [BOUND, NO_INDEX], CHANGED, target_repos=["frontend"]
+ )
+
+ assert result.summary["relevant_contract_links"] == 1
+ assert not result.unresolved, "the mobile link was never considered"
+
+ async def test_measured_can_be_excluded(self, workspace: WorkspaceIndex) -> None:
+ result = await analyze_workspace_test_impact(
+ workspace, [BOUND], CHANGED, include_measured=False
+ )
+
+ assert {rec.basis for rec in result.recommendations} == {"inferred"}
+ assert result.summary["passes"] == {"measured": False, "inferred": True}
+
+ async def test_inferred_can_be_excluded(self, workspace: WorkspaceIndex) -> None:
+ result = await analyze_workspace_test_impact(
+ workspace, [BOUND], CHANGED, include_inferred=False
+ )
+
+ assert {rec.basis for rec in result.recommendations} == {"measured"}
+ assert result.summary["passes"]["inferred"] is False
+
+ async def test_both_passes_are_reported_as_run_by_default(
+ self, workspace: WorkspaceIndex
+ ) -> None:
+ result = await analyze_workspace_test_impact(workspace, [BOUND], CHANGED)
+
+ assert result.summary["passes"] == {"measured": True, "inferred": True}
+ assert result.recommendations_by_basis == {"measured": 1, "inferred": 1}
+
+
+# ---------------------------------------------------------------------------
+# What the join skips, and what it reports about the change itself
+# ---------------------------------------------------------------------------
+
+
+async def test_a_link_inside_one_repo_and_service_is_not_cross_repo(
+ workspace: WorkspaceIndex,
+) -> None:
+ same_repo = _link(
+ consumer_file="src/api.ts",
+ consumer_symbol_id="src/api.ts::getUser",
+ provider_repo="frontend",
+ provider_file="src/server.ts",
+ )
+ result = await analyze_workspace_test_impact(
+ workspace, [same_repo], [{"repo": "frontend", "path": "src/server.ts"}]
+ )
+
+ assert result.summary["relevant_contract_links"] == 0
+ assert result.summary["reason"] == "no_matching_links"
+ assert not result.recommendations
+
+
+async def test_a_changed_file_no_contract_names_is_reported(
+ workspace: WorkspaceIndex,
+) -> None:
+ changed = [*CHANGED, {"repo": "backend", "path": "app/util.py"}]
+ result = await analyze_workspace_test_impact(workspace, [BOUND], changed)
+
+ assert result.summary["changed_files_without_contracts"] == {
+ "backend": ["app/util.py"]
+ }
+ assert result.summary["changed_provider_files"] == {
+ "backend": [PROVIDER_FILE, "app/util.py"]
+ }
+
+
+async def test_a_windows_path_still_matches_its_contract(
+ workspace: WorkspaceIndex,
+) -> None:
+ result = await analyze_workspace_test_impact(
+ workspace,
+ [BOUND],
+ [{"repo": "backend", "path": "app\\routers\\users.py"}],
+ include_measured=False,
+ )
+
+ assert result.recommendations
+
+
+# ---------------------------------------------------------------------------
+# Bounds and provenance
+# ---------------------------------------------------------------------------
+
+
+async def test_the_cap_says_how_many_it_dropped(tmp_path: Path) -> None:
+ """Sixty tests call the linked symbol; fifty are emitted and it says so."""
+ from repowise.core.analysis.test_reachability import MAX_TESTS_PER_TARGET
+
+ tests = [f"tests/t{i:02d}.test.ts" for i in range(60)]
+ index = await make_repo_index(
+ tmp_path / "frontend",
+ {"src/api.ts": [_symbol("src/api.ts::getUser")]},
+ alias="frontend",
+ graph_nodes=(("src/api.ts", False), *((t, True) for t in tests)),
+ graph_edges=(
+ ("src/api.ts", "src/api.ts::getUser", "defines"),
+ *((t, f"{t}::it", "defines") for t in tests),
+ *((f"{t}::it", "src/api.ts::getUser", "calls") for t in tests),
+ ),
+ )
+ try:
+ result = await analyze_workspace_test_impact(
+ WorkspaceIndex({"frontend": index}), [BOUND], CHANGED, include_measured=False
+ )
+ finally:
+ await index.close()
+
+ assert result.recommendations_total == 60
+ assert result.recommendations_emitted == MAX_TESTS_PER_TARGET == 50
+ assert result.recommendations_truncated is True
+ assert result.recommendations_omitted == 10
+ assert len(result.recommendations) == 50
+
+
+async def test_an_inferred_row_carries_the_link_confidence_unchanged(
+ workspace: WorkspaceIndex,
+) -> None:
+ link = _link(
+ consumer_file="src/api.ts",
+ consumer_symbol_id="src/api.ts::getUser",
+ confidence=0.83,
+ )
+ result = await analyze_workspace_test_impact(
+ workspace, [link], CHANGED, include_measured=False
+ )
+
+ assert [rec.confidence for rec in result.recommendations] == [0.83]
+
+
+async def test_a_file_row_counts_the_tests_the_walk_found(
+ workspace: WorkspaceIndex,
+) -> None:
+ result = await analyze_workspace_test_impact(
+ workspace, [BOUND], CHANGED, include_measured=False
+ )
+
+ row = next(f for f in result.files_analyzed if f["consumer_file"] == "src/api.ts")
+ assert row["inferred_tests_count"] == 1
+ assert row["measured_tests_count"] == 0
+ assert "inferred_tests_total" not in row
+
+
+async def test_the_json_mirrors_the_dataclasses(workspace: WorkspaceIndex) -> None:
+ result = await analyze_workspace_test_impact(workspace, ALL_LINKS, CHANGED)
+ payload = workspace_test_impact_to_dict(result)
+
+ assert payload["workspace"] is True
+ assert payload["recommendations_emitted"] == len(result.recommendations)
+ assert len(payload["unresolved"]) == len(result.unresolved)
+ assert {u["reason"] for u in payload["unresolved"]} == {
+ u.reason for u in result.unresolved
+ }
+ row = payload["recommendations"][0]
+ assert row["contract_ids"] == result.recommendations[0].contract_ids
+ assert row["contract_types"] == result.recommendations[0].contract_types
+ assert "provider_file" not in row
+ assert "contract_id" not in row
+
+
+async def test_a_workspace_without_a_contract_store_says_which_step_is_missing(
+ tmp_path: Path,
+) -> None:
+ (tmp_path / "backend").mkdir()
+ WorkspaceConfig(repos=[RepoEntry(path="backend", alias="backend")]).save(tmp_path)
+
+ result = await workspace_test_impact_from_root(tmp_path, CHANGED)
+
+ assert result.summary["reason"] == "no_contract_store"
+ assert not result.recommendations
+
+
+async def test_only_the_named_aliases_are_opened(tmp_path: Path) -> None:
+ """The join opens the consumers it needs, not the whole workspace."""
+ for alias, directory in (("frontend", "web-app"), ("backend", "backend")):
+ index = await make_repo_index(
+ tmp_path / directory,
+ {"src/api.ts": [_symbol("src/api.ts::getUser")]},
+ alias=alias,
+ )
+ await index.close()
+
+ ws_config = WorkspaceConfig(
+ repos=[
+ RepoEntry(path="backend", alias="backend"),
+ RepoEntry(path="web-app", alias="frontend"),
+ ]
+ )
+ workspace = await open_workspace_index(ws_config, tmp_path, aliases={"frontend"})
+ try:
+ assert workspace.get("frontend") is not None
+ assert workspace.get("backend") is None
+ finally:
+ await workspace.close()
+
+
+async def test_two_links_in_one_file_each_get_only_their_own_symbols_tests(
+ workspace: WorkspaceIndex,
+) -> None:
+ """Symbol entry holds link by link, not file by file.
+
+ ``getUser`` and ``listUsers`` share ``src/api.ts``; each is reached by one
+ test, and neither link may be credited with the other's.
+ """
+ list_link = _link(
+ consumer_file="src/api.ts",
+ consumer_symbol_id="src/api.ts::listUsers",
+ contract_id="http::GET::/users",
+ )
+ result = await analyze_workspace_test_impact(
+ workspace, [BOUND, list_link], CHANGED, include_measured=False
+ )
+
+ by_test = {rec.test_file: rec.contract_ids for rec in result.recommendations}
+ assert by_test == {
+ "tests/api.test.ts": [BOUND.contract_id],
+ "tests/list.test.ts": ["http::GET::/users"],
+ }