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.

refactor(workspace): serve workspace reads from importable functions (#2530)

Raghav Chamadiyae2dcc4e2c44c
diff --git a/packages/api-client/src/types/workspace.ts b/packages/api-client/src/types/workspace.ts
index 746c511f4..65da44a5b 100644
--- a/packages/api-client/src/types/workspace.ts
+++ b/packages/api-client/src/types/workspace.ts
@@ -118,8 +118,9 @@ export interface WorkspaceContractLinkEntry {
provider_symbol_id: string | null;
consumer_symbol_id: string | null;
/**
- * The consumer's own contract id when it reached the provider under another
- * name (a queue bound to the exchange `contract_id` names); null otherwise.
+ * The consumer's own contract id when it is not spelled like `contract_id`,
+ * which names the provider's (a queue bound to that exchange, or a path
+ * matched across case, a wildcard method or a mount prefix); null otherwise.
*/
consumer_contract_id?: string | null;
}
diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.py
index a9aafd38e..1e20c9c71 100644
--- a/packages/core/src/repowise/core/workspace/contracts.py
+++ b/packages/core/src/repowise/core/workspace/contracts.py
@@ -171,9 +171,10 @@ class ContractLink:
#: a display label. None when the contract never bound to one.
provider_symbol_id: str | None = None
consumer_symbol_id: str | None = None
- #: The consumer's own contract id, when it reached the provider under
- #: another name (a queue bound to the exchange ``contract_id`` names).
- #: None when both ends share ``contract_id``, which is every other link.
+ #: The consumer's own contract id when it is not spelled like the
+ #: provider's ``contract_id``: a queue bound to the exchange that id names,
+ #: or a path matched across case, a wildcard method or a mount prefix.
+ #: None when both ends share ``contract_id``.
consumer_contract_id: str | None = None
def to_dict(self) -> dict[str, Any]:
diff --git a/packages/core/src/repowise/core/workspace/matching/common.py b/packages/core/src/repowise/core/workspace/matching/common.py
index 258f8863b..7fbe0d5a0 100644
--- a/packages/core/src/repowise/core/workspace/matching/common.py
+++ b/packages/core/src/repowise/core/workspace/matching/common.py
@@ -63,11 +63,13 @@ class MatchState:
) -> bool:
"""Record one link unless an identical one exists; True when it was added.
- A link's ``contract_id`` is the id both ends share. *via_alias* marks a
- consumer that reached the provider under another name (a queue bound to
- an exchange): the link then carries the provider's id, and the
- consumer's own id as ``consumer_contract_id``. One queue bound to two
- exchanges is two links, so an aliased key names the provider's id too.
+ A link's ``contract_id`` is the provider's id, and ``consumer_contract_id``
+ the consumer's whenever it is spelled differently (another case, a
+ wildcard method, a prefix the candidate pass collapsed), so each side
+ finds its links under its own id. *via_alias* marks a consumer that
+ reached the provider under another name (a queue bound to an exchange).
+ One queue bound to two exchanges is two links, so an aliased key names
+ the provider's id too.
"""
dedup_key = (
normalize_contract_id(consumer.contract_id),
@@ -82,7 +84,7 @@ class MatchState:
self.seen.add(dedup_key)
self.links.append(
ContractLink(
- contract_id=provider.contract_id if via_alias else consumer.contract_id,
+ contract_id=provider.contract_id,
contract_type=consumer.contract_type,
match_type=match_type,
confidence=confidence,
@@ -96,7 +98,9 @@ class MatchState:
provider_symbol_id=provider.symbol_id,
consumer_symbol_id=consumer.symbol_id,
consumer_service=consumer.service,
- consumer_contract_id=consumer.contract_id if via_alias else None,
+ consumer_contract_id=(
+ consumer.contract_id if consumer.contract_id != provider.contract_id else None
+ ),
)
)
self.matched.add(id(consumer))
diff --git a/packages/core/src/repowise/core/workspace/reads.py b/packages/core/src/repowise/core/workspace/reads.py
new file mode 100644
index 000000000..d7bea2ecb
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/reads.py
@@ -0,0 +1,445 @@
+"""Workspace read views over the stored cross-repo artifacts.
+
+Pure functions over the parsed ``contracts.json``, ``cross_repo_edges.json``,
+``system_graph.json``, ``breaking_changes.json`` and ``conformance.json``
+payloads. They hold every filter, rollup and projection the workspace API
+serves, so any server answering those routes calls these rather than keeping
+its own copy. Each returns the wire shape as plain dicts.
+
+A link's ``contract_id`` names its provider's contract and
+``consumer_contract_id`` its consumer's when that differs, so the consumer side
+of a link is always read as ``consumer_contract_id or contract_id``.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from repowise.core.workspace.cross_repo import MAX_EDGES, MAX_EDGES_PER_REPO_PAIR
+
+if TYPE_CHECKING:
+ from collections.abc import Iterable, Sequence
+
+__all__ = [
+ "breaking_changes_view",
+ "co_change_structure",
+ "conformance_for_repo",
+ "conformance_view",
+ "contract_detail",
+ "contract_row",
+ "link_row",
+ "list_co_changes",
+ "list_contracts",
+ "unmatched_reason",
+]
+
+
+def contract_row(c: dict) -> dict[str, Any]:
+ """One raw ``contracts.json`` row in its wire shape.
+
+ ``schema`` is dropped on purpose: it is the one field a list cannot afford,
+ and :func:`contract_detail` carries it separately.
+ """
+ return {
+ "contract_id": c.get("contract_id", ""),
+ "contract_type": c.get("contract_type", ""),
+ "role": c.get("role", ""),
+ "repo": c.get("repo", ""),
+ "file_path": c.get("file_path", ""),
+ "symbol_name": c.get("symbol_name", ""),
+ "confidence": c.get("confidence", 0.0),
+ "service": c.get("service"),
+ "line": c.get("line"),
+ "symbol_id": c.get("symbol_id"),
+ "meta": c.get("meta") or {},
+ }
+
+
+def link_row(lk: dict) -> dict[str, Any]:
+ """One raw ``contract_links`` row in its wire shape."""
+ return {
+ "contract_id": lk.get("contract_id", ""),
+ "contract_type": lk.get("contract_type", ""),
+ "match_type": lk.get("match_type", "exact"),
+ "confidence": lk.get("confidence", 0.0),
+ "provider_repo": lk.get("provider_repo", ""),
+ "provider_file": lk.get("provider_file", ""),
+ "provider_symbol": lk.get("provider_symbol", ""),
+ "consumer_repo": lk.get("consumer_repo", ""),
+ "consumer_file": lk.get("consumer_file", ""),
+ "consumer_symbol": lk.get("consumer_symbol", ""),
+ "provider_service": lk.get("provider_service"),
+ "consumer_service": lk.get("consumer_service"),
+ "provider_symbol_id": lk.get("provider_symbol_id"),
+ "consumer_symbol_id": lk.get("consumer_symbol_id"),
+ "consumer_contract_id": lk.get("consumer_contract_id"),
+ }
+
+
+def _consumer_id(lk: dict) -> Any:
+ return lk.get("consumer_contract_id") or lk.get("contract_id")
+
+
+def _contract_haystack(c: dict) -> str:
+ return " ".join(
+ str(c.get(k) or "") for k in ("contract_id", "file_path", "symbol_name", "repo", "service")
+ ).lower()
+
+
+def _link_haystack(lk: dict) -> str:
+ return " ".join(
+ str(lk.get(k) or "")
+ for k in (
+ "contract_id",
+ "consumer_contract_id",
+ "provider_repo",
+ "provider_file",
+ "provider_symbol",
+ "consumer_repo",
+ "consumer_file",
+ "consumer_symbol",
+ )
+ ).lower()
+
+
+def _matches_terms(haystack: str, terms: list[str]) -> bool:
+ return all(t in haystack for t in terms)
+
+
+def list_contracts(
+ contracts: Sequence[dict],
+ links: Sequence[dict],
+ *,
+ contract_type: str | None = None,
+ repo: str | None = None,
+ role: str | None = None,
+ q: str | None = None,
+ linked: bool | None = None,
+ include_links: bool = True,
+ limit: int = 200,
+ offset: int = 0,
+) -> dict[str, Any]:
+ """The contracts list: filtered, counted by type, one page of contracts.
+
+ ``q`` is case-insensitive and every whitespace-separated term must match.
+ ``linked`` keeps only contracts on a matched link (true) or on none (false).
+ ``include_links=False`` omits the link rows but still counts them. Only
+ contracts are paged; links are typically small enough to send whole.
+ """
+ all_links = links
+ contracts = list(contracts)
+ links = list(links)
+
+ if contract_type:
+ contracts = [c for c in contracts if c.get("contract_type") == contract_type]
+ links = [lk for lk in links if lk.get("contract_type") == contract_type]
+ if repo:
+ contracts = [c for c in contracts if c.get("repo") == repo]
+ links = [
+ lk for lk in links if lk.get("provider_repo") == repo or lk.get("consumer_repo") == repo
+ ]
+ if role:
+ contracts = [c for c in contracts if c.get("role") == role]
+ if linked is not None:
+ # Keyed on the side each contract plays, from the unfiltered links, so a
+ # type or repo filter above cannot turn a linked contract into an unused one.
+ on_link = set()
+ for lk in all_links:
+ on_link.add(
+ ("provider", lk.get("provider_repo"), lk.get("provider_file"), lk.get("contract_id"))
+ )
+ on_link.add(
+ ("consumer", lk.get("consumer_repo"), lk.get("consumer_file"), _consumer_id(lk))
+ )
+ contracts = [
+ c
+ for c in contracts
+ if (
+ (c.get("role"), c.get("repo"), c.get("file_path"), c.get("contract_id"))
+ in on_link
+ )
+ == linked
+ ]
+ terms = (q or "").lower().split()
+ if terms:
+ contracts = [c for c in contracts if _matches_terms(_contract_haystack(c), terms)]
+ links = [lk for lk in links if _matches_terms(_link_haystack(lk), terms)]
+
+ by_type: dict[str, int] = {}
+ for c in contracts:
+ ct = c.get("contract_type", "unknown")
+ by_type[ct] = by_type.get(ct, 0) + 1
+
+ return {
+ "contracts": [contract_row(c) for c in contracts[offset : offset + limit]],
+ "links": [link_row(lk) for lk in links] if include_links else [],
+ "total_contracts": len(contracts),
+ "total_links": len(links),
+ "by_type": by_type,
+ }
+
+
+def unmatched_reason(
+ diagnostics: dict | None, repo: str, file_path: str, contract_id: str
+) -> str | None:
+ """Why one consumer matched nothing, from the system graph's diagnostics.
+
+ The reasons live in ``system_graph.json``, not ``contracts.json``, keyed by
+ the same ``(repo, file_path, contract_id)`` triple. None when no graph is
+ built or the consumer did match.
+ """
+ for u in (diagnostics or {}).get("unmatched_consumers", []):
+ if (
+ u.get("repo") == repo
+ and u.get("file_path") == file_path
+ and u.get("contract_id") == contract_id
+ ):
+ return u.get("reason")
+ return None
+
+
+def contract_detail(
+ contracts: Iterable[dict],
+ links: Iterable[dict],
+ diagnostics: dict | None,
+ *,
+ repo: str,
+ file_path: str,
+ contract_id: str,
+) -> dict[str, Any] | None:
+ """One contract with its schema, its links and its unmatched reason, or None.
+
+ The triple is the shareable identity, not a primary key: one file may call
+ the same endpoint from two lines, and the first row wins. The links are
+ filtered by the same triple, so they are identical whichever row wins.
+ """
+ match = next(
+ (
+ c
+ for c in contracts
+ if c.get("repo") == repo
+ and c.get("file_path") == file_path
+ and c.get("contract_id") == contract_id
+ ),
+ None,
+ )
+ if match is None:
+ return None
+
+ role = match.get("role", "")
+ if role == "consumer":
+ own = [
+ lk
+ for lk in links
+ if _consumer_id(lk) == contract_id
+ and lk.get("consumer_repo") == repo
+ and lk.get("consumer_file") == file_path
+ ]
+ else:
+ own = [
+ lk
+ for lk in links
+ if lk.get("contract_id") == contract_id
+ and lk.get("provider_repo") == repo
+ and lk.get("provider_file") == file_path
+ ]
+
+ reason = None
+ if role == "consumer" and not own:
+ reason = unmatched_reason(diagnostics, repo, file_path, contract_id)
+
+ return {
+ "contract": contract_row(match),
+ "contract_schema": match.get("schema"),
+ "links": [link_row(lk) for lk in own],
+ "unmatched_reason": reason,
+ }
+
+
+def list_co_changes(
+ co_changes: Sequence[dict],
+ total_mined: int | None = None,
+ *,
+ repo: str | None = None,
+ min_strength: float = 0.0,
+ limit: int = 50,
+) -> dict[str, Any]:
+ """Co-changing file pairs, filtered, strongest first, with the miner's caps.
+
+ *total_mined* is how many pairs cleared the miner's thresholds before its
+ caps trimmed the stored list; ``truncated_by`` names the cap that did.
+ """
+ pairs = list(co_changes)
+ if total_mined is None:
+ total_mined = len(pairs)
+ # Judged before any query filter. The miner walks pairs strongest first, so
+ # a full global budget means the workspace-wide cap stopped it (the
+ # per-pair cap may also have applied).
+ if total_mined <= len(pairs):
+ truncated_by = None
+ elif len(pairs) >= MAX_EDGES:
+ truncated_by = "total"
+ else:
+ truncated_by = "per_repo_pair"
+
+ if repo:
+ pairs = [cc for cc in pairs if cc.get("source_repo") == repo or cc.get("target_repo") == repo]
+ if min_strength > 0:
+ pairs = [cc for cc in pairs if cc.get("strength", 0) >= min_strength]
+ pairs.sort(key=lambda cc: -cc.get("strength", 0))
+
+ return {
+ "co_changes": [
+ {
+ "source_repo": cc.get("source_repo", ""),
+ "source_file": cc.get("source_file", ""),
+ "target_repo": cc.get("target_repo", ""),
+ "target_file": cc.get("target_file", ""),
+ "strength": cc.get("strength", 0.0),
+ "frequency": cc.get("frequency", 0),
+ "last_date": cc.get("last_date", ""),
+ }
+ for cc in pairs[:limit]
+ ],
+ "total": len(pairs),
+ "total_mined": total_mined,
+ # The constants name the rules the miner applied; the overlay does not
+ # store them.
+ "per_repo_pair_cap": MAX_EDGES_PER_REPO_PAIR,
+ "total_cap": MAX_EDGES,
+ "truncated_by": truncated_by,
+ }
+
+
+def co_change_structure(
+ links: Sequence[dict],
+ *,
+ source_repo: str,
+ source_file: str,
+ target_repo: str,
+ target_file: str,
+) -> dict[str, Any]:
+ """Declared structure behind one co-changing pair.
+
+ The contract links between the two files, and a count by type of the links
+ between their repositories through any files.
+ """
+
+ def touching(repo: str, path: str) -> list[dict]:
+ # Provider ends first, then consumer ends, each in artifact order.
+ return [
+ *(lk for lk in links if lk.get("provider_repo") == repo and lk.get("provider_file") == path),
+ *(lk for lk in links if lk.get("consumer_repo") == repo and lk.get("consumer_file") == path),
+ ]
+
+ src_links = touching(source_repo, source_file)
+ pair = {(source_repo, source_file), (target_repo, target_file)}
+ pair_links = [
+ lk
+ for lk in src_links
+ if {
+ (lk.get("provider_repo"), lk.get("provider_file")),
+ (lk.get("consumer_repo"), lk.get("consumer_file")),
+ }
+ == pair
+ ]
+
+ repos = {source_repo, target_repo}
+ by_type: dict[str, int] = {}
+ for lk in links:
+ if {lk.get("provider_repo"), lk.get("consumer_repo")} == repos:
+ ct = lk.get("contract_type", "unknown")
+ by_type[ct] = by_type.get(ct, 0) + 1
+
+ return {
+ "pair_links": [link_row(lk) for lk in pair_links],
+ "repo_links_total": sum(by_type.values()),
+ "repo_links_by_type": by_type,
+ "source_file_links": len(src_links),
+ "target_file_links": len(touching(target_repo, target_file)),
+ }
+
+
+def breaking_changes_view(
+ report: dict, *, repo: str | None = None, severity: str | None = None
+) -> dict[str, Any]:
+ """The breaking-change report, narrowed to a provider repo and/or severity.
+
+ Rollups are recomputed when a filter narrowed the set, so the answer stays
+ self-consistent; otherwise the stored report passes through unchanged.
+ """
+ if not (repo or severity):
+ return dict(report)
+
+ changes = list(report.get("changes", []))
+ if repo:
+ changes = [c for c in changes if c.get("provider_repo") == repo]
+ if severity:
+ changes = [c for c in changes if c.get("severity") == severity]
+ consumers = [ic for c in changes for ic in c.get("impacted_consumers", [])]
+ return {
+ "version": report.get("version", 1),
+ "generated_at": report.get("generated_at") or None,
+ "changes": changes,
+ "total": len(changes),
+ "breaking_count": sum(1 for c in changes if c.get("severity") == "breaking"),
+ "warning_count": sum(1 for c in changes if c.get("severity") == "warning"),
+ "impacted_repos": sorted({ic.get("repo", "") for ic in consumers}),
+ "impacted_services": sorted({ic.get("node_id", "") for ic in consumers}),
+ "total_impacted_consumers": len(consumers),
+ }
+
+
+def _node_repo(node_id: str) -> str:
+ """Repo alias for a system-graph node id (``repo`` or ``repo::service``)."""
+ return node_id.split("::", 1)[0]
+
+
+def conformance_for_repo(report: dict | None, repo: str) -> dict[str, list]:
+ """Violations and cycles that involve *repo*.
+
+ A violation involves the repo when either endpoint lives in it; a cycle
+ when any participating service does.
+ """
+ if not report:
+ return {"violations": [], "cycles": []}
+ violations = [
+ v
+ for v in report.get("violations", [])
+ if _node_repo(v.get("source", "")) == repo or _node_repo(v.get("target", "")) == repo
+ ]
+ cycles = [
+ c
+ for c in report.get("cycles", [])
+ if any(_node_repo(n) == repo for n in c.get("nodes", []))
+ ]
+ return {"violations": violations, "cycles": cycles}
+
+
+def conformance_view(report: dict, *, repo: str | None = None) -> dict[str, Any]:
+ """The conformance report, narrowed to findings that involve *repo*."""
+ # A report written before cycle totals were recorded has no total_cycles;
+ # the listed count beats a default of zero beside a non-empty list.
+ total_cycles = report.get("total_cycles", len(report.get("cycles", [])))
+ if not repo:
+ return {**report, "total_cycles": total_cycles}
+
+ scoped = conformance_for_repo(report, repo)
+ violations = scoped["violations"]
+ cycles = scoped["cycles"]
+ return {
+ "version": report.get("version", 1),
+ "generated_at": report.get("generated_at") or None,
+ "rules_evaluated": report.get("rules_evaluated", 0),
+ "violations": violations,
+ "cycles": cycles,
+ "violation_count": len(violations),
+ "cycle_count": len(cycles),
+ # The unscoped total: how many cycles the workspace has does not change
+ # because the view was narrowed.
+ "total_cycles": total_cycles,
+ "violating_repos": sorted(
+ {_node_repo(v.get("source", "")) for v in violations}
+ | {_node_repo(v.get("target", "")) for v in violations}
+ ),
+ }
diff --git a/packages/core/src/repowise/core/workspace/repo_index.py b/packages/core/src/repowise/core/workspace/repo_index.py
index 8ef88d0e2..4ec613ee0 100644
--- a/packages/core/src/repowise/core/workspace/repo_index.py
+++ b/packages/core/src/repowise/core/workspace/repo_index.py
@@ -21,11 +21,11 @@ import json
import logging
import re
from dataclasses import dataclass
+from pathlib import Path
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
- from collections.abc import Collection
- from pathlib import Path
+ from collections.abc import Collection, Iterable, Mapping, Sequence
from sqlalchemy.ext.asyncio import AsyncSession
@@ -79,16 +79,17 @@ _QUALIFIER_RE = re.compile(r"::|\.")
class RepoIndex:
"""Read-only accessor over one repo's ``wiki.db``.
- Built by :func:`open_workspace_index`; the caller owns :meth:`close`. Every
- accessor is a pure in-memory read of what :meth:`_load` fetched, so a
- dialect may call one from the worker thread it runs in.
+ Built by :func:`open_workspace_index`, or by :meth:`from_symbols` from rows
+ the caller already holds; the caller owns :meth:`close`. Every accessor is a
+ pure in-memory read of what was loaded, so a dialect may call one from the
+ worker thread it runs in.
"""
def __init__(
self,
alias: str,
repo_path: Path,
- session: AsyncSession,
+ session: AsyncSession | Any,
engine: Any,
*,
# Required: an empty id makes every repository-scoped query return nothing.
@@ -103,8 +104,41 @@ class RepoIndex:
self._by_name: dict[str, list[IndexedSymbol]] = {}
self._externals: list[ExternalImport] = []
+ @classmethod
+ def from_symbols(
+ cls,
+ alias: str,
+ symbols: Iterable[IndexedSymbol],
+ *,
+ repo_id: str,
+ session: Any = None,
+ names: Mapping[str, Sequence[IndexedSymbol]] | None = None,
+ ) -> RepoIndex:
+ """An index over *symbols* the caller already holds, with no database.
+
+ *session* is whatever the caller's test-impact reads take (see
+ :func:`.test_impact.analyze_workspace_test_impact`); :meth:`close` leaves
+ it alone. *names* replaces the name lookup built from *symbols*, for a
+ caller that loads only some files but resolves names across the repo.
+ """
+ index = cls(alias, Path(), session, None, repo_id=repo_id)
+ index._index(symbols)
+ if names is not None:
+ index._by_name = names # type: ignore[assignment]
+ return index
+
# -- Loading -----------------------------------------------------------
+ def _index(self, symbols: Iterable[IndexedSymbol]) -> None:
+ for sym in symbols:
+ self._by_file.setdefault(sym.file_path, []).append(sym)
+ # Outermost first, so the first span containing a line is the class and
+ # the last is the method.
+ for file_symbols in self._by_file.values():
+ file_symbols.sort(key=lambda s: (s.start_line, -s.end_line))
+ for sym in file_symbols:
+ self._by_name.setdefault(sym.name, []).append(sym)
+
async def _load(self, repo_id: str) -> None:
from sqlalchemy import select
@@ -124,29 +158,23 @@ class RepoIndex:
WikiSymbol.language,
).where(WikiSymbol.repository_id == repo_id)
)
- for row in rows:
- # By keyword: eight of the ten fields are strings, so a reordered
- # or inserted column would swap values positionally without error.
- self._by_file.setdefault(row.file_path, []).append(
- IndexedSymbol(
- symbol_id=row.symbol_id,
- name=row.name,
- qualified_name=row.qualified_name,
- kind=row.kind,
- signature=row.signature,
- file_path=row.file_path,
- start_line=row.start_line,
- end_line=row.end_line,
- visibility=row.visibility,
- language=row.language or "",
- )
+ # By keyword: eight of the ten fields are strings, so a reordered or
+ # inserted column would swap values positionally without error.
+ self._index(
+ IndexedSymbol(
+ symbol_id=row.symbol_id,
+ name=row.name,
+ qualified_name=row.qualified_name,
+ kind=row.kind,
+ signature=row.signature,
+ file_path=row.file_path,
+ start_line=row.start_line,
+ end_line=row.end_line,
+ visibility=row.visibility,
+ language=row.language or "",
)
- # Outermost first, so the first span containing a line is the class and
- # the last is the method.
- for symbols in self._by_file.values():
- symbols.sort(key=lambda s: (s.start_line, -s.end_line))
- for sym in symbols:
- self._by_name.setdefault(sym.name, []).append(sym)
+ for row in rows
+ )
edges = await self._session.execute(
select(
@@ -177,7 +205,7 @@ class RepoIndex:
# -- Public API --------------------------------------------------------
@property
- def session(self) -> AsyncSession:
+ def session(self) -> AsyncSession | Any:
"""The connection the index holds; reachability queries run on it too."""
return self._session
@@ -257,6 +285,9 @@ class RepoIndex:
return [s for syms in self._by_file.values() for s in syms if s.visibility == "public"]
async def close(self) -> None:
+ # No engine means the caller built this over its own handle and owns it.
+ if self._engine is None:
+ return
await self._session.close()
await self._engine.dispose()
diff --git a/packages/core/src/repowise/core/workspace/test_impact.py b/packages/core/src/repowise/core/workspace/test_impact.py
index eff5f9963..94ca52806 100644
--- a/packages/core/src/repowise/core/workspace/test_impact.py
+++ b/packages/core/src/repowise/core/workspace/test_impact.py
@@ -31,10 +31,18 @@ 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 collections.abc import Awaitable, Callable, Collection, Mapping, Sequence
from repowise.core.workspace.repo_index import RepoIndex
+ #: The measured read: ``(session, repo_id, files) -> {file: [coverage rows]}``,
+ #: the shape of :func:`tests_covering_files`.
+ CoveringReads = Callable[
+ [Any, str, set[str]], Awaitable[Mapping[str, Sequence[Mapping[str, Any]]]]
+ ]
+ #: The inferred read, the signature of :func:`tests_reaching_by_tier`.
+ ReachingReads = Callable[..., Awaitable[Mapping[str, Any]]]
+
_BASIS_ORDER = {"measured": 0, "inferred": 1}
_TIER_PRIORITY = {"call-graph": 0, "import-graph": 1}
@@ -219,6 +227,8 @@ async def _analyze_consumer(
import_depth: int,
include_measured: bool,
include_inferred: bool,
+ covering: CoveringReads,
+ reaching: ReachingReads,
) -> _ConsumerOutcome:
"""Resolve one consumer repo, sequentially on the one session it holds."""
out = _ConsumerOutcome()
@@ -257,7 +267,7 @@ async def _analyze_consumer(
session = repo_index.session
if include_measured:
try:
- rows = await tests_covering_files(session, repo_index.repo_id, set(files))
+ rows = await covering(session, repo_index.repo_id, set(files))
for path, covering in rows.items():
measured[path] = [
{
@@ -277,7 +287,7 @@ async def _analyze_consumer(
# 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(
+ by_symbol = await reaching(
session,
repo_index.repo_id,
symbol_ids,
@@ -288,7 +298,7 @@ async def _analyze_consumer(
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(
+ by_file_reached = await reaching(
session,
repo_index.repo_id,
unanswered,
@@ -412,12 +422,19 @@ async def analyze_workspace_test_impact(
min_confidence: float = 0.0,
target_repos: Collection[str] | None = None,
max_tests_per_pair: int | None = MAX_TESTS_PER_TARGET,
+ covering: CoveringReads | None = None,
+ reaching: ReachingReads | 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. ``max_tests_per_pair=None`` turns
the per-pair cap off, for a caller that caps and banks the tail itself.
+
+ *covering* and *reaching* are the two consumer reads, defaulting to
+ :func:`tests_covering_files` and :func:`tests_reaching_by_tier`. Each is
+ handed the consumer's :attr:`RepoIndex.session`, so a caller whose indexes
+ hold something other than a database session passes reads that take it.
"""
changed_by_provider: dict[str, set[str]] = defaultdict(set)
for entry in changed_files:
@@ -483,6 +500,9 @@ async def analyze_workspace_test_impact(
import_depth=import_depth,
include_measured=include_measured,
include_inferred=include_inferred,
+ # Resolved per call, so a default is always the module's current one.
+ covering=covering or tests_covering_files,
+ reaching=reaching or tests_reaching_by_tier,
)
for alias in aliases
)
diff --git a/packages/server/src/repowise/server/mcp_server/_enrichment.py b/packages/server/src/repowise/server/mcp_server/_enrichment.py
index c33b49feb..ec39138ae 100644
--- a/packages/server/src/repowise/server/mcp_server/_enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/_enrichment.py
@@ -1,6 +1,7 @@
"""Cross-repo enrichment for MCP tool responses.
-Loaded once at MCP lifespan start from ``.repowise-workspace/cross_repo_edges.json``.
+Loaded once at MCP lifespan start from ``.repowise-workspace/cross_repo_edges.json``,
+or built with :meth:`CrossRepoEnricher.from_data` from payloads already parsed.
Provides O(1) in-memory lookups — never blocks or slows MCP queries.
"""
@@ -20,7 +21,7 @@ class CrossRepoEnricher:
def __init__(
self,
- data_path: Path,
+ data_path: Path | None,
contracts_path: Path | None = None,
system_graph_path: Path | None = None,
breaking_changes_path: Path | None = None,
@@ -77,15 +78,49 @@ class CrossRepoEnricher:
self._breaking_changes_path = breaking_changes_path
self._conformance_path = conformance_path
- self._load(data_path)
- if contracts_path is not None:
- self._load_contracts(contracts_path)
- if system_graph_path is not None:
- self._load_system_graph(system_graph_path)
- if breaking_changes_path is not None:
- self._load_breaking_changes(breaking_changes_path)
- if conformance_path is not None:
- self._load_conformance(conformance_path)
+ self._load_all()
+
+ @classmethod
+ def from_data(
+ cls,
+ *,
+ overlay: dict | None = None,
+ contracts: dict | None = None,
+ system_graph: dict | None = None,
+ breaking_changes: dict | None = None,
+ conformance: dict | None = None,
+ ) -> CrossRepoEnricher:
+ """An enricher over artifact payloads the caller has already parsed.
+
+ Each argument is the parsed JSON of the file of the same name
+ (``cross_repo_edges.json`` for *overlay*), and gets the same validation
+ and indexes a file load does. A None payload is an absent artifact.
+ There are no files, so :meth:`reload` leaves this enricher empty.
+ """
+ enricher = cls(None)
+ if overlay is not None:
+ enricher._ingest_overlay(overlay, "<data>")
+ if contracts is not None:
+ enricher._ingest_contracts(contracts)
+ if system_graph is not None:
+ enricher._ingest_system_graph(system_graph)
+ if breaking_changes is not None:
+ enricher._ingest_breaking_changes(breaking_changes)
+ if conformance is not None:
+ enricher._ingest_conformance(conformance)
+ return enricher
+
+ def _load_all(self) -> None:
+ if self._data_path is not None:
+ self._load(self._data_path)
+ if self._contracts_path is not None:
+ self._load_contracts(self._contracts_path)
+ if self._system_graph_path is not None:
+ self._load_system_graph(self._system_graph_path)
+ if self._breaking_changes_path is not None:
+ self._load_breaking_changes(self._breaking_changes_path)
+ if self._conformance_path is not None:
+ self._load_conformance(self._conformance_path)
def _load(self, data_path: Path) -> None:
"""Parse JSON and build indexes."""
@@ -102,14 +137,16 @@ class CrossRepoEnricher:
}
_log.warning("Failed to parse cross-repo data at %s", data_path, exc_info=True)
return
+ self._ingest_overlay(data, data_path)
+ def _ingest_overlay(self, data: dict, source: object) -> None:
if data.get("version", 1) < 2:
# v1 overlays carry unbounded strength values; everything
# downstream now assumes the bounded [0, 1) session share, so
# skip stale files until a workspace update regenerates them.
_log.info(
"Ignoring cross-repo data at %s (version %s < 2)",
- data_path,
+ source,
data.get("version", 1),
)
self._cross_repo_analysis = {
@@ -261,7 +298,9 @@ class CrossRepoEnricher:
}
_log.warning("Failed to parse contract data at %s", contracts_path, exc_info=True)
return
+ self._ingest_contracts(data)
+ def _ingest_contracts(self, data: dict) -> None:
self._contracts = data.get("contracts", [])
self._contract_links = data.get("contract_links", [])
self._contract_analysis = {
@@ -316,10 +355,13 @@ class CrossRepoEnricher:
return
try:
graph = json.loads(system_graph_path.read_text(encoding="utf-8"))
- self._system_graph = graph
except Exception:
_log.warning("Failed to parse system graph at %s", system_graph_path, exc_info=True)
return
+ self._ingest_system_graph(graph)
+
+ def _ingest_system_graph(self, graph: dict) -> None:
+ self._system_graph = graph
_log.debug(
"System graph loaded: %d nodes, %d edges",
len(graph.get("nodes", [])),
@@ -333,12 +375,15 @@ class CrossRepoEnricher:
return
try:
report = json.loads(breaking_changes_path.read_text(encoding="utf-8"))
- self._breaking_changes = report
except Exception:
_log.warning(
"Failed to parse breaking changes at %s", breaking_changes_path, exc_info=True
)
return
+ self._ingest_breaking_changes(report)
+
+ def _ingest_breaking_changes(self, report: dict) -> None:
+ self._breaking_changes = report
for change in report.get("changes", []):
repo = change.get("provider_repo")
if repo:
@@ -355,10 +400,13 @@ class CrossRepoEnricher:
return
try:
report = json.loads(conformance_path.read_text(encoding="utf-8"))
- self._conformance = report
except Exception:
_log.warning("Failed to parse conformance at %s", conformance_path, exc_info=True)
return
+ self._ingest_conformance(report)
+
+ def _ingest_conformance(self, report: dict) -> None:
+ self._conformance = report
_log.debug(
"Conformance report loaded: %d violation(s), %d cycle(s)",
len(report.get("violations", [])),
@@ -402,15 +450,7 @@ class CrossRepoEnricher:
self._breaking_changes_by_repo = defaultdict(list)
self._conformance = None
- self._load(self._data_path)
- if self._contracts_path is not None:
- self._load_contracts(self._contracts_path)
- if self._system_graph_path is not None:
- self._load_system_graph(self._system_graph_path)
- if self._breaking_changes_path is not None:
- self._load_breaking_changes(self._breaking_changes_path)
- if self._conformance_path is not None:
- self._load_conformance(self._conformance_path)
+ self._load_all()
_log.info(
"Cross-repo enricher reloaded: %d co-change edges, %d package deps, %d contract links",
@@ -429,6 +469,26 @@ class CrossRepoEnricher:
or self._contract_links
)
+ @property
+ def contracts(self) -> list[dict]:
+ """Every contract row, as stored."""
+ return self._contracts
+
+ @property
+ def contract_links(self) -> list[dict]:
+ """Every matched link row, as stored."""
+ return self._contract_links
+
+ @property
+ def co_changes(self) -> list[dict]:
+ """The stored co-change pairs, already capped by the miner."""
+ return self._co_changes
+
+ @property
+ def total_co_changes(self) -> int:
+ """How many pairs cleared the miner's thresholds before its caps."""
+ return self._total_co_changes
+
@property
def has_contract_data(self) -> bool:
"""True if contracts or contract links are available."""
@@ -484,33 +544,15 @@ class CrossRepoEnricher:
"""Return the raw conformance report (violations + cycles + rollups)."""
return self._conformance
- @staticmethod
- def _node_repo(node_id: str) -> str:
- """Repo alias for a system-graph node id (``repo`` or ``repo::service``)."""
- return node_id.split("::", 1)[0]
-
def get_conformance_for_repo(self, repo_alias: str) -> dict:
"""Violations + cycles that involve *repo_alias*.
- A violation involves the repo when either endpoint lives in it; a cycle
- when any participating service does. Used by the ``get_risk`` PR-mode
- directive to surface architecture findings a diff's repo participates in.
+ Used by the ``get_risk`` PR-mode directive to surface architecture
+ findings a diff's repo participates in.
"""
- report = self._conformance
- if not report:
- return {"violations": [], "cycles": []}
- violations = [
- v
- for v in report.get("violations", [])
- if self._node_repo(v.get("source", "")) == repo_alias
- or self._node_repo(v.get("target", "")) == repo_alias
- ]
- cycles = [
- c
- for c in report.get("cycles", [])
- if any(self._node_repo(n) == repo_alias for n in c.get("nodes", []))
- ]
- return {"violations": violations, "cycles": cycles}
+ from repowise.core.workspace.reads import conformance_for_repo
+
+ return conformance_for_repo(self._conformance, repo_alias)
def get_architecture_metrics(self) -> dict | None:
"""Compute the architecture-complexity metrics from the system graph.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_architecture.py b/packages/server/src/repowise/server/mcp_server/tool_architecture.py
index 5f149f4d3..41b191fdf 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_architecture.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_architecture.py
@@ -56,6 +56,22 @@ async def get_architecture() -> dict[str, Any]:
"_meta": _build_meta(),
}
+ payload = architecture_payload(metrics)
+ payload["_meta"] = _build_meta(
+ extra=_analysis_meta(
+ metrics.get("generated_at"),
+ {
+ alias: provenance.get("head")
+ for alias, provenance in metrics.get("repo_provenance", {}).items()
+ if provenance.get("head")
+ },
+ )
+ )
+ return payload
+
+
+def architecture_payload(metrics: dict[str, Any]) -> dict[str, Any]:
+ """The ``get_architecture`` answer over computed *metrics*, without ``_meta``."""
core_members = metrics.get("core_members", [])
shown_core = core_members[:_MCP_CORE_MEMBER_LIMIT]
breakdown = metrics.get("role_breakdown", {})
@@ -87,14 +103,4 @@ async def get_architecture() -> dict[str, Any]:
"conformance_violations": metrics.get("conformance_violations", 0),
"role_breakdown": breakdown,
"summary": summary,
- "_meta": _build_meta(
- extra=_analysis_meta(
- metrics.get("generated_at"),
- {
- alias: provenance.get("head")
- for alias, provenance in metrics.get("repo_provenance", {}).items()
- if provenance.get("head")
- },
- )
- ),
}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py
index e2211b5d3..850e06024 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py
@@ -10,7 +10,7 @@ services carry an impact ``score`` and a ``distance``.
from __future__ import annotations
from collections import defaultdict
-from typing import Any
+from typing import TYPE_CHECKING, Any
from repowise.core.registry import mcp_tool_registry as mcp
from repowise.server.mcp_server import _state
@@ -20,6 +20,16 @@ from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server._meta import persisted_analysis_meta as _analysis_meta
from repowise.server.mcp_server._test_impact import cross_repo_tests_for, tests_block_for
+if TYPE_CHECKING:
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
+
+ from repowise.core.workspace.test_impact import WorkspaceTestImpactResult
+
+ #: The cross-repo test join, the signature of :func:`cross_repo_tests_for`.
+ TestsFor = Callable[
+ [Mapping[str, Sequence[str]]], Awaitable[WorkspaceTestImpactResult | None]
+ ]
+
#: How many impacted services the MCP response carries inline. The full set is
#: available via the REST endpoint / the map; here we keep the agent payload
#: tight and report the true count in ``total_impacted``.
@@ -82,17 +92,54 @@ async def get_blast_radius(
"_meta": _build_meta(),
}
+ collector = OmissionCollector("get_blast_radius", repo_root=_state._repo_path)
+ payload = await blast_radius_payload(
+ enricher,
+ raw,
+ targets,
+ max_depth=max_depth,
+ include_behavioral=include_behavioral,
+ collector=collector,
+ )
+ payload["_meta"] = _build_meta(
+ extra=_analysis_meta(
+ raw.get("generated_at"),
+ {
+ alias: provenance.get("head")
+ for alias, provenance in raw.get("repo_provenance", {}).items()
+ if provenance.get("head")
+ },
+ )
+ )
+ collector.attach(payload)
+ return payload
+
+
+async def blast_radius_payload(
+ enricher: Any,
+ raw_graph: dict[str, Any],
+ targets: list[str],
+ *,
+ max_depth: int = 3,
+ include_behavioral: bool = True,
+ collector: OmissionCollector | None = None,
+ tests_for: TestsFor | None = None,
+) -> dict[str, Any]:
+ """The ``get_blast_radius`` answer over *raw_graph*, without ``_meta``.
+
+ *enricher* answers the symbol-target lookups; *tests_for* is the cross-repo
+ test join, defaulting to :func:`cross_repo_tests_for`.
+ """
from repowise.core.analysis.risk_semantics import workspace_impact_score_semantics
from repowise.core.workspace.blast_radius import cross_repo_blast_radius, resolve_targets
from repowise.core.workspace.system_graph import SystemGraph
- graph = SystemGraph.from_dict(raw)
+ graph = SystemGraph.from_dict(raw_graph)
# Only targets the node/alias resolver rejected are tried as symbol ids, so
# a string that already names a node keeps its existing meaning.
_, unresolved = resolve_targets(graph, targets)
- collector = OmissionCollector("get_blast_radius", repo_root=_state._repo_path)
symbol_targets, effective = await _resolve_symbol_targets(
- enricher, graph, targets, unresolved, collector
+ enricher, graph, targets, unresolved, collector, tests_for=tests_for
)
result = cross_repo_blast_radius(
graph,
@@ -136,20 +183,9 @@ async def get_blast_radius(
"unresolved_targets": result.unresolved_targets,
"impact_score_semantics": workspace_impact_score_semantics(),
"summary": summary,
- "_meta": _build_meta(
- extra=_analysis_meta(
- raw.get("generated_at"),
- {
- alias: provenance.get("head")
- for alias, provenance in raw.get("repo_provenance", {}).items()
- if provenance.get("head")
- },
- )
- ),
}
if symbol_targets:
payload["symbol_targets"] = symbol_targets
- collector.attach(payload)
return payload
@@ -179,13 +215,16 @@ async def _resolve_symbol_targets(
targets: list[str],
unresolved: list[str],
collector: OmissionCollector | None = None,
+ *,
+ tests_for: TestsFor | None = None,
) -> tuple[list[dict[str, Any]], list[str]]:
"""Expand symbol-id targets into graph nodes plus their symbol-level consumers.
Returns the per-symbol blocks and the target list to traverse from: the
caller's targets with each matched symbol id swapped for the node(s) that
publish it. A symbol id matching nothing is left in place, so it still lands
- in the result's ``unresolved_targets``.
+ in the result's ``unresolved_targets``. *tests_for* is the test join,
+ defaulting to :func:`cross_repo_tests_for`.
"""
blocks: list[dict[str, Any]] = []
replacements: dict[str, list[str]] = {}
@@ -244,8 +283,10 @@ async def _resolve_symbol_targets(
}
)
+ # Resolved per call, so the default is always the module's current one.
+ join = tests_for or cross_repo_tests_for
impact = (
- await cross_repo_tests_for(
+ await join(
{repo: sorted(files) for repo, files in sorted(changed_by_repo.items())}
)
if changed_by_repo
diff --git a/packages/server/src/repowise/server/mcp_server/tool_conformance.py b/packages/server/src/repowise/server/mcp_server/tool_conformance.py
index 3706abebf..35ec4ee96 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_conformance.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_conformance.py
@@ -73,8 +73,23 @@ async def get_conformance(repo: str | None = None) -> dict[str, Any]:
"_meta": _build_meta(),
}
+ graph = enricher.get_system_graph() or {}
+ analysis_commits = {
+ alias: provenance.get("head")
+ for alias, provenance in graph.get("repo_provenance", {}).items()
+ if provenance.get("head")
+ }
+ payload = conformance_payload(report, repo)
+ payload["_meta"] = _build_meta(extra=_analysis_meta(report.get("generated_at"), analysis_commits))
+ return payload
+
+
+def conformance_payload(report: dict[str, Any], repo: str | None = None) -> dict[str, Any]:
+ """The ``get_conformance`` answer over a *report* that ran, without ``_meta``."""
+ from repowise.core.workspace.reads import conformance_for_repo
+
if repo:
- scoped = enricher.get_conformance_for_repo(repo)
+ scoped = conformance_for_repo(report, repo)
violations = scoped["violations"]
cycles = scoped["cycles"]
# Scoping picks from the already-capped stored list, so the pre-cap
@@ -87,12 +102,6 @@ async def get_conformance(repo: str | None = None) -> dict[str, Any]:
shown_violations = violations[:_MCP_VIOLATION_LIMIT]
shown_cycles = cycles[:_MCP_CYCLE_LIMIT]
- graph = enricher.get_system_graph() or {}
- analysis_commits = {
- alias: provenance.get("head")
- for alias, provenance in graph.get("repo_provenance", {}).items()
- if provenance.get("head")
- }
if violations or cycles:
summary = (
@@ -119,5 +128,4 @@ async def get_conformance(repo: str | None = None) -> dict[str, Any]:
"total_cycles": total_cycles,
"checked_at": report.get("generated_at"),
"summary": summary,
- "_meta": _build_meta(extra=_analysis_meta(report.get("generated_at"), analysis_commits)),
}
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index 094db2e24..4b695b67d 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -14,7 +14,7 @@ from pathlib import Path
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from repowise.core.docs_mode import resolve_docs_mode
-from repowise.core.workspace.cross_repo import MAX_EDGES, MAX_EDGES_PER_REPO_PAIR
+from repowise.core.workspace import reads
from repowise.server.deps import (
get_cross_repo_enricher,
get_workspace_config,
@@ -25,13 +25,10 @@ from repowise.server.schemas import (
WorkspaceArchitectureResponse,
WorkspaceBlastRadiusResponse,
WorkspaceBreakingChangesResponse,
- WorkspaceCoChangeEntry,
WorkspaceCoChangesResponse,
WorkspaceCoChangeStructure,
WorkspaceConformanceResponse,
WorkspaceContractDetail,
- WorkspaceContractEntry,
- WorkspaceContractLinkEntry,
WorkspaceContractsResponse,
WorkspaceContractSummary,
WorkspaceCrossRepoSummary,
@@ -251,74 +248,6 @@ async def get_workspace(
)
-def _contract_entry(c: dict) -> WorkspaceContractEntry:
- """Project one raw ``contracts.json`` row onto the wire model.
-
- ``schema`` is dropped on purpose — it is the one field the list endpoint
- cannot afford and the detail endpoint carries separately.
- """
- return WorkspaceContractEntry(
- contract_id=c.get("contract_id", ""),
- contract_type=c.get("contract_type", ""),
- role=c.get("role", ""),
- repo=c.get("repo", ""),
- file_path=c.get("file_path", ""),
- symbol_name=c.get("symbol_name", ""),
- confidence=c.get("confidence", 0.0),
- service=c.get("service"),
- line=c.get("line"),
- symbol_id=c.get("symbol_id"),
- meta=c.get("meta") or {},
- )
-
-
-def _contract_link(lk: dict) -> WorkspaceContractLinkEntry:
- """Project one raw ``contract_links`` row onto the wire model."""
- return WorkspaceContractLinkEntry(
- contract_id=lk.get("contract_id", ""),
- contract_type=lk.get("contract_type", ""),
- match_type=lk.get("match_type", "exact"),
- confidence=lk.get("confidence", 0.0),
- provider_repo=lk.get("provider_repo", ""),
- provider_file=lk.get("provider_file", ""),
- provider_symbol=lk.get("provider_symbol", ""),
- consumer_repo=lk.get("consumer_repo", ""),
- consumer_file=lk.get("consumer_file", ""),
- consumer_symbol=lk.get("consumer_symbol", ""),
- provider_service=lk.get("provider_service"),
- consumer_service=lk.get("consumer_service"),
- provider_symbol_id=lk.get("provider_symbol_id"),
- consumer_symbol_id=lk.get("consumer_symbol_id"),
- consumer_contract_id=lk.get("consumer_contract_id"),
- )
-
-
-def _contract_haystack(c: dict) -> str:
- return " ".join(
- str(c.get(k) or "") for k in ("contract_id", "file_path", "symbol_name", "repo", "service")
- ).lower()
-
-
-def _link_haystack(lk: dict) -> str:
- return " ".join(
- str(lk.get(k) or "")
- for k in (
- "contract_id",
- "consumer_contract_id",
- "provider_repo",
- "provider_file",
- "provider_symbol",
- "consumer_repo",
- "consumer_file",
- "consumer_symbol",
- )
- ).lower()
-
-
-def _matches_terms(haystack: str, terms: list[str]) -> bool:
- return all(t in haystack for t in terms)
-
-
# ---------------------------------------------------------------------------
# GET /api/workspace/contracts
# ---------------------------------------------------------------------------
@@ -360,60 +289,19 @@ async def get_contracts(
total_links=0,
)
- contracts = list(getattr(enricher, "_contracts", []))
- links = list(getattr(enricher, "_contract_links", []))
-
- # Apply filters to contracts
- if contract_type:
- contracts = [c for c in contracts if c.get("contract_type") == contract_type]
- links = [lk for lk in links if lk.get("contract_type") == contract_type]
- if repo:
- contracts = [c for c in contracts if c.get("repo") == repo]
- links = [
- lk for lk in links if lk.get("provider_repo") == repo or lk.get("consumer_repo") == repo
- ]
- if role:
- contracts = [c for c in contracts if c.get("role") == role]
- if linked is not None:
- # Keyed on the side each contract plays, from the unfiltered links, so a
- # type or repo filter above cannot turn a linked contract into an unused one.
- on_link = set()
- for lk in getattr(enricher, "_contract_links", []):
- cid = lk.get("contract_id")
- on_link.add(("provider", lk.get("provider_repo"), lk.get("provider_file"), cid))
- on_link.add(("consumer", lk.get("consumer_repo"), lk.get("consumer_file"), cid))
- contracts = [
- c
- for c in contracts
- if (
- (c.get("role"), c.get("repo"), c.get("file_path"), c.get("contract_id"))
- in on_link
- )
- == linked
- ]
- terms = (q or "").lower().split()
- if terms:
- contracts = [c for c in contracts if _matches_terms(_contract_haystack(c), terms)]
- links = [lk for lk in links if _matches_terms(_link_haystack(lk), terms)]
-
- total_contracts = len(contracts)
- total_links = len(links)
-
- # Count by type
- by_type: dict[str, int] = {}
- for c in contracts:
- ct = c.get("contract_type", "unknown")
- by_type[ct] = by_type.get(ct, 0) + 1
-
- # Paginate contracts only (links are typically small enough)
- contracts_page = contracts[offset : offset + limit]
-
return WorkspaceContractsResponse(
- contracts=[_contract_entry(c) for c in contracts_page],
- links=[_contract_link(lk) for lk in links] if include_links else [],
- total_contracts=total_contracts,
- total_links=total_links,
- by_type=by_type,
+ **reads.list_contracts(
+ enricher.contracts,
+ enricher.contract_links,
+ contract_type=contract_type,
+ repo=repo,
+ role=role,
+ q=q,
+ linked=linked,
+ include_links=include_links,
+ limit=limit,
+ offset=offset,
+ )
)
@@ -422,24 +310,6 @@ async def get_contracts(
# ---------------------------------------------------------------------------
-def _unmatched_reason(enricher, repo: str, file_path: str, contract_id: str) -> str | None:
- """Look up why one consumer matched nothing, from the system graph.
-
- The reasons live in ``system_graph.json``, not ``contracts.json``, and are
- keyed by the same ``(repo, file_path, contract_id)`` triple this endpoint
- takes. Returns None when no graph is built or the consumer did match.
- """
- diagnostics = enricher.get_diagnostics() or {}
- for u in diagnostics.get("unmatched_consumers", []):
- if (
- u.get("repo") == repo
- and u.get("file_path") == file_path
- and u.get("contract_id") == contract_id
- ):
- return u.get("reason")
- return None
-
-
@router.get("/contracts/detail", response_model=WorkspaceContractDetail)
async def get_contract_detail(
ws_config=Depends(get_workspace_config),
@@ -466,38 +336,17 @@ async def get_contract_detail(
if enricher is None:
raise HTTPException(status_code=404, detail="No contract data for this workspace")
- match = next(
- (
- c
- for c in getattr(enricher, "_contracts", [])
- if c.get("repo") == repo and c.get("file_path") == file and c.get("contract_id") == id
- ),
- None,
+ detail = reads.contract_detail(
+ enricher.contracts,
+ enricher.contract_links,
+ enricher.get_diagnostics(),
+ repo=repo,
+ file_path=file,
+ contract_id=id,
)
- if match is None:
+ if detail is None:
raise HTTPException(status_code=404, detail="Contract not found")
-
- role = match.get("role", "")
- if role == "consumer":
- repo_key, file_key = "consumer_repo", "consumer_file"
- else:
- repo_key, file_key = "provider_repo", "provider_file"
- links = [
- lk
- for lk in getattr(enricher, "_contract_links", [])
- if lk.get("contract_id") == id and lk.get(repo_key) == repo and lk.get(file_key) == file
- ]
-
- reason = None
- if role == "consumer" and not links:
- reason = _unmatched_reason(enricher, repo, file, id)
-
- return WorkspaceContractDetail(
- contract=_contract_entry(match),
- contract_schema=match.get("schema"),
- links=[_contract_link(lk) for lk in links],
- unmatched_reason=reason,
- )
+ return WorkspaceContractDetail(**detail)
# ---------------------------------------------------------------------------
@@ -519,53 +368,14 @@ async def get_co_changes(
if enricher is None:
return WorkspaceCoChangesResponse(co_changes=[], total=0, total_mined=0)
- co_changes = list(getattr(enricher, "_co_changes", []))
- total_mined = getattr(enricher, "_total_co_changes", len(co_changes))
- # Which cap trimmed the stored overlay, judged before any query filter. The
- # miner walks pairs strongest first, so a full global budget means the
- # workspace-wide cap stopped it (the per-pair cap may also have applied).
- if total_mined <= len(co_changes):
- truncated_by = None
- elif len(co_changes) >= MAX_EDGES:
- truncated_by = "total"
- else:
- truncated_by = "per_repo_pair"
-
- if repo:
- co_changes = [
- cc
- for cc in co_changes
- if cc.get("source_repo") == repo or cc.get("target_repo") == repo
- ]
- if min_strength > 0:
- co_changes = [cc for cc in co_changes if cc.get("strength", 0) >= min_strength]
-
- # Sort by strength descending
- co_changes.sort(key=lambda cc: -cc.get("strength", 0))
-
- total = len(co_changes)
- co_changes = co_changes[:limit]
-
return WorkspaceCoChangesResponse(
- co_changes=[
- WorkspaceCoChangeEntry(
- source_repo=cc.get("source_repo", ""),
- source_file=cc.get("source_file", ""),
- target_repo=cc.get("target_repo", ""),
- target_file=cc.get("target_file", ""),
- strength=cc.get("strength", 0.0),
- frequency=cc.get("frequency", 0),
- last_date=cc.get("last_date", ""),
- )
- for cc in co_changes
- ],
- total=total,
- total_mined=total_mined,
- # The constants name the rules the miner applied; the overlay does not
- # store them.
- per_repo_pair_cap=MAX_EDGES_PER_REPO_PAIR,
- total_cap=MAX_EDGES,
- truncated_by=truncated_by,
+ **reads.list_co_changes(
+ enricher.co_changes,
+ enricher.total_co_changes,
+ repo=repo,
+ min_strength=min_strength,
+ limit=limit,
+ )
)
@@ -593,40 +403,14 @@ async def get_co_change_structure(
target_file_links=0,
)
- provider_index = getattr(enricher, "_contract_provider_index", {})
- consumer_index = getattr(enricher, "_contract_consumer_index", {})
- src = (source_repo, source_file)
- tgt = (target_repo, target_file)
-
- def touching(key: tuple[str, str]) -> list[dict]:
- # .get, not []: the indexes are defaultdicts and a read must not grow them.
- return [*provider_index.get(key, []), *consumer_index.get(key, [])]
-
- src_links = touching(src)
- pair = {src, tgt}
- pair_links = [
- lk
- for lk in src_links
- if {
- (lk.get("provider_repo"), lk.get("provider_file")),
- (lk.get("consumer_repo"), lk.get("consumer_file")),
- }
- == pair
- ]
-
- repos = {source_repo, target_repo}
- by_type: dict[str, int] = {}
- for lk in getattr(enricher, "_contract_links", []):
- if {lk.get("provider_repo"), lk.get("consumer_repo")} == repos:
- ct = lk.get("contract_type", "unknown")
- by_type[ct] = by_type.get(ct, 0) + 1
-
return WorkspaceCoChangeStructure(
- pair_links=[_contract_link(lk) for lk in pair_links],
- repo_links_total=sum(by_type.values()),
- repo_links_by_type=by_type,
- source_file_links=len(src_links),
- target_file_links=len(touching(tgt)),
+ **reads.co_change_structure(
+ enricher.contract_links,
+ source_repo=source_repo,
+ source_file=source_file,
+ target_repo=target_repo,
+ target_file=target_file,
+ )
)
@@ -682,8 +466,7 @@ async def get_workspace_graph(
if enricher is not None:
# Contract-based edges: each link connects two repos
- links = list(getattr(enricher, "_contract_links", []))
- for lk in links:
+ for lk in enricher.contract_links:
p_repo = lk.get("provider_repo", "")
c_repo = lk.get("consumer_repo", "")
if not p_repo or not c_repo or p_repo == c_repo:
@@ -705,9 +488,8 @@ async def get_workspace_graph(
)
# Co-change-based edges: aggregate per repo-pair
- co_changes = list(getattr(enricher, "_co_changes", []))
pair_strengths: dict[tuple[str, str], list[float]] = {}
- for cc in co_changes:
+ for cc in enricher.co_changes:
s_repo = cc.get("source_repo", "")
t_repo = cc.get("target_repo", "")
if not s_repo or not t_repo or s_repo == t_repo:
@@ -895,35 +677,9 @@ async def get_breaking_changes(
report = enricher.get_breaking_changes() if enricher is not None else None
if not report:
return WorkspaceBreakingChangesResponse()
-
- changes = list(report.get("changes", []))
- if repo:
- changes = [c for c in changes if c.get("provider_repo") == repo]
- if severity:
- changes = [c for c in changes if c.get("severity") == severity]
-
- # Recompute rollups when a filter narrowed the set so the response stays
- # self-consistent; otherwise pass the persisted rollups straight through.
- if repo or severity:
- impacted_repos = sorted(
- {ic.get("repo", "") for c in changes for ic in c.get("impacted_consumers", [])}
- )
- impacted_services = sorted(
- {ic.get("node_id", "") for c in changes for ic in c.get("impacted_consumers", [])}
- )
- return WorkspaceBreakingChangesResponse(
- version=report.get("version", 1),
- generated_at=report.get("generated_at") or None,
- changes=changes,
- total=len(changes),
- breaking_count=sum(1 for c in changes if c.get("severity") == "breaking"),
- warning_count=sum(1 for c in changes if c.get("severity") == "warning"),
- impacted_repos=impacted_repos,
- impacted_services=impacted_services,
- total_impacted_consumers=sum(len(c.get("impacted_consumers", [])) for c in changes),
- )
-
- return WorkspaceBreakingChangesResponse(**report)
+ return WorkspaceBreakingChangesResponse(
+ **reads.breaking_changes_view(report, repo=repo, severity=severity)
+ )
# ---------------------------------------------------------------------------
@@ -951,40 +707,7 @@ async def get_conformance(
report = enricher.get_conformance() if enricher is not None else None
if not report:
return WorkspaceConformanceResponse()
-
- if not repo:
- # An artifact written before cycle totals were recorded has no
- # total_cycles key; falling back to the listed count is better than
- # letting the model default report zero cycles alongside a non-zero list.
- return WorkspaceConformanceResponse(
- **{
- **report,
- "total_cycles": report.get("total_cycles", len(report.get("cycles", []))),
- }
- )
-
- # Narrow to findings that involve the repo, recomputing rollups so the
- # response stays self-consistent.
- scoped = enricher.get_conformance_for_repo(repo)
- violations = scoped["violations"]
- cycles = scoped["cycles"]
- violating_repos = sorted(
- {v.get("source", "").split("::", 1)[0] for v in violations}
- | {v.get("target", "").split("::", 1)[0] for v in violations}
- )
- return WorkspaceConformanceResponse(
- version=report.get("version", 1),
- generated_at=report.get("generated_at") or None,
- rules_evaluated=report.get("rules_evaluated", 0),
- violations=violations,
- cycles=cycles,
- violation_count=len(violations),
- cycle_count=len(cycles),
- # The unscoped total, not the scoped count: how many cycles the
- # workspace has does not change because the view was narrowed.
- total_cycles=report.get("total_cycles", len(report.get("cycles", []))),
- violating_repos=violating_repos,
- )
+ return WorkspaceConformanceResponse(**reads.conformance_view(report, repo=repo))
# ---------------------------------------------------------------------------
diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.py
index dae39ce51..18bd40ba4 100644
--- a/packages/server/src/repowise/server/schemas/workspace.py
+++ b/packages/server/src/repowise/server/schemas/workspace.py
@@ -131,8 +131,9 @@ class WorkspaceContractLinkEntry(BaseModel):
#: than a display label. None when that side never bound to one.
provider_symbol_id: str | None = None
consumer_symbol_id: str | None = None
- #: The consumer's own contract id when it reached the provider under another
- #: name (a queue bound to the exchange ``contract_id`` names); None otherwise.
+ #: The consumer's own contract id when it is not spelled like ``contract_id``,
+ #: which names the provider's (a queue bound to that exchange, or a path
+ #: matched across case, a wildcard method or a mount prefix); None otherwise.
consumer_contract_id: str | None = None
diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.ts
index 36b966dc1..ade058bfa 100644
--- a/packages/types/src/workspace.ts
+++ b/packages/types/src/workspace.ts
@@ -58,8 +58,9 @@ export interface WorkspaceContractLinkEntry {
provider_symbol_id: string | null;
consumer_symbol_id: string | null;
/**
- * The consumer's own contract id when it reached the provider under another
- * name (a queue bound to the exchange `contract_id` names); null otherwise.
+ * The consumer's own contract id when it is not spelled like `contract_id`,
+ * which names the provider's (a queue bound to that exchange, or a path
+ * matched across case, a wildcard method or a mount prefix); null otherwise.
*/
consumer_contract_id?: string | null;
}
diff --git a/tests/unit/server/test_enrichment_contracts.py b/tests/unit/server/test_enrichment_contracts.py
index 9e418e348..fb837bff2 100644
--- a/tests/unit/server/test_enrichment_contracts.py
+++ b/tests/unit/server/test_enrichment_contracts.py
@@ -193,3 +193,46 @@ class TestEnricherContractLoading:
enricher = CrossRepoEnricher(missing_path, contracts_path=contracts_json)
assert enricher.has_data is True
assert enricher.has_contract_data is True
+
+
+class TestEnricherFromData:
+ """Parsed payloads get the same validation and indexes a file load does."""
+
+ def test_payloads_build_the_indexes_a_file_load_builds(
+ self, contracts_json: Path, empty_cross_repo: Path
+ ) -> None:
+ payload = json.loads(contracts_json.read_text(encoding="utf-8"))
+ from_file = CrossRepoEnricher(empty_cross_repo, contracts_path=contracts_json)
+ from_data = CrossRepoEnricher.from_data(
+ overlay={"version": 2, "co_changes": [], "package_deps": []}, contracts=payload
+ )
+
+ assert from_data.contracts == from_file.contracts
+ assert from_data.contract_links == from_file.contract_links
+ assert from_data.contract_analysis == from_file.contract_analysis
+ assert from_data.cross_repo_analysis == from_file.cross_repo_analysis
+ assert from_data.get_contract_links_as_provider(
+ "backend", "routes.py"
+ ) == from_file.get_contract_links_as_provider("backend", "routes.py")
+ assert from_data.get_affected_repos("backend", "routes.py") == ["frontend"]
+
+ def test_a_stale_overlay_payload_is_refused_like_a_stale_file(self) -> None:
+ pair = {
+ "source_repo": "a",
+ "source_file": "x",
+ "target_repo": "b",
+ "target_file": "y",
+ "strength": 0.5,
+ }
+ enricher = CrossRepoEnricher.from_data(overlay={"version": 1, "co_changes": [pair]})
+ assert enricher.co_changes == []
+ assert enricher.cross_repo_analysis["reason"] == "unsupported_contract_version"
+
+ def test_absent_payloads_are_absent_artifacts(self) -> None:
+ enricher = CrossRepoEnricher.from_data(
+ conformance={"generated_at": "t", "violations": [], "cycles": []}
+ )
+ assert enricher.has_data is False
+ assert enricher.get_system_graph() is None
+ assert enricher.has_conformance is True
+ assert enricher.contract_analysis["status"] == "unavailable"
diff --git a/tests/unit/server/test_mcp_blast_radius_symbols.py b/tests/unit/server/test_mcp_blast_radius_symbols.py
index 09d63499b..dc2b94b71 100644
--- a/tests/unit/server/test_mcp_blast_radius_symbols.py
+++ b/tests/unit/server/test_mcp_blast_radius_symbols.py
@@ -261,3 +261,29 @@ async def test_no_tests_block_when_the_symbol_has_no_consumers(tmp_path: Path):
block = result["symbol_targets"][0]
assert block["consumers"] == []
assert "tests_summary" not in block
+
+
+async def test_a_caller_supplies_the_test_join(tmp_path: Path):
+ """The payload builder runs over any enricher and any join, outside the tool."""
+ from repowise.core.workspace.test_impact import WorkspaceTestImpactResult
+ from repowise.server.mcp_server.tool_blast_radius import blast_radius_payload
+
+ provider = _provider()
+ consumer = _consumer()
+ enricher = _enricher(tmp_path, [provider, consumer], [_link(provider, consumer)])
+ asked: list[dict] = []
+
+ async def join(changed_by_repo):
+ asked.append(dict(changed_by_repo))
+ return WorkspaceTestImpactResult(summary={"reason": "no_matching_links"})
+
+ payload = await blast_radius_payload(
+ enricher, enricher.get_system_graph(), ["src/types.ts::Order"], tests_for=join
+ )
+ assert asked == [{"backend": ["src/types.ts"]}]
+ assert payload["symbol_targets"][0]["consumers"][0]["tests"]["state"] == "none"
+ assert "_meta" not in payload
+ with _in_workspace(enricher):
+ tool = await get_blast_radius(["src/types.ts::Order"])
+ assert set(tool) - set(payload) == {"_meta"}
diff --git a/tests/unit/server/test_mcp_conformance.py b/tests/unit/server/test_mcp_conformance.py
index 10cd4315f..b96d36ce8 100644
--- a/tests/unit/server/test_mcp_conformance.py
+++ b/tests/unit/server/test_mcp_conformance.py
@@ -225,3 +225,26 @@ def test_conformance_directive_ignores_an_unstamped_report(tmp_path: Path):
finally:
_state._registry = prev_registry
_state._cross_repo_enricher = prev_enricher
+
+
+async def test_the_payload_builder_is_the_tool_answer_without_meta(workspace_state):
+ from repowise.server.mcp_server.tool_conformance import conformance_payload
+
+ report = _state._cross_repo_enricher.get_conformance()
+ for repo in (None, "frontend"):
+ tool = await get_conformance(repo=repo)
+ assert {k: v for k, v in tool.items() if k != "_meta"} == conformance_payload(report, repo)
+
+
+async def test_the_architecture_payload_is_the_tool_answer_without_meta(workspace_state):
+ from repowise.server.mcp_server.tool_architecture import architecture_payload, get_architecture
+
+ enricher = CrossRepoEnricher.from_data(system_graph={**_graph().to_dict(), "generated_at": "t"})
+ _state._cross_repo_enricher = enricher
+ tool = await get_architecture()
+ assert {k: v for k, v in tool.items() if k != "_meta"} == architecture_payload(
+ enricher.get_architecture_metrics()
+ )
+ assert tool["node_count"] == 2
diff --git a/tests/unit/workspace/test_contracts.py b/tests/unit/workspace/test_contracts.py
index 288652cbd..6e358e6ae 100644
--- a/tests/unit/workspace/test_contracts.py
+++ b/tests/unit/workspace/test_contracts.py
@@ -995,6 +995,39 @@ class TestCandidateMatching:
# Candidate confidence is strictly lower than an exact min() would give.
assert links[0].confidence < 0.75
+ def test_a_link_names_each_end_by_its_own_id(self) -> None:
+ # The provider's page reads its links by contract_id and the consumer's
+ # by consumer_contract_id or contract_id, so each must find this one.
+ contracts = [
+ self._c(repo="backend", role="provider", contract_id="http::GET::/resource/search"),
+ self._c(repo="frontend", role="consumer", contract_id="http::GET::/api/resource/search",
+ file_path="c.ts"),
+ ]
+ [link] = match_contracts(contracts)
+ assert link.contract_id == "http::GET::/resource/search"
+ assert link.consumer_contract_id == "http::GET::/api/resource/search"
+
+ def test_an_exact_match_spelled_differently_keeps_both_ids(self) -> None:
+ contracts = [
+ self._c(repo="backend", role="provider", contract_id="http::GET::/Users"),
+ self._c(repo="frontend", role="consumer", contract_id="http::GET::/users",
+ file_path="c.ts"),
+ ]
+ [link] = match_contracts(contracts)
+ assert link.match_type == "exact"
+ assert link.contract_id == "http::GET::/Users"
+ assert link.consumer_contract_id == "http::GET::/users"
+
+ def test_a_link_spelled_alike_carries_no_consumer_id(self) -> None:
+ contracts = [
+ self._c(repo="backend", role="provider", contract_id="http::GET::/users"),
+ self._c(repo="frontend", role="consumer", contract_id="http::GET::/users",
+ file_path="c.ts"),
+ ]
+ [link] = match_contracts(contracts)
+ assert link.consumer_contract_id is None
+ assert "consumer_contract_id" not in link.to_dict()
+
def test_version_prefix_with_base_param(self) -> None:
# Provider /v1/resource; consumer base resolved to a leading {param}.
contracts = [
diff --git a/tests/unit/workspace/test_reads.py b/tests/unit/workspace/test_reads.py
new file mode 100644
index 000000000..1fdf0b291
--- /dev/null
+++ b/tests/unit/workspace/test_reads.py
@@ -0,0 +1,154 @@
+"""The workspace read views, called on plain artifact payloads.
+
+The API routes are covered through the router; these pin what a caller holding
+only the parsed JSON gets, and the one rule every view shares: a link's
+consumer end is named by ``consumer_contract_id or contract_id``.
+"""
+
+from __future__ import annotations
+
+from repowise.core.workspace.reads import (
+ breaking_changes_view,
+ co_change_structure,
+ conformance_view,
+ contract_detail,
+ list_co_changes,
+ list_contracts,
+)
+
+PROVIDER = {
+ "contract_id": "http::GET::/users",
+ "contract_type": "http",
+ "role": "provider",
+ "repo": "backend",
+ "file_path": "api/users.py",
+ "symbol_name": "list_users",
+ "schema": {"type": "array"},
+}
+CONSUMER = {
+ "contract_id": "http::GET::/api/users",
+ "contract_type": "http",
+ "role": "consumer",
+ "repo": "frontend",
+ "file_path": "src/api.ts",
+ "symbol_name": "getUsers",
+}
+LINK = {
+ "contract_id": "http::GET::/users",
+ "consumer_contract_id": "http::GET::/api/users",
+ "contract_type": "http",
+ "match_type": "candidate",
+ "confidence": 0.6,
+ "provider_repo": "backend",
+ "provider_file": "api/users.py",
+ "consumer_repo": "frontend",
+ "consumer_file": "src/api.ts",
+}
+
+
+def test_both_ends_of_a_differently_spelled_link_find_it():
+ for contract in (PROVIDER, CONSUMER):
+ detail = contract_detail(
+ [PROVIDER, CONSUMER],
+ [LINK],
+ None,
+ repo=contract["repo"],
+ file_path=contract["file_path"],
+ contract_id=contract["contract_id"],
+ )
+ assert detail is not None
+ assert [lk["contract_id"] for lk in detail["links"]] == ["http::GET::/users"]
+ assert detail["unmatched_reason"] is None
+
+
+def test_detail_carries_the_schema_the_list_drops():
+ detail = contract_detail(
+ [PROVIDER], [], None, repo="backend", file_path="api/users.py", contract_id=PROVIDER["contract_id"]
+ )
+ assert detail["contract_schema"] == {"type": "array"}
+ assert "schema" not in detail["contract"]
+ assert contract_detail([PROVIDER], [], None, repo="x", file_path="y", contract_id="z") is None
+
+
+def test_an_unmatched_consumer_names_its_reason():
+ diagnostics = {
+ "unmatched_consumers": [
+ {**{k: CONSUMER[k] for k in ("repo", "file_path", "contract_id")}, "reason": "no_provider"}
+ ]
+ }
+ detail = contract_detail(
+ [CONSUMER],
+ [],
+ diagnostics,
+ repo="frontend",
+ file_path="src/api.ts",
+ contract_id=CONSUMER["contract_id"],
+ )
+ assert detail["unmatched_reason"] == "no_provider"
+
+
+def test_linked_filter_counts_the_consumer_under_its_own_id():
+ linked = list_contracts([PROVIDER, CONSUMER], [LINK], linked=True)
+ assert linked["total_contracts"] == 2
+ assert list_contracts([PROVIDER, CONSUMER], [LINK], linked=False)["total_contracts"] == 0
+
+
+def test_contract_list_pages_contracts_and_can_omit_links():
+ page = list_contracts([PROVIDER, CONSUMER], [LINK], limit=1, offset=1, include_links=False)
+ assert [c["repo"] for c in page["contracts"]] == ["frontend"]
+ assert page["links"] == []
+ assert page["total_links"] == 1
+ assert page["by_type"] == {"http": 2}
+
+
+def test_co_changes_report_which_cap_trimmed_the_overlay():
+ pairs = [
+ {"source_repo": "a", "source_file": "x", "target_repo": "b", "target_file": "y", "strength": 0.3},
+ {"source_repo": "a", "source_file": "z", "target_repo": "c", "target_file": "w", "strength": 0.9},
+ ]
+ view = list_co_changes(pairs, 5, repo="a", limit=1)
+ assert view["total"] == 2
+ assert [p["strength"] for p in view["co_changes"]] == [0.9]
+ assert view["truncated_by"] == "per_repo_pair"
+ assert list_co_changes(pairs)["truncated_by"] is None
+
+
+def test_co_change_structure_reads_the_pair_from_the_links():
+ view = co_change_structure(
+ [LINK],
+ source_repo="frontend",
+ source_file="src/api.ts",
+ target_repo="backend",
+ target_file="api/users.py",
+ )
+ assert len(view["pair_links"]) == 1
+ assert view["repo_links_by_type"] == {"http": 1}
+ assert view["source_file_links"] == view["target_file_links"] == 1
+
+
+def test_a_filtered_breaking_report_recomputes_its_rollups():
+ report = {
+ "generated_at": "t",
+ "changes": [
+ {"provider_repo": "a", "severity": "breaking", "impacted_consumers": [{"repo": "b", "node_id": "b"}]},
+ {"provider_repo": "c", "severity": "warning", "impacted_consumers": []},
+ ],
+ "total": 2,
+ }
+ assert breaking_changes_view(report) == report
+ view = breaking_changes_view(report, repo="a")
+ assert (view["total"], view["breaking_count"], view["impacted_repos"]) == (1, 1, ["b"])
+
+
+def test_a_scoped_conformance_view_keeps_the_workspace_cycle_total():
+ report = {
+ "generated_at": "t",
+ "violations": [{"source": "web::ui", "target": "db"}],
+ "cycles": [{"nodes": ["api", "worker"]}],
+ "total_cycles": 4,
+ }
+ view = conformance_view(report, repo="web")
+ assert view["violating_repos"] == ["db", "web"]
+ assert view["cycles"] == []
+ assert view["total_cycles"] == 4
+ assert conformance_view({"cycles": [{"nodes": ["a"]}]})["total_cycles"] == 1
diff --git a/tests/unit/workspace/test_repo_index.py b/tests/unit/workspace/test_repo_index.py
index e22c46bcd..a53db9da8 100644
--- a/tests/unit/workspace/test_repo_index.py
+++ b/tests/unit/workspace/test_repo_index.py
@@ -123,3 +123,41 @@ class TestOpening:
assert workspace.get("beta") is None
finally:
await workspace.close()
+
+
+class TestFromSymbols:
+ def _indexed(self, name: str, start: int, end: int, path: str = "a.py"):
+ from repowise.core.workspace.repo_index import IndexedSymbol
+
+ return IndexedSymbol(
+ symbol_id=f"{path}::{name}",
+ name=name,
+ qualified_name=name,
+ kind="function",
+ signature=f"def {name}()",
+ file_path=path,
+ start_line=start,
+ end_line=end,
+ visibility="public",
+ )
+
+ def test_rows_answer_the_same_lookups_a_database_load_does(self) -> None:
+ from repowise.core.workspace.repo_index import RepoIndex
+
+ inner, outer = self._indexed("inner", 5, 9), self._indexed("Outer", 1, 20)
+ index = RepoIndex.from_symbols("web", [inner, outer], repo_id="r1")
+ assert [s.name for s in index.symbols_for_file("a.py")] == ["Outer", "inner"]
+ assert index.symbol_at("a.py", 7) is inner
+ assert index.symbol_named("inner") is inner
+ assert index.repo_id == "r1"
+ assert index.session is None
+
+ def test_a_name_lookup_can_reach_past_the_loaded_files(self) -> None:
+ from repowise.core.workspace.repo_index import RepoIndex
+
+ elsewhere = self._indexed("handler", 1, 3, path="b.py")
+ index = RepoIndex.from_symbols(
+ "web", [self._indexed("f", 1, 2)], repo_id="r1", names={"handler": [elsewhere]}
+ )
+ assert index.symbol_named("handler") is elsewhere
+ assert index.symbols_for_file("b.py") == []
diff --git a/tests/unit/workspace/test_test_impact.py b/tests/unit/workspace/test_test_impact.py
index cf1bd354c..9ad6768b1 100644
--- a/tests/unit/workspace/test_test_impact.py
+++ b/tests/unit/workspace/test_test_impact.py
@@ -663,3 +663,54 @@ async def test_two_links_in_one_file_each_get_only_their_own_symbols_tests(
"tests/api.test.ts": [BOUND.contract_id],
"tests/list.test.ts": ["http::GET::/users"],
}
+
+
+async def test_a_caller_supplies_its_own_reads_over_an_index_built_from_rows() -> None:
+ """No database: the index is built from rows and the reads take its handle.
+
+ Each read is handed the index's ``session``, whatever the caller put there,
+ so one join serves an index that never opened a ``wiki.db``.
+ """
+ from repowise.core.analysis.test_reachability import ReachedBy
+ from repowise.core.workspace.repo_index import IndexedSymbol
+
+ handle = object()
+ seen: list[object] = []
+
+ async def covering(session, repo_id, files):
+ seen.append(session)
+ return {"src/api.ts": [{"test_id": "tests/cov.test.ts::a"}]}
+
+ async def reaching(session, repo_id, targets, *, call_depth, import_depth, symbol_seeds=None):
+ seen.append(session)
+ if symbol_seeds:
+ return {"src/api.ts::getUser": ReachedBy(tests=["tests/walk.test.ts"], via="call-graph")}
+ return {}
+
+ symbol = IndexedSymbol(
+ symbol_id="src/api.ts::getUser",
+ name="getUser",
+ qualified_name="getUser",
+ kind="function",
+ signature="function getUser()",
+ file_path="src/api.ts",
+ start_line=1,
+ end_line=5,
+ visibility="public",
+ )
+ index = RepoIndex.from_symbols("frontend", [symbol], repo_id="r1", session=handle)
+ result = await analyze_workspace_test_impact(
+ WorkspaceIndex({"frontend": index}),
+ [BOUND],
+ CHANGED,
+ covering=covering,
+ reaching=reaching,
+ )
+ await index.close() # the caller owns the handle; close leaves it alone
+
+ assert seen and all(s is handle for s in seen)
+ assert {(r.test_file, r.basis) for r in result.recommendations} == {
+ ("tests/cov.test.ts", "measured"),
+ ("tests/walk.test.ts", "inferred"),
+ }
+ assert result.unresolved == []