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(mcp): route workspace targets to the repo that owns them (#3740)
Raghav Chamadiyac8046f05ea5a
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex c9c45e964..5dc42f21b 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -527,6 +527,8 @@ Only four tools answer across every repo with `repo="all"`. The rest return an e| `get_conformance` | No `"all"` value; it covers the whole workspace when `repo` is omitted || `get_blast_radius`, `get_architecture`, `list_repos` | No `repo` parameter; they always read the whole workspace |+With `repo` omitted, `get_context`, `get_symbol`, `get_risk` and `get_health` route each path or `path::Name` target to its repo: the default repo when the file exists there, else the one other repo whose checkout has it. Write `<alias>:<target>` (for example `web:src/app.ts::App`) to name the repo outright. A path found in several other repos returns its `candidates`. A path in no repo gets the default repo's usual not-found answer plus a `hint` naming `search_codebase(repo="all")` and the `<alias>:<path>` form; routed results carry `repo`. `get_context` takes a batch spanning repos, while `get_risk` and `get_health` answer one repo per call and name the per-repo calls when a batch spans several.+Single-repo tools also gain cross-repo evidence in workspace mode:- `get_context` adds a per-target `cross_repo` block: co-change partners in other repos and contract consumers or providers.diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex 81bb52e6d..7f563ffcb 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -521,6 +521,7 @@ Conformance and the cycle finder answer *per-relationship* questions (is this edWorkspace init registers the MCP server with your editors (skip with `--no-editor-setup`). The MCP server is workspace-aware:- **Default repo context**, queries go to the primary repo unless you specify otherwise+- **Target routing**, `get_context`, `get_symbol`, `get_risk` and `get_health` send a path that only another repo has to that repo, and accept `<alias>:<path>` targets ([details](../agent/MCP_TOOLS.md#workspace-mode))- **Cross-repo context**, single-repo tools add co-change and contract evidence from the other repos- **Repo parameter**, most tools accept an optional `repo` parameter to target a specific repo. Four also accept `"all"` to query across the workspace: `get_overview` (the cross-repo topology), `search_codebase` (results from every repo), `get_dead_code` (findings from every repo) and `get_why` with a query (decisions from every repo). The other tools answer about one repo at a time; see [MCP_TOOLS.md](../agent/MCP_TOOLS.md#workspace-mode)- **Opt-in workspace tools**, off by default and enabled with `mcp.tools` in `.repowise/config.yaml`: `get_blast_radius` ([Cross-Repo Blast Radius](#cross-repo-blast-radius)), `get_conformance` ([Architecture Conformance](#architecture-conformance)) and `get_architecture` ([Architecture Metrics](#architecture-metrics))diff --git a/packages/server/src/repowise/server/mcp_server/_workspace_routing.py b/packages/server/src/repowise/server/mcp_server/_workspace_routing.pynew file mode 100644index 000000000..600f63f6c--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/_workspace_routing.py@@ -0,0 +1,313 @@+"""Route path and symbol targets to the workspace repo that owns them.++Used by ``get_context``, ``get_symbol``, ``get_risk`` and ``get_health`` when+the server runs in workspace mode and the caller gave no ``repo``. Without it+a path from another repo silently answers about the default repo.++Rules, exact matches only:++- ``<alias>:<target>`` names the repo outright (``backend:src/app.py``,+ ``backend:src/app.py::App``). ``component:`` and ``module:`` stay target+ kinds, never repo prefixes.+- A path, or the file part of ``path::Name`` / ``path:120-140``, is served by+ the default repo when it exists there, as before. Otherwise it is routed to+ the one other repo whose checkout has it; when several do, the candidates+ are returned and nothing is guessed.+- A path in no repo falls through to the default repo, whose own not-found+ answer (suggestions, ``moved_to``) is kept; :func:`hint_misses` only adds a+ pointer to ``search_codebase``. In a change set it is a deleted file and+ gets no hint (:func:`settle_missing`).+- Bare names and opaque refs stay with the default repo: resolving them+ elsewhere needs a workspace-wide symbol locator.++Existence is checked on each repo's checkout, so routing opens no database.+Ceiling: one ``exists()`` per non-default repo per missed target; a workspace+locator replaces the probe when the workspace store lands.+"""++from __future__ import annotations++import os+from collections.abc import Awaitable, Callable, Collection, Sequence+from dataclasses import dataclass, replace+from pathlib import Path+from typing import Any++from repowise.server.mcp_server import _state+from repowise.server.mcp_server._query_shape import _LINE_SUFFIX_RE, _is_path++_TARGET_KINDS = frozenset({"component", "module"})+++@dataclass(frozen=True)+class Route:+ """Where one caller target is served."""++ target: str # as the caller wrote it+ local: str # the target inside its repo, any ``alias:`` prefix removed+ repo: str | None # owning alias; None when unresolved+ routed: bool = False # True when the repo came from a prefix or a lookup+ candidates: tuple[str, ...] = () # set when several repos have the path+ missed: bool = False # no repo has the path; served by the default repo++ @property+ def refusal(self) -> str | None:+ if self.repo is not None or not self.candidates:+ return None+ listed = ", ".join(self.candidates)+ return (+ f"'{self.target}' exists in several workspace repos ({listed}). "+ f"Name one: '{self.candidates[0]}:{self.local}', or pass repo=."+ )++ def card(self) -> dict[str, Any]:+ """The per-target entry for an unresolved route."""+ entry: dict[str, Any] = {"error": self.refusal}+ if self.candidates:+ entry["candidates"] = list(self.candidates)+ return entry+++def route_targets(targets: Sequence[str], *, paths_only: bool = False) -> list[Route] | None:+ """One :class:`Route` per target, or None outside workspace mode.++ ``paths_only`` reads every target without a path shape as a path anyway+ (``get_risk`` and ``get_health`` take only paths, and ``Makefile`` is one).+ """+ registry = _state._registry+ if registry is None:+ return None+ roots = _repo_roots()+ default = registry.get_default_alias()+ return [_route_one(t, roots, default, paths_only) for t in targets]+++def needs_routing(routes: list[Route] | None) -> bool:+ """True when any target needs more than the default repo's plain path."""+ return routes is not None and any(r.routed or r.missed or r.repo is None for r in routes)+++def single_repo(routes: list[Route]) -> str | None:+ """The one repo every route resolved to, or None."""+ repos = {r.repo for r in routes}+ return next(iter(repos)) if len(repos) == 1 and None not in repos else None+++def one_repo_refusal(tool: str, routes: list[Route]) -> dict[str, Any]:+ """For a tool that answers about one repo per call: what each target resolved to.++ Names the per-repo calls when the targets span repos, else the unresolved+ targets' own refusals.+ """+ unresolved = [r for r in routes if r.repo is None]+ if unresolved:+ error = " ".join(r.refusal or "" for r in unresolved)+ else:+ groups = _group(routes)+ calls = "; ".join(+ f'{tool}(targets={[r.local for r in rs]!r}, repo="{alias}")'+ for alias, rs in groups.items()+ )+ error = f"The targets span several workspace repos; {tool} reads one per call: {calls}."+ return {+ "error": error,+ "routes": {+ r.target: {"candidates": list(r.candidates)} if r.candidates else {"repo": r.repo}+ for r in routes+ },+ }+++def settle_missing(routes: list[Route], changed: Collection[str]) -> list[Route]:+ """Serve ``changed`` paths no checkout has from the batch's one repo, else the default.++ A change set names deleted files, so for ``changed_files`` absence is not a+ typo; the tool's own history reading answers for them as before. Other+ missing targets keep the default-repo not-found path and its hint.+ """+ registry = _state._registry+ if registry is None:+ return routes+ default = registry.get_default_alias()+ repos = {r.repo for r in routes if r.repo is not None and not r.missed}+ home = next(iter(repos)) if len(repos) == 1 else default+ return [+ replace(r, repo=home, routed=home != default, missed=False)+ if r.missed and r.target in changed+ else r+ for r in routes+ ]+++_MISS_HINT = (+ 'Not in any workspace repo. Find it with search_codebase(query=..., repo="all"), '+ "then pass '<alias>:<path>'."+)+++def hint_misses(response: dict[str, Any], routes: list[Route]) -> None:+ """Add the search hint to a not-found answer for each target no repo has."""+ missed = {r.target for r in routes if r.missed}+ if not missed:+ return+ cards = response.get("targets")+ if isinstance(cards, dict):+ for key, card in cards.items():+ if key in missed and isinstance(card, dict) and (+ card.get("error") or card.get("unresolved_reason")+ ):+ card["hint"] = _MISS_HINT+ for item in response.get("unresolved") or ():+ if isinstance(item, dict) and item.get("target") in missed:+ item["hint"] = _MISS_HINT+ if response.get("error") and not isinstance(cards, dict):+ response["hint"] = _MISS_HINT+++def rekey_targets(response: dict[str, Any], routes: list[Route]) -> None:+ """Key the ``targets`` map by what the caller wrote, not the local form."""+ targets = response.get("targets")+ if not isinstance(targets, dict):+ return+ original = {r.local: r.target for r in routes}+ response["targets"] = {original.get(k, k): v for k, v in targets.items()}+++async def run_grouped(+ routes: list[Route],+ call: Callable[[str, list[str]], Awaitable[dict[str, Any]]],+) -> dict[str, Any]:+ """Run ``call(alias, local_targets)`` once per repo and merge the ``targets`` maps.++ Cards keep the caller's target order and key; a routed card carries+ ``repo``. Top-level fields come from the default repo's call (else the+ first), with omission refs pooled so nothing dropped is unrecoverable.+ Sequential on purpose: shared fan-out belongs to one federation helper.+ """+ groups = _group([r for r in routes if r.repo is not None])+ results: dict[str, dict[str, Any]] = {}+ for alias, rs in groups.items():+ results[alias] = await call(alias, list(dict.fromkeys(r.local for r in rs)))++ default = _state._registry.get_default_alias() if _state._registry is not None else None+ lead = results.get(default) if default in results else next(iter(results.values()), {})+ merged: dict[str, Any] = {k: v for k, v in lead.items() if k != "targets"}+ for result in results.values():+ if result is not lead:+ _pool_omissions(merged, result)++ cards: dict[str, Any] = {}+ for r in routes:+ if r.repo is None:+ cards[r.target] = r.card()+ continue+ result = results[r.repo]+ card = (result.get("targets") or {}).get(r.local)+ if card is None:+ card = {"error": result.get("error") or f"No result for '{r.local}'"}+ cards[r.target] = {"repo": r.repo, **card} if r.routed else card+ merged.setdefault("_meta", {})+ response = {"targets": cards, **merged}+ hint_misses(response, routes)+ return response+++# -- internals ---------------------------------------------------------------+++def _repo_roots() -> dict[str, Path]:+ registry = _state._registry+ if registry is None:+ return {}+ base = Path(registry.workspace_root)+ return {e.alias: Path(os.path.normpath(base / e.path)) for e in registry.ws_config.repos}+++def _route_one(target: str, roots: dict[str, Path], default: str, paths_only: bool) -> Route:+ if target.partition(":")[0].casefold() in _TARGET_KINDS:+ return Route(target, target, default)+ alias, local = _split_prefix(target, roots)+ if alias is not None:+ return Route(target, local, alias, routed=True)+ file_part = _LINE_SUFFIX_RE.sub("", target.split("::", 1)[0])+ if not file_part or file_part.startswith("repowise#"):+ return Route(target, target, default)+ if not (paths_only or "::" in target or _is_path(file_part)):+ return Route(target, target, default)++ if Path(file_part).is_absolute():+ return _route_absolute(target, file_part, roots, default)+ if _exists(roots.get(default), file_part):+ return Route(target, target, default)+ owners = tuple(a for a, root in roots.items() if a != default and _exists(root, file_part))+ if len(owners) == 1:+ return Route(target, target, owners[0], routed=True)+ if len(owners) > 1:+ return Route(target, target, None, candidates=owners)+ return Route(target, target, default, missed=True)+++def _route_absolute(target: str, file_part: str, roots: dict[str, Path], default: str) -> Route:+ """An absolute path belongs to the repo whose checkout contains it."""+ path = Path(os.path.normpath(file_part))+ # Deepest root first: a nested repo owns its own files.+ for alias, root in sorted(roots.items(), key=lambda kv: -len(kv[1].parts)):+ if not _contains(root, path):+ continue+ if alias == default:+ return Route(target, target, default)+ local = path.relative_to(root).as_posix() + target[len(file_part) :]+ return Route(target, local, alias, routed=True)+ return Route(target, target, default, missed=True)+++def _split_prefix(target: str, roots: dict[str, Path]) -> tuple[str | None, str]:+ head, sep, rest = target.partition(":")+ if not sep or not rest or rest.startswith(":") or Path(target).is_absolute():+ return None, target+ for alias in roots:+ if alias.casefold() == head.strip().casefold():+ return alias, rest+ return None, target+++def _exists(root: Path | None, rel: str) -> bool:+ if root is None:+ return False+ norm = os.path.normpath(rel)+ if norm == ".." or norm.startswith(".." + os.sep):+ return False+ try:+ return (root / norm).exists()+ except (OSError, ValueError):+ return False+++def _contains(root: Path, path: Path) -> bool:+ try:+ rel = os.path.relpath(os.path.normcase(path), os.path.normcase(root))+ except ValueError: # another drive on Windows+ return False+ return rel == "." or not (rel == ".." or rel.startswith(".." + os.sep))+++def _group(routes: list[Route]) -> dict[str, list[Route]]:+ groups: dict[str, list[Route]] = {}+ for r in routes:+ groups.setdefault(r.repo or "", []).append(r)+ return groups+++def _pool_omissions(merged: dict[str, Any], other: dict[str, Any]) -> None:+ marker = other.get("omission_marker")+ if marker:+ merged["omission_marker"] = "\n".join(filter(None, [merged.get("omission_marker"), marker]))+ omitted = (other.get("_meta") or {}).get("omitted")+ if not isinstance(omitted, dict):+ return+ meta = merged.setdefault("_meta", {})+ mine = meta.get("omitted")+ if not isinstance(mine, dict):+ meta["omitted"] = omitted+ return+ mine["refs"] = list(dict.fromkeys([*(mine.get("refs") or []), *(omitted.get("refs") or [])]))diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.pyindex 4293fa316..268c327cf 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/context.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/context.py@@ -68,6 +68,11 @@ from repowise.server.mcp_server._helpers import ()from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._meta import completeness_line as _completeness_line+from repowise.server.mcp_server._workspace_routing import (+ needs_routing,+ route_targets,+ run_grouped,+)from repowise.server.mcp_server.tool_context.enrichment import attach_doc_referencesfrom repowise.server.mcp_server.tool_context.targets import _resolve_one_target@@ -149,6 +154,12 @@ async def get_context("""if repo == "all":return _unsupported_repo_all("get_context")+ routes = route_targets(targets) if repo is None else None+ if needs_routing(routes):+ return await run_grouped(+ routes,+ lambda alias, local: get_context(local, include=include, compact=compact, repo=alias),+ )ctx = await _resolve_repo_context(repo)collector = OmissionCollector("get_context", repo_root=ctx.path)diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py b/packages/server/src/repowise/server/mcp_server/tool_health/tool.pyindex 537680077..11e25c8f4 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/tool.py@@ -30,6 +30,13 @@ from repowise.server.mcp_server._helpers import (_unsupported_repo_all,)from repowise.server.mcp_server._meta import build_meta as _build_meta+from repowise.server.mcp_server._workspace_routing import (+ hint_misses,+ needs_routing,+ one_repo_refusal,+ route_targets,+ single_repo,+)from repowise.server.mcp_server.tool_health.analysis_meta import (_attach_health_analysis_meta,_attach_repository_analysis_meta,@@ -185,6 +192,13 @@ async def get_health()if conflict is not None:return _note_inapplicable_controls(conflict, scope, counts)+ routes = route_targets(targets, paths_only=True) if repo is None and targets else None+ routed_repo = None+ if needs_routing(routes):+ routed_repo = single_repo(routes)+ if routed_repo is None:+ return {**one_repo_refusal("get_health", routes), "_meta": _build_meta()}+ targets, repo = [r.local for r in routes], routed_reporeq = HealthRequest(targets=targets,include=include,@@ -260,6 +274,10 @@ async def get_health(_attach_semantics(result, req)# Server-side wall clock, as ``get_context`` reports.result["_meta"]["timing_ms"] = round((perf_counter() - started) * 1000, 2)+ if routed_repo is not None:+ if any(r.routed for r in routes):+ result["repo"] = routed_repo+ hint_misses(result, routes)return resultdiff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.pyindex 649dbb3a7..40f05b5e9 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py@@ -42,6 +42,15 @@ from repowise.server.mcp_server._test_selection import (files_change,select_change_tests,)+from repowise.server.mcp_server._workspace_routing import (+ hint_misses,+ needs_routing,+ one_repo_refusal,+ rekey_targets,+ route_targets,+ settle_missing,+ single_repo,+)from .assessment import (_assess_one_target,@@ -449,6 +458,29 @@ async def get_risk(return _unsupported_repo_all("get_risk")if not targets and not changed_files:return {"error": "targets or changed_files is required", "_meta": _build_meta()}+ routes = (+ route_targets([*(targets or []), *(changed_files or [])], paths_only=True)+ if repo is None+ else None+ )+ if routes is not None and changed_files:+ routes = settle_missing(routes, set(changed_files))+ if needs_routing(routes):+ alias = single_repo(routes)+ if alias is None:+ return {**one_repo_refusal("get_risk", routes), "_meta": _build_meta()}+ local = {r.target: r.local for r in routes}+ routed = await get_risk(+ [local[t] for t in targets] if targets else None,+ repo=alias,+ changed_files=[local[t] for t in changed_files] if changed_files else None,+ include=include,+ )+ rekey_targets(routed, routes)+ if any(r.routed for r in routes):+ routed["repo"] = alias+ hint_misses(routed, routes)+ return routedignored: list[dict] = []include_set = {blockdiff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.pyindex 9122d0e7b..461a048b9 100644--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py@@ -90,6 +90,11 @@ from repowise.server.mcp_server._verify import (heal_symbol_row,parse_live_symbols,)+from repowise.server.mcp_server._workspace_routing import (+ hint_misses,+ needs_routing,+ route_targets,+)_log = __import__("logging").getLogger("repowise.mcp.symbol")@@ -1054,6 +1059,19 @@ async def get_symbol(canonical_omission, omission_ref, query, ctx.path, t0)+ routes = route_targets([symbol_id.strip()]) if repo is None else None+ if needs_routing(routes):+ route = routes[0]+ if route.repo is None:+ return {"symbol_id": symbol_id, **route.card(), "_meta": _build_meta()}+ routed = await get_symbol(+ route.local, context_lines=context_lines, repo=route.repo, query=query, depth=depth+ )+ if route.routed:+ routed = {"repo": route.repo, **routed}+ hint_misses(routed, routes)+ return routed+# Range read: "path/to/file.py:140-180" (single colon + numeric range —# never collides with "{path}::{name}").range_match = _RANGE_ID_RE.match(symbol_id.strip())diff --git a/tests/unit/server/test_mcp_workspace_routing.py b/tests/unit/server/test_mcp_workspace_routing.pynew file mode 100644index 000000000..7e583d32a--- /dev/null+++ b/tests/unit/server/test_mcp_workspace_routing.py@@ -0,0 +1,250 @@+"""Workspace target routing for get_context, get_symbol, get_risk and get_health.++Builds on the two-repo ``workspace_mcp`` fixture (backend is the default, both+repos have ``src/probe.py``) and adds a third repo so a path can be ambiguous.+"""++from __future__ import annotations++import json+from types import SimpleNamespace++import pytest++from repowise.server.mcp_server import _state+from repowise.server.mcp_server._workspace_routing import Route, route_targets+from tests.unit.server.test_mcp_workspace import ( # noqa: F401 (fixture)+ _make_repo_context,+ workspace_mcp,+)+++async def routed_ws(workspace_mcp): # noqa: F811+ root = workspace_mcp.workspace_root+ docs_root = root / "docs-site"+ (docs_root / "src").mkdir(parents=True)+ workspace_mcp._contexts["docs"] = await _make_repo_context("docs", str(docs_root), pages=[])+ workspace_mcp.ws_config.repos.append(SimpleNamespace(alias="docs", path="docs-site"))+ (root / "web-client/src/only_fe.py").write_text("def only_fe():\n return 1\n")+ for repo in ("web-client", "docs-site"):+ (root / repo / "src/shared.py").write_text("def shared():\n return 2\n")+ return workspace_mcp+++def _by_target(routes: list[Route]) -> dict[str, Route]:+ return {r.target: r for r in routes}+++# -- the router -------------------------------------------------------------+++def test_router_is_off_outside_workspace_mode():+ assert _state._registry is None+ assert route_targets(["src/probe.py", "frontend:src/probe.py"]) is None+++async def test_router_rules(routed_ws):+ abs_fe = str(routed_ws.workspace_root / "web-client" / "src" / "only_fe.py")+ routes = _by_target(+ route_targets(+ [+ "src/probe.py",+ "src/only_fe.py",+ "FRONTEND:src/probe.py::frontend_probe",+ "src/shared.py",+ "src/nowhere.py",+ "module:src",+ "backend_probe",+ abs_fe,+ "src/only_fe.py:1-2",+ ]+ )+ )+ # Present in the default repo: served there, as before.+ assert routes["src/probe.py"] == Route("src/probe.py", "src/probe.py", "backend")+ assert routes["src/only_fe.py"].repo == "frontend"+ assert routes["src/only_fe.py"].routed+ prefixed = routes["FRONTEND:src/probe.py::frontend_probe"]+ assert (prefixed.repo, prefixed.local) == ("frontend", "src/probe.py::frontend_probe")+ assert routes["src/shared.py"].repo is None+ assert routes["src/shared.py"].candidates == ("frontend", "docs")+ assert routes["src/nowhere.py"].repo == "backend"+ assert routes["src/nowhere.py"].missed+ # Target kinds and bare names never leave the default repo.+ assert routes["module:src"] == Route("module:src", "module:src", "backend")+ assert routes["backend_probe"] == Route("backend_probe", "backend_probe", "backend")+ assert (routes[abs_fe].repo, routes[abs_fe].local) == ("frontend", "src/only_fe.py")+ assert routes["src/only_fe.py:1-2"].repo == "frontend"+++async def test_router_never_lets_a_path_escape_its_repo(routed_ws):+ (route,) = route_targets(["../web-client/src/only_fe.py"])+ assert (route.repo, route.missed) == ("backend", True)+++# -- get_context --------------------------------------------------------------+++async def test_get_context_default_repo_shape_unchanged(routed_ws):+ from repowise.server.mcp_server import get_context++ implicit = await get_context(targets=["src/probe.py"])+ explicit = await get_context(targets=["src/probe.py"], repo="backend")+ assert implicit["targets"] == explicit["targets"]+ assert "repo" not in implicit["targets"]["src/probe.py"]+ assert set(implicit) == set(explicit)+++async def test_get_context_routes_a_mixed_batch(routed_ws):+ from repowise.server.mcp_server import get_context++ targets = [+ "src/probe.py",+ "frontend:src/probe.py",+ "src/only_fe.py",+ "src/shared.py",+ "src/nowhere.py",+ ]+ result = await get_context(targets=targets)+ cards = result["targets"]++ assert list(cards) == targets+ assert "repo" not in cards["src/probe.py"]+ assert cards["src/probe.py"]["docs"]["title"] == "Backend Probe"+ assert cards["frontend:src/probe.py"]["repo"] == "frontend"+ assert cards["frontend:src/probe.py"]["docs"]["title"] == "Frontend Probe"+ assert cards["src/only_fe.py"]["repo"] == "frontend"+ assert cards["src/shared.py"]["candidates"] == ["frontend", "docs"]+ assert "frontend:src/shared.py" in cards["src/shared.py"]["error"]+ assert "Target not found" in cards["src/nowhere.py"]["error"]+ assert 'search_codebase(query=..., repo="all")' in cards["src/nowhere.py"]["hint"]+ assert "_meta" in result+++async def test_get_context_miss_keeps_the_default_repo_answer(routed_ws):+ from repowise.server.mcp_server import get_context++ plain = (await get_context(targets=["src/nowhere.py"], repo="backend"))["targets"]+ hinted = (await get_context(targets=["src/nowhere.py"]))["targets"]+ assert hinted["src/nowhere.py"].pop("hint")+ assert hinted == plain+++# -- get_symbol ---------------------------------------------------------------+++async def test_get_symbol_routes_repo_qualified_id(routed_ws):+ from repowise.server.mcp_server import get_symbol++ result = await get_symbol("frontend:src/probe.py::frontend_probe")+ assert result["repo"] == "frontend"+ assert result["name"] == "frontend_probe"+ assert "frontend_probe" in result["source"]+++async def test_get_symbol_routes_a_unique_path(routed_ws):+ from repowise.server.mcp_server import get_symbol++ result = await get_symbol("src/only_fe.py:1-2")+ assert result["repo"] == "frontend"+ assert "only_fe" in json.dumps(result)+++async def test_get_symbol_default_repo_unchanged(routed_ws):+ from repowise.server.mcp_server import get_symbol++ result = await get_symbol("src/probe.py::backend_probe")+ assert "repo" not in result+ assert result["name"] == "backend_probe"+++async def test_get_symbol_refuses_ambiguous_and_unknown(routed_ws):+ from repowise.server.mcp_server import get_symbol++ ambiguous = await get_symbol("src/shared.py::shared")+ assert ambiguous["candidates"] == ["frontend", "docs"]+ unknown = await get_symbol("src/nowhere.py::x")+ assert "error" in unknown+ assert 'search_codebase(query=..., repo="all")' in unknown["hint"]+ assert "repo" not in unknown+++# -- get_risk -----------------------------------------------------------------+++async def test_get_risk_routes_to_the_owning_repo(routed_ws):+ from repowise.server.mcp_server import get_risk++ result = await get_risk(targets=["frontend:src/probe.py"])+ assert result["repo"] == "frontend"+ assert list(result["targets"]) == ["frontend:src/probe.py"]+ default = await get_risk(targets=["src/probe.py"])+ assert "repo" not in default+++async def test_get_risk_refuses_a_cross_repo_batch(routed_ws):+ from repowise.server.mcp_server import get_risk++ result = await get_risk(targets=["src/probe.py", "src/only_fe.py"])+ assert 'get_risk(targets=[\'src/probe.py\'], repo="backend")' in result["error"]+ assert 'get_risk(targets=[\'src/only_fe.py\'], repo="frontend")' in result["error"]+ assert result["routes"]["src/only_fe.py"] == {"repo": "frontend"}+++async def test_get_risk_refuses_ambiguous_and_unknown(routed_ws):+ from repowise.server.mcp_server import get_risk++ ambiguous = await get_risk(targets=["src/shared.py"])+ assert ambiguous["routes"]["src/shared.py"] == {"candidates": ["frontend", "docs"]}+ unknown = await get_risk(targets=["src/nowhere.py"])+ assert "repo" not in unknown+ assert 'search_codebase(query=..., repo="all")' in unknown["targets"]["src/nowhere.py"]["hint"]+++async def test_get_risk_pr_mode_keeps_deleted_files_with_their_change(routed_ws):+ from repowise.server.mcp_server import get_risk++ result = await get_risk(changed_files=["src/only_fe.py", "src/deleted.py"])+ assert result["repo"] == "frontend"+ assert "error" not in result+++async def test_get_risk_pr_mode_leaves_a_missing_target_on_the_default_repo(routed_ws):+ from repowise.server.mcp_server import get_risk++ result = await get_risk(targets=["src/nowhere.py"], changed_files=["src/only_fe.py"])+ assert result["routes"]["src/nowhere.py"] == {"repo": "backend"}+ assert result["routes"]["src/only_fe.py"] == {"repo": "frontend"}+++# -- get_health ---------------------------------------------------------------+++async def test_get_health_routes_to_the_owning_repo(routed_ws):+ from repowise.server.mcp_server import get_health++ result = await get_health(targets=["frontend:src/probe.py"])+ assert result["repo"] == "frontend"+ assert "frontend_probe_health" in json.dumps(result)+ assert "backend_probe_health" not in json.dumps(result)+++async def test_get_health_default_repo_unchanged(routed_ws):+ from repowise.server.mcp_server import get_health++ result = await get_health(targets=["src/probe.py"])+ assert "repo" not in result+ assert "backend_probe_health" in json.dumps(result)+++async def test_get_health_refuses_cross_repo_and_ambiguous_hints_unknown(routed_ws):+ from repowise.server.mcp_server import get_health++ mixed = await get_health(targets=["src/probe.py", "src/only_fe.py"])+ assert "get_health(targets=" in mixed["error"]+ ambiguous = await get_health(targets=["src/shared.py"])+ assert ambiguous["routes"]["src/shared.py"] == {"candidates": ["frontend", "docs"]}+ unknown = await get_health(targets=["src/nowhere.py"])+ assert "repo" not in unknown+ assert "search_codebase" in unknown["unresolved"][0]["hint"]