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): run repo="all" through one federation helper with partial results (#3742)
Raghav Chamadiya5afc283f7ce4
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 5dc42f21b..d6c5f738f 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -529,6 +529,8 @@ Only four tools answer across every repo with `repo="all"`. The rest return an eWith `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.+A `repo="all"` call queries up to 4 repos at a time and gives each 60 seconds (`REPOWISE_WORKSPACE_CONCURRENCY`, `REPOWISE_WORKSPACE_REPO_TIMEOUT_S`). A repo that fails to open, errors or times out is listed in `repos_failed` with its reason while the other repos still answer. A repo whose index is behind its checkout is listed in `repos_stale` with `indexed_commit` and `live_head`, and its rows carry `stale: true`. Both keys appear only when non-empty.+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/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex 2c81c8fcb..9be9c814c 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -45,7 +45,7 @@ Routine responses carry a lean envelope. `get_overview`, called once per session| `floor` | When a count comes from walking the graph | Names those fields. Their values are lower bounds: an unresolved edge is uncounted, not proven absent || `state` | Only when something fired | `degraded` with `degraded_reasons`, `partial`, `truncated`. A roll-up of the response's own flags |-`list_repos`, `get_architecture`, `get_blast_radius`, `get_conformance` and `get_dependency_path` carry no freshness fields. Neither does a workspace-wide `search_codebase(repo="all")`, since there is no single indexed commit to compare.+`list_repos`, `get_architecture`, `get_blast_radius`, `get_conformance` and `get_dependency_path` carry no freshness fields. Neither does a workspace-wide `repo="all"` call, since there is no single indexed commit to compare; it names stale repos in a top-level `repos_stale` instead.---diff --git a/packages/core/src/repowise/core/workspace/registry.py b/packages/core/src/repowise/core/workspace/registry.pyindex 903da2500..64091977b 100644--- a/packages/core/src/repowise/core/workspace/registry.py+++ b/packages/core/src/repowise/core/workspace/registry.py@@ -92,6 +92,8 @@ class RepoRegistry:self._contexts: dict[str, RepoContext] = {}self._access_order: dict[str, float] = {}self._vs_tasks: dict[str, asyncio.Task[None]] = {}+ # Serialises loads so concurrent callers can't overshoot the cap.+ self._load_lock = asyncio.Lock()self._validate_public_identities()def _identity_key(self, value: str | Path) -> str:@@ -195,18 +197,22 @@ class RepoRegistry:self._access_order[alias] = time.monotonic()return self._contexts[alias]- # Evict if at capacity. The default repo is protected from eviction, so- # only count non-default contexts against the cap — this prevents the- # cap from being silently bypassed when the default is always loaded.- default_alias = self.get_default_alias()- evictable = [a for a in self._contexts if a != default_alias]- if len(evictable) >= self.MAX_LOADED:- await self._evict_lru()-- ctx = await self._load_context(alias)- self._contexts[alias] = ctx- self._access_order[alias] = time.monotonic()- return ctx+ async with self._load_lock:+ if alias in self._contexts:+ self._access_order[alias] = time.monotonic()+ return self._contexts[alias]+ # Evict if at capacity. The default repo is protected from eviction, so+ # only count non-default contexts against the cap — this prevents the+ # cap from being silently bypassed when the default is always loaded.+ default_alias = self.get_default_alias()+ evictable = [a for a in self._contexts if a != default_alias]+ if len(evictable) >= self.MAX_LOADED:+ await self._evict_lru()++ ctx = await self._load_context(alias)+ self._contexts[alias] = ctx+ self._access_order[alias] = time.monotonic()+ return ctxasync def get_default(self) -> RepoContext:"""Shortcut for ``get(default_alias)``."""@@ -239,7 +245,12 @@ class RepoRegistry:engine, session_factory = await open_repo_db(repo_path)fts = FullTextSearch(engine)- await fts.ensure_index()+ try:+ await fts.ensure_index()+ except BaseException:+ # A timeout cancels here; don't leak the engine.+ await engine.dispose()+ raise# Seed placeholder vector stores.# decision_store is repointed to the shared page store — decisions arediff --git a/packages/server/src/repowise/server/mcp_server/_federation.py b/packages/server/src/repowise/server/mcp_server/_federation.pynew file mode 100644index 000000000..1e8254af3--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/_federation.py@@ -0,0 +1,229 @@+"""Workspace fan-out for ``repo="all"``: one per-repo call run across every repo.++Every tool that answers across the workspace goes through :class:`Federation`,+so concurrency, timeouts, partial results and freshness mean the same thing in+each of them. A repo that cannot be opened, raises or runs past its timeout is+named in ``repos_failed`` and the rest still answer; a repo whose index is+behind its checkout is named in ``repos_stale`` and its rows carry+``stale: true``. Both keys are added only when non-empty, so a healthy+workspace gets the response shape it always had.++The merge rules live here too, one per kind of result: ranked lists+(:func:`merge_ranked`), findings (:func:`merge_findings`) and aggregates+(:func:`sum_fields`).+"""++from __future__ import annotations++import asyncio+import logging+import os+from collections.abc import Awaitable, Callable, Iterable, Sequence+from typing import Any, TypeVar++from repowise.core.persistence.database import get_session+from repowise.server.mcp_server import _state+from repowise.server.mcp_server._helpers import _get_repo, _resolve_repo_context+from repowise.server.mcp_server._meta import freshness_from_repo, served_root++_log = logging.getLogger("repowise.mcp")++T = TypeVar("T")++_CONCURRENCY_ENV = "REPOWISE_WORKSPACE_CONCURRENCY"+# Kept below the registry's open-repo cap (5 plus the default) so the repos in+# flight fit in it together.+_CONCURRENCY_DEFAULT = 4+_TIMEOUT_ENV = "REPOWISE_WORKSPACE_REPO_TIMEOUT_S"+# A cold repo pays its vector-store open (bounded at 30s) before searching.+_TIMEOUT_DEFAULT_S = 60.0+_TIMEOUT_MAX_S = 300.0+_REASON_MAX_CHARS = 200+++def _env_number(name: str, default: float, ceiling: float) -> float:+ """A positive number from the environment, else *default* (with a warning)."""+ raw = (os.environ.get(name) or "").strip()+ if not raw:+ return default+ try:+ value = float(raw)+ except ValueError:+ value = float("nan")+ if not value > 0:+ _log.warning("Ignoring unusable %s=%r", name, raw)+ return default+ return min(value, ceiling)+++def fanout_concurrency() -> int:+ """Repos queried at once, from env or the default, never above the open-repo cap."""+ limit = int(_env_number(_CONCURRENCY_ENV, _CONCURRENCY_DEFAULT, 64)) or 1+ cap = getattr(_state._registry, "MAX_LOADED", None)+ return min(limit, cap) if isinstance(cap, int) and cap > 0 else limit+++def fanout_timeout_s() -> float:+ """Seconds one repo's share of a call may take, from env or the default."""+ return _env_number(_TIMEOUT_ENV, _TIMEOUT_DEFAULT_S, _TIMEOUT_MAX_S)+++async def _open(alias: str | None) -> Any:+ registry = _state._registry+ if registry is None:+ return await _resolve_repo_context(None)+ return await registry.get(alias)+++def _stale_entry(alias: str, repository: Any, root: str | None) -> dict[str, Any] | None:+ """The repo-level freshness verdict every single-repo response already gives.++ Stale means ``_meta`` would warn for a repo-level answer: HEAD moved past the+ indexed commit with real file changes, or the index is very old with no git.+ """+ fresh = freshness_from_repo(repository, targets=None, root=root)+ if "stale_warning" not in fresh:+ return None+ entry: dict[str, Any] = {"repo": alias}+ for key in ("indexed_commit", "live_head", "index_age_days"):+ if fresh.get(key) is not None:+ entry[key] = fresh[key]+ return entry+++class Federation:+ """One ``repo="all"`` call: run per-repo work, remember who failed or is stale.++ :meth:`run` may be called more than once in a call (a tool with several+ stages); a repo that failed an earlier stage is skipped by later ones.++ Ceiling: contexts come from the registry's LRU, so a workspace larger than+ its cap still reopens repos on every call and can evict one mid-call (that+ repo then lands in ``repos_failed`` rather than failing the call). Short-lived+ read-only connections for fan-out are the upgrade path.+ """++ def __init__(self, *, concurrency: int | None = None, timeout_s: float | None = None):+ registry = _state._registry+ self._aliases: list[str | None] = registry.get_all_aliases() if registry else [None]+ self._semaphore = asyncio.Semaphore(concurrency or fanout_concurrency())+ self._timeout_s = timeout_s or fanout_timeout_s()+ self._failed: dict[str | None, str] = {}+ self._stale: dict[str, dict[str, Any]] = {}+ self._checked: set[str] = set()++ @property+ def multi(self) -> bool:+ """More than one repo configured: rows are tagged by repo even if one failed."""+ return len(self._aliases) > 1++ async def run(self, fn: Callable[[Any], Awaitable[T]]) -> list[tuple[Any, T]]:+ """``(context, fn(context))`` for every repo that answered, in workspace order."""+ live = [alias for alias in self._aliases if alias not in self._failed]+ outcomes = await asyncio.gather(*(self._one(alias, fn) for alias in live))+ return [outcome for outcome in outcomes if outcome is not None]++ async def _one(self, alias: str | None, fn: Callable[[Any], Awaitable[T]]) -> tuple[Any, T] | None:+ async with self._semaphore:+ try:+ return await asyncio.wait_for(self._call(alias, fn), self._timeout_s)+ except TimeoutError:+ reason = f"timed out after {self._timeout_s:g}s"+ except Exception as exc:+ _log.warning("repo=all: repo %r failed", alias, exc_info=True)+ reason = f"{type(exc).__name__}: {exc}"[:_REASON_MAX_CHARS]+ self._failed[alias] = reason+ return None++ async def _call(self, alias: str | None, fn: Callable[[Any], Awaitable[T]]) -> tuple[Any, T]:+ ctx = await _open(alias)+ if ctx.alias not in self._checked:+ self._checked.add(ctx.alias)+ await self._check_freshness(ctx)+ return ctx, await fn(ctx)++ async def _check_freshness(self, ctx: Any) -> None:+ # A freshness probe that fails says nothing about the repo's answer.+ try:+ async with get_session(ctx.session_factory) as session:+ repository = await _get_repo(session)+ root = served_root(repository, ctx.path)+ # May spawn git (ancestry, changed files), so off the event loop.+ entry = await asyncio.to_thread(_stale_entry, ctx.alias, repository, root)+ except Exception:+ _log.debug("repo=all: freshness check failed for %r", ctx.alias, exc_info=True)+ return+ if entry is not None:+ self._stale[ctx.alias] = entry++ def annotate(+ self, response: dict[str, Any], rows: Iterable[Any] = (), *, repo_key: str = "repo"+ ) -> dict[str, Any]:+ """Add ``repos_failed`` / ``repos_stale`` when non-empty; mark stale repos' rows."""+ if self._stale:+ for row in rows:+ if isinstance(row, dict) and row.get(repo_key) in self._stale:+ row["stale"] = True+ if self._failed:+ response["repos_failed"] = [+ {"repo": alias or "default", "reason": reason}+ for alias in self._aliases+ if (reason := self._failed.get(alias)) is not None+ ]+ if self._stale:+ response["repos_stale"] = [+ self._stale[alias] for alias in self._aliases if alias in self._stale+ ]+ return response+++# ---------------------------------------------------------------------------+# Merge rules+# ---------------------------------------------------------------------------+++def merge_ranked(+ groups: Iterable[Sequence[T]],+ key: Callable[[T], Any],+ *,+ limit: int | None = None,+ per_repo_cap: int | None = None,+) -> list[T]:+ """Ranked lists: one order across repos by ascending *key*.++ Each group is one repo's list in its own best-first order, given in+ workspace order. The sort is stable, so equal keys fall back to workspace+ order and then to each repo's own order: the same inputs always merge the+ same way. *per_repo_cap* keeps one repo from filling the window.+ """+ pooled: list[T] = []+ for group in groups:+ pooled.extend(group[:per_repo_cap] if per_repo_cap is not None else group)+ pooled.sort(key=key)+ return pooled[:limit] if limit is not None else pooled+++def merge_findings(groups: Iterable[tuple[str, Iterable[dict[str, Any]]]]) -> list[dict[str, Any]]:+ """Findings: concatenated in workspace order, each tagged with its ``repo``.++ Ranking is left to the caller, whose scores (confidence, severity) already+ mean the same thing in every repo.+ """+ merged: list[dict[str, Any]] = []+ for alias, rows in groups:+ for row in rows:+ row["repo"] = alias+ merged.append(row)+ return merged+++def sum_fields(rows: Iterable[dict[str, Any]], fields: Sequence[str]) -> dict[str, int]:+ """Aggregates: per-field totals over the repos that answered.++ The basis is the rows summed; a repo in ``repos_failed`` is not in it.+ """+ totals = dict.fromkeys(fields, 0)+ for row in rows:+ for field in fields:+ totals[field] += row.get(field) or 0+ return totalsdiff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.pyindex a2239c0ab..3fe078926 100644--- a/packages/server/src/repowise/server/mcp_server/_helpers.py+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py@@ -197,26 +197,11 @@ async def _resolve_repo_context(repo: str | None = None) -> Any:if isinstance(resolved, list):raise ValueError("repo='all' must be handled explicitly by each tool. "- "Use _resolve_all_contexts() instead."+ "Fan out with _federation.Federation instead.")return await registry.get(resolved)-async def _resolve_all_contexts() -> list[Any]:- """Return ``RepoContext`` objects for all repos in the workspace.-- In single-repo mode, returns a single-element list wrapping ``_state``.- """- registry = _state._registry- if registry is None:- ctx = await _resolve_repo_context(None)- return [ctx]- contexts = []- for alias in registry.get_all_aliases():- contexts.append(await registry.get(alias))- return contexts--def _unsupported_repo_all(tool_name: str) -> dict:"""Return an error dict for tools that don't support ``repo='all'``."""registry = _state._registrydiff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.pyindex e50592c74..f2aff0224 100644--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py@@ -35,11 +35,11 @@ from repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server import _statefrom repowise.server.mcp_server._basis import call_resolution_basesfrom repowise.server.mcp_server._budget import OmissionCollector+from repowise.server.mcp_server._federation import Federation, merge_findingsfrom repowise.server.mcp_server._helpers import (_get_exclude_spec,_get_repo,_is_workspace_mode,- _resolve_all_contexts,_resolve_repo_context,attach_ignored_arguments,filter_rows_by_attr,@@ -64,38 +64,37 @@ async def _get_dead_code_all_repos(apply_limit_note: Callable[[dict[str, Any]], None],) -> dict:"""Aggregate dead-code findings across every repo in the workspace."""- contexts = await _resolve_all_contexts()- merged_findings: list[dict] = []- count_parts: list[dict[str, Any]] = []- merged_withheld: dict[str, dict] = {}- merged_gated: dict[str, dict] = {}- for ctx in contexts:+ async def _one_repo(ctx: Any) -> tuple[list[dict], dict[str, Any], dict, dict]:async with get_session(ctx.session_factory) as session:repository = await _get_repo(session)-repo_findings = filter_rows_by_attr(await get_dead_code_findings(session, repository.id, include_withheld=True),"file_path",_get_exclude_spec(ctx.path),)- repo_findings, repo_withheld = filters.split_withheld(repo_findings)- repo_findings, repo_gated = filters.split_gated(repo_findings)- for into, held in ((merged_withheld, repo_withheld), (merged_gated, repo_gated)):- for name, entry in held.items():- merged = into.setdefault(name, {**entry, "count": 0})- merged["count"] += entry["count"]-+ repo_findings, withheld = filters.split_withheld(repo_findings)+ repo_findings, gated = filters.split_gated(repo_findings)git_meta_map = await _load_git_meta_map(session, repository.id, repo_findings)-- for f in apply_filters(repo_findings, filters):- serialized = serialize_finding(f, git_meta_map, repository=ctx.alias)- serialized["repo"] = ctx.alias- merged_findings.append(serialized)- count_parts.append(summary_counts(repo_findings))+ serialized = [+ serialize_finding(f, git_meta_map, repository=ctx.alias)+ for f in apply_filters(repo_findings, filters)+ ]+ return serialized, summary_counts(repo_findings), withheld, gated++ fed = Federation()+ answered = await fed.run(_one_repo)+ merged_findings = merge_findings((ctx.alias, part[0]) for ctx, part in answered)+ merged_withheld: dict[str, dict] = {}+ merged_gated: dict[str, dict] = {}+ for _, (_, _, withheld, gated) in answered:+ for into, held in ((merged_withheld, withheld), (merged_gated, gated)):+ for name, entry in held.items():+ merged = into.setdefault(name, {**entry, "count": 0})+ merged["count"] += entry["count"]summary = build_summary(- merge_summary_counts(count_parts),+ merge_summary_counts([part[1] for _, part in answered]),len(merged_findings),filters,merged_withheld,@@ -112,6 +111,7 @@ async def _get_dead_code_all_repos(}apply_limit_note(result_ws)result_ws["_meta"] = _build_meta()+ fed.annotate(result_ws, merged_findings)return result_ws@@ -248,23 +248,29 @@ async def get_dead_code(# --- repo="all": aggregate dead code across all repos ---if repo == "all":if finding_id:- for candidate_ctx in await _resolve_all_contexts():- resolved = await get_dead_code(- repo=candidate_ctx.alias,+ fed = Federation()+ probes = await fed.run(+ lambda ctx: get_dead_code(+ repo=ctx.alias if _is_workspace_mode() else None,min_confidence="low",finding_id=finding_id,)+ )+ # Workspace order decides between two repos that both claim the id.+ for _, resolved in probes:if resolved.get("resolved"):resolved["workspace"] = True- return resolved- return {- "mode": "finding",- "finding_id": finding_id,- "finding": None,- "resolved": False,- "workspace": True,- "_meta": _build_meta(),- }+ return fed.annotate(resolved)+ return fed.annotate(+ {+ "mode": "finding",+ "finding_id": finding_id,+ "finding": None,+ "resolved": False,+ "workspace": True,+ "_meta": _build_meta(),+ }+ )result_ws = await _get_dead_code_all_repos(filters, limit, tier, _maybe_limit_note)attach_ignored_arguments(result_ws, ignored)return result_wsdiff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/workspace.py b/packages/server/src/repowise/server/mcp_server/tool_overview/workspace.pyindex e8af77ff3..3d0f52a5a 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview/workspace.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/workspace.py@@ -11,7 +11,8 @@ from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import GraphNodefrom repowise.server.mcp_server import _statefrom repowise.server.mcp_server._budget import OmissionCollector-from repowise.server.mcp_server._helpers import _get_repo, _resolve_all_contexts+from repowise.server.mcp_server._federation import Federation, sum_fields+from repowise.server.mcp_server._helpers import _get_repofrom repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server.tool_overview.pages import _load_overview_pagefrom repowise.server.mcp_server.tool_overview.surface import _tool_surface_guide@@ -19,17 +20,18 @@ from repowise.server.mcp_server.tool_overview.surface import _tool_surface_guideasync def _workspace_overview() -> dict:"""Build a concise workspace-level overview across all repos."""- contexts = await _resolve_all_contexts()registry = _state._registry- repos_info = [await _repo_entry(ctx, registry) for ctx in contexts]+ fed = Federation()+ repos_info = [entry for _, entry in await fed.run(lambda ctx: _repo_entry(ctx, registry))]cross_repo_topology = _cross_repo_topology(repos_info)+ totals = sum_fields(repos_info, ("file_count", "symbol_count"))result: dict[str, Any] = {"workspace": True,"workspace_root": str(registry.workspace_root) if registry else "","total_repos": len(repos_info),- "total_files": sum(r["file_count"] for r in repos_info),- "total_symbols": sum(r["symbol_count"] for r in repos_info),+ "total_files": totals["file_count"],+ "total_symbols": totals["symbol_count"],"repos": repos_info,"hint": ("Use repo='<alias>' to query a specific repo. Omit repo to use the default."),"tool_surface": _tool_surface_guide(is_workspace=True),@@ -42,7 +44,7 @@ async def _workspace_overview() -> dict:"get_overview", repo_root=registry.workspace_root if registry else None)collector.attach(result)- return result+ return fed.annotate(result, repos_info, repo_key="alias")async def _repo_entry(ctx: Any, registry: Any) -> dict[str, Any]:diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.pyindex 298fa3c0c..a0bdef1ce 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py@@ -36,11 +36,11 @@ from repowise.server.mcp_server._budget import (register_post_enforce,register_post_shed,)+from repowise.server.mcp_server._federation import Federation, merge_rankedfrom repowise.server.mcp_server._helpers import (_VECTOR_TIMEOUT_ENV,_get_exclude_spec,_get_repo,- _resolve_all_contexts,_resolve_repo_context,attach_ignored_arguments,filter_dicts_by_key,@@ -898,30 +898,37 @@ async def _search_single_repo(return _collapse_by_file(output)[:limit]+def _neg_score(key: str):+ """Best-first sort key on a row's *key* score, for :func:`merge_ranked`."""+ return lambda item: -(item.get(key) or 0.0)++async def _federated_search(- query: str, limit: int, page_type: str | None, kind: str | None = None+ query: str, limit: int, page_type: str | None, kind: str | None, fed: Federation) -> dict:"""Search across all repos using Reciprocal Rank Fusion."""- contexts = await _resolve_all_contexts()- all_results = []- for ctx in contexts:+ async def _one_repo(ctx) -> list[dict]:repo_results = await _search_single_repo(ctx, query, limit, page_type, kind)for rank, item in enumerate(repo_results):item["repo"] = ctx.aliasitem["rrf_score"] = 1.0 / (rank + 60) # RRF constant k=60- all_results.extend(repo_results)+ return repo_results- # Sort by RRF score and take top N- all_results.sort(key=lambda x: x.get("rrf_score", 0), reverse=True)+ answered = await fed.run(_one_repo)+ contexts = [ctx for ctx, _ in answered]+ all_results = merge_ranked(+ (rows for _, rows in answered), _neg_score("rrf_score"), per_repo_cap=limit+ )output = all_results[:limit]# Derive confidence from RRF position_assign_confidence(output, "rrf_score", "confidence_score")- # No freshness here: results come from several repos at once, so there is- # no single indexed commit to compare a live HEAD against.+ # No single indexed commit to compare a live HEAD against: per-repo+ # freshness rides on ``repos_stale`` and the rows' ``stale`` flag instead.response: dict = {"results": output, "_meta": _build_meta()}+ fed.annotate(response, output)# Drawn from every repo's ranked list, not the merged cut: a workspace# search that spends its window on module pages should still be able to# name files.@@ -996,11 +1003,12 @@ def _grep_hint_for(query: str, names: Container[str] | None = None) -> str | Nonreturn None-async def _contexts_for(repo: str | None) -> list:- """The repo contexts a structured search runs over (one, or all in 'all')."""- if repo == "all":- return await _resolve_all_contexts()- return [await _resolve_repo_context(repo)]+async def _per_repo(repo: str | None, fed: Federation | None, fn) -> list[tuple[Any, Any]]:+ """``(context, fn(context))`` for the one repo asked for, or every repo via *fed*."""+ if fed is not None:+ return await fed.run(fn)+ ctx = await _resolve_repo_context(repo)+ return [(ctx, await fn(ctx))]def _lead_candidates(response: dict, issue: IssueFiles | None, limit: int) -> None:@@ -1054,6 +1062,7 @@ async def _structured_search(mode: str,grep_hint: str | None,names: Container[str] | None = None,+ fed: Federation | None = None,) -> dict:"""Run symbol / path / hybrid search and shape the response.@@ -1062,16 +1071,7 @@ async def _structured_search(single-repo helpers). The grep_hint is attached only as a fallback — whenthe structural index produced nothing, the agent still has a path forward."""- contexts = await _contexts_for(repo)- multi = len(contexts) > 1-- symbols: list[dict] = []- # Symbol rows past each repo's ``limit``: they only backfill slots that- # collapsing same-file rows frees, and never steer the exact-match signal.- spare: list[dict] = []- files: list[dict] = []- indexed_paths: list[str] = []- concepts: list[dict] = []+ multi = fed is not None and fed.multi# A hybrid query is prose wrapped around an identifier ("where is X# defined"). The symbol scorer ranks on token overlap, so handing it the@@ -1094,32 +1094,41 @@ async def _structured_search(fetch = limit * _FILE_WINDOW_OVERFETCH if mode == "hybrid" else limitif mode == "symbol":fetch = _MAX_CANDIDATES- for ctx in contexts:++ async def _one_repo(ctx) -> tuple[list[dict], list[dict], list[str], list[dict]]:+ s: list[dict] = []+ f: list[dict] = []+ paths: list[str] = []+ c: list[dict] = []if mode in ("symbol", "hybrid"):s = await search_symbols_single(ctx, symbol_query, fetch, symbol_kind=symbol_kind, kind=kind)- _tag_repo(s, ctx, multi)- symbols.extend(s[:limit])- spare.extend(s[limit:])if mode == "path":f = await search_paths_single(ctx, query, limit)async with get_session(ctx.session_factory) as session:- index = await file_path_index(session, (await _get_repo(session)).id)- indexed_paths.extend(index.paths)- _tag_repo(f, ctx, multi)- files.extend(f)+ paths = (await file_path_index(session, (await _get_repo(session)).id)).pathsif mode == "hybrid":c = await _search_single_repo(ctx, query, limit, page_type, kind)for item in c:item["type"] = "page"await attach_hit_symbols(ctx, query, c)- _tag_repo(c, ctx, multi)- concepts.extend(c)+ for rows in (s, f, c):+ _tag_repo(rows, ctx, multi)+ return s, f, paths, c- symbols.sort(key=lambda x: -(x.get("score") or 0.0))- spare.sort(key=lambda x: -(x.get("score") or 0.0))- files.sort(key=lambda x: -(x.get("score") or 0.0))+ answered = await _per_repo(repo, fed, _one_repo)+ contexts = [ctx for ctx, _ in answered]+ parts = [part for _, part in answered]+ # Symbol rows past each repo's ``limit``: they only backfill slots that+ # collapsing same-file rows frees, and never steer the exact-match signal.+ symbols = merge_ranked((p[0] for p in parts), _neg_score("score"), per_repo_cap=limit)+ spare = merge_ranked((p[0][limit:] for p in parts), _neg_score("score"))+ files = merge_ranked((p[1] for p in parts), _neg_score("score"))+ indexed_paths = [path for p in parts for path in p[2]]+ # Re-ranked by relevance so a strong page in repo B isn't buried under+ # repo A's weak ones.+ concepts = merge_ranked((p[3] for p in parts), _neg_score("relevance_score"))candidates = _identifier_candidates(query, mode, names)if mode == "symbol":symbols = _protect_exact_symbols(query, symbols)@@ -1153,10 +1162,6 @@ async def _structured_search(elif mode == "path":results = files[:limit]else: # hybrid: interleave symbol matches and concept pages for new files- # Federation appends per-repo concept lists in repo order — re-rank by- # relevance so a strong page in repo B isn't buried under repo A's weak- # ones. (Single-repo: already sorted upstream; this is a no-op.)- concepts.sort(key=lambda x: -(x.get("relevance_score") or 0.0))window = _hybrid_window(query, symbols, concepts, limit, exact, names)# One row per file, so ``limit`` buys distinct files (mode "symbol"# stays row-per-symbol: overloads there are the answer). Collapsing@@ -1174,7 +1179,7 @@ async def _structured_search(results = [item for item in results if hit_file_path(item)]repository = None- if not multi:+ if not multi and contexts:async with get_session(contexts[0].session_factory) as session:repository = await _get_repo(session)@@ -1231,6 +1236,8 @@ async def _structured_search()if grep_hint and not results:response["grep_hint"] = grep_hint+ if fed is not None:+ fed.annotate(response, results)# Last, so nothing above has to know the field is on its way out. Paths# first, so a page whose target_path is dropped keeps its page_id._slim_served_rows(@@ -1319,8 +1326,13 @@ async def search_codebase(if mode is not None and mode.lower() in _VALID_MODES:mode = mode.lower()mode = resolve_enum_argument(mode, _VALID_MODES, argument="mode", ignored=ignored)+ # One fan-out state for the whole call: a repo that fails one stage is+ # skipped by the next and reported once.+ fed = Federation() if repo == "all" else None# Loaded once so routing, candidates, ordering and the hint validate alike.- names = await indexed_names(await _contexts_for(repo), query)+ names: set[str] = set()+ for _, repo_names in await _per_repo(repo, fed, lambda ctx: indexed_names([ctx], query)):+ names |= repo_namesgrep_hint = _grep_hint_for(query, names)resolved_mode = _resolve_mode(query, mode, names)# Single repo only: a federated list has no one tree to name files in.@@ -1333,17 +1345,17 @@ async def search_codebase(if resolved_mode in ("symbol", "path", "hybrid"):structured = await _structured_search(- query, limit, page_type, kind, symbol_kind, repo, resolved_mode, grep_hint, names+ query, limit, page_type, kind, symbol_kind, repo, resolved_mode, grep_hint, names, fed)_lead_candidates(structured, issue, limit)await attach_line_hits(structured, query, resolved_mode, names, repo)attach_ignored_arguments(structured, ignored)return structured- if repo == "all":+ if fed is not None:# kind is filtered per-repo inside _search_single_repo, before each# repo's limit cut, so the fused list is already kind-pure and full.- federated = await _federated_search(query, limit, page_type, kind)+ federated = await _federated_search(query, limit, page_type, kind, fed)if grep_hint and not federated.get("results"):federated["grep_hint"] = grep_hintattach_ignored_arguments(federated, ignored)diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/workspace.py b/packages/server/src/repowise/server/mcp_server/tool_why/workspace.pyindex be4116044..2c111299f 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why/workspace.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why/workspace.py@@ -9,11 +9,11 @@ from repowise.server.mcp_server._budget import (OmissionCollector,cap_collection,)+from repowise.server.mcp_server._federation import Federation, merge_rankedfrom repowise.server.mcp_server._helpers import (_decision_body,_get_exclude_spec,_get_repo,- _resolve_all_contexts,)from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._why_evidence import (@@ -42,43 +42,25 @@ async def _why_workspace_search(query: str) -> dict:decide which store loses a slot, approximately. If that ever needs to beexact, sweep a floor against a pooled corpus rather than pool under this one."""- scored = await _score_workspace(query)- if not scored:- return {- "mode": "search",- "query": query,- "workspace": True,- "decisions": [],- **redirect_for(query),- "_meta": _build_meta(),- }-+ fed = Federation()+ answered = await fed.run(lambda ctx: _score_repo(ctx, query))# The store's own key first; alias and id settle ties, for a stable order.- scored.sort(key=lambda t: (t[0], t[1], t[3]))- selected = scored- collector = OmissionCollector(- "get_why", repo_root=selected[0][2].path if selected else None- )- for selected_ctx in {entry[2].alias: entry[2] for entry in selected}.values():- selected_records = [entry[4] for entry in selected if entry[2] is selected_ctx]- async with get_session(selected_ctx.session_factory) as session:- await _attach_decision_evidence(session, selected_records)- decisions: list[dict] = []- entries_by_alias: dict[str, list[dict[str, Any]]] = {}- records_by_alias: dict[str, list[Any]] = {}- contexts_by_alias = {entry[1]: entry[2] for entry in selected}- for _, alias, _selected_ctx, _id, d, folded in selected:- entry = _workspace_entry(alias, d, folded)- entries_by_alias.setdefault(alias, []).append(entry)- records_by_alias.setdefault(alias, []).append(d)- decisions.append(entry)- for alias, entries in entries_by_alias.items():- await annotate_response_evidence_async(- {"decisions": entries},- alias,- records_by_alias[alias],- repo_root=contexts_by_alias[alias].path,+ selected = merge_ranked((rows for _, rows in answered), key=lambda t: (t[0], t[1], t[2]))+ if not selected:+ return fed.annotate(+ {+ "mode": "search",+ "query": query,+ "workspace": True,+ "decisions": [],+ **redirect_for(query),+ "_meta": _build_meta(),+ })++ paths = {ctx.alias: ctx.path for ctx, _ in answered}+ collector = OmissionCollector("get_why", repo_root=paths[selected[0][1]])+ decisions = [entry for *_, entry in selected]result = {"mode": "search","query": query,@@ -86,6 +68,7 @@ async def _why_workspace_search(query: str) -> dict:"decisions": decisions,"_meta": _build_meta(),}+ fed.annotate(result, decisions)cap_collection(result,"decisions",@@ -98,23 +81,32 @@ async def _why_workspace_search(query: str) -> dict:return result-async def _score_workspace(- query: str,-) -> list[tuple[tuple[float, float, int], str, Any, str, Any, list[str]]]:- """Every store's relevant records, collapsed per store, with their sort keys."""- contexts = await _resolve_all_contexts()- scored: list[tuple[tuple[float, float, int], str, Any, str, Any, list[str]]] = []- for ctx in contexts:- async with get_session(ctx.session_factory) as session:- repository = await _get_repo(session)- records = await _decision_corpus(session, repository.id, _get_exclude_spec(ctx.path))+async def _score_repo(+ ctx: Any, query: str+) -> list[tuple[tuple[float, float, int], str, str, dict[str, Any]]]:+ """One store's relevant records, collapsed, as ``(key, alias, id, entry)`` best first."""+ async with get_session(ctx.session_factory) as session:+ repository = await _get_repo(session)+ records = await _decision_corpus(session, repository.id, _get_exclude_spec(ctx.path))ranked = _score_keyword_matches(records, query, set())# Collapsed per store: ``_evidence_key`` carries no repo, so stores# sharing a commit would fold into one across the merge.key_by_id = {d.id: key for key, d in ranked}- for d, folded in _collapse_restatements([d for _, d in ranked]):- scored.append((key_by_id[d.id], ctx.alias, ctx, d.id, d, folded))- return scored+ collapsed = sorted(+ _collapse_restatements([d for _, d in ranked]),+ key=lambda pair: (key_by_id[pair[0].id], pair[0].id),+ )+ kept = [d for d, _ in collapsed]+ await _attach_decision_evidence(session, kept)+ entries = [_workspace_entry(ctx.alias, d, folded) for d, folded in collapsed]+ if entries:+ await annotate_response_evidence_async(+ {"decisions": entries}, ctx.alias, kept, repo_root=ctx.path+ )+ return [+ (key_by_id[d.id], ctx.alias, d.id, entry)+ for (d, _), entry in zip(collapsed, entries, strict=True)+ ]def _workspace_entry(alias: str, d: Any, folded: list[str]) -> dict[str, Any]:diff --git a/tests/unit/server/mcp/test_federation.py b/tests/unit/server/mcp/test_federation.pynew file mode 100644index 000000000..b42da07dd--- /dev/null+++ b/tests/unit/server/mcp/test_federation.py@@ -0,0 +1,303 @@+"""The workspace fan-out behind every ``repo="all"`` tool."""++from __future__ import annotations++import asyncio+import subprocess+from pathlib import Path+from types import SimpleNamespace++import pytest+from sqlalchemy import update++from repowise.core.persistence.models import Repository+from repowise.server.mcp_server import _federation+from repowise.server.mcp_server._federation import (+ Federation,+ fanout_concurrency,+ fanout_timeout_s,+ merge_findings,+ merge_ranked,+ sum_fields,+)+from tests.unit.server.test_mcp_workspace import workspace_mcp # noqa: F401+++class _Registry:+ """Aliases to bare contexts; ``get`` raises for aliases listed in *broken*."""++ def __init__(self, aliases: list[str], broken: tuple[str, ...] = ()):+ self._aliases = aliases+ self._broken = broken++ def get_all_aliases(self) -> list[str]:+ return list(self._aliases)++ async def get(self, alias: str):+ if alias in self._broken:+ raise OSError(f"cannot open {alias}")+ # No session_factory: the freshness probe fails quietly, as designed.+ return SimpleNamespace(alias=alias, path=Path("."))+++def registry(monkeypatch):+ def install(aliases: list[str], broken: tuple[str, ...] = ()) -> _Registry:+ reg = _Registry(aliases, broken)+ monkeypatch.setattr(_federation._state, "_registry", reg)+ return reg++ return install+++# ---------------------------------------------------------------------------+# Fan-out+# ---------------------------------------------------------------------------+++async def test_concurrency_bound_is_respected_and_order_kept(registry):+ registry([f"r{i}" for i in range(6)])+ in_flight = 0+ peak = 0+ full = asyncio.Event()++ async def work(ctx):+ nonlocal in_flight, peak+ in_flight += 1+ peak = max(peak, in_flight)+ if in_flight == 2:+ full.set()+ await full.wait()+ in_flight -= 1+ return ctx.alias.upper()++ answered = await Federation(concurrency=2).run(work)++ assert peak == 2+ assert [value for _, value in answered] == [f"R{i}" for i in range(6)]+++async def test_timeout_names_the_slow_repo_and_keeps_the_rest(registry):+ registry(["fast", "slow", "also_fast"])++ async def work(ctx):+ if ctx.alias == "slow":+ await asyncio.Event().wait()+ return ctx.alias++ fed = Federation(timeout_s=0.05)+ answered = await fed.run(work)+ response = fed.annotate({"results": []})++ assert [value for _, value in answered] == ["fast", "also_fast"]+ assert response["repos_failed"] == [{"repo": "slow", "reason": "timed out after 0.05s"}]+++async def test_exception_in_one_repo_is_isolated_and_skipped_later(registry):+ registry(["a", "b", "c"], broken=("c",))+ calls: list[str] = []++ async def work(ctx):+ calls.append(ctx.alias)+ if ctx.alias == "b":+ raise RuntimeError("index corrupt")+ return ctx.alias++ fed = Federation()+ first = await fed.run(work)+ second = await fed.run(work)+ response = fed.annotate({})++ assert [v for _, v in first] == ["a"]+ assert [v for _, v in second] == ["a"]+ # b failed in the first stage, so the second never asks it again.+ assert calls == ["a", "b", "a"]+ assert response["repos_failed"] == [+ {"repo": "b", "reason": "RuntimeError: index corrupt"},+ {"repo": "c", "reason": "OSError: cannot open c"},+ ]+++def test_multi_follows_the_configured_repos_not_the_answers(registry):+ registry(["only"])+ assert not Federation().multi+ registry(["a", "b"], broken=("b",))+ assert Federation().multi+++async def test_happy_path_adds_nothing(registry):+ registry(["a", "b"])++ async def work(ctx):+ return [{"repo": ctx.alias}]++ fed = Federation()+ rows = [row for _, part in await fed.run(work) for row in part]+ response = fed.annotate({"results": rows}, rows)++ assert response == {"results": [{"repo": "a"}, {"repo": "b"}]}+++def test_config_from_env_with_defaults_and_cap(monkeypatch):+ monkeypatch.setattr(_federation._state, "_registry", None)+ monkeypatch.delenv("REPOWISE_WORKSPACE_CONCURRENCY", raising=False)+ monkeypatch.delenv("REPOWISE_WORKSPACE_REPO_TIMEOUT_S", raising=False)+ assert fanout_concurrency() == 4+ assert fanout_timeout_s() == 60.0++ monkeypatch.setenv("REPOWISE_WORKSPACE_CONCURRENCY", "16")+ monkeypatch.setenv("REPOWISE_WORKSPACE_REPO_TIMEOUT_S", "nope")+ assert fanout_concurrency() == 16+ assert fanout_timeout_s() == 60.0+ # Never more in flight than the registry keeps open.+ monkeypatch.setattr(_federation._state, "_registry", SimpleNamespace(MAX_LOADED=5))+ assert fanout_concurrency() == 5+++# ---------------------------------------------------------------------------+# Merge rules+# ---------------------------------------------------------------------------+++def test_merge_ranked_ties_fall_back_to_workspace_then_repo_order():+ a = [{"id": "a1", "s": 0.9}, {"id": "a2", "s": 0.5}, {"id": "a3", "s": 0.1}]+ b = [{"id": "b1", "s": 0.9}, {"id": "b2", "s": 0.5}]+ key = lambda row: -row["s"] # noqa: E731++ merged = merge_ranked([a, b], key)+ assert [r["id"] for r in merged] == ["a1", "b1", "a2", "b2", "a3"]+ assert merge_ranked([a, b], key) == merged+ capped = merge_ranked([a, b], key, per_repo_cap=1, limit=3)+ assert [r["id"] for r in capped] == ["a1", "b1"]+++def test_merge_findings_tags_rows_in_workspace_order():+ merged = merge_findings([("a", [{"id": 1}]), ("b", [{"id": 2}, {"id": 3}])])+ assert merged == [{"id": 1, "repo": "a"}, {"id": 2, "repo": "b"}, {"id": 3, "repo": "b"}]+++def test_sum_fields_totals_the_rows_given():+ rows = [{"files": 2, "symbols": 5}, {"files": 3, "symbols": None}]+ assert sum_fields(rows, ("files", "symbols")) == {"files": 5, "symbols": 5}+++# ---------------------------------------------------------------------------+# The four repo="all" tools+# ---------------------------------------------------------------------------++_ALL_CALLS = {+ "search_codebase": {"query": "overview"},+ "get_dead_code": {},+ "get_why": {"query": "REST"},+ "get_overview": {},+}++[email protected]("tool_name", sorted(_ALL_CALLS))+async def test_each_tool_fans_out_through_the_helper(workspace_mcp, monkeypatch, tool_name): # noqa: F811+ import repowise.server.mcp_server as mcp_server++ seen: list[str] = []+ real_run = Federation.run++ async def spy(self, fn):+ answered = await real_run(self, fn)+ seen.extend(ctx.alias for ctx, _ in answered)+ return answered++ monkeypatch.setattr(Federation, "run", spy)+ result = await getattr(mcp_server, tool_name)(repo="all", **_ALL_CALLS[tool_name])++ assert {"backend", "frontend"} <= set(seen)+ # A healthy workspace keeps the shape it always had.+ assert "repos_failed" not in result+ assert "repos_stale" not in result++[email protected]("tool_name", sorted(_ALL_CALLS))+async def test_one_broken_repo_leaves_a_partial_answer(workspace_mcp, monkeypatch, tool_name): # noqa: F811+ import repowise.server.mcp_server as mcp_server++ real_get = workspace_mcp.get++ async def get(alias):+ if alias == "frontend":+ raise OSError("database is locked")+ return await real_get(alias)++ monkeypatch.setattr(workspace_mcp, "get", get)+ result = await getattr(mcp_server, tool_name)(repo="all", **_ALL_CALLS[tool_name])++ assert result["repos_failed"] == [{"repo": "frontend", "reason": "OSError: database is locked"}]+ assert "error" not in result+++async def test_partial_answers_keep_the_healthy_repos_rows(workspace_mcp, monkeypatch): # noqa: F811+ from repowise.server.mcp_server import get_dead_code, get_overview, search_codebase++ real_get = workspace_mcp.get++ async def get(alias):+ if alias == "frontend":+ raise OSError("database is locked")+ return await real_get(alias)++ monkeypatch.setattr(workspace_mcp, "get", get)++ overview = await get_overview(repo="all")+ assert [r["alias"] for r in overview["repos"]] == ["backend"]+ dead = await get_dead_code(repo="all")+ assert dead["summary"]["total_findings"] == 1+ symbols = await search_codebase("backend_probe", repo="all", mode="symbol")+ assert [r["repo"] for r in symbols["results"]] == ["backend"]+++async def test_happy_path_shapes_unchanged(workspace_mcp): # noqa: F811+ from repowise.server.mcp_server import get_dead_code, get_overview, get_why++ overview = await get_overview(repo="all")+ assert set(overview) == {+ "workspace", "workspace_root", "total_repos", "total_files", "total_symbols",+ "repos", "hint", "tool_surface", "_meta",+ }+ assert overview["total_repos"] == 2+ assert all("stale" not in r for r in overview["repos"])++ dead = await get_dead_code(repo="all")+ assert set(dead) == {"workspace", "summary", "tiers", "impact", "_meta"}+ rows = [f for t in dead["tiers"].values() for f in t["findings"]]+ assert {f["repo"] for f in rows} == {"backend", "frontend"}+ assert all("stale" not in f for f in rows)++ why = await get_why(query="REST", repo="all")+ assert {"mode", "query", "workspace", "decisions", "_meta"} <= set(why)+ assert [d["repo"] for d in why["decisions"]] == ["backend"]+++async def test_stale_repo_is_named_and_its_rows_marked(workspace_mcp): # noqa: F811+ from repowise.server.mcp_server import get_dead_code++ backend = await workspace_mcp.get("backend")+ root = backend.path++ def git(*args: str) -> str:+ done = subprocess.run(["git", *args], cwd=root, check=True, capture_output=True, text=True)+ return done.stdout.strip()++ indexed = git("rev-parse", "HEAD")+ async with backend.session_factory() as session:+ await session.execute(+ update(Repository).where(Repository.id == "repo-backend").values(head_commit=indexed)+ )+ await session.commit()+ (root / "src/probe.py").write_text("def backend_probe():\n return 2\n", encoding="utf-8")+ git("commit", "-qam", "move past the index")++ result = await get_dead_code(repo="all")++ [stale] = result["repos_stale"]+ assert stale["repo"] == "backend"+ assert stale["indexed_commit"] == indexed[:12]+ assert stale["live_head"] == git("rev-parse", "HEAD")[:12]+ rows = [f for t in result["tiers"].values() for f in t["findings"]]+ assert {f["repo"]: f.get("stale", False) for f in rows} == {"backend": True, "frontend": False}diff --git a/tests/unit/server/mcp/test_search.py b/tests/unit/server/mcp/test_search.pyindex f07d6f374..1e64364ef 100644--- a/tests/unit/server/mcp/test_search.py+++ b/tests/unit/server/mcp/test_search.py@@ -1879,16 +1879,10 @@ class TestPathlessPagesInCodeLocationModes:assert f"{file_page['page_type']}:{file_page['path']}" == "file_page:pkg/cmd/release/list.go"@pytest.mark.asyncio- async def test_federated_rows_carry_path(self, setup_mcp, monkeypatch):- from repowise.server.mcp_server import search_codebase, tool_search+ async def test_federated_rows_carry_path(self, setup_mcp):+ from repowise.server.mcp_server import search_codebaseawait self._seed()- ctx = await tool_search._resolve_repo_context(None)-- async def one_context():- return [ctx]-- monkeypatch.setattr(tool_search, "_resolve_all_contexts", one_context)res = await search_codebase("listing releases in order", mode="concept", repo="all")by_type = {r["page_type"]: r for r in res["results"]}assert by_type["file_page"]["path"] == "pkg/cmd/release/list.go"